Files

730 lines
31 KiB
Python
Executable File

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["click", "requests"]
# ///
"""handoff — hand a conversation over to a new one on another model, harness or machine.
The model that has the context writes a brief (template.md); this CLI does the
mechanical half around it: it gathers the facts (git state, the source's
guidelines, its model and machine), assembles and saves the final prompt, checks
that uncommitted work can follow, and starts the successor through the ai-agent
hub with `ai-agent new --detach`, then links the two conversations through the
Handoff plugin's `link` action (the hub draws "Continued in →" / "Continued from ←").
handoff context [ID] facts about a conversation (default: this one)
handoff start BRIEF [--from ID] --model M assemble + save + start the new conversation
handoff start BRIEF --print assemble + save, print it (to paste elsewhere)
handoff material ID --model M cold path: a file a writer model reads
handoff cold ID --model M [--writer haiku] cold path: a writer conversation does it all
handoff link FROM TO [--model M] record a handoff started by hand (a Mac)
This file ships in the ai-agent Handoff plugin's skill (scripts/handoff is the
wrapper to call); the plugin's actions are reached through the hub's tool proxy
(scripts/hubclient.py: AIA_TOOLS_URL + AIA_TOOLS_TOKEN, else hub.json).
Target flags (start / material / cold): --model, --harness, --on, --account,
--effort, --cwd — the same as `ai-agent new`.
Global flags come before the subcommand: `--json` (one JSON object on stdout),
`-v` (chatter on stderr). Exit 0 ok, 1 handled failure, 2 usage.
"""
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile
import time
from datetime import date
from pathlib import Path
import click
import requests
SCRIPT_DIR = Path(__file__).resolve().parent
SKILL_DIR = SCRIPT_DIR.parent
# What to run: the wrapper beside this file (the skill isn't on PATH — it is a
# live plugin's, materialized by the hub; the lab sync copies it to the Macs).
HANDOFF_CMD = str(SCRIPT_DIR / "handoff")
TEMPLATE = SKILL_DIR / "template.md"
PLUGIN_ID = "handoff"
sys.path.insert(0, str(SCRIPT_DIR))
import hubclient # noqa: E402 (stdlib: the hub's tool proxy)
HOMELAB = Path(os.environ.get("HANDOFF_HOMELAB", "~/homelab")).expanduser()
HUB = os.environ.get("AI_AGENT_URL", "http://127.0.0.1:8096").rstrip("/")
# A prompt travels as one argv string: Linux caps one at 128 KiB (MAX_ARG_STRLEN).
MAX_PROMPT = 100_000
# The cold path's material file: what fits a writer's context with room to spare.
MATERIAL_BUDGET = 240_000
SCAFFOLD_BUDGET = 60_000
WORKTREES = Path("~/worktrees").expanduser()
# --------------------------------------------------------------------------- #
# shared helpers
# --------------------------------------------------------------------------- #
def load_env_claude() -> None:
"""Load private defaults from the gitignored .env.claude: up from this file,
then the hub's root checkout (the skill lives in the hub's plugin data now)."""
for d in [*SCRIPT_DIR.parents, HOMELAB]:
f = d / ".env.claude"
if f.is_file():
for line in f.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export "):]
if "=" not in line:
continue
key, _, val = line.partition("=")
key, val = key.strip(), val.strip()
if len(val) >= 2 and val[0] == val[-1] and val[0] in "\"'":
val = val[1:-1]
os.environ[key] = val
return
load_env_claude()
def err(msg: str) -> None:
click.echo(msg, err=True)
def die(msg: str, code: int = 1):
err(f"handoff: {msg}")
sys.exit(code)
def emit(ctx: click.Context, payload: dict, human: str) -> None:
if ctx.obj["json"]:
click.echo(json.dumps(payload, ensure_ascii=False, indent=2))
else:
click.echo(human)
def run(cmd: list[str], cwd: str | None = None, timeout: float = 60) -> subprocess.CompletedProcess:
try:
return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout)
except FileNotFoundError:
return subprocess.CompletedProcess(cmd, 127, "", f"{cmd[0]}: not found")
except subprocess.TimeoutExpired:
return subprocess.CompletedProcess(cmd, 124, "", f"{cmd[0]}: timed out after {timeout:.0f}s")
# --------------------------------------------------------------------------- #
# the hub
# --------------------------------------------------------------------------- #
def my_session() -> str:
"""This session's id: $CLAUDE_SESSION_ID, else the conv-meta PID-ancestry helper."""
sid = os.environ.get("CLAUDE_SESSION_ID", "").strip()
if sid:
return sid
for root in (HOMELAB,):
helper = root / ".claude/skills/conv-meta/scripts/resolve-session.sh"
if helper.is_file():
out = run([str(helper)], timeout=30)
if out.returncode == 0 and out.stdout.strip():
return out.stdout.strip().splitlines()[-1]
return ""
def ai_agent(*args: str, timeout: float = 120) -> subprocess.CompletedProcess:
return run(["ai-agent", *args], timeout=timeout)
def conversation(ref: str, messages: bool = True, rendered: bool = False) -> dict:
"""The hub's record of a conversation: ids, url, title, meta, model, messages.
`ai-agent show` resolves every spelling of an id (session, conversation,
prefix, viewer link); the card adds the model, which `show --json` lacks.
"""
args = ["show", ref, "--json"] + (["--full"] if messages else [])
out = ai_agent(*args)
if out.returncode == 2 and "worker" in (out.stderr or "").lower():
die("the ai-agent CLI is lab-only — on a Mac, follow SKILL.md → 'On a Mac'")
if out.returncode != 0:
die(f"ai-agent show {ref}: {(out.stderr or out.stdout).strip()[:300]}")
c = json.loads(out.stdout)
try:
r = requests.get(f"{HUB}/api/conversations", params={"sessions": c["sessionId"]}, timeout=20)
cards = r.json().get("conversations") or []
c["model"] = (cards[0].get("model") if cards else None) or c["meta"].get("model")
except (requests.RequestException, ValueError):
c["model"] = c["meta"].get("model")
if rendered:
# The thread in the same markdown `ai-agent show --full` prints.
text = ai_agent("show", ref, "--full", "--tools")
c["rendered"] = text.stdout if text.returncode == 0 else ""
return c
def first_prompt(c: dict) -> str:
for m in c.get("messages") or []:
if m.get("role") == "user" and m.get("kind") == "text" and (m.get("text") or "").strip():
return m["text"]
return ""
_GUIDELINES = re.compile(r"(?m)^Guidelines:[ \t]*$")
def guidelines_of(prompt: str) -> str:
"""The `Guidelines:` block the composer appends to a first prompt, verbatim."""
m = None
for m in _GUIDELINES.finditer(prompt):
pass
return prompt[m.start():].strip() if m else ""
def transcript_cwd(sid: str) -> str:
"""The working directory recorded in this machine's transcript of `sid`."""
roots = [Path("~/.claude/projects").expanduser()]
if os.environ.get("CLAUDE_CONFIG_DIR"):
roots.insert(0, Path(os.environ["CLAUDE_CONFIG_DIR"]) / "projects")
roots += list(Path("~").expanduser().glob(".claude-*/projects"))
for root in roots:
for path in root.glob(f"*/{sid}.jsonl"):
with path.open() as fh:
for _, line in zip(range(40), fh):
try:
cwd = json.loads(line).get("cwd")
except ValueError:
continue
if cwd:
return cwd
return ""
def worker_label(worker: str | None) -> str:
return worker or "lab"
def workers() -> list[dict]:
out = ai_agent("workers", "--json", timeout=30)
try:
return json.loads(out.stdout) if out.returncode == 0 else []
except ValueError:
return []
def same_machine(src_worker: str | None, on: str | None) -> bool:
"""Does `--on` name the machine the source runs on? (None/local/lab = the lab.)"""
lab = {"", "local", "lab"}
target = (on or "").strip()
if target.lower() in lab:
return src_worker in (None, "")
if not src_worker:
return False
if target == src_worker:
return True
names = {w.get("id"): (w.get("name") or "") for w in workers()}
return names.get(src_worker, "").lower() == target.lower()
# --------------------------------------------------------------------------- #
# git
# --------------------------------------------------------------------------- #
def git(d: str, *args: str) -> str:
out = run(["git", "-C", d, *args], timeout=30)
# rstrip only: `status --short` lines start with a meaningful space.
return out.stdout.rstrip() if out.returncode == 0 else ""
def repo_state(d: str) -> dict | None:
top = git(d, "rev-parse", "--show-toplevel")
if not top:
return None
branch = git(top, "rev-parse", "--abbrev-ref", "HEAD")
upstream = git(top, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
ahead = behind = None
if upstream:
counts = git(top, "rev-list", "--left-right", "--count", f"{upstream}...HEAD").split()
if len(counts) == 2:
behind, ahead = int(counts[0]), int(counts[1])
base = next((b for b in ("main", "master", "origin/main", "origin/master")
if git(top, "rev-parse", "--verify", "--quiet", b)), "")
commits = git(top, "log", "--oneline", "-15", f"{base}..HEAD").splitlines() if base and branch not in ("main", "master") else []
status = git(top, "status", "--short").splitlines()
return {"dir": top, "branch": branch, "upstream": upstream or None, "ahead": ahead,
"behind": behind, "base": base or None, "commits": commits,
"dirty": len(status), "status": status[:25]}
def repo_dirs(c: dict, cwd: str) -> list[str]:
"""The source's working directory plus its live worktrees under ~/worktrees."""
dirs = [cwd] if cwd else []
for wt in c["meta"].get("worktrees") or []:
if wt.get("removedAt") or not wt.get("dir"):
continue
p = WORKTREES / wt["dir"]
if p.is_dir():
dirs.append(str(p))
return dirs
def repos(c: dict, cwd: str) -> list[dict]:
seen, out = set(), []
for d in repo_dirs(c, cwd):
st = repo_state(d)
if st and st["dir"] not in seen:
seen.add(st["dir"])
out.append(st)
return out
def unpushed(st: dict) -> bool:
if st["branch"] in ("HEAD", ""):
return True
if st["upstream"] is None:
return bool(st["commits"])
return bool(st["ahead"])
# --------------------------------------------------------------------------- #
# facts
# --------------------------------------------------------------------------- #
def facts(c: dict, cwd: str | None = None) -> dict:
m = c["meta"]
local = not m.get("worker")
cwd = cwd if cwd is not None else (transcript_cwd(c["sessionId"]) if local else "")
return {
"id": c["id"], "sessionId": c["sessionId"], "url": c["url"],
"title": c.get("title") or "", "model": c.get("model"), "harness": m.get("harness"),
"account": m.get("account"), "worker": m.get("worker"), "machine": worker_label(m.get("worker")),
"projects": m.get("projects") or [], "cwd": cwd or None,
"worktrees": [w for w in (m.get("worktrees") or []) if not w.get("removedAt")],
"repos": repos(c, cwd) if local else [],
"guidelines": guidelines_of(first_prompt(c)),
}
def facts_md(f: dict) -> str:
lines = [f"# {f['title'] or 'Conversation'}", "",
f"- conversation: {f['id']} — {f['url']}",
f"- session: {f['sessionId']}",
f"- ran on: {' · '.join(str(x) for x in (f['model'], f['harness'], f['account'], f['machine']) if x)}"]
if f["projects"]:
lines.append(f"- projects: {', '.join(f['projects'])}")
if f["cwd"]:
lines.append(f"- working directory: {f['cwd']}")
if f["worktrees"] and not f["repos"]:
lines.append("- worktrees: " + ", ".join(w.get("dir") or w.get("name") or "?" for w in f["worktrees"]))
for st in f["repos"]:
track = st["upstream"] or "no upstream"
sync = ""
if st["ahead"] is not None:
sync = f", {st['ahead']} ahead / {st['behind']} behind"
lines += ["", f"## {st['dir']}", "",
f"branch `{st['branch']}` → {track}{sync}; {st['dirty']} uncommitted"]
if st["commits"]:
lines += ["", f"commits on the branch (not on {st['base']}):", "```", *st["commits"], "```"]
if st["status"]:
lines += ["", "uncommitted:", "```", *st["status"], "```"]
lines += ["", "## Guidelines (`handoff start` appends them verbatim)", "",
f["guidelines"] or "(none in the first prompt)"]
return "\n".join(lines)
# --------------------------------------------------------------------------- #
# the prompt
# --------------------------------------------------------------------------- #
def slugify(text: str) -> str:
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return s[:48].rstrip("-") or "handoff"
def assemble(brief: str, f: dict | None) -> str:
"""Brief + a link back to the source + the source's guidelines, verbatim."""
parts = [brief.strip()]
if f:
ran = " · ".join(str(x) for x in (f["model"], f["harness"], f["machine"]) if x)
parts.append(
"---\n"
f"Handed over from conversation {f['id']} ({ran}): {f['url']}\n"
f"Read more of it with `ai-agent show {f['id']} --tail 20` "
"(on a Mac: the hub's get_conversation tool)."
)
if f["guidelines"] and not _GUIDELINES.search(brief):
parts.append("The original task's guidelines follow, word for word. A step it lists "
"that the brief says is done (questions asked, a worktree made) is not "
"repeated.\n\n" + f["guidelines"])
return "\n\n".join(parts) + "\n"
def handoff_dir() -> Path:
env = os.environ.get("HANDOFF_DIR")
if env:
return Path(env).expanduser()
if (HOMELAB / "data").is_dir():
return HOMELAB / "data" / "handoffs"
return Path("~/.local/share/handoff").expanduser()
def save(prompt: str, sid: str) -> Path:
first = next((ln for ln in prompt.splitlines() if ln.strip()), "handoff")
first = re.sub(r"^(#+\s*)?(continue:\s*)?", "", first, flags=re.I)
d = handoff_dir()
d.mkdir(parents=True, exist_ok=True)
path = d / f"{date.today().isoformat()}-{(sid or 'nosession')[:8]}-{slugify(first)}.md"
path.write_text(prompt)
return path
def target_args(model, harness, on, account, effort) -> list[str]:
args = []
for flag, val in (("--model", model), ("--harness", harness), ("--on", on),
("--account", account), ("--effort", effort)):
if val:
args += [flag, val]
return args
def target_options(f):
for opt in reversed([
click.option("--model", help="Target model (matched against `ai-agent models`)."),
click.option("--harness", type=click.Choice(["claude", "opencode", "pi", "agy"]),
help="Target harness (default: the one serving --model)."),
click.option("--on", "on", metavar="WORKER", help="Target machine: a worker id or name, or 'local'."),
click.option("--account", help="The login it bills (default: the machine's ★)."),
click.option("--effort", type=click.Choice(["low", "medium", "high", "xhigh", "max"])),
]):
f = opt(f)
return f
# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.option("--json", "as_json", is_flag=True, help="Emit the result as JSON on stdout.")
@click.option("-v", "--verbose", is_flag=True, help="Log progress to stderr.")
@click.version_option("0.2.0", prog_name="handoff")
@click.pass_context
def cli(ctx: click.Context, as_json: bool, verbose: bool) -> None:
"""Hand a conversation over to a new one on another model, harness or machine."""
ctx.obj = {"json": as_json, "verbose": verbose}
@cli.command()
@click.argument("ref", required=False)
@click.pass_context
def context(ctx: click.Context, ref: str | None) -> None:
"""Facts about a conversation (default: this one) — what the brief must not get wrong."""
sid = ref or my_session()
if not sid:
die("could not tell which conversation this is — pass its id")
c = conversation(sid)
f = facts(c)
emit(ctx, f, facts_md(f))
@cli.command()
@click.argument("brief", type=click.File("r"))
@click.option("--from", "src", metavar="ID", help="The conversation handed over (default: this one).")
@target_options
@click.option("--cwd", help="Working directory of the new conversation "
"(default on the same machine: the source's).")
@click.option("--project", "projects", multiple=True, help="Tag a project (default: the source's).")
@click.option("--print", "print_only", is_flag=True,
help="Assemble and save the prompt, print it — start nothing (to paste into another tool).")
@click.option("--allow-dirty", is_flag=True,
help="Start on another machine even though work here is uncommitted or unpushed.")
@click.option("--test", "test_run", is_flag=True,
help="A throwaway successor (archived when its turn ends) — to try the skill out.")
@click.pass_context
def start(ctx, brief, src, model, harness, on, account, effort, cwd, projects, print_only, allow_dirty,
test_run):
"""Assemble BRIEF ('-' = stdin) into the new conversation's prompt and start it."""
text = brief.read()
if len(text.strip()) < 200:
die("the brief is nearly empty — write it first (see template.md)")
if not print_only and not (model or harness):
die("say where it goes: --model and/or --harness (or --print to paste it elsewhere)", 2)
sid = src or my_session()
f = None
if sid:
f = facts(conversation(sid))
elif not print_only:
die("could not tell which conversation this is — pass --from ID")
else:
err("handoff: no source conversation found — no link back, no guidelines appended")
prompt = assemble(text, f)
if len(prompt) > MAX_PROMPT:
die(f"the prompt is {len(prompt):,} characters — keep the brief under ~{MAX_PROMPT // 1000}K "
"(point to files instead of pasting them)")
saved = save(prompt, f["sessionId"] if f else "")
if print_only:
if ctx.obj["json"]:
emit(ctx, {"saved": str(saved), "prompt": prompt, "from": f}, "")
else:
click.echo(prompt, nl=False)
err(f"saved: {saved}")
return
# Uncommitted work follows only on the same machine (the successor reuses the
# worktree); elsewhere it has to be on the remote first.
same = same_machine(f["worker"], on)
if same and not cwd and f["cwd"]:
cwd = f["cwd"]
if not same and not allow_dirty:
stuck = [st for st in f["repos"] if st["dirty"] or unpushed(st)]
if stuck:
lines = []
for st in stuck:
lines.append(f" {st['dir']} ({st['branch']}): {st['dirty']} uncommitted"
+ (", commits not pushed" if unpushed(st) else ""))
lines += [f" {ln}" for ln in st["status"][:8]]
die("the new conversation runs on another machine and can't see this work:\n"
+ "\n".join(lines)
+ "\ncommit it (a WIP commit is fine), push the branch, name it in the brief, "
"then run start again — or pass --allow-dirty (changes that aren't this "
"conversation's work, or a target that doesn't need them)")
# `--detach`: a handoff is no child of this conversation (no report back);
# the Handoff plugin's `link` action then stamps both ends.
args = ["new", prompt, "--json", "--detach",
*target_args(model, harness, on, account, effort)]
if cwd:
args += ["--cwd", cwd]
if test_run:
args.append("--test")
for p in projects or f["projects"]:
args += ["--project", p]
out = ai_agent(*args, timeout=180)
if out.returncode != 0:
die(f"ai-agent new: {(out.stderr or out.stdout).strip()[:500]}\n(the prompt is saved: {saved})")
try:
new = json.loads(out.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
new = {"raw": out.stdout.strip()}
linked = False
if new.get("sessionId"):
try:
link_call(f["sessionId"], new["sessionId"], model=model, harness=harness, worker=on,
title=title_of(text))
linked = True
except hubclient.HubError as e:
# Started all the same: only the two banners are missing.
err(f"handoff: started, but not linked (the Handoff plugin's link action: {e}) — "
f"`{HANDOFF_CMD} link {f['sessionId']} {new['sessionId']}` to retry")
if not new.get("url") and new.get("sessionId"):
new.update(lookup(new["sessionId"]))
url = new.get("url") or ""
for line in (out.stderr or "").splitlines():
if ctx.obj["verbose"] or "→" in line:
err(line)
emit(ctx, {"from": {k: f[k] for k in ("id", "sessionId", "url", "model", "harness", "machine")},
"to": new, "url": url, "saved": str(saved), "cwd": cwd, "linked": linked},
f"handed over → {url}\nprompt saved: {saved}")
def title_of(brief: str) -> str:
"""The new conversation's title: the brief's first line, without `Continue:`."""
first = next((ln for ln in brief.splitlines() if ln.strip()), "")
return re.sub(r"^(#+\s*)?(continue:\s*)?", "", first.strip(), flags=re.I)[:200]
def link_call(src: str, new: str, *, model=None, harness=None, worker=None, title=None) -> dict:
"""The Handoff plugin's `link` action: `new` continues `src` (both ends stamped)."""
body = {"from": src, "to": new, "model": model, "harness": harness, "worker": worker,
"title": title}
return hubclient.call("POST", f"plugins/{PLUGIN_ID}/actions/link",
json_body={k: v for k, v in body.items() if v}, timeout=60)
def lookup(sid: str, tries: int = 8, pause: float = 3.0) -> dict:
"""`ai-agent new --json` names the session only: find its conversation id and
link once the hub has indexed the new transcript (a few seconds)."""
for i in range(tries):
out = ai_agent("show", sid, "--json", timeout=30)
if out.returncode == 0:
try:
c = json.loads(out.stdout)
return {"id": c.get("id"), "url": c.get("url")}
except ValueError:
pass
if i < tries - 1:
time.sleep(pause)
return {}
@cli.command()
@click.argument("ref")
@target_options
@click.option("--cwd", help="Passed through to the `handoff start` line it writes.")
@click.option("--out", "out_path", type=click.Path(dir_okay=False), help="Where to write the file.")
@click.option("--budget", type=int, default=MATERIAL_BUDGET, show_default=True,
help="Characters of material (the thread is trimmed from the middle).")
@click.pass_context
def material(ctx, ref, model, harness, on, account, effort, cwd, out_path, budget):
"""Cold path: write what a writer model needs to brief conversation REF, print its path.
The file opens with the writer's instructions (the template and the exact
`handoff start` line to run), then the facts, conv-scaffold's digest and the
thread itself.
"""
if not (model or harness):
die("say where it goes: --model and/or --harness", 2)
c = conversation(ref, rendered=True)
f = facts(c)
workdir = Path(tempfile.gettempdir()) / f"handoff-{c['sessionId'][:8]}"
workdir.mkdir(parents=True, exist_ok=True)
out = Path(out_path) if out_path else workdir / "material.md"
brief_path = workdir / "brief.md"
start_cmd = shlex.join([HANDOFF_CMD, "start", str(brief_path), "--from", c["sessionId"],
*target_args(model, harness, on, account, effort),
*(["--cwd", cwd] if cwd else [])])
scaffold = run(["conv-scaffold", "--session", c["sessionId"], "--stdout"], timeout=150)
scaffold_txt = scaffold.stdout if scaffold.returncode == 0 else f"(conv-scaffold failed: {scaffold.stderr.strip()[:200]})"
# Its Summary / Analysis sections are the `complete` skill's blanks to fill.
scaffold_txt = re.split(r"(?m)^## Summary\s*$", scaffold_txt)[0]
scaffold_txt = trim(scaffold_txt, SCAFFOLD_BUDGET, "conv-scaffold")
head = "\n".join([
f"# Handoff material — {f['title'] or c['id']}",
"",
"## Your instructions",
"",
f"You are writing the handoff brief for conversation {c['id']} ({f['url']}). "
"You were not in it: everything you need is in this file. Do not continue its work yourself.",
"",
"1. Read this whole file.",
f"2. Write the brief to `{brief_path}` following the template below.",
f"3. Run: `{start_cmd}`",
" If it refuses because work is uncommitted on another machine, do NOT commit for it: "
"rerun with `--allow-dirty` and say in the brief which files are uncommitted where.",
"4. Your final message is the new conversation's link (the `handed over →` line).",
"",
TEMPLATE.read_text().strip(),
"",
"## Facts",
"",
facts_md(f),
"",
"## Digest (conv-scaffold: prompts, tool summaries, the squashed diff)",
"",
scaffold_txt.strip(),
"",
"## The thread",
"",
])
thread = trim_thread(c.get("rendered") or "", max(20_000, budget - len(head)))
out.write_text(head + thread + "\n")
emit(ctx, {"material": str(out), "brief": str(brief_path), "start": start_cmd,
"chars": len(head) + len(thread)}, str(out))
def trim(text: str, budget: int, what: str) -> str:
if len(text) <= budget:
return text
keep = budget // 2
return f"{text[:keep]}\n\n[… {len(text) - budget:,} characters of {what} cut …]\n\n{text[-keep:]}"
_MSG = re.compile(r"(?m)^## .+ \[\d+\]\s*$")
def trim_thread(text: str, budget: int) -> str:
"""Keep the opening messages and as many of the latest as fit; cut the middle."""
if len(text) <= budget:
return text
starts = [m.start() for m in _MSG.finditer(text)]
if len(starts) < 4:
return trim(text, budget, "the thread")
chunks = [text[a:b] for a, b in zip(starts, starts[1:] + [len(text)])]
head = text[:starts[0]] + "".join(chunks[:2])
room = budget - len(head)
tail: list[str] = []
for ch in reversed(chunks[2:]):
if len(ch) > room:
break
tail.insert(0, ch)
room -= len(ch)
cut = len(chunks) - 2 - len(tail)
marker = f"\n[… {cut} messages cut — read them with `ai-agent show <id> --full` if needed …]\n\n" if cut else ""
return head + marker + "".join(tail)
def writer_prompt(conv_id: str, model, harness, on, account, effort, note: str | None) -> str:
"""The cold writer's prompt — the Handoff plugin's `handoff` action (mode cold,
handlers/handoff_lib.cold_prompt) sends the same text."""
cmd = shlex.join(["handoff", "material", conv_id, *target_args(model, harness, on, account, effort)])
text = (f"Hand off conversation {conv_id} to {model or harness} — write its handoff brief from the transcript.\n\n"
f"Use the handoff skill: run its `{cmd}`, read the file it prints and follow the instructions "
"at its top: write the brief, then run the `handoff start` command it gives. Your final message "
"is the new conversation's link.")
if note:
text += f"\n\nNote for the next agent (put it in the brief): {note.strip()}"
return text
@cli.command()
@click.argument("ref")
@target_options
@click.option("--writer", default="haiku", show_default=True,
help="The model that writes the brief (e.g. 'qwen' or 'gemini-3.8-flash' when Claude is out).")
@click.option("--note", help="Something to tell the next agent; it goes into the brief.")
@click.option("--wait", "wait_", is_flag=True, help="Block until the writer is done, print its answer.")
@click.option("--timeout", type=int, default=540, show_default=True, help="--wait gives up after N s.")
@click.pass_context
def cold(ctx, ref, model, harness, on, account, effort, writer, note, wait_, timeout):
"""Cold path: a cheap writer conversation briefs conversation REF from its transcript and starts the successor.
For when REF's own model can't write the brief (out of quota, broken, gone).
"""
if not (model or harness):
die("say where it goes: --model and/or --harness", 2)
c = conversation(ref, messages=False)
prompt = writer_prompt(c["id"], model, harness, on, account, effort, note)
out = ai_agent("new", prompt, "--model", writer, "--test", "--detach",
"--cwd", str(HOMELAB), "--json", timeout=180)
if out.returncode != 0:
die(f"ai-agent new: {(out.stderr or out.stdout).strip()[:500]}")
try:
w = json.loads(out.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
die(f"unexpected ai-agent output: {out.stdout[:300]}")
if not w.get("url") and w.get("sessionId"):
w.update(lookup(w["sessionId"]))
url = w.get("url") or ""
if not wait_:
emit(ctx, {"writer": w, "url": url, "from": c["id"]},
f"writer started → {url}\nits final message will be the new conversation's link")
return
done = ai_agent("wait", w["sessionId"], "--timeout", str(timeout), timeout=timeout + 30)
if done.returncode == 4:
die(f"the writer is still going after {timeout}s — `ai-agent wait {w['sessionId'][:8]}` again", 4)
emit(ctx, {"writer": w, "url": url, "answer": done.stdout}, done.stdout.strip())
@cli.command()
@click.argument("src", metavar="FROM")
@click.argument("new", metavar="TO")
@click.option("--model", help="The model the new conversation runs (shown on the banner).")
@click.option("--harness", type=click.Choice(["claude", "opencode", "pi", "agy"]))
@click.option("--on", "on", metavar="WORKER", help="The machine it runs on.")
@click.option("--title", help="Its title (default: none until it has synced).")
@click.pass_context
def link(ctx, src, new, model, harness, on, title):
"""Record that conversation TO continues FROM (both session ids) — after a
successor started by hand (a Mac: the hub's start_conversation tool)."""
try:
out = link_call(src, new, model=model, harness=harness, worker=on, title=title)
except hubclient.HubError as e:
die(f"link: {e}")
emit(ctx, out, f"linked: {new} continues {src}")
if __name__ == "__main__":
cli()