herdr-orchestra 6.33.0 → 6.34.0
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.
- package/CHANGELOG.md +28 -0
- package/README.md +2 -1
- package/VERSION +1 -1
- package/bin/__pycache__/orchcpython-314.pyc +0 -0
- package/bin/orch +551 -28
- package/package.json +1 -1
- package/view/index.html +11 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,34 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes. Versions follow [semantic versioning](https://semver.org).
|
|
4
4
|
|
|
5
|
+
## [6.34.0] - 2026-11-28
|
|
6
|
+
|
|
7
|
+
The summary now shows how many tokens each milestone used, next to the estimate vs actual time. The board and `orch view` show the same numbers, and `orch tokens` prints the table at any time.
|
|
8
|
+
|
|
9
|
+
Example: at the end of a run the summary has
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
| M1 Goals screen | agy-1 | 182k (in 150k, of which 120k cached; out 32k) | 41k (codex-r) | 223k |
|
|
13
|
+
| M2 Emergency card | codex-2 | 64k (in 58k, of which 40k cached; out 6k) | 22k (codex-r) | 86k |
|
|
14
|
+
| Lead (whole run) | | 120k | | 120k |
|
|
15
|
+
| Total | | | | 431k |
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
"In" is what the agent read (its task, files and own chat), "cached" is the part that was its own chat read again (much cheaper), "out" is what it wrote.
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
- **Tokens per milestone** in `summary.md` ("Tokens: per milestone"), `orch report` (`--no-tokens` skips it, `--json` adds `tokens`) and the new `orch tokens [--json]`: coder jobs (fix rounds shown too), review rounds, the lead for the whole run, "Between jobs" (an agent's `/compact` or you typing in its pane) and the total.
|
|
22
|
+
- **Read from each agent's own session log, read only.** Claude Code (`~/.claude/projects`, sub-agent logs included, a reply written twice counted once), Codex (`~/.codex/sessions` rollouts: the job's share of the running total), Pi (`~/.pi/agent/sessions`) and Antigravity (`~/.gemini/antigravity-cli/brain/.../transcript_full.jsonl`). Each tool's own setting is followed (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `PI_CODING_AGENT_SESSION_DIR`); compressed Codex logs (`.jsonl.zst`) are read with `zstd` when it is installed. The formats were checked on a real machine (codex-cli 0.167, Claude Code 2.1.332, pi 1.6.1, agy 1.5.19).
|
|
23
|
+
- **Exact split, also for one coder doing several milestones in one chat.** orch finds a job's chat by the exact prompt it typed (unique per job, so coders sharing one folder are told apart) and counts only the replies between that job's start and the agent's next job.
|
|
24
|
+
- **Saved when each job ends.** The event manager reads the tokens about 20 seconds after a job ends and saves them in `state.json`, so they stay after the tool deletes its old logs. A log not found within 10 minutes is marked "not available".
|
|
25
|
+
- **Board and browser view.** Each milestone line shows its tokens (`42k tok`), the board's header the run's total and the lead; in `orch view` each milestone card and its details show them, and the "Time and tokens" card lists the lead and the total.
|
|
26
|
+
|
|
27
|
+
### Changed
|
|
28
|
+
- **Never a guess.** A job whose log has no token counts (for example agy versions before about October 2026) shows "not available" with the reason, and the total gets a `+`.
|
|
29
|
+
- The coder's result file no longer has a `usage` field: coders can't see their own token counts, and orch now reads them itself. The old money cost line is gone (Codex at work is company-paid, and prices change).
|
|
30
|
+
|
|
31
|
+
### After updating
|
|
32
|
+
Nothing to do. Runs started before 6.34.0 show `-` for jobs that ended before the update.
|
|
5
33
|
## [6.33.0] - 2026-11-28
|
|
6
34
|
|
|
7
35
|
Project setup before the first plan (`orch-onboard`). orch checks what a project has for its agents: the stack, the commands, the rule files and the skills each agent can see. If something is missing, the lead offers it in one list and writes only what you tick.
|
package/README.md
CHANGED
|
@@ -201,6 +201,7 @@ Model why: one module, a clear contract, an existing endpoint to copy; no design
|
|
|
201
201
|
- **Policy.** Ultra-premium models (`*fable*`, `*astra*`) are kept out of runs: `orch sync` refuses a plan that names one. Everything else your agents reach is allowed, open-weight models included. Edit `[policy] deny` to change the list.
|
|
202
202
|
- **Checked against reality.** `summary.md` has a table of planned tier against the model that really did each milestone, and `orch report` shows first-pass rate and escalations per model. When a model does worse than its rating, lower the rating.
|
|
203
203
|
- **A role for every coder.** The lead writes `Role:` on each milestone (for UI work, for example, "senior frontend engineer with a designer's eye: matches the existing components, works on a small screen, has loading, empty and error states"). The coder's task file starts with it, so the coder works to that standard.
|
|
204
|
+
- **Tokens per milestone.** Next to the time, the summary, the board and `orch view` show the tokens each milestone used (in, cached, out; coder, review and fix rounds), the lead and the total. orch reads them from each agent's own log (Claude Code, Codex, Pi, agy) when a job ends and saves them. A job whose log has no counts shows "not available", never a guess.
|
|
204
205
|
- **Estimate vs actual time.** The lead writes `Estimate:` for each milestone and for the whole feature. orch measures the real time, and the summary shows both. When something took longer, it lists where the time went and who it waited on (for example "10m claude-1 (sonnet): fix rounds: the check command failed" or "20m developer / lead: paused, waiting for an answer"), only from what orch recorded.
|
|
205
206
|
- **Yours to change.** Add or re-rate models in `~/.config/herdr-orchestra/models.toml` (merged over `models.default.toml`). The default ratings are starting points with their sources, not benchmarks run by this project. A model that is not in the catalog still works; it just has no tier.
|
|
206
207
|
|
|
@@ -425,7 +426,7 @@ The event manager starts in its own systemd scope when it can (`systemd-run --us
|
|
|
425
426
|
### Contracts and reports
|
|
426
427
|
`plan.md` stays the file you edit. From it `orch` generates a `task.json` for each milestone (numbered acceptance criteria `AC1…`, allowed files, interfaces, the commits of its dependencies). Coders answer with a `result-N.json` (status, commit message, files changed, the check they ran, each criterion met or not), and the reviewer with a `review-N.json` (a verdict per criterion plus findings). The old line formats (`COMMIT:`, `QUESTION:`, `BLOCKER:`) still work as a fallback. The shapes are in [docs/contracts.md](docs/contracts.md).
|
|
427
428
|
|
|
428
|
-
Every status change is written to `.orchestrate/events.jsonl`, and `orch report [--json]` shows estimated vs actual time (and why anything took longer), time per milestone, fix/review/conflict rounds, first-pass rate and wasted work, plus how each model did
|
|
429
|
+
Every status change is written to `.orchestrate/events.jsonl`, and `orch report [--json]` shows estimated vs actual time (and why anything took longer), time per milestone, fix/review/conflict rounds, first-pass rate and wasted work, plus how each model did, and tokens per milestone. `orch tokens` prints only the tokens.
|
|
429
430
|
|
|
430
431
|
Optional plan header lines: `Lead mode: events | off` (default `events` when the plan has a `Lead:` line) · `Scope: warn | strict` · `Risk hold: on | off` · `Budget: 3h` (autopilot stops when its running time is used up) · `Estimate: 1h30m` (the lead's estimate for the feature) · `Setup inputs: <globs>` (which files mean "run setup again"; default: lockfiles and manifests). Per milestone: `Why separate` (why it is its own milestone; needed when the plan has more than one) · `Tier`, `Needs`, `Model why` (see [Models and tiers](#models-and-tiers)) · `Estimate: 40m` (dispatch to landed if nothing goes wrong) · `Parallel: allow` lets it run next to a milestone that shares its `Likely files`.
|
|
431
432
|
|
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
6.
|
|
1
|
+
6.34.0
|
|
Binary file
|
package/bin/orch
CHANGED
|
@@ -2236,7 +2236,6 @@ RESULT_FORMAT = {
|
|
|
2236
2236
|
"check": {"ran": True, "passed": True, "summary": "lint ok, 42 tests pass"},
|
|
2237
2237
|
"criteria": [{"id": "AC1", "met": True, "evidence": "test 'rejects a missing amount column' passes"}],
|
|
2238
2238
|
"questions": ["only when status is question: what you need decided, with 2-3 options"],
|
|
2239
|
-
"usage": {"input_tokens": None, "output_tokens": None, "cost_usd": None},
|
|
2240
2239
|
"proof": "only when task.md says the milestone is hard to undo: what you ran to show it is safe, and what it showed",
|
|
2241
2240
|
}
|
|
2242
2241
|
REVIEW_FORMAT = {
|
|
@@ -2272,10 +2271,473 @@ def read_result(path):
|
|
|
2272
2271
|
return d, None
|
|
2273
2272
|
|
|
2274
2273
|
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2274
|
+
# ---- token usage, read from each tool's OWN session log (6.33.0). Nothing is guessed: a job whose log orch can't
|
|
2275
|
+
# find or read gets {"na": "<why>"} and shows as "not available (<why>)". In = everything the agent read (cached
|
|
2276
|
+
# included), cached = the part it re-read from its own chat, out = everything it wrote (thinking included).
|
|
2277
|
+
TOKEN_GRACE_S = int(os.environ.get("ORCH_TOKEN_GRACE_S", "20")) # let the tool write its last reply first
|
|
2278
|
+
TOKEN_GIVE_UP_S = int(os.environ.get("ORCH_TOKEN_GIVE_UP_S", "600")) # no log after this: "not available"
|
|
2279
|
+
TOKEN_KINDS = ("claude", "codex", "pi", "agy")
|
|
2280
|
+
|
|
2281
|
+
|
|
2282
|
+
class TokenNA(Exception):
|
|
2283
|
+
"""Why this job's tokens are not available (shown to the developer as is)."""
|
|
2284
|
+
|
|
2285
|
+
|
|
2286
|
+
def token_roots(kind):
|
|
2287
|
+
"""Where each tool keeps its session logs (each tool's own setting first)."""
|
|
2288
|
+
home = Path.home()
|
|
2289
|
+
test = os.environ.get("ORCH_TOKEN_HOME") # tests: every tool's logs under one folder, never the real ones
|
|
2290
|
+
if test:
|
|
2291
|
+
return [Path(test) / {"claude": "claude/projects", "codex": "codex/sessions", "pi": "pi/sessions",
|
|
2292
|
+
"agy": "agy/brain"}.get(kind, kind)]
|
|
2293
|
+
if kind == "claude":
|
|
2294
|
+
return [Path(os.environ.get("CLAUDE_CONFIG_DIR") or home / ".claude") / "projects"]
|
|
2295
|
+
if kind == "codex":
|
|
2296
|
+
return [Path(os.environ.get("CODEX_HOME") or home / ".codex") / "sessions"]
|
|
2297
|
+
if kind == "pi":
|
|
2298
|
+
return [Path(os.environ.get("PI_CODING_AGENT_SESSION_DIR") or home / ".pi" / "agent" / "sessions")]
|
|
2299
|
+
if kind == "agy":
|
|
2300
|
+
return [home / ".gemini" / "antigravity-cli" / "brain"]
|
|
2301
|
+
return []
|
|
2302
|
+
|
|
2303
|
+
|
|
2304
|
+
TOKEN_GLOBS = {"claude": "*/*.jsonl", "codex": "**/rollout-*.jsonl*", "pi": "*/*.jsonl",
|
|
2305
|
+
"agy": "*/.system_generated/logs/transcript_full.jsonl"}
|
|
2306
|
+
|
|
2307
|
+
|
|
2308
|
+
def _tok_text(path):
|
|
2309
|
+
p = str(path)
|
|
2310
|
+
if p.endswith(".zst"):
|
|
2311
|
+
if not shutil.which("zstd"):
|
|
2312
|
+
raise TokenNA("the log is compressed (.zst) and the `zstd` tool is not installed")
|
|
2313
|
+
r = subprocess.run(["zstd", "-dcq", p], capture_output=True, timeout=120)
|
|
2314
|
+
if r.returncode:
|
|
2315
|
+
raise TokenNA("the compressed log could not be unpacked")
|
|
2316
|
+
return r.stdout.decode("utf-8", "replace")
|
|
2317
|
+
try:
|
|
2318
|
+
return Path(p).read_text(errors="replace")
|
|
2319
|
+
except OSError:
|
|
2320
|
+
raise TokenNA("the log could not be read")
|
|
2321
|
+
|
|
2322
|
+
|
|
2323
|
+
def _tok_rows(text):
|
|
2324
|
+
for ln in text.splitlines():
|
|
2325
|
+
if not ln.startswith("{"):
|
|
2326
|
+
continue
|
|
2327
|
+
try:
|
|
2328
|
+
d = json.loads(ln)
|
|
2329
|
+
except ValueError:
|
|
2330
|
+
continue
|
|
2331
|
+
if isinstance(d, dict):
|
|
2332
|
+
yield d
|
|
2333
|
+
|
|
2334
|
+
|
|
2335
|
+
def _tok_ts(v):
|
|
2336
|
+
"""A log timestamp (ISO text, or epoch seconds / milliseconds) as epoch seconds, or None."""
|
|
2337
|
+
if isinstance(v, bool):
|
|
2338
|
+
return None
|
|
2339
|
+
if isinstance(v, (int, float)):
|
|
2340
|
+
return v / 1000 if v > 1e11 else float(v)
|
|
2341
|
+
if isinstance(v, str) and v:
|
|
2342
|
+
import datetime as _dt
|
|
2343
|
+
try:
|
|
2344
|
+
t = _dt.datetime.fromisoformat(v.strip().replace("Z", "+00:00"))
|
|
2345
|
+
except ValueError:
|
|
2346
|
+
return None
|
|
2347
|
+
return (t if t.tzinfo else t.replace(tzinfo=_dt.timezone.utc)).timestamp()
|
|
2348
|
+
return None
|
|
2349
|
+
|
|
2350
|
+
|
|
2351
|
+
def _tok_str(c):
|
|
2352
|
+
"""Message content (a string, or a list of text parts) as one string."""
|
|
2353
|
+
if isinstance(c, str):
|
|
2354
|
+
return c
|
|
2355
|
+
if isinstance(c, list):
|
|
2356
|
+
return "\n".join(_tok_str(x.get("text") if isinstance(x, dict) else x) for x in c)
|
|
2357
|
+
return ""
|
|
2358
|
+
|
|
2359
|
+
|
|
2360
|
+
def _tok_user_text(kind, d):
|
|
2361
|
+
"""What the PERSON (here: orch typing into the pane) said in this log line, else ""."""
|
|
2362
|
+
if kind == "claude":
|
|
2363
|
+
if d.get("type") == "user" and not d.get("toolUseResult") and isinstance(d.get("message"), dict):
|
|
2364
|
+
c = d["message"].get("content")
|
|
2365
|
+
if isinstance(c, list) and any(isinstance(x, dict) and x.get("type") == "tool_result" for x in c):
|
|
2366
|
+
return ""
|
|
2367
|
+
return _tok_str(c)
|
|
2368
|
+
elif kind == "codex":
|
|
2369
|
+
p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
|
|
2370
|
+
if d.get("type") == "event_msg" and p.get("type") == "user_message":
|
|
2371
|
+
return _tok_str(p.get("message"))
|
|
2372
|
+
if d.get("type") == "response_item" and p.get("role") == "user":
|
|
2373
|
+
return _tok_str(p.get("content"))
|
|
2374
|
+
elif kind == "pi":
|
|
2375
|
+
m = d.get("message") if isinstance(d.get("message"), dict) else {}
|
|
2376
|
+
if d.get("type") == "message" and m.get("role") == "user":
|
|
2377
|
+
return _tok_str(m.get("content"))
|
|
2378
|
+
elif kind == "agy":
|
|
2379
|
+
if d.get("source") == "USER_EXPLICIT" or d.get("type") == "USER_INPUT":
|
|
2380
|
+
return _tok_str(d.get("content"))
|
|
2381
|
+
return ""
|
|
2382
|
+
|
|
2383
|
+
|
|
2384
|
+
def token_log_has(kind, path, marker):
|
|
2385
|
+
"""True when orch's own prompt with this marker is a user message in the log."""
|
|
2386
|
+
try:
|
|
2387
|
+
text = _tok_text(path)
|
|
2388
|
+
except TokenNA:
|
|
2389
|
+
return False
|
|
2390
|
+
if marker not in text:
|
|
2391
|
+
return False
|
|
2392
|
+
return any(marker in _tok_user_text(kind, d) for d in _tok_rows(text))
|
|
2393
|
+
|
|
2394
|
+
|
|
2395
|
+
def token_log_find(kind, marker, since, known=()):
|
|
2396
|
+
"""The session log of `kind` in which orch typed the prompt holding `marker` (unique per job), or None. Logs
|
|
2397
|
+
orch already tied to this pane are tried first; then every log of that tool changed since the job started."""
|
|
2398
|
+
for p in known:
|
|
2399
|
+
if Path(p).exists() and token_log_has(kind, p, marker):
|
|
2400
|
+
return str(p)
|
|
2401
|
+
cands = []
|
|
2402
|
+
for r in token_roots(kind):
|
|
2403
|
+
if not r.is_dir():
|
|
2404
|
+
continue
|
|
2405
|
+
for p in r.glob(TOKEN_GLOBS.get(kind, "*.jsonl")):
|
|
2406
|
+
try:
|
|
2407
|
+
mt = p.stat().st_mtime
|
|
2408
|
+
except OSError:
|
|
2409
|
+
continue
|
|
2410
|
+
if mt >= since - 5 and str(p) not in known:
|
|
2411
|
+
cands.append((mt, p))
|
|
2412
|
+
for _, p in sorted(cands, reverse=True):
|
|
2413
|
+
if token_log_has(kind, p, marker):
|
|
2414
|
+
return str(p)
|
|
2415
|
+
return None
|
|
2416
|
+
|
|
2417
|
+
|
|
2418
|
+
def _tok_add(acc, ts, start, end, inp, cached, out):
|
|
2419
|
+
if ts is None or ts < start or ts > end:
|
|
2420
|
+
return
|
|
2421
|
+
acc["in"] += int(inp or 0)
|
|
2422
|
+
acc["cached"] += int(cached or 0)
|
|
2423
|
+
acc["out"] += int(out or 0)
|
|
2424
|
+
acc["replies"] += 1
|
|
2425
|
+
|
|
2426
|
+
|
|
2427
|
+
def token_window(kind, path, start, end):
|
|
2428
|
+
"""Tokens one session log used between start and end (epoch seconds): {"in", "cached", "out", "replies"}.
|
|
2429
|
+
Raises TokenNA when the log has no token counts at all."""
|
|
2430
|
+
acc = {"in": 0, "cached": 0, "out": 0, "replies": 0}
|
|
2431
|
+
text = _tok_text(path)
|
|
2432
|
+
seen_counts = False
|
|
2433
|
+
if kind == "claude":
|
|
2434
|
+
files = [text] + [_tok_text(s) for s in sorted((Path(path).with_suffix("") / "subagents").glob("*.jsonl"))]
|
|
2435
|
+
for tx in files:
|
|
2436
|
+
msgs = {} # one reply is often written as several lines with the same message id
|
|
2437
|
+
for d in _tok_rows(tx):
|
|
2438
|
+
m = d.get("message") if isinstance(d.get("message"), dict) else {}
|
|
2439
|
+
u = m.get("usage")
|
|
2440
|
+
if d.get("type") != "assistant" or not isinstance(u, dict):
|
|
2441
|
+
continue
|
|
2442
|
+
seen_counts = True
|
|
2443
|
+
key = (m.get("id"), d.get("requestId")) if m.get("id") else d.get("uuid") or id(d)
|
|
2444
|
+
ts = _tok_ts(d.get("timestamp"))
|
|
2445
|
+
row = (int(u.get("input_tokens") or 0) + int(u.get("cache_creation_input_tokens") or 0)
|
|
2446
|
+
+ int(u.get("cache_read_input_tokens") or 0), int(u.get("cache_read_input_tokens") or 0),
|
|
2447
|
+
int(u.get("output_tokens") or 0))
|
|
2448
|
+
old = msgs.get(key)
|
|
2449
|
+
msgs[key] = (ts if old is None else old[0], tuple(max(a, b) for a, b in zip(row, old[1])) if old else row)
|
|
2450
|
+
for ts, (i, c, o) in msgs.values():
|
|
2451
|
+
_tok_add(acc, ts, start, end, i, c, o)
|
|
2452
|
+
elif kind == "codex":
|
|
2453
|
+
before = last = None # Codex writes a running total: the job's share is end total - start total
|
|
2454
|
+
for d in _tok_rows(text):
|
|
2455
|
+
p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
|
|
2456
|
+
if d.get("type") != "event_msg" or p.get("type") != "token_count":
|
|
2457
|
+
continue
|
|
2458
|
+
tot = (p.get("info") or {}).get("total_token_usage") if isinstance(p.get("info"), dict) else None
|
|
2459
|
+
if not isinstance(tot, dict):
|
|
2460
|
+
continue
|
|
2461
|
+
seen_counts = True
|
|
2462
|
+
ts = _tok_ts(d.get("timestamp"))
|
|
2463
|
+
if ts is None:
|
|
2464
|
+
continue
|
|
2465
|
+
row = (int(tot.get("input_tokens") or 0), int(tot.get("cached_input_tokens") or 0),
|
|
2466
|
+
int(tot.get("output_tokens") or 0))
|
|
2467
|
+
if ts < start:
|
|
2468
|
+
before = row
|
|
2469
|
+
elif ts <= end:
|
|
2470
|
+
if last is not None and row != last:
|
|
2471
|
+
acc["replies"] += 1
|
|
2472
|
+
elif last is None:
|
|
2473
|
+
acc["replies"] += 1
|
|
2474
|
+
last = row
|
|
2475
|
+
if last is not None:
|
|
2476
|
+
b = before or (0, 0, 0)
|
|
2477
|
+
acc.update({"in": max(0, last[0] - b[0]), "cached": max(0, last[1] - b[1]), "out": max(0, last[2] - b[2])})
|
|
2478
|
+
elif kind == "pi":
|
|
2479
|
+
for d in _tok_rows(text):
|
|
2480
|
+
m = d.get("message") if isinstance(d.get("message"), dict) else {}
|
|
2481
|
+
u = m.get("usage") if d.get("type") == "message" and m.get("role") == "assistant" else d.get("usage")
|
|
2482
|
+
if not isinstance(u, dict) or d.get("type") == "message" and m.get("role") != "assistant":
|
|
2483
|
+
continue
|
|
2484
|
+
seen_counts = True
|
|
2485
|
+
_tok_add(acc, _tok_ts(d.get("timestamp")) or _tok_ts(m.get("timestamp")), start, end,
|
|
2486
|
+
int(u.get("input") or 0) + int(u.get("cacheRead") or 0) + int(u.get("cacheWrite") or 0),
|
|
2487
|
+
u.get("cacheRead"), u.get("output"))
|
|
2488
|
+
elif kind == "agy":
|
|
2489
|
+
steps = 0
|
|
2490
|
+
for d in _tok_rows(text):
|
|
2491
|
+
if d.get("source") == "MODEL" or d.get("type") == "PLANNER_RESPONSE":
|
|
2492
|
+
steps += 1
|
|
2493
|
+
if not any(k in d for k in ("input_tokens", "output_tokens")):
|
|
2494
|
+
continue
|
|
2495
|
+
seen_counts = True
|
|
2496
|
+
_tok_add(acc, _tok_ts(d.get("created_at")), start, end,
|
|
2497
|
+
int(d.get("input_tokens") or 0) + int(d.get("cache_read_tokens") or 0),
|
|
2498
|
+
d.get("cache_read_tokens"), d.get("output_tokens"))
|
|
2499
|
+
if steps and not seen_counts:
|
|
2500
|
+
raise TokenNA("this agy version saves no token counts (update agy)")
|
|
2501
|
+
else:
|
|
2502
|
+
raise TokenNA(f"orch can't read {kind}'s logs")
|
|
2503
|
+
if not seen_counts:
|
|
2504
|
+
raise TokenNA(f"{kind}'s log has no token counts")
|
|
2505
|
+
return acc
|
|
2506
|
+
|
|
2507
|
+
|
|
2508
|
+
def agent_kind_of(st, agent):
|
|
2509
|
+
if (st.get("lead") or {}).get("name") == agent:
|
|
2510
|
+
return st["lead"].get("kind")
|
|
2511
|
+
if agent and agent == st.get("reviewer"):
|
|
2512
|
+
return (st.get("reviewer_info") or {}).get("kind")
|
|
2513
|
+
return (st.get("workers", {}).get(agent) or {}).get("kind")
|
|
2514
|
+
|
|
2515
|
+
|
|
2516
|
+
def token_marker(prompt):
|
|
2517
|
+
"""The part of orch's job prompt that is unique to that one job: the result or review file it names."""
|
|
2518
|
+
m = re.search(r"[\w./-]*(?:result-\d+\.json|review-task-\d+\.md)", prompt or "")
|
|
2519
|
+
return m.group(0) if m else None
|
|
2520
|
+
|
|
2521
|
+
|
|
2522
|
+
def token_measure(st, agent, kind, marker, start, end, cap=None):
|
|
2523
|
+
"""{"in", "cached", "out", "log"} for one job, or {"na": why}, or None (not written yet: try again later)."""
|
|
2524
|
+
if not kind:
|
|
2525
|
+
return {"na": "orch does not know which tool this agent runs"}
|
|
2526
|
+
if kind not in TOKEN_KINDS:
|
|
2527
|
+
return {"na": f"orch can't read {kind}'s logs"}
|
|
2528
|
+
if not marker:
|
|
2529
|
+
return {"na": "no job prompt to find the log by"}
|
|
2530
|
+
logs = st.setdefault("token_logs", {})
|
|
2531
|
+
known = logs.get(agent) or []
|
|
2532
|
+
try:
|
|
2533
|
+
path = token_log_find(kind, marker, start, known)
|
|
2534
|
+
if not path:
|
|
2535
|
+
return None if now() - end < TOKEN_GIVE_UP_S else {"na": f"no {kind} log has this job's prompt"}
|
|
2536
|
+
acc = token_window(kind, path, start, min(end + TOKEN_GRACE_S, cap or float("inf")))
|
|
2537
|
+
except TokenNA as e:
|
|
2538
|
+
return {"na": str(e)}
|
|
2539
|
+
if path not in known:
|
|
2540
|
+
logs[agent] = (known + [path])[-6:]
|
|
2541
|
+
if not acc["replies"]:
|
|
2542
|
+
return None if now() - end < TOKEN_GIVE_UP_S else {"na": "no replies in the log during this job"}
|
|
2543
|
+
return {"in": acc["in"], "cached": acc["cached"], "out": acc["out"], "log": kind}
|
|
2544
|
+
|
|
2545
|
+
|
|
2546
|
+
def token_fill(st, force=False):
|
|
2547
|
+
"""Read the tokens of every finished job that has none yet (each tool's log, read only). True if any changed.
|
|
2548
|
+
`force` (summary, report): don't wait for the grace time and give up on logs that are not there."""
|
|
2549
|
+
changed = False
|
|
2550
|
+
starts = {} # the agent's next job starts where this one's window must end
|
|
2551
|
+
for t in st.get("tasks", {}).values():
|
|
2552
|
+
for a in t.get("attempts") or []:
|
|
2553
|
+
starts.setdefault(a.get("agent"), []).append(a.get("start", 0))
|
|
2554
|
+
for w in st.get("tasks", {}).values():
|
|
2555
|
+
if w.get("wait"):
|
|
2556
|
+
starts.setdefault(w["wait"].get("agent"), []).append(w["wait"].get("started", w["wait"].get("since", 0)))
|
|
2557
|
+
for tid in st.get("order", []):
|
|
2558
|
+
for a in (st["tasks"].get(tid) or {}).get("attempts") or []:
|
|
2559
|
+
if "tokens" in a or not a.get("tok_marker"):
|
|
2560
|
+
continue
|
|
2561
|
+
if not force and now() - a.get("end", 0) < TOKEN_GRACE_S:
|
|
2562
|
+
continue
|
|
2563
|
+
r = token_measure(st, a.get("agent"), a.get("tok_kind") or agent_kind_of(st, a.get("agent")),
|
|
2564
|
+
a["tok_marker"], a.get("start", 0), a.get("end", now()),
|
|
2565
|
+
min([x for x in starts.get(a.get("agent"), []) if x > a.get("start", 0)] or [None],
|
|
2566
|
+
key=lambda x: x or float("inf")))
|
|
2567
|
+
if r is not None:
|
|
2568
|
+
a["tokens"] = r
|
|
2569
|
+
changed = True
|
|
2570
|
+
return changed
|
|
2571
|
+
|
|
2572
|
+
|
|
2573
|
+
def token_fill_saved():
|
|
2574
|
+
"""token_fill on the saved state, under the state lock (orch report, orch tokens, orch view)."""
|
|
2575
|
+
if not STATE.exists():
|
|
2576
|
+
return
|
|
2577
|
+
try:
|
|
2578
|
+
with state_lock():
|
|
2579
|
+
st = load()
|
|
2580
|
+
if token_fill(st, force=True):
|
|
2581
|
+
save(st)
|
|
2582
|
+
except Exception as e: # a strange log never stops a report
|
|
2583
|
+
print(f"(token count skipped: {e})", file=sys.stderr)
|
|
2584
|
+
|
|
2585
|
+
|
|
2586
|
+
def lead_tokens(st):
|
|
2587
|
+
"""The lead's tokens from the run's start to its end (or now), found by orch's wake-up text."""
|
|
2588
|
+
ld, run = st.get("lead") or {}, st.get("run") or {}
|
|
2589
|
+
if not ld.get("name"):
|
|
2590
|
+
return None
|
|
2591
|
+
if not run.get("started"):
|
|
2592
|
+
return {"na": "the run has not started"}
|
|
2593
|
+
marker = f"in the run on {st.get('branch')} need the lead"
|
|
2594
|
+
r = token_measure(st, ld["name"], ld.get("kind"), marker, run["started"], run.get("ended") or now()) \
|
|
2595
|
+
or {"na": "the lead was never woken by orch, so its log can't be told apart"}
|
|
2596
|
+
saved = run.get("lead_tokens") # read at ALL_DONE: still good if the tool deleted the log since
|
|
2597
|
+
return saved if "na" in r and isinstance(saved, dict) and "na" not in saved else r
|
|
2598
|
+
|
|
2599
|
+
|
|
2600
|
+
def between_tokens(st, account_rows):
|
|
2601
|
+
"""Tokens agents used outside every job window during the run (their /compact, the developer typing into the
|
|
2602
|
+
pane between jobs): the logs' run total minus what the jobs got."""
|
|
2603
|
+
run = st.get("run") or {}
|
|
2604
|
+
if not run.get("started"):
|
|
2605
|
+
return None
|
|
2606
|
+
start, end = run["started"], run.get("ended") or now()
|
|
2607
|
+
total = {"in": 0, "cached": 0, "out": 0}
|
|
2608
|
+
got = {"in": 0, "cached": 0, "out": 0}
|
|
2609
|
+
lead = (st.get("lead") or {}).get("name")
|
|
2610
|
+
for agent, paths in (st.get("token_logs") or {}).items():
|
|
2611
|
+
if agent == lead:
|
|
2612
|
+
continue
|
|
2613
|
+
kind = agent_kind_of(st, agent)
|
|
2614
|
+
for p in paths:
|
|
2615
|
+
try:
|
|
2616
|
+
w = token_window(kind, p, start, end)
|
|
2617
|
+
except TokenNA:
|
|
2618
|
+
return None
|
|
2619
|
+
for k in total:
|
|
2620
|
+
total[k] += w[k]
|
|
2621
|
+
for r in account_rows:
|
|
2622
|
+
for part in ("coder", "review"):
|
|
2623
|
+
u = r[part]
|
|
2624
|
+
if u and "na" not in u:
|
|
2625
|
+
for k in got:
|
|
2626
|
+
got[k] += u[k]
|
|
2627
|
+
out = {k: max(0, total[k] - got[k]) for k in total}
|
|
2628
|
+
return out if any(out.values()) else None
|
|
2629
|
+
|
|
2630
|
+
|
|
2631
|
+
def _tok_merge(rows):
|
|
2632
|
+
"""Add up job token rows: {"in", "cached", "out", "jobs", "na": [why, ...]} or None for no jobs."""
|
|
2633
|
+
if not rows:
|
|
2634
|
+
return None
|
|
2635
|
+
acc = {"in": 0, "cached": 0, "out": 0, "jobs": 0, "known": 0, "na": []}
|
|
2636
|
+
for u in rows:
|
|
2637
|
+
acc["jobs"] += 1
|
|
2638
|
+
if not isinstance(u, dict) or "na" in u:
|
|
2639
|
+
acc["na"].append((u or {}).get("na") if isinstance(u, dict) else "not read yet")
|
|
2640
|
+
continue
|
|
2641
|
+
acc["known"] += 1
|
|
2642
|
+
for k in ("in", "cached", "out"):
|
|
2643
|
+
acc[k] += int(u.get(k) or 0)
|
|
2644
|
+
return acc
|
|
2645
|
+
|
|
2646
|
+
|
|
2647
|
+
_TOK_CACHE = {}
|
|
2648
|
+
|
|
2649
|
+
|
|
2650
|
+
def _tok_cached(key, fn, ttl=60):
|
|
2651
|
+
"""For the live board and view: read the logs at most once a minute."""
|
|
2652
|
+
hit = _TOK_CACHE.get(key)
|
|
2653
|
+
if hit and time.time() - hit[0] < ttl:
|
|
2654
|
+
return hit[1]
|
|
2655
|
+
v = fn()
|
|
2656
|
+
_TOK_CACHE[key] = (time.time(), v)
|
|
2657
|
+
return v
|
|
2658
|
+
|
|
2659
|
+
|
|
2660
|
+
def token_account(st, live=False):
|
|
2661
|
+
"""Tokens per milestone (coder jobs, review rounds), the lead, between jobs and the total. Only what the logs
|
|
2662
|
+
said: a milestone with a job whose log was missing is marked so the total reads "at least"."""
|
|
2663
|
+
rows = []
|
|
2664
|
+
for tid in st.get("order", []):
|
|
2665
|
+
t = st["tasks"][tid]
|
|
2666
|
+
if t.get("status") == "skipped":
|
|
2667
|
+
continue
|
|
2668
|
+
at = [a for a in t.get("attempts") or [] if isinstance(a, dict)]
|
|
2669
|
+
at = [a for a in at if a.get("tok_marker") or a.get("tokens")] # jobs that were really sent
|
|
2670
|
+
co = [a for a in at if a.get("kind") != "reviewer"]
|
|
2671
|
+
rv = [a for a in at if a.get("kind") == "reviewer"]
|
|
2672
|
+
fixes = [a for a in co if a.get("file") and a["file"] != "task.md"]
|
|
2673
|
+
rows.append({"task": tid, "title": t.get("title") or tid,
|
|
2674
|
+
"coders": list(dict.fromkeys(a.get("agent") for a in co if a.get("agent"))),
|
|
2675
|
+
"reviewers": list(dict.fromkeys(a.get("agent") for a in rv if a.get("agent"))),
|
|
2676
|
+
"coder": _tok_merge([a.get("tokens") for a in co]),
|
|
2677
|
+
"fixes": _tok_merge([a.get("tokens") for a in fixes]),
|
|
2678
|
+
"review": _tok_merge([a.get("tokens") for a in rv])})
|
|
2679
|
+
if live: # board / view redraw often: lead once a minute, "between jobs" only in the summary
|
|
2680
|
+
lead = _tok_cached(("lead", st.get("branch")), lambda: lead_tokens(json.loads(json.dumps(st)))) \
|
|
2681
|
+
if st.get("lead") else None
|
|
2682
|
+
between = None
|
|
2683
|
+
else:
|
|
2684
|
+
lead = lead_tokens(st) if st.get("lead") else None
|
|
2685
|
+
between = between_tokens(st, rows)
|
|
2686
|
+
total, partial = 0, False
|
|
2687
|
+
for r in rows:
|
|
2688
|
+
r["total"] = sum(r[p]["in"] + r[p]["out"] for p in ("coder", "review") if r[p])
|
|
2689
|
+
r["partial"] = any(r[p] and r[p]["na"] for p in ("coder", "review"))
|
|
2690
|
+
total += r["total"]
|
|
2691
|
+
partial |= r["partial"]
|
|
2692
|
+
if lead and "na" not in lead:
|
|
2693
|
+
total += lead["in"] + lead["out"]
|
|
2694
|
+
elif lead:
|
|
2695
|
+
partial = True
|
|
2696
|
+
if between:
|
|
2697
|
+
total += between["in"] + between["out"]
|
|
2698
|
+
return {"tasks": rows, "lead": lead, "between": between, "total": total, "partial": partial}
|
|
2699
|
+
|
|
2700
|
+
|
|
2701
|
+
def _tk(n):
|
|
2702
|
+
n = int(n or 0)
|
|
2703
|
+
return f"{n / 1e6:.1f}M" if n >= 1_000_000 else f"{round(n / 1000)}k" if n >= 1000 else str(n)
|
|
2704
|
+
|
|
2705
|
+
|
|
2706
|
+
def _tok_cell(u, who=""):
|
|
2707
|
+
if not u:
|
|
2708
|
+
return "-"
|
|
2709
|
+
if not u["known"]:
|
|
2710
|
+
return f"not available ({u['na'][0]})"
|
|
2711
|
+
s = f"{_tk(u['in'] + u['out'])} (in {_tk(u['in'])}, of which {_tk(u['cached'])} cached; out {_tk(u['out'])})"
|
|
2712
|
+
if u["na"]:
|
|
2713
|
+
s += f" + {len(u['na'])} job(s) not available ({u['na'][0]})"
|
|
2714
|
+
return s + (f" {who}" if who else "")
|
|
2715
|
+
|
|
2716
|
+
|
|
2717
|
+
def token_lines(acct):
|
|
2718
|
+
"""Tokens per milestone as markdown."""
|
|
2719
|
+
out = ["| Milestone | Built by | Coder tokens | Review tokens | Total |", "|---|---|---|---|---|"]
|
|
2720
|
+
for r in acct["tasks"]:
|
|
2721
|
+
fx = r["fixes"]
|
|
2722
|
+
coder = _tok_cell(r["coder"]) + (f"; fixes {_tk(fx['in'] + fx['out'])}" if fx and fx["known"] else "")
|
|
2723
|
+
out.append(f"| {r['task']} {r['title']} | {', '.join(r['coders']) or '-'} | {coder} | "
|
|
2724
|
+
f"{_tok_cell(r['review'], '(' + ', '.join(r['reviewers']) + ')' if r['reviewers'] else '')} | "
|
|
2725
|
+
f"{_tk(r['total'])}{'+' if r['partial'] else ''} |")
|
|
2726
|
+
ld = acct["lead"]
|
|
2727
|
+
if ld:
|
|
2728
|
+
out.append("| Lead (whole run) | | " + (f"not available ({ld['na']})" if "na" in ld else
|
|
2729
|
+
f"{_tk(ld['in'] + ld['out'])} (in {_tk(ld['in'])}, of which {_tk(ld['cached'])} cached; out "
|
|
2730
|
+
f"{_tk(ld['out'])})") + f" | | {'-' if 'na' in ld else _tk(ld['in'] + ld['out'])} |")
|
|
2731
|
+
bt = acct["between"]
|
|
2732
|
+
if bt:
|
|
2733
|
+
out.append(f"| Between jobs (/compact, typing in a pane) | | {_tk(bt['in'] + bt['out'])} | | "
|
|
2734
|
+
f"{_tk(bt['in'] + bt['out'])} |")
|
|
2735
|
+
out.append(f"| **Total** | | | | **{_tk(acct['total'])}{'+' if acct['partial'] else ''}** |")
|
|
2736
|
+
out += ["", "Read from each agent's own log. In = what the agent read (its chat included; the cached part is its "
|
|
2737
|
+
"own chat read again, much cheaper), out = what it wrote."]
|
|
2738
|
+
if acct["partial"]:
|
|
2739
|
+
out.append("`+` = some jobs' tokens are not available (reason in the row), so the real number is higher.")
|
|
2740
|
+
return out
|
|
2279
2741
|
|
|
2280
2742
|
|
|
2281
2743
|
def finding_axis(f):
|
|
@@ -2996,6 +3458,9 @@ def record_attempt(t, outcome, usage=None):
|
|
|
2996
3458
|
a["blocked_s"] = min(blocked, a["secs"]) # time herdr showed the agent stopped at a prompt in its pane
|
|
2997
3459
|
if usage:
|
|
2998
3460
|
a["usage"] = usage
|
|
3461
|
+
mk = token_marker(w.get("prompt")) if outcome != "not delivered" else None
|
|
3462
|
+
if mk:
|
|
3463
|
+
a["tok_marker"] = mk # the job's own prompt: how orch finds its tokens in the tool's log
|
|
2999
3464
|
t.setdefault("attempts", []).append(a)
|
|
3000
3465
|
del t["attempts"][:-100]
|
|
3001
3466
|
|
|
@@ -3378,7 +3843,7 @@ def cmd_poll(args):
|
|
|
3378
3843
|
agent, sentinel = w["agent"], Path(w["sentinel"])
|
|
3379
3844
|
age = now() - w["since"]
|
|
3380
3845
|
if sentinel.exists():
|
|
3381
|
-
record_attempt(t, "done"
|
|
3846
|
+
record_attempt(t, "done")
|
|
3382
3847
|
if w["kind"] == "coder":
|
|
3383
3848
|
move(st, tid, "verifying")
|
|
3384
3849
|
t["last_report"] = w["report"]
|
|
@@ -5023,7 +5488,7 @@ WORKER_RULES = """## Rules for you (the coder)
|
|
|
5023
5488
|
- Do NOT commit, push, or switch branches. orch commits your work for you.
|
|
5024
5489
|
- Never push to main (or master, or the repo's default branch) and never merge a PR, in any situation, even when the developer or the lead asks you to. Say no and offer the run's branch and a PR instead; a person merges by hand. The repo's pre-push guard refuses such a push anyway: never get around it (no `--no-verify`, no editing or deleting `.git/hooks`).
|
|
5025
5490
|
- Stay inside the files listed under Likely files (`files_allowed` in task.json) unless the task can't be done otherwise; say why in your report if you leave them. orch compares your diff with that list.
|
|
5026
|
-
- Finish with a result file (the prompt names it) in the `result_format` shape from task.json: `status` done / question / blocked, `commit`, `files_changed`, the `check` you ran, one entry per acceptance criterion (`id`, `met`, `evidence`)
|
|
5491
|
+
- Finish with a result file (the prompt names it) in the `result_format` shape from task.json: `status` done / question / blocked, `commit`, `files_changed`, the `check` you ran, and one entry per acceptance criterion (`id`, `met`, `evidence`). orch reads it, so keep it valid JSON.
|
|
5027
5492
|
- The commit message (`commit` in the result, and the last report line `COMMIT: <commit message>`) says what changed, in the repo's commit style (for example `feat(api): add categories endpoint`). It becomes the commit message, so describe the change, not the milestone.
|
|
5028
5493
|
- If anything is ambiguous, do not guess: set status `question`, put the question in `questions` and on a report line starting `QUESTION:`, finish the files and the done file, and stop.
|
|
5029
5494
|
- If an acceptance criterion can't be met in this repo (it needs an outside API, service or account that doesn't exist), don't keep trying: ask (status `question`), name the criterion and why, and offer to build the rest. A criterion marked DEFERRED above was approved to stay undone: don't build it, and report it `met: false`.
|
|
@@ -6860,6 +7325,22 @@ def _autopilot(args):
|
|
|
6860
7325
|
return s_["workers"].get(name) if name in s_.get("workers", {}) else \
|
|
6861
7326
|
(s_.get("reviewer_info") if name == s_.get("reviewer") else None)
|
|
6862
7327
|
|
|
7328
|
+
tok_tick = [0.0]
|
|
7329
|
+
|
|
7330
|
+
def tend_tokens():
|
|
7331
|
+
"""Read the tokens of jobs that finished (each tool's own log, read only) soon after they end, so the numbers
|
|
7332
|
+
are saved in state.json before the tool may delete its old logs. At most every 30s, only when a job waits."""
|
|
7333
|
+
if time.time() - tok_tick[0] < 30:
|
|
7334
|
+
return
|
|
7335
|
+
tok_tick[0] = time.time()
|
|
7336
|
+
st_ = load()
|
|
7337
|
+
if any("tokens" not in a and a.get("tok_marker") and now() - a.get("end", 0) >= TOKEN_GRACE_S
|
|
7338
|
+
for t in st_["tasks"].values() for a in t.get("attempts") or []):
|
|
7339
|
+
try:
|
|
7340
|
+
patch_state(lambda s_: token_fill(s_))
|
|
7341
|
+
except Exception as e: # a strange log must never stop the run
|
|
7342
|
+
say(f"token count skipped this time: {e}")
|
|
7343
|
+
|
|
6863
7344
|
def tend_compacts():
|
|
6864
7345
|
"""Coders and the reviewer whose milestone landed get their tool's compact command while they are idle and
|
|
6865
7346
|
hold no job; one that is compacting is free again once herdr shows it idle (or after COMPACT_MAX_S)."""
|
|
@@ -7128,6 +7609,7 @@ def _autopilot(args):
|
|
|
7128
7609
|
watch_herdr()
|
|
7129
7610
|
tend_stops()
|
|
7130
7611
|
tend_compacts()
|
|
7612
|
+
tend_tokens()
|
|
7131
7613
|
# 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
|
|
7132
7614
|
el, last_tick = time.time() - last_tick, time.time()
|
|
7133
7615
|
asleep = slept()
|
|
@@ -7192,8 +7674,14 @@ def _autopilot(args):
|
|
|
7192
7674
|
sugg += [f"- {k}: {s}" for s in review_findings(k, rnd)[1]]
|
|
7193
7675
|
if v.get("out_of_scope"):
|
|
7194
7676
|
scope.append(f"- {k}: {', '.join(v['out_of_scope'])}")
|
|
7195
|
-
_, report = run("report", "--no-time", ok=(0, 1, 2))
|
|
7677
|
+
_, report = run("report", "--no-time", "--no-tokens", ok=(0, 1, 2))
|
|
7196
7678
|
timing = "\n".join(time_lines(time_account(load())))
|
|
7679
|
+
try:
|
|
7680
|
+
patch_state(lambda s_: token_fill(s_, force=True))
|
|
7681
|
+
tokens_md = "\n".join(token_lines(token_account(load())))
|
|
7682
|
+
except Exception as e: # a strange log must never stop the summary
|
|
7683
|
+
tokens_md = f"not available ({e})"
|
|
7684
|
+
patch_state(lambda s_: s_["run"].update(lead_tokens=lead_tokens(s_)) if s_.get("lead") else None)
|
|
7197
7685
|
models = []
|
|
7198
7686
|
for k, v in tasks.items():
|
|
7199
7687
|
used = [a for a in v.get("attempts") or [] if a.get("kind") == "coder" and a.get("model")]
|
|
@@ -7221,6 +7709,7 @@ def _autopilot(args):
|
|
|
7221
7709
|
+ ("## Models: planned and actual\n| Milestone | Planned tier | Ran on | Escalated | Why this tier |\n"
|
|
7222
7710
|
"|---|---|---|---|---|\n" + "\n".join(models) + "\n\n" if models else "") +
|
|
7223
7711
|
f"## Time: estimate vs actual\n{timing}\n\n"
|
|
7712
|
+
f"## Tokens: per milestone\n{tokens_md}\n\n"
|
|
7224
7713
|
f"## Waiting: time milestones sat still\nA finished or ready milestone that waited for something else "
|
|
7225
7714
|
f"first (counted in the times above).\n{wait_table(tasks)}\n\n"
|
|
7226
7715
|
f"## Checked automatically\nAlready verified by the run; nobody needs to redo these by hand.\n"
|
|
@@ -7348,7 +7837,7 @@ def run_report(st):
|
|
|
7348
7837
|
"""Numbers for one run, from what orch recorded (attempts, checks, rounds). No guesses: unknown stays unknown."""
|
|
7349
7838
|
rows, tot = [], {"tasks": 0, "merged": 0, "failed": 0, "first_pass": 0, "reviewed": 0, "re_reviewed": 0,
|
|
7350
7839
|
"conflicts": 0, "lost": 0, "fix_rounds": 0, "agent_s": 0, "wasted_s": 0, "check_s": 0,
|
|
7351
|
-
|
|
7840
|
+
}
|
|
7352
7841
|
for tid in st["order"]:
|
|
7353
7842
|
t = st["tasks"][tid]
|
|
7354
7843
|
if t["status"] == "skipped":
|
|
@@ -7360,13 +7849,6 @@ def run_report(st):
|
|
|
7360
7849
|
check_s = sum(c.get("secs", 0) for c in t.get("checks") or [])
|
|
7361
7850
|
first = (t["status"] == "merged" and t.get("fix", 0) == 0 and t.get("review_round", 0) <= 1
|
|
7362
7851
|
and not t.get("conflicts") and len([a for a in coder if a.get("outcome") == "done"]) <= 1)
|
|
7363
|
-
for a in at:
|
|
7364
|
-
u = a.get("usage") or {}
|
|
7365
|
-
if u:
|
|
7366
|
-
tot["usage_known"] += 1
|
|
7367
|
-
for k in ("input_tokens", "output_tokens", "cost_usd"):
|
|
7368
|
-
if isinstance(u.get(k), (int, float)):
|
|
7369
|
-
tot[k] += u[k]
|
|
7370
7852
|
rows.append({"task": tid, "status": t["status"], "attempts": len(coder), "fix_rounds": t.get("fix", 0),
|
|
7371
7853
|
"review_rounds": t.get("review_round", 0), "conflicts": t.get("conflicts", 0),
|
|
7372
7854
|
"lost": t.get("lost", 0), "agent_s": agent_s, "wasted_s": wasted, "check_s": check_s,
|
|
@@ -7646,14 +8128,27 @@ def time_lines(acct):
|
|
|
7646
8128
|
return out
|
|
7647
8129
|
|
|
7648
8130
|
|
|
8131
|
+
def cmd_tokens(args):
|
|
8132
|
+
"""orch tokens [--json] -> tokens per milestone, read from each agent's own session log (read only)."""
|
|
8133
|
+
token_fill_saved()
|
|
8134
|
+
acct = token_account(load())
|
|
8135
|
+
if "--json" in args:
|
|
8136
|
+
print(json.dumps(acct, indent=2))
|
|
8137
|
+
return
|
|
8138
|
+
print("\n".join(token_lines(acct)))
|
|
8139
|
+
|
|
8140
|
+
|
|
7649
8141
|
def cmd_report(args):
|
|
7650
|
-
"""orch report [--json] [--no-time] -> estimated vs actual time (and why it took longer),
|
|
7651
|
-
rate and wasted work for this run."""
|
|
8142
|
+
"""orch report [--json] [--no-time] [--no-tokens] -> estimated vs actual time (and why it took longer), tokens
|
|
8143
|
+
per milestone, rounds, first-pass rate and wasted work for this run."""
|
|
8144
|
+
if "--no-tokens" not in args or "--json" in args:
|
|
8145
|
+
token_fill_saved()
|
|
7652
8146
|
st = load()
|
|
7653
8147
|
rep_ = run_report(st)
|
|
7654
8148
|
by_axis, rules_broken = review_axes(st)
|
|
7655
8149
|
if "--json" in args:
|
|
7656
8150
|
rep_["time"] = time_account(st)
|
|
8151
|
+
rep_["tokens"] = token_account(st)
|
|
7657
8152
|
rep_["review_axes"] = {"spec": len(by_axis["spec"]), "rules": len(by_axis["rules"]), "rules_broken": rules_broken}
|
|
7658
8153
|
rep_["risk"] = [{"task": k, "door": v.get("door") or "two-way", "door_why": v.get("door_why"),
|
|
7659
8154
|
"blast": v.get("blast"), "proof": v.get("proof")}
|
|
@@ -7662,6 +8157,8 @@ def cmd_report(args):
|
|
|
7662
8157
|
return
|
|
7663
8158
|
if "--no-time" not in args:
|
|
7664
8159
|
print("Estimate vs actual\n" + "\n".join(time_lines(time_account(st))) + "\n")
|
|
8160
|
+
if "--no-tokens" not in args:
|
|
8161
|
+
print("Tokens per milestone\n" + "\n".join(token_lines(token_account(st))) + "\n")
|
|
7665
8162
|
tot = rep_["totals"]
|
|
7666
8163
|
print(f"{'task':<5} {'status':<15} {'tries':>5} {'fix':>4} {'review':>6} {'confl':>5} {'lost':>4} "
|
|
7667
8164
|
f"{'agent time':>10} {'wasted':>8} {'checks':>8} first pass")
|
|
@@ -7682,11 +8179,6 @@ def cmd_report(args):
|
|
|
7682
8179
|
f"{m['first_pass']:>10} {m['escalated_away']:>8} {_fmt_secs(m['agent_s']):>10}")
|
|
7683
8180
|
print("(moved up = milestones this model could not finish, escalated to a stronger one; compare with "
|
|
7684
8181
|
"`orch models`)")
|
|
7685
|
-
if tot["usage_known"]:
|
|
7686
|
-
print(f"usage reported by agents on {tot['usage_known']} attempt(s): {tot['input_tokens']} input tokens, "
|
|
7687
|
-
f"{tot['output_tokens']} output tokens, ${tot['cost_usd']:.2f}")
|
|
7688
|
-
else:
|
|
7689
|
-
print("tokens/cost: unknown (no agent reported `usage` in its result file)")
|
|
7690
8182
|
if "--no-time" in args: # the summary (its only caller) has its own sections for the lines below
|
|
7691
8183
|
return
|
|
7692
8184
|
rows = risk_rows(st)
|
|
@@ -8220,6 +8712,16 @@ VIEW_WORDS = {"pending": "waiting", "coding": "building", "needs-fix": "fix roun
|
|
|
8220
8712
|
VIEW_PORT = int(os.environ.get("ORCH_VIEW_PORT", "47231"))
|
|
8221
8713
|
|
|
8222
8714
|
|
|
8715
|
+
def _tok_view(r):
|
|
8716
|
+
"""One milestone's tokens for the board and the browser view (None: no job sent yet)."""
|
|
8717
|
+
if not r or not (r["coder"] or r["review"]):
|
|
8718
|
+
return None
|
|
8719
|
+
part = {p: (None if not r[p] else {"total": r[p]["in"] + r[p]["out"], "in": r[p]["in"], "cached": r[p]["cached"],
|
|
8720
|
+
"out": r[p]["out"], "known": r[p]["known"], "jobs": r[p]["jobs"],
|
|
8721
|
+
"na": r[p]["na"][:1]}) for p in ("coder", "review")}
|
|
8722
|
+
return {"total": r["total"], "partial": r["partial"], **part}
|
|
8723
|
+
|
|
8724
|
+
|
|
8223
8725
|
def _usage_sum(rows):
|
|
8224
8726
|
tok = cost = 0
|
|
8225
8727
|
known = False
|
|
@@ -8319,6 +8821,11 @@ def view_model(st=None, recent=40):
|
|
|
8319
8821
|
"notices": run_notices(None)}
|
|
8320
8822
|
tasks, t_now = st.get("tasks", {}), now()
|
|
8321
8823
|
ms, by_model = [], {}
|
|
8824
|
+
try:
|
|
8825
|
+
tacct = token_account(st, live=True)
|
|
8826
|
+
except Exception:
|
|
8827
|
+
tacct = {"tasks": [], "lead": None, "total": 0, "partial": False}
|
|
8828
|
+
trow = {r["task"]: r for r in tacct["tasks"]}
|
|
8322
8829
|
for tid in st.get("order", []):
|
|
8323
8830
|
t = tasks.get(tid) or {}
|
|
8324
8831
|
w = t.get("wait") or {}
|
|
@@ -8342,6 +8849,7 @@ def view_model(st=None, recent=40):
|
|
|
8342
8849
|
"estimate_s": t.get("estimate_s"), "started": (w.get("started") or w.get("since")) if cur else None,
|
|
8343
8850
|
"spent_s": int(sum(a.get("secs", 0) for a in atts) + cur),
|
|
8344
8851
|
"usage": _usage_sum([a.get("usage") for a in atts if a.get("usage")]),
|
|
8852
|
+
"tokens": _tok_view(trow.get(tid)),
|
|
8345
8853
|
"attempts": [{"kind": a.get("kind"), "agent": a.get("agent"), "model": a.get("model"),
|
|
8346
8854
|
"tier": a.get("tier"), "secs": a.get("secs"), "outcome": a.get("outcome")}
|
|
8347
8855
|
for a in atts[-12:]],
|
|
@@ -8382,6 +8890,11 @@ def view_model(st=None, recent=40):
|
|
|
8382
8890
|
"active": len([g for g in groups if g in ("building", "checking", "review", "landing")]),
|
|
8383
8891
|
"waiting": groups.count("waiting")},
|
|
8384
8892
|
"time": {"driven_s": int(run.get("driven_s", 0)), "estimate_s": st.get("estimate_s")},
|
|
8893
|
+
"tokens": {"total": tacct["total"], "partial": tacct["partial"],
|
|
8894
|
+
"lead": None if not tacct["lead"] else
|
|
8895
|
+
{"na": tacct["lead"]["na"]} if "na" in tacct["lead"] else
|
|
8896
|
+
{"total": tacct["lead"]["in"] + tacct["lead"]["out"], "in": tacct["lead"]["in"],
|
|
8897
|
+
"cached": tacct["lead"]["cached"], "out": tacct["lead"]["out"]}},
|
|
8385
8898
|
"usage": {"total": _usage_sum([u for v in by_model.values() for u in v]),
|
|
8386
8899
|
"by_model": {k: _usage_sum(v) for k, v in by_model.items()}},
|
|
8387
8900
|
"milestones": ms, "agents": agents,
|
|
@@ -9199,9 +9712,12 @@ def render_board(vm, width=100, color=True, sel=None, note=""):
|
|
|
9199
9712
|
+ (" · " + c("r", f"{cn['needs_you']} needs you") if cn["needs_you"] else "")
|
|
9200
9713
|
+ c("d", f" · {_fmt_min(vm['time']['driven_s'])} so far"
|
|
9201
9714
|
+ (f" of ~{_fmt_min(vm['time']['estimate_s'])}" if vm["time"].get("estimate_s") else ""))]
|
|
9202
|
-
|
|
9203
|
-
if
|
|
9204
|
-
|
|
9715
|
+
tk = vm.get("tokens") or {}
|
|
9716
|
+
if tk.get("total") or tk.get("lead"):
|
|
9717
|
+
ld = tk.get("lead") or {}
|
|
9718
|
+
out.append(c("d", f"tokens {_tk(tk.get('total'))}{'+' if tk.get('partial') else ''} so far"
|
|
9719
|
+
+ (f" · lead {_tk(ld['total'])}" if ld.get("total") else
|
|
9720
|
+
" · lead: not available" if ld.get("na") else "")))
|
|
9205
9721
|
if vm.get("all_done"):
|
|
9206
9722
|
out.append(c("g", "ALL DONE — `orch finish` pushes the branch and opens the PR"))
|
|
9207
9723
|
out += notes
|
|
@@ -9217,6 +9733,10 @@ def render_board(vm, width=100, color=True, sel=None, note=""):
|
|
|
9217
9733
|
who = m.get("worker") or ""
|
|
9218
9734
|
extra = (f"{_fmt_min(m['spent_s'])} of ~{_fmt_min(m['estimate_s'])}" if m.get("started")
|
|
9219
9735
|
and m.get("estimate_s") else f"{_fmt_min(m['spent_s'])}" if m["spent_s"] else "")
|
|
9736
|
+
mt = m.get("tokens")
|
|
9737
|
+
if mt:
|
|
9738
|
+
extra += (" " if extra else "") + (f"{_tk(mt['total'])}{'+' if mt['partial'] else ''} tok"
|
|
9739
|
+
if mt["total"] else "tokens n/a")
|
|
9220
9740
|
if g == "waiting" and m["deps"]:
|
|
9221
9741
|
word = "waits for " + ",".join(d for d in m["deps"] if ms.get(d, {}).get("group") != "landed") \
|
|
9222
9742
|
if any(ms.get(d, {}).get("group") != "landed" for d in m["deps"]) else "ready"
|
|
@@ -9599,7 +10119,7 @@ COMMANDS = {
|
|
|
9599
10119
|
"write-task": cmd_write_task, "nudge": cmd_nudge, "autopilot": cmd_autopilot,
|
|
9600
10120
|
"send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
|
|
9601
10121
|
"requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
|
|
9602
|
-
"report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
|
|
10122
|
+
"report": cmd_report, "tokens": cmd_tokens, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
|
|
9603
10123
|
"escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "manual": cmd_manual, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
|
|
9604
10124
|
"free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
|
|
9605
10125
|
"view": lambda a: cmd_view(a), "board": lambda a: cmd_board(a), "changes": lambda a: cmd_changes(a),
|
|
@@ -9688,7 +10208,10 @@ USAGE = """usage: orch <command> [args]
|
|
|
9688
10208
|
[f] or [enter] on a milestone shows its changed files, [enter] on a file its diff
|
|
9689
10209
|
changes [Mn [file]] [--json] what each milestone changed: files with +/- counts, or one file's diff
|
|
9690
10210
|
(live while a coder works, unsaved files included; landed = its commit). Read-only
|
|
9691
|
-
report [--json]
|
|
10211
|
+
report [--json] [--no-tokens] estimate vs actual time (why longer, who), tokens per milestone, rounds,
|
|
10212
|
+
first-pass rate, wasted work
|
|
10213
|
+
tokens [--json] tokens per milestone (coder, review, fix rounds), the lead and the total, read from each
|
|
10214
|
+
agent's own log (Claude Code, Codex, Pi, agy); "not available" when a log has none
|
|
9692
10215
|
ready free coder slots, FIX jobs (do these first), then READY milestones
|
|
9693
10216
|
pick <Mn> first available worker for the task (respects Tier, then Prefer), or NONE (exit 3)
|
|
9694
10217
|
escalate <Mn> [reason] out of rounds: one more go on a stronger model, if the team has one (exit 3 if not)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "herdr-orchestra",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.34.0",
|
|
4
4
|
"description": "Orchestrate AI coding agents (Claude Code, Codex, OpenCode, Amp, Pi) as one team: a lead plans, coders build, a reviewer checks, you get one PR. Runs in Herdr panes, or in one Pi window with subagents.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"bin": {
|
package/view/index.html
CHANGED
|
@@ -108,7 +108,9 @@ const $ = (id) => document.getElementById(id);
|
|
|
108
108
|
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
|
109
109
|
const mins = (s) => s == null ? "?" : (s >= 3600 ? `${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m` : `${Math.max(0, Math.floor(s/60))}m`);
|
|
110
110
|
const clock = (ts) => new Date(ts * 1000).toLocaleTimeString([], {hour:"2-digit", minute:"2-digit"});
|
|
111
|
-
const
|
|
111
|
+
const tk = (n) => n >= 1e6 ? `${(n/1e6).toFixed(1)}M` : n >= 1000 ? `${Math.round(n/1000)}k` : String(n || 0);
|
|
112
|
+
const tokPart = (p) => !p ? "-" : !p.known ? `not available (${p.na[0] || "no log"})` : `${tk(p.total)} (in ${tk(p.in)}, ${tk(p.cached)} cached · out ${tk(p.out)})${p.na.length ? " + some jobs not available" : ""}`;
|
|
113
|
+
const tokShort = (t) => !t ? "" : t.total ? `${tk(t.total)}${t.partial ? "+" : ""} tok` : "tokens n/a";
|
|
112
114
|
|
|
113
115
|
function view() { return replayAt == null || !HIST ? VM : replayed(VM, HIST, replayAt); }
|
|
114
116
|
|
|
@@ -198,7 +200,7 @@ function nodeHTML(m, v) {
|
|
|
198
200
|
return `<div><span class="id">${esc(m.id)}</span> <span class="nm">${esc(m.title)}</span></div>
|
|
199
201
|
${m.desc && m.desc !== m.title ? `<div class="ds" title="${esc(m.desc)}">${esc(m.desc)}</div>` : ""}
|
|
200
202
|
<div class="s">${ICON[m.group]} ${esc(m.group === "needs_you" ? "NEEDS YOU · " + m.word : word)}${m.attempt > 1 ? " · try " + m.attempt : ""}</div>
|
|
201
|
-
<div class="m">${esc([who, tm].filter(Boolean).join(" · "))}</div>
|
|
203
|
+
<div class="m">${esc([who, tm, tokShort(m.tokens)].filter(Boolean).join(" · "))}</div>
|
|
202
204
|
${pct != null ? `<div class="bar"><i style="width:${pct}%;background:${GROUP_COLOR[m.group]}"></i></div>` : ""}`;
|
|
203
205
|
}
|
|
204
206
|
function waitsFor(m, v) {
|
|
@@ -270,6 +272,7 @@ function detail(v) {
|
|
|
270
272
|
${you && ask ? `<div class="q">${esc(ask)}</div>` : (m.reason ? `<div class="muted" style="margin-top:6px">${esc(m.reason)}</div>` : "")}
|
|
271
273
|
<div class="muted" style="margin-top:6px">${esc([m.worker ? "coder " + m.worker : "", m.tier ? "tier " + m.tier : "", m.deps.length ? "after " + m.deps.join(", ") : "", m.door === "one-way" ? "hard to undo" : ""].filter(Boolean).join(" · "))}</div>
|
|
272
274
|
${you && how ? `<div style="margin-top:8px">Answer in the lead's pane, or run:</div><code>${esc(how)}</code>` : ""}
|
|
275
|
+
${m.tokens ? `<div class="h" style="margin:10px 0 4px">Tokens</div><table><tr><td class="muted">coder</td><td>${esc(tokPart(m.tokens.coder))}</td></tr><tr><td class="muted">review</td><td>${esc(tokPart(m.tokens.review))}</td></tr><tr><td><b>total</b></td><td><b>${esc(tokShort(m.tokens))}</b></td></tr></table>` : ""}
|
|
273
276
|
${m.attempts.length ? `<div class="h" style="margin:10px 0 4px">Steps so far</div><table>${m.attempts.map((a) => `<tr><td class="muted">${esc(a.kind || "step")} · ${esc(a.agent || "")}${a.model ? " · " + esc(a.model) : ""}</td><td>${mins(a.secs)} ${esc(a.outcome || "")}</td></tr>`).join("")}</table>` : ""}
|
|
274
277
|
<div class="h" style="margin:12px 0 2px">Changed files</div><div class="chg" id="chg" data-id="${esc(m.id)}">${chgHTML(m.id)}</div>
|
|
275
278
|
${m.files && m.files.length ? `<div class="h" style="margin:10px 0 4px">Files the plan expects</div><div class="mono muted">${m.files.map(esc).join("<br>")}</div>` : ""}
|
|
@@ -343,14 +346,15 @@ function cost(v) {
|
|
|
343
346
|
const est = v.time.estimate_s, so = v.time.driven_s;
|
|
344
347
|
const rows = done.map((m) => {
|
|
345
348
|
const late = m.spent_s > m.estimate_s * 1.2;
|
|
346
|
-
return `<tr><td class="muted">${esc(m.id)} ${esc(m.title)}</td><td class="${late ? "warn" : ""}">${mins(m.spent_s)} / est ${mins(m.estimate_s)}</td></tr>` +
|
|
349
|
+
return `<tr><td class="muted">${esc(m.id)} ${esc(m.title)}</td><td class="${late ? "warn" : ""}">${mins(m.spent_s)} / est ${mins(m.estimate_s)}${m.tokens ? " · " + esc(tokShort(m.tokens)) : ""}</td></tr>` +
|
|
347
350
|
(late && (m.fix || m.review_round > 1 || m.attempt > 1) ? `<tr><td colspan="2" class="faint" style="text-align:left;font-size:10.5px">longer: ${esc([m.fix ? m.fix + " fix round(s)" : "", m.attempt > 1 ? m.attempt + " tries" : "", m.review_round > 1 ? m.review_round + " review rounds" : ""].filter(Boolean).join(", "))}</td></tr>` : "");
|
|
348
351
|
}).join("");
|
|
349
|
-
const
|
|
350
|
-
|
|
352
|
+
const T = v.tokens || {}, L = T.lead;
|
|
353
|
+
const lead = L ? `<tr><td class="muted">lead (whole run)</td><td>${L.total != null ? tk(L.total) + " tok" : "tokens n/a (" + esc(L.na) + ")"}</td></tr>` : "";
|
|
354
|
+
$("cost").innerHTML = `<div class="card"><div class="h" style="margin-bottom:6px">Time and tokens</div>
|
|
351
355
|
<div style="margin-bottom:8px">${mins(so)} so far${est ? ` of ~${mins(est)} planned` : ""}</div>
|
|
352
|
-
<table>${rows}${
|
|
353
|
-
|
|
356
|
+
<table>${rows}${lead}<tr><td><b>Total tokens</b></td><td><b>${T.total ? tk(T.total) + (T.partial ? "+" : "") : "none yet"}</b></td></tr></table>
|
|
357
|
+
<div class="faint" style="font-size:11px;margin-top:6px">Read from each agent's own log. In = what it read (cached = its own chat read again, much cheaper), out = what it wrote. + = some jobs not available.</div></div>`;
|
|
354
358
|
}
|
|
355
359
|
|
|
356
360
|
function timeline(v) {
|