agent-dispatch 0.16.0__tar.gz → 0.17.0__tar.gz
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.
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/AGENTS.md +4 -1
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/CHANGELOG.md +34 -1
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/PKG-INFO +26 -3
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/README.md +25 -2
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/agents.example.yaml +6 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/pyproject.toml +1 -1
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/__init__.py +1 -1
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/cli.py +93 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/config.py +5 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/models.py +15 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/runner.py +164 -2
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/server.py +10 -1
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/usage.py +106 -1
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/conftest.py +7 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_cli.py +133 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_config.py +17 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_jobs.py +13 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_models.py +9 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_runner.py +302 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_server.py +38 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_usage.py +106 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/.github/dependabot.yml +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/.github/workflows/ci.yml +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/.github/workflows/publish.yml +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/.gitignore +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/LICENSE +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/SECURITY.md +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/assets/mascot.png +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/scripts/check_install.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/cache.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/concurrency.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/jobs.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/progress.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/src/agent_dispatch/servers.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/__init__.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_cache.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_concurrency.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_progress.py +0 -0
- {agent_dispatch-0.16.0 → agent_dispatch-0.17.0}/tests/test_servers.py +0 -0
|
@@ -12,7 +12,7 @@ MCP server + CLI that lets Claude Code agents delegate tasks to agents in other
|
|
|
12
12
|
|------|------|
|
|
13
13
|
| `src/agent_dispatch/runner.py` | Sync subprocess wrapper around `claude -p` — the actual work |
|
|
14
14
|
| `src/agent_dispatch/server.py` | Async FastMCP interface (21 MCP tools), wraps runner in `asyncio.to_thread` with a shared process limit |
|
|
15
|
-
| `src/agent_dispatch/usage.py` | Append-only dispatch journal (cost/duration/outcome) + aggregation for `stats` and the `typical` block |
|
|
15
|
+
| `src/agent_dispatch/usage.py` | Append-only dispatch journal (cost/duration/outcome/tokens/model) + aggregation for `stats` and the `typical` block |
|
|
16
16
|
| `src/agent_dispatch/servers.py` | Registry of live `serve` processes and the version each one runs (`doctor` reads it) |
|
|
17
17
|
| `src/agent_dispatch/cli.py` | Click CLI: `init`, `add`, `update`, `remove`, `list`, `describe`, `test`, `doctor`, `jobs`, `job`, `cancel`, `gc`, `group` (add/list/inspect/update/remove), `serve` |
|
|
18
18
|
| `src/agent_dispatch/models.py` | Pydantic v2 models (`AgentConfig`, `DispatchGroup`/`GroupMember`, `Settings`, `DispatchResult`) |
|
|
@@ -71,9 +71,12 @@ The autouse guard in `tests/conftest.py` rejects real Claude process launches wh
|
|
|
71
71
|
- **`--json` output must be valid JSON on the empty path too.** `stats --json` printed prose when the journal had no records — i.e. on a fresh install, which is exactly when a script first pipes it somewhere.
|
|
72
72
|
- **The usage journal is written by a decorator, not at each return.** `runner._journaled` wraps `dispatch`/`dispatch_stream` because each has a dozen early returns; instrumenting them one by one guarantees the next new return path goes unrecorded. It records the outermost call only (`_use_session_flag` is False on the stream's old-CLI retry, which would otherwise double-count one dispatch). It also swallows exceptions itself even though `usage.record` already does: the result in hand is billed, and the guarantee has to hold at the boundary that owns the damage rather than on another module's promise (`test_a_broken_journal_never_breaks_a_paid_dispatch` removes record()'s guard to prove it).
|
|
73
73
|
- **A journal record is one `O_APPEND` write under `PIPE_BUF`**, never a locked read-modify-write: the CLI and every running server share one file, and this user has 14+ servers alive. Every field is capped so the line cannot approach 4096 bytes. Rotation is an atomic rename at ~2 MB, two generations kept.
|
|
74
|
+
- **`total_cost_usd` is per SESSION on `--resume`** (claude ≥ 2.1.277; verified live on 2.1.322: $0.0798, then $0.0953 after a resume that cost $0.0155). `runner._call_cost` turns it into the call's own cost by subtracting `usage.session_total(session_id)` — the newest journal record for that `sid` (`cum`, or `cost` for a session's first call) — read **before** the spawn, and carries the reported cumulative figure as `cum` in the journal telemetry. Amounts cannot tell cumulative from per-call reporting, so the CLI **version** decides (`_cli_reports_session_totals`: `claude --version` ≥ 2.1.277, memoized per binary+mtime, probe failure = do not adjust; `tests/conftest.py` stubs it to True). It subtracts only when the reported total is a finite number ≥ the prior total within `_COST_EPSILON` (the journal rounds to 6 places — without the tolerance an unchanged total was charged whole again), and not at all when the session is unknown to the journal or `usage_log` is off: those keep the reported figure. `session_total` reads the live generation before `.1` (the other order loses the newest records to a concurrent rotation) and never takes `cost` from a record that has a `cum` key. Known limits, accepted: two processes resuming one session at once can both subtract the same baseline; a costless record in between (timeout) folds its spend into the next call — the sum stays right, the split does not. `_apply_budget` therefore judges the call, not the session. Only `dispatch` resumes; `dispatch_stream` has no `session_id`.
|
|
75
|
+
- **Token usage is journal-only.** `DispatchResult.token_usage` has `exclude=True`: never expose it in tool payloads or job files. `runner._token_usage` extracts `in`/`out`/`cr`/`cw` and the highest-cost `model` from CLI results, including failures; `_journaled` passes it to `usage.record`, which revalidates counts in `[0, 10**12)` and caps model names at 60 characters. Cache hits have no tokens. `stats` reports separate token sums, measured `records`, cache-read share, and model counts; text shows combined input/cache percentages plus output totals and each agent's most frequent model (`+N more` when needed). Old records remain valid, disk counts go through `as_float` plus plausibility bounds, and `_profile` must not grow.
|
|
74
76
|
- **Profiles are memoized on the journal's (path, size, mtime) and read a NARROWER tail than `stats`.** `list_agents`/`inspect_agent` run on the event-loop thread: a full 2 MB journal cost **24.8 ms** per discovery call at the 512 KB report window — 33x the config parse that 0.13.0 exists to have fixed. Now 3.3 ms cold, ~0 warm. Every profile consumer goes through `usage.profiles()`; never add a caller that re-parses per agent.
|
|
75
77
|
- **`usage_limit` is its own error type** (observed live: `You've hit your session limit · resets 6pm`). It is checked *before* the permission patterns and its hint says the limit is account-wide, so "try another agent" is not a workaround. Text-classified errors attach their advisory through the single `_classification_hint`, not per site.
|
|
76
78
|
- **Server liveness is an advisory lock, not a PID.** `servers.register` holds an exclusive `flock` on `<config dir>/servers/<pid>.json` for the process lifetime; a reader that *takes* that lock owns a dead entry and deletes it. `os.kill(pid, 0)` would believe a recycled PID and would never notice a SIGKILLed server. Never close that fd (re-registering closes the old one first).
|
|
79
|
+
- **Startup trims are opt-in flags, never defaults.** `AgentConfig.skills` (default true; false → `--disable-slash-commands`) and `strict_mcp` (default false; true → `--strict-mcp-config`, plus `--mcp-config <dir>/.mcp.json` when that file exists) come from `runner._startup_trim_flags`, are sent on `--resume` too, and are pruned from YAML at their defaults. `--mcp-config` is variadic in the CLI: keep a flag right after its path. Mutation is CLI-only (`update --no-skills/--skills`, `--strict-mcp/--no-strict-mcp`); `doctor` probes the flags only when some agent uses them. Measured basis (claude 2.1.322): a new task text re-creates ~32k preamble tokens per dispatch; a stable `--append-system-prompt` does not help. A resumed session, by contrast, re-reads its preamble from cache: live, a follow-up via `dispatch_session` cost $0.005–0.017 against $0.089 for a fresh dispatch of the same agent.
|
|
77
80
|
- **The dispatch protocol goes in the system prompt, not the task.** `_build_system_prompt` (runner.py) renders the protocol (non-interactive, time/spend budget, lead with the outcome, trailing `STATUS:` line) plus the agent's `instructions`, and `_build_command` passes it as `--append-system-prompt` — on `--resume` too, since the CLI re-applies an appended prompt on every launch. `_build_prompt` (the `-p` text) is unchanged. Standing instructions and protocol settings are captured separately in `_cache_config_key`. The text always starts with a `##` header line so it can never be read as a flag. `settings.dispatch_protocol: false` turns the protocol off (for CLIs that predate the flag; `doctor` probes `claude --help` for it); per-agent `instructions` still go through when set.
|
|
78
81
|
- **`outcome` is lifted from the LAST line of the result** (`_split_outcome`), before JSON parsing, by the shared `_build_success_result` (the success-side twin of `_build_error_result` — both `dispatch` and `dispatch_stream` go through it) and by the plain-text fallback tier. A bare marker line is removed from `result`; a marker with a trailing reason stays. `outcome` never flips `success`; `partial`/`blocked` add a `hint` with the `dispatch_session(...)` continuation, after the denial hint. In JSON mode the protocol omits the STATUS instruction (the JSON footer governs), but a STATUS line that arrives anyway is still stripped so `parsed_result` survives.
|
|
79
82
|
- Remediation text is a contract: a hint that names a flag must name one that exists (`test_printed_budget_hint_is_a_runnable_command` feeds the printed flags back into the CLI). Run the command you print.
|
|
@@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.17.0] - 2026-11-10
|
|
11
|
+
|
|
12
|
+
The cost round, driven by measurements on the live CLI rather than by reading
|
|
13
|
+
code: what a dispatch pays for before the agent does anything, and what the
|
|
14
|
+
journal was getting wrong about resumed sessions.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- Per-agent startup-context trims, both opt-in: `agent-dispatch update <name>
|
|
18
|
+
--no-skills` (sends `--disable-slash-commands`) and `--strict-mcp` (sends
|
|
19
|
+
`--strict-mcp-config` with the agent directory's own `.mcp.json`). A dispatch
|
|
20
|
+
with a new task re-writes the whole session preamble to the prompt cache —
|
|
21
|
+
about 32k tokens on claude 2.1.322 — and these cut the cold-start cost by 27%
|
|
22
|
+
and 11% (43% together) in a live measurement. `describe` and `inspect_agent`
|
|
23
|
+
show them when set; `doctor` checks that the installed CLI knows the flags.
|
|
24
|
+
Restart running sessions before enabling them: a server on an older release
|
|
25
|
+
drops keys it does not know the next time it saves the config.
|
|
26
|
+
- Usage journal records input, output, cache-read and cache-write tokens plus
|
|
27
|
+
the highest-cost model reported by the CLI, including failed and budget-stopped
|
|
28
|
+
runs. `agent-dispatch stats` shows token totals, cache percentages and each
|
|
29
|
+
agent's most frequent model; `--json` includes counts and measurement coverage.
|
|
30
|
+
Token metadata stays out of tool responses, job files and discovery profiles.
|
|
31
|
+
|
|
32
|
+
### Fixed
|
|
33
|
+
- A resumed session's cost was counted again on every `dispatch_session`.
|
|
34
|
+
Since claude 2.1.277 `total_cost_usd` covers the whole session on `--resume`;
|
|
35
|
+
the result and the journal now carry the call's own cost (the difference from
|
|
36
|
+
the session's last journaled total), so `stats` no longer overstates spend and
|
|
37
|
+
a cheap follow-up no longer raises `budget_exceeded` on the session's history.
|
|
38
|
+
Sessions the journal has not seen, and runs with `usage_log: false`, keep the
|
|
39
|
+
reported figure.
|
|
40
|
+
- `return_ref` payloads dropped `budget_exceeded`.
|
|
41
|
+
|
|
10
42
|
## [0.16.0] - 2026-09-30
|
|
11
43
|
|
|
12
44
|
The process-control round. One concurrency limit now covers every dispatch
|
|
@@ -906,7 +938,8 @@ cache bounding, and stale-job recovery.
|
|
|
906
938
|
- Dependabot for `pip` + `github-actions`, GitHub Actions pinned to
|
|
907
939
|
commit SHAs for supply-chain integrity.
|
|
908
940
|
|
|
909
|
-
[Unreleased]: https://github.com/ginkida/agent-dispatch/compare/v0.
|
|
941
|
+
[Unreleased]: https://github.com/ginkida/agent-dispatch/compare/v0.17.0...HEAD
|
|
942
|
+
[0.17.0]: https://github.com/ginkida/agent-dispatch/compare/v0.16.0...v0.17.0
|
|
910
943
|
[0.16.0]: https://github.com/ginkida/agent-dispatch/compare/v0.15.1...v0.16.0
|
|
911
944
|
[0.15.1]: https://github.com/ginkida/agent-dispatch/compare/v0.15.0...v0.15.1
|
|
912
945
|
[0.15.0]: https://github.com/ginkida/agent-dispatch/compare/v0.14.0...v0.15.0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: agent-dispatch
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.17.0
|
|
4
4
|
Summary: MCP server that lets Claude Code agents delegate tasks to agents in other project directories
|
|
5
5
|
Project-URL: Homepage, https://github.com/ginkida/agent-dispatch
|
|
6
6
|
Project-URL: Repository, https://github.com/ginkida/agent-dispatch
|
|
@@ -301,6 +301,8 @@ Check container logs for recent errors related to the scheduler service
|
|
|
301
301
|
|
|
302
302
|
That last line is lifted out of `result` into **`outcome`** — the agent's own verdict, deterministic to check: `"done"` means complete; `"partial"` / `"blocked"` mean the agent says the work is unfinished, the result names what is missing, and a `hint` spells out the continuation (usually `dispatch_session(..., session_id=...)`). Read `outcome` before reading the text. It never flips `success`, `partial` / `blocked` results are **not cached**, and a `dispatch_parallel(..., aggregate=...)` labels such members for the aggregator so a blocked report is not synthesized as a finished one. Absent when the agent did not report one — the protocol is off (`settings.dispatch_protocol: false`), `response_format="json"` was requested (the JSON footer governs the reply shape there), or the agent simply skipped it.
|
|
303
303
|
|
|
304
|
+
**Startup cost.** Each dispatch is a fresh `claude` session, and a session's preamble — the project's `CLAUDE.md`, the skill listing, MCP server instructions and tool names — is written to the prompt cache again for every new task text (the task sits in front of it, so two different tasks share none of it). Measured on claude 2.1.322 in a gateway directory: ~32k tokens per dispatch before the agent does anything, which is most of what a short run costs. Two opt-in per-agent switches trim it — `agent-dispatch update <name> --no-skills` (no skill/command listing, user-level skills included: −27% in that measurement) and `--strict-mcp` (only the directory's own `.mcp.json`, no user-scope servers or connectors: −11%; the agent then cannot dispatch others, and loses any tool it got from a user-scope server). Check what an agent actually uses before turning either on; `--skills` / `--no-strict-mcp` undo them. A follow-up to the same agent is the opposite case: `dispatch_session` with the `session_id` from the previous result re-reads that preamble from cache (measured: $0.005–0.017 per follow-up against $0.089 for a fresh dispatch), so continue a session rather than re-dispatching when the question builds on the last answer. The larger levers stay outside this tool: a cheaper `model` for gateway agents and a shorter agent `CLAUDE.md`.
|
|
305
|
+
|
|
304
306
|
**Standing orders.** Per-agent `instructions` (set via `add_agent` / `update_agent` or `agent-dispatch update <name> --instructions "..."`) follow the protocol in the same system prompt on **every** dispatch — "read-only SQL only", "never restart a stack unless the task says so", "answer with exact log lines". Unlike `context`, which is per call, and unlike the project's own `CLAUDE.md`, which is written for an interactive session, these are the rules for *being dispatched*.
|
|
305
307
|
|
|
306
308
|
```json
|
|
@@ -587,6 +589,8 @@ agents:
|
|
|
587
589
|
- deploy_debug
|
|
588
590
|
risky_capabilities: # high-risk labels, surfaced for visibility
|
|
589
591
|
- restart_services
|
|
592
|
+
# skills: false # no skill/command listing at startup (cheaper dispatches)
|
|
593
|
+
# strict_mcp: true # load only this directory's .mcp.json, no user-scope MCP servers
|
|
590
594
|
# instructions: | # standing orders, appended to the system prompt on every dispatch
|
|
591
595
|
# Read-only: never restart or redeploy unless the task says so.
|
|
592
596
|
# Quote exact log lines with timestamps.
|
|
@@ -643,7 +647,11 @@ Config is reloaded on every tool call — add agents without restarting.
|
|
|
643
647
|
|
|
644
648
|
Every dispatch appends one line to `~/.config/agent-dispatch/usage.jsonl`
|
|
645
649
|
(override with `AGENT_DISPATCH_USAGE_LOG`): agent, success, cost, duration,
|
|
646
|
-
turns, `outcome`, error type, caller
|
|
650
|
+
turns, `outcome`, error type, caller, plus token counts and the model when the
|
|
651
|
+
CLI reports them. Token fields are `in` (uncached input), `out` (output),
|
|
652
|
+
`cr` (cache read), and `cw` (cache write). `model` is the highest-cost model
|
|
653
|
+
in that dispatch's `modelUsage` (first on ties or when no cost is reported).
|
|
654
|
+
Cache hits are recorded too, flagged
|
|
647
655
|
`cached`, so the report can show what the cache saves.
|
|
648
656
|
|
|
649
657
|
```console
|
|
@@ -651,18 +659,33 @@ $ agent-dispatch stats --days 7
|
|
|
651
659
|
Usage (last 7 day(s))
|
|
652
660
|
dispatches: 33, 1 served from cache
|
|
653
661
|
spend: $13.0390
|
|
662
|
+
tokens: in 1.2M (cache read 62%, cache write 35%), out 310k
|
|
654
663
|
duration: median 87s, p90 2m40s, max 10m00s
|
|
655
664
|
outcomes: blocked 1, done 27, partial 3
|
|
656
665
|
failures: timeout 1, usage_limit 1
|
|
657
666
|
|
|
658
667
|
Per agent
|
|
659
668
|
analytic 18 runs $ 8.9441 median 2m04s p90 2m51s
|
|
669
|
+
tokens: in 800k (cache read 62%, cache write 35%), out 210k
|
|
670
|
+
model: claude-fable-5-2 +1 more
|
|
660
671
|
done 15, partial 3
|
|
661
672
|
gitlab 12 runs $ 3.7949 median 60s p90 86s
|
|
673
|
+
tokens: in 400k (cache read 62%, cache write 35%), out 100k
|
|
674
|
+
model: claude-fable-5-2
|
|
662
675
|
done 12 | 1 cached
|
|
663
676
|
```
|
|
664
677
|
|
|
665
678
|
`--agent NAME` narrows it, `--json` emits the same report as JSON.
|
|
679
|
+
The text's `in` includes uncached input, cache reads, and cache writes; its
|
|
680
|
+
percentages use that combined input. JSON keeps those counts separate in
|
|
681
|
+
`tokens: {input, output, cache_read, cache_write, records}`, adds
|
|
682
|
+
`cache_read_share` rounded to three decimals when total input is nonzero,
|
|
683
|
+
and counts dispatches by primary model in `models`. `records` counts live
|
|
684
|
+
dispatches with valid token measurements; older records and cache hits do
|
|
685
|
+
not dilute the share. Each agent's text shows its most frequent model and
|
|
686
|
+
how many other models were recorded. Runs that fail or reach the spend cap
|
|
687
|
+
still contribute their reported usage. Token telemetry is journal-only:
|
|
688
|
+
tool responses, job files, and discovery's `typical` block stay compact.
|
|
666
689
|
|
|
667
690
|
The journal is what makes three other things work: the `typical` block in
|
|
668
691
|
`list_agents` / `inspect_agent`, the timeout error naming a value derived from
|
|
@@ -776,7 +799,7 @@ See [SECURITY.md](SECURITY.md) for the full threat model (including the `bypassP
|
|
|
776
799
|
|---------|-------------|
|
|
777
800
|
| `agent-dispatch init` | Create config + register MCP server with Claude Code |
|
|
778
801
|
| `agent-dispatch add <name> <dir>` | Add an agent (auto-generates description) |
|
|
779
|
-
| `agent-dispatch update <name>` | Update agent config (permissions, timeout, model, `--instructions`, etc.) |
|
|
802
|
+
| `agent-dispatch update <name>` | Update agent config (permissions, timeout, model, `--instructions`, `--no-skills`, `--strict-mcp`, etc.) |
|
|
780
803
|
| `agent-dispatch remove <name>` | Remove an agent |
|
|
781
804
|
| `agent-dispatch list` | List agents with health status and permissions |
|
|
782
805
|
| `agent-dispatch group <add\|list\|inspect\|update\|remove>` | Manage [groups](#groups) — cross-project working sets of agents |
|
|
@@ -271,6 +271,8 @@ Check container logs for recent errors related to the scheduler service
|
|
|
271
271
|
|
|
272
272
|
That last line is lifted out of `result` into **`outcome`** — the agent's own verdict, deterministic to check: `"done"` means complete; `"partial"` / `"blocked"` mean the agent says the work is unfinished, the result names what is missing, and a `hint` spells out the continuation (usually `dispatch_session(..., session_id=...)`). Read `outcome` before reading the text. It never flips `success`, `partial` / `blocked` results are **not cached**, and a `dispatch_parallel(..., aggregate=...)` labels such members for the aggregator so a blocked report is not synthesized as a finished one. Absent when the agent did not report one — the protocol is off (`settings.dispatch_protocol: false`), `response_format="json"` was requested (the JSON footer governs the reply shape there), or the agent simply skipped it.
|
|
273
273
|
|
|
274
|
+
**Startup cost.** Each dispatch is a fresh `claude` session, and a session's preamble — the project's `CLAUDE.md`, the skill listing, MCP server instructions and tool names — is written to the prompt cache again for every new task text (the task sits in front of it, so two different tasks share none of it). Measured on claude 2.1.322 in a gateway directory: ~32k tokens per dispatch before the agent does anything, which is most of what a short run costs. Two opt-in per-agent switches trim it — `agent-dispatch update <name> --no-skills` (no skill/command listing, user-level skills included: −27% in that measurement) and `--strict-mcp` (only the directory's own `.mcp.json`, no user-scope servers or connectors: −11%; the agent then cannot dispatch others, and loses any tool it got from a user-scope server). Check what an agent actually uses before turning either on; `--skills` / `--no-strict-mcp` undo them. A follow-up to the same agent is the opposite case: `dispatch_session` with the `session_id` from the previous result re-reads that preamble from cache (measured: $0.005–0.017 per follow-up against $0.089 for a fresh dispatch), so continue a session rather than re-dispatching when the question builds on the last answer. The larger levers stay outside this tool: a cheaper `model` for gateway agents and a shorter agent `CLAUDE.md`.
|
|
275
|
+
|
|
274
276
|
**Standing orders.** Per-agent `instructions` (set via `add_agent` / `update_agent` or `agent-dispatch update <name> --instructions "..."`) follow the protocol in the same system prompt on **every** dispatch — "read-only SQL only", "never restart a stack unless the task says so", "answer with exact log lines". Unlike `context`, which is per call, and unlike the project's own `CLAUDE.md`, which is written for an interactive session, these are the rules for *being dispatched*.
|
|
275
277
|
|
|
276
278
|
```json
|
|
@@ -557,6 +559,8 @@ agents:
|
|
|
557
559
|
- deploy_debug
|
|
558
560
|
risky_capabilities: # high-risk labels, surfaced for visibility
|
|
559
561
|
- restart_services
|
|
562
|
+
# skills: false # no skill/command listing at startup (cheaper dispatches)
|
|
563
|
+
# strict_mcp: true # load only this directory's .mcp.json, no user-scope MCP servers
|
|
560
564
|
# instructions: | # standing orders, appended to the system prompt on every dispatch
|
|
561
565
|
# Read-only: never restart or redeploy unless the task says so.
|
|
562
566
|
# Quote exact log lines with timestamps.
|
|
@@ -613,7 +617,11 @@ Config is reloaded on every tool call — add agents without restarting.
|
|
|
613
617
|
|
|
614
618
|
Every dispatch appends one line to `~/.config/agent-dispatch/usage.jsonl`
|
|
615
619
|
(override with `AGENT_DISPATCH_USAGE_LOG`): agent, success, cost, duration,
|
|
616
|
-
turns, `outcome`, error type, caller
|
|
620
|
+
turns, `outcome`, error type, caller, plus token counts and the model when the
|
|
621
|
+
CLI reports them. Token fields are `in` (uncached input), `out` (output),
|
|
622
|
+
`cr` (cache read), and `cw` (cache write). `model` is the highest-cost model
|
|
623
|
+
in that dispatch's `modelUsage` (first on ties or when no cost is reported).
|
|
624
|
+
Cache hits are recorded too, flagged
|
|
617
625
|
`cached`, so the report can show what the cache saves.
|
|
618
626
|
|
|
619
627
|
```console
|
|
@@ -621,18 +629,33 @@ $ agent-dispatch stats --days 7
|
|
|
621
629
|
Usage (last 7 day(s))
|
|
622
630
|
dispatches: 33, 1 served from cache
|
|
623
631
|
spend: $13.0390
|
|
632
|
+
tokens: in 1.2M (cache read 62%, cache write 35%), out 310k
|
|
624
633
|
duration: median 87s, p90 2m40s, max 10m00s
|
|
625
634
|
outcomes: blocked 1, done 27, partial 3
|
|
626
635
|
failures: timeout 1, usage_limit 1
|
|
627
636
|
|
|
628
637
|
Per agent
|
|
629
638
|
analytic 18 runs $ 8.9441 median 2m04s p90 2m51s
|
|
639
|
+
tokens: in 800k (cache read 62%, cache write 35%), out 210k
|
|
640
|
+
model: claude-fable-5-2 +1 more
|
|
630
641
|
done 15, partial 3
|
|
631
642
|
gitlab 12 runs $ 3.7949 median 60s p90 86s
|
|
643
|
+
tokens: in 400k (cache read 62%, cache write 35%), out 100k
|
|
644
|
+
model: claude-fable-5-2
|
|
632
645
|
done 12 | 1 cached
|
|
633
646
|
```
|
|
634
647
|
|
|
635
648
|
`--agent NAME` narrows it, `--json` emits the same report as JSON.
|
|
649
|
+
The text's `in` includes uncached input, cache reads, and cache writes; its
|
|
650
|
+
percentages use that combined input. JSON keeps those counts separate in
|
|
651
|
+
`tokens: {input, output, cache_read, cache_write, records}`, adds
|
|
652
|
+
`cache_read_share` rounded to three decimals when total input is nonzero,
|
|
653
|
+
and counts dispatches by primary model in `models`. `records` counts live
|
|
654
|
+
dispatches with valid token measurements; older records and cache hits do
|
|
655
|
+
not dilute the share. Each agent's text shows its most frequent model and
|
|
656
|
+
how many other models were recorded. Runs that fail or reach the spend cap
|
|
657
|
+
still contribute their reported usage. Token telemetry is journal-only:
|
|
658
|
+
tool responses, job files, and discovery's `typical` block stay compact.
|
|
636
659
|
|
|
637
660
|
The journal is what makes three other things work: the `typical` block in
|
|
638
661
|
`list_agents` / `inspect_agent`, the timeout error naming a value derived from
|
|
@@ -746,7 +769,7 @@ See [SECURITY.md](SECURITY.md) for the full threat model (including the `bypassP
|
|
|
746
769
|
|---------|-------------|
|
|
747
770
|
| `agent-dispatch init` | Create config + register MCP server with Claude Code |
|
|
748
771
|
| `agent-dispatch add <name> <dir>` | Add an agent (auto-generates description) |
|
|
749
|
-
| `agent-dispatch update <name>` | Update agent config (permissions, timeout, model, `--instructions`, etc.) |
|
|
772
|
+
| `agent-dispatch update <name>` | Update agent config (permissions, timeout, model, `--instructions`, `--no-skills`, `--strict-mcp`, etc.) |
|
|
750
773
|
| `agent-dispatch remove <name>` | Remove an agent |
|
|
751
774
|
| `agent-dispatch list` | List agents with health status and permissions |
|
|
752
775
|
| `agent-dispatch group <add\|list\|inspect\|update\|remove>` | Manage [groups](#groups) — cross-project working sets of agents |
|
|
@@ -16,6 +16,12 @@ agents:
|
|
|
16
16
|
instructions: |
|
|
17
17
|
Read-only unless the task explicitly asks to restart or redeploy.
|
|
18
18
|
Quote exact log lines with timestamps; never paraphrase an error.
|
|
19
|
+
# Startup-context trims: every dispatch pays for the session preamble, so
|
|
20
|
+
# drop what this agent never uses. `skills: false` removes the skill/command
|
|
21
|
+
# listing; `strict_mcp: true` loads only this directory's .mcp.json (no
|
|
22
|
+
# user-scope MCP servers — the agent can no longer dispatch others).
|
|
23
|
+
skills: false
|
|
24
|
+
strict_mcp: true
|
|
19
25
|
|
|
20
26
|
# Analytics gateway — a browser + Yandex Metrica agent, no codebase of its own.
|
|
21
27
|
# Its value is its MCP servers + access, not its source. Shared across groups.
|
|
@@ -421,6 +421,18 @@ def list_agents() -> None:
|
|
|
421
421
|
default=None,
|
|
422
422
|
help="Standing orders for every dispatch (replaces the text). Use 'none' to clear.",
|
|
423
423
|
)
|
|
424
|
+
@click.option(
|
|
425
|
+
"--skills/--no-skills",
|
|
426
|
+
default=None,
|
|
427
|
+
help="Load the skill/command listing at startup (default: on). "
|
|
428
|
+
"--no-skills trims the per-dispatch startup context.",
|
|
429
|
+
)
|
|
430
|
+
@click.option(
|
|
431
|
+
"--strict-mcp/--no-strict-mcp",
|
|
432
|
+
default=None,
|
|
433
|
+
help="Load only the agent directory's .mcp.json, not user-scope MCP servers "
|
|
434
|
+
"(default: off). Trims startup context; the agent can no longer dispatch others.",
|
|
435
|
+
)
|
|
424
436
|
@click.pass_context
|
|
425
437
|
def update(
|
|
426
438
|
ctx: click.Context,
|
|
@@ -435,6 +447,8 @@ def update(
|
|
|
435
447
|
capabilities: str | None,
|
|
436
448
|
risky_capabilities: str | None,
|
|
437
449
|
instructions: str | None,
|
|
450
|
+
skills: bool | None,
|
|
451
|
+
strict_mcp: bool | None,
|
|
438
452
|
) -> None:
|
|
439
453
|
"""Update an existing agent's configuration."""
|
|
440
454
|
_check_timeout_or_exit(timeout)
|
|
@@ -459,6 +473,8 @@ def update(
|
|
|
459
473
|
capabilities=capabilities,
|
|
460
474
|
risky_capabilities=risky_capabilities,
|
|
461
475
|
instructions=instructions,
|
|
476
|
+
skills=skills,
|
|
477
|
+
strict_mcp=strict_mcp,
|
|
462
478
|
)
|
|
463
479
|
|
|
464
480
|
if not updated:
|
|
@@ -482,6 +498,8 @@ def _apply_cli_updates(
|
|
|
482
498
|
capabilities: str | None,
|
|
483
499
|
risky_capabilities: str | None,
|
|
484
500
|
instructions: str | None = None,
|
|
501
|
+
skills: bool | None = None,
|
|
502
|
+
strict_mcp: bool | None = None,
|
|
485
503
|
) -> list[str]:
|
|
486
504
|
"""Apply `update`'s explicitly-passed options in place; return the fields touched."""
|
|
487
505
|
updated: list[str] = []
|
|
@@ -533,6 +551,12 @@ def _apply_cli_updates(
|
|
|
533
551
|
stripped = instructions.strip()
|
|
534
552
|
agent.instructions = "" if stripped.lower() == "none" else stripped
|
|
535
553
|
updated.append("instructions")
|
|
554
|
+
if skills is not None:
|
|
555
|
+
agent.skills = skills
|
|
556
|
+
updated.append("skills")
|
|
557
|
+
if strict_mcp is not None:
|
|
558
|
+
agent.strict_mcp = strict_mcp
|
|
559
|
+
updated.append("strict_mcp")
|
|
536
560
|
|
|
537
561
|
return updated
|
|
538
562
|
|
|
@@ -663,6 +687,10 @@ def describe(name: str) -> None:
|
|
|
663
687
|
click.echo(f" instructions: {first}")
|
|
664
688
|
for line in rest:
|
|
665
689
|
click.echo(f" {line}")
|
|
690
|
+
if not agent.skills:
|
|
691
|
+
click.echo(" skills: off (--disable-slash-commands)")
|
|
692
|
+
if agent.strict_mcp:
|
|
693
|
+
click.echo(" strict_mcp: on (only the directory's .mcp.json)")
|
|
666
694
|
click.echo(f" allowed_tools: {_render_tools(agent.allowed_tools)}")
|
|
667
695
|
click.echo(f" disallowed_tools: {_render_tools(agent.disallowed_tools)}")
|
|
668
696
|
|
|
@@ -935,6 +963,43 @@ def _protocol_flag_verdict(
|
|
|
935
963
|
return "warn", msg, details
|
|
936
964
|
|
|
937
965
|
|
|
966
|
+
# (flag the runner sends, AgentConfig predicate, the `update` option that stops sending it)
|
|
967
|
+
_TRIM_FLAGS = (
|
|
968
|
+
("--disable-slash-commands", lambda a: not a.skills, "--skills"),
|
|
969
|
+
("--strict-mcp-config", lambda a: a.strict_mcp, "--no-strict-mcp"),
|
|
970
|
+
)
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _trim_flag_verdicts(
|
|
974
|
+
config: DispatchConfig | None, claude_path: str
|
|
975
|
+
) -> list[tuple[str, str, list[str]]]:
|
|
976
|
+
"""Doctor lines for the opt-in startup trims (AgentConfig.skills / strict_mcp).
|
|
977
|
+
|
|
978
|
+
Silent unless some agent actually uses a trim: the flags are only sent for
|
|
979
|
+
those agents, so an old CLI is a problem for them alone.
|
|
980
|
+
"""
|
|
981
|
+
if config is None:
|
|
982
|
+
return []
|
|
983
|
+
verdicts: list[tuple[str, str, list[str]]] = []
|
|
984
|
+
for flag, uses, undo in _TRIM_FLAGS:
|
|
985
|
+
names = [name for name, agent in config.agents.items() if uses(agent)]
|
|
986
|
+
if not names:
|
|
987
|
+
continue
|
|
988
|
+
supported = _claude_supports_flag(claude_path, flag)
|
|
989
|
+
if supported is True:
|
|
990
|
+
verdicts.append(("ok", f"claude CLI supports {flag} (used by {', '.join(names)})", []))
|
|
991
|
+
elif supported is False:
|
|
992
|
+
verdicts.append((
|
|
993
|
+
"warn",
|
|
994
|
+
f"claude CLI predates {flag}: dispatches to {', '.join(names)} will fail",
|
|
995
|
+
[" Upgrade claude (recommended), or stop sending the flag:"]
|
|
996
|
+
+ [f" agent-dispatch update {name} {undo}" for name in names],
|
|
997
|
+
))
|
|
998
|
+
else:
|
|
999
|
+
verdicts.append(("warn", f"Could not run `claude --help` to check {flag} support", []))
|
|
1000
|
+
return verdicts
|
|
1001
|
+
|
|
1002
|
+
|
|
938
1003
|
@cli.command()
|
|
939
1004
|
@click.option("--json", "as_json", is_flag=True, help="Output a structured diagnostic report.")
|
|
940
1005
|
@click.option("--strict", is_flag=True, help="Exit with code 1 for warnings as well as failures.")
|
|
@@ -995,6 +1060,8 @@ def doctor(as_json: bool, strict: bool) -> None:
|
|
|
995
1060
|
emit(*_protocol_flag_verdict(config, cp))
|
|
996
1061
|
else:
|
|
997
1062
|
warn("Could not run `claude --help` to check --append-system-prompt support")
|
|
1063
|
+
for status, msg, details in _trim_flag_verdicts(config, claude_path):
|
|
1064
|
+
emit(status, msg, details)
|
|
998
1065
|
else:
|
|
999
1066
|
fail("claude CLI not found on PATH")
|
|
1000
1067
|
detail(" Install: https://docs.anthropic.com/en/docs/claude-code")
|
|
@@ -1372,6 +1439,24 @@ def _fmt_counts(counts: dict[str, int]) -> str:
|
|
|
1372
1439
|
return ", ".join(f"{k} {v}" for k, v in counts.items())
|
|
1373
1440
|
|
|
1374
1441
|
|
|
1442
|
+
def _fmt_token_count(count: int) -> str:
|
|
1443
|
+
for scale, suffix in ((1_000_000, "M"), (1_000, "k")):
|
|
1444
|
+
if count >= scale:
|
|
1445
|
+
return f"{count / scale:.1f}".rstrip("0").rstrip(".") + suffix
|
|
1446
|
+
return str(count)
|
|
1447
|
+
|
|
1448
|
+
|
|
1449
|
+
def _fmt_tokens(tokens: dict[str, int]) -> str:
|
|
1450
|
+
total_input = tokens["input"] + tokens["cache_read"] + tokens["cache_write"]
|
|
1451
|
+
cache = ""
|
|
1452
|
+
if total_input:
|
|
1453
|
+
cache = (
|
|
1454
|
+
f" (cache read {tokens['cache_read'] / total_input:.0%}, "
|
|
1455
|
+
f"cache write {tokens['cache_write'] / total_input:.0%})"
|
|
1456
|
+
)
|
|
1457
|
+
return f"in {_fmt_token_count(total_input)}{cache}, out {_fmt_token_count(tokens['output'])}"
|
|
1458
|
+
|
|
1459
|
+
|
|
1375
1460
|
@cli.command("stats")
|
|
1376
1461
|
@click.option("--days", default=0, type=int, help="Only count the last N days (default: all).")
|
|
1377
1462
|
@click.option("--agent", default=None, help="Only this agent.")
|
|
@@ -1413,6 +1498,8 @@ def usage_stats(days: int, agent: str | None, as_json: bool) -> None:
|
|
|
1413
1498
|
cached = f", {total['cached_hits']} served from cache" if total["cached_hits"] else ""
|
|
1414
1499
|
click.echo(f" dispatches: {total['dispatches']}{cached}")
|
|
1415
1500
|
click.echo(f" spend: ${total['cost_usd']:.4f}")
|
|
1501
|
+
if "tokens" in total:
|
|
1502
|
+
click.echo(f" tokens: {_fmt_tokens(total['tokens'])}")
|
|
1416
1503
|
if "median_ms" in total:
|
|
1417
1504
|
click.echo(
|
|
1418
1505
|
f" duration: median {_fmt_seconds(total['median_ms'])}, "
|
|
@@ -1436,6 +1523,12 @@ def usage_stats(days: int, agent: str | None, as_json: bool) -> None:
|
|
|
1436
1523
|
f" median {_fmt_seconds(st['median_ms']):>6} p90 {_fmt_seconds(st['p90_ms']):>6}"
|
|
1437
1524
|
)
|
|
1438
1525
|
click.echo(head)
|
|
1526
|
+
if "tokens" in st:
|
|
1527
|
+
click.echo(f" tokens: {_fmt_tokens(st['tokens'])}")
|
|
1528
|
+
if st.get("models"):
|
|
1529
|
+
model = max(st["models"], key=st["models"].get)
|
|
1530
|
+
more = f" +{len(st['models']) - 1} more" if len(st["models"]) > 1 else ""
|
|
1531
|
+
click.echo(f" model: {model}{more}")
|
|
1439
1532
|
detail = []
|
|
1440
1533
|
if st.get("outcomes"):
|
|
1441
1534
|
detail.append(_fmt_counts(st["outcomes"]))
|
|
@@ -225,6 +225,11 @@ def save_config(config: DispatchConfig, path: Path | None = None) -> None:
|
|
|
225
225
|
for key in ("capabilities", "risky_capabilities", "instructions"):
|
|
226
226
|
if not agent_data.get(key):
|
|
227
227
|
agent_data.pop(key, None)
|
|
228
|
+
# Booleans at their defaults: same reason, opposite polarity each.
|
|
229
|
+
if agent_data.get("skills") is True:
|
|
230
|
+
agent_data.pop("skills", None)
|
|
231
|
+
if agent_data.get("strict_mcp") is False:
|
|
232
|
+
agent_data.pop("strict_mcp", None)
|
|
228
233
|
# `groups` also defaults to {} (not None), so exclude_none keeps it — prune
|
|
229
234
|
# the whole block when empty, and drop empty per-group member lists. Empty
|
|
230
235
|
# LISTS only, mirroring capabilities; empty strings (description /
|
|
@@ -60,6 +60,19 @@ class AgentConfig(BaseModel):
|
|
|
60
60
|
# protocol — so they hold across every task, unlike `context`, which is
|
|
61
61
|
# per call. Empty = nothing appended. Pruned from YAML when empty.
|
|
62
62
|
instructions: str = ""
|
|
63
|
+
# Startup-context trims. Every dispatch with a new task re-writes the whole
|
|
64
|
+
# per-session preamble to the prompt cache (measured on claude 2.1.322:
|
|
65
|
+
# ~32k tokens, most of a short run's cost), so what the agent does not need
|
|
66
|
+
# is paid for on every call. Both default to "unchanged behaviour" and are
|
|
67
|
+
# pruned from YAML at their defaults.
|
|
68
|
+
# skills=False -> --disable-slash-commands: no skill/command listing
|
|
69
|
+
# (user-level skills included). ~27% of the preamble.
|
|
70
|
+
# strict_mcp=True -> --strict-mcp-config: only the agent directory's own
|
|
71
|
+
# .mcp.json is loaded; user-scope servers and
|
|
72
|
+
# connectors (agent-dispatch itself among them, so no
|
|
73
|
+
# nested dispatch) are not. ~11%.
|
|
74
|
+
skills: bool = True
|
|
75
|
+
strict_mcp: bool = False
|
|
63
76
|
|
|
64
77
|
@field_validator("directory", mode="before")
|
|
65
78
|
@classmethod
|
|
@@ -218,6 +231,8 @@ class DispatchResult(BaseModel):
|
|
|
218
231
|
cost_usd: float | None = None
|
|
219
232
|
duration_ms: int | None = None
|
|
220
233
|
num_turns: int | None = None
|
|
234
|
+
# Journal-only telemetry: never inflate tool responses or persisted jobs.
|
|
235
|
+
token_usage: dict[str, Any] | None = Field(default=None, exclude=True)
|
|
221
236
|
error: str | None = None
|
|
222
237
|
error_type: str | None = None # permission, timeout, recursion, not_found, budget, cli_error
|
|
223
238
|
# Set when response_format="json" was requested AND the agent's result
|