agentpath 0.0.0-stage → 0.1.0-alpha.2

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.
Files changed (127) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +101 -2
  3. package/THIRD_PARTY_NOTICES +12 -0
  4. package/apps/demo-site/dist/site.js +92 -0
  5. package/apps/studio/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  6. package/apps/studio/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  7. package/apps/studio/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  8. package/apps/studio/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  9. package/apps/studio/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  10. package/apps/studio/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  11. package/apps/studio/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  12. package/apps/studio/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  13. package/apps/studio/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  14. package/apps/studio/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  15. package/apps/studio/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  16. package/apps/studio/dist/assets/index-DH4wJPHm.js +67 -0
  17. package/apps/studio/dist/assets/index-DrnNh2ip.css +1 -0
  18. package/apps/studio/dist/index.html +14 -0
  19. package/audit.md +173 -0
  20. package/autonomous-mode.md +104 -0
  21. package/ci.md +118 -0
  22. package/coding-agents.md +143 -0
  23. package/concepts.md +145 -0
  24. package/contracts.md +356 -0
  25. package/examples/tasks/ambiguous.json +98 -0
  26. package/examples/tasks/assertion-failure.json +98 -0
  27. package/examples/tasks/broken.json +98 -0
  28. package/examples/tasks/fixed.json +98 -0
  29. package/examples/tasks/recovery.json +19 -0
  30. package/images/compare-recovery-desktop.jpg +0 -0
  31. package/images/compare-variants-desktop.jpg +0 -0
  32. package/images/overview-desktop.jpg +0 -0
  33. package/images/run-autonomous-passed-desktop.jpg +0 -0
  34. package/images/run-failed-desktop.jpg +0 -0
  35. package/images/run-failed-mobile.jpg +0 -0
  36. package/images/run-missing-artifact-desktop.jpg +0 -0
  37. package/images/task-editor-laptop.jpg +0 -0
  38. package/installation.md +102 -0
  39. package/ledger.md +62 -0
  40. package/licenses/-fontsource-variable-geist-mono.txt +93 -0
  41. package/licenses/-fontsource-variable-geist.txt +93 -0
  42. package/licenses/lucide-react.txt +43 -0
  43. package/licenses/react-dom.txt +21 -0
  44. package/licenses/react.txt +21 -0
  45. package/licenses/scheduler.txt +21 -0
  46. package/licenses/tailwindcss.txt +21 -0
  47. package/licenses/zod.txt +21 -0
  48. package/package.json +165 -4
  49. package/packages/cli/bin/agentpath.js +39 -0
  50. package/packages/cli/dist/audit-rerun.js +384 -0
  51. package/packages/cli/dist/audit.js +387 -0
  52. package/packages/cli/dist/change-summaries.js +87 -0
  53. package/packages/cli/dist/ci-report.js +88 -0
  54. package/packages/cli/dist/demo.js +88 -0
  55. package/packages/cli/dist/doctor.js +265 -0
  56. package/packages/cli/dist/explain.js +89 -0
  57. package/packages/cli/dist/git.js +7 -0
  58. package/packages/cli/dist/inspect.js +118 -0
  59. package/packages/cli/dist/ledger.js +509 -0
  60. package/packages/cli/dist/local.js +102 -0
  61. package/packages/cli/dist/main.js +708 -0
  62. package/packages/cli/dist/mcp.js +231 -0
  63. package/packages/cli/dist/paths.js +6 -0
  64. package/packages/cli/dist/playwright-fixture.js +185 -0
  65. package/packages/cli/dist/playwright-reporter.js +49 -0
  66. package/packages/cli/dist/tasks.js +37 -0
  67. package/packages/cli/dist/test-source.js +283 -0
  68. package/packages/cli/dist/watch.js +96 -0
  69. package/packages/contracts/dist/agent-settings.js +18 -0
  70. package/packages/contracts/dist/agent.js +175 -0
  71. package/packages/contracts/dist/audit.js +115 -0
  72. package/packages/contracts/dist/guidance.js +339 -0
  73. package/packages/contracts/dist/index.js +14 -0
  74. package/packages/contracts/dist/inspect.js +63 -0
  75. package/packages/contracts/dist/ledger.js +80 -0
  76. package/packages/contracts/dist/local.js +171 -0
  77. package/packages/contracts/dist/outcomes.js +94 -0
  78. package/packages/contracts/dist/platform.js +105 -0
  79. package/packages/contracts/dist/playwright-live.js +76 -0
  80. package/packages/contracts/dist/policy.js +93 -0
  81. package/packages/contracts/dist/run.js +178 -0
  82. package/packages/contracts/dist/task-issues.js +39 -0
  83. package/packages/contracts/dist/task.js +185 -0
  84. package/packages/contracts/dist/watch.js +57 -0
  85. package/packages/core/dist/action-feedback.js +103 -0
  86. package/packages/core/dist/actions.js +160 -0
  87. package/packages/core/dist/agent-loop.js +122 -0
  88. package/packages/core/dist/artifacts.js +156 -0
  89. package/packages/core/dist/assertions.js +120 -0
  90. package/packages/core/dist/autonomous.js +1 -0
  91. package/packages/core/dist/browser.js +196 -0
  92. package/packages/core/dist/compare.js +141 -0
  93. package/packages/core/dist/control-state.js +62 -0
  94. package/packages/core/dist/diagnostics.js +134 -0
  95. package/packages/core/dist/evidence-diff.js +93 -0
  96. package/packages/core/dist/evidence.js +203 -0
  97. package/packages/core/dist/index.js +22 -0
  98. package/packages/core/dist/inspect.js +257 -0
  99. package/packages/core/dist/integrity.js +176 -0
  100. package/packages/core/dist/liveness.js +114 -0
  101. package/packages/core/dist/local-files.js +61 -0
  102. package/packages/core/dist/locators.js +214 -0
  103. package/packages/core/dist/model-provider.js +88 -0
  104. package/packages/core/dist/observation.js +257 -0
  105. package/packages/core/dist/playwright-live.js +519 -0
  106. package/packages/core/dist/playwright-results.js +543 -0
  107. package/packages/core/dist/policy.js +182 -0
  108. package/packages/core/dist/privacy.js +93 -0
  109. package/packages/core/dist/recovery.js +54 -0
  110. package/packages/core/dist/retention.js +204 -0
  111. package/packages/core/dist/run-index.js +177 -0
  112. package/packages/core/dist/run-plan.js +28 -0
  113. package/packages/core/dist/run-repository.js +518 -0
  114. package/packages/core/dist/runner.js +913 -0
  115. package/packages/core/dist/storage.js +63 -0
  116. package/packages/core/dist/task-fingerprint.js +36 -0
  117. package/packages/core/dist/test-change-rerun.js +84 -0
  118. package/packages/core/dist/test-changes.js +896 -0
  119. package/packages/core/dist/timing.js +41 -0
  120. package/packages/core/dist/watch.js +165 -0
  121. package/packages/server/dist/index.js +265 -0
  122. package/packages/server/dist/task-store.js +103 -0
  123. package/quickstart.md +85 -0
  124. package/security.md +136 -0
  125. package/try-on-your-repo.md +54 -0
  126. package/understanding-results.md +159 -0
  127. package/writing-tasks.md +196 -0
@@ -0,0 +1,708 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { browserObservationsSchema, configuredExpectation, guidanceFor, planOperation, runIdSchema, runListQuerySchema, SCHEMA_VERSION, taskOperation, taskSchema } from "#agentpath/contracts";
6
+ import { compareRuns, executePrune, failureGuidance, parseAge, planPrune, RunRepository, runTask } from "#agentpath/core";
7
+ import { studioPort } from "#agentpath/server";
8
+ import { junitXml, markdownSummary } from "./ci-report.js";
9
+ import { demo } from "./demo.js";
10
+ import { auditCommand } from "./audit.js";
11
+ import { ledgerCommand } from "./ledger.js";
12
+ import { explainCommand } from "./explain.js";
13
+ import { loadTaskFiles } from "./tasks.js";
14
+ import { displayPath } from "./paths.js";
15
+ import { watchCommand } from "./watch.js";
16
+ import { inspectCommand } from "./inspect.js";
17
+ import { mcpCommand } from "./mcp.js";
18
+ import { doctor, installBrowser } from "./doctor.js";
19
+ import { errorCode, portOption, startStudio, startupError, waitForShutdown, withShutdown } from "./local.js";
20
+ const MAX_RUN_TASKS = 50;
21
+ /** Each worker runs its own Chromium, so the cap keeps a typo from starting dozens of browsers. */
22
+ const MAX_WORKERS = 8;
23
+ const usage = `Usage:
24
+ agentpath --version
25
+ agentpath doctor [--json] [--port <port>] [--workspace <directory>]
26
+ agentpath browser install
27
+ agentpath demo [--port <studio-port>] [--site-port <demo-port>]
28
+ agentpath init [task.json] [--url <url>]
29
+ agentpath run <task.json>... [--runs-dir <directory>] [--json] [--capture-text]
30
+ [--junit <file>] [--summary <file>] [--workers <n>]
31
+ agentpath inspect <url> [--allow <host>...] [--mobile] [--json]
32
+ agentpath explain [<playwright-output-dir>] [--json]
33
+ agentpath audit --base <commit> [--head <commit>] [<path>...] [--json] [--summary <file>] [--fail-on-weakening]
34
+ [--rerun [--config <file>] [--project <name>] [--rerun-timeout <seconds>]
35
+ [--fail-on-change-needed]]
36
+ agentpath ledger [--head <commit>] [--days <n>] [<path>...] [--json] [--summary <file>]
37
+ agentpath watch <task.json>... --every <interval> [--rounds <n>] [--state <file>]
38
+ [--runs-dir <directory>] [--json] [--capture-text]
39
+ agentpath mcp --allow <host> [--allow <host>...] [--runs-dir <directory>] [--capture-text]
40
+ agentpath report <run-id> [--json] [--runs-dir <directory>]
41
+ agentpath compare <run-a> <run-b> [--variants] [--json] [--runs-dir <directory>]
42
+ agentpath runs list [--status <s,...>] [--task <id>] [--since <iso>] [--until <iso>]
43
+ [--limit <n>] [--cursor <c>] [--json] [--runs-dir <directory>]
44
+ agentpath runs reindex [--runs-dir <directory>]
45
+ agentpath runs verify <run-id> [--json] [--runs-dir <directory>]
46
+ agentpath runs prune --older-than <age> [--include-stale] [--include-abandoned]
47
+ [--include-unreadable] [--yes] [--json] [--runs-dir <directory>]
48
+ agentpath studio [--port <port>] [--workspace <directory>]
49
+ agentpath --help
50
+ agentpath <command> --help
51
+
52
+ Use --shutdown-on-stdin-close with demo or studio when supervising them via a pipe.
53
+
54
+ Run, watch, inspect and mcp open real pages. Use them only on development or test sites you are
55
+ authorized to operate.
56
+
57
+ Exit codes: 0 passed or command succeeded, 1 task failed or integrity mismatch, 2 usage or
58
+ runtime error, 130 cancelled via SIGINT, 143 cancelled via SIGTERM.
59
+
60
+ run takes up to 50 task files and runs them one after another, or up to --workers (at most 8) at
61
+ a time, each in its own browser. Results print in the order of the files either way. It exits 1 if
62
+ any failed. --junit writes a JUnit XML report and --summary a Markdown summary for a CI job or pull
63
+ request; with --json, each task prints one JSON line. The task format is in writing-tasks.md,
64
+ shipped with the package, and agentpath init writes an example. Use it only on sites you are authorized to test.
65
+
66
+ watch runs deterministic tasks in rounds, one after another, and starts the next round --every
67
+ (such as 30s, 10m or 2h) after the previous one finished. It alerts only when a task's verdict
68
+ changes between passed and failed; a first verdict is a baseline. The state file (default
69
+ watch-state.json next to the runs directory) is rebuilt from run directories when missing or
70
+ unreadable. With --json, each round prints one JSON line. watch exits 0 when its rounds end,
71
+ whatever the verdicts. Use it only on sites you are authorized to test.
72
+
73
+ explain reads the error-context.md files (and trace.zip, when traces are kept) that Playwright wrote
74
+ under test-results, or under the directory given. It runs nothing and visits nothing. It explains
75
+ page-level getByRole with a string name and getByLabel, and names any other locator it does not
76
+ support instead of guessing. Page text in its output comes from the page and is untrusted.
77
+
78
+ audit lists the Playwright tests changed between two commits (--head defaults to HEAD) and marks
79
+ the changes that can let a test pass when it would fail: a skip or fixme, a removed or conditional
80
+ assertion, a removed step, a removed test, .first(). Without --rerun it reads test source from git
81
+ only and runs nothing. Files it cannot read are listed, never guessed.
82
+ With --fail-on-weakening it exits 1 when a test was weakened and 3 when anything was not read.
83
+ --rerun, in a clean checkout at --head with dependencies installed, runs the old version of each
84
+ changed test beside the new one with the project's own Playwright, and says whether the change is
85
+ needed for the test to pass on this build. That runs the project's tests, configuration and web
86
+ server, with no egress boundary from AgentPath: use it only where you would run those tests.
87
+ With --fail-on-change-needed it exits 1 when a weakened test's change is needed, a needed
88
+ change's evidence points to the site, or .only was added, and 3 when a weakened test's rerun
89
+ was inconclusive.
90
+ --summary writes a Markdown summary for a CI job or pull request (appended to $GITHUB_STEP_SUMMARY).
91
+ The kinds of change and the rerun rules are in audit.md, shipped with the package.
92
+
93
+ ledger lists the Playwright tests turned off at --head (default HEAD) by skip, fixme or fail,
94
+ oldest first, with the commit that turned each off and whether it says flaky or came from a bot
95
+ or agent. It also lists tests turned off and back on in the last --days days (default 365), and
96
+ whether the commit that turned one back on also changed product files. It reads test source and
97
+ first-parent history from git only and runs nothing. --summary writes a Markdown summary for a CI
98
+ job. Details are in ledger.md, shipped with the package.
99
+
100
+ mcp serves inspect, validate, run and report to a coding agent over stdio. The browser reaches only
101
+ the --allow hosts, and the agent cannot widen them; allow only sites you are authorized to test.
102
+ Register it with, for example:
103
+ claude mcp add agentpath -- agentpath mcp --allow 127.0.0.1:3000
104
+
105
+ runs prune only previews unless --yes is given. Ages use m, h, d, or w, such as 30d.
106
+
107
+ inspect opens one page behind the same egress guard as run and lists the role and name pairs,
108
+ form labels and unnamed controls a task can target, confirmed with the exact locator a step
109
+ uses. Without --allow, only the URL's own host is reachable. Every --allow host is an exact host
110
+ or host:port, and the URL must be on one of them; add the hosts a page loads scripts from. It
111
+ performs no actions and saves no run. Page text is quoted, stripped of control characters and
112
+ cut at 160 characters; at most 200 targets and 100 labels are listed. --json prints one object
113
+ in the inspection v1 shape (contracts.md, shipped with the package). A page that fails to load,
114
+ answers with HTTP 400 or higher, or redirects off the allowlist exits 2.
115
+ Use it only on sites you are authorized to test.`;
116
+ const summaries = {
117
+ doctor: "Check Node.js, storage, the Studio port, Chromium and optional model endpoints.",
118
+ browser: "Download the Chromium build AgentPath runs tasks in (agentpath browser install).",
119
+ demo: "Start a sample shop and Studio with four recorded runs. No model or API key needed.",
120
+ init: "Write a sample task file, or with --url a starting task that opens one page of your own site.",
121
+ run: "Run task files in real Chromium. Independent assertions decide each verdict.",
122
+ inspect: "List the roles, names and labels a task can target on one page, without acting.",
123
+ audit: "List the Playwright test changes between two commits that can hide a bug: skips, removed assertions and steps.",
124
+ ledger: "List the Playwright tests turned off by skip, fixme or fail: since when, by which commit, and which were turned back on.",
125
+ explain: "Read a Playwright output directory offline and say, for each failed locator, whether the page points to the test or the site.",
126
+ watch: "Run deterministic tasks on a schedule and alert only when a verdict changes.",
127
+ mcp: "Serve AgentPath to a coding agent over the Model Context Protocol, bounded by the hosts you allow.",
128
+ report: "Print a stored run: verdicts, the failing step, evidence and guidance.",
129
+ compare: "Compare two stored runs step by step.",
130
+ runs: "List, verify, reindex or prune stored runs.",
131
+ studio: "Open the local Studio web app for tasks and runs.",
132
+ };
133
+ /** Help for one command: its summary, its usage lines and, when there is one, its paragraph from the full usage. */
134
+ export function commandHelp(command) {
135
+ const summary = summaries[command];
136
+ if (!summary)
137
+ return undefined;
138
+ const lines = usage.split("\n");
139
+ const own = [];
140
+ for (let i = 0; i < lines.length; i++) {
141
+ if (!(lines[i].startsWith(` agentpath ${command} `) || lines[i] === ` agentpath ${command}`))
142
+ continue;
143
+ own.push(lines[i]);
144
+ while (lines[i + 1]?.startsWith(" ") && !lines[i + 1].trimStart().startsWith("agentpath"))
145
+ own.push(lines[++i]);
146
+ }
147
+ const paragraph = usage.split("\n\n").find((block) => block.startsWith(`${command} `) || (command === "runs" && block.startsWith("runs prune")));
148
+ return [summary, "", "Usage:", ...own, ...(paragraph ? ["", paragraph] : []), "", "All commands: agentpath --help"].join("\n");
149
+ }
150
+ function bytes(value) {
151
+ return value >= 1024 * 1024 ? `${(value / 1024 / 1024).toFixed(1)} MiB` : value >= 1024 ? `${(value / 1024).toFixed(1)} KiB` : `${value} B`;
152
+ }
153
+ async function runsCommand(args) {
154
+ const [subcommand, ...rest] = args;
155
+ const { positionals, values } = parseArgs({
156
+ args: rest, allowPositionals: true,
157
+ options: {
158
+ "runs-dir": { type: "string" }, json: { type: "boolean" }, status: { type: "string" }, task: { type: "string" },
159
+ since: { type: "string" }, until: { type: "string" }, limit: { type: "string" }, cursor: { type: "string" },
160
+ "older-than": { type: "string" }, "include-stale": { type: "boolean" }, "include-abandoned": { type: "boolean" },
161
+ "include-unreadable": { type: "boolean" }, yes: { type: "boolean" },
162
+ },
163
+ });
164
+ const runs = new RunRepository(values["runs-dir"]);
165
+ if (subcommand === "list") {
166
+ if (positionals.length)
167
+ throw new Error("runs list takes no positional arguments.");
168
+ const query = runListQuerySchema.safeParse(Object.fromEntries(Object.entries({
169
+ status: values.status, taskId: values.task, since: values.since, until: values.until, limit: values.limit, cursor: values.cursor,
170
+ }).filter(([, value]) => value !== undefined)));
171
+ if (!query.success)
172
+ throw new Error(`Invalid listing options\n${query.error.issues.map((issue) => `${issue.path.join(".")} — ${issue.message}`).join("\n")}`);
173
+ const page = await runs.list(query.data);
174
+ if (values.json)
175
+ console.log(JSON.stringify(page));
176
+ else {
177
+ for (const run of page.runs) {
178
+ console.log([run.runId, run.status.padEnd(10), run.startedAt ?? "-".padEnd(24), run.taskId ?? "-"].join(" "));
179
+ }
180
+ if (!page.runs.length)
181
+ console.log("No matching runs. Try clearing filters or run a task with agentpath run.");
182
+ if (page.nextCursor)
183
+ console.log(`More runs: --cursor ${page.nextCursor}`);
184
+ }
185
+ return 0;
186
+ }
187
+ if (subcommand === "reindex") {
188
+ if (positionals.length)
189
+ throw new Error("runs reindex takes no positional arguments.");
190
+ const result = await runs.reindex();
191
+ if (!result.available)
192
+ throw new Error("The run index is unavailable. Run agentpath doctor and confirm the selected runs directory exists.");
193
+ console.log(`Indexed ${result.indexed} runs (${result.unreadable} unreadable) from ${displayPath(runs.root)}`);
194
+ return 0;
195
+ }
196
+ if (subcommand === "verify") {
197
+ if (positionals.length !== 1)
198
+ throw new Error("runs verify requires one run ID.");
199
+ const id = runIdSchema.parse(positionals[0]);
200
+ if (!(await runs.ids()).includes(id))
201
+ throw new Error("Run not found.");
202
+ const report = await runs.integrity(id);
203
+ if (values.json)
204
+ console.log(JSON.stringify(report));
205
+ else {
206
+ const meaning = {
207
+ consistent: "Files match the recorded SHA-256 digests.",
208
+ mismatch: "Files differ from the recorded digests.",
209
+ legacy: "This recording predates integrity digests.",
210
+ unsealed: "Finalization did not complete; no digests were sealed.",
211
+ "sidecar-missing": "The integrity record is missing from a recording that should have one.",
212
+ "sidecar-invalid": "The integrity record is unreadable.",
213
+ }[report.status];
214
+ console.log(`${report.status.toUpperCase()} ${id}\n${meaning}`);
215
+ for (const issue of report.issues)
216
+ console.log(` ${issue.problem.padEnd(10)} ${issue.path}`);
217
+ console.log("Digests detect changes relative to the recorded manifest. They do not prove who wrote the files.");
218
+ }
219
+ return report.status === "consistent" || report.status === "legacy" ? 0 : 1;
220
+ }
221
+ if (subcommand === "prune") {
222
+ if (positionals.length)
223
+ throw new Error("runs prune takes no positional arguments.");
224
+ if (!values["older-than"])
225
+ throw new Error("runs prune requires --older-than, such as --older-than 30d.");
226
+ const options = {
227
+ olderThanMs: parseAge(values["older-than"]), includeStale: values["include-stale"],
228
+ includeAbandoned: values["include-abandoned"], includeUnreadable: values["include-unreadable"],
229
+ };
230
+ const plan = await planPrune(runs, options);
231
+ if (!values.yes) {
232
+ if (values.json)
233
+ console.log(JSON.stringify({ dryRun: true, plan }));
234
+ else {
235
+ console.log(`Dry run: ${plan.candidates.length} runs started before ${plan.cutoff} would be deleted (${bytes(plan.totalBytes)}).`);
236
+ for (const entry of plan.candidates)
237
+ console.log(` ${entry.runId} ${entry.status.padEnd(10)} ${bytes(entry.bytes)}`);
238
+ const reasons = Object.entries(Object.groupBy(plan.excluded, (entry) => entry.reason));
239
+ for (const [reason, entries] of reasons)
240
+ console.log(`Kept ${entries?.length ?? 0} older runs: ${reason}`);
241
+ if (plan.interruptedDeletions)
242
+ console.log(`${plan.interruptedDeletions} interrupted deletions will be completed.`);
243
+ console.log("Nothing was deleted. Re-run with --yes to delete these runs.");
244
+ }
245
+ return 0;
246
+ }
247
+ const outcome = await executePrune(runs, plan, options);
248
+ if (values.json)
249
+ console.log(JSON.stringify({ dryRun: false, plan, outcome }));
250
+ else {
251
+ console.log(`Deleted ${outcome.deleted.length} runs (${bytes(outcome.reclaimedBytes)}).`);
252
+ for (const entry of outcome.skipped)
253
+ console.log(` Skipped ${entry.runId}: ${entry.reason}`);
254
+ for (const id of outcome.failed)
255
+ console.log(` Failed to delete ${id}`);
256
+ if (outcome.completedInterruptedDeletions)
257
+ console.log(`Completed ${outcome.completedInterruptedDeletions} interrupted deletions.`);
258
+ if (outcome.remainingInterruptedDeletions)
259
+ console.log(`${outcome.remainingInterruptedDeletions} interrupted deletions could not be completed; they stay in the trash directory and are retried next time.`);
260
+ }
261
+ return outcome.failed.length ? 2 : 0;
262
+ }
263
+ throw new Error("Unknown runs subcommand. Use list, reindex, verify, or prune.");
264
+ }
265
+ function sampleTask() {
266
+ return taskSchema.parse({
267
+ schemaVersion: SCHEMA_VERSION,
268
+ id: "demo-cart",
269
+ name: "Add two Trail Mugs to cart",
270
+ baseUrl: "http://127.0.0.1:4173",
271
+ goal: "Add two Trail Mugs to the shopping cart and verify the cart quantity.",
272
+ mode: "deterministic",
273
+ allowedHosts: ["127.0.0.1:4173"],
274
+ steps: [
275
+ { action: "navigate", url: "/fixed" },
276
+ { action: "click", target: { by: "role", role: "link", name: "Trail Mug" } },
277
+ { action: "select", target: { by: "role", role: "combobox", name: "Quantity" }, option: { by: "value", value: "2" } },
278
+ { action: "click", target: { by: "role", role: "button", name: "Add to cart" } },
279
+ ],
280
+ assertions: [
281
+ { assert: "text", target: { by: "role", role: "region", name: "Cart" }, contains: "Trail Mug × 2" },
282
+ ],
283
+ });
284
+ }
285
+ /** A starting task for one page of the user's own site: open it and check the address. Targets come from inspect. */
286
+ function starterTask(raw) {
287
+ let url;
288
+ try {
289
+ url = new URL(raw);
290
+ }
291
+ catch {
292
+ throw new Error("--url must be a full http or https URL, such as http://127.0.0.1:3000/signup.");
293
+ }
294
+ if (url.protocol !== "http:" && url.protocol !== "https:")
295
+ throw new Error("--url must be a full http or https URL, such as http://127.0.0.1:3000/signup.");
296
+ const path = `${url.pathname}${url.search}`;
297
+ // Runs, watch state and the index are filed by task ID, so each page gets its own, from its host and path.
298
+ const id = `${url.host}${url.pathname}`.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 80).replace(/-+$/, "") || "my-page";
299
+ const parsed = taskSchema.safeParse({
300
+ schemaVersion: SCHEMA_VERSION,
301
+ id,
302
+ name: `Open ${url.host}${url.pathname}`.slice(0, 200),
303
+ baseUrl: url.origin,
304
+ goal: `Open ${path} and check that the page loads at that address.`,
305
+ mode: "deterministic",
306
+ allowedHosts: [url.host],
307
+ steps: [{ action: "navigate", url: path }],
308
+ assertions: [{ assert: "url", pattern: `${url.origin}${url.pathname}*` }],
309
+ });
310
+ if (!parsed.success)
311
+ throw new Error(`AgentPath cannot write a task for this URL: ${parsed.error.issues[0]?.message ?? "invalid"}.`);
312
+ return parsed.data;
313
+ }
314
+ async function main(args) {
315
+ if (args.length === 0 || (args.length === 1 && ["--help", "-h"].includes(args[0] ?? ""))) {
316
+ console.log(usage);
317
+ return 0;
318
+ }
319
+ const [command, ...rest] = args;
320
+ if (command === "help" || rest.some((arg) => arg === "--help" || arg === "-h")) {
321
+ const topic = command === "help" ? rest[0] : command;
322
+ const help = topic === undefined ? usage : commandHelp(topic);
323
+ if (!help)
324
+ throw new Error(`Unknown command ${JSON.stringify(topic)}. Use --help for usage.`);
325
+ console.log(help);
326
+ return 0;
327
+ }
328
+ if (command === "init") {
329
+ const { positionals, values } = parseArgs({ args: rest, allowPositionals: true, options: { url: { type: "string" } } });
330
+ if (positionals.length > 1)
331
+ throw new Error("init takes at most one output path.");
332
+ const task = values.url === undefined ? sampleTask() : starterTask(values.url);
333
+ const path = resolve(positionals[0] ?? "agentpath.task.json");
334
+ try {
335
+ await writeFile(path, JSON.stringify(task, null, 2) + "\n", { flag: "wx", mode: 0o600 });
336
+ }
337
+ catch (error) {
338
+ if (errorCode(error) === "EEXIST")
339
+ throw new Error("The task file already exists. Choose another output path.");
340
+ if (errorCode(error) === "ENOENT")
341
+ throw new Error("The target directory does not exist. Create it or choose a different output path.");
342
+ throw error;
343
+ }
344
+ const shown = displayPath(path);
345
+ if (values.url !== undefined) {
346
+ console.log(`Created ${shown} for ${values.url}\nNext:\n 1. List the roles, names and labels a step can target: agentpath inspect ${JSON.stringify(values.url)}\n 2. Add steps and assertions (writing-tasks.md, shipped with the package), then: agentpath run ${shown}`);
347
+ return 0;
348
+ }
349
+ console.log(`Created ${shown}\nNext:\n 1. Start the sample site: agentpath demo --site-port 4173\n 2. In another terminal: agentpath run ${shown}`);
350
+ return 0;
351
+ }
352
+ if (command === "doctor")
353
+ return doctor(rest);
354
+ if (command === "browser")
355
+ return installBrowser(rest);
356
+ if (command === "demo")
357
+ return demo(rest);
358
+ if (command === "studio") {
359
+ const { values } = parseArgs({ args: rest, options: {
360
+ port: { type: "string" }, workspace: { type: "string" }, "shutdown-on-stdin-close": { type: "boolean" },
361
+ } });
362
+ const port = portOption(values.port, studioPort);
363
+ return withShutdown(async (signal) => {
364
+ const { server, url } = await startStudio(values.workspace, port).catch((error) => {
365
+ throw startupError(error);
366
+ });
367
+ try {
368
+ console.log(`AgentPath Studio at ${url}\nPress Ctrl+C to stop Studio.`);
369
+ await waitForShutdown(signal);
370
+ }
371
+ finally {
372
+ await server.close();
373
+ }
374
+ }, values["shutdown-on-stdin-close"]);
375
+ }
376
+ if (command === "runs")
377
+ return runsCommand(rest);
378
+ if (command === "inspect")
379
+ return inspectCommand(rest);
380
+ if (command === "explain")
381
+ return explainCommand(rest);
382
+ if (command === "audit")
383
+ return auditCommand(rest);
384
+ if (command === "ledger")
385
+ return ledgerCommand(rest);
386
+ if (command === "watch")
387
+ return watchCommand(rest);
388
+ if (command === "mcp")
389
+ return mcpCommand(rest);
390
+ if (command === "report" || command === "compare") {
391
+ const { positionals, values } = parseArgs({
392
+ args: rest, allowPositionals: true,
393
+ options: { "runs-dir": { type: "string" }, json: { type: "boolean" }, ...(command === "compare" ? { variants: { type: "boolean" } } : {}) },
394
+ });
395
+ const runs = new RunRepository(values["runs-dir"]);
396
+ async function lookup(id) {
397
+ if (!(await runs.ids()).includes(id))
398
+ throw new Error("Run not found.");
399
+ return runs.detail(id);
400
+ }
401
+ const runId = (value) => {
402
+ const parsed = runIdSchema.safeParse(value);
403
+ if (!parsed.success)
404
+ throw new Error(`${JSON.stringify(value)} is not a run ID. List runs with agentpath runs list.`);
405
+ return parsed.data;
406
+ };
407
+ if (command === "report") {
408
+ if (positionals.length !== 1)
409
+ throw new Error("report requires one run ID.");
410
+ const detail = await lookup(runId(positionals[0]));
411
+ if (values.json)
412
+ console.log(JSON.stringify(detail, null, 2));
413
+ else
414
+ for (const line of describeRun(detail))
415
+ console.log(line);
416
+ }
417
+ else {
418
+ if (positionals.length !== 2)
419
+ throw new Error("compare requires two run IDs.");
420
+ const baseline = runId(positionals[0]);
421
+ const candidate = runId(positionals[1]);
422
+ const mode = values.variants ? "scenario-variants" : "same-task";
423
+ await Promise.all([lookup(baseline), lookup(candidate)]);
424
+ const [a, b] = await Promise.all([runs.comparisonDetail(baseline), runs.comparisonDetail(candidate)]);
425
+ let comparison;
426
+ try {
427
+ comparison = compareRuns(a, b, mode);
428
+ }
429
+ catch (error) {
430
+ if (mode === "same-task" && error instanceof Error && /scenario-variants/.test(error.message)) {
431
+ throw new Error(`${error.message} Add --variants to compare two variants of a scenario.`);
432
+ }
433
+ throw error;
434
+ }
435
+ if (values.json)
436
+ console.log(JSON.stringify(comparison, null, 2));
437
+ else
438
+ for (const line of describeComparison(comparison))
439
+ console.log(line);
440
+ }
441
+ return 0;
442
+ }
443
+ if (command !== "run")
444
+ throw new Error(`Unknown command ${JSON.stringify(command)}. Use --help for usage.`);
445
+ const { positionals, values } = parseArgs({
446
+ args: rest, allowPositionals: true,
447
+ options: {
448
+ "runs-dir": { type: "string" }, json: { type: "boolean" }, "capture-text": { type: "boolean" },
449
+ junit: { type: "string" }, summary: { type: "string" }, workers: { type: "string" },
450
+ },
451
+ });
452
+ if (positionals.length === 0)
453
+ throw new Error("run requires at least one task JSON path.");
454
+ const workers = values.workers === undefined ? 1 : Number(values.workers);
455
+ if (!Number.isInteger(workers) || workers < 1 || workers > MAX_WORKERS || !/^\d+$/.test(values.workers ?? "1")) {
456
+ throw new Error(`--workers must be a whole number from 1 to ${MAX_WORKERS}.`);
457
+ }
458
+ if (positionals.length > MAX_RUN_TASKS)
459
+ throw new Error(`run accepts at most ${MAX_RUN_TASKS} task files.`);
460
+ // Validate every task before any browser starts, so a typo in the last file fails fast.
461
+ const tasks = await loadTaskFiles(positionals);
462
+ const controller = new AbortController();
463
+ const abort = () => controller.abort();
464
+ let interrupted = 130;
465
+ const terminate = () => {
466
+ interrupted = 143;
467
+ abort();
468
+ };
469
+ process.on("SIGINT", abort);
470
+ process.on("SIGTERM", terminate);
471
+ const entries = [];
472
+ // A run that could not be recorded at all (for example a full disk) stops the batch, but the reports still
473
+ // carry every verdict recorded before it.
474
+ let runError;
475
+ const started = [];
476
+ const startNext = () => {
477
+ if (started.length >= tasks.length || runError !== undefined || controller.signal.aborted)
478
+ return;
479
+ const { task } = tasks[started.length];
480
+ started.push(runTask(task, {
481
+ runsDirectory: values["runs-dir"],
482
+ signal: controller.signal,
483
+ captureText: values["capture-text"] === true,
484
+ }).then((stored) => ({ stored }), (error) => {
485
+ runError ??= error;
486
+ return { error };
487
+ }).finally(() => startNext()));
488
+ };
489
+ try {
490
+ for (let worker = 0; worker < workers; worker++)
491
+ startNext();
492
+ for (let index = 0; index < started.length; index++) {
493
+ const outcome = await started[index];
494
+ if (!("stored" in outcome))
495
+ continue;
496
+ const { file, task, document } = tasks[index];
497
+ const { directory, result } = outcome.stored;
498
+ const browser = await browserObservations(directory);
499
+ const guidance = result.status === "failed" ? failureGuidance(task, result.failure, browser, document) : undefined;
500
+ entries.push({ file, name: task.name, result, ...(guidance ? { guidance } : {}) });
501
+ if (values.json) {
502
+ console.log(JSON.stringify({
503
+ ...(tasks.length > 1 ? { file } : {}),
504
+ directory, result,
505
+ ...(browser?.blockedHosts ? { blockedHosts: browser.blockedHosts } : {}),
506
+ ...(browser?.failedRequests ? { failedRequests: browser.failedRequests } : {}),
507
+ ...(guidance ? { guidance } : {}),
508
+ }));
509
+ }
510
+ else {
511
+ if (entries.length > 1)
512
+ console.log("");
513
+ // The runs directory as the user gave it (or the default), so output shows neither more nor less of the path than they typed.
514
+ console.log(`${result.status.toUpperCase()} ${result.taskId} (${result.mode})\nArtifacts ${join(values["runs-dir"] ?? ".agentpath/runs", basename(directory))}`);
515
+ if (result.status === "failed") {
516
+ const { category, location, observed, expected } = result.failure;
517
+ const where = location.phase === "startup" ? "startup" : `${location.phase} ${location.index + 1}`;
518
+ const pointer = guidance?.taskPath ? ` (task file ${guidance.taskPath})` : "";
519
+ console.log(`${category} at ${where}${pointer}\n${observed}\nExpected ${expected}`);
520
+ const requested = requestedTarget(taskOperation(task, result.failure)?.target);
521
+ if (requested)
522
+ console.log(requested);
523
+ const configured = configuredExpectation(task, result.failure);
524
+ if (configured)
525
+ console.log(configured);
526
+ for (const line of failureFindings(result.failure, browser, guidance))
527
+ console.log(line);
528
+ if (category === "BROWSER_ERROR" && location.phase === "startup") {
529
+ console.log("Run agentpath doctor to diagnose Chromium startup. Install the managed browser with agentpath browser install.");
530
+ }
531
+ console.log(`Details: agentpath report ${result.runId}${values["runs-dir"] ? ` --runs-dir ${values["runs-dir"]}` : ""}`);
532
+ }
533
+ }
534
+ }
535
+ }
536
+ finally {
537
+ // Every started run is awaited above, so none is still writing its record when the reports are written.
538
+ process.removeListener("SIGINT", abort);
539
+ process.removeListener("SIGTERM", terminate);
540
+ }
541
+ const passed = entries.filter((entry) => entry.result.status === "passed").length;
542
+ const failed = entries.filter((entry) => entry.result.status === "failed").length;
543
+ if (tasks.length > 1 && !values.json) {
544
+ const notRun = tasks.length - entries.length;
545
+ console.log(`\n${passed} passed, ${failed} failed${entries.length - passed - failed ? `, ${entries.length - passed - failed} cancelled` : ""}${notRun ? `, ${notRun} not run` : ""} of ${tasks.length} tasks`);
546
+ }
547
+ if (values.junit)
548
+ await writeFile(values.junit, junitXml(entries));
549
+ if (values.summary)
550
+ await writeFile(values.summary, markdownSummary(entries), { flag: values.summary === process.env.GITHUB_STEP_SUMMARY ? "a" : "w" });
551
+ if (runError)
552
+ throw runError;
553
+ if (controller.signal.aborted || entries.some((entry) => entry.result.status === "cancelled"))
554
+ return interrupted;
555
+ return failed ? 1 : 0;
556
+ }
557
+ async function browserObservations(directory) {
558
+ try {
559
+ const parsed = browserObservationsSchema.safeParse(JSON.parse(await readFile(join(directory, "browser-observations.json"), "utf8")));
560
+ return parsed.success ? parsed.data : undefined;
561
+ }
562
+ catch {
563
+ return undefined;
564
+ }
565
+ }
566
+ const relations = {
567
+ "same-name-other-role": "different role; same name, or one differing only in case, spacing or punctuation",
568
+ "case-or-spacing": "differs in case, spacing or punctuation",
569
+ "similar-name": "similar name",
570
+ "accessible-name-matches-label": "accessible name equals the requested label",
571
+ "visible-text-matches": "shows this text, but its accessible name is the quoted one",
572
+ };
573
+ function where(location) {
574
+ return location.phase === "startup" ? "startup" : `${location.phase} ${location.index + 1}`;
575
+ }
576
+ /** A readable summary of a stored run; --json prints the full record. */
577
+ /** The target the failed operation asked for, as the task names it. */
578
+ function requestedTarget(target) {
579
+ if (!target)
580
+ return undefined;
581
+ return target.by === "label" ? `Requested: the control labelled ${JSON.stringify(target.label)}`
582
+ : `Requested: ${target.role}${target.name === undefined ? "" : ` named ${JSON.stringify(target.name)}`}`;
583
+ }
584
+ function describeRun(detail) {
585
+ const { summary, result } = detail;
586
+ const lines = [`${summary.status.toUpperCase()} ${summary.taskId ?? "(unknown task)"}${summary.mode ? ` (${summary.mode})` : ""} · run ${summary.runId}`];
587
+ if (summary.startedAt)
588
+ lines.push(`Started ${summary.startedAt}${summary.durationMs !== undefined ? `, took ${summary.durationMs} ms` : ""}`);
589
+ if (result) {
590
+ // Totals come from the plan, so operations the run never reached still count.
591
+ const count = (items, planned = items.length) => `${items.filter((item) => item.status === "passed").length} of ${Math.max(planned, items.length)} passed`;
592
+ lines.push(`Steps: ${count(result.steps, detail.plan?.steps.length)}. Assertions: ${count(result.assertions, detail.plan?.assertions.length)}.`);
593
+ }
594
+ if (result?.status === "failed") {
595
+ const { failure } = result;
596
+ const guidance = guidanceFor(planOperation(detail.plan, failure), failure, detail.browserObservations);
597
+ lines.push(`${failure.category} at ${where(failure.location)}${guidance.taskPath ? ` (task file ${guidance.taskPath})` : ""}`, failure.observed, `Expected ${failure.expected}`);
598
+ const requested = requestedTarget(planOperation(detail.plan, failure)?.target);
599
+ if (requested)
600
+ lines.push(requested);
601
+ lines.push(...failureFindings(failure, detail.browserObservations, guidance));
602
+ }
603
+ if (detail.evidenceAvailability?.integrity && !["consistent", "legacy"].includes(detail.evidenceAvailability.integrity)) {
604
+ lines.push(`Integrity: ${detail.evidenceAvailability.integrity}. Check with agentpath runs verify ${summary.runId}.`);
605
+ }
606
+ lines.push(`Full record: agentpath report ${summary.runId} --json`);
607
+ return lines;
608
+ }
609
+ /** A readable summary of a comparison; --json prints the full comparison. */
610
+ function describeComparison(comparison) {
611
+ const { summary, interpretation } = comparison;
612
+ const lines = [`${interpretation.label}. ${interpretation.explanation}`,
613
+ `Baseline ${summary.baselineRunId} ${summary.baselineStatus} → candidate ${summary.candidateRunId} ${summary.candidateStatus}`];
614
+ if (summary.firstDivergence) {
615
+ const { location, baseline, candidate } = summary.firstDivergence;
616
+ lines.push(`First difference at ${where(location)}: ${baseline} → ${candidate}`);
617
+ }
618
+ if (comparison.durationDeltaMs)
619
+ lines.push(`Duration change: ${comparison.durationDeltaMs > 0 ? "+" : ""}${comparison.durationDeltaMs} ms`);
620
+ lines.push("Full comparison: add --json");
621
+ return lines;
622
+ }
623
+ /** Recorded facts that help act on a failure. Page-provided names and hosts are quoted, never interpreted. */
624
+ function failureFindings(failure, browser, guidance) {
625
+ const lines = [];
626
+ const { observation } = failure;
627
+ if (observation.observedText !== undefined) {
628
+ lines.push(`Observed text: ${JSON.stringify(observation.observedText)}${observation.observedTextTruncated ? " (truncated)" : ""}`);
629
+ }
630
+ if (observation.nearMatches?.length) {
631
+ const options = observation.nearMatches.every((match) => match.role === "option");
632
+ lines.push(options ? "Similar options in the control (not used; options match exactly):" : "Similar targets on the page (not used; names must match exactly):");
633
+ for (const match of observation.nearMatches)
634
+ lines.push(` ${match.role} ${JSON.stringify(match.name)} — ${relations[match.relation]}`);
635
+ }
636
+ if (observation.nearMatchesWithheld) {
637
+ const count = observation.nearMatchesWithheld;
638
+ lines.push(`${count} similar ${count === 1 ? "target was" : "targets were"} not listed: input had been typed, and names the task does not use are withheld after input.`);
639
+ lines.push(" Rerun with --capture-text on a test site to list them with typed values redacted.");
640
+ }
641
+ if (observation.nearMatchesRedacted) {
642
+ const count = observation.nearMatchesRedacted;
643
+ lines.push(`${count} similar ${count === 1 ? "target was" : "targets were"} not listed: ${count === 1 ? "its name contains" : "their names contain"} a value the task types. Text capture does not list ${count === 1 ? "it" : "them"} either.`);
644
+ }
645
+ if (observation.pageMessages?.length) {
646
+ const captured = observation.pageMessages.some((message) => message.text !== undefined);
647
+ lines.push("Messages visible at failure:");
648
+ for (const message of observation.pageMessages) {
649
+ lines.push(` ${message.role} ${message.text !== undefined ? JSON.stringify(message.text) : `(text ${message.textState === "empty" ? "empty" : message.textState === "withheld" ? "withheld: it contained an input value" : "not captured"})`}`);
650
+ }
651
+ if (!captured && observation.pageMessages.some((message) => message.textState === "not-captured")) {
652
+ lines.push(" Rerun with --capture-text on a test site to record message text.");
653
+ }
654
+ }
655
+ if (observation.embeddedFrames) {
656
+ lines.push(`The page had ${observation.embeddedFrames} embedded frame${observation.embeddedFrames === 1 ? "" : "s"} (iframe). Targets and text inside frames are not searched.`);
657
+ }
658
+ if (observation.disallowedHost !== undefined)
659
+ lines.push(`Blocked destination host: ${JSON.stringify(observation.disallowedHost)}`);
660
+ if (browser?.blockedHosts?.length) {
661
+ const hosts = browser.blockedHosts.map(({ host, requests }) => `${JSON.stringify(host)} (${requests})`).join(", ");
662
+ lines.push(`Blocked requests to hosts outside allowedHosts (not necessarily the cause): ${hosts}${browser.blockedHostsTruncated ? ", and more" : ""}`);
663
+ }
664
+ if (browser?.pageErrors || browser?.consoleErrors) {
665
+ const counted = [browser.pageErrors ? `${browser.pageErrors} uncaught page error${browser.pageErrors === 1 ? "" : "s"}` : "",
666
+ browser.consoleErrors ? `${browser.consoleErrors} console error${browser.consoleErrors === 1 ? "" : "s"}` : ""].filter(Boolean).join(" and ");
667
+ lines.push(`The page reported ${counted} during the run (counted; messages are not recorded). Open the page in a browser's developer tools to read them.`);
668
+ }
669
+ if (browser?.failedRequests?.length) {
670
+ lines.push("Failed requests to allowed hosts:");
671
+ for (const entry of browser.failedRequests) {
672
+ lines.push(` ${entry.method} ${entry.host}${entry.path} → ${entry.status ?? "network error"} (${entry.resourceType}${entry.count > 1 ? `, ${entry.count} times` : ""})`);
673
+ }
674
+ }
675
+ if (guidance?.findings.length) {
676
+ lines.push("Diagnosis:");
677
+ const label = { task: "points to the task", site: "points to the site", unclear: "fact" };
678
+ for (const finding of guidance.findings)
679
+ lines.push(` [${label[finding.pointsTo]}] ${finding.statement}`);
680
+ }
681
+ if (guidance?.suggestedChanges.length) {
682
+ lines.push("Possible task changes (JSON Patch; not applied, each assumes the page is correct):");
683
+ for (const change of guidance.suggestedChanges) {
684
+ lines.push(` ${JSON.stringify({ op: change.op, path: change.path, value: change.value })}`);
685
+ lines.push(` because ${change.because}`);
686
+ }
687
+ }
688
+ if (failure.investigation)
689
+ lines.push(`Next: ${failure.investigation}`);
690
+ return lines;
691
+ }
692
+ try {
693
+ process.exitCode = await main(process.argv.slice(2));
694
+ }
695
+ catch (error) {
696
+ const code = errorCode(error);
697
+ if (code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" || code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE" || code === "ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL") {
698
+ const option = /'([^']+)'/.exec(error instanceof Error ? error.message : "")?.[1];
699
+ console.error(`${code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" ? "Unknown option" : code === "ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL" ? "Unexpected argument" : "Invalid value for"}${option ? ` ${option}` : ""}. See agentpath --help.`);
700
+ }
701
+ else if (["EROFS", "EACCES", "EPERM"].includes(code ?? "")) {
702
+ console.error("Permission denied accessing the task or run storage. Choose a readable task and a writable workspace or --runs-dir.");
703
+ }
704
+ else {
705
+ console.error(error instanceof Error ? error.message : "AgentPath could not complete the command.");
706
+ }
707
+ process.exitCode = 2;
708
+ }