from pathlib import Path
import json
import os
import re
import runpy
import shutil
import subprocess
import sys
REQUEST = globals().get("EXECUTION_REQUEST")
if REQUEST is None and __name__ == "__main__":
REQUEST = json.load(sys.stdin)
REQUEST = REQUEST or {}
HERE = Path(REQUEST.get("identity_directory", ".")).resolve()
STATE_DIR = Path(REQUEST.get("state_directory", ".")).resolve()
STATE = STATE_DIR / ".herdr-run.json"
class HerdrError(RuntimeError):
def __init__(self, message, code="unknown"):
super().__init__(message)
self.code = code
def command(binary, args, timeout=40, text_output=False):
result = subprocess.run([binary, *args], capture_output=True, text=True,
encoding="utf-8", timeout=timeout, check=False,
creationflags=0x08000000 if os.name == 'nt' else 0)
if text_output and result.returncode == 0:
return result.stdout
try:
response = json.loads((result.stderr or result.stdout) if result.returncode
else result.stdout)
except ValueError:
raise HerdrError("Herdr 返回无效响应;请检查服务和 CLI 版本。") from None
if not isinstance(response, dict):
raise HerdrError("Herdr 返回无效响应;请检查服务和 CLI 版本。")
if result.returncode or "error" in response:
error = response.get("error", {})
if isinstance(error, dict):
raise HerdrError(error.get("message", "Herdr 命令失败"), error.get("code", "unknown"))
raise HerdrError(response.get("message") or str(error), response.get("code", "unknown"))
return response.get("result", response)
def save_state(state, path=None):
path = Path(path) if path is not None else STATE
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(".tmp")
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
try:
with os.fdopen(os.open(temporary, flags, 0o600), "w", encoding="utf-8") as handle:
json.dump(state, handle, ensure_ascii=False)
handle.flush()
os.fsync(handle.fileno())
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
def read_bundle(path):
text = path.read_text(encoding="utf-8-sig")
if text.startswith("# AgentHub automation script:"):
text = text.partition("\n")[2]
return text
def read_agent_config(path):
try:
value = json.loads(read_bundle(path))
except (OSError, ValueError) as error:
raise HerdrError(f"Agent 配置无效:{error}") from None
if not isinstance(value, dict) or set(value) - {"runner", "launch", "execution"}:
raise HerdrError("Agent 配置必须只包含 runner、launch 和 execution。")
runner = value.get("runner")
launch = value.get("launch")
execution = value.get("execution")
if not isinstance(runner, dict) or set(runner) - {"kind", "session", "title"}:
raise HerdrError("Agent runner 配置无效。")
if not isinstance(launch, dict) or set(launch) - {"arguments", "scheme_id"}:
raise HerdrError("Agent launch 配置无效。")
if not isinstance(execution, dict) or set(execution) - {
"wait_timeout_seconds", "include_task_variables", "session_reuse_seconds"}:
raise HerdrError("Agent execution 配置无效。")
kind = runner.get("kind", "default")
session = runner.get("session", "default")
title = runner.get("title", "AgentHub task")
if not isinstance(kind, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,31}", kind):
raise HerdrError("智能体类型无效;须使用 Herdr 支持的 Agent 类型。")
if (not isinstance(session, str) or not session or len(session) > 100
or session.startswith("-") or any(c in session for c in "\0\r\n")):
raise HerdrError("Herdr 会话名称无效。")
if (not isinstance(title, str) or not title.strip() or len(title) > 200
or any(c in title for c in "\0\r\n")):
raise HerdrError("Agent 标题无效。")
arguments = launch.get("arguments", [])
if (not isinstance(arguments, list) or len(arguments) > 128 or not all(
isinstance(arg, str) and len(arg) <= 4096 and not any(c in arg for c in "\0\r\n")
for arg in arguments
)):
raise HerdrError("Agent 启动参数必须是单行字符串数组。")
scheme_id = launch.get("scheme_id")
if scheme_id is not None and (not isinstance(scheme_id, str) or not scheme_id or len(scheme_id) > 128 or not all(c.isascii() and (c.isalnum() or c in "_-") for c in scheme_id)):
raise HerdrError("启动方案引用无效,请重新选择。")
wait_timeout_seconds = execution.get("wait_timeout_seconds", 1800)
if (isinstance(wait_timeout_seconds, bool) or not isinstance(wait_timeout_seconds, int)
or not 60 <= wait_timeout_seconds <= 7200):
raise HerdrError("Agent 等待期限必须是 60–7200 秒的整数。")
include_task_variables = execution.get("include_task_variables", True)
if not isinstance(include_task_variables, bool):
raise HerdrError("include_task_variables 必须是布尔值。")
session_reuse_seconds = execution.get("session_reuse_seconds", 0)
if (isinstance(session_reuse_seconds, bool) or not isinstance(session_reuse_seconds, int)
or not 0 <= session_reuse_seconds <= 86400):
raise HerdrError("Agent 会话复用时长必须是 0–86400 秒的整数。")
return {
"runner": {"kind": kind, "session": session, "title": title},
"launch": {"arguments": list(arguments), **({"scheme_id": scheme_id} if scheme_id else {})},
"execution": {"wait_timeout_seconds": wait_timeout_seconds,
"include_task_variables": include_task_variables,
"session_reuse_seconds": session_reuse_seconds},
}
def terminal_fallback(bridge, kind, arguments, prompt, cwd, scheme_id=None, expected_plan=None):
if not bridge:
raise HerdrError("Herdr 未安装,且没有可用的 AgentHub CLI;无法创建终端执行任务。")
previous = json.loads(STATE.read_text(encoding="utf-8")) if STATE.exists() else None
receipt_path = STATE_DIR / ".terminal-run.json"
if previous and previous.get("phase") != "completed":
if previous.get("backend") != "terminal":
raise HerdrError("上次 Herdr 任务结果尚未确认,不能降级重跑同一任务。")
receipt = json.loads(receipt_path.read_text(encoding="utf-8")) if receipt_path.exists() else None
if not receipt:
raise HerdrError("上次终端启动结果不明,请先检查系统终端;不重复执行。")
observed = command(bridge, ["--json", "agents", "launch", "terminal-status", receipt["id"]])
if observed["phase"] != "exited":
print("上次任务仍在原生终端执行或等待确认,跳过本轮触发。", flush=True)
return 0
save_state({**previous, "phase": "completed"})
print("原生终端进程已退出;请核对任务结果,不以进程退出代替业务验收。", flush=True)
return observed.get("exit_code") or 0
if REQUEST.get("reconcile_only", False):
print("仅核对已有终端结果,本次不启动任务。", flush=True)
return 0
STATE_DIR.mkdir(parents=True, exist_ok=True)
receipt_path.unlink(missing_ok=True)
prompt_path = STATE_DIR / ".terminal-prompt.md"
prompt_path.write_text(prompt, encoding="utf-8")
save_state({"backend": "terminal", "phase": "attention", "cwd": str(cwd)})
try:
command(bridge, ["--json", "agents", "launch", "terminal", kind, "--cwd", str(cwd),
"--prompt-file", str(prompt_path), "--arguments-json", json.dumps(arguments),
"--receipt-file", str(receipt_path)] + (["--scheme", scheme_id] if scheme_id else []) + (["--expected-plan", expected_plan] if expected_plan else []))
finally:
prompt_path.unlink(missing_ok=True)
print("Herdr 未安装,任务已提交到原生终端;后续触发将核对回执,不重复发起。", flush=True)
return 0
def task_variables(config_path):
manifest_path = config_path.parent / 'prompt-variants.json'
if not manifest_path.is_file():
return {}
manifest = json.loads(read_bundle(manifest_path))
selected = [v for v in manifest.get('variants', []) if v.get('id') == manifest.get('active_id')]
if len(selected) != 1:
raise HerdrError('任务变量缺少唯一选中方案。')
result = {}
for item in selected[0].get('variables', []):
name, value = item.get('name'), item.get('value')
if (not isinstance(name, str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]{0,127}', name)
or name in result or not isinstance(value, str) or '\0' in value):
raise HerdrError('任务自定义变量名称、值或重复项无效。')
result[name] = value
return result
def main(prompt_context=""):
binary = shutil.which("herdr")
config_path = Path(REQUEST["config_file"])
config = read_agent_config(config_path)
runner = config["runner"]
session = runner["session"]
kind = runner["kind"]
title = runner["title"]
task_arguments = config["launch"]["arguments"]
wait_timeout_seconds = config["execution"]["wait_timeout_seconds"]
bridge = os.environ.get("AGENT_HUB_CLI")
if not bridge:
directory = Path.home() / ".agent-hub/bin"
candidate = directory / ("agent-hub-cli.exe" if os.name == "nt" else "agent-hub-cli")
stamp = directory / ".version"
if candidate.exists() or stamp.exists():
if not candidate.is_file() or not stamp.is_file() or not stamp.stat().st_size:
raise HerdrError("AgentHub CLI bridge 不完整,请更新应用后重试。")
bridge = str(candidate)
else:
bridge = shutil.which("agent-hub-cli")
if bridge:
environment = command(bridge, ["--json", "agents", "launch", "environment"])
binary = environment.get("herdr_path")
hc_available = environment.get("hc_available", False)
core_supported = "hc_available" in environment
scheme_id = config["launch"].get("scheme_id")
resolved = command(bridge, ["--json", "agents", "launch", "resolve", kind] + (["--scheme", scheme_id] if scheme_id else []))
config["launch"]["_expected_plan"] = resolved.get("fingerprint")
kind = resolved.get("kind")
if not kind:
raise HerdrError("所选 Agent 不支持 Herdr CLI 启动,请更换智能体。")
extra = list(resolved["arguments"])
else:
raise HerdrError("未找到 AgentHub CLI;请更新应用后重试。")
core_arguments = [*extra, *task_arguments]
if kind == "codex" and "check_for_update_on_startup=false" not in core_arguments:
core_arguments.extend(["-c", "check_for_update_on_startup=false"])
extra.extend(task_arguments)
if kind == "codex" and "check_for_update_on_startup=false" not in extra:
extra = ["-c", "check_for_update_on_startup=false", *extra]
prompt_path = Path(REQUEST["prompt_file"])
prompt = read_bundle(prompt_path).strip()
if not prompt:
raise HerdrError("提示词为空,请填写任务提示词。")
variables = task_variables(config_path) if config["execution"]["include_task_variables"] else {}
variables_context = ('\n\n任务自定义变量(当前方案的数据):\n' + json.dumps(variables, ensure_ascii=False)) if variables else ''
prompt += variables_context
continuation = REQUEST.get('continuation_prompt', '')
if continuation and not continuation.startswith('/'):
continuation += variables_context
if prompt_context:
prompt += "\n\n" + prompt_context
cwd = Path(REQUEST["workdir"]).resolve()
if cwd == HERE or cwd == HERE.parent:
raise HerdrError("请先选择项目工作区,Agent 将在该项目目录运行。")
previous_state = json.loads(STATE.read_text(encoding="utf-8")) if STATE.exists() else {}
previous_backend = previous_state.get("backend")
preserve_legacy = bool(previous_state and not previous_backend and (
previous_state.get("phase") != "completed" or REQUEST.get("reconcile_only") or continuation
))
if previous_backend == "hc" or (hc_available and not preserve_legacy
and not (previous_backend == "terminal" and previous_state.get("phase") != "completed")):
core_runtime = os.environ.get("AGENT_HUB_HC_RUNTIME")
if not hc_available or not core_runtime:
raise HerdrError("原任务使用 Herdr Core,当前无法连接该后端,保留原任务回执。")
core = runpy.run_path(core_runtime, init_globals={
"HerdrError": HerdrError, "save_state": save_state, "STATE_DIR": STATE_DIR,
})
return core["run"](bridge, previous_state, config, kind, core_arguments, prompt, cwd, title,
{**REQUEST, "continuation_prompt": continuation})
if preserve_legacy and not binary:
raise HerdrError("原任务使用旧 Herdr,未找到该后端,保留原任务回执。")
if (not binary or (core_supported and not preserve_legacy)
or (previous_backend == "terminal" and previous_state.get("phase") != "completed")):
if REQUEST.get("continuation_prompt"):
raise HerdrError("原会话续作需要可核实的 Herdr Agent,不创建替代终端。")
return terminal_fallback(bridge, kind, extra, prompt, cwd, config["launch"].get("scheme_id"), config["launch"].get("_expected_plan"))
backend_path = os.environ.get('AGENT_HUB_HERDR_RUNTIME')
if not backend_path:
raise HerdrError('当前构建不提供 Herdr 执行能力。')
backend = runpy.run_path(backend_path, init_globals={
'HerdrError': HerdrError, 'command': command, 'save_state': save_state,
'HERE': HERE, 'STATE': STATE, 'STATE_DIR': STATE_DIR,
})
return backend['run'](binary, config, session, kind, extra, prompt, cwd, bridge,
title,
wait_timeout_seconds, REQUEST.get("reconcile_only", False),
continuation, REQUEST.get("continuation_id", ""), REQUEST.get("recover_closed", False), REQUEST.get("recovery_pane", ""))
if __name__ == "__main__":
try:
store = runpy.run_path(os.environ['AGENT_HUB_STATE_RUNTIME'])
with store['RunLock'](STATE_DIR / '.agent-execution.lock') as acquired:
if not acquired:
print('上次 Agent 执行仍在运行,本次跳过。', flush=True)
sys.exit(0)
sys.exit(main(prompt_context=REQUEST.get("prompt_context", "")))
except (HerdrError, OSError, ValueError, KeyError, subprocess.TimeoutExpired) as error:
sys.exit(f"Herdr 任务未完成:{str(error).rstrip('。')}。保留现有会话,不自动重发或回答审批。")