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,283 @@
1
+ import { posix } from "node:path";
2
+ import { MAX_SOURCE_BYTES, readTests, UnreadableSource } from "#agentpath/core";
3
+ import { git } from "./git.js";
4
+ export const TEST_FILE = /\.(spec|test)\.(ts|mts|cts|js|mjs|cjs)$/;
5
+ export const JSX_TEST_FILE = /\.(spec|test)\.(tsx|jsx)$/;
6
+ export const CONFIG_FILE = /(^|\/)playwright\.config\.[cm]?[jt]s$/;
7
+ const SOURCE_FILE = /\.[cm]?[jt]s$/;
8
+ const under = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
9
+ /** A configuration's source without comments. Strings are kept whole, so a quoted glob holding a slash and a star is not a comment. */
10
+ export function stripComments(source) {
11
+ let out = "";
12
+ let quote = "";
13
+ for (let index = 0; index < source.length; index++) {
14
+ const char = source[index];
15
+ if (quote) {
16
+ out += char;
17
+ if (char === "\\")
18
+ out += source[++index] ?? "";
19
+ else if (char === quote)
20
+ quote = "";
21
+ continue;
22
+ }
23
+ if (char === "'" || char === '"' || char === "`") {
24
+ quote = char;
25
+ out += char;
26
+ continue;
27
+ }
28
+ if (char === "/" && source[index + 1] === "/") {
29
+ while (index < source.length && source[index] !== "\n")
30
+ index++;
31
+ out += "\n";
32
+ continue;
33
+ }
34
+ if (char === "/" && source[index + 1] === "*") {
35
+ const end = source.indexOf("*/", index + 2);
36
+ index = end < 0 ? source.length : end + 1;
37
+ out += " ";
38
+ continue;
39
+ }
40
+ out += char;
41
+ }
42
+ return out;
43
+ }
44
+ /**
45
+ * A string `testMatch` glob as a regular expression on a repository path, with Playwright's own rule: a pattern not
46
+ * starting with `**` + `/` gets one in front, and the match ignores case and includes dot files. Only a fixed grammar is
47
+ * accepted: literal name characters, `/`, `*`, `**` as a whole segment, `?`, and one level of `{a,b}` without stars. Anything
48
+ * else gives undefined. Repository text never becomes a regular expression of its own.
49
+ */
50
+ export function globMatcher(glob) {
51
+ if (glob.length > 200 || glob.startsWith("/") || glob.startsWith("./"))
52
+ return undefined;
53
+ const pattern = glob.startsWith("**/") ? glob : `**/${glob}`;
54
+ const segments = pattern.split("/");
55
+ if (segments.some((segment) => !segment))
56
+ return undefined;
57
+ const parts = [];
58
+ for (const [index, segment] of segments.entries()) {
59
+ const last = index === segments.length - 1;
60
+ if (segment === "**") {
61
+ parts.push(last ? ".*" : "(?:[^/]*/)*");
62
+ continue;
63
+ }
64
+ let out = "";
65
+ for (let at = 0; at < segment.length; at++) {
66
+ const char = segment[at];
67
+ if (char === "*") {
68
+ if (segment[at + 1] === "*")
69
+ return undefined;
70
+ out += "[^/]*";
71
+ }
72
+ else if (char === "?")
73
+ out += "[^/]";
74
+ else if (char === "{") {
75
+ const end = segment.indexOf("}", at);
76
+ const options = end < 0 ? [] : segment.slice(at + 1, end).split(",");
77
+ if (options.length < 2 || options.some((option) => !/^[A-Za-z0-9._@+-]+$/.test(option)))
78
+ return undefined;
79
+ out += `(?:${options.map((option) => option.replace(/[.+]/g, "\\$&")).join("|")})`;
80
+ at = end;
81
+ }
82
+ else if (/[A-Za-z0-9_@-]/.test(char))
83
+ out += char;
84
+ else if (char === "." || char === "+")
85
+ out += `\\${char}`;
86
+ else
87
+ return undefined;
88
+ }
89
+ parts.push(last ? out : `${out}/`);
90
+ }
91
+ return new RegExp(`^${parts.join("")}$`, "i");
92
+ }
93
+ /** The file-name ending a `testMatch` regular expression literal selects (/.*\.e2e\.tsx?/), or undefined. Only endings are read. */
94
+ function regexSuffixes(source) {
95
+ const rest = source.replace(/^\^?(?:\.[*+])?/, "").replace(/\$$/, "");
96
+ const match = /^((?:\\\.|[A-Za-z0-9_.-])+?)(?:([A-Za-z])\?)?$/.exec(rest);
97
+ if (!match)
98
+ return undefined;
99
+ const suffix = match[1].replace(/\\\./g, ".");
100
+ if (!suffix.includes("."))
101
+ return undefined;
102
+ return [suffix, ...(match[2] ? [suffix + match[2]] : [])];
103
+ }
104
+ /** The string and regular expression literals of a `testMatch` value written as one literal or an array of them, across lines. */
105
+ function testMatchLiterals(value) {
106
+ const one = String.raw `(?:'[^'\n]*'|"[^"\n]*"|\`[^\`$\n]*\`|\/(?:[^/\\\n]|\\.)+\/[a-z]*)`;
107
+ const expression = new RegExp(String.raw `^\s*(?:${one}|\[\s*${one}(?:\s*,\s*${one})*\s*,?\s*\])`).exec(value)?.[0];
108
+ if (!expression)
109
+ return undefined;
110
+ const strings = [...expression.matchAll(/(['"`])([^'"`\n]*)\1/g)].map((match) => match[2]);
111
+ const regexes = [...expression.matchAll(/(?:^|[[,\s])\/((?:[^/\\\n]|\\.)+)\/[a-z]*/g)].map((match) => match[1]);
112
+ return strings.length || regexes.length ? { strings, regexes } : undefined;
113
+ }
114
+ /**
115
+ * Reads one `testMatch` value: one string or regular expression literal, or an array of them. String globs are
116
+ * matched as Playwright matches them (see globMatcher); a regular expression only when it ends in a fixed file-name
117
+ * ending. Anything else, such as a variable, gives undefined: the value cannot be applied without running it.
118
+ */
119
+ export function readTestMatch(value) {
120
+ const literals = testMatchLiterals(value);
121
+ if (!literals)
122
+ return undefined;
123
+ const { strings, regexes } = literals;
124
+ const read = { globs: [], suffixes: [], patterns: [] };
125
+ for (const glob of strings) {
126
+ const matcher = globMatcher(glob);
127
+ if (!matcher)
128
+ return undefined;
129
+ read.globs.push(matcher);
130
+ read.patterns.push(glob.startsWith("**/") ? glob : `**/${glob}`);
131
+ }
132
+ for (const source of regexes) {
133
+ const suffixes = regexSuffixes(source);
134
+ if (!suffixes)
135
+ return undefined;
136
+ read.suffixes.push(...suffixes);
137
+ read.patterns.push(...suffixes.map((suffix) => `**/*${suffix}`));
138
+ }
139
+ return read;
140
+ }
141
+ /** Index ranges of `projects: [...]` in a source without comments, or undefined when a bracket cannot be matched. */
142
+ function projectSpans(source) {
143
+ const spans = [];
144
+ for (const match of source.matchAll(/\bprojects\s*:\s*/g)) {
145
+ const start = match.index + match[0].length;
146
+ if (source[start] !== "[")
147
+ return undefined;
148
+ let depth = 0;
149
+ let quote = "";
150
+ let end = -1;
151
+ for (let index = start; index < source.length; index++) {
152
+ const char = source[index];
153
+ if (quote) {
154
+ if (char === "\\")
155
+ index++;
156
+ else if (char === quote)
157
+ quote = "";
158
+ continue;
159
+ }
160
+ if (char === "'" || char === '"' || char === "`")
161
+ quote = char;
162
+ else if (char === "[" || char === "{" || char === "(")
163
+ depth++;
164
+ else if (char === "]" || char === "}" || char === ")") {
165
+ depth--;
166
+ if (depth === 0) {
167
+ end = index;
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ if (end < 0)
173
+ return undefined;
174
+ spans.push([start, end]);
175
+ }
176
+ return spans;
177
+ }
178
+ export async function testMatchScopes(root, commit, tree) {
179
+ const scopes = [];
180
+ for (const config of tree.filter((path) => CONFIG_FILE.test(path) && !path.split("/").includes("node_modules"))) {
181
+ const source = stripComments(await git(root, ["cat-file", "blob", `${commit}:${config}`]).catch(() => ""));
182
+ const configDir = posix.dirname(config) === "." ? "" : posix.dirname(config);
183
+ const testDirs = [...source.matchAll(/\btestDir\s*:\s*(?:(['"])([^'"`${}\\\n]*)\1)?/g)];
184
+ let dir = configDir;
185
+ if (testDirs.length === 1 && testDirs[0][2] !== undefined) {
186
+ const resolved = posix.normalize(posix.join(configDir || ".", testDirs[0][2])).replace(/\/$/, "");
187
+ dir = resolved === "." || resolved.startsWith("..") ? "" : resolved;
188
+ }
189
+ // The value after each testMatch, up to 2,000 characters: an array may span lines.
190
+ const values = [...source.matchAll(/\btestMatch\s*:/g)].map((match) => ({ index: match.index, value: source.slice(match.index + match[0].length, match.index + match[0].length + 2000) }));
191
+ if (!values.length) {
192
+ scopes.push({ config, dir, kind: "default" });
193
+ continue;
194
+ }
195
+ const reads = values.map((entry) => readTestMatch(entry.value));
196
+ if (reads.some((read) => !read)) {
197
+ const literals = values.map((entry) => testMatchLiterals(entry.value));
198
+ const defaultNames = literals.every((one) => one && !one.regexes.length && one.strings.every((glob) => /\.(spec|test)\.[^/]*$/.test(glob.split("/").at(-1))));
199
+ scopes.push({ config, dir, kind: "unapplied", ...(defaultNames ? { defaultNames } : {}) });
200
+ continue;
201
+ }
202
+ const spans = projectSpans(source);
203
+ const narrows = spans !== undefined && values.every((entry) => !spans.some(([start, end]) => entry.index > start && entry.index < end));
204
+ const read = { globs: reads.flatMap((one) => one.globs), suffixes: [...new Set(reads.flatMap((one) => one.suffixes))], patterns: [...new Set(reads.flatMap((one) => one.patterns))] };
205
+ scopes.push({ config, dir, kind: "applied", read, narrows });
206
+ }
207
+ return scopes;
208
+ }
209
+ const selects = (read, path) => read.globs.some((glob) => glob.test(path)) || read.suffixes.some((suffix) => path.endsWith(suffix));
210
+ /** A test file: named with .spec. or .test., or selected by a `testMatch` that could be applied. */
211
+ export const isTestFile = (path, scopes) => TEST_FILE.test(path)
212
+ || (SOURCE_FILE.test(path) && !CONFIG_FILE.test(path) && scopes.some((scope) => scope.read && under(path, scope.dir) && selects(scope.read, path)));
213
+ /** A source file that a `testMatch` which could not be applied may select under a name other than .spec. or .test. */
214
+ export const mayBeTestFile = (path, scopes) => !isTestFile(path, scopes) && SOURCE_FILE.test(path)
215
+ && !CONFIG_FILE.test(path) && scopes.some((scope) => scope.kind === "unapplied" && !scope.defaultNames && under(path, scope.dir));
216
+ /**
217
+ * A test file that some configuration selects. A file only configurations with a narrowing `testMatch` cover is a test
218
+ * only when one of them selects it, so a .spec. file of another runner below a wide `testDir` is not read as Playwright.
219
+ * Used by the ledger only: audit reads every file named as a test, because leaving one out would hide its changes.
220
+ */
221
+ export const isSelectedTestFile = (path, scopes) => {
222
+ if (!isTestFile(path, scopes))
223
+ return false;
224
+ const covering = scopes.filter((scope) => under(path, scope.dir));
225
+ if (!covering.length || covering.some((scope) => !(scope.kind === "applied" && scope.narrows)))
226
+ return true;
227
+ return covering.some((scope) => selects(scope.read, path));
228
+ };
229
+ /** git pathspecs for the files the applied `testMatch` values may select, below each configuration's directory. */
230
+ export function testMatchPathspecs(scopes) {
231
+ const specs = new Set();
232
+ for (const scope of scopes) {
233
+ for (const pattern of scope.read?.patterns ?? []) {
234
+ // git globs have no braces: expand the one level the grammar allows.
235
+ let expanded = [pattern];
236
+ while (expanded.some((one) => one.includes("{")) && expanded.length <= 64) {
237
+ expanded = expanded.flatMap((one) => {
238
+ const match = /\{([^{}]*)\}/.exec(one);
239
+ return match ? match[1].split(",").map((option) => one.slice(0, match.index) + option + one.slice(match.index + match[0].length)) : [one];
240
+ });
241
+ }
242
+ for (const one of expanded)
243
+ specs.add(`:(glob,icase)${scope.dir ? `${scope.dir}/` : ""}${one}`);
244
+ }
245
+ }
246
+ return [...specs];
247
+ }
248
+ /** An import or require of a Playwright module. */
249
+ export const PLAYWRIGHT_IMPORT = /(?:from|import|require\s*\()\s*['"`][^'"`\n]*playwright[^'"`\n]*['"`]/;
250
+ /** An import or require of another test runner. */
251
+ export const OTHER_RUNNER_IMPORT = /(?:from|import|require\s*\()\s*['"`](?:vitest|mocha|jest|@jest\/globals|node:test|ava|uvu|bun:test)['"`]/;
252
+ /** Whether a source imports another test runner and no Playwright module. */
253
+ export const usesOtherRunnerSource = (source) => OTHER_RUNNER_IMPORT.test(source) && !PLAYWRIGHT_IMPORT.test(source);
254
+ /** A command-line mistake: the command prints the message and exits 2. */
255
+ export class GitUsageError extends Error {
256
+ }
257
+ export async function resolveCommit(cwd, ref, option) {
258
+ if (!ref || ref.startsWith("-") || /[\u0000-\u001f]/.test(ref))
259
+ throw new GitUsageError(`${option} must name a git commit, branch or tag.`);
260
+ try {
261
+ return (await git(cwd, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`])).trim();
262
+ }
263
+ catch {
264
+ throw new GitUsageError(`${option} ${JSON.stringify(ref)} is not a commit in this repository.`);
265
+ }
266
+ }
267
+ /** readSide's answer when git cannot read the file, as when it does not exist at that commit. */
268
+ export const MISSING_FILE = "git could not read the file.";
269
+ /** Reads the tests of one file at one commit, or says why it could not. */
270
+ export async function readSide(cwd, commit, path) {
271
+ const object = `${commit}:${path}`;
272
+ try {
273
+ const size = Number((await git(cwd, ["cat-file", "-s", object])).trim());
274
+ if (!(size <= MAX_SOURCE_BYTES))
275
+ return "The file is larger than 1 MiB.";
276
+ return readTests(await git(cwd, ["cat-file", "blob", object]));
277
+ }
278
+ catch (error) {
279
+ if (error instanceof UnreadableSource)
280
+ return error.message;
281
+ return MISSING_FILE;
282
+ }
283
+ }
@@ -0,0 +1,96 @@
1
+ import { resolve } from "node:path";
2
+ import { parseArgs } from "node:util";
3
+ import { watchTasks } from "#agentpath/core";
4
+ import { loadTaskFiles } from "./tasks.js";
5
+ import { displayPath } from "./paths.js";
6
+ const MAX_WATCH_TASKS = 50;
7
+ const MAX_ROUNDS = 100_000;
8
+ /** A round interval such as 30s, 10m or 2h: at least one second, at most a week. */
9
+ export function parseInterval(value) {
10
+ const match = /^([0-9]{1,6})([smh])$/.exec(value.trim());
11
+ const ms = match ? Number(match[1]) * { s: 1_000, m: 60_000, h: 3_600_000 }[match[2]] : NaN;
12
+ if (!(ms >= 1_000 && ms <= 7 * 24 * 3_600_000))
13
+ throw new Error("Use an interval such as 30s, 10m or 2h, from 1s to one week.");
14
+ return ms;
15
+ }
16
+ const evidenceText = { site: "the evidence points to the site", task: "the evidence points to the task", unclear: "the evidence does not say whether the task or the site changed" };
17
+ function describe(round) {
18
+ const infrastructure = round.tasks.filter((task) => task.infrastructure);
19
+ const count = (status) => round.tasks.filter((task) => task.status === status && !task.infrastructure).length;
20
+ const cancelled = count("cancelled");
21
+ const lines = [`Round ${round.round} ${round.finishedAt}: ${count("passed")} passed, ${count("failed")} failed${cancelled ? `, ${cancelled} cancelled` : ""}${infrastructure.length ? `, ${infrastructure.length} not checked` : ""}${round.notRun?.length ? `, ${round.notRun.length} not run` : ""}${round.alerts.length ? "" : ", no change"}`];
22
+ const failing = round.tasks.filter((task) => task.status === "failed" && !task.infrastructure).map((task) => task.taskId);
23
+ if (failing.length)
24
+ lines.push(` Failing: ${failing.join(", ")}${round.round === 1 && round.state === "new" ? " (first verdicts are a baseline; watch alerts only when a verdict changes)" : ""}`);
25
+ for (const alert of round.alerts) {
26
+ lines.push(`ALERT ${alert.taskId} ${alert.from} -> ${alert.to}${alert.category ? ` (${alert.category})` : ""}${alert.evidence ? `: ${evidenceText[alert.evidence]}` : ""}. Run ${alert.runId}, previous ${alert.previousRunId}. See agentpath report ${alert.runId}.`);
27
+ }
28
+ for (const task of round.notRun ?? [])
29
+ lines.push(`NOT RUN ${task.taskId}: ${task.reason} Retried next round.`);
30
+ if (round.stateNotSaved)
31
+ lines.push("The watch state file could not be written, so watch stopped. Check the state path and free space.");
32
+ for (const task of infrastructure) {
33
+ lines.push(`NOT CHECKED ${task.taskId}: the browser could not start on this machine (run ${task.runId}). This is not a verdict and does not alert. Run agentpath doctor.`);
34
+ }
35
+ return lines;
36
+ }
37
+ export async function watchCommand(args) {
38
+ const { positionals, values } = parseArgs({
39
+ args, allowPositionals: true,
40
+ options: {
41
+ every: { type: "string" }, rounds: { type: "string" }, state: { type: "string" },
42
+ "runs-dir": { type: "string" }, json: { type: "boolean" }, "capture-text": { type: "boolean" },
43
+ },
44
+ });
45
+ if (positionals.length === 0)
46
+ throw new Error("watch requires at least one task JSON path.");
47
+ if (positionals.length > MAX_WATCH_TASKS)
48
+ throw new Error(`watch accepts at most ${MAX_WATCH_TASKS} task files.`);
49
+ if (!values.every)
50
+ throw new Error("watch requires --every, such as --every 10m.");
51
+ const everyMs = parseInterval(values.every);
52
+ let rounds;
53
+ if (values.rounds !== undefined) {
54
+ rounds = Number(values.rounds);
55
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > MAX_ROUNDS)
56
+ throw new Error(`--rounds must be a whole number from 1 to ${MAX_ROUNDS}.`);
57
+ }
58
+ const tasks = await loadTaskFiles(positionals);
59
+ for (const { file, task } of tasks) {
60
+ if (task.mode !== "deterministic")
61
+ throw new Error(`${file}: watch accepts deterministic tasks only.`);
62
+ }
63
+ const ids = tasks.map(({ task }) => task.id);
64
+ if (new Set(ids).size !== ids.length)
65
+ throw new Error("watch compares runs by task ID, so every task file needs a different ID.");
66
+ const runsDirectory = values["runs-dir"];
67
+ const statePath = resolve(values.state ?? resolve(runsDirectory ?? ".agentpath/runs", "..", "watch-state.json"));
68
+ const controller = new AbortController();
69
+ let interrupted = 0;
70
+ const abort = () => { interrupted ||= 130; controller.abort(); };
71
+ const terminate = () => { interrupted ||= 143; controller.abort(); };
72
+ process.on("SIGINT", abort);
73
+ process.on("SIGTERM", terminate);
74
+ try {
75
+ if (!values.json)
76
+ console.log(`Watching ${tasks.length} task${tasks.length === 1 ? "" : "s"} every ${values.every}. State ${displayPath(statePath)}. Press Ctrl+C to stop.`);
77
+ await watchTasks(tasks, {
78
+ statePath, everyMs, rounds, runsDirectory, captureText: values["capture-text"] === true, signal: controller.signal,
79
+ onRound: (round) => {
80
+ if (values.json)
81
+ console.log(JSON.stringify(round));
82
+ else {
83
+ if (round.state === "rebuilt-unreadable")
84
+ console.log("The watch state file was unreadable; previous verdicts were rebuilt from run directories.");
85
+ for (const line of describe(round))
86
+ console.log(line);
87
+ }
88
+ },
89
+ });
90
+ }
91
+ finally {
92
+ process.removeListener("SIGINT", abort);
93
+ process.removeListener("SIGTERM", terminate);
94
+ }
95
+ return interrupted;
96
+ }
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ export const agentSettingsSchema = z.strictObject({
3
+ provider: z.enum(["openai-compatible", "ollama"]),
4
+ endpoint: z.url().max(2048).refine((value) => {
5
+ const url = new URL(value);
6
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash;
7
+ }, "Use a credential-free HTTP(S) model base URL with a plain path"),
8
+ model: z.string().trim().min(1).max(200),
9
+ temperature: z.number().min(0).max(2).optional(),
10
+ ollamaThink: z.boolean().optional(),
11
+ ollamaFormat: z.enum(["json", "schema"]).optional(),
12
+ maxActions: z.int().min(1).max(100).default(20),
13
+ maxDecisions: z.int().min(1).max(150).default(30),
14
+ maxOutputTokens: z.int().min(64).max(4096).default(512),
15
+ maxTokenBudget: z.int().min(1024).max(262144).default(65536),
16
+ requestTimeoutMs: z.int().min(100).max(60000).default(30000),
17
+ storeMessages: z.boolean().default(false),
18
+ });
@@ -0,0 +1,175 @@
1
+ import { z } from "zod";
2
+ import { browserActionSchema, pressKeySchema, roleLocatorSchema, selectOptionSchema, semanticLocatorSchema } from "./task.js";
3
+ import { agentSettingsSchema } from "./agent-settings.js";
4
+ export { agentSettingsSchema } from "./agent-settings.js";
5
+ const shortText = z.string().trim().min(1).max(512);
6
+ /** An observation-local control reference. It is only valid for the observation that issued it. */
7
+ export const controlRefSchema = z.strictObject({ by: z.literal("ref"), ref: z.string().regex(/^c[1-9][0-9]{0,3}$/) });
8
+ export const agentTargetSchema = z.discriminatedUnion("by", [...semanticLocatorSchema.options, controlRefSchema]);
9
+ /**
10
+ * Model-facing action protocol v2. A select names the control to operate on (`control`) separately from the
11
+ * choice inside it (`option`), so an option label can never be proposed as the control itself.
12
+ */
13
+ const navigate = z.strictObject({ action: z.literal("navigate"), url: z.string().min(1).max(2048) });
14
+ const click = z.strictObject({ action: z.literal("click"), target: z.discriminatedUnion("by", [roleLocatorSchema, controlRefSchema]) });
15
+ const fill = z.strictObject({ action: z.literal("fill"), target: agentTargetSchema, value: z.string().max(16_384) });
16
+ const select = z.strictObject({ action: z.literal("select"), control: agentTargetSchema, option: selectOptionSchema });
17
+ const press = z.strictObject({ action: z.literal("press"), target: agentTargetSchema, key: pressKeySchema });
18
+ export const agentActionSchema = z.discriminatedUnion("action", [navigate, click, fill, select, press]);
19
+ const tools = z.enum(["observe", "complete", "unable"]);
20
+ /** The current decision protocol, advertised to providers and used for schema-constrained decoding. */
21
+ export const agentDecisionV2Schema = z.union([
22
+ z.strictObject({ schemaVersion: z.literal(2), tool: z.literal("act"), action: agentActionSchema }),
23
+ z.strictObject({ schemaVersion: z.literal(2), tool: tools }),
24
+ ]);
25
+ /** The first decision protocol (v1). Still accepted at runtime; its select `target` is the control. */
26
+ export const agentDecisionV1Schema = z.union([
27
+ z.strictObject({ schemaVersion: z.literal(1), tool: z.literal("act"), action: browserActionSchema }),
28
+ z.strictObject({ schemaVersion: z.literal(1), tool: tools }),
29
+ ]);
30
+ export const agentDecisionSchema = z.union([agentDecisionV2Schema, agentDecisionV1Schema]);
31
+ // Runtime validation remains authoritative, including key/chord refinements.
32
+ export const agentDecisionJsonSchema = z.toJSONSchema(agentDecisionV2Schema);
33
+ /**
34
+ * Decoder-only constraints. Legacy and unstructured replies still go through the shared runtime
35
+ * parser and the browser's independent binding and action checks.
36
+ */
37
+ export function scopedAgentDecisionJsonSchema(controls) {
38
+ const targetFor = (action) => {
39
+ const semantic = action === "click" ? roleLocatorSchema : semanticLocatorSchema;
40
+ const refs = controls.filter((control) => control.enabled && control.supports.includes(action)).map((control) => control.ref);
41
+ return refs.length ? z.union([semantic, controlRefSchema.extend({ ref: z.enum(refs) })]) : semantic;
42
+ };
43
+ const action = z.discriminatedUnion("action", [
44
+ navigate,
45
+ click.extend({ target: targetFor("click") }),
46
+ fill.extend({ target: targetFor("fill") }),
47
+ select.extend({ control: targetFor("select") }),
48
+ press.extend({ target: targetFor("press") }),
49
+ ]);
50
+ return z.toJSONSchema(z.union([agentDecisionV2Schema.options[0].extend({ action }), agentDecisionV2Schema.options[1]]));
51
+ }
52
+ /**
53
+ * Observation bounds. `bytes` keeps the worst-case decision request inside an 8192-token local context with the
54
+ * system prompt, history and output reserve; a 40 kB observation measured about 12k prompt tokens with qwen3.5:4b.
55
+ */
56
+ export const OBSERVATION_LIMITS = {
57
+ nodes: 200, nameLength: 500, controls: 25, choices: 25, controlNameLength: 200, choiceLength: 120, bytes: 16_000,
58
+ stateEvidence: 8, feedbackControls: 4, feedbackStatuses: 6, repetitionWindow: 8,
59
+ };
60
+ export const agentChoiceSchema = z.strictObject({
61
+ label: z.string().max(OBSERVATION_LIMITS.choiceLength),
62
+ value: z.string().max(OBSERVATION_LIMITS.choiceLength).optional(),
63
+ group: z.string().max(OBSERVATION_LIMITS.choiceLength).optional(),
64
+ selected: z.literal(true).optional(),
65
+ disabled: z.literal(true).optional(),
66
+ });
67
+ const valueFreeState = {
68
+ hasValue: z.boolean().optional(),
69
+ wasChangedByAgent: z.literal(true).optional(),
70
+ isChecked: z.boolean().optional(),
71
+ };
72
+ const supportedAction = z.enum(["click", "fill", "select", "press"]);
73
+ export const agentControlSchema = z.strictObject({
74
+ ref: controlRefSchema.shape.ref,
75
+ role: z.string().max(100),
76
+ name: z.string().max(OBSERVATION_LIMITS.controlNameLength),
77
+ /** native-select is a real <select>; custom-combobox is any other combobox and does not support select. */
78
+ kind: z.enum(["native-select", "custom-combobox", "text-input", "checkable"]),
79
+ enabled: z.boolean(),
80
+ supports: z.array(supportedAction).max(4),
81
+ ...valueFreeState,
82
+ expanded: z.boolean().optional(),
83
+ multiple: z.literal(true).optional(),
84
+ choices: z.array(agentChoiceSchema).max(OBSERVATION_LIMITS.choices).optional(),
85
+ /** Present when the control has more choices than were included. */
86
+ choiceCount: z.int().nonnegative().optional(),
87
+ });
88
+ // Only structured, value-free evidence is saved in the trace. Control names stay in the request observation.
89
+ export const agentControlStateEvidenceSchema = agentControlSchema.pick({
90
+ ref: true, role: true, kind: true, enabled: true, supports: true,
91
+ }).extend({
92
+ ...valueFreeState, expanded: z.boolean().optional(),
93
+ selectedCount: z.int().min(0).max(OBSERVATION_LIMITS.choices).optional(),
94
+ });
95
+ const feedbackCount = z.int().min(1).max(OBSERVATION_LIMITS.nodes + OBSERVATION_LIMITS.controls);
96
+ const observationGap = z.enum(["privacy", "truncated", "empty"]);
97
+ export const agentActionFeedbackSchema = z.strictObject({
98
+ action: z.enum(["navigate", "click", "fill", "select", "press"]),
99
+ outcome: z.enum(["completed", "rejected", "failed"]),
100
+ change: z.enum(["observed", "none-observed", "unknown"]).optional(),
101
+ target: z.strictObject({ role: z.string().max(100).optional(), ref: controlRefSchema.shape.ref.optional() }).optional(),
102
+ navigated: z.boolean().optional(),
103
+ urlChanged: z.literal(true).optional(),
104
+ targetDisappeared: z.literal(true).optional(),
105
+ targetReplaced: z.literal(true).optional(),
106
+ actionsAppeared: feedbackCount.optional(),
107
+ actionsDisappeared: feedbackCount.optional(),
108
+ headingsChanged: z.literal(true).optional(),
109
+ statusAppeared: feedbackCount.optional(),
110
+ statusDisappeared: feedbackCount.optional(),
111
+ statusChanged: z.int().min(1).max(OBSERVATION_LIMITS.feedbackStatuses * 2).optional(),
112
+ statusTextWithheld: z.literal(true).optional(),
113
+ gaps: z.array(observationGap).max(3).optional(),
114
+ controls: z.array(z.strictObject({
115
+ ref: controlRefSchema.shape.ref,
116
+ changed: z.array(z.enum(["hasValue", "isChecked", "enabled", "selection", "expanded"])).max(5),
117
+ })).max(OBSERVATION_LIMITS.feedbackControls).optional(),
118
+ });
119
+ export const agentObservationSchema = z.strictObject({
120
+ url: z.string().max(2048),
121
+ accessibility: z.array(z.strictObject({ role: z.string().max(100), name: z.string().max(OBSERVATION_LIMITS.nameLength) })).max(OBSERVATION_LIMITS.nodes),
122
+ controls: z.array(agentControlSchema).max(OBSERVATION_LIMITS.controls).optional(),
123
+ truncated: z.literal(true).optional(),
124
+ lastAction: agentActionFeedbackSchema.optional(),
125
+ });
126
+ /** Normalizes either protocol version to the v2 action shape. */
127
+ export function normalizeAgentAction(decision) {
128
+ if (decision.tool !== "act")
129
+ return undefined;
130
+ if (decision.schemaVersion === 2)
131
+ return decision.action;
132
+ const action = decision.action;
133
+ if (action.action === "select")
134
+ return { action: "select", control: action.target, option: action.option };
135
+ return action;
136
+ }
137
+ export const agentTraceSchema = z.strictObject({
138
+ schemaVersion: z.literal(1), runId: z.uuid(),
139
+ provider: z.enum(["openai-compatible", "ollama"]), model: z.string(),
140
+ endpointOrigin: z.string(),
141
+ inference: agentSettingsSchema.pick({ temperature: true, ollamaThink: true, ollamaFormat: true }).optional(),
142
+ limits: agentSettingsSchema.pick({ maxActions: true, maxDecisions: true, maxOutputTokens: true, maxTokenBudget: true, requestTimeoutMs: true }),
143
+ /** Absent in older recordings, which used flat observations and decision protocol v1. */
144
+ observationVersion: z.union([z.literal(2), z.literal(3), z.literal(4)]).optional(),
145
+ declaredCompletion: z.boolean(), verifiedCompletion: z.boolean(),
146
+ actionCount: z.int().nonnegative(), decisionCount: z.int().nonnegative(), chargedTokens: z.int().nonnegative(),
147
+ failureKind: z.string().optional(),
148
+ termination: z.strictObject({
149
+ kind: z.enum(["verified", "premature-completion", "verification-unavailable", "unable", "budget-exhausted", "repetition", "action-failure", "cancelled", "unknown"]),
150
+ verification: z.enum(["passed", "failed", "unavailable", "not-run"]),
151
+ }).optional(),
152
+ entries: z.array(z.strictObject({
153
+ sequence: z.int().nonnegative(), url: z.string(), nodeCount: z.int().nonnegative(),
154
+ controlCount: z.int().nonnegative().optional(),
155
+ proposalDigest: z.string(), observationDigest: z.string(), tool: z.enum(["act", "observe", "complete", "unable", "invalid"]),
156
+ action: z.string().optional(),
157
+ targetRef: controlRefSchema.shape.ref.optional(),
158
+ repeated: z.literal(true).optional(),
159
+ repetition: z.strictObject({
160
+ previousDecision: z.int().nonnegative(),
161
+ priorNoChange: z.int().min(1).max(OBSERVATION_LIMITS.repetitionWindow),
162
+ stopped: z.literal(true).optional(),
163
+ }).optional(),
164
+ completion: z.strictObject({
165
+ actionableCount: feedbackCount.or(z.literal(0)),
166
+ statusCount: z.int().min(0).max(OBSERVATION_LIMITS.feedbackStatuses),
167
+ gaps: z.array(observationGap).max(3),
168
+ previousAction: agentActionFeedbackSchema.optional(),
169
+ }).optional(),
170
+ controlStates: z.array(agentControlStateEvidenceSchema).max(OBSERVATION_LIMITS.stateEvidence).optional(),
171
+ feedback: agentActionFeedbackSchema.optional(), stepIndex: z.int().nonnegative().optional(), message: z.string().optional(),
172
+ /** Host policy decision for this proposal. A blocked proposal has no stepIndex: it never executed. */
173
+ policy: z.strictObject({ decision: z.enum(["blocked", "permitted-violation"]), ruleIds: z.array(shortText).max(50) }).optional(),
174
+ })).max(150),
175
+ });