Files
ai-agent/backend/runs/bgtasks.py
gabrielvidalandClaude Opus 5.5 e94deb8174 feat(parse): neutral tool names in the readers, the fold and the buckets (parser v45)
The readers put the neutral name in a tool_call's `tool` and the record's
own in `native` (readers/toolnames.py): Bash → shell, Read → read,
Agent/Task → agent, the five task tools → todo, CronCreate →
claude:CronCreate; a converter-written legacy file namespaces its own
tools under its entrypoint (agy:manage_task, opencode:execute), an
unstamped one's lowercase names are pi's. MCP names are untouched.

The fold, the cost buckets (bash → shell, task → todo; TaskOutput /
TaskStop now count as shell, TaskGet / TaskList as todo), taskevents, the
resource miner, the lifecycle / deploy / worktree detection, tree.py's
agent cards, spawned children, the scaffold and the bgtasks route key on
the neutral names only. The `todo` calls are told apart by their input
(tools.todo_op). A tool card carries `native` when it differs.

PARSER_VERSION 45 (a full re-index). docs/transcript-format.md gets the
"Tool names" table with the agy column filled from sidecar/agy_tools.py;
the v1 fixtures use the neutral names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:14:14 +01:00

104 lines
4.6 KiB
Python

"""A conversation's background shells and Monitors: the tail of one task's
output, and a stop — what the Details drawer's *Background shells* card reads
and does (frontend ``BackgroundShellsCard.tsx``).
Both go to the runner the session lives on (the host sidecar, or the worker
it ran on — ``_session_worker``), whose ``bgtasks.py`` reads
``tasks/<id>.output`` and signals the task's process group inside the run's
own process tree. The task must be one this conversation started: its id is
looked up on the parsed thread (a ``run_in_background`` Bash or a Monitor
card carrying ``taskId``), and a Monitor's command — what the runner finds
its process by — comes from that card, never from the client.
A stop is stamped on the meta (``taskStops``: task id → epoch s): the CLI
records it as an ordinary failed exit, and the card reads the stamp to say
*stopped by you* instead, on every device.
"""
from __future__ import annotations
import time
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import schemas
from core.http import _r
from core.state import State
from runs.service import _session_worker
from runs.sidecar_client import _sidecar_call
from users import access
from users.caller import CallerDep
router = APIRouter()
TASK_TOOLS = ("shell", "claude:Monitor") # neutral tool names
MAX_LINES = 200
def _task(deps, caller, conv_id: str, task_id: str) -> tuple[str, dict]:
"""The conversation's session id and the thread card that started the task
(404 for a conversation the caller can't see or a task it didn't start)."""
# conversations.routes reaches into runs at import time: imported here.
from conversations.catalog import _resolve_transcript # noqa: PLC0415
from conversations.routes import _parse_full_snapshot, _public_id # noqa: PLC0415
cid = _public_id(deps, conv_id)
access.ensure_visible(deps, caller, cid)
data, _, _ = _parse_full_snapshot(_resolve_transcript(cid))
sid = data.get("sessionId")
item = next((it for it in data.get("thread") or []
if it.get("taskId") == task_id and it.get("name") in TASK_TOOLS), None)
if not sid or item is None:
raise HTTPException(404, "no such background task in this conversation")
return sid, item
def _message(e: HTTPException) -> str:
d = e.detail
return d.get("message", str(d)) if isinstance(d, dict) else str(d)
@router.get("/api/conversation-task-output", responses=_r(schemas.TaskOutput))
def task_output(deps: State, caller: CallerDep, id: str, task: str, lines: int = 20):
"""The last ``lines`` lines a background shell / Monitor wrote."""
sid, _ = _task(deps, caller, id, task)
try:
out = _sidecar_call(deps, "/tasks/output",
{"sessionId": sid, "taskId": task,
"lines": max(1, min(lines, MAX_LINES))},
timeout=8, worker=_session_worker(deps, sid))
except HTTPException as e:
# Gone with the run's temp dir, a worker offline, no sidecar: the card
# says so in place of the tail — not an error toast every 2 s.
if e.status_code in (404, 409, 502, 503):
return {"taskId": task, "available": False, "lines": [], "reason": _message(e)}
raise
return {**out, "taskId": task, "available": True}
class TaskStopBody(BaseModel):
id: str
taskId: str
@router.post("/api/conversation-task-stop", responses=_r(schemas.TaskStopResult))
def task_stop(deps: State, caller: CallerDep, body: TaskStopBody):
"""Stop one background shell / Monitor of a live run (SIGTERM to its
process group, SIGKILL after a grace) — who may stop the run may stop it."""
sid, item = _task(deps, caller, body.id, body.taskId)
access.ensure_runs_here(deps, caller, sid)
if not caller.is_owner and not access.can_send(deps, caller, sid, stop=True):
raise HTTPException(403, "you can read this conversation but not stop it")
monitor = item.get("name") == "claude:Monitor"
inp = item.get("input") if isinstance(item.get("input"), dict) else {}
out = _sidecar_call(deps, "/tasks/stop",
{"sessionId": sid, "taskId": body.taskId,
"kind": "monitor" if monitor else "shell",
"command": inp.get("command") if monitor else None},
timeout=20, worker=_session_worker(deps, sid))
stops = dict(deps.meta_store.peek(sid).get("taskStops") or {})
stops[body.taskId] = round(time.time(), 3)
deps.meta_store.update(sid, {"taskStops": stops})
deps.hub.publish({"type": "meta", "id": sid})
return {"ok": True, "taskId": body.taskId, "forced": bool(out.get("forced"))}