herdr-orchestra 6.33.0 → 6.35.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 +47 -0
- package/README.md +2 -1
- package/VERSION +1 -1
- package/agents.default.toml +4 -1
- package/bin/__pycache__/orchcpython-314.pyc +0 -0
- package/bin/orch +653 -43
- package/models.default.toml +17 -1
- package/package.json +1 -1
- package/view/index.html +11 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,53 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes. Versions follow [semantic versioning](https://semver.org).
|
|
4
4
|
|
|
5
|
+
## [6.35.0] - 2026-11-28
|
|
6
|
+
|
|
7
|
+
Antigravity (`agy`) panes now start on a model the lead chose for the step, taken from the models your agy account really has. Before, orch knew no agy model, so every agy pane started on whatever model was saved last with `/model` (often an old one).
|
|
8
|
+
|
|
9
|
+
Example: your account has Gemini 4 Hydrogen. `orch models` asks `agy models` and shows `gemini-3.8-flash@low` (small), `gemini-4-hydrogen@low` (medium) and `gemini-4-hydrogen@high` (high). The lead gives a rename step to the small level and a new API contract to the high one, so `orch team up` opens `agy --mode accept-edits --model gemini-4-hydrogen --effort high` for that coder. When Google adds a newer model, agy lists it and orch uses it the next time: no model name is written in orch.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
- **orch asks agy for its models.** New `[discover.agy]` in `models.default.toml` runs `agy models` (cached for 6 hours, like Codex) and fills small with the newest Flash on low thinking, medium with the newest Hydrogen on low, high with the newest Hydrogen on high. Without Hydrogen it falls back to Pro, then Flash. Claude and GPT models inside agy are never put in a level (you can still pick one with `orch plan model`).
|
|
13
|
+
- **agy starts on a model and thinking level.** The agy registry entry has `model_flag = "--model"`, `effort_flag = "--effort {effort}"` and `efforts = ["low", "medium", "high"]`, so `orch agents launch agy --model gemini-4-hydrogen@high`, `orch team agy`, `orch team up` and `orch plan model` work for agy like they do for Codex.
|
|
14
|
+
- **Any tool with a plain model list.** Model discovery now reads a list printed one model per line, not only Codex's JSON: `gemini-3.8-flash-high` (level at the end), `Gemini 3.1 Pro (High)` (level in brackets) or `<id> <description>`. Ids that differ only by level become one model with those levels. A `family` can be a list tried in order, and a model without a ranking is chosen by its highest version number. Add `[discover.<kind>]` in your own `models.toml` for another tool (the docs show OpenCode).
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
- A model found for a tool with no shipped entries borrows the ratings of a model of the same level from another tool and says so in `orch models show <id>` (e.g. "Ratings copied from opus").
|
|
18
|
+
|
|
19
|
+
### Not checked with the real tool
|
|
20
|
+
agy's model options come from public agy guides (1.1 to 1.5): the agy download is blocked where this was built. Tests use a fake agy that prints both list formats. If your `agy models` looks different, `orch models` simply shows no agy models and agy panes start as before.
|
|
21
|
+
|
|
22
|
+
### After updating
|
|
23
|
+
Run `orch models` once: you should see agy lines with Hydrogen. If not, run `agy models` yourself and check you are signed in.
|
|
24
|
+
## [6.34.0] - 2026-11-28
|
|
25
|
+
|
|
26
|
+
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.
|
|
27
|
+
|
|
28
|
+
Example: at the end of a run the summary has
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
| M1 Goals screen | agy-1 | 182k (in 150k, of which 120k cached; out 32k) | 41k (codex-r) | 223k |
|
|
32
|
+
| M2 Emergency card | codex-2 | 64k (in 58k, of which 40k cached; out 6k) | 22k (codex-r) | 86k |
|
|
33
|
+
| Lead (whole run) | | 120k | | 120k |
|
|
34
|
+
| Total | | | | 431k |
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
"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.
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
- **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.
|
|
41
|
+
- **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).
|
|
42
|
+
- **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.
|
|
43
|
+
- **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".
|
|
44
|
+
- **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.
|
|
45
|
+
|
|
46
|
+
### Changed
|
|
47
|
+
- **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 `+`.
|
|
48
|
+
- 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).
|
|
49
|
+
|
|
50
|
+
### After updating
|
|
51
|
+
Nothing to do. Runs started before 6.34.0 show `-` for jobs that ended before the update.
|
|
5
52
|
## [6.33.0] - 2026-11-28
|
|
6
53
|
|
|
7
54
|
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.35.0
|
package/agents.default.toml
CHANGED
|
@@ -136,6 +136,9 @@ notes = "Not installed on the machine this was written on: launch flag and skill
|
|
|
136
136
|
[agy]
|
|
137
137
|
binary = "agy"
|
|
138
138
|
launch = "agy --mode accept-edits"
|
|
139
|
+
model_flag = "--model"
|
|
140
|
+
effort_flag = "--effort {effort}"
|
|
141
|
+
efforts = ["low", "medium", "high"]
|
|
139
142
|
herdr_detect = true
|
|
140
143
|
interrupt_keys = ["esc"]
|
|
141
144
|
compact = "/compact"
|
|
@@ -145,7 +148,7 @@ skills_dirs = ["~/.gemini/config/skills"]
|
|
|
145
148
|
invoke = "use the orch-plan skill: <feature>"
|
|
146
149
|
verified = true
|
|
147
150
|
project_skills_reads = [".agent/skills"]
|
|
148
|
-
notes = "Antigravity CLI 1.5: --mode accept-edits|auto|plan and --dangerously-skip-permissions. The binary documents ~/.gemini/config/skills/<name>/SKILL.md as the global skills folder."
|
|
151
|
+
notes = "Antigravity CLI 1.5: --mode accept-edits|auto|plan and --dangerously-skip-permissions. The binary documents ~/.gemini/config/skills/<name>/SKILL.md as the global skills folder. Model and thinking (from public agy guides, 2026-11, not run here): --model <id> and --effort low|medium|high (added in 1.1.5; some guides add xhigh/max for API-key sign-in: add them to efforts in your agents.toml if your agy takes them). `agy models` lists the account's models (see [discover.agy] in models.default.toml)."
|
|
149
152
|
|
|
150
153
|
[pi]
|
|
151
154
|
binary = "pi"
|
|
Binary file
|
package/bin/orch
CHANGED
|
@@ -814,9 +814,59 @@ def split_effort(mid):
|
|
|
814
814
|
return mid, None
|
|
815
815
|
|
|
816
816
|
|
|
817
|
+
EFFORT_ORDER = ("off", "minimal", "low", "medium", "high", "xhigh", "max")
|
|
818
|
+
_EFFORT_TAIL = re.compile(r"^(.+?)[-_ ](minimal|low|medium|high|xhigh|max)$", re.I)
|
|
819
|
+
_NOT_A_MODEL = re.compile(r"(?i)sign[ -]?in|log[ -]?in|please|error|usage:|available models|^warning|\bcli\b|\bversion\b")
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def _slugify(name):
|
|
823
|
+
return re.sub(r"\s+", "-", name.strip()).strip("-").lower()
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def parse_model_lines(out):
|
|
827
|
+
"""A tool's model list printed as plain text (no JSON), one model per line, as `agy models` does:
|
|
828
|
+
`gemini-3.8-flash-high` (thinking level at the end of the id), `Gemini 3.1 Pro (High)` (level in brackets),
|
|
829
|
+
or `<id> <description>` (two spaces or a tab between). Bullets, headers, empty and sign-in lines are skipped.
|
|
830
|
+
Ids that differ only by thinking level become ONE model with the levels it was listed with, in list order."""
|
|
831
|
+
rows, by = [], {}
|
|
832
|
+
for raw in out.splitlines():
|
|
833
|
+
line = re.sub(r"^\s*(?:[-*\u2022>]|\d+[.)])\s+", "", raw).strip()
|
|
834
|
+
if not line or line.startswith("#") or line.endswith(":") or _NOT_A_MODEL.search(line):
|
|
835
|
+
continue
|
|
836
|
+
cols = re.split(r"\t+|\s{2,}|\s+[\u2014|]\s+", line, maxsplit=1)
|
|
837
|
+
name, desc = cols[0].strip(), (cols[1].strip() if len(cols) > 1 else "")
|
|
838
|
+
eff = None
|
|
839
|
+
m = re.fullmatch(r"(.+?)\s*\(([^()]+)\)", name)
|
|
840
|
+
if m:
|
|
841
|
+
name, tag = m.group(1), m.group(2).strip().lower()
|
|
842
|
+
if tag in EFFORT_ORDER:
|
|
843
|
+
eff = tag
|
|
844
|
+
else:
|
|
845
|
+
desc = (desc + " " + m.group(2)).strip()
|
|
846
|
+
if len(name.split()) > 5:
|
|
847
|
+
continue # a sentence, not a model name
|
|
848
|
+
slug = _slugify(name)
|
|
849
|
+
if not eff:
|
|
850
|
+
t = _EFFORT_TAIL.match(slug)
|
|
851
|
+
if t:
|
|
852
|
+
slug, eff = t.group(1), t.group(2).lower()
|
|
853
|
+
if not re.fullmatch(r"[a-z0-9][a-z0-9._/:+-]*", slug):
|
|
854
|
+
continue
|
|
855
|
+
if slug not in by:
|
|
856
|
+
by[slug] = {"slug": slug, "description": desc, "visibility": None, "upgrade": None, "priority": None,
|
|
857
|
+
"efforts": []}
|
|
858
|
+
rows.append(by[slug])
|
|
859
|
+
if eff and eff not in by[slug]["efforts"]:
|
|
860
|
+
by[slug]["efforts"].append(eff)
|
|
861
|
+
if desc and not by[slug]["description"]:
|
|
862
|
+
by[slug]["description"] = desc
|
|
863
|
+
return rows
|
|
864
|
+
|
|
865
|
+
|
|
817
866
|
def _tool_models(kind, cmd):
|
|
818
|
-
"""The models `cmd` lists ([{slug, description, visibility, upgrade, priority}]), or None.
|
|
819
|
-
|
|
867
|
+
"""The models `cmd` lists ([{slug, description, visibility, upgrade, priority, efforts}]), or None. JSON output
|
|
868
|
+
(`codex debug models`) or a plain list, one model per line (`agy models`, see parse_model_lines). The answer is
|
|
869
|
+
kept for DISCOVER_TTL_S in the share folder; an older answer is used when the command fails now."""
|
|
820
870
|
cache = share_dir() / f"models-{kind}.json"
|
|
821
871
|
try:
|
|
822
872
|
old = json.loads(cache.read_text())
|
|
@@ -827,12 +877,18 @@ def _tool_models(kind, cmd):
|
|
|
827
877
|
models = None
|
|
828
878
|
try:
|
|
829
879
|
r = subprocess.run(shlex.split(cmd), text=True, capture_output=True, timeout=20, stdin=subprocess.DEVNULL)
|
|
830
|
-
out = r.stdout
|
|
831
|
-
data =
|
|
880
|
+
out = r.stdout if r.returncode == 0 else ""
|
|
881
|
+
data = None
|
|
882
|
+
if "{" in out or out.lstrip().startswith("["):
|
|
883
|
+
with contextlib.suppress(ValueError):
|
|
884
|
+
start = min(i for i in (out.find("{"), out.find("[")) if i >= 0)
|
|
885
|
+
data = json.loads(out[start:])
|
|
832
886
|
rows = data.get("models") if isinstance(data, dict) else data
|
|
833
887
|
if isinstance(rows, list):
|
|
834
888
|
models = [{k: m.get(k) for k in ("slug", "description", "visibility", "upgrade", "priority")}
|
|
835
889
|
for m in rows if isinstance(m, dict) and isinstance(m.get("slug"), str)]
|
|
890
|
+
elif out.strip():
|
|
891
|
+
models = parse_model_lines(out)
|
|
836
892
|
except (OSError, ValueError, subprocess.TimeoutExpired):
|
|
837
893
|
models = None
|
|
838
894
|
if not models:
|
|
@@ -843,13 +899,33 @@ def _tool_models(kind, cmd):
|
|
|
843
899
|
return models
|
|
844
900
|
|
|
845
901
|
|
|
902
|
+
def _version_key(slug):
|
|
903
|
+
"""Higher version numbers first: gemini-4-hydrogen before gemini-3.8-flash (sorts as a negative tuple)."""
|
|
904
|
+
m = re.search(r"\d+(?:\.\d+)*", slug)
|
|
905
|
+
return tuple(-int(x) for x in m.group(0).split(".")) if m else (0,)
|
|
906
|
+
|
|
907
|
+
|
|
846
908
|
def newest_of(models, family):
|
|
847
|
-
"""The tool's preferred current model of a family (a word in its id): not hidden, not legacy
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
909
|
+
"""The tool's preferred current model of a family (a word in its id): not hidden, not legacy. A list that ranks
|
|
910
|
+
its models (Codex's priority) decides; else the highest version number in the id, then list order. `family`
|
|
911
|
+
may be a list: the first family the tool has wins (e.g. ["hydrogen", "pro"])."""
|
|
912
|
+
for fam in ([family] if isinstance(family, str) else list(family or [])):
|
|
913
|
+
cands = [(i, m) for i, m in enumerate(models) if str(fam).lower() in re.split(r"[-_.@/:]", m["slug"].lower())
|
|
914
|
+
and m.get("visibility") != "hide" and not m.get("upgrade")
|
|
915
|
+
and not LEGACY_RE.search(m.get("description") or "")]
|
|
916
|
+
prio = lambda m: m["priority"] if isinstance(m.get("priority"), (int, float)) else 1e9
|
|
917
|
+
best = min(cands, key=lambda im: (prio(im[1]), _version_key(im[1]["slug"]), im[0]), default=None)
|
|
918
|
+
if best:
|
|
919
|
+
return best[1]
|
|
920
|
+
return None
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def nearest_effort(want, listed):
|
|
924
|
+
"""The thinking level to use: `want`, or when the tool listed the model only on other levels, the closest one."""
|
|
925
|
+
if not want or not listed or want in listed:
|
|
926
|
+
return want
|
|
927
|
+
order = {e: i for i, e in enumerate(EFFORT_ORDER)}
|
|
928
|
+
return min(listed, key=lambda e: (abs(order.get(e, 3) - order.get(want, 3)), -order.get(e, 3)))
|
|
853
929
|
|
|
854
930
|
|
|
855
931
|
def discover_models(cat):
|
|
@@ -878,12 +954,23 @@ def discover_models(cat):
|
|
|
878
954
|
m = newest_of(models, want["family"])
|
|
879
955
|
if not m:
|
|
880
956
|
continue
|
|
881
|
-
|
|
882
|
-
|
|
957
|
+
eff = nearest_effort(want.get("effort"), m.get("efforts") or [])
|
|
958
|
+
mid = m["slug"].lower() + (f"@{eff}" if eff else "")
|
|
959
|
+
if mid in made: # the same model and level already fills a lower level: one level per model
|
|
960
|
+
continue
|
|
961
|
+
like = next((x for x in shipped.values() if str(x.get("tier", "")).lower() == level), None)
|
|
962
|
+
src = f"the shipped {level} entry"
|
|
963
|
+
if like is None: # a kind with no shipped entries (agy): borrow the ratings of a model of this level
|
|
964
|
+
other = next(((oid, x) for oid, x in cat["models"].items() if not x.get("found")
|
|
965
|
+
and str(x.get("tier", "")).lower() == level and not x.get("open_weights")), None)
|
|
966
|
+
like, src = (other[1], f"{other[0]} (same level, another tool)") if other else ({}, "nowhere (unrated)")
|
|
967
|
+
like = {k: v for k, v in like.items() if k not in ("context_k", "open_weights")}
|
|
968
|
+
fams = [want["family"]] if isinstance(want["family"], str) else list(want["family"])
|
|
969
|
+
fam = next((f for f in fams if str(f).lower() in re.split(r"[-_.@/:]", m["slug"].lower())), fams[0])
|
|
883
970
|
made[mid] = dict(like, kinds=[kind], tier=level, found=True, evidence=(
|
|
884
|
-
f"found by `{cmd}`: \"{(m.get('description') or '').strip()}\". {level} level = the newest "
|
|
885
|
-
f"{
|
|
886
|
-
+ f" ([discover.{kind}]). Ratings copied from
|
|
971
|
+
f"found by `{cmd}`: \"{(m.get('description') or m['slug']).strip()}\". {level} level = the newest "
|
|
972
|
+
f"{fam} model" + (f" on {eff} thinking" if eff else "")
|
|
973
|
+
+ f" ([discover.{kind}]). Ratings copied from {src}; not benchmarked here."))
|
|
887
974
|
used.add(m["slug"])
|
|
888
975
|
if not made:
|
|
889
976
|
continue
|
|
@@ -2236,7 +2323,6 @@ RESULT_FORMAT = {
|
|
|
2236
2323
|
"check": {"ran": True, "passed": True, "summary": "lint ok, 42 tests pass"},
|
|
2237
2324
|
"criteria": [{"id": "AC1", "met": True, "evidence": "test 'rejects a missing amount column' passes"}],
|
|
2238
2325
|
"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
2326
|
"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
2327
|
}
|
|
2242
2328
|
REVIEW_FORMAT = {
|
|
@@ -2272,10 +2358,473 @@ def read_result(path):
|
|
|
2272
2358
|
return d, None
|
|
2273
2359
|
|
|
2274
2360
|
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2361
|
+
# ---- token usage, read from each tool's OWN session log (6.33.0). Nothing is guessed: a job whose log orch can't
|
|
2362
|
+
# find or read gets {"na": "<why>"} and shows as "not available (<why>)". In = everything the agent read (cached
|
|
2363
|
+
# included), cached = the part it re-read from its own chat, out = everything it wrote (thinking included).
|
|
2364
|
+
TOKEN_GRACE_S = int(os.environ.get("ORCH_TOKEN_GRACE_S", "20")) # let the tool write its last reply first
|
|
2365
|
+
TOKEN_GIVE_UP_S = int(os.environ.get("ORCH_TOKEN_GIVE_UP_S", "600")) # no log after this: "not available"
|
|
2366
|
+
TOKEN_KINDS = ("claude", "codex", "pi", "agy")
|
|
2367
|
+
|
|
2368
|
+
|
|
2369
|
+
class TokenNA(Exception):
|
|
2370
|
+
"""Why this job's tokens are not available (shown to the developer as is)."""
|
|
2371
|
+
|
|
2372
|
+
|
|
2373
|
+
def token_roots(kind):
|
|
2374
|
+
"""Where each tool keeps its session logs (each tool's own setting first)."""
|
|
2375
|
+
home = Path.home()
|
|
2376
|
+
test = os.environ.get("ORCH_TOKEN_HOME") # tests: every tool's logs under one folder, never the real ones
|
|
2377
|
+
if test:
|
|
2378
|
+
return [Path(test) / {"claude": "claude/projects", "codex": "codex/sessions", "pi": "pi/sessions",
|
|
2379
|
+
"agy": "agy/brain"}.get(kind, kind)]
|
|
2380
|
+
if kind == "claude":
|
|
2381
|
+
return [Path(os.environ.get("CLAUDE_CONFIG_DIR") or home / ".claude") / "projects"]
|
|
2382
|
+
if kind == "codex":
|
|
2383
|
+
return [Path(os.environ.get("CODEX_HOME") or home / ".codex") / "sessions"]
|
|
2384
|
+
if kind == "pi":
|
|
2385
|
+
return [Path(os.environ.get("PI_CODING_AGENT_SESSION_DIR") or home / ".pi" / "agent" / "sessions")]
|
|
2386
|
+
if kind == "agy":
|
|
2387
|
+
return [home / ".gemini" / "antigravity-cli" / "brain"]
|
|
2388
|
+
return []
|
|
2389
|
+
|
|
2390
|
+
|
|
2391
|
+
TOKEN_GLOBS = {"claude": "*/*.jsonl", "codex": "**/rollout-*.jsonl*", "pi": "*/*.jsonl",
|
|
2392
|
+
"agy": "*/.system_generated/logs/transcript_full.jsonl"}
|
|
2393
|
+
|
|
2394
|
+
|
|
2395
|
+
def _tok_text(path):
|
|
2396
|
+
p = str(path)
|
|
2397
|
+
if p.endswith(".zst"):
|
|
2398
|
+
if not shutil.which("zstd"):
|
|
2399
|
+
raise TokenNA("the log is compressed (.zst) and the `zstd` tool is not installed")
|
|
2400
|
+
r = subprocess.run(["zstd", "-dcq", p], capture_output=True, timeout=120)
|
|
2401
|
+
if r.returncode:
|
|
2402
|
+
raise TokenNA("the compressed log could not be unpacked")
|
|
2403
|
+
return r.stdout.decode("utf-8", "replace")
|
|
2404
|
+
try:
|
|
2405
|
+
return Path(p).read_text(errors="replace")
|
|
2406
|
+
except OSError:
|
|
2407
|
+
raise TokenNA("the log could not be read")
|
|
2408
|
+
|
|
2409
|
+
|
|
2410
|
+
def _tok_rows(text):
|
|
2411
|
+
for ln in text.splitlines():
|
|
2412
|
+
if not ln.startswith("{"):
|
|
2413
|
+
continue
|
|
2414
|
+
try:
|
|
2415
|
+
d = json.loads(ln)
|
|
2416
|
+
except ValueError:
|
|
2417
|
+
continue
|
|
2418
|
+
if isinstance(d, dict):
|
|
2419
|
+
yield d
|
|
2420
|
+
|
|
2421
|
+
|
|
2422
|
+
def _tok_ts(v):
|
|
2423
|
+
"""A log timestamp (ISO text, or epoch seconds / milliseconds) as epoch seconds, or None."""
|
|
2424
|
+
if isinstance(v, bool):
|
|
2425
|
+
return None
|
|
2426
|
+
if isinstance(v, (int, float)):
|
|
2427
|
+
return v / 1000 if v > 1e11 else float(v)
|
|
2428
|
+
if isinstance(v, str) and v:
|
|
2429
|
+
import datetime as _dt
|
|
2430
|
+
try:
|
|
2431
|
+
t = _dt.datetime.fromisoformat(v.strip().replace("Z", "+00:00"))
|
|
2432
|
+
except ValueError:
|
|
2433
|
+
return None
|
|
2434
|
+
return (t if t.tzinfo else t.replace(tzinfo=_dt.timezone.utc)).timestamp()
|
|
2435
|
+
return None
|
|
2436
|
+
|
|
2437
|
+
|
|
2438
|
+
def _tok_str(c):
|
|
2439
|
+
"""Message content (a string, or a list of text parts) as one string."""
|
|
2440
|
+
if isinstance(c, str):
|
|
2441
|
+
return c
|
|
2442
|
+
if isinstance(c, list):
|
|
2443
|
+
return "\n".join(_tok_str(x.get("text") if isinstance(x, dict) else x) for x in c)
|
|
2444
|
+
return ""
|
|
2445
|
+
|
|
2446
|
+
|
|
2447
|
+
def _tok_user_text(kind, d):
|
|
2448
|
+
"""What the PERSON (here: orch typing into the pane) said in this log line, else ""."""
|
|
2449
|
+
if kind == "claude":
|
|
2450
|
+
if d.get("type") == "user" and not d.get("toolUseResult") and isinstance(d.get("message"), dict):
|
|
2451
|
+
c = d["message"].get("content")
|
|
2452
|
+
if isinstance(c, list) and any(isinstance(x, dict) and x.get("type") == "tool_result" for x in c):
|
|
2453
|
+
return ""
|
|
2454
|
+
return _tok_str(c)
|
|
2455
|
+
elif kind == "codex":
|
|
2456
|
+
p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
|
|
2457
|
+
if d.get("type") == "event_msg" and p.get("type") == "user_message":
|
|
2458
|
+
return _tok_str(p.get("message"))
|
|
2459
|
+
if d.get("type") == "response_item" and p.get("role") == "user":
|
|
2460
|
+
return _tok_str(p.get("content"))
|
|
2461
|
+
elif kind == "pi":
|
|
2462
|
+
m = d.get("message") if isinstance(d.get("message"), dict) else {}
|
|
2463
|
+
if d.get("type") == "message" and m.get("role") == "user":
|
|
2464
|
+
return _tok_str(m.get("content"))
|
|
2465
|
+
elif kind == "agy":
|
|
2466
|
+
if d.get("source") == "USER_EXPLICIT" or d.get("type") == "USER_INPUT":
|
|
2467
|
+
return _tok_str(d.get("content"))
|
|
2468
|
+
return ""
|
|
2469
|
+
|
|
2470
|
+
|
|
2471
|
+
def token_log_has(kind, path, marker):
|
|
2472
|
+
"""True when orch's own prompt with this marker is a user message in the log."""
|
|
2473
|
+
try:
|
|
2474
|
+
text = _tok_text(path)
|
|
2475
|
+
except TokenNA:
|
|
2476
|
+
return False
|
|
2477
|
+
if marker not in text:
|
|
2478
|
+
return False
|
|
2479
|
+
return any(marker in _tok_user_text(kind, d) for d in _tok_rows(text))
|
|
2480
|
+
|
|
2481
|
+
|
|
2482
|
+
def token_log_find(kind, marker, since, known=()):
|
|
2483
|
+
"""The session log of `kind` in which orch typed the prompt holding `marker` (unique per job), or None. Logs
|
|
2484
|
+
orch already tied to this pane are tried first; then every log of that tool changed since the job started."""
|
|
2485
|
+
for p in known:
|
|
2486
|
+
if Path(p).exists() and token_log_has(kind, p, marker):
|
|
2487
|
+
return str(p)
|
|
2488
|
+
cands = []
|
|
2489
|
+
for r in token_roots(kind):
|
|
2490
|
+
if not r.is_dir():
|
|
2491
|
+
continue
|
|
2492
|
+
for p in r.glob(TOKEN_GLOBS.get(kind, "*.jsonl")):
|
|
2493
|
+
try:
|
|
2494
|
+
mt = p.stat().st_mtime
|
|
2495
|
+
except OSError:
|
|
2496
|
+
continue
|
|
2497
|
+
if mt >= since - 5 and str(p) not in known:
|
|
2498
|
+
cands.append((mt, p))
|
|
2499
|
+
for _, p in sorted(cands, reverse=True):
|
|
2500
|
+
if token_log_has(kind, p, marker):
|
|
2501
|
+
return str(p)
|
|
2502
|
+
return None
|
|
2503
|
+
|
|
2504
|
+
|
|
2505
|
+
def _tok_add(acc, ts, start, end, inp, cached, out):
|
|
2506
|
+
if ts is None or ts < start or ts > end:
|
|
2507
|
+
return
|
|
2508
|
+
acc["in"] += int(inp or 0)
|
|
2509
|
+
acc["cached"] += int(cached or 0)
|
|
2510
|
+
acc["out"] += int(out or 0)
|
|
2511
|
+
acc["replies"] += 1
|
|
2512
|
+
|
|
2513
|
+
|
|
2514
|
+
def token_window(kind, path, start, end):
|
|
2515
|
+
"""Tokens one session log used between start and end (epoch seconds): {"in", "cached", "out", "replies"}.
|
|
2516
|
+
Raises TokenNA when the log has no token counts at all."""
|
|
2517
|
+
acc = {"in": 0, "cached": 0, "out": 0, "replies": 0}
|
|
2518
|
+
text = _tok_text(path)
|
|
2519
|
+
seen_counts = False
|
|
2520
|
+
if kind == "claude":
|
|
2521
|
+
files = [text] + [_tok_text(s) for s in sorted((Path(path).with_suffix("") / "subagents").glob("*.jsonl"))]
|
|
2522
|
+
for tx in files:
|
|
2523
|
+
msgs = {} # one reply is often written as several lines with the same message id
|
|
2524
|
+
for d in _tok_rows(tx):
|
|
2525
|
+
m = d.get("message") if isinstance(d.get("message"), dict) else {}
|
|
2526
|
+
u = m.get("usage")
|
|
2527
|
+
if d.get("type") != "assistant" or not isinstance(u, dict):
|
|
2528
|
+
continue
|
|
2529
|
+
seen_counts = True
|
|
2530
|
+
key = (m.get("id"), d.get("requestId")) if m.get("id") else d.get("uuid") or id(d)
|
|
2531
|
+
ts = _tok_ts(d.get("timestamp"))
|
|
2532
|
+
row = (int(u.get("input_tokens") or 0) + int(u.get("cache_creation_input_tokens") or 0)
|
|
2533
|
+
+ int(u.get("cache_read_input_tokens") or 0), int(u.get("cache_read_input_tokens") or 0),
|
|
2534
|
+
int(u.get("output_tokens") or 0))
|
|
2535
|
+
old = msgs.get(key)
|
|
2536
|
+
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)
|
|
2537
|
+
for ts, (i, c, o) in msgs.values():
|
|
2538
|
+
_tok_add(acc, ts, start, end, i, c, o)
|
|
2539
|
+
elif kind == "codex":
|
|
2540
|
+
before = last = None # Codex writes a running total: the job's share is end total - start total
|
|
2541
|
+
for d in _tok_rows(text):
|
|
2542
|
+
p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
|
|
2543
|
+
if d.get("type") != "event_msg" or p.get("type") != "token_count":
|
|
2544
|
+
continue
|
|
2545
|
+
tot = (p.get("info") or {}).get("total_token_usage") if isinstance(p.get("info"), dict) else None
|
|
2546
|
+
if not isinstance(tot, dict):
|
|
2547
|
+
continue
|
|
2548
|
+
seen_counts = True
|
|
2549
|
+
ts = _tok_ts(d.get("timestamp"))
|
|
2550
|
+
if ts is None:
|
|
2551
|
+
continue
|
|
2552
|
+
row = (int(tot.get("input_tokens") or 0), int(tot.get("cached_input_tokens") or 0),
|
|
2553
|
+
int(tot.get("output_tokens") or 0))
|
|
2554
|
+
if ts < start:
|
|
2555
|
+
before = row
|
|
2556
|
+
elif ts <= end:
|
|
2557
|
+
if last is not None and row != last:
|
|
2558
|
+
acc["replies"] += 1
|
|
2559
|
+
elif last is None:
|
|
2560
|
+
acc["replies"] += 1
|
|
2561
|
+
last = row
|
|
2562
|
+
if last is not None:
|
|
2563
|
+
b = before or (0, 0, 0)
|
|
2564
|
+
acc.update({"in": max(0, last[0] - b[0]), "cached": max(0, last[1] - b[1]), "out": max(0, last[2] - b[2])})
|
|
2565
|
+
elif kind == "pi":
|
|
2566
|
+
for d in _tok_rows(text):
|
|
2567
|
+
m = d.get("message") if isinstance(d.get("message"), dict) else {}
|
|
2568
|
+
u = m.get("usage") if d.get("type") == "message" and m.get("role") == "assistant" else d.get("usage")
|
|
2569
|
+
if not isinstance(u, dict) or d.get("type") == "message" and m.get("role") != "assistant":
|
|
2570
|
+
continue
|
|
2571
|
+
seen_counts = True
|
|
2572
|
+
_tok_add(acc, _tok_ts(d.get("timestamp")) or _tok_ts(m.get("timestamp")), start, end,
|
|
2573
|
+
int(u.get("input") or 0) + int(u.get("cacheRead") or 0) + int(u.get("cacheWrite") or 0),
|
|
2574
|
+
u.get("cacheRead"), u.get("output"))
|
|
2575
|
+
elif kind == "agy":
|
|
2576
|
+
steps = 0
|
|
2577
|
+
for d in _tok_rows(text):
|
|
2578
|
+
if d.get("source") == "MODEL" or d.get("type") == "PLANNER_RESPONSE":
|
|
2579
|
+
steps += 1
|
|
2580
|
+
if not any(k in d for k in ("input_tokens", "output_tokens")):
|
|
2581
|
+
continue
|
|
2582
|
+
seen_counts = True
|
|
2583
|
+
_tok_add(acc, _tok_ts(d.get("created_at")), start, end,
|
|
2584
|
+
int(d.get("input_tokens") or 0) + int(d.get("cache_read_tokens") or 0),
|
|
2585
|
+
d.get("cache_read_tokens"), d.get("output_tokens"))
|
|
2586
|
+
if steps and not seen_counts:
|
|
2587
|
+
raise TokenNA("this agy version saves no token counts (update agy)")
|
|
2588
|
+
else:
|
|
2589
|
+
raise TokenNA(f"orch can't read {kind}'s logs")
|
|
2590
|
+
if not seen_counts:
|
|
2591
|
+
raise TokenNA(f"{kind}'s log has no token counts")
|
|
2592
|
+
return acc
|
|
2593
|
+
|
|
2594
|
+
|
|
2595
|
+
def agent_kind_of(st, agent):
|
|
2596
|
+
if (st.get("lead") or {}).get("name") == agent:
|
|
2597
|
+
return st["lead"].get("kind")
|
|
2598
|
+
if agent and agent == st.get("reviewer"):
|
|
2599
|
+
return (st.get("reviewer_info") or {}).get("kind")
|
|
2600
|
+
return (st.get("workers", {}).get(agent) or {}).get("kind")
|
|
2601
|
+
|
|
2602
|
+
|
|
2603
|
+
def token_marker(prompt):
|
|
2604
|
+
"""The part of orch's job prompt that is unique to that one job: the result or review file it names."""
|
|
2605
|
+
m = re.search(r"[\w./-]*(?:result-\d+\.json|review-task-\d+\.md)", prompt or "")
|
|
2606
|
+
return m.group(0) if m else None
|
|
2607
|
+
|
|
2608
|
+
|
|
2609
|
+
def token_measure(st, agent, kind, marker, start, end, cap=None):
|
|
2610
|
+
"""{"in", "cached", "out", "log"} for one job, or {"na": why}, or None (not written yet: try again later)."""
|
|
2611
|
+
if not kind:
|
|
2612
|
+
return {"na": "orch does not know which tool this agent runs"}
|
|
2613
|
+
if kind not in TOKEN_KINDS:
|
|
2614
|
+
return {"na": f"orch can't read {kind}'s logs"}
|
|
2615
|
+
if not marker:
|
|
2616
|
+
return {"na": "no job prompt to find the log by"}
|
|
2617
|
+
logs = st.setdefault("token_logs", {})
|
|
2618
|
+
known = logs.get(agent) or []
|
|
2619
|
+
try:
|
|
2620
|
+
path = token_log_find(kind, marker, start, known)
|
|
2621
|
+
if not path:
|
|
2622
|
+
return None if now() - end < TOKEN_GIVE_UP_S else {"na": f"no {kind} log has this job's prompt"}
|
|
2623
|
+
acc = token_window(kind, path, start, min(end + TOKEN_GRACE_S, cap or float("inf")))
|
|
2624
|
+
except TokenNA as e:
|
|
2625
|
+
return {"na": str(e)}
|
|
2626
|
+
if path not in known:
|
|
2627
|
+
logs[agent] = (known + [path])[-6:]
|
|
2628
|
+
if not acc["replies"]:
|
|
2629
|
+
return None if now() - end < TOKEN_GIVE_UP_S else {"na": "no replies in the log during this job"}
|
|
2630
|
+
return {"in": acc["in"], "cached": acc["cached"], "out": acc["out"], "log": kind}
|
|
2631
|
+
|
|
2632
|
+
|
|
2633
|
+
def token_fill(st, force=False):
|
|
2634
|
+
"""Read the tokens of every finished job that has none yet (each tool's log, read only). True if any changed.
|
|
2635
|
+
`force` (summary, report): don't wait for the grace time and give up on logs that are not there."""
|
|
2636
|
+
changed = False
|
|
2637
|
+
starts = {} # the agent's next job starts where this one's window must end
|
|
2638
|
+
for t in st.get("tasks", {}).values():
|
|
2639
|
+
for a in t.get("attempts") or []:
|
|
2640
|
+
starts.setdefault(a.get("agent"), []).append(a.get("start", 0))
|
|
2641
|
+
for w in st.get("tasks", {}).values():
|
|
2642
|
+
if w.get("wait"):
|
|
2643
|
+
starts.setdefault(w["wait"].get("agent"), []).append(w["wait"].get("started", w["wait"].get("since", 0)))
|
|
2644
|
+
for tid in st.get("order", []):
|
|
2645
|
+
for a in (st["tasks"].get(tid) or {}).get("attempts") or []:
|
|
2646
|
+
if "tokens" in a or not a.get("tok_marker"):
|
|
2647
|
+
continue
|
|
2648
|
+
if not force and now() - a.get("end", 0) < TOKEN_GRACE_S:
|
|
2649
|
+
continue
|
|
2650
|
+
r = token_measure(st, a.get("agent"), a.get("tok_kind") or agent_kind_of(st, a.get("agent")),
|
|
2651
|
+
a["tok_marker"], a.get("start", 0), a.get("end", now()),
|
|
2652
|
+
min([x for x in starts.get(a.get("agent"), []) if x > a.get("start", 0)] or [None],
|
|
2653
|
+
key=lambda x: x or float("inf")))
|
|
2654
|
+
if r is not None:
|
|
2655
|
+
a["tokens"] = r
|
|
2656
|
+
changed = True
|
|
2657
|
+
return changed
|
|
2658
|
+
|
|
2659
|
+
|
|
2660
|
+
def token_fill_saved():
|
|
2661
|
+
"""token_fill on the saved state, under the state lock (orch report, orch tokens, orch view)."""
|
|
2662
|
+
if not STATE.exists():
|
|
2663
|
+
return
|
|
2664
|
+
try:
|
|
2665
|
+
with state_lock():
|
|
2666
|
+
st = load()
|
|
2667
|
+
if token_fill(st, force=True):
|
|
2668
|
+
save(st)
|
|
2669
|
+
except Exception as e: # a strange log never stops a report
|
|
2670
|
+
print(f"(token count skipped: {e})", file=sys.stderr)
|
|
2671
|
+
|
|
2672
|
+
|
|
2673
|
+
def lead_tokens(st):
|
|
2674
|
+
"""The lead's tokens from the run's start to its end (or now), found by orch's wake-up text."""
|
|
2675
|
+
ld, run = st.get("lead") or {}, st.get("run") or {}
|
|
2676
|
+
if not ld.get("name"):
|
|
2677
|
+
return None
|
|
2678
|
+
if not run.get("started"):
|
|
2679
|
+
return {"na": "the run has not started"}
|
|
2680
|
+
marker = f"in the run on {st.get('branch')} need the lead"
|
|
2681
|
+
r = token_measure(st, ld["name"], ld.get("kind"), marker, run["started"], run.get("ended") or now()) \
|
|
2682
|
+
or {"na": "the lead was never woken by orch, so its log can't be told apart"}
|
|
2683
|
+
saved = run.get("lead_tokens") # read at ALL_DONE: still good if the tool deleted the log since
|
|
2684
|
+
return saved if "na" in r and isinstance(saved, dict) and "na" not in saved else r
|
|
2685
|
+
|
|
2686
|
+
|
|
2687
|
+
def between_tokens(st, account_rows):
|
|
2688
|
+
"""Tokens agents used outside every job window during the run (their /compact, the developer typing into the
|
|
2689
|
+
pane between jobs): the logs' run total minus what the jobs got."""
|
|
2690
|
+
run = st.get("run") or {}
|
|
2691
|
+
if not run.get("started"):
|
|
2692
|
+
return None
|
|
2693
|
+
start, end = run["started"], run.get("ended") or now()
|
|
2694
|
+
total = {"in": 0, "cached": 0, "out": 0}
|
|
2695
|
+
got = {"in": 0, "cached": 0, "out": 0}
|
|
2696
|
+
lead = (st.get("lead") or {}).get("name")
|
|
2697
|
+
for agent, paths in (st.get("token_logs") or {}).items():
|
|
2698
|
+
if agent == lead:
|
|
2699
|
+
continue
|
|
2700
|
+
kind = agent_kind_of(st, agent)
|
|
2701
|
+
for p in paths:
|
|
2702
|
+
try:
|
|
2703
|
+
w = token_window(kind, p, start, end)
|
|
2704
|
+
except TokenNA:
|
|
2705
|
+
return None
|
|
2706
|
+
for k in total:
|
|
2707
|
+
total[k] += w[k]
|
|
2708
|
+
for r in account_rows:
|
|
2709
|
+
for part in ("coder", "review"):
|
|
2710
|
+
u = r[part]
|
|
2711
|
+
if u and "na" not in u:
|
|
2712
|
+
for k in got:
|
|
2713
|
+
got[k] += u[k]
|
|
2714
|
+
out = {k: max(0, total[k] - got[k]) for k in total}
|
|
2715
|
+
return out if any(out.values()) else None
|
|
2716
|
+
|
|
2717
|
+
|
|
2718
|
+
def _tok_merge(rows):
|
|
2719
|
+
"""Add up job token rows: {"in", "cached", "out", "jobs", "na": [why, ...]} or None for no jobs."""
|
|
2720
|
+
if not rows:
|
|
2721
|
+
return None
|
|
2722
|
+
acc = {"in": 0, "cached": 0, "out": 0, "jobs": 0, "known": 0, "na": []}
|
|
2723
|
+
for u in rows:
|
|
2724
|
+
acc["jobs"] += 1
|
|
2725
|
+
if not isinstance(u, dict) or "na" in u:
|
|
2726
|
+
acc["na"].append((u or {}).get("na") if isinstance(u, dict) else "not read yet")
|
|
2727
|
+
continue
|
|
2728
|
+
acc["known"] += 1
|
|
2729
|
+
for k in ("in", "cached", "out"):
|
|
2730
|
+
acc[k] += int(u.get(k) or 0)
|
|
2731
|
+
return acc
|
|
2732
|
+
|
|
2733
|
+
|
|
2734
|
+
_TOK_CACHE = {}
|
|
2735
|
+
|
|
2736
|
+
|
|
2737
|
+
def _tok_cached(key, fn, ttl=60):
|
|
2738
|
+
"""For the live board and view: read the logs at most once a minute."""
|
|
2739
|
+
hit = _TOK_CACHE.get(key)
|
|
2740
|
+
if hit and time.time() - hit[0] < ttl:
|
|
2741
|
+
return hit[1]
|
|
2742
|
+
v = fn()
|
|
2743
|
+
_TOK_CACHE[key] = (time.time(), v)
|
|
2744
|
+
return v
|
|
2745
|
+
|
|
2746
|
+
|
|
2747
|
+
def token_account(st, live=False):
|
|
2748
|
+
"""Tokens per milestone (coder jobs, review rounds), the lead, between jobs and the total. Only what the logs
|
|
2749
|
+
said: a milestone with a job whose log was missing is marked so the total reads "at least"."""
|
|
2750
|
+
rows = []
|
|
2751
|
+
for tid in st.get("order", []):
|
|
2752
|
+
t = st["tasks"][tid]
|
|
2753
|
+
if t.get("status") == "skipped":
|
|
2754
|
+
continue
|
|
2755
|
+
at = [a for a in t.get("attempts") or [] if isinstance(a, dict)]
|
|
2756
|
+
at = [a for a in at if a.get("tok_marker") or a.get("tokens")] # jobs that were really sent
|
|
2757
|
+
co = [a for a in at if a.get("kind") != "reviewer"]
|
|
2758
|
+
rv = [a for a in at if a.get("kind") == "reviewer"]
|
|
2759
|
+
fixes = [a for a in co if a.get("file") and a["file"] != "task.md"]
|
|
2760
|
+
rows.append({"task": tid, "title": t.get("title") or tid,
|
|
2761
|
+
"coders": list(dict.fromkeys(a.get("agent") for a in co if a.get("agent"))),
|
|
2762
|
+
"reviewers": list(dict.fromkeys(a.get("agent") for a in rv if a.get("agent"))),
|
|
2763
|
+
"coder": _tok_merge([a.get("tokens") for a in co]),
|
|
2764
|
+
"fixes": _tok_merge([a.get("tokens") for a in fixes]),
|
|
2765
|
+
"review": _tok_merge([a.get("tokens") for a in rv])})
|
|
2766
|
+
if live: # board / view redraw often: lead once a minute, "between jobs" only in the summary
|
|
2767
|
+
lead = _tok_cached(("lead", st.get("branch")), lambda: lead_tokens(json.loads(json.dumps(st)))) \
|
|
2768
|
+
if st.get("lead") else None
|
|
2769
|
+
between = None
|
|
2770
|
+
else:
|
|
2771
|
+
lead = lead_tokens(st) if st.get("lead") else None
|
|
2772
|
+
between = between_tokens(st, rows)
|
|
2773
|
+
total, partial = 0, False
|
|
2774
|
+
for r in rows:
|
|
2775
|
+
r["total"] = sum(r[p]["in"] + r[p]["out"] for p in ("coder", "review") if r[p])
|
|
2776
|
+
r["partial"] = any(r[p] and r[p]["na"] for p in ("coder", "review"))
|
|
2777
|
+
total += r["total"]
|
|
2778
|
+
partial |= r["partial"]
|
|
2779
|
+
if lead and "na" not in lead:
|
|
2780
|
+
total += lead["in"] + lead["out"]
|
|
2781
|
+
elif lead:
|
|
2782
|
+
partial = True
|
|
2783
|
+
if between:
|
|
2784
|
+
total += between["in"] + between["out"]
|
|
2785
|
+
return {"tasks": rows, "lead": lead, "between": between, "total": total, "partial": partial}
|
|
2786
|
+
|
|
2787
|
+
|
|
2788
|
+
def _tk(n):
|
|
2789
|
+
n = int(n or 0)
|
|
2790
|
+
return f"{n / 1e6:.1f}M" if n >= 1_000_000 else f"{round(n / 1000)}k" if n >= 1000 else str(n)
|
|
2791
|
+
|
|
2792
|
+
|
|
2793
|
+
def _tok_cell(u, who=""):
|
|
2794
|
+
if not u:
|
|
2795
|
+
return "-"
|
|
2796
|
+
if not u["known"]:
|
|
2797
|
+
return f"not available ({u['na'][0]})"
|
|
2798
|
+
s = f"{_tk(u['in'] + u['out'])} (in {_tk(u['in'])}, of which {_tk(u['cached'])} cached; out {_tk(u['out'])})"
|
|
2799
|
+
if u["na"]:
|
|
2800
|
+
s += f" + {len(u['na'])} job(s) not available ({u['na'][0]})"
|
|
2801
|
+
return s + (f" {who}" if who else "")
|
|
2802
|
+
|
|
2803
|
+
|
|
2804
|
+
def token_lines(acct):
|
|
2805
|
+
"""Tokens per milestone as markdown."""
|
|
2806
|
+
out = ["| Milestone | Built by | Coder tokens | Review tokens | Total |", "|---|---|---|---|---|"]
|
|
2807
|
+
for r in acct["tasks"]:
|
|
2808
|
+
fx = r["fixes"]
|
|
2809
|
+
coder = _tok_cell(r["coder"]) + (f"; fixes {_tk(fx['in'] + fx['out'])}" if fx and fx["known"] else "")
|
|
2810
|
+
out.append(f"| {r['task']} {r['title']} | {', '.join(r['coders']) or '-'} | {coder} | "
|
|
2811
|
+
f"{_tok_cell(r['review'], '(' + ', '.join(r['reviewers']) + ')' if r['reviewers'] else '')} | "
|
|
2812
|
+
f"{_tk(r['total'])}{'+' if r['partial'] else ''} |")
|
|
2813
|
+
ld = acct["lead"]
|
|
2814
|
+
if ld:
|
|
2815
|
+
out.append("| Lead (whole run) | | " + (f"not available ({ld['na']})" if "na" in ld else
|
|
2816
|
+
f"{_tk(ld['in'] + ld['out'])} (in {_tk(ld['in'])}, of which {_tk(ld['cached'])} cached; out "
|
|
2817
|
+
f"{_tk(ld['out'])})") + f" | | {'-' if 'na' in ld else _tk(ld['in'] + ld['out'])} |")
|
|
2818
|
+
bt = acct["between"]
|
|
2819
|
+
if bt:
|
|
2820
|
+
out.append(f"| Between jobs (/compact, typing in a pane) | | {_tk(bt['in'] + bt['out'])} | | "
|
|
2821
|
+
f"{_tk(bt['in'] + bt['out'])} |")
|
|
2822
|
+
out.append(f"| **Total** | | | | **{_tk(acct['total'])}{'+' if acct['partial'] else ''}** |")
|
|
2823
|
+
out += ["", "Read from each agent's own log. In = what the agent read (its chat included; the cached part is its "
|
|
2824
|
+
"own chat read again, much cheaper), out = what it wrote."]
|
|
2825
|
+
if acct["partial"]:
|
|
2826
|
+
out.append("`+` = some jobs' tokens are not available (reason in the row), so the real number is higher.")
|
|
2827
|
+
return out
|
|
2279
2828
|
|
|
2280
2829
|
|
|
2281
2830
|
def finding_axis(f):
|
|
@@ -2996,6 +3545,9 @@ def record_attempt(t, outcome, usage=None):
|
|
|
2996
3545
|
a["blocked_s"] = min(blocked, a["secs"]) # time herdr showed the agent stopped at a prompt in its pane
|
|
2997
3546
|
if usage:
|
|
2998
3547
|
a["usage"] = usage
|
|
3548
|
+
mk = token_marker(w.get("prompt")) if outcome != "not delivered" else None
|
|
3549
|
+
if mk:
|
|
3550
|
+
a["tok_marker"] = mk # the job's own prompt: how orch finds its tokens in the tool's log
|
|
2999
3551
|
t.setdefault("attempts", []).append(a)
|
|
3000
3552
|
del t["attempts"][:-100]
|
|
3001
3553
|
|
|
@@ -3378,7 +3930,7 @@ def cmd_poll(args):
|
|
|
3378
3930
|
agent, sentinel = w["agent"], Path(w["sentinel"])
|
|
3379
3931
|
age = now() - w["since"]
|
|
3380
3932
|
if sentinel.exists():
|
|
3381
|
-
record_attempt(t, "done"
|
|
3933
|
+
record_attempt(t, "done")
|
|
3382
3934
|
if w["kind"] == "coder":
|
|
3383
3935
|
move(st, tid, "verifying")
|
|
3384
3936
|
t["last_report"] = w["report"]
|
|
@@ -5023,7 +5575,7 @@ WORKER_RULES = """## Rules for you (the coder)
|
|
|
5023
5575
|
- Do NOT commit, push, or switch branches. orch commits your work for you.
|
|
5024
5576
|
- 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
5577
|
- 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`)
|
|
5578
|
+
- 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
5579
|
- 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
5580
|
- 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
5581
|
- 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 +7412,22 @@ def _autopilot(args):
|
|
|
6860
7412
|
return s_["workers"].get(name) if name in s_.get("workers", {}) else \
|
|
6861
7413
|
(s_.get("reviewer_info") if name == s_.get("reviewer") else None)
|
|
6862
7414
|
|
|
7415
|
+
tok_tick = [0.0]
|
|
7416
|
+
|
|
7417
|
+
def tend_tokens():
|
|
7418
|
+
"""Read the tokens of jobs that finished (each tool's own log, read only) soon after they end, so the numbers
|
|
7419
|
+
are saved in state.json before the tool may delete its old logs. At most every 30s, only when a job waits."""
|
|
7420
|
+
if time.time() - tok_tick[0] < 30:
|
|
7421
|
+
return
|
|
7422
|
+
tok_tick[0] = time.time()
|
|
7423
|
+
st_ = load()
|
|
7424
|
+
if any("tokens" not in a and a.get("tok_marker") and now() - a.get("end", 0) >= TOKEN_GRACE_S
|
|
7425
|
+
for t in st_["tasks"].values() for a in t.get("attempts") or []):
|
|
7426
|
+
try:
|
|
7427
|
+
patch_state(lambda s_: token_fill(s_))
|
|
7428
|
+
except Exception as e: # a strange log must never stop the run
|
|
7429
|
+
say(f"token count skipped this time: {e}")
|
|
7430
|
+
|
|
6863
7431
|
def tend_compacts():
|
|
6864
7432
|
"""Coders and the reviewer whose milestone landed get their tool's compact command while they are idle and
|
|
6865
7433
|
hold no job; one that is compacting is free again once herdr shows it idle (or after COMPACT_MAX_S)."""
|
|
@@ -7128,6 +7696,7 @@ def _autopilot(args):
|
|
|
7128
7696
|
watch_herdr()
|
|
7129
7697
|
tend_stops()
|
|
7130
7698
|
tend_compacts()
|
|
7699
|
+
tend_tokens()
|
|
7131
7700
|
# 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
|
|
7132
7701
|
el, last_tick = time.time() - last_tick, time.time()
|
|
7133
7702
|
asleep = slept()
|
|
@@ -7192,8 +7761,14 @@ def _autopilot(args):
|
|
|
7192
7761
|
sugg += [f"- {k}: {s}" for s in review_findings(k, rnd)[1]]
|
|
7193
7762
|
if v.get("out_of_scope"):
|
|
7194
7763
|
scope.append(f"- {k}: {', '.join(v['out_of_scope'])}")
|
|
7195
|
-
_, report = run("report", "--no-time", ok=(0, 1, 2))
|
|
7764
|
+
_, report = run("report", "--no-time", "--no-tokens", ok=(0, 1, 2))
|
|
7196
7765
|
timing = "\n".join(time_lines(time_account(load())))
|
|
7766
|
+
try:
|
|
7767
|
+
patch_state(lambda s_: token_fill(s_, force=True))
|
|
7768
|
+
tokens_md = "\n".join(token_lines(token_account(load())))
|
|
7769
|
+
except Exception as e: # a strange log must never stop the summary
|
|
7770
|
+
tokens_md = f"not available ({e})"
|
|
7771
|
+
patch_state(lambda s_: s_["run"].update(lead_tokens=lead_tokens(s_)) if s_.get("lead") else None)
|
|
7197
7772
|
models = []
|
|
7198
7773
|
for k, v in tasks.items():
|
|
7199
7774
|
used = [a for a in v.get("attempts") or [] if a.get("kind") == "coder" and a.get("model")]
|
|
@@ -7221,6 +7796,7 @@ def _autopilot(args):
|
|
|
7221
7796
|
+ ("## Models: planned and actual\n| Milestone | Planned tier | Ran on | Escalated | Why this tier |\n"
|
|
7222
7797
|
"|---|---|---|---|---|\n" + "\n".join(models) + "\n\n" if models else "") +
|
|
7223
7798
|
f"## Time: estimate vs actual\n{timing}\n\n"
|
|
7799
|
+
f"## Tokens: per milestone\n{tokens_md}\n\n"
|
|
7224
7800
|
f"## Waiting: time milestones sat still\nA finished or ready milestone that waited for something else "
|
|
7225
7801
|
f"first (counted in the times above).\n{wait_table(tasks)}\n\n"
|
|
7226
7802
|
f"## Checked automatically\nAlready verified by the run; nobody needs to redo these by hand.\n"
|
|
@@ -7348,7 +7924,7 @@ def run_report(st):
|
|
|
7348
7924
|
"""Numbers for one run, from what orch recorded (attempts, checks, rounds). No guesses: unknown stays unknown."""
|
|
7349
7925
|
rows, tot = [], {"tasks": 0, "merged": 0, "failed": 0, "first_pass": 0, "reviewed": 0, "re_reviewed": 0,
|
|
7350
7926
|
"conflicts": 0, "lost": 0, "fix_rounds": 0, "agent_s": 0, "wasted_s": 0, "check_s": 0,
|
|
7351
|
-
|
|
7927
|
+
}
|
|
7352
7928
|
for tid in st["order"]:
|
|
7353
7929
|
t = st["tasks"][tid]
|
|
7354
7930
|
if t["status"] == "skipped":
|
|
@@ -7360,13 +7936,6 @@ def run_report(st):
|
|
|
7360
7936
|
check_s = sum(c.get("secs", 0) for c in t.get("checks") or [])
|
|
7361
7937
|
first = (t["status"] == "merged" and t.get("fix", 0) == 0 and t.get("review_round", 0) <= 1
|
|
7362
7938
|
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
7939
|
rows.append({"task": tid, "status": t["status"], "attempts": len(coder), "fix_rounds": t.get("fix", 0),
|
|
7371
7940
|
"review_rounds": t.get("review_round", 0), "conflicts": t.get("conflicts", 0),
|
|
7372
7941
|
"lost": t.get("lost", 0), "agent_s": agent_s, "wasted_s": wasted, "check_s": check_s,
|
|
@@ -7646,14 +8215,27 @@ def time_lines(acct):
|
|
|
7646
8215
|
return out
|
|
7647
8216
|
|
|
7648
8217
|
|
|
8218
|
+
def cmd_tokens(args):
|
|
8219
|
+
"""orch tokens [--json] -> tokens per milestone, read from each agent's own session log (read only)."""
|
|
8220
|
+
token_fill_saved()
|
|
8221
|
+
acct = token_account(load())
|
|
8222
|
+
if "--json" in args:
|
|
8223
|
+
print(json.dumps(acct, indent=2))
|
|
8224
|
+
return
|
|
8225
|
+
print("\n".join(token_lines(acct)))
|
|
8226
|
+
|
|
8227
|
+
|
|
7649
8228
|
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."""
|
|
8229
|
+
"""orch report [--json] [--no-time] [--no-tokens] -> estimated vs actual time (and why it took longer), tokens
|
|
8230
|
+
per milestone, rounds, first-pass rate and wasted work for this run."""
|
|
8231
|
+
if "--no-tokens" not in args or "--json" in args:
|
|
8232
|
+
token_fill_saved()
|
|
7652
8233
|
st = load()
|
|
7653
8234
|
rep_ = run_report(st)
|
|
7654
8235
|
by_axis, rules_broken = review_axes(st)
|
|
7655
8236
|
if "--json" in args:
|
|
7656
8237
|
rep_["time"] = time_account(st)
|
|
8238
|
+
rep_["tokens"] = token_account(st)
|
|
7657
8239
|
rep_["review_axes"] = {"spec": len(by_axis["spec"]), "rules": len(by_axis["rules"]), "rules_broken": rules_broken}
|
|
7658
8240
|
rep_["risk"] = [{"task": k, "door": v.get("door") or "two-way", "door_why": v.get("door_why"),
|
|
7659
8241
|
"blast": v.get("blast"), "proof": v.get("proof")}
|
|
@@ -7662,6 +8244,8 @@ def cmd_report(args):
|
|
|
7662
8244
|
return
|
|
7663
8245
|
if "--no-time" not in args:
|
|
7664
8246
|
print("Estimate vs actual\n" + "\n".join(time_lines(time_account(st))) + "\n")
|
|
8247
|
+
if "--no-tokens" not in args:
|
|
8248
|
+
print("Tokens per milestone\n" + "\n".join(token_lines(token_account(st))) + "\n")
|
|
7665
8249
|
tot = rep_["totals"]
|
|
7666
8250
|
print(f"{'task':<5} {'status':<15} {'tries':>5} {'fix':>4} {'review':>6} {'confl':>5} {'lost':>4} "
|
|
7667
8251
|
f"{'agent time':>10} {'wasted':>8} {'checks':>8} first pass")
|
|
@@ -7682,11 +8266,6 @@ def cmd_report(args):
|
|
|
7682
8266
|
f"{m['first_pass']:>10} {m['escalated_away']:>8} {_fmt_secs(m['agent_s']):>10}")
|
|
7683
8267
|
print("(moved up = milestones this model could not finish, escalated to a stronger one; compare with "
|
|
7684
8268
|
"`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
8269
|
if "--no-time" in args: # the summary (its only caller) has its own sections for the lines below
|
|
7691
8270
|
return
|
|
7692
8271
|
rows = risk_rows(st)
|
|
@@ -8220,6 +8799,16 @@ VIEW_WORDS = {"pending": "waiting", "coding": "building", "needs-fix": "fix roun
|
|
|
8220
8799
|
VIEW_PORT = int(os.environ.get("ORCH_VIEW_PORT", "47231"))
|
|
8221
8800
|
|
|
8222
8801
|
|
|
8802
|
+
def _tok_view(r):
|
|
8803
|
+
"""One milestone's tokens for the board and the browser view (None: no job sent yet)."""
|
|
8804
|
+
if not r or not (r["coder"] or r["review"]):
|
|
8805
|
+
return None
|
|
8806
|
+
part = {p: (None if not r[p] else {"total": r[p]["in"] + r[p]["out"], "in": r[p]["in"], "cached": r[p]["cached"],
|
|
8807
|
+
"out": r[p]["out"], "known": r[p]["known"], "jobs": r[p]["jobs"],
|
|
8808
|
+
"na": r[p]["na"][:1]}) for p in ("coder", "review")}
|
|
8809
|
+
return {"total": r["total"], "partial": r["partial"], **part}
|
|
8810
|
+
|
|
8811
|
+
|
|
8223
8812
|
def _usage_sum(rows):
|
|
8224
8813
|
tok = cost = 0
|
|
8225
8814
|
known = False
|
|
@@ -8319,6 +8908,11 @@ def view_model(st=None, recent=40):
|
|
|
8319
8908
|
"notices": run_notices(None)}
|
|
8320
8909
|
tasks, t_now = st.get("tasks", {}), now()
|
|
8321
8910
|
ms, by_model = [], {}
|
|
8911
|
+
try:
|
|
8912
|
+
tacct = token_account(st, live=True)
|
|
8913
|
+
except Exception:
|
|
8914
|
+
tacct = {"tasks": [], "lead": None, "total": 0, "partial": False}
|
|
8915
|
+
trow = {r["task"]: r for r in tacct["tasks"]}
|
|
8322
8916
|
for tid in st.get("order", []):
|
|
8323
8917
|
t = tasks.get(tid) or {}
|
|
8324
8918
|
w = t.get("wait") or {}
|
|
@@ -8342,6 +8936,7 @@ def view_model(st=None, recent=40):
|
|
|
8342
8936
|
"estimate_s": t.get("estimate_s"), "started": (w.get("started") or w.get("since")) if cur else None,
|
|
8343
8937
|
"spent_s": int(sum(a.get("secs", 0) for a in atts) + cur),
|
|
8344
8938
|
"usage": _usage_sum([a.get("usage") for a in atts if a.get("usage")]),
|
|
8939
|
+
"tokens": _tok_view(trow.get(tid)),
|
|
8345
8940
|
"attempts": [{"kind": a.get("kind"), "agent": a.get("agent"), "model": a.get("model"),
|
|
8346
8941
|
"tier": a.get("tier"), "secs": a.get("secs"), "outcome": a.get("outcome")}
|
|
8347
8942
|
for a in atts[-12:]],
|
|
@@ -8382,6 +8977,11 @@ def view_model(st=None, recent=40):
|
|
|
8382
8977
|
"active": len([g for g in groups if g in ("building", "checking", "review", "landing")]),
|
|
8383
8978
|
"waiting": groups.count("waiting")},
|
|
8384
8979
|
"time": {"driven_s": int(run.get("driven_s", 0)), "estimate_s": st.get("estimate_s")},
|
|
8980
|
+
"tokens": {"total": tacct["total"], "partial": tacct["partial"],
|
|
8981
|
+
"lead": None if not tacct["lead"] else
|
|
8982
|
+
{"na": tacct["lead"]["na"]} if "na" in tacct["lead"] else
|
|
8983
|
+
{"total": tacct["lead"]["in"] + tacct["lead"]["out"], "in": tacct["lead"]["in"],
|
|
8984
|
+
"cached": tacct["lead"]["cached"], "out": tacct["lead"]["out"]}},
|
|
8385
8985
|
"usage": {"total": _usage_sum([u for v in by_model.values() for u in v]),
|
|
8386
8986
|
"by_model": {k: _usage_sum(v) for k, v in by_model.items()}},
|
|
8387
8987
|
"milestones": ms, "agents": agents,
|
|
@@ -9199,9 +9799,12 @@ def render_board(vm, width=100, color=True, sel=None, note=""):
|
|
|
9199
9799
|
+ (" · " + c("r", f"{cn['needs_you']} needs you") if cn["needs_you"] else "")
|
|
9200
9800
|
+ c("d", f" · {_fmt_min(vm['time']['driven_s'])} so far"
|
|
9201
9801
|
+ (f" of ~{_fmt_min(vm['time']['estimate_s'])}" if vm["time"].get("estimate_s") else ""))]
|
|
9202
|
-
|
|
9203
|
-
if
|
|
9204
|
-
|
|
9802
|
+
tk = vm.get("tokens") or {}
|
|
9803
|
+
if tk.get("total") or tk.get("lead"):
|
|
9804
|
+
ld = tk.get("lead") or {}
|
|
9805
|
+
out.append(c("d", f"tokens {_tk(tk.get('total'))}{'+' if tk.get('partial') else ''} so far"
|
|
9806
|
+
+ (f" · lead {_tk(ld['total'])}" if ld.get("total") else
|
|
9807
|
+
" · lead: not available" if ld.get("na") else "")))
|
|
9205
9808
|
if vm.get("all_done"):
|
|
9206
9809
|
out.append(c("g", "ALL DONE — `orch finish` pushes the branch and opens the PR"))
|
|
9207
9810
|
out += notes
|
|
@@ -9217,6 +9820,10 @@ def render_board(vm, width=100, color=True, sel=None, note=""):
|
|
|
9217
9820
|
who = m.get("worker") or ""
|
|
9218
9821
|
extra = (f"{_fmt_min(m['spent_s'])} of ~{_fmt_min(m['estimate_s'])}" if m.get("started")
|
|
9219
9822
|
and m.get("estimate_s") else f"{_fmt_min(m['spent_s'])}" if m["spent_s"] else "")
|
|
9823
|
+
mt = m.get("tokens")
|
|
9824
|
+
if mt:
|
|
9825
|
+
extra += (" " if extra else "") + (f"{_tk(mt['total'])}{'+' if mt['partial'] else ''} tok"
|
|
9826
|
+
if mt["total"] else "tokens n/a")
|
|
9220
9827
|
if g == "waiting" and m["deps"]:
|
|
9221
9828
|
word = "waits for " + ",".join(d for d in m["deps"] if ms.get(d, {}).get("group") != "landed") \
|
|
9222
9829
|
if any(ms.get(d, {}).get("group") != "landed" for d in m["deps"]) else "ready"
|
|
@@ -9599,7 +10206,7 @@ COMMANDS = {
|
|
|
9599
10206
|
"write-task": cmd_write_task, "nudge": cmd_nudge, "autopilot": cmd_autopilot,
|
|
9600
10207
|
"send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
|
|
9601
10208
|
"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,
|
|
10209
|
+
"report": cmd_report, "tokens": cmd_tokens, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
|
|
9603
10210
|
"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
10211
|
"free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
|
|
9605
10212
|
"view": lambda a: cmd_view(a), "board": lambda a: cmd_board(a), "changes": lambda a: cmd_changes(a),
|
|
@@ -9688,7 +10295,10 @@ USAGE = """usage: orch <command> [args]
|
|
|
9688
10295
|
[f] or [enter] on a milestone shows its changed files, [enter] on a file its diff
|
|
9689
10296
|
changes [Mn [file]] [--json] what each milestone changed: files with +/- counts, or one file's diff
|
|
9690
10297
|
(live while a coder works, unsaved files included; landed = its commit). Read-only
|
|
9691
|
-
report [--json]
|
|
10298
|
+
report [--json] [--no-tokens] estimate vs actual time (why longer, who), tokens per milestone, rounds,
|
|
10299
|
+
first-pass rate, wasted work
|
|
10300
|
+
tokens [--json] tokens per milestone (coder, review, fix rounds), the lead and the total, read from each
|
|
10301
|
+
agent's own log (Claude Code, Codex, Pi, agy); "not available" when a log has none
|
|
9692
10302
|
ready free coder slots, FIX jobs (do these first), then READY milestones
|
|
9693
10303
|
pick <Mn> first available worker for the task (respects Tier, then Prefer), or NONE (exit 3)
|
|
9694
10304
|
escalate <Mn> [reason] out of rounds: one more go on a stronger model, if the team has one (exit 3 if not)
|
package/models.default.toml
CHANGED
|
@@ -124,12 +124,28 @@ evidence = "`codex debug models` (codex-cli 0.172, 2026-11): \"Fast, go-to model
|
|
|
124
124
|
[discover.codex]
|
|
125
125
|
# How orch finds Codex's current models: it runs `cmd` (at most every few hours, the answer is cached), skips
|
|
126
126
|
# models Codex hides or calls legacy / previous generation, and takes the newest model of each family (a word in
|
|
127
|
-
# its id). Each level is that model on a thinking level. If the command fails,
|
|
127
|
+
# its id; a list of families is tried in order). Each level is that model on a thinking level. If the command fails,
|
|
128
|
+
# the entries above are used. A tool that prints plain lines instead of JSON works too (see [discover.agy]).
|
|
128
129
|
cmd = "codex debug models"
|
|
129
130
|
small = { family = "luna", effort = "high" }
|
|
130
131
|
medium = { family = "sol", effort = "low" }
|
|
131
132
|
high = { family = "sol", effort = "medium" }
|
|
132
133
|
|
|
134
|
+
# ---------------------------------------------------------------- Antigravity CLI (`agy --model <id> --effort <level>`)
|
|
135
|
+
# No agy model is written here: orch asks agy itself (`agy models`, the models YOUR account can use) and fills each
|
|
136
|
+
# level with the newest model of a family, so a new Gemini is picked up the day agy lists it. The family list is
|
|
137
|
+
# tried in order: Hydrogen when your plan has it, else Pro, else Flash. Claude or GPT models agy offers are never
|
|
138
|
+
# put in a level (you can still pick one with `orch plan model`). If `agy models` fails (not signed in), agy panes
|
|
139
|
+
# start on the model agy has saved (`/model` inside agy), as before.
|
|
140
|
+
[discover.agy]
|
|
141
|
+
cmd = "agy models"
|
|
142
|
+
small = { family = ["flash"], effort = "low" }
|
|
143
|
+
medium = { family = ["hydrogen", "pro", "flash"], effort = "low" }
|
|
144
|
+
high = { family = ["hydrogen", "pro", "flash"], effort = "high" }
|
|
145
|
+
|
|
146
|
+
# Any other tool that can print its models (one per line, or JSON) can be added the same way in your models.toml,
|
|
147
|
+
# e.g. for OpenCode: [discover.opencode] cmd = "opencode models" high = { family = ["sonnet"] }
|
|
148
|
+
|
|
133
149
|
# ---------------------------------------------------------------- open-weight models (optional)
|
|
134
150
|
# These need somewhere to run: a local server (Ollama, LM Studio, vLLM) or a hosted provider. The id is what
|
|
135
151
|
# your agent expects after its model flag (OpenCode: `provider/model`), so copy an entry into models.toml
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "herdr-orchestra",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.35.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) {
|