Files
ai-agent/backend/runs/service.py

1035 lines
54 KiB
Python

"""The one send path behind both composers: spawn, resume, runner and account routing."""
import logging
import datetime
import os
import pathlib
import time
import uuid as uuidlib
from fastapi import HTTPException
import accounts as accounts_mod
import models as models_mod
from conversations import autoarchive
from conversations import ids
from conversations.catalog import _session_conv_map
from core.config import WORKERS_SOURCE_DIR
from core.i18n import tr
from core import liveruns
from core.state import AppState
from plugins import run_limits, run_router
from runs import attachments
from runs import queue as run_queue
from runs.extras import run_extras
from workers import guests, picks as worker_picks
from profiles import runners as runners_mod
from profiles import store as profiles_store
from runs.sidecar_client import (
_sidecar_busy,
_sidecar_call,
_sidecar_live_sids,
_valid_sid,
)
log = logging.getLogger(__name__)
# A worker session whose transcript grew this recently with no worker-launched
# run behind it is probably still open in a terminal on that machine.
TERMINAL_LIVE_S = float(os.environ.get("TERMINAL_LIVE_S", "60"))
# ``meta.runAs`` of a run launched without a scope (the owner's permissions).
OWNER_RUN = "owner"
def _refuse_foreign_live_run(deps: AppState, sid: str, worker: str | None,
run_as: str | None = None) -> None:
"""A guest's turn into a session whose live run wasn't launched for them:
the inbox would hand it that run's permissions, and a restart would stop
someone else's work — so it waits until the run is over. Unknown (the
runner didn't answer) counts as live: the restart path stops what runs.
The refusal is worded in ``run_as``'s language (the guest sending)."""
live = _sidecar_live_sids(deps, worker)
if live is None or sid in live:
lang = deps.users.lang_of(run_as) if run_as and run_as != OWNER_RUN else "en"
raise HTTPException(409, {
"message": tr(lang, "someone else's run is still working in this "
"conversation — send your message once it stops"),
"kind": "run_busy"})
def _session_worker(deps: AppState, sid: str) -> str | None:
"""The worker a session lives on: the one the hub launched it on
(``meta.worker``), else the one the mirror imported it from
(``meta.workerSource``). None = the host sidecar's."""
m = deps.meta_store.peek(sid)
return m.get("worker") or m.get("workerSource")
def _mirror_transcript(sid: str) -> pathlib.Path | None:
if not WORKERS_SOURCE_DIR or not WORKERS_SOURCE_DIR.is_dir():
return None
return next(WORKERS_SOURCE_DIR.glob(f"*/{sid}.jsonl"), None)
def _terminal_live_guard(deps: AppState, sid: str, worker: str) -> None:
"""Refuse (409 ``terminal_live``) to resume a worker session a terminal on
that machine may still hold: two writers on one transcript interleave its
parent chain. The worker can't see the terminal's process, so it is a
heuristic — the mirror copy grew in the last TERMINAL_LIVE_S and the worker
has no run of its own for the session. The UI turns it into a confirm."""
ap = _mirror_transcript(sid)
if ap is None:
return
try:
age = time.time() - ap.stat().st_mtime
except OSError:
return
if age > TERMINAL_LIVE_S:
return
live = _sidecar_live_sids(deps, worker) or set()
if sid in live:
return # our own run — a normal force-resume
# Growth our own last run explains: it wrote the file, then the exit
# watcher stamped exitedAt (or hasn't ticked yet and it still reads
# running). Only writes *after* that are a terminal's.
m = deps.meta_store.peek(sid)
if m.get("worker") and m.get("state") == "running":
return
exited = m.get("exitedAt")
if exited:
try:
ex = datetime.datetime.strptime(exited, "%Y-%m-%dT%H:%M:%SZ") \
.replace(tzinfo=datetime.timezone.utc).timestamp()
if ap.stat().st_mtime <= ex + 5:
return
except (ValueError, OSError):
pass
w = deps.worker_store.get(worker) or {}
raise HTTPException(409, {
"message": f"this session was active in a terminal on "
f"{w.get('name') or 'the worker'} {int(age)}s ago",
"kind": "terminal_live", "ageSeconds": int(age),
"hint": "close it there first, or continue anyway — two writers on "
"one session garble its history"})
# The explicit "run it on the lab's own sidecar" runner pick.
LOCAL_RUNNER = "local"
def _mirrored_harnesses() -> tuple[str, ...]:
"""The harnesses whose sessions a mirror turns into transcripts from the
machine's own store (opencode, agy — ``loginMode`` worker / machine): a
conversation can't switch onto or off one of them."""
return _reg().hosted_harnesses()
def _harness_has(harness: str | None, cap: str) -> bool:
"""Whether the harness plugin declares ``cap`` (``lean``, ``fork``…)."""
h = _reg().harnesses.get((harness or "").lower())
return bool(h) and cap in (h.spec.get("caps") or [])
def _model_efforts(harness: str | None) -> bool:
h = _reg().harnesses.get((harness or "").lower())
return bool(h and h.spec.get("modelEfforts"))
def _catalog_entry(harness: str, model: str) -> dict | None:
if harness == "agy":
return models_mod.agy_model(model)
return next((m for m in models_mod.list_models()
if m.get("harness") == harness and m.get("id") == model), None)
def lab_hosts(deps: AppState, account: str) -> bool:
"""Whether the lab's own sidecar declares this opencode / agy account (its
``/accounts``, as the login-health monitor last read it)."""
health = getattr(deps, "account_health", None)
return bool(health and account in health.host_accounts())
def _offline(deps: AppState, wid: str, why: str = "") -> HTTPException:
w = deps.worker_store.get(wid) or {}
name = w.get("name") or wid
return HTTPException(409, {
"message": f"{name} is offline{why}",
"kind": "worker_offline", "worker": wid,
"hint": "wake the machine, send it later, or pick another worker in Runs on"})
def _profiles_for_run(deps: AppState, profile: str | None,
account: str | None) -> list[dict]:
"""The profile(s) a new run may take its runner from: the one it was sent
from (the composer's home switch); unset (a cron file, the API), the one
where the account it names is a runner's ★ login, else the default one —
then the others, for a harness that one can't run."""
store = deps.profile_store
if profile:
p = store.get(profile)
if not p:
raise HTTPException(400, {"message": f"unknown profile: {profile!r}",
"kind": "profile"})
# The Guests profile runs nothing of its own: an owner's prompt sent
# from it routes like one with no profile.
if not profiles_store.is_guests(p):
return [p]
first = (store.for_account_star(account) if account else None) or store.default()
return [first, *[p for p in store.list() if p["id"] != first["id"]
and not profiles_store.is_guests(p)]]
def _reg():
from plugins import providers
return providers.current()
def run_vendor(harness: str, account: str | None = None, model: str | None = None) -> str | None:
"""The provider vendor a new run on ``harness`` bills: the pinned
account's, else the model's (``ProviderRegistry.vendor_of_model`` — an
opencode ``evox2/…`` twin is the EVOX2's, a ``gpt-…`` OpenAI's), else the
harness's default model's, else the harness's first vendor."""
reg = _reg()
vendors = reg.vendors_of_harness(harness)
for v in (accounts_mod.vendor_of_account(account) if account else None,
reg.vendor_of_model(model) if model else None,
reg.vendor_of_model((reg.harnesses.get(harness).spec.get("defaultModel")
if reg.harnesses.get(harness) else None))):
if v and v in vendors:
return v
if model and "/" in model and not reg.is_local(model):
# an OpenRouter-browser pick the catalogue doesn't list
hit = next((v for v in vendors if (reg.providers[v].spec.get("pricing") or {})
.get("kind") == "openrouter_catalogue"), None)
if hit:
return hit
return vendors[0] if vendors else None
def _lab_only(harness: str) -> bool:
h = _reg().harnesses.get(harness)
return bool(h) and h.spec.get("runsOn") == "lab"
def route_new_run(deps: AppState, harness: str, account: str | None,
worker: str | None, profile: str | None = None, *,
check_online: bool = True,
guest: str | None = None,
model: str | None = None) -> tuple[str | None, str]:
"""``(runner, account)`` for a *new* run — runner None = the lab.
**Runner.** The composer's pick (``"local"`` = the lab; an offline worker
is a 409, never a silent reroute), else the default runner of the profile
it was sent from (Settings → Profiles: its first worker) — or, when that
one can't run the harness / the pinned account, the profile's first
runner that can. A default runner that is offline hands the prompt to
the profile's next runner that can take it *and is up* (the Work
profile's MacBook shut in a bag → the Orus devbox); only when every one
of them is down is it a 409 — the composer offers *Send later* or
another worker. Never outside the profile: the Mac asleep doesn't land
its prompt on the lab. ``check_online=False`` (a schedule frozen ahead
of time) skips that and takes the default runner. pi runs on the lab
only.
**Account.** The run's **vendor** first (:func:`run_vendor`: the pin's,
else the model's — ``gpt-6-sol`` → openai, ``evox2/…`` → evox2): the pin,
which the runner must hold (``profiles/runners``); else the profile's ★
login for that vendor (the runner's override first), on the first runner
that holds a login of it — a keyless vendor (the EVOX2) needs none. A pin
of another harness's account only says which profile (a caller with no
profile). A lab-only harness (pi — ``runsOn: "lab"``) runs on the lab,
billing its model's vendor (the EVOX2 or the OpenRouter key).
A guest's own computer (workers/guests.py) only ever runs that guest's
runs (``guest``): nobody else — the owner included — can pin it, and no
profile routes to it."""
h = (harness or "claude").lower()
if account and not accounts_mod.valid(account):
raise HTTPException(400, f"unknown account: {account!r}")
# An id, a name or the lab (workers/picks.py) — else a 400 naming the valid ones.
c = worker_picks.resolve(deps.worker_store, worker, guest=guest)
acct = accounts_mod.valid_for(account, h)
vendor = run_vendor(h, acct, model)
if _lab_only(h):
if c and c != LOCAL_RUNNER:
label = (_reg().harnesses[h].spec.get("label") or h)
raise HTTPException(400, {"message": f"{label} runs on the Homelab only",
"kind": "worker_harness"})
held = runners_mod.logins(deps, None).get(vendor or "", [])
pick = acct if acct in held else deps.profile_store.default_login(
LOCAL_RUNNER, vendor or h, held)
return None, pick or accounts_mod.default_for_vendor(vendor) or accounts_mod.DEFAULT
store = deps.profile_store
pool: list[str] = [] # auto: the profile's runners that could take it
if c == LOCAL_RUNNER:
rid = LOCAL_RUNNER
elif c:
w = deps.worker_store.get(c)
if guests.owner_of(w) != guest:
raise HTTPException(403, {"message": "that computer belongs to a guest — "
"only they run on it" if guests.owner_of(w)
else "a guest runs on their own computers only",
"kind": "worker_guest"})
rid = c
else:
candidates = _profiles_for_run(deps, profile, account)
rid = None
for p in candidates:
can = [e["id"] for e in p.get("workers") or []
if (runners_mod.holds(deps, e["id"], acct, h) if acct
else _vendor_held(deps, e["id"], h, vendor))]
if can:
pool = can
rid = _first_up(deps, can) if check_online else can[0]
break
if rid is None:
p = candidates[0]
label = (accounts_mod.get(acct) or {}).get("label") if acct else None
raise HTTPException(400, {
"message": (f"no {p['label']} worker has the {label} login" if acct else
f"no {p['label']} worker can run {h}"),
"kind": "worker_harness",
"hint": "add the login on one of its workers (Settings → Profiles), "
"or pick a worker in Runs on"})
runner = None if rid == LOCAL_RUNNER else rid
if acct:
if not runners_mod.holds(deps, runner, acct, h):
label = (accounts_mod.get(acct) or {}).get("label") or acct
raise HTTPException(400, {
"message": f"{runners_mod.runner_name(deps, runner)} has no {label} login",
"kind": "worker_harness" if runner else "account",
"hint": "pick one of its own accounts, or another worker"})
else:
acct = store.default_login(rid, vendor or h, _vendor_held(deps, runner, h, vendor))
if not acct:
raise HTTPException(400, {
"message": f"{runners_mod.runner_name(deps, runner)} has no {h} login",
"kind": "worker_harness"})
if runner and check_online and not deps.worker_store.online(runner):
# A worker the composer pinned (never one auto-routing picked — that
# one already fell back to the profile's next runner up) is woken
# when the machine.wake plugin has it on auto-wake, and waited for.
if not (c and c != LOCAL_RUNNER and _auto_wake(deps, runner)):
raise _offline(deps, runner, _also_down(deps, runner, pool))
return runner, acct
def _auto_wake(deps: AppState, wid: str) -> bool:
"""Wake an offline worker through the ``machine.wake`` plugin and wait
for it (``plugins/machine_wake.py``); False — refuse as offline — when
no plugin has it on auto-wake or it didn't come up in time."""
from plugins import machine_wake
try:
return machine_wake.maybe_wake_and_wait(deps, wid)
except Exception as e: # noqa: BLE001 — a broken wake is just "offline"
log.warning("auto-wake of %s failed: %s", wid, e)
return False
def _vendor_held(deps: AppState, runner: str | None, harness: str,
vendor: str | None) -> list[str]:
"""The logins ``runner`` can run ``harness`` on for ``vendor``: the
harness's logins there (a hosted harness: the ones the machine declares),
narrowed to the vendor's accounts."""
held = runners_mod.harness_logins(deps, runner).get(harness, [])
if not vendor:
return held
return [a for a in held if accounts_mod.vendor_of_account(a) == vendor] \
or ([] if any(accounts_mod.vendor_of_account(a) == vendor for a in
accounts_mod.for_harness(harness)) else held)
def _first_up(deps: AppState, runners: list[str]) -> str:
"""The first of a profile's runners (in its order) that is up — the lab
always is — else its first: the default runner, which the caller then
refuses as offline. An unpinned prompt sent while the default (the Work
profile's MacBook, shut in a bag) is down goes to the next one up (the
Orus devbox); never outside the profile (the lab)."""
return next((r for r in runners
if r == LOCAL_RUNNER or deps.worker_store.online(r)), runners[0])
def _also_down(deps: AppState, runner: str, runners: list[str]) -> str:
"""The refusal's tail when a profile's every runner is down: their names
(``" — and so is Orus devbox"``)."""
rest = [(deps.worker_store.get(r) or {}).get("name") or r
for r in runners if r != runner]
return f" — and so {'is' if len(rest) == 1 else 'are'} {', '.join(rest)}" if rest else ""
def _session_account(deps: AppState, sid: str, cwd: str | None = None) -> str:
"""The account an existing session runs on — the one a resume/fork must
launch on, since its transcript lives only in that account's ``projects/``.
Same order as ``accounts.resolve``, fed from the metadata stamp and the
stored summary's cwd (falling back to the cwd the caller sent, for a
session whose transcript hasn't been parsed yet)."""
conv = _session_conv_map(deps, ).get(sid)
summary = deps.store.get_summary(ids.path_of(conv)) if conv else None
return accounts_mod.resolve(summary or {"cwd": cwd}, deps.meta_store.peek(sid))
def _session_summary(deps: AppState, sid: str) -> dict:
"""The stored summary of session ``sid``'s transcript ({} before it is
indexed)."""
conv = _session_conv_map(deps).get(sid)
return (deps.store.get_summary(ids.path_of(conv)) if conv else None) or {}
def _session_harness(deps: AppState, sid: str) -> str:
"""The harness an existing session runs on: the spawn's stamp, else what
its account runs (an opencode session started in a terminal has no stamp,
but its import source names the opencode account), else what its
transcript says, else claude."""
m = deps.meta_store.peek(sid)
if m.get("harness"):
return m["harness"]
for key in ("account", "accountSource"):
a = accounts_mod.valid(m.get(key))
if a and not accounts_mod.is_keyless(a) and accounts_mod.harness_of(a) != "claude":
return accounts_mod.harness_of(a)
conv = _session_conv_map(deps).get(sid)
summary = deps.store.get_summary(ids.path_of(conv)) if conv else None
return (summary or {}).get("harness") or "claude"
def _new_run_account(deps: AppState, account: str | None, harness: str,
model: str | None = None) -> str:
"""What a run of ``harness`` bills when the session can't say (an
opencode resume/fork whose account stamp is gone): the pick when it is an
account of that harness, else the first account of the run's vendor."""
hit = accounts_mod.valid_for(account, harness)
if hit:
return hit
vendor = run_vendor(harness, None, model)
return (accounts_mod.default_for_vendor(vendor)
or (accounts_mod.for_harness(harness) or [accounts_mod.DEFAULT])[0])
def _utc_now() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _launch(deps: AppState, account: str | None, path: str, payload: dict, *,
worker: str | None = None) -> dict:
"""``_sidecar_call`` for a launch, telling the login-health monitor when
the host refused it for the account's login or usage limit."""
# The runner's agent limit rides the launch: the sidecar hands it to the
# run, whose harness hooks cap its native subagents (plugins/run_limits.py).
limit = run_limits.limit_for(deps, worker)
if limit:
payload = {**payload, "agentLimit": limit}
payload = {**payload, **subagent_extra(deps, payload, account, worker)}
if payload.get("account"):
# the runner's own name for it (the EVOX2's opencode account is
# ``opencode-lab`` to the lab sidecar)
payload = {**payload, "account": accounts_mod.wire_id(payload["account"],
payload.get("harness"))}
try:
return _sidecar_call(deps, path, payload, worker=worker)
except HTTPException as e:
d = e.detail if isinstance(e.detail, dict) else {}
# A worker bills the hub's Claude login through the Claude proxy (one
# whose sidecar predates it, its own); an opencode account lives on
# one machine wherever that is — both are the hub's to watch.
# An agy login is each machine's own: a worker's refusal says nothing
# about the lab's (its per-machine row in /api/accounts shows it).
held = (deps.worker_store.status(worker).get("claudeProxy") or {}) if worker else {}
hub_login = (not worker or accounts_mod.harness_of(account) == "opencode"
or account in (held.get("accounts") or []))
if hub_login and account and d.get("kind") in ("auth", "rate_limit"):
try:
deps.account_health.report(account, d.get("message") or "", d["kind"])
except Exception:
pass
raise
def subagent_extra(deps: AppState, payload: dict, account: str | None,
worker: str | None) -> dict:
"""``{"subagentModel": …}`` for a claude launch on one of the owner's
logins — new, resumed or forked: the model its own subagents and
workflow agents are held to (the ``subagents`` preset's first Claude
route with room on this run's account — models/ladders.py
``subagent_model``; the sidecar exports it as
``CLAUDE_CODE_SUBAGENT_MODEL``). Nothing for a guest's run (a scope, their
own login, their computer) or while no preset is set for subagents."""
if (payload.get("harness") or "claude") != "claude" or payload.get("scope") \
or accounts_mod.guest_of(account) \
or (worker and guests.is_guest(deps.worker_store.get(worker))):
return {}
try:
own = payload.get("model")
if not own and payload.get("sessionId") and not payload.get("srcSessionId") \
and "force" in payload: # a resume: what the session runs on
own = _session_summary(deps, payload["sessionId"]).get("contextModel")
sub = run_router.subagent_model(deps, account, own)
except Exception: # noqa: BLE001 — a launch never fails on this
log.exception("subagent model for %s", payload.get("sessionId"))
return {}
return {"subagentModel": sub} if sub else {}
def _extras(deps: AppState, account: str | None, run_on: str | None, cwd: str | None,
scope: dict | None, harness: str, append_prompt: str | None,
run_as: str | None = None) -> dict:
"""What rides along a run (runs/extras.py + per-run ``appendSystemPrompt``).
Non-claude harnesses still get ``appendSystemPrompt`` when set; a guest's
computer gets none of the lab's agents — only the run's own system-prompt lines."""
ap = (append_prompt.strip()[:run_router.MAX_APPEND_PROMPT]
if isinstance(append_prompt, str) and append_prompt.strip() else None)
if harness != "claude":
return {"appendSystemPrompt": ap} if ap else {}
if guests.is_guest(deps.worker_store.get(run_on) if run_on else None):
return {"appendSystemPrompt": ap} if ap else {}
out = run_extras(deps, account, run_on, cwd, scoped=bool(scope), person=run_as)
if ap:
out["appendSystemPrompt"] = "\n\n".join(
x for x in (out.get("appendSystemPrompt"), ap) if x)
# Owner lab runs: inject enabled live plugins' skills + hub tool proxy env.
if not scope and not run_on and getattr(deps, "plugin_store", None):
p_skills = deps.plugin_store.live_skill_dirs("owner")
if p_skills:
from toolproxy import access as tp_access
out["pluginSkills"] = [p["ref"] for p in p_skills]
out["toolsEnv"] = {
"AIA_TOOLS_URL": os.environ.get("TOOLS_PROXY_LAB_URL", "http://127.0.0.1:8096/proxy/tools"),
"AIA_TOOLS_TOKEN": tp_access.mint("owner"),
}
return out
def code_mode_stamp(out: dict, asked: bool) -> dict:
"""The metadata a launch's ``codeMode`` answer (the sidecar's read of the
CLI's start banner) stamps: on → ``codeMode`` true; off → false and
``codeModeOff`` = why. Not shown yet (a slow start, a consent dialog) ⇒
``codeModeAsked``: the exit watcher stamps it from /sessions
(:func:`code_mode_seen`). A resume that says nothing changes nothing."""
st = out.get("codeMode") if isinstance(out, dict) else None
if isinstance(st, dict) and isinstance(st.get("on"), bool):
if st["on"]:
return {"codeMode": True, "codeModeOff": "", "codeModeAsked": True}
return {"codeMode": False, "codeModeAsked": True,
"codeModeOff": str(st.get("reason") or "Code Mode isn't available")[:300]}
return {"codeModeAsked": True} if asked else {}
def code_mode_seen(deps: AppState, sessions: list[dict]) -> None:
"""The exit watcher's tick: a live Code Mode run whose banner the launch
answer didn't carry gets its stamp from the runner's /sessions."""
for s in sessions:
st = s.get("codeMode")
if not isinstance(st, dict):
continue
sid = s.get("sessionId")
m = deps.meta_store.peek(sid) if sid else {}
if not m.get("codeModeAsked") or isinstance(m.get("codeMode"), bool):
continue
deps.meta_store.update(sid, code_mode_stamp({"codeMode": st}, True))
deps.hub.publish({"type": "meta", "id": sid})
def _compact_for(deps: AppState, sid: str, harness: str | None, compact: dict | None,
fresh: bool, run_as: str | None) -> dict | None:
"""The compaction a continue runs first, or None: the one the send names
(checked), else — ``fresh`` — the ``runs.compact`` plugin's. 400 when the
harness can't compact or nothing says how."""
if not compact and not fresh:
return None
from plugins import composer_bridge
from plugins import providers as providers_mod
hs = providers_mod.registry(deps).harnesses.get(harness or "")
if hs is None or "fresh_context" not in (hs.spec.get("caps") or []):
raise HTTPException(400, {"message": f"{harness or 'this harness'} can't compact a "
"session before a reply",
"kind": "fresh_context"})
if compact:
clean = composer_bridge.clean_compact(compact)
if not clean:
raise HTTPException(400, {"message": "compact must be {model, instructions}",
"kind": "fresh_context"})
return clean
own = _session_summary(deps, sid).get("contextModel")
spec = composer_bridge.compact_spec(deps, run_as, sid, own)
if not spec:
raise HTTPException(400, {"message": "no plugin says how to compact (runs.compact) — "
"install the fresh-context plugin",
"kind": "fresh_context"})
return spec
def _send_message(deps: AppState, prompt: str, *, session_id: str | None = None,
model: str | None = None, cwd: str | None = None,
harness: str | None = None,
thinking: bool | None = None,
effort: str | None = None,
account: str | None = None,
projects: list[str] | None = None,
worker: str | None = None,
takeover: bool = False,
scope: dict | None = None,
stamp: dict | None = None,
resume_account: str | None = None,
profile: str | None = None,
restart: bool = False,
inbox_only: bool = False,
chrome: bool | None = None,
code_mode: bool | None = None,
fresh: bool = False,
compact: dict | None = None,
run_as: str | None = None,
lean: dict | None = None,
append_prompt: str | None = None,
_admitted: bool = False,
_sid: str | None = None,
_nowait: bool = False) -> dict:
"""The one send path behind both composers.
**Presets.** ``model`` may be ``preset:<id>`` — a preset with a ladder
(models/ladders.py). A new run then goes to the ladder's first route with
quota left for its profile: that route's harness, model and effort, and
the profile's login for it (``harness`` / ``account`` are ignored; a
``worker`` pin and the ``profile`` still apply). A new owner run that
names no model, harness or account gets its source's default preset
(the composer, a script, a run's child, a plugin). Stamped
``meta.preset`` + ``meta.route``. Every route full and the ladder says
*wait*: the start is held in the queue until the earliest reset
(``queued.reason == "quota"``; ``_nowait`` — *Start now* — skips that).
A continue of such a conversation whose route has filled steps down to
the ladder's next route with room on the same harness and login
(``meta.routeSteps``); a turn that picks one exact model stops that.
**Agent limits.** A launch on a machine at its limit (the ``runs.limits``
provider — plugins/run_limits.py) doesn't start: it waits in the hub's
queue (runs/queue.py) and the answer says so (``queued``: ``{worker,
position, limit, running}``, no ``pid``); a new conversation keeps the
session id minted here. The queue replays this very call when a slot
frees (``_admitted``, with ``_sid`` for a new one). A follow-up into a
live run never waits.
``compact`` (``{model, instructions}`` — a continue on a harness with the
``fresh_context`` cap) compacts the session before the prompt goes out:
the sidecar runs the CLI's ``/compact`` first, then the turn, as one run.
``fresh`` asks for one without naming it: the ``runs.compact`` plugin
says what it runs on (plugins/composer_bridge.py; none ⇒ 400). The core
holds no compaction policy of its own. It
never goes through a live run's inbox, and
the turn is pinned to the conversation's own model unless one was picked
(a bare ``--resume`` would take the CLI's default).
``chrome`` launches the run with ``--chrome`` (the Claude in Chrome tools,
paired to the account's browser — the lab's ``services/chrome`` container
or a Mac worker's own Chrome; chrome/). Stamped as ``meta.chrome`` so a
continue keeps it unless told otherwise; it never applies through the
inbox (a flag, like the model).
``code_mode`` (a new claude run — the composer's *Code β* chip) starts
it in Claude Code's Code Mode: the sidecar runs it as an interactive
session on its pty wrapper (sidecar/launch.py "Code Mode"). Sticky by
nature: the sidecar resumes and forks any session whose transcript says
Code Mode the same way, so a continue needs no flag. Code Mode turns
Claude in Chrome off — ``chrome`` is dropped. What the CLI's banner said
is stamped (:func:`code_mode_stamp`): ``meta.codeMode`` true, or false
with ``codeModeOff`` = why (a proxied runner, an old CLI, an account it
isn't open to yet — the run then went on with the normal tools).
``append_prompt`` is added to the run's system prompt — a guest's run on
their own computer, which carries no sidecar scope (its machine, its
permissions), says whose it is and in which language to answer there.
``lean`` (a new claude/pi run — a cron job's ``lean:`` frontmatter,
cron/scheduler.py) launches it without the default context: a short system
prompt, no CLAUDE.md / skills / MCP, ``{tools, allow}`` (the sidecar's
launch.py "lean runs"). No run extras ride along. Stamped ``meta.lean``; a
continue is a normal run.
With no ``session_id`` this starts a new conversation: we mint the UUID here
so the frontend can start watching for the transcript to sync (~2s) and
redirect to it without waiting for the run. With one, it continues that
session — and a continue *always* takes the prompt: if a run is still live
(or parked on a ScheduleWakeup/Monitor), the sidecar stops it first (SIGINT
the group, wait for it to die) and then launches the ``--resume`` with the
new turn, so sending into a "running"/"paused" conversation restarts it on
the new message. Either way the actual agent process (`claude -p` or the pi
runner, per ``harness``) is launched by the host sidecar (the container
can't reach the host's authenticated CLIs), and we stamp ``running``
immediately so the UI flips before the first turn has synced.
**Runner and account** of a new run: ``route_new_run`` — the composer's
``worker`` pick, else the default runner of the ``profile`` it was sent
from — the next of its runners that is up while that one is down; every
one down ⇒ a 409, never a move out of the profile; the ``account`` pin when that
runner holds it, else the runner's ★ login (Settings → Profiles). It
starts in the runner's start dir unless ``cwd`` says otherwise. The
conversation's profile is then its runner's — whatever account it bills.
pi runs aren't a login: the lab, billing the default account.
A continue always keeps the account the session started on — whatever
the caller asks — and goes where the session lives (``_session_worker``):
its transcript isn't anywhere else; a session a terminal may still hold
needs ``takeover`` (``_terminal_live_guard``). ``resume_account``
overrides a continue's account — a guest's turn on their own login or the
fallback onto the owner's (users/runs.py); both logins share one
transcripts tree, so the session resumes on either. A launch refused for
an expired login or a usage limit is reported to the login-health monitor
on the spot. Stamped as ``meta.account`` / ``meta.worker``.
**Scope.** ``scope`` (a guest's run — users/runs.py) goes to the sidecar,
which launches the run with those permissions; ``stamp`` is merged into
a new conversation's metadata (``owner``, ``projects``). A follow-up into a
live run (the inbox) keeps whatever scope that run was launched with —
so a guest's turn (``run_as`` = their id) only rides a live run that
was launched for them (``meta.runAs``). Any other live run (the owner's,
with its bypass permissions; another guest's grants) refuses it with a
409 ``run_busy`` instead of handing it over or being stopped for it.
**Restart.** ``restart`` skips the inbox: a live run is stopped and the
prompt starts a fresh turn at once — the queued echo's *Stop & send now*,
for a follow-up that would otherwise wait out a long tool call.
``inbox_only`` is its opposite: the inbox or nothing (``delivered: None``)
— a queued message's Cancel note never starts a run."""
# What the queue keeps to replay this send (runs/queue.py).
_args = {k: v for k, v in locals().items()
if k not in ("deps", "_admitted", "_sid", "_nowait")}
_kw = None if _admitted else _args
prompt = (prompt or "").strip()
if not prompt:
raise HTTPException(400, "empty prompt")
if _model_efforts(harness) and model and effort:
# an opencode / agy model takes its own reasoning levels only
m = _catalog_entry(harness.lower(), model)
if m and effort not in (m.get("efforts") or []):
effort = None
if session_id:
sid = _valid_sid(session_id)
# A conversation resumes on the harness it started on — and with the
# thinking setting it last ran with — unless the caller overrides. Both
# were stamped into the metadata sidecar by the spawn.
prev = deps.meta_store.get(sid)
own = _session_harness(deps, sid)
# ``preset:<id>`` on a continue re-attaches the conversation to that
# preset; a plain model is one exact pick, which ends any stepping.
preset_pick = run_router.preset_id(model)
if preset_pick is not None:
model = None
exact_pick = model
caller_append = append_prompt
if append_prompt is None and prev.get("appendSystemPrompt"):
append_prompt = prev["appendSystemPrompt"]
harness = (harness or own).lower()
mirrored = set(_mirrored_harnesses()) & {harness, own}
if mirrored and harness != own:
# Both transcripts would be the same conversation file: the
# mirror's and the other harness's would overwrite each other.
which = sorted(mirrored)[0]
raise HTTPException(409, {"message": f"an {which} conversation can't switch "
"harness (nor another one move onto "
f"{which}) — start a new one",
"kind": "harness_switch"})
if thinking is None:
thinking = prev.get("thinking")
if effort is None:
effort = prev.get("effort")
if chrome is None:
chrome = bool(prev.get("chrome"))
if prev.get("codeMode") or _session_summary(deps, sid).get("codeMode"):
chrome = False # Code Mode has no Claude in Chrome
if harness == "claude":
account = resume_account or _session_account(deps, sid, cwd)
elif harness in _mirrored_harnesses():
# Its sessions live in that account's opencode database only / in
# agy's own conversation store on the machine it ran on.
account = accounts_mod.valid_for(_session_account(deps, sid, cwd), harness) \
or _new_run_account(deps, None, harness, model)
else:
# a lab-only harness (pi): the vendor of the model it runs on now
account = _new_run_account(deps, None, harness,
model or _session_summary(deps, sid).get("contextModel"))
run_on = (None if _lab_only(harness) else _session_worker(deps, sid))
compact = _compact_for(deps, sid, harness, compact, fresh, run_as)
if compact:
model = model or _session_summary(deps, sid).get("contextModel")
if run_on:
w = deps.worker_store.get(run_on)
if w and not deps.worker_store.online(run_on) and not _auto_wake(deps, run_on):
raise HTTPException(409, {
"message": f"this session lives on {w.get('name') or run_on}"
", which is offline",
"kind": "worker_offline",
"hint": "wake the machine — a session can't move runners"})
if not takeover:
_terminal_live_guard(deps, sid, run_on)
if not cwd: # --resume is cwd-scoped: the session's own, on the Mac
conv = _session_conv_map(deps, ).get(sid)
summ = deps.store.get_summary(ids.path_of(conv)) \
if conv else None
cwd = (summ or {}).get("cwd")
if _kw is not None and not inbox_only and not liveruns.alive(sid):
# No live process to take it: this turn launches one — it waits
# when the machine is at its agent limit.
queued = run_queue.gate(deps, sid, run_on, "resume", _kw, run_as=run_as,
title=prev.get("title"))
if queued:
queued["name"] = runners_mod.runner_name(deps, run_on)
deps.meta_store.update(sid, {"queued": {**queued, "at": _utc_now()}})
deps.hub.publish({"type": "meta", "id": sid})
return {"sessionId": sid, "pid": None, "queued": queued}
prompt = attachments.place(deps, prompt, run_on, scope)
if not run_on: # a guest's lab run reads its own attachments folder
attachments.grant(scope)
# A run that is still alive takes the follow-up through its inbox
# socket (sidecar /message): its background work — a build, a
# subagent, a Monitor on a form — survives, and the model reads the
# message between tool calls, or at once when it is idle-waiting.
# Only when nothing is live (404: a plain --resume) or the live run
# can't take it (409 inbox_unavailable: a pi run, an older CLI) does
# the message restart the session the old way, below. A model /
# thinking / effort switch doesn't apply through the inbox — the run
# keeps what it was launched with; Stop it first to switch.
if run_as is not None and prev.get("runAs") != run_as:
_refuse_foreign_live_run(deps, sid, run_on, run_as)
elif harness == "claude" and not restart and not compact:
try:
out = _sidecar_call(deps, "/message", {"sessionId": sid,
"prompt": prompt},
worker=run_on)
except HTTPException as e:
if e.status_code not in (404, 409):
raise
else:
deps.meta_store.update(sid, {"state": "running",
**autoarchive.on_resume(prev)})
deps.hub.publish({"type": "meta", "id": sid})
return {"sessionId": sid, "pid": out.get("pid"),
"delivered": out.get("delivered") or "inbox"}
if inbox_only:
return {"sessionId": sid, "pid": None, "delivered": None}
if chrome and harness == "claude" and not run_on:
# The lab browser it drives, up first (the chrome.lab provider).
from plugins import chrome_bridge
chrome_bridge.ensure(deps, sid, resume=True)
# A force-resume swaps the session's process; shield the swap from the
# exit watcher so the old run's vanish isn't stamped "finished" over
# the "running" written below.
route_patch: dict = {}
if run_as is None and not scope:
model, effort, append_override, route_patch = _turn_route(
deps, prev, preset_pick, exact_pick, model, effort, account, harness, run_on)
if append_override is not None:
cp = (caller_append or "").strip() if isinstance(caller_append, str) else ""
if append_override and cp:
append_prompt = f"{append_override}\n\n{cp}"
elif append_override:
append_prompt = append_override
elif not cp:
append_prompt = None
elif preset_pick is not None:
raise HTTPException(400, {"message": "presets are the hub owner's",
"kind": "preset"})
_sidecar_busy.add(sid)
try:
# The clarifier subagent and the lab's portable agents (claude) +
# per-run appendSystemPrompt (all harnesses).
extras = _extras(deps, account, run_on, cwd, scope, harness, append_prompt, run_as)
out = _launch(deps, account, "/resume", {"sessionId": sid, "prompt": prompt,
"model": model, "cwd": cwd,
"harness": harness,
"thinking": thinking,
"effort": effort,
"account": account,
"scope": scope,
"chrome": bool(chrome) or None,
"compact": compact,
"force": True, **extras}, worker=run_on)
if out.get("reused"):
# force=True makes the sidecar stop a live run instead of
# answering `reused`; only a sidecar predating the flag still
# can. The turn was dropped either way — a 409, not a success,
# so the composer says so instead of waiting on an answer that
# isn't coming.
deps.meta_store.update(sid, {"state": "running"})
deps.hub.publish({"type": "meta", "id": sid})
raise HTTPException(409, "this session is still running and "
"the sidecar is too old to stop it — "
"restart the claude-sidecar service")
# Stamp running (and re-stamp harness + thinking) before lifting the
# shield — the UI flips before the transcript syncs. A None thinking
# is dropped by the merge, so the session keeps what it had.
ap_resume = (
{"appendSystemPrompt": append_prompt.strip()[:run_router.MAX_APPEND_PROMPT]}
if (caller_append is not None and isinstance(append_prompt, str)
and append_prompt.strip() and "appendSystemPrompt" not in route_patch)
else {}
)
deps.meta_store.update(sid, {"state": "running", "harness": harness,
"thinking": thinking, "effort": effort,
"account": account, "worker": run_on,
"chrome": bool(chrome),
"runAs": run_as or OWNER_RUN,
**code_mode_stamp(out, False),
**ap_resume,
**route_patch,
# back on the list (an archived one)
**autoarchive.on_resume(prev)})
finally:
_sidecar_busy.discard(sid)
else:
sid = _valid_sid(_sid) if _sid else str(uuidlib.uuid4())
res = _preset_route(deps, model, harness, account, worker, profile, stamp,
run_as, scope)
if res is not None:
wait = res.get("wait")
if wait and not _nowait:
# Every route is full and the preset waits: the start is held
# until the earliest reset, then resolved again.
why = "; ".join(str(k["reason"]) for k in (res.get("skipped") or [])[:3]
if isinstance(k, dict) and k.get("reason"))
hold_runner = None if res.get("runner") in (None, LOCAL_RUNNER) else res["runner"]
queued = run_queue.hold(deps, sid, hold_runner, "new", _args,
until=wait["until"], why=why, run_as=run_as,
title=(stamp or {}).get("title"))
if queued:
queued["name"] = runners_mod.runner_name(deps, hold_runner)
deps.meta_store.update(sid, {
"runAs": run_as or OWNER_RUN, "preset": res["preset"],
"presetName": res.get("name"),
"queued": {**queued, "at": _utc_now()}, **(stamp or {})})
deps.hub.publish({"type": "meta", "id": sid})
return {"sessionId": sid, "pid": None, "queued": queued}
# The route replaces the harness, the model, the effort and the
# account (the profile's login for that route — routed below), plus
# its default worker (when unpinned) and appended system prompt.
harness, model, effort, account = res["harness"], res["model"], res["effort"], None
worker = worker or res.get("worker")
res_ap = (res.get("appendSystemPrompt") or "").strip()
caller_ap = (append_prompt or "").strip() if isinstance(append_prompt, str) else ""
if res_ap and caller_ap:
append_prompt = f"{res_ap}\n\n{caller_ap}"
elif res_ap:
append_prompt = res_ap
stamp = {**(stamp or {}), "preset": res["preset"], "presetName": res.get("name"),
"route": run_router.route_stamp(res),
**({"profile": profile} if profile else {})}
harness = (harness or "claude").lower()
if account and not accounts_mod.valid(account):
raise HTTPException(400, f"unknown account: {account!r}")
run_on, account = route_new_run(deps, harness, account, worker, profile,
guest=run_as, model=model)
if res is not None and isinstance((stamp or {}).get("route"), dict):
rt = dict(stamp["route"])
if not rt.get("account") and account:
rt["account"] = account
if not rt.get("worker") and (worker or run_on):
rt["worker"] = worker or run_on
stamp = {**stamp, "route": rt}
ap_clean = (append_prompt.strip()[:run_router.MAX_APPEND_PROMPT]
if isinstance(append_prompt, str) and append_prompt.strip() else None)
if ap_clean:
stamp = {**(stamp or {}), "appendSystemPrompt": ap_clean}
if _kw is not None:
# At its agent limit the machine takes it later: the start waits
# in the queue, pinned to the runner it was routed to.
queued = run_queue.gate(deps, sid, run_on, "new",
{**_kw, "worker": run_on or LOCAL_RUNNER},
run_as=run_as, title=(stamp or {}).get("title"))
if queued:
queued["name"] = runners_mod.runner_name(deps, run_on)
# No state yet: nothing ran. The stamp is there for whoever
# waits on this id (a parent's report-back, the CLI).
deps.meta_store.update(sid, {"harness": harness, "worker": run_on,
"runAs": run_as or OWNER_RUN,
"queued": {**queued, "at": _utc_now()},
**(stamp or {})})
deps.hub.publish({"type": "meta", "id": sid})
return {"sessionId": sid, "pid": None, "queued": queued}
if not _lab_only(harness):
# Where its profile entry says a run there starts — else the
# runner's own default (the lab sidecar's, a Mac's install dir).
cwd = cwd or deps.profile_store.runner_cwd(run_on or LOCAL_RUNNER)
prompt = attachments.place(deps, prompt, run_on, scope)
if not run_on: # a guest's lab run reads its own attachments folder
attachments.grant(scope)
if chrome and harness == "claude" and not run_on and not code_mode:
# The lab browser is started on demand (the chrome.lab provider —
# the lab-chrome plugin; plugins/chrome_bridge.py).
from plugins import chrome_bridge
chrome_bridge.ensure(deps, sid)
if run_on and guests.is_guest(deps.worker_store.get(run_on)):
# Its first proxied call may arrive before the meta stamp below.
from workers import terminal as worker_terminal
worker_terminal.expect_run(run_on, sid)
lean = lean if _harness_has(harness, "lean") else None
code_mode = bool(code_mode) and harness == "claude" and lean is None
if code_mode:
chrome = False # Code Mode has no Claude in Chrome
extras = (_extras(deps, account, run_on, cwd, scope, harness, append_prompt, run_as)
if lean is None else ({"appendSystemPrompt": ap_clean} if ap_clean else {}))
if lean is not None:
extras["lean"] = lean
out = _launch(deps, account, "/spawn", {"prompt": prompt, "sessionId": sid,
"model": model, "harness": harness,
"thinking": thinking, "effort": effort,
"account": account, "cwd": cwd,
"scope": scope,
"chrome": bool(chrome) or None,
**({"codeMode": True} if code_mode else {}),
**extras},
worker=run_on)
# A fresh id can't be in the exit watcher's baseline — no shield needed.
deps.meta_store.update(sid, {"state": "running", "harness": harness,
"thinking": thinking, "effort": effort,
"account": account, "worker": run_on,
"chrome": bool(chrome),
"runAs": run_as or OWNER_RUN,
**code_mode_stamp(out, code_mode),
**({"lean": True} if lean is not None else {}),
**(stamp or {})})
_dispatch_started(deps, sid, prompt, projects, run_on, stamp)
deps.hub.publish({"type": "meta", "id": sid})
return {"sessionId": sid, "pid": out.get("pid")}
def _preset_route(deps: AppState, model: str | None, harness: str | None,
account: str | None, worker: str | None, profile: str | None,
stamp: dict | None, run_as: str | None, scope: dict | None) -> dict | None:
"""Where a new run on a preset goes (``plugins/run_router.py``), or None
for a plain run."""
return run_router.resolve_new_run(
deps, model=model, harness=harness, account=account, worker=worker,
profile=profile, stamp=stamp, run_as=run_as, scope=scope)
def _turn_route(deps: AppState, prev: dict, preset_pick: str | None, exact_pick: str | None,
model: str | None, effort: str | None, account: str | None,
harness: str, worker: str | None = None) -> tuple[str | None, str | None, str | None, dict]:
"""A continue's ``(model, effort, append_prompt_override, meta_patch)``
from the ``runs.route`` provider (``plugins/run_router.py``)."""
return run_router.resolve_turn(
deps, prev, preset_pick=preset_pick, exact_pick=exact_pick,
model=model, effort=effort, account=account, harness=harness, worker=worker)
# How much of the first prompt a ``conversation.started`` subscriber sees.
_STARTED_PROMPT_MAX = 4000
def _dispatch_started(deps: AppState, sid: str, prompt: str, projects, worker,
stamp: dict | None) -> None:
"""Live plugins subscribed to ``conversation.started`` (e.g. Plans linking
the run its *Implement* button opened): the owner's installs, best-effort —
a plugin never holds a launch up."""
try:
from plugins.scheduler import dispatch_event
from plugins.store import OWNER_UID
st = stamp or {}
dispatch_event(deps, "conversation.started", {
"sessionId": sid,
"prompt": (prompt or "")[:_STARTED_PROMPT_MAX],
"projects": list(projects or []),
"worker": worker or "local",
"owner": st.get("owner") or OWNER_UID,
"origin": st.get("origin") or "",
}, owner_uid=OWNER_UID)
except Exception:
log.exception("conversation.started dispatch for %s", sid)