hadley 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hadley/__init__.py +3 -0
- hadley/__main__.py +4 -0
- hadley/cli.py +572 -0
- hadley/config.py +498 -0
- hadley/engine.py +447 -0
- hadley/mcp_server.py +175 -0
- hadley/paths.py +70 -0
- hadley/project_files.py +109 -0
- hadley/prompts.py +142 -0
- hadley/providers/__init__.py +25 -0
- hadley/providers/base.py +65 -0
- hadley/providers/claude_code.py +235 -0
- hadley/service.py +156 -0
- hadley/store.py +262 -0
- hadley/tui.py +220 -0
- hadley-0.5.0.dist-info/METADATA +457 -0
- hadley-0.5.0.dist-info/RECORD +20 -0
- hadley-0.5.0.dist-info/WHEEL +4 -0
- hadley-0.5.0.dist-info/entry_points.txt +2 -0
- hadley-0.5.0.dist-info/licenses/LICENSE +21 -0
hadley/__init__.py
ADDED
hadley/__main__.py
ADDED
hadley/cli.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
"""Command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import signal
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
|
|
14
|
+
from . import __version__, paths, project_files, prompts
|
|
15
|
+
from .config import (
|
|
16
|
+
GOAL_PLACEHOLDER,
|
|
17
|
+
HADLEY_DIR,
|
|
18
|
+
TEMPLATES,
|
|
19
|
+
MissingEnv,
|
|
20
|
+
find_project_file,
|
|
21
|
+
load_project,
|
|
22
|
+
mcp_launch_config,
|
|
23
|
+
parse_project,
|
|
24
|
+
)
|
|
25
|
+
from .engine import Engine, EngineLocked, acquire_daemon_lock, daemon_running, run_claimed, try_lock
|
|
26
|
+
from .providers import get_provider
|
|
27
|
+
from .store import JOB_FINAL, Job, Run, Store
|
|
28
|
+
|
|
29
|
+
app = typer.Typer(
|
|
30
|
+
help="Hadley: run a tree of AI agents (Mother + specialists) from one portable YAML file.",
|
|
31
|
+
no_args_is_help=True,
|
|
32
|
+
add_completion=False,
|
|
33
|
+
)
|
|
34
|
+
service_app = typer.Typer(help="Run the engine as a background service that survives reboots.")
|
|
35
|
+
app.add_typer(service_app, name="service")
|
|
36
|
+
|
|
37
|
+
KIND_COLORS = {
|
|
38
|
+
"text": None,
|
|
39
|
+
"tool": typer.colors.BLUE,
|
|
40
|
+
"delegate": typer.colors.MAGENTA,
|
|
41
|
+
"start": typer.colors.CYAN,
|
|
42
|
+
"done": typer.colors.GREEN,
|
|
43
|
+
"error": typer.colors.RED,
|
|
44
|
+
"limit": typer.colors.YELLOW,
|
|
45
|
+
"plan": typer.colors.GREEN,
|
|
46
|
+
"info": typer.colors.YELLOW,
|
|
47
|
+
}
|
|
48
|
+
STATUS_ICONS = {
|
|
49
|
+
"queued": "·",
|
|
50
|
+
"running": "▶",
|
|
51
|
+
"waiting": "…",
|
|
52
|
+
"paused": "‖",
|
|
53
|
+
"done": "✓",
|
|
54
|
+
"failed": "✗",
|
|
55
|
+
"cancelled": "-",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _err(msg: str) -> None:
|
|
60
|
+
typer.secho(f"error: {msg}", fg=typer.colors.RED, err=True)
|
|
61
|
+
raise typer.Exit(1)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _store() -> Store:
|
|
65
|
+
return Store()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _here() -> Path | None:
|
|
69
|
+
"""The project file of the current folder or a parent (like git), if there is one."""
|
|
70
|
+
try:
|
|
71
|
+
return find_project_file(None)
|
|
72
|
+
except FileNotFoundError:
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _runs_in_scope(store: Store, all_projects: bool = False, limit: int = 20) -> tuple[list[Run], Path | None]:
|
|
77
|
+
"""Runs of the project in the current folder, or of all projects when outside one."""
|
|
78
|
+
here = None if all_projects else _here()
|
|
79
|
+
runs = store.list_runs(limit=100_000 if here else limit)
|
|
80
|
+
if here:
|
|
81
|
+
runs = [r for r in runs if Path(r.project_path) == here][:limit]
|
|
82
|
+
return runs, here
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _resolve_run(store: Store, run_id: int | None) -> Run:
|
|
86
|
+
if run_id is None:
|
|
87
|
+
runs, here = _runs_in_scope(store, limit=1)
|
|
88
|
+
if not runs:
|
|
89
|
+
_err(f"no runs yet for {here.parent}" if here else "no runs yet (start one with `hadley run`)")
|
|
90
|
+
return runs[0]
|
|
91
|
+
run = store.get_run(run_id)
|
|
92
|
+
if not run:
|
|
93
|
+
_err(f"run {run_id} not found")
|
|
94
|
+
return run
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _follow(store: Store, r: Run, lines: int = 200, follow: bool = True) -> None:
|
|
98
|
+
agents = _job_names(store, r)
|
|
99
|
+
last = 0
|
|
100
|
+
for e in store.tail_events(r.id, lines):
|
|
101
|
+
_fmt_event(e.kind, e.text, agents.get(e.job_id))
|
|
102
|
+
last = e.id
|
|
103
|
+
if not follow:
|
|
104
|
+
return
|
|
105
|
+
try:
|
|
106
|
+
while True:
|
|
107
|
+
evs = store.events(r.id, after_id=last)
|
|
108
|
+
if evs:
|
|
109
|
+
agents = _job_names(store, r)
|
|
110
|
+
for e in evs:
|
|
111
|
+
_fmt_event(e.kind, e.text, agents.get(e.job_id))
|
|
112
|
+
last = e.id
|
|
113
|
+
run_now = store.get_run(r.id)
|
|
114
|
+
if run_now.status in ("done", "failed", "cancelled") and not evs:
|
|
115
|
+
_print_summary(run_now)
|
|
116
|
+
return
|
|
117
|
+
time.sleep(1)
|
|
118
|
+
except KeyboardInterrupt:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _fmt_event(kind: str, text: str, agent: str | None) -> None:
|
|
123
|
+
who = f"{agent:>10} " if agent else " " * 11
|
|
124
|
+
color = KIND_COLORS.get(kind)
|
|
125
|
+
first, *rest = text.splitlines() or [""]
|
|
126
|
+
typer.secho(f"{who}{kind:<8} {first}", fg=color)
|
|
127
|
+
for line in rest:
|
|
128
|
+
typer.secho(f"{' ' * 20}{line}", fg=color)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
_ALIAS_CACHE: dict[int, dict[str, str]] = {}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def alias_of(run: Run, agent: str) -> str:
|
|
135
|
+
"""Display name of an agent in a run (from the run's snapshot of the project file)."""
|
|
136
|
+
if run.id not in _ALIAS_CACHE:
|
|
137
|
+
p = parse_project(run.config)
|
|
138
|
+
_ALIAS_CACHE[run.id] = {n: p.alias(n) for n in p.agents}
|
|
139
|
+
return _ALIAS_CACHE[run.id].get(agent, agent)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _job_names(store: Store, run: Run) -> dict[int, str]:
|
|
143
|
+
return {j.id: alias_of(run, j.agent) for j in store.jobs_for_run(run.id)}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _echo(run: Run, job: Job | None, kind: str, text: str) -> None:
|
|
147
|
+
_fmt_event(kind, text, alias_of(run, job.agent) if job else None)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _run_engine_foreground(run_id: int, lock=None) -> None:
|
|
151
|
+
lock = lock or try_lock(paths.run_lock_path(run_id))
|
|
152
|
+
if lock is None:
|
|
153
|
+
typer.echo(f"Run {run_id} is already being worked on by another Hadley process (e.g. the service).")
|
|
154
|
+
typer.echo("Following its log; Ctrl-C stops following, not the run.\n")
|
|
155
|
+
_follow(_store(), _store().get_run(run_id), lines=50)
|
|
156
|
+
return
|
|
157
|
+
engine = Engine(only_run=run_id, stop_when_idle=True, echo=_echo, run_lock=lock)
|
|
158
|
+
loop = asyncio.new_event_loop()
|
|
159
|
+
|
|
160
|
+
def _sigint(*_):
|
|
161
|
+
typer.secho("\nstopping… (state is saved; continue with `hadley resume`)", fg=typer.colors.YELLOW)
|
|
162
|
+
engine.stop()
|
|
163
|
+
|
|
164
|
+
loop.add_signal_handler(signal.SIGINT, _sigint)
|
|
165
|
+
loop.add_signal_handler(signal.SIGTERM, _sigint)
|
|
166
|
+
try:
|
|
167
|
+
loop.run_until_complete(engine.serve())
|
|
168
|
+
finally:
|
|
169
|
+
loop.close()
|
|
170
|
+
lock.close()
|
|
171
|
+
run = Store().get_run(run_id)
|
|
172
|
+
_print_summary(run)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _print_summary(run: Run) -> None:
|
|
176
|
+
typer.echo()
|
|
177
|
+
color = {"done": typer.colors.GREEN, "failed": typer.colors.RED}.get(run.status, typer.colors.YELLOW)
|
|
178
|
+
typer.secho(f"run {run.id} ({run.name}): {run.status}", fg=color, bold=True)
|
|
179
|
+
if run.status == "done" and run.result:
|
|
180
|
+
typer.echo(run.result)
|
|
181
|
+
elif run.status == "failed" and run.error:
|
|
182
|
+
typer.echo(run.error)
|
|
183
|
+
elif run.plan_state == "pending":
|
|
184
|
+
typer.echo("Mother's plan is ready for your review:")
|
|
185
|
+
typer.echo(f" hadley plan {run.id} read it (edit .hadley/plan.md if you like)")
|
|
186
|
+
typer.echo(f" hadley resume {run.id} approve it and continue")
|
|
187
|
+
elif run.status in ("running", "queued", "paused"):
|
|
188
|
+
typer.echo(f"continue with: hadley resume {run.id}")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ---- project commands ------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@app.command()
|
|
195
|
+
def init(
|
|
196
|
+
directory: Path = typer.Argument(Path("."), help="Project folder (default: the current folder)."),
|
|
197
|
+
name: str | None = typer.Option(None, help="Project name (default: folder name)."),
|
|
198
|
+
template: str = typer.Option(
|
|
199
|
+
"minimal", "--template", "-t", help=f"Starter tree: {', '.join(TEMPLATES)}. minimal = Mother only."
|
|
200
|
+
),
|
|
201
|
+
force: bool = typer.Option(False, "--force", help="Replace an existing .hadley/ folder without asking."),
|
|
202
|
+
):
|
|
203
|
+
"""Create .hadley/hadley.yaml in a project folder (by default with Mother only)."""
|
|
204
|
+
if template not in TEMPLATES:
|
|
205
|
+
_err(f"unknown template '{template}' (choose from: {', '.join(TEMPLATES)})")
|
|
206
|
+
directory = directory.expanduser().resolve()
|
|
207
|
+
hd = directory / HADLEY_DIR
|
|
208
|
+
existing = project_files.describe_existing(directory)
|
|
209
|
+
if hd.exists():
|
|
210
|
+
store = _store()
|
|
211
|
+
active = [r for r in store.list_runs(active_only=True, limit=1000) if Path(r.project_path).parent == hd]
|
|
212
|
+
if active:
|
|
213
|
+
_err(f"run {active[0].id} of this project is still active. Cancel it first: hadley cancel {active[0].id}")
|
|
214
|
+
if not force:
|
|
215
|
+
typer.echo(f"{hd} already exists:")
|
|
216
|
+
for item in existing or ["(empty)"]:
|
|
217
|
+
typer.echo(f" - {item}")
|
|
218
|
+
if not typer.confirm("Drop it and start a new project? Everything listed above is deleted.", default=False):
|
|
219
|
+
typer.echo("Nothing changed.")
|
|
220
|
+
raise typer.Exit(0)
|
|
221
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
222
|
+
project_name = name or directory.name
|
|
223
|
+
f = project_files.init_project(directory, TEMPLATES[template].format(name=project_name), wipe=True)
|
|
224
|
+
typer.echo(f"created {f}")
|
|
225
|
+
typer.echo("Next: write your task under `goal:`, then run `hadley validate` and `hadley run`.")
|
|
226
|
+
typer.echo(f"Tip: add `{HADLEY_DIR}/` to your project's .gitignore to keep Hadley private,")
|
|
227
|
+
typer.echo(" or commit it to share the team and the plan.")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _mcp_env_problems(p) -> list[str]:
|
|
231
|
+
environ = paths.mcp_environ()
|
|
232
|
+
problems = []
|
|
233
|
+
for name in sorted({m for a in p.agents.values() for m in a.mcp}):
|
|
234
|
+
try:
|
|
235
|
+
mcp_launch_config(name, p.mcp_servers[name], environ)
|
|
236
|
+
except MissingEnv as e:
|
|
237
|
+
problems.append(str(e))
|
|
238
|
+
return problems
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@app.command()
|
|
242
|
+
def validate(path: Path | None = typer.Argument(None, help="Project folder (default: this folder or a parent).")):
|
|
243
|
+
"""Check the project file and show its agent tree."""
|
|
244
|
+
try:
|
|
245
|
+
lp = load_project(path)
|
|
246
|
+
except Exception as e:
|
|
247
|
+
_err(str(e))
|
|
248
|
+
p = lp.project
|
|
249
|
+
typer.secho(f"✓ {lp.path} is valid", fg=typer.colors.GREEN)
|
|
250
|
+
typer.echo(f"project: {p.name} folder: {lp.project_dir} workdir: {lp.workdir}")
|
|
251
|
+
if p.plan_approval:
|
|
252
|
+
typer.echo("plan approval: on (the run pauses after Mother writes her plan)")
|
|
253
|
+
typer.echo()
|
|
254
|
+
for line in p.tree_lines():
|
|
255
|
+
typer.echo(" " + line)
|
|
256
|
+
for w in p.warnings():
|
|
257
|
+
typer.secho(f"warning: {w}", fg=typer.colors.YELLOW)
|
|
258
|
+
for problem in _mcp_env_problems(p):
|
|
259
|
+
typer.secho(f"✗ {problem} (set it, or add it to {paths.env_file()})", fg=typer.colors.RED)
|
|
260
|
+
providers = {a.provider for a in p.agents.values()}
|
|
261
|
+
for name in sorted(providers):
|
|
262
|
+
try:
|
|
263
|
+
ok, msg = get_provider(name).check()
|
|
264
|
+
except ValueError as e:
|
|
265
|
+
ok, msg = False, str(e)
|
|
266
|
+
typer.secho(("✓ " if ok else "✗ ") + msg, fg=typer.colors.GREEN if ok else typer.colors.RED)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@app.command()
|
|
270
|
+
def run(
|
|
271
|
+
path: Path | None = typer.Argument(None, help="Project folder (default: this folder or a parent)."),
|
|
272
|
+
goal: str | None = typer.Option(None, "--goal", "-g", help="The task; overrides `goal:` in the file."),
|
|
273
|
+
detach: bool = typer.Option(False, "--detach", "-d", help="Queue the run for the background service."),
|
|
274
|
+
from_plan: bool = typer.Option(False, "--from-plan", help="Continue from the plan in .hadley/plan.md."),
|
|
275
|
+
):
|
|
276
|
+
"""Start a run: hand the task to Mother."""
|
|
277
|
+
try:
|
|
278
|
+
lp = load_project(path)
|
|
279
|
+
except Exception as e:
|
|
280
|
+
_err(str(e))
|
|
281
|
+
p = lp.project
|
|
282
|
+
text = (goal or p.goal or "").strip()
|
|
283
|
+
if not text or text == GOAL_PLACEHOLDER:
|
|
284
|
+
_err("no goal: set `goal:` in the project file or pass --goal")
|
|
285
|
+
for name in {a.provider for a in p.agents.values()}:
|
|
286
|
+
ok, msg = get_provider(name).check()
|
|
287
|
+
if not ok:
|
|
288
|
+
_err(msg)
|
|
289
|
+
problems = _mcp_env_problems(p)
|
|
290
|
+
if problems:
|
|
291
|
+
_err("; ".join(problems) + f". Set them, or add them to {paths.env_file()}.")
|
|
292
|
+
store = _store()
|
|
293
|
+
busy = [x for x in store.list_runs(active_only=True, limit=1000) if Path(x.workdir) == lp.workdir]
|
|
294
|
+
if busy:
|
|
295
|
+
b = busy[0]
|
|
296
|
+
_err(
|
|
297
|
+
f"run {b.id} ({b.status}) is still active in {lp.workdir}. Two runs in one workdir would "
|
|
298
|
+
f"overwrite each other's files. Wait for it, or stop it with `hadley cancel {b.id}`."
|
|
299
|
+
)
|
|
300
|
+
plan_file = project_files.plan_path(lp.hadley_dir)
|
|
301
|
+
if from_plan and not plan_file.is_file():
|
|
302
|
+
_err(f"no plan to continue from ({plan_file} does not exist)")
|
|
303
|
+
if not from_plan and plan_file.is_file():
|
|
304
|
+
# the previous run's plan is archived in .hadley/runs/; keep one loose copy just in case
|
|
305
|
+
plan_file.replace(plan_file.with_name("plan.previous.md"))
|
|
306
|
+
typer.echo("starting with a fresh plan (the previous one is in .hadley/plan.previous.md;")
|
|
307
|
+
typer.echo("use --from-plan to continue from a plan instead)")
|
|
308
|
+
lp.workdir.mkdir(parents=True, exist_ok=True)
|
|
309
|
+
r, _ = store.create_run(
|
|
310
|
+
name=p.name,
|
|
311
|
+
project_path=str(lp.path),
|
|
312
|
+
config=p.model_dump(mode="json"),
|
|
313
|
+
goal=text,
|
|
314
|
+
workdir=str(lp.workdir),
|
|
315
|
+
root_agent=p.root,
|
|
316
|
+
root_task=prompts.from_plan(text) if from_plan else None,
|
|
317
|
+
)
|
|
318
|
+
# claim the run at once, so a running service does not pick it up first
|
|
319
|
+
lock = None if detach else try_lock(paths.run_lock_path(r.id))
|
|
320
|
+
typer.secho(f"run {r.id} created for project '{p.name}' (workdir {lp.workdir})", fg=typer.colors.CYAN)
|
|
321
|
+
if detach:
|
|
322
|
+
if not daemon_running():
|
|
323
|
+
typer.secho(
|
|
324
|
+
"warning: the service is not running. Start it with `hadley service install` or `hadley daemon`.",
|
|
325
|
+
fg=typer.colors.YELLOW,
|
|
326
|
+
)
|
|
327
|
+
typer.echo(f"queued. Follow with: hadley logs -f {r.id}")
|
|
328
|
+
return
|
|
329
|
+
_run_engine_foreground(r.id, lock)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# ---- run control -----------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@app.command()
|
|
336
|
+
def status(
|
|
337
|
+
run_id: int | None = typer.Argument(None, help="Run id (default: list runs)."),
|
|
338
|
+
all_projects: bool = typer.Option(False, "--all", "-a", help="List runs of all projects."),
|
|
339
|
+
):
|
|
340
|
+
"""List runs (of the project in this folder, or all), or show one run's job tree."""
|
|
341
|
+
store = _store()
|
|
342
|
+
if run_id is None:
|
|
343
|
+
runs, here = _runs_in_scope(store, all_projects)
|
|
344
|
+
if here:
|
|
345
|
+
typer.secho(f"runs of {here.parent} (use --all for every project)\n", dim=True)
|
|
346
|
+
if not runs:
|
|
347
|
+
typer.echo("no runs yet")
|
|
348
|
+
for r in runs:
|
|
349
|
+
extra = ""
|
|
350
|
+
if r.status == "paused" and r.paused_until:
|
|
351
|
+
extra = f" until {time.strftime('%H:%M', time.localtime(r.paused_until))} ({r.pause_reason})"
|
|
352
|
+
if r.status in ("queued", "running", "paused") and not run_claimed(r.id):
|
|
353
|
+
extra += f" ⚠ nothing is working on it: hadley resume {r.id}"
|
|
354
|
+
started = time.strftime("%Y-%m-%d %H:%M", time.localtime(r.created_at))
|
|
355
|
+
typer.echo(f"{STATUS_ICONS.get(r.status, '?')} {r.id:>4} {r.status:<9}{extra} {started} {r.name}")
|
|
356
|
+
typer.echo(f"\nservice: {'running' if daemon_running() else 'not running'}")
|
|
357
|
+
return
|
|
358
|
+
r = _resolve_run(store, run_id)
|
|
359
|
+
typer.secho(f"run {r.id} · {r.name} · {r.status}", bold=True)
|
|
360
|
+
typer.echo(f"goal: {r.goal.strip().splitlines()[0][:100]}")
|
|
361
|
+
typer.echo(f"workdir: {r.workdir}\n")
|
|
362
|
+
for line in job_tree_lines(store.jobs_for_run(r.id), parse_project(r.config).label):
|
|
363
|
+
typer.echo(line)
|
|
364
|
+
cost = sum(j.cost_usd for j in store.jobs_for_run(r.id))
|
|
365
|
+
if cost:
|
|
366
|
+
typer.echo(f"\nAPI-equivalent cost: ${cost:.2f}")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def job_tree_lines(jobs: list[Job], label=lambda name: name) -> list[str]:
|
|
370
|
+
by_parent: dict[int | None, list[Job]] = {}
|
|
371
|
+
for j in jobs:
|
|
372
|
+
by_parent.setdefault(j.parent_id, []).append(j)
|
|
373
|
+
out: list[str] = []
|
|
374
|
+
|
|
375
|
+
def walk(j: Job, prefix: str, last: bool, top: bool) -> None:
|
|
376
|
+
task = " ".join(j.task.split())[:70]
|
|
377
|
+
line = f"{STATUS_ICONS.get(j.status, '?')} {label(j.agent)} #{j.id} [{j.status}] {task}"
|
|
378
|
+
out.append(line if top else prefix + ("└── " if last else "├── ") + line)
|
|
379
|
+
kids = by_parent.get(j.id, [])
|
|
380
|
+
nxt = prefix if top else prefix + (" " if last else "│ ")
|
|
381
|
+
for i, k in enumerate(kids):
|
|
382
|
+
walk(k, nxt, i == len(kids) - 1, False)
|
|
383
|
+
|
|
384
|
+
for root in by_parent.get(None, []):
|
|
385
|
+
walk(root, "", True, True)
|
|
386
|
+
return out
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
@app.command()
|
|
390
|
+
def plan(run_id: int | None = typer.Argument(None, help="Run id (default: latest run of this project).")):
|
|
391
|
+
"""Show Mother's plan."""
|
|
392
|
+
store = _store()
|
|
393
|
+
r = _resolve_run(store, run_id)
|
|
394
|
+
text = project_files.plan_for_run(r)
|
|
395
|
+
state = {"pending": " (waiting for your approval: `hadley resume` approves)"}.get(r.plan_state or "", "")
|
|
396
|
+
typer.secho(f"plan of run {r.id} · {r.name} · {r.status}{state}\n", bold=True)
|
|
397
|
+
if not text:
|
|
398
|
+
typer.echo("(Mother has not written a plan yet)")
|
|
399
|
+
return
|
|
400
|
+
typer.echo(text.rstrip())
|
|
401
|
+
if r.plan_state == "pending":
|
|
402
|
+
typer.echo(f"\nEdit it in {project_files.plan_path(project_files.hadley_dir_of(r))} if you like,")
|
|
403
|
+
typer.echo(f"then approve with: hadley resume {r.id}")
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@app.command()
|
|
407
|
+
def logs(
|
|
408
|
+
run_id: int | None = typer.Argument(None, help="Run id (default: latest)."),
|
|
409
|
+
follow: bool = typer.Option(False, "--follow", "-f", help="Keep printing new events."),
|
|
410
|
+
lines: int = typer.Option(200, "--lines", "-n", help="How many past events to show."),
|
|
411
|
+
):
|
|
412
|
+
"""Show what the agents of a run have been doing."""
|
|
413
|
+
store = _store()
|
|
414
|
+
_follow(store, _resolve_run(store, run_id), lines=lines, follow=follow)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@app.command()
|
|
418
|
+
def pause(run_id: int | None = typer.Argument(None, help="Run id (default: latest).")):
|
|
419
|
+
"""Pause a run. Agents are stopped and resumed later in the same session."""
|
|
420
|
+
store = _store()
|
|
421
|
+
r = _resolve_run(store, run_id)
|
|
422
|
+
if r.status not in ("queued", "running", "paused"):
|
|
423
|
+
_err(f"run {r.id} is {r.status}")
|
|
424
|
+
store.update_run(r.id, status="paused", paused_until=None, pause_reason="paused by user")
|
|
425
|
+
store.add_event(r.id, None, "info", "paused by user")
|
|
426
|
+
typer.echo(f"run {r.id} paused")
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
@app.command()
|
|
430
|
+
def resume(
|
|
431
|
+
run_id: int | None = typer.Argument(None, help="Run id (default: latest)."),
|
|
432
|
+
detach: bool = typer.Option(False, "--detach", "-d", help="Leave it to the background service."),
|
|
433
|
+
):
|
|
434
|
+
"""Resume a paused or interrupted run (this also approves a plan waiting for approval)."""
|
|
435
|
+
store = _store()
|
|
436
|
+
r = _resolve_run(store, run_id)
|
|
437
|
+
if r.status in ("done", "failed", "cancelled"):
|
|
438
|
+
if r.status == "failed":
|
|
439
|
+
_retry_failed(store, r)
|
|
440
|
+
else:
|
|
441
|
+
_err(f"run {r.id} is {r.status}")
|
|
442
|
+
if r.plan_state == "pending":
|
|
443
|
+
store.update_run(r.id, plan_state="approved")
|
|
444
|
+
store.add_event(r.id, None, "info", "plan approved by user")
|
|
445
|
+
typer.secho("plan approved", fg=typer.colors.GREEN)
|
|
446
|
+
store.update_run(r.id, status="running", paused_until=None, pause_reason=None)
|
|
447
|
+
store.add_event(r.id, None, "info", "resumed by user")
|
|
448
|
+
if detach or daemon_running() or run_claimed(r.id):
|
|
449
|
+
typer.echo(f"run {r.id} resumed. Follow with: hadley logs -f {r.id}")
|
|
450
|
+
return
|
|
451
|
+
_run_engine_foreground(r.id)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _retry_failed(store: Store, r: Run) -> None:
|
|
455
|
+
"""Give a failed run another go: requeue failed jobs that have a session."""
|
|
456
|
+
for j in store.jobs_for_run(r.id):
|
|
457
|
+
if j.status == "failed":
|
|
458
|
+
store.update_job(
|
|
459
|
+
j.id,
|
|
460
|
+
status="queued",
|
|
461
|
+
attempts=0,
|
|
462
|
+
finished_at=None,
|
|
463
|
+
resume_note=f"[Hadley] The user asked to retry after this error: {j.error}. Continue the task."
|
|
464
|
+
if j.session_id
|
|
465
|
+
else None,
|
|
466
|
+
)
|
|
467
|
+
store.update_run(r.id, error=None)
|
|
468
|
+
typer.echo(f"retrying failed jobs of run {r.id}")
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
@app.command()
|
|
472
|
+
def cancel(run_id: int = typer.Argument(..., help="Run id.")):
|
|
473
|
+
"""Cancel a run for good."""
|
|
474
|
+
store = _store()
|
|
475
|
+
r = _resolve_run(store, run_id)
|
|
476
|
+
store.update_run(r.id, status="cancelled")
|
|
477
|
+
for j in store.jobs_for_run(r.id):
|
|
478
|
+
if j.status not in JOB_FINAL:
|
|
479
|
+
store.update_job(j.id, status="cancelled", finished_at=time.time())
|
|
480
|
+
store.add_event(r.id, None, "info", "cancelled by user")
|
|
481
|
+
with contextlib.suppress(OSError):
|
|
482
|
+
project_files.archive_run(store.get_run(r.id))
|
|
483
|
+
typer.echo(f"run {r.id} cancelled")
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
# ---- engine / service ------------------------------------------------------
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
@app.command()
|
|
490
|
+
def daemon():
|
|
491
|
+
"""Run the engine in the foreground for all runs (what the service runs)."""
|
|
492
|
+
try:
|
|
493
|
+
lock = acquire_daemon_lock()
|
|
494
|
+
except EngineLocked as e:
|
|
495
|
+
_err(str(e))
|
|
496
|
+
engine = Engine(
|
|
497
|
+
echo=lambda run, job, kind, text: print(
|
|
498
|
+
f"[run {run.id}] {alias_of(run, job.agent) if job else '-':>10} {kind:<8} "
|
|
499
|
+
f"{text.splitlines()[0] if text else ''}",
|
|
500
|
+
flush=True,
|
|
501
|
+
)
|
|
502
|
+
)
|
|
503
|
+
loop = asyncio.new_event_loop()
|
|
504
|
+
loop.add_signal_handler(signal.SIGTERM, engine.stop)
|
|
505
|
+
loop.add_signal_handler(signal.SIGINT, engine.stop)
|
|
506
|
+
print(f"hadley engine {__version__} started (state: {paths.home()})", flush=True)
|
|
507
|
+
try:
|
|
508
|
+
loop.run_until_complete(engine.serve())
|
|
509
|
+
finally:
|
|
510
|
+
loop.close()
|
|
511
|
+
lock.close()
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
@service_app.command("install")
|
|
515
|
+
def service_install():
|
|
516
|
+
"""Install and start the engine as a user service (systemd / launchd)."""
|
|
517
|
+
from . import service
|
|
518
|
+
|
|
519
|
+
try:
|
|
520
|
+
for m in service.install():
|
|
521
|
+
typer.echo(m)
|
|
522
|
+
except Exception as e:
|
|
523
|
+
_err(str(e))
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
@service_app.command("uninstall")
|
|
527
|
+
def service_uninstall():
|
|
528
|
+
"""Stop and remove the service."""
|
|
529
|
+
from . import service
|
|
530
|
+
|
|
531
|
+
for m in service.uninstall():
|
|
532
|
+
typer.echo(m)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
@service_app.command("status")
|
|
536
|
+
def service_status():
|
|
537
|
+
"""Is the service running?"""
|
|
538
|
+
from . import service
|
|
539
|
+
|
|
540
|
+
typer.echo(service.status())
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
@app.command()
|
|
544
|
+
def tui(run_id: int | None = typer.Argument(None, help="Run to open (default: latest).")):
|
|
545
|
+
"""Live terminal dashboard: runs, agent tree and log."""
|
|
546
|
+
from .tui import HadleyApp
|
|
547
|
+
|
|
548
|
+
HadleyApp(run_id).run()
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
@app.command()
|
|
552
|
+
def doctor():
|
|
553
|
+
"""Check that everything Hadley needs is in place."""
|
|
554
|
+
ok, msg = get_provider("claude-code").check()
|
|
555
|
+
typer.secho(("✓ " if ok else "✗ ") + msg, fg=typer.colors.GREEN if ok else typer.colors.RED)
|
|
556
|
+
typer.echo(f"✓ state directory: {paths.home()}")
|
|
557
|
+
typer.echo("✓ service is running" if daemon_running() else "· service is not running")
|
|
558
|
+
typer.echo(f"· python {sys.version.split()[0]}, hadley {__version__}")
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
@app.command("version")
|
|
562
|
+
def version():
|
|
563
|
+
"""Print the Hadley version."""
|
|
564
|
+
typer.echo(__version__)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
@app.command("mcp-serve", hidden=True)
|
|
568
|
+
def mcp_serve(job: int = typer.Option(..., help="Job id of the calling agent.")):
|
|
569
|
+
"""(internal) Serve the delegate tool to one agent over stdio."""
|
|
570
|
+
from .mcp_server import serve
|
|
571
|
+
|
|
572
|
+
serve(job)
|