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,178 @@
1
+ import { z } from "zod";
2
+ import { artifactSettingsSchema, browserSettingsSchema, stepActionSchema, assertionKindSchema, SCHEMA_VERSION, semanticRoleSchema, taskIdSchema, } from "./task.js";
3
+ const version = z.literal(SCHEMA_VERSION);
4
+ const time = z.iso.datetime();
5
+ const ms = z.number().finite().nonnegative();
6
+ const index = z.int().nonnegative();
7
+ export const runIdSchema = z.uuid();
8
+ const text = z.string().min(1);
9
+ const stepAction = stepActionSchema;
10
+ const assertionKind = assertionKindSchema;
11
+ export const artifactKindSchema = z.enum(["screenshot", "accessibility", "failure", "trace", "environment", "agent", "policy"]);
12
+ export const artifactRefSchema = z.strictObject({
13
+ kind: artifactKindSchema,
14
+ path: z.string().regex(/^(?:[a-z0-9_-]+\/)*[a-z0-9_-]+\.(?:json|png|zip)$/),
15
+ });
16
+ const stepLocation = z.strictObject({ phase: z.literal("step"), index, action: stepAction });
17
+ const assertionLocation = z.strictObject({ phase: z.literal("assertion"), index, assertion: assertionKind });
18
+ const agentLocation = z.strictObject({ phase: z.literal("agent"), index });
19
+ const startupLocation = z.strictObject({ phase: z.literal("startup") });
20
+ export const locationSchema = z.discriminatedUnion("phase", [stepLocation, assertionLocation, startupLocation, agentLocation]);
21
+ export const failureCategorySchema = z.enum([
22
+ "TARGET_NOT_FOUND", "TARGET_AMBIGUOUS", "TARGET_NOT_INTERACTABLE",
23
+ "NAVIGATION_FAILURE", "ASSERTION_FAILED", "TIMEOUT", "BROWSER_ERROR", "UNKNOWN",
24
+ "AGENT_RESPONSE_INVALID", "AGENT_BUDGET_EXHAUSTED", "AGENT_STOPPED", "PROVIDER_ERROR",
25
+ // control grounding and action policy.
26
+ "OPTION_NOT_FOUND", "TARGET_STALE", "UNSUPPORTED_CONTROL", "POLICY_BLOCKED",
27
+ ]);
28
+ export const NEAR_MATCH_LIMIT = 5;
29
+ export const PAGE_MESSAGE_LIMIT = 5;
30
+ export const PAGE_TEXT_LIMIT = 300;
31
+ export const nearMatchSchema = z.strictObject({
32
+ role: semanticRoleSchema,
33
+ name: z.string().min(1).max(160),
34
+ /** Why it resembles the missing target. A resemblance, never a claim that it is the intended element. */
35
+ relation: z.enum(["same-name-other-role", "case-or-spacing", "similar-name", "accessible-name-matches-label", "visible-text-matches"]),
36
+ // role "option" entries are similar option labels inside the targeted select control, and
37
+ // "visible-text-matches" marks an element whose visible text is the requested name but whose accessible name differs.
38
+ });
39
+ export const observationSchema = z.strictObject({
40
+ matchCount: index.optional(),
41
+ role: semanticRoleSchema.optional(),
42
+ roleCandidateCount: index.optional(),
43
+ unnamedRoleCandidateCount: index.optional(),
44
+ visible: z.boolean().optional(),
45
+ enabled: z.boolean().optional(),
46
+ editable: z.boolean().optional(),
47
+ httpStatus: z.int().min(100).max(599).optional(),
48
+ errorKind: z.enum(["timeout", "strict", "unsupported_target", "browser_closed", "navigation", "unclassified", "renderer_crash", "browser_disconnected", "run_timeout",
49
+ "wrong_control_type", "control_disabled", "option_not_found", "option_disabled", "stale_reference", "unsupported_control", "policy_blocked"]).optional(),
50
+ referenceState: z.enum(["never-issued", "expired", "node-changed"]).optional(),
51
+ disallowedHost: z.string().optional(),
52
+ timeoutScope: z.enum(["operation", "run"]).optional(),
53
+ // the operation timeout in effect, and bounded targets on the page that resemble a missing one.
54
+ timeoutMs: z.int().min(0).max(600_000).optional(),
55
+ nearMatches: z.array(nearMatchSchema).max(NEAR_MATCH_LIMIT).optional(),
56
+ /**
57
+ * near matches observed but left out because the privacy policy withheld their names (after
58
+ * input, a name the task does not itself name can echo typed values). A count only; no name is recorded.
59
+ */
60
+ nearMatchesWithheld: z.int().min(1).max(NEAR_MATCH_LIMIT).optional(),
61
+ /**
62
+ * near matches left out because their name contains a value the task types. Text capture
63
+ * does not record them either. A count only; no name is recorded.
64
+ */
65
+ nearMatchesRedacted: z.int().min(1).max(NEAR_MATCH_LIMIT).optional(),
66
+ /** Embedded frames on the page when a target or assertion failed. Targets inside frames are not searched. */
67
+ embeddedFrames: z.int().min(1).max(10_000).optional(),
68
+ // evidence gathered after a failure, by observation only. None of it changes the verdict.
69
+ /**
70
+ * After the operation failed, the same check was repeated, without acting, for a bounded window.
71
+ * "passed-later": it would have succeeded `afterMs` after the operation started. "still-failing": it did not
72
+ * succeed within `windowMs`.
73
+ */
74
+ lateCheck: z.strictObject({
75
+ outcome: z.enum(["passed-later", "still-failing"]),
76
+ afterMs: z.int().min(0).max(600_000).optional(),
77
+ windowMs: z.int().min(0).max(600_000),
78
+ }).optional(),
79
+ /** For a missing label target: a <label> with exactly this text exists but labels no control. */
80
+ labelState: z.enum(["detached"]).optional(),
81
+ /** Visible alert and status messages at failure. Text is present only when the operator enabled text capture. */
82
+ pageMessages: z.array(z.strictObject({
83
+ role: z.enum(["alert", "status"]),
84
+ text: z.string().max(PAGE_TEXT_LIMIT).optional(),
85
+ textState: z.enum(["not-captured", "withheld", "empty"]).optional(),
86
+ })).max(PAGE_MESSAGE_LIMIT).optional(),
87
+ /** The visible text of a failed text assertion's element. Only with operator-enabled text capture. */
88
+ observedText: z.string().max(PAGE_TEXT_LIMIT).optional(),
89
+ observedTextTruncated: z.literal(true).optional(),
90
+ });
91
+ export const failureSchema = z.strictObject({
92
+ category: failureCategorySchema,
93
+ location: locationSchema,
94
+ expected: text,
95
+ observed: text,
96
+ investigation: text.optional(),
97
+ observation: observationSchema,
98
+ evidence: z.array(artifactRefSchema).min(1),
99
+ });
100
+ export const verdictSchema = z.enum(["passed", "failed", "cancelled"]);
101
+ const operationResultShape = {
102
+ startedAt: time,
103
+ durationMs: ms,
104
+ status: verdictSchema,
105
+ url: text,
106
+ evidence: z.array(artifactRefSchema),
107
+ };
108
+ export const stepResultSchema = z.strictObject({ index, action: stepAction, ...operationResultShape });
109
+ export const assertionResultSchema = z.strictObject({ index, assertion: assertionKind, ...operationResultShape });
110
+ export const environmentSchema = z.strictObject({
111
+ schemaVersion: version,
112
+ engine: z.literal("chromium"),
113
+ browserVersion: text.optional(),
114
+ nodeVersion: text,
115
+ platform: text,
116
+ arch: text,
117
+ browser: browserSettingsSchema.required({ viewport: true, timeoutMs: true }),
118
+ artifacts: artifactSettingsSchema.required(),
119
+ });
120
+ const resultShape = {
121
+ schemaVersion: version,
122
+ runId: runIdSchema,
123
+ taskId: taskIdSchema,
124
+ mode: z.enum(["deterministic", "autonomous"]),
125
+ startedAt: time,
126
+ finishedAt: time,
127
+ durationMs: ms,
128
+ steps: z.array(stepResultSchema),
129
+ assertions: z.array(assertionResultSchema),
130
+ artifacts: z.array(artifactRefSchema),
131
+ };
132
+ export const runResultSchema = z.discriminatedUnion("status", [
133
+ z.strictObject({ ...resultShape, status: z.literal("passed") }),
134
+ z.strictObject({ ...resultShape, status: z.literal("failed"), failure: failureSchema }),
135
+ z.strictObject({ ...resultShape, status: z.literal("cancelled") }),
136
+ ]).superRefine((result, ctx) => {
137
+ if (result.status === "passed" && ((result.mode === "deterministic" && !result.steps.length) || !result.assertions.length ||
138
+ [...result.steps, ...result.assertions].some(({ status }) => status !== "passed"))) {
139
+ ctx.addIssue({ code: "custom", path: ["status"], message: "A passed run needs passing steps and assertions." });
140
+ }
141
+ });
142
+ const locatorIntent = z.discriminatedUnion("by", [
143
+ z.strictObject({ by: z.literal("role"), role: semanticRoleSchema }),
144
+ z.strictObject({ by: z.literal("label") }),
145
+ ]);
146
+ const eventShape = { schemaVersion: version, runId: runIdSchema, sequence: index, at: time };
147
+ export const runEventSchema = z.discriminatedUnion("type", [
148
+ z.strictObject({ ...eventShape, type: z.literal("run.started"), taskId: taskIdSchema }),
149
+ z.strictObject({ ...eventShape, type: z.literal("step.started"), index, action: stepAction, url: text, target: locatorIntent.optional() }),
150
+ z.strictObject({ ...eventShape, type: z.literal("assertion.started"), index, assertion: assertionKind, url: text }),
151
+ z.strictObject({ ...eventShape, type: z.literal("step.finished"), step: stepResultSchema }),
152
+ z.strictObject({ ...eventShape, type: z.literal("assertion.finished"), assertion: assertionResultSchema }),
153
+ z.strictObject({ ...eventShape, type: z.literal("artifact.warning"), kind: artifactKindSchema }),
154
+ z.strictObject({ ...eventShape, type: z.literal("run.finished"), status: verdictSchema, durationMs: ms, failure: failureSchema.optional() })
155
+ .refine(({ status, failure }) => (status === "failed") === (failure !== undefined), { path: ["failure"], message: "Only failed runs carry failure details." }),
156
+ ]);
157
+ export const comparisonSchema = z.strictObject({
158
+ schemaVersion: version,
159
+ baselineRunId: runIdSchema,
160
+ candidateRunId: runIdSchema,
161
+ baselineStatus: verdictSchema,
162
+ candidateStatus: verdictSchema,
163
+ firstDivergence: z.strictObject({
164
+ location: locationSchema,
165
+ baseline: z.union([verdictSchema, z.literal("not_run")]),
166
+ candidate: z.union([verdictSchema, z.literal("not_run")]),
167
+ }).optional(),
168
+ });
169
+ export const failureEvidenceSchema = failureSchema.omit({ evidence: true }).extend({
170
+ schemaVersion: version,
171
+ url: text,
172
+ });
173
+ export const accessibilitySnapshotSchema = z.strictObject({
174
+ schemaVersion: version,
175
+ url: text,
176
+ nodes: z.array(z.strictObject({ role: text, name: z.string(), nameState: z.enum(["withheld", "redacted"]).optional() })),
177
+ truncated: z.boolean(),
178
+ });
@@ -0,0 +1,39 @@
1
+ const UNSUPPORTED_TARGET = `Use {"by": "role", "role": "button", "name": "Save"} or {"by": "label", "label": "Email"}; CSS selectors, XPath and test IDs are not accepted. agentpath inspect <url> lists the roles, names and labels on a page.`;
2
+ /**
3
+ * Plain messages for a task's schema issues. A target of an unsupported kind (CSS, XPath, test ID) fails every
4
+ * branch of the target union, so its per-branch errors become one line that says what is accepted.
5
+ */
6
+ export function taskIssues(raw, issues) {
7
+ const unsupported = new Map();
8
+ for (const issue of issues) {
9
+ const at = issue.path.lastIndexOf("target");
10
+ if (at < 0)
11
+ continue;
12
+ const path = issue.path.slice(0, at + 1);
13
+ // Only a target that is there but of another kind; a missing target keeps its own "Required".
14
+ const target = valueAt(raw, path);
15
+ if (typeof target !== "object" || target === null || Array.isArray(target))
16
+ continue;
17
+ const by = target.by;
18
+ if (by !== "role" && by !== "label")
19
+ unsupported.set(path.map(String).join("."), { path, by });
20
+ }
21
+ const inside = (path) => [...unsupported.keys()].some((key) => `${path.map(String).join(".")}.`.startsWith(`${key}.`));
22
+ return [
23
+ ...issues.filter((issue) => !inside(issue.path)).map((issue) => ({
24
+ path: [...issue.path], message: /received undefined$/.test(issue.message) ? "Required" : issue.message,
25
+ })),
26
+ ...[...unsupported.values()].map(({ path, by }) => ({
27
+ path, message: `${by === undefined ? `A target needs "by"` : `Targets by ${JSON.stringify(by)} are not supported`}. ${UNSUPPORTED_TARGET}`,
28
+ })),
29
+ ];
30
+ }
31
+ function valueAt(value, path) {
32
+ let current = value;
33
+ for (const key of path) {
34
+ if (typeof current !== "object" || current === null)
35
+ return undefined;
36
+ current = current[key];
37
+ }
38
+ return current;
39
+ }
@@ -0,0 +1,185 @@
1
+ import { z } from "zod";
2
+ import { agentSettingsSchema } from "./agent-settings.js";
3
+ export const SCHEMA_VERSION = 1;
4
+ const shortText = z.string().trim().min(1).max(512);
5
+ export const semanticRoleSchema = z.enum([
6
+ "alert", "button", "checkbox", "combobox", "dialog", "form", "heading",
7
+ "link", "list", "listbox", "listitem", "main", "menuitem", "navigation",
8
+ "option", "radio", "region", "row", "searchbox", "slider", "spinbutton",
9
+ "status", "switch", "tab", "table", "tabpanel", "textbox",
10
+ ]);
11
+ export const roleLocatorSchema = z.strictObject({
12
+ by: z.literal("role"),
13
+ role: semanticRoleSchema,
14
+ name: shortText,
15
+ });
16
+ const labelLocatorSchema = z.strictObject({ by: z.literal("label"), label: shortText });
17
+ export const semanticLocatorSchema = z.discriminatedUnion("by", [roleLocatorSchema, labelLocatorSchema]);
18
+ /**
19
+ * Targets for waits and assertions, which only inspect the page. Omitting the name matches the only element
20
+ * with that role, such as an unnamed main landmark; several still fail as ambiguous. Actions keep names.
21
+ */
22
+ export const inspectionLocatorSchema = z.discriminatedUnion("by", [
23
+ roleLocatorSchema.extend({ name: shortText.optional() }),
24
+ labelLocatorSchema,
25
+ ]);
26
+ const modifiers = new Set(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]);
27
+ const namedKeys = new Set([
28
+ ...modifiers, "Backspace", "Tab", "Enter", "Escape", "Space", "PageUp", "PageDown", "Home", "End",
29
+ "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Insert", "Delete",
30
+ ]);
31
+ export const pressKeySchema = z.string().max(64).refine((key) => {
32
+ // A trailing plus is a printable key, including in chords such as Control++.
33
+ const parts = key.split(/\+(?=.)/);
34
+ const last = parts.pop() ?? "";
35
+ return parts.length <= 4 && parts.every((part) => modifiers.has(part)) &&
36
+ (namedKeys.has(last) || /^[!-~]$/.test(last) || /^F(?:[1-9]|1[0-2])$/.test(last));
37
+ }, "Use a supported key or modifier chord, such as Enter or ControlOrMeta+a");
38
+ /** The choice inside a select control, matched exactly by its label or its value. */
39
+ export const selectOptionSchema = z.discriminatedUnion("by", [
40
+ z.strictObject({ by: z.literal("label"), label: shortText }),
41
+ z.strictObject({ by: z.literal("value"), value: z.string().max(512) }),
42
+ ]);
43
+ export const browserActionSchema = z.discriminatedUnion("action", [
44
+ z.strictObject({ action: z.literal("navigate"), url: z.string().min(1).max(2048) }),
45
+ z.strictObject({ action: z.literal("click"), target: roleLocatorSchema }),
46
+ z.strictObject({ action: z.literal("fill"), target: semanticLocatorSchema, value: z.string().max(16_384) }),
47
+ z.strictObject({ action: z.literal("select"), target: semanticLocatorSchema, option: selectOptionSchema }),
48
+ z.strictObject({ action: z.literal("press"), target: semanticLocatorSchema, key: pressKeySchema }),
49
+ ]);
50
+ export const browserStepSchema = z.discriminatedUnion("action", [
51
+ ...browserActionSchema.options,
52
+ z.strictObject({ action: z.literal("wait"), target: inspectionLocatorSchema, state: z.enum(["visible", "hidden"]) }),
53
+ ]);
54
+ export const stepActionSchema = z.enum(["navigate", "click", "fill", "select", "press", "wait"]);
55
+ export const assertionKindSchema = z.enum(["url", "visible", "text", "count"]);
56
+ export const assertionSchema = z.discriminatedUnion("assert", [
57
+ z.strictObject({ assert: z.literal("url"), pattern: z.string().min(1).max(2048) }),
58
+ z.strictObject({ assert: z.literal("visible"), target: inspectionLocatorSchema }),
59
+ z.strictObject({ assert: z.literal("text"), target: inspectionLocatorSchema, contains: shortText }),
60
+ z.strictObject({ assert: z.literal("count"), target: inspectionLocatorSchema, count: z.int().min(0).max(100_000) }),
61
+ ]);
62
+ export function httpUrl(input, base) {
63
+ try {
64
+ const url = new URL(input, base);
65
+ if (["http:", "https:"].includes(url.protocol) && !url.username && !url.password) {
66
+ return url;
67
+ }
68
+ }
69
+ catch {
70
+ // Invalid URL.
71
+ }
72
+ }
73
+ export const allowedHostSchema = z.string().min(1).max(260).refine((value) => {
74
+ const url = httpUrl(`http://${value}`);
75
+ const secureUrl = httpUrl(`https://${value}`);
76
+ return url?.host === value || secureUrl?.host === value;
77
+ }, "Use a canonical lowercase hostname or hostname:port, without a scheme or path");
78
+ export function allowedUrl(url, hosts) {
79
+ return hosts.includes(url.host);
80
+ }
81
+ const viewportSchema = z.strictObject({
82
+ width: z.int().min(320).max(3840),
83
+ height: z.int().min(240).max(2160),
84
+ });
85
+ export const browserSettingsSchema = z.strictObject({
86
+ viewport: viewportSchema.default({ width: 1280, height: 800 }),
87
+ timeoutMs: z.int().min(100).max(60_000).default(5_000),
88
+ runTimeoutMs: z.int().min(250).max(600_000).optional(),
89
+ // Phone emulation in Chromium: touch, isMobile, a 3x pixel ratio and a mobile user agent, at the task's viewport.
90
+ // Optional with no default, so tasks without it keep their fingerprint.
91
+ mobile: z.boolean().optional(),
92
+ });
93
+ export const artifactSettingsSchema = z.strictObject({
94
+ screenshots: z.enum(["off", "failure", "steps"]).default("off"),
95
+ accessibility: z.enum(["off", "failure", "steps"]).default("failure"),
96
+ trace: z.boolean().default(false),
97
+ });
98
+ const setupMetadata = z.strictObject({ description: shortText });
99
+ export const taskIdSchema = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,79}$/);
100
+ /**
101
+ * Action policy v1: trusted, developer-declared protected interactions. Matching is deterministic: an action
102
+ * rule matches when the action kind is listed and, if a target is given, the action's single resolved element
103
+ * also matches the rule's semantic locator. A request rule matches method and exact or prefix path on an
104
+ * allowed host. Policies never reach the autonomous adapter and are not a reference path.
105
+ */
106
+ export const policyRuleIdSchema = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, "Use 1–64 lowercase letters, digits, underscores, or hyphens, starting with a letter or digit");
107
+ export const policyActionSchema = z.enum(["click", "fill", "select", "press"]);
108
+ const unique = (values) => new Set(values).size === values.length;
109
+ export const actionPolicyRuleSchema = z.strictObject({
110
+ id: policyRuleIdSchema,
111
+ kind: z.literal("action"),
112
+ actions: z.array(policyActionSchema).min(1).max(4).refine(unique, "Use unique actions"),
113
+ target: semanticLocatorSchema.optional(),
114
+ description: shortText.optional(),
115
+ });
116
+ export const requestPolicyRuleSchema = z.strictObject({
117
+ id: policyRuleIdSchema,
118
+ kind: z.literal("request"),
119
+ path: z.string().min(1).max(512).regex(/^\/[^?#\s]*$/, "Use an absolute path without a query or fragment"),
120
+ match: z.enum(["exact", "prefix"]).optional(),
121
+ methods: z.array(z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"])).min(1).max(5).refine(unique, "Use unique methods").optional(),
122
+ host: z.string().min(1).max(260).optional(),
123
+ description: shortText.optional(),
124
+ });
125
+ export const policyRuleSchema = z.discriminatedUnion("kind", [actionPolicyRuleSchema, requestPolicyRuleSchema]);
126
+ export const actionPolicySchema = z.strictObject({
127
+ schemaVersion: z.literal(1),
128
+ /** audit records violations and lets them run; enforce rejects them before their browser side effect. */
129
+ mode: z.enum(["audit", "enforce"]),
130
+ rules: z.array(policyRuleSchema).min(1).max(50)
131
+ .refine((rules) => unique(rules.map((rule) => rule.id)), "Use unique rule IDs"),
132
+ });
133
+ const sharedTaskShape = {
134
+ schemaVersion: z.literal(SCHEMA_VERSION),
135
+ id: taskIdSchema,
136
+ name: shortText,
137
+ baseUrl: z.string().min(1).max(2048),
138
+ goal: z.string().trim().min(1).max(4096),
139
+ browser: browserSettingsSchema.prefault({}),
140
+ allowedHosts: z.array(allowedHostSchema).min(1).max(50)
141
+ .refine((hosts) => new Set(hosts).size === hosts.length, "Use unique hosts"),
142
+ assertions: z.array(assertionSchema).min(1).max(100),
143
+ artifacts: artifactSettingsSchema.prefault({}),
144
+ setup: setupMetadata.optional(),
145
+ teardown: setupMetadata.optional(),
146
+ policy: actionPolicySchema.optional(),
147
+ };
148
+ export const taskSchema = z.discriminatedUnion("mode", [
149
+ z.strictObject({
150
+ ...sharedTaskShape,
151
+ mode: z.literal("deterministic"),
152
+ steps: z.array(browserStepSchema).min(1).max(100),
153
+ }),
154
+ z.strictObject({
155
+ ...sharedTaskShape,
156
+ mode: z.literal("autonomous"),
157
+ agent: agentSettingsSchema.optional(),
158
+ }),
159
+ ]).superRefine((task, ctx) => {
160
+ const base = httpUrl(task.baseUrl);
161
+ if (!base) {
162
+ ctx.addIssue({ code: "custom", path: ["baseUrl"], message: "Use a credential-free HTTP(S) URL on an allowed host" });
163
+ return;
164
+ }
165
+ if (!allowedUrl(base, task.allowedHosts)) {
166
+ ctx.addIssue({ code: "custom", path: ["baseUrl"], message: `The host ${JSON.stringify(base.host)} is not in allowedHosts. Hosts match exactly, including any port (for example "127.0.0.1:4173")` });
167
+ return;
168
+ }
169
+ // Requests to other hosts are already rejected by the destination allowlist, a hard boundary.
170
+ for (const [index, rule] of (task.policy?.rules ?? []).entries()) {
171
+ if (rule.kind === "request" && rule.host !== undefined && !task.allowedHosts.includes(rule.host)) {
172
+ ctx.addIssue({ code: "custom", path: ["policy", "rules", index, "host"], message: "A request rule host must be one of the allowed hosts" });
173
+ }
174
+ }
175
+ if (task.mode === "deterministic") {
176
+ for (const [index, step] of task.steps.entries()) {
177
+ if (step.action !== "navigate")
178
+ continue;
179
+ const url = httpUrl(step.url, base.href);
180
+ if (!url || !allowedUrl(url, task.allowedHosts)) {
181
+ ctx.addIssue({ code: "custom", path: ["steps", index, "url"], message: "Navigation must resolve to an allowed HTTP(S) host" });
182
+ }
183
+ }
184
+ }
185
+ });
@@ -0,0 +1,57 @@
1
+ import { z } from "zod";
2
+ import { failureCategorySchema, runIdSchema } from "./run.js";
3
+ import { taskIdSchema } from "./task.js";
4
+ /** A verdict `agentpath watch` compares between rounds. A cancelled run is not one. */
5
+ export const watchVerdictSchema = z.enum(["passed", "failed"]);
6
+ /**
7
+ * The local watch state file: each task's latest verdict and the run that produced it. It is derived from run
8
+ * directories, which stay the source of truth, and is rebuilt from them when it is missing or unreadable.
9
+ */
10
+ export const watchStateSchema = z.strictObject({
11
+ schemaVersion: z.literal(1),
12
+ tasks: z.record(taskIdSchema, z.strictObject({ verdict: watchVerdictSchema, runId: runIdSchema, at: z.iso.datetime() })),
13
+ });
14
+ /**
15
+ * Where a failed run's recorded evidence points, from its failure guidance: "site" when any finding points to the
16
+ * site, otherwise "task" when any points to the task, otherwise "unclear". Never a cause beyond those facts.
17
+ */
18
+ export const watchEvidenceSchema = z.enum(["task", "site", "unclear"]);
19
+ export const watchAlertSchema = z.strictObject({
20
+ taskId: taskIdSchema,
21
+ from: watchVerdictSchema,
22
+ to: watchVerdictSchema,
23
+ runId: runIdSchema,
24
+ previousRunId: runIdSchema,
25
+ category: failureCategorySchema.optional(),
26
+ /** Set on a passed-to-failed alert. */
27
+ evidence: watchEvidenceSchema.optional(),
28
+ });
29
+ /** One line of `agentpath watch --json`: one round of every task. */
30
+ export const watchRoundSchema = z.strictObject({
31
+ schemaVersion: z.literal(1),
32
+ round: z.int().positive(),
33
+ startedAt: z.iso.datetime(),
34
+ finishedAt: z.iso.datetime(),
35
+ /** How the previous verdicts were obtained: the state file, rebuilt from run directories, or neither (first round). */
36
+ state: z.enum(["read", "rebuilt", "rebuilt-unreadable", "new"]).optional(),
37
+ tasks: z.array(z.strictObject({
38
+ file: z.string().optional(),
39
+ taskId: taskIdSchema,
40
+ runId: runIdSchema,
41
+ status: z.enum(["passed", "failed", "cancelled"]),
42
+ category: failureCategorySchema.optional(),
43
+ /** Set on a failed run: where its recorded evidence points. */
44
+ evidence: watchEvidenceSchema.optional(),
45
+ /**
46
+ * The browser could not start on this machine (a startup BROWSER_ERROR). It is an infrastructure fact, not a
47
+ * verdict on the site: like a cancelled run, it leaves the watch state unchanged and never alerts.
48
+ */
49
+ infrastructure: z.literal(true).optional(),
50
+ })),
51
+ /** Verdict transitions only. A first verdict sets a baseline and is never an alert. */
52
+ alerts: z.array(watchAlertSchema),
53
+ /** Tasks whose run could not be recorded at all this round (for example a full disk). Not verdicts; retried next round. */
54
+ notRun: z.array(z.strictObject({ file: z.string().optional(), taskId: taskIdSchema, reason: z.string().max(200) })).optional(),
55
+ /** Set when the state file could not be written after this round; `watch` then stops. */
56
+ stateNotSaved: z.literal(true).optional(),
57
+ });
@@ -0,0 +1,103 @@
1
+ import { OBSERVATION_LIMITS } from "#agentpath/contracts";
2
+ function controlChanges(before, after) {
3
+ const changed = [];
4
+ for (const key of ["hasValue", "isChecked", "enabled", "expanded"]) {
5
+ if (before[key] !== undefined && after[key] !== undefined && before[key] !== after[key])
6
+ changed.push(key);
7
+ }
8
+ const previous = before.selectedOptions;
9
+ const current = after.selectedOptions;
10
+ const sameChoices = before.choices.length === after.choices.length && before.choices.every((choice, index) => choice.label === after.choices[index]?.label && choice.value === after.choices[index]?.value);
11
+ if (sameChoices && previous && current && previous.length === current.length && previous.some((selected, index) => current[index] !== selected)) {
12
+ changed.push("selection");
13
+ }
14
+ return changed;
15
+ }
16
+ const targetKey = (target) => JSON.stringify([target.role, target.name]);
17
+ /** Multiset subtraction preserves duplicates and ignores ordering and equivalent node replacements. */
18
+ function differences(left, right) {
19
+ const counts = new Map();
20
+ for (const key of left)
21
+ counts.set(key, (counts.get(key) ?? 0) + 1);
22
+ for (const key of right)
23
+ counts.set(key, (counts.get(key) ?? 0) - 1);
24
+ let appeared = 0;
25
+ let disappeared = 0;
26
+ for (const delta of counts.values()) {
27
+ if (delta > 0)
28
+ disappeared += delta;
29
+ else
30
+ appeared -= delta;
31
+ }
32
+ return { appeared, disappeared };
33
+ }
34
+ export function observationGaps(snapshot) {
35
+ const gaps = [];
36
+ if (snapshot.staticTextWithheld)
37
+ gaps.push("privacy");
38
+ if (snapshot.observation.truncated || snapshot.statusesLimited)
39
+ gaps.push("truncated");
40
+ if (!snapshot.targets.length && !snapshot.statuses.size &&
41
+ !snapshot.observation.accessibility.some((node) => node.name && node.role !== "RootWebArea"))
42
+ gaps.push("empty");
43
+ return gaps;
44
+ }
45
+ export function actionFeedback(before, after, feedback, target) {
46
+ if (feedback.outcome !== "completed")
47
+ return feedback;
48
+ const navigated = before.navigation !== after.navigation;
49
+ const statusTextWithheld = before.staticTextWithheld || after.staticTextWithheld;
50
+ const gaps = navigated ? observationGaps(after) : [...new Set([...observationGaps(before), ...observationGaps(after)])];
51
+ const limited = before.observation.truncated || after.observation.truncated;
52
+ const canCompareStatuses = !limited && !before.statusesLimited && !after.statusesLimited;
53
+ const statusKey = (status) => JSON.stringify([status.role, statusTextWithheld ? "" : status.name, statusTextWithheld ? "" : status.text]);
54
+ const oldStatuses = [...before.statuses].filter(([id]) => navigated || !after.statuses.has(id)).map(([, status]) => statusKey(status));
55
+ const newStatuses = [...after.statuses].filter(([id]) => navigated || !before.statuses.has(id)).map(([, status]) => statusKey(status));
56
+ const statuses = differences(navigated ? [] : oldStatuses, newStatuses);
57
+ const statusUpdated = navigated || statusTextWithheld ? 0 : [...after.statuses].filter(([id, status]) => {
58
+ const previous = before.statuses.get(id);
59
+ return previous?.text !== undefined && status.text !== undefined && statusKey(previous) !== statusKey(status);
60
+ }).length;
61
+ const statusAppeared = canCompareStatuses ? statuses.appeared : 0;
62
+ const statusDisappeared = canCompareStatuses ? statuses.disappeared : 0;
63
+ const statusChanged = statusUpdated + statusAppeared;
64
+ const previous = new Map([...before.refs.values()].map((control) => [control.backendNodeId, control]));
65
+ const controls = [];
66
+ if (!navigated)
67
+ for (const current of after.refs.values()) {
68
+ const prior = previous.get(current.backendNodeId);
69
+ if (!prior)
70
+ continue;
71
+ const changed = controlChanges(prior, current);
72
+ if (changed.length)
73
+ controls.push({ ref: current.ref, changed });
74
+ if (controls.length >= OBSERVATION_LIMITS.feedbackControls)
75
+ break;
76
+ }
77
+ const actions = limited || navigated ? { appeared: 0, disappeared: 0 } :
78
+ differences(before.targets.filter((node) => node.enabled).map(targetKey), after.targets.filter((node) => node.enabled).map(targetKey));
79
+ const headings = (sample) => sample.observation.accessibility
80
+ .filter((node) => node.role === "heading").map((node) => node.name);
81
+ const headingDelta = limited || navigated || statusTextWithheld ? undefined : differences(headings(before), headings(after));
82
+ const headingsChanged = headingDelta && (headingDelta.appeared > 0 || headingDelta.disappeared > 0);
83
+ const targetAbsent = !limited && !navigated && target && !after.targets.some((node) => node.id === target.id);
84
+ const targetReplaced = targetAbsent && before.targets.filter((node) => targetKey(node) === targetKey(target)).length === 1 &&
85
+ after.targets.filter((node) => targetKey(node) === targetKey(target)).length === 1;
86
+ const changed = navigated || controls.length > 0 || statusChanged > 0 || statusDisappeared > 0 ||
87
+ actions.appeared > 0 || actions.disappeared > 0 || headingsChanged;
88
+ const urlChanged = before.observation.url !== after.observation.url && !statusTextWithheld;
89
+ return {
90
+ ...feedback, change: changed || urlChanged ? "observed" : gaps.length ? "unknown" : "none-observed", navigated,
91
+ ...(urlChanged ? { urlChanged: true } : {}),
92
+ ...(targetAbsent ? targetReplaced ? { targetReplaced: true } : { targetDisappeared: true } : {}),
93
+ ...(actions.appeared ? { actionsAppeared: actions.appeared } : {}),
94
+ ...(actions.disappeared ? { actionsDisappeared: actions.disappeared } : {}),
95
+ ...(headingsChanged ? { headingsChanged: true } : {}),
96
+ ...(statusAppeared ? { statusAppeared } : {}),
97
+ ...(statusDisappeared ? { statusDisappeared } : {}),
98
+ ...(statusChanged ? { statusChanged } : {}),
99
+ ...(statusTextWithheld && (before.statuses.size || after.statuses.size) ? { statusTextWithheld: true } : {}),
100
+ ...(gaps.length ? { gaps } : {}),
101
+ ...(controls.length ? { controls } : {}),
102
+ };
103
+ }