> _**HTTP skill (FULL: basic + all 21 namespaces)** · ~318,825 tokens · hoody-sdk v1.0.0-beta.17_ # HTTP mode — drive Hoody with curl Drive Hoody with `curl` or any HTTP client. No SDK or CLI. ## What is Hoody Hoody is a remote-first computing platform: every workflow — coding, browsing, scheduling, agent runtimes, file storage, GUI desktops, HTTP services, scripts, databases, displays — runs in account-owned cloud containers reachable by URL, with zero local setup. **Thesis: everything remote, no friction.** A container is a **full Linux box (systemd + root, just like a VM — not a Docker-style minimal sandbox)** you can spin up, fill, and use from anywhere; ports are auto-published on `https://...containers.hoody.com`; GUIs render to browser tabs; one-shot scripts mount as HTTP endpoints; databases, terminals, file watchers, full XFCE/MATE desktops, and SSH are first-class kits. Standard distro tooling works as expected — `apt install nginx && systemctl enable --now nginx`, `journalctl`, `crontab`, etc. The CLI / SDK / HTTP surfaces are three skins on the same control + container plane — drive whichever fits your runtime. **Prefer a GUI?** The **Hoody Agent** browser GUI runs at `https://{P}-{C}-agent-1.{N}.containers.hoody.com` — file browser, code editor, agent sessions, PR review, MCP, memory, image-gen, web search, all in a browser tab. It's the human-facing surface over the same `agent` kit these skills drive programmatically (same `-agent-1` host — the HTTP API lives under its `/api/v1/agent/` path). **Every kit URL is also iframable** (`code`, `files`, `terminal`, `display`, `desktop`, `notes`, `agent`, …) — you can compose a full HTML "operating system" out of kit iframes with no native code. Use whichever surface fits the moment. **Need a custom API, script-as-service, or multi-step workflow?** Default to `exec`. Drop a `.ts` / `.js` (or shell-out via Bun) into the scripts dir and it auto-mounts as an HTTP endpoint — no framework, no deploy, schema-validated, logged, metric-instrumented, alias-able to a public hostname. Each script is a micro-service, kept warm by the kit; **multi-step workflows** (call agent A → check with agent B → trigger action C) are just one script orchestrating the steps. (Not a sandbox for untrusted code — see `exec` namespace.) **Need a GET-only URL for something that's actually a POST?** Use `curl` — `GET /api/v1/curl/request?url=…&method=POST` on the curl kit URL turns any REST call into a single GET-able link (the GET surface takes 21 query params (`body` and `body_base64` are aliases of `data` and `data_base64`) — including `data`, `json`, `data_base64` and a repeatable `header`, so bodies AND headers DO work as query params, and supplying a body auto-upgrades the upstream call GET→POST; URL-encoded `form` fields, a headers map, cookies, Basic auth and the connection limits stay `POST /api/v1/curl/request`-only, and neither form sends multipart uploads). See `curl` namespace. **Stuck, or unsure how to do something?** Ask Hoody's public docs assistant — an unauthenticated MCP endpoint at `https://chatbot.hoody.com/mcp` (one tool, `search_hoody_docs`; or the `POST /api/chat` SSE fallback) answers any "how do I…" with cited doc URLs. Use it for discovery when you're not sure which namespace fits. ## When to choose HTTP Use when there's no SDK for your language, you need copy-pasteable recipes (runbooks, CI, webhooks), gluing into an HTTP toolchain, or debugging the wire. Skip for SDK ergonomics (`SKILL-SDK.md`) or `hoody` CLI (`SKILL-CLI.md`). You handle pagination, retries, errors. ## Endpoint surface | Surface | Hostname | Auth | |---|---|---| | Control plane | `https://api.hoody.com` | `Authorization: Bearer ` | | Container kit | `https://{projectId}-{containerId}-{kit_slug}-{serviceIndex}.{server}.containers.hoody.com` | URL is the credential | See § Proxy URLs and § Auth model below. ## Reference table sigils Per-namespace `## Reference` tables compress params with sigils: - `{x}` — path param (already in URL). - `?x` / `?x*` — query param (`*` = required). - `body` / `body*` — JSON body (`*` = required); `body*:foo_CreateInput` names the schema. - `H:x` / `H:x*` — header param. - Type column dropped — inferable from name (`id` string, `limit` int, `enabled` bool). Body schema refs are kept verbatim. Bare `body*` rows are spelled out under the same service in a **Body shapes** block: `{ field*: type=default, … }` one-liners (`*` = required, `=v` = default, `|` = alternatives) plus field-semantics bullets. Named refs (`body*:foo_CreateInput`) resolve in the namespace's **Body schemas** appendix. ## Auth - Control plane: header starts with `Bearer ` (one space, capital B); an `hdy_` auth token may also be sent bare. Kit URL: none, on every kit including `bot`'s management routes — gate kit URLs with proxy permissions. - Sign-in: browser sign-in is the default — `POST /api/v1/auth/device/code`, give the user the link and code, poll `POST /api/v1/auth/device/token` (§ Login). Never collect a password in chat. - Password login (fallback the user chooses): `POST /api/v1/users/auth/login` with `{ username, password }` **or** `{ email, password }` — field **`token`**. `password` plus one identifier (`username` or `email`) is required; `username` must match `^[a-zA-Z0-9_-]+$` (3–50 chars), so an email address authenticates **only** through the `email` field — sending one as `username` returns `422 Validation failed`. Every Hoody account is created with an email, so `email` is the common path. - Long-lived: `POST /api/v1/auth/tokens`, only for unattended automation the user asked for. ## Response envelope Control plane (`api.hoody.com`) success: `{ "statusCode": 200, "message": "...", "data": { ...payload } }`. Paginated: shape varies per route. The page-based shape is `data.{: [...], pagination: { total, page, limit, totalPages }}` (e.g. projects, containers); iterate `?page=` until `totalPages`. A few routes (e.g. events) use `{ total, limit, offset, has_more }` instead — check the response type for the call you're making. `GET /api/v1/auth/available-regions` returns `r.data.regions` (single envelope wrap, like every other API response — earlier docs incorrectly called it doubly-wrapped). Errors: `{ "statusCode": 401, "error": "...", "message": "..." }`. Codes: § Reference appendix. Kit URLs use per-kit shapes: many answer bare JSON with no `data` wrapper (e.g. watch `POST /api/v1/watch/watchers` returns `{id,...}` at the root; tunnel `GET /api/v1/tunnel/tunnels` returns `{sessions,...}`). Check the kit's response schema before writing a `jq` path. ## Streaming - **SSE** — `Accept: text/event-stream`; use `curl --no-buffer`. Resume mechanism is per-endpoint: watcher uses `?since_id=` / `?since_timestamp=`; proxy-logs `/_logs/stream` honours `Last-Event-ID:` (on `event: reset` discard the saved id and reconnect fresh); `/api/v1/exec/logs/stream?file=` has no resume cursor (re-reads the file). Endpoints: watcher events, `/api/v1/exec/logs/stream?file=`, proxy-logs `/_logs/stream`. (Notifications `GET /api/v1/notifications/stream` serves both: a WebSocket upgrade, or SSE on a plain GET with `?displays=all` or a display list; the SDK's `notifications.connect` uses WebSocket.) - **WebSocket** — watcher `events/ws`, tunnel data planes. Use `websocat`/`wscat`. ## Index of common ops § Core ops cheat-sheet covers: auth (signup/login/2FA/refresh/long-lived); projects + containers (list/create/lifecycle, kit-URL resolution); one-off shell and terminal sessions; files up/down/append; display screenshot and click; sqlite db and KV; watch SSE; tunnels; snapshot/restore; vault; wallet; proxy alias. Per-namespace recipes in `SKILL-HTTP/.md`: `agent api bot browser code cron curl daemon display egress exec files notes notifications pipe proxyLogs run sqlite terminal tunnel watch`. --- # Proxy URLs — capability-based per-container routing ## What it is `https://{projectId}-{containerId}-{kit_slug}-{n}.{node}.containers.hoody.com` - Proxy terminates TLS on `*.containers.hoody.com`, parses the hostname segments (project, container, kit, index) and routes to that kit. - Hoody API: global `https://api.hoody.com`. - Aliases (`my-api.{N}.containers.hoody.com`) are shortcuts; canonical URL is authoritative. ## Components | Segment | Meaning | |---|---| | `projectId` | 24-char hex. | | `containerId` | 24-char hex. Bearer credential. | | `kit_slug` | Kit id (see Kit slug table); some namespaces differ from their slug (e.g. `notifications` → `n`, `proxyLogs` → `logs`). | | `n` | 1-based instance index; single-instance kits use `1`. | | `node` | Bare server hostname (use the `server_name` field from container responses). | | Suffix | `.containers.hoody.com` | ## Every kit URL is iframable — compose a UI out of kits Each kit URL serves a regular HTML/JS page (or HTTP/WS API) — drop it into an ` ``` You can compose a **full HTML "operating system" out of Hoody kit iframes** — no native code, no installer, just URLs. Hoody itself does this: `os.hoody.com` is essentially a kit-iframe shell. ### Collaborative embeds — work from inside the chat Most modern collaboration tools accept iframes (or unfurl URLs into rich previews that render iframes), so a Hoody kit URL drops straight into: | Platform | Embed surface | Outcome | |---|---|---| | **Slack** | Canvas embed, custom unfurls, Slack apps | Drop a `terminal-1` URL into a channel canvas → live shell that everyone in the channel can see + drive. Pair with a Cline `?extension=…` `code-1` URL for "agent-in-the-channel" support. | | **Notion** | `/embed` block (paste URL → Embed) | Wiki page that contains the live editor / agent / file browser as part of the doc. | | **ClickUp** | Embed view in any list / dashboard | Project board with the relevant repo's `files-1` and `code-1` panes alongside tickets. | | **Matrix / Element** | `m.html` event, custom widgets | Same as Slack — live terminal / agent in a room. | | **Microsoft Teams / Zoom** | Apps that accept URL iframes | Shared workbench during calls. | | **Discord** | Activity URLs, link previews | Drop the URL; viewers click into the live surface. | | **Confluence / Jira** | "Smart Link" / iframe macro | Runbook page with the live tool baked in. | | **Plain HTML** | ` ``` To keep the `containerId` out of the iframe `src`, create a proxy alias on the `code` service with the landing query as its `target_path`, and use the URL the call returns. Leave `id` out of the target: the alias's `index` picks the instance, and a target query naming `id` is refused with `404 ALIAS_TARGET_QUERY_FORCED_KEY`. The `folder` (and `extension`) in the target is a landing preference only: the editor opens there, but it does not confine the session, and anyone using the editor can open any other folder the container user can read. ```bash curl -sX POST "https://api.hoody.com/api/v1/proxy/aliases" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d "$(jq -nc --arg cid "$C" '{container_id:$cid, program:"code", index:1, alias:"agent", target_path:"/?extension=saoudrizwan.claude-dev&folder=/home/user/myrepo"}')" ``` Gate the alias with `* /api/v1/containers/{id}/proxy/permissions*` before sharing it (see the `api` namespace). The same iframe pattern works for **every** Hoody kit (`files`, `terminal`, `display`, `desktop`, `browser`, `notes`, `agent`, …). ## Reference ### `code` (1) — VS Code web interface | Method | Summary | Params | |--------|---------|--------| | `DELETE /api/v1/code` | Stop an editor instance | `?id` | **Param notes:** - `id` — Which instance to stop. On a `code-{N}` service URL the edge proxy sets it from the hostname and overrides any value sent, so a caller there neither needs to send it nor can change it. It is required: there is no default instance to stop, so a request without it is answered `400`. Read exactly as strictly as the selector on `GET /api/v1/code`: an unsigned decimal integer, under the literal name `id` only, never given more than once, and at most `65535 - basePort`. ### `extensions` (2) — Extension staging and inspection | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/code/extensions/install` | Stage a VS Code extension from a URL | `?id` `body*` | | `GET /api/v1/code/extensions/list` | Staged extensions, and what the instance appears to have installed | `?id` | **Param notes:** - `id` — Which instance this request is about. Required here, unlike on `GET /api/v1/code`. That operation has a discovery branch to fall back to when no selector is given; this one does not, so a request without an `id` has named no instance and is rejected rather than defaulted to a first one. The value is read exactly as strictly as the selector on `GET /api/v1/code`: an unsigned decimal integer, under the literal name `id` only, never given more than once, and at most `65535 - basePort`. See that operation for the full rules. Where it comes from: On a `code-N` service URL the platform's edge proxy sets it from the hostname, so a caller behind the edge neither sends it nor can override it, and the generated clients leave it out of the query for exactly that reason. It is required because there is no discovery branch here to fall back to: a request without an `id` has named no instance and is answered `400`. **Body shapes:** - `POST /api/v1/code/extensions/install` body — `{ url*: string, allowDowngrade: bool=false }` - `url` — HTTPS or HTTP URL of the `.vsix` to stage. - `allowDowngrade` — Permit replacing a staged version with an older one. Refused by default so a routine restage cannot silently roll an extension back. ### `kit` (3) — Health, version and status monitoring | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/code/health` | Service health check | | | `GET /status` | Get orchestrator and instance status | | | `GET /api/v1/code/version` | Versions of the running orchestrator and its packaged editor | | ### `ui` (4) — Static assets and descriptors served by this host | Method | Summary | Params | |--------|---------|--------| | `GET /favicon.ico` | Site icon | | | `GET /api/v1/code/manifest.json` | Web application manifest for installing the editor | | | `GET /robots.txt` | Crawler policy | | | `GET /security.txt` | Security contact information | | --- # `cron` — managed crontab entries per system user ## Purpose Edit `crontab(1)` of a system user. UUID-keyed managed entries (name, comment, expiry, enabled) coexist with hand-written lines. Sweep drops expired. ## When to use - Recurring jobs via cron daemon. - Future commands with `expires_at` cleanup. - Repair crontab without losing hand-written lines. ## When NOT to use Not for: ad-hoc → `terminal`/`exec`, long-runners → `daemon`, FS triggers → `watch`. ## Prerequisites - `crontab(1)` + cron daemon present; `user` in `/etc/passwd`. - `user`-scoped. ## Capability URL → See `SKILL-HTTP.md § Proxy URLs`. **Reaching a service you host on a container port** (any port, any namespace): - `https://{projectId}-{containerId}-http-.{node}.containers.hoody.com` — proxy speaks HTTP to `localhost:`. - `https://{projectId}-{containerId}-https-.{node}.containers.hoody.com` — proxy speaks HTTPS to `localhost:` (target needs TLS). Edge is always `https://`. No alias, firewall edit, or proxy registration needed; capability-token gates still apply. ## Common workflows ### 1. Schedule `POST /api/v1/cron/users/{user}/entries` takes a schedule + command (plus name/comment/expires_at/enabled) and returns the created entry with its `id`. ### 2. List `GET /api/v1/cron/users/{user}/entries` (`page`/`limit`, max 200). ### 3. Edit / disable / extend `PATCH /api/v1/cron/users/{user}/entries/{id}` PATCH. `clear_expiration: true` overrides `expires_at`. `enabled: false` keeps rule prefixed `# hoody-cron-disabled:`. ### 4. Bulk replace For a normal bulk replace, read with `GET /api/v1/cron/users/{user}/crontab` (sweep), edit the returned text, then call `PUT /api/v1/cron/users/{user}/crontab` with the body — it revalidates `# hoody-cron:` blocks, and the response has `removed_expired`. If a read or entry call fails with `409 STORED_CRONTAB_INVALID` (the stored crontab cannot be used), read `details` and repair it by calling `PUT /api/v1/cron/users/{user}/crontab` directly with a complete, valid replacement: PUT does not read the stored crontab, and anything you leave out of the replacement is removed. ### 5. Audit all users `GET /api/v1/cron/crontab` → paginated `{ items: [{ user, crontab }], total, page, limit }`. ## Quirks & gotchas - `user`: matches `^[A-Za-z0-9_.-]{1,32}$` for the character class, but the validator additionally rejects a **leading** `-` (trailing `-` is allowed). - Vixie 5-field plus standard `@`-macros; Quartz rejected. - `command`/`name`/`comment` reject newline/null/VT/FF/NEL/LS/PS; caps 4096/120/500. - Send a managed entry's command exactly as a shell would run it, and do not escape `%`: the kit writes it into the crontab as `\%` so cron runs the command unchanged and reads it back the same way. A `\%` you send is escaped again and runs as `\%`, backslash included. Raw lines in a `PUT /api/v1/cron/users/{user}/crontab` body are written as given, so a `%` there follows crontab rules: a bare `%` ends the command, and `\%` is a literal `%`. - A managed entry's command is read back from the spool exactly as written, runs of whitespace included, so a later write for that user stores it unchanged: `echo "a b"` stays `echo "a b"`. - `expires_at` RFC 3339, strictly future. - Body cap 256 KiB by default, which the deployment can change, AND 10,000 lines; duplicate entry id rejected, and a duplicate `id=` within one metadata line is rejected. - **`PUT /api/v1/cron/users/{user}/crontab` replaces the whole crontab.** `GET /api/v1/cron/users/{user}/crontab` returns each managed entry as its `# hoody-cron:` metadata line followed by its rule line, and PUT parses those pairs back into the same managed entries with the same ids. So a read, edit, write cycle keeps every managed entry whose two lines are still in the body; a managed entry left out of the body is deleted. Edit the text from `GET /api/v1/cron/users/{user}/crontab` instead of writing a fresh body, and do not re-create managed entries after a PUT: they are still there. Re-creating an identical entry answers 200 with the existing one and writes nothing; the same schedule and command with a different name, comment, `expires_at` or `enabled` is `409 ENTRY_EXISTS` (details give its id), so change it with PATCH. Comment or blank lines placed between a metadata line and its rule line are dropped. - A PUT body may contain `# hoody-cron:` metadata lines written by the caller. The kit revalidates every managed entry it parses from them (schedule, command, name, comment) and rejects duplicate ids, but it does not check where the metadata came from: a well-formed pair written by hand is accepted as a managed entry, and a metadata line it cannot parse or pair is kept as a raw line. Every other non-comment line gets the syntax check of `crontab(1)`: a line it would refuse is `400 INVALID_CRONTAB` naming that line, and nothing is written. - `GET /api/v1/cron/users/{user}/entries`/`GET /api/v1/cron/users/{user}/entries/{id}` clean expired entries before serializing under a per-user mutex — a GET can mutate the spool. - `GET /api/v1/cron/users/{user}/entries` items have `type: "managed"` or `"raw"`; only `managed` items carry `id`. - Sweep every 60s default; per-user lock. ## Common errors Error bodies are `{ code, message, details }`, except where noted. - `409 STORED_CRONTAB_INVALID` — the crontab already stored for the user cannot be used (a Unicode line break, a `# hoody-cron:` line with two id fields, or over the line or byte cap); nothing in your request is wrong. Repair it with `PUT /api/v1/cron/users/{user}/crontab` (workflow 4). - `400 INVALID_EXPIRES_AT` / `EXPIRES_IN_PAST`. - `400 INVALID_SCHEDULE / Invalid schedule` — Vixie 5-field plus `@`-macros only; Quartz / 6-field rejected. - `400 INVALID_USER` (bad user name), `INVALID_COMMAND`, `INVALID_NAME`, `INVALID_COMMENT`: a field failed validation (see Quirks for the rules). - `400 INVALID_ID` `Entry id must be a UUID`: the `{id}` path segment is not a UUID. - `400 INVALID_PAGINATION`: `page` must be 1 or more and `limit` 1 to 200 (default 50). - `404 USER_NOT_FOUND`: the user is not in `/etc/passwd`. `404 ENTRY_NOT_FOUND`: no managed entry has that id (it may have expired and been swept). - `413 PAYLOAD_TOO_LARGE`: a request body over the size cap (256 KiB by default), or a crontab over 10,000 lines or over its separate byte ceiling of about 40 MB, which only a deployment that raised the size cap can reach. - `415 UNSUPPORTED_MEDIA_TYPE`: the Content-Type is neither `application/json` nor an `application/*+json` type. `400 INVALID_JSON`: the body is not valid JSON. `400 INVALID_BODY`: the JSON does not match the request fields (a missing or mistyped field). - `500 BACKEND_ERROR` — `crontab(1)` fail / 30s timeout. - `403 Forbidden` — Refused by the Source IP Guard: Hoody Kit programs are reached through their URLs only. The body is the plain text `Forbidden`, not JSON. ## Related namespaces - `terminal`, `daemon`, `exec`, `watch`, `files`. ## Examples Each step has a copy-pasteable code block in the mode you're reading (curl for HTTP, `hoody` for CLI, TypeScript for SDK). Set `P`, `C`, `N` (project id, container id, server name) from `GET /api/v1/containers/{id}` first. ### 1. Set up a nightly DB backup with trial-run dry-fire **Goal:** schedule `pg_dump` daily at 02:00 in the container's LOCAL timezone (the kit does no TZ conversion; only `expires_at` is UTC-anchored), set the entry to expire one year from now; first verify it actually fires by running it every minute for one cycle. **Step 1 — create the entry.** Capture the returned `id`; `schedule_human` should read `"At 02:00 every day"`. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" EXP=$(date -u -d '+1 year' +%FT%TZ) # expires_at must be in the future ID=$(curl -sX POST "$KIT/api/v1/cron/users/root/entries" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg e "$EXP" '{ schedule: "0 2 * * *", command: "pg_dump -U postgres mydb | gzip > /backups/db-$(date +%F).sql.gz", name: "nightly-db-backup", expires_at: $e }')" | jq -r '.id') echo "id=$ID" ``` **Step 2 — trial-run** by tightening to every minute. Wait ~70 s then `tail /var/log/syslog` (via the `terminal` kit) to confirm cron actually fired the job. ```bash curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ID" \ -H 'Content-Type: application/json' \ -d '{"schedule":"* * * * *","comment":"TEST MODE — revert before merge"}' ``` **Step 3 — promote back to nightly** with a clean comment. ```bash curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ID" \ -H 'Content-Type: application/json' \ -d '{"schedule":"0 2 * * *","comment":"production schedule"}' ``` ### 2. Maintenance window — pause every managed job, do work, resume **Goal:** disable every managed entry so nothing fires during a 30-min DB migration; re-enable once clean. **Step 1 — capture every enabled managed id.** The listing is paginated (50 per page by default, at most 200), so over HTTP read every page before filtering: a job left on a later page stays enabled through the migration. The CLI fetches every page itself, up to 10,000 items or 1,000 requests, so check that it returned `total` rows. Run steps 1 and 2 as one script that exits on any listing or update failure, and start the migration only when it exits successfully; a partial list or a failed disable leaves jobs enabled. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" IDS=""; page=1 while :; do body=$(curl -sf "$KIT/api/v1/cron/users/root/entries?page=$page&limit=200") \ || { echo "listing page $page failed" >&2; exit 1; } ids=$(jq -r '.entries[] | select(.type=="managed" and .enabled) | .id' <<<"$body") \ || { echo "unreadable listing" >&2; exit 1; } IDS="$IDS $ids" [ $((page * 200)) -lt "$(jq -r .total <<<"$body")" ] || break page=$((page + 1)) done echo "$IDS" ``` **Step 2 — bulk disable.** ```bash for id in $IDS; do curl -sf -X PATCH "$KIT/api/v1/cron/users/root/entries/$id" \ -H 'Content-Type: application/json' \ -d '{"enabled":false}' >/dev/null \ || { echo "disable failed for $id: do not start the migration" >&2; exit 1; } done ``` **Step 3 — run your migration. Step 4 — bulk re-enable** the captured ids (same loop with `enabled: true`). After a failed step 2, re-enable the same list: the entries disabled before the failure are still disabled. Entries pick up at their next regular tick; no missed-window catch-up. ### 3. Migrate a hand-written crontab into managed entries **Goal:** convert legacy raw lines (no `id`, no metadata) into managed entries with names + lifecycle fields, then remove the raw originals so nothing runs twice. **Step 1 — collect the raw lines to migrate.** `GET /api/v1/cron/users/{user}/entries` returns hand-written lines as `{ type: 'raw', line }` items; managed entries are `type: 'managed'` and are left alone. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" # Raw items only; skip blanks, comments and environment lines (SHELL=, MAILTO = ..., "A B" = c). : > /tmp/cron-migrate.txt; page=1 while :; do body=$(curl -sf "$KIT/api/v1/cron/users/root/entries?page=$page&limit=200") || exit 1 jq -r '.entries[] | select(.type=="raw") | .line' <<<"$body" \ | grep -Ev "^[[:space:]]*(\$|#|([A-Za-z_][A-Za-z0-9_]*|\"[^\"]*\"|'[^']*')[[:space:]]*=)" >> /tmp/cron-migrate.txt [ $((page * 200)) -lt "$(jq -r .total <<<"$body")" ] || break page=$((page + 1)) done cat /tmp/cron-migrate.txt ``` **Before step 2 — check every line for `%` and `\`.** A raw line is in crontab syntax and a managed command is not: in a raw line a bare `%` ends the command and sends the rest to its stdin, and `\%` and `\\` stand for `%` and `\`, while the kit escapes a managed command itself (see Quirks). The scripts below copy the command text as it is, so they keep a line's meaning only when it contains neither `%` nor `\`. Take any other line out of the step 1 list and migrate it by hand: write the command cron actually runs (`\%` becomes `%`, `\\` becomes `\`, and a `%`-delimited stdin becomes a pipe or a here-string) and create its entry from that. Step 3 drops only the lines still in the list, so remove the raw lines you migrated by hand the same way, or each of those jobs runs twice. **Step 2 — create a managed entry per line.** An `@macro` line (`@daily`, `@reboot`, ...) has a one-field schedule; any other line has five fields. The rest of the line is the command. ```bash i=0; FAILED=0 while IFS= read -r LINE; do i=$((i + 1)) case "$(echo "$LINE" | sed -E 's/^[[:space:]]+//')" in @*) F=1 ;; *) F=5 ;; esac SCHED=$(echo "$LINE" | awk -v f="$F" '{s=$1; for (k = 2; k <= f; k++) s = s " " $k; print s}') CMD=$(echo "$LINE" | sed -E "s/^[[:space:]]*([^[:space:]]+[[:space:]]+){$F}//") curl -sf -X POST "$KIT/api/v1/cron/users/root/entries" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg s "$SCHED" --arg c "$CMD" --arg n "migrated-$i" '{schedule:$s,command:$c,name:$n}')" >/dev/null \ || { echo "create failed for: $LINE" >&2; FAILED=1; break; } done < /tmp/cron-migrate.txt [ "$FAILED" = 0 ] || exit 1 # stop here: step 3 must not run after a failed create ``` **Step 3 — remove only the migrated raw lines.** Only after every create in step 2 succeeded: run steps 2 and 3 as one script, so the stop after a failed create also skips this step. After a partial failure, the managed entries created so far run alongside their raw lines (each of those jobs runs twice) until you delete them or finish the migration. Read the crontab text again (it now contains the new managed entries as `# hoody-cron:` metadata and rule line pairs), drop the raw lines from step 1 and write the rest back. A new managed entry's rule line is usually the same text as the raw line it replaces, so match a line only when the line before it is not a `# hoody-cron:` metadata line: dropping a rule line leaves its metadata unpaired, and the managed entry is lost. The PUT keeps every managed entry that is still in the text, with the same id. Do not PUT an empty crontab here: that would delete the entries step 2 just created. ```bash [ -s /tmp/cron-migrate.txt ] || exit 0 # nothing to drop BODY=$(curl -sf "$KIT/api/v1/cron/users/root/crontab") || exit 1 CUR=$(jq -er '.crontab | select(type == "string")' <<<"$BODY") || exit 1 # Drop a listed line only when it does not follow a "# hoody-cron:" metadata line. NEW=$(printf '%s\n' "$CUR" | awk 'NR == FNR { drop[$0] = 1; next } { keep = !($0 in drop) || prev ~ /^[[:space:]]*# hoody-cron:/; prev = $0 } keep' /tmp/cron-migrate.txt -) curl -sf -X PUT "$KIT/api/v1/cron/users/root/crontab" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg c "$NEW" '{crontab:$c}')" ``` ### 4. Hourly poll → tighten to every 5 minutes after a failure **Goal:** a health-poller is failing intermittently; you want denser data without redeploying anything. Find by name, change schedule, restore later. **Step 1 — find the entry id by name.** Names are not unique and the listing is paginated, so read every page and stop unless exactly one managed entry carries the name. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" ID=""; page=1 while :; do body=$(curl -sf "$KIT/api/v1/cron/users/root/entries?page=$page&limit=200") || exit 1 ID="$ID $(jq -r '.entries[] | select(.type=="managed" and .name=="health-poll") | .id' <<<"$body")" [ $((page * 200)) -lt "$(jq -r .total <<<"$body")" ] || break page=$((page + 1)) done set -- $ID [ $# -eq 1 ] || { echo "expected one entry named health-poll, found $#: $ID" >&2; exit 1; } ID=$1 ``` **Step 2 — tighten to `*/5 * * * *`.** `schedule_human` becomes `"Every 5 minutes"` immediately on the response. ```bash curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ID" \ -H 'Content-Type: application/json' -d '{"schedule":"*/5 * * * *"}' ``` **Step 3 — restore** to hourly once the investigation is over: the same call with the JSON body `{"schedule":"0 * * * *"}`. ### 5. Time-bounded experiment — auto-expire after 30 days **Goal:** run a daily metrics sample for one month, then have it self-remove. Then learn how to extend or unbound the deadline. **Step 1 — create with `expires_at`.** ISO 8601 RFC 3339; must be in the future. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" EXP=$(date -u -d '+30 days' +%FT%TZ) ID=$(curl -sX POST "$KIT/api/v1/cron/users/root/entries" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg e "$EXP" '{ schedule: "@daily", command: "/opt/metrics/sample.sh", name: "metrics-experiment", expires_at: $e }')" | jq -r .id) ``` After the timestamp passes, the kit's 60 s sweep **deletes** expired managed entries. `GET /api/v1/cron/users/{user}/entries`/`GET /api/v1/cron/users/{user}/entries/{id}` also clean expired entries before serializing, so once the sweep runs you can no longer read the expired entry — the entry simply disappears from listings. The `removed_expired` count on `PUT /api/v1/cron/users/{user}/crontab` tells you how many expired entries got dropped during a bulk replace. **Step 2a — extend the deadline mid-experiment** (to 60 days from now): ```bash curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ID" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg e "$(date -u -d '+60 days' +%FT%TZ)" '{expires_at:$e}')" ``` **Step 2b — make it permanent** instead. Pass `clear_expiration: true`. If you also send `expires_at` in the same call, `clear_expiration` silently wins (server returns `200` with `expires_at: null` — no error). ```bash curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ID" \ -H 'Content-Type: application/json' -d '{"clear_expiration":true}' ``` ### 6. Quick-disable a misbehaving entry by name **Goal:** A teammate paged you about a runaway cron at 3am. You don't have the id, only the name they mentioned (`noisy-job`). **Step 1 — find its id by name.** Read every page and require exactly one match; if several entries share the name, pick the intended id explicitly. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" ENTRY_ID=""; page=1 while :; do body=$(curl -sf "$KIT/api/v1/cron/users/root/entries?page=$page&limit=200") || exit 1 ENTRY_ID="$ENTRY_ID $(jq -r '.entries[] | select(.type=="managed" and .name=="noisy-job") | .id' <<<"$body")" [ $((page * 200)) -lt "$(jq -r .total <<<"$body")" ] || break page=$((page + 1)) done set -- $ENTRY_ID [ $# -eq 1 ] || { echo "expected one entry named noisy-job, found $#: $ENTRY_ID" >&2; exit 1; } ENTRY_ID=$1 ``` **Step 2 — disable it (entry stays in the listing for forensics; cron won't fire it).** ```bash curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ENTRY_ID" \ -H 'Content-Type: application/json' \ -d "{\"enabled\":false,\"comment\":\"disabled $(date -u +%FT%TZ) — investigating\"}" ``` **Step 3 — re-enable later** by calling the same update with `enabled: true`. ### 7. Audit which users on the container have any cron entries **Goal:** compliance question — "who has scheduled jobs?". A container has 60+ system users, more than the default page of 50, so read every page. `GET /api/v1/cron/crontab` returns one record per account in `/etc/passwd` (`{ user, crontab }`), 50 per page by default and at most 200. Filter client-side for non-empty `crontab`. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" page=1 while :; do body=$(curl -sf "$KIT/api/v1/cron/crontab?page=$page&limit=200") || break jq '.items[] | select(.crontab | test("\\S")) | {user, crontab}' <<<"$body" [ $((page * 200)) -lt "$(jq -r .total <<<"$body")" ] || break page=$((page + 1)) done ``` For each non-empty user, drill in via `GET /api/v1/cron/users/{user}/entries` for that user for the managed view, or read the `crontab` text directly from the listing above. ### 8. Atomic full-crontab replace from versioned config **Goal:** your IaC layer keeps the canonical crontab as a string in Git; on deploy, push the whole thing. ⚠ The canonical text becomes the whole crontab: raw lines not in it are removed, and so is every managed entry whose `# hoody-cron:` metadata and rule lines are not in it. **Step 1 — snapshot current state** for forensics: ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/cron/users/root/crontab" > /tmp/cron-snapshot.json ``` **Step 2 — push the canonical config.** Body MUST use `application/json` or an `application/*+json` Content-Type (raw `text/plain` returns `415`). Response carries `removed_expired` (count of managed entries that were dropped because their `expires_at` had passed). ```bash NEW=$(cat /etc/iac/canonical-crontab.txt) curl -sX PUT "$KIT/api/v1/cron/users/root/crontab" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg c "$NEW" '{crontab:$c}')" ``` ### 9. Update only the comment / metadata, leave the schedule untouched **Goal:** add a runbook URL or owner tag without changing the schedule or the enabled state. PATCH is partial — fields you don't pass are not assigned. ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" curl -sX PATCH "$KIT/api/v1/cron/users/root/entries/$ID" \ -H 'Content-Type: application/json' \ -d '{"comment":"owner: @team · runbook: https://wiki.example.com/cron-x"}' ``` `updated_at` advances; `schedule`, `enabled` and `command` are unchanged. ### 10. Rotate-and-replace pattern — read, edit text, write back **Goal:** a teammate wants ONE hand-written line gone without disturbing the rest. You don't have an id (it's raw). Match the whole line exactly, and skip a matching line that follows a `# hoody-cron:` metadata line: that one is a managed entry's rule, and dropping it orphans the entry. **Step 1 — fetch** the multi-line string. **Step 2 — edit client-side** (split, drop, rejoin). **Step 3 — write back.** Managed entries survive: the fetched text holds each one as a `# hoody-cron:` metadata line plus its rule line, and the PUT parses them back with the same ids. Leave those lines untouched; there is nothing to re-create afterwards (an identical create answers 200 with the existing entry, a changed one `409 ENTRY_EXISTS`). ```bash KIT="https://${P}-${C}-cron-1.${N}.containers.hoody.com" # Check the read and the parse separately: a failed read must never become an empty PUT. BODY=$(curl -sf "$KIT/api/v1/cron/users/root/crontab") || exit 1 CUR=$(jq -er '.crontab | select(type == "string")' <<<"$BODY") || exit 1 NEW=$(printf '%s\n' "$CUR" | awk -v target='*/30 * * * * /old.sh' \ '{ keep = $0 != target || prev ~ /^[[:space:]]*# hoody-cron:/; prev = $0 } keep') curl -sX PUT "$KIT/api/v1/cron/users/root/crontab" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg c "$NEW" '{crontab:$c}')" ``` ## Reference ### `crontabs` (3) — Raw crontab management | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/cron/users/{user}/crontab` | Get Crontab | | | `GET /api/v1/cron/crontab` | List All Crontabs | `?page` `?limit` | | `PUT /api/v1/cron/users/{user}/crontab` | Put Crontab | `body*:cron_RawCrontabRequest` | **Param notes:** - `user` — System username - `page` — Page number (1-based, default 1) - `limit` — Items per page (default 50, max 200) ### `entries` (5) — Managed entry CRUD | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/cron/users/{user}/entries` | Create Entry | `body*:cron_CreateEntryRequest` | | `DELETE /api/v1/cron/users/{user}/entries/{id}` | Delete Entry | | | `GET /api/v1/cron/users/{user}/entries/{id}` | Get Entry | | | `GET /api/v1/cron/users/{user}/entries` | List Entries | `?page` `?limit` | | `PATCH /api/v1/cron/users/{user}/entries/{id}` | Update Entry | `body*:cron_UpdateEntryRequest` | **Param notes:** - `user` — System username - `page` — Page number (1-based, default 1) - `limit` — Items per page (default 50, max 200) ### `kit` (1) — System endpoints | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/cron/health` | Health Check | | ### Body schemas - `cron_RawCrontabRequest` — `{ crontab*: string }` - `cron_CreateEntryRequest` — `{ command*: string, comment: string|null, enabled: bool|null, expires_at: string|null, name: string|null, schedule*: string }` - `cron_UpdateEntryRequest` — `{ clear_expiration: bool|null, command: string|null, comment: string|null, enabled: bool|null, expires_at: string|null, name: string|null, schedule: string|null }` --- # `curl` — full HTTP client gateway + REST-as-GET-URL bridge ## Purpose Full HTTP client gateway. Sync/async jobs, cookie jars, bodies to storage, cron schedules. **Killer use case: turn any REST request — POST / PUT / PATCH / DELETE with bodies and headers — into a single GET-able URL** that works in a browser tab, a webhook field that only takes a URL, an LLM tool with web-search-only access, an `` / ``, or any environment that can't issue a non-GET request. The kit takes care of the actual HTTP call; the caller just hits a query-string URL. ## When to use - **REST-as-GET bridge** — any environment that can only do GET (browsers, restricted webhooks, agents with only "fetch URL" capability, RSS-style schedulers, copy-pasteable links). See workflow #1 for the URL recipe. - A server-side HTTP client (redirect following, TLS verification control, retries, cookie sessions) when you can't / don't want to use `fetch()`. Client certificates, custom CA files and outbound proxies are rejected over the API, and there is no HTTP-version option. - Long downloads as background jobs. - Multi-step auth with cookie jars (server-side session reused across hits). - Recurring HTTP (pings, scrapes, webhooks) on a cron. ## When NOT to use Not for: browser → `browser`, shell → `exec`/`terminal`, KV/SQL → `sqlite`, files → `files`, non-HTTP timers → `cron`. ## Prerequisites - Instance `1`; no workspace ID. - `* /api/v1/curl/schedule*` 404s if disabled. ## Capability URL → See `SKILL-HTTP.md § Proxy URLs`. **Reaching a service you host on a container port** (any port, any namespace): - `https://{projectId}-{containerId}-http-.{node}.containers.hoody.com` — proxy speaks HTTP to `localhost:`. - `https://{projectId}-{containerId}-https-.{node}.containers.hoody.com` — proxy speaks HTTPS to `localhost:` (target needs TLS). Edge is always `https://`. No alias, firewall edit, or proxy registration needed; capability-token gates still apply. ## Common workflows ### 1. Convert any REST call into a single GET-able URL (HTTP only) `GET /api/v1/curl/request?url=&method=` on the curl kit URL. The kit executes the upstream request and returns a JSON envelope `{ success, job_id, status_code, headers, body, is_binary, timing, metadata }`. Useful when the caller can only emit a GET (browser, webhook, sandboxed agent, RSS-ish puller, link in an email). Note: the GET bridge accepts `url` + `method` + the 13 timing/follow/session/response/save flags (`response`, `mode`, `session_id`, `follow_redirects`, `timeout`, `user_agent`, `referer`, `bearer_token`, `save`, `save_path`, `insecure`, `compressed`, `job_name`) **AND a full request body + headers right in the query string**: `data` (raw body, curl `--data`), `json` (parsed JSON; sets `Content-Type: application/json`), `data_base64` (binary-safe; standard OR URL-safe base64, padding optional; takes precedence over `data`/`json`), the aliases `body` and `body_base64` (for `data` and `data_base64`; the canonical name wins when both are given), and repeatable `header=Name: Value`. **Supplying a body auto-upgrades the default method GET→POST** — so a body-bearing POST/PUT/PATCH (with headers) is expressible as a single GET URL. Every other request field is POST-only: a headers map, `form` (URL-encoded fields), `cookie`, `auth_user` / `auth_password` / `auth_method`, `connect_timeout`, `max_redirects`, `max_filesize`, `tcp_nodelay`, `keepalive`, `keepalive_time`, `range`, `speed_limit`, `speed_time`, `retry_count` and `retry_delay`. The GET bridge ignores any of them in the query string without an error, so the request is sent without it. Neither form sends a multipart upload or reads a file from disk (`--data-binary @file`). To send arbitrary binary bytes, use `data_base64` on the GET bridge; the POST JSON form rejects a `data_base64` field with 400 (it refuses any unknown field). Live examples (verified — replace the kit URL with your container's): - Plain GET upstream: `https://{P}-{C}-curl-1.{N}.containers.hoody.com/api/v1/curl/request?url=https://httpbin.org/get` - HEAD upstream: `https://{P}-{C}-curl-1.{N}.containers.hoody.com/api/v1/curl/request?url=https://httpbin.org/get&method=HEAD` Combine with `POST /api/v1/proxy/aliases` with `{ program: 'curl' }` to give the bridge a brandable hostname like `https://api-bridge.{server_name}.containers.hoody.com/api/v1/curl/request?...` and hide the `containerId`. Every hit on `GET /api/v1/curl/request` **executes** the upstream request. When the deployment enables the kit's response cache (it is off by default), an eligible request can be answered from the cache instead. To compose a URL without firing it, build it client-side or create a proxy alias with `program: 'curl'`: a request to the alias host that carries its own path, such as `/api/v1/curl/request?...`, is forwarded as sent, and `target_path` only sets what the bare root URL serves. For the imperative full-cURL surface (a headers map, `form` fields sent URL-encoded, cookies, auth, follow-redirects, `insecure`, etc.) use the POST form below — though note the kit refuses client-certificate files and an upstream proxy (an SSRF guard; the request schema no longer lists them), and accepts every other body, auth and connection field. ### 2. Sync request `POST /api/v1/curl/request` with `mode:"sync"` (default), `response:"json"` (envelope) or `"transparent"` (raw). ### 3. Async job 1. `POST /api/v1/curl/request` with `mode:"async"` → `job_id`. 2. Poll `GET /api/v1/curl/jobs/{id}` or subscribe `GET /api/v1/curl/sse` (SSE) filtered by `job_id`. 3. `GET /api/v1/curl/jobs/{id}/result`; `DELETE /api/v1/curl/jobs/{id}` aborts. `GET /api/v1/curl/jobs/{id}` reports `retry_attempts`: 1 for a job that ran once, plus one per retry after a transfer error. ### 4. Cookie-jar session 1. `POST /api/v1/curl/request` with `session_id:""` auto-creates jar. 2. Reuse same `session_id` on follow-ups. 3. `GET /api/v1/curl/sessions/{id}/cookies` / `DELETE /api/v1/curl/sessions/{id}`. ### 5. Save download 1. `POST /api/v1/curl/request` with `save:true` and optional relative `save_path` under `downloads/by-job/{job_id}/`. 2. `GET /api/v1/curl/storage`/`GET /api/v1/curl/storage/{path}`/`DELETE /api/v1/curl/storage/{path}` with relative path (e.g. `by-job//x.pdf`). ### 6. Scheduled request 1. `POST /api/v1/curl/schedule` with `{cron,request}` → `schedule_id`. Add `enabled: false` to create it paused: it never fires until `PATCH /api/v1/curl/schedule/{id}` sets `enabled: true`. 2. `GET /api/v1/curl/schedule`/`GET /api/v1/curl/schedule/{id}`/`PATCH /api/v1/curl/schedule/{id}` (`{"enabled":bool}` pauses or resumes)/`DELETE /api/v1/curl/schedule/{id}`. 3. Each admitted occurrence creates a job; inspect via `GET /api/v1/curl/jobs`. An occurrence is skipped, with no job, while the previous run is still in flight or when the job queue rejects it. ## Quirks & gotchas - Default `response`: POST→`transparent`, GET→`json`. - Default `mode:"sync"`; pass `"async"` for `job_id`. - `save_path` rejected if empty, absolute, rooted, or has `..`. - Saved files at `downloads/by-job/{job_id}/...`; pass relative path. - **A saved download is stored under `by-job/{job_id}/`, with best-effort index links** `by-date//` and `by-domain//`. A URL whose host is an IP literal gets no `by-domain` link, and a symlink that cannot be created is skipped silently (failing to create an index directory fails the save), so expect one to three entries. `GET /api/v1/curl/storage` returns one item per path; the bytes are the same file. - `*.list` returns ALL when `limit` omitted; always pass `limit`. - `* /api/v1/curl/schedule*` 404s if disabled. - `PATCH /api/v1/curl/schedule/{id}` changes any of `cron`, `request` and `enabled`; omitted fields keep their current value, so pause or resume by sending `enabled: false` or `enabled: true` alone. The `PATCH /api/v1/curl/schedule/{id}/toggle` route instead requires an explicit boolean `enabled`; else 400. - `POST /api/v1/curl/schedule` takes `enabled` (default `true`). A schedule created with `enabled: false` has no `next_run` and does not fire; its `cron` must still parse but need not have a future occurrence yet. Any field other than `cron`, `request` and `enabled` is refused with 400 `INVALID_PARAMETER`. - `bearer_token` sends `Authorization: Bearer `, but an `Authorization` entry in `headers` (or `header=Authorization: …` on the GET bridge) wins: the token is then not sent, so the request carries one `Authorization` header. - `GET /api/v1/curl/jobs/{id}/result` always answers `200` with the target's body and headers, whatever the target answered; the target's status code is in the `X-Curl-Status` header (and in `response.status_code` from `GET /api/v1/curl/jobs/{id}`). A stored `429` or `503` is therefore not retried as a kit failure. - **`schedules.create.cron` is 6-field (with seconds), NOT the standard 5-field crontab.** `*/15 * * * *` is rejected as `Invalid cron expression`; use `0 */15 * * * *` (at second 0 every 15 min). The standard @-nicknames (`@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`) ARE accepted (expanded internally to 6-field), but Go-style `@every 15m` is NOT — for anything else use explicit 6-field expressions. Different syntax from the `cron` namespace, which uses Vixie 5-field. - `session_id` is caller-provided. - Job events stream over a WebSocket at `/api/v1/curl/ws`; filter by `job_id`. ## Common errors - `504` — the upstream request timed out (libcurl timeout); raise `timeout`. An async job does not wait on the caller's connection, but the same `timeout` still applies to the upstream request. The kit itself does not answer `408`; a transparent `run` response passes the upstream's own status through (`GET /api/v1/curl/jobs/{id}/result` does not: it answers 200 with `X-Curl-Status`), so an upstream `408` arrives as `408`. - Cancelling a job answers `200`; no REST call answers `410`. Read `GET /api/v1/curl/jobs/{id}` for `status: "cancelled"`, and stop waiting once a job is `failed` or `cancelled`. `GET /api/v1/curl/jobs/{id}/result` answers `404 JOB_RESULT_NOT_READY` when the job has no response body (still pending or running, or finished without an upstream response). - `503 queue full` (also SSE capacity exhausted) — back off. ## Related namespaces `browser` (JS/DOM), `exec` (shell), `cron` (timers), `files` (general IO), `sqlite` (parsed data). ## Examples Each step has a copy-pasteable code block in the mode you're reading (curl for HTTP, `hoody` for CLI, TypeScript for SDK). Set `P`, `C`, `N` (project id, container id, server name) from `GET /api/v1/containers/{id}` first. ### 1. Webhook receiver bridge — outbound system can only fire GETs **Goal:** your CRM can fire URLs but not POST. Translate a click → real upstream POST with JSON body + bearer. **Step 1 — compose the bridge URL — body and headers go right in the query string.** The GET bridge takes `url`, `method`, the timing/session/response flags (`response`, `mode`, `session_id`, `timeout`, `bearer_token`, …), **plus the request body + headers**: `data` (raw body), `json` (JSON body; sets `Content-Type: application/json`), `data_base64` (binary-safe base64, standard or URL-safe, precedence over `data`/`json`), and repeatable `header=Name: Value`. **Supplying a body auto-upgrades the method GET→POST.** So a real `POST … {json} + headers` becomes one GET-able link a CRM/webhook can fire: ``` # Full POST as ONE GET URL (json body + header; method auto-upgrades to POST): https://${P}-${C}-curl-1.${N}.containers.hoody.com/api/v1/curl/request?url=&json=%7B%22event%22%3A%22X%22%7D&header=Authorization:%20Bearer%20XYZ # For payloads with &, quotes, newlines, or binary, prefer data_base64 (URL-safe base64) to dodge escaping: https://${P}-${C}-curl-1.${N}.containers.hoody.com/api/v1/curl/request?url=&data_base64=eyJldmVudCI6IlgifQ&header=Content-Type:%20application/json ``` (`form` fields, sent URL-encoded, cookies, Basic auth, retries, ranges and the connection limits are POST-only, and the GET bridge drops them without an error — use the POST form below for those. Neither form sends multipart uploads.) ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" # Drive the upstream POST directly from the kit (server-to-server, no clickable URL): curl -sf -X POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d '{"url":"https://my-api/events","method":"POST","data":"{\"event\":\"X\"}","headers":{"Content-Type":"application/json"}}' ``` **Step 2 — hide the `containerId` behind a proxy alias.** Now `https://webhook-bridge.{server_name}.containers.hoody.com/api/v1/curl/request?...` becomes the public URL. ```bash curl -sX POST "https://api.hoody.com/api/v1/proxy/aliases" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d "$(jq -nc --arg cid "$C" '{container_id:$cid, alias:"webhook-bridge", program:"curl", target_path:"/api/v1/curl/request", allow_path_override:true}')" ``` ### 2. Multi-step OAuth login — cookie jar reuse across hits **Goal:** authenticate against an API that uses a CSRF token + session cookie, then issue an authorized call. Pick a unique `session_id` per flow — once deleted, the same id returns `404 Session not found: (tombstoned)` until the tombstone is garbage-collected (~24 h), after which the id is reusable again. **Step 1 — fetch CSRF.** The Set-Cookie / response cookies are stored in the kit's jar. ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" SID="oauth-$(date +%s)" TOKEN=$(curl -sf -X POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg sid "$SID" '{url:"https://api.example.com/csrf", method:"GET", session_id:$sid, response:"json"}')" \ | jq -r '.body | fromjson | .csrf_token') echo "csrf=$TOKEN session=$SID" ``` **Step 2 — submit login.** The session cookie returned by the upstream is auto-stored in the same jar. Encode the token: `data` is sent as written, so a token holding `+`, `&` or `=` would be altered. The `form` field encodes each value and sets the form content type. ```bash curl -sX POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg sid "$SID" --arg t "$TOKEN" '{ url:"https://api.example.com/login", method:"POST", form:{username:"alex", password:"secret", csrf:$t}, session_id:$sid }')" ``` **Step 3 — authorized call.** Stored cookie is auto-attached. ```bash curl -sX POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg sid "$SID" '{url:"https://api.example.com/me", method:"GET", session_id:$sid, response:"json"}')" \ | jq -r .body # Inspect the jar: curl -sf "$KIT/api/v1/curl/sessions/$SID/cookies" # Drop when done: curl -sX DELETE "$KIT/api/v1/curl/sessions/$SID" ``` ### 3. Fan-out — submit 3 async jobs, await all, collect results **Goal:** fetch from 3 upstreams in parallel, combine the results. **Step 1 — submit each, capture `job_id`s.** ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" JOBS=() for URL in https://httpbin.org/delay/1 https://httpbin.org/delay/2 https://httpbin.org/get; do JID=$(curl -sf -X POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d "$(jq -nc --arg u "$URL" '{url:$u, method:"GET", mode:"async"}')" \ | jq -r .job_id) JOBS+=("$JID") done echo "${JOBS[@]}" ``` **Step 2 — poll until every job is terminal.** A job ends `completed`, `failed` or `cancelled`; stop on the last two, on a failed status request, and at a deadline. The deadline is checked between polls, so each status request is also capped (10 s here) to keep one stalled request from outliving it. ```bash DEADLINE=$((SECONDS + 300)) while :; do pending=0 for JID in "${JOBS[@]}"; do R=$(curl -sf --max-time 10 "$KIT/api/v1/curl/jobs/$JID") || { echo "status check failed: $JID" >&2; exit 1; } case "$(jq -r .status <<<"$R")" in completed) ;; failed|cancelled) echo "job $JID: $(jq -r '.status + " " + (.error // "")' <<<"$R")" >&2; exit 1 ;; *) pending=1 ;; esac done [ "$pending" = 0 ] && break [ "$SECONDS" -lt "$DEADLINE" ] || { echo "jobs still running after 300 s" >&2; exit 1; } sleep 1 done ``` **Step 3 — collect bodies.** `GET /api/v1/curl/jobs/{id}/result` returns just the upstream body, always with status 200; the upstream's status is in `X-Curl-Status`. ```bash for JID in "${JOBS[@]}"; do curl -sf "$KIT/api/v1/curl/jobs/$JID/result" > "/tmp/$JID.json" done ``` ### 4. Cancel a runaway long-poll mid-flight **Goal:** kill a hung async request, free the queue slot. Status flips from `running` to `cancelled`, and the cancelled job's `error` field is set to `Cancelled`. ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" JID=$(curl -sf -X POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d '{"url":"https://httpbin.org/delay/30","method":"GET","mode":"async","timeout":60}' \ | jq -r .job_id) sleep 1 curl -sX DELETE "$KIT/api/v1/curl/jobs/$JID" sleep 1 curl -sf "$KIT/api/v1/curl/jobs/$JID" | jq '{status, error}' ``` ### 5. Schedule + drift detection — fire every 15 min, audit history **Goal:** ping a health endpoint every 15 min, fast-find failures. ⚠ Scheduler uses **6-field** cron syntax (with seconds) — `*/15 * * * *` (5-field) is rejected as `Invalid cron expression`. **Step 1 — create.** ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" SID=$(curl -sf -X POST "$KIT/api/v1/curl/schedule" \ -H 'Content-Type: application/json' \ -d '{ "cron":"0 */15 * * * *", "request":{"url":"https://prod.example.com/health","method":"GET","job_name":"prod-health"} }' | jq -r .schedule_id) echo "schedule=$SID" ``` **Step 2 — audit failures.** A job is `failed` when the request could not be completed (DNS, connect, timeout) or when processing after the response failed, such as saving a download. An upstream HTTP error status alone does not fail the job: an upstream that answers `500` still yields a `completed` job, so also read the `response.status_code` of completed runs (from `GET /api/v1/curl/jobs/{id}`; the listing does not carry it). ```bash curl -sf "$KIT/api/v1/curl/jobs?limit=200" \ | jq -r '.items[] | select(.name=="prod-health") | "\(.id) \(.status)"' \ | while read -r JID ST; do if [ "$ST" = failed ]; then echo "$JID failed"; continue; fi [ "$ST" = completed ] || continue CODE=$(curl -sf "$KIT/api/v1/curl/jobs/$JID" | jq -r '.response.status_code // empty') [ -n "$CODE" ] && [ "$CODE" -lt 400 ] || echo "$JID HTTP ${CODE:-?}" done ``` **Step 3 — pause during deploy** (set `enabled: false` and back, or `delete` to drop entirely): ```bash curl -sX PATCH "$KIT/api/v1/curl/schedule/$SID/toggle" \ -H 'Content-Type: application/json' -d '{"enabled":false}' # Resume: same call with {"enabled":true}. Drop entirely: curl -sX DELETE "$KIT/api/v1/curl/schedule/$SID" ``` ### 6. Background download → kit storage → fetch later **Goal:** pull a 1 GB ISO without blocking the caller; access bytes from elsewhere later. **Step 1 — submit async + save.** ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" JID=$(curl -sf -X POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d '{ "url":"https://example.com/big.iso","method":"GET","mode":"async", "save":true,"save_path":"iso/ubuntu.iso","timeout":600 }' | jq -r .job_id) ``` **Step 2 — wait + inspect storage.** Stop on `failed` or `cancelled` and at a deadline instead of waiting for `completed` forever; the deadline is checked between polls, and each status request is capped at 10 s. Up to three entries point at the SAME bytes: `by-job/`, plus the best-effort `by-date/` and `by-domain/` links (no `by-domain/` for an IP-literal host). ```bash DEADLINE=$((SECONDS + 1800)) while :; do S=$(curl -sf --max-time 10 "$KIT/api/v1/curl/jobs/$JID" | jq -r .status) && [ -n "$S" ] || { echo "status check failed" >&2; exit 1; } case "$S" in completed) break ;; failed|cancelled) echo "job $S" >&2; exit 1 ;; esac [ "$SECONDS" -lt "$DEADLINE" ] || { echo "still downloading after 30 min" >&2; exit 1; } sleep 2 done curl -sf "$KIT/api/v1/curl/storage?limit=10" | jq '.items[] | .path' ``` **Step 3 — fetch & delete.** A delete through ANY of the paths removes the shared file, so every entry stops serving it (the others return `404` afterwards); the remaining index links may be left behind, dangling. ```bash curl -sf "$KIT/api/v1/curl/storage/by-job/$JID/iso/ubuntu.iso" > /tmp/ubuntu.iso curl -sX DELETE "$KIT/api/v1/curl/storage/by-job/$JID/iso/ubuntu.iso" ``` ### 7. Bearer-authenticated upstream — header auto-injection **Goal:** call the GitHub API with a token without composing the Authorization header. Against `httpbin.org/bearer` it returns `{"authenticated":true,"token":"…"}`. ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/curl/request" \ -H 'Content-Type: application/json' \ -d '{ "url":"https://api.github.com/user","method":"GET", "bearer_token":"ghp_xxxxxxxxxxxx","response":"json" }' | jq '{status_code, headers: .headers | {x_ratelimit_remaining: .["x-ratelimit-remaining"], x_ratelimit_reset: .["x-ratelimit-reset"]}, body}' ``` **HTTP Basic alternative** — swap the auth fields. Body `{ url, method, auth_user, auth_password, auth_method: 'basic' }`. Against `httpbin.org/basic-auth/alex/secret` it returns `{"authenticated":true,"user":"alex"}`. ### 8. REST→GET bridge for chat-channel embedding **Goal:** drop a one-liner URL into Slack so a teammate can re-trigger a build by clicking. URL pattern + alias + IP gate. **Step 1 — compose** (no kit call — URL pattern). The GET bridge carries the full request in the query string — `url`, `method`, body via `data`/`json`/`data_base64`, and repeatable `header=Name: Value` (a body auto-upgrades the method to POST). So a build-trigger that needs a JSON body + auth header is still one clickable link. ``` # GET-bridge URL — a real POST (json body + bearer header) as a single clickable link: https://${P}-${C}-curl-1.${N}.containers.hoody.com/api/v1/curl/request?url=&json=%7B%22ref%22%3A%22main%22%7D&header=Authorization:%20Bearer%20XYZ ``` **Step 2 — wrap with an alias** so the public URL hides `containerId`. The alias target must carry the whole request, body and auth included: the bridge reads the body and headers only from the query string, so an alias carrying just `url` and `method` sends an empty, unauthenticated POST. `target_path` refuses percent escapes (and spaces, quotes and braces), so the step 1 query cannot be pasted as is: write the target URL unescaped, send the JSON body (here `{"ref":"main"}`) as URL-safe base64 in `data_base64` (`` below) with a `Content-Type:application/json` header, and pass the token as `bearer_token`. The token then lives in the alias configuration, so gate the alias (step 3). Keep `allow_path_override: false`: the alias then serves only this `target_path`, at its root and at `/api/v1/curl/request` (both with the target's query), and any other path is refused with `404 ALIAS_PATH_PINNED`. A query key written in `target_path` wins over the visitor's, so a visitor cannot override the target `url`, `method`, body, headers or `bearer_token`. Keys the target does not set (for example `timeout` or `save`) still pass from the visitor, so write into `target_path` every key you want fixed. Step 3's gate is what limits who can fire it. ```bash TARGET='/api/v1/curl/request?url=https://ci.example.com/build&method=POST&data_base64=&header=Content-Type:application/json&bearer_token=XYZ' curl -sX POST "https://api.hoody.com/api/v1/proxy/aliases" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d "$(jq -nc --arg cid "$C" --arg p "$TARGET" \ '{container_id:$cid, alias:"rebuild-main", program:"curl", target_path:$p, allow_path_override:false}')" ``` **Step 3 — gate it** — only your office IPs can fire it (uses `PUT /api/v1/containers/{id}/proxy/permissions/groups/{groupName}/ip`; see the `api` namespace). ### 9. Recover a result from yesterday's scheduled job **Goal:** a scheduled scrape ran 18 hours ago; you want the body now. Finished job records, response bodies included, are deleted by an hourly sweep once they are older than the retention period (7 days by default; the deployment can change it). Saved downloads are kept. **Step 1 — find the right job** (the schedule was created with `request.job_name: 'prod-health'`). The listing is ordered by creation time, newest first, and runs do not necessarily complete in that order; a schedule firing every 15 minutes also leaves many runs with the same name. So read every page and select by completion time: here, the completed run with the latest `completed_at` at or before 18 hours ago. `completed_at` carries fractional seconds, which jq's `fromdate` rejects; strip them first. ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" CUTOFF=$(( $(date +%s) - 18 * 3600 )); : > /tmp/curl-runs.txt; page=1 while :; do body=$(curl -sf "$KIT/api/v1/curl/jobs?page=$page&limit=200") || exit 1 # One " " line per completed prod-health run on this page. jq -r '.items[] | select(.status=="completed" and .name=="prod-health" and .completed_at != null) | "\(.completed_at | sub("\\.[0-9]+Z$"; "Z") | fromdate) \(.id)"' <<<"$body" >> /tmp/curl-runs.txt || exit 1 [ $((page * 200)) -lt "$(jq -r .meta.total <<<"$body")" ] || break page=$((page + 1)) done JID=$(awk -v c="$CUTOFF" '$1 <= c' /tmp/curl-runs.txt | sort -n | tail -1 | cut -d' ' -f2) [ -n "$JID" ] || { echo "no completed prod-health run 18 h ago" >&2; exit 1; } ``` **Step 2 — fetch.** `GET /api/v1/curl/jobs/{id}/result` returns just the upstream body; `GET /api/v1/curl/jobs/{id}` returns the full record (timing, headers, original request). ```bash curl -sf "$KIT/api/v1/curl/jobs/$JID/result" # body only curl -sf "$KIT/api/v1/curl/jobs/$JID" | jq '.' # full record ``` ### 10. Storage triage — purge files older than N days **Goal:** keep storage tidy by deleting old downloads. Use the `by-date/` index because the date is in the path. The listing is newest first, so the old entries are on the last pages: collect every page before deleting anything, because each delete shifts the pages after it. ```bash KIT="https://${P}-${C}-curl-1.${N}.containers.hoody.com" CUTOFF=$(date -u -d '30 days ago' +%Y-%m-%d) : > /tmp/curl-purge.txt; page=1 while :; do body=$(curl -sf "$KIT/api/v1/curl/storage?page=$page&limit=200") || exit 1 jq -r --arg c "$CUTOFF" '.items[] | select(.path | startswith("by-date/")) | select((.path | split("/")[1]) < $c) | .path' \ <<<"$body" >> /tmp/curl-purge.txt [ $((page * 200)) -lt "$(jq -r .meta.total <<<"$body")" ] || break page=$((page + 1)) done while IFS= read -r P; do curl -sX DELETE "$KIT/api/v1/curl/storage/$P" done < /tmp/curl-purge.txt # Deleting one mirror path removes the shared file; the other 2 paths stop serving it. ``` ## Reference ### `channel` (1) — WebSocket event endpoints | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/curl/channel` | Execute cURL requests over a WebSocket channel | `?max_concurrent` `?max_concurrent_streams` `?max_pool` `?max_queue` `?max_frame_bytes` `?max_request_bytes` `?chunk_bytes` `?stream_timeout_secs` `?idle_timeout_secs` `?max_outbound_messages` `?binary` | **Param notes:** - `max_concurrent` — Alias for max concurrent streams on this channel connection - `max_concurrent_streams` — Maximum concurrently executing streams on this channel connection - `max_pool` — Alias for max_concurrent; does not configure outbound libcurl connection pooling - `max_queue` — Maximum queued streams waiting for a per-connection execution slot - `max_frame_bytes` — Maximum inbound WebSocket text frame size in bytes - `max_request_bytes` — Maximum assembled request JSON size in bytes - `chunk_bytes` — Maximum upstream response bytes encoded into one channel body frame - `stream_timeout_secs` — Per-stream execution timeout in seconds - `idle_timeout_secs` — Idle channel timeout in seconds - `max_outbound_messages` — Maximum queued outbound channel messages - `binary` — `true` negotiates binary frames: response bodies arrive as binary BODY frames and `request.start` may set `binary_body` to send its body as binary REQUEST_BODY frames. Every binary frame starts with a 16-byte little-endian header: version, kind, flags (bit 0 marks the last chunk) and the stream id. Default false ### `curl` (1) — cURL execution endpoints | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/curl/request` | Execute HTTP request with full cURL capabilities | `body*:curl_CurlRequest` | ### `jobs` (6) — Job management endpoints | Method | Summary | Params | |--------|---------|--------| | `DELETE /api/v1/curl/jobs/{id}` | Cancel a pending or running job, or delete a finished one | | | `GET /api/v1/curl/ws` | Subscribe to job events over WebSocket | `?job_id` `?since` `?incarnation` | | `GET /api/v1/curl/jobs/{id}` | Get detailed job information | | | `GET /api/v1/curl/jobs/{id}/result` | Get job response body | | | `GET /api/v1/curl/jobs` | List all async jobs | `?page` `?limit` | | `GET /api/v1/curl/sse` | Subscribe to job events over Server-Sent Events | `?job_id` `?since` `?incarnation` `H:Last-Event-ID` | **Param notes:** - `job_id` — Optional job ID filter - `since` — Resume cursor: the last `seq` (or `replay_boundary.max_seq`) received; `0` for everything still kept. The lifecycle events after it are replayed first, then a `replay_boundary` frame _(on `GET /api/v1/curl/ws`)_ - `incarnation` — The `incarnation` of the last control frame received; a different one means the server restarted since _(on `GET /api/v1/curl/ws`)_ - `page` — 1-based page number (optional) - `limit` — Items per page (optional; current handler returns all items when omitted) - `since` — Resume cursor: the last `seq` (SSE `id:`) received; `0` for everything still kept. Wins over `Last-Event-ID` _(on `GET /api/v1/curl/sse`)_ - `incarnation` — The `incarnation` of the last `lagged` event received; a different one means the server restarted since _(on `GET /api/v1/curl/sse`)_ - `Last-Event-ID` — Resume cursor as sent by an EventSource reconnect: the last `id:` received. Ignored when it is not a number or when `since` is given ### `kit` (2) — Operational endpoints (health and metrics) | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/curl/health` | Service health check | | | `GET /metrics` | Prometheus metrics | | ### `schedules` (5) — Schedule management endpoints | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/curl/schedule` | Create a recurring scheduled job | `body*:curl_CreateScheduleRequest` | | `DELETE /api/v1/curl/schedule/{id}` | Delete a schedule | | | `GET /api/v1/curl/schedule/{id}` | Get schedule details | | | `GET /api/v1/curl/schedule` | List all scheduled jobs | `?page` `?limit` | | `PATCH /api/v1/curl/schedule/{id}` | Update a schedule's cron expression, request or enabled state | `body*:curl_UpdateScheduleRequest` | **Param notes:** - `page` — 1-based page number (optional) - `limit` — Items per page (optional; current handler returns all items when omitted) ### `sessions` (4) — Session management endpoints | Method | Summary | Params | |--------|---------|--------| | `DELETE /api/v1/curl/sessions/{id}` | Delete a session | | | `GET /api/v1/curl/sessions/{id}` | Get session details | | | `GET /api/v1/curl/sessions` | List all cookie sessions | `?page` `?limit` | | `GET /api/v1/curl/sessions/{id}/cookies` | Get session cookies only | | **Param notes:** - `page` — 1-based page number (optional) - `limit` — Items per page (optional; current handler returns all items when omitted) ### `storage` (3) — Storage management endpoints | Method | Summary | Params | |--------|---------|--------| | `DELETE /api/v1/curl/storage/{path}` | Delete a saved file or directory | `?recursive` | | `GET /api/v1/curl/storage/{path}` | Download a saved file | | | `GET /api/v1/curl/storage` | List all saved downloads | `?page` `?limit` | **Param notes:** - `path` — Relative path to a file or directory in storage _(on `DELETE /api/v1/curl/storage/{path}`)_ - `recursive` — `true` deletes a directory and everything in it (default false) - `path` — Relative path to file in storage (supports nested paths) _(on `GET /api/v1/curl/storage/{path}`)_ - `page` — 1-based page number (optional) - `limit` — Items per page (optional; current handler returns all items when omitted) ### Body schemas - `curl_CurlRequest` — `{ auth_method: string|null, auth_password: string|null, auth_user: string|null, bearer_token: string|null, compressed: bool|null, connect_timeout: int|null, cookie: string|null, data: string|null, follow_redirects: bool|null, form: { [key: string]: string }|null, headers: { [key: string]: string }|null, insecure: bool|null, job_name: string|null, json: any, keepalive: bool|null, keepalive_time: int|null, max_filesize: int|null, max_redirects: int|null, method: string|null, mode: null | curl_ExecutionMode, range: string|null, referer: string|null, response: null | curl_ResponseMode, retry_count: int|null, retry_delay: int|null, save: bool|null, save_path: string|null, session_id: string|null, speed_limit: int|null, speed_time: int|null, tcp_nodelay: bool|null, timeout: int|null, url*: string, user_agent: string|null }` - cURL request parameters A JSON body carrying any field not listed here is rejected with `400`. This protects against silently sending a removed or not-yet-released field that would otherwise slip past validation unnoticed. - `save_path` — Relative path under this job's download directory (downloads/by-job/{job_id}). Must not be absolute or contain `..`. - `curl_CreateScheduleRequest` — `{ cron*: string, enabled: bool|null, request*: curl_CurlRequest }` - `curl_UpdateScheduleRequest` — `{ cron: string|null, enabled: bool|null, request: null | curl_CurlRequest }` - Partial update of a schedule. Every field is optional, at least one is required; absent fields keep their current value. - `curl_ExecutionMode` — `"sync" | "async"` - `curl_ResponseMode` — `"transparent" | "json"` --- # `daemon` — supervisord program lifecycle (start any program; logs kept) ## Purpose **Default for "start a program" / "spawn a process"** when you don't need an interactive shell or a TUI. REST over `supervisord` — every process is supervised, auto-restart-eligible, log-captured by default (stdout + stderr written under `/hoody/storage/hoody-daemon/logs//stdout.log` and `/hoody/storage/hoody-daemon/logs//stderr.log` — one directory per program, with rotated timestamped log files behind those symlinks), and inspectable after the fact. Those are the default paths: a program can set its own log files or turn logging off. Log files rotate by size. When an apply changes a program's configuration, its old timestamped default log sessions older than the retention period (30 days by default) are deleted; the active session is kept, and custom log files are not covered by that cleanup. Log FILES outlive the process on disk, but the ephemeral tracking entry is dropped 10 minutes after the program finishes or is stopped — after that `GET /api/v1/daemon/quick-start/{id}/logs` 404s (see Quirks); read the logs within those 10 minutes, or read the on-disk files directly (e.g. via the `files` namespace). `GET /api/v1/daemon/programs/{id}/logs` covers configured (non-ephemeral) programs. Two flavours: - **Quick-start (ephemeral, not added to the program list)** — `POST /api/v1/daemon/quick-start` with `{ command, user, ttl?, wait?, timeout? }`. Returns `temporary_id = quick__`. Best for one-offs and short-lived jobs (build steps, batch transforms, "run this once and tell me the output"). It adds no durable program entry, but it does write a temporary supervisord configuration and records the program in the kit's ephemeral tracking file so the cleanup pass can find it. The log files stay on disk, but `GET /api/v1/daemon/quick-start/{id}/logs` works only while the tracking entry exists. The cleanup pass (every 30 s) finalizes a program that is `stopped` or `fatal`, or `exited` with autorestart turned off; under `autorestart: "unexpected"` an `exited` program is finalized when its exit code is known to be 0, and is kept while its exit code is unknown. A finalized program's result and logs stay readable for 10 minutes; then the pass drops the entry and the logs route 404s. Stopping a program that already finished does not extend that window. Optional `ttl` auto-stops after N seconds. A quick-start defaults to `autorestart: "false"` and runs once, even when the command fails; set `autorestart: "unexpected"` to restart it after a nonzero exit. - **Registered program (durable, persists across kit restarts)** — `POST /api/v1/daemon/programs/add` with `{ name, command, user, enabled: true, boot: true?, autorestart: 'unexpected', … }` → `POST /api/v1/daemon/programs/{id}/start` with `{ wait: false }`, then poll `GET /api/v1/daemon/status/{id}`. Use this when the process should come back after a container restart, when you want auto-restart on crash, or when you need port-range fan-out / lazy-load on first proxy hit. ## When to use - "Run this command and keep the logs" → `POST /api/v1/daemon/quick-start`. - "Run this server / agent / script as a long-running supervised process, restart on failure" → `POST /api/v1/daemon/programs/add` + `POST /api/v1/daemon/programs/{id}/start`. - Background workers, port-range fan-out, lazy-loaded HTTP services, supervisord-event webhooks. ## When NOT to use - **Traditional system services that ship native systemd units** (apache2, nginx, postgresql, mysql, redis, mosquitto, sshd, postfix, …) — leave them on `systemd`. Hoody containers are full Linux boxes with systemd + root (they behave like VMs, not Docker), so the standard `apt install nginx && systemctl enable --now nginx` flow Just Works and benefits from the upstream unit's hardening (drop-in directories, sd_notify, journal integration, etc.). Mixing systemd-managed and `daemon`-managed processes in the same container is fine — pick whichever fits the program. - Need an interactive TTY (Claude Code, Codex, htop, vim, anything that paints the screen) → a one-off or hand-driven session is `terminal` with a **pinned non-ephemeral `terminal_id`**; a program that must be supervised (auto-restart, start at boot) is a `daemon` program with `terminal_id`, which runs on that terminal's PTY. Without `terminal_id` a daemon program has no TTY. A program with `terminal_id` cannot also have an effective sandbox. - Watch or type into a daemon program's terminal → the terminal WebSocket `/api/v1/terminal/ws` on host `terminal-`, with no spawn parameters. Snapshot, press, paste, write and wait drive it over REST without a WebSocket. Execute and session create on that id answer `409 DAEMON_TERMINAL`; a stopped program answers `409 DAEMON_PROGRAM_NOT_RUNNING` and closes a WebSocket with `4404`. - After starting a program with `terminal_id`, attach to its terminal or use the terminal's REST automation at least once. Until something connects, its output waits in the terminal up to about 19 KB, and a program that writes more blocks and can stall. Once connected, hoody-terminal stays connected until the program ends or the terminal session is deleted. - Need to pipe input mid-run / send keystrokes → `terminal` (`POST /api/v1/terminal/press`, `POST /api/v1/terminal/paste`). - One-shot synchronous request/response → `exec` (HTTP handler, returns body). - Schedule (cron syntax) → `cron`. Access logs → `proxyLogs`. File-system events → `watch`. ### When to prefer `daemon` over `systemd` - Custom scripts and binaries you wrote that don't have a packaged unit. - Quick experiments where you want REST-driven start/stop/log without writing a unit file. - Port-range fan-out (`port_range` + `port_param` + `lazy_load`) — supervisord-side feature, not a systemd one. - Programs you want to provision / mutate / remove via the Hoody API (CI scripts, multi-tenant container fleets) — `POST /api/v1/daemon/programs/add` is one HTTP call. ### When to prefer `systemd` over `daemon` - Any service whose Debian/Ubuntu package already drops a working unit in `/lib/systemd/system/` (most server software). - You want `journalctl -u `, `systemctl status`, drop-in overrides, socket-activated services, timers (cron-equivalent), or any other systemd feature. - The program is part of the container's "default-on" baseline (boots with the container, never managed externally). ## Prerequisites - `/dev/hoody`, `/hoody` and the log directory `/hoody/storage/hoody-daemon/logs/` exist. - `user` = real system account. ## Capability URL → See `SKILL-HTTP.md § Proxy URLs`. **Reaching a service you host on a container port** (any port, any namespace): - `https://{projectId}-{containerId}-http-.{node}.containers.hoody.com` — proxy speaks HTTP to `localhost:`. - `https://{projectId}-{containerId}-https-.{node}.containers.hoody.com` — proxy speaks HTTPS to `localhost:` (target needs TLS). Edge is always `https://`. No alias, firewall edit, or proxy registration needed; capability-token gates still apply. ## Common workflows ### 1. Register and boot - `POST /api/v1/daemon/programs/add` (`name`/`command`/`user`; `enabled`, `boot`; opt `directory`/`environment`/`autorestart`/`priority`/`*_logfile`) -> `POST /api/v1/daemon/programs/{id}/start` with `{ wait: false }`, then poll `GET /api/v1/daemon/status/{id}` (`include_stats`) until `status.status` is `running` (`wait: true` blocks the request and easily exceeds 30 s on a cold kit; see Example 1); `GET /api/v1/daemon/programs/{id}/logs` on failure. ### 2. Ephemeral with TTL - `POST /api/v1/daemon/quick-start` (`command`/`user`, opt `ttl?`/`wait?`/`timeout?`) returns `temporary_id` = `quick__`. Poll/tail with `GET /api/v1/daemon/quick-start/{id}/status`/`GET /api/v1/daemon/quick-start/{id}/logs`; `POST /api/v1/daemon/quick-start/{id}/stop` to terminate. ### 3. Lazy port-range fleet - `POST /api/v1/daemon/programs/add` + `port_range: { start, end }`, `port_param`, `lazy_load: true`, `enabled: true`. `GET /api/v1/daemon/programs?port=8042&include_status=true`. `POST /api/v1/daemon/programs/{id}/start` with `{ port: 8042 }`; `POST /api/v1/daemon/programs/{id}/stop` with `{ port }` or `{ all: true }`. ### 4. Reach a service you just started Any container port is publicly addressable as soon as the listener is up — no proxy alias, firewall edit, or extra registration needed: - HTTP service on `:8080` → `https://{projectId}-{containerId}-http-8080.{node}.containers.hoody.com` - HTTPS service on `:8443` → `https://{projectId}-{containerId}-https-8443.{node}.containers.hoody.com` Edge is always `https://`; the slug only describes the inner protocol. Gate access via `* /api/v1/containers/{id}/proxy/permissions*` if it shouldn't be public. See § Proxy URLs. ### 5. Update / wipe `POST /api/v1/daemon/programs/edit/{id}` (partial: an omitted field keeps its stored value, but `environment`, `sandbox`, `port_range` and `webhooks.enabled`+`webhooks.urls` are replaced whole when sent; see Quirks); `POST /api/v1/daemon/programs/{id}/disable`/`POST /api/v1/daemon/programs/{id}/enable`; `POST /api/v1/daemon/programs/remove/{id}`; `POST /api/v1/daemon/programs/reset` -> `programs.default.json`. ## Quirks & gotchas - Boolean query params (`hoody_kit`, `lazy_load`, `enabled`, `boot`, `include_status`, `include_stats`) STRICT: only `true`/`false`, in any letter case; `1`/`yes`/`0`/`""` -> 400. Send lowercase, which is what the SDK's typed values are. - Webhook URLs are validated only in an enabled block: `webhooks.enabled: false` skips every URL, event, header, timeout and retry check (the block must still carry `enabled` and `urls`). In an enabled block, URLs are HTTPS-only. Userinfo is rejected; the literal label `localhost` and private/CGNAT/link-local/v6-ULA addresses are too, including when written as NAT64, v4-mapped-v6, or non-standard v4 (`2130706433`, `0x7f000001`, `127.1`), when the URL authority is an IP literal or `localhost`. A DNS name is not resolved when the block is saved; at delivery time, private and reserved addresses are dropped from its resolution and delivery fails when none remains. Delivery never follows redirects and ignores the environment's HTTP proxy settings. - A `webhooks` edit must send `enabled` AND `urls` (a block without `urls` is a 400, `missing field urls`) and replaces both; `events`, `headers`, `timeout` and `retry` keep their stored values when omitted. An enabled block with an empty `urls` is a 400. Callbacks are delivered only when the deployment enables event delivery for the kit; the block is validated and stored either way. - Duplicate names + overlapping port ranges rejected on create AND update (adjacent OK); `port_param` requires `port_range`. - `command` no newlines/CR/NUL; `user` `(?i)[a-z_][a-z0-9_-]*\$?` (case-insensitive) via `id`; `*_logfile` must resolve under `/hoody/storage/hoody-daemon/logs/`. - `POST /api/v1/daemon/programs/{id}/start` on `port_range` REQUIRES `{ port }`; `POST /api/v1/daemon/programs/{id}/stop` with `{ port }` or `{ all: true }`. - `POST /api/v1/daemon/quick-start` returns `temporary_id` = `quick__` (e.g. `quick_1700000000000_1`); pass it unchanged to `GET /api/v1/daemon/quick-start/{id}/status`, `GET /api/v1/daemon/quick-start/{id}/logs` and `POST /api/v1/daemon/quick-start/{id}/stop` on every surface. TTL polled ~10 s. - A program is addressed by its integer `id` from `GET /api/v1/daemon/programs`, never by its name: a name in the `{id}` slot is refused with 404 before the daemon looks anything up. To find the id of a named program, filter the list by name. - Default ephemeral log paths are `/hoody/storage/hoody-daemon/logs//stdout.log` and `/hoody/storage/hoody-daemon/logs//stderr.log` (one directory per program), NOT `.out.log`/`.err.log`. - After `POST /api/v1/daemon/quick-start/{id}/stop`, the program's result and logs stay readable for 10 minutes; then its tracking entry is dropped and `GET /api/v1/daemon/quick-start/{id}/logs` returns `404`, while the on-disk log files persist. If withdrawing the program's supervisord group fails, the stop still reports success, with `cleaned_up: false`, and the next cleanup pass retries the withdrawal. Read `GET /api/v1/daemon/quick-start/{id}/logs` within those 10 minutes, or fetch the on-disk file directly. - `POST /api/v1/daemon/programs/{id}/start` accepts `if_not_running: true` for an idempotent boot — early-returns with `already_running: true` if the program is already running and, for a standard program with a `ready_port`, that port accepts connections; otherwise, including a running program whose `ready_port` is not serving, it takes the start path, and polls for readiness only with `wait: true` (port-range responses include an `instance` block with the instance's status, but a newly dispatched start leaves out its pid — only the already-running shortcut returns an observed pid; standard programs omit the `instance` field entirely. Read the pid from `GET /api/v1/daemon/status/{id}?port=`). Use it for "ensure started" workflows. - **`environment` REPLACES the whole map** on `POST /api/v1/daemon/programs/edit/{id}` (not per-key merge). If the existing env is `{A:"1",B:"2"}` and you update with `{environment:{A:"9"}}`, the stored map becomes `{A:"9"}` (values are strings). To preserve secrets, GET the program first and re-send the merged map. - **`sandbox` is three-state on `POST /api/v1/daemon/programs/edit/{id}`**: absent keeps the stored block, `null` clears it, and an object REPLACES the whole block (no field merge). Sending `{sandbox:{process:{max_pids:64}}}` to a program that also had `filesystem.read_only_root` and `network.mode: restricted` leaves only `max_pids`, and the program runs without the others. Read `GET /api/v1/daemon/programs/{id}/sandbox` first (`configured` is the stored block) and resend every restriction you want kept: merge locally and send the whole block. - Quick-start programs cannot be sandboxed: a non-null `sandbox` on `POST /api/v1/daemon/quick-start` is a 400 (`sandbox is not supported for quick-start programs`); `null` is accepted as absent. - An effective sandbox is refused for a `user` that resolves to uid 0 (under any name) and together with `terminal_id`. A block that restricts nothing is stored as absent and does not appear on the program. - **A sandboxed program fails CLOSED at launch.** If a mechanism its policy needs is missing the program does not start unconfined, it refuses to start at all: Landlock below the network ABI, a `bwrap` or `systemd-run` the container does not have, or an ingress policy with no `nft`. Expect the program to be down, not unprotected. A launch-stage refusal is printed as `sandbox: ` on the PROGRAM's stderr, not in the daemon log, so read `GET /api/v1/daemon/programs/{id}/logs` with `type=stderr`; the daemon log carries the earlier failures instead (validation, rendering, firewall admission, the supervisord apply). A stored block is also re-validated every time the program is rendered, so a block that later breaks a rule refuses the render rather than running the program unconfined. - A NON-EMPTY `network.ingress_allow_from`, or an `ingress_rate_limit`, needs a listening set: without `bind_ports`, `port_range` or `ready_port` the edit is a 400 (`sandbox.network.ingress_* requires a listening set`). An empty list owes no rules and so needs nothing. They filter IPv4 TCP arriving on `eth0` at those ports only, leave established connections alone, and an empty `ingress_allow_from` restricts nothing rather than denying everyone. - **Do not test an ingress allowlist from inside the same container.** The chain only matches what arrives on `eth0`, so same-container traffic never reaches it at all; and `ingress_allow_platform` defaults to `true`, which returns traffic whose source is loopback or the container's gateway ahead of both the meter and the allowlist. Either way a local probe proves nothing. Test with a new connection from an outside source. Public traffic the proxy forwards keeps the client's own address and IS filtered. The rate meter runs before the allowlist and stops tracking new sources once its 65535-entry set is full, while the allowlist keeps applying. - `GET /api/v1/daemon/programs/{id}/sandbox` answers with more than the stored block, and none of it certifies a running program: `configured` is what was persisted; `rev` is the 12-hex revision recomputed from the currently valid stored policy, the one the daemon WOULD place on the wrapper command line rather than an observation of the running process, and null when no effective policy validates; `effective` is DIAGNOSTIC argv recomputed from the stored policy, carrying placeholders like `` and ``, never the observed command, and it omits what the wrapper applies from inside itself (Landlock ports and the open-file limit); `live` reports the nft table, chain and rules read from the kernel at request time; `firewall` is `none`, `ok`, `draining` or `degraded`, with `problems` listing validation, state, integrity and unresolved-install failures. Read `problems` before concluding a restriction is in force. - **`restricted` is a PORT policy, not a destination policy.** `full` restricts neither bind nor connect. `restricted` limits which TCP ports the program may bind and connect to, at every destination including loopback: it cannot allow one host and deny another, and it does not touch UDP, ICMP or raw sockets, because Landlock has no hook for them. It also governs the `bind` and `connect` CALLS, not a socket that starts listening without an explicit bind, and a listener obtained that way is outside the ingress rules too. `none` is different in kind: it unshares the network namespace, so it removes IP networking of every protocol. Network mode alone does not block filesystem Unix sockets: under every mode, `none` included, they are governed by filesystem restrictions and file permissions rather than by this field. Every effective sandbox also masks `/run/user` with an empty directory, so sockets beneath it (the user manager, the session bus, agent sockets) are unreachable. - Ports are numbers or inclusive `"a-b"` strings. An omitted `bind_ports` defaults to the union of `port_range` and `ready_port`, and an explicit list has to cover both. `restricted` needs a non-empty resolved bind set, and an omitted or empty `connect_ports` denies outbound TCP entirely; a non-empty `connect_ports` requires `restricted`. `none` refuses declared listeners, a non-null explicit `bind_ports` (`[]` included), a non-empty connect or allow list, and a configured rate limit. Empty lists and either value of `ingress_allow_platform` are accepted and inert. - **The filesystem side is confinement, not a private container.** An effective sandbox drops all capabilities and unshares the user, PID and IPC namespaces, but the program keeps its account's supplementary groups and still sees the container's filesystem subject to ordinary permissions. `read_only_root` stops writes, not reads, and `/dev` and `/proc` are mounted over it. Private `/tmp` and `/var/tmp` are added only with `process.private_tmp: true`, which defaults to false: otherwise the program shares the container's temporary directories. `hidden` is not a secrecy boundary against an actor who can rename a validated directory or one of its ancestors: writable sources are pinned by descriptor at launch, but mount destinations are still resolved by pathname. - Process limits have fixed domains and are rejected outside them: `max_memory` from `16M` to `64G` (decimal bytes, or uppercase binary `K`/`M`/`G`, with scope swap disabled), `max_pids` from 4 to 65536 counting threads and two wrapper helpers, `max_open_files` from 8 to 1048576 applied as both the soft and the hard limit. `max_cpu` (`"%"`, whole numbers from `1%` to `102400%`, `100%` = one CPU), `max_file_size` (a per-file size limit, `1K` to `1024G`) and `tmp_size` (the size of each private tmpfs, `1M` to `64G`, only with `private_tmp: true`) are accepted too; a daemon built before they were added refuses them as unknown fields. There is no aggregate disk quota. - **A stored sandbox is not proof that one is installed.** An add or edit can persist the new block and still fail to apply it to supervisord; the response says so, and the earlier process may keep running unconfined when its stop cannot be confirmed. Treat a failed write as unresolved, read `problems`, fix the cause and reapply, rather than assuming either the old or the new policy is in force. - The ingress table `ip hoody_daemon` is rebuilt from desired state, not continuously enforced. Flushing or weakening it out of band can leave running programs unprotected: status turns `degraded` and new ingress launches refuse, but there is no integrity-repair loop and nothing stops what is already running. The next firewall transaction or reconcile rebuilds the table; re-applying an identical policy does not. Restore it and check `live` plus `firewall` after any out-of-band change. - Ingress rules are attached to a destination PORT on `eth0`, not to a process. Another listener on that same port at a different local address gets the same filtering, and the ownership check only knows about ports other programs have DECLARED, so an undeclared listener is neither protected from this nor protected against it. - **A policy change restarts the program.** The revision is part of the supervisord command line, so changing the resolved policy replaces the definition and stops the running instance; whether another starts is decided by `boot` and `lazy_load`, not by the edit. The old revision's ingress rules and port reservations can linger as `draining` after the call returns, so for a short window traffic meets both policies and the port is not yet free to reuse. - Webhook delivery needs per-program `webhooks.enabled: true` AND a deployment that enables event delivery for the kit. No request turns event delivery on, so a program whose `webhooks.enabled` is `true` can still receive no callbacks; a saved `webhooks` block is not proof that any will arrive. - `port_range` is an object `{ start, end }`. ## Common errors - 400 webhook (enabled blocks only): `must use HTTPS protocol`, `must not contain userinfo`, `cannot point to private, loopback, link-local, or cloud-metadata IP addresses`. - 400 `name already in use` / `Port range overlaps` / `port_param requires port_range`. - success=false `Port parameter required for port-range programs` -> resend with a `port` from the program's range. success=false `Program with ID {id} is disabled` -> `POST /api/v1/daemon/programs/{id}/enable` first. - `403 Forbidden` — Refused by the Source IP Guard: Hoody Kit programs are reached through their URLs only. The body is the plain text `Forbidden` with no reason; use the capability URL. - 1 MB request body limit. ## Related namespaces `exec` sync. `cron` scheduled. `proxyLogs` access log. `terminal` TTY. `display` virtual display. ## Examples Each step has a copy-pasteable code block in the mode you're reading (curl for HTTP, `hoody` for CLI, TypeScript for SDK). Set `P`, `C`, `N` (project id, container id, server name) from `GET /api/v1/containers/{id}` first. The kit returns numeric `program.id` (not a UUID) — capture it from the `POST /api/v1/daemon/programs/add` response. ### 1. Register a long-running supervised program with auto-boot **Goal:** add a tick-emitting worker that supervisord keeps alive across kit restarts, then start it without blocking the caller. **Step 1 — add (`enabled: true`, `boot: true`).** Capture `program.id`. Use `user: "user"` (uid 1000); the daemon's `command` allows shell metachars but you must own the quoting — single-quote the outer payload to avoid double-escaping. ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" ID=$(curl -sX POST "$KIT/api/v1/daemon/programs/add" \ -H 'Content-Type: application/json' \ -d '{ "name":"examples-daemon-tick", "command":"sh -c '\''while :; do echo tick $(date -u +%%s); sleep 5; done'\''", "user":"user","enabled":true,"boot":true,"autorestart":"unexpected" }' | jq -r '.program.id') echo "id=$ID" ``` **Step 2 — `POST /api/v1/daemon/programs/{id}/start` with `wait: false`.** ⚠ `wait: true` blocks the HTTP request until the process is running and easily exceeds 30 s on a cold kit (`wait:true,timeout:30` hits the client-side timeout). Pass `wait: false` and poll `GET /api/v1/daemon/status/{id}` instead. ```bash curl -sX POST "$KIT/api/v1/daemon/programs/$ID/start" \ -H 'Content-Type: application/json' -d '{"wait":false}' # Poll until running: while [ "$(curl -sf "$KIT/api/v1/daemon/status/$ID" | jq -r .status.status)" != "running" ]; do sleep 1; done ``` ### 2. Quick-start ephemeral with TTL — launch, check status, tail logs **Goal:** fire a one-shot command (no durable program entry), let it run up to 10 minutes, retrieve its output. `POST /api/v1/daemon/quick-start` returns `temporary_id = "quick__"` (e.g. `quick_1700000000000_1`); every later call takes that id unchanged. Truncating it to `quick_` returns 404. **Step 1 — launch.** ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" QID=$(curl -sX POST "$KIT/api/v1/daemon/quick-start" \ -H 'Content-Type: application/json' \ -d '{ "name":"examples-daemon-qs", "command":"sh -c \"for i in $(seq 1 30); do echo qs-$i; sleep 1; done\"", "user":"user","ttl":600 }' | jq -r .temporary_id) echo "qid=$QID" # e.g. quick_1700000000000_1 ``` **Step 2 — check status.** ```bash curl -sf "$KIT/api/v1/daemon/quick-start/$QID/status" | jq '{temporary_id,status,expires_at}' ``` **Step 3 — tail logs.** ```bash curl -sf "$KIT/api/v1/daemon/quick-start/$QID/logs?type=stdout&lines=10" | jq -r .logs ``` **Step 4 — stop.** Read the logs within 10 minutes of the stop: after that the tracking entry is dropped and `GET /api/v1/daemon/quick-start/{id}/logs` returns 404 (the on-disk log files stay). ```bash curl -sX POST "$KIT/api/v1/daemon/quick-start/$QID/stop" ``` ### 3. Lazy port-range fan-out — one program, N port-bound instances **Goal:** declare an HTTP service that listens on any port in `18800–18802`, materialised on demand the first time someone hits the proxy URL. **Step 1 — add with `port_range` + `port_param` + `lazy_load`.** ⚠ `port_param` cannot be empty (the kit returns `400 Invalid port_param format: ""`). Use a real CLI flag, e.g. `--port`. At start-time the kit appends `=` — **equals-joined**, one instance per port in the range — so the program must accept the `--flag=value` form. `python3 -m http.server` does NOT (its port is positional and `--port` is an unrecognised argument), so the example wraps it in a one-line `sh -c` that turns the appended flag back into the positional port. ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" ID=$(curl -sX POST "$KIT/api/v1/daemon/programs/add" \ -H 'Content-Type: application/json' \ -d '{ "name":"examples-daemon-fanout", "command":"sh -c \"exec python3 -m http.server ${1##*=}\" sh", "user":"user","enabled":true, "port_range":{"start":18800,"end":18802}, "port_param":"--port","lazy_load":true }' | jq -r .program.id) ``` **Step 2 — start one specific port and read fleet-wide status.** `GET /api/v1/daemon/programs?port=18800&include_status=true` returns the program with a `status: { type: "port-range", running_instances, total_instances, instances: [{ port, status, … }] }` block. ```bash curl -sX POST "$KIT/api/v1/daemon/programs/$ID/start" \ -H 'Content-Type: application/json' -d '{"port":18800}' curl -sf "$KIT/api/v1/daemon/programs?port=18800&include_status=true" \ | jq '.programs[].status' ``` The instance is reachable at `https://${P}-${C}-http-18800.${N}.containers.hoody.com` — no extra alias needed (see § "Reach a service you just started"). ### 4. Tail program logs (`GET /api/v1/daemon/programs/{id}/logs` with type / lines) **Goal:** investigate why a worker keeps restarting. `GET /api/v1/daemon/programs/{id}/logs` returns `{ logs, type, lines, log_file }` where `log_file` is the on-disk path under `/hoody/storage/hoody-daemon/logs//{stdout,stderr}.log`. ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/daemon/programs/$ID/logs?type=stderr&lines=200" | jq -r .logs ``` For a port-range program, select the instance when reading logs: append `&port=18800` to the example's existing query string. ### 5. Webhook on supervisord process events (e.g. crash → HTTPS callback) **Goal:** when the program enters the `FATAL` state, POST to your HTTPS endpoint. ⚠ Webhook URLs must be **HTTPS** (and reject userinfo, `localhost`, and private/CGNAT/link-local ranges). ⚠ **Event names are kit-specific, not the supervisord canonical `PROCESS_STATE_*` ones**: the kit accepts only `STARTING, RUNNING, BACKOFF, STOPPING, STOPPED, EXITED, FATAL, UNKNOWN, "all", "*"`. Sending `PROCESS_STATE_FATAL` returns `400 Invalid event type`. ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/daemon/programs/edit/$ID" \ -H 'Content-Type: application/json' \ -d '{ "webhooks":{ "enabled":true, "urls":["https://hooks.example.com/daemon-events"], "events":["FATAL","BACKOFF"], "headers":{"X-Source":"hoody-daemon"}, "timeout":10,"retry":2 } }' ``` ⚠ A `webhooks` edit replaces `enabled` and `urls` and must send both: `{ webhooks: { enabled: false } }` on its own is a 400 (`missing field urls`). To turn delivery off, resend the current `urls` with `enabled: false`; to rotate URLs, send the full new `urls` array. `events`, `headers`, `timeout` and `retry` keep their stored values when omitted. `POST /api/v1/daemon/programs/edit/{id}` needs only the id on every surface: the SDK edit type is `ProgramUpdate`, with nothing required. ### 6. Wipe + reset to defaults — non-destructive snapshot first **Goal:** restore the supervisord program set to whatever ships in `programs.default.json`. ⚠ **Destructive** — every program you added gets wiped. Snapshot before you call. ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" # 1) snapshot curl -sf "$KIT/api/v1/daemon/programs" > /tmp/daemon-snapshot.json # programs.list takes no `limit` query # 2) reset curl -sX POST "$KIT/api/v1/daemon/programs/reset" # 3) restore the entries you want by replaying programs.add for each ``` ### 7. Patch only the env vars on a running program **Goal:** flip `LOG_LEVEL=debug` without restating `command`/`user`/etc. `POST /api/v1/daemon/programs/edit/{id}` is partial on every surface: fields absent from the request body keep their stored values. `environment` itself is replaced whole (see the note below). ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/daemon/programs/edit/$ID" \ -H 'Content-Type: application/json' \ -d '{"environment":{"LOG_LEVEL":"debug","BUILD":"examples"}}' # Restart so the child inherits the new env. stop needs a JSON body ({} is enough); # without Content-Type: application/json it is rejected with 400 and nothing stops. curl -sX POST "$KIT/api/v1/daemon/programs/$ID/stop" \ -H 'Content-Type: application/json' -d '{}' curl -sX POST "$KIT/api/v1/daemon/programs/$ID/start" \ -H 'Content-Type: application/json' -d '{"wait":false}' ``` ⚠ `environment` REPLACES the whole map (not per-key merge). If you have `{A:"1",B:"2"}` and update with `{environment:{A:"9"}}`, you end up with just `{A:"9"}` — re-send everything you want to keep. ### 8. Inspect a running program with stats **Goal:** read CPU/RSS/uptime to feed a dashboard. For a standard program, `GET /api/v1/daemon/status/{id}?include_stats=true` returns `{ success, status: { id, status, pid?, uptime? }, stats? }`: the resource figures are in the separate `stats` object, present only when they could be collected for a running process. A program that is not running (`backoff`, `stopped`, `fatal`, …) has no `pid`, `uptime` or `stats`; supervisord's diagnostic text is never returned as `uptime`. A port-range program answers with `instances` instead, each instance carrying its own `stats`. ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/daemon/status/$ID?include_stats=true" | jq . ``` ⚠ `include_stats` is a **string** boolean (`"true"`/`"false"`) — `1`/`yes`/empty string return `400` (strict-bool query parse, see Quirks). ### 9. Stop one port instance OR every instance in a port-range fleet **Goal:** kill just port 18800 vs. drain the whole fleet for a deploy. **Single port** (other ports keep running): ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/daemon/programs/$ID/stop" \ -H 'Content-Type: application/json' -d '{"port":18800}' ``` **Whole fleet** (`all: true`): ```bash curl -sX POST "$KIT/api/v1/daemon/programs/$ID/stop" \ -H 'Content-Type: application/json' -d '{"all":true}' ``` ⚠ For a port-range program, `POST /api/v1/daemon/programs/{id}/start` REQUIRES `{ port }` (single-port only); there is no "start them all" — boot each port individually or rely on `lazy_load: true` to materialise on first proxy hit. ### 10. Disable now, re-enable after the migration **Goal:** keep the program defined but stop supervisord from auto-restarting it. `POST /api/v1/daemon/programs/{id}/disable` flips `enabled: false` (process stays in the listing for forensics); `POST /api/v1/daemon/programs/{id}/enable` brings it back without touching `command`/`environment`. Enabling reapplies the program's configuration, so a program with `boot: true` (and not `lazy_load`) can start right away; follow it with an ensure-start (`if_not_running: true`), which returns early when the program is running and ready, and otherwise takes the start path (readiness polling only with `wait: true`). ```bash KIT="https://${P}-${C}-daemon-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/daemon/programs/$ID/disable" # … run migration … curl -sX POST "$KIT/api/v1/daemon/programs/$ID/enable" # enable can already start a boot:true program; ensure it is running either way: curl -sX POST "$KIT/api/v1/daemon/programs/$ID/start" \ -H 'Content-Type: application/json' -d '{"wait":false,"if_not_running":true}' ``` ⚠ Trying `POST /api/v1/daemon/programs/{id}/start` while `enabled: false` returns `success: false` with `Program with ID {id} is disabled` (e.g. `Program with ID 7 is disabled`) — call `POST /api/v1/daemon/programs/{id}/enable` first. ## Reference ### `ephemeralPrograms` (5) — Ephemeral program launcher - Create temporary programs that auto-cleanup when stopped or on reboot | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/daemon/quick-start/{id}/logs` | Get ephemeral program logs | `?type` `?lines` | | `GET /api/v1/daemon/quick-start/{id}/status` | Get ephemeral program status | | | `GET /api/v1/daemon/quick-start` | List all ephemeral programs | | | `POST /api/v1/daemon/quick-start` | Launch ephemeral CUSTOM program | `body*:daemon_EphemeralProgramInput` | | `POST /api/v1/daemon/quick-start/{id}/stop` | Stop ephemeral program | | **Param notes:** - `type` — Log stream: stdout or stderr - `lines` — Number of lines to return from the end of the file (default 100). A non-negative integer: `0` returns empty content, and the server clamps values above 10000 to 10000. ### `kit` (1) — Service health check endpoint - returns the standardized health response for monitoring and readiness probes | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/daemon/health` | Service health check | | ### `programs` (15) — Program management endpoints - create, read, update, and delete daemon programs | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/daemon/programs/add` | Add a new CUSTOM program | `body*:daemon_ProgramInput` | | `POST /api/v1/daemon/programs/remove/{id}` | Remove a program | | | `POST /api/v1/daemon/programs/{id}/disable` | Disable a program | | | `POST /api/v1/daemon/programs/{id}/enable` | Enable a program | | | `GET /api/v1/daemon/programs/{id}` | Get a specific program | | | `GET /api/v1/daemon/programs/{id}/logs` | Get program logs | `?type` `?lines` `?port` | | `GET /api/v1/daemon/programs/{id}/sandbox` | Get sandbox status for a program | | | `GET /api/v1/daemon/status/{id}` | Get specific program status | `?port` `?include_stats` | | `GET /api/v1/daemon/programs` | List all programs | `?hoody_kit` `?lazy_load` `?enabled` `?boot` `?name` `?port` `?port_from` `?port_to` `?include_status` `?include_stats` | | `GET /api/v1/daemon/status` | Get all program statuses | | | `POST /api/v1/daemon/programs/reset` | Reset programs to default | | | `POST /api/v1/daemon/programs/{id}/start` | Start a program or port instance | `body*` | | `POST /api/v1/daemon/programs/{id}/stop` | Stop a program or port instance | `body*` | | `GET /api/v1/daemon/programs/{id}/logs/stream` | Follow program logs (SSE) | `?type` `?lines` `?port` `?offset` `H:Last-Event-ID` | | `POST /api/v1/daemon/programs/edit/{id}` | Edit a program | `body*:daemon_ProgramUpdate` | **Param notes:** - `type` — Log stream: stdout or stderr - `lines` — Number of lines to return from the end of the file (default 100). A non-negative integer: `0` returns empty content, and the server clamps values above 10000 to 10000. _(on `GET /api/v1/daemon/programs/{id}/logs`)_ - `port` — Port number (required for port-range programs) _(on `GET /api/v1/daemon/programs/{id}/logs`, `GET /api/v1/daemon/programs/{id}/logs/stream`)_ - `port` — Filter to specific port instance (for port-range programs only) _(on `GET /api/v1/daemon/status/{id}`)_ - `include_stats` — Include resource stats (CPU, memory, process tree) for running programs. WHERE the stats land depends on the program: a standard program gets a top-level `stats`; a port-range program gets one `stats` per instance, on the instance itself (`instance.stats`, or `instances[].stats`), never at the top level. Each carries pid, started_at, cpu_percent, memory_rss_bytes, process_count and a per-process breakdown. _(on `GET /api/v1/daemon/status/{id}`)_ - `hoody_kit` — Filter by hoody_kit status. Use "true" for Hoody Kit programs only, "false" for user (non-kit) programs only. - `lazy_load` — Filter by lazy_load status. Use "true" for lazy-loaded programs only (started on-demand), "false" for programs that auto-start. - `enabled` — Filter by enabled status. Use "true" for enabled programs only, "false" for disabled programs only. - `boot` — Filter by boot status. Use "true" for programs that auto-start on system boot, "false" for manual-start programs. - `name` — Filter by exact program name (e.g. "hoody-agent"). Lazy mode: the proxy resolves the agent BY NAME because it is a standard program with no port_range (the port filter cannot match it) and program ids are positional. Invalid names return 400. - `port` — Filter programs by single port number. Returns only programs whose port_range includes this specific port. Example: ?port=8042 returns programs with ranges containing 8042. _(on `GET /api/v1/daemon/programs`)_ - `port_from` — Filter by port range start (must be used with port_to). Returns programs whose port ranges overlap with the specified range. Uses overlap logic: program.start <= port_to AND program.end >= port_from. - `port_to` — Filter by port range end (must be used with port_from). Returns programs whose port ranges overlap with the specified range. Multiple programs may be returned if their ranges overlap. - `include_status` — Include runtime status for each program. When true, adds a "status" field to each program showing current running state, instances, and process details. - `include_stats` — Include resource stats (CPU, memory, process tree) for each running program. Turns status on only when `include_status` is omitted: an explicit `include_status=false` suppresses both status and stats. Adds a "stats" field with pid, started_at, cpu_percent, memory_rss_bytes, process_count, and per-process breakdown. Only present for running programs. _(on `GET /api/v1/daemon/programs`)_ - `lines` — Number of complete lines replayed from the end of the file before following (default 100). `0` replays nothing and only follows; values above 10000 are clamped to 10000. The replay is found in the last 10 MiB of the file. Ignored when resuming with `offset` or `Last-Event-ID`. _(on `GET /api/v1/daemon/programs/{id}/logs/stream`)_ - `offset` — Resume cursor: the `id` of the last `line` event received (a byte offset just past that line). Streaming restarts at the next line and no backlog is replayed. An offset beyond the end of the current file means it was truncated or replaced since: the stream sends a `reset` event and starts from the top of the file. The cursor is a byte position, not a file identity, so a file replaced by one at least as long is not detected across a reconnect. Takes precedence over `Last-Event-ID`. - `Last-Event-ID` — Same cursor as `offset`, as sent automatically by an EventSource when it reconnects. Must be a non-negative integer. **Body shapes:** - `POST /api/v1/daemon/programs/{id}/start` body — `{ port: int, wait: bool=false, timeout: int=30, if_not_running: bool=false }` — Optional port parameter for port-range programs - `port` — Port number to start (required for port-range programs) - `wait` — Poll until the program is running (and, if it declares `ready_port`, until that port accepts a TCP connection on 127.0.0.1) before returning. With `if_not_running`, an already-running or shared result can come back without polling. - `timeout` — Readiness polling budget in seconds when `wait=true` (default 30). Not a total request deadline: configuration and the supervisord start come first. - `if_not_running` — Only start if not already running (idempotent mode). If true, checks if instance is running first. Returns already_running field in response. Use this for edge proxy automation. - `POST /api/v1/daemon/programs/{id}/stop` body — `{ port: int, all: bool }` — Optional parameters for port-range programs - `port` — Specific port to stop - `all` — Stop all instances (for port-range programs) ### Body schemas - `daemon_ProgramInput` — `{ id: int, name*: string, description: string, command*: string, user*: string, enabled: bool=true, boot: bool=false, delay_seconds: int=0, autorestart: "true" | "false" | "unexpected" | bool="unexpected", directory: string, priority: int=999, stdout_logfile: string, stderr_logfile: string, logs_enabled: bool=true, log_max_bytes: int=5242880, log_backups: int=2, environment: { [key: string]: string }, hoody_kit: bool=false, inject_container_env: bool, port_range: { start*: int, end*: int }, port_param: string, lazy_load: bool=false, ready_port: int|null, display: string|null | int, terminal_id: int, terminal_shell: string|null, terminal_interactive: bool|null, webhooks: { enabled*: bool, urls*: string[], events: string | string[], headers: object, timeout: int, retry: int }|null, sandbox: daemon_SandboxConfig|null }` - `daemon_ProgramUpdate` — `{ id: int|null, name: string|null, description: string|null, command: string|null, user: string|null, enabled: bool|null, boot: bool|null, delay_seconds: int|null, autorestart: "true" | "false" | "unexpected" | bool|null, directory: string|null, priority: int|null, stdout_logfile: string|null, stderr_logfile: string|null, logs_enabled: bool|null, log_max_bytes: int|null, log_backups: int|null, environment: { [key: string]: string }|null, hoody_kit: bool, inject_container_env: bool, port_range: { start*: int, end*: int }|null, port_param: string|null, lazy_load: bool|null, ready_port: int|null, display: string|null | int, terminal_id: int|null, terminal_shell: string|null, terminal_interactive: bool|null, webhooks: { enabled*: bool, urls*: string[], events: string|null | string[], headers: object|null, timeout: int|null, retry: int|null }|null, sandbox: daemon_SandboxConfig|null }` - `daemon_EphemeralProgramInput` — `{ command*: string, user*: string, name: string, autorestart: "true" | "false" | "unexpected" | bool="false", directory: string, environment: { [key: string]: string }, inject_container_env: bool, priority: int=999, delay_seconds: int=0, stdout_logfile: string, stderr_logfile: string, logs_enabled: bool=true, log_max_bytes: int=5242880, log_backups: int=2, ttl: int, wait: bool=false, timeout: int=30, display: string|null | int, terminal_id: int, terminal_shell: string|null, terminal_interactive: bool|null }` - `daemon_SandboxConfig` — `{ filesystem: daemon_SandboxFilesystem|null, network: daemon_SandboxNetwork|null, process: daemon_SandboxProcess|null }` - … Consequences that callers must expect — the pid supervisord tracks is the wrapper, not the program; a signal death reaches supervisord as exit code `128+n` rather than as a signal; and any edit that changes the RESOLVED policy replaces the loaded definition, stopping the instance that ran under … - `daemon_SandboxFilesystem` — `{ read_only_root: bool|null=false, writable: string[]|null, hidden: string[]|null }` - … Independently of these fields, every sandboxed program sees an empty `/run/user` in place of the real one, so it cannot reach its account's systemd user manager or session bus; a sandboxed program whose `directory` is under `/run/user` is rejected with 400. Unknown keys are rejected with 400. … - `read_only_root` — Bind `/` read-only (`--ro-bind / /`). … `/sys` is bound read-only for every sandboxed program regardless of this flag, so the program cannot edit its own cgroup limits. - `writable` — … Each must already exist and is canonicalized. `read_only_root` must be true — `writable` on its own is a 400, not a restriction. … `/hoody` and `/hoody/storage` are therefore refused because they contain the daemon's own tree; `/hoody/storage/apps/` is accepted. At launch the wrapper's outer stage canonicalizes each path, records its `(st_dev, st_ino)`, and compares those against a fresh stat immediately before the sandbox is spawned; a path that changed identity, or is no longer a directory, is refused. … - `daemon_SandboxNetwork` — `{ mode: "full" | "restricted" | "none"|null="full", bind_ports: (int | string)[]|null, connect_ports: (int | string)[]|null, ingress_allow_from: string[]|null, ingress_allow_platform: bool|null=true, ingress_rate_limit: string|null, udp: "allow" | "deny"|null="allow" }` - Network confinement. … Unknown keys are rejected with 400. … - `daemon_SandboxProcess` — `{ max_memory: string|null, max_pids: int|null, max_open_files: int|null, max_cpu: string|null, max_file_size: string|null, tmp_size: string|null, private_tmp: bool|null=false }` - Process limits, applied by three different mechanisms: `max_memory`, `max_pids` and `max_cpu` by systemd on the transient scope that owns the program's cgroup (each read back from the cgroup before the program runs; a limit that did not land refuses the launch), `max_open_files` and `max_file_size` as in-process resource limits set just before the program is executed, and `private_tmp` and `tmp_size` as bubblewrap mounts. The program sees `/sys` read-only and cannot raise the cgroup limits. Unknown keys are rejected with 400. … - `max_pids` — `TasksMax=` on the scope, from 4 to 65536. The count includes the two wrapper helpers (the scope payload and bubblewrap), so budget at least 2 above the program's own process and thread count. - `max_cpu` — … Written to the scope as `CPUQuota=%`; before the program runs, the scope's `cpu.max` is read back and the launch is refused if it holds no limit or a share more than 1 % away from the request. … - `tmp_size` — Size of EACH of the program's private `/tmp` and `/var/tmp`, from 1M to 64G, in the size grammar of `max_memory`. Requires `private_tmp: true`; on its own it is a 400. … Needs bubblewrap 0.10.0 or newer (`/health` reports `bwrap_tmpfs_size`); on an older one the launch is refused. - `private_tmp` — … Rejected with 400 when a `filesystem.writable` entry equals, contains or is contained by `/tmp` or `/var/tmp`: the private mounts are applied first, so a writable bind over them would expose the container's shared directory. Also rejected when the program's `directory` lies strictly below `/tmp` or `/var/tmp`, or when the daemon itself is installed below either: the private mounts would hide them and the launch could not reach the program. … --- # `display` — programmatic GUI desktops with screenshots, input, and windows ## Purpose Per-container HTML5 desktop (X11 via proxy): screenshots, input, windows, clipboard. ## When to use - Click/type/drag/scroll at coords; screenshots/thumbnails for vision; X11 window ops; clipboard r/w. - **Multiple GUI apps → one display (one `terminal_id`) per app (almost always the right call).** A single X display *can* host many windows, but giving each app its own display (`display: ":N"` paired to a distinct `terminal_id`) gives each its own `display-` kit URL — a dedicated full-surface stream you can screenshot, embed / iframe, and route input to **independently, per window** — with no window-search / focus juggling on a shared display. Pin matching ids (`terminal_id=1`↔`:1`, `terminal_id=2`↔`:2`, …) so the routing stays one-to-one. Reuse a single display only when you deliberately want the apps composited together (e.g. a full desktop — see the `desktop-` alias). ## When NOT to use Not for: shell → `terminal`/`exec`, files → `files`, headless web → `browser`, toasts → `notifications`. ## Prerequisites - Active X11 display (`DISPLAY=:N`). To render X apps from a terminal into display `:N`, create the terminal session with an explicit string `display: "N"`: the create call takes `display` from the request body only, and no `terminal_id` value ever implies a `DISPLAY`. (A session the terminal kit has to create on demand for a command is configured from the request URL instead, where a `terminal-N` host already supplies `display=N`.) - Display ID resolution: `*-display-N.*` host (e.g. `https://{projectId}-{containerId}-display-1.{node}.containers.hoody.com` for display `1`) or query override `?displayId=N`. ## Capability URL → See `SKILL-HTTP.md § Proxy URLs`. **Reaching a service you host on a container port** (any port, any namespace): - `https://{projectId}-{containerId}-http-.{node}.containers.hoody.com` — proxy speaks HTTP to `localhost:`. - `https://{projectId}-{containerId}-https-.{node}.containers.hoody.com` — proxy speaks HTTPS to `localhost:` (target needs TLS). Edge is always `https://`. No alias, firewall edit, or proxy registration needed; capability-token gates still apply. ## Common workflows ### 1. See-then-act loop 1. `GET /api/v1/display/screenshot` with `base64` on (for vision). One response carries the image (`image.data`) and its metadata (`info.timestamp`, `info.full.width`/`height`). 2. `POST /api/v1/display/input/click-at` / `POST /api/v1/display/input/type-at` at a point picked on that screenshot: a screenshot spans the whole screen, so its pixel (x, y) is the point (x, y) these act on. 3. `GET /api/v1/display/screenshot` again to see the result. There is no cheap change check: `GET /api/v1/display/screenshot` takes a full new capture as well, and `timestamp` is the capture time in whole seconds, not a "screen changed" marker. ### 2. Find and focus a window 1. `GET /api/v1/display/windows` (`onlyVisible` on). 2. `POST /api/v1/display/window/search` — a `pattern` plus which fields to match (`name`, `class`, `classname`). 3. `POST /api/v1/display/window/focus` with `sync` on. Read `details.inputFocus` in the response: proceed with keyboard input only when it is `true`. `false` means the window was activated but is not viewable, so keyboard input cannot reach it. `POST /api/v1/display/window/raise` is not a substitute for focusing. 4. `GET /api/v1/display/window/{windowId}/geometry` — coords. 5. `GET /api/v1/display/window/active` — confirms activation only, not keyboard focus. `GET /api/v1/display/windows`, `POST /api/v1/display/window/focus` and `GET /api/v1/display/window/active` need a window manager on the display: `409 NO_WINDOW_MANAGER` means none is running, and retrying does not help. Start a window manager (for example a desktop session), or use `POST /api/v1/display/window/search`, window geometry and name queries, and mouse and keyboard actions, which work without one. ### 3. Drag / select 1. `POST /api/v1/display/mouse/move` — optional pre-position. 2. `POST /api/v1/display/input/drag` `(sx,sy)`→`(ex,ey)`, optional `steps`. 3. Or `POST /api/v1/display/input/select` — click + shift-click. 4. `POST /api/v1/display/input/reset` — release stuck buttons. ### 4. Clipboard hand-off 1. `POST /api/v1/display/clipboard` — `text`, optional `selection`. 2. `POST /api/v1/display/keyboard/key` — `["ctrl+v"]` (`["shift+Insert"]` for primary). 3. `GET /api/v1/display/clipboard` — read back after GUI copy. ### 5. Batch input replay 1. `POST /api/v1/display/input/batch` — an ordered list of actions in one request. It stops at the first failure and still answers 200, so check `success` and `failed`. 2. `POST /api/v1/display/input/wait` — interleave waits. 3. `GET /api/v1/display/screenshot` — confirm. ### 6. Press a key or a key combination 1. `POST /api/v1/display/keyboard/key` with `keys`, a list of up to 20 combinations pressed in turn: `["Return"]`, `["Escape"]`, `["ctrl+l"]`, `["ctrl+shift+t"]`, `["Tab", "Down", "Return"]`. Names are X keysym names (`Return`, `Escape`, `Tab`, `BackSpace`, `Delete`, `Up`/`Down`/`Left`/`Right`, `Home`, `End`, `Page_Up`, `F1`…) joined to modifiers (`ctrl`, `shift`, `alt`, `super`) with `+`. 2. To submit typed text, end it with a line break instead: in `POST /api/v1/display/keyboard/type` and `POST /api/v1/display/input/type-at`, `\n` presses Return. 3. `POST /api/v1/display/keyboard/key-down` / `POST /api/v1/display/keyboard/key-up` hold and release one key; `POST /api/v1/display/input/reset` releases anything left held. ## Quirks & gotchas - `?displayId=N` overrides `*-display-N.*` host. - `displayId` `1..999999`, digits only (must match `^\d+$`); an out-of-range or non-numeric value is silently ignored and the id is taken from the host instead. - All endpoints except `GET /api/v1/display/health` and the HTML client root (`GET /api/v1/display/`) need a displayId or return `400 NO_DISPLAY_CONTEXT`. - Screenshot GETs return binary PNG; turn `base64` on for JSON. - `GET /api/v1/display/screenshot/{timestamp}` needs numeric `timestamp`, not `timestamp_human`. - **A screenshot pixel is a click coordinate.** A screenshot spans the whole screen at its current size, read from the windows as they are when it is taken, so pixel (x, y) is the point `POST /api/v1/display/input/click-at` and the other pointer calls act on at (x, y). Where no window is, the image is transparent. A `region` crop starts at its `x1,y1`: add them to a point picked on the crop. Take a new screenshot after a viewer attaches: the screen then takes the viewer's size and the windows move. - `POST /api/v1/display/input/click-at` and `POST /api/v1/display/input/type-at` refuse a point with no viewable window with `409 WINDOW_NOT_VIEWABLE` and click nothing. While no viewer is attached to the display that is every point; with one attached, it is the bare desktop between windows. Attach a viewer and pick a point on a window in a fresh screenshot. - A line break in `text` (`\n`, `\r\n` or `\r`) presses Return in `POST /api/v1/display/keyboard/type` and `POST /api/v1/display/input/type-at`, so `"https://example.com\n"` types the address and submits it; `\t` presses Tab. Every other key or combination (Escape, ctrl+l, arrows) goes through `POST /api/v1/display/keyboard/key`. - `POST /api/v1/display/input/click-at` refuses a point outside the display's current size with `400 VALIDATION_ERROR` instead of clicking the screen edge, and its `details.pointer` reports where the pointer was after the click and the window under it (`x`, `y`, `window`). A `200` means the click was delivered there, not that the program acted on it: take a new screenshot to see the effect. - Clipboard `selection`: `clipboard` (default), `primary`, `secondary`. PRIMARY ≠ Ctrl+V. - Clipboard reads and writes can fail with `CLIPBOARD_FAILED`, carrying a shortened tool error; read the clipboard back after a write to confirm it landed. - Window IDs are accepted as decimal or hex (`0x...`). `GET /api/v1/display/windows`, `POST /api/v1/display/window/search` and `GET /api/v1/display/window/active` return decimal numbers; the path-parameter routes (`GET /api/v1/display/window/{windowId}/properties`, `GET /api/v1/display/window/{windowId}/geometry`, `GET /api/v1/display/window/{windowId}/name`) echo `windowId` exactly as sent, as a string. Compare ids as numbers, not strings.{1,8}$/"] - `POST /api/v1/display/window/focus` activates the window and then tries to give it X input focus. The second step fails on a window that is not viewable, and the call still answers `success: true` with `details.inputFocus: false` and a `warning`; untargeted keyboard input then does not reach that window. `GET /api/v1/display/window/active` confirms the activation only. - `GET /api/v1/display/info` returns display info, a window list (each with per-window `position`/`size`), and the screenshot list — but NOT the virtual screen dimensions (those live on `GET /api/v1/display/input/display-geometry`). - `POST /api/v1/display/input/reset` clears stuck modifiers/buttons. - `POST /api/v1/display/input/wait-until` answers 200 even when it times out: the body is `success: false, timedOut: true`, so check `timedOut`, not the status. `timeoutMs` is 100-25000 (default 10000). Too many waits at once on one display give `429 QUEUE_FULL`. - `POST /api/v1/display/window/restore` waits by default (`sync`, up to 2 s) until the window manager reports the window as no longer minimized, unlike the other window actions; a window still minimized after that is `500 INPUT_ACTION_FAILED`. With `sync: false` the answer's `details.state` is `null`, unless the window was already normal: that no-op answers `details.state: "normal"` with `details.synced: true`. ## Common errors - `400 NO_DISPLAY_CONTEXT` — supply `?displayId=N` or `*-display-N.*`. - `DISPLAY_NOT_AVAILABLE` — the X server for that `displayId` is unreachable. Returned by the input, clipboard and window routes alike. - `404 SCREENSHOT_NOT_FOUND` on `GET /api/v1/display/screenshot/{timestamp}` — no stored capture has that timestamp. Refresh by calling `GET /api/v1/display/screenshot`, which **takes a fresh screenshot** (with `base64` on, the response carries its `info.timestamp`), then retry `GET /api/v1/display/screenshot/{timestamp}` with the new timestamp. `GET /api/v1/display/screenshot/last` returns the latest stored image by default; its metadata-only form (`GET /api/v1/display/screenshot/last/info`) returns only that image's metadata. Neither takes a fresh screenshot, so neither replaces a missed timestamp. ## Related namespaces `terminal`, `notifications`, `browser`, `files`, `exec`. ## Examples Each step has a copy-pasteable code block in the mode you're reading (curl for HTTP, `hoody` for CLI, TypeScript for SDK). Set `P`, `C`, `N` (project id, container id, server name) from `GET /api/v1/containers/{id}` first. The `N` in the `display-N` kit hostname is the display id, so `display-1` addresses display 1; `?displayId=N` overrides it. The examples pass `displayId=1` explicitly, matching the host. ### 1. See-then-act loop — capture, click, re-capture **Goal:** capture the screen, click a coordinate, capture again — the typical inner loop for vision-driven agents. Each capture with `base64` on returns the image and its metadata in one response, so no separate metadata call is needed. `info.timestamp` is the capture time in whole seconds; two captures in the same second share it, so it cannot tell you whether the screen changed. **Step 1 — capture a baseline with `base64` so the bytes round-trip in JSON.** ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/display/screenshot?displayId=1&base64=true" > /tmp/before.json jq -r .info.timestamp /tmp/before.json jq -r .image.data /tmp/before.json > /tmp/before.b64 ``` **Step 2 — click at `(75, 50)`.** `POST /api/v1/display/input/click-at` moves AND clicks in one call; default `button=1` (left). ```bash curl -sX POST "$KIT/api/v1/display/input/click-at?displayId=1" \ -H 'Content-Type: application/json' -d '{"x":75,"y":50,"button":1}' ``` **Step 3 — capture again and give the new image to the vision model.** With `base64` on, `GET /api/v1/display/screenshot` returns the fresh image and its metadata. There is no cheaper probe: the metadata-only form (`GET /api/v1/display/screenshot/info`) still takes a full screenshot and only leaves the image bytes out. ```bash curl -sf "$KIT/api/v1/display/screenshot?displayId=1&base64=true" | jq -r .image.data > /tmp/after.b64 ``` ### 2. Find a window by name + focus it **Goal:** locate the `xeyes` window without knowing its decimal `windowId`, then focus and confirm. **Step 1 — `POST /api/v1/display/window/search` with a regex `pattern`.** The booleans control which X11 fields to match against (`name` = WM_NAME / `_NET_WM_NAME`, `class` / `classname` = WM_CLASS pair). Returns an object whose `windows` field is an array of numeric window ids. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" WID=$(curl -sX POST "$KIT/api/v1/display/window/search?displayId=1" \ -H 'Content-Type: application/json' \ -d '{"pattern":"xeyes","name":true,"class":true,"classname":true}' \ | jq -er '.windows[0] // error("No window matched xeyes")') || exit 1 echo "wid=$WID" ``` **Step 2 — focus + confirm.** Focus with `sync` on, then read `details.inputFocus` in the focus response. The call answers `success: true` even when it could only activate the window: `inputFocus: false` (with a `warning`) means the window is not viewable (no viewer attached, or unmapped), so keyboard input cannot reach it. `GET /api/v1/display/window/active` reports the active window, which confirms the activation only. ```bash FOCUS=$(curl -sX POST "$KIT/api/v1/display/window/focus?displayId=1" \ -H 'Content-Type: application/json' -d "{\"windowId\":$WID,\"sync\":true}") [ "$(echo "$FOCUS" | jq -r .details.inputFocus)" = "true" ] && echo "keyboard focus OK" ACTIVE=$(curl -sf "$KIT/api/v1/display/window/active?displayId=1" | jq -r .windowId) [ "$ACTIVE" = "$WID" ] && echo "active OK" ``` ### 3. Click sequence, then type into the focused window **Goal:** focus an editable field (e.g. a text input at `(120, 80)`), type a string, with a small per-keystroke delay so the target app doesn't drop characters. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" # 1. click to set keyboard focus on the field curl -sX POST "$KIT/api/v1/display/input/click-at?displayId=1" \ -H 'Content-Type: application/json' -d '{"x":120,"y":80}' # 2. type. `delay` is inter-keystroke ms (0..1000) curl -sX POST "$KIT/api/v1/display/keyboard/type?displayId=1" \ -H 'Content-Type: application/json' \ -d '{"text":"hello world","delay":20}' ``` `POST /api/v1/display/input/type-at` collapses click-then-type into one call when you only need plain ASCII at one point: `{ x, y, text, delay }`. End `text` with `\n` to press Return after it (to submit a form or an address bar). ### 4. Drag from one position to another **Goal:** smooth-drag from `(50, 50)` to `(200, 150)` over `steps=20` interpolated mouse positions (raise `steps` if the target app's drag-recogniser misses fast moves; cap is 1000). ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/display/input/drag?displayId=1" \ -H 'Content-Type: application/json' \ -d '{"startX":50,"startY":50,"endX":200,"endY":150,"steps":20,"button":1}' ``` If a drag aborts mid-way and the button stays "pressed" (next click misbehaves), see example 10 — `POST /api/v1/display/input/reset` releases stuck buttons + modifiers. ### 5. Clipboard hand-off — write text, paste with Ctrl+V **Goal:** stage text in the X11 CLIPBOARD selection, then send Ctrl+V into the focused window so it's pasted natively. Clipboard calls can fail with `CLIPBOARD_FAILED` (see Quirks), so read the clipboard back after the write. **Step 1 — `POST /api/v1/display/clipboard` to the standard CLIPBOARD buffer.** PRIMARY (middle-click paste) is a different selection — Ctrl+V reads CLIPBOARD only. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/display/clipboard?displayId=1" \ -H 'Content-Type: application/json' \ -d '{"text":"pasted via hoody","selection":"clipboard"}' # Verify curl -sf "$KIT/api/v1/display/clipboard?displayId=1&selection=clipboard" | jq -r .text ``` **Step 2 — Ctrl+V into the focused window.** `keys` is an array — pass `["shift+Insert"]` instead if the target app paste-binds to PRIMARY. ```bash curl -sX POST "$KIT/api/v1/display/keyboard/key?displayId=1" \ -H 'Content-Type: application/json' -d '{"keys":["ctrl+v"]}' ``` ### 6. Read window properties (geometry + WM_CLASS + WM_NAME) **Goal:** for an unknown window id `WID`, read its title, class hints, and pixel rectangle to decide where to click. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/display/window/$WID/properties?displayId=1" | jq '.properties' # → { wmClass:["xeyes","XEyes"], wmName:"xeyes", wmRole:null, pid:null, wmState:[], wmType:[], transientFor:null } curl -sf "$KIT/api/v1/display/window/$WID/geometry?displayId=1" | jq '{x,y,width,height}' ``` `windowId` accepts decimal or hex (`0x...`). These two path-parameter calls echo `windowId` back exactly as sent, as a string; only the list, search and active-window calls return decimal numbers. ### 7. List visible windows with `onlyVisible` filter **Goal:** list the window manager's windows minus the minimized ones, then pick the one named `xeyes`, no regex. `onlyVisible` only drops windows marked `_NET_WM_STATE_HIDDEN`; it does not test whether a window is actually mapped or viewable (the list is also capped at 200 windows). ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/display/windows?displayId=1&onlyVisible=true" \ | jq '.windows[] | select(.name=="xeyes") | {windowId, name, class, geometry}' ``` Each item carries `windowId`, `name`, `class` (the WM_CLASS instance/class pair when it can be read, otherwise an empty array), `desktop`, a per-window geometry object (the JSON key is "geometry", shaped `{x,y,width,height}`), `focused`, `states`. Use `focusedWindowId` on the parent object to find the active window without a second call. ### 8. Batch input replay — one POST, many actions **Goal:** replay a recorded interaction (move → wait → click → wait → type) in one request. `actions[]` cap is 50, each item is `{ action: "/", params: {...} }`. The actions run in order and the batch stops at the first failure; nothing is rolled back, so actions before it have already taken effect. A failed action is still HTTP 200: check `success`, then `completed` (the actions that ran), `failed` (`{index, action, error}`) and `skipped`. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/display/input/batch?displayId=1" \ -H 'Content-Type: application/json' \ -d '{ "actions":[ {"action":"mouse/move", "params":{"x":120,"y":80}}, {"action":"input/wait", "params":{"ms":150}}, {"action":"mouse/click", "params":{"button":1}}, {"action":"keyboard/type","params":{"text":"replayed","delay":15}} ] }' ``` `POST /api/v1/display/input/wait` standalone (`{ ms, screenshot }`) is the right way to insert pauses between separate calls if you don't want to use `POST /api/v1/display/input/batch`. `ms` floor 50, ceiling 30 000. ### 9. Get display information — geometry, screenshots, X server status **Goal:** one call that returns the running PID/session-name, connected clients, the window list, and the recent screenshot list — then pair it with `GET /api/v1/display/input/display-geometry` for the X server's pixel size. Useful as a one-shot diagnostic before driving input. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sf "$KIT/api/v1/display/info?displayId=1" \ | jq '{display, pid, session_name, user, start_time, connected_clients, latency, windowCount: (.windows|length), screenshotCount: (.screenshots|length)}' # Just the geometry (cheaper): curl -sf "$KIT/api/v1/display/input/display-geometry?displayId=1" | jq '{width,height,screen}' # → e.g. { width: 8192, height: 4096, screen: 0 } (the virtual screen, much larger than any monitor) ``` Note: the geometry returned is the display's virtual screen (often `8192x4096`), not a physical monitor size. Pointer coordinates (`POST /api/v1/display/input/click-at` and the rest) are in this screen space, and a screenshot covers the same space, pixel for pixel. ### 10. Reset stuck modifiers / buttons after a misfired drag **Goal:** after an aborted drag or a `POST /api/v1/display/keyboard/key-down` you forgot to release, the X server still thinks Shift / Ctrl / Button-1 is held. Symptom: every subsequent click acts as Shift-click; typed letters arrive uppercase. `POST /api/v1/display/input/reset` releases everything in one call. ```bash KIT="https://${P}-${C}-display-1.${N}.containers.hoody.com" curl -sX POST "$KIT/api/v1/display/input/reset?displayId=1" \ -H 'Content-Type: application/json' -d '{}' # → {"success":true,"action":"reset","details":{"message":"All modifier keys and mouse buttons released"}} ``` Safe to call any time, even when nothing is stuck. Pair it with the start of every new automation run as a defensive default. ## Reference ### `clipboard` (2) — Display information and management | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/display/clipboard` | Read clipboard text | `?displayId` `?selection` | | `POST /api/v1/display/clipboard` | Write clipboard text | `?displayId` `body*:display_ClipboardWriteBody` | **Param notes:** - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 - `selection` — Clipboard buffer selection ### `display` (2) — Display information and management | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/display/info` | Get display information and screenshots | `?displayId` | | `GET /api/v1/display/input/display-geometry` | Get display dimensions | `?displayId` | **Param notes:** - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 ### `input` (8) — Mouse, keyboard, and window control operations | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/display/input/act` | Execute one action with optional screenshot | `?displayId` `body*:display_ActBody` | | `POST /api/v1/display/input/batch` | Execute a sequence of actions | `?displayId` `body*:display_BatchBody` | | `POST /api/v1/display/input/click-at` | Move cursor and click | `?displayId` `body*:display_ClickAtBody` | | `POST /api/v1/display/input/drag` | Drag from one position to another | `?displayId` `body*:display_DragBody` | | `POST /api/v1/display/input/reset` | Emergency release all inputs | `?displayId` | | `POST /api/v1/display/input/select` | Select a range via click + shift-click | `?displayId` `body*:display_SelectBody` | | `POST /api/v1/display/input/type-at` | Move, click, and type in one operation | `?displayId` `body*:display_TypeAtBody` | | `POST /api/v1/display/input/wait` | Wait for a duration with optional screenshot | `?displayId` `body*:display_WaitBody` | **Param notes:** - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 ### `keyboard` (4) — Mouse, keyboard, and window control operations | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/display/keyboard/key-down` | Hold a key down | `?displayId` `body*:display_KeyboardKeyDownBody` | | `POST /api/v1/display/keyboard/key` | Press key combinations | `?displayId` `body*:display_KeyboardKeyBody` | | `POST /api/v1/display/keyboard/type` | Type a string of text | `?displayId` `body*:display_KeyboardTypeBody` | | `POST /api/v1/display/keyboard/key-up` | Release a held key | `?displayId` `body*` | **Param notes:** - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 **Body shapes:** - `POST /api/v1/display/keyboard/key-up` body — `{ key*: string, window: int | string }` ### `kit` (1) — Server health and status endpoints | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/display/health` | Service health check | | ### `mouse` (8) — Mouse, keyboard, and window control operations | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/display/mouse/click` | Click a mouse button | `?displayId` `body:display_MouseClickBody` | | `POST /api/v1/display/mouse/double-click` | Double-click a mouse button | `?displayId` `body` | | `POST /api/v1/display/mouse/down` | Press and hold a mouse button | `?displayId` `body` | | `GET /api/v1/display/mouse/location` | Get cursor position | `?displayId` | | `POST /api/v1/display/mouse/move` | Move cursor to absolute position | `?displayId` `body*:display_MouseMoveBody` | | `POST /api/v1/display/mouse/move-relative` | Move cursor by offset | `?displayId` `body*` | | `POST /api/v1/display/mouse/scroll` | Scroll in a direction | `?displayId` `body*:display_MouseScrollBody` | | `POST /api/v1/display/mouse/up` | Release a mouse button | `?displayId` `body` | **Param notes:** - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 **Body shapes:** - `POST /api/v1/display/mouse/double-click` body — `{ button: int=1, window: int | string }` - `POST /api/v1/display/mouse/down` body — `{ button: int=1, window: int | string, holdMs: int }` - `holdMs` — Auto-release after this many milliseconds - `POST /api/v1/display/mouse/move-relative` body — `{ x*: int, y*: int, sync: bool }` - `POST /api/v1/display/mouse/up` body — `{ button: int=1, window: int | string }` ### `screenshots` (4) — Screenshot capture and retrieval operations | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/display/screenshot` | Capture a new screenshot | `?base64` `?displayId` `?region` `?cursor` `?metadata` | | `GET /api/v1/display/screenshot/{timestamp}` | Retrieve a specific screenshot by timestamp | `?base64` `?displayId` | | `GET /api/v1/display/screenshot/last` | Retrieve the most recent screenshot | `?base64` `?displayId` `?metadata` | | `GET /api/v1/display/screenshots` | List all available screenshots | `?displayId` | **Param notes:** - `base64` — Return base64-encoded JSON response instead of binary image. Useful for AI agents and systems that can't handle binary data. Accepted values: `true`, `1`, `` (empty) - Return base64 JSON; `false`, `0` - Return binary (default) - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 - `region` — Crop the returned image to `x1,y1,x2,y2`. Minimum 10x10 px, maximum 65535 on each axis, `x2 > x1` and `y2 > y1`; anything else is a 400. A capture spans the whole screen, so these are screen coordinates: the same ones `POST /input/click-at` takes and `GET /input/display-geometry` describes. The cropped image starts at `x1,y1`: its pixel (x, y) is screen point (x1 + x, y1 + y). - `cursor` — Include the pointer position in the response. Only has an effect on the base64 JSON form, which gains a `cursor` object; a binary PNG response has nowhere to put it. Accepted values: `true`, `1`, `` (empty). Anything else is off. - `metadata` — Answer the screenshot metadata instead of the image. _(on `GET /api/v1/display/screenshot`)_ - `timestamp` — Unix timestamp of the screenshot. Use the `timestamp` field returned by screenshot metadata/list endpoints. Do not use `timestamp_human` for path queries. Must be numeric only for security. - `metadata` — Answer the latest screenshot metadata instead of the image. _(on `GET /api/v1/display/screenshot/last`)_ ### `thumbnails` (3) — Thumbnail image operations | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/display/thumbnail` | Capture a new screenshot thumbnail | `?base64` `?displayId` | | `GET /api/v1/display/thumbnail/{timestamp}` | Retrieve a specific thumbnail by timestamp | `?base64` `?displayId` | | `GET /api/v1/display/thumbnail/last` | Retrieve the most recent thumbnail | `?base64` `?displayId` | **Param notes:** - `base64` — Return base64-encoded JSON response instead of binary image. Useful for AI agents and systems that can't handle binary data. Accepted values: `true`, `1`, `` (empty) - Return base64 JSON; `false`, `0` - Return binary (default) - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 - `timestamp` — Unix timestamp of the screenshot. Use the `timestamp` field returned by screenshot metadata/list endpoints. Do not use `timestamp_human` for path queries. Must be numeric only for security. ### `windows` (14) — Mouse, keyboard, and window control operations | Method | Summary | Params | |--------|---------|--------| | `POST /api/v1/display/window/close` | Close a window | `?displayId` `body*:display_WindowIdBody` | | `POST /api/v1/display/window/focus` | Focus/activate a window | `?displayId` `body*:display_WindowSyncBody` | | `GET /api/v1/display/window/{windowId}/properties` | Get extended properties for a window | `?displayId` | | `GET /api/v1/display/window/active` | Get the active window ID | `?displayId` | | `GET /api/v1/display/window/{windowId}/geometry` | Get window position and size | `?displayId` | | `GET /api/v1/display/window/{windowId}/name` | Get window title | `?displayId` | | `GET /api/v1/display/windows` | List windows on the current display | `?displayId` `?onlyVisible` | | `POST /api/v1/display/window/minimize` | Minimize a window | `?displayId` `body*:display_WindowSyncBody` | | `POST /api/v1/display/window/move` | Move a window | `?displayId` `body*:display_WindowMoveBody` | | `POST /api/v1/display/window/raise` | Raise a window to the top | `?displayId` `body*:display_WindowIdBody` | | `POST /api/v1/display/window/resize` | Resize a window | `?displayId` `body*:display_WindowResizeBody` | | `POST /api/v1/display/window/restore` | Restore (un-minimize) a window | `?displayId` `body*:display_WindowRestoreBody` | | `POST /api/v1/display/window/search` | Search for windows by pattern | `?displayId` `body*:display_WindowSearchBody` | | `POST /api/v1/display/input/wait-until` | Wait for a window to appear or disappear | `?displayId` `body*:display_WaitUntilBody` | **Param notes:** - `displayId` — Display ID to use (overrides the `*-display-N.*` hostname pattern). Valid range: 1-999999 - `onlyVisible` — Drop windows carrying `_NET_WM_STATE_HIDDEN`. A minimized window carries that state, so this does exclude minimized windows. This is a different test from the `onlyVisible` on `window/search` and `input/wait-until`, which ask the X server whether the window is viewable and still match a minimized one. ### Body schemas - `display_ClipboardWriteBody` — `{ text*: string, selection: "clipboard" | "primary" | "secondary"="clipboard" }` - `display_WindowSyncBody` — `{ windowId*: int | string, sync: bool }` - `display_WindowMoveBody` — `{ windowId*: int | string, x*: int, y*: int, sync: bool, relative: bool }` - `display_WindowResizeBody` — `{ windowId*: int | string, width*: int, height*: int, sync: bool, useHints: bool }` - `display_WindowRestoreBody` — `{ windowId*: int | string, sync: bool=true }` - `sync` — Wait (up to 2 s) until the window manager reports the window as no longer minimized. Defaults to true, unlike the other window actions: the restore request is a message the window manager may ignore, so without waiting the response cannot say whether it worked. - `display_WindowIdBody` — `{ windowId*: int | string }` - `display_WindowSearchBody` — `{ pattern*: string, name: bool, class: bool, classname: bool, onlyVisible: bool }` - `display_WaitUntilBody` — `{ condition*: "window-present" | "window-absent", pattern: string, match: "name" | "class" | "classname"="name", onlyVisible: bool=false, windowId: int | string, timeoutMs: int=10000, pollMs: int=250 }` - `pattern` — Extended POSIX regex. Required for `window-present`; for `window-absent` give either this or `windowId`, not both. A pattern that does not compile is a 400, not an empty result, and so is one containing a NUL (it could never reach the subprocess). - `onlyVisible` — … Sending it alongside `windowId` is rejected: that is an identity check, not a search, so the flag would be silently ignored. … - `pollMs` — Gap between observations. An explicit value above `timeoutMs` is rejected; the default is not, so a `timeoutMs` under 250 is a legal request for a single look rather than an error. - `display_MouseClickBody` — `{ button: int=1, repeat: int=1, delay: int, window: int | string }` - `repeat` — Number of clicks. `repeat` x `delay` must not exceed 4000 ms, or the request is rejected with 400 `VALIDATION_ERROR` naming both fields. The count is never silently capped, so `repeat: 100` stays valid at `delay: 40` or less. - `display_MouseMoveBody` — `{ x*: int, y*: int, window: int | string, screen: int, sync: bool }` - `display_MouseScrollBody` — `{ direction*: "up" | "down" | "left" | "right", clicks: int=5, delay: int, x: int, y: int }` - `clicks` — Wheel clicks. `clicks` x `delay` must not exceed 4000 ms, or the request is rejected with 400 `VALIDATION_ERROR`; `clicks: 100` therefore needs `delay: 40` or less. - `x` — Scroll at this point instead of wherever the pointer happens to be. Must be given together with `y`. The move and the wheel events are sent as one chained command, so nothing can move the pointer in between. - `y` — Must be given together with `x`. - `display_KeyboardTypeBody` — `{ text*: string, window: int | string, delay: int, clearModifiers: bool }` - `display_KeyboardKeyBody` — `{ keys*: string[], window: int | string, delay: int, clearModifiers: bool }` - `display_KeyboardKeyDownBody` — `{ key*: string, window: int | string, holdMs: int }` - `display_ClickAtBody` — `{ x*: int, y*: int, button: int=1, repeat: int=1, delay: int }` - `repeat` — Clicks at that point, in one chained invocation, so the pointer cannot be moved between them. Same 4000 ms `repeat` x `delay` budget as `/mouse/click`. - `display_TypeAtBody` — `{ x*: int, y*: int, text*: string, delay: int }` - `display_DragBody` — `{ startX*: int, startY*: int, endX*: int, endY*: int, button: int=1, steps: int }` - `display_SelectBody` — `{ x*: int, y*: int, endX*: int, endY*: int }` - `display_ActBody` — `{ action*: string, params: object, screenshot: bool=true, screenshotDelay: int=100, screenshotRegion: string }` - `action` — Action path. … `act` runs one action, so a rejection here IS a 400 `VALIDATION_ERROR` (inside `/input/batch` the same rejection is reported in the 200 body as `failed.error` instead). - `display_WaitBody` — `{ ms*: int, screenshot: bool=false }` - `display_BatchBody` — `{ actions*: { action*: string, params: object }[] }` --- # `egress` — the container's outbound HTTP proxy ## Purpose **Mental model: a proxy the standard container provision already runs, whose exit IP you choose at runtime.** Point any HTTP client at the container's egress URL and the request leaves through the container. Configure an *upstream* and the same URL routes through that instead, so the exit IP changes without touching the client. It answers on the container's own host at the `egress` service slug, so on a normally-provisioned container there is nothing to install, start, or configure first — registration happens at provision time, not on demand, and Prerequisites has the one precondition and a one-call check. Indexed forms reach the same single process and share one upstream setting — the index is not a second proxy. What the index does change is proxy permissions, which are evaluated per service index, so `egress-1` and `egress-2` can carry different credentials while exiting through the same address. The canonical URL carries no index; an explicit `egress-` is accepted and selects the permission scope described above. It handles `CONNECT` tunnelling for HTTPS (never seeing inside the TLS session) and absolute-URI forwarding for plain HTTP. ## When to use Use it when something inside a container needs to make outbound HTTP requests through a controllable exit: giving a scraper a specific egress IP, routing container traffic through a third-party SOCKS5 or HTTP proxy, or exposing a proxy endpoint to a client that only accepts a host and port. Use `PUT /api/v1/egress/upstream` to chain, `GET /api/v1/egress/upstream` to inspect, and `DELETE /api/v1/egress/upstream` to go back to the container's own IP. ## When NOT to use Do not use it as a general ingress path: any request whose target begins with `/` and is not one of the management routes returns 404 and is never forwarded, so it cannot be repurposed as a reverse proxy. (`OPTIONS` is the one exception, answered 204 before routing.) Do not reach for it to expose a local service to the internet — that is the `tunnel` namespace. Do not expect request hooks to apply; egress is on the hook-rejected list. ## Prerequisites A running container whose provision registered egress — the overwhelmingly common case, not something to arrange. Provisioning registers egress on a new container by default, and containers created before egress existed are backfilled over time, so the gaps to expect are a container whose host has it turned off and one that has not been backfilled yet. No kit program needs enabling first — where registered, hoody-egress is eager (`boot: true`, `lazy_load: false`, unlike lazily-loaded siblings such as `pipe` or `run`), so the endpoint answers as soon as the container is up. To confirm before relying on it, probe the unauthenticated health route: a 200 with the standard JSON health blob from `GET /api/v1/egress/health` confirms egress is live; any other outcome does not establish that it is absent. A failed probe cannot separate an unregistered kit from an overloaded or unreachable one: the server checks its connection cap before reading the request, so it can answer 503 while alive, and an edge or transport failure looks the same from outside. Registration can also be read from the always-present daemon kit: look for a `hoody-egress` entry in `GET /api/v1/daemon/programs`. Setting an upstream needs nothing beyond the container URL and whatever proxy permissions guard it. ## Capability URL The endpoint is `https://{projectId}-{containerId}-egress-{serviceIndex}.{server}.containers.hoody.com` — see `SKILL-HTTP.md § Proxy URLs` for the routing rules — and it is a capability URL: the project and container identifiers in the hostname *are* the credential, and hoody-egress performs no authentication of its own. An open egress endpoint is therefore an open proxy — anyone holding the URL can send traffic through it, consuming the server's bandwidth and attributed to its exit IP. Set proxy permissions on the `egress` service before sharing it or configuring an upstream. ## Common workflows **Inspect the current setting.** `GET /api/v1/egress/upstream` reports `enabled`, `state`, the scheme, host and port, the config path, and an `auth` boolean. The two flags answer different questions. `enabled` says an upstream is CONFIGURED. `state` says which configuration is in force: `active` (an address has been checked and approved and requests are sent through it), `unavailable` (configured but no approved address, so proxied requests get 502 and are never sent directly instead) or `direct` (nothing configured). Neither flag reports reachability. `active` means approved pins exist, not that anything answers on them, so a permitted address with nothing listening stays `active` while every request fails. `unavailable` is the one that operators most often read backwards: it means proxied traffic is REFUSED with `502 configured upstream proxy is unavailable`, never quietly sent direct. `enabled` is therefore `true` in both `active` and `unavailable`; only `direct` reads `false`. Scheme, host, port and `auth` are present whenever there is a parsed upstream configuration to report, and absent when there is not: nothing is configured (`direct`), the configured text did not parse, or the persisted setting could not be read. Credentials are never returned, by design, so a read cannot be used to recover a secret someone else configured. One compatibility rule for anything that branches on `state`: it is newer than the other fields, so a container running an older egress build answers without it. Treat its ABSENCE as "this kit predates the field" and fall back to `enabled`, rather than comparing a missing value against `'active'` and concluding the upstream is broken. **Point traffic somewhere else.** `PUT /api/v1/egress/upstream` takes a `text/plain` body whose value is the first non-blank, non-`#` line; `POST` to the same path is accepted as an alias; the kit handles both verbs in one branch. Four schemes are accepted: `socks5h` sends the destination hostname upstream for resolution there, `socks5` resolves locally and sends an address, and `http` / `https` chain through an HTTP proxy using `CONNECT`, the latter with TLS to the upstream. Prefer `socks5h` when the point of the exercise is to avoid leaking destination lookups. **Go back to the container's own IP.** `DELETE /api/v1/egress/upstream`, or equivalently a `PUT` with an empty body — the kit treats a body with no URL line as a disable. Check with `GET /api/v1/egress/upstream`. **Lease an upstream that should end with its client.** `PUT /api/v1/egress/upstream?lease=60` (or the `POST` alias) installs the upstream for that many whole seconds, from 5 to 3600. The answer, and every later read while that upstream is configured, carries `lease: { id, ttl, expires_at, expires_in }` (`expires_at` in Unix seconds). Renew it before the deadline with `POST /api/v1/egress/upstream/renew?lease_id=` (no body): the deadline moves to `ttl` seconds from now, never earlier than it already was and never more than 3600 seconds ahead, and the answer is the same body a read returns. If no renewal arrives in time, the kit disables the upstream the way an explicit disable does and records the disable in its config file, so the container goes back to its own IP and stays there across a restart. A lease that ran out while the kit was down is disabled at startup. A set without `lease` installs a permanent upstream and ends any earlier lease. A replacement or a disable also ends it, and renewing the old id then answers 409. **Confirm where traffic exits.** Request `https://ip.hoody.com` through the proxy; it reports the address it saw, which is the container's or the upstream's once one is set. ## Quirks & gotchas - **Teardown deletes, it does not restore.** Clearing removes the upstream, and the kit never returns credentials — a read reports scheme, host, port and an `auth` flag only — so an authenticated upstream that some other tool configured cannot be put back unless whoever configured it still holds the full URL. An unauthenticated one can be rebuilt from a read taken before the clear. - **The setting is applied without a restart.** It lands in the file reported as `config_path` in the response and is picked up within about a second. A clear does not remove that file — it records an explicit `disabled` state, which is what makes the disable survive a restart of a process that was started with an upstream. A URL line the destination guard refuses, or one that does not parse, is NOT a fall back to direct, and which of two things it does depends on whether an upstream is already working: with one in force that upstream keeps carrying traffic, and with none in force the kit reports `state: "unavailable"` and answers proxied requests with 502 until the line is fixed or removed. - **Direct destinations are filtered, unconditionally, and IPv4 only.** With no upstream in force, the kit resolves the destination, refuses private, loopback, link-local, CGNAT, benchmarking, documentation, TEST-NET, multicast and reserved addresses with `403 destination not permitted`, and dials the address it checked, so a short-TTL record cannot pass the check and then point elsewhere. An IPv6 literal destination is refused on every path, upstream or not, mapped (`::ffff:a.b.c.d`), compatible and NAT64 spellings included; a name the kit resolves itself that has no IPv4 address is refused too. There is no flag, environment variable, file or API field that admits one. The same address rule applies to the upstream itself, with one exception for chaining: a `socks5`/`socks5h` upstream on IPv4 loopback is accepted on any port, credentials optional, because that is the shape a local exit installs. Past an upstream, the destination is that exit's business for all four schemes: `socks5` resolves the name here and sends the first IPv4 address without the private-address check, and `socks5h`, `http` and `https` hand the name to the exit, which also decides its address family. - **A configured upstream that cannot be used refuses traffic; it does not fall back to direct.** With no upstream in force, a configured one that is refused, unresolvable or unparsable reads as `enabled: true, state: "unavailable"`, and proxied requests get `502 configured upstream proxy is unavailable`. That is deliberate: a request must not leave from the container's own address after someone asked for an exit. The kit keeps retrying, so a transient DNS failure recovers on its own. For an upstream set without a lease, direct egress returns only on an explicit disable (`DELETE`, an empty or `disabled` body, or emptying a config file that has governed); an upstream set with a `lease` (in seconds) is also disabled automatically when the lease runs out without a renewal. A replacement refused by the management API (the `400` answers below) changes nothing at all. A replacement written into the config file behaves differently: an unparsable line is ignored while an upstream is working, but a line that parses and is refused only for now becomes the pending setting. The working upstream keeps carrying traffic meanwhile, the kit keeps re-checking the new line, and it takes over as soon as a later check approves it. - **The body is small and strictly framed.** A missing `Content-Length` is 411, and a *declared* `Content-Length` over 4096 is 413 — the check is on the header, before the body is read. This is not a channel for anything but a URL. - **Health answers almost any method.** The health route matches on path alone, so every method except `OPTIONS` reaches it; `OPTIONS` is answered 204 with CORS headers before routing, which is what makes browser preflight work against the management API. - **A local exit shows up as an upstream of `socks5h://127.0.0.1:`.** The SDK and CLI ship a helper that binds that loopback port over hoody-tunnel and terminates SOCKS5 on the user's own machine, so the container's traffic exits from wherever that helper runs. The reverse does not hold: the kit accepts any SOCKS upstream on IPv4 loopback, so that address alone does not tell you what is listening there or where the traffic leaves. There is no way to start one over plain HTTP; you can only observe it (`GET /api/v1/egress/upstream`) or clear it (`DELETE /api/v1/egress/upstream`). - **A dead loopback port breaks every request.** If a local exit dies without clearing the upstream, the container keeps pointing at a port that no longer answers and every request through its egress fails until the upstream is cleared. Recover with `DELETE /api/v1/egress/upstream`. - **Browsers need a PAC file, not the manual proxy fields.** The connection to the proxy is itself TLS, so the manual host-and-port fields open a plaintext connection that the edge refuses with 400. A PAC file returning `HTTPS host:443` works in both Chrome and Firefox. ## Common errors Errors come from two surfaces that answer differently. The management surface always sends a body: `text/plain` for every error except the 404, which is JSON, and every body ends with a trailing newline, so match on prefix or substring rather than equality. Most framing and forwarding errors send no response body and no `Content-Type`; the exceptions are a destination-policy refusal (403) and an unavailable configured upstream (502), which both carry a `text/plain` body. The status line still arrives with headers, always including `Vary: Origin` and `Connection: close`. **Management surface** (path-form requests: `/api/v1/egress/upstream`, `/api/v1/egress/upstream/renew` and the route catch-all): - 400 — the following causes, each with its own `text/plain` body: `Invalid upstream URL` when the value does not parse or its scheme is not one of the four, `Upstream destination not permitted` when it parses but every address it resolves to is refused by the destination guard, `Upstream unresolvable` when the host did not resolve inside the connect timeout (transient, worth a retry, and distinct from the previous one), `Failed to read body` when the read fails or times out, and `Body must be UTF-8`. A set request can also return `Invalid lease: give whole seconds from 5 to 3600`, or `A lease needs an upstream URL` when a lease accompanies an empty or `disabled` body. The OpenAPI 400 description names the same bodies; it is documentation, not additional wire text. A refused or unresolvable replacement leaves a working upstream in force, so a 400 here does not mean the container lost its exit. - 404 — a path-form target that is not a management route, and the one JSON error: `{"error":"not found"}` with `Content-Type: application/json`. It is never forwarded, so it means the request was addressed to the proxy rather than through it. - 400 — `Missing or invalid lease_id` on a renewal whose `lease_id` is absent or is not 1 to 64 ASCII letters and digits. - 405 — `Method Not Allowed` for any verb on the upstream route other than `GET`, `PUT`, `POST`, or `DELETE`, and for any verb but `POST` on the renew route. `OPTIONS` never reaches it; it is answered 204 before routing. - 411 — `Missing Content-Length` on a set request. - 413 — `Body too large` when the declared `Content-Length` exceeds 4096 bytes. - 409 — `No upstream lease with this id is in force` on a renewal: the lease already expired, the upstream was replaced or disabled, or the config file no longer holds that lease. Nothing is rewritten, so the old upstream is not revived. Set the upstream again, with a new lease, if it is still wanted. - 500 — `Failed to write config` when persisting the upstream file fails, on set, clear and renewal alike, and `Failed to read config` when a renewal cannot read it. The in-memory upstream is swapped only after a successful write, so after a 500 the previous setting still applies. **Proxy data path and request framing.** Most of these send no response body; the two policy answers below (403, and the 502 whose body names an unavailable upstream) are the exceptions, and both carry `Content-Type: text/plain` plus CORS headers. - 400 — an oversized or truncated header block, a bad request line, an invalid `CONNECT` authority, or a non-`CONNECT` target that is neither absolute-form `http://` nor asterisk-form `*`. An `https://` URL sent without `CONNECT` lands here. Asterisk-form is the one non-absolute target that forwards: `*` with a `Host` header is sent to the authority the header names; without one it is a 400. Header lines themselves never trigger it: a line with no colon is silently skipped, not rejected. IPv6 spellings split across 400 and 403: a bracketed authority must hold a plain IPv6 address, so `[fe80::1%eth0]`, `[example.com]` and `[]` are malformed authorities (400) rejected before any lookup, while a well-formed `[2606:4700::1111]` is a policy refusal (403). An unbracketed literal such as `CONNECT ::1:443` is also a 400. - 403 — `destination not permitted`, the destination guard's refusal, on `CONNECT` and absolute-URI forwarding alike. With no upstream in force it covers private, loopback, link-local, CGNAT, benchmarking, documentation, TEST-NET, multicast and reserved IPv4. On every path it covers an IPv6 literal destination and a name this kit resolves that has no IPv4 address (the kit is IPv4-only); a name handed to a `socks5h`, `http` or `https` upstream is resolved by that exit instead. Nothing turns it off, so retrying or changing client is pointless: use a public IPv4 destination. The body is identical whether or not anything is listening there, so it is not a port scanner. One stated limitation: for a body-bearing forward the request body is written before the response is read, so an early refusal during a large upload can reach the client as a connection close rather than a 403. - 408 — request headers not completed within the read timeout. - 502 — `configured upstream proxy is unavailable` when an upstream is configured but has no approved address (refused, unresolvable, or unparsable text). The destination is not even resolved, and the request is never sent directly instead, so this status is the kit refusing to leak a request out of the container's own IP after you asked for an exit. Read `state` on `GET /api/v1/egress/upstream` to confirm, and either fix the address or clear the upstream. Every other 502 has no body: the outbound connection failed, the destination was unreachable, the chained upstream refused or timed out, or no valid response came back. It is also the answer when the client's own request body breaks mid-forward: a malformed chunk size or chunk ending fails inside the forwarding path, and the outer handler reports every forwarding failure as 502, so a bad client body reads the same as a dead upstream. A 502 is not always a standalone response either: after the `CONNECT` 200 has been sent, or after a forwarded response has started, a relay failure appends the 502 to the bytes already written. With an upstream set and `state: "active"`, a bodyless 502 on every request usually means the upstream itself is dead; see the dead-loopback quirk. - 503 — the concurrent-connection cap is reached. ## Related namespaces `tunnel` for the opposite direction (exposing a local service through the container). `proxy.containerPermissions` for gating the endpoint, which matters more here than almost anywhere else because the URL is the only credential. `proxy.aliases` to hand out a hostname that does not carry the container id. `api` for container firewall rules, whose `firewall/egress` routes govern packet filtering and are unrelated to this service despite the shared word. ## Examples Set `P`, `C`, `N` (project id, container id, server name) from `GET /api/v1/containers/{id}` first. The endpoint is `https://{P}-{C}-egress-1.{N}.containers.hoody.com`. Every `egress-` index reaches the same single process and shares one upstream, but proxy permissions are evaluated per index, so use the index you granted access on (see § Purpose). The SDK's `getKitUrl` and the URL `startLocalExit` hands back omit the suffix; the edge normalizes a missing index to 1, so `…-egress.…` and `…-egress-1.…` are the same endpoint and the same permission scope. ### 1. Send a request through the proxy — confirm the container is the exit **Goal:** prove the endpoint routes traffic and see the IP the destination sees. The connection to the proxy is itself TLS, so the proxy address carries an `https://` scheme. `CONNECT` tunnels HTTPS; plain HTTP rides absolute-form forwarding. ```bash EGRESS="https://${P}-${C}-egress-1.${N}.containers.hoody.com" curl -sf "$EGRESS/api/v1/egress/health" # kit alive? (unauthenticated) curl -x "$EGRESS:443" https://ip.hoody.com | jq -r '.data.ip' # the container's public IP — the upstream's, once one is set (#2) curl -x "$EGRESS:443" http://example.com/ # plain HTTP works too ``` `ip.hoody.com` reports the address it saw the request come from, so it doubles as the before/after check for every recipe below. Browsers cannot use their manual proxy fields — plaintext to a TLS port is refused with 400; use a PAC file returning `HTTPS host:443` (see Quirks). ### 2. Set an upstream, read it back, clear it **Goal:** change the exit IP without touching the client. Four schemes are accepted (`socks5h`, `socks5`, `http`, `https`); prefer `socks5h` when the upstream should also resolve DNS. Set and clear both answer `200` with the current status blob, so the response doubles as the read-back. ```bash EGRESS="https://${P}-${C}-egress-1.${N}.containers.hoody.com" curl -X PUT --data-binary 'socks5h://user:pass@proxy.example.com:1080' \ "$EGRESS/api/v1/egress/upstream" # {"enabled":true,"state":"active","scheme":"socks5h","host":"proxy.example.com","port":1080,"auth":true,...} curl "$EGRESS/api/v1/egress/upstream" # same blob — credentials never come back curl -X DELETE "$EGRESS/api/v1/egress/upstream" # {"enabled":false,"state":"direct","config_path":"/hoody/storage/hoody-egress/config/upstream_proxy.txt"} ``` The setting lands in the config file atomically and is picked up within about a second (see Quirks). Re-run the exit check from #1: the reported address flips to the upstream's, and back after the clear. `auth: true` is the only trace of the credentials — they are never returned. ### 3. Make your own machine the exit — a local exit **Goal:** turn the container's egress URL into a proxy whose traffic leaves from the machine you are sitting at. Needs the container's tunnel kit running; nothing listens on your machine (see Quirks). ```bash # A local exit cannot be STARTED over plain HTTP — observe or clear only: EGRESS="https://${P}-${C}-egress-1.${N}.containers.hoody.com" curl "$EGRESS/api/v1/egress/upstream" # a live local exit reads as socks5h://127.0.0.1: curl -X DELETE "$EGRESS/api/v1/egress/upstream" # recover from one that died uncleanly ``` While the exit runs, treat the proxy URL like a password: anyone holding it relays through your connection. ### 4. The takeover guard, and the deliberate override **Goal:** understand why a local exit refuses to start, and take a container over knowingly. Teardown deletes the upstream and credentials can never be read back, so silently replacing a third-party proxy would destroy it (see Quirks). ```bash EGRESS="https://${P}-${C}-egress-1.${N}.containers.hoody.com" curl "$EGRESS/api/v1/egress/upstream" | jq '.enabled, .state' # true + "active" → something already owns the exit: an approved upstream is in force # true + "unavailable" → still owned: configured but unusable, and it still blocks a local exit # false + "direct" → nothing configured curl -X DELETE "$EGRESS/api/v1/egress/upstream" # the explicit-clear alternative ``` The check-then-set is not atomic — the guard protects against accidents, not races. These checks belong to the SDK and CLI helpers: a raw `DELETE /api/v1/egress/upstream` clears whatever upstream is set, with no ownership check. The helper's teardown re-reads the upstream and compares scheme, host, port and `auth` before clearing, so it leaves an upstream that is visibly someone else's alone and says so; a replacement that matches on all four is indistinguishable from this exit's own, because the kit reports only `auth: true` and never credential identity. That needs a stale handle to reach: two live exits cannot share the container's loopback port, so it takes an exit whose listener is already gone, its port reused by a newer exit, and a late teardown on the old handle. When an exit started with the override stops cleanly, the container returns to its own IP, not to the proxy it displaced. ## Reference ### `kit` (1) — egress | Method | Summary | Params | |--------|---------|--------| | `GET /api/v1/egress/health` | Service health check | | ### `upstream` (4) — egress | Method | Summary | Params | |--------|---------|--------| | `DELETE /api/v1/egress/upstream` | Disable upstream | | | `GET /api/v1/egress/upstream` | Get upstream status | | | `POST /api/v1/egress/upstream/renew` | Renew the upstream lease | `?lease_id*` | | `PUT /api/v1/egress/upstream` | Set upstream | `?lease` `body*:text/plain` | **Param notes:** - `lease_id` — The `lease.id` returned when the upstream was set - `lease` — Lease the upstream for this many seconds. The service disables the upstream (as `DELETE` does) unless the lease is renewed before then with `POST /api/v1/egress/upstream/renew`. For an upstream that only works while its client is alive, such as the loopback exit `hoody egress local start` installs. --- # `exec` — micro-services: any script or API as an instant HTTP endpoint ## Purpose **Default tool when the user asks "write me an API" or "expose this script".** Drop a `.ts` / `.js` file in the scripts dir and it becomes a live HTTP handler — no framework, no build step, no deploy. The kit keeps it loaded and ready: each request is fast, supervised, schematized via magic comments / OpenAPI, log-streamed, metric-instrumented, and updateable by overwriting the file. Treat each script like a tiny microservice — single responsibility, simple in spirit, but it can shell out to anything (curl, ffmpeg, Python, native binaries, …) since it runs as a normal process inside the container. **Routes only auto-mount for `.ts` / `.js` files.** Bare `.sh` / `.py` files dropped in the scripts dir are NOT exposed as HTTP — wrap them by writing a thin `.ts` handler that shells out via `Bun.$`. From a `.ts` handler you can run anything on `$PATH` (curl, ffmpeg, Python, native binaries) in one line. To give a script a **public** address: create an alias with `POST /api/v1/proxy/aliases` (`program: 'exec'`, and `target_path: '/'` as the landing page) and you get back `https://.{server_name}.containers.hoody.com` with no `containerId` in the URL. With the default `allow_path_override: true` the alias points at the WHOLE exec kit, not at one script: `target_path` only answers a request with no path, and every other path is forwarded as sent. That includes the kit's own management API under `/api/v1/exec/` (`POST /api/v1/exec/scripts/write`, `DELETE /api/v1/exec/scripts/delete`, …), so anyone holding the link may be able to write and run code in the container. Set `allow_path_override: false` to serve only the script: it is served at the alias root AND at `/`, while any other path (sub-paths, assets and the management API under `/api/v1/exec/` included) is refused with `404 ALIAS_PATH_PINNED`, and the visitor's method, body and query keys the target does not set still reach the script. Either way, before sharing the alias, gate it with `* /api/v1/containers/{id}/proxy/permissions*` (a password, token, JWT or IP group, plus a `default` policy that denies what the group does not allow), exactly as for any kit URL. **Trust model — read carefully.** Scripts run inside the container with full container privileges. They are NOT a sandbox for untrusted user code. Anyone who can invoke a script can do everything the script can do (read files, hit other kits, spawn processes). Use them for *your* APIs / cron logic / webhooks / ETL — don't expose them as an arbitrary code-execution surface to anonymous internet users without thinking through the gate stack first. ## When to use - "Write me an API endpoint that does X" — default to a `hoody-exec` script before reaching for a Node app + framework. - **"Build a workflow"** — multi-step pipelines (call agent A → validate with agent B → trigger action C, fan-out / fan-in, retry logic, conditional branches). One script = one orchestrator; each step is a function call inside the same Bun process, so no inter-service plumbing. State between requests via `bun:sqlite` (`Database`), the `sqlite` kit or the `files` kit for durable state, or the injected `shared` object for in-memory state (one per deployment, lost when the kit restarts or evicts an idle deployment from its cache). Variables declared in the script body do not carry over: the body runs again on every request. - Webhooks (GitHub / Stripe / your CI), ETL pipelines, batch transformers, AI agent tools. - Wrap a bash one-liner or Python helper as an HTTP API with zero scaffolding. - Describe inputs / outputs in a companion `.openapi.json` file per script, auto-publish OpenAPI. - Install and pin npm deps in the kit's one shared scripts-root `package.json` (every script uses the same versions), stream logs/metrics. ## When NOT to use - **Untrusted-input code execution** — it's not sandboxed. Use a fresh container (or a stricter runtime) per untrusted caller. - Long-lived processes / supervisors → `daemon` (exec is request/response). - Schedules outliving the kit → `cron` (`exec.schedules.*` is in-process and dies with the kit). - File I/O outside the scripts dir → `files`. Interactive shells → `terminal`. Container lifecycle → `api`. Headless web → `browser`. ## Prerequisites - Scripts dir `/hoody/storage/hoody-exec/scripts/{subdomain}/{instanceId}/` (subdomain defaults to `default`, e.g. `…/scripts/default/1/`) is service-managed; write only via `POST /api/v1/exec/scripts/write`. - **`require('hoody-sdk')` works with no install step** — it loads the installed npm package from the scripts root's `node_modules`. Exec installs a missing SDK automatically (at startup, or on a script's first `require`), honors a version you declare in the scripts-root `package.json` (an exact version or a tag stops updates, a range keeps them inside it), and stages a newer registry release that the next kit startup swaps in; a running kit never replaces its live copy. (Other `require()`d npm packages are auto-installed on first execution.) Import from `'hoody-sdk'`. The constructor takes an explicit config; `withContainer` is async and returns a container-scoped client. Calls go through the edge proxy, so all the usual capability gates / request hooks / proxy logs apply (see § Source IP Guard in `SKILL-HTTP.md`). - The `hoody` CLI is also on `$PATH` if you'd rather shell out, but exec sets no account token and the CLI needs one (for a kit command too: it looks the container up). Put `HOODY_TOKEN=` in the script's `.env` companion and pass the script's env on: `Bun.$\`hoody projects list\`.env({ ...process.env })`. ## Capability URL → See `SKILL-HTTP.md § Proxy URLs`. **Reaching a service you host on a container port** (any port, any namespace): - `https://{projectId}-{containerId}-http-.{node}.containers.hoody.com` — proxy speaks HTTP to `localhost:`. - `https://{projectId}-{containerId}-https-.{node}.containers.hoody.com` — proxy speaks HTTPS to `localhost:` (target needs TLS). Edge is always `https://`. No alias, firewall edit, or proxy registration needed; capability-token gates still apply. ## Common workflows ### 1. Write, validate, invoke 1. `POST /api/v1/exec/scripts/write` — `path`, `content`, `createDirs:true`, `validate:true` (default); 400 + `validation` on fail. 2. `GET /api/v1/exec/scripts/read` — confirm bytes. 3. `POST {EXEC_BASE_URL}/` — body parsed, return auto-serialised, output streamed. 4. `GET /api/v1/exec/scripts/list` — verify. ### 2. Pin deps, iterate 1. `POST /api/v1/exec/dependencies/check` → `POST /api/v1/exec/dependencies/install` → `POST /api/v1/exec/package/pin`. 2. `POST /api/v1/exec/validate/script` + `POST /api/v1/exec/validate/magic-comments` (`// @description`, `// @cors`, `// @timeout`). 3. `POST /api/v1/exec/scripts/write` (auto-validates unless `validate:false`). 4. `POST /api/v1/exec/cache/clear` — drop cached worker VMs, selected by `hostname` (optionally with `execId`) or `clearAll:true`; a call with neither is a 400. The `shared` state survives unless you also pass `clearState:true`. ### 3. Debug + OpenAPI 1. `GET /api/v1/exec/logs/list` / `POST /api/v1/exec/logs/search` / `POST /api/v1/exec/logs/read` (one JSON response; `lines` and `tail` pick the slice). For a live tail use `GET /api/v1/exec/logs/stream` (SSE). 2. `GET /api/v1/exec/monitor/active-requests` / `GET /api/v1/exec/monitor/stats`; per script, `GET /api/v1/exec/monitor/scripts` first, then `POST /api/v1/exec/monitor/script-performance` with one `scriptPath` from that listing (an empty body returns an empty `metrics` stub). 3. `GET /api/v1/exec/user-openapi/list`, then `POST /api/v1/exec/user-openapi/generate` / `GET /api/v1/exec/user-openapi/spec` (a document built from the current scripts) or `POST /api/v1/exec/user-openapi/merge`. Merge scans scripts only for the `directories` you name (`['scripts']` for the calling deployment's scripts directory — the `/` the kit URL names, unless you pass `subdomain` / `execId`) and otherwise merges just the `specs` you pass; it answers `{success, data}` with the document in `data`. None of the three writes anything to disk, so store a merge result yourself if you need to keep it. `POST /api/v1/exec/user-openapi/validate` checks one script's `.openapi.json` sidecar. ## Quirks & gotchas - **Direct execution / top-level `return` is the canonical script shape**; `req`, `res`, `metadata`, `shared`, `console`, and `require` are auto-injected. `module.exports = handler` and many `export default` forms are accepted as compatibility inputs. A script may instead export one function per HTTP method (`export async function GET(request)`, `POST`, …; the first argument is a Web `Request`): `HEAD` falls back to `GET`, `OPTIONS` is answered automatically, and any other method without an export answers 405 with `Allow`. The pattern-normaliser never rewrites the stored file; it rewrites the code at load time on every request, independent of `validate`. - **Reads redact secrets.** `GET /api/v1/exec/scripts/read` replaces the values of `// @token` and `// @ai-key` lines with `[REDACTED]`. Writing that content back keeps the stored secret for each placeholder; a placeholder with no stored secret to restore is refused. - **`req.rawBody` holds the request bytes as received** (a Buffer), next to the parsed `req.body`, whenever the kit parses the body for you. Verify webhook signatures against `req.rawBody`; re-serialising `req.body` does not reproduce the sender's bytes. A script that declares `// @rawBody` gets neither field: `req` stays the raw request stream, so read and hash that stream yourself. The line must be exactly `// @rawBody` (or `// @rawBody true` / `false`): with any other text after it the line is ignored and the body is parsed. `GET` and `HEAD` bodies are never read. - Prefer top-level code with auto-injected `req`/`res` (or just `return …` from the script body); use `module.exports = handler` only as a compatibility style. - `DELETE /api/v1/exec/scripts/delete` needs literal `confirm=true`. - `POST /api/v1/exec/scripts/write` defaults `createDirs:true`, `validate:true`. `.md`/`.yaml`/`.env`/any other non-`.ts`/`.js`/`.json` extension skip; `.json` JSON.parse; only `.ts`/`.js` full pipeline. - Invocation = bare path (`POST /greeting`), NOT `/api/v1/exec/...`. - Proxy-alias uses `program: 'exec'`; `GET /api/v1/containers/{id}/proxy/services` returning `[]` is normal (it lists only services named in proxy permission rules or hooks). - `POST /api/v1/exec/schedules/trigger` and `GET /api/v1/exec/schedules/history` scope a relative `scriptPath` by the kit URL you call, like `POST /api/v1/exec/scripts/write`: through the `exec-1` kit URL, `tick.js` means `default/1/tick.js` (the `scriptRel` of `GET /api/v1/exec/schedules/list`), and a path that already starts with `default/1/` is kept as is. An absolute `scriptPath` is used as given (history converts it to the root-relative form); a script at the scripts root, outside any deployment folder, is reachable from a deployment URL only by its absolute path. - `POST /api/v1/exec/scripts/write`/`delete` accept optional `execId` (alias `exec_id`) + `subdomain`; query wins. - `PUT /api/v1/exec/magic-comments/update` and `GET /api/v1/exec/magic-comments/read` resolve `path` like `POST /api/v1/exec/scripts/write`: through the `exec-1` kit URL, `tick.js` is looked up as `default/1/tick.js` first (the `execId` / `subdomain` parameters pick another deployment), then as given relative to the scripts root, so the root-relative `default/1/tick.js` (the write's `resolvedPath`, or its `path` in `GET /api/v1/exec/scripts/list`) also works; the first that exists is used, and none answers 404 `Script not found`. - `POST /api/v1/exec/magic-comments/bulk-update` with neither `directory` nor `execId` edits the calling deployment's own tree (`default/1` through `exec-1`); a `directory` resolves like a script path (under the calling deployment's tree first, then relative to the scripts root). - `PUT /api/v1/exec/magic-comments/update` sets `// @schedule` (`comments.schedule`; an empty string removes it). The value is a 5-field cron expression (`minute hour day month weekday`) or a nickname (`@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`), always in UTC, one per file. `// @schedule-timeout ` is the time limit of one scheduled run (the run is released, not stopped), as `@timeout` is for HTTP, where an unstarted response gets 504 and the script keeps running; HTTP requests keep `@timeout` (a scheduled run without it uses `@timeout`, else 30 s). It is registered at once, as by a write whose header has the line (no `POST /api/v1/exec/schedules/reload`); `GET /api/v1/exec/schedules/list` shows its `nextFire`. - A `@schedule` fire bypasses the script's `@token`, and a script that also declares `@websocket` is not registered (`GET /api/v1/exec/schedules/history` records it as `incompatible`). The `curl` kit's schedules take 6 fields (seconds first); the `cron` namespace takes 5, in the container's own crontab. - **Built-in AI, zero setup — never wire up your own provider/key for AI in a script.** Every endpoint gets these script-scoped bindings, enabled by default (off with `// @ai false`; not on `globalThis`; `pre.js` / `post.js` get none): `ai` (`ai.generate(prompt)` / `ai.stream(prompt)` / `ai.object({ schema, prompt })`), plus `openai` (provider factory), `model` (the default model instance), and `generateText`/`streamText`/`generateObject`. They are already wired to **Hoody AI** (`https://ai.hoody.com/api/v1` unless the kit runs with another `--ai-url`; default model **`hoody-ai/hoody-free`** unless `--ai-default-model` changes it). **No `require()`, no base URL, and no API key**: the key defaults to `container-`, and `// @ai-key` replaces it. Exec does not price, meter or refuse models; what a model costs and what happens without wallet credit is decided by the AI service. Override per-script with magic comments (`// @ai-model `, `// @ai-temperature 0.7`, `// @ai-max-tokens 2048`, `// @ai-key `); set a default system prompt via a sibling `