> _**CLI skill (FULL: basic + all 21 namespaces)** · ~214,206 tokens · hoody-sdk v1.0.0-beta.17_ # CLI mode — `hoody` command **Online? Use HTTP, not this CLI** (`SKILL-HTTP.md`): in a web chat (ChatGPT, claude.ai, …) or a throwaway sandbox that is not a Hoody container or the user's own computer, `hoody` is not installed, a login made there does not last, and it is not the user's machine. Check `command -v hoody`; if it is missing, use HTTP rather than installing it. Covers a mapped subset of the SDK / HTTP surface (somewhat fewer CLI operations than SDK methods) — not a 1:1 mirror. Command names sometimes differ from SDK accessors (e.g. `hoody files get` for the SDK's `files.get`), a few kits carry commands of their own shape (`pipe`, `tunnel`), and SDK-only helpers (`listAll` / `listIterator`) have no CLI form. For the exact command for a given operation, consult the `SKILL-CLI/.md` per-namespace pages. ## 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/PUT?** Use `curl` — `hoody curl run --url --method POST [...]` drives the curl kit; over HTTP the kit can turn any REST call into a single GET-able link for browser-only callers, restricted webhooks, agents with web-fetch-only access (the CLI and SDK send the POST form). 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 CLI Agents that need a single-binary surface: `-o table|json` dense; pipe `jq`; streams via `-o ndjson`. ## Getting a `hoody` CLI ### Already installed? ```bash hoody --version # if this works, skip to "Login" ``` ### Zero-install — public SSH bridge `ssh hoody.com` opens an in-memory shell with the CLI already on `$PATH` — nothing to install, runs anywhere `ssh` works (CI, locked-down boxes, etc.). Two modes: ```bash ssh hoody.com # interactive — prompts for username + password ssh @hoody.com # scripted — token-as-username, no prompt ``` Inside the SSH session: `hoody --help`, `hoody login`, `hoody projects list`, etc. — exactly the same binary as a local install. Sessions are RAM-only (no disk record); short-lived connection metadata is kept solely for anti-DDoS. ### One-shot run via npx (no install) ```bash npx hoody-sdk # also: bunx, pnpm dlx, yarn dlx ``` ### Install — Linux / macOS ```bash curl -fsSL https://install.hoody.com | sh ``` ### Install — Windows (PowerShell) ```powershell iwr https://install.hoody.com/install.ps1 -UseB | iex ``` ### Other install paths - `https://cli.hoody.com/` — landing with all install variants + source build. - `https://install.hoody.com/` — pre-signed binaries (Linux/macOS/Windows, x64/arm64). - `https://sdk.hoody.com/` — TypeScript/JS SDK, when you'd rather script than CLI. After install: `hoody update` reports whether a newer release exists. With a configured update domain the manifest is minisign-verified; with none (the npm and install-script default) the version comes from npm/GitHub and no signature is checked. ## Login ```bash hoody login --web --no-browser # browser sign-in: prints a link + code for the user, polls, saves the session ``` Browser sign-in is the default when a person is present: give the user the printed link and code; they sign in and approve on Hoody's page, and the CLI saves the session. If your shell tool shows output only after a command exits, run it in the background and read the link from its output. Never ask for the user's password in chat. The password flags below are for a user who signs in from their own terminal: ```bash hoody login --username alex --password "$HOODY_PASSWORD" ``` - `--username` (`-u`) is the primary login flag; the CLI accepts `--email` as an alternative for email-based login. The server enforces the alphanumeric/underscore/hyphen pattern, so a malformed value fails at the request. - `--password` takes an optional value: a bare `-p` prompts for it securely. In a terminal, `hoody login` with no flags opens a menu (password, browser, or token). Without a terminal (a script, `-o json`, `--non-interactive`) it needs an identifier AND a password, supplied through flags, `--password-stdin` or environment variables: a missing identifier comes from `HOODY_USERNAME`/`HOODY_USER` (a value containing `@` is sent as `email`), a missing password from `HOODY_PASSWORD`/`HOODY_PASS`. Without both it stops with `Missing credentials.`. Token cached at `~/.hoody/config.json`. - Base URL: the CLI targets `https://api.hoody.com` by default. Override it with `--base-url ` (CLI flag is kebab-case), the `HOODY_BASE_URL` environment variable, or `hoody config set baseUrl ` (config key is camelCase); `hoody config get --resolved` prints the effective settings. ## Config and profiles `hoody config set|get ` writes `~/.hoody/config.json`. `--profile ` switches account; each has own token, base-url, default container. ## Auth modes Priority: `--token`/`-t` > `HOODY_TOKEN` > stored session. Kit-service routing uses the per-container capability URL. ## Container scope — `--container`/`-c` (REQUIRED for kit commands) Every command that targets a container kit (`hoody browser|code|cron|curl|daemon|display|exec|files|notes|notifications|pipe|db|kv|terminal|tunnel|watch …`; `db` (short form `sql`) is the sqlite kit's SQL group, and `kv` is its key-value group; `logs` is a kit URL slug only and has no CLI command group; tail logs via `proxy logs` / `exec logs` / `daemon programs logs`) needs a container id. (`hoody agent` IS a kit command group whose *bare* form opens the in-container Agent TUI; `hoody agent prompt …` and the generated `agent sessions|models|…` subcommands live under it.) Resolution order: 1. `--container ` / `-c ` (global flag, before the subcommand) 2. `HOODY_CONTAINER` env var 3. Per-profile sticky default via `hoody local defaults set container ` (recommended; `local defaults` covers the curated user-facing keys `container`/`realm`/`output`/`noColor`/`quiet`). `hoody config set container ` writes the same setting. A container id is the 24-hex id from `hoody containers list` (the CLI rejects anything else). ```bash CONTAINER_ID=$(hoody containers list -o json | jq -r '.containers[0].id') hoody --container "$CONTAINER_ID" files get /home/user # inline HOODY_CONTAINER="$CONTAINER_ID" hoody files get /home/user # env hoody local defaults set container "$CONTAINER_ID" # sticky; then plain `hoody files get /home/user` ``` Account-level commands (`hoody login`, `hoody projects`, `hoody wallet`, `hoody auth`, `hoody vault`, `hoody containers list`, etc.) hit the control-plane API and ignore `--container`. Control-plane commands that act on ONE container read it from `--container` and require it, e.g. `hoody containers env …`, `hoody snapshots …`, `hoody firewall …`, `hoody network …`, `hoody storage …`. Check `--help` for a `Requires: --container` line. ## Output formats `--output`/`-o`. Default `table` (requests), `ndjson` (streams). | Fmt | For | |---|---| |`table`|default| |`json`|`jq`| |`yaml`|structured| |`wide`|extra cols| |`raw`|unwrapped body| |`ndjson`|streams (auto SSE)| |`pretty`|stream variant| ## Convenience aliases - `chat`, `login`, `signup`, `logout`, `config`, `local`, `update` - `shell` (the one-shot command is positional: `hoody shell -- uname -a`; there is no `--command` flag) - `open` (kit UI); `screenshot` (kit capture); `desktop open`; `kits list` ## Index of common ops § Core operations covers: login/2FA, projects, containers, exec, files, screenshots, sqlite, watch, snapshots, vault, wallet. Per-namespace deep dives: `SKILL-CLI/.md`. URL routing → § Proxy URLs. Auth → § Auth model. --- # 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 hoody proxy aliases create --container-id "$C" --program code --index 1 --alias agent \ --target-path '/?extension=saoudrizwan.claude-dev&folder=/home/user/myrepo' ``` Gate the alias with `hoody containers proxy *` before sharing it (see the `api` namespace). The same iframe pattern works for **every** Hoody kit (`files`, `terminal`, `display`, `desktop`, `browser`, `notes`, `agent`, …). ## Reference ### `hoody code` (8) — VS Code server | Command | Aliases | Category | Summary | SDK Link | Example | |---------|---------|----------|---------|----------|---------| | `hoody code embed` | | read | Build an iframeable URL for a VS Code extension (extension-only mode) | `embeds.code.extension` | `hoody code embed rooveterinaryinc.roo-cline --folder /home/user/project` | | `hoody code extensions install` | | write | Stage a VS Code extension (.vsix) from a URL; it is installed at the instance's next start | `code.extensions.install` | `hoody code extensions install --url https://example.com/publisher.name-1.2.3.vsix --allow-downgrade` | | `hoody code extensions list` | | read | List staged extensions and the extensions the instance reports as installed | `code.extensions.list` | `hoody code extensions list` | | `hoody code health` | | read | Service health check | `code.kit.getHealth` | `hoody code health` | | `hoody code open` | | action | Open the Code kit editor on a folder in your browser | | `hoody code open --folder /home/user/project` | | `hoody code status` | | read | Orchestrator configuration and running editor instances | `code.kit.getStatus` | `hoody code status` | | `hoody code stop` | | action | Stop an editor instance; its settings, extensions and workspace state are kept | `code.stop` | `hoody code stop 1` | | `hoody code version` | | read | Versions of the running orchestrator and its packaged editor | `code.kit.getVersion` | `hoody code version` | --- # `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-CLI.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 `hoody cron entries create` takes a schedule + command (plus name/comment/expires_at/enabled) and returns the created entry with its `id`. ### 2. List `hoody cron entries list` (`page`/`limit`, max 200). ### 3. Edit / disable / extend `hoody cron entries update` 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 `hoody cron crontabs get` (sweep), edit the returned text, then call `hoody cron crontabs set` 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 `hoody cron crontabs set` 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 `hoody cron crontabs list` → 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 `hoody cron crontabs set` 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. - **`hoody cron crontabs set` replaces the whole crontab.** `hoody cron crontabs get` 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 `hoody cron crontabs get` 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. - `hoody cron entries list`/`hoody cron entries get` clean expired entries before serializing under a per-user mutex — a GET can mutate the spool. - `hoody cron entries list` 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 `hoody cron crontabs set` (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 `hoody containers get` 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 ID=$(hoody --container "$C" cron entries create root \ --schedule '0 2 * * *' \ --command 'pg_dump -U postgres mydb | gzip > /backups/db-$(date +%F).sql.gz' \ --name nightly-db-backup \ --expires-at "$(date -u -d '+1 year' +%FT%TZ)" \ -o json | jq -r '.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 hoody --container "$C" cron entries update root "$ID" \ --schedule '* * * * *' --comment 'TEST MODE — revert before merge' ``` **Step 3 — promote back to nightly** with a clean comment. ```bash hoody --container "$C" cron entries update root "$ID" \ --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 # One call fetches every page. body=$(hoody --container "$C" cron entries list root -o json) \ || { echo "listing failed" >&2; exit 1; } [ "$(jq '.entries | length' <<<"$body")" -eq "$(jq .total <<<"$body")" ] || { echo "listing incomplete" >&2; exit 1; } IDS=$(jq -r '.entries[] | select(.type=="managed" and .enabled) | .id' <<<"$body") \ || { echo "unreadable listing" >&2; exit 1; } ``` **Step 2 — bulk disable.** ```bash # --no-enabled sends {"enabled":false}; --enabled sends true. for id in $IDS; do hoody --container "$C" cron entries update root "$id" --no-enabled >/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`, that is `--enabled`). 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.** `hoody cron entries list` returns hand-written lines as `{ type: 'raw', line }` items; managed entries are `type: 'managed'` and are left alone. ```bash # Raw items only; skip blanks, comments and environment lines (SHELL=, MAILTO = ..., "A B" = c). body=$(hoody --container "$C" cron entries list root -o json) || exit 1 # every page jq -r '.entries[] | select(.type=="raw") | .line' <<<"$body" \ | grep -Ev "^[[:space:]]*(\$|#|([A-Za-z_][A-Za-z0-9_]*|\"[^\"]*\"|'[^']*')[[:space:]]*=)" > /tmp/cron-migrate.txt 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}//") hoody --container "$C" cron entries create root \ --schedule "$SCHED" --command "$CMD" --name "migrated-$i" >/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=$(hoody --container "$C" cron crontabs get root -o json) || 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 -) hoody --container "$C" cron crontabs set root --crontab "$NEW" ``` ### 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 body=$(hoody --container "$C" cron entries list root -o json) || exit 1 # every page [ "$(jq '.entries | length' <<<"$body")" -eq "$(jq .total <<<"$body")" ] || { echo "listing incomplete" >&2; exit 1; } ID=$(jq -r '.entries[] | select(.type=="managed" and .name=="health-poll") | .id' <<<"$body") 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 hoody --container "$C" cron entries update root "$ID" --schedule '*/5 * * * *' ``` **Step 3 — restore** to hourly once the investigation is over: the same call with `--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 ID=$(hoody --container "$C" cron entries create root \ --schedule @daily --command /opt/metrics/sample.sh \ --name metrics-experiment --expires-at "$(date -u -d '+30 days' +%FT%TZ)" \ -o json | jq -r .id) ``` After the timestamp passes, the kit's 60 s sweep **deletes** expired managed entries. `hoody cron entries list`/`hoody cron entries get` 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 `hoody cron crontabs set` 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 hoody --container "$C" cron entries update root "$ID" \ --expires-at "$(date -u -d '+60 days' +%FT%TZ)" ``` **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 hoody --container "$C" cron entries update root "$ID" --clear-expiration ``` ### 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 body=$(hoody --container "$C" cron entries list root -o json) || exit 1 # every page [ "$(jq '.entries | length' <<<"$body")" -eq "$(jq .total <<<"$body")" ] || { echo "listing incomplete" >&2; exit 1; } ENTRY_ID=$(jq -r '.entries[] | select(.type=="managed" and .name=="noisy-job") | .id' <<<"$body") 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 hoody --container "$C" cron entries update root "$ENTRY_ID" \ --no-enabled --comment "disabled $(date -u +%FT%TZ) — investigating" ``` **Step 3 — re-enable later** by calling the same update with `enabled: true`, that is `--enabled`. ### 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. `hoody cron crontabs list` 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 body=$(hoody --container "$C" cron crontabs list -o json) || exit 1 # every page jq '.items[] | select(.crontab | test("\\S")) | {user, crontab}' <<<"$body" ``` For each non-empty user, drill in via `hoody cron entries list` 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 hoody --container "$C" cron crontabs get root -o json > /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 hoody --container "$C" cron crontabs set root \ --crontab "$(cat /etc/iac/canonical-crontab.txt)" ``` ### 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 hoody --container "$C" cron entries update root "$ID" \ --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 # Check the read and the parse separately: a failed read must never become an empty PUT. BODY=$(hoody --container "$C" cron crontabs get root -o json) || 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') hoody --container "$C" cron crontabs set root --crontab "$NEW" ``` ## Reference ### `hoody cron` (10) — Cron scheduling | Command | Aliases | Category | Summary | SDK Link | Example | |---------|---------|----------|---------|----------|---------| | `hoody cron crontabs get` | | read | get crontab | `cron.crontabs.get` | `hoody cron crontabs get alice` | | `hoody cron crontabs list` | | read | list all crontabs | `cron.crontabs.list` | `hoody cron crontabs list --page 10 --limit 10` | | `hoody cron crontabs set` | | write | put crontab | `cron.crontabs.set` | `hoody cron crontabs set alice --crontab ` | | `hoody cron entries create` | | write | create entry | `cron.entries.create` | `hoody cron entries create alice --command 'ls -la' --comment Hello --enabled --schedule '0 * * * *'` | | `hoody cron entries delete` | | destructive | delete entry | `cron.entries.delete` | `hoody cron entries delete alice 3fa85f64-5717-4562-b3fc-2c963f66afa6 -y` | | `hoody cron entries get` | | read | get entry | `cron.entries.get` | `hoody cron entries get alice 3fa85f64-5717-4562-b3fc-2c963f66afa6` | | `hoody cron entries list` | | read | list entries | `cron.entries.list` | `hoody cron entries list alice --page 10 --limit 10` | | `hoody cron entries update` | | write | update entry | `cron.entries.update` | `hoody cron entries update alice 3fa85f64-5717-4562-b3fc-2c963f66afa6 --clear-expiration --command 'ls -la'` | | `hoody cron health` | | read | health check | `cron.kit.getHealth` | `hoody cron health` | | `hoody cron open` | | action | Open the Cron kit job manager in your browser | | `hoody cron open` | --- # `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. - `hoody curl schedules *` 404s if disabled. ## Capability URL → See `SKILL-CLI.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 `hoody proxy aliases create --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`. `hoody curl run` **executes** the request and prints the response (a text body as-is, a JSON body pretty-printed; with `--response json` that is the `{status_code, headers, body}` envelope); it does NOT just compose a URL string. The CLI has no command for the GET route: `curl run` sends the POST form. 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 `hoody curl run` with `mode:"sync"` (default), `response:"json"` (envelope) or `"transparent"` (raw). ### 3. Async job 1. `hoody curl run` with `mode:"async"` → `job_id`. 2. Poll `hoody curl jobs get` or subscribe `hoody curl jobs stream` (SSE) filtered by `job_id` (`hoody curl jobs stream --job-id `; the CLI has no WebSocket form). 3. `hoody curl jobs result get`; `hoody curl jobs cancel` aborts. `hoody curl jobs get` reports `retry_attempts`: 1 for a job that ran once, plus one per retry after a transfer error. ### 4. Cookie-jar session 1. `hoody curl run` with `session_id:""` auto-creates jar. 2. Reuse same `session_id` on follow-ups. 3. `hoody curl sessions cookies list` / `hoody curl sessions delete`. ### 5. Save download 1. `hoody curl run` with `save:true` and optional relative `save_path` under `downloads/by-job/{job_id}/`. 2. `hoody curl storage list`/`hoody curl storage get`/`hoody curl storage delete` with relative path (e.g. `by-job//x.pdf`). ### 6. Scheduled request 1. `hoody curl schedules create` with `{cron,request}` → `schedule_id`. Add `enabled: false` to create it paused: it never fires until `hoody curl schedules update` sets `enabled: true`. 2. `hoody curl schedules list`/`hoody curl schedules get`/`hoody curl schedules update` (`{"enabled":bool}` pauses or resumes)/`hoody curl schedules delete`. 3. Each admitted occurrence creates a job; inspect via `hoody curl jobs list`. 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. - **Save downloads with `--out-file`.** With `--out-file `, `curl storage get`, `curl jobs result get` and `curl run` save the body byte for byte. Without it, `curl storage get` always streams the raw bytes to stdout, while `curl run` and `curl jobs result get` parse a JSON body and print it like any other output, and stream only a binary body. A terminal refuses streamed binary output (`--out-file -` prints it anyway). For a streamed body, `-o json` prints `{ saved_to, bytes, content_type }` with `--out-file` and is refused without it. - **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. `hoody curl storage list` returns one item per path; the bytes are the same file. - `*.list` returns ALL when `limit` omitted; always pass `limit`. - `hoody curl schedules *` 404s if disabled. - `hoody curl schedules update` 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. - `hoody curl schedules create` 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` wins: the token is then not sent, so the request carries one `Authorization` header. - `hoody curl jobs result get` 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 `hoody curl jobs get`). 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 (`hoody curl jobs result get` 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 `hoody curl jobs get` for `status: "cancelled"`, and stop waiting once a job is `failed` or `cancelled`. `hoody curl jobs result get` 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 `hoody containers get` 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 # `hoody curl run` fires the request (it does not print a clickable URL). `--header NAME=VALUE` # sets a request header and repeats once per header (the value may itself contain `=`); # --json already sets Content-Type, and --bearer-token adds the Authorization header. # --json takes an object or array only from a file (@path), never inline. printf '%s' '{"event":"X"}' > event.json hoody --container "$C" curl run \ --url 'https://my-api/events' --method POST \ --json @event.json \ --header 'X-Request-Id=evt-1' \ --bearer-token "$API_TOKEN" ``` **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 hoody proxy aliases create --container-id "$C" --alias webhook-bridge \ --program curl --target-path /api/v1/curl/request --allow-path-override ``` ### 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 SID="oauth-$(date +%s)" TOKEN=$(hoody --container "$C" curl run \ --url https://api.example.com/csrf --method GET --response json \ --session-id "$SID" -o json | jq -r '.body | fromjson | .csrf_token') # --response json is REQUIRED for a .body envelope ``` **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 # --form NAME=VALUE repeats once per field and sends the body's `form` map; --session-id keeps the cookie jar. hoody --container "$C" curl run \ --url 'https://api.example.com/login' --method POST \ --form username=alex --form password=secret --form csrf="$TOKEN" \ --session-id "$SID" ``` **Step 3 — authorized call.** Stored cookie is auto-attached. ```bash hoody --container "$C" curl run --url https://api.example.com/me \ --method GET --response json --session-id "$SID" -o json | jq -r .body hoody --container "$C" curl sessions cookies list "$SID" hoody --container "$C" curl sessions delete "$SID" -y ``` ### 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 JOBS=() for URL in https://httpbin.org/delay/1 https://httpbin.org/delay/2 https://httpbin.org/get; do JID=$(hoody --container "$C" curl run --url "$URL" --method GET --mode async -o json | jq -r .job_id) JOBS+=("$JID") done ``` **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=$(timeout 10 hoody --container "$C" curl jobs get "$JID" -o json) || { 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.** `hoody curl jobs result get` returns just the upstream body, always with status 200; the upstream's status is in `X-Curl-Status`. ```bash # --out-file saves each body as received: JSON, text or binary. for JID in "${JOBS[@]}"; do hoody --container "$C" curl jobs result get "$JID" --out-file "/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 JID=$(hoody --container "$C" curl run --url https://httpbin.org/delay/30 \ --method GET --mode async --timeout 60 -o json | jq -r .job_id) sleep 1 hoody --container "$C" curl jobs cancel "$JID" sleep 1 hoody --container "$C" curl jobs get "$JID" -o json | 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 SID=$(hoody --container "$C" curl schedules create \ --cron '0 */15 * * * *' \ --request-url 'https://prod.example.com/health' \ --request-method GET \ --request-job-name prod-health \ -o json | jq -r .schedule_id) ``` **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 `hoody curl jobs get`; the listing does not carry it). ```bash hoody --container "$C" curl jobs list --limit 200 -o json \ | 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=$(hoody --container "$C" curl jobs get "$JID" -o json | 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 hoody --container "$C" curl schedules update "$SID" --no-enabled # Resume: update "$SID" --enabled. Drop entirely: hoody --container "$C" curl schedules delete "$SID" -y ``` ### 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 JID=$(hoody --container "$C" curl run --url https://example.com/big.iso \ --method GET --mode async --save --save-path iso/ubuntu.iso --timeout 600 \ -o json | 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=$(timeout 10 hoody --container "$C" curl jobs get "$JID" -o json | 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 hoody --container "$C" curl storage list --limit 10 ``` **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 hoody --container "$C" curl storage get "by-job/$JID/iso/ubuntu.iso" --out-file /tmp/ubuntu.iso hoody --container "$C" curl storage delete "by-job/$JID/iso/ubuntu.iso" -y ``` ### 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 hoody --container "$C" curl run --url https://api.github.com/user --method GET \ --bearer-token ghp_xxxxxxxxxxxx --response json -o json \ | jq '{status_code, headers, 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 hoody proxy aliases create --container-id "$C" --alias rebuild-main --no-allow-path-override \ --program curl --target-path '/api/v1/curl/request?url=https://ci.example.com/build&method=POST&data_base64=&header=Content-Type:application/json&bearer_token=XYZ' ``` **Step 3 — gate it** — only your office IPs can fire it (uses `hoody containers proxy groups ip set`; 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 CUTOFF=$(( $(date +%s) - 18 * 3600 )) body=$(hoody --container "$C" curl jobs list -o json) || exit 1 # every page [ "$(jq '.items | length' <<<"$body")" -eq "$(jq .meta.total <<<"$body")" ] || { echo "listing incomplete" >&2; exit 1; } # One " " line per completed prod-health run. 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 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.** `hoody curl jobs result get` returns just the upstream body; `hoody curl jobs get` returns the full record (timing, headers, original request). ```bash hoody --container "$C" curl jobs result get "$JID" hoody --container "$C" curl jobs get "$JID" ``` ### 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 CUTOFF=$(date -u -d '30 days ago' +%Y-%m-%d) body=$(hoody --container "$C" curl storage list -o json) || exit 1 # every page [ "$(jq '.items | length' <<<"$body")" -eq "$(jq .meta.total <<<"$body")" ] || { echo "listing incomplete" >&2; exit 1; } jq -r --arg c "$CUTOFF" '.items[] | select(.path | startswith("by-date/")) | select((.path | split("/")[1]) < $c) | .path' \ <<<"$body" > /tmp/curl-purge.txt || exit 1 while IFS= read -r P; do hoody --container "$C" curl storage delete "$P" -y done < /tmp/curl-purge.txt ``` ## Reference ### `hoody curl` (21) — cURL jobs and schedules | Command | Aliases | Category | Summary | SDK Link | Example | |---------|---------|----------|---------|----------|---------| | `hoody curl health` | | read | Service health check | `curl.kit.getHealth` | `hoody curl health` | | `hoody curl jobs cancel` | | destructive | Cancel a pending or running job; the record stays | `curl.jobs.cancel` | `hoody curl jobs cancel 550e8400-e29b-41d4-a716-446655440000` | | `hoody curl jobs delete` | | destructive | Permanently delete a finished job's record and its saved downloads (a running job must be cancelled first) | `curl.jobs.delete` | `hoody curl jobs delete 550e8400-e29b-41d4-a716-446655440000` | | `hoody curl jobs get` | | read | Get detailed job information | `curl.jobs.get` | `hoody curl jobs get 550e8400-e29b-41d4-a716-446655440000` | | `hoody curl jobs list` | | read | List all async jobs | `curl.jobs.list` | `hoody curl jobs list --page 1 --limit 50` | | `hoody curl jobs result get` | | read | Get job response body | `curl.jobs.getResult` | `hoody curl jobs result get 550e8400-e29b-41d4-a716-446655440000` | | `hoody curl jobs stream` | | read | Stream job lifecycle events live | `curl.jobs.stream` | `hoody curl jobs stream --job-id 550e8400-e29b-41d4-a716-446655440000 --since 0` | | `hoody curl metrics` | | read | Prometheus metrics | `curl.kit.getMetrics` | `hoody curl metrics` | | `hoody curl run` | | action | Execute HTTP request with full cURL capabilities | `curl.run` | `hoody curl run --compressed --connect-timeout 10 --url https://example.com` | | `hoody curl schedules create` | | write | Create a recurring scheduled job | `curl.schedules.create` | `hoody curl schedules create --cron '0 0 * * * *' --enabled --request-compressed --request-url https://example.com` | | `hoody curl schedules delete` | | destructive | Delete a schedule | `curl.schedules.delete` | `hoody curl schedules delete 770e8400-e29b-41d4-a716-446655440000 -y` | | `hoody curl schedules get` | | read | Get schedule details | `curl.schedules.get` | `hoody curl schedules get 770e8400-e29b-41d4-a716-446655440000` | | `hoody curl schedules list` | | read | List all scheduled jobs | `curl.schedules.list` | `hoody curl schedules list --page 1 --limit 50` | | `hoody curl schedules update` | | write | Change a schedule's cron expression, enabled state or request. Omitted fields keep their stored value; passing any request flag, such as --request-url, replaces the whole stored request | `curl.schedules.update` | `hoody curl schedules update 770e8400-e29b-41d4-a716-446655440000 --cron '0 */5 * * * *' --enabled` | | `hoody curl sessions cookies list` | | read | Get session cookies only | `curl.sessions.listCookies` | `hoody curl sessions cookies list user-session-123` | | `hoody curl sessions delete` | | destructive | Delete a session | `curl.sessions.delete` | `hoody curl sessions delete user-session-123 -y` | | `hoody curl sessions get` | | read | Get session details | `curl.sessions.get` | `hoody curl sessions get user-session-123` | | `hoody curl sessions list` | | read | List all cookie sessions | `curl.sessions.list` | `hoody curl sessions list --page 1 --limit 50` | | `hoody curl storage delete` | | destructive | Delete a saved file | `curl.storage.delete` | `hoody curl storage delete by-job/550e8400-e29b-41d4-a716-446655440000/report.pdf --recursive -y` | | `hoody curl storage get` | | read | Download a saved file | `curl.storage.get` | `hoody curl storage get by-job/550e8400-e29b-41d4-a716-446655440000/report.pdf` | | `hoody curl storage list` | | read | List all saved downloads | `curl.storage.list` | `hoody curl storage list --page 1 --limit 50` | --- # `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 `hoody daemon ephemeral programs logs get` 404s (see Quirks); read the logs within those 10 minutes, or read the on-disk files directly (e.g. via the `files` namespace). `hoody daemon programs logs get` covers configured (non-ephemeral) programs. Two flavours: - **Quick-start (ephemeral, not added to the program list)** — `hoody daemon ephemeral programs start --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 `hoody daemon ephemeral programs logs get` 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)** — `hoody daemon programs create --name --command --user --enabled [--boot] --autorestart unexpected ...` → `hoody daemon programs start `, then poll `hoody daemon programs status`. 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" → `hoody daemon ephemeral programs start`. - "Run this server / agent / script as a long-running supervised process, restart on failure" → `hoody daemon programs create` + `hoody daemon programs 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 → `hoody daemon programs attach ` (Ctrl-] detaches and leaves the program running; `--readonly` watches only). 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` (`hoody terminal sessions press`, `hoody terminal sessions 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) — `hoody daemon programs create` 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-CLI.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 - `hoody daemon programs create` (`name`/`command`/`user`; `enabled`, `boot`; opt `directory`/`environment`/`autorestart`/`priority`/`*_logfile`) -> `hoody daemon programs start `, then poll `hoody daemon programs status` (`include_stats`) until `status.status` is `running` (`wait: true` blocks the request and easily exceeds 30 s on a cold kit; see Example 1); `hoody daemon programs logs get` on failure. ### 2. Ephemeral with TTL - `hoody daemon ephemeral programs start` (`command`/`user`, opt `ttl?`/`wait?`/`timeout?`) returns `temporary_id` = `quick__`. Poll/tail with `hoody daemon ephemeral programs status`/`hoody daemon ephemeral programs logs get`; `hoody daemon ephemeral programs stop` to terminate. ### 3. Lazy port-range fleet - `hoody daemon programs create` + `port_range: { start, end }`, `port_param`, `lazy_load: true`, `enabled: true`. `hoody daemon programs list --port 8042 --include-status`. `hoody daemon programs start --port 8042`; `hoody daemon programs stop --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 `hoody containers proxy *` if it shouldn't be public. See § Proxy URLs. ### 5. Update / wipe `hoody daemon programs update` (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); `hoody daemon programs disable`/`hoody daemon programs enable`; `hoody daemon programs delete`; `hoody 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/`. - `hoody daemon programs start` on `port_range` REQUIRES `{ port }`; `hoody daemon programs stop --port ` or `{ all: true }`. - `hoody daemon ephemeral programs start` returns `temporary_id` = `quick__` (e.g. `quick_1700000000000_1`); pass it unchanged to `hoody daemon ephemeral programs status`, `hoody daemon ephemeral programs logs get` and `hoody daemon ephemeral programs stop` on every surface. TTL polled ~10 s. - A program is addressed by its integer `id` from `hoody daemon programs list`, 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 (`hoody daemon programs list --name -o json`). - 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 `hoody daemon ephemeral programs stop`, the program's result and logs stay readable for 10 minutes; then its tracking entry is dropped and `hoody daemon ephemeral programs logs get` 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 `hoody daemon ephemeral programs logs get` within those 10 minutes, or fetch the on-disk file directly. - `hoody daemon programs 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 `hoody daemon programs status `). Use it for "ensure started" workflows. - **`environment` REPLACES the whole map** on `hoody daemon programs update` (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 `hoody daemon programs update`**: 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 `hoody daemon programs sandbox get ` first (`configured` is the stored block) and resend every restriction you want kept. The CLI does this check for you: a `--sandbox-*` edit that would drop a stored restriction is refused, nothing is sent, and each restriction is listed with the flag that resends it; `--sandbox-replace` sends the edit anyway. - Quick-start programs cannot be sandboxed: a non-null `sandbox` on `hoody daemon ephemeral programs 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 `hoody daemon programs logs get` 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. - `hoody daemon programs sandbox get ` 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 }`; the CLI flags `--port-range-start` and `--port-range-end` build it. ## 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, via `--port`. success=false `Program with ID {id} is disabled` -> `hoody daemon programs 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 `hoody containers get` first. The kit returns numeric `program.id` (not a UUID) — capture it from the `hoody daemon programs create` 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 ID=$(hoody --container "$C" daemon programs create \ --name examples-daemon-tick \ --command 'sh -c '\''while :; do echo tick $(date -u +%%s); sleep 5; done'\''' \ --user user --enabled --boot --autorestart unexpected \ -o json | jq -r '.program.id') ``` **Step 2 — `hoody daemon programs 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 `hoody daemon programs status` instead. ```bash hoody --container "$C" daemon programs start "$ID" while [ "$(hoody --container "$C" daemon programs status "$ID" -o json | 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. `hoody daemon ephemeral programs 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 QID=$(hoody --container "$C" daemon ephemeral programs start \ --name examples-daemon-qs --user user --ttl 600 \ --command 'sh -c "for i in $(seq 1 30); do echo qs-$i; sleep 1; done"' \ -o json | jq -r .temporary_id) ``` **Step 2 — check status.** ```bash hoody --container "$C" daemon ephemeral programs status "$QID" -o json ``` **Step 3 — tail logs.** ```bash hoody --container "$C" daemon ephemeral programs logs get "$QID" --type stdout --lines 10 ``` **Step 4 — stop.** Read the logs within 10 minutes of the stop: after that the tracking entry is dropped and `hoody daemon ephemeral programs logs get` returns 404 (the on-disk log files stay). ```bash hoody --container "$C" daemon ephemeral programs stop "$QID" ``` ### 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 ID=$(hoody --container "$C" daemon programs create \ --name examples-daemon-fanout --command 'sh -c "exec python3 -m http.server ${1##*=}" sh' \ --user user --enabled \ --port-range-start 18800 --port-range-end 18802 \ --port-param=--port --lazy-load \ -o json | jq -r .program.id) ``` **Step 2 — start one specific port and read fleet-wide status.** `hoody daemon programs list --port 18800 --include-status` returns the program with a `status: { type: "port-range", running_instances, total_instances, instances: [{ port, status, … }] }` block. ```bash hoody --container "$C" daemon programs start "$ID" --port 18800 hoody --container "$C" daemon programs list --port 18800 --include-status true -o json \ | 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 (`hoody daemon programs logs get` with type / lines) **Goal:** investigate why a worker keeps restarting. `hoody daemon programs logs get` returns `{ logs, type, lines, log_file }` where `log_file` is the on-disk path under `/hoody/storage/hoody-daemon/logs//{stdout,stderr}.log`. ```bash hoody --container "$C" daemon programs logs get "$ID" --type stderr --lines 200 ``` For a port-range program, select the instance when reading logs: add `--port 18800`. ### 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 # `programs update` needs only the id; every other flag is optional. hoody --container "$C" daemon programs update "$ID" \ --webhooks-enabled \ --webhooks-urls https://hooks.example.com/daemon-events \ --webhooks-events FATAL --webhooks-events BACKOFF \ --webhooks-headers X-Source=hoody-daemon \ --webhooks-timeout 10 --webhooks-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. `hoody daemon programs update` 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 hoody --container "$C" daemon programs list -o json > /tmp/daemon-snapshot.json # CLI list has no --limit hoody --container "$C" daemon programs reset -y ``` ### 7. Patch only the env vars on a running program **Goal:** flip `LOG_LEVEL=debug` without restating `command`/`user`/etc. `hoody daemon programs update` is partial on every surface: fields absent from the request body keep their stored values. `environment` itself is replaced whole (see the note below). > The CLI sends only the flags you pass: `hoody daemon programs update "$ID" --environment LOG_LEVEL=debug` transmits `{"environment":{"LOG_LEVEL":"debug"}}` and nothing else, so no stored field is overwritten by a default. ```bash # environment is replaced whole: pass every variable the program should keep. hoody --container "$C" daemon programs update "$ID" \ --environment LOG_LEVEL=debug --environment BUILD=examples hoody --container "$C" daemon programs stop "$ID" hoody --container "$C" daemon programs start "$ID" ``` ⚠ `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, `hoody daemon programs status ` 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 hoody --container "$C" daemon programs status "$ID" --include-stats true ``` ⚠ `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 hoody --container "$C" daemon programs stop "$ID" --port 18800 ``` **Whole fleet** (`all: true`): ```bash hoody --container "$C" daemon programs stop "$ID" --all ``` ⚠ For a port-range program, `hoody daemon programs 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. `hoody daemon programs disable` flips `enabled: false` (process stays in the listing for forensics); `hoody daemon programs 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 hoody --container "$C" daemon programs disable "$ID" hoody --container "$C" daemon programs enable "$ID" hoody --container "$C" daemon programs start "$ID" --if-not-running ``` ⚠ Trying `hoody daemon programs start` while `enabled: false` returns `success: false` with `Program with ID {id} is disabled` (e.g. `Program with ID 7 is disabled`) — call `hoody daemon programs enable` first. ## Reference ### `hoody daemon` (21) — Daemon and ephemeral programs | Command | Aliases | Category | Summary | SDK Link | Example | |---------|---------|----------|---------|----------|---------| | `hoody daemon ephemeral programs list` | | read | List all ephemeral programs | `daemon.ephemeralPrograms.list` | `hoody daemon ephemeral programs list` | | `hoody daemon ephemeral programs logs get` | | read | Get ephemeral program logs | `daemon.ephemeralPrograms.getLogs` | `hoody daemon ephemeral programs logs get --type stdout --lines 100` | | `hoody daemon ephemeral programs start` | | write | Launch ephemeral CUSTOM program | `daemon.ephemeralPrograms.start` | `hoody daemon ephemeral programs start --command 'python my_batch_job.py' --user worker --directory /opt/app --inject-container-env` | | `hoody daemon ephemeral programs status` | | read | Get ephemeral program status | `daemon.ephemeralPrograms.getStatus` | `hoody daemon ephemeral programs status quick_1731605123456_0` | | `hoody daemon ephemeral programs stop` | | write | Stop ephemeral program | `daemon.ephemeralPrograms.stop` | `hoody daemon ephemeral programs stop quick_1731605123456_0` | | `hoody daemon health` | | read | Service health check | `daemon.kit.getHealth` | `hoody daemon health` | | `hoody daemon programs create` | | write | Add a new CUSTOM program | `daemon.programs.create` | `hoody daemon programs create --id 100 --name my-app --description 'My Node.js application' --command 'node app.js' --user nodejs` | | `hoody daemon programs delete` | | destructive | Remove a program | `daemon.programs.delete` | `hoody daemon programs delete 100 -y` | | `hoody daemon programs disable` | | write | Disable a program | `daemon.programs.disable` | `hoody daemon programs disable 100` | | `hoody daemon programs enable` | | write | Enable a program | `daemon.programs.enable` | `hoody daemon programs enable 100` | | `hoody daemon programs get` | | read | Get a specific program | `daemon.programs.get` | `hoody daemon programs get 100` | | `hoody daemon programs list` | | read | List all programs | `daemon.programs.list` | `hoody daemon programs list --hoody-kit true --lazy-load true` | | `hoody daemon programs logs get` | | read | Get program logs | `daemon.programs.getLogs` | `hoody daemon programs logs get 100 --type stdout --lines 100` | | `hoody daemon programs logs stream` | | read | Follow a program's log live: replays the last --lines lines, then prints every new line. A reconnect resumes after the last line received | `daemon.programs.streamLogs` | `hoody daemon programs logs stream --id 100 --type stdout --port 8080` | | `hoody daemon programs reset` | | destructive | Reset programs to default | `daemon.programs.reset` | `hoody daemon programs reset -y` | | `hoody daemon programs sandbox get` | | read | Show a program's sandbox: the stored block, the policy revision, what it resolves to, and what the firewall is holding | `daemon.programs.getSandbox` | `hoody daemon programs sandbox get 100` | | `hoody daemon programs start` | | write | Start a program or port instance | `daemon.programs.start` | `hoody daemon programs start 100 --port 8042 --wait` | | `hoody daemon programs status` | | read | Get the status of every program (no id) | `daemon.programs.listStatus` | `hoody daemon programs status --port 8080` | | `hoody daemon programs status` | | read | Get the status of one program | `daemon.programs.getStatus` | `hoody daemon programs status --port 8080` | | `hoody daemon programs stop` | | write | Stop a program or port instance | `daemon.programs.stop` | `hoody daemon programs stop 100 --port 8042` | | `hoody daemon programs update` | | write | Edit a program | `daemon.programs.update` | `hoody daemon programs update 100 --name my-app --description 'My Node.js application'` | --- # `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`.) On `hoody terminal sessions create` the flag is `--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-CLI.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. `hoody display screenshots capture` with `base64` on (for vision). One response carries the image (`image.data`) and its metadata (`info.timestamp`, `info.full.width`/`height`). 2. `hoody display input click` / `hoody display input type` 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. `hoody display screenshots capture` again to see the result. There is no cheap change check: `hoody display screenshots capture` 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. `hoody display windows list` (`onlyVisible` on). 2. `hoody display windows search` — a `pattern` plus which fields to match (`name`, `class`, `classname`). Add `-o json` to the list and search commands to get the full response, window ids included. 3. `hoody display windows 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. `hoody display windows raise` is not a substitute for focusing. 4. `hoody display windows geometry get` — coords. 5. `hoody display windows active get` — confirms activation only, not keyboard focus. `hoody display windows list`, `hoody display windows focus` and `hoody display windows active get` 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 `hoody display windows search`, window geometry and name queries, and mouse and keyboard actions, which work without one. ### 3. Drag / select 1. `hoody display mouse move` — optional pre-position. 2. `hoody display input drag` `(sx,sy)`→`(ex,ey)`, optional `steps`. 3. Or `hoody display input select` — click + shift-click. 4. `hoody display input reset` — release stuck buttons. ### 4. Clipboard hand-off 1. `hoody display clipboard set` — `text`, optional `selection`. 2. `hoody display keyboard press` — `["ctrl+v"]` (`["shift+Insert"]` for primary). 3. `hoody display clipboard get` — read back after GUI copy. ### 5. Batch input replay 1. `hoody display input batch act` — an ordered list of actions in one request. It stops at the first failure and still answers 200, so check `success` and `failed`. Add `-o json` to get the full result body. When the body says `success: false`, the command still prints it, then writes `✗ … reported success: false` to stderr and exits 1. 2. `hoody display input wait` — interleave waits. 3. `hoody display screenshots capture` — confirm. ### 6. Press a key or a key combination 1. `hoody display keyboard press` 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 `+`. `hoody display keyboard press --display-id 1 --keys ctrl+l`. 2. To submit typed text, end it with a line break instead: in `hoody display keyboard type` and `hoody display input type`, `\n` presses Return. 3. `hoody display keyboard down` / `hoody display keyboard up` hold and release one key; `hoody 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 `hoody 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. - `hoody display screenshots get` 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 `hoody display input click` 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. - `hoody display input click` and `hoody display input type` 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 `hoody display keyboard type` and `hoody display input type`, 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 `hoody display keyboard press`. - `hoody display input click` 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...`). `hoody display windows list`, `hoody display windows search` and `hoody display windows active get` return decimal numbers; the path-parameter routes (`hoody display windows get`, `hoody display windows geometry get`, `hoody display windows title get`) echo `windowId` exactly as sent, as a string. Compare ids as numbers, not strings.{1,8}$/"] - `hoody display windows 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. `hoody display windows active get` confirms the activation only. - `hoody display get` 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 `hoody display geometry get`). - `hoody display input reset` clears stuck modifiers/buttons. - `hoody display windows wait` 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`. - `hoody display windows 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 `hoody display screenshots get` — no stored capture has that timestamp. Refresh by calling `hoody display screenshots capture`, which **takes a fresh screenshot** (with `base64` on, the response carries its `info.timestamp`), then retry `hoody display screenshots get` with the new timestamp. `hoody display screenshots latest get` returns the latest stored image by default; its metadata-only form (`--metadata`) 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 `hoody containers get` first. The `N` in the `display-N` kit hostname is the display id, so `display-1` addresses display 1; `--display-id 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 hoody --container "$C" display screenshots capture --display-id 1 --base64 -o json > /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)`.** `hoody display input click` moves AND clicks in one call; default `button=1` (left). ```bash hoody --container "$C" display input click --display-id 1 --x 75 --y 50 --button 1 ``` **Step 3 — capture again and give the new image to the vision model.** With `base64` on, `hoody display screenshots capture` returns the fresh image and its metadata. There is no cheaper probe: the metadata-only form (`--metadata`) still takes a full screenshot and only leaves the image bytes out. ```bash hoody --container "$C" display screenshots capture --display-id 1 --base64 -o json | 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 — `hoody display windows 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 WID=$(hoody --container "$C" display windows search --display-id 1 \ --pattern xeyes --name --class --classname -o json \ | jq -er '.windows[0] // error("No window matched xeyes")') || exit 1 ``` **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. `hoody display windows active get` reports the active window, which confirms the activation only. ```bash hoody --container "$C" display windows focus --display-id 1 --window-id "$WID" --sync -o json \ | jq -r .details.inputFocus # true = keyboard input will reach the window hoody --container "$C" display windows active get --display-id 1 -o json | jq -r .windowId ``` ### 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 hoody --container "$C" display input click --display-id 1 --x 120 --y 80 hoody --container "$C" display keyboard type --display-id 1 --text "hello world" --delay 20 ``` `hoody display input type` 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 hoody --container "$C" display input drag --display-id 1 \ --start-x 50 --start-y 50 --end-x 200 --end-y 150 --button 1 --steps 20 ``` If a drag aborts mid-way and the button stays "pressed" (next click misbehaves), see example 10 — `hoody 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 — `hoody display clipboard set` to the standard CLIPBOARD buffer.** PRIMARY (middle-click paste) is a different selection — Ctrl+V reads CLIPBOARD only. ```bash hoody --container "$C" display clipboard set --display-id 1 --text "pasted via hoody" --selection clipboard hoody --container "$C" display clipboard get --display-id 1 --selection clipboard ``` **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 hoody --container "$C" display keyboard press --display-id 1 --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 hoody --container "$C" display windows get "$WID" --display-id 1 -o json | jq '.properties' hoody --container "$C" display windows geometry get "$WID" --display-id 1 -o json | 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 hoody --container "$C" display windows list --display-id 1 --only-visible -o json \ | 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 # --actions takes a file holding the actions ARRAY (not the {"actions": ...} wrapper): cat > /tmp/actions.json <<'JSON' [ {"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}} ] JSON hoody --container "$C" display input batch act --display-id 1 --actions @/tmp/actions.json -o json \ | jq '{success, failed, skipped}' ``` `hoody display input wait` standalone (`{ ms, screenshot }`) is the right way to insert pauses between separate calls if you don't want to use `hoody display input batch act`. `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 `hoody display geometry get` for the X server's pixel size. Useful as a one-shot diagnostic before driving input. ```bash hoody --container "$C" display get --display-id 1 -o json hoody --container "$C" display geometry get --display-id 1 -o json ``` Note: the geometry returned is the display's virtual screen (often `8192x4096`), not a physical monitor size. Pointer coordinates (`hoody display input click` 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 `hoody display keyboard 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. `hoody display input reset` releases everything in one call. ```bash hoody --container "$C" display input reset --display-id 1 ``` 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 ### `hoody display` (49) — Display control — screenshots, input, windows, clipboard | Command | Aliases | Category | Summary | SDK Link | Example | |---------|---------|----------|---------|----------|---------| | `hoody display clipboard get` | | read | Read clipboard text | `display.clipboard.get` | `hoody display clipboard get --display-id 10 --selection clipboard` | | `hoody display clipboard set` | | write | Write clipboard text | `display.clipboard.set` | `hoody display clipboard set --display-id 10 --text Hello --selection clipboard` | | `hoody display geometry get` | | read | Get display dimensions | `display.getGeometry` | `hoody display geometry get --display-id 10` | | `hoody display get` | | read | Get display information and screenshots | `display.get` | `hoody display get --display-id 10` | | `hoody display health` | | read | Service health check | `display.kit.getHealth` | `hoody display health` | | `hoody display input act` | | write | Execute one action with optional screenshot | `display.input.act` | `hoody display input act --display-id 10 --action mouse/click --screenshot` | | `hoody display input batch act` | | write | Execute a sequence of actions | `display.input.actMany` | `hoody display input batch act --display-id 10 --actions @path.json` | | `hoody display input click` | | write | Move cursor and click | `display.input.click` | `hoody display input click --display-id 10 --x 10 --y 10 --button 1` | | `hoody display input drag` | | write | Drag from one position to another | `display.input.drag` | `hoody display input drag --display-id 10 --start-x 10 --start-y 10 --end-x 10 --end-y 10 --button 1` | | `hoody display input reset` | | write | Emergency release all inputs | `display.input.reset` | `hoody display input reset --display-id 10` | | `hoody display input select` | | write | Select a range via click + shift-click | `display.input.select` | `hoody display input select --display-id 10 --x 10 --y 10 --end-x 10 --end-y 10` | | `hoody display input type` | | write | Move, click, and type in one operation | `display.input.type` | `hoody display input type --display-id 10 --x 10 --y 10 --text Hello --delay 10` | | `hoody display input wait` | | write | Wait for a duration with optional screenshot | `display.input.wait` | `hoody display input wait --display-id 10 --ms 100 --screenshot` | | `hoody display keyboard down` | | write | Hold a key down | `display.keyboard.down` | `hoody display keyboard down --display-id 10 --key Shift_L --window 100` | | `hoody display keyboard press` | | write | Press key combinations | `display.keyboard.press` | `hoody display keyboard press --display-id 10 --keys --window 100` | | `hoody display keyboard type` | | write | Type a string of text | `display.keyboard.type` | `hoody display keyboard type --display-id 10 --text Hello --window 100` | | `hoody display keyboard up` | | write | Release a held key | `display.keyboard.up` | `hoody display keyboard up --display-id 10 --key --window 100` | | `hoody display mouse click` | | write | Click a mouse button | `display.mouse.click` | `hoody display mouse click --double --display-id 10` | | `hoody display mouse click` | | write | Double-click a mouse button | `display.mouse.doubleClick` | `hoody display mouse click --double --display-id 10` | | `hoody display mouse down` | | write | Press and hold a mouse button | `display.mouse.down` | `hoody display mouse down --display-id 10 --button 1` | | `hoody display mouse move` | | write | Move the cursor to an absolute position | `display.mouse.move` | `hoody display mouse move --relative --display-id 10 --x 10 --y 10` | | `hoody display mouse move` | | write | Move the cursor by an offset from its current position | `display.mouse.moveBy` | `hoody display mouse move --relative --display-id 10 --x 10 --y 10` | | `hoody display mouse position get` | | read | Get cursor position | `display.mouse.getPosition` | `hoody display mouse position get --display-id 10` | | `hoody display mouse scroll` | | write | Scroll in a direction | `display.mouse.scroll` | `hoody display mouse scroll --display-id 10 --direction up --clicks 5` | | `hoody display mouse up` | | write | Release a mouse button | `display.mouse.up` | `hoody display mouse up --display-id 10 --button 1` | | `hoody display open` | | action | Open the Display kit service in your browser | | `hoody display open` | | `hoody display screenshots capture` | | read | Capture a new screenshot | `display.screenshots.capture` | `hoody display screenshots capture --metadata --base64` | | `hoody display screenshots capture` | | read | Capture a screenshot and return only its metadata | `display.screenshots.capture` | `hoody display screenshots capture --metadata --base64` | | `hoody display screenshots get` | | read | Retrieve a specific screenshot by timestamp | `display.screenshots.get` | `hoody display screenshots get 1749541160 --base64 --display-id 10` | | `hoody display screenshots latest get` | | read | Retrieve the most recent screenshot | `display.screenshots.getLatest` | `hoody display screenshots latest get --metadata --base64` | | `hoody display screenshots latest get` | | read | Get only the metadata of the most recent screenshot | `display.screenshots.getLatest` | `hoody display screenshots latest get --metadata --base64` | | `hoody display screenshots list` | | read | List all available screenshots | `display.screenshots.list` | `hoody display screenshots list --display-id 10` | | `hoody display thumbnails capture` | | read | Capture a new screenshot thumbnail | `display.thumbnails.capture` | `hoody display thumbnails capture --base64 --display-id 10` | | `hoody display thumbnails get` | | read | Retrieve a specific thumbnail by timestamp | `display.thumbnails.get` | `hoody display thumbnails get 1749541160 --base64 --display-id 10` | | `hoody display thumbnails latest get` | | read | Retrieve the most recent thumbnail | `display.thumbnails.getLatest` | `hoody display thumbnails latest get --base64 --display-id 10` | | `hoody display windows active get` | | read | Get the active window ID | `display.windows.getActive` | `hoody display windows active get --display-id 10` | | `hoody display windows close` | | write | Close a window | `display.windows.close` | `hoody display windows close --display-id 10 --window-id 100` | | `hoody display windows focus` | | write | Focus/activate a window | `display.windows.focus` | `hoody display windows focus --display-id 10 --window-id 100 --sync` | | `hoody display windows geometry get` | | read | Get window position and size | `display.windows.getGeometry` | `hoody display windows geometry get 1 --display-id 10` | | `hoody display windows get` | | read | Get extended properties for a window | `display.windows.get` | `hoody display windows get 1 --display-id 10` | | `hoody display windows list` | | read | List windows on the current display | `display.windows.list` | `hoody display windows list --display-id 10 --only-visible` | | `hoody display windows minimize` | | write | Minimize a window | `display.windows.minimize` | `hoody display windows minimize --display-id 10 --window-id 100 --sync` | | `hoody display windows move` | | write | Move a window | `display.windows.move` | `hoody display windows move --display-id 10 --window-id 100 --x 10 --y 10 --sync` | | `hoody display windows raise` | | write | Raise a window to the top | `display.windows.raise` | `hoody display windows raise --display-id 10 --window-id 100` | | `hoody display windows resize` | | write | Resize a window | `display.windows.resize` | `hoody display windows resize --display-id 10 --window-id 100 --width 10 --height 10 --sync` | | `hoody display windows restore` | | write | Restore (un-minimize) a window | `display.windows.restore` | `hoody display windows restore --display-id 10 --window-id 100 --sync` | | `hoody display windows search` | | read | Search for windows by pattern | `display.windows.search` | `hoody display windows search --display-id 10 --pattern TODO --name` | | `hoody display windows title get` | | read | Get window title | `display.windows.getTitle` | `hoody display windows title get 1 --display-id 10` | | `hoody display windows wait` | | read | Wait for a window to appear or disappear | `display.windows.wait` | `hoody display windows wait --display-id 10 --condition window-present --pattern Firefox` | --- # `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 `hoody egress upstream set` to chain, `hoody egress upstream get` to inspect, and `hoody egress upstream disable` to go back to the container's own IP. Use `hoody egress local start` when the exit should be your own machine rather than a rented proxy; see Quirks. ## 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: `hoody --container egress health` printing the standard health blob confirms egress is live; an error 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 `hoody daemon programs list`. Setting an upstream needs nothing beyond the container URL and whatever proxy permissions guard it. A local exit (`hoody egress local start`) needs more: the container's hoody-tunnel kit must be running, because the exit is wired as a tunnel PULL bind onto the container's loopback, and the CLI must be logged in (`hoody login`), because the tunnel WebSocket authenticates with your account token. Every `hoody --container` command, the plain upstream commands included, also needs that login the first time it meets a container: the CLI looks up the container's routing with your account token and then caches it. If the tunnel kit is down, startup fails before the container is touched. ## Capability URL The endpoint is `https://{projectId}-{containerId}-egress-{serviceIndex}.{server}.containers.hoody.com` — see `SKILL-CLI.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.** `hoody egress upstream get` 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.** `hoody egress upstream set ` takes the proxy URL as its one required argument — e.g. `hoody egress upstream set socks5h://user:pass@host:1080` — and sends it as the request body; it does not read stdin. 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.** `hoody egress upstream disable`. There is no empty-body form here: `set` requires its argument and refuses an empty value, so use `disable`. Check with `hoody egress upstream get`. **Lease an upstream that should end with its client.** `hoody egress upstream set --lease 60` 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 `hoody egress upstream renew --lease-id `: 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 makes your own machine the exit** (`hoody egress local start`). It binds a loopback port inside the container over hoody-tunnel, points the upstream at it, and terminates SOCKS5 on your side, so requests leave from the machine the CLI is running on. Nothing listens on that machine; every socket it opens is outbound. Destinations are gated to public IPv4 by default, every resolved A record is authorised, and the pinned address is what gets dialled, so DNS rebinding cannot redirect a connection after approval. **Only destination ports 80 and 443 are allowed by default**, so SSH, database or `:8080` traffic through the exit is refused; widen it with `--allow-ports 22,443,5432` (or `"*"` for any). `--allow-private` admits private and loopback destinations, and `--dns` picks the resolvers. - **A local exit refuses to clobber an existing upstream.** If the container already has one configured, which includes one currently reported as `state: "unavailable"`, `hoody egress local start` fails with `local exit: this container already has an upstream (://:)` instead of replacing it (when the kit reports no address for the upstream, the message says so in place of the address), because teardown clears the upstream and the kit never returns credentials, so an authenticated upstream it replaced could not be put back automatically. Clear a stale one first with `hoody egress upstream disable`, or pass `--replace-upstream` to take the container over knowingly; when that exit stops, the container goes back to its own IP, not to the proxy it displaced. - **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 `hoody --container egress upstream disable`. - **The URL — credentials included — is a command-line argument.** `hoody egress upstream set` has no stdin, file, or environment form; `--input` is rejected for this command. The full URL therefore lands in shell history and is visible in `ps` while the command runs. On a shared machine, set the upstream through the SDK (its upstream.set method) or with a raw HTTP `PUT /api/v1/egress/upstream` whose body is read from a mode-`0600` file instead. - **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 `hoody containers get` 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 hoody --container "$C" egress health # kit alive? # There is no CLI verb that proxies a request — none is needed. The endpoint # speaks the standard proxy protocol, so curl/git/pip/npm take the URL directly: EGRESS="https://${P}-${C}-egress-1.${N}.containers.hoody.com" curl -x "$EGRESS:443" https://ip.hoody.com | jq -r '.data.ip' ``` `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 hoody --container "$C" egress upstream set 'socks5h://user:pass@proxy.example.com:1080' hoody --container "$C" egress upstream get -o json # {"enabled":true,"state":"active","scheme":"socks5h","host":"proxy.example.com","port":1080,"auth":true,...} hoody --container "$C" egress upstream disable # alias: disable; `set` refuses # an empty URL, so clear is the way back ``` 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 hoody login --web --no-browser # browser sign-in; the tunnel WebSocket authenticates with your account token hoody --container "$C" egress local start # Proxy URL: https://P-C-egress.N.containers.hoody.com # Exit IP: 203.0.113.42 (SG) confirmed # Ctrl+C tears it down and then the CLI exits, which closes the tunnel. On a clean # teardown the upstream is cleared and the container is back on its own IP. If the # clear failed, the container is left pointing at a dead port and the CLI prints # the fix: hoody --container "$C" egress upstream disable # If only the read-back could not confirm the clear, check with `egress upstream get`. ``` 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 hoody --container "$C" egress local start # Failed to start local exit: local exit: this container already has an upstream # (socks5h://proxy.example.com:1080). Stopping this exit would clear it, and its # credentials cannot be read back to restore it. Clear it first, or pass # replaceExistingUpstream/--replace-upstream to take it over. hoody --container "$C" egress local start --replace-upstream # take it over knowingly ``` The check-then-set is not atomic — the guard protects against accidents, not races. 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 prints `Left the upstream alone: another exit has taken this container over.`; 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 ### `hoody egress` (6) — Container egress proxy — outbound HTTP/CONNECT with an optional upstream | Command | Aliases | Category | Summary | SDK Link | Example | |---------|---------|----------|---------|----------|---------| | `hoody egress health` | | read | Egress service health | `egress.kit.getHealth` | `hoody egress health` | | `hoody egress local start` | | action | Publish this machine's IP as the container's HTTPS proxy exit (long-running, Ctrl+C to stop) | | `hoody egress local start` | | `hoody egress upstream disable` | | destructive | Stop chaining through an upstream; egress goes direct | `egress.upstream.disable` | `hoody egress upstream disable` | | `hoody egress upstream get` | | read | Show the upstream proxy the container chains through | `egress.upstream.get` | `hoody egress upstream get` | | `hoody egress upstream renew` | | action | Renew the upstream lease, pushing its deadline out by its ttl from now | `egress.upstream.renewLease` | `hoody egress upstream renew --lease-id 64f1a2b3c4d5e6f7a8b9c0d1` | | `hoody egress upstream set` | | action | Route the container's egress through an upstream proxy | `egress.upstream.set` | `hoody egress upstream set socks5h://user:pass@host:1080 --lease 10` | --- # `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 `hoody proxy aliases create` (`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/` (`hoody exec scripts write`, `hoody 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 `hoody containers proxy *` (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 `hoody 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-CLI.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-CLI.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. `hoody exec scripts write` — `path`, `content`, `createDirs:true`, `validate:true` (default); 400 + `validation` on fail. 2. `hoody exec scripts read` — confirm bytes. 3. `POST {EXEC_BASE_URL}/` — body parsed, return auto-serialised, output streamed. 4. `hoody exec scripts list` — verify. ### 2. Pin deps, iterate 1. `hoody exec modules test` → `hoody exec modules install` → `hoody exec packages pin`. 2. `hoody exec scripts validate` + `hoody exec magic comments validate` (`// @description`, `// @cors`, `// @timeout`). 3. `hoody exec scripts write` (auto-validates unless `validate:false`). 4. `hoody 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. `hoody exec logs list` / `hoody exec logs search` / `hoody exec logs get` (one JSON response; `lines` and `tail` pick the slice). For a live tail use `hoody exec logs stream` (SSE). 2. `hoody exec requests list` / `hoody exec stats`; per script, `hoody exec scripts stats list` first, then `hoody exec scripts stats get` with one `scriptPath` from that listing (an empty body returns an empty `metrics` stub). 3. `hoody exec openapi scripts list`, then `hoody exec openapi generate` / `hoody exec openapi get` (a document built from the current scripts) or `hoody exec 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. `hoody exec openapi schema 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.** `hoody 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. - `hoody exec scripts delete` needs literal `confirm=true`. - `hoody 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'`; `hoody containers proxy services list` returning `[]` is normal (it lists only services named in proxy permission rules or hooks). - `hoody exec schedules run` and `hoody exec schedules history list` scope a relative `scriptPath` by the kit URL you call, like `hoody exec scripts write`: through the `exec-1` kit URL, `tick.js` means `default/1/tick.js` (the `scriptRel` of `hoody 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. - `hoody exec scripts write`/`delete` accept optional `execId` (alias `exec_id`) + `subdomain`; query wins. - `hoody exec magic comments update` and `hoody exec magic comments get` resolve `path` like `hoody 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 `hoody exec scripts list`) also works; the first that exists is used, and none answers 404 `Script not found`. - `hoody exec magic comments batch 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). - `hoody 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 `hoody exec schedules reload`); `hoody exec schedules list` shows its `nextFire`. - A `@schedule` fire bypasses the script's `@token`, and a script that also declares `@websocket` is not registered (`hoody exec schedules history list` 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 `