refactor: 案例项目目录规范化并同步 harness

将 apps/、docs/facts(+business/tech-topic)、.overnight-runner 收敛为统一布局,并刷新安装器默认值与 skill 占位符(DESIGNS_DIR→FACTS_DIR)。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ning-inspire
2026-11-17 10:34:28 +08:00
parent 26975e5c3a
commit 2fb2fc3361
215 changed files with 740 additions and 426 deletions

View File

@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# overnight-runner 启动脚本(由 install.sh 生成)
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHONPATH="$DIR${PYTHONPATH:+:$PYTHONPATH}" export PYTHONPATH
exec "python3" -m overnight_runner "$@"

View File

@@ -0,0 +1,6 @@
@echo off
REM overnight-runner 启动脚本(Windows,由 install.sh 生成)
setlocal
set "DIR=%~dp0"
set "PYTHONPATH=%DIR%;%PYTHONPATH%"
"python3" -m overnight_runner %*

View File

@@ -0,0 +1,38 @@
# overnight-runner 运行配置(.overnight-runner/,全队列共享)
#
# 这里回答的是"这个项目怎么跑":agent 是谁 / 看门狗多严 / 决策怎么处理。
#
# "跑哪些任务"不在这里 —— 队列定义在
# .overnight-runner/queue/<队列名>/queue.yaml
# 用 `overnight-runner --queue <名字> add docs/plans/xxx.md` 追加。
runner:
agent:
command: opencode
args:
- run
- "--dangerously-skip-permissions"
env: {}
watchdog:
maxRetries: 2
backoffSec: 60
idleTimeoutSec: 1800
totalTimeoutSec: 7200
killGraceSec: 15
# 决策策略:agent 抛 "QUESTION: <问题>" 时怎么办
decision:
# attended —— 有人值守(白天):打断 agent,TUI 弹决策窗口问你;
# timeoutSec 内没回答就按默认决策规则自动决策
# unattended —— 无人值守(夜里):不打断 agent,直接按默认决策规则决策
# 临时切换:overnight-runner run --mode unattended
mode: attended
timeoutSec: 600
resume: session
outputFormat: json
sessionArgs: ["--session", "{session}"]
state:
dir: .overnight-runner
workdir: .
ui:
refreshHz: 8
logTail: 400

View File

@@ -0,0 +1,5 @@
"""overnight-runner:把一串 plan 交给 coding agent 无人值守地跑一晚上。"""
__version__ = "0.1.0"
APP_NAME = "overnight-runner"

View File

@@ -0,0 +1,4 @@
from .cli import main
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,301 @@
"""调用 coding agent 子进程,实时收集输出。"""
from __future__ import annotations
import json
import os
import re
import signal
import subprocess
import sys
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
from .util import is_windows
LineCallback = Callable[[str], None]
def extract_session_id(line: str, pattern: str) -> str:
"""用正则从 agent 输出里抓 session id(text 模式的兜底)。"""
if not pattern:
return ""
try:
m = re.search(pattern, line)
except re.error:
return ""
return m.group(1) if m else ""
def _render_tool(part: dict) -> list[str]:
"""把一次工具调用渲染成几行可读文本。"""
state = part.get("state") or {}
inp = state.get("input") or {}
tool = part.get("tool") or "tool"
title = state.get("title") or ""
cmd = inp.get("command") or inp.get("filePath") or inp.get("path") or ""
output = state.get("output") or ""
lines: list[str] = []
head = title or cmd or tool
lines.append(f"$ {head}")
if cmd and cmd != head:
lines.append(f" {cmd}")
for ln in str(output).splitlines():
lines.append(ln)
return lines
def parse_agent_output(line: str, output_format: str) -> tuple[list[str], str]:
"""把 agent 的一行原始输出解析成 (显示用的行列表, session_id)。
- `text` 模式:原样返回,session id 交给正则抓
- `json` 模式:解析事件 —— `part.type=text` 取文本,`part.type=tool` 取工具摘要,
session id 从事件顶层的 `sessionID` 拿
"""
if output_format != "json":
return [line], ""
s = line.strip()
if not (s.startswith("{") and s.endswith("}")):
# 不是 json(agent 的 stderr 混进来了)—— 原样透传
return [line], ""
try:
obj = json.loads(s)
except json.JSONDecodeError:
return [line], ""
if not isinstance(obj, dict):
return [], ""
session_id = str(obj.get("sessionID") or "")
part = obj.get("part") or {}
ptype = part.get("type")
if ptype == "text":
text = str(part.get("text") or "")
return (text.splitlines() or [""]), session_id
if ptype == "tool":
return _render_tool(part), session_id
return [], session_id
@dataclass
class AgentResult:
exit_code: int | None = None
timed_out: bool = False
timeout_kind: str = "" # idle | total | ""
killed: bool = False
error: str = ""
duration_sec: float = 0.0
@dataclass
class AgentProcess:
"""一次 agent 调用。"""
command: list[str]
cwd: Path
env: dict[str, str] = field(default_factory=dict)
on_line: LineCallback | None = None
idle_timeout_sec: int = 1800
total_timeout_sec: int = 7200
kill_grace_sec: int = 15
output_format: str = "text"
session_pattern: str = ""
_proc: subprocess.Popen | None = field(default=None, init=False, repr=False)
_thread: threading.Thread | None = field(default=None, init=False, repr=False)
_last_output_at: float = field(default_factory=time.monotonic, init=False)
_started_at: float = field(default_factory=time.monotonic, init=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
_session_id: str = field(default="", init=False)
# ── 生命周期 ────────────────────────────────────────────────────
def start(self) -> None:
env = os.environ.copy()
env.update(self.env)
env.setdefault("PYTHONIOENCODING", "utf-8")
# 让 agent 认得非交互终端
env.setdefault("CI", "1")
kwargs: dict = dict(
cwd=str(self.cwd),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
if is_windows():
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
kwargs["start_new_session"] = True
self._started_at = time.monotonic()
self._last_output_at = self._started_at
self._proc = subprocess.Popen(self.command, **kwargs)
self._thread = threading.Thread(target=self._pump, name="agent-reader", daemon=True)
self._thread.start()
def _pump(self) -> None:
proc = self._proc
if proc is None or proc.stdout is None:
return
try:
for raw in proc.stdout:
line = raw.rstrip("\n").rstrip("\r")
with self._lock:
self._last_output_at = time.monotonic()
for out in self._expand(line):
if self.on_line is not None:
try:
self.on_line(out)
except Exception: # noqa: BLE001 - UI 回调不该拖垮 agent
pass
except (ValueError, OSError):
pass
finally:
try:
proc.stdout.close()
except (OSError, AttributeError):
pass
def _expand(self, line: str) -> list[str]:
"""把一行原始输出展开成若干行可读文本,并顺手抓 session id。"""
lines, session_id = parse_agent_output(line, self.output_format)
if session_id:
self._remember_session(session_id)
elif self.output_format != "json" and self.session_pattern:
found = extract_session_id(line, self.session_pattern)
if found:
self._remember_session(found)
return lines
def _remember_session(self, session_id: str) -> None:
with self._lock:
if not self._session_id:
self._session_id = session_id
@property
def session_id(self) -> str:
"""抓到的 agent session id(用于 `--session` 续跑)。"""
with self._lock:
return self._session_id
@property
def alive(self) -> bool:
return self._proc is not None and self._proc.poll() is None
@property
def idle_seconds(self) -> float:
with self._lock:
return time.monotonic() - self._last_output_at
@property
def total_seconds(self) -> float:
return time.monotonic() - self._started_at
def poll(self) -> int | None:
return self._proc.poll() if self._proc else None
def wait(self, timeout: float | None = None) -> int | None:
if self._proc is None:
return None
try:
return self._proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
return None
# ── 超时判定 ────────────────────────────────────────────────────
def check_timeout(self) -> tuple[bool, str]:
"""返回 (是否超时, 超时类型)。"""
if self.total_timeout_sec and self.total_seconds > self.total_timeout_sec:
return True, "total"
if self.idle_timeout_sec and self.idle_seconds > self.idle_timeout_sec:
return True, "idle"
return False, ""
# ── 终止 ────────────────────────────────────────────────────────
def terminate(self) -> bool:
"""优雅终止:先 TERM,宽限期后 KILL。返回是否真的杀掉了。"""
proc = self._proc
if proc is None or proc.poll() is not None:
return False
killed = False
try:
if is_windows():
proc.send_signal(signal.CTRL_BREAK_EVENT)
else:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
killed = True
except (ProcessLookupError, PermissionError, OSError):
try:
proc.terminate()
killed = True
except OSError:
pass
try:
proc.wait(timeout=self.kill_grace_sec)
except subprocess.TimeoutExpired:
try:
if is_windows():
proc.kill()
else:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except (ProcessLookupError, PermissionError, OSError):
try:
proc.kill()
except OSError:
pass
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
return killed
def build_command(
agent_command: str,
agent_args: list[str],
prompt: str,
prompt_file: Path | None = None,
) -> list[str]:
"""组装 agent 命令行。
提示词优先通过文件传(避免超长命令行在 Windows 上炸掉);
只有当 agent 明确支持时才用 stdin。
"""
cmd = [agent_command, *agent_args]
if prompt_file is not None:
cmd += ["--prompt-file", str(prompt_file)]
else:
cmd.append(prompt)
return cmd
def check_agent_available(agent_command: str) -> tuple[bool, str]:
"""检查 agent 命令是否可用。"""
import shutil
if shutil.which(agent_command):
return True, ""
# 允许写成 "python -m foo" 这种形式,取第一段做 which
first = agent_command.split()[0] if agent_command.split() else agent_command
if shutil.which(first):
return True, ""
return False, f"找不到 agent 命令: {agent_command}"
def platform_hint() -> str:
return f"{sys.platform} / {'Windows' if is_windows() else 'POSIX'}"

View File

@@ -0,0 +1,439 @@
"""命令行入口。
子命令:
init 初始化配置文件(队列 + 项目配置)
add 往队列里追加 plan
list 列出队列
status 查看运行状态
decisions 查看决策记录
queues 列出所有队列
run 启动(默认分屏面板;--headless 无界面)
所有子命令都支持全局参数 `--queue <name>`(默认 `default`)。
"""
from __future__ import annotations
import argparse
import json
import sys
import threading
from pathlib import Path
from . import __version__
from .config import (
DECISION_MODE_ATTENDED,
DECISION_MODE_UNATTENDED,
DECISION_MODES,
DEFAULT_AGENT_ARGS,
DEFAULT_AGENT_COMMAND,
DEFAULT_PROJECT_PROMPT,
DEFAULT_QUEUE_NAME,
ProjectConfig,
QueuePaths,
load_project_config,
load_runner_config,
migrate_legacy_queue,
queue_config_path,
queue_names,
queue_paths,
save_project_config,
save_runner_config,
)
from .controller import RunnerController
from .decisions import DecisionLog
from .queue import (
PENDING,
Queue,
build_task,
load_queue,
load_queue_defs,
save_queue_defs,
save_state,
)
from .util import QueueLock, StopFlag, fmt_duration, fmt_ts, now
def _project_root(args) -> Path:
return Path(args.project).expanduser().resolve()
def _queue_paths(args) -> QueuePaths:
"""解析本次命令要操作的队列(顺带做老布局迁移)。"""
root = _project_root(args)
note = migrate_legacy_queue(root)
if note:
print(f"已迁移旧队列布局 → .overnight-runner/queue/{DEFAULT_QUEUE_NAME}/({note})")
name = getattr(args, "queue", DEFAULT_QUEUE_NAME) or DEFAULT_QUEUE_NAME
try:
return queue_paths(root, name)
except ValueError as exc:
print(f"错误: {exc}", file=sys.stderr)
raise SystemExit(2)
def resolve_decision_mode(
cfg, mode_override: str | None = None, headless: bool = False
) -> str:
"""决定本次运行用哪个决策模式。
优先级:headless(强制无人值守)> 命令行 --mode > 配置文件。
"""
if headless:
return DECISION_MODE_UNATTENDED
if mode_override:
return mode_override
return cfg.decision.mode
# ── init ────────────────────────────────────────────────────────────
def cmd_init(args) -> int:
root = _project_root(args)
root.mkdir(parents=True, exist_ok=True)
paths = _queue_paths(args)
qpath = queue_config_path(root)
if not qpath.exists():
cfg = load_runner_config(root)
cfg.agent_command = args.agent or cfg.agent_command
cfg.agent_args = list(args.agent_args) if args.agent_args else cfg.agent_args
save_runner_config(root, cfg)
print(f"已创建运行配置: {qpath}")
else:
print(f"运行配置已存在,保持不变: {qpath}")
if not paths.config.exists():
paths.dir.mkdir(parents=True, exist_ok=True)
save_queue_defs(paths, Queue())
print(f"已创建队列: {paths.name} → {paths.config}")
else:
print(f"队列已存在,保持不变: {paths.config}")
ppath = root / ".overnight-runner" / "project.yaml"
if not ppath.exists():
pcfg = ProjectConfig(name=root.name)
pcfg.agent_command = args.agent or DEFAULT_AGENT_COMMAND
pcfg.agent_args = list(args.agent_args) if args.agent_args else list(DEFAULT_AGENT_ARGS)
pcfg.default_prompt = DEFAULT_PROJECT_PROMPT
save_project_config(root, pcfg)
print(f"已创建项目配置: {ppath}")
else:
print(f"项目配置已存在,保持不变: {ppath}")
print()
print("下一步:")
print(f" 1) 编辑 {paths.config} 填入 queue(plan 用相对项目根的路径)")
print(f" 2) 编辑 {ppath} 配默认提示词与默认决策")
print(f" 3) 运行: overnight-runner --queue {paths.name} run")
return 0
# ── add ─────────────────────────────────────────────────────────────
def cmd_add(args) -> int:
root = _project_root(args)
paths = _queue_paths(args)
cfg = load_runner_config(root)
queue = load_queue(paths, load_queue_defs(paths))
try:
task = build_task(
root,
args.plan,
prompt=args.prompt or "",
role=args.role or "",
priority=args.priority,
existing_ids={t.id for t in queue.tasks},
)
queue.add(task)
except ValueError as exc:
print(f"错误: {exc}", file=sys.stderr)
return 1
save_queue_defs(paths, queue)
print(f"已加入队列 [{paths.name}]: {task.id} → {task.plan}")
return 0
# ── list ────────────────────────────────────────────────────────────
def cmd_list(args) -> int:
root = _project_root(args)
paths = _queue_paths(args)
queue = load_queue(paths, load_queue_defs(paths))
print(f"队列: {paths.name}")
if not len(queue):
print("队列为空。用 `overnight-runner add <plan>` 追加。")
return 0
print(f"{'ID':<32} {'状态':<8} {'次':<3} {'耗时':<8} PLAN")
print("-" * 100)
for t in queue.tasks:
print(
f"{t.id:<32} {t.status:<8} {t.attempts:<3} "
f"{fmt_duration(t.duration_sec):<8} {t.plan}"
)
return 0
# ── status ──────────────────────────────────────────────────────────
def cmd_status(args) -> int:
root = _project_root(args)
paths = _queue_paths(args)
cfg = load_runner_config(root)
queue = load_queue(paths, load_queue_defs(paths))
stats = queue.stats()
print(f"项目: {root}")
print(f"队列: {paths.name}")
print(f"agent: {cfg.agent_command} {' '.join(cfg.agent_args)}")
print(f"决策: {cfg.decision.mode}({DECISION_MODE_ATTENDED}=有人值守 / "
f"{DECISION_MODE_UNATTENDED}=无人值守)· 等待 {cfg.decision.timeout_sec}s")
print(f"看门狗: 重试 {cfg.watchdog.max_retries} 次 · 退避 {cfg.watchdog.backoff_sec}s · "
f"空闲超时 {cfg.watchdog.idle_timeout_sec}s · 总超时 {cfg.watchdog.total_timeout_sec}s")
print()
for k in ("pending", "running", "retrying", "success", "failed", "blocked", "stopped"):
if stats.get(k):
print(f" {k:<10} {stats[k]}")
print()
for t in queue.tasks:
if t.status in ("failed", "blocked"):
print(f" ✘ {t.id}: {t.last_error}")
return 0
# ── decisions ───────────────────────────────────────────────────────
def cmd_decisions(args) -> int:
paths = _queue_paths(args)
log = DecisionLog(paths.decisions)
records = log.load()
if not records:
print(f"队列 [{paths.name}] 还没有决策记录。")
return 0
if args.json:
print(json.dumps(records, ensure_ascii=False, indent=2))
return 0
print(f"队列: {paths.name}")
print(f"{'时间':<20} {'任务':<28} {'来源':<9} 问题 → 答案")
print("-" * 110)
for r in records:
print(
f"{str(r.get('at',''))[:19]:<20} {str(r.get('task_id',''))[:27]:<28} "
f"{str(r.get('source','')):<9} {r.get('question','')} → {r.get('answer','')}"
)
return 0
# ── queues ──────────────────────────────────────────────────────────
def cmd_queues(args) -> int:
root = _project_root(args)
note = migrate_legacy_queue(root)
if note:
print(f"已迁移旧队列布局 → .overnight-runner/queue/{DEFAULT_QUEUE_NAME}/({note})")
names = queue_names(root)
if not names:
print("还没有任何队列。用 `overnight-runner init` 建一条。")
return 0
print(f"{'队列':<16} {'任务':<6} {'待跑':<6} {'运行':<6} {'成功':<6} {'失败':<6} 最后活动")
print("-" * 78)
for name in names:
paths = queue_paths(root, name)
queue = load_queue(paths, load_queue_defs(paths))
stats = queue.stats()
last = _last_activity(queue)
print(
f"{name:<16} {len(queue):<6} {stats.get(PENDING, 0):<6} "
f"{stats.get('running', 0):<6} {stats.get('success', 0):<6} "
f"{stats.get('failed', 0):<6} {last}"
)
return 0
def _last_activity(queue: Queue) -> str:
times = [t.finished_at or t.started_at for t in queue.tasks]
times = [t for t in times if t is not None]
if not times:
return "-"
return fmt_ts(max(times))
# ── run ─────────────────────────────────────────────────────────────
def cmd_run(args) -> int:
root = _project_root(args)
paths = _queue_paths(args)
cfg = load_runner_config(root)
project_cfg = load_project_config(root)
queue = load_queue(paths, load_queue_defs(paths))
# 决策模式:命令行优先;headless 强制无人值守(没人看面板,不能卡在等决策上)
cfg.decision.mode = resolve_decision_mode(
cfg, getattr(args, "mode", None), args.headless
)
if getattr(args, "retry_failed", False):
reset = 0
for t in queue.tasks:
if t.status in ("failed", "blocked", "stopped"):
t.status = PENDING
t.attempts = 0
t.last_error = ""
t.exit_code = None
t.finished_at = None
t.summary = ""
reset += 1
if reset:
save_state(paths, queue)
print(f"已重置 {reset} 个失败/阻塞任务。")
lock = QueueLock(paths.lock)
ok, err = lock.acquire()
if not ok:
print(f"错误: {err}(同一条队列不能同时跑两个 runner)", file=sys.stderr)
return 2
stop = StopFlag()
controller = RunnerController(root, cfg, project_cfg, queue, paths, stop=stop)
try:
if args.headless:
return _run_headless(controller, queue, paths, stop, args)
try:
from .ui import RunnerUI
except ImportError as exc: # pragma: no cover - 只在环境被破坏时触发
print(f"无法启动面板: {exc}", file=sys.stderr)
print("也可以用 --headless 无界面运行。", file=sys.stderr)
return 2
ui = RunnerUI(controller, queue, cfg, root, paths)
worker = threading.Thread(target=controller.run_forever, name="runner", daemon=True)
worker.start()
heartbeat = threading.Thread(target=_heartbeat, args=(lock, stop), daemon=True)
heartbeat.start()
try:
ui.run()
finally:
stop.set()
worker.join(timeout=10)
finally:
lock.release()
save_state(paths, queue)
return 0
def _heartbeat(lock: QueueLock, stop: StopFlag) -> None:
"""定期更新锁的心跳(长跑时用来识别 stale 锁)。"""
while not stop.is_set():
lock.touch()
stop.wait(timeout=15)
def _run_headless(controller, queue, paths, stop, args) -> int:
"""无界面模式:直接跑,输出到 stdout。适合 CI / 脚本。"""
def on_event(kind: str, task) -> None:
if task is not None:
print(f"[{fmt_ts(now())}] {kind:<16} {task.id} {task.plan}")
else:
print(f"[{fmt_ts(now())}] {kind}")
def on_log(line: str) -> None:
if args.verbose:
print(f" {line}")
controller.on_event = on_event
controller.on_log = on_log
controller.run_forever()
save_state(paths, queue)
stats = queue.stats()
failed = [t for t in queue.tasks if t.status in ("failed", "blocked")]
print()
print(controller.snapshot())
if failed:
print()
print("失败任务:")
for t in failed:
print(f" ✘ {t.id}: {t.last_error}")
return 1 if failed else 0
# ── 参数解析 ────────────────────────────────────────────────────────
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="overnight-runner",
description="把一串 plan 交给 coding agent 无人值守地跑",
)
p.add_argument("--version", action="version", version=f"overnight-runner {__version__}")
p.add_argument("--project", default=".", help="项目根目录(默认当前目录)")
p.add_argument(
"--queue",
default=DEFAULT_QUEUE_NAME,
help=f"队列名(默认 {DEFAULT_QUEUE_NAME})",
)
sub = p.add_subparsers(dest="command")
s = sub.add_parser("init", help="初始化配置文件")
s.add_argument("--agent", help="coding agent 命令,如 opencode / claude / codex")
s.add_argument("--agent-args", nargs="*", help="agent 参数,默认 run")
s.set_defaults(func=cmd_init)
s = sub.add_parser("add", help="往队列追加 plan")
s.add_argument("plan", help="plan 文件路径(相对项目根或绝对路径)")
s.add_argument("--prompt", default="", help="补充要求")
s.add_argument("--role", default="", help="角色标签 BA / DEV / QA")
s.add_argument("--priority", type=int, default=100, help="优先级,数字小的先跑")
s.set_defaults(func=cmd_add)
s = sub.add_parser("list", help="列出队列")
s.set_defaults(func=cmd_list)
s = sub.add_parser("status", help="查看运行状态")
s.set_defaults(func=cmd_status)
s = sub.add_parser("decisions", help="查看决策记录")
s.add_argument("--json", action="store_true", help="输出 JSON")
s.set_defaults(func=cmd_decisions)
s = sub.add_parser("queues", help="列出所有队列")
s.set_defaults(func=cmd_queues)
s = sub.add_parser("run", help="启动(默认分屏面板;--headless 无界面)")
s.add_argument("--headless", action="store_true", help="无界面模式")
s.add_argument("--verbose", action="store_true", help="headless 模式下打印 agent 输出")
s.add_argument(
"--retry-failed",
action="store_true",
help="把失败/阻塞的任务重置为待跑",
)
s.add_argument(
"--mode",
choices=list(DECISION_MODES),
default=None,
help=(
f"决策模式:{DECISION_MODE_ATTENDED}=有人值守(弹窗问人,"
f"超时自动决策)/ {DECISION_MODE_UNATTENDED}=无人值守(直接决策)"
),
)
s.set_defaults(func=cmd_run)
return p
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if not getattr(args, "func", None):
parser.print_help()
return 2
return args.func(args)
if __name__ == "__main__": # pragma: no cover
sys.exit(main())

View File

@@ -0,0 +1,565 @@
"""配置加载:队列配置与项目配置(均在 `.overnight-runner/` 下)。
配置分三层:
- **runner 级**:`.overnight-runner/overnight-runner.yaml` —— agent / 看门狗 / UI / 决策策略
- **project 级**:`.overnight-runner/project.yaml` —— 默认提示词与默认决策规则(全队列共享)
- **queue 级**:`.overnight-runner/queue/<name>/queue.yaml` —— 队列里的任务列表(每条队列一份)
兼容:若仅项目根还有旧的 `overnight-runner.yaml`,首次加载时自动迁入 `.overnight-runner/`。
"""
from __future__ import annotations
import re
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from . import yaml_lite as yaml
from .util import atomic_write
QUEUE_CONFIG_NAME = "overnight-runner.yaml"
PROJECT_DIR_NAME = ".overnight-runner"
PROJECT_CONFIG_NAME = "project.yaml"
# 多队列:每条队列在 .overnight-runner/queue/<name>/ 下有一份独立目录
QUEUE_DIR_NAME = "queue"
DEFAULT_QUEUE_NAME = "default"
QUEUE_FILE_NAME = "queue.yaml"
STATE_FILE_NAME = "state.json"
LOGS_DIR_NAME = "logs"
DECISIONS_FILE_NAME = "decisions.jsonl"
LOCK_FILE_NAME = ".lock"
DEFAULT_AGENT_COMMAND = "opencode"
DEFAULT_AGENT_ARGS: list[str] = ["run"]
# 决策模式:attended = 有人值守(弹窗问人);unattended = 无人值守(直接决策)
DECISION_MODE_ATTENDED = "attended"
DECISION_MODE_UNATTENDED = "unattended"
DECISION_MODES = (DECISION_MODE_ATTENDED, DECISION_MODE_UNATTENDED)
# 队列名白名单:不允许路径穿越
QUEUE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
# ── 项目配置 ────────────────────────────────────────────────────────
@dataclass
class DecisionRule:
"""一条默认决策:命中问题类别就用预设答案,并且记一笔。"""
id: str
question: str = ""
match: str = ""
answer: str = ""
enabled: bool = True
def describe(self) -> str:
return f"{self.id}: {self.question or self.match} → {self.answer}"
@dataclass
class ProjectConfig:
name: str = ""
agent_command: str = DEFAULT_AGENT_COMMAND
agent_args: list[str] = field(default_factory=lambda: list(DEFAULT_AGENT_ARGS))
agent_env: dict[str, str] = field(default_factory=dict)
default_prompt: str = ""
decisions: list[DecisionRule] = field(default_factory=list)
on_unknown_decision: str = "跳过并记录到决策日志"
source_path: Path | None = None
def decision_text(self) -> str:
if not self.decisions:
return ""
lines = [f"- [{d.id}] {d.question or d.match} → {d.answer}" for d in self.decisions]
return "\n".join(lines)
def to_yaml(self) -> str:
data = {
"project": {
"name": self.name,
"agent": {
"command": self.agent_command,
"args": self.agent_args,
"env": self.agent_env,
},
},
"default": {
"prompt": self.default_prompt,
"onUnknownDecision": self.on_unknown_decision,
},
"decisions": [
{
"id": d.id,
"question": d.question,
"match": d.match,
"answer": d.answer,
"enabled": d.enabled,
}
for d in self.decisions
],
}
return yaml.dumps(data)
DEFAULT_PROJECT_PROMPT = """\
你在无人值守模式下工作,不要停下来等待人工确认。
按下面的方案执行,遇到需要决策的问题,按"默认决策"处理:
{{DECISIONS}}
{{PLAN}}
执行要求:
1. 每做出一个决策,输出一行:DECISION: <问题> → <决策>
2. 全部完成后输出一行:DONE: <一句话总结>
3. 如果无法继续,输出一行:BLOCKED: <原因>
"""
def load_project_config(project_root: Path) -> ProjectConfig:
path = project_root / PROJECT_DIR_NAME / PROJECT_CONFIG_NAME
cfg = ProjectConfig(source_path=path)
if not path.exists():
cfg.default_prompt = DEFAULT_PROJECT_PROMPT
return cfg
data = yaml.loads(path.read_text(encoding="utf-8")) or {}
proj = data.get("project") or {}
cfg.name = proj.get("name") or project_root.name
agent = proj.get("agent") or {}
cfg.agent_command = agent.get("command") or DEFAULT_AGENT_COMMAND
cfg.agent_args = list(agent.get("args") or DEFAULT_AGENT_ARGS)
cfg.agent_env = dict(agent.get("env") or {})
default = data.get("default") or {}
cfg.default_prompt = default.get("prompt") or DEFAULT_PROJECT_PROMPT
cfg.on_unknown_decision = default.get("onUnknownDecision") or cfg.on_unknown_decision
for item in data.get("decisions") or []:
cfg.decisions.append(
DecisionRule(
id=str(item.get("id") or f"rule-{len(cfg.decisions) + 1}"),
question=item.get("question") or "",
match=item.get("match") or "",
answer=item.get("answer") or "",
enabled=bool(item.get("enabled", True)),
)
)
return cfg
def save_project_config(project_root: Path, cfg: ProjectConfig) -> Path:
path = project_root / PROJECT_DIR_NAME / PROJECT_CONFIG_NAME
atomic_write(path, cfg.to_yaml())
return path
# ── 多队列:路径解析与老布局迁移 ────────────────────────────────────
@dataclass(frozen=True)
class QueuePaths:
"""一条队列在磁盘上的全部路径。"""
root: Path
name: str
@property
def dir(self) -> Path:
return self.root / PROJECT_DIR_NAME / QUEUE_DIR_NAME / self.name
@property
def config(self) -> Path:
"""队列定义(进版本库)。"""
return self.dir / QUEUE_FILE_NAME
@property
def state(self) -> Path:
"""运行时状态(不进版本库)。"""
return self.dir / STATE_FILE_NAME
@property
def logs(self) -> Path:
"""agent 日志与 prompt 文件(不进版本库)。"""
return self.dir / LOGS_DIR_NAME
@property
def decisions(self) -> Path:
"""决策记录(进版本库)。"""
return self.dir / DECISIONS_FILE_NAME
@property
def lock(self) -> Path:
"""单实例锁(不进版本库)。"""
return self.dir / LOCK_FILE_NAME
def queue_paths(project_root: Path, name: str = DEFAULT_QUEUE_NAME) -> QueuePaths:
"""解析一条队列的路径。队列名非法直接报错(防路径穿越)。"""
if not name or not QUEUE_NAME_RE.match(name):
raise ValueError(
f"队列名不合法: {name!r}(只允许字母、数字、. _ -,且必须以字母或数字开头)"
)
return QueuePaths(root=project_root, name=name)
def queue_names(project_root: Path) -> list[str]:
"""列出磁盘上已有的队列名(按字典序)。"""
base = project_root / PROJECT_DIR_NAME / QUEUE_DIR_NAME
if not base.is_dir():
return []
out = [
p.name
for p in sorted(base.iterdir(), key=lambda x: x.name)
if p.is_dir() and QUEUE_NAME_RE.match(p.name)
]
return out
def strip_queue_section(text: str) -> str:
"""从 YAML 文本里删掉顶层的 `queue:` 段,**其余内容原样保留**。
为什么不用"解析 → 改 → 重新序列化":那样会把用户写的注释全弄丢。
这里按行做手术,只动 `queue:` 那一段。
- `queue:` 后面跟缩进内容(块序列)→ 整段删掉
- `queue: []` 这种内联写法 → 改成 `queue: []`(保持只有一个空段)
"""
lines = text.split("\n")
out: list[str] = []
i = 0
n = len(lines)
while i < n:
line = lines[i]
m = re.match(r"^queue\s*:(.*)$", line)
if not m:
out.append(line)
i += 1
continue
tail = m.group(1).strip()
if tail and not tail.startswith("#"):
# 内联写法(queue: [] / queue: [...])—— 归一成空列表
out.append("queue: []")
i += 1
continue
# 块序列:吃掉这一行 + 后面所有缩进行
i += 1
while i < n:
nxt = lines[i]
if nxt.strip() == "":
# 空行:后面若还有缩进内容就一并吃掉
j = i
while j < n and lines[j].strip() == "":
j += 1
if j < n and lines[j][:1] in (" ", "\t"):
i = j
continue
break
if nxt[:1] in (" ", "\t"):
i += 1
continue
break
return "\n".join(out)
def migrate_runner_config_into_project_dir(project_root: Path) -> str:
"""把项目根的 `overnight-runner.yaml` 迁到 `.overnight-runner/`(幂等)。
- 目标已存在:不覆盖,也不动根文件(避免误删用户双份配置)
- 仅根文件存在:move 到 `.overnight-runner/overnight-runner.yaml`
"""
dest = queue_config_path(project_root)
src = legacy_root_queue_config_path(project_root)
if dest.exists() or not src.exists():
return ""
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), str(dest))
return f"{src.name} → {PROJECT_DIR_NAME}/{QUEUE_CONFIG_NAME}"
def migrate_legacy_queue(project_root: Path) -> str:
"""把老布局迁移到 `.overnight-runner/queue/default/`。
老布局:
<root>/overnight-runner.yaml (先迁入 `.overnight-runner/`)
配置文件里的 queue: 段
<root>/.overnight-runner/state.json
<root>/.overnight-runner/logs/
<root>/.overnight-runner/decisions.jsonl
迁移是 **幂等** 的:源清空后第二次调用直接返回空串。
用的是 move(rename)不是 copy,源文件不会留下两份。
返回一句人类可读的迁移说明(没迁移则返回空串)。
"""
notes: list[str] = []
moved = migrate_runner_config_into_project_dir(project_root)
if moved:
notes.append(moved)
default = queue_paths(project_root, DEFAULT_QUEUE_NAME)
# 1) 队列定义:配置文件的 queue: 段 → queue/default/queue.yaml
cfg_path = queue_config_path(project_root)
if cfg_path.exists():
raw = cfg_path.read_text(encoding="utf-8")
data = yaml.loads(raw) or {}
legacy_queue = list(data.get("queue") or [])
if legacy_queue and not default.config.exists():
default.dir.mkdir(parents=True, exist_ok=True)
atomic_write(
default.config,
yaml.dumps({"queue": legacy_queue}),
)
notes.append(f"队列定义 → {default.config}")
# 把配置里的 queue: 段清空,保证只迁移一次。
# 按行做手术,保留用户写的注释与排版。
atomic_write(cfg_path, strip_queue_section(raw))
# 2) 运行时状态 / 日志 / 决策记录:整体搬进 default 队列目录
legacy_dir = project_root / PROJECT_DIR_NAME
for name, dest in (
(STATE_FILE_NAME, default.state),
(LOGS_DIR_NAME, default.logs),
(DECISIONS_FILE_NAME, default.decisions),
):
src = legacy_dir / name
if not src.exists():
continue
if dest.exists():
continue
default.dir.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), str(dest))
notes.append(f"{src} → {dest}")
return ";".join(notes)
# ── 队列配置 ────────────────────────────────────────────────────────
@dataclass
class WatchdogConfig:
max_retries: int = 2
backoff_sec: int = 60
idle_timeout_sec: int = 1800
total_timeout_sec: int = 7200
kill_grace_sec: int = 15
@classmethod
def from_dict(cls, data: dict | None) -> "WatchdogConfig":
data = data or {}
return cls(
max_retries=int(data.get("maxRetries", 2)),
backoff_sec=int(data.get("backoffSec", 60)),
idle_timeout_sec=int(data.get("idleTimeoutSec", 1800)),
total_timeout_sec=int(data.get("totalTimeoutSec", 7200)),
kill_grace_sec=int(data.get("killGraceSec", 15)),
)
def to_dict(self) -> dict:
return {
"maxRetries": self.max_retries,
"backoffSec": self.backoff_sec,
"idleTimeoutSec": self.idle_timeout_sec,
"totalTimeoutSec": self.total_timeout_sec,
"killGraceSec": self.kill_grace_sec,
}
@dataclass
class DecisionConfig:
"""决策策略。
- `mode=attended`(有人值守):agent 抛问题时打断它,TUI 弹决策窗口问人;
超时没人答就按规则/兜底策略自动决策。
- `mode=unattended`(无人值守):不打断 agent,按规则/兜底策略直接决策。
"""
mode: str = DECISION_MODE_ATTENDED
timeout_sec: int = 600
resume: str = "session" # session | restart
output_format: str = "json" # json | text
json_args: list[str] = field(default_factory=lambda: ["--format", "json"])
session_args: list[str] = field(default_factory=lambda: ["--session", "{session}"])
session_pattern: str = r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"'
@classmethod
def from_dict(cls, data: dict | None) -> "DecisionConfig":
data = data or {}
mode = str(data.get("mode") or DECISION_MODE_ATTENDED)
if mode not in DECISION_MODES:
mode = DECISION_MODE_ATTENDED
resume = str(data.get("resume") or "session")
if resume not in ("session", "restart"):
resume = "session"
output_format = str(data.get("outputFormat") or "json")
if output_format not in ("json", "text"):
output_format = "json"
args = data.get("sessionArgs")
if not isinstance(args, list) or not args:
args = ["--session", "{session}"]
json_args = data.get("jsonArgs")
if not isinstance(json_args, list) or not json_args:
json_args = ["--format", "json"]
return cls(
mode=mode,
timeout_sec=int(data.get("timeoutSec", 600)),
resume=resume,
output_format=output_format,
json_args=[str(a) for a in json_args],
session_args=[str(a) for a in args],
session_pattern=str(
data.get("sessionPattern")
or r'"sessionID"\s*:\s*"(ses_[A-Za-z0-9]+)"'
),
)
def to_dict(self) -> dict:
return {
"mode": self.mode,
"timeoutSec": self.timeout_sec,
"resume": self.resume,
"outputFormat": self.output_format,
"jsonArgs": list(self.json_args),
"sessionArgs": list(self.session_args),
"sessionPattern": self.session_pattern,
}
def session_command(self, session_id: str) -> list[str]:
"""把 session_args 里的 {session} 占位符替换成真实 session id。"""
return [a.replace("{session}", session_id) for a in self.session_args]
@dataclass
class RunnerConfig:
"""启动时用的队列配置(overnight-runner.yaml)。"""
agent_command: str = DEFAULT_AGENT_COMMAND
agent_args: list[str] = field(default_factory=lambda: list(DEFAULT_AGENT_ARGS))
agent_env: dict[str, str] = field(default_factory=dict)
watchdog: WatchdogConfig = field(default_factory=WatchdogConfig)
decision: DecisionConfig = field(default_factory=DecisionConfig)
state_dir: str = PROJECT_DIR_NAME
workdir: str = "."
refresh_hz: int = 8
log_tail: int = 400
queue: list[dict] = field(default_factory=list)
source_path: Path | None = None
@classmethod
def from_dict(cls, data: dict, source_path: Path | None = None) -> "RunnerConfig":
runner = data.get("runner") or {}
agent = runner.get("agent") or {}
cfg = cls(
agent_command=agent.get("command") or DEFAULT_AGENT_COMMAND,
agent_args=list(agent["args"]) if agent.get("args") is not None else list(DEFAULT_AGENT_ARGS),
agent_env=dict(agent.get("env") or {}),
watchdog=WatchdogConfig.from_dict(runner.get("watchdog")),
decision=DecisionConfig.from_dict(runner.get("decision")),
state_dir=runner.get("state", {}).get("dir") or PROJECT_DIR_NAME,
workdir=runner.get("workdir") or ".",
refresh_hz=int((runner.get("ui") or {}).get("refreshHz", 8)),
log_tail=int((runner.get("ui") or {}).get("logTail", 400)),
queue=list(data.get("queue") or []),
source_path=source_path,
)
return cfg
def to_dict(self) -> dict:
data: dict[str, Any] = {
"runner": {
"agent": {
"command": self.agent_command,
"args": self.agent_args,
"env": self.agent_env,
},
"watchdog": self.watchdog.to_dict(),
"decision": self.decision.to_dict(),
"state": {"dir": self.state_dir},
"workdir": self.workdir,
"ui": {"refreshHz": self.refresh_hz, "logTail": self.log_tail},
}
}
# 队列定义已经搬到 .overnight-runner/queue/<name>/queue.yaml,这里只在
# 还没迁移时保留(迁移后为空 → 不写出去)
if self.queue:
data["queue"] = self.queue
return data
def to_yaml(self) -> str:
header = (
"# overnight-runner 运行配置\n"
"# agent / 看门狗 / UI / 决策策略 —— 项目级,全队列共享\n"
"# 队列里的任务在 .overnight-runner/queue/<name>/queue.yaml\n"
)
return header + yaml.dumps(self.to_dict())
def queue_config_path(project_root: Path) -> Path:
"""当前规范路径:`.overnight-runner/overnight-runner.yaml`。"""
return project_root / PROJECT_DIR_NAME / QUEUE_CONFIG_NAME
def legacy_root_queue_config_path(project_root: Path) -> Path:
"""旧路径:项目根的 `overnight-runner.yaml`。"""
return project_root / QUEUE_CONFIG_NAME
def load_runner_config(project_root: Path) -> RunnerConfig:
migrate_runner_config_into_project_dir(project_root)
path = queue_config_path(project_root)
if not path.exists():
return RunnerConfig(source_path=path)
data = yaml.loads(path.read_text(encoding="utf-8")) or {}
return RunnerConfig.from_dict(data, source_path=path)
def save_runner_config(project_root: Path, cfg: RunnerConfig) -> Path:
path = queue_config_path(project_root)
atomic_write(path, cfg.to_yaml())
return path
def default_queue_config(project_root: Path) -> RunnerConfig:
cfg = RunnerConfig(source_path=queue_config_path(project_root))
cfg.queue = []
return cfg
__all__ = [
"DECISION_MODES",
"DECISION_MODE_ATTENDED",
"DECISION_MODE_UNATTENDED",
"DEFAULT_QUEUE_NAME",
"DecisionConfig",
"DecisionRule",
"ProjectConfig",
"QueuePaths",
"RunnerConfig",
"WatchdogConfig",
"default_queue_config",
"load_project_config",
"load_runner_config",
"legacy_root_queue_config_path",
"migrate_legacy_queue",
"migrate_runner_config_into_project_dir",
"queue_config_path",
"queue_names",
"queue_paths",
"save_project_config",
"save_runner_config",
"DEFAULT_AGENT_ARGS",
"DEFAULT_AGENT_COMMAND",
"DEFAULT_PROJECT_PROMPT",
"PROJECT_CONFIG_NAME",
"PROJECT_DIR_NAME",
"QUEUE_CONFIG_NAME",
"QUEUE_DIR_NAME",
"QUEUE_FILE_NAME",
]

View File

@@ -0,0 +1,605 @@
"""调度器:取任务 → 跑 agent → 看门狗 → 决策 → 失败重试 → 落状态。
决策有两条路:
- **unattended(无人值守)**:agent 抛 `QUESTION:` 时当场按规则/兜底策略决策,
**不打断** agent;决策会在下一次拉起 agent 时注入 prompt。
- **attended(有人值守)**:打断 agent,TUI 弹决策窗口问人;人答了就用
`opencode run --session <sid>` 续跑;超时没人答就按规则/兜底策略兜底。
"""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
from .agent import AgentProcess, check_agent_available
from .config import ProjectConfig, QueuePaths, RunnerConfig
from .decisions import (
SOURCE_AGENT,
SOURCE_FALLBACK,
SOURCE_HUMAN,
SOURCE_RULE,
SOURCE_TIMEOUT,
DecisionEvent,
DecisionLog,
parse_agent_line,
resolve_answer,
should_ask,
)
from .prompts import build_prompt, build_resume_prompt
from .queue import (
BLOCKED,
FAILED,
PENDING,
RETRYING,
RUNNING,
STOPPED,
SUCCESS,
Queue,
Task,
save_state,
)
from .util import StopFlag, fmt_ts, now, sleep_interruptible
EventCallback = Callable[[str, Task], None]
# 单个任务最多被打断几次(防止 agent 无限提问拖死队列)
MAX_DECISIONS_PER_TASK = 10
@dataclass
class TaskOutcome:
task_id: str
status: str
exit_code: int | None
attempts: int
duration_sec: float
error: str = ""
summary: str = ""
decisions: int = 0
@dataclass
class WatchResult:
"""一次 agent 运行的观察结果。"""
kind: str = "exited" # exited | timeout | question | stopped
timeout_kind: str = ""
question: str = ""
session_id: str = ""
class RunnerController:
"""把队列里的 plan 一个一个交给 coding agent 跑。"""
def __init__(
self,
project_root: Path,
runner_cfg: RunnerConfig,
project_cfg: ProjectConfig,
queue: Queue,
paths: QueuePaths,
stop: StopFlag | None = None,
on_event: EventCallback | None = None,
on_log: Callable[[str], None] | None = None,
) -> None:
self.project_root = project_root
self.runner_cfg = runner_cfg
self.project_cfg = project_cfg
self.queue = queue
self.paths = paths
self.stop = stop or StopFlag()
self.on_event = on_event
self.on_log = on_log
self.log_dir = paths.logs
self.decision_log = DecisionLog(paths.decisions)
self.decision_log.load()
self._current: Task | None = None
self._current_proc: AgentProcess | None = None
self._current_lines: list[str] = []
self._lock = threading.Lock()
# 决策:agent 抛出的问题、等待人回答、已作出的决策
self._ask_question: tuple[str, str] | None = None
self._decisions_made: list[tuple[str, str]] = []
self._decision_lock = threading.Lock()
self._decision_event = threading.Event()
self._pending: dict | None = None
self._answer: str | None = None
# ── 事件 ────────────────────────────────────────────────────────
def _emit(self, kind: str, task: Task | None = None) -> None:
if self.on_event is not None:
try:
self.on_event(kind, task or self._current) # type: ignore[arg-type]
except Exception: # noqa: BLE001
pass
def _log(self, line: str) -> None:
with self._lock:
self._current_lines.append(line)
if len(self._current_lines) > 2000:
self._current_lines = self._current_lines[-1000:]
if self.on_log is not None:
try:
self.on_log(line)
except Exception: # noqa: BLE001
pass
@property
def current_lines(self) -> list[str]:
with self._lock:
return list(self._current_lines)
def clear_log(self) -> None:
with self._lock:
self._current_lines = []
# ── 决策:等待人回答 ────────────────────────────────────────────
def pending_question(self) -> dict | None:
"""当前正在等人回答的问题(没有则 None)。UI 渲染决策窗口用。"""
with self._decision_lock:
if self._pending is None:
return None
pending = dict(self._pending)
deadline = pending.get("deadline")
pending["remaining"] = (
max(0.0, deadline - time.monotonic()) if deadline else None
)
return pending
def submit_decision(self, answer: str) -> None:
"""人在 TUI 里回答了问题。"""
with self._decision_lock:
self._answer = answer
self._decision_event.set()
def cancel_decision(self) -> None:
"""人按 Esc:不等了,直接用默认决策兜底。"""
with self._decision_lock:
self._answer = None
self._decision_event.set()
def _wait_for_human(
self, task: Task, question: str, session_id: str
) -> tuple[str | None, float]:
"""等人回答。返回 (答案 or None, 等了多久秒)。"""
timeout = self.runner_cfg.decision.timeout_sec
started = time.monotonic()
deadline = (started + timeout) if timeout else None
with self._decision_lock:
self._pending = {
"task_id": task.id,
"question": question,
"session_id": session_id,
"deadline": deadline,
"timeout_sec": timeout,
}
self._answer = None
self._decision_event.clear()
self._emit("question_pending", task)
answer: str | None = None
try:
while True:
if self._decision_event.wait(timeout=0.2):
with self._decision_lock:
answer = self._answer
break
if deadline is not None and time.monotonic() >= deadline:
answer = None
break
if self.stop.is_set():
return None, time.monotonic() - started
finally:
with self._decision_lock:
self._pending = None
self._decision_event.clear()
return answer, time.monotonic() - started
def _resolve_question(
self, task: Task, question: str, session_id: str
) -> tuple[str, str, float, str]:
"""有人值守模式下的决策:问人 → 答 / 超时兜底。"""
answer, waited = self._wait_for_human(task, question, session_id)
if answer is None:
fallback, rule_id = resolve_answer(self.project_cfg, question)
self.decision_log.record(
DecisionEvent(
task_id=task.id,
question=question,
answer=fallback,
source=SOURCE_TIMEOUT,
rule_id=rule_id,
waited_sec=waited,
session_id=session_id,
)
)
return fallback, SOURCE_TIMEOUT, waited, session_id
self.decision_log.record(
DecisionEvent(
task_id=task.id,
question=question,
answer=answer,
source=SOURCE_HUMAN,
waited_sec=waited,
session_id=session_id,
)
)
return answer, SOURCE_HUMAN, waited, session_id
def _append_decision(self, question: str, answer: str) -> None:
with self._lock:
self._decisions_made.append((question, answer))
@property
def decisions_made(self) -> list[tuple[str, str]]:
with self._lock:
return list(self._decisions_made)
# ── 主循环 ──────────────────────────────────────────────────────
def run_forever(self) -> None:
"""一直取任务跑,直到队列跑完或收到停止信号。"""
self._emit("runner_started")
while not self.stop.is_set():
task = self.queue.next_ready()
if task is None:
if not self.queue.has_unfinished():
break
# 有任务卡在依赖或重试等待里
if not self._wait_for_retry():
break
continue
self.run_task(task)
self._emit("runner_stopped")
self._save()
def _wait_for_retry(self) -> bool:
"""等一个正在重试等待中的任务到期。返回 False 表示应该退出。"""
for t in self.queue.tasks:
if t.status == RETRYING:
wait = max(0.0, t.duration_sec or 0.0)
if wait <= 0:
return True
self._emit("retry_wait", t)
sleep_interruptible(min(wait, 5), self.stop)
return True
# 没有在重试的任务,但还有未完成 —— 说明被依赖卡住了
blocked = [t for t in self.queue.tasks if t.status == PENDING and not t.enabled]
if blocked:
self._emit("queue_blocked", blocked[0])
return False
return False
# ── 单任务 ──────────────────────────────────────────────────────
def run_task(self, task: Task) -> TaskOutcome:
"""跑一个任务(含看门狗、决策打断与重试)。"""
self.clear_log()
self._current = task
with self._lock:
self._decisions_made = []
task.status = RUNNING
task.started_at = now()
task.finished_at = None
task.exit_code = None
task.last_error = ""
task.summary = ""
self._emit("task_started", task)
max_attempts = self.runner_cfg.watchdog.max_retries + 1
outcome = TaskOutcome(task.id, FAILED, None, 0, 0.0)
for attempt in range(1, max_attempts + 1):
if self.stop.is_set():
task.status = STOPPED
task.finished_at = now()
break
task.attempts = attempt
self._save()
kind, info = self._run_leg(task)
if kind == "success":
task.status = SUCCESS
task.last_error = ""
task.finished_at = now()
self._emit("task_succeeded", task)
break
if kind == "timeout":
task.last_error = (
f"{'总时长' if info == 'total' else '空闲'}超时 "
f"({info}),已终止 agent"
)
self._emit("task_timeout", task)
elif kind == "stopped":
task.status = STOPPED
task.finished_at = now()
elif kind == "blocked":
task.status = BLOCKED
task.finished_at = now()
else:
task.last_error = task.last_error or info
self._emit("task_error", task)
# 失败:决定是否重试
task.finished_at = task.finished_at or now()
if attempt < max_attempts and not self.stop.is_set():
task.status = RETRYING
self._emit("task_retrying", task)
self._save()
sleep_interruptible(self.runner_cfg.watchdog.backoff_sec, self.stop)
if self.stop.is_set():
break
task.status = RUNNING
task.started_at = now()
continue
else:
task.status = FAILED if task.status != BLOCKED else BLOCKED
self._emit("task_failed", task)
if task.status != SUCCESS:
task.status = task.status if task.status != RUNNING else FAILED
task.finished_at = task.finished_at or now()
outcome = TaskOutcome(
task.id,
task.status,
task.exit_code,
task.attempts,
task.duration_sec or 0.0,
error=task.last_error,
summary=task.summary,
decisions=len(self.decisions_made),
)
self._save()
self._emit("task_done", task)
self._current = None
self._current_proc = None
return outcome
# ── 一次 agent 运行(含决策打断与续跑)────────────────────────
def _run_leg(self, task: Task) -> tuple[str, str]:
"""跑一次 agent。返回 (kind, info)。
kind ∈ success / failed / timeout / stopped / blocked
"""
session_id = ""
resume_prompt = ""
decision_count = 0
while True:
prompt, err = build_prompt(
self.project_root,
self.project_cfg,
task.plan,
task.prompt,
)
if err:
task.last_error = err
return "failed", err
made = self.decisions_made
if made:
prompt += "\n已经做出的决策(不要重复询问):\n" + "\n".join(
f"- {q} → {a}" for q, a in made
) + "\n"
if resume_prompt:
prompt = resume_prompt
prompt_file = self.log_dir / f"{task.id}.prompt.md"
prompt_file.parent.mkdir(parents=True, exist_ok=True)
prompt_file.write_text(prompt, encoding="utf-8")
ok, avail_err = check_agent_available(self.runner_cfg.agent_command)
if not ok:
task.last_error = avail_err
return "failed", avail_err
command = self._build_command(prompt, session_id)
log_path = self.log_dir / f"{task.id}.log"
task.log_path = str(log_path.relative_to(self.project_root))
proc = AgentProcess(
command=command,
cwd=self.project_root / self.runner_cfg.workdir,
env={**self.runner_cfg.agent_env, **self.project_cfg.agent_env},
on_line=lambda line: self._on_agent_line(task, line),
idle_timeout_sec=self.runner_cfg.watchdog.idle_timeout_sec,
total_timeout_sec=self.runner_cfg.watchdog.total_timeout_sec,
kill_grace_sec=self.runner_cfg.watchdog.kill_grace_sec,
output_format=self.runner_cfg.decision.output_format,
session_pattern=self.runner_cfg.decision.session_pattern,
)
self._current_proc = proc
try:
proc.start()
except (OSError, ValueError) as exc:
task.last_error = f"无法启动 agent: {exc}"
return "failed", task.last_error
result = self._watch(proc, task)
exit_code = proc.wait(timeout=30)
if exit_code is None:
proc.terminate()
exit_code = proc.wait(timeout=10)
task.exit_code = exit_code
self._write_log(task, log_path)
# ── agent 抛了问题 ────────────────────────────────────
if result.kind == "question":
decision_count += 1
if decision_count > MAX_DECISIONS_PER_TASK:
task.last_error = (
f"决策次数超过上限({MAX_DECISIONS_PER_TASK} 次),任务中止"
)
return "failed", task.last_error
answer, source, waited, sid = self._resolve_question(
task, result.question, result.session_id
)
self._append_decision(result.question, answer)
self._log(f" ↳ 决策[{source}]: {answer}")
self._emit("decision", task)
if (
self.runner_cfg.decision.resume == "session"
and sid
and self.runner_cfg.decision.session_args
):
# 用同一个 session 续跑,agent 的上下文不丢
session_id = sid
resume_prompt = build_resume_prompt(
result.question, answer, task.plan
)
continue
# 拿不到 session(或配置成 restart)→ 重跑整个任务,
# 决策历史会注入新一轮的 prompt
session_id = ""
resume_prompt = ""
continue
if result.kind == "timeout":
return "timeout", result.timeout_kind
if result.kind == "stopped":
return "stopped", ""
if task.status == BLOCKED:
return "blocked", task.last_error
if exit_code == 0:
return "success", ""
return "failed", f"agent 退出码 {exit_code}"
def _build_command(self, prompt: str, session_id: str) -> list[str]:
"""组装 agent 命令行(含 json 输出格式与 session 续跑参数)。"""
cfg = self.runner_cfg.decision
command = [self.runner_cfg.agent_command, *self.runner_cfg.agent_args]
if cfg.output_format == "json":
command.extend(cfg.json_args)
if session_id:
command.extend(cfg.session_command(session_id))
command.append(prompt)
return command
def _write_log(self, task: Task, log_path: Path) -> None:
with self._lock:
log_text = "\n".join(self._current_lines)
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
log_path.write_text(log_text + "\n", encoding="utf-8")
except OSError:
pass
# ── 看门狗 ──────────────────────────────────────────────────────
def _watch(self, proc: AgentProcess, task: Task) -> WatchResult:
"""盯住 agent:空闲超时 / 总时长超时 / agent 抛问题 → 终止。"""
while True:
if self.stop.is_set():
proc.terminate()
return WatchResult(kind="stopped")
asked = self._take_question()
if asked is not None:
proc.terminate()
return WatchResult(
kind="question", question=asked[0], session_id=asked[1]
)
timed_out, kind = proc.check_timeout()
if timed_out:
proc.terminate()
return WatchResult(kind="timeout", timeout_kind=kind)
if not proc.alive:
# agent 可能问完就退出了 —— 再查一次标志,别漏掉
asked = self._take_question()
if asked is not None:
return WatchResult(
kind="question", question=asked[0], session_id=asked[1]
)
return WatchResult(kind="exited")
time.sleep(0.1)
# ── agent 输出处理 ──────────────────────────────────────────────
def _take_question(self) -> tuple[str, str] | None:
with self._lock:
asked = self._ask_question
self._ask_question = None
return asked
def _on_agent_line(self, task: Task, line: str) -> None:
self._log(line)
kind, value = parse_agent_line(line)
if kind == "decision":
question, answer = value # type: ignore[misc]
self.decision_log.record(
DecisionEvent(
task_id=task.id,
question=question,
answer=answer,
source=SOURCE_AGENT,
session_id=self._session_id(),
)
)
self._append_decision(question, answer)
self._emit("decision", task)
elif kind == "question":
if should_ask(self.runner_cfg.decision.mode):
# 有人值守:打断 agent,等人来答
with self._lock:
self._ask_question = (value, self._session_id()) # type: ignore[assignment]
return
# 无人值守:当场按规则/兜底策略决策,agent 继续跑
answer, rule_id = resolve_answer(self.project_cfg, value) # type: ignore[arg-type]
self.decision_log.record(
DecisionEvent(
task_id=task.id,
question=value, # type: ignore[arg-type]
answer=answer,
source=SOURCE_RULE if rule_id else SOURCE_FALLBACK,
rule_id=rule_id,
session_id=self._session_id(),
)
)
self._append_decision(value, answer) # type: ignore[arg-type]
self._log(f" ↳ 默认决策[{rule_id or 'fallback'}]: {answer}")
self._emit("decision", task)
elif kind == "done":
task.summary = value # type: ignore[assignment]
self._emit("task_summary", task)
elif kind == "blocked":
task.last_error = value # type: ignore[assignment]
task.status = BLOCKED
self._emit("task_blocked", task)
def _session_id(self) -> str:
proc = self._current_proc
return proc.session_id if proc is not None else ""
# ── 状态持久化 ──────────────────────────────────────────────────
def _save(self) -> None:
try:
save_state(self.paths, self.queue)
except OSError:
pass
def snapshot(self) -> str:
stats = self.queue.stats()
return (
f"{fmt_ts(now())} 总 {len(self.queue)} · "
f"待跑 {stats.get(PENDING, 0)} · 运行 {stats.get(RUNNING, 0)} · "
f"成功 {stats.get(SUCCESS, 0)} · 失败 {stats.get(FAILED, 0)}"
)

View File

@@ -0,0 +1,174 @@
"""默认决策:规则匹配 + 决策记录。
三种来源:
1. agent 自己按默认决策执行后输出 `DECISION: <问题> → <决策>`,我们解析并记录;
2. agent 抛出一个待决问题(输出 `QUESTION: <问题>`)—— 无人值守时用规则匹配给答案,
有人值守时先问人(见 controller),答案最终都会回灌给 agent 并记录。
记录写在 `<queue>/decisions.jsonl`,一行一条,便于后续回溯。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from .config import DECISION_MODE_ATTENDED, DecisionRule, ProjectConfig
from .util import append_jsonl, now_iso
DECISION_RE = re.compile(r"^\s*DECISION\s*[::]\s*(.+?)\s*(?:→|->)\s*(.+?)\s*$")
QUESTION_RE = re.compile(r"^\s*QUESTION\s*[::]\s*(.+?)\s*$")
BLOCKED_RE = re.compile(r"^\s*BLOCKED\s*[::]\s*(.+?)\s*$")
DONE_RE = re.compile(r"^\s*DONE\s*[::]\s*(.+?)\s*$")
# 决策来源
SOURCE_AGENT = "agent" # agent 自己输出的 DECISION
SOURCE_RULE = "rule" # 命中预设规则
SOURCE_FALLBACK = "fallback" # 兜底策略(onUnknownDecision)
SOURCE_HUMAN = "human" # 人在 TUI 里回答的
SOURCE_TIMEOUT = "timeout" # 等待超时后自动兜底的
@dataclass
class DecisionEvent:
task_id: str
question: str
answer: str
source: str = SOURCE_AGENT
rule_id: str = ""
at: str = ""
waited_sec: float | None = None
session_id: str = ""
def to_record(self) -> dict:
return {
"at": self.at or now_iso(),
"task_id": self.task_id,
"question": self.question,
"answer": self.answer,
"source": self.source,
"rule_id": self.rule_id,
"waited_sec": round(self.waited_sec, 1) if self.waited_sec is not None else 0.0,
"session_id": self.session_id,
}
class DecisionLog:
"""决策记录:JSONL 追加写 + 内存缓存。"""
def __init__(self, path: Path) -> None:
self.path = path
self._records: list[dict] = []
def load(self) -> list[dict]:
import json
if not self.path.exists():
self._records = []
return self._records
out = []
for line in self.path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
try:
out.append(json.loads(line))
except json.JSONDecodeError:
continue
self._records = out
return out
def record(self, event: DecisionEvent) -> dict:
rec = event.to_record()
append_jsonl(self.path, rec)
self._records.append(rec)
return rec
@property
def records(self) -> list[dict]:
return list(self._records)
def for_task(self, task_id: str) -> list[dict]:
return [r for r in self._records if r.get("task_id") == task_id]
def match_rule(rules: list[DecisionRule], question: str) -> DecisionRule | None:
"""用关键词/正则匹配一条默认决策。"""
q = question.strip()
for rule in rules:
if not rule.enabled:
continue
if rule.question and (rule.question.strip() == q or rule.question.strip() in q):
return rule
if rule.match:
try:
if re.search(rule.match, q):
return rule
except re.error:
if rule.match.lower() in q.lower():
return rule
return None
def parse_agent_line(line: str) -> tuple[str, str]:
"""解析 agent 的一行输出。
返回 (kind, value),kind ∈ decision / question / blocked / done / ''。
"""
m = DECISION_RE.match(line)
if m:
return "decision", (m.group(1).strip(), m.group(2).strip()) # type: ignore[return-value]
m = QUESTION_RE.match(line)
if m:
return "question", m.group(1).strip() # type: ignore[return-value]
m = BLOCKED_RE.match(line)
if m:
return "blocked", m.group(1).strip() # type: ignore[return-value]
m = DONE_RE.match(line)
if m:
return "done", m.group(1).strip() # type: ignore[return-value]
return "", ""
def resolve_answer(project_cfg: ProjectConfig, question: str) -> tuple[str, str]:
"""算出(答案, rule_id)—— **纯函数,不写日志**。
命中规则就用规则答案,否则用项目的兜底策略。
"""
rule = match_rule(project_cfg.decisions, question)
if rule is not None:
return (rule.answer or project_cfg.on_unknown_decision), rule.id
return project_cfg.on_unknown_decision, ""
def should_ask(mode: str) -> bool:
"""该模式下要不要问人。
- `attended`(有人值守):要问
- `unattended`(无人值守):不问
"""
return mode == DECISION_MODE_ATTENDED
def decide(
project_cfg: ProjectConfig,
log: DecisionLog,
task_id: str,
question: str,
) -> tuple[str, str]:
"""给 agent 抛出的问题一个默认答案(无人值守路径)。
返回 (answer, rule_id)。命中规则就用规则答案,否则用项目的兜底策略。
"""
answer, rule_id = resolve_answer(project_cfg, question)
log.record(
DecisionEvent(
task_id=task_id,
question=question,
answer=answer,
source=SOURCE_RULE if rule_id else SOURCE_FALLBACK,
rule_id=rule_id,
)
)
return answer, rule_id

View File

@@ -0,0 +1,329 @@
"""跨平台按键读取:POSIX 用 termios,Windows 用 msvcrt。
只依赖标准库,不需要 prompt_toolkit 之类的重依赖。
"""
from __future__ import annotations
import os
import sys
import threading
from typing import Callable
from .util import is_windows
# 规范化按键名
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
ENTER = "enter"
ESC = "esc"
BACKSPACE = "backspace"
TAB = "tab"
CTRL_C = "ctrl-c"
NONE = ""
KEYBOARD_HELP = (
"↑↓ 选择 a 追加 plan r 重试 p 暂停/恢复 d 移除 "
"Enter 查看日志 Esc 返回 c 清屏 q 退出"
)
DECISION_HELP = (
"待决策时: Enter 提交答案 · Esc 用默认决策 · Ctrl-C 退出"
)
_WIN_SPECIAL = {
"H": UP,
"P": DOWN,
"K": LEFT,
"M": RIGHT,
"G": ENTER,
"S": LEFT,
"R": RIGHT,
"\x0d": ENTER,
"\x1b": ESC,
"\x08": BACKSPACE,
"\x09": TAB,
}
# 按下 ESC 后等这么久还等不到后续字节,就认为用户是单独按了 ESC
ESC_TIMEOUT = 0.05
# 轮询间隔(秒):让读线程能及时响应 stop()
POLL_INTERVAL = 0.2
class RawMode:
"""进入原始模式(按键立即返回,不回显),退出时恢复。"""
def __init__(self) -> None:
self._fd = None
self._old = None
self._active = False
def __enter__(self) -> "RawMode":
if is_windows():
self._active = True
return self
try:
import termios
import tty
self._fd = sys.stdin.fileno()
self._old = termios.tcgetattr(self._fd)
tty.setraw(self._fd)
self._active = True
except Exception: # noqa: BLE001 - 没有 tty 时降级为行模式
self._active = False
return self
def __exit__(self, *exc) -> None:
if not self._active or self._fd is None or self._old is None:
return
try:
import termios
termios.tcsetattr(self._fd, termios.TCSADRAIN, self._old)
except Exception: # noqa: BLE001
pass
def _utf8_seq_len(lead: int) -> int:
"""按 UTF-8 首字节判断这个字符总共占几个字节。
汉字 3 字节、emoji 4 字节。读键盘必须 **按字节凑齐再解**,
否则一个汉字会被拆成 3 次读、每次都解码失败 → 中文全变问号。
"""
if lead < 0x80:
return 1
if lead >= 0xF0:
return 4
if lead >= 0xE0:
return 3
if lead >= 0xC0:
return 2
return 1 # 非法首字节(续字节开头)—— 当 1 字节处理,别死循环
def _normalize_key(ch: str) -> str:
"""把一个字符归一成按键名(控制键给名字,其余原样返回)。"""
if ch in ("\r", "\n"):
return ENTER
if ch in ("\x7f", "\x08"):
return BACKSPACE
if ch == "\x03":
return CTRL_C
if ch == "\t":
return TAB
return ch
_CSI_KEYS = {
"[A": UP,
"[B": DOWN,
"[C": RIGHT,
"[D": LEFT,
"[H": UP,
"[F": DOWN,
}
class PosixKeyReader:
"""POSIX 下的按键读取:懂 UTF-8 多字节字符,也懂 ESC 序列。
为什么不用"一次 os.read(fd, 1)":那样会把一个汉字的 3 个字节
拆成 3 次读,每次 `decode(errors="replace")` 都失败 → 中文全变问号
(实测:决策窗口里输入"先修 Bug",落盘变成"??? Bug")。
做法:字节先进缓冲区,按 UTF-8 首字节凑齐长度再整体解码。
"""
def __init__(self) -> None:
self._buf = bytearray()
self._eof = False
# ── 字节层 ──────────────────────────────────────────────────────
def _pump(self, fd: int, timeout: float | None) -> bool:
"""把 fd 里的可用字节读进缓冲区。返回是否读到东西。"""
import select
try:
ready, _, _ = select.select([fd], [], [], timeout)
except (OSError, ValueError):
return False
if not ready:
return False
try:
data = os.read(fd, 1024)
except OSError:
return False
if not data:
self._eof = True
return False
self._buf.extend(data)
return True
def _take_char(self) -> str | None:
"""从缓冲区头部取一个完整字符;字节还不够返回 None。"""
if not self._buf:
return None
need = _utf8_seq_len(self._buf[0])
if len(self._buf) < need:
return None
raw = bytes(self._buf[:need])
del self._buf[:need]
return raw.decode("utf-8", errors="replace")
def _find_csi_final(self) -> int | None:
"""在缓冲区里找 CSI 序列的结束字节下标。
缓冲区形如 b"[A" / b"[1;5C"(下标 0 是 '[')。
返回 None 表示"还没收全";返回 -1 表示"非法序列"。
"""
for i in range(1, len(self._buf)):
b = self._buf[i]
if 0x40 <= b <= 0x7E:
return i
if not (0x20 <= b <= 0x3F):
return -1
return None
# ── ESC 序列 ────────────────────────────────────────────────────
def _read_escape(self, fd: int) -> str:
"""已经读到 ESC,判断它是单独按键还是某个序列的开头。"""
if not self._buf:
self._pump(fd, ESC_TIMEOUT)
if not self._buf or self._buf[0] != 0x5B: # '['
return ESC # 后面的字节留给下一次读
while True:
idx = self._find_csi_final()
if idx is not None and idx >= 0:
seq = bytes(self._buf[: idx + 1])
del self._buf[: idx + 1]
return _CSI_KEYS.get(seq.decode("ascii", errors="replace"), NONE)
if idx == -1: # 非法序列,丢掉 ESC[ 别把后面的正文吃掉
del self._buf[:1]
return NONE
if not self._pump(fd, ESC_TIMEOUT):
del self._buf[:1]
return NONE
# ── 对外 ────────────────────────────────────────────────────────
def read_key(self, fd: int) -> str:
"""读一个按键(控制键给名字,其余返回原字符)。
返回 NONE 表示"暂时没读到"(超时或输入流结束)。
"""
while True:
ch = self._take_char()
if ch is None:
if self._eof:
return NONE
self._pump(fd, POLL_INTERVAL)
continue
if ch == "\x1b":
return self._read_escape(fd)
return _normalize_key(ch)
_POSIX_READER = PosixKeyReader()
def _read_posix_key(fd: int) -> str:
"""读一个按键(POSIX)。保留函数形式,内部共用一个带缓冲的读取器。"""
return _POSIX_READER.read_key(fd)
def _read_win_key() -> str:
import msvcrt
ch = msvcrt.getwch()
if ch in ("\x00", "\xe0"):
ch2 = msvcrt.getwch()
return _WIN_SPECIAL.get(ch2, NONE)
if ch in ("\r", "\n"):
return ENTER
if ch in ("\x7f", "\x08"):
return BACKSPACE
if ch == "\x03":
return CTRL_C
if ch == "\t":
return TAB
return ch
class KeyReader:
"""后台线程读按键,交给回调。"""
def __init__(self, on_key: Callable[[str], None]) -> None:
self.on_key = on_key
self._thread: threading.Thread | None = None
self._stop = threading.Event()
self._raw = RawMode()
self._posix = PosixKeyReader()
def start(self) -> None:
self._raw.__enter__()
self._thread = threading.Thread(target=self._loop, name="key-reader", daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop.set()
self._raw.__exit__()
def _loop(self) -> None:
while not self._stop.is_set():
try:
if is_windows():
key = _read_win_key()
else:
fd = sys.stdin.fileno()
key = self._posix.read_key(fd)
except Exception: # noqa: BLE001
break
if key == NONE:
continue
try:
self.on_key(key)
except Exception: # noqa: BLE001
pass
if key == CTRL_C:
break
def read_line(prompt: str = "") -> str:
"""行模式读一行(用于非 TUI 场景)。"""
if prompt:
print(prompt, end="", flush=True)
try:
return sys.stdin.readline().strip()
except (EOFError, KeyboardInterrupt):
return ""
def confirm(prompt: str, default: bool = False) -> bool:
suffix = "[Y/n]" if default else "[y/N]"
ans = read_line(f"{prompt} {suffix} ").lower()
if not ans:
return default
return ans in ("y", "yes")
__all__ = [
"BACKSPACE",
"CTRL_C",
"DOWN",
"ENTER",
"ESC",
"KEYBOARD_HELP",
"KeyReader",
"LEFT",
"NONE",
"PosixKeyReader",
"RawMode",
"RIGHT",
"TAB",
"UP",
"confirm",
"read_line",
]

View File

@@ -0,0 +1,66 @@
"""提示词组装:把项目默认提示词 + 默认决策 + plan 内容拼成给 agent 的一次性提示。"""
from __future__ import annotations
from pathlib import Path
from .config import ProjectConfig
PLAN_PLACEHOLDER = "{{PLAN}}"
DECISIONS_PLACEHOLDER = "{{DECISIONS}}"
def read_plan(project_root: Path, plan_rel: str) -> tuple[str, str]:
"""读 plan 文件,返回 (内容, 错误信息)。"""
path = project_root / plan_rel
if not path.exists():
return "", f"plan 文件不存在: {plan_rel}"
try:
text = path.read_text(encoding="utf-8")
except OSError as exc:
return "", f"plan 文件读取失败: {plan_rel} ({exc})"
if not text.strip():
return "", f"plan 文件为空: {plan_rel}"
return text, ""
def build_prompt(
project_root: Path,
project_cfg: ProjectConfig,
plan_rel: str,
task_prompt: str = "",
) -> tuple[str, str]:
"""返回 (最终提示词, 错误信息)。"""
plan_text, err = read_plan(project_root, plan_rel)
if err:
return "", err
decisions = project_cfg.decision_text() or "(无预设决策,遇到需决策的问题请选择最安全、可回滚的方案)"
template = project_cfg.default_prompt or ""
if PLAN_PLACEHOLDER in template:
prompt = template.replace(PLAN_PLACEHOLDER, plan_text)
else:
prompt = f"{template}\n\n{plan_text}"
if DECISIONS_PLACEHOLDER in prompt:
prompt = prompt.replace(DECISIONS_PLACEHOLDER, decisions)
elif decisions:
prompt = f"{prompt}\n\n默认决策:\n{decisions}"
prompt += f"\n\n---\n本次任务:{plan_rel}\n"
if task_prompt:
prompt += f"补充要求:\n{task_prompt}\n"
return prompt, ""
def build_resume_prompt(question: str, answer: str, plan_rel: str) -> str:
"""续跑时的提示词:把人的决策送回给同一个 session 的 agent。"""
return (
f"针对你刚才提出的问题:{question}\n\n"
f"决策如下:{answer}\n\n"
f"请基于这个决策继续完成原任务(计划:{plan_rel})。"
"不要重复已经完成的步骤,只做剩下的部分。"
)

View File

@@ -0,0 +1,324 @@
"""任务队列:加载 / 追加 / 状态跟踪。
队列定义在 `.overnight-runner/queue/<name>/queue.yaml`(可提交进仓库),
运行时状态放在同目录的 `state.json`(不提交)。
每条队列一个独立目录 —— 多人可以在同一个项目里各跑各的队列,互不干扰。
"""
from __future__ import annotations
import json
import re
import threading
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any
from . import yaml_lite as yaml
from .config import QueuePaths
from .util import atomic_write, now, now_iso, slugify, today_stamp
# 任务状态
PENDING = "pending"
RUNNING = "running"
RETRYING = "retrying"
SUCCESS = "success"
FAILED = "failed"
STOPPED = "stopped"
BLOCKED = "blocked"
STATUSES = (PENDING, RUNNING, RETRYING, SUCCESS, FAILED, STOPPED, BLOCKED)
# plan 文件名常带日期前缀(YYYYMMDD-xxx / YYYY-MM-DD-xxx),别再拼一遍
DATE_PREFIX_RE = re.compile(r"^\d{4}-?\d{2}-?\d{2}[-_]")
@dataclass
class Task:
id: str
plan: str
prompt: str = ""
priority: int = 100
enabled: bool = True
role: str = "" # BA / DEV / QA —— 只是标签,用于分组显示
depends_on: list[str] = field(default_factory=list)
# 运行时状态
status: str = PENDING
attempts: int = 0
started_at: datetime | None = None
finished_at: datetime | None = None
exit_code: int | None = None
last_error: str = ""
summary: str = ""
log_path: str = ""
@property
def plan_path(self) -> Path:
return Path(self.plan)
@property
def duration_sec(self) -> float | None:
if self.started_at is None:
return None
end = self.finished_at or now()
# 状态文件是手改过的,可能写了不带时区的时间 —— 别让渲染循环炸掉
if end.tzinfo is None and self.started_at.tzinfo is not None:
end = end.replace(tzinfo=self.started_at.tzinfo)
elif end.tzinfo is not None and self.started_at.tzinfo is None:
self.started_at = self.started_at.replace(tzinfo=end.tzinfo)
return (end - self.started_at).total_seconds()
def to_def(self) -> dict:
"""写回 YAML 的定义部分。"""
data: dict[str, Any] = {"id": self.id, "plan": self.plan}
if self.prompt:
data["prompt"] = self.prompt
if self.priority != 100:
data["priority"] = self.priority
if self.role:
data["role"] = self.role
if self.depends_on:
data["depends_on"] = self.depends_on
if not self.enabled:
data["enabled"] = False
return data
def to_state(self) -> dict:
return {
"id": self.id,
"plan": self.plan,
"status": self.status,
"attempts": self.attempts,
"started_at": self.started_at.isoformat(timespec="seconds") if self.started_at else None,
"finished_at": self.finished_at.isoformat(timespec="seconds") if self.finished_at else None,
"exit_code": self.exit_code,
"last_error": self.last_error,
"summary": self.summary,
"log_path": self.log_path,
}
class Queue:
"""线程安全的任务队列。"""
def __init__(self, tasks: list[Task] | None = None) -> None:
self._tasks: list[Task] = tasks or []
self._lock = threading.RLock()
# ── 基本访问 ────────────────────────────────────────────────────
@property
def tasks(self) -> list[Task]:
with self._lock:
return list(self._tasks)
def get(self, task_id: str) -> Task | None:
with self._lock:
for t in self._tasks:
if t.id == task_id:
return t
return None
def __len__(self) -> int:
with self._lock:
return len(self._tasks)
# ── 变更 ────────────────────────────────────────────────────────
def add(self, task: Task) -> Task:
with self._lock:
if self.get(task.id) is not None:
raise ValueError(f"任务 id 已存在: {task.id}")
self._tasks.append(task)
self._tasks.sort(key=lambda t: (t.priority, t.id))
return task
def remove(self, task_id: str) -> bool:
with self._lock:
before = len(self._tasks)
self._tasks = [t for t in self._tasks if t.id != task_id]
return len(self._tasks) != before
def update(self, task_id: str, **fields) -> Task | None:
with self._lock:
task = self.get(task_id)
if task is None:
return None
for key, value in fields.items():
setattr(task, key, value)
return task
# ── 调度 ────────────────────────────────────────────────────────
def next_ready(self) -> Task | None:
"""下一个可以跑的任务:enabled + pending + 依赖已完成 + 优先级最高。"""
with self._lock:
done = {t.id for t in self._tasks if t.status == SUCCESS}
candidates = [
t
for t in self._tasks
if t.enabled and t.status == PENDING and all(d in done for d in t.depends_on)
]
if not candidates:
return None
candidates.sort(key=lambda t: (t.priority, t.id))
return candidates[0]
def pending_count(self) -> int:
with self._lock:
return sum(1 for t in self._tasks if t.status in (PENDING, RUNNING, RETRYING))
def has_unfinished(self) -> bool:
with self._lock:
return any(t.status in (PENDING, RUNNING, RETRYING) for t in self._tasks)
def stats(self) -> dict[str, int]:
with self._lock:
out = {s: 0 for s in STATUSES}
for t in self._tasks:
out[t.status] = out.get(t.status, 0) + 1
return out
def build_task(
project_root: Path,
plan: str,
prompt: str = "",
role: str = "",
priority: int = 100,
task_id: str | None = None,
existing_ids: set[str] | None = None,
) -> Task:
"""由 plan 路径构造任务;plan 相对项目根目录。
id 默认取 plan 文件名(去掉日期前缀)—— 同一个 plan 可以在同一天被排多次,
冲突时自动加 `-2` / `-3` 序号。
"""
plan_rel = _normalize_rel(project_root, plan)
if task_id is None:
# plan 文件名通常已经带日期前缀(20261106-xxx):保留原日期,别再拼成双日期
stem = Path(plan_rel).stem
if DATE_PREFIX_RE.match(stem):
base = slugify(stem, fallback="task")
task_id = base
else:
base = slugify(stem, fallback="task")
task_id = f"{today_stamp()}-{base}"
taken = existing_ids or set()
if task_id in taken:
n = 2
while f"{task_id}-{n}" in taken:
n += 1
task_id = f"{task_id}-{n}"
return Task(
id=task_id,
plan=plan_rel,
prompt=prompt,
role=role,
priority=priority,
)
def _normalize_rel(project_root: Path, plan: str) -> str:
"""把 plan 路径规范成相对项目根的 POSIX 风格路径。"""
p = Path(plan)
if p.is_absolute():
try:
p = p.resolve().relative_to(project_root.resolve())
except ValueError:
return p.as_posix()
return p.as_posix()
def task_from_def(defs: dict, index: int = 0) -> Task:
plan = defs.get("plan") or ""
task_id = defs.get("id") or f"task-{index + 1}"
return Task(
id=str(task_id),
plan=plan,
prompt=defs.get("prompt") or "",
priority=int(defs.get("priority", 100)),
enabled=bool(defs.get("enabled", True)),
role=defs.get("role") or "",
depends_on=list(defs.get("depends_on") or []),
)
def load_queue(paths: QueuePaths, queue_defs: list[dict]) -> Queue:
"""把 YAML 定义与运行时状态合并成队列。"""
tasks = [task_from_def(d, i) for i, d in enumerate(queue_defs)]
queue = Queue(tasks)
for st in _read_states(paths):
task = queue.get(st.get("id", ""))
if task is None:
# 兼容老 id(如 20261106-20261106-xxx)—— 退化成按 plan 路径匹配
task = next(
(t for t in queue.tasks if t.plan == st.get("plan", "")), None
)
if task is None:
continue
task.status = st.get("status", PENDING)
task.attempts = int(st.get("attempts", 0))
task.exit_code = st.get("exit_code")
task.last_error = st.get("last_error", "")
task.summary = st.get("summary", "")
task.log_path = st.get("log_path", "")
started = st.get("started_at")
finished = st.get("finished_at")
task.started_at = datetime.fromisoformat(started) if started else None
task.finished_at = datetime.fromisoformat(finished) if finished else None
return queue
def _read_states(paths: QueuePaths) -> list[dict]:
"""读运行时状态。
`state.json` 缺失或损坏时回落到 `state.json.bak` —— 避免误删状态文件
就把已经跑完的任务全部重新排队。
"""
for path in (paths.state, paths.state.with_name(paths.state.name + ".bak")):
if not path.exists():
continue
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
continue
if isinstance(data, dict):
return list(data.get("tasks") or [])
return []
def save_state(paths: QueuePaths, queue: Queue) -> Path:
"""写运行时状态(同时留一份 .bak 兜底)。"""
payload = {
"updated_at": now_iso(),
"tasks": [t.to_state() for t in queue.tasks],
}
text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
atomic_write(paths.state, text)
try:
atomic_write(paths.state.with_name(paths.state.name + ".bak"), text)
except OSError:
pass
return paths.state
def load_queue_defs(paths: QueuePaths) -> list[dict]:
"""读队列定义(`.overnight-runner/queue/<name>/queue.yaml`)。"""
if not paths.config.exists():
return []
try:
data = yaml.loads(paths.config.read_text(encoding="utf-8")) or {}
except (OSError, ValueError):
return []
return list(data.get("queue") or [])
def save_queue_defs(paths: QueuePaths, queue: Queue) -> Path:
"""把队列定义写回 `queue.yaml`(追加 plan 用)。"""
paths.dir.mkdir(parents=True, exist_ok=True)
payload = {"queue": [t.to_def() for t in queue.tasks]}
atomic_write(paths.config, yaml.dumps(payload))
return paths.config

View File

@@ -0,0 +1,279 @@
"""纯 ANSI 终端绘制 —— 零第三方依赖。
只依赖标准库。用 ANSI 转义序列直接画:
- 备用屏幕(全屏面板)
- 光标定位 / 隐藏
- 颜色(SGR)
- 边框(圆角 / 直角)
- 中日韩宽字符的显示宽度计算
没有 TTY 时(管道 / CI)会自动降级:不做任何转义,只输出纯文本。
"""
from __future__ import annotations
import os
import shutil
import sys
import unicodedata
from typing import Iterable
# ── 转义序列 ────────────────────────────────────────────────────────
ESC = "\x1b"
CSI = ESC + "["
ALT_SCREEN_ON = CSI + "?1049h"
ALT_SCREEN_OFF = CSI + "?1049l"
CURSOR_HIDE = CSI + "?25l"
CURSOR_SHOW = CSI + "?25h"
CLEAR = CSI + "2J"
CURSOR_HOME = CSI + "H"
RESET = CSI + "0m"
def _sgr(*codes: int | str) -> str:
return CSI + ";".join(str(c) for c in codes) + "m"
class Style:
"""语义色。"""
RESET = _sgr(0)
BOLD = _sgr(1)
DIM = _sgr(2)
ITALIC = _sgr(3)
REVERSE = _sgr(7)
BLACK = _sgr(30)
RED = _sgr(31)
GREEN = _sgr(32)
YELLOW = _sgr(33)
BLUE = _sgr(34)
MAGENTA = _sgr(35)
CYAN = _sgr(36)
WHITE = _sgr(37)
GREY = _sgr(90)
BRIGHT_RED = _sgr(91)
BRIGHT_GREEN = _sgr(92)
BRIGHT_YELLOW = _sgr(93)
BRIGHT_BLUE = _sgr(94)
BRIGHT_MAGENTA = _sgr(95)
BRIGHT_CYAN = _sgr(96)
BRIGHT_WHITE = _sgr(97)
# ── 显示宽度 ────────────────────────────────────────────────────────
import re
_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
def char_width(ch: str) -> int:
"""字符的显示宽度(0 / 1 / 2)。"""
if ch == "\t":
return 4
if unicodedata.combining(ch):
return 0
if unicodedata.east_asian_width(ch) in ("W", "F"):
return 2
return 1
def _tokens(text: str) -> list[tuple[str, int]]:
"""把文本切成 (片段, 显示宽度) 序列。
ANSI 转义序列宽度算 0 —— 否则带颜色的文本会被算宽。
"""
out: list[tuple[str, int]] = []
i = 0
while i < len(text):
if text[i] == "\x1b":
m = _ANSI_RE.match(text, i)
if m:
out.append((m.group(0), 0))
i = m.end()
continue
out.append((text[i], char_width(text[i])))
i += 1
return out
def dwidth(text: str) -> int:
"""字符串的显示宽度(忽略 ANSI 转义序列)。"""
return sum(w for _, w in _tokens(text))
def truncate(text: str, width: int, ellipsis: str = "…") -> str:
"""按显示宽度截断(不切断 ANSI 序列)。"""
if width <= 0:
return ""
if dwidth(text) <= width:
return text
limit = width - dwidth(ellipsis)
out: list[str] = []
used = 0
for tok, w in _tokens(text):
if used + w > limit:
break
out.append(tok)
used += w
return "".join(out) + ellipsis + Style.RESET
def pad(text: str, width: int, align: str = "left") -> str:
"""按显示宽度补齐(忽略 ANSI 转义序列)。"""
w = dwidth(text)
if w >= width:
return text
space = " " * (width - w)
if align == "right":
return space + text
if align == "center":
left = (width - w) // 2
return " " * left + text + " " * (width - w - left)
return text + space
def wrap(text: str, width: int) -> list[str]:
"""按显示宽度折行(不打断宽字符,不切断 ANSI 序列)。"""
if width <= 0:
return [""]
lines: list[str] = []
for raw in text.split("\n"):
if dwidth(raw) <= width:
lines.append(raw)
continue
cur: list[str] = []
used = 0
for tok, w in _tokens(raw):
if used + w > width and cur:
lines.append("".join(cur))
cur = []
used = 0
cur.append(tok)
used += w
lines.append("".join(cur))
return lines or [""]
# ── 边框字符 ────────────────────────────────────────────────────────
class Box:
ROUND = "┌┐└┘─│├┤┬┴┼"
SQUARE = "┌┐└┘─│├┤┬┴┼"
ASCII = "+-++|+++++"
class Term:
"""终端绘制器。"""
def __init__(self, stream=None) -> None:
self.out = stream or sys.stdout
self.tty = bool(getattr(self.out, "isatty", lambda: False)())
self._alt = False
# ── 尺寸 ────────────────────────────────────────────────────────
def size(self) -> tuple[int, int]:
try:
size = shutil.get_terminal_size(fallback=(120, 40))
return max(40, size.columns), max(10, size.lines)
except OSError:
return 120, 40
# ── 基础输出 ────────────────────────────────────────────────────
def write(self, text: str) -> None:
try:
self.out.write(text)
except (OSError, ValueError):
pass
def flush(self) -> None:
try:
self.out.flush()
except (OSError, ValueError):
pass
def enter(self) -> None:
"""进备用屏幕 + 隐藏光标。"""
if not self.tty:
return
self.write(ALT_SCREEN_ON + CURSOR_HIDE + CLEAR + CURSOR_HOME)
self._alt = True
self.flush()
def leave(self) -> None:
"""退出备用屏幕 + 恢复光标。"""
if not self.tty:
self.flush()
return
self.write(CURSOR_SHOW + ALT_SCREEN_OFF)
self._alt = False
self.flush()
def clear(self) -> None:
if self.tty:
self.write(CLEAR + CURSOR_HOME)
def move(self, row: int, col: int) -> None:
"""移动光标(1-based)。"""
if self.tty:
self.write(f"{CSI}{row};{col}H")
def style(self, code: str, text: str) -> str:
if not self.tty or not code:
return text
return f"{code}{text}{Style.RESET}"
# ── 画框 ────────────────────────────────────────────────────────
def draw_box(
self,
x: int,
y: int,
w: int,
h: int,
title: str = "",
lines: Iterable[str] = (),
border: str = Style.CYAN,
title_style: str = Style.BOLD,
footer: str = "",
) -> None:
"""在 (x, y) 处画一个 w×h 的框,内容放 lines。"""
if w < 4 or h < 3:
return
b = Box.ROUND
tl, tr, bl, br, hz, vt = b[0], b[1], b[2], b[3], b[4], b[5]
# 上边框(带标题)
self.move(y, x)
if title:
label = " " + truncate(title, max(0, w - 6)) + " "
self.write(self.style(border, tl))
self.write(self.style(title_style, label))
self.write(self.style(border, hz * max(0, w - 2 - dwidth(label)) + tr))
else:
self.write(self.style(border, tl + hz * (w - 2) + tr))
# 内容
body = list(lines)
for i in range(h - 2):
content = body[i] if i < len(body) else ""
self.move(y + 1 + i, x)
self.write(self.style(border, vt))
self.write(pad(truncate(content, w - 2), w - 2))
self.write(self.style(border, vt))
# 下边框(带 footer)
self.move(y + h - 1, x)
if footer:
label = " " + truncate(footer, max(0, w - 6)) + " "
self.write(self.style(border, bl))
self.write(self.style(Style.DIM, label))
self.write(self.style(border, hz * max(0, w - 2 - dwidth(label)) + br))
else:
self.write(self.style(border, bl + hz * (w - 2) + br))
def draw_line(self, x: int, y: int, text: str, style: str = "") -> None:
"""在 (x, y) 处写一行(1-based 坐标)。"""
self.move(y, x)
self.write(self.style(style, text))

View File

@@ -0,0 +1,460 @@
"""分屏面板:左边任务队列,右边 coding agent 输出。
零第三方依赖 —— 用 ANSI 转义序列直接画(见 term.py)。
"""
from __future__ import annotations
import threading
import time
from pathlib import Path
from typing import Callable
from .config import QueuePaths, RunnerConfig
from .controller import RunnerController
from .keys import (
BACKSPACE,
CTRL_C,
DECISION_HELP,
DOWN,
ENTER,
ESC,
KEYBOARD_HELP,
UP,
)
from .queue import BLOCKED, FAILED, PENDING, RETRYING, RUNNING, SUCCESS, STOPPED, Queue, Task
from .term import Style, Term, dwidth, pad, truncate, wrap
STATUS_STYLE = {
PENDING: Style.DIM,
RUNNING: Style.BRIGHT_CYAN,
RETRYING: Style.BRIGHT_YELLOW,
SUCCESS: Style.BRIGHT_GREEN,
FAILED: Style.BRIGHT_RED,
BLOCKED: Style.BRIGHT_MAGENTA,
STOPPED: Style.GREY,
}
STATUS_LABEL = {
PENDING: "待跑",
RUNNING: "运行中",
RETRYING: "待重试",
SUCCESS: "成功",
FAILED: "失败",
BLOCKED: "阻塞",
STOPPED: "已停",
}
LEFT_WIDTH = 46
FOOTER_HEIGHT = 3
class RunnerUI:
"""overnight-runner 的分屏界面。"""
def __init__(
self,
controller: RunnerController,
queue: Queue,
runner_cfg: RunnerConfig,
project_root: Path,
paths: QueuePaths | None = None,
) -> None:
self.controller = controller
self.queue = queue
self.cfg = runner_cfg
self.project_root = project_root
self.paths = paths
self.term = Term()
self.selected = 0
self.detail_task_id: str | None = None
self.message = ""
self.message_level = "info"
self._quit = threading.Event()
self._input: dict | None = None # {"prompt": str, "buffer": str}
self._log_lines: list[str] = []
self._log_lock = threading.Lock()
# 决策窗口:人正在回答 agent 的问题
self._decision_buffer: str | None = None
self._decision_lock = threading.Lock()
controller.on_log = self._on_log
controller.on_event = self._on_event
# ── 回调 ────────────────────────────────────────────────────────
def _on_log(self, line: str) -> None:
with self._log_lock:
self._log_lines.append(line)
if len(self._log_lines) > 4000:
self._log_lines = self._log_lines[-2000:]
def _on_event(self, kind: str, task: Task | None) -> None:
labels = {
"task_started": f"▶ 开始 {task.id if task else ''}",
"task_succeeded": f"✔ 成功 {task.id if task else ''}",
"task_failed": f"✘ 失败 {task.id if task else ''}",
"task_timeout": f"⏱ 超时 {task.id if task else ''}",
"task_retrying": f"↻ 重试 {task.id if task else ''}",
"task_blocked": f"⛔ 阻塞 {task.id if task else ''}",
"task_done": f"— 结束 {task.id if task else ''}",
"decision": f"◆ 决策已记录 {task.id if task else ''}",
"retry_wait": f"⏳ 等待重试 {task.id if task else ''}",
"runner_started": "启动 overnight-runner",
"runner_stopped": "overnight-runner 已停止",
}
text = labels.get(kind)
if text:
self._set_message(text, "warn" if kind.endswith(("failed", "timeout", "blocked")) else "info")
def _set_message(self, text: str, level: str = "info") -> None:
self.message = text
self.message_level = level
# ── 交互 ────────────────────────────────────────────────────────
def handle_key(self, key: str) -> None:
# 决策窗口优先级最高 —— 它在阻塞 agent,等不起
if self.controller.pending_question() is not None:
self._handle_decision_key(key)
return
if self._input is not None:
self._handle_input_key(key)
return
if key == CTRL_C or key == "q":
self._quit.set()
self.controller.stop.set()
elif key == UP:
self.selected = max(0, self.selected - 1)
elif key == DOWN:
self.selected = min(max(0, len(self.queue) - 1), self.selected + 1)
elif key == "a":
self._input = {"prompt": "追加 plan 路径:", "buffer": ""}
elif key == "r":
self._retry_selected()
elif key == "p":
self._toggle_pause()
elif key == "d":
self._delete_selected()
elif key == ENTER:
task = self._selected_task()
if task is not None:
self.detail_task_id = task.id
elif key == ESC:
self.detail_task_id = None
elif key == "c":
self.controller.clear_log()
with self._log_lock:
self._log_lines = []
def _handle_decision_key(self, key: str) -> None:
"""决策窗口的按键处理。"""
with self._decision_lock:
if self._decision_buffer is None:
self._decision_buffer = ""
buffer = self._decision_buffer
if key == CTRL_C:
self._decision_buffer = None
self._quit.set()
self.controller.stop.set()
return
if key == ESC:
self._decision_buffer = None
self.controller.cancel_decision()
self._set_message("已放弃回答,按默认决策继续", "warn")
return
if key == ENTER:
answer = buffer.strip()
self._decision_buffer = None
if answer:
self.controller.submit_decision(answer)
else:
self.controller.cancel_decision()
return
if key == BACKSPACE:
self._decision_buffer = buffer[:-1]
return
if len(key) == 1 and key.isprintable():
self._decision_buffer = buffer + key
def _handle_input_key(self, key: str) -> None:
assert self._input is not None
if key == ESC:
self._input = None
return
if key == ENTER:
value = self._input["buffer"].strip()
self._input = None
if value:
self._append_plan(value)
return
if key == BACKSPACE:
self._input["buffer"] = self._input["buffer"][:-1]
return
if key == CTRL_C:
self._input = None
self._quit.set()
self.controller.stop.set()
return
if len(key) == 1 and key.isprintable():
self._input["buffer"] += key
def _append_plan(self, plan: str) -> None:
from .queue import build_task, save_queue_defs
if self.paths is None:
self._set_message("队列路径未设置,无法追加", "error")
return
task = build_task(
self.project_root,
plan,
existing_ids={t.id for t in self.queue.tasks},
)
try:
self.queue.add(task)
save_queue_defs(self.paths, self.queue)
self._set_message(f"已加入队列: {task.id} → {task.plan}", "ok")
except ValueError as exc:
self._set_message(str(exc), "error")
def _selected_task(self) -> Task | None:
tasks = self.queue.tasks
if not tasks:
return None
self.selected = min(self.selected, len(tasks) - 1)
return tasks[self.selected]
def _running_task(self) -> Task | None:
"""当前正在跑的任务(可能没有)。"""
for t in self.queue.tasks:
if t.status == RUNNING:
return t
return None
def _retry_selected(self) -> None:
task = self._selected_task()
if task is None:
return
task.status = PENDING
task.attempts = 0
task.last_error = ""
task.exit_code = None
task.finished_at = None
self._set_message(f"已重置 {task.id},将重新排队", "ok")
def _toggle_pause(self) -> None:
task = self._selected_task()
if task is None:
return
task.enabled = not task.enabled
self._set_message(f"{task.id} 已{'恢复' if task.enabled else '暂停'}", "ok")
def _delete_selected(self) -> None:
task = self._selected_task()
if task is None:
return
if task.status == RUNNING:
self._set_message("任务正在运行,不能删除", "error")
return
self.queue.remove(task.id)
self.selected = max(0, self.selected - 1)
self._set_message(f"已移除 {task.id}", "ok")
# ── 渲染:左边 ──────────────────────────────────────────────────
def _left_lines(self, width: int) -> list[str]:
tasks = self.queue.tasks
stats = self.queue.stats()
if not tasks:
body = ["", "队列为空", "", "按 a 追加 plan", ""]
else:
body = []
id_w = max(8, min(18, width - 22))
for idx, t in enumerate(tasks):
marker = "▶" if idx == self.selected else " "
name = truncate(t.id, id_w)
status = STATUS_LABEL.get(t.status, t.status)
line = f"{marker} {pad(name, id_w)} {pad(status, 6)} {t.attempts:>2}"
if idx == self.selected:
line = Style.BRIGHT_WHITE + line + Style.RESET
else:
line = f"{marker} {name}{' ' * max(0, id_w - dwidth(name))} " \
f"{STATUS_STYLE.get(t.status, '')}{pad(status, 6)}{Style.RESET} {t.attempts:>2}"
body.append(line)
body.append("")
body.append(
Style.DIM
+ f"待跑 {stats.get(PENDING, 0)} · 运行 {stats.get(RUNNING, 0)} · "
+ f"成功 {stats.get(SUCCESS, 0)} · 失败 {stats.get(FAILED, 0)}"
+ Style.RESET
)
return body
# ── 渲染:决策窗口 ──────────────────────────────────────────────
def _decision_lines(self, width: int) -> list[str]:
"""正在等人回答时的决策框(没有则空)。"""
pending = self.controller.pending_question()
if pending is None:
self._decision_buffer = None
return []
with self._decision_lock:
if self._decision_buffer is None:
self._decision_buffer = ""
buffer = self._decision_buffer
remaining = pending.get("remaining")
if remaining is None:
countdown = "不限时"
else:
secs = int(max(0, remaining))
countdown = f"剩余 {secs // 60}:{secs % 60:02d}"
box: list[str] = [
Style.BOLD + Style.BRIGHT_YELLOW + "◆ 待决策" + Style.RESET,
Style.DIM + f" 任务: {pending.get('task_id', '')}" + Style.RESET,
]
for ln in wrap(str(pending.get("question", "")), max(10, width - 4)):
box.append(" " + ln)
box.append("")
box.append(Style.BOLD + " 你的决策:" + Style.RESET)
box.append(" > " + Style.BRIGHT_WHITE + buffer + Style.RESET + "▏")
box.append("")
box.append(
Style.DIM
+ f" {countdown} Enter 确认 · Esc 用默认决策 · Ctrl-C 退出"
+ Style.RESET
)
box.append("")
return box
# ── 渲染:右边 ──────────────────────────────────────────────────
def _right_lines(self, width: int) -> list[str]:
if self._input is not None:
return [
"",
self._input["prompt"] + Style.BRIGHT_WHITE + self._input["buffer"] + Style.RESET + "▏",
"",
Style.DIM + "Enter 确认 · Esc 取消" + Style.RESET,
]
detail = self.queue.get(self.detail_task_id) if self.detail_task_id else None
lines: list[str] = self._decision_lines(width)
if detail is not None:
log_file = self.project_root / detail.log_path if detail.log_path else None
if log_file and log_file.exists():
raw = log_file.read_text(encoding="utf-8", errors="replace").splitlines()
else:
raw = [f"({detail.id} 还没有日志)"]
else:
with self._log_lock:
raw = list(self._log_lines)
raw = raw[-self.cfg.log_tail:]
if self.message:
style = {"error": Style.BRIGHT_RED, "warn": Style.BRIGHT_YELLOW, "ok": Style.BRIGHT_GREEN}.get(
self.message_level, ""
)
lines.append(style + self.message + Style.RESET)
lines.append("")
for ln in raw:
lines.extend(wrap(ln, width))
decisions = self.controller.decision_log.records[-6:]
if decisions:
lines.append("")
lines.append(Style.BOLD + Style.DIM + "最近决策" + Style.RESET)
# 问题占 40%,答案占剩下的
q_w = max(8, (width - 3) * 2 // 5)
a_w = max(8, width - q_w - 3)
for d in decisions:
q = truncate(str(d.get("question", "")), q_w)
a = truncate(str(d.get("answer", "")), a_w)
lines.append(f"{Style.DIM}{q}{Style.RESET} → {a}")
if not lines:
lines = [Style.DIM + "等待任务开始…" + Style.RESET]
return lines
# ── 渲染:整体 ──────────────────────────────────────────────────
def render(self) -> None:
term = self.term
cols, rows = term.size()
left_w = min(LEFT_WIDTH, max(30, cols // 3))
right_x = left_w + 1
right_w = cols - left_w - 1
body_h = max(3, rows - FOOTER_HEIGHT)
term.clear()
# 左:任务队列
title = f"任务队列 ({len(self.queue)})"
term.draw_box(
x=1,
y=1,
w=left_w,
h=body_h,
title=title,
lines=self._left_lines(left_w - 4),
border=Style.CYAN,
title_style=Style.BOLD + Style.CYAN,
)
# 右:agent 输出
# 标题用 **正在跑** 的任务,而不是选中行 —— 否则按 ↓ 切行后标题和内容对不上
running = self._running_task()
if self._input is not None:
right_title = "追加任务"
elif self.detail_task_id:
right_title = f"任务日志 · {self.detail_task_id}"
elif running is not None:
right_title = f"Coding Agent · {running.id}"
else:
right_title = "Coding Agent"
term.draw_box(
x=right_x,
y=1,
w=right_w,
h=body_h,
title=right_title,
lines=self._right_lines(right_w - 4),
border=Style.CYAN,
title_style=Style.BOLD + Style.CYAN,
)
# 底:快捷键
if self.controller.pending_question() is not None:
hint = truncate(DECISION_HELP, cols - 4)
else:
hint = truncate(KEYBOARD_HELP, cols - 4)
term.draw_box(
x=1,
y=body_h + 1,
w=cols - 1,
h=FOOTER_HEIGHT,
lines=[Style.DIM + hint + Style.RESET],
border=Style.GREY,
)
term.flush()
# ── 主循环 ──────────────────────────────────────────────────────
def run(self) -> None:
from .keys import KeyReader
reader = KeyReader(self.handle_key)
self.term.enter()
reader.start()
try:
while not self._quit.is_set():
self.render()
time.sleep(1.0 / max(1, self.cfg.refresh_hz))
finally:
reader.stop()
self.term.leave()
print(self.controller.snapshot())

View File

@@ -0,0 +1,233 @@
"""跨平台小工具:时间、时长、原子写、终端宽度。"""
from __future__ import annotations
import os
import shutil
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
def now() -> datetime:
return datetime.now(timezone.utc).astimezone()
def now_iso() -> str:
return now().isoformat(timespec="seconds")
def fmt_ts(dt: datetime | None) -> str:
if dt is None:
return "-"
return dt.strftime("%m-%d %H:%M:%S")
def fmt_duration(seconds: float | None) -> str:
if seconds is None:
return "-"
seconds = int(max(0, seconds))
h, rem = divmod(seconds, 3600)
m, s = divmod(rem, 60)
if h:
return f"{h}h{m:02d}m"
if m:
return f"{m}m{s:02d}s"
return f"{s}s"
def atomic_write(path: Path, text: str) -> None:
"""同目录临时文件 + rename,避免读到写了一半的内容。"""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
fh.write(text)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def append_jsonl(path: Path, record: dict) -> None:
import json
path.parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(record, ensure_ascii=False, sort_keys=False)
with path.open("a", encoding="utf-8", newline="\n") as fh:
fh.write(line + "\n")
fh.flush()
os.fsync(fh.fileno())
def terminal_size() -> tuple[int, int]:
size = shutil.get_terminal_size(fallback=(100, 30))
return size.columns, size.lines
def is_windows() -> bool:
return os.name == "nt"
def slugify(text: str, fallback: str = "task") -> str:
keep = []
for ch in text.lower():
if ch.isalnum() or ch in "-_":
keep.append(ch)
elif ch in " /\\":
keep.append("-")
slug = "".join(keep).strip("-")
while "--" in slug:
slug = slug.replace("--", "-")
return slug[:48] or fallback
def today_stamp() -> str:
return now().strftime("%Y%m%d")
def sleep_interruptible(seconds: float, stop: "StopFlag") -> None:
"""可被 stop 打断的 sleep。"""
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if stop.is_set():
return
time.sleep(min(0.25, max(0.0, deadline - time.monotonic())))
class StopFlag:
"""线程安全的停止标志。"""
def __init__(self) -> None:
import threading
self._event = threading.Event()
def set(self) -> None:
self._event.set()
def is_set(self) -> bool:
return self._event.is_set()
def wait(self, timeout: float | None = None) -> bool:
return self._event.wait(timeout)
def pid_alive(pid: int) -> bool:
"""进程还活着吗?
Windows 上不能用 `os.kill(pid, 0)` —— 那会真的把进程杀掉,
所以 Windows 走心跳判断(见 QueueLock)。
"""
if pid <= 0:
return False
if is_windows():
return True # Windows 上无法安全探测,交给心跳
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
except OSError:
return False
return True
class QueueLock:
"""队列级单实例锁。
同一个队列同时跑两个 runner 会把同一个 pending 任务跑两遍(白烧 agent),
所以每条队列目录放一个锁文件。
锁文件内容:{"pid": 12345, "started_at": "...", "heartbeat": 1793...}
判定为 stale 的条件:pid 已死(POSIX)或心跳超过 STALE_SEC(Windows / 兜底)。
"""
STALE_SEC = 120.0
def __init__(self, path: Path) -> None:
self.path = path
self._held = False
# ── 内部 ────────────────────────────────────────────────────────
def _read(self) -> dict:
import json
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def _write(self, data: dict) -> None:
import json
atomic_write(self.path, json.dumps(data, ensure_ascii=False) + "\n")
def _is_stale(self, data: dict) -> bool:
pid = int(data.get("pid") or 0)
if pid and not pid_alive(pid):
return True
if is_windows():
heartbeat = float(data.get("heartbeat") or 0)
if heartbeat and (time.time() - heartbeat) > self.STALE_SEC:
return True
return False
# ── 对外 ────────────────────────────────────────────────────────
def acquire(self) -> tuple[bool, str]:
"""拿锁。返回 (是否成功, 失败原因)。"""
self.path.parent.mkdir(parents=True, exist_ok=True)
if self.path.exists():
data = self._read()
if not self._is_stale(data):
pid = int(data.get("pid") or 0)
return False, f"队列已被 pid {pid} 占用"
# 残留锁,清掉重建
try:
self.path.unlink()
except OSError:
pass
self._write(
{
"pid": os.getpid(),
"started_at": now_iso(),
"heartbeat": time.time(),
}
)
self._held = True
return True, ""
def touch(self) -> None:
"""更新心跳(长跑时定期调)。"""
if not self._held:
return
data = self._read()
data["heartbeat"] = time.time()
try:
self._write(data)
except OSError:
pass
def release(self) -> None:
if not self._held:
return
self._held = False
try:
self.path.unlink()
except OSError:
pass
def __enter__(self) -> "QueueLock":
ok, err = self.acquire()
if not ok:
raise RuntimeError(err)
return self
def __exit__(self, *exc) -> None:
self.release()

View File

@@ -0,0 +1,566 @@
"""极简 YAML 子集解析 / 序列化 —— 零第三方依赖。
支持(覆盖本仓库用到的全部语法):
- 缩进映射、序列
- 序列项为映射(``- key: value`` 及其续行)
- 标量:plain / ``'single'`` / ``"double"``
- 流式序列 ``[a, b]`` 与流式映射 ``{a: 1}``
- 块标量 ``|`` ``|-`` ``>`` ``>-``
- 注释(引号外、行首或前置空白后)
- 类型推断:bool / null / int / float / str
- 文档分隔符 ``---``
不支持(遇到会明确报错,不静默出错):
- 锚点 ``&`` / 别名 ``*`` / 标签 ``!``
- 复杂键(``? key``)
- 多文档(只取第一个)
之所以自己写而不是用 PyYAML:让 overnight-runner **零依赖**,
在任何装了 Python 3.9+ 的机器上直接跑,不用 pip install。
"""
from __future__ import annotations
from typing import Any
__all__ = ["loads", "dumps", "YamlError"]
class YamlError(ValueError):
"""YAML 解析失败。消息里带行号,便于定位。"""
# 序列项标记(用不可能出现在正文里的字符,避免与缩进层级混淆)
_SEQ = "\x00seq"
# ── 行处理 ──────────────────────────────────────────────────────────
class _Line:
__slots__ = ("indent", "text", "lineno", "raw_idx")
def __init__(self, indent: int, text: str, lineno: int, raw_idx: int) -> None:
self.indent = indent
self.text = text
self.lineno = lineno
self.raw_idx = raw_idx
def __repr__(self) -> str: # pragma: no cover - 调试用
return f"_Line({self.indent}, {self.text!r}, line={self.lineno})"
def _strip_comment(text: str) -> str:
"""去掉引号外的注释。"""
out = []
quote = ""
i = 0
while i < len(text):
ch = text[i]
if quote:
out.append(ch)
if ch == "\\" and quote == '"' and i + 1 < len(text):
out.append(text[i + 1])
i += 2
continue
if ch == quote:
quote = ""
i += 1
continue
if ch in ("'", '"'):
quote = ch
out.append(ch)
i += 1
continue
if ch == "#" and (not out or out[-1] in " \t"):
break
out.append(ch)
i += 1
return "".join(out).rstrip()
def _split_key(text: str) -> tuple[str, str, str]:
"""拆 ``key: value``。
返回 (key, sep, value)。sep 为空表示这一行不是映射项。
引号内的冒号不算分隔符。
"""
quote = ""
i = 0
while i < len(text):
ch = text[i]
if quote:
if ch == "\\" and quote == '"' and i + 1 < len(text):
i += 2
continue
if ch == quote:
quote = ""
i += 1
continue
if ch in ("'", '"'):
quote = ch
i += 1
continue
if ch in "[{":
break
if ch == ":":
rest = text[i + 1:]
if rest == "" or rest[0] in " \t":
return text[:i].strip(), ":", rest.strip()
i += 1
return text.strip(), "", ""
def _unterminated(text: str) -> bool:
"""引号没闭合(只关心行尾的引号状态)。"""
t = text.rstrip()
if len(t) >= 1 and t[-1] in ("'", '"'):
# 可能闭合了,也可能是转义过的
return t.count(t[-1]) % 2 == 1
if t.startswith("'") or t.startswith('"'):
return True
return False
def _fold(parts: list[str]) -> str:
"""多行引号标量的折行规则:单换行折成空格,空行保留为换行。"""
result = ""
prev_blank = False
for i, ln in enumerate(parts):
if i == 0:
result = ln
continue
if ln.strip() == "":
result += "\n"
prev_blank = True
continue
if not prev_blank:
result += " "
result += ln
prev_blank = False
return result
def _preprocess(raw_lines: list[str]) -> list[_Line]:
"""把原始行变成逻辑行。
做三件事:
1. 跳过空行、整行注释、``---``
2. 把 ``- key: value`` 拆成序列标记 + 内容行
3. 把跨行的引号标量合并成一行
"""
out: list[_Line] = []
idx = 0
total = len(raw_lines)
while idx < total:
raw = raw_lines[idx]
if "\t" in raw[: len(raw) - len(raw.lstrip())]:
raise YamlError(f"第 {idx + 1} 行:YAML 缩进不能用 Tab")
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
idx += 1
continue
if stripped == "---":
idx += 1
continue
if stripped in ("...",):
break
indent = len(raw) - len(raw.lstrip(" "))
text = _strip_comment(raw[indent:])
if text == "-" or text.startswith("- "):
rest = text[1:].strip()
key, sep, _ = _split_key(rest)
# 统一拆成:序列标记 + 内容行
out.append(_Line(indent, _SEQ, idx + 1, idx))
if rest:
content_indent = indent + 2 if (sep and key) else indent
out.append(_Line(content_indent, rest, idx + 1, idx))
idx += 1
continue
# 跨行的引号标量(PyYAML 会把带换行的字符串写成这种形式)
key, sep, val = _split_key(text)
if sep and val and _unterminated(val):
prefix = text[: len(text) - len(val)]
parts = [val]
j = idx + 1
while j < total and _unterminated(_fold(parts)):
parts.append(raw_lines[j].strip())
j += 1
out.append(_Line(indent, prefix + _fold(parts), idx + 1, idx))
idx = j
continue
out.append(_Line(indent, text, idx + 1, idx))
idx += 1
return out
# ── 标量 ────────────────────────────────────────────────────────────
_TRUE = {"true", "True", "TRUE"}
_FALSE = {"false", "False", "FALSE"}
_NULL = {"", "~", "null", "Null", "NULL"}
def _parse_scalar(text: str, lineno: int) -> Any:
t = text.strip()
if len(t) >= 2 and t[0] == '"' and t[-1] == '"':
return _unescape_double(t[1:-1], lineno)
if len(t) >= 2 and t[0] == "'" and t[-1] == "'":
return t[1:-1].replace("''", "'")
if t.startswith("[") and t.endswith("]"):
return _parse_flow_seq(t[1:-1], lineno)
if t.startswith("{") and t.endswith("}"):
return _parse_flow_map(t[1:-1], lineno)
if t in _TRUE:
return True
if t in _FALSE:
return False
if t in _NULL:
return None
try:
if t.lstrip("+-").isdigit():
return int(t)
except ValueError:
pass
try:
if any(c in t for c in ".eE") and t.lstrip("+-").replace(".", "", 1).isdigit():
return float(t)
except ValueError:
pass
return t
def _unescape_double(s: str, lineno: int) -> str:
out = []
i = 0
while i < len(s):
ch = s[i]
if ch == "\\" and i + 1 < len(s):
nxt = s[i + 1]
mapping = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\", "/": "/", "0": "\0"}
if nxt in mapping:
out.append(mapping[nxt])
i += 2
continue
if nxt == "u" and i + 5 < len(s) + 1:
try:
out.append(chr(int(s[i + 2: i + 6], 16)))
i += 6
continue
except ValueError:
raise YamlError(f"第 {lineno} 行:非法的 \\u 转义")
raise YamlError(f"第 {lineno} 行:未知的转义 \\{nxt}")
out.append(ch)
i += 1
return "".join(out)
def _split_flow(body: str, lineno: int) -> list[str]:
"""按顶层逗号切分流式集合的内容。"""
parts = []
buf = []
depth = 0
quote = ""
for ch in body:
if quote:
buf.append(ch)
if ch == quote:
quote = ""
continue
if ch in ("'", '"'):
quote = ch
buf.append(ch)
continue
if ch in "[{":
depth += 1
elif ch in "]}":
depth -= 1
if ch == "," and depth == 0:
parts.append("".join(buf))
buf = []
continue
buf.append(ch)
tail = "".join(buf)
if tail.strip() or parts:
parts.append(tail)
return [p.strip() for p in parts]
def _parse_flow_seq(body: str, lineno: int) -> list:
body = body.strip()
if not body:
return []
return [_parse_scalar(p, lineno) for p in _split_flow(body, lineno)]
def _parse_flow_map(body: str, lineno: int) -> dict:
body = body.strip()
if not body:
return {}
out = {}
for part in _split_flow(body, lineno):
key, sep, value = _split_key(part)
if not sep:
raise YamlError(f"第 {lineno} 行:流式映射项格式错误: {part!r}")
out[_parse_scalar(key, lineno)] = _parse_scalar(value, lineno)
return out
# ── 块标量 ──────────────────────────────────────────────────────────
def _read_block_scalar(
raw_lines: list[str], start_raw: int, key_indent: int, style: str, lineno: int
) -> tuple[str, int]:
"""读块标量(| 或 >)。返回 (文本, 消耗到的 raw 索引)。"""
folded = style[0] == ">"
chomp = "clip"
if style.endswith("-"):
chomp = "strip"
elif style.endswith("+"):
chomp = "keep"
body: list[str] = []
i = start_raw
block_indent: int | None = None
while i < len(raw_lines):
raw = raw_lines[i]
if raw.strip() == "":
body.append("")
i += 1
continue
indent = len(raw) - len(raw.lstrip(" "))
if indent <= key_indent:
break
if block_indent is None:
block_indent = indent
body.append(raw[block_indent:] if len(raw) >= block_indent else "")
i += 1
# 去掉尾部空行(按 chomp 策略再决定加不加回来)
while body and body[-1] == "":
body.pop()
i -= 1
if folded:
text = ""
for idx, ln in enumerate(body):
if idx == 0:
text = ln
elif ln == "" or body[idx - 1] == "":
text += "\n" + ln
else:
text += " " + ln
else:
text = "\n".join(body)
if chomp == "strip":
return text, i
if chomp == "keep":
return text + "\n", i
return (text + "\n") if text else "", i
# ── 主解析 ──────────────────────────────────────────────────────────
def loads(text: str) -> Any:
"""解析 YAML 文本。"""
raw_lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
lines = _preprocess(raw_lines)
if not lines:
return None
value, idx = _parse_node(lines, 0, lines[0].indent, raw_lines)
if idx < len(lines):
raise YamlError(f"第 {lines[idx].lineno} 行:缩进异常")
return value
def _parse_node(lines: list[_Line], i: int, indent: int, raw_lines: list[str]) -> tuple[Any, int]:
if lines[i].text == _SEQ:
return _parse_sequence(lines, i, indent, raw_lines)
return _parse_mapping(lines, i, indent, raw_lines)
def _parse_mapping(
lines: list[_Line], i: int, indent: int, raw_lines: list[str]
) -> tuple[dict, int]:
result: dict = {}
while i < len(lines) and lines[i].indent == indent:
line = lines[i]
if line.text == _SEQ:
break
key, sep, rest = _split_key(line.text)
if not sep:
raise YamlError(f"第 {line.lineno} 行:期望 `key: value`,得到 {line.text!r}")
if key.startswith("&") or key.startswith("*") or key.startswith("!"):
raise YamlError(f"第 {line.lineno} 行:不支持锚点/别名/标签")
key_value = _parse_scalar(key, line.lineno)
if rest and rest[0] in "|>":
value, consumed = _read_block_scalar(
raw_lines, line.raw_idx + 1, indent, rest, line.lineno
)
result[key_value] = value
# 跳到块标量之后的第一条逻辑行
i += 1
while i < len(lines) and lines[i].raw_idx < consumed:
i += 1
continue
if rest == "":
nxt = lines[i + 1] if i + 1 < len(lines) else None
# 块序列可以与它的 key 同缩进(PyYAML 的写法),也可以更深
if nxt is not None and (
nxt.indent > indent
or (nxt.indent == indent and nxt.text == _SEQ)
):
value, i = _parse_node(lines, i + 1, nxt.indent, raw_lines)
else:
value = None
i += 1
else:
value = _parse_scalar(rest, line.lineno)
i += 1
result[key_value] = value
return result, i
def _parse_sequence(
lines: list[_Line], i: int, indent: int, raw_lines: list[str]
) -> tuple[list, int]:
result: list = []
while i < len(lines) and lines[i].indent == indent and lines[i].text == _SEQ:
marker = lines[i]
i += 1
if i >= len(lines):
result.append(None)
break
content = lines[i]
if content.indent == indent + 2:
# 序列项是映射
value, i = _parse_mapping(lines, i, content.indent, raw_lines)
result.append(value)
continue
if content.indent != indent:
# 空项 / 嵌套块
value, i = _parse_node(lines, i, content.indent, raw_lines)
result.append(value)
continue
rest = content.text
if rest and rest[0] in "|>":
value, consumed = _read_block_scalar(
raw_lines, marker.raw_idx + 1, indent, rest, marker.lineno
)
result.append(value)
i += 1
while i < len(lines) and lines[i].raw_idx < consumed:
i += 1
continue
result.append(_parse_scalar(rest, marker.lineno))
i += 1
return result, i
# ── 序列化 ──────────────────────────────────────────────────────────
_PLAIN_SAFE = set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./+@"
)
def _needs_quote(s: str) -> bool:
if s == "":
return True
if s.strip() != s:
return True
if s[0] in "-?:,[]{}#&*!|>'\"%@`":
return True
if ": " in s or " #" in s or s.endswith(":"):
return True
if "\n" in s or "\t" in s:
return True
if any(c not in _PLAIN_SAFE for c in s):
# 含中文、空格等 —— 加引号更安全
return True
if s in _TRUE or s in _FALSE or s in _NULL:
return True
try:
float(s)
return True
except ValueError:
return False
def _dump_scalar(value: Any) -> str:
if value is None:
return "null"
if value is True:
return "true"
if value is False:
return "false"
if isinstance(value, (int, float)):
return str(value)
s = str(value)
if "\n" in s:
return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
if _needs_quote(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
return s
def dumps(data: Any, indent: int = 0) -> str:
"""把数据序列化成 YAML 子集文本。"""
lines: list[str] = []
def emit(node: Any, level: int) -> None:
pad = " " * (level * 2)
if isinstance(node, dict):
for key, value in node.items():
if isinstance(value, dict) and value:
lines.append(f"{pad}{key}:")
emit(value, level + 1)
elif isinstance(value, list) and value:
lines.append(f"{pad}{key}:")
emit(value, level + 1)
elif isinstance(value, dict):
lines.append(f"{pad}{key}: {{}}")
elif isinstance(value, list):
lines.append(f"{pad}{key}: []")
elif isinstance(value, str) and "\n" in value:
lines.append(f"{pad}{key}: |")
for ln in value.rstrip("\n").split("\n"):
lines.append(f"{pad} {ln}")
else:
lines.append(f"{pad}{key}: {_dump_scalar(value)}")
elif isinstance(node, list):
for item in node:
if isinstance(item, dict) and item:
first = True
for key, value in item.items():
prefix = f"{pad}- " if first else f"{pad} "
first = False
if isinstance(value, dict) and value:
lines.append(f"{prefix}{key}:")
emit(value, level + 2)
elif isinstance(value, list) and value:
lines.append(f"{prefix}{key}:")
emit(value, level + 2)
elif isinstance(value, str) and "\n" in value:
lines.append(f"{prefix}{key}: |")
for ln in value.rstrip("\n").split("\n"):
lines.append(f"{pad} {ln}")
else:
lines.append(f"{prefix}{key}: {_dump_scalar(value)}")
elif isinstance(item, (list, dict)):
lines.append(f"{pad}-")
emit(item, level + 1)
else:
lines.append(f"{pad}- {_dump_scalar(item)}")
else:
lines.append(f"{pad}{_dump_scalar(node)}")
emit(data, indent)
return "\n".join(lines) + "\n"