agentleFS
devswhadevswha/herdr-web-ui/server/AGENTS.md

herdr-web-ui / server

AGENTS.md459 starsChanged 2 months agoMITView on GitHub

Bun backend: HTTP API + WebSocket fan-out over herdr's unix-socket API, plus the PTY attach sidecar. The attachment lifecycle and transport quirks live here and nowhere else.

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository2 other files it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Never let an attachment outlive its last client.

    line 6
  2. Very specific:

    Never attachments.set outside spawnAttachment, and never await between that set and new PtySession(...): the record's pty is a placeholder …

    line 7
  3. Very specific:

    Never add the client to attachment.clients before checking client.data.attached still holds the pane after the await.

    line 8
  4. Very specific:

    Always resize the pty from the geometry of an INTERACT client's attach (attach handler calls resizePty when mode === "interact").

    line 9
  5. Very specific:

    Keep herdr/ free of HTTP concepts — it speaks only herdr's socket protocol.

    line 11

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

server/

Bun backend: HTTP API + WebSocket fan-out over herdr's unix-socket API, plus the PTY attach sidecar. The attachment lifecycle and transport quirks live here and nowhere else.

ANTI-PATTERNS

  • Never let an attachment outlive its last client. Cleanup paths: detach/close for members (detach() closes on an empty client set), releaseUnclaimed for an attach cancelled mid-creation, onExit for a pty that died, stop() for everything.
  • Never attachments.set outside spawnAttachment, and never await between that set and new PtySession(...): the record's pty is a placeholder until then.
  • Never add the client to attachment.clients before checking client.data.attached still holds the pane after the await.
  • Always resize the pty from the geometry of an INTERACT client's attach (attach handler calls resizePty when mode === "interact"); an observe attach never resizes. Never spawn herdr terminal attach without cols/rows.
  • Answer in-band: handler failures are sent as {type:"error"} frames. The only deliberate closes are 4008 (output stall/overflow), 1008 (device revoked) and 1012 (relay/PC gone).
  • Keep herdr/ free of HTTP concepts — it speaks only herdr's socket protocol; HTTP shaping belongs in index.ts.

CONVENTIONS

  • attachments: Map<paneId, PaneAttachment> holds { pty, clients, cols, rows, replay }. cols/rows are the pty's current grid: resizePty updates them and broadcasts pane-geometry to the pane's clients whenever they change. replay is a bounded 256KB tail sent to clients that attach late; pty-exit broadcasts first, then closes the attachment.
  • createServer starts startStatusCollector (collector.ts): per-pane agent_status_changed for EVERY pane in the snapshot plus a global pane.created/pane.closed/pane.exited subscription. Every stream reopens itself when herdr closes it (events_lost, restart) with 250 ms→5 s backoff; a lifecycle stream that comes back reconciles, and a lost status stream resyncs from a snapshot taken after the new subscription started. Its callbacks broadcastAll pane-status / pane-exited / session-changed to every connected client — pane-status no longer depends on attachment. The client set is tracked in a clients Set (open/close).
  • Sidecar protocol (pty-host.mjs): argv <cols> <rows> <command> [args...]; stdin newline-JSON frames — {"t":"i","d":"<text>"} writes, {"t":"r","c":cols,"r":rows} resizes; stdout is raw pty bytes unmodified; exit mirrors the child's code; sidecar clamps cols/rows to 1..1000.
  • Output control adds {"t":"p","paused":true|false}. Parent pause and stdout backpressure are independent; both must clear to resume. Kill resumes the reader to observe EOF and has a bounded forced cleanup. PtySession awaits stdout EOF before reporting process exit.
  • ACK-capable attaches carry flow_control:"ack"; pty-data.flow identifies the subscription and cumulative UTF-8 byte offset. pty-ack releases only already-sent credit in that subscription. Pause at 256 KiB, resume at <=64 KiB, close consumers blocked for 2s with code 4008; 1 MiB hard application/transport budgets. -1 from Bun send is already queued, never retransmit it. Legacy clients have the transport cap only. See docs/terminal-flow-control.md and server/output.contract.test.ts.
  • HerdrError.code → HTTP status (http.ts errorResponse): connect_failed/timeout → 502; other HerdrError codes → 404; anything else → 500 internal_error.
  • Auth: auth.ts isAuthenticated accepts the herdr_web_token cookie or an Authorization Bearer (length-safe compare); access.ts decideAccess (token → device cookie → Tailscale owner → loopback local → pairing) runs for /ws and every /api/* route except /api/health, /api/auth and /api/devices/pair; static files stay open.
  • An unauthenticated /ws upgrade is refused with a plain-text 401 unauthorized (the WS client never parses a body); every other refusal is the JSON envelope.
  • terminalInfoFor resolves pane_id → { terminalId, rect } from one fresh session.snapshot (rect = the pane's layouts[].panes[].rect, null when absent); missing pane → pane_not_found, pane without terminal → no_terminal.
  • The layout rect is NOT the terminal's current size (measured on herdr 0.9.3): it stayed 120x40 while a terminal attach sized the pane 100x30, then 140x40, and the pane kept 140x40 after that attach left. Only the attached client's size is real; nothing in the API tells another bridge's size. An attachment started again (held retry, live handoff) therefore reuses its own cached cols/rows (#363 review).
  • Attachment creation: ensureAttachment returns the existing record, else joins the in-flight creation in pendingAttachments (cleared in finally), else starts spawnAttachment. An observe-first creation spawns at the pane's rect (fallback 80x24), never the observer's grid; an interact-first one at the client's grid.
  • The attach handler records the pane in client.data.attached BEFORE awaiting the creation, so a detach (the client's pane switch sends detach-old then attach-new) or close landing mid-creation cancels it; on resume a cancelled attach calls releaseUnclaimed, which closes the record only if it has no clients AND no other client still has the pane in attached (a joiner of the same creation that has not resumed yet). A failed creation removes the pane from attached again.
  • closeAttachment removes the pane from every member's attached: after a pty exit the members sit on "terminal ended" and a stale entry would read as a live claim in releaseUnclaimed.
  • An attach exit (not a read race, attach_held or a retired refusal) is not yet the pane's end: ended looks the pane up every 100 ms for ATTACH_RELOOKUP_FOR_MS (5 s). A new terminal_id (herdr live handoff) starts a new attach for the same clients; a gone pane gets pty-exit at once; the same terminal or an unreachable herdr gets it at the deadline. The timer is attachment.relookup, cleared in closeAttachment (#370).
  • SocketData holds attached, mode, per-pane output windows and a closing flag. An observe connection's input/keys/resize answer {type:"error", code:"read_only"}, and its attach never resizes the pty — it receives the current pane-geometry and adopts it. Observers can acknowledge output.
  • WS keys messages go through herdr RPC (pane.send_keys), not the pty; input goes straight into the pty.
  • Malformed client frames get {type:"error", code:"invalid_json"} back; the connection is never dropped for a bad frame.
  • Malformed roles (role with anything but interact/observe) and impossible geometry (non-integer or outside 1..1000 cols/rows) answer invalid_role / invalid_geometry error frames.
  • On open every client immediately receives snapshot; if that herdr call fails it gets an error frame carrying the herdr code or snapshot_failed.
  • createServer({ port: 0, stateDir }) boots on an ephemeral port (how the contract tests run it, always with a temp stateDir); stop() closes every attachment before server.stop(true).
  • Push state (push.ts): VAPID keys load-or-generate lazily on first need; subscriptions keyed by endpoint, persisted via temp+rename 0600; 404/410 → delete + persist, other failures → log + keep. seed(panes) replaces titles and only FILLS missing status baselines (an event is newer than any snapshot). Payload = shared/protocol.ts PushPayload; TTL 12h; urgency high for blocked.
  • The collector calls onBaseline(snapshot.panes) on EVERY reconcile (before the same-set early return): without it the first status event after a restart has no baseline and is dropped as a first sighting.

REMOTE BRIDGES

  • Machine proxy forwards only allowlisted pane/workspace routes and its own bridge bearer credential. Never forward browser cookies/Authorization or remote Set-Cookie.
  • SSH askpass secrets are in memory through private Unix sockets; persistent private keys and registries are 0600. Host-key changes fail closed.
  • Remote process replacement requires explicit setup update approval, authenticated bridge/PID verification and managed_remote ownership. Never stop herdr itself or an independent bridge.
  • Bundled runtime releases are immutable checksum-addressed directories. MachineRelay carries ACKs unchanged; never acknowledge remote output before the browser has parsed it.

WHERE TO LOOK

TaskLocationNotes
SSH remote PCsmachines.ts + ssh.ts + machine-api.ts + machine-relay.ts; shared/machines.tsPC-scoped APIs/SSE/WS; private versioned runtimes, same-socket bridge reuse, explicit setup/update approval; docs/remote-pcs.md
HTTP routing / static servingindex.ts createServer().fetchroute order matters (root AGENTS.md); /api/machines/local/* rewrites to /api/*; handler modules return a Response, or null to fall through
Updating herdr itselfherdr-update.ts (HerdrUpdater, handleHerdrUpdateRequest) + GET/POST /api/herdr/update in index.tsruns herdr update --handoff with every HERDR_* variable removed, stdin closed and HERDR_SOCKET_PATH set to this server's herdr, then herdr server live-handoff when herdr status --json says the binary differs from the server; only the real entrypoint passes herdrUpdate, so tests offer nothing unless they pass a stand-in herdr. NEVER run the real herdr update in a test: it replaces the herdr on PATH (#373)
App updatesmanaged.ts (launcher) + supervisor.ts + updater.ts + update-api.ts + update-state.tslauncher runs the active release's supervisor and falls back if it dies before ready; supervisor owns Git/build/restart and exits 75 (HANDOVER_EXIT) after an install so the new supervisor takes over; bridge relays status/commands over IPC; /api/updates* gated + POST custom-header/same-origin guard; no update side effects in createServer tests; real Git/build/IPC/rollback tests in updater.test.ts
Workspace / agent HTTP endpointsindex.ts + herdr/client.ts/api/agents and /api/workspace/create/rename/move/close; creation validates cwd and may start an agent in the root pane
Slash-command discoverycommands.ts + GET /api/pane/commands in index.tsper-agent built-ins; Claude user/project .claude/commands/**/*.md
File mention searchfiles.ts + GET /api/pane/files in index.tsgit inventory or bounded walk, ranked filtering, 5s cwd cache
Chat-lens transcriptsconversation.ts + codex.ts + GET /api/pane/conversation in index.tsCodex native rollouts: session metadata/open descriptors first, unique substantial pane-text match for shared app-server TUIs; canonical store paths only, no subagent sessions, no cwd-recency guess. createServer({ codexHome }) isolates test stores. claude/omp use agent.get; omo uses its process tree + own store. Cache compares inode/size/mtime; end_ts records actual assistant activity.
Interactive pane promptsprompt.ts + /api/pane/prompt routes in index.tsvisible-screen parser and responder-specific key/text answers; prompt hashes prevent stale answers
Model / reasoning metadataconversation-metadata.ts + conversation.ts cacheLatest recorded settings only: Codex turn_context, omp/omo model_change + thinking_level_change, Claude message.model. HTTP metadata.model / metadata.reasoning_effort use null for unknown values; never infer effort from thinking text.
Background task stateconversation.ts taskNotice / placeStrayNoticesClaude's <task-notification> (a user turn, a queue-operation enqueue, or a queued_command attachment) sets task: { status, summary } on the tool part its <tool-use-id> names and never shows as a turn. The newest page parses in stretches, so notices a stretch cannot place are matched to earlier stretches by tool_use id (kept in a WeakMap, off the wire). Older pages are not revisited.
PTY spawn/write/resize/killpty/session.ts (PtySession) + pty/pty-host.mjssidecar protocol above
Web pushpush.ts (createPushService, handlePushRequest)wired in index.ts: collector onStatus/onPaneEnded → push.onStatus/onEnded (rejections logged, never unhandled), onBaseline → push.seed, onResync (after a lost status stream) → push.resync; lookupTitle = fresh session.snapshot
Image pastepaste.ts (savePaneImage, PasteImageError)POST /api/pane/image (index.ts): file under <pane cwd>/.herdr-web-ui/ (0600, tmpdir fallback when cwd is null), or under HERDR_WEB_PASTE_DIR when the server's environment sets it (pasteDirectory, read on every save: ~/… is the home directory, a relative value resolves against the server's cwd), ≤8MB png/jpeg/gif/webp; PasteImageError carries its own status (413/415/400) which the route maps to the shared envelope; unknown pane is the usual herdr pane_not_found

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.