A preset is a named ladder of routes (model + harness + effort). A run sent on preset:<id> — or on its source's default preset — takes the first rung with room for its profile's login, and a follow-up steps down when its rung fills. Provider plugins say which usage windows a model draws on (quotaWindows). A Claude run's own subagents are held to the subagents preset's first Claude route with room (subagentModel → CLAUDE_CODE_SUBAGENT_MODEL). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
119 lines
5.2 KiB
Python
119 lines
5.2 KiB
Python
"""
|
|
``POST /fork`` — branch a new session off an existing one at a message
|
|
boundary — the harness plugin's driver does it (claude: a truncated copy
|
|
of the transcript, ``harness-claude``'s ``runs.fork_transcript``; pi: the
|
|
runner's native fork; opencode: opencode's own) — and ``POST /relocate``.
|
|
"""
|
|
|
|
import re
|
|
import shutil
|
|
|
|
from fastapi import APIRouter, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
import harness_loader
|
|
import inhibit
|
|
import pids
|
|
from claude_env import _account_projects, _valid_account
|
|
from launch import _run_cwd, _stop_run, agent_limit
|
|
from validate import _auth, _valid_harness, _valid_uuid, harness_unavailable
|
|
|
|
router = APIRouter()
|
|
|
|
class ForkBody(BaseModel):
|
|
sessionId: str # fresh uuid for the fork (backend-minted)
|
|
srcSessionId: str # the session to branch off
|
|
prompt: str # the edited message — the fork's next turn
|
|
cutLine: int # raw JSONL line index of the fork point
|
|
cutText: str | None = None # collapsed prefix of that message (canary)
|
|
cutUserOrd: int | None = None # its 0-based ordinal among user msgs (pi)
|
|
cutKey: str | None = None # its record's `ocKey` (opencode: user:<msg id>)
|
|
model: str | None = None
|
|
effort: str | None = None # opencode: the model ref's #variant
|
|
cwd: str | None = None # must match the source session's cwd
|
|
harness: str | None = None # "claude" (default) | "pi" | "opencode"
|
|
account: str | None = None # the source session's account
|
|
scope: dict | None = None # a scoped run (see routes_runs.SpawnBody)
|
|
appendSystemPrompt: str | None = None # per-run extras (routes_runs.SpawnBody)
|
|
agents: dict | None = None
|
|
agentLimit: int | None = None # see routes_runs.SpawnBody.agentLimit
|
|
subagentModel: str | None = None # see routes_runs.SpawnBody.subagentModel
|
|
|
|
|
|
@router.post("/fork")
|
|
def fork(body: ForkBody, authorization: str | None = Header(default=None)) -> dict:
|
|
"""Branch a new session off an existing one at a message boundary.
|
|
|
|
Claude Code has no message-level fork (``--fork-session`` clones whole
|
|
sessions), so: copy the source session file truncated at the fork point
|
|
under a fresh session id (see ``_fork_transcript``), then ``claude -p
|
|
<prompt> --resume <newSid>`` — claude loads the truncated history and
|
|
appends the edited turn. The pi harness forks natively: pi sessions are
|
|
trees, so the runner branches pi's own session file (``--fork-from``) and
|
|
mirrors the truncated prefix itself."""
|
|
_auth(authorization)
|
|
prompt = (body.prompt or "").strip()
|
|
if not prompt:
|
|
raise HTTPException(400, "empty prompt")
|
|
new_sid = _valid_uuid(body.sessionId)
|
|
src_sid = _valid_uuid(body.srcSessionId)
|
|
harness = _valid_harness(body.harness)
|
|
driver = harness_loader.get(harness)
|
|
if driver is None:
|
|
raise harness_unavailable(harness)
|
|
driver.valid_model(body.model)
|
|
cwd = _run_cwd(body.cwd)
|
|
with agent_limit(body.agentLimit, body.subagentModel):
|
|
out = driver.fork(body, src_sid, new_sid, cwd, harness_loader.context())
|
|
inhibit.INHIBITOR.poke() # the fork runs a turn: hold the sleep lock
|
|
return out
|
|
|
|
|
|
class RelocateBody(BaseModel):
|
|
sessionId: str
|
|
cwd: str # the directory the session goes on in
|
|
account: str | None = None # the session's account
|
|
|
|
|
|
def _cwd_slug(cwd: str) -> str:
|
|
"""Claude Code's transcript folder name for a cwd: every character that
|
|
isn't a letter or digit becomes ``-``."""
|
|
return re.sub(r"[^A-Za-z0-9]", "-", cwd)
|
|
|
|
|
|
@router.post("/relocate")
|
|
def relocate(body: RelocateBody, authorization: str | None = Header(default=None)) -> dict:
|
|
"""Let a session go on in another working directory.
|
|
|
|
``--resume`` only finds a session in the current directory's transcript
|
|
folder, so the session file is copied (same id) into ``cwd``'s folder;
|
|
the next ``/resume`` with that ``cwd`` picks it up there with its whole
|
|
history, and Claude Code appends to that copy. The hub collapses the two
|
|
files into one conversation (``_dedup_by_session``: the newest wins).
|
|
|
|
A live run is stopped first — it would otherwise keep writing to the old
|
|
copy. What the hub's *New project* flow calls once the project exists."""
|
|
_auth(authorization)
|
|
sid = _valid_uuid(body.sessionId)
|
|
cwd = _run_cwd(body.cwd)
|
|
account = _valid_account(body.account)
|
|
rec = pids._live_record(sid)
|
|
if rec:
|
|
_stop_run(sid, rec)
|
|
projects = _account_projects(account)
|
|
dst_dir = projects / _cwd_slug(cwd)
|
|
dst = dst_dir / f"{sid}.jsonl"
|
|
copies = list(projects.glob(f"*/{sid}.jsonl"))
|
|
if not copies:
|
|
raise HTTPException(404, f"session {sid} not found under {projects}")
|
|
# Several copies (it moved before): the one written last is the session.
|
|
src = max(copies, key=lambda p: p.stat().st_mtime)
|
|
if src == dst:
|
|
return {"sessionId": sid, "cwd": cwd, "path": str(dst), "copied": False}
|
|
dst_dir.mkdir(parents=True, exist_ok=True)
|
|
tmp = dst.with_suffix(".jsonl.tmp")
|
|
shutil.copyfile(src, tmp)
|
|
tmp.replace(dst)
|
|
return {"sessionId": sid, "cwd": cwd, "path": str(dst), "from": str(src),
|
|
"copied": True}
|