1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! The headless Claude Code child that answers a diverted bulk read (#6887).
//!
//! Why: the worker has to be a model the developer is already paying for under
//! the login they already have. Owner ruling 2026-09-07 settles which one —
//! Claude Code's own Haiku, run headless as `claude -p`, under the parent
//! session's `CLAUDE_CONFIG_DIR`. That removes every provider, credential, and
//! registry the earlier draft carried: there is no API key here, no provider
//! selector, and nothing to configure beyond a model name.
//!
//! What: [`worker_argv`] and [`wrap_files`] build the child's argv and its
//! stdin payload — the file bytes travel on stdin, never in argv, so they stay
//! out of every process listing. [`spawn_worker`] runs it with the parent's
//! session bindings removed ([`NESTED_SESSION_ENV`]) and a timeout;
//! [`parse_worker_json`] turns `--output-format json` into a [`WorkerReply`].
//! [`worker_available`] is the cheap predicate the `PreToolUse` hook uses to
//! avoid blocking into a dead end.
//!
//! Nesting works: `claude -p` starts normally inside a running Claude Code
//! session even with `CLAUDECODE=1` and the messaging socket present. The scrub
//! is not a workaround for a refusal — it exists because those variables bind
//! the child to the PARENT's session (its id, its IPC socket and token, its
//! output cap and effort level), all of which are wrong for a detached worker.
//! Test: `divert_worker_tests.rs`.
use ;
use Stdio;
use Duration;
use AsyncWriteExt;
/// The external binary the worker runs.
///
/// Why: resolved through `trusty_common::bin_resolve::resolve_binary`, the
/// workspace's single answer to "find this executable", so a hook firing under
/// Claude Code's minimal `PATH` still locates it (#1298).
/// What: `"claude"`.
/// Test: `worker_available_reports_the_resolver`.
pub const WORKER_BINARY: &str = "claude";
/// Model the worker runs on when the manifest names none.
///
/// Why: Haiku 4.5 is the arm the #6882 POC measured (-45% cost, -54% output
/// tokens against the undiverted baseline).
/// What: `"claude-haiku-4-5"` — an alias `claude --model` accepts.
/// Test: `worker_argv_carries_the_model_and_no_file_content`.
pub const DEFAULT_WORKER_MODEL: &str = "claude-haiku-4-5";
/// Seconds the worker may run before it is killed.
///
/// Why: the agent is blocked on this command. A worker that hangs must become a
/// fall-through the agent can recover from, not an indefinite stall.
/// What: `60`. Overridable per invocation with `--timeout-secs`.
/// Test: `spawn_worker_at_times_out`.
pub const DEFAULT_TIMEOUT_SECS: u64 = 60;
/// Environment variables that bind a process to the PARENT Claude Code session.
///
/// Why: the child is a detached worker, not a continuation of this session.
/// Inheriting `CLAUDE_CODE_MESSAGING_SOCKET`/`_TOKEN` would point it at the
/// parent's IPC channel; inheriting `CLAUDE_CODE_SESSION_ID` would make it
/// claim an id that is not its own; inheriting `CLAUDE_CODE_MAX_OUTPUT_TOKENS`
/// and `CLAUDE_EFFORT` would apply the expensive session's budget to the cheap
/// worker, which is the exact cost this feature exists to avoid.
///
/// `CLAUDE_CONFIG_DIR` is deliberately NOT in this list: it is the login, and
/// the whole point is that the child authenticates as the same developer.
/// What: the ten variables scrubbed from the child's environment.
/// Test: `scrubbed_env_drops_every_nested_session_binding`,
/// `scrubbed_env_keeps_the_config_dir`.
pub const NESTED_SESSION_ENV: = ;
/// The fixed summarization instruction the child runs under.
///
/// Why: passed as `--system-prompt`, which REPLACES Claude Code's own harness
/// prompt. That is most of the saving — the default prompt plus tool schemas
/// measured ~48k cache-write tokens on this workstation; replacing it and
/// dropping tools and MCP brings the same call to ~9k.
/// What: a summarizer with no tools to reach for and no latitude to invent.
/// Test: `worker_argv_carries_the_model_and_no_file_content`.
const SYSTEM_PROMPT: &str = "You are a file-reading worker for a coding agent. \
The user message contains whole files wrapped in <file path=\"...\">...</file> \
tags, followed by a question. Answer the question about those files \
precisely and briefly. Quote exact identifiers. Never invent content that \
is not present in the supplied files. You have no tools; answer from the \
supplied text alone.";
/// What the child reported about one worker call.
///
/// Why: the usage numbers are acceptance criterion 6 — the ledger line records
/// what the diversion actually cost, so the saving can be checked rather than
/// asserted.
/// What: the answer text plus the child's own `usage` and `total_cost_usd`.
/// Test: `parse_worker_json_extracts_text_and_usage`.
pub
/// Whether a worker binary is resolvable right now.
///
/// Why (acceptance criterion 4): the `PreToolUse` hook must never block into a
/// dead end. With no `claude` on `PATH` the replacement command cannot run, so
/// the hook has to let the original read through instead.
/// What: `true` when `resolve_binary("claude")` finds an executable. No process
/// is spawned — a hook has a 10-second budget and this runs on every `Read`.
/// Test: `worker_available_reports_the_resolver`.
pub
/// Locate the worker binary.
///
/// Why: one resolution path, shared with the rest of the workspace.
/// What: `trusty_common::bin_resolve::resolve_binary(WORKER_BINARY)`.
/// Test: covered via `worker_available_reports_the_resolver`.
/// Build the child's argument vector.
///
/// Why: pure, so a test can assert the exact flags AND assert that no file
/// content ever reaches argv — content travels on stdin, which keeps it out of
/// `ps` output and off any argv length limit.
/// What: headless print mode on `model`, JSON output so usage comes back
/// structured, a replaced system prompt, and every capability the worker does
/// not need switched off: `--restricted` drops the command-running tools and
/// WebFetch, `--strict-mcp-config` with no `--mcp-config` loads no MCP server,
/// `--disable-slash-commands` skips skills, and `--permission-prompts none`
/// denies anything that would prompt, since nobody is there to answer.
/// Test: `worker_argv_carries_the_model_and_no_file_content`.
pub
/// Wrap file contents and the question into the child's stdin payload.
///
/// Why: the child needs to know which bytes came from which file. This is
/// shunt's own wire shape (`<file path="…">…</file>`), kept identical so the
/// #6882 measurements carry over.
/// What: one `<file>` element per `(path, content)` pair, then a blank line and
/// `Question: <question>`.
/// Test: `wrap_files_uses_the_shunt_envelope`.
pub
/// Extract the answer and usage from the child's `--output-format json`.
///
/// Why: the child reports failure IN the JSON with `is_error: true` and a
/// human-readable `result` (a logged-out worker prints `Not logged in · Please
/// run /login` and still exits 0), so a zero exit code alone does not mean it
/// answered.
/// What: `Ok` only when `is_error` is absent or false and `result` is non-empty.
/// Usage fields default to zero individually so a schema that gains or loses an
/// optional counter does not turn a good answer into a failure.
/// Test: `parse_worker_json_extracts_text_and_usage`,
/// `parse_worker_json_rejects_an_error_result`.
pub
/// Run the worker and return its reply.
///
/// Why: every failure mode the agent could hit — binary missing, non-zero exit,
/// timeout, unparseable output, a logged-out child — has to come back as one
/// `Err` string, because the caller's only move on any of them is the same:
/// fall through and let the agent read the file itself.
/// What: spawns [`WORKER_BINARY`] with [`worker_argv`], writes `payload` to its
/// stdin, and waits at most `timeout`. Kills the child on timeout so a hung
/// worker leaves nothing behind. The parent's session bindings are removed from
/// the child's environment ([`NESTED_SESSION_ENV`]) and `TRUSTY_MPM_DISABLE_HOOKS`
/// is set so this crate's own hooks — the diversion hook included — never fire
/// inside the worker.
/// Test: `spawn_worker_at_reports_an_unstartable_binary`, `spawn_worker_at_times_out`.
pub async
/// Run a specific worker binary and return its reply.
///
/// Why: the program path is a PARAMETER rather than something this function
/// resolves, so a test drives the real spawn, timeout, and kill against a stand-in
/// script without touching `PATH` — this bin target's env-mutation ratchet
/// (#5544) forbids a process-global `set_var`, and a `PATH` rewrite in one test
/// corrupts every other test in the binary regardless.
/// What: see [`spawn_worker`], which resolves the path and delegates here.
/// Test: `spawn_worker_at_reports_an_unstartable_binary`, `spawn_worker_at_times_out`.
pub async