import json
import subprocess
import time
import uuid
from pathlib import Path
def bridge_call(bridge, op, **args):
encoded = json.dumps({"op": op, **args}, ensure_ascii=False)
result = subprocess.run(
[bridge, "--json", "agents", "launch", "core-request"],
input=encoded, capture_output=True, text=True, encoding="utf-8", timeout=20,
)
if result.returncode:
raise HerdrError("Herdr Core 请求结果未确认,保留原任务回执。")
response = json.loads(result.stdout)
if response.get("error"):
raise HerdrError(response["error"]["message"])
return response["result"]
def resolve_terminal(call, state):
records = call("find", token=state["token"])["terminals"]
records = [row for row in records if row.get("labels", {}).get("agenthub.run") == state["token"]]
if len(records) != 1:
raise HerdrError("无法唯一确认原 Herdr Core 启动结果,保留原任务回执。")
row = records[0]
if state.get("address") and row["address"] != state["address"]:
raise HerdrError("原 Herdr Core 终端地址发生变化。")
if state.get("identity") and row["identity"] != state["identity"]:
raise HerdrError("原 Herdr Core 终端身份发生变化。")
if (not row.get("identity") or row.get("keep") is not False
or row["labels"].get("agenthub.checkout") != state["cwd"]):
raise HerdrError("无法核实原 Herdr Core 终端的项目归属。")
if not state.get("address") or not state.get("identity"):
state.update(address=row["address"], pane=row["address"], identity=row["identity"])
save_state(state)
return row
def terminal_status(row):
status = row.get("status")
return status.get("state") if isinstance(status, dict) and row.get("reported") is True else None
def collect(call, state, row, timeout, observe_only):
deadline = time.monotonic() + timeout
while True:
status = terminal_status(row)
if row.get("state") != "live" or status in ("blocked", "error"):
state["phase"] = "attention"
save_state(state)
print("Herdr Core 终端已退出、报错或等待确认。", flush=True)
return 1
if status in ("idle", "done") and (row.get("turn") or 0) > state["baseline_turn"]:
output = call("read", terminal=state["address"])
print(output.get("text", ""), flush=True)
state.update(phase="completed", completion_seq=row["turn"])
if state.get("continuation"):
state["continuation"]["status"] = "submitted"
save_state(state)
return 0
if observe_only or time.monotonic() >= deadline:
print("原 Herdr Core 回合尚无完成证据,保留终端,不重复发起。", flush=True)
return 1
time.sleep(2)
row = resolve_terminal(call, state)
def send(call, state, row, prompt, continuation_id=None):
if row.get("state") != "live" or terminal_status(row) not in ("idle", "done"):
raise HerdrError("原 Agent 未就绪,保留终端。")
turn = row.get("turn") or 0
state.update(phase="submitted", baseline_turn=turn)
if continuation_id:
state["continuation"] = {"id": continuation_id, "status": "uncertain"}
else:
state.pop("continuation", None)
save_state(state)
reply = call("send", terminal=state["address"], identity=state["identity"],
cwd=state["cwd"], turn=turn, prompt=prompt)
if continuation_id and reply.get("started") is True:
state["continuation"]["status"] = "submitted"
save_state(state)
def run(bridge, previous, config, kind, arguments, prompt, cwd, title, request):
def call(op, **args):
return bridge_call(bridge, op, **args)
core_id = call("status").get("core", {}).get("id")
if not core_id:
raise HerdrError("Herdr Core 没有返回可核实的身份。")
continuation = request.get("continuation_prompt", "")
continuation_id = request.get("continuation_id", "")
observe_only = request.get("reconcile_only", False)
recovery = request.get("recover_closed", False)
timeout = config["execution"]["wait_timeout_seconds"]
migrated = None
if previous.get("backend") != "hc":
if observe_only:
return 1 if continuation else 0
if previous:
if previous.get("phase") != "completed":
raise HerdrError("原后端任务仍未完成。")
migrated = STATE_DIR / ("previous-agent-" + uuid.uuid4().hex + ".json")
save_state(previous, migrated)
previous = {}
if previous:
if previous.get("core_id") != core_id or previous.get("cwd") != str(cwd):
raise HerdrError("原 Herdr Core 或项目发生变化,保留原任务回执。")
row = resolve_terminal(call, previous)
if recovery:
if (row.get("state") != "finished" or request.get("recovery_pane")
or previous.get("phase") != "completed"
or previous.get("continuation", {}).get("status") == "uncertain"):
raise HerdrError("需要已确认结束的 Core 终端和已完成的原回合,才能恢复。")
if previous.get("recovery", {}).get("id") == continuation_id:
raise HerdrError("同一恢复操作已尝试,保留原任务回执。")
archive = STATE_DIR / ("closed-agent-" + uuid.uuid4().hex + ".json")
save_state(previous, archive)
prompt = continuation
elif continuation:
if previous.get("continuation", {}).get("id") == continuation_id:
print("同一续作已尝试,保留原终端,不重复投递。", flush=True)
return 0
if previous.get("phase") != "completed":
raise HerdrError("原 Agent 回合未确认完成,不能投递续作。")
send(call, previous, row, continuation, continuation_id)
return 0
elif previous.get("phase") != "completed":
return collect(call, previous, row, timeout, observe_only)
elif observe_only:
return 0
elif (row.get("state") == "live" and terminal_status(row) in ("idle", "done")
and time.time() - previous.get("agent_started_at", 0) < config["execution"].get("session_reuse_seconds", 0)):
send(call, previous, row, prompt)
return collect(call, previous, row, timeout, False)
elif observe_only:
return 1 if continuation else 0
state = {
"backend": "hc", "core_id": core_id, "cwd": str(cwd), "session": "default",
"token": str(uuid.uuid4()), "phase": "submitted", "prompt_attempted": True,
"baseline_turn": 0, "agent_started_at": int(time.time()),
}
if migrated:
state["previous_checkpoint"] = str(migrated)
if recovery:
state["recovery"] = {"id": continuation_id, "previous_checkpoint": str(archive)}
save_state(state)
started = call(
"start", cwd=str(cwd), token=state["token"], title=title,
agent=kind, scheme=config["launch"].get("scheme_id"),
expected_plan=config["launch"].get("_expected_plan"),
arguments=arguments, prompt=prompt,
)
state["address"] = started["address"]
save_state(state)
row = resolve_terminal(call, state)
if recovery:
return 0
return collect(call, state, row, timeout, False)