Files
ai-agent/cli/mcp_tools.py

644 lines
32 KiB
Python

"""The ``ai-agent`` CLI as MCP tools — what the hub's MCP server
(``ai-agent mcp`` over stdio, the backend's ``/mcp`` over HTTP) offers an AI
app: start and continue conversations, wait for their answers, read them back,
search them, run agents, browse the lab.
Each tool is one CLI command (or a few read-only ones folded into ``browse``)
built on the same :class:`ai_agent.Hub` calls, so the two never drift. A tool
returns text for the model — compact, the way the CLI prints it — never raw
cards (a card list is ~1.5 MB).
A tool sits in a **group** (``read`` · ``run`` · ``agents``);
the server offers the groups the connection may use, and a ``read``-scoped
connection only the read-only tools. A connection **bound to a worker** (the
Orus MacBook's Claude Code) gets :data:`WORKER_TOOLS` only — the hub answers
its calls as the owner narrowed to that worker (backend workers/bound.py).
Live plugins add their own tools, ``plugin_<id>_<command>``: the commands a
plugin's ``plugin.json`` marks ``"mcp": true`` (``plugin_commands.py``),
listed from the hub per call — ``read`` group when the action is readOnly,
``run`` otherwise; a guest's connection gets those of their granted plugins
(the hub answers the catalogue as them); a worker-bound one none. Send later
is one of them since 2026-11-28 (``plugin_scheduled-conversations_add`` /
``_ls`` / ``_show`` / ``_cancel`` / ``_start`` — the core's
``schedule_conversation`` / ``cancel_scheduled`` / ``browse scheduled`` went,
with the ``schedule`` group), so a worker-bound connection can't schedule.
Stdlib only, like the CLI.
"""
from __future__ import annotations
import dataclasses
import json
import types
import urllib.parse
from typing import Callable
import ai_agent as aa
import plugin_commands
from ai_agent import Hub, HubError
GROUPS = ("read", "run", "agents")
# A `wait` holds the HTTP request open: most MCP clients give a tool call
# 60 s, so a slice stays under it and the model calls `wait_for_conversation`
# again (the result says so).
DEFAULT_MAX_WAIT_S = 50
# Text a tool returns beyond this is cut (a whole transcript can be MBs).
MAX_TEXT = 60_000
@dataclasses.dataclass
class Ctx:
"""Who a tool call runs for, and how."""
hub: Hub
view_url: str = aa.VIEW_URL
scope: str = "full" # "read" | "full"
groups: frozenset = frozenset(GROUPS)
max_wait_s: int = DEFAULT_MAX_WAIT_S
# Called with the session id of every conversation a tool starts (the
# backend stamps which app started it: ``meta.via``).
on_spawn: Callable[[str], None] | None = None
# A guest's connection: the owner-only tools are off.
guest: bool = False
# Bound to one of the owner's workers (its id): WORKER_TOOLS only, and the
# hub sees that worker's profile and starts runs there.
worker: str | None = None
# The plugin commands the hub listed for this caller (one fetch per ctx).
plugin_cmds: list | None = dataclasses.field(default=None, compare=False, repr=False)
@dataclasses.dataclass(frozen=True)
class Tool:
name: str
title: str
description: str
params: dict
required: tuple
group: str
fn: Callable
read_only: bool = False
destructive: bool = False
idempotent: bool = False
guest_ok: bool = False
def schema(self) -> dict:
return {"type": "object", "properties": self.params,
"required": list(self.required), "additionalProperties": False}
def describe(self) -> dict:
return {"name": self.name, "title": self.title, "description": self.description,
"inputSchema": self.schema(),
"annotations": {"title": self.title, "readOnlyHint": self.read_only,
"destructiveHint": self.destructive,
"idempotentHint": self.idempotent,
"openWorldHint": not self.read_only}}
class ToolError(Exception):
"""A refusal the model should read (bad arguments, not allowed)."""
TOOLS: dict[str, Tool] = {}
def tool(name: str, title: str, group: str, description: str, params: dict | None = None,
required: tuple = (), **flags):
def deco(fn):
TOOLS[name] = Tool(name, title, description.strip(), params or {}, required, group,
fn, **flags)
return fn
return deco
# What a connection bound to a worker keeps: its own profile's conversations,
# runs on that machine — never the lab's projects, memories, inbox or agents
# (the hub refuses those routes anyway, workers/bound.py), and no plugin
# tools (its scopes have no plugins.use — so no cron jobs and no scheduling:
# both are plugins' commands).
WORKER_TOOLS = frozenset({
"list_conversations", "get_conversation", "search_conversations",
"past_conversations", "wait_for_conversation", "browse",
"start_conversation", "send_message", "fork_conversation", "stop_conversation",
"rename_conversation", "archive_conversation"})
def allowed(t: Tool, ctx: Ctx) -> bool:
if t.group not in ctx.groups:
return False
if ctx.scope == "read" and not t.read_only:
return False
if ctx.worker and t.name not in WORKER_TOOLS:
return False
return t.guest_ok or not ctx.guest
def plugin_tools(ctx: Ctx) -> dict[str, dict]:
"""The plugin commands this connection may call as tools, by tool name:
opted in (``mcp``), in a group the connection has, read-only ones only on
a read connection, none on a worker-bound one. A hub that can't list them
leaves the core tools alone."""
if ctx.worker:
return {}
if ctx.plugin_cmds is None:
try:
ctx.plugin_cmds = plugin_commands.catalogue(ctx.hub)
except HubError:
ctx.plugin_cmds = []
out = {}
for c in ctx.plugin_cmds:
if not (c.get("mcp") and c.get("tool")) or c["tool"] in TOOLS:
continue
ro = bool(c.get("readOnly"))
if ("read" if ro else "run") not in ctx.groups or (ctx.scope == "read" and not ro):
continue
out[c["tool"]] = c
return out
def listing(ctx: Ctx) -> list[dict]:
return ([t.describe() for t in TOOLS.values() if allowed(t, ctx)]
+ [plugin_commands.describe(c) for c in plugin_tools(ctx).values()])
def _call_plugin_tool(ctx: Ctx, name: str, args: dict) -> str:
c = plugin_tools(ctx).get(name)
if not c:
raise KeyError(name)
schema = plugin_commands.input_schema(c)
args = dict(args or {})
unknown = set(args) - set(schema["properties"])
if unknown:
raise ToolError(f"unknown argument(s): {', '.join(sorted(unknown))}")
missing = [k for k in schema["required"] if args.get(k) in (None, "", [])]
if missing:
raise ToolError(f"missing argument(s): {', '.join(missing)}")
return plugin_commands.call_tool(ctx.hub, c, args)
def call(ctx: Ctx, name: str, args: dict) -> str:
"""Run tool ``name``; :class:`ToolError` / :class:`HubError` for the
model to read."""
t = TOOLS.get(name)
if not t and name.startswith("plugin_"):
text = _call_plugin_tool(ctx, name, args)
return text if len(text) <= MAX_TEXT else text[:MAX_TEXT] + f"\n\n… (cut at {MAX_TEXT} characters)"
if not t or not allowed(t, ctx):
raise KeyError(name)
args = dict(args or {})
unknown = set(args) - set(t.params)
if unknown:
raise ToolError(f"unknown argument(s): {', '.join(sorted(unknown))}")
missing = [k for k in t.required if args.get(k) in (None, "", [])]
if missing:
raise ToolError(f"missing argument(s): {', '.join(missing)}")
text = t.fn(ctx, **args)
if len(text) > MAX_TEXT:
text = text[:MAX_TEXT] + f"\n\n… (cut at {MAX_TEXT} characters — ask for fewer messages)"
return text
# ── shared bits ──────────────────────────────────────────────────────────────
def _s(desc: str, **kw) -> dict:
return {"type": "string", "description": desc, **kw}
def _i(desc: str, **kw) -> dict:
return {"type": "integer", "description": desc, **kw}
def _b(desc: str) -> dict:
return {"type": "boolean", "description": desc}
ID = _s("The conversation: its id (a UUID, as in its viewer link), a session id, a "
"unique 6+ character prefix of one (the 8-character ids the listings show), "
"or its viewer link.")
MODEL = _s("Model: opus | sonnet | haiku | fable, a full id, or words matched against the "
"hub's catalog (`browse` kind=models) — e.g. 'qwen' starts a pi run on Qwen.")
EFFORT = _s("How hard the run works a turn.", enum=["low", "medium", "high", "xhigh", "max"])
WAIT = _i("Seconds to wait for the run's final answer (0 = return at once with its id). "
"Capped by the server; if it is still running, call wait_for_conversation.",
minimum=0)
def _url(ctx: Ctx, cid: str) -> str:
return f"{ctx.view_url}/conversation/{cid}"
def _line(ctx: Ctx, c: dict) -> str:
m = c.get("meta") or {}
when = "active" if m.get("state") in aa.LIVE_STATES else "ended"
bits = [m.get("state", "?"), f"{when} {aa._ago(c.get('endedAt'))}",
f"${c.get('cost') or 0:.2f}", m.get("worker") or "lab"]
projects = m.get("projects") or ([c["project"]] if c.get("project") else [])
if projects:
bits.append(", ".join(projects[:3]))
return f"- {(c.get('sessionId') or '')[:8]} {aa._title(c)[:90]} ({' · '.join(bits)})"
def _head(ctx: Ctx, 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 {aa._ago(c.get('endedAt'))}"]
lines = [f"# {aa._title(c)}", " · ".join(b for b in bits if b),
f"session {c.get('sessionId')}", _url(ctx, c["id"])]
parent = (m.get("spawnedBy") or {}).get("sessionId")
if parent:
lines.append(f"started by {parent}")
return "\n".join(lines)
def _model(ctx: Ctx, model: str | None, harness: str | None, new: bool) -> tuple:
"""``model`` matched against the catalog, as the CLI's ``--model``."""
if not model:
return None, harness
a = types.SimpleNamespace(model=model, harness=harness)
aa.pick_model(ctx.hub, a, set_harness=new)
return a.model, a.harness
def _run_body(ctx: Ctx, *, model=None, effort=None, harness=None, thinking=None,
chrome=None, new: bool) -> dict:
model, harness = _model(ctx, model, harness, new)
body = {"model": model, "effort": effort, "harness": harness if new else None,
"thinking": thinking, "chrome": chrome or None}
return {k: v for k, v in body.items() if v is not None}
def _wait_for(ctx: Ctx, sid: str, seconds: int | None, since: str | None = None) -> str:
seconds = max(0, min(int(seconds or 0), ctx.max_wait_s))
try:
c = aa.wait_done(ctx.hub, sid, seconds, since=since)
except HubError as e:
if e.code == 404: # not indexed yet: the run is just starting
return f"{sid}: still starting — call wait_for_conversation again."
raise
if not c:
return (f"{sid}: still running after {seconds} s — call wait_for_conversation "
f"again (or get_conversation to see where it is).")
d = aa.detail(ctx.hub, c)
ans = aa.final_answer(d.get("thread") or [])
return _head(ctx, c) + "\n\n## Final answer\n\n" + (
ans or "(no answer — the run wrote no text: an API error, a dead key or a stop; "
"the link shows what happened)")
def _started(ctx: Ctx, out: dict, wait_seconds: int | None, sent_at: str,
what: str = "Started") -> str:
sid = out.get("sessionId")
if not sid:
return json.dumps(out, ensure_ascii=False)
if ctx.on_spawn:
try:
ctx.on_spawn(sid)
except Exception: # noqa: BLE001 — a missed stamp never fails the run
pass
if wait_seconds:
return _wait_for(ctx, sid, wait_seconds, since=sent_at)
how = " (queued into the live run's inbox)" if out.get("delivered") == "inbox" else ""
link = _url(ctx, out["id"]) if out.get("id") else f"{ctx.view_url}/conversations?q={sid}"
return (f"{what}{how}: session {sid}\n{link}\n"
f"Call wait_for_conversation with this id for its final answer.")
# ── read: conversations ──────────────────────────────────────────────────────
@tool("list_conversations", "List conversations", "read", """
Recent ai-agent conversations (Claude Code / pi / opencode runs on the homelab
and its workers), newest first: 8-char id, title, state, when it ended, cost,
where it ran, projects. Filter to the running ones or to one project.""",
{"limit": _i("How many (default 20, max 100).", minimum=1, maximum=100),
"running": _b("Only the ones running now."),
"project": _s("Only those tagged with this project/service slug."),
"include_archived": _b("Also the archived ones.")},
read_only=True, idempotent=True, guest_ok=True)
def list_conversations(ctx: Ctx, limit: int = 20, running: bool = False,
project: str | None = None, include_archived: bool = False) -> str:
limit = max(1, min(int(limit or 20), 100))
cards = ctx.hub.get("/api/conversations", limit=0 if (project or running) else limit,
archived="all" if include_archived else "false")["conversations"]
if running:
cards = [c for c in cards if (c.get("meta") or {}).get("state") in aa.LIVE_STATES]
if project:
cards = [c for c in cards if project in ((c.get("meta") or {}).get("projects") or [])
or c.get("project") == project]
cards = cards[:limit]
if not cards:
return "No conversations."
return "\n".join(_line(ctx, c) for c in cards)
@tool("get_conversation", "Read a conversation", "read", """
One conversation: its header (state, model, cost, link), then either its first
prompt and last answer (default) or its last N messages (`messages`), or the
whole thread (`full`). `tools` adds a one-line note per tool call.""",
{"id": ID,
"messages": _i("The last N messages instead of prompt + last answer.", minimum=1),
"full": _b("Every message (long conversations are cut)."),
"tools": _b("Include a line per tool call.")},
("id",), read_only=True, idempotent=True, guest_ok=True)
def get_conversation(ctx: Ctx, id: str, messages: int | None = None, full: bool = False,
tools: bool = False) -> str:
c = aa.resolve(ctx.hub, id)
thread = aa.detail(ctx.hub, c).get("thread") or []
out = [_head(ctx, c)]
if full or messages:
msgs = aa._messages(thread, tools)
out.append(aa.render_messages(msgs if full else msgs[-int(messages):]))
else:
first = next((it for it in thread if it.get("role") == "user"
and it.get("kind") == "text"), None)
if first:
out.append("## Prompt\n\n" + first["text"].strip()[:3000])
out.append("## Last answer\n\n" + (aa.final_answer(thread) or "(none yet)"))
return "\n\n".join(out)
@tool("search_conversations", "Search conversations", "read", """
Find conversations whose title or messages contain every word of the query
(case-insensitive), newest first; when none has them all, the ones with the
most of them (said so). Each row says the machine it ran on. `project` and
`since` (7d, 2w, 2026-11-01) narrow it. Returns ids, titles and a snippet of
the matching messages — read one with get_conversation.""",
{"query": _s("Words to look for."),
"limit": _i("How many (default 10, max 50).", minimum=1, maximum=50),
"project": _s("Only conversations tagged with this project or service."),
"since": _s("Only those ended since: 7d, 2w, 12h or a date (2026-11-01).")},
("query",), read_only=True, idempotent=True, guest_ok=True)
def search_conversations(ctx: Ctx, query: str, limit: int = 10, project: str | None = None,
since: str | None = None) -> str:
words = [w.casefold() for w in query.split() if w]
rows = ctx.hub.get("/api/search-index").get("conversations") or []
hits, partial = aa.search_hits(rows, words, project=project or None, since=since or None)
if not hits:
return "No match."
names = aa._machines(ctx.hub)
out = [f"No conversation has every word of {query!r}; the closest:"] if partial else []
for n, _, r, m in hits[:max(1, min(int(limit or 10), 50))]:
where = names.get(r.get("worker"), r.get("worker")) if r.get("worker") else "lab"
extra = f", {n}/{len(words)} words" if partial else ""
out.append(f"- {aa._sid(r)[:8]} {(r.get('title') or '')[:90]} "
f"(ended {aa._ago(r.get('endedAt'))} on {where}{extra})")
for i, t in m[:2]:
out.append(f" [{i}] {aa._snippet(t, words)}")
return "\n".join(out)
@tool("past_conversations", "Conversations on an issue / PR / branch", "read", """
Earlier conversations about a subject: a Linear issue key (INS-2229), a PR link
or number, a branch, or a conversation (its id or viewer link: the issues and
PRs it is about). The ones running now, then the newest ended ones of the
last 30 days, each with the last message that names the subject.""",
{"keys": {"type": "array", "items": {"type": "string"}, "minItems": 1,
"description": "Issue keys, PR links/numbers, branch names or conversation ids."}},
("keys",), read_only=True, idempotent=True)
def past_conversations(ctx: Ctx, keys: list) -> str:
res = ctx.hub.get("/api/past-conversations", keys=",".join(str(k) for k in keys))
out = []
for s in res.get("subjects") or []:
out.append(f"## {s['label']}")
for r in s.get("running") or []:
out.append(f"- RUNNING NOW {aa._sid(r)[:8]} {aa._clip(r.get('title') or '', 80)}"
f" {r.get('url') or ''}")
for c in s.get("past") or []:
out.append(f"- {(c.get('endedAt') or '')[:10]} {aa._sid(c)[:8]} "
f"{c.get('state') or '?'} {aa._clip(c.get('title') or '', 80)}")
if c.get("excerpt"):
out.append(f" “{aa._clip(c['excerpt'], 400)}”")
if not (s.get("running") or s.get("past")):
out.append(f"(nothing in the last {res.get('maxAgeDays', 30)} days)")
if res.get("skipped"):
out.append(f"not looked up: {', '.join(res['skipped'])}")
return "\n".join(out) or "Nothing found."
@tool("inbox", "What waits on Gabriel", "read", """
What waits on the owner: open forms and questions agents asked (with their
conversation), then the unread push notifications.""",
{"limit": _i("How many unread notifications to list (default 15).", minimum=0)},
read_only=True, idempotent=True, guest_ok=True)
def inbox(ctx: Ctx, limit: int = 15) -> str:
items = aa.waiting(ctx.hub)
out = [f"## Waiting for feedback ({len(items)})"]
for x in items:
opts = f" [{' / '.join(x['options'])}]" if x.get("options") else ""
out.append(f"- {x['kind']} {(x.get('sessionId') or '')[:8]} {aa._ago(x.get('at'))}: "
f"{' '.join((x.get('title') or '').split())[:160]}{opts}")
if not ctx.guest:
unread = ctx.hub.get("/api/notifications/unread")
notes = unread.get("notifications") or []
out.append(f"\n## Unread notifications ({unread.get('total', len(notes))})")
for n in notes[:max(0, int(limit if limit is not None else 15))]:
out.append(f"- {aa._ago(n.get('at'))}: {' '.join((n.get('title') or '').split())[:80]}"
f"{' — ' + n['convTitle'][:60] if n.get('convTitle') else ''}")
return "\n".join(out)
# ── read: the lab ────────────────────────────────────────────────────────────
BROWSE_KINDS = ("projects", "skills", "agents",
"models", "workers", "usage", "budget")
# What a guest's connection may browse: their granted projects, the models
# they may pick, their budget — what their `ai-agent` CLI sees.
GUEST_KINDS = ("projects", "models", "budget")
# What a connection bound to a worker may browse: nothing that reads the lab's
# own files.
WORKER_KINDS = ("models", "workers", "usage", "budget")
def _matches(row: dict, words: list[str], keys: tuple) -> bool:
blob = " ".join(str(row.get(k) or "") for k in keys).casefold()
return all(w in blob for w in words)
def _rows(ctx: Ctx, kind: str) -> list[dict]:
h = ctx.hub
if kind == "projects":
return [{"name": r["name"], "url": r.get("url"), "goal": aa._goal(r.get("goal")),
"description": (r.get("description") or "")[:160], "keywords": r.get("keywords")}
for r in h.get("/api/projects").get("projects") or []]
if kind == "skills":
return [{"name": r["name"], "uses": r.get("count"), "description": (r.get("description") or "")[:200]}
for r in h.get("/api/skills").get("skills") or [] if r.get("sourceKind") != "builtin"]
if kind == "agents":
return [{"name": r["name"], "model": r.get("model"), "description": (r.get("description") or "")[:200]}
for r in h.get("/api/agents").get("agents") or [] if r.get("sourceKind") != "builtin"]
if kind == "models":
return [{"id": m.get("alias") or m["id"], "harness": m.get("harness"), "name": m.get("displayName")}
for m in h.get("/api/models").get("models") or []]
if kind == "workers":
return [{"id": "local", "name": "lab", "status": "online"}] + [
{k: w.get(k) for k in ("id", "name", "status", "account", "platform", "running")}
for w in h.get("/api/workers").get("workers") or []]
if kind == "usage":
lim = h.get("/api/usage/limits").get("accounts") or {}
health = {x["id"]: x for x in h.get("/api/accounts/health").get("accounts") or []}
return [{"account": k,
"windows": {w: round(v.get("pct") or 0) for w, v in ((lim.get(k) or {}).get("windows") or {}).items()},
"status": (health.get(k) or {}).get("status"),
"limited": (health.get(k) or {}).get("limited")} for k in sorted(set(lim) | set(health))]
raise ToolError(f"kind must be one of: {', '.join(BROWSE_KINDS)}")
@tool("browse", "Browse the lab", "read", """
Look up the homelab: projects, skills, agents (.claude/agents), models a run
can pick, workers (machines that run conversations), plan usage per account,
or the week's budget. `query` keeps the rows containing every word. One JSON
row per line. Services, plans, memories, cron jobs, scheduled conversations
and other plugins' data come through those plugins' own `plugin_*` tools
(`plugin_services_ls`, `plugin_cron-jobs_ls`,
`plugin_scheduled-conversations_ls`).""",
{"kind": _s("What to list.", enum=list(BROWSE_KINDS)),
"query": _s("Words a row must contain (optional)."),
"account": _s("budget only: the account (default personal).")},
("kind",), read_only=True, idempotent=True, guest_ok=True)
def browse(ctx: Ctx, kind: str, query: str | None = None, account: str | None = None) -> str:
if ctx.guest and kind not in GUEST_KINDS:
raise ToolError(f"kind: one of {', '.join(GUEST_KINDS)}")
if ctx.worker and kind not in WORKER_KINDS:
raise ToolError(f"kind: one of {', '.join(WORKER_KINDS)} (this connection "
f"is bound to a worker)")
if kind == "budget" and ctx.guest:
me = ctx.hub.get("/api/me")
return json.dumps({k: me.get(k) for k in ("budgetUsd", "spentUsd", "models")},
ensure_ascii=False)
if kind == "budget":
b = ctx.hub.get("/api/usage/budget", account=account or "personal")
keep = {k: b.get(k) for k in ("account", "pct", "hoursLeft", "resetsAt", "left",
"free", "pace", "stale")}
keep["upcoming"] = {k: (b.get("upcoming") or {}).get(k) for k in ("pct", "units")}
return json.dumps(keep, ensure_ascii=False, default=str)
rows = _rows(ctx, kind)
words = [w.casefold() for w in (query or "").split()]
if words:
rows = [r for r in rows if _matches(r, words, tuple(r))]
if not rows:
return "Nothing matches."
return "\n".join(json.dumps(r, ensure_ascii=False, default=str) for r in rows)
# ── run ──────────────────────────────────────────────────────────────────────
@tool("start_conversation", "Start a conversation", "run", """
Start a new ai-agent conversation: a coding agent (Claude Code by default) that
works on the homelab — or on a paired worker machine — with the prompt as its
task. It is visible and resumable in the ai-agent app. Returns its id and link;
give `wait_seconds` to wait for its final answer, or call wait_for_conversation
later. Leave model/effort/cwd unset for the hub's defaults.""",
{"prompt": _s("The task, as you would type it in the app."),
"model": MODEL, "effort": EFFORT,
"harness": _s("Which agent runs it — any active harness plugin (claude, pi, opencode, "
"agy…; default: the model's)."),
"worker": _s("Which machine: a worker id or name from `browse` kind=workers, or 'local' "
"for the lab (default: the profile's default runner; on a connection "
"bound to a worker, that worker — the only one it may use)."),
"account": _s("The login it bills (default: the runner's default)."),
"cwd": _s("Working directory on that machine (default: the runner's start dir)."),
"projects": {"type": "array", "items": {"type": "string"},
"description": "Project/service slugs to tag it with. On a guest's "
"connection: required, the first is the project it runs in "
"(`browse` kind=projects lists theirs)."},
"chrome": _b("Let it drive the paired Chrome browser."),
"thinking": _b("false turns extended thinking off."),
"test": _b("A throwaway run to test something: archived once its turn ends, "
"whatever the outcome (still readable with get_conversation)."),
"wait_seconds": WAIT},
("prompt",), guest_ok=True)
def start_conversation(ctx: Ctx, prompt: str, model=None, effort=None, harness=None,
worker=None, account=None, cwd=None, projects=None, chrome=None,
thinking=None, test=None, wait_seconds: int = 0) -> str:
body = {"prompt": prompt, **_run_body(ctx, model=model, effort=effort, harness=harness,
thinking=thinking, chrome=chrome, new=True)}
for k, v in (("worker", worker), ("account", account), ("cwd", cwd), ("projects", projects),
("test", test)):
if v:
body[k] = v
sent_at = aa._now_iso()
return _started(ctx, ctx.hub.post("/api/spawn", body), wait_seconds, sent_at)
@tool("send_message", "Continue a conversation", "run", """
Send a new turn to an existing conversation (it resumes with its whole
context). If it is running, the message is queued into its inbox unless
`now` stops it first. `fresh` compacts a long session before the turn.""",
{"id": ID, "prompt": _s("The message."), "model": MODEL, "effort": EFFORT,
"now": _b("Stop a live run and send now instead of queueing."),
"fresh": _b("Compact the session first (cheaper on a long, cold one)."),
"wait_seconds": WAIT},
("id", "prompt"), guest_ok=True)
def send_message(ctx: Ctx, id: str, prompt: str, model=None, effort=None, now: bool = False,
fresh: bool = False, wait_seconds: int = 0) -> str:
c = aa.resolve(ctx.hub, id)
body = {"sessionId": c["sessionId"], "prompt": prompt,
**_run_body(ctx, model=model, effort=effort, new=False), "now": now, "fresh": fresh}
sent_at = aa._now_iso()
out = ctx.hub.post("/api/resume", body)
out.setdefault("id", c["id"])
out.setdefault("sessionId", c["sessionId"])
return _started(ctx, out, wait_seconds, sent_at, what="Sent")
@tool("fork_conversation", "Fork a conversation", "run", """
Branch a new conversation off message `at` of an existing one (the index
shown as [n] by get_conversation), with a new prompt.""",
{"id": ID, "at": _i("The message index to branch after.", minimum=0),
"prompt": _s("The new prompt."), "model": MODEL, "effort": EFFORT, "wait_seconds": WAIT},
("id", "at", "prompt"), guest_ok=True)
def fork_conversation(ctx: Ctx, id: str, at: int, prompt: str, model=None, effort=None,
wait_seconds: int = 0) -> str:
c = aa.resolve(ctx.hub, id)
body = {"id": c["id"], "mi": int(at), "prompt": prompt,
**_run_body(ctx, model=model, effort=effort, new=False)}
sent_at = aa._now_iso()
return _started(ctx, ctx.hub.post("/api/fork", body), wait_seconds, sent_at, what="Forked")
@tool("wait_for_conversation", "Wait for a conversation's answer", "read", """
Wait until a conversation's run stops, then return its final answer. Waits at
most `timeout_seconds` (capped by the server, ~50 s); if it is still running,
say so and call again.""",
{"id": ID, "timeout_seconds": _i("How long to wait (default: the server's cap).", minimum=1)},
("id",), read_only=True, idempotent=True, guest_ok=True)
def wait_for_conversation(ctx: Ctx, id: str, timeout_seconds: int | None = None) -> str:
sid = aa.wait_session(ctx.hub, id)
return _wait_for(ctx, sid, timeout_seconds or ctx.max_wait_s)
@tool("stop_conversation", "Stop a running conversation", "run", """
Interrupt a running conversation (its transcript stays; send_message resumes it).""",
{"id": ID}, ("id",), destructive=True, guest_ok=True)
def stop_conversation(ctx: Ctx, id: str) -> str:
c = aa.resolve(ctx.hub, id)
out = ctx.hub.post("/api/interrupt", {"sessionId": c["sessionId"]})
return f"stopped {c['sessionId']}" if out.get("ok") else f"{c['sessionId']}: nothing running"
@tool("rename_conversation", "Rename a conversation", "run", """
Give a conversation a title (an agent rename: the owner's own rename in the app
always wins).""",
{"id": ID, "title": _s("The new title.")}, ("id", "title"), idempotent=True, guest_ok=True)
def rename_conversation(ctx: Ctx, id: str, title: str) -> str:
c = aa.resolve(ctx.hub, id)
ctx.hub.post("/api/conversation-meta", {"id": c["sessionId"], "title": title,
"titleSource": "agent"})
return f"{c['sessionId'][:8]}: {title}"
@tool("archive_conversation", "Archive a conversation", "run", """
Hide a conversation from the default list (`undo` brings it back).""",
{"id": ID, "undo": _b("Unarchive instead.")}, ("id",), idempotent=True, guest_ok=True)
def archive_conversation(ctx: Ctx, id: str, undo: bool = False) -> str:
c = aa.resolve(ctx.hub, id)
ctx.hub.post("/api/conversation-meta", {"id": c["sessionId"], "archived": not undo})
return f"{'unarchived' if undo else 'archived'} {c['sessionId']}"
# ── agents ──────────────────────────────────────────────────────────────────
@tool("run_agent", "Run an agent now", "agents", """
Run one of the lab's agent definitions (.claude/agents — `browse` kind=agents)
now, optionally with an extra prompt.""",
{"name": _s("The agent's name."), "prompt": _s("Extra instructions (optional)."),
"wait_seconds": WAIT}, ("name",))
def run_agent(ctx: Ctx, name: str, prompt: str | None = None, wait_seconds: int = 0) -> str:
sent_at = aa._now_iso()
out = ctx.hub.post(f"/api/agents/{urllib.parse.quote(name)}/run", {"prompt": prompt or None})
return _started(ctx, out, wait_seconds, sent_at)