main
John Lauer Publish 0.1.0 d8a45ab

name: hydrogen-ai-threads-api description: >- Open and drive AI conversations in Hydrogen from code over the control API: open a thread, list open ones, put text in a chat box, send a prompt and confirm it landed, reopen or close. Use when asked to open a new claude/codex thread, send a prompt to an AI, or list open AI conversations.

Driving Hydrogen's AI threads from your own app

Hydrogen keeps every open AI conversation (Claude, Codex, Kimi) in one live tree and exposes it over its control API. Anything that can reach that port can do everything the AI Threads panel does: the panel itself is a plain HTTP client with no privileged access, so there is no capability you are missing.

Find the API

The control port is dynamic (it drifts when 47084 is busy), so never hardcode it.

Inside the workspace:

BASE="$(cat ~/.adom/hydrogen-control-url)"      # e.g. http://127.0.0.1:55038
curl -s "$BASE/ai-threads" | jq .

From a Hydrogen panel or webview, ask your own origin: fetch('/ports') returns the resolved control port. If neither is available, the discovery responder answers on the first bindable of 47080, 48080, 49180, 50280 and returns the live control_url.

From outside the workspace (host apps, Adom Bridge, a dock card)

The workspace shares the Linux host's network, so 127.0.0.1 is the same on both sides. On the host, read ~/.config/hydrogen-desktop/ports.json for the live control port, or probe the discovery responder (GET http://127.0.0.1:<c>/ for c in 47080, 48080, 49180, 50280; the first answer carries control_url). Then call the same /ai-threads/* routes. Note: while the AI Threads panel is off (its default), the first driving call wakes the machinery for that session; read-only census calls while parked return ok:false by design.

How it drives the editor on Linux. WebKitGTK has no DevTools protocol, so Hydrogen reaches the workbench and the AI panels through its frame bus: a script in every frame of its webview, in an isolated script world (the DOM is shared with the page, page JS globals are not). Evals, workbench clicks and reading webview DOM are proven on Linux; the end-to-end typing and delivery flows below had not yet been exercised on Linux against a signed-in Claude as of the 2026-11-02 Linux notes. Trust ok and the on-disk delivery check, and report a failure with its _hints rather than retrying blind.

Open a new thread

curl -sX POST "$BASE/ai-threads/new" -H 'content-type: application/json' -d '{}'

Omit type and the user's own preference decides. That is the point: a caller like the dock knows which APP the user clicked, not which AI they like, and hardcoding one imposes a choice that is not yours to make. The default is claude, the workhorse every Adom user is required to have, so the fallback is always something the user actually has installed.

{"ok": true, "type": "claude", "from_default": true, "result": { "via": "keybinding", ... }}
  • type is the AI that was actually used.
  • from_default: true means it came from the setting rather than your request.
  • via: "keybinding" means it opened without flashing the command palette at the user.

THE RESPONSE CARRIES NO THREAD ID, EVER (sid: null, tid: null, explicit since 1.0.143): a new thread has no identity until its first submitted prompt, and the tab itself settles in a background task after this call returns. Do NOT open-then-target: new followed by run-prompt {sid} always fails because there is no sid to pass. To open a thread AND deliver a first prompt, use the ONE-CALL composite:

curl -sX POST "$BASE/ai-threads/run-prompt" -H 'content-type: application/json' \
  -d '{"new": true, "prompt": "Search Mouser for STM32G474", "submit": true,
       "name": "Parts - say it", "tags": ["dock:my-app"]}'

name and tags stage exactly as they do on /new (1.0.143+) and attach when the sid appears; the response verifies delivery against the on-disk transcript (delivered_to). To find a thread you opened earlier, poll GET /ai-threads for your staged name/tags to attach, never guess by position.

Client timeouts: 45 seconds for targeted calls, 120 for the new:true composite. Opening drives the editor (extension command, dual detection, tab placement) and its internal create cap alone is 60s on a busy workbench. A 5-10s client timeout manufactures phantom failures. On a create-timeout error, follow the response's _hints: poll GET /ai-threads for your staged name/tags (a late tab claims them), then deliver by tid; a blind retry opens a duplicate.

Adopt semantics (1.0.143+): when an idle EMPTY Claude tab already exists, the composite delivers into it (adopted_empty_tab: true) instead of asking the editor for a new tab, which is deterministic where the editor's own "new conversation" may reuse an arbitrary tab. Every /ai-threads response also now carries _hints telling the calling AI what happened and how to recover; surface that text in your failure UI.

Name one explicitly only when your feature is genuinely AI-specific:

curl -sX POST "$BASE/ai-threads/new" -H 'content-type: application/json' \
  -d '{"type":"codex","prompt":"review the diff in this repo"}'

prompt is optional and seeds the conversation's first message.

tags is optional and marks the thread as YOURS before it even has an id:

curl -sX POST "$BASE/ai-threads/new" -H 'content-type: application/json' \
  -d '{"tags":["dock","app:kicad"],"prompt":"help me with this board"}'

A brand-new thread has no stable id until its first message creates the conversation, so tags passed here STAGE and attach automatically the moment the id appears (the response carries tags_staged confirming that). Staged tags expire after 10 minutes if no thread materializes, so a failed open cannot mis-tag a stranger.

Read or change the preference (it is a normal setting, so let the user own it):

curl -s "$BASE/ai-threads/settings" | jq .default_ai            # "claude"
curl -sX POST "$BASE/ai-threads/settings" -H 'content-type: application/json' \
  -d '{"default_ai":"kimi"}'

Open the AI's CLI in a terminal tab instead (the caret menu next to each toolbar button does exactly this):

curl -sX POST "$BASE/ai-threads/new-tui" -H 'content-type: application/json' \
  -d '{"type":"claude"}'

A named terminal ("Claude TUI" / "Codex TUI" / "Kimi TUI") opens as an editor tab running that AI's full CLI. TUI threads are FIRST-CLASS rows in the tree (marked tui: true): they list alongside webview threads, and /ai-threads/rename and /ai-threads/close work on them (close also answers VS Code's "terminate running processes?" dialog). Delivery endpoints (run-prompt, inject) do not type into TUIs; drive a TUI conversation in its terminal.

The AI picker: what happens when you do not name the AI (1.0.213)

POST /ai-threads/new and POST /ai-threads/run-prompt {new:true} take an optional type (claude | codex | kimi). Name it and that AI opens, no questions. Leave it out and the USER decides: a picker dialog appears in the shell (the same idea as the Browser Picker) with a 5 second countdown to their default AI, keys 1/2/3, Enter, Escape, and a "remember for this app" checkbox keyed on the thread's app: tag. This is what a dashboard's "Send to AI" hits, so the human chooses where their phrase goes and can switch from Claude to Codex before the countdown fires.

What that means for you as a caller:

  • No answer within 45 s, or the user's setting ai_picker: "never": the default AI is used and the call proceeds as before. You are never stranded.
  • The user cancels: the call returns {ok:false, cancelled:true} and nothing was opened or delivered. Do not retry in a loop; either pass type or tell the user.
  • A Codex or Kimi pick with a prompt: the thread opens through that AI's own command, the fresh tab is found in the census (type matches, no sid yet) and the prompt is typed in; the answer carries tid, inject, and delivered:false with a reason when the tab never surfaced (then POST /ai-threads/inject {tid, text} once GET /ai-threads lists it).
  • To open silently from a thread, pass type. The picker is for humans; an AI that wants a Codex thread says so.
  • A dashboard that belongs to one AI (the Codex, Claude or Antigravity dock apps) passes prefer:"codex" (or claude, kimi): the picker still shows, with THAT AI as the countdown default, beating the user's default and any remembered per-app choice; Enter or the countdown picks it, the user can still choose another. type skips the picker; prefer keeps it.
  • GET /ai-threads/run-prompt/status?job= (1.0.240+) also answers progress (0..1), step, steps (ordered, each done|current|pending|failed), ai (the AI's name), human (a ready toast line), terminal, succeeded, failed, error, surface, picked_by. A dashboard narrates ONE live toast from human + progress and stops on terminal.
  • INJECT INTO AN EXISTING CONVERSATION (1.0.252+): POST /ai-threads/inject {prompt, tid|label|sid, type?, mode?}. mode:front types into the open tab (any of the four; Antigravity via type:"antigravity"), mode:back runs the AI's own CLI headlessly on that session (claude -p --resume, codex exec resume, kimi --print -r; not while that conversation is open in the editor, and never for Antigravity), auto picks front when a tab holds it, else back when sid is given; when back is refused because the conversation is open (Codex's agent panel shows no id, 1.0.254+), auto opens it as its own tab by id and types there. background:true returns a job; done carries answer.
  • antigravity is a target too (Hydrogen 1.0.234+, when the Google Antigravity extension is installed): it opens as an editor tab with a new conversation and the prompt is typed into its chat box and sent. It has no tid: the tab is the thread, and its side bar keeps its own conversation.

POST /ai-threads/settings {ai_picker: "ask"|"never", default_ai: "claude"|"codex"|"kimi", show_kimi: bool} controls it; the AI threads panel's settings expose the first two. The picker offers Claude and Codex; Kimi is hidden unless show_kimi is true (or it is the default), though type: "kimi" always works for a caller that names it.

Know where your prompt went: jobs, status polling, toasts (1.0.218)

Every POST /ai-threads/run-prompt call is a job from its first millisecond, before the picker, the open, or the typing. The answer always carries job and state; poll GET /ai-threads/run-prompt/status?job=<job> about once a second and stop at terminal:true.

# a dashboard's "Send to AI": hand the id back right away, run the rest detached
curl -sX POST "$BASE/ai-threads/run-prompt" -H 'content-type: application/json' \
  -d '{"new":true,"prompt":"open the symbol in kicad","tags":["app:kicad-bridge"],"background":true}'
# -> {"ok":true,"job":"7f2c...","state":"accepted","background":true}

curl -s "$BASE/ai-threads/run-prompt/status?job=7f2c..."
# -> {"ok":true,"state":"picking","terminal":false,"elapsed_ms":1200,"human":"waiting for the AI picker", ...}
# -> {"ok":true,"state":"picked","job":{"type":"codex","picked_by":"user",...},"human":"Codex picked"}
# -> {"ok":true,"state":"delivered","terminal":true,"job":{"result":{...the full call response...}}}

A question is waiting (1.0.607+). When a Claude thread asks with its AskUserQuestion tool, the job goes to needs_you and carries job.question: {questions: [{header, text, options: [{label, description}], multi_select}], at_ms}. Show it to your human or decide yourself, then answer it (1.0.659+) with POST /ai-threads/answer {job|sid|tid, option}: option is a label or a 0-based index, options: [...] for a multi-select, other: "text" for a typed answer, or answers: [{question: <index|header>, option|options|other}, ...] when it asks several questions. It clicks the options and "Submit answers" in that tab, and answers ok once the question is gone (answered lists what was picked; a wrong label returns the real options). With no job/sid/tid it answers the one question showing, and refuses when several threads ask at once. Older builds: answer in the tab. When it is answered the job returns to working and question is gone. A watcher that does not own the job reads GET /claude/conversation-state pending_questions (session id to the same object). Before 1.0.607 a question never left working; four minutes with no change in msgs was the only hint.

The states, in order: accepted -> picking (the picker is up, counting down) -> picked (job.type and job.picked_by: user | default | caller) -> opening -> prefilled (Claude: prompt in the composer) or tab_found (Codex/Kimi; 1.0.258+: seen through the extension's tab push within seconds, adopted_empty_panel:true when the AI's own plain panel was already open, active and empty) -> submitted -> working -> needs_you (a permission or question waits) | done. All four AIs report through hooks once the panel's "Install hook" ran (1.0.255+: Claude and Codex SessionStart / UserPromptSubmit / Stop / Notification; Kimi the same from its config.toml [[hooks]]; Antigravity PreInvocation / Stop with its conversationId, no needs_you, and its backend reads the hooks file only after an editor reload). Without a hook event within 30s a job ends at delivered; an existing tid goes delivering -> delivered | failed. HOW A NEW CODEX/KIMI TAB IS TYPED INTO (1.0.280): one extension command opens it (no editor polling), the extension reveals it by position, the tab's own front webview is located by the editor's DOM join (never a pooled webview of another conversation; if it never mounts the job ends inject_failed with nothing typed anywhere), the prompt is typed once, and the AI's hooks confirm it (a failed typing check with a fresh SessionStart since the attempt counts as landed, never a retype). Steady state measured 2026-09-07: Codex on a parked ConfRoomROG picked 5s, tab 6s, sent 11s, working 13s, done 15s. Failure terminals: cancelled (Escape in the picker), rejected, open_failed, open_unconfirmed, tab_not_found, inject_failed, submit_failed, failed, timeout. Every status answer carries human, a ready-made toast line for that phase ("Codex is working", "Claude Code needs you"), and _hints.states repeats this glossary.

  • background: true returns {job, state: "accepted"} at once. Without it the call blocks through the picker (5 s countdown, up to 45 s) and the open, then returns the same fields; wait: true additionally holds for the Claude turn to finish. It does NOT keep the person's view: delivery still brings the chat's tab to the front.
  • focus: false keeps the person's view (1.0.741+; also on POST /ai-threads/resume). Delivery still has to show the chat for a moment (its chat box only loads when shown, and it takes real keystrokes), so Hydrogen notes the tab in front of every editor group first, delivers, then puts those tabs back, the person's own group last. The answer carries focus_restored: {ok, revealed:[{tid, ok}], unchanged}. Use it for anything unattended: a routine posting into its own thread, a scheduled check-in, a dashboard that should not interrupt.
  • Pass your own job (any string) to correlate a retry, or leave it out and use the one you are given. GET /ai-threads/run-prompt/status with no ?job= lists the 20 most recent jobs, newest first, for a dashboard that lost an id.
  • The shell toasts the pick: "Sending to Codex" or "Sending to Claude Code (your default)" appears in Hydrogen the moment the countdown resolves, so the person sees where the prompt went even when your dashboard is on another screen. POST /ai-threads/new says picked_by in its answer and toasts "Opening Codex" the same way.
  • An AI calling this from a thread should pass type (no picker) and, for anything longer than a one-liner, background:true then poll; human is what to say back to the person.

See what is open

curl -s "$BASE/ai-threads" | jq '.groups[].threads[] | {tid, type, label, sid, instantiated}'
  • tid is the CURRENT position (g0t3). It changes when tabs move, so do not store it.
  • sid is the STABLE conversation id. Store this one.
  • instantiated: false means the tab exists but VS Code has not materialized its webview yet. Text cannot be typed into it until it has been focused once.
  • summary.identity reports how each row was identified, so you can tell a solid row from a guessed one.
  • tags is the thread's durable tag list (see "Tag a thread" below). Filter on it to find the threads that belong to your app: jq '.groups[].threads[] | select(.tags | index("dock"))'.
  • mention (claude rows with a live session) is the thread's cross-session @mention address, e.g. "@project-d5": any other Claude session on the machine can message it by typing that name in its composer.

GET /ai-threads/wait long-polls and returns when the tree changes. Use it instead of polling on a timer.

Put text in a chat box, or send it

# stage it for the human to review, nothing is sent
curl -sX POST "$BASE/ai-threads/inject" -H 'content-type: application/json' \
  -d '{"tid":"g0t1","prompt":"summarize this file","submit":false}'

# send it, and confirm it actually landed in THAT conversation
curl -sX POST "$BASE/ai-threads/run-prompt" -H 'content-type: application/json' \
  -d '{"sid":"<stable id>","prompt":"what model are you?"}'

Two guarantees worth relying on:

  • submit: false really does not send. Prefer it when a human should see the text first.
  • run-prompt confirms delivery by reading the AI's own message list, not by assuming the keystrokes went somewhere. If it says it delivered, it checked.
  • run-prompt {sid} types into the OPEN tab that carries that sid. When no open tab carries it (the conversation is closed, or its tab is not matched yet) it is rejected with "no open editor tab carries sid ...: nothing was delivered" (1.0.659+; older builds said "pass 'tid' or new: true"). For a conversation that is not open, use POST /ai-threads/inject {sid, type, mode:"back"}: its own CLI resumes it headlessly.
  • VS Code's single-tab mode (workbench.editor.showTabs: "single") hides tabs from the tab strip; since 1.0.659 the census reads those groups from adom-vscode's tab list instead (summary.tabs_from: "extension"), so tid, sid, focus and run-prompt work the same.

Typical latency is single-digit to low-double-digit milliseconds against a loaded thread. A thread whose webview has never been materialized costs a few seconds the first time while VS Code creates it, so if you care about that, POST /ai-threads/focus {tid} first.

Rename a thread

POST /ai-threads/rename {tid, name} names a thread; the name is keyed to its stable id, so it survives restarts. For a Claude thread (1.0.614+) it is also Claude's own title: Hydrogen writes the same two lines Claude Code's /rename writes to the session transcript (custom-title, agent-name), so the name shows on the Claude tab and in claude --resume. An open tab reads its title only when it opens, so an idle thread's tab is closed and reopened at once (claude_title.reopened: true); a thread that is answering is left alone (claude_title.busy: true) and shows the name the next time it opens. {reopen: false} skips the reopen. Codex and Kimi keep no title of their own, so their names live in Hydrogen only.

Tag a thread, and find it again forever

Tags are durable strings keyed to the conversation's STABLE id, so they survive restart, drag, rename, close, and reopen. This is how an external app (the dock) re-finds ITS threads without guessing from titles.

# tag an existing thread (ai + sid, or its current tid, or an explicit "<ai>:<sid>" key)
curl -sX POST "$BASE/ai-threads/tag" -H 'content-type: application/json' \
  -d '{"ai":"claude","sid":"<sid>","add":["dock","app:kicad"]}'

# remove one
curl -sX POST "$BASE/ai-threads/tag" -H 'content-type: application/json' \
  -d '{"ai":"claude","sid":"<sid>","remove":["app:kicad"]}'

# the whole store
curl -s "$BASE/ai-threads/tags"

Tags come back on BOTH surfaces, open and closed:

curl -s "$BASE/ai-threads" | jq '.groups[].threads[] | {label, sid, tags}'
curl -s "$BASE/ai-threads/history?tag=app:adom/fusion-bridge"    # server-side filter

Bring the user back to their thread, with a visual cue. highlight: true on focus foregrounds the tab AND pulses its header for about a second, so the user sees WHY this tab just came forward ("this existing thread is why nothing new opened"):

curl -sX POST "$BASE/ai-threads/focus" -H 'content-type: application/json' \
  -d '{"sid":"<sid>","highlight":true}'

A thread with no conversation yet cannot be tagged here (there is no id to key on); pass tags to /ai-threads/new instead and they attach when the id appears.

Route wiki issues into a thread

Associate a thread with a wiki repo and Hydrogen's global notification watcher queues new issues on that thread's row (amber count; the user injects with one click, or opts into auto-inject in Settings):

curl -sX POST "$BASE/ai-threads/repo-link" -H 'content-type: application/json' \
  -d '{"ai":"claude","sid":"<sid>","repo":"adom/adom-shotlog"}'   # repo:"" clears
curl -s "$BASE/ai-threads/repo-links"
curl -s "$BASE/ai-threads/issue-queue"                            # or ?key=<ai>:<sid>
curl -sX POST "$BASE/ai-threads/issue-inject" -H 'content-type: application/json' \
  -d '{"ai":"claude","sid":"<sid>"}'                              # injects the next queued issue

One thread per repo (a new association moves it and reports replaced). Injected issues are framed as bug reports to evaluate, never as instructions, and only an injected issue's notification is marked read.

Reopen a past conversation

curl -s "$BASE/ai-threads/history" | jq '.items[] | {ai, id, title, updated_ms}'
curl -sX POST "$BASE/ai-threads/resume" -H 'content-type: application/json' \
  -d '{"ai":"codex","id":"01a01bfb-a89d-75e0-9f17-01a163ba399b"}'

Add "focus":false to reopen it without changing which tab the person sees (the same restore as run-prompt's).

History lists conversations on disk for all three AIs and EXCLUDES anything currently open, so "in History" means "not open right now". Every AI reopens into a real editor tab.

Close a tab

curl -sX POST "$BASE/ai-threads/close" -H 'content-type: application/json' -d '{"tid":"g0t1"}'

The conversation is not deleted. It moves to History and can be reopened.

Rules that will save you time

  1. Store sid, never tid. tid is a position and moves.
  2. Do not pick an AI on the user's behalf. Omit type unless your feature is genuinely specific to one.
  3. Trust ok, and read the rest. These endpoints verify against real state (a tab appeared, the composer holds exactly your text, the message reached the conversation) and report ok: false with a reason rather than claiming success.
  4. Do not drive the editor UI yourself. Clicking tabs or typing into webviews from outside races Hydrogen's own sweep and will deliver to the wrong conversation. Everything you need is here.
  5. Do not hardcode the port.

Complete example: a dock icon opens a thread about its app

const base = await fetch('/ports').then(r => r.json()).then(p => `http://127.0.0.1:${p.control}`);

async function openThreadFor(app) {
  const r = await fetch(`${base}/ai-threads/new`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    // No `type`: the user's default_ai decides. No prompt if you would rather they type.
    body: JSON.stringify({ prompt: `I just opened ${app.name}. Help me use it.` }),
  }).then(r => r.json());

  if (!r.ok) throw new Error(r.error || 'could not open a thread');
  return r;   // {ok, type, from_default, result:{via, ...}}
}