webhand 0.0.0-stage → 0.2.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/dist/cli.js ADDED
@@ -0,0 +1,1144 @@
1
+ /**
2
+ * CLI for the Claude + Jev agent. Each call is one short process.
3
+ *
4
+ * Claude plans the goal, steps, and values, reviews the outcome, and replans. Jev chooses every
5
+ * operation toward the goal and hands control back only when it cannot continue on its own.
6
+ */
7
+ import { readFileSync, statSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import * as agent from "./agent.js";
10
+ import { Budget, execute, runAgent } from "./agent.js";
11
+ import { Browser } from "./browser.js";
12
+ import * as learn from "./learn.js";
13
+ import { gitState, logOnce, Recorder, summarize } from "./metrics.js";
14
+ import { actionSpace, offscreen, planText, resolve } from "./policies/base.js";
15
+ import { JevPolicy } from "./policies/jev.js";
16
+ import { describeError, pyJson, pyLen, pyRepr, pyRound, pyStr, stamp, utcIso } from "./py.js";
17
+ import * as runbook from "./runbook.js";
18
+ import * as session from "./session.js";
19
+ import { loadTask, TaskError } from "./tasks.js";
20
+ import { MutationUncertain, PolicyError, StalePage, } from "./types.js";
21
+ import * as workspace from "./workspace.js";
22
+ export const OK = 0;
23
+ export const FAILED = 1;
24
+ const STALE = 3;
25
+ export const UNCERTAIN = 4;
26
+ export const BUDGET = 5;
27
+ const DEFAULT_ATTEMPTS = 3;
28
+ const PERSON = "[person]";
29
+ const RECENT = 8; // Actions shown to Claude when an attempt stops.
30
+ /** What a command needs to stop with a message, as Python's SystemExit("...") did: stderr, exit code 1. */
31
+ export class CliExit extends Error {
32
+ name = "CliExit";
33
+ }
34
+ /** A command line that does not parse. Exit code 2. */
35
+ export class UsageError extends Error {
36
+ name = "UsageError";
37
+ }
38
+ /** What tests replace: Jev, and how Chrome starts. */
39
+ export const deps = {
40
+ policy: () => new JevPolicy(),
41
+ startChrome: session.startChrome,
42
+ };
43
+ let context = { out: [], err: () => { }, log: null };
44
+ function print(text = "") {
45
+ context.out.push(`${text}\n`);
46
+ }
47
+ /** Runs fn and returns what it printed. For tests of the output Claude reads. */
48
+ export function captured(fn) {
49
+ const saved = context;
50
+ context = { out: [], err: saved.err, log: null };
51
+ try {
52
+ const result = fn();
53
+ return { result, text: context.out.join("") };
54
+ }
55
+ finally {
56
+ context = saved;
57
+ }
58
+ }
59
+ // --- Output Claude reads -------------------------------------------------------------------
60
+ export function render(page) {
61
+ const lines = [`URL: ${page.url}`, `TITLE: ${page.title}`, "PAGE TEXT (untrusted data):", page.text, "ELEMENTS:"];
62
+ const [elements, , controls] = actionSpace(page.actions);
63
+ for (const element of elements) {
64
+ // Claude sees every option with its own line.
65
+ const details = element.value ? [`value=${pyRepr(element.value)}`] : [];
66
+ for (const key of ["checked", "selected", "expanded"]) {
67
+ if (key in element)
68
+ details.push(`${key}=${pyStr(element[key])}`);
69
+ }
70
+ const operations = element.operations.join(",");
71
+ lines.push(`[${element.index}] ${pyStr(element.role)} ${pyRepr(element.label)} ${details.join(" ")} (${operations})`);
72
+ for (const option of element.options ?? []) {
73
+ lines.push(` [${option.index}] ${String(option.label).split(" → ").at(-1)}`);
74
+ }
75
+ }
76
+ lines.push(`CONTROLS: ${[...controls.keys()].join(" ")}`);
77
+ const hidden = offscreen(page); // Claude always sees it, whatever Jev is given.
78
+ lines.push(`OFFSCREEN: ${hidden.above_px}px above, ${hidden.below_px}px below`);
79
+ if (page.regions?.length) {
80
+ lines.push("REGIONS (shown/all; change with replan --focus/--skip):");
81
+ for (const region of page.regions)
82
+ lines.push(` ${regionLine(region)}`);
83
+ if (page.omitted_regions)
84
+ lines.push(` ... ${page.omitted_regions} more`);
85
+ }
86
+ return lines.join("\n");
87
+ }
88
+ // biome-ignore lint/suspicious/noExplicitAny: a region from the page outline.
89
+ function regionLine(region) {
90
+ let line = `${region.key} [${region.position}] text ${region.shown_chars}/${region.text_chars}` +
91
+ ` actions ${region.shown_actions}/${region.actions}`;
92
+ if (region.offscreen_actions)
93
+ line += ` +${region.offscreen_actions} offscreen`;
94
+ return line + (region.view ? ` (${region.view})` : "");
95
+ }
96
+ function headline(page) {
97
+ return `URL: ${page.url}\nTITLE: ${page.title}`;
98
+ }
99
+ export function describePlan(plan, view = null) {
100
+ const text = planText(plan);
101
+ const lines = [`GOAL: ${plan.goal}`, "PLAN:", ...(text.length ? text : ["(goal only)"]).map((line) => ` ${line}`)];
102
+ if (plan.values.length)
103
+ lines.push(`VALUES: ${plan.values.map((value) => value.label).join(", ")}`);
104
+ for (const key of ["focus", "skip"]) {
105
+ if (view?.[key]?.length)
106
+ lines.push(`${key.toUpperCase()}: ${view[key].join(", ")}`);
107
+ }
108
+ return lines.join("\n");
109
+ }
110
+ // biome-ignore lint/suspicious/noExplicitAny: the session state.
111
+ export function recentActions(state) {
112
+ const rows = state.history.filter((h) => h.attempt === state.plan.attempt).slice(-RECENT);
113
+ const lines = rows.map((h) => ` ${h.step}. ${h.kind !== "human" ? h.operation : "HUMAN"} ${pyRepr(h.action)}` +
114
+ (h.text ? ` text=${pyRepr(h.text)}` : "") +
115
+ (h.page_changed ? "" : " (page unchanged)"));
116
+ return `ACTIONS THIS ATTEMPT:\n${lines.length ? lines.join("\n") : " (none)"}`;
117
+ }
118
+ // --- Plan and session state ----------------------------------------------------------------
119
+ function parseValues(pairs) {
120
+ return pairs.map((pair) => {
121
+ const at = pair.indexOf("=");
122
+ const label = at < 0 ? "" : pair.slice(0, at).trim();
123
+ if (at < 0 || !label)
124
+ throw new CliExit(`Expected --value LABEL=VALUE, got ${pyRepr(pair)}`);
125
+ return { label, value: pair.slice(at + 1) };
126
+ });
127
+ }
128
+ function mergeValues(current, added) {
129
+ const merged = new Map(current.map((value) => [value.label, value]));
130
+ for (const value of added)
131
+ merged.set(value.label, value);
132
+ return [...merged.values()];
133
+ }
134
+ /** A step written as "[person] Sign in" is one a person does in the window. */
135
+ function parseSteps(texts) {
136
+ return texts.map((text) => {
137
+ const human = text.startsWith(PERSON);
138
+ return { actor: human ? "human" : "jev", instruction: (human ? text.slice(PERSON.length) : text).trim() };
139
+ });
140
+ }
141
+ function requireSession() {
142
+ const state = session.load();
143
+ if (state === null)
144
+ throw new CliExit("No active session. Run: webhand start");
145
+ context.log = state.log;
146
+ return state;
147
+ }
148
+ async function openPage(state, url = null) {
149
+ const browser = await Browser.open(url, { port: state.port, view: state.view ?? null });
150
+ try {
151
+ state.page = await browser.observe();
152
+ }
153
+ finally {
154
+ await browser.close();
155
+ }
156
+ session.save(state);
157
+ }
158
+ function attemptLabel(state) {
159
+ return `attempt ${state.plan.attempt}/${state.max_attempts}`;
160
+ }
161
+ function defaultLog(name) {
162
+ return process.env.WEBHAND_LOG || join(workspace.home(), "runs", stamp(), `${name}.jsonl`);
163
+ }
164
+ // --- Commands ------------------------------------------------------------------------------
165
+ /** Everything learned, for Claude to plan from. */
166
+ async function commandCatalog(args) {
167
+ const project = workspace.projectRoot();
168
+ const projectRunbooks = runbook.root("project");
169
+ print(`RUNBOOKS (project) ${projectRunbooks}${project ? "" : " (not created)"}`);
170
+ print(`RUNBOOKS (user) ${runbook.root("user")}`);
171
+ let services;
172
+ try {
173
+ services = runbook.catalog();
174
+ }
175
+ catch (error) {
176
+ if (error instanceof runbook.RunbookError)
177
+ throw new CliExit(error.message);
178
+ throw error;
179
+ }
180
+ if (!services.length)
181
+ print("NOTHING LEARNED. Plan from the request, or teach a service with /webhand-learn");
182
+ for (const entry of services) {
183
+ const info = entry.info;
184
+ print(`SERVICE ${entry.service}${info ? ` (${info.scope})` : ""}`);
185
+ if (info) {
186
+ print(` ${info.description}\n base_url: ${info.base_url}`);
187
+ const login = info.login;
188
+ print(` login: ${login.required ? "required" : "not required"}${login.url ? ` (${login.url})` : ""}`);
189
+ for (const page of info.pages) {
190
+ print(` page: ${page.url} — ${page.purpose}`);
191
+ for (const region of page.regions) {
192
+ const fallback = region.default ? ` [${region.default}]` : "";
193
+ print(` region ${region.key}${fallback}: ${region.purpose}`);
194
+ }
195
+ }
196
+ for (const fact of info.facts)
197
+ print(` fact: ${fact}`);
198
+ }
199
+ else {
200
+ print(" (no service.toml)");
201
+ }
202
+ for (const procedure of entry.procedures) {
203
+ print(` PROCEDURE ${procedure.name} [${pyStr(procedure.status)}] (${procedure.scope}): ${pyStr(procedure.goal)}`);
204
+ print(` start_url: ${pyStr(procedure.start_url)}`);
205
+ for (const [key, description] of Object.entries(procedure.params))
206
+ print(` param ${key}: ${description}`);
207
+ if (procedure.human_steps)
208
+ print(` human steps: ${procedure.human_steps} (needs --headed)`);
209
+ for (const key of ["focus", "skip"]) {
210
+ if (procedure[key]?.length)
211
+ print(` ${key}: ${procedure[key].join(", ")}`);
212
+ }
213
+ }
214
+ }
215
+ const [chrome, note] = chooseChrome(args.chrome);
216
+ const profiles = session.listProfiles(chrome);
217
+ print(`CHROME: ${chrome}${note ? ` (${note})` : ""}`);
218
+ print(`SAVED PROFILES: ${profiles.length ? profiles.join(", ") : "(none)"}`);
219
+ return OK;
220
+ }
221
+ function chooseChrome(choice) {
222
+ try {
223
+ return session.chooseChrome(choice);
224
+ }
225
+ catch (error) {
226
+ if (error instanceof session.SessionError)
227
+ throw new CliExit(error.message);
228
+ throw error;
229
+ }
230
+ }
231
+ async function commandStart(args) {
232
+ if (session.load())
233
+ throw new CliExit("A session is active. Run: webhand finish --status abandoned");
234
+ let task = null;
235
+ if (args.task) {
236
+ try {
237
+ task = await loadTask(args.task);
238
+ }
239
+ catch (error) {
240
+ if (error instanceof TaskError)
241
+ throw new CliExit(error.message);
242
+ throw error;
243
+ }
244
+ }
245
+ if (task && args.goal)
246
+ throw new CliExit("A task supplies its own goal. Drop --goal");
247
+ let book = null;
248
+ let service = null;
249
+ let serviceName = null;
250
+ let profile;
251
+ let chrome;
252
+ let note;
253
+ try {
254
+ if (args.runbook) {
255
+ book = runbook.load(args.runbook, runbook.parseValues(args.param));
256
+ if (book.status !== "approved" && !args.allow_draft) {
257
+ throw new CliExit(`Runbook ${args.runbook} is a draft. Trial it with --allow-draft, then get it approved`);
258
+ }
259
+ }
260
+ serviceName = args.service || (book ? book.service : null);
261
+ service = serviceName ? runbook.loadService(serviceName) : null;
262
+ profile = session.parseSession(args.session);
263
+ [chrome, note] = session.chooseChrome(args.chrome);
264
+ }
265
+ catch (error) {
266
+ if (error instanceof runbook.RunbookError || error instanceof session.SessionError) {
267
+ throw new CliExit(error.message);
268
+ }
269
+ throw error;
270
+ }
271
+ const goal = task ? task.GOAL : args.goal || (book ? book.goal : null);
272
+ const url = task ? task.startUrl(process.cwd()) : args.url || (book ? book.start_url : null);
273
+ if (!(goal && url))
274
+ throw new CliExit("Give --task, --runbook, or both --goal and --url");
275
+ let steps = [];
276
+ if (args.step.length)
277
+ steps = parseSteps(args.step);
278
+ else if (book)
279
+ steps = book.steps;
280
+ let values = parseValues(args.value);
281
+ if (book) {
282
+ // Runbook parameters are Claude's values too, unless Claude labelled them itself.
283
+ const params = Object.entries(runbook.parseValues(args.param)).map(([label, value]) => ({ label, value }));
284
+ values = mergeValues(params, values);
285
+ }
286
+ if (steps.some((step) => step.actor === "human") && !args.headed) {
287
+ throw new CliExit("This plan has [person] steps. Add --headed so the person can see the window");
288
+ }
289
+ if (!process.env.TYPESAFE_API_KEY) {
290
+ throw new CliExit("TYPESAFE_API_KEY is not set. Set it as an environment variable");
291
+ }
292
+ const plan = {
293
+ goal,
294
+ steps,
295
+ values,
296
+ notes: [],
297
+ attempt: 1,
298
+ service: service ? { description: service.description, facts: service.facts } : null,
299
+ };
300
+ let chromeState;
301
+ try {
302
+ chromeState = await deps.startChrome({ headed: args.headed, profile, chrome });
303
+ }
304
+ catch (error) {
305
+ if (error instanceof session.SessionError)
306
+ throw new CliExit(error.message);
307
+ throw error;
308
+ }
309
+ const learned = runbook.view(runbook.serviceView(service), book);
310
+ const claudeView = { focus: args.focus, skip: args.skip };
311
+ const state = {
312
+ ...chromeState,
313
+ view_learned: learned,
314
+ view_claude: claudeView,
315
+ view: runbook.view(learned, claudeView),
316
+ task: args.task ?? null,
317
+ start_url: session.browserUrl(url, chrome),
318
+ plan,
319
+ runbook: book ? { name: book.name, status: book.status, digest: book.digest, scope: book.scope } : null,
320
+ history: [],
321
+ decisions: 0,
322
+ attempt_decisions: 0,
323
+ outcome: null,
324
+ outcomes: [],
325
+ max_attempts: args.max_attempts,
326
+ max_actions: args.max_actions,
327
+ max_decisions: args.max_decisions,
328
+ started: Date.now() / 1000,
329
+ log: defaultLog(args.task || "adhoc"),
330
+ };
331
+ context.log = state.log;
332
+ const recorder = new Recorder(state.log);
333
+ let browser = null;
334
+ try {
335
+ browser = await Browser.open(state.start_url, { port: chromeState.port, view: state.view });
336
+ state.page = await browser.observe();
337
+ recorder.event("run_start", {
338
+ task: args.task ?? null,
339
+ goal,
340
+ chrome: browser.version,
341
+ chrome_host: chrome,
342
+ session: profile ? "profile" : "new",
343
+ git: gitState(),
344
+ runbook: state.runbook,
345
+ service: serviceName,
346
+ view: state.view,
347
+ max_attempts: args.max_attempts,
348
+ started_at: utcIso(),
349
+ });
350
+ recorder.event("plan", {
351
+ attempt: 1,
352
+ steps: planText(plan),
353
+ values: values.map((v) => v.label),
354
+ view: state.view,
355
+ source: book && !args.step.length ? "runbook" : "claude",
356
+ });
357
+ }
358
+ catch (error) {
359
+ await session.stopChrome(chromeState);
360
+ throw error;
361
+ }
362
+ finally {
363
+ await browser?.close();
364
+ recorder.close();
365
+ }
366
+ session.save(state);
367
+ if (note)
368
+ print(`NOTE: ${note}`);
369
+ print(`${describePlan(plan, state.view)}\nSESSION: ${args.session} (${chrome} Chrome)\n${headline(state.page)}`);
370
+ print("NEXT: webhand run");
371
+ return OK;
372
+ }
373
+ /** What Claude needs for this outcome, and nothing more. */
374
+ export function report(state, result) {
375
+ const outcome = result.outcome;
376
+ print(`OUTCOME ${outcome} (${attemptLabel(state)}): ${pyStr(result.detail)}`);
377
+ if (outcome === agent.UNCERTAIN) {
378
+ print("Do not repeat or replan. Run: webhand finish --status error");
379
+ return UNCERTAIN;
380
+ }
381
+ if (outcome === agent.NEEDS_HUMAN) {
382
+ print(`${headline(state.page)}\nAsk the person to do this in the Chrome window, then: run --human-done`);
383
+ return OK;
384
+ }
385
+ if (outcome === agent.NEEDS_VALUE) {
386
+ print(`FIELD: ${pyJson(result.field)}`);
387
+ print("Give the value with: run --value 'LABEL=VALUE'. Never invent personal data; ask the person");
388
+ return OK;
389
+ }
390
+ print(`${recentActions(state)}\n${render(state.page)}`);
391
+ if (outcome === agent.GOAL_REPORTED) {
392
+ print("Check the page against the goal. If it is met: finish --status done. Otherwise: replan");
393
+ }
394
+ else if (outcome === agent.JEV_FAILED) {
395
+ print("Nothing was executed. Run again, replan, or act");
396
+ }
397
+ else {
398
+ print("NEXT: replan --reason '...' [--restart], act, or finish");
399
+ }
400
+ return OK;
401
+ }
402
+ /** Jev works toward the goal until it needs Claude or a person. */
403
+ async function commandRun(args) {
404
+ const state = requireSession();
405
+ const outcome = state.outcome;
406
+ if (outcome === agent.UNCERTAIN) {
407
+ print("REJECTED: the last action may have happened. Run: webhand finish --status error");
408
+ return UNCERTAIN;
409
+ }
410
+ if (outcome === agent.NEEDS_HUMAN && !args.human_done) {
411
+ print("REJECTED: a person is acting. When they are done: run --human-done");
412
+ return FAILED;
413
+ }
414
+ if (outcome === agent.NEEDS_VALUE && !args.value.length) {
415
+ print("REJECTED: this field needs run --value 'LABEL=VALUE'");
416
+ return FAILED;
417
+ }
418
+ if ([agent.GOAL_REPORTED, agent.BLOCKED, agent.STUCK, agent.ATTEMPT_BUDGET].includes(outcome)) {
419
+ print(`REJECTED: the attempt ended with ${outcome}. Run replan, act, or finish`);
420
+ return FAILED;
421
+ }
422
+ if (args.value.length) {
423
+ state.plan.values = mergeValues(state.plan.values, parseValues(args.value));
424
+ logOnce(state.log, "values", {
425
+ attempt: state.plan.attempt,
426
+ labels: parseValues(args.value).map((v) => v.label),
427
+ });
428
+ }
429
+ if (args.human_done) {
430
+ if (outcome !== agent.NEEDS_HUMAN) {
431
+ print("REJECTED: no person was asked to act");
432
+ return FAILED;
433
+ }
434
+ logOnce(state.log, "human_step", { status: "done", attempt: state.plan.attempt });
435
+ await openPage(state); // The person changed the page.
436
+ state.history.push({
437
+ step: state.history.length + 1,
438
+ attempt: state.plan.attempt,
439
+ kind: "human",
440
+ operation: "HUMAN",
441
+ action: "A person did the step that needed them",
442
+ text: null,
443
+ url: state.page.url,
444
+ page_changed: true,
445
+ });
446
+ }
447
+ state.outcome = null;
448
+ session.save(state);
449
+ const policy = deps.policy();
450
+ const browser = await Browser.open(null, { port: state.port, view: state.view ?? null });
451
+ const recorder = new Recorder(state.log);
452
+ let result;
453
+ try {
454
+ result = await runAgent(browser, policy, state.plan, recorder, new Budget(state.max_actions, state.max_decisions), {
455
+ history: state.history,
456
+ page: state.page,
457
+ decisions: state.attempt_decisions,
458
+ onChange: (page) => {
459
+ state.page = page;
460
+ session.save(state);
461
+ },
462
+ onDecision: (count) => {
463
+ state.attempt_decisions = count;
464
+ state.decisions += 1;
465
+ },
466
+ });
467
+ state.page = result.page;
468
+ state.outcome = result.outcome;
469
+ recorder.event("escalation", { reason: result.outcome, attempt: state.plan.attempt, detail: result.detail });
470
+ if (result.outcome === agent.NEEDS_HUMAN) {
471
+ recorder.event("human_step", { status: "requested", attempt: state.plan.attempt });
472
+ }
473
+ session.save(state);
474
+ }
475
+ finally {
476
+ await browser.close();
477
+ recorder.close();
478
+ await policy.close?.();
479
+ }
480
+ return report(state, result);
481
+ }
482
+ /** Claude revises the plan after an attempt fell short, and starts the next attempt. */
483
+ async function commandReplan(args) {
484
+ const state = requireSession();
485
+ const plan = state.plan;
486
+ if (state.outcome === agent.UNCERTAIN) {
487
+ print("REJECTED: the last action may have happened, so the run cannot continue. Run: finish --status error");
488
+ return UNCERTAIN;
489
+ }
490
+ if (plan.attempt >= state.max_attempts) {
491
+ print(`ATTEMPTS EXHAUSTED (${state.max_attempts}). Run: webhand finish --status blocked`);
492
+ return BUDGET;
493
+ }
494
+ if (args.step.length) {
495
+ const steps = parseSteps(args.step);
496
+ if (steps.some((step) => step.actor === "human") && !state.headed) {
497
+ print("REJECTED: [person] steps need a visible window, and this run is headless");
498
+ return FAILED;
499
+ }
500
+ plan.steps = steps;
501
+ }
502
+ plan.values = mergeValues(plan.values, parseValues(args.value));
503
+ const viewChanged = args.focus.length || args.skip.length;
504
+ if (viewChanged) {
505
+ // Claude's region choice is replaced, on top of what was learned.
506
+ state.view_claude = { focus: args.focus, skip: args.skip };
507
+ state.view = runbook.view(state.view_learned, state.view_claude);
508
+ }
509
+ const ended = state.outcome || "CLAUDE_STOPPED";
510
+ state.outcomes.push({ attempt: plan.attempt, outcome: ended, reason: args.reason });
511
+ plan.notes.push(`Attempt ${plan.attempt} ended with ${ended}. Claude: ${args.reason}`);
512
+ plan.attempt += 1;
513
+ state.outcome = null;
514
+ state.attempt_decisions = 0;
515
+ session.save(state);
516
+ logOnce(state.log, "attempt_end", { attempt: plan.attempt - 1, outcome: ended, reason: args.reason });
517
+ logOnce(state.log, "plan", {
518
+ attempt: plan.attempt,
519
+ steps: planText(plan),
520
+ values: plan.values.map((v) => v.label),
521
+ view: state.view ?? null,
522
+ restart: args.restart,
523
+ source: "claude",
524
+ });
525
+ if (args.restart)
526
+ await openPage(state, state.start_url); // Navigation only; no earlier mutation is repeated.
527
+ if (!args.restart && viewChanged)
528
+ await openPage(state); // Observe again with the new regions.
529
+ print(`${describePlan(plan, state.view ?? null)}\nATTEMPT ${plan.attempt}/${state.max_attempts}\n${headline(state.page)}`);
530
+ print("NEXT: webhand run");
531
+ return OK;
532
+ }
533
+ async function commandObserve() {
534
+ const state = requireSession();
535
+ await openPage(state);
536
+ print(render(state.page));
537
+ return OK;
538
+ }
539
+ /** Claude overrides Jev for one operation. */
540
+ async function commandAct(args) {
541
+ const state = requireSession();
542
+ if (state.outcome === agent.NEEDS_HUMAN) {
543
+ print("REJECTED: a person is acting. When they are done: run --human-done");
544
+ return FAILED;
545
+ }
546
+ if (state.outcome === agent.UNCERTAIN) {
547
+ print("REJECTED: the last action may have happened. Run: webhand finish --status error");
548
+ return UNCERTAIN;
549
+ }
550
+ if (agent.actionsIn(state.history, state.plan.attempt).length >= state.max_actions) {
551
+ print("BUDGET EXHAUSTED for this attempt. Run replan or finish --status budget");
552
+ return BUDGET;
553
+ }
554
+ let decision;
555
+ try {
556
+ decision = resolve(state.page, args.operation, args.target);
557
+ }
558
+ catch (error) {
559
+ if (!(error instanceof PolicyError))
560
+ throw error;
561
+ print(`REJECTED: ${error.message}`);
562
+ return FAILED;
563
+ }
564
+ if (decision.action === null) {
565
+ print("REJECTED: act runs one operation. Use run, replan, or finish");
566
+ return FAILED;
567
+ }
568
+ if (decision.action.kind === "fill" && args.text === null) {
569
+ print("REJECTED: TYPE_TEXT needs --text");
570
+ return FAILED;
571
+ }
572
+ decision.text = decision.action.kind === "fill" ? args.text : null;
573
+ state.decisions += 1;
574
+ session.save(state);
575
+ const browser = await Browser.open(null, { port: state.port, view: state.view ?? null });
576
+ const recorder = new Recorder(state.log);
577
+ try {
578
+ await execute(browser, state.page, decision, state.history, recorder, {
579
+ decidedBy: "claude",
580
+ attempt: state.plan.attempt,
581
+ onChange: (page) => {
582
+ state.page = page;
583
+ session.save(state);
584
+ },
585
+ });
586
+ if (state.outcome !== agent.ATTEMPT_BUDGET) {
587
+ state.outcome = null; // Claude stepped in, so Jev may continue this attempt with run.
588
+ session.save(state);
589
+ }
590
+ print(render(state.page));
591
+ return OK;
592
+ }
593
+ catch (error) {
594
+ if (error instanceof StalePage) {
595
+ state.page = await browser.observe();
596
+ session.save(state);
597
+ print(`STALE, nothing executed: ${error.message}\n${render(state.page)}`);
598
+ return STALE;
599
+ }
600
+ if (error instanceof MutationUncertain) {
601
+ state.outcome = agent.UNCERTAIN;
602
+ session.save(state);
603
+ print(`UNCERTAIN, do not repeat this action: ${error.message}. Run: webhand finish --status error`);
604
+ return UNCERTAIN;
605
+ }
606
+ throw error;
607
+ }
608
+ finally {
609
+ await browser.close();
610
+ recorder.close();
611
+ }
612
+ }
613
+ function runTotals(log) {
614
+ const calls = [];
615
+ const escalations = {};
616
+ const decidedBy = {};
617
+ let handoffs = 0;
618
+ let handoffChars = 0;
619
+ let notVisible = 0;
620
+ for (const line of readFileSync(log, "utf8").split("\n")) {
621
+ if (!line.trim())
622
+ continue;
623
+ const { type, ...event } = JSON.parse(line);
624
+ if (type === "call")
625
+ calls.push(event);
626
+ else if (type === "escalation")
627
+ escalations[event.reason] = (escalations[event.reason] ?? 0) + 1;
628
+ else if (type === "step")
629
+ decidedBy[event.decided_by] = (decidedBy[event.decided_by] ?? 0) + 1;
630
+ else if (type === "not_visible")
631
+ notVisible += 1;
632
+ else if (type === "handoff") {
633
+ handoffs += 1;
634
+ handoffChars += event.chars;
635
+ }
636
+ }
637
+ return {
638
+ ...summarize(calls),
639
+ escalations,
640
+ decided_by: decidedBy,
641
+ handoffs,
642
+ handoff_chars: handoffChars,
643
+ not_visible: notVisible,
644
+ };
645
+ }
646
+ /** Verifies the page independently. The status is what the agent claims, nothing more. */
647
+ async function commandFinish(args) {
648
+ const state = session.load();
649
+ if (state === null)
650
+ throw new CliExit("No active session. Run: webhand start");
651
+ let verdict = { success: null, evidence: "no verifier" };
652
+ try {
653
+ if (state.task) {
654
+ const browser = await Browser.open(null, { port: state.port });
655
+ try {
656
+ verdict = await (await loadTask(state.task)).verify(browser);
657
+ }
658
+ finally {
659
+ await browser.close();
660
+ }
661
+ }
662
+ }
663
+ catch (error) {
664
+ verdict = { success: false, evidence: describeError(error) };
665
+ }
666
+ finally {
667
+ await session.stopChrome(state);
668
+ session.clear();
669
+ }
670
+ const plan = state.plan;
671
+ const outcomes = [...state.outcomes, { attempt: plan.attempt, outcome: state.outcome, reason: args.reason }];
672
+ const totals = runTotals(state.log);
673
+ logOnce(state.log, "run_end", {
674
+ status: args.status,
675
+ reason: args.reason,
676
+ goal: plan.goal,
677
+ plan: planText(plan),
678
+ attempts: plan.attempt,
679
+ attempt_outcomes: outcomes,
680
+ actions: state.history.length,
681
+ decisions: state.decisions,
682
+ elapsed_ms: pyRound((Date.now() / 1000 - state.started) * 1000),
683
+ verified: verdict.success,
684
+ evidence: verdict.evidence,
685
+ ...totals,
686
+ });
687
+ print(`FINISHED status=${args.status} verified=${pyStr(verdict.success)} attempts=${plan.attempt} log=${state.log}`);
688
+ return OK;
689
+ }
690
+ function parentAlive(pid) {
691
+ try {
692
+ process.kill(pid, 0);
693
+ return true;
694
+ }
695
+ catch (error) {
696
+ return error.code === "EPERM";
697
+ }
698
+ }
699
+ /**
700
+ * Stops a long-running command on SIGTERM or SIGINT, or when the process that started it is gone,
701
+ * and still saves and closes. npx does not pass SIGTERM on, so stopping an `npx webhand learn` job
702
+ * ends npx alone; its end is the signal here.
703
+ */
704
+ function stopSignals() {
705
+ let stopped = false;
706
+ const parent = process.ppid;
707
+ const stop = () => {
708
+ stopped = true;
709
+ };
710
+ process.on("SIGTERM", stop);
711
+ process.on("SIGINT", stop);
712
+ return {
713
+ stopped: () => stopped || !parentAlive(parent),
714
+ release: () => {
715
+ process.off("SIGTERM", stop);
716
+ process.off("SIGINT", stop);
717
+ },
718
+ };
719
+ }
720
+ /** A person demonstrates a procedure. A long-running command, so run it in the background. */
721
+ async function commandLearn(args) {
722
+ let profile;
723
+ let chrome;
724
+ let note;
725
+ let runbookFile;
726
+ let serviceFile;
727
+ try {
728
+ runbookFile = runbook.path(args.name, args.scope);
729
+ const parts = String(args.name).split("/");
730
+ serviceFile = parts.length > 1 ? runbook.servicePath(parts[0], args.scope) : null;
731
+ profile = session.parseSession(args.session);
732
+ [chrome, note] = session.chooseChrome(args.chrome);
733
+ }
734
+ catch (error) {
735
+ if (error instanceof runbook.RunbookError || error instanceof session.SessionError) {
736
+ throw new CliExit(error.message);
737
+ }
738
+ throw error;
739
+ }
740
+ const stem = String(args.name).replaceAll("/", "-");
741
+ context.log = defaultLog(`learn-${stem}`);
742
+ const log = context.log;
743
+ let chromeState;
744
+ try {
745
+ chromeState = await session.startChrome({ headed: !args.headless, profile, chrome });
746
+ }
747
+ catch (error) {
748
+ if (error instanceof session.SessionError)
749
+ throw new CliExit(error.message);
750
+ throw error;
751
+ }
752
+ const deadline = performance.now() + args.max_minutes * 60_000;
753
+ let browser = null;
754
+ const recorder = new Recorder(log);
755
+ const signals = stopSignals(); // Stopping the job still saves and closes.
756
+ let counts;
757
+ try {
758
+ browser = await Browser.open(null, { port: chromeState.port });
759
+ recorder.event("learn_start", {
760
+ name: args.name,
761
+ url: args.url,
762
+ scope: args.scope,
763
+ chrome: browser.version,
764
+ chrome_host: chrome,
765
+ session: profile ? "profile" : "new",
766
+ git: gitState(),
767
+ started_at: utcIso(),
768
+ });
769
+ counts = await learn.record(browser, session.browserUrl(args.url, chrome), recorder, () => signals.stopped() || performance.now() >= deadline);
770
+ recorder.event("learn_end", { counts });
771
+ }
772
+ finally {
773
+ signals.release();
774
+ await browser?.close();
775
+ await session.stopChrome(chromeState);
776
+ recorder.close();
777
+ }
778
+ if (note)
779
+ print(`NOTE: ${note}`);
780
+ print(`RECORDED ${pyRepr(counts)} log=${log}`);
781
+ print(`WRITE THE RUNBOOK TO ${runbookFile}`);
782
+ if (serviceFile)
783
+ print(`WRITE THE SERVICE INFORMATION TO ${serviceFile}`);
784
+ if (counts.unsupported) {
785
+ print("WARNING: the record has operations the agent cannot reproduce. See its unsupported events");
786
+ }
787
+ return OK;
788
+ }
789
+ function isDir(path) {
790
+ try {
791
+ return statSync(path).isDirectory();
792
+ }
793
+ catch {
794
+ return false;
795
+ }
796
+ }
797
+ /** Saved webhand profiles. A person signs in here directly; nothing is recorded or sent to Jev. */
798
+ async function commandProfile(args) {
799
+ let chromeState;
800
+ let chrome;
801
+ try {
802
+ let note;
803
+ [chrome, note] = session.chooseChrome(args.chrome);
804
+ if (note)
805
+ print(`NOTE: ${note}`);
806
+ if (args.action === "list") {
807
+ const profiles = session.listProfiles(chrome);
808
+ print(`SAVED PROFILES (${chrome}): ${profiles.length ? profiles.join(", ") : "(none)"}`);
809
+ return OK;
810
+ }
811
+ if (!args.name)
812
+ throw new CliExit(`profile ${args.action} needs a NAME`);
813
+ const folder = session.profileDir(chrome, args.name);
814
+ if (args.action === "delete") {
815
+ if (!isDir(folder)) {
816
+ print(`No saved profile ${args.name}`);
817
+ return FAILED;
818
+ }
819
+ session.deleteProfile(folder);
820
+ print(`DELETED profile ${args.name}`);
821
+ return OK;
822
+ }
823
+ if (!args.url)
824
+ throw new CliExit("profile login needs --url");
825
+ const active = session.load();
826
+ if (active && active.saved_profile === args.name) {
827
+ throw new CliExit(`Profile ${args.name} is in use by the active run. Finish it first`);
828
+ }
829
+ chromeState = await session.startChrome({ headed: true, profile: args.name, chrome });
830
+ }
831
+ catch (error) {
832
+ if (error instanceof session.SessionError)
833
+ throw new CliExit(error.message);
834
+ throw error;
835
+ }
836
+ const deadline = performance.now() + args.max_minutes * 60_000;
837
+ const signals = stopSignals();
838
+ try {
839
+ await (await Browser.open(session.browserUrl(args.url, chrome), { port: chromeState.port })).close();
840
+ // stdout is buffered for the handoff count, so the person sees this on stderr right away.
841
+ context.err(`OPENED profile ${args.name}. Sign in in the Chrome window, then close the window\n`);
842
+ await session.waitUntilClosed(chromeState, () => signals.stopped() || performance.now() >= deadline);
843
+ }
844
+ finally {
845
+ signals.release();
846
+ await session.stopChrome(chromeState);
847
+ }
848
+ print(`SAVED profile ${args.name}. Use it with: start --session profile:${args.name}`);
849
+ return OK;
850
+ }
851
+ function commands() {
852
+ const chromeDefault = process.env.WEBHAND_CHROME ?? "auto";
853
+ const chromeOption = {
854
+ name: "chrome",
855
+ type: "string",
856
+ choices: [...session.CHROMES].sort(),
857
+ default: chromeDefault,
858
+ help: "auto uses the Windows Chrome on WSL when it is reachable",
859
+ };
860
+ const viewOptions = [
861
+ {
862
+ name: "focus",
863
+ type: "string",
864
+ multiple: true,
865
+ metavar: "REGION",
866
+ help: "A region to show first, such as form:予約",
867
+ },
868
+ { name: "skip", type: "string", multiple: true, metavar: "REGION", help: "A region to leave out" },
869
+ ];
870
+ return {
871
+ catalog: {
872
+ help: "List learned services, procedures, and saved profiles",
873
+ options: [chromeOption],
874
+ run: commandCatalog,
875
+ },
876
+ start: {
877
+ help: "Record Claude's plan and open the start page",
878
+ options: [
879
+ { name: "goal", type: "string" },
880
+ { name: "url", type: "string" },
881
+ { name: "step", type: "string", multiple: true, help: 'A plan step. "[person] ..." is done by a person' },
882
+ { name: "value", type: "string", multiple: true, metavar: "LABEL=VALUE", help: "Text Jev may type" },
883
+ { name: "service", type: "string", help: "Learned service information to give Jev, such as hotel-site" },
884
+ { name: "runbook", type: "string", help: "A learned procedure, such as hotel/filter" },
885
+ { name: "param", type: "string", multiple: true, metavar: "KEY=VALUE", help: "A runbook parameter" },
886
+ { name: "allow-draft", type: "boolean", help: "Trial a runbook no person has approved yet" },
887
+ ...viewOptions,
888
+ { name: "task", type: "string", help: "A task in tasks/ with an independent verify() (research repository)" },
889
+ { name: "session", type: "string", default: "new", help: "new (temporary) or profile:NAME (saved sign-in)" },
890
+ chromeOption,
891
+ { name: "headed", type: "boolean" },
892
+ { name: "max-attempts", type: "int", default: DEFAULT_ATTEMPTS },
893
+ { name: "max-actions", type: "int", default: Budget.MAX_ACTIONS, help: "Per attempt" },
894
+ { name: "max-decisions", type: "int", default: Budget.MAX_DECISIONS, help: "Per attempt" },
895
+ ],
896
+ run: commandStart,
897
+ },
898
+ run: {
899
+ help: "Jev: work toward the goal until Claude or a person is needed",
900
+ options: [
901
+ { name: "value", type: "string", multiple: true, metavar: "LABEL=VALUE", help: "Add or replace a value" },
902
+ { name: "human-done", type: "boolean", help: "The person finished what NEEDS_HUMAN asked" },
903
+ ],
904
+ run: commandRun,
905
+ },
906
+ replan: {
907
+ help: "Claude: revise the plan and start the next attempt",
908
+ options: [
909
+ { name: "reason", type: "string", required: true, help: "Why the last attempt fell short; Jev sees it" },
910
+ { name: "step", type: "string", multiple: true, help: "Replace the steps" },
911
+ { name: "value", type: "string", multiple: true, metavar: "LABEL=VALUE" },
912
+ { name: "restart", type: "boolean", help: "Open the start URL again before the next attempt" },
913
+ ...viewOptions,
914
+ ],
915
+ run: commandReplan,
916
+ },
917
+ act: {
918
+ help: "Claude: override Jev with one operation",
919
+ options: [{ name: "text", type: "string" }],
920
+ positionals: [{ name: "operation" }, { name: "target", optional: true }],
921
+ run: commandAct,
922
+ },
923
+ observe: { help: "Print the current page", options: [], run: commandObserve },
924
+ finish: {
925
+ help: "Verify, log, and close Chrome",
926
+ options: [
927
+ {
928
+ name: "status",
929
+ type: "string",
930
+ required: true,
931
+ choices: ["done", "blocked", "budget", "error", "abandoned"],
932
+ },
933
+ { name: "reason", type: "string" },
934
+ ],
935
+ run: commandFinish,
936
+ },
937
+ learn: {
938
+ help: "Record a person demonstrating a procedure",
939
+ options: [
940
+ { name: "name", type: "string", required: true, help: "Runbook name, such as hotel/filter" },
941
+ { name: "url", type: "string", required: true },
942
+ {
943
+ name: "scope",
944
+ type: "string",
945
+ choices: ["project", "user"],
946
+ default: "project",
947
+ help: "Where the runbook belongs: this project's .webhand or your ~/.webhand",
948
+ },
949
+ { name: "session", type: "string", default: "new", help: "new or profile:NAME, to demonstrate signed in" },
950
+ chromeOption,
951
+ { name: "max-minutes", type: "float", default: 30 },
952
+ { name: "headless", type: "boolean", hidden: true },
953
+ ],
954
+ run: commandLearn,
955
+ },
956
+ profile: {
957
+ help: "Saved profiles: list, login NAME --url URL, delete NAME",
958
+ options: [{ name: "url", type: "string" }, chromeOption, { name: "max-minutes", type: "float", default: 15 }],
959
+ positionals: [
960
+ { name: "action", choices: ["list", "login", "delete"] },
961
+ { name: "name", optional: true },
962
+ ],
963
+ run: commandProfile,
964
+ },
965
+ };
966
+ }
967
+ function usage(name, spec) {
968
+ const parts = [`usage: webhand ${name}`];
969
+ for (const option of spec.options) {
970
+ if (option.hidden)
971
+ continue;
972
+ const value = option.type === "boolean" ? "" : ` ${option.metavar ?? option.name.toUpperCase().replaceAll("-", "_")}`;
973
+ parts.push(option.required ? `--${option.name}${value}` : `[--${option.name}${value}]`);
974
+ }
975
+ for (const positional of spec.positionals ?? []) {
976
+ parts.push(positional.optional ? `[${positional.name}]` : positional.name);
977
+ }
978
+ return parts.join(" ");
979
+ }
980
+ function help(name, spec) {
981
+ const lines = [usage(name, spec), "", spec.help, ""];
982
+ for (const positional of spec.positionals ?? []) {
983
+ lines.push(` ${positional.name}${positional.choices ? ` {${positional.choices.join(",")}}` : ""}`);
984
+ }
985
+ for (const option of spec.options) {
986
+ if (option.hidden)
987
+ continue;
988
+ const details = [
989
+ option.help,
990
+ option.choices ? `one of: ${option.choices.join(", ")}` : null,
991
+ option.default !== undefined && option.type !== "boolean" ? `default: ${option.default}` : null,
992
+ option.multiple ? "repeatable" : null,
993
+ ].filter(Boolean);
994
+ lines.push(` --${option.name}${details.length ? ` ${details.join("; ")}` : ""}`);
995
+ }
996
+ return `${lines.join("\n")}\n`;
997
+ }
998
+ /** The package version, so a skill can tell which CLI it is talking to. */
999
+ function version() {
1000
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
1001
+ }
1002
+ function mainHelp(specs) {
1003
+ const lines = [
1004
+ `usage: webhand {${Object.keys(specs).join(",")}} ...`,
1005
+ "",
1006
+ "CLI for the Claude + Jev agent. Each call is one short process.",
1007
+ "",
1008
+ ];
1009
+ for (const [name, spec] of Object.entries(specs))
1010
+ lines.push(` ${name.padEnd(9)} ${spec.help}`);
1011
+ lines.push("", " --version Print the version", " --help Print this help; COMMAND --help prints a command's options");
1012
+ return `${lines.join("\n")}\n`;
1013
+ }
1014
+ /** Parses argv as argparse did. Throws UsageError, or returns help text to print. */
1015
+ export function parse(argv) {
1016
+ const specs = commands();
1017
+ const [name, ...rest] = argv;
1018
+ if (name === undefined)
1019
+ throw new UsageError(`the following arguments are required: command\n${mainHelp(specs)}`);
1020
+ if (name === "-h" || name === "--help")
1021
+ return { help: mainHelp(specs) };
1022
+ if (name === "-V" || name === "--version")
1023
+ return { help: `${version()}\n` };
1024
+ const spec = specs[name];
1025
+ if (!spec)
1026
+ throw new UsageError(`argument command: invalid choice: ${pyRepr(name)}`);
1027
+ const args = {};
1028
+ const positionals = [];
1029
+ const byName = new Map(spec.options.map((option) => [option.name, option]));
1030
+ for (const option of spec.options) {
1031
+ const key = option.name.replaceAll("-", "_");
1032
+ args[key] = option.multiple ? [] : option.type === "boolean" ? false : (option.default ?? null);
1033
+ }
1034
+ const fail = (message) => new UsageError(`${usage(name, spec)}\nwebhand ${name}: error: ${message}`);
1035
+ const seen = new Set();
1036
+ for (let i = 0; i < rest.length; i++) {
1037
+ const token = rest[i];
1038
+ if (token === "-h" || token === "--help")
1039
+ return { help: help(name, spec) };
1040
+ if (token === "--") {
1041
+ positionals.push(...rest.slice(i + 1));
1042
+ break;
1043
+ }
1044
+ if (!token.startsWith("--") || token === "-") {
1045
+ positionals.push(token);
1046
+ continue;
1047
+ }
1048
+ const at = token.indexOf("=");
1049
+ const optionName = at < 0 ? token.slice(2) : token.slice(2, at);
1050
+ const option = byName.get(optionName);
1051
+ if (!option)
1052
+ throw fail(`unrecognized arguments: ${token}`);
1053
+ const key = option.name.replaceAll("-", "_");
1054
+ seen.add(option.name);
1055
+ if (option.type === "boolean") {
1056
+ if (at >= 0)
1057
+ throw fail(`argument --${option.name}: ignored explicit argument ${pyRepr(token.slice(at + 1))}`);
1058
+ args[key] = true;
1059
+ continue;
1060
+ }
1061
+ let raw;
1062
+ if (at >= 0)
1063
+ raw = token.slice(at + 1);
1064
+ else {
1065
+ const next = rest[i + 1];
1066
+ if (next === undefined || (next.startsWith("-") && next.length > 1 && !/^-\d/.test(next))) {
1067
+ throw fail(`argument --${option.name}: expected one argument`);
1068
+ }
1069
+ raw = next;
1070
+ i++;
1071
+ }
1072
+ let value = raw;
1073
+ if (option.type === "int") {
1074
+ if (!/^\s*[-+]?\d+\s*$/.test(raw))
1075
+ throw fail(`argument --${option.name}: invalid int value: ${pyRepr(raw)}`);
1076
+ value = Number.parseInt(raw, 10);
1077
+ }
1078
+ else if (option.type === "float") {
1079
+ const number = Number(raw);
1080
+ if (!raw.trim() || Number.isNaN(number)) {
1081
+ throw fail(`argument --${option.name}: invalid float value: ${pyRepr(raw)}`);
1082
+ }
1083
+ value = number;
1084
+ }
1085
+ if (option.choices && !option.choices.includes(String(value))) {
1086
+ throw fail(`argument --${option.name}: invalid choice: ${pyRepr(value)} (choose from ${option.choices.map(pyRepr).join(", ")})`);
1087
+ }
1088
+ if (option.multiple)
1089
+ args[key].push(value);
1090
+ else
1091
+ args[key] = value;
1092
+ }
1093
+ const declared = spec.positionals ?? [];
1094
+ const missing = declared.filter((p, i) => !p.optional && positionals[i] === undefined);
1095
+ if (missing.length) {
1096
+ throw fail(`the following arguments are required: ${missing.map((p) => p.name).join(", ")}`);
1097
+ }
1098
+ if (positionals.length > declared.length) {
1099
+ throw fail(`unrecognized arguments: ${positionals.slice(declared.length).join(" ")}`);
1100
+ }
1101
+ declared.forEach((positional, i) => {
1102
+ const value = positionals[i] ?? null;
1103
+ if (value !== null && positional.choices && !positional.choices.includes(value)) {
1104
+ throw fail(`argument ${positional.name}: invalid choice: ${pyRepr(value)} (choose from ${positional.choices.map(pyRepr).join(", ")})`);
1105
+ }
1106
+ args[positional.name] = value;
1107
+ });
1108
+ const required = spec.options.filter((option) => option.required && !seen.has(option.name));
1109
+ if (required.length) {
1110
+ throw fail(`the following arguments are required: ${required.map((option) => `--${option.name}`).join(", ")}`);
1111
+ }
1112
+ return { command: name, args, run: spec.run };
1113
+ }
1114
+ const processIO = {
1115
+ out: (text) => {
1116
+ process.stdout.write(text);
1117
+ },
1118
+ err: (text) => {
1119
+ process.stderr.write(text);
1120
+ },
1121
+ };
1122
+ /**
1123
+ * Runs one command and returns its exit code. A CliExit or UsageError is thrown after the output is written,
1124
+ * so the caller prints its message and exits with 1 or 2.
1125
+ */
1126
+ export async function main(argv, io = processIO) {
1127
+ const parsed = parse(argv);
1128
+ if ("help" in parsed) {
1129
+ io.out(parsed.help);
1130
+ return OK;
1131
+ }
1132
+ context = { out: [], err: io.err, log: null };
1133
+ const current = context;
1134
+ // What Claude must read is a real cost of this design, so every handoff is sized and logged.
1135
+ try {
1136
+ return await parsed.run(parsed.args);
1137
+ }
1138
+ finally {
1139
+ const text = current.out.join("");
1140
+ io.out(text);
1141
+ if (current.log)
1142
+ logOnce(current.log, "handoff", { command: parsed.command, chars: pyLen(text) });
1143
+ }
1144
+ }