Files
ai-agent/cli/ai_agent.py

1537 lines
69 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""ai-agent — drive the ai-agent hub from a shell: start conversations, continue
them, wait for their answers, read them back. What a session uses to hand
work to a *real* conversation (visible in the viewer, resumable, on another
machine, account, harness or model) instead of a subagent.
ai-agent new PROMPT|- [--on W] [--model M] [--harness H] [--effort E] [--account A]
[--cwd DIR] [--project P]… [--chrome] [--no-think] [--detach] [--no-report]
[--test] [--wait] [--timeout N] [--json]
ai-agent send ID PROMPT [--model M] [--effort E] [--now] [--fresh] [--wait] …
ai-agent wait ID… [--timeout N] [--json] until each run stops → its final answer
ai-agent show ID [--full | --tail N] [--tools] [--json]
ai-agent ls [--limit N] [--running] [--project P] [--children [ID]] [--json]
ai-agent stop ID
ai-agent fork ID --at MI PROMPT [--model M] [--wait]
ai-agent search QUERY… [--limit N] [--json]
ai-agent past KEY… [--json] earlier conversations on INS-2229 / a PR / a branch
(also on a worker, through its outbox)
ai-agent archive ID [--undo] · ai-agent title ID "…"
ai-agent agents [NAME [PROMPT]]
ai-agent workers · ai-agent usage · ai-agent models
ai-agent budget [--account A] what's left of the week once the crons due are paid
ai-agent projects|skills [WORDS…]
ai-agent plugin <id> <command> … a live plugin's own commands (its plugin.json
`commands`): `ai-agent plugin commands` lists them,
e.g. `ai-agent plugin plans ls`, `… memories show SLUG`,
`… services ls` (the homelab services),
`… cron-jobs ls|add|run|pause …` (cron jobs), Send later:
`… scheduled-conversations add "…" --in 2h [--to ID|.]`
ai-agent inbox what waits on Gabriel + unread pushes
ai-agent worktrees [ls [--stale] | rm DIR… [--force] | clean [--days N] [--yes]]
the git worktrees under ~/worktrees; sweep the stale ones
Every command takes ``--json``. ``--model`` is matched against the hub's
catalog: ``--model qwen`` starts a pi run on Qwen, ``--model "qwen local"``
the EVOX2 one, ``--model gpt-6-sol`` an opencode run.
An ID is a session id (or a unique ≥ 6-char prefix of one), a conversation id
(its UUIDv7 — or the older ``<dir>/<sid>.jsonl`` spelling) or a viewer link
(``…/conversation/<id>``).
A conversation started from inside another one (``$CLAUDE_SESSION_ID``) is
recorded as its child — the hub's subagent, on any harness and model: the hub
stamps ``spawnedBy`` on it, the viewer shows it inside its parent, the hub
enforces the nesting / fan-out limits, and when its turn ends **its final
answer comes back to the parent on its own** (into the live run, else as a new
turn) — so the parent may end its turn instead of blocking in ``wait``. A
``send`` from the parent re-arms it; ``wait`` from the parent claims the
answer (no report twice). ``--no-report`` keeps the link without the report;
``--detach`` starts it unlinked.
A PROMPT of ``-`` is read from stdin (a brief longer than a command line
takes). Handoffs are the Handoff plugin's: its skill starts the successor with
``new --detach`` and links the two (``ai-agent plugin handoff link``).
Talks to the hub at ``AI_AGENT_URL`` (default ``http://127.0.0.1:8096``), as
the owner — the lab's trusted-caller gate. Stdlib only, like notify.py, whose
session resolution it reuses.
"""
from __future__ import annotations
import argparse
import datetime
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from notify import Transport, _mint, host_token, load_env_claude, resolve_session_id # noqa: E402
if __name__ == "__main__":
# The sibling modules' `import ai_agent` is this running script, not a
# second copy with its own HubError (plugin_commands raises the CLI's).
sys.modules.setdefault("ai_agent", sys.modules[__name__])
import plugin_commands # noqa: E402
import plugins_cmd # noqa: E402
import tag_looks # noqa: E402
import worktrees # noqa: E402
VIEW_URL = os.environ.get("AI_AGENT_VIEW_URL", "https://ai-agent.lab.gabvdl.xyz").rstrip("/")
# A guest's run: the guard brokers its plain `ai-agent …` commands (sidecar
# guard.py) and runs them with AIA_AS_SESSION = that run's session id. Every
# call then carries it, and the hub answers as the guest the run is for —
# their own conversations and projects only (backend users/cli.py).
AS_SESSION = os.environ.get("AIA_AS_SESSION", "").strip()
# Set in every process of a guest's run (sidecar launch.py). The CLI calls the
# hub on loopback, where it is the owner — so inside a guest's run it never
# runs at all: the guard's broker runs it *for* the run, outside it, in a
# clean environment that carries AIA_AS_SESSION and no AIA_GUEST. Whatever
# the spelling that got here (a path, quotes, `sh -c`, a Monitor command, a
# pi job without a guard), the answer is the same.
IN_GUEST_RUN = bool(os.environ.get("AIA_GUEST", "").strip())
# What a guest's session may run: the rest is the owner's, or works on this
# host directly (worktrees).
GUEST_COMMANDS = ("new", "send", "fork", "wait", "show", "ls", "search", "stop",
"title", "archive", "inbox", "models", "projects", "budget",
"plugin")
# What a run on a worker may use: the outbox carries one-shot lookups only.
WORKER_COMMANDS = ("past",)
# The broker runs inside a hook with a deadline: a guest's wait is one slice.
GUEST_MAX_WAIT_S = int(os.environ.get("AIA_GUEST_MAX_WAIT_S", "240"))
# How often `wait` re-reads the card. The hub stamps `finished` the moment the
# run's process exits, so a few seconds is the whole latency.
POLL_S = 3
# A card can take a couple of seconds to appear after a spawn (the transcript
# syncs, then gets indexed): `wait` tolerates a missing card this long.
APPEAR_S = 60
# States a run is over in (cards.py `_resolve_state`): anything but running.
LIVE_STATES = ("running",)
_SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
def _err(msg: str) -> None:
print(msg, file=sys.stderr, flush=True)
class HubError(Exception):
def __init__(self, code: int, detail: str):
super().__init__(detail)
self.code = code
self.detail = detail
# ── transport ────────────────────────────────────────────────────────────────
class Hub:
"""The hub's HTTP API. ``base`` / ``headers`` let the MCP endpoint
(backend mcpserver/) reach its own API as the caller a token is for."""
def __init__(self, base: str | None = None, headers: dict | None = None) -> None:
self.base = (base or os.environ.get("AI_AGENT_URL") or "http://127.0.0.1:8096").rstrip("/")
self.headers = dict(headers or {})
if "X-Internal-Auth" not in self.headers and host_token():
# the host token (notify.host_token): loopback isn't a credential
self.headers["X-Internal-Auth"] = host_token()
def call(self, method: str, path: str, body: dict | None = None,
query: dict | None = None, timeout: float = 30):
url = self.base + path
if query:
q = {k: v for k, v in query.items() if v not in (None, "")}
if q:
url += "?" + urllib.parse.urlencode(q)
data = json.dumps(body).encode() if body is not None else None
headers = {"Content-Type": "application/json", **self.headers}
if AS_SESSION:
headers["X-AIA-As-Session"] = AS_SESSION
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
text = r.read().decode(errors="replace")
_guest_view_url(r.headers.get("X-AIA-View-Url"))
except urllib.error.HTTPError as e:
raise HubError(e.code, _detail(e.read().decode(errors="replace"))) from None
except (urllib.error.URLError, OSError) as e:
raise HubError(0, f"hub unreachable at {self.base}: {e}") from None
try:
return json.loads(text) if text else {}
except ValueError:
raise HubError(0, f"not JSON from {path}: {text[:200]}") from None
def get(self, path: str, **query):
return self.call("GET", path, query=query)
def post(self, path: str, body: dict, timeout: float = 60):
return self.call("POST", path, body, timeout=timeout)
def _guest_view_url(url: str | None) -> None:
"""A guest's links open their app (the hub says where), not the owner's."""
global VIEW_URL
if AS_SESSION and url:
VIEW_URL = url.rstrip("/")
def _detail(text: str) -> str:
"""FastAPI's ``{"detail": …}`` (a string or ``{message}``) as one line."""
try:
d = json.loads(text).get("detail")
except (ValueError, AttributeError):
return text[:300]
if isinstance(d, dict):
return str(d.get("message") or d)
return str(d)
# ── ids ──────────────────────────────────────────────────────────────────────
def _sid_of(cid: str) -> str:
"""A legacy ``<dir>/<sid>.jsonl`` id → ``<sid>`` (a uid is returned as is:
prefer the payload's own ``sessionId`` — see :func:`_sid`)."""
return cid.rsplit("/", 1)[-1].removesuffix(".jsonl")
def _sid(row: dict) -> str:
"""A conversation row's session id."""
return row.get("sessionId") or _sid_of(row.get("id") or "")
def resolve(hub: Hub, ref: str) -> dict:
"""The card of the conversation ``ref`` names (see the module doc)."""
ref = ref.strip()
if "/conversation/" in ref:
ref = urllib.parse.unquote(ref.split("/conversation/", 1)[1].split("?")[0].split("#")[0])
sid = _sid_of(ref) if ref.endswith(".jsonl") else ref
if _SID_RE.match(sid):
cards = hub.get("/api/conversations", sessions=sid)["conversations"]
if cards:
return cards[0]
# Not a session id: a conversation id (a UUIDv7) looks the same.
try:
return hub.get("/api/conversation-summary", id=sid)
except HubError as e:
if e.code not in (400, 404):
raise
raise HubError(404, f"no conversation {sid} (yet?)")
if len(sid) < 6:
raise HubError(400, f"ambiguous id {ref!r}: give at least 6 characters")
# The recent page first: the whole list is ~1.5 MB for one id.
for limit in (300, 0):
cards = hub.get("/api/conversations", limit=limit, archived="all")["conversations"]
hits = [c for c in cards if (c.get("sessionId") or "").startswith(sid)]
if hits or len(cards) < limit:
break
if len(hits) == 1:
return hits[0]
if not hits:
raise HubError(404, f"no conversation matches {ref!r}")
raise HubError(400, f"{ref!r} matches {len(hits)} conversations — give more of the id")
def wait_session(hub: Hub, ref: str) -> str:
"""The session id to wait on for ``ref`` (any spelling :func:`resolve`
takes). A full session id the hub hasn't indexed yet — ``new`` prints it
before the card exists — is waited on as is: ``wait_done``'s grace covers
it. A conversation's own id (a UUIDv7) looks just like one, which is why
it must be resolved rather than taken for a session id."""
ref = ref.strip()
try:
return resolve(hub, ref)["sessionId"]
except HubError as e:
if e.code == 404 and _SID_RE.match(ref):
return ref
raise
def view_url(card_or_id) -> str:
cid = card_or_id["id"] if isinstance(card_or_id, dict) else card_or_id
return f"{VIEW_URL}/conversation/{cid}"
# ── rendering ────────────────────────────────────────────────────────────────
def _ago(ts: str | None) -> str:
if not ts:
return "?"
try:
dt = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00"))
except ValueError:
return ts
s = int((datetime.datetime.now(datetime.timezone.utc) - dt).total_seconds())
if s < 90:
return f"{max(s, 0)}s ago"
if s < 5400:
return f"{s // 60}m ago"
if s < 172800:
return f"{s // 3600}h ago"
return f"{s // 86400}d ago"
def _title(card: dict) -> str:
m = card.get("meta") or {}
return (m.get("title") or m.get("resourceTitle") or card.get("title")
or card.get("firstPrompt") or "(untitled)").strip().splitlines()[0]
def card_line(c: dict) -> str:
m = c.get("meta") or {}
where = m.get("worker") or "lab"
cost = f"${c.get('cost') or 0:.2f}"
return (f"{(c.get('sessionId') or '')[:8]} {m.get('state', '?'):<11} "
f"{_ago(c.get('endedAt')):>8} {cost:>7} {where:<8} {_title(c)[:70]}")
def card_head(c: dict) -> str:
m = c.get("meta") or {}
bits = [m.get("state", "?"), c.get("model") or "", m.get("harness") or "",
m.get("account") or "", m.get("worker") or "lab",
f"${c.get('cost') or 0:.2f}", f"ended {_ago(c.get('endedAt'))}"]
parent = (m.get("spawnedBy") or {}).get("sessionId")
lines = [f"# {_title(c)}", " · ".join(b for b in bits if b),
f"session {c.get('sessionId')}", view_url(c)]
if parent:
lines.append(f"started by {parent}")
return "\n".join(lines)
def _messages(thread: list[dict], tools: bool) -> list[dict]:
"""The thread's user/assistant text (and, with ``tools``, a one-line note
per tool call), in order."""
out = []
for it in thread:
kind = it.get("kind")
if kind == "text" and (it.get("text") or "").strip():
out.append(it)
elif tools and kind == "tool_use":
out.append(it)
return out
# A tool call's name: a hub since parser v45 sends the neutral one (`shell`,
# `read`, `edit`, `agent`, `claude:CronCreate` — the hub's
# docs/transcript-format.md "Tool names"); an older hub, Claude Code's. This
# CLI can talk to either, so the old names print as the new ones.
_OLD_TOOL_NAMES = {
"Bash": "shell", "BashOutput": "shell_output", "TaskOutput": "shell_output",
"KillShell": "shell_kill", "TaskStop": "shell_kill",
"Read": "read", "NotebookRead": "read", "Write": "write",
"Edit": "edit", "MultiEdit": "edit", "NotebookEdit": "edit",
"Grep": "grep", "Glob": "glob", "LS": "list_dir",
"WebFetch": "web_fetch", "WebSearch": "web_search",
"Agent": "agent", "Task": "agent", "Skill": "skill",
"TodoWrite": "todo", "TaskCreate": "todo", "TaskUpdate": "todo",
"TaskGet": "todo", "TaskList": "todo", "AskUserQuestion": "ask_user",
"ApplyPatch": "apply_patch", "DeleteFile": "delete_file",
}
def tool_name(name: str | None) -> str:
"""The neutral name of a tool card's ``name``, old or new."""
n = name or "tool"
return _OLD_TOOL_NAMES.get(n, n)
def _tool_note(it: dict) -> str:
inp = it.get("input") or {}
arg = ""
if isinstance(inp, dict):
arg = (inp.get("command") or inp.get("description") or inp.get("file_path")
or inp.get("skill") or inp.get("pattern") or inp.get("url") or "")
arg = " ".join(str(arg).split())[:100]
err = " ✗" if it.get("isError") else ""
return f" → {tool_name(it.get('name'))}{': ' + arg if arg else ''}{err}"
def render_messages(items: list[dict]) -> str:
out = []
for it in items:
if it.get("kind") == "tool_use":
out.append(_tool_note(it))
continue
who = "You" if it.get("role") == "user" else "Claude"
mi = f" [{it['mi']}]" if it.get("mi") is not None else ""
out.append(f"\n## {who}{mi}\n\n{it['text'].strip()}")
return "\n".join(out).strip()
def final_answer(thread: list[dict]) -> str:
"""The last assistant text of the thread — a run's answer."""
for it in reversed(thread):
if it.get("role") == "assistant" and it.get("kind") == "text" and (it.get("text") or "").strip():
return it["text"].strip()
return ""
# Where a session's transcript can be on the lab: every Claude account's
# projects/ (the hub mirrors a worker's under its data dir, AI_AGENT_DATA).
_TRANSCRIPT_ROOTS = ("~/.claude/projects", "~/.claude-*/projects")
def local_transcript(sid: str | None) -> str | None:
"""The session's ``.jsonl`` on this machine, if it is here."""
if not sid or not _SID_RE.match(sid):
return None
import glob
roots = list(_TRANSCRIPT_ROOTS)
if os.environ.get("CLAUDE_CONFIG_DIR"):
roots.insert(0, os.path.join(os.environ["CLAUDE_CONFIG_DIR"], "projects"))
data = os.environ.get("AI_AGENT_DATA")
if data:
roots += [os.path.join(data, "workers", "transcripts"), os.path.join(data, "transcripts")]
for root in roots:
for d in glob.glob(os.path.expanduser(root)):
hits = glob.glob(os.path.join(d, "*", f"{sid}.jsonl"))
if hits:
return hits[0]
return None
def detail(hub: Hub, card: dict) -> dict:
"""The conversation's detail, its messages whole: a message the hub
clipped (``clipped.text``, past 8,000 chars) gets the rest from
``/api/conversation-full-text`` — a few at most, tool output stays cut."""
d = hub.get("/api/conversation", id=card["id"])
for it in d.get("thread") or []:
n = (it.get("clipped") or {}).get("text")
if it.get("kind") != "text" or not n or it.get("clipId") is None:
continue
try:
it["text"] = hub.get("/api/conversation-full-text", id=card["id"],
clip=it["clipId"])["fields"]["text"]
except (HubError, KeyError, TypeError):
it["text"] = (it.get("text") or "") + f"\n… [{n - len(it.get('text') or '')} more chars in the viewer]"
return d
# ── wait ─────────────────────────────────────────────────────────────────────
def wait_done(hub: Hub, sid: str, timeout: float, since: str | None = None) -> dict | None:
"""Poll the card until the run is over; None on timeout. ``since`` (ISO,
when we sent) ignores a stale ``finished`` read before our turn landed.
Each poll names this session as the ``waiter``: a child of ours we find
ended is claimed — its answer is printed here, so the hub doesn't also
report it back into this conversation."""
start = time.monotonic()
me = resolve_session_id(guess=False) or ""
while True:
cards = hub.get("/api/conversations", sessions=sid,
**({"waiter": me} if me else {}))["conversations"]
c = cards[0] if cards else None
if c:
state = (c.get("meta") or {}).get("state")
fresh = not since or (c.get("endedAt") or "") >= since
if state not in LIVE_STATES and fresh:
return c
elif time.monotonic() - start > APPEAR_S:
raise HubError(404, f"conversation {sid} never appeared")
if timeout and time.monotonic() - start > timeout:
return None
time.sleep(POLL_S)
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
def _report_done(hub: Hub, c: dict, as_json: bool) -> None:
d = detail(hub, c)
ans = final_answer(d.get("thread") or [])
if as_json:
print(json.dumps({"sessionId": c["sessionId"], "id": c["id"],
"state": c["meta"].get("state"), "cost": c.get("cost"),
"url": view_url(c), "answer": ans}, ensure_ascii=False))
return
print(card_head(c))
print()
print(ans or "(no answer — the run wrote no text: an API error, a dead key or a stop; "
"the viewer link shows what happened)")
# ── models ───────────────────────────────────────────────────────────────────
def harness_ids(hub: Hub) -> list[str] | None:
"""The hub's active harnesses (its harness plugins, ``GET
/api/providers``) — None when the hub can't say (an older hub, no
access): the harness then goes through as typed."""
try:
resp = hub.get("/api/providers")
except HubError:
return None
ids = [h.get("id") for h in (resp or {}).get("harnesses") or [] if h.get("id")]
return ids or None
def check_harness(hub: Hub, a: argparse.Namespace) -> None:
"""``--harness`` must name an active harness plugin (exit 2 otherwise)."""
h = (getattr(a, "harness", None) or "").strip().lower()
if not h:
return
known = harness_ids(hub)
if known is not None and h not in known:
raise HubError(400, f"unknown harness {h!r} — this hub runs {', '.join(known)}")
a.harness = h
def pick_model(hub: Hub, a: argparse.Namespace, *, set_harness: bool = True) -> None:
"""Turn ``--model`` into a catalog id and, for a new run with no
``--harness``, the harness that serves it — so ``--model qwen`` is a pi
run on Qwen and ``--model "qwen local"`` the EVOX2 one. Words match the
id, label and display name (catalog order: newest first). An id the
catalog doesn't list (an OpenRouter pick) goes through as typed."""
check_harness(hub, a)
want = (getattr(a, "model", None) or "").strip()
if not want:
return
try:
resp = hub.get("/api/models")
except HubError:
return # no catalog: the id goes through as typed
rows, presets = resp.get("models") or [], resp.get("presets") or {}
harness = getattr(a, "harness", None)
if harness:
rows = [m for m in rows if m.get("harness") == harness]
low = want.casefold()
exact = [m for m in rows if low in ((m.get("id") or "").casefold(),
(m.get("alias") or "").casefold(),
(m.get("label") or "").casefold())]
words = low.split()
hits = exact or [m for m in rows if all(
w in " ".join(str(m.get(k) or "") for k in ("id", "label", "displayName")).casefold()
for w in words)]
if not hits:
return
# A model that can't run now (OpenRouter's pi chips while the host's key is
# refused) loses to one that can; named exactly, it still goes through.
m = hits[0] if exact else min(hits, key=lambda h: bool(h.get("unavailable")))
p = presets.get(m.get("key") or "") if set_harness and not harness else None
if p:
# The model decides the harness (Settings → Models): the entry of its
# preset's harness and GPT tier, whichever twin the words hit first.
twins = [r for r in rows if r.get("key") == m.get("key")
and r.get("harness") == p.get("harness")]
m = next((r for r in twins if (r.get("fastMode") or "") == (p.get("fast") or "")),
twins[0] if twins else m)
if m.get("unavailable"):
_err(f"ai-agent: warning — {m['id']}: {m['unavailable']}")
a.model = m.get("alias") or m["id"]
if set_harness and not harness and m.get("harness"):
a.harness = m["harness"]
if a.model != want or (set_harness and not harness and m.get("harness") != "claude"):
_err(f"ai-agent: model {want!r} → {m['id']} ({m.get('harness')}"
f"{' · ' + m['provider'] if m.get('provider') else ''})")
# ── commands ─────────────────────────────────────────────────────────────────
def _run_opts(a: argparse.Namespace) -> dict:
body = {"model": a.model, "effort": a.effort}
if getattr(a, "harness", None):
body["harness"] = a.harness
if getattr(a, "no_think", False):
body["thinking"] = False
if getattr(a, "chrome", None):
body["chrome"] = True
return {k: v for k, v in body.items() if v is not None}
def _started(hub: Hub, a: argparse.Namespace, out: dict, sent_at: str,
reports: bool = False) -> int:
sid = out["sessionId"]
if a.wait:
c = wait_done(hub, sid, a.timeout, since=sent_at)
if not c:
_err(f"ai-agent: still running after {a.timeout}s — `ai-agent wait {sid}`")
return 4
_report_done(hub, c, a.json)
return 0
if a.json:
print(json.dumps({"sessionId": sid, "delivered": out.get("delivered"),
"reportsBack": reports}))
else:
how = " (into the live run's inbox)" if out.get("delivered") == "inbox" else ""
print(f"{sid}{how}")
print(f"{VIEW_URL}/conversations?q={sid}" if not out.get("id") else view_url(out))
if reports:
print("reports back: its final answer comes into this conversation when its "
"turn ends — you may end your turn instead of waiting")
return 0
def cmd_new(a: argparse.Namespace) -> int:
hub = Hub()
pick_model(hub, a)
prompt = sys.stdin.read() if a.prompt == "-" else a.prompt
body = {"prompt": prompt, **_run_opts(a)}
if a.on:
body["worker"] = a.on
if a.account:
body["account"] = a.account
if a.cwd:
body["cwd"] = os.path.abspath(os.path.expanduser(a.cwd))
if a.project:
body["projects"] = a.project
if a.test:
body["test"] = True
# Only a session that is really ours: from a plain terminal the newest
# transcript of the cwd is some other conversation, which would be stamped
# as this one's parent (and count against its children).
parent = "" if a.detach else resolve_session_id(guess=False)
if parent:
body["parent"] = parent
if a.no_report:
body["report"] = False
sent_at = _now_iso()
out = hub.post("/api/spawn", body)
return _started(hub, a, out, sent_at, reports=bool(parent) and not a.no_report)
def cmd_send(a: argparse.Namespace) -> int:
hub = Hub()
c = resolve(hub, a.id)
pick_model(hub, a, set_harness=False)
body = {"sessionId": c["sessionId"], "prompt": a.prompt, **_run_opts(a),
"now": a.now, "fresh": a.fresh}
# Our own child: its answer to this turn reports back too (the hub checks
# the link — anyone else's conversation ignores it).
me = resolve_session_id(guess=False)
if me and me != c["sessionId"]:
body["parent"] = me
sent_at = _now_iso()
out = hub.post("/api/resume", body)
out.setdefault("id", c["id"])
mine = bool(me) and (c["meta"].get("spawnedBy") or {}).get("sessionId") == me
return _started(hub, a, out, sent_at, reports=mine)
def cmd_fork(a: argparse.Namespace) -> int:
hub = Hub()
c = resolve(hub, a.id)
pick_model(hub, a, set_harness=False)
body = {"id": c["id"], "mi": a.at, "prompt": a.prompt, **_run_opts(a)}
sent_at = _now_iso()
out = hub.post("/api/fork", body)
return _started(hub, a, out, sent_at)
def cmd_wait(a: argparse.Namespace) -> int:
hub = Hub()
sids = [wait_session(hub, r) for r in a.ids]
rc = 0
for sid in sids:
done = wait_done(hub, sid, a.timeout)
if not done:
_err(f"ai-agent: {sid} still running after {a.timeout}s")
rc = 4
continue
_report_done(hub, done, a.json)
if len(sids) > 1 and not a.json:
print("\n" + "─" * 60 + "\n")
return rc
def cmd_show(a: argparse.Namespace) -> int:
hub = Hub()
c = resolve(hub, a.id)
d = detail(hub, c)
thread = d.get("thread") or []
if a.json:
msgs = _messages(thread, a.tools)
if not a.full:
msgs = msgs[-a.tail:] if a.tail else []
print(json.dumps({"sessionId": c["sessionId"], "id": c["id"],
"title": _title(c), "state": c["meta"].get("state"),
"cost": c.get("cost"), "url": view_url(c),
"meta": c["meta"], "answer": final_answer(thread),
"messages": [{k: m.get(k) for k in ("role", "kind", "mi", "ts", "text", "name")}
for m in msgs]}, ensure_ascii=False))
return 0
print(card_head(c))
path = local_transcript(c.get("sessionId"))
if path:
print(f"transcript {path}")
if a.full or a.tail:
msgs = _messages(thread, a.tools)
print()
print(render_messages(msgs if a.full else msgs[-a.tail:]))
else:
first = next((it for it in thread if it.get("role") == "user" and it.get("kind") == "text"), None)
if first:
print("\n## Prompt\n\n" + first["text"].strip()[:1500])
print("\n## Last answer\n\n" + (final_answer(thread) or "(none yet)"))
print(f"\n(more: ai-agent show {c['sessionId'][:8]} --full · --tail N · --tools)")
return 0
def cmd_ls(a: argparse.Namespace) -> int:
hub = Hub()
cards = hub.get("/api/conversations", limit=0 if (a.children or a.project) else a.limit,
archived="all" if a.all else "false")["conversations"]
if a.running:
cards = [c for c in cards if c["meta"].get("state") in LIVE_STATES]
if a.project:
cards = [c for c in cards if a.project in (c["meta"].get("projects") or [])
or c.get("project") == a.project]
if a.children:
parent = resolve_session_id() if a.children == "." else resolve(hub, a.children)["sessionId"]
cards = [c for c in cards if (c["meta"].get("spawnedBy") or {}).get("sessionId") == parent]
cards = cards[:a.limit] if a.limit else cards
if a.json:
print(json.dumps([{"sessionId": c.get("sessionId"), "id": c["id"], "title": _title(c),
"state": c["meta"].get("state"), "endedAt": c.get("endedAt"),
"cost": c.get("cost"), "worker": c["meta"].get("worker"),
"projects": c["meta"].get("projects"),
"spawnedBy": (c["meta"].get("spawnedBy") or {}).get("sessionId")}
for c in cards], ensure_ascii=False))
return 0
for c in cards:
print(card_line(c))
if not cards:
_err("ai-agent: no conversations")
return 0
def cmd_stop(a: argparse.Namespace) -> int:
hub = Hub()
c = resolve(hub, a.id)
out = hub.post("/api/interrupt", {"sessionId": c["sessionId"]})
print(f"stopped {c['sessionId']}" if out.get("ok") else f"{c['sessionId']}: nothing running")
return 0
def cmd_archive(a: argparse.Namespace) -> int:
hub = Hub()
c = resolve(hub, a.id)
hub.post("/api/conversation-meta", {"id": c["sessionId"], "archived": not a.undo})
print(f"{'unarchived' if a.undo else 'archived'} {c['sessionId']}")
return 0
def cmd_title(a: argparse.Namespace) -> int:
"""Rename a conversation. As an agent rename: the owner's own rename in the
viewer always wins (``titleSource`` agent, like ``conv title``)."""
hub = Hub()
c = resolve(hub, a.id)
hub.post("/api/conversation-meta", {"id": c["sessionId"], "title": a.title,
"titleSource": "agent"})
print(f"{c['sessionId'][:8]}: {a.title}")
return 0
# `past` on a worker: the hub collects the outbox every ~2 s (a computer on the
# worker link every 4 s) — a minute covers a slow pass.
PAST_TIMEOUT_S = 90
def _past_via_outbox(keys: list[str], sid: str) -> dict:
"""A ``lookup`` outbox item: the hub answers it in the ack."""
t = Transport()
oid = _mint("lkp")
code, res = t.submit("lookup", {"id": oid, "sessionId": sid, "keys": keys})
if code not in (200, 202):
raise HubError(code, f"outbox refused the lookup: {res.get('detail') or res.get('error') or res}")
deadline = time.monotonic() + PAST_TIMEOUT_S
while time.monotonic() < deadline:
code, it = t.status(oid, wait_s=int(min(55, max(1, deadline - time.monotonic()))))
st = it.get("status")
hub = it.get("hub") or {}
if st == "applied":
return hub.get("result") or {}
if st == "failed":
raise HubError(0, hub.get("error") or "the hub refused the lookup")
if code not in (200, 0):
raise HubError(code, f"outbox: {it.get('detail') or it}")
t.cancel(oid)
raise HubError(0, f"no answer from the hub in {PAST_TIMEOUT_S} s (is it polling this worker?)")
def _clip(text: str, n: int) -> str:
text = " ".join((text or "").split())
return text if len(text) <= n else text[:n - 1] + "…"
def _conv_key(hub: Hub, key: str) -> str:
"""``a2533c3a`` (a session or conversation id prefix) → the full
conversation id; any other key as it was."""
if not re.fullmatch(r"[0-9a-f]{6,35}", key) or not re.search(r"[a-f]", key):
return key
try:
return resolve(hub, key)["id"]
except HubError:
return key
def cmd_past(a: argparse.Namespace) -> int:
"""Earlier conversations on a subject — the Linear issue (a PR or an
``ins-2229-…`` branch counts as its issue): the ones running now, then
the newest ended ones (30 days), each with its last message that names
the subject. Backend conversations/past.py."""
sid = a.session or resolve_session_id(guess=False)
keys = [k for k in a.keys if k.strip()]
if not os.environ.get("AI_AGENT_OUTBOX_URL"):
# A conversation's id prefix stands for that conversation (the hub
# reads a full id or a link itself): its issues and PRs.
keys = [_conv_key(Hub(), k) for k in keys]
if os.environ.get("AI_AGENT_OUTBOX_URL"):
res = _past_via_outbox(keys, sid)
else:
res = Hub().get("/api/past-conversations", keys=",".join(keys), session=sid)
if a.json:
print(json.dumps(res, ensure_ascii=False))
return 0
for s in res.get("subjects") or []:
via = [k for k in s.get("sources") or [] if k.upper() != s["label"].upper()]
print(f"## {s['label']}" + (f" (from {', '.join(via)})" if via else ""))
for r in s.get("running") or []:
print(f"RUNNING NOW {_sid(r)[:8]} started {_ago(r.get('startedAt'))} "
f"{_clip(r.get('title') or '', 70)}\n {r['url']}")
for c in s.get("past") or []:
print(f"{(c.get('endedAt') or '')[:10]} {_sid(c)[:8]} {c.get('state') or '?':<9} "
f"{_clip(c.get('title') or '', 70)}\n {c['url']}")
if c.get("excerpt"):
print(f" “{_clip(c['excerpt'], 400)}”")
if not (s.get("running") or s.get("past")):
print(f"(no conversation on it in the last {res.get('maxAgeDays', 30)} days)")
elif s.get("more"):
print(f"(+{s['more']} older)")
if res.get("skipped"):
print(f"not looked up: {', '.join(res['skipped'])}")
return 0
def _machines(hub: Hub) -> dict[str, str]:
"""Worker id → its name, for the rows (none on a hub that won't say)."""
try:
rows = hub.get("/api/workers")
except HubError:
return {}
rows = rows.get("workers", rows) if isinstance(rows, dict) else rows
return {w.get("id"): w.get("name") or w.get("id") for w in rows or [] if isinstance(w, dict)}
_DUR_RE = re.compile(r"(\d+(?:\.\d+)?)\s*([smhdw])")
_DUR_S = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
def _since(spec: str | None, now: datetime.datetime | None = None) -> str | None:
"""``7d`` / ``2w`` / ``12h`` / ``2026-11-01`` → the ISO cut-off, None for none."""
if not spec:
return None
if re.fullmatch(r"\d{4}-\d{2}-\d{2}(T.*)?", spec):
return spec
total = sum(float(n) * _DUR_S[u] for n, u in _DUR_RE.findall(spec))
if not total:
raise HubError(0, f"--since {spec!r}: a duration (7d, 2w, 12h) or a date (2026-11-01)")
now = now or datetime.datetime.now(datetime.timezone.utc)
return (now - datetime.timedelta(seconds=total)).strftime("%Y-%m-%dT%H:%M:%S")
def search_hits(rows: list[dict], words: list[str], *, project: str | None = None,
since: str | None = None) -> tuple[list[tuple], bool]:
"""The search-index rows with every word (title or messages, case-folded),
newest first: ``([(words found, endedAt, row, matching msgs)…], partial)``.
When none has them all, the ones with at least half of them, most words
first (``partial``). ``project`` / ``since`` (:func:`_since`) narrow it.
Shared by ``ai-agent search`` and the MCP's ``search_conversations``."""
cut = _since(since)
hits = []
for r in rows:
if cut and (r.get("endedAt") or "") < cut:
continue
tags = r.get("projects") or []
if project and project != r.get("project") and not any(
t == project or t.split("@")[0] == project for t in tags):
continue
texts = [(m.get("i"), m.get("text") or "") for m in r.get("msgs") or []]
blob = ((r.get("title") or "") + "\n" + "\n".join(t for _, t in texts)).casefold()
found = sum(1 for w in words if w in blob)
if not found:
continue
matching = [(i, t) for i, t in texts if any(w in t.casefold() for w in words)]
hits.append((found, r.get("endedAt") or "", r, matching))
full = [h for h in hits if h[0] == len(words)]
if full or len(words) < 2:
return sorted(full, key=lambda h: h[1], reverse=True), False
floor = max(1, (len(words) + 1) // 2)
return sorted((h for h in hits if h[0] >= floor), key=lambda h: (h[0], h[1]), reverse=True), True
def cmd_search(a: argparse.Namespace) -> int:
"""Every query word in a conversation's title or messages, newest first;
an OR fallback when nobody has them all (said on stderr); ``--project`` /
``--since``; each row says where it ran (:func:`search_hits`)."""
hub = Hub()
words = [w.casefold() for w in " ".join(a.query).split() if w]
rows = hub.get("/api/search-index").get("conversations") or []
hits, partial = search_hits(rows, words, project=a.project, since=a.since)
hits = hits[:a.limit]
names = _machines(hub) if hits and not a.json else {}
if a.json:
print(json.dumps([{"id": r["id"], "sessionId": _sid(r), "title": r.get("title"),
"endedAt": r.get("endedAt"), "worker": r.get("worker"),
"projects": r.get("projects") or [], "words": n,
"hits": len(m), "partial": partial,
"snippets": [{"mi": i, "text": _snippet(t, words)} for i, t in m[:3]]}
for n, _, r, m in hits], ensure_ascii=False))
return 0
if partial and hits:
_err(f"ai-agent: no conversation has all of {' '.join(words)!r} — the closest:")
for n, _, r, m in hits:
where = names.get(r.get("worker"), r.get("worker")) if r.get("worker") else "lab"
tag = f" ({n}/{len(words)} words)" if partial else ""
print(f"{_sid(r)[:8]} {_ago(r.get('endedAt')):>8} {where[:14]:<14} "
f"{(r.get('title') or '')[:64]}{tag}")
for i, t in m[:2]:
print(f" [{i}] {_snippet(t, words)}")
if not hits:
_err("ai-agent: no match")
elif not a.json:
_err("read one: ai-agent show ID (--full, --tail N, --tools for more)")
return 0
def _snippet(text: str, words: list[str], width: int = 110) -> str:
flat = " ".join(text.split())
low = flat.casefold()
at = min((low.find(w) for w in words if w in low), default=0)
start = max(0, at - width // 3)
s = flat[start:start + width]
return ("…" if start else "") + s + ("…" if start + width < len(flat) else "")
# ── agents ──────────────────────────────────────────────────────────────────
def cmd_agents(a: argparse.Namespace) -> int:
hub = Hub()
if a.name:
sent_at = _now_iso()
out = hub.post(f"/api/agents/{urllib.parse.quote(a.name)}/run",
{"prompt": a.prompt or None})
return _started(hub, a, out, sent_at)
rows = [r for r in hub.get("/api/agents").get("agents") or [] if r.get("sourceKind") != "builtin"]
if a.json:
print(json.dumps([{k: r.get(k) for k in ("name", "description", "model", "harness",
"lastRun", "runs", "cost")} for r in rows],
ensure_ascii=False))
return 0
for r in rows:
print(f"{r['name']:<26} {(r.get('model') or ''):<7} {(r.get('description') or '')[:80]}")
return 0
def cmd_cron(a: argparse.Namespace) -> int:
"""The cron jobs left the core on 2026-11-28: they are the Cron jobs
plugin's, and so are their commands (owner and guests alike)."""
_err("ai-agent: `cron` is the Cron jobs plugin's — run: ai-agent plugin cron-jobs "
"<command> (ls, show, add, edit, pause, resume, run, rm; "
"`ai-agent plugin cron-jobs --help`)")
return 2
# ── runners, accounts, usage ─────────────────────────────────────────────────
def cmd_workers(a: argparse.Namespace) -> int:
rows = Hub().get("/api/workers").get("workers") or []
if a.json:
print(json.dumps([{k: w.get(k) for k in ("id", "name", "status", "account", "platform",
"running", "lastSeen", "cwd")} for w in rows],
ensure_ascii=False))
return 0
print(f"{'local':<14} {'lab':<22} online (the host sidecar)")
for w in rows:
print(f"{w['id']:<14} {w.get('name', '')[:22]:<22} {w.get('status', '?'):<8} "
f"{w.get('account') or '':<9} {w.get('running') or 0} running")
return 0
def cmd_usage(a: argparse.Namespace) -> int:
hub = Hub()
lim = hub.get("/api/usage/limits").get("accounts") or {}
health = {h["id"]: h for h in hub.get("/api/accounts/health").get("accounts") or []}
if a.json:
print(json.dumps({k: {"windows": {w: v.get("pct") for w, v in (u.get("windows") or {}).items()},
"status": (health.get(k) or {}).get("status"),
"limited": (health.get(k) or {}).get("limited")}
for k, u in lim.items()}))
return 0
names = {"five_hour": "5h", "seven_day": "week"}
for k in sorted(set(lim) | set(health)):
u, h = lim.get(k) or {}, health.get(k) or {}
wins = " ".join(f"{names.get(w, w)} {v.get('pct', 0):.0f}%"
for w, v in (u.get("windows") or {}).items())
flag = "" if h.get("status") in (None, "ok") else f" ⚠ {h.get('status')}"
flag += " ⚠ at its limit" if h.get("limited") else ""
print(f"{k:<14} {wins or '-':<22}{flag}")
return 0
def _tok(n: float | None) -> str:
if not n:
return "-"
return f"{n / 1e9:.1f} Gtok" if n >= 1e9 else f"{n / 1e6:.0f} Mtok"
def guest_budget(a: argparse.Namespace) -> int:
"""A guest's budget: their month on the owner's account, and their own
Claude login when they connected one (runs go there first)."""
me = Hub().get("/api/me")
if a.json:
print(json.dumps({k: me.get(k) for k in ("budgetUsd", "spentUsd", "models", "claude")},
ensure_ascii=False))
return 0
cap, spent = me.get("budgetUsd"), me.get("spentUsd") or 0
left = f" · ${max(cap - spent, 0):.2f} left" if cap is not None else ""
print(f"this month ${spent:.2f}{f' of ${cap:.2f}' if cap is not None else ''}{left} "
f"(runs on the owner's account)")
print(f"models {', '.join(me.get('models') or []) or '—'}")
own = me.get("claude") or {}
if own.get("connected"):
print(f"own login connected{' · ' + own['status'] if own.get('status') else ''} — "
"runs go there first (any model, outside this budget)")
return 0
def cmd_budget(a: argparse.Namespace) -> int:
if AS_SESSION:
return guest_budget(a)
b = Hub().get("/api/usage/budget", account=a.account)
if a.json:
print(json.dumps(b, ensure_ascii=False))
return 0
if not b.get("window"):
_err(f"ai-agent: no usage reading for {a.account}")
return 1
rate, left, up, free, pace = (b.get(k) or {} for k in ("rate", "left", "upcoming",
"free", "pace"))
fams = b.get("families") or {}
plan = (b.get("plan") or {}).get("label") or ""
reset = (datetime.datetime.fromtimestamp(b["resetsAt"]).strftime("%a %d %b %H:%M")
if b.get("resetsAt") else "?")
usd = lambda v: f" ≈ ${v:,.0f}" if v is not None else "" # noqa: E731
stale = " ⚠ stale reading" if b.get("stale") else ""
print(f"{b['account']} · {plan} · week {b['pct']:.0f}% · resets {reset} "
f"(in {b['hoursLeft']:.1f}h){stale}")
per = " · ".join(f"{_tok(fams[f].get('tokensPerPct'))} {f}" for f in ("opus", "fable", "sonnet")
if fams.get(f, {}).get("tokensPerPct"))
print(f"rate 1% ≈ {rate.get('unitsPerPct', 0):.1f} units{usd(rate.get('usdPerPct'))}"
f" ({rate.get('source')}){' · ' + per if per else ''}")
print(f"left {left.get('pct', 0):5.1f}% {left.get('units', 0):7.0f} units{usd(left.get('usd'))}")
items = up.get("items") or []
print(f"due {up.get('pct', 0):5.2f}% {up.get('units', 0):7.1f} units "
f"({sum(i['runs'] for i in items)} runs before the reset)")
for i in items[:12]:
when = datetime.datetime.fromtimestamp(i["next"]).strftime("%a %H:%M")
guess = "" if i.get("sampled") else " (guess)"
print(f" {i['kind']:<9} {i['name'][:28]:<28} ×{i['runs']:<3} "
f"{i['unitsPerRun']:6.2f} u/run{guess} next {when}")
buys = " · ".join(f"{_tok(fams[f].get('freeTokens'))} {f}" for f in ("opus", "fable", "sonnet")
if fams.get(f, {}).get("freeTokens"))
print(f"free {free.get('pct', 0):5.1f}% {free.get('units', 0):7.0f} units"
f"{usd(free.get('usd'))}{' = ' + buys if buys else ''}")
seen = pace.get("last6h") if pace.get("last6h") is not None else pace.get("last24h")
if seen is not None:
print(f"pace {seen:.2f}%/h now → {pace.get('projected', 0):.0f}% at the reset · "
f"{pace.get('needed') or 0:.2f}%/h uses it all")
elif pace.get("needed") is not None:
print(f"pace {pace['needed']:.2f}%/h uses it all")
streams = " · ".join(
f"{fams[f]['streams']:.1f} {f} ({fams[f]['unitsPerHour']:.0f} u/h"
f"{'' if fams[f].get('rateRuns') else ', default'})"
for f in ("opus", "fable", "sonnet") if fams.get(f, {}).get("streams") is not None)
if streams:
print(f"streams {streams} running nonstop until the reset")
return 0
def cmd_models(a: argparse.Namespace) -> int:
rows = Hub().get("/api/models").get("models") or []
if a.json:
print(json.dumps(rows))
return 0
for m in rows:
print(f"{m.get('harness', ''):<9} {m.get('alias') or m['id']:<14} {m.get('displayName', '')}")
return 0
# ── knowledge ────────────────────────────────────────────────────────────────
def _matches(row: dict, query: list[str], keys: tuple) -> bool:
blob = " ".join(str(row.get(k) or "") for k in keys).casefold()
return all(w.casefold() in blob for w in query)
def _listing(a: argparse.Namespace, rows: list[dict], keys: tuple, line) -> int:
rows = [r for r in rows if _matches(r, a.query, keys)]
if a.json:
print(json.dumps(rows, ensure_ascii=False, default=str))
return 0
for r in rows:
print(line(r))
if not rows:
_err("ai-agent: nothing matches")
return 0
def _goal(g) -> str:
return f"{g['done']}/{g['total']}" if isinstance(g, dict) and g.get("total") else "-"
def cmd_projects(a: argparse.Namespace) -> int:
rows = Hub().get("/api/projects").get("projects") or []
return _listing(a, rows, ("name", "description", "url", "keywords"), lambda r: (
f"{r['name']:<26} {_goal(r.get('goal')):>6} {(r.get('url') or '-'):<40} "
f"{(r.get('description') or '')[:60]}"))
def cmd_services(a: argparse.Namespace) -> int:
"""The homelab services left the core on 2026-11-28: the catalogue is the
services plugin's, and so are its commands."""
_err("ai-agent: `services` is the Services plugin's — run: ai-agent plugin services <command> "
"(ls, show SLUG; `ai-agent plugin services --help`)")
return 2
SCHEDULED_MOVED = {
"later": 'add "…" --in 2h|--at HH:MM [--to ID|.]',
"scheduled": "ls [--all]",
"unschedule": "cancel SCH_ID",
}
def cmd_scheduled_moved(a: argparse.Namespace) -> int:
"""Send later left the core on 2026-11-28: ``later`` / ``scheduled`` /
``unschedule`` are the Scheduled conversations plugin's commands (no
alias — this only says where they went)."""
_err(f"ai-agent: `{a.cmd}` is the Scheduled conversations plugin's now — run: "
f"ai-agent plugin scheduled-conversations {SCHEDULED_MOVED[a.cmd]}")
return 2
def cmd_skills(a: argparse.Namespace) -> int:
rows = [r for r in Hub().get("/api/skills").get("skills") or [] if r.get("sourceKind") != "builtin"]
return _listing(a, rows, ("name", "description", "triggerWords"), lambda r: (
f"{r['name']:<24} {r.get('count') or 0:>5}× {(r.get('description') or '')[:90]}"))
# ── feedback inbox ───────────────────────────────────────────────────────────
def waiting(hub: Hub) -> list[dict]:
"""What waits on Gabriel, oldest first: open ask-form forms, plugin
inbox-waiting items, and unanswered asks — the home page's *Waiting for
feedback* (frontend lib/waiting.ts)."""
out = []
seen = set()
for f in hub.get("/api/ask-form/forms", status="pending").get("forms") or []:
seen.add(f["id"])
out.append({"kind": "form", "id": f["id"], "title": f.get("title"),
"at": f.get("createdAt"), "sessionId": f.get("sessionId")})
try:
for p in hub.get("/api/inbox/waiting").get("items") or []:
pid = p.get("formId") or p.get("id")
if pid and pid not in seen:
seen.add(pid)
out.append({"kind": p.get("kind") or "form", "id": pid,
"title": p.get("title"), "at": p.get("at"),
"sessionId": p.get("sessionId")})
except Exception:
pass
now = _now_iso()
for n in hub.get("/api/notify-log", limit=200).get("notifications") or []:
if n.get("kind") == "ask" and n.get("status") == "pending" and (n.get("expiresAt") or "~") > now:
out.append({"kind": "ask", "id": n["id"], "title": n.get("body"),
"options": n.get("options"), "at": n.get("at"),
"sessionId": n.get("sessionId")})
return sorted(out, key=lambda x: x.get("at") or "")
def cmd_inbox(a: argparse.Namespace) -> int:
hub = Hub()
items = waiting(hub)
# The unread pushes are the owner's read ledger; a guest's are in their app.
unread = {} if AS_SESSION else hub.get("/api/notifications/unread")
if a.json:
print(json.dumps({"waiting": items, "unread": unread.get("notifications") or [],
"unreadCount": unread.get("total", unread.get("count"))},
ensure_ascii=False))
return 0
print(f"Waiting for feedback ({len(items)})")
for x in items:
print(f" {x['kind']:<4} {(x.get('sessionId') or '')[:8]:<8} {_ago(x.get('at')):>8} "
f"{' '.join((x.get('title') or '').split())[:80]}")
notes = unread.get("notifications") or []
print(f"\nUnread notifications ({unread.get('total', len(notes))})")
for n in notes[:a.limit]:
print(f" {_ago(n.get('at')):>8} {' '.join((n.get('title') or '').split())[:50]:<50} "
f"{(n.get('convTitle') or '')[:40]}")
return 0
# ── parser ───────────────────────────────────────────────────────────────────
def _run_flags(p: argparse.ArgumentParser, *, new: bool) -> None:
p.add_argument("--model", help="opus | sonnet | haiku | fable | a full id")
p.add_argument("--effort", help="low | medium | high | xhigh | max")
p.add_argument("--no-think", action="store_true", help="extended thinking off")
p.add_argument("--chrome", action="store_true", default=None,
help="launch with --chrome (drive the paired browser)")
if new:
p.add_argument("--harness", type=str.lower, metavar="HARNESS",
help="any active harness plugin (claude, pi, opencode, agy… — "
"GET /api/providers); default: the model's")
p.add_argument("--wait", action="store_true",
help="block until the run stops, then print its final answer")
p.add_argument("--timeout", type=int, default=3600,
help="--wait gives up after N s (exit 4; default 3600)")
p.add_argument("--json", action="store_true")
# ── worktrees ────────────────────────────────────────────────────────────────
def _with_sessions(hub: Hub, ws: list) -> None:
"""Attach the conversations that recorded each worktree — state + title,
from their cards (a card's state is the live one; the raw meta lags)."""
by_dir = worktrees.owners(hub.get("/api/conversation-meta").get("meta") or {})
sids = sorted({s for w in ws for s in by_dir.get(w.dir, ())})
cards: dict[str, dict] = {}
for i in range(0, len(sids), 40): # a handful per call keeps the URL short
for c in hub.get("/api/conversations", sessions=",".join(sids[i:i + 40]))["conversations"]:
cards[c.get("sessionId")] = c
for w in ws:
w.sessions = [{"sessionId": s,
"state": ((cards.get(s) or {}).get("meta") or {}).get("state"),
"title": _title(cards[s]) if s in cards else None}
for s in by_dir.get(w.dir, ())]
def _pick_worktrees(ws: list, refs: list[str]) -> list:
"""The worktrees ``refs`` name: a directory name, a path, or a unique
prefix of a name."""
out = []
for ref in refs:
name = os.path.basename(ref.rstrip("/"))
hits = [w for w in ws if w.dir == name] or [w for w in ws if w.dir.startswith(name)]
if not hits:
raise HubError(404, f"no worktree {ref!r} under {worktrees.ROOT}")
if len(hits) > 1:
raise HubError(400, f"{ref!r} matches {', '.join(w.dir for w in hits)}")
out.append(hits[0])
return out
def _remove_worktree(hub: Hub, w, force: bool, keep_branch: bool) -> bool:
try:
lines = worktrees.remove(w, force=force, keep_branch=keep_branch)
except RuntimeError as e:
_err(f"ai-agent: {e}")
return False
# Strike it through on every conversation that recorded it.
for s in w.sessions:
try:
hub.post("/api/conversation-meta",
{"id": s["sessionId"], "worktree": {"dir": w.dir, "removedAt": _now_iso()}})
except HubError as e:
_err(f"ai-agent: {w.dir}: couldn't stamp {s['sessionId'][:8]}: {e.detail}")
for line in lines:
print(f"{w.dir}: {line}")
return True
def cmd_worktrees(a: argparse.Namespace) -> int:
hub = Hub()
ws = worktrees.scan(size=a.size)
_with_sessions(hub, ws)
if a.action == "rm":
if not a.targets:
raise HubError(0, "worktrees rm: which? (`ai-agent worktrees` lists them)")
rc = 0
for w in _pick_worktrees(ws, a.targets):
why = worktrees.unsafe(w)
if why and not a.force:
_err(f"ai-agent: kept {w.dir}: {why} (--force removes it anyway)")
rc = 1
continue
rc |= 0 if _remove_worktree(hub, w, a.force, a.keep_branch) else 1
return rc
why = {w.dir: worktrees.verdict(w, a.days, a.unmerged_days) for w in ws}
stale = [w for w in ws if why[w.dir] is None]
if a.action == "clean":
if a.json and not a.yes:
print(json.dumps([w.as_dict() for w in stale], ensure_ascii=False))
return 0
if not stale:
print("nothing stale")
return 0
if not a.yes:
for w in stale:
print(worktrees.fmt_row(w, None))
print(f"\n{len(stale)} stale — dry run: `ai-agent worktrees clean --yes` removes them")
return 0
ok = sum(_remove_worktree(hub, w, False, a.keep_branch) for w in stale)
print(f"removed {ok} of {len(stale)}")
return 0 if ok == len(stale) else 1
rows = stale if a.stale else ws
if a.json:
print(json.dumps([{**w.as_dict(), "keep": why[w.dir]} for w in rows], ensure_ascii=False))
return 0
for w in rows:
print(worktrees.fmt_row(w, why[w.dir]))
print(f"\n{len(ws)} worktrees, {len(stale)} stale"
+ (" — `ai-agent worktrees clean` lists what it would remove" if stale else ""))
return 0
def cmd_tags(a: argparse.Namespace) -> int:
try:
return tag_looks.cmd(Hub(), a)
except ValueError as e:
raise HubError(0, str(e)) from None
def cmd_plugin(a: argparse.Namespace) -> int:
hub = Hub()
if a.action == "commands":
return plugin_commands.list_cli(hub, a.json)
if a.action == "call":
if not (a.target and a.extra):
raise HubError(0, "ai-agent plugin call <id> <action> [--payload JSON|-] [--get]")
return plugin_commands.call_cli(hub, a.target, a.extra, a.payload, a.get)
return plugins_cmd.run(a, lambda m, path, body=None: hub.call(m, path, body))
def _plugin_hint(argv: list[str], known) -> str | None:
"""``ai-agent plans`` when ``plans`` is no core command but an active
plugin with commands: say where its commands live."""
if not argv or argv[0] in known or argv[0].startswith("-"):
return None
try:
cmds = [c for c in plugin_commands.catalogue(Hub()) if c.get("plugin") == argv[0]]
except HubError:
return None
if not cmds:
return None
names = ", ".join(c["name"] for c in cmds)
return (f"ai-agent: `{argv[0]}` is the {cmds[0].get('pluginName') or argv[0]} plugin's — "
f"`ai-agent plugin {argv[0]} <command>` ({names}; "
f"`ai-agent plugin {argv[0]} --help`)")
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(prog="ai-agent", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = p.add_subparsers(dest="cmd")
n = sub.add_parser("new", help="start a conversation")
n.add_argument("prompt")
n.add_argument("--on", metavar="WORKER", help="runner: a worker id or name, or 'local'")
n.add_argument("--account", help="the login it bills (default: the runner's ★)")
n.add_argument("--cwd", help="working directory on the runner")
n.add_argument("--project", action="append", help="tag a project (repeatable)")
n.add_argument("--detach", action="store_true",
help="don't record it as this conversation's child")
n.add_argument("--no-report", action="store_true",
help="a child whose final answer does NOT come back into this "
"conversation on its own (read it with `wait`/`show`)")
n.add_argument("--test", action="store_true",
help="a throwaway run to test something: archived once its turn "
"ends, whatever the outcome (wait/show still read it)")
_run_flags(n, new=True)
n.set_defaults(fn=cmd_new)
s = sub.add_parser("send", help="continue a conversation with a new turn")
s.add_argument("id")
s.add_argument("prompt")
s.add_argument("--now", action="store_true",
help="stop a live run and send now (default: queue into its inbox)")
s.add_argument("--fresh", action="store_true", help="compact the session first")
_run_flags(s, new=True)
s.set_defaults(fn=cmd_send)
f = sub.add_parser("fork", help="branch a new conversation off a message")
f.add_argument("id")
f.add_argument("prompt")
f.add_argument("--at", type=int, required=True, metavar="MI",
help="message ordinal to replace (the [n] in `ai-agent show --full`)")
_run_flags(f, new=True)
f.set_defaults(fn=cmd_fork)
w = sub.add_parser("wait", help="block until runs stop, print their answers")
w.add_argument("ids", nargs="+", metavar="ID")
w.add_argument("--timeout", type=int, default=3600)
w.add_argument("--json", action="store_true")
w.set_defaults(fn=cmd_wait)
sh = sub.add_parser("show", help="a conversation: header + prompt + last answer")
sh.add_argument("id")
sh.add_argument("--full", action="store_true", help="every message")
sh.add_argument("--tail", type=int, default=0, metavar="N", help="the last N messages")
sh.add_argument("--tools", action="store_true", help="include one line per tool call")
sh.add_argument("--json", action="store_true")
sh.set_defaults(fn=cmd_show)
ls = sub.add_parser("ls", help="list conversations, newest first")
ls.add_argument("--limit", type=int, default=20)
ls.add_argument("--running", action="store_true")
ls.add_argument("--project")
ls.add_argument("--children", nargs="?", const=".", metavar="ID",
help="the ones started by ID (default: this conversation)")
ls.add_argument("--all", action="store_true", help="include archived")
ls.add_argument("--json", action="store_true")
ls.set_defaults(fn=cmd_ls)
st = sub.add_parser("stop", help="interrupt a running conversation")
st.add_argument("id")
st.set_defaults(fn=cmd_stop)
se = sub.add_parser("search", help="find conversations by words in their messages")
se.add_argument("query", nargs="+")
se.add_argument("--limit", type=int, default=10)
se.add_argument("--project", help="only conversations tagged with this project or service")
se.add_argument("--since", metavar="WHEN", help="ended since: 7d, 2w, 12h or 2026-11-01")
se.add_argument("--json", action="store_true")
se.set_defaults(fn=cmd_search)
pa = sub.add_parser("past", help="earlier conversations on a Linear issue / PR / branch / conversation")
pa.add_argument("keys", nargs="+", metavar="KEY",
help="INS-2229, a PR link or #number, an ins-2229-… branch, or a conversation "
"(its id, a prefix, a viewer link: the issues and PRs it is about)")
pa.add_argument("--session", help="the asking conversation (default: this one)")
pa.add_argument("--json", action="store_true")
pa.set_defaults(fn=cmd_past)
ag = sub.add_parser("agents", help="list .claude/agents definitions, or run one now")
ag.add_argument("name", nargs="?", help="run this agent now")
ag.add_argument("prompt", nargs="?", help="what it should do this time (appended)")
_wait_flags(ag)
ag.set_defaults(fn=cmd_agents)
cr = sub.add_parser("cron", help="moved: `ai-agent plugin cron-jobs <command>`")
cr.add_argument("rest", nargs=argparse.REMAINDER)
cr.set_defaults(fn=cmd_cron)
wk = sub.add_parser("workers", help="runners: the lab + paired workers, online or not")
wk.add_argument("--json", action="store_true")
wk.set_defaults(fn=cmd_workers)
ug = sub.add_parser("usage", help="plan usage %% per account, signed-out / limited flags")
ug.add_argument("--json", action="store_true")
ug.set_defaults(fn=cmd_usage)
bg = sub.add_parser("budget", help="what's left of the week: free %%, units, tokens, "
"after the crons/scheduled runs due before the reset")
bg.add_argument("--account", default="personal")
bg.add_argument("--json", action="store_true")
bg.set_defaults(fn=cmd_budget)
md = sub.add_parser("models", help="the models a run can pick")
md.add_argument("--json", action="store_true")
md.set_defaults(fn=cmd_models)
ar = sub.add_parser("archive", help="hide a conversation from the default list")
ar.add_argument("id")
ar.add_argument("--undo", action="store_true", help="unarchive")
ar.set_defaults(fn=cmd_archive)
ti = sub.add_parser("title", help="rename a conversation (the owner's rename wins)")
ti.add_argument("id")
ti.add_argument("title")
ti.set_defaults(fn=cmd_title)
for name, fn, hlp in (("projects", cmd_projects, "~/projects: name, GOAL progress, URL"),
("services", cmd_services, "moved: `ai-agent plugin services ls|show`"),
("skills", cmd_skills, "skills on disk, with how often they ran")):
k = sub.add_parser(name, help=hlp)
k.add_argument("query", nargs="*", help="filter words")
k.add_argument("--json", action="store_true")
k.set_defaults(fn=fn)
for name in SCHEDULED_MOVED:
sub.add_parser(name, help="moved: `ai-agent plugin scheduled-conversations …`")
ib = sub.add_parser("inbox", help="what waits on Gabriel: open forms, asks, unread pushes")
ib.add_argument("--limit", type=int, default=10, help="unread notifications shown")
ib.add_argument("--json", action="store_true")
ib.set_defaults(fn=cmd_inbox)
wt = sub.add_parser("worktrees", help="git worktrees under ~/worktrees: ls | rm DIR… | clean")
wt.add_argument("action", nargs="?", default="ls", choices=("ls", "rm", "clean"))
wt.add_argument("targets", nargs="*", metavar="DIR", help="rm: worktree names (or paths)")
wt.add_argument("--stale", action="store_true", help="ls: only the ones clean would remove")
wt.add_argument("--days", type=float, default=worktrees.DEFAULT_DAYS,
help="idle days before a merged worktree is stale (default %(default)g)")
wt.add_argument("--unmerged-days", type=float, metavar="N",
help="also stale: unmerged ones idle N days whose conversations ended "
"(their branch is kept)")
wt.add_argument("--yes", action="store_true", help="clean: remove them (default: a dry run)")
wt.add_argument("--force", action="store_true",
help="rm: even with uncommitted changes, unmerged commits or a running run")
wt.add_argument("--keep-branch", action="store_true", help="don't delete the merged branch")
wt.add_argument("--size", action="store_true", help="measure each one (du, slow)")
wt.add_argument("--json", action="store_true")
wt.set_defaults(fn=cmd_worktrees)
tag_looks.add_parser(sub).set_defaults(fn=cmd_tags)
plugins_cmd.add_parser(sub).set_defaults(fn=cmd_plugin)
return p
def _wait_flags(p: argparse.ArgumentParser) -> None:
p.add_argument("--wait", action="store_true")
p.add_argument("--timeout", type=int, default=3600)
p.add_argument("--json", action="store_true")
def main(argv: list[str] | None = None) -> int:
if IN_GUEST_RUN:
_err("ai-agent: not run — in a guest's session the hub runs this CLI for you, "
"and only as a plain `ai-agent …` command on its own (no path in front, "
"no quotes around its name, no pipe, `&&`, `sh -c` or wrapper).")
return 2
if not AS_SESSION: # a guest's run gets nothing of the owner's .env.claude
load_env_claude()
p = build_parser()
argv = sys.argv[1:] if argv is None else list(argv)
if plugins_cmd.is_plugin_command(argv):
# a plugin's own command: its parser is built from the hub's catalogue
a = argparse.Namespace(cmd="plugin", fn=lambda _a: plugin_commands.run_cli(argv[1:], Hub()))
else:
known = next((x.choices for x in p._actions
if isinstance(x, argparse._SubParsersAction)), {})
hint = _plugin_hint(argv, known)
if hint:
_err(hint)
return 2
if argv and argv[0] in SCHEDULED_MOVED: # whatever its old flags
a = argparse.Namespace(cmd=argv[0], fn=cmd_scheduled_moved)
else:
a = p.parse_args(argv)
if not getattr(a, "fn", None):
p.print_help()
return 2
if os.environ.get("AI_AGENT_OUTBOX_URL") and a.cmd not in WORKER_COMMANDS:
_err("ai-agent: lab sessions only — this run is on a worker (it can't "
"call the hub; the hub polls it). Use the ai-agent MCP tools "
"(mcp__ai-agent__*, a connection bound to this worker: the hub's "
"docs/mcp.md → \"On a worker\"); `ai-agent past` works here, "
"through the outbox")
return 2
if AS_SESSION:
if a.cmd not in GUEST_COMMANDS:
_err(f"ai-agent {a.cmd}: not open to a guest's session — "
f"these are: {', '.join(GUEST_COMMANDS)}")
return 2
if hasattr(a, "timeout"):
a.timeout = min(a.timeout or GUEST_MAX_WAIT_S, GUEST_MAX_WAIT_S)
try:
rc = a.fn(a)
sys.stdout.flush()
return rc
except HubError as e:
_err(f"ai-agent: {e.detail}" + (f" (HTTP {e.code})" if e.code else ""))
return 1
except KeyboardInterrupt:
return 130
except BrokenPipeError: # `ai-agent … | head`
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
return 0
if __name__ == "__main__":
sys.exit(main())