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>
376 lines
18 KiB
Python
376 lines
18 KiB
Python
"""Tool calls: the activity buckets and their sub-labels, the project /
|
|
service / worktree / commit evidence mined from them, the lifecycle stamps and
|
|
deploys, agent launches and task lists."""
|
|
|
|
import pathlib
|
|
import re
|
|
|
|
from ..deploycmd import deploy_invocation
|
|
|
|
|
|
# Map a neutral tool name (readers/toolnames.py) → the activity bucket we
|
|
# attribute its turn's tokens/cost to (so a conversation's spend can be broken
|
|
# down by what it was spent doing: plain messages, sub-agents, the shell, file
|
|
# reads/edits, …). Anything else — a harness's own tool, an MCP tool,
|
|
# `ask_user` — is the catch-all "tool".
|
|
TOOL_BUCKETS = {
|
|
"shell": "shell", "shell_output": "shell", "shell_kill": "shell",
|
|
"read": "read",
|
|
"write": "edit", "edit": "edit", "apply_patch": "edit", "delete_file": "edit",
|
|
"grep": "search", "glob": "search", "list_dir": "search",
|
|
"web_fetch": "web", "web_search": "web",
|
|
"agent": "agent",
|
|
"skill": "skill",
|
|
"todo": "todo",
|
|
}
|
|
# All buckets the UI may show ("msg" = text-only turns, "context" = the first
|
|
# API call's injected context share, "tool" = catch-all).
|
|
TOOL_BUCKET_ORDER = ["msg", "context", "agent", "shell", "read", "edit", "search",
|
|
"skill", "web", "todo", "tool"]
|
|
|
|
|
|
# Where homelab projects and services live — only there do `projects/<slug>/`
|
|
# and `services/<slug>/` name one. Other repos have folders of those names of
|
|
# their own (the Orus monorepo's `docs/projects/nl-aovql/`,
|
|
# `…/modules/<m>/services/<file>.ts`), and those are not lab projects/services.
|
|
# A homelab checkout is `~/homelab`, `~/homelab-<wt>`, `~/worktrees/homelab-<wt>`
|
|
# or a `.claude/worktrees/<wt>` of one; a repo-relative path counts too.
|
|
_HOMELAB_ROOT = r"/homelab[^/]*/(?:\.claude/worktrees/[^/]+/)?"
|
|
# A homelab project is `~/projects/<slug>/…` (on the lab or a worker), or
|
|
# `projects/<slug>/…` under a homelab checkout (the old layout). Claude's own
|
|
# transcript store (`.claude/projects/<encoded-path>`) is excluded by the
|
|
# leading-dash filter below, since those encoded names always start with a dash.
|
|
_PROJECT_RE = re.compile(
|
|
rf"(?:^|^/(?:home|Users)/[^/]+/|{_HOMELAB_ROOT})projects/([A-Za-z0-9._][\w.-]*)/")
|
|
# A homelab service is `<homelab checkout>/services/<slug>/…` — the infra side
|
|
# of the repo. <slug> is a directory: a file right in `services/` is none.
|
|
_SERVICE_RE = re.compile(rf"(?:^|{_HOMELAB_ROOT})services/([A-Za-z0-9._][\w.-]*)/")
|
|
|
|
# A conversation is attributed to a project/service only when it actually
|
|
# **worked on** it — i.e. created or edited a file under `projects/<slug>` or
|
|
# `services/<slug>`. We therefore mine the auto-tags exclusively from the
|
|
# file-mutating tools' target paths (`write` / `edit` / `delete_file` →
|
|
# `file_path`, a notebook `edit` → `notebook_path`), *not* from the cwd, plain
|
|
# reads, searches, or shell commands that merely mention a path. This keeps the
|
|
# tag list to projects the conversation genuinely changed, instead of
|
|
# everything it happened to look at or `cd` into.
|
|
_EDIT_TOOLS = {"write", "edit", "delete_file"}
|
|
# Caps on the stored `writtenDirsAuto` / `gitRootsAuto` / `worktreeAddsAuto`.
|
|
_MAX_WRITTEN_DIRS = 300
|
|
_MAX_GIT_ROOTS = 40
|
|
_MAX_WORKTREE_ADDS = 40
|
|
|
|
# A conversation that ran `scripts/new-worktree.sh <name>` spun up an isolated git
|
|
# worktree to do its work in (per the repo's CLAUDE.md convention), and one that
|
|
# ran `new-worktree.sh -r <path>` tore one down. We mine both out of the command
|
|
# so the viewer can flag which worktrees a conversation created (and when it
|
|
# removed them). To avoid matching mentions inside quoted strings / echo / grep
|
|
# (rife in a conversation *about* the script, like this one), we anchor to a
|
|
# command position: the script must sit at the start of the command or right
|
|
# after a shell separator (`;`, `&&`, `|`, `(`, newline) or a `bash`/`sudo`/…
|
|
# prefix — an optional path in front, then `new-worktree.sh` and its arg tail (up
|
|
# to the next separator). Events are teased out in `_worktree_events`.
|
|
_WORKTREE_RE = re.compile(
|
|
r"(?:^|[\n;&|(]|\b(?:bash|sh|sudo|exec|command)[ \t])[ \t]*"
|
|
r"(?:[\w./-]*/)?new-worktree\.sh\b([^\n|&;<>]*)")
|
|
# Management-mode flags that only list/help — they create and remove nothing.
|
|
_WORKTREE_NOOP_FLAGS = {"-l", "--list", "-h", "--help"}
|
|
# A plausible worktree name / directory basename (git-ref-ish). Anything with
|
|
# shell quoting or punctuation is parse noise, not a real invocation, and is
|
|
# dropped — a second line of defense behind the command-position anchor above.
|
|
_WORKTREE_NAME_RE = re.compile(r"^[A-Za-z0-9][\w./-]*$")
|
|
|
|
|
|
# A shell command that can print git's `[branch sha] subject` commit line.
|
|
_COMMIT_CMD_RE = re.compile(r"\bgit\b[^\n]*\b(commit|merge|cherry-pick|revert|rebase|am|pull)\b"
|
|
r"|\bcommit-(homelab|project)\b")
|
|
# …that commits, then prints the result with a one-commit `git log`.
|
|
_LOG_ONE_RE = re.compile(r"\bgit\b[^\n;&|]*\bcommit\b[\s\S]*\bgit\b[^\n;&|]*\blog\b"
|
|
r"[^\n;&|]*(\s-1\b|\s-n\s*1\b|--max-count=1\b)")
|
|
|
|
|
|
# An `agent` call spawned with ``run_in_background`` gets its tool_result the
|
|
# instant the agent launches ("Async agent launched successfully… agentId: …"),
|
|
# so — unlike a blocking agent, whose result *is* its report — that result says
|
|
# nothing about whether the agent is still working. Its real end signal is the
|
|
# ``<task-notification>`` Claude Code injects when the agent stops, which names
|
|
# the agent call it belongs to. Only a result that *starts* with the agentId
|
|
# is a launch: a blocking agent's report ends on an "agentId: … (use
|
|
# SendMessage …)" line too.
|
|
_AGENT_ASYNC_RE = re.compile(r"Async agent launched|\A\s*agentId:")
|
|
# A SendMessage to an agent that had already stopped resumes it in the
|
|
# background ("Resuming agent …"): its call runs again until the next
|
|
# `<task-notification>` — which names the SendMessage, not the Agent call
|
|
# (``_agents_done``). One sent to a running agent is only queued.
|
|
_AGENT_RESUMED_RE = re.compile(r'"resumedAgentId"\s*:\s*"([\w-]+)"')
|
|
|
|
|
|
# A *recalled* memory is injected into the transcript (as a tool_result) with its
|
|
# full file content — frontmatter + body. We detect each one by its frontmatter
|
|
# (``name: <slug>`` shortly above ``node_type: memory``) and record the slug, so
|
|
# the viewer can show which memories a conversation read. The lazy span keeps the
|
|
# slug bound to the nearest ``node_type: memory`` below it; the session-start
|
|
# MEMORY.md index (plain ``- [..](..md)`` lines) carries no such frontmatter and
|
|
# so is correctly ignored.
|
|
_MEMORY_RE = re.compile(
|
|
r"name:\s*([A-Za-z0-9][\w.-]*)\s*\n[\s\S]{0,400}?node_type:\s*memory")
|
|
|
|
|
|
# ── lifecycle backfill ───────────────────────────────────────────────────────
|
|
# The CI/CD-style stamps (committed/pushed/merged/deployed/notified) are normally
|
|
# written live by the skill scripts (conv-meta.sh, called from the commit / deploy
|
|
# / notify skills) into the metadata sidecar. For conversations that ran before
|
|
# those hooks existed — or that committed/deployed via plain git/deploy commands —
|
|
# the sidecar is empty, so the status icons never light up. We *derive* the stamps
|
|
# from the transcript instead: scan each skill/shell tool call for evidence the
|
|
# action happened, and stamp it with that turn's timestamp. These derived values
|
|
# are merged non-destructively under `lifecycleAuto` (the live sidecar wins).
|
|
#
|
|
# The actual deploy commands (as opposed to the `conv-meta ... deployed` stamp
|
|
# below, which only *records* one after the fact) are recognised by what the
|
|
# command *runs* — `deploycmd.deploy_invocation` — not by a regex over its text,
|
|
# which also lit up on `cat deploy.sh`, `bash -n deploy.sh`, commit messages….
|
|
# Reused to detect a deploy in flight, see `_deploy_call`.
|
|
|
|
# Each pattern matches a command/skill-name string; a hit lights its stage(s).
|
|
_LIFECYCLE_PATTERNS: list[tuple[str, re.Pattern]] = [
|
|
# commit-homelab / commit-project both commit *and* push to Gitea.
|
|
("committed", re.compile(r"\b(?:commit-homelab|commit-project)\b")),
|
|
("pushed", re.compile(r"\b(?:commit-homelab|commit-project)\b")),
|
|
("committed", re.compile(r"\bgit\b[^\n|&;]*\bcommit\b")),
|
|
("pushed", re.compile(r"\bgit\b[^\n|&;]*\bpush\b")),
|
|
("merged", re.compile(r"\bgit\s+merge\b")),
|
|
# (deploy paths: skill/alias, npm/pnpm/yarn deploy, zipgo, make deploy,
|
|
# *.sh — matched by `deploy_invocation` in `_lifecycle_stages`.)
|
|
("notified", re.compile(r"\b(?:notify-done|notify-ask|notify\.sh|notify\s+(?:send|ask|form))\b")),
|
|
# explicit conv-meta stamps (e.g. `conv-meta.sh committed`).
|
|
("committed", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bcommitted\b")),
|
|
("pushed", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bpushed\b")),
|
|
("merged", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bmerged\b")),
|
|
("deployed", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bdeployed\b")),
|
|
("notified", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bnotified\b")),
|
|
]
|
|
# `skill` invocations (matched on the `skill` input) → stage(s).
|
|
_SKILL_STAGES: dict[str, tuple[str, ...]] = {
|
|
"commit-homelab": ("committed", "pushed"),
|
|
"commit-project": ("committed", "pushed"),
|
|
"deploy-html": ("deployed",),
|
|
"notify-done": ("notified",),
|
|
}
|
|
|
|
|
|
# ── deployed URL ─────────────────────────────────────────────────────────────
|
|
# Every deploy path prints where the thing landed, but always *last* and often
|
|
# after a very long build log — and the result we ship to the UI is clipped to
|
|
# MAX_BLOCK chars. So the URL is pulled out of the raw output here, before the
|
|
# clip, and hung on the tool card as `deployedUrl` (the UI turns it into a live
|
|
# preview widget + the conversation's "open the deploy" gizmo).
|
|
_DEPLOY_URL_PATTERNS: list[re.Pattern] = [
|
|
re.compile(r"Deployed URL\s*[:=]\s*(https?://[^\s'\"<>]+)"),
|
|
re.compile(r"Live:\s*HTTP\s*\d+\s*at\s+(https?://[^\s'\"<>]+)"),
|
|
re.compile(r"(?:deployed|live|serving|available)\s+(?:at|on)\s+(https?://[^\s'\"<>]+)",
|
|
re.IGNORECASE),
|
|
re.compile(r"https://[\w.-]+\.(?:gabvdl\.xyz|gabriel\.vidal--ayrinhac\.xyz)[^\s'\"<>]*"),
|
|
]
|
|
|
|
|
|
def _deployed_url(rtext: str) -> str | None:
|
|
"""The URL a deploy command reported, best-effort (raw, unclipped output)."""
|
|
for pat in _DEPLOY_URL_PATTERNS:
|
|
m = pat.search(rtext)
|
|
if m:
|
|
url = m.group(1) if m.groups() else m.group(0)
|
|
return url.rstrip(".,;:)\"'")
|
|
return None
|
|
|
|
|
|
def _lifecycle_stages(name: str | None, inp: dict) -> set[str]:
|
|
"""Stages a tool call provides evidence for (best-effort, may over-report)."""
|
|
stages: set[str] = set()
|
|
if name == "skill":
|
|
stages.update(_SKILL_STAGES.get((inp.get("skill") or ""), ()))
|
|
cmd = inp.get("command")
|
|
if isinstance(cmd, str) and cmd:
|
|
for stage, pat in _LIFECYCLE_PATTERNS:
|
|
if stage not in stages and pat.search(cmd):
|
|
stages.add(stage)
|
|
if "deployed" not in stages and deploy_invocation(cmd):
|
|
stages.add("deployed")
|
|
return stages
|
|
|
|
|
|
def _deploy_call(name: str | None, inp: dict) -> dict | None:
|
|
"""``{kind, target}`` if this tool call itself performs (or wraps) a deploy,
|
|
else ``None`` — hung on the tool card as ``deploy`` (the UI's deploy widget)
|
|
and used to detect one in flight, unlike `_lifecycle_stages`'s "deployed"
|
|
hit, which also fires on the post-hoc `conv-meta ... deployed` stamp."""
|
|
if name == "skill":
|
|
if inp.get("skill") == "deploy-html":
|
|
args = inp.get("args")
|
|
return {"kind": "deploy-html", "target": args if isinstance(args, str) else ""}
|
|
return None
|
|
if name != "shell":
|
|
return None
|
|
hit = deploy_invocation(inp.get("command"))
|
|
return {"kind": hit[0], "target": hit[1]} if hit else None
|
|
|
|
|
|
def _bucket(tool: str | None) -> str:
|
|
return TOOL_BUCKETS.get(tool or "", "tool")
|
|
|
|
|
|
# The leading program of a shell command — the sub-label a "shell" turn is broken
|
|
# down by (git / npm / docker / …). We skip common env/prefix wrappers so the
|
|
# real command shows through (e.g. `sudo docker …` → docker, `FOO=1 npm …` → npm).
|
|
_BASH_PREFIX = {"sudo", "env", "time", "nice", "nohup", "exec", "command",
|
|
"xargs", "then", "do", "if", "!"}
|
|
|
|
|
|
def _bash_program(command) -> str:
|
|
"""First real program name in a shell command (for the shell sub-breakdown)."""
|
|
if not isinstance(command, str):
|
|
return "?"
|
|
cmd = command.strip()
|
|
# `cd <dir> && <real cmd>` / `(cd <dir>; …)` is pervasive here — skip the cd
|
|
# prefix so the actual command shows through instead of "cd".
|
|
cmd = re.sub(r"^\(?\s*cd\s+[^\n&;|]+(?:&&|;|\|\|)\s*", "", cmd).lstrip("(").strip()
|
|
# Only look at the first pipeline/segment; strip a leading subshell/paren.
|
|
seg = re.split(r"[|;&\n]", cmd, 1)[0].strip().lstrip("(").strip()
|
|
for tok in seg.split():
|
|
# Skip VAR=value assignments and known wrapper prefixes.
|
|
if "=" in tok and not tok.startswith("-") and re.match(r"^\w+=", tok):
|
|
continue
|
|
if tok in _BASH_PREFIX:
|
|
continue
|
|
# Basename, drop any path so `/usr/bin/git` and `git` collapse together.
|
|
prog = tok.rsplit("/", 1)[-1]
|
|
return prog or "?"
|
|
return "?"
|
|
|
|
|
|
def _file_ext(inp: dict) -> str:
|
|
"""File extension sub-label for a read/edit turn (e.g. `.py`, `.tsx`)."""
|
|
p = inp.get("file_path") or inp.get("notebook_path") or ""
|
|
if not isinstance(p, str) or not p:
|
|
return "?"
|
|
base = p.rsplit("/", 1)[-1]
|
|
dot = base.rfind(".")
|
|
# Leading-dot names (`.env`) are extension-less; everything after the dot else.
|
|
if dot > 0:
|
|
return base[dot:].lower()
|
|
return "(no ext)"
|
|
|
|
|
|
def _subkey(bucket: str, tool: str | None, inp: dict) -> str | None:
|
|
"""The second-level breakdown label for a turn, given its activity bucket:
|
|
shell → program, read/edit → file extension, skill → constant "skills
|
|
read", any other tool bucket → the (neutral) tool name. ``None`` for
|
|
text-only (msg) turns, which are split by prompt/reply at accumulation time
|
|
instead."""
|
|
if bucket == "shell":
|
|
return _bash_program(inp.get("command"))
|
|
if bucket in ("read", "edit"):
|
|
return _file_ext(inp)
|
|
if bucket == "skill":
|
|
return "skills read"
|
|
if bucket == "msg":
|
|
return None
|
|
return tool or "tool"
|
|
|
|
|
|
def todo_op(inp: dict) -> str:
|
|
"""What a ``todo`` call does, told by its input (the neutral name covers
|
|
Claude Code's five task tools): ``snapshot`` — the whole list again
|
|
(TodoWrite's ``todos``); ``update`` — one task by id (TaskUpdate;
|
|
TaskGet's lone id changes nothing); ``create`` — a new task (TaskCreate's
|
|
``subject``); ``list`` — nothing to fold (TaskList)."""
|
|
if isinstance(inp.get("todos"), list):
|
|
return "snapshot"
|
|
if inp.get("taskId") or inp.get("task_id"):
|
|
return "update"
|
|
if inp.get("subject") or inp.get("content"):
|
|
return "create"
|
|
return "list"
|
|
|
|
|
|
# Valid task states we normalise to; anything else falls back to "pending".
|
|
_TASK_STATES = {"pending", "in_progress", "completed", "cancelled"}
|
|
_TASK_SUBJECT_MAX = 200
|
|
|
|
|
|
def _task_subject(s) -> str:
|
|
"""A short, single-line label for a task (bounded for the compact panel)."""
|
|
s = " ".join(str(s or "").split()).strip() or "task"
|
|
return s[:_TASK_SUBJECT_MAX]
|
|
|
|
|
|
def _projects_in(text) -> set[str]:
|
|
"""Pull homelab `projects/<name>` slugs out of an edited file's path."""
|
|
if not isinstance(text, str):
|
|
return set()
|
|
return {m.group(1) for m in _PROJECT_RE.finditer(text)
|
|
if not m.group(1).startswith("-")}
|
|
|
|
|
|
def _services_in(text) -> set[str]:
|
|
"""Pull homelab `services/<name>` slugs out of an edited file's path."""
|
|
if not isinstance(text, str):
|
|
return set()
|
|
return {m.group(1) for m in _SERVICE_RE.finditer(text)
|
|
if not m.group(1).startswith("-")}
|
|
|
|
|
|
def _worktree_events(text) -> list[dict]:
|
|
"""Worktree create/remove events in a `new-worktree.sh` command string.
|
|
|
|
Each event is ``{"kind": "create"|"remove", "name": str, "dir": str}`` where
|
|
``dir`` is the worktree *directory* basename — the stable key both a create
|
|
and its later removal share:
|
|
- create (``new-worktree.sh <name> [branch]`` / ``-p <project> <name>``):
|
|
``name`` is the ``<name>`` arg; ``dir`` is ``homelab-<name>`` (super mode)
|
|
or ``<project>-<name>`` (project mode) — i.e. the created directory —
|
|
and ``project`` the repo it is a worktree of (``homelab`` or the ``-p``
|
|
value; ``dir`` alone can't say where a dashed slug ends).
|
|
- remove (``new-worktree.sh -r <path>``): ``dir`` is ``basename(<path>)``
|
|
(``name`` empty — the short name is recovered by pairing on ``dir``).
|
|
List/help modes create nothing and yield no events."""
|
|
events: list[dict] = []
|
|
if not isinstance(text, str):
|
|
return events
|
|
for m in _WORKTREE_RE.finditer(text):
|
|
args = m.group(1).split()
|
|
i = 0
|
|
name = project = remove_path = None
|
|
noop = False
|
|
while i < len(args):
|
|
a = args[i]
|
|
if a in _WORKTREE_NOOP_FLAGS:
|
|
noop = True
|
|
break
|
|
if a in ("-r", "--remove"):
|
|
remove_path = args[i + 1] if i + 1 < len(args) else None
|
|
i += 2
|
|
continue
|
|
if a in ("-p", "--project"): # takes a value (the project) — skip both
|
|
project = args[i + 1] if i + 1 < len(args) else None
|
|
i += 2
|
|
continue
|
|
if a.startswith("-"): # any other flag (e.g. --no-link)
|
|
i += 1
|
|
continue
|
|
if name is None:
|
|
name = a # first bare positional = worktree name
|
|
i += 1
|
|
if noop:
|
|
continue
|
|
if remove_path:
|
|
d = pathlib.PurePosixPath(remove_path.rstrip("/")).name
|
|
if _WORKTREE_NAME_RE.match(d):
|
|
events.append({"kind": "remove", "name": "", "dir": d})
|
|
elif name and _WORKTREE_NAME_RE.match(name) and (
|
|
project is None or _WORKTREE_NAME_RE.match(project)):
|
|
d = f"{project}-{name}" if project else f"homelab-{name}"
|
|
events.append({"kind": "create", "name": name, "dir": d,
|
|
"project": project or "homelab"})
|
|
return events
|