Skip to content

Latest commit

 

History

History
1083 lines (1016 loc) · 90.2 KB

optio-local.md

File metadata and controls

1083 lines (1016 loc) · 90.2 KB

Optio Local

Optio Local manages terminal sessions running on your own machine from the Optio web UI. A small daemon (optio local up, part of the Optio CLI) runs on your workstation, makes a single outbound WebSocket connection to the API, and exposes an allowlisted set of directories. From the browser you can spawn terminals in those directories (bare shells, raw commands, or agent CLIs like claude), switch between many of them, and see at a glance which ones need you. Tickets, webhooks, and schedules can spawn terminals automatically via Local Blueprints wired into the existing polymorphic trigger system.

In the session model, Optio Local is the Where = your machine answer. Every kind of session that can run in a pod can run in a directory on a paired machine instead — a one-shot PR session on a new branch, a scheduled or webhook job, an interactive agent you chat with, or an automation woken by GitHub / Slack / Linear events (those only run on a machine) — picked from the same New Session form and shown in the same Sessions feed. Local runs use your locally-installed CLIs and their local auth — the server never ships secrets to your machine.

Concepts

  • Host (local_hosts) — one paired machine, bound to the registering user (hosts are personal, never workspace-shared compute). Carries an allowlist of directories, each with an auto-detected git remote. Online/offline tracked via daemon heartbeat. Directories live in the machine's local.json and belong to its daemon: the CLI's optio local add|remove edit them there, and the Machines page / New work form edit them through the daemon (POST|DELETE /api/local/hosts/:id/dirs → a dirs frame; the daemon resolves ~ and symlinks, checks the directory exists, detects its remote, saves, and answers with the whole new list, which the row mirrors). From Optio a path must be absolute or under ~, and / is refused. optio local up --no-remote-dirs keeps the list local-only (the hello then doesn't set manageDirs, and the server never asks). A shell in any allowlisted directory can already reach the rest of the account, so the list scopes where work runs rather than fencing the machine off from its owner. Identity: the daemon keeps the host id each server gave it (local.json, per server URL) and sends it back on every registration, so a machine keeps its row — terminals, automations, resumable sessions — when its hostname changes (macOS renames itself as it moves between networks); the row's hostname, and its name unless someone chose one, follow. Without an id (first pairing, or a daemon from before ids were sent) the row is matched by (user, hostname). A computer that got a second row under an old daemon shows up twice, the old row offline for good: Merge on the Machines page (POST /api/local/hosts/:id/merge) moves the offline row's terminals, automations, and Task / Job run locations to the other machine and removes it; terminals that were waiting for it start there. A daemon that sends its id under a hostname an offline row of the same user still has folds that row in by itself.
  • Terminal (local_terminals) — one PTY on a host: state machine pending → launching → running → exited | error, plus an attention state (working / needs_you / idle) that drives the UI's "needs you" queue. A terminal may execute a Job run or a Repo Task whose run location is this host (spawned_by = "job" | "task", see "Local runs" below).
  • Automation (work_definitions rows with kind = 'local-blueprint'; "blueprint" in the API and code) — "when X happens, run this agent on my machine". Who (agent: claude-code / codex / cursor / gemini / opencode, or null for a plain shell command), What (commandTemplate, rendered with {{param}} substitution — the agent's prompt, or the shell command; or promptTemplateId, a saved prompt from the Prompts library that replaces it, so one reviewed "review this PR" prompt can back many automations), Where (hostId / dir / repoUrl, all optional — see dir resolution below; plus baseBranch: when set, an agent spawn's prompt is wrapped with "create a branch off this base, commit, push, open a PR" instructions — the "new branch that becomes a PR" choice in the New session form; the same wrapper applies to a hand-opened agent terminal whose spec carries baseBranch), When (triggers) and Then (sessionMode). Triggers are rows in workflow_triggers with target_type = "local_blueprint": the generic manual / schedule / webhook / ticket ones shared with Jobs and Task Configs, plus the event triggers github / slack / linear / pagerduty fed by the signed ingress endpoints and pylon fed by a per-trigger URL (see "Automations" below). spawn_mode = "hold" creates the terminal pending for one-click human start; "auto" spawns immediately (or parks as pending/host_offline when the host is offline, flushed on reconnect). Agent spawns get the same attention hooks as hand-started ones and enter the "needs you" queue while alive, not only on exit.
  • Session mode (sessionMode, agent automations only):
    • interactive (default) — the agent runs at its normal prompt. When its turn ends it halts and waits (needs_you, reason stop); you open the session and keep chatting.
    • headless — the agent's one-shot entry point (claude -p, codex exec, cursor-agent -p, gemini -p, opencode run): it prints its result and the process exits. A clean exit lands in the queue as needs_you / done for review. Claude Code still fires hooks in -p mode, and Codex's rollout names its thread, so the daemon captures the agent's own session id (local_terminals.agent_session_id) and the run can be resumed later.
  • Resume — POST /api/local/terminals/:id/resume (the "Resume chat" button on an exited agent session) opens a fresh interactive terminal in the same dir with claude --resume <id> (or codex resume <id>). It is the same session continued: it keeps the original's title, spawnedBy, trigger, blueprint and ticket (so its badge and icon are the original's) and the two rows point at each other (resumed_from_terminal_id / resumed_by_terminal_id); the rail shows the latest of the chain in the original's place. Exiting a resume later goes quiet like a manual shell (rows from before v0.23 carry spawnedBy = "resume"). It runs on the session's own host (the agent's transcript lives there); while that host is offline the new terminal waits as pending / host_offline and its page says so. Asking again while a resume of the same session hasn't ended (waiting, starting, or open) returns that one (reused: true) instead of a second copy of the conversation.

Claude token refresh from your machine

The cluster's CLAUDE_CODE_OAUTH_TOKEN expires; the old fix was a Keychain one-liner and a paste into Secrets. A paired machine already holds a fresh login, so the daemon can hand it over (services/local-auth-refresh-service.ts, cli/src/local/claude-credentials.ts):

  • The daemon's hello carries claudeCredentials: true when the machine has a Claude Code login (macOS Keychain item "Claude Code-credentials", else $CLAUDE_CONFIG_DIR/.credentials.json). Live only — GET /api/local/hosts reports it per host, false while offline.
  • The server sends {type:"credentials", requestId}; the daemon answers {type:"credentials-result", requestId, token, expiresAt} with the access token only (the refresh token never leaves the machine), or an error. The server validates the token against Anthropic, stores it as the global CLAUDE_CODE_OAUTH_TOKEN (what the validation worker, usage probe, and agent pods read), invalidates the credential / usage caches, marks the validation cache good, and publishes auth:status_changed.
  • Who may: a host owned by a deployment admin (the same gate as global secrets), or any host in auth-disabled dev.
  • Explicit: POST /api/auth/claude-token/refresh-from-host {hostId} (deployment admin, own host); the expired-token banner shows a "Refresh from machine" button for every online host that can, above the copy/paste steps.
  • Automatic: when the token-validation worker finds the stored token expired it tries every capable online host first and only raises the auth:failed banner if none worked; and a capable daemon that connects while the stored token is known-bad refreshes it on hello. Each host is tried at most once per 10 minutes, so a machine whose own login is also stale isn't polled on every cycle.
  • A stale login renews itself. Claude Code only renews its access token when it runs, so a machine where nobody has opened claude for a while holds the same expired token the cluster is trying to replace. Before answering, the daemon checks the token's expiry (credentialsExpireSoon, a 10-minute margin) and, when it is stale, runs claude -p once in a scratch directory through the login shell (renewClaudeLogin: one short turn on the smallest model, no tools, no session file) so Claude Code refreshes the token with its refresh token and writes the new one where claude login does, then reads again. Concurrent requests share one renewal. Only when that fails does the server say "sign in again on that machine". Codex needs none of this: a pod's Codex signs in with an OpenAI API key or the managed app-server (CODEX_AUTH_MODE), never with a copy of a machine's ChatGPT login.

Local runs: Tasks and Jobs on your machine

Run location is a first-class attribute of every Task, Job, and scheduled Task blueprint (run_target on tasks and work_definitions): cluster (an Optio pod, the default) or local — a directory on one of your paired hosts. The "Where" section of the New Task form, the Job editor, and the scheduled-Task editor all use the same picker (components/run-location-picker.tsx): choose Optio pod or My machine first — a pod Task then picks a registered repo, while on a machine you pick the host and a directory (for a Task only git checkouts are offered, and the checkout's detected remote becomes the task's repo — there is no separate repo choice) — and Then — headless (default: claude -p etc., the run finishes when the agent exits) or interactive (the agent stays at its prompt; the run keeps going until you close the session).

A local run is an ordinary run row plus a local_terminals row that executes it (spawned_by = "job" | "task", back-links workflow_run_id / task_id; the run points back via local_terminal_id). The pipeline, in services/local-run-service.ts:

  1. The run is created and queued exactly as before (REST, trigger, schedule, webhook, retry). The workflow / task worker picks it up and, seeing run_target = "local", calls dispatchLocalWorkflowRun / dispatchLocalTask instead of provisioning a pod. No cluster concurrency or off-peak gating applies; the reconciler skips capacity, stall, and pod-death checks for local runs (spec.runTarget).
  2. Dispatch re-checks the location (host still paired, dir still allowlisted, agent one the daemon can launch — Claude Code / Codex / Cursor / Gemini / OpenCode; a command Job has no agent), claims a terminal id on the run under CAS (so a worker + reconciler race can't spawn twice), and createTerminals the spec — {kind: "command"} with the rendered command for a command Job (its exit code settles the run), else an {kind: "agent"} spec: the rendered prompt, the session mode, and what the run's agent options set for a run on a machine (localAgentParams in @optio/shared): the model (--model / -m), the reasoning effort, and Claude Code's permission mode — see "Launching agents" below. A Task's prompt is wrapped with "work on optio/task-<id> off <base>, push, open a PR, print its URL"; a resume (CI failure / review feedback) carries the resume prompt and, for Claude Code, -p --resume <session>. Host offline → the terminal parks and the run stays queued until the daemon's next hello flushes it. Machine full → the same: every host has an agent limit (local_hosts.max_concurrent_agents, default 3, set on the Machines page or with PATCH /api/local/hosts/:id), the machines' answer to a repo's concurrency limit. An agent terminal that an automation, Job, Task or ticket starts while the host already runs that many agents parks in pending / capacity ("Queued", with its place in the machine's line — queuePosition, 1 = next) and starts, in queue order (local_terminals.queue_priority, then oldest first), as agents finish, when the limit is raised, and on the daemon's hello — the host row is locked for the check-and-claim (claimAgentSlot), so two spawns racing for the last slot can't both take it. Like a queued Repo Task, a queued session can jump the line: Move to front (POST /api/local/terminals/:id/front) makes it the next to start, and Start now (POST /api/local/terminals/:id/start with { now: true }) starts it at once, past the limit — the limit holds back automations, never a person. A session a person opens by hand always starts (their machine, their call) but counts toward the limit; shells and plain commands never count. The sweeper restarts waiters whose flush was lost with an instance.
  3. Daemon frames drive the run (syncLinkedRun, called from every terminal update): launching/running → Job running (Task provisioning → running); usage → live cost / tokens / model on the run; session → tasks.session_id (resume handle); a links frame with a PR of the task's repo → Task pr_opened (the PR watcher and auto-review / auto-merge take over from there); exit 0 → Job completed (Task completed, or pr_opened when a PR exists — even on a non-zero exit); exit ≠ 0 / spawn-error → failed. The last preview lines, session id, and links are stored in the Job run's output.
  4. Cancel / server-side failure (cancel button, reconciler intent, dependency cascade, force redo) kills the terminal; the daemon's trailing exit then changes nothing.

Local runs use the machine's own agent CLI and login — no server secrets ship to laptops — and follow the same attention rules as automations: a finished run lands in Needs you (done / exit). The Job run page and the Task page embed the session (components/local/embedded-session.tsx) in place of the pod log viewer; the Local cockpit shows the same terminal with a job / task badge and an "Open run" / "Open task" link. The REST bodies: runTarget, localHostId, localDir, localSessionMode on POST /api/tasks (all kinds), POST/PATCH /api/jobs, and POST/PATCH /api/task-configs (validated by validateRunLocation: the host must be the caller's own).

Automations: event triggers

The ingress endpoints turn things that happen to you (or to your repos and services) into automation runs. The signed ones are public, verified purely by the provider's HMAC or shared token, workspace-wide (one webhook per GitHub org / GitLab group / Slack app / Linear workspace / Jira site / Sentry integration), and each trigger's config carries the identity it listens for, so several people's automations can share one ingress. The self-secret ones (Pylon, Alertmanager / Grafana, Datadog, Jenkins) are per trigger.

Source Ingress Secret Trigger config
GitHub POST /api/webhooks/github (the existing receiver, X-Hub-Signature-256) GITHUB_WEBHOOK_SECRET { events?: GitHubEventKind[] (the 31 kinds in GITHUB_EVENT_KINDS: about-me, PR, issue, label, repository, security and discussion kinds — see docs/tasks.md), login?, repos?: ["owner/name"], branches?, workflows?, labels?, postedBy?: people | bots | anyone, ignoreLogins?, authorOnly?, bodyMatches?, reviewStates?, severities? }. Params add actor, commentAuthor, labels, label, ref, sha, commits, compareUrl, tag, workflow, conclusion, merged, changes, reviewState, environment, alertSeverity, dispatchType, dispatchPayload
GitLab POST /api/webhooks/gitlab (project / group webhook; X-Gitlab-Token = the webhook's secret token; X-Gitlab-Event-UUID deduped) GITLAB_WEBHOOK_SECRET { events?: ("review_requested" | "mentioned" | "assigned" | "mr_opened" | "mr_merged" | "issue_opened" | "labeled" | "push" | "release_published" | "pipeline_succeeded" | "pipeline_failed")[], username?, projects?: ["group/project"], branches?, labels? }. Params: event, kind, project, projectUrl, iid, title, body, url, author, sourceBranch, targetBranch, commentBody, commentUrl, labels, label, ref, sha, commits, compareUrl, tag, pipelineStatus, action
Slack POST /api/webhooks/slack/events (Events API; answers url_verification; X-Slack-Signature v0) SLACK_SIGNING_SECRET { channelId, keyword?, mentionOnly?, includeThreads?, postedBy?: "people" | "bots" | "anyone", bot? }
Linear POST /api/webhooks/linear (Linear-Signature over the raw body + webhookTimestamp ≤ 60 s) LINEAR_WEBHOOK_SECRET { events?: ("assigned" | "mentioned" | "created" | "labeled")[], user?, labels?, teams?, othersOnly? }
Jira POST /api/webhooks/jira (Jira Cloud webhook with a secret; X-Hub-Signature: sha256= over the raw body; a comment delivered twice fires once) JIRA_WEBHOOK_SECRET { events?: ("assigned" | "mentioned" | "created" | "commented" | "transitioned" | "labeled")[], user? (account id, display name or email), projects?: [keys], labels?, issueTypes?, statuses? }. Params: event, key, title, description, url, project, projectName, status, previousStatus, assignee, priority, labels, issueType, commentBody, commentUrl, actor, plus the ticket* aliases
Sentry POST /api/webhooks/sentry (an internal integration's webhook; Sentry-Hook-Signature = hex HMAC over the raw body; Sentry-Hook-Resource picks the resource — issue, event_alert, metric_alert) SENTRY_WEBHOOK_SECRET (the integration's client secret) { events?: ("issue_created" | "issue_unresolved" | "issue_resolved" | "issue_assigned" | "issue_archived" | "alert_triggered" | "metric_alert_critical" | "metric_alert_warning" | "metric_alert_resolved")[], projects?: [slugs], environments?, levels? }. Params: event, resource, action, issueId, shortId, title, culprit, level, project, projectName, url, environment, status, assignee, count, userCount, firstSeen, lastSeen, actor, alertRule, plus the ticket* aliases
Alertmanager POST /api/hooks/alertmanager/<trigger id> (Prometheus Alertmanager webhook_config, or a Grafana Alerting webhook contact point; the secret as Authorization: Bearer, basic-auth password, or X-Optio-Secret) per trigger: config.secret, minted on create and returned once (hasSecret: true afterwards) { events?: ("firing" | "resolved")[], alertnames?, severities?, receivers? } — one firing per alert group. Params: event, status, receiver, groupKey, title, message, alertnames, severities, count, firing, resolved, externalUrl, labels / annotations (JSON), alerts (JSON), payload (JSON, ≤ 20 000 chars)
Datadog POST /api/hooks/datadog/<trigger id> (Integrations → Webhooks, a custom header carrying the secret as X-Optio-Secret or Authorization: Bearer; paste DATADOG_PAYLOAD_TEMPLATE as the payload) per trigger: config.secret, minted on create and returned once (hasSecret: true afterwards) { events?: ("triggered" | "warning" | "no_data" | "recovered")[], priorities?: ["P1"…"P5"], tags?, monitors? }. Params: event, transition, alertType, eventId, alertId, title, body, link, priority, status, tags, hostname, query, scope, metric, org, date, payload (JSON, ≤ 20 000 chars)
Pylon POST /api/hooks/pylon/<trigger id> (Pylon → Settings → Triggers, a webhook action; unsigned, so the delivery carries the trigger's secret as the custom header X-Optio-Secret, or Authorization: Bearer <secret>) per trigger: config.secret, minted on create and returned once (hasSecret: true afterwards) { events?: string[] } — free-text kinds matched case-insensitively against the payload's event / event_type / type / trigger / data.event; empty = any. Params: event, issueId, issueNumber, title, body, state, url, account, requester, assignee, tags, payload (the JSON, ≤ 20 000 chars)
PagerDuty POST /api/webhooks/pagerduty (Webhooks v3; X-PagerDuty-Signature v1= HMAC over the raw body, any of several; X-Webhook-Id deduped) PAGERDUTY_WEBHOOK_SECRET { events?: ("incident.triggered" | "incident.acknowledged" | "incident.resolved" | "incident.escalated" | "incident.reassigned" | "incident.priority_updated" | "incident.annotated" | …)[], services?: [id or name], urgency?: "high" | "low" }. Params: event, incidentId, incidentNumber, title, url, urgency, priority, service, serviceId, status, assignees, plus the ticket* aliases

Matching lives in services/event-trigger-service.ts as pure functions (normalize* → one event; match* → the matched kind or null); fireEventTriggers fans an event out to every enabled trigger of that type — whatever it targets: a Local automation, a Job or scheduled Task in a pod, a persistent agent — and starts each match through the shared trigger dispatcher with the event's fields as prompt params. Personal kinds (review_requested, mentioned, assigned) only match when the trigger's login / user is among the event's targets (reviewer, assignee, @-mentions, case-insensitive; Linear matches user id, name, display name, or the @handle in a mention link); pr_opened / issue_opened / created / labeled need no identity. A comment you wrote that mentions yourself never fires. Nothing one of a GitHub trigger's ignoreLogins does fires it; its comment / review / edit / PR-push kinds (issue_commented, pr_commented, pr_review_submitted, pr_synchronized, issue_edited, discussion_commented) fire for people by default (postedBy), never for the trigger's own login, and with authorOnly only when the issue's / PR's author is the one writing; bodyMatches keeps slash commands. The Machines page's trigger editor and the Work form both offer these filters. Linear's othersOnly ("Only tickets from someone else", needs user) skips an issue user created (creatorId, or the creator itself when the payload has it) and any change user made (the webhook's actor, or the person behind an integration's botActor): a ticket you file and assign to yourself, or assign to yourself later, starts nothing. When the ticket is assigned to user, all the assignee's keys count as theirs, so a trigger set up with a display name still recognizes its user's id as creator or actor.

Prompt params: GitHub {{event}} {{kind}} {{repo}} {{repoUrl}} {{number}} {{title}} {{body}} {{url}} {{author}} {{headBranch}} {{baseBranch}} {{commentBody}} {{commentUrl}} {{action}}; Slack {{channelId}} {{userId}} {{text}} {{ts}} {{threadTs}} {{permalink}} {{botName}} {{botId}}; Linear {{event}} {{identifier}} {{title}} {{description}} {{url}} {{labels}} {{teamKey}} {{assignee}} {{priority}} {{state}} {{commentBody}} {{commentUrl}} {{actor}} plus the ticket* aliases used by ticket triggers. GitHub and Linear runs are linked to the PR / issue (ticket_* columns) so the session shows the badge.

Dir resolution (resolveBlueprintDir): the automation's dir → the host dir whose git remote matches its repoUrl → the dir matching the event's repo (a GitHub PR's repository) → the host's first allowlisted dir, but only when the spawn names no repo at all (Slack, manual). A repo the host doesn't have — pinned or from the event — is an error, not a fallback: "review acme/api#12" must never run inside an unrelated checkout. So "Where: the event's repo" makes one PR-review automation cover every repo you have checked out, and skips the ones you don't.

Scoping and replay: a GitHub event about a repo registered in Optio only reaches automations in that repo's workspace (or workspace-less ones, i.e. auth-disabled dev), whatever login they claim. Deliveries are de-duplicated in-process by id (X-GitHub-Delivery, Slack event_id, Linear type+action+entity+timestamp) so provider retries don't fire twice. An automation's pinned hostId must be the caller's own host — checked on create/update and again at spawn.

Slack notes: subscribe the app to message.channels (plain messages) and/or app_mention (mentionOnly triggers listen to the latter only, so an @-mention never fires twice), invite the app to the channel, and use the channel id (C0…) from the channel details. Only people's posts fire a trigger unless its postedBy says bots (apps, integrations and incoming webhooks: a post with a bot_id or the bot_message subtype) or anyone; bot narrows that to one bot, by the name on its posts, its bot id (B…) or its app id (A…), case-insensitive. A bot's {{text}} adds what its attachments and blocks say (title, text, fields, sections, context, rich text), since alerting tools put the details there; {{userId}} is empty and {{botName}} names it. Anything the receiving app posts itself (its app id, or its bot user in the event's authorizations) never fires, so Optio's own Slack messages can't start work; Optio's notification webhook, if it belongs to a different Slack app, is not excluded, which is what bot is for. Edits, deletes, joins and other subtypes are dropped; thread replies only match with includeThreads; event_ids are remembered so Slack's retries don't double-fire. The endpoint acks before dispatching (Slack retries anything slower than 3 s).

Recipes

  • "When I'm tagged on a PR, review it, then stop": automation with agent Claude Code, Where = the event's repo, Then = exit when done, prompt using {{url}} / {{headBranch}} / {{baseBranch}}; trigger github with events: ["review_requested", "mentioned"] and your login. The result lands in Needs you with reason done; "Resume chat" picks the session back up if you want to discuss it.
  • "When a message lands in #channel, do it and wait for me": agent automation with Then = keep the session open and a prompt around {{text}} / {{permalink}}; trigger slack with the channelId (optionally a keyword).
  • "When the alert bot posts in #alerts, debug it": agent automation (Codex, say, with Permissions = Skip all checks), Then = keep the session open, prompt {{botName}} posted this alert ({{permalink}}):\n\n{{text}}\n\nFind the cause.; trigger slack with the channelId, postedBy: "bots" and the bot's name as bot.
  • "When a Linear ticket is assigned to me, triage it and open a PR": agent automation pinned to the repo's dir (or repoUrl), Then = exit when done, prompt around {{identifier}} / {{title}} / {{description}} / {{url}}; trigger linear with events: ["assigned"] and your user.

The Automations section on /machines ships these three as one-click presets.

Attention detection (daemon-side)

Layered, best signal wins per terminal:

  1. Program status, OSC 7501 (the program's own word). The Program Status Protocol (Ghostty 1.4 parses it; Claude Code, Pi and Crush emit it) lets a program tell its terminal working / blocked / done / error / idle, a blocked with a kind (permission / question / auth) and a one-line msg. The daemon's screen model is the terminal the program talks to, so it answers the capability query (OSC 7501 ; ? — Claude Code reports only once something answered; a viewer's xterm.js never does) and hands each report to the tracker (program-status.ts, attention.statusEvent): working → working, idle → idle, blocked → needs_you with the kind as the reason (permission, question, auth, or blocked), done → needs_you (reason done), error → needs_you (reason error). Only the root record counts (a subagent's record says nothing about the whole; clear says nothing). Once a program has reported, it owns the terminal: hooks, bells, silence and keystrokes are ignored for it (Claude Code sends both hooks and status, and status is the finer: a Stop hook followed by idle would otherwise leave a stale needs_you) — with one exception, a Codex turn boundary that ends a working status (layer 1). Reports are untrusted output: values are checked against the spec's alphabet and limits, msg / title must not decode to a control character, and a report over a limit is dropped whole. The daemon must never export CLAUDE_CODE_DISABLE_TERMINAL_TITLE to an agent: Claude Code turns program status off with it.
  2. Claude Code hooks (exact). For agent: "claude-code" spawns the daemon injects a settings file (--settings) whose Stop / Notification / UserPromptSubmit hooks POST to the daemon's localhost hook server (http://127.0.0.1:$OPTIO_LOCAL_DAEMON_PORT/hook/$OPTIO_LOCAL_TERMINAL_ID). Stop → needs_you (reason stop), Notification → needs_you (reason notification), UserPromptSubmit → working. Once a hook fires, heuristics are disabled for that terminal. Codex has no hooks Optio can use, but its rollout marks every turn: task_started → working, task_complete / turn_aborted → needs_you (reason stop), read by the transcript poll (TranscriptTracker.onCodexTurn → attention.turnEvent) with the same authority — Codex's TUI keeps repainting after it finishes, so the silence heuristic alone would leave it working forever. Codex 0.164+ also reports program status (layer 0), which then owns the terminal, but the rollout's turn end still rules on one thing: a task_complete / turn_aborted while the status says working → needs_you (reason stop). Codex keeps reporting working after a turn while a /goal is active or a background process it started is alive — even at its prompt, waiting for you — and sends only a status that changed, so nothing would ever correct it. blocked, idle (your keystroke) and done stay the status's call, and a turn end changes nothing when the status is one of those.
  3. Terminal bell (generic). A BEL (0x07) in PTY output that is not an OSC/DCS/APC string terminator → needs_you (reason bell). The scanner is a small cross-chunk state machine (ESC ]/P/_/^ opens a string; BEL or ESC \ closes it).
  4. Silence (fallback). Output → working; ≥12 s of quiet after prior output means the terminal is waiting on you → needs_you. For agent spawns always (reason quiet — Claude Code's trust/login prompts fire before any hook does; non-hooked agents sit at their input line). For shells and commands once you have typed in them (reason finished — your command is done); a shell nobody has typed in that just went quiet at its prompt is idle, not a request. Layer 1 disables this once a hook has fired.

needs_you is sticky against output and silence; it clears when you respond (UserPromptSubmit hook or any keystroke) and decays to idle after 2 hours with no response (reason stale, STALE_MS) — a session you walked away from stops shouting. The decay applies to hook-owned terminals too.

Exit: spawnedBy != "manual" → needs_you (reason exit) so automation results land in the queue for review; manual shells exit to idle.

Kill: POST /api/local/terminals/:id/kill marks the terminal idle with reason killed before the daemon hears of it. Whatever the process does on its way out (a last Stop hook, shutdown output, a non-zero exit) changes nothing, and it lands in Finished: you ended it, so there's nothing to review. A run behind the terminal ends too (killedOutcome in local-run-service.ts). An interactive run completes, because closing its session is how it ends. A headless run killed mid-flight stops without a retry: a Task is cancelled, and a Job run is marked "Stopped by user" with its retry budget spent, like a cancel. A Task that already opened a PR follows its PR.

Architecture

Browser ── /ws/local/terminals/:id/stream ──┐
Browser ── REST /api/local/* ───────────────┤
                                            ├── API (relay, DB)  ⇐ outbound WS ⇐  Daemon (optio local up)
Webhook/Schedule/Ticket triggers ───────────┘        /ws/local/daemon               node-pty PTYs in
                                                                                    allowlisted dirs
  • The relay (apps/api/src/services/local-relay.ts) holds a daemon's socket on the API instance it connected to and routes frames by terminalId; with several API instances, viewers and REST calls on the others reach it over Redis (see Several API instances). Browsers never connect to the daemon; the daemon never accepts inbound connections (its hook server binds 127.0.0.1 only).
  • Scrollback lives in the daemon (512 KB ring per terminal), alongside a screen model (@xterm/headless, 2000 lines of scrollback) fed the same bytes. Previews and links are read off the screen model, never off the flattened byte stream: TUIs paint cells, and Claude Code repaints only the cells that changed with absolute cursor moves, so stripping ANSI from the stream glues fragments of different repaints into text that was never on screen (…/jonwi + jump + ns/optio/pull/607, or #6 + jump + 07).
  • Attaching gets the terminal as it stands, not the raw tail of its output: ScreenModel.snapshot serializes the screen model (@xterm/addon-serialize: scrollback, screen, the alternate screen when a full-screen program is up, the cursor, and the modes the program set — mouse tracking plus its SGR encoding, bracketed paste, focus events, a hidden cursor), with output not yet parsed appended raw. The raw tail lost a program's setup once a session had run a while: Claude Code turns on the alternate screen and mouse reporting once at startup, so a viewer attaching after 512 KB of repaints got neither, and wheel and drag scrolled nothing. The scrollback frame names the grid the snapshot was drawn for; the relay sends viewers a replay frame with it just ahead of the bytes. The web lays the snapshot out at that grid, then sizes it for its own screen (xterm reflows, as it would have live). iOS and Android hold the bytes for the size that follows and write them once at the grid they will show (SwiftTerm doesn't reflow). The snapshot also carries colors the program changed (OSC 4 / 10 / 11 / 12).
  • The terminal the programs see is xterm.js, whoever watches: spawns get TERM=xterm-256color and COLORTERM=truecolor (without it Claude Code and Codex fall back to 256 colors and Codex drops most of its own), and lose the variables naming the terminal the daemon was started from (TERM_PROGRAM, TERMINFO, GHOSTTY_*, ITERM_*, TMUX, …): with TERM_PROGRAM=ghostty Claude Code turns on keyboard protocols xterm.js lacks, and TMUX makes programs wrap OSC 52 copies for a tmux that isn't there (TERMINAL_ENV / OUTER_TERMINAL_ENV in terminal-manager.ts). The screen model answers the program's queries — cursor position, device status and attributes, modes, colors (OSC 4 / 10 / 11 / 12, from TERMINAL_THEME in @optio/shared, the web viewer's theme), and the program-status capability (OSC 7501, see "Attention detection") — like tmux does: a PTY has no viewer while nobody watches (Codex asks for the background color as it starts and draws no composer band without an answer) and several when a tab and a phone do, each of which would answer again into the program's input. The hello says answersQueries; the daemon drops any viewer's answers (isTerminalQueryReply), the server doesn't count them as someone using the screen, and the stream's first status frame carries answersQueries so the web viewer doesn't answer at all (silenceQueryReplies in lib/xterm-setup.ts; e2e/terminal-queries.spec.ts). Character widths follow Unicode 11 on both sides (an emoji is two cells, as the program laid it out). The DB stores only metadata plus a throttled preview (last ~12 lines) for the wall view — and, once a terminal exits, its final screen: the daemon sends the same snapshot (≤384 KB) plus the PTY grid right before exit, stored in local_terminal_snapshots (own table, so terminal rows and list responses stay lean; cascades on delete). Opening an exited terminal replays it into the xterm at the recorded grid, so a finished session reads the way it ran instead of as a text preview; the preview is the fallback for rows recorded before snapshots existed.
  • The conversation (local_terminal_transcripts). A screen is not a record of an agent session: Claude Code draws a full-screen TUI, so the bytes that survive its exit are one redraw of the last screen — the last message, not the exchange. The daemon also distills the agent's own transcript into plain entries — every prompt, reply, tool call (name + one-line summary + full input, bounded) with its result (bounded), and thinking — and streams them as transcript frames: every 3 s while the session runs, and once more right before exit. Rows are keyed by the daemon's per-terminal seq, so a re-sent batch is a no-op.
    • Claude Code: the JSONL at the hooks' transcript_path (the same file the usage chip is summed from, cli/src/local/transcript-tracker.ts), also read on every hook. Sidechain (subagent) lines and Claude Code's bookkeeping (slash-command echoes, meta lines) are skipped.
    • Codex: the session rollout ($CODEX_HOME/sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl, cli/src/local/codex-transcript.ts). Codex creates it with the first message and holds it open for the session's life, so the daemon finds it among the open files of a codex process under the terminal's PTY (lsof on macOS, /proc on Linux; codex-sessions.ts) — an agent spawn or a codex typed into a shell alike. Since Codex 0.160 the TUI talks to a machine-wide app-server daemon that holds every rollout open instead, so a Codex holding none is matched by what the rollouts say: the session in the terminal's dir that started with its codex process (else the one written to since — a resume), never one another terminal follows. Codex's own hooks could name it, but Codex asks the person to trust every new hook. Text comes from the rollout's event_msg lines (what the person typed, what the assistant said — user_message / agent_message, or item_completed items from 0.160 — not the <environment_context> and AGENTS.md Codex injects as "user" messages), tool calls and outputs from its response_item lines; subagent threads are skipped. The file's thread id is reported as the session id, so a Codex run can be resumed (codex resume, or codex exec resume for a headless run) and backfilled.
    • Who said it. user is the person typing in the session. Everything else an agent CLI files as a "user" turn is system, with a source: task (a background task or agent reporting back, <task-notification>), agent (another session's message), compact (the summary that replaced the conversation), interrupt, rewind (Codex rolled back), other. Claude Code's newer transcripts say where a turn came from (origin.kind, promptSource, isCompactSummary); older lines are judged by their text, and so are rows stored before sources existed, on read (classifyTranscriptUserText in @optio/shared). The prompt a session was started with (the spawn's prompt, or a claude -p run's) is role user with source prompt, shown as Prompt rather than You. GET /api/local/terminals/:id/transcript serves it; the session page opens a finished agent session on this Chat view (the Terminal toggle brings the recorded grid back), which reflows to any width — a session run on a 132×40 grid reads on a phone. Backfill: a finished Claude Code or Codex session with a session id but no stored entries (it ran under a daemon that predates transcripts, or its hooks never named the file) is read off its machine on demand. The first transcript read asks the host's daemon (transcript-request, only to daemons whose hello set transcriptBackfill); the daemon finds <CLAUDE_CONFIG_DIR or ~/.claude>/projects/*/<session id>.jsonl (Codex: the rollout named after the thread id), refuses a session whose working dir is outside its allowlist, and answers with the whole conversation as transcript-backfill frames addressed to the request id. Meanwhile the read returns backfilling: true and clients poll briefly; a host that had nothing isn't asked again for 10 minutes (cli/src/local/transcript-backfill.ts, requestTranscriptBackfill in local-terminal-service.ts).
  • Live UI updates: content-free nudges {type:"local:changed", terminalId, hostId, userId} on the shared /ws/events stream (that stream is visible to all authenticated users, so no terminal content may ever be published there); clients refetch via REST.
  • Daemon auth: the CLI's existing PAT via Sec-WebSocket-Protocol (optio-auth-<pat>), same as every other WS. The hello's hostId must belong to the authenticated user. Clients may send the moment the socket opens: every WS route holds frames that arrive while it is still authenticating and setting up, then handles them in order (ws/ws-connection.ts; a client that sends more than 256 frames or 4 MB before then is closed with 1008), so the daemon's hello can go out on open.

Several API instances

Any number of API pods may share one Postgres and one Redis (docs/plans/scale-out.md §4). A daemon is one WebSocket on one of them; a viewer, a REST call or a worker that wants it may be on another.

  • Ownership. The instance a daemon's hello lands on becomes the host's owner: it seizes the lease local-host:<hostId> in leases (30 s TTL, renewed every 10 s), held per daemon connection (<instance>#<connection>). "The newest daemon wins": a new connection takes the lease by force and publishes host-taken. host-taken is only a nudge to look: a connection gives the host up (closing its socket with 4000) only when its claim has completed and the lease, read after the message, names another connection; it also finds out when its next renew fails. So two daemons connecting at once leave exactly one, never none. A connection releases only its own lease (by its holder id), even one that closed while its claim was in flight (the offline mark waits for that release), and the host is marked offline only while no connection holds one, so a daemon that already reconnected elsewhere is never marked offline by the old pod's late close.
  • Online and capabilities. Online is the lease: isHostOnline is "this instance has the socket, or the lease is live", and getHost / listHosts / pickOnlineHost read state from the lease in the same query, so every instance says the same; the local_hosts.state column is the last-known state the online / offline alerts and the sweep go by. What the daemon advertised in its hello (claudeCredentials, manageDirs, modelProviders, refreshLimits, transcriptBackfill, answersQueries) is stored on the host row (local_hosts.capabilities) before the lease is taken and read off the rows already loaded (capabilitiesOf; the host list makes no query per host).
  • The bus (services/local-bus.ts): one Redis subscriber per instance, started after listen and retried with backoff; binary envelopes (a JSON header, then raw bytes); messages on a channel arrive in publish order (sharded pub/sub in cluster mode, docs/redis.md). optio:local:host:<hostId>:in carries everything for the daemon (viewer attach, input, resize, view reports, pongs, spawn, kill, dirs, limits, transcript requests) and only the owner subscribes, while it owns the host; every message names the lease holder its sender read, so an old owner mid-handover never acts twice, and messages for a connection that arrive before its claim completes are handled right after it. optio:local:term:<terminalId>:out carries what a terminal's viewers get (output, the attach snapshot, size and status frames); an instance subscribes only while it has a viewer of it. optio:local:reply:<instanceId> carries answers: a frame sent to a daemon elsewhere is acknowledged by its owner. Nobody listening means the host is offline (a spawn parks, a kill settles the row, as locally); an owner that heard it but didn't acknowledge within 5 s means unknown, never "not sent": a spawn stays launching and is never sent again (started settles it, from launching or pending, or the stuck-launching sweep fails it). A daemon's answer to a request (dirs-result, limits-refresh-result, transcript-backfill) is relayed back to the instance that asked and delivered there in order per host. A Claude token never crosses Redis: a refresh asked on another instance runs entirely on the owner (an owner task: ask the daemon, validate, store) and only the outcome travels back; the owner never sends a credentials request on another instance's behalf, nor relays its answer.
  • Viewers. On the owner, a viewer on another instance is a socket-shaped proxy whose frames go out on the terminal's channel, so the attach handshake, the snapshot-then-live ordering and the grid arbiter (local-grid.ts, which stays with the owner, fed by view reports over the bus) work the same for both. The viewer's own instance relays only the frames of the owner it attached through. Every 10 s (one tick at a time, one lease query for every host) each instance reports its remote viewers whose attach has gone out to their owners (who drop the ones no longer reported and ask unknown ones to reconnect) and checks the owner still holds the lease; a viewer whose daemon moved is closed with 4503 and reattaches to the new connection, as the clients do after any host blip. Output reaches Redis only when some viewer is on another instance.
  • Sweeps. The liveness sweep is a BullMQ job scheduler (local-sweep.sweep, every OPTIO_LOCAL_SWEEP_INTERVAL) under the poller:local-sweep lease: hosts whose daemon stopped pinging, or whose lease lapsed (the owning pod died), go offline; terminals parked as host-offline whose host is back are started; launches an online daemon never acknowledged fail.
  • Per instance (caches, never correctness): the transcript-backfill bookkeeping (each instance asks a host at most once per window) and the one-write-a-minute throttle on last_interacted_at (a conditional update across instances, the throttle starting from the stamp as stored). The Claude token's automatic refresh window is a lease (claude-auto-refresh:<hostId>) across instances.
  • Without Redis the relay still works on each instance alone: its own daemons and their viewers.

REST API (all under /api/local, member role for mutations, owner-scoped)

  • POST /api/local/hosts/register — daemon registration: the host it names in hostId (its id from last time), else upsert by (userId, hostname); body {hostId?, name?, hostname, platform, arch, daemonVersion, dirs: [{path, repoUrl?}]} → {host} (see "Identity" under Host)
  • GET /api/local/hosts / DELETE /api/local/hosts/:id — each host carries the live claudeCredentials and manageDirs of its connected daemon (false while offline)
  • PATCH /api/local/hosts/:id — {name?, maxConcurrentAgents?} (1–50): how many agent terminals the machine runs at once; automation agents past it wait in pending / capacity. Raising it starts waiting terminals at once → {host}
  • POST /api/local/hosts/:id/dirs {path} / DELETE /api/local/hosts/:id/dirs?path= — add / remove an allowlisted directory through the machine's daemon (see Host above) → {host, path} with path as the machine resolved it; 400 with the daemon's reason (no such directory, not in the list, a relative path), 409 while the machine is offline or its daemon didn't offer manageDirs, 504 when it doesn't answer within 10 s
  • POST /api/local/hosts/:id/merge — {intoHostId}: one computer registered twice; moves this (offline) host's terminals, automations, and run locations to intoHostId, removes it, and starts terminals that were waiting for it → {host, moved: {terminals, automations, runLocations}}; 409 while the host is connected
  • GET /api/local/terminals?state=&hostId= — caller's terminals (with preview)
  • POST /api/local/terminals — {hostId, dir?, title?, spec?} where spec is {kind:"shell"} | {kind:"command", command} | {kind:"agent", agent, prompt?} (defaults to {kind:"shell"}); optional ticket: {repoId, issueNumber, title, body?, agentType?} — when present, the repo's matching allowlisted dir is resolved (so dir may be omitted), the issue's comments are fetched and appended to the seeded agent prompt, the terminal is linked to the issue, and a "working on this" comment is posted. Dir must be inside the host allowlist.
  • GET /api/local/terminals/:id
  • GET /api/local/terminals/:id/transcript?after=&limit= — the agent session's conversation as {entries, complete, backfilling} (see "The conversation" above); after is a seq, for live polling; backfilling while the host reads a finished session's conversation off disk
  • POST /api/local/terminals/:id/start — spawn a pending terminal
  • POST /api/local/terminals/:id/resume — new interactive terminal resuming the agent's own session (agentSessionId) → 201 {terminal, reused: false}, or 200 {terminal, reused: true} with a resume of that session that hasn't ended; 409 when the session never reported an id
  • POST /api/local/terminals/:id/kill — {signal?} (default SIGTERM); the session finishes (see "Kill" under Attention detection)
  • POST /api/local/terminals/:id/input — {data} (fallback for non-WS input; primary input path is the stream WS)
  • DELETE /api/local/terminals/:id — delete a non-running record
  • GET|POST /api/local/blueprints, GET|PATCH|DELETE /api/local/blueprints/:id — automations (agent, commandTemplate, hostId?, dir?, repoUrl?, spawnMode, sessionMode)
  • POST /api/local/blueprints/:id/spawn — {params?} manual run
  • GET|POST /api/local/blueprints/:id/triggers, PATCH|DELETE /api/local/blueprints/:id/triggers/:triggerId — trigger CRUD (manual | schedule | webhook | ticket | github | gitlab | slack | linear | jira | pylon | pagerduty | sentry | alertmanager | datadog | jenkins — the same fifteen every target takes, see docs/tasks.md "Triggers"), rows in workflow_triggers with target_type = "local_blueprint", served by the shared services/trigger-service.ts. Generic webhook ingress reuses POST /api/hooks/:webhookPath; event ingress is described under "Automations".
  • POST /api/webhooks/slack/events, POST /api/webhooks/linear, POST /api/webhooks/pagerduty, POST /api/webhooks/gitlab, POST /api/webhooks/jira, POST /api/webhooks/sentry — signed event ingress (routes/event-ingress.ts); GitHub events ride the existing POST /api/webhooks/github; Pylon, Alertmanager, Datadog and Jenkins deliveries go to POST /api/hooks/<type>/:triggerId (routes/hooks.ts), checked against that trigger's own secret. Events fan out to every matching trigger whatever it targets (fireEventTriggers in services/event-trigger-service.ts) — a Job or scheduled Task in a pod as well as a Local automation.

Command safety: webhook/trigger payloads never carry commands. Params reach the user-authored command (a blueprint's commandTemplate, or a command Job's) through renderCommandTemplate: each value becomes a shell variable assigned single-quoted on the command's first line (OPTIO_PARAM_title='…'), and each {{title}} only references it — "${OPTIO_PARAM_title}" bare, ${OPTIO_PARAM_title} inside double quotes — so the shell running the command never parses a value as code, bare or inside quotes ({{#if}} blocks are decided on the raw values first, so an empty param drops its block). A second parser still would: a template that hands the value to sh -c "…", ssh host "…", eval, python -c, a pipe into a shell, or bash arithmetic ((( )), $(( )), [[ {{n}} -eq 1 ]], let, array subscripts) is refused when it is saved (services/command-template-check.ts; a stored one keeps running), and a command automation never runs a saved prompt, which other people may edit. Agent prompts are passed as a single quoted argv element, never interpolated into shell syntax; a prompt that starts with - gets a leading space so an event payload can't smuggle in a CLI flag.

Launching agents

cli/src/local/agent-command.ts builds each agent's command line; every value in it is a single shell-quoted argv element.

  • Permissions. Agents skip their permission checks unless the spawn asks for another mode — the same as in a pod, and what work started from Optio (by a person, a trigger, or Ask Optio) needs to run on its own. The spec's permissionMode (the claudePermissionMode / codexPermissionMode catalog field, shown only for runs on a machine) is bypassPermissions by default ("Skip all checks"), auto, or default.
    • Claude Code: bypassPermissions is --dangerously-skip-permissions; auto is --permission-mode auto, where Claude's classifier approves routine actions (edits and commands in the working directory) and blocks risky ones; default ("Ask first") passes --permission-mode default. Without a flag, a headless claude -p starts in Manual mode, where every action that needs approval is denied because nobody can answer the prompt. Claude Code falls back to Manual on its own when auto mode isn't available to the account or model.
    • Codex: bypassPermissions is --dangerously-bypass-approvals-and-sandbox (--yolo is Codex's alias for it); auto keeps Codex in its workspace-write sandbox (-c sandbox_mode="workspace-write": --full-auto is gone from recent Codex releases); default ("Codex's own settings") keeps the machine's own approval and sandbox config. The flag goes on new, headless (codex exec) and resumed sessions alike. A pod runs codex exec --dangerously-bypass-approvals-and-sandbox (the pod is the sandbox).
  • Effort. The spec's effort becomes Claude Code's --effort and Codex's -c model_reasoning_effort="…". The New work form offers it for runs on a machine as well as in pods.
  • What the CLI accepts. The daemon reads claude --help at start and hourly (cli/src/local/cli-probes.ts). An older Claude Code without auto mode or --effort would refuse to start with them, so they're left out for it.
  • Codex's models. On connect and every 6 hours the daemon runs codex debug models (Codex's own catalog, refreshed the way Codex refreshes it, else the list its release ships with; ~/.codex/models_cache.json as a fallback) and sends the models Codex lists in its picker, each with its reasoning efforts and default, in an agent-models frame. The server keeps it on local_hosts.agent_models, and GET /api/agents/openai/options merges it ahead of the baseline (mergeCodexModels): ?hostId= for a run on that machine, else the freshest list any of the caller's machines reported. The picker narrows the effort field to the chosen model's own efforts, and says "Models from Codex on ". Codex runs in pods get the same model and effort (-m, model_reasoning_effort).
  • Model providers (Bedrock). A spec with provider ({kind: "bedrock", providerId, name, region, awsProfile?}; see model providers) runs Claude Code or Codex through Amazon Bedrock with the machine's own AWS credentials. The command is prefixed with env: CLAUDE_CODE_USE_BEDROCK=1 (Claude Code), AWS_REGION / AWS_DEFAULT_REGION, and AWS_PROFILE when the provider names one, set on the command itself so login rc files can't override them; with a named profile, AWS keys exported in the daemon's environment are dropped (env -u) so the profile wins. Codex also gets -c model_provider="amazon-bedrock". The server never sends a credential: it builds the launch from the provider row (createTerminal's modelProviderId) after checking that the terminal's owner may use it. A daemon advertises modelProviders: true in its hello and reports awsProfiles (profile names from ~/.aws/config and ~/.aws/credentials, never keys); the server refuses a provider spawn on a daemon without the capability instead of letting it run on the CLI's own sign-in.

Daemon WebSocket protocol (/ws/local/daemon, JSON text frames)

Daemon → server:

  • {type:"hello", hostId, daemonVersion, dirs, terminals:[{terminalId, running}], claudeCredentials?, transcriptBackfill?, manageDirs?} — first frame; server reconciles DB rows against terminals (rows believed running that the daemon doesn't have → exited, reason daemon_restart) and flushes pending/host_offline spawns.
  • {type:"started", terminalId} / {type:"spawn-error", terminalId, message}
  • {type:"output", terminalId, dataB64} — only while the server holds a subscription
  • {type:"scrollback", terminalId, attachId, dataB64} — snapshot addressed to one viewer's attach; {type:"attach-error", terminalId, attachId, message} when unknown. A terminal whose process has exited stays attachable until its final preview, snapshot and exit are sent (a command like echo hi is done before its pane opens); it is forgotten only after its exit. If the daemon still refuses an attach and the terminal is (or within 3 s becomes) exited, the server sends that viewer the recorded screen instead of the error.
  • {type:"attention", terminalId, state, reason}
  • {type:"preview", terminalId, preview, lastActivityAt} — throttled (≥2 s)
  • {type:"session", terminalId, agentSessionId} — the agent CLI's own session id, once its hooks report it (sent once per terminal); stored on local_terminals.agent_session_id and what POST /api/local/terminals/:id/resume hands back to claude --resume
  • {type:"links", terminalId, links:[{url, kind:"pr"|"issue"|"ref", provider, label}]} — PR / ticket links found anywhere on the screen model (normal buffer + scrollback, plus the alternate screen while a full-screen program is up), merged into every link seen before — a full-screen agent scrolls its own history off the screen, but a PR printed ten minutes ago still identifies the session (extractWorkLinks in @optio/shared: GitHub PRs/issues, GitLab MRs/issues, Linear, Jira; soft wraps are healed by the emulator, hard-wrapped URLs by the scanner — only after lines that reach the terminal's width, so a URL ending a short line isn't glued to digits opening the next; URLs inside OSC 8 hyperlinks are harvested from the raw bytes since Claude Code / gh print #581 with the URL only in the escape; bare #N mentions resolve to the dir's GitHub/GitLab remote as kind ref). One link per PR / ticket (dedupeWorkLinks): a bare #607 seen early and the PR's URL printed later are one PR, and so are owner / repo spellings that differ in case; the most telling link wins. Rides the preview throttle, sent only when the set changes; the server sanitizes (https only, known kinds/providers, ≤50), dedupes again for older daemons, and stores it in local_terminals.links. Terminal responses dedupe once more, for rows stored before, and carry triggerType (github, schedule, …) so a trigger-started session's badge names its source instead of "trigger"
  • {type:"transcript", terminalId, entries:[{seq, role, kind, text, detail, toolName, toolUseId, isError, at}]} — new conversation entries distilled from the agent's transcript (Claude Code), batched (40 per frame), in seq order; sent on hooks, every 3 s while the session runs, and flushed once more just before exit. Accepted only from the owning host while the row is live; the server bounds text (16 KB) / detail (8 KB) and caps a terminal at 20 000 entries
  • {type:"dirs-result", requestId, dirs?, path?, error?} — answer to dirs: the whole allowlist after the change (stored as the host's dirs) and the directory as resolved, or why the daemon refused
  • {type:"transcript-backfill", requestId, terminalId, entries, done, error?} — answer to transcript-request: a finished session's whole conversation read off disk, batched (40 per frame) with seq from 1; done on the last frame, error when there was nothing to send. Stored only when it answers the request in flight for that terminal, from the host it was sent to
  • {type:"snapshot", terminalId, dataB64, cols, rows} — the final screen (ring tail + grid), sent right before exit; its own frame so an oversize one the server drops (>1 MB) can never swallow the exit. Accepted only from the owning host while the row is still live.
  • {type:"exit", terminalId, exitCode}
  • {type:"credentials-result", requestId, token?, expiresAt?, error?} — answer to the server's credentials request (see "Claude token refresh from your machine")
  • {type:"agent-limits", limits:{codex?}} — Codex's newest rate-limit snapshot (see "Usage limits" under Web UI); on connect, every 3 minutes, and a moment after any attention change (a turn ending logs fresh limits)
  • {type:"agent-models", models:{codex?:{models:[{id, label, description?, efforts, defaultEffort}], fetchedAt}}} — the models the machine's Codex offers (see "Launching agents"); sanitized and stored per host
  • {type:"ping"} every 30 s (server updates lastSeenAt, replies {type:"pong"})

Server → daemon:

  • {type:"spawn", terminalId, dir, cols, rows, spec} (spec as in REST; agent specs may carry model, passed to the CLI as --model / -m, effort, and permissionMode (Claude Code; auto when absent) — see "Launching agents" — and mode: "headless" combined with resumeSessionId runs claude -p --resume for Claude Code)
  • {type:"input", terminalId, dataB64} / {type:"resize", terminalId, cols, rows}
  • {type:"kill", terminalId, signal}
  • {type:"attach", terminalId, attachId} / {type:"detach", terminalId} — daemon snapshots the ring buffer and enables live output atomically on attach; the snapshot is routed only to the attaching viewer (no gap, no duplicated history for others)
  • {type:"credentials", requestId} — ask for the machine's Claude OAuth access token
  • {type:"transcript-request", requestId, terminalId, agent, agentSessionId} — read a finished session's conversation off disk (see "Backfill" above)
  • {type:"dirs", requestId, op:"add"|"remove", path} — change the allowlist, as optio local add|remove would on the machine; only sent to daemons whose hello set manageDirs (services/local-dirs-service.ts, cli/src/local/dir-allowlist.ts)
  • {type:"pong"}

Host liveness: sweeper marks hosts offline after 90 s without a ping and fails launching terminals older than 30 s ("spawn timeout, host unreachable").

Browser stream WebSocket (/ws/local/terminals/:id/stream)

Auth: standard WS auth + requireWsRole(member) + terminal ownership. Server → client: binary frames are raw terminal bytes (scrollback replay first, then live); JSON text frames are control: {type:"status", state, attentionState, attentionReason?, answersQueries?} | {type:"size", cols, rows} | {type:"exit", exitCode} | {type:"error", message}. An exited terminal is not attached: the server sends size (the grid the final screen was recorded at), the screen bytes, then exit — in that order, so the viewer lays the grid out before painting. The web pane pins that grid ("Recorded screen 132×40" strip, no "use this screen"), so a click to select text or a window resize can never reflow the replay. A viewer that was streaming when the terminal exited gets exit followed by a size with that recorded grid, so it pins the same way. Client → server (JSON only — no raw-keystroke frames, which eliminates the classic "pasted JSON swallowed as control" bug): {type:"input", data} | {type:"resize", cols, rows} | {type:"view", cols, rows, visible, idleMs, open?}.

Which screen the PTY is sized for. One PTY has one grid, and every viewer of a terminal is its owner on some screen (a laptop tab, a second window, the phone), so the server picks: the screen in use (services/local-grid.ts, per terminal in the relay). Each viewer reports how it sees the terminal in view frames: the grid that fits its screen, whether the terminal is on screen (web: the tab is visible; iOS / Android: the Terminal face is up with the app in front), and how long since its user touched it. open marks an arrival: the pane opened, its tab came to the front, or the user came back after a minute away. On an arrival the PTY is fitted to that screen, unless the screen holding the grid is still in use: on screen, alive, and touched within LOCAL_VIEW_IN_USE_MS (60 s). In that case the newcomer renders the holder's grid scaled to fit, with the "Sized for another device · Use this screen" strip. Typing, a click or tap in the terminal, or "Use this screen" (resize) takes the grid outright, and the holder's own screen changing size resizes the PTY with it. "Alive" is checked, not assumed: a laptop that went to sleep with the session open keeps its socket for minutes, so a holder that looks in use but hasn't been heard from in 5 s gets a WebSocket ping, and stops counting if it doesn't answer within 1.5 s. Every size frame carries yours: true | false per viewer: ours → fit our own screen; not ours → render it scaled. A viewer that leaves frees the grid without handing it on. The next arrival, click, or keystroke takes it, including the same pane reconnecting after a blip. A reconnect only asks for the grid when the pane held it or was used in the last minute, so a restart never hands it to whichever screen reconnects first. Older clients never send view: they count as on screen, count as in use when they type or resize, take the grid only by resizing, and ignore yours. Clients facing an older server (no yours) infer ownership from the echoes of their own resizes, as before.

Web UI

  • /work — local terminals are rows in the unified Work list (the old /local cockpit redirects here; /local?new=1 redirects to /work/new). Paired hosts, the work on each (its terminals, automations, and Tasks / Jobs run there — Work rows carry where.hostId), their directories, and the Automations (blueprints) editor live on /machines, followed by the work running in Optio pods. Add machine there (and "My machine" in the New work form while none is paired) shows the pairing steps with this server's own commands — --server is the API as the page reaches it, sign-in is skipped when auth is off — and watches for the machine to connect (components/local/pair-machine.tsx). Each machine's directories are added and removed there, and the form's Directory list has "+ Add a directory…" (components/local/host-dirs.tsx); a machine that can't take the request shows the optio local add command instead.
  • /local/[id] — focus view: full xterm.js terminal + header (title, host, dir, state, attention, PR / ticket badges, where it came from — GitHub, Slack, Linear, a schedule, … for a trigger-started one — Kill / Start / Delete). Sessions on the Work list (/work) opens it at the session that has waited on you longest, else the most recently active one (sessionScreenTarget in lib/work-feed.ts). Agent sessions with a recorded conversation — and live Claude Code / Codex sessions before their first entry — get a Chat / Terminal toggle (components/local/session-view-toggle.tsx, rule in session-view.ts): a session opened after it finished lands on Chat (components/local/transcript-view.tsx — prompts, markdown replies, tool calls with results folded underneath, thinking collapsed, sticks to the bottom while live); a live session opens on its terminal (on a phone-width screen, on Chat when there is a conversation), and one you watched end stays where it was. While the session runs, Chat has a reply box (components/local/chat-composer.tsx) that writes your text plus Enter to the PTY over POST /api/local/terminals/:id/input. The Job run / Task pages' embedded session does the same. Codex async questions appear above that reply box on web, iOS, and Android, with the supplied choices and a free-text Other answer. Nothing is selected or sent automatically. Answers use the same input endpoint, and a failed send leaves the question available. Terminal rendering and input are unchanged. The existing input handler separates text from Enter to avoid Codex's paste detection; Enter delivers input to an active CLI turn, so an async answer does not wait for the agent to finish. The daemon recognizes request_user_input_async calls and the equivalent AgentMessage.questions rollout item, deduplicating them by call ID. Replies carry {answer, question, questionItemId} inside send_user_message_question_reply; questionItemId is the JSON tuple ["request_user_input_async", callId, index]. Matching structured replies from any client settle that card; a normal user reply dismisses the pending batch. Blank messages, failed sends, and malformed reply envelopes do not dismiss questions. Chat renders replies as readable text. While any question remains unanswered, the API projects Needs your answer (needs_you, reason question) across session lists, Work, Watch and live status. This is derived from stored question/reply/rewind entries, independent of chat pagination and the daemon version. The daemon's execution status stays intact: working or turn-complete reports cannot hide a pending question, and answering the last one (or sending a normal reply) restores the latest status. Rewinds clear questions; killed and exited processes keep their lifecycle status. The iOS Live Activity puts unanswered questions ahead of ordinary pending sessions (oldest first within each group), in both foreground snapshots and server push updates; Later snoozes still take precedence. The terminal's bytes and input are unchanged. This convention was checked against Codex CLI 0.166.0's generated schema and rollout. It is distinct from blocking item/tool/requestUserInput JSON-RPC requests, which still need the terminal. See the official app-server protocol and async tool guidance: the async tool's schema belongs to its host, not the Responses API. Inside a terminal the app sidebar is replaced by the session rail (components/local/terminal-rail.tsx): every terminal grouped as Needs you (oldest wait first) / Working / Idle / Finished, searchable by title, dir, host, or PR / ticket, with badges per row. A thumbtack at a row's top right (shown on hover, next to the side-by-side button) pins the session to the top of its group until you unpin it — kept on the server (POST / DELETE /api/local/terminals/:id/pin, pinnedAt), so every session list and the apps agree (components/local/session-order.ts). Keyboard, captured before xterm: Ctrl/⌘+Shift+↑/↓ previous / next session, Ctrl/⌘+Shift+↵ jump to the oldest "needs you" session, Ctrl/⌘+Shift+B hide / show the rail (also the ⊟ button in the rail header and the ⊞ button in the terminal header; persisted in localStorage, wide screens only — components/local/rail-store.ts). Inside the terminal, Shift+↵ sends ESC CR (what claude /terminal-setup installs) so Claude Code inserts a newline instead of submitting; components/local/conn-state.ts. Links in the terminal — OSC 8 hyperlinks (Claude Code and gh print PR links that way) and URLs in the text — open on ⌘-click (Ctrl-click off a Mac), straight into a new tab with no "Do you want to navigate to…?" prompt; a plain click stays a click in the terminal, and a tap opens on a touch screen (lib/terminal-links.ts, every web terminal). Copying works over a program that tracks the mouse (Claude Code's fullscreen renderer takes every drag): what the program copies itself with OSC 52 (Claude Code's copy-on-select and /copy, tmux) lands on the browser's clipboard, straight away where the browser allows it and on the next ⌘C otherwise (Safari); ⌥-drag (Shift-drag off a Mac) still selects in the terminal for ⌘C. Replayed output never copies, and a program asking to read the clipboard gets no answer (lib/terminal-clipboard.ts, every web terminal; e2e/terminal-clipboard.spec.ts). The iOS and Android apps take OSC 52 the same way. On a Mac, Option keys reach the agent as a Mac terminal sends them (⌥↑ is ESC[1;3A, Codex's key for answering a question or editing a queued message). This relies on apps/web/next.config.ts including xterm.js unparsed: webpack's process polyfill otherwise makes xterm.js believe it runs under Node and drop its Mac key handling (e2e/terminal-keys.spec.ts).
  • Attention from another tab (components/local/attention-watcher.tsx, mounted on every /local* route): the favicon gets a status dot — yellow = a session needs you, green = agents working, grey = quiet — and the tab title a (N) needs-you count. The same yellow / green / grey scheme is used for the attention dots in the rail, rows, and cards. The bell in a session's header arms a browser Notification for that session (per browser, localStorage, components/local/bell-store.ts): it fires the moment the session flips to needs-you unless you're already looking at it, and clicking it focuses the tab on that session. Uses the page-scoped Notification API, so the tab must be open (server Web Push for Local sessions is not wired up yet). All Local pages share one terminals/hosts feed (components/local/local-feed.ts).
  • Usage in the header (components/local/usage-chips.tsx): the gauge pill shows the Claude subscription's 5-hour / 7-day limit utilization (account-wide, from GET /api/auth/usage, polled every minute; the server caches the upstream call for 5 min), turning yellow at 80% and red at 95%. The coin chip is this session's tokens and estimated spend: the daemon reads the transcript_path from Claude Code's hooks and folds the transcript's assistant turns incrementally (cli/src/local/usage-tracker.ts, deduped by message id since Claude Code writes one line per content block), prices them with the public list prices in packages/shared/src/utils/agent-usage.ts, and sends a usage frame; stored on local_terminals.usage. Works for agent spawns and for a claude you start by hand in an Optio shell: the daemon prepends a claude shim (<config>/bin/claude, written by writeClaudeShim) to every spawn's PATH that adds --settings <hook file> unless you passed your own. For zsh the daemon also routes the shell's dotfiles through a ZDOTDIR wrapper (<config>/zsh/, writeZshDotDir) that sources your real .zshenv/.zprofile/.zshrc/.zlogin and then moves the shim back to the front of PATH — otherwise an rc file that prepends ~/.local/bin or asdf shims buries the shim behind the real claude and that terminal silently loses hooks. A daemon started from inside an Optio terminal inherits the outer daemon's shim and wrapper: the shim skips any other Optio shim on PATH (else the two exec each other forever) and the spawn keeps the recorded OPTIO_USER_ZDOTDIR rather than the inherited wrapper (else the wrapper sources itself until zsh's recursion limit). Bash keeps the plain prepend: an rc that resets PATH drops the shim there, and the terminal falls back to the silence heuristic.
  • One status dot per header (StatusDot, statusDescriptor in terminal-card.tsx): lifecycle + attention folded into a single color — purple working, yellow pulse needs you, green completed (exit 0), grey idle/pending/killed/error (sessionTone in attention.ts, shared by card, row, rail and favicon) — with the description on hover. Inside /work/:id the favicon shows that session's dot; on /work it shows the fleet's (yellow beats green beats grey). The (N) title badge is always the fleet's needs-you count.
  • Rename in place: the title in the terminal header is a text box (Enter / blur saves, Escape reverts); PATCH /api/local/terminals/:id { title }.
  • Split view — up to three terminals at once: /local/<primary>?split=<id2>,<id3> (&layout=rows stacks them; phones always stack). Open a pane from the rail row's ⧉ button or Shift+click; each extra pane has a one-line strip with kill / make-primary / close. Open terminal here starts an independent shell on the same host in the session's configured directory. Extra panes appear beneath the primary session in the rail; clicking one focuses it, and ungrouping only closes the view. Making a pane primary keeps the group; navigating to another session leaves it. Grouping is URL state, never a stored parent/child relationship, so another device can open each session independently. State helpers in components/local/split-state.ts, per-pane UI in components/local/terminal-pane.tsx.
  • Pod sessions offer the same Open terminal here action, with up to two extra tmux shells in the existing pod. New shells start in the main terminal's current directory (or the session worktree if there is no main shell). Closing a pane detaches it; ending the session stops every shell. The auxiliary shells share the session's existing access controls and are selected only in that view's URL.
  • Work-link badges (components/local/work-links.tsx) — the daemon-scanned PR / ticket links (plus the spawning ticket) render as badges on cockpit cards, the focus header, and rail rows; each opens in a new tab. The cockpit and rail searches match badge labels and URLs, so a session is findable by the PR or ticket it's working on.
  • Issues page (/issues) gains "Work on locally" next to "Assign to Optio" when an online host advertises a dir whose repoUrl matches the issue's repo.
  • Sidebar: machines live under Library → Machines; Local sessions sit in the one Work list.
  • Overview (/): the dashboard opens with a cross-concept Needs you strip (local terminals waiting on you + repo tasks in needs_attention, oldest wait first — components/dashboard/needs-you.tsx), then one stats strip per concept. Local gets the same strip as the others (needs you / working / idle / finished / hosts online, variant="local") plus cards for live terminals and anything finished in the last 24 h. A paired host with an open terminal counts as "started" — the welcome hero no longer shows just because there are zero repo tasks. Three more overview panels: Usage limits (limits-panel.tsx) shows Claude's live 5h / 7d account utilization next to Codex's — the daemon reads Codex's newest rate_limits snapshot from ~/.codex/sessions/**/rollout-*.jsonl (no token leaves the laptop; cli/src/local/codex-limits.ts), reports it in an agent-limits frame every few minutes, and it lands on local_hosts.agent_limits; the panel labels it "as of " since it only moves when Codex runs, and zeroes a window whose reset has passed. A session's header shows the same numbers (SessionLimitsPills in components/local/usage-chips.tsx): Codex's in a Codex session, Claude's otherwise, and both in a plain terminal on a machine where Codex ran inside its current 5-hour window. Live (live-panel.tsx) is one grid of every open local terminal, interactive session, and awake persistent agent, each linking into its view. Recent (recent-runs.tsx) is a newest-first feed of repo tasks, job runs, and agent turns from GET /api/runs/recent (routes/recent-runs.ts, a workspace-scoped UNION).

CLI

  • optio local up — register host (name defaults to os.hostname()), connect, serve. --no-remote-dirs: Optio can't add or remove this machine's directories.
  • optio local add <dir> / optio local remove <dir> / optio local dirs
  • optio local status — host + terminal summary.
  • Dir list and the host id each server gave this machine persist in ~/.config/optio/local.json ($XDG_CONFIG_HOME/optio/local.json); git remote auto-detected per dir. The host id is the machine's identity: don't copy this file to another computer.

Non-goals / follow-ups (v1)

  • Cost tracking for local terminals (needs transcript-sidecar parsing; column exists).
  • GitHub notifications poller as an alternative to the webhook for review requests (for installs without a public URL) — needs the notifications OAuth scope, which the login flow doesn't request yet.
  • Web push for needs_you transitions (in-app only for now).
  • Terminal survival across daemon restarts (PTYs are daemon children; claude --continue in the same dir is the recovery path).

Codex ChatGPT login from your machine

Codex pod work can use your machine's ChatGPT login as well as an OpenAI API key. In Who → Signed in with → Add credentials → ChatGPT login, choose Use login from machine, or export a short-lived token on macOS and paste it in the same form:

optio local codex-token | pbcopy

On Linux use wl-copy instead of pbcopy; on Windows use clip. The command requires an updated Optio CLI and a Codex CLI signed in with codex login. It asks Codex's stdio app server for getAuthStatus with includeToken and refreshToken, so both file and OS keyring logins work. It emits only the access token. Never paste it into chat, logs, or an issue. The setup wizard offers the same controls.

An updated Local daemon advertises codexCredentials and answers a provider-tagged credentials request. Older daemons continue to support Claude only. Importing selects personal or organization ownership; members can import their own login, and only deployment admins can share a login across the deployment. Tokens are stored encrypted as CODEX_AUTH_TOKEN, with CODEX_AUTH_MODE=chatgpt. No refresh token leaves the machine. Credentials do not cross Redis: the API instance connected to that daemon performs the import and returns only the outcome.

A daemon import remembers its source machine. The token-validation worker refreshes that source when the token has less than ten minutes left, and reconnecting the source checks again. Automatic refresh does not switch ChatGPT accounts. Manual pastes disconnect the source; pasted tokens must be replaced when they expire. Removing a credential or switching sign-in methods stops automatic renewal.

Every Codex run writes an access-only auth.json with mode 600 inside its private CODEX_HOME, which is removed with the run home. Concurrent pods never receive the machine's rotating refresh token. The integration was checked with Codex CLI 0.164.0, including a real access-only inference turn. Background refresh requires the source machine and its updated daemon to be online.

OpenAI documents local login storage and copying a login cache to headless hosts in Codex authentication. Optio shares only the short-lived access credential and leaves renewal on the source machine.

One session workspace for local and pod work

The /work/:id sidebar uses the Local session rail for both locations. Local terminals and pod sessions share search (including agent and location), stable ordering, keyboard switching, Live/Finished groups, and the compact workspace header. Local pins remain server-backed; pod pins are browser preferences scoped to the signed-in user and workspace. Local split groups keep their existing behavior; pod terminal panes stay grouped under their own workspace. Cross-location rows navigate normally rather than passing a pod id to a local terminal API. An explicit Chat/Terminal choice follows navigation within the browser tab where supported. Agent-only pods show Chat; ended pods show their saved conversation. Pod creation time is labeled Created, not elapsed agent execution time.

Repo tasks, standalone Job runs (agents and commands), persistent agents, and PR reviews now use the same workspace at /work/:id. The session rail includes these executions alongside local terminals and interactive pods; saved recurring blueprints remain on their management pages. A linked local terminal represents its task or Job run once in the rail, with exact attempt links preserved. Task PR/pipeline controls, Job output/retry controls, agent turns/configuration, and review findings/submission controls remain in their respective workspace content. Legacy task, agent, review, and Job-run URLs redirect while preserving query parameters and fragments. Non-terminal run pins use the browser's scoped pin preferences; only local terminal rows offer local kill/delete/split actions. Reviews are read from the workspace-scoped stored review list, including submitted history, rather than polling a git provider for every sidebar refresh.