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.
- package/LICENSE.md +105 -0
- package/README.md +101 -2
- package/THIRD_PARTY_NOTICES +12 -0
- package/apps/demo-site/dist/site.js +92 -0
- package/apps/studio/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/apps/studio/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/apps/studio/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/apps/studio/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/apps/studio/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/apps/studio/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/apps/studio/dist/assets/index-DH4wJPHm.js +67 -0
- package/apps/studio/dist/assets/index-DrnNh2ip.css +1 -0
- package/apps/studio/dist/index.html +14 -0
- package/audit.md +173 -0
- package/autonomous-mode.md +104 -0
- package/ci.md +118 -0
- package/coding-agents.md +143 -0
- package/concepts.md +145 -0
- package/contracts.md +356 -0
- package/examples/tasks/ambiguous.json +98 -0
- package/examples/tasks/assertion-failure.json +98 -0
- package/examples/tasks/broken.json +98 -0
- package/examples/tasks/fixed.json +98 -0
- package/examples/tasks/recovery.json +19 -0
- package/images/compare-recovery-desktop.jpg +0 -0
- package/images/compare-variants-desktop.jpg +0 -0
- package/images/overview-desktop.jpg +0 -0
- package/images/run-autonomous-passed-desktop.jpg +0 -0
- package/images/run-failed-desktop.jpg +0 -0
- package/images/run-failed-mobile.jpg +0 -0
- package/images/run-missing-artifact-desktop.jpg +0 -0
- package/images/task-editor-laptop.jpg +0 -0
- package/installation.md +102 -0
- package/ledger.md +62 -0
- package/licenses/-fontsource-variable-geist-mono.txt +93 -0
- package/licenses/-fontsource-variable-geist.txt +93 -0
- package/licenses/lucide-react.txt +43 -0
- package/licenses/react-dom.txt +21 -0
- package/licenses/react.txt +21 -0
- package/licenses/scheduler.txt +21 -0
- package/licenses/tailwindcss.txt +21 -0
- package/licenses/zod.txt +21 -0
- package/package.json +165 -4
- package/packages/cli/bin/agentpath.js +39 -0
- package/packages/cli/dist/audit-rerun.js +384 -0
- package/packages/cli/dist/audit.js +387 -0
- package/packages/cli/dist/change-summaries.js +87 -0
- package/packages/cli/dist/ci-report.js +88 -0
- package/packages/cli/dist/demo.js +88 -0
- package/packages/cli/dist/doctor.js +265 -0
- package/packages/cli/dist/explain.js +89 -0
- package/packages/cli/dist/git.js +7 -0
- package/packages/cli/dist/inspect.js +118 -0
- package/packages/cli/dist/ledger.js +509 -0
- package/packages/cli/dist/local.js +102 -0
- package/packages/cli/dist/main.js +708 -0
- package/packages/cli/dist/mcp.js +231 -0
- package/packages/cli/dist/paths.js +6 -0
- package/packages/cli/dist/playwright-fixture.js +185 -0
- package/packages/cli/dist/playwright-reporter.js +49 -0
- package/packages/cli/dist/tasks.js +37 -0
- package/packages/cli/dist/test-source.js +283 -0
- package/packages/cli/dist/watch.js +96 -0
- package/packages/contracts/dist/agent-settings.js +18 -0
- package/packages/contracts/dist/agent.js +175 -0
- package/packages/contracts/dist/audit.js +115 -0
- package/packages/contracts/dist/guidance.js +339 -0
- package/packages/contracts/dist/index.js +14 -0
- package/packages/contracts/dist/inspect.js +63 -0
- package/packages/contracts/dist/ledger.js +80 -0
- package/packages/contracts/dist/local.js +171 -0
- package/packages/contracts/dist/outcomes.js +94 -0
- package/packages/contracts/dist/platform.js +105 -0
- package/packages/contracts/dist/playwright-live.js +76 -0
- package/packages/contracts/dist/policy.js +93 -0
- package/packages/contracts/dist/run.js +178 -0
- package/packages/contracts/dist/task-issues.js +39 -0
- package/packages/contracts/dist/task.js +185 -0
- package/packages/contracts/dist/watch.js +57 -0
- package/packages/core/dist/action-feedback.js +103 -0
- package/packages/core/dist/actions.js +160 -0
- package/packages/core/dist/agent-loop.js +122 -0
- package/packages/core/dist/artifacts.js +156 -0
- package/packages/core/dist/assertions.js +120 -0
- package/packages/core/dist/autonomous.js +1 -0
- package/packages/core/dist/browser.js +196 -0
- package/packages/core/dist/compare.js +141 -0
- package/packages/core/dist/control-state.js +62 -0
- package/packages/core/dist/diagnostics.js +134 -0
- package/packages/core/dist/evidence-diff.js +93 -0
- package/packages/core/dist/evidence.js +203 -0
- package/packages/core/dist/index.js +22 -0
- package/packages/core/dist/inspect.js +257 -0
- package/packages/core/dist/integrity.js +176 -0
- package/packages/core/dist/liveness.js +114 -0
- package/packages/core/dist/local-files.js +61 -0
- package/packages/core/dist/locators.js +214 -0
- package/packages/core/dist/model-provider.js +88 -0
- package/packages/core/dist/observation.js +257 -0
- package/packages/core/dist/playwright-live.js +519 -0
- package/packages/core/dist/playwright-results.js +543 -0
- package/packages/core/dist/policy.js +182 -0
- package/packages/core/dist/privacy.js +93 -0
- package/packages/core/dist/recovery.js +54 -0
- package/packages/core/dist/retention.js +204 -0
- package/packages/core/dist/run-index.js +177 -0
- package/packages/core/dist/run-plan.js +28 -0
- package/packages/core/dist/run-repository.js +518 -0
- package/packages/core/dist/runner.js +913 -0
- package/packages/core/dist/storage.js +63 -0
- package/packages/core/dist/task-fingerprint.js +36 -0
- package/packages/core/dist/test-change-rerun.js +84 -0
- package/packages/core/dist/test-changes.js +896 -0
- package/packages/core/dist/timing.js +41 -0
- package/packages/core/dist/watch.js +165 -0
- package/packages/server/dist/index.js +265 -0
- package/packages/server/dist/task-store.js +103 -0
- package/quickstart.md +85 -0
- package/security.md +136 -0
- package/try-on-your-repo.md +54 -0
- package/understanding-results.md +159 -0
- package/writing-tasks.md +196 -0
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { agentControlStateEvidenceSchema, agentTraceSchema, BLOCKED_HOST_LIMIT, browserObservationsSchema, captureStateRecordSchema, environmentSchema, failureEvidenceSchema, operationObservationsSchema, runMetadataSchema, runResultSchema, OBSERVATION_LIMITS, SCHEMA_VERSION, taskSchema, } from "#agentpath/contracts";
|
|
6
|
+
import { chromium } from "playwright";
|
|
7
|
+
import { runAgentLoop, AgentLoopError } from "./agent-loop.js";
|
|
8
|
+
import { ProviderError } from "./model-provider.js";
|
|
9
|
+
import { executeStep } from "./actions.js";
|
|
10
|
+
import { collectObservation, confirmControl, confirmTarget, staleReference } from "./observation.js";
|
|
11
|
+
import { actionFeedback, observationGaps } from "./action-feedback.js";
|
|
12
|
+
import { readPopulation } from "./control-state.js";
|
|
13
|
+
import { PolicyMonitor, policyBlocked } from "./policy.js";
|
|
14
|
+
import { ArtifactRecorder } from "./artifacts.js";
|
|
15
|
+
import { assertionHolds, verifyAssertion } from "./assertions.js";
|
|
16
|
+
import { detachedLabel, lateCheck, lateWindow, observedText, pageMessages, RequestFailures } from "./evidence.js";
|
|
17
|
+
import { browserContextOptions, EgressSinkhole, launchGuardedBrowser, NavigationGuard } from "./browser.js";
|
|
18
|
+
import { afterLateCheck, ambiguousTarget, classifyError, navigationFailure, RunFailure } from "./diagnostics.js";
|
|
19
|
+
import { observeTarget, semanticLocator } from "./locators.js";
|
|
20
|
+
import { fingerprintTask } from "./task-fingerprint.js";
|
|
21
|
+
import { INTEGRITY_FILE, pendingIntegrity, sealRun } from "./integrity.js";
|
|
22
|
+
import { LIVENESS_FILE, RunHeartbeat } from "./liveness.js";
|
|
23
|
+
import { RunRepository } from "./run-repository.js";
|
|
24
|
+
import { recordPlan } from "./run-plan.js";
|
|
25
|
+
import { RunStorage } from "./storage.js";
|
|
26
|
+
import { Deadline } from "./timing.js";
|
|
27
|
+
export class UnsupportedExecutionModeError extends Error {
|
|
28
|
+
constructor() {
|
|
29
|
+
super("Autonomous execution requires model provider settings. Configure an endpoint and model in Task Studio or the task JSON.");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function duration(start) {
|
|
33
|
+
return Math.round(Math.max(0, performance.now() - start));
|
|
34
|
+
}
|
|
35
|
+
function navigable(page, guard) {
|
|
36
|
+
const blocked = guard.check(page);
|
|
37
|
+
if (blocked)
|
|
38
|
+
throw navigationFailure(blocked);
|
|
39
|
+
}
|
|
40
|
+
export async function runTask(input, options = {}) {
|
|
41
|
+
const task = taskSchema.parse(input);
|
|
42
|
+
if (task.mode === "autonomous" && !task.agent)
|
|
43
|
+
throw new UnsupportedExecutionModeError();
|
|
44
|
+
const storage = await RunStorage.create(options.runsDirectory, options.onEvent);
|
|
45
|
+
const heartbeat = new RunHeartbeat(storage.path(LIVENESS_FILE), storage.runId, options.liveness);
|
|
46
|
+
try {
|
|
47
|
+
// The lease and the pending integrity record mark this recording as one with liveness and integrity records before any event.
|
|
48
|
+
await heartbeat.start();
|
|
49
|
+
await storage.write(INTEGRITY_FILE, pendingIntegrity(storage.runId));
|
|
50
|
+
return await execute(task, storage, options);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
await heartbeat.release();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function execute(task, storage, options) {
|
|
57
|
+
const repository = new RunRepository(dirname(storage.directory));
|
|
58
|
+
const plan = task.mode === "deterministic" ? task.steps : [];
|
|
59
|
+
const executionTask = { ...task, mode: "deterministic", steps: plan };
|
|
60
|
+
let declaredCompletion = false;
|
|
61
|
+
let decisionCount = 0;
|
|
62
|
+
let chargedTokens = 0;
|
|
63
|
+
let agentFailureKind;
|
|
64
|
+
let termination;
|
|
65
|
+
const agentEntries = [];
|
|
66
|
+
const cancellation = options.signal ?? new AbortController().signal;
|
|
67
|
+
const execution = new AbortController();
|
|
68
|
+
const runTimeoutMs = task.browser.runTimeoutMs ?? 120_000;
|
|
69
|
+
let stopReason;
|
|
70
|
+
function stop(reason) {
|
|
71
|
+
if (stopReason)
|
|
72
|
+
return;
|
|
73
|
+
stopReason = reason;
|
|
74
|
+
execution.abort();
|
|
75
|
+
}
|
|
76
|
+
const cancel = () => stop("cancelled");
|
|
77
|
+
const signal = execution.signal;
|
|
78
|
+
const recorder = new ArtifactRecorder(storage, task.artifacts, executionTask, task.mode === "deterministic" && options.captureText === true);
|
|
79
|
+
if (task.mode === "autonomous")
|
|
80
|
+
recorder.privacy.addValue(process.env.AGENTPATH_MODEL_API_KEY ?? "");
|
|
81
|
+
const guard = new NavigationGuard(task.allowedHosts, (host) => recorder.privacy.host(host));
|
|
82
|
+
let policyContext = { source: task.mode === "autonomous" ? "agent" : "step" };
|
|
83
|
+
const fingerprint = fingerprintTask(task);
|
|
84
|
+
const policy = task.policy ? new PolicyMonitor(task.policy, fingerprint.policyFingerprint, task.baseUrl, (value) => recorder.redact(value), () => policyContext) : undefined;
|
|
85
|
+
const issuedRefs = new Set();
|
|
86
|
+
let referenceSequence = 0;
|
|
87
|
+
let snapshot;
|
|
88
|
+
let navigation = 0;
|
|
89
|
+
const agentChanged = new Set();
|
|
90
|
+
const sinkhole = new EgressSinkhole();
|
|
91
|
+
const startedAt = new Date().toISOString();
|
|
92
|
+
const started = performance.now();
|
|
93
|
+
const steps = [];
|
|
94
|
+
const assertions = [];
|
|
95
|
+
const observations = [];
|
|
96
|
+
let targetObservation = {};
|
|
97
|
+
let browser;
|
|
98
|
+
let browserServer;
|
|
99
|
+
let cleanup = "complete";
|
|
100
|
+
let context;
|
|
101
|
+
let page;
|
|
102
|
+
let browserVersion;
|
|
103
|
+
let traceStarted = false;
|
|
104
|
+
let location = { phase: "startup" };
|
|
105
|
+
let failure;
|
|
106
|
+
let crash;
|
|
107
|
+
let cleaning = false;
|
|
108
|
+
function interruptedFailure() {
|
|
109
|
+
if (stopReason === "cancelled")
|
|
110
|
+
return undefined;
|
|
111
|
+
if (stopReason === "run_timeout")
|
|
112
|
+
return {
|
|
113
|
+
category: "TIMEOUT", expected: "Execution finishes within the configured overall run deadline.",
|
|
114
|
+
observed: "The overall run deadline elapsed.",
|
|
115
|
+
observation: { errorKind: "run_timeout", timeoutScope: "run" },
|
|
116
|
+
};
|
|
117
|
+
if (!cleaning && browserServer && (browserServer.process().exitCode !== null || browserServer.process().signalCode !== null)) {
|
|
118
|
+
crash ??= "browser_disconnected";
|
|
119
|
+
}
|
|
120
|
+
if (crash)
|
|
121
|
+
return {
|
|
122
|
+
category: "BROWSER_ERROR", expected: "A usable Chromium session.",
|
|
123
|
+
observed: crash === "renderer_crash" ? "Chromium confirmed a renderer crash." : "Chromium disconnected during execution.",
|
|
124
|
+
investigation: "Inspect the local browser process and system resource availability.",
|
|
125
|
+
observation: { errorKind: crash },
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
// Closing the live page interrupts Playwright actions, which do not accept AbortSignal.
|
|
129
|
+
let closingPage;
|
|
130
|
+
const interrupt = () => {
|
|
131
|
+
if (page && !page.isClosed())
|
|
132
|
+
closingPage ??= page.close().catch(() => { });
|
|
133
|
+
};
|
|
134
|
+
let consoleErrors = 0;
|
|
135
|
+
let pageErrors = 0;
|
|
136
|
+
const requestFailures = new RequestFailures(task.allowedHosts, recorder.privacy, (request) => policy?.wasBlocked(request) ?? false);
|
|
137
|
+
await storage.write("metadata.json", runMetadataSchema.parse({
|
|
138
|
+
schemaVersion: SCHEMA_VERSION, runId: storage.runId, taskId: task.id,
|
|
139
|
+
fingerprintVersion: 1, hashAlgorithm: "sha256", privacyPolicy: "minimal-after-input-v1",
|
|
140
|
+
...fingerprint,
|
|
141
|
+
}));
|
|
142
|
+
await storage.write("plan.json", { ...recordPlan(executionTask, recorder), mode: task.mode });
|
|
143
|
+
await storage.emit({ type: "run.started", taskId: task.id });
|
|
144
|
+
await repository.recordInIndex(storage.runId);
|
|
145
|
+
signal.addEventListener("abort", interrupt, { once: true });
|
|
146
|
+
cancellation.addEventListener("abort", cancel, { once: true });
|
|
147
|
+
if (cancellation.aborted)
|
|
148
|
+
cancel();
|
|
149
|
+
const timer = setTimeout(() => stop("run_timeout"), runTimeoutMs);
|
|
150
|
+
const executionDeadline = new Deadline(runTimeoutMs, signal);
|
|
151
|
+
try {
|
|
152
|
+
try {
|
|
153
|
+
signal.throwIfAborted();
|
|
154
|
+
browserServer = await launchGuardedBrowser(task.allowedHosts, sinkhole, () => Math.min(10_000, executionDeadline.remaining()));
|
|
155
|
+
browserServer.on("close", () => { if (!cleaning && !signal.aborted)
|
|
156
|
+
crash ??= "browser_disconnected"; });
|
|
157
|
+
browser = await chromium.connect({ wsEndpoint: browserServer.wsEndpoint(), timeout: executionDeadline.remaining() });
|
|
158
|
+
browser.on("disconnected", () => { if (!cleaning && !signal.aborted)
|
|
159
|
+
crash ??= "browser_disconnected"; });
|
|
160
|
+
browserVersion = browser.version();
|
|
161
|
+
signal.throwIfAborted();
|
|
162
|
+
context = await executionDeadline.observe(() => browser.newContext(browserContextOptions(executionTask.browser.viewport, executionTask.browser.mobile === true)));
|
|
163
|
+
await executionDeadline.observe(() => guard.install(context, (request) => policy?.wasBlocked(request) ?? false));
|
|
164
|
+
// Installed after the destination guard so request rules run first and fall back to it.
|
|
165
|
+
if (policy)
|
|
166
|
+
await executionDeadline.observe(() => policy.install(context));
|
|
167
|
+
page = await executionDeadline.observe(() => context.newPage());
|
|
168
|
+
page.on("crash", () => { if (!cleaning && !signal.aborted)
|
|
169
|
+
crash ??= "renderer_crash"; });
|
|
170
|
+
if (task.mode === "autonomous") {
|
|
171
|
+
page.on("framenavigated", (frame) => {
|
|
172
|
+
if (frame !== page?.mainFrame())
|
|
173
|
+
return;
|
|
174
|
+
navigation++;
|
|
175
|
+
agentChanged.clear();
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
requestFailures.watch(page);
|
|
179
|
+
page.on("pageerror", () => { pageErrors++; });
|
|
180
|
+
page.on("console", (message) => { if (message.type() === "error")
|
|
181
|
+
consoleErrors++; });
|
|
182
|
+
signal.throwIfAborted();
|
|
183
|
+
await executionDeadline.observe(() => guard.installRedirectGuard(page));
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
try {
|
|
187
|
+
executionDeadline.remaining();
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
if (!signal.aborted)
|
|
191
|
+
stop("run_timeout");
|
|
192
|
+
}
|
|
193
|
+
if (!signal.aborted)
|
|
194
|
+
failure = interruptedFailure() ?? classifyError(error, location, browser?.isConnected() === false);
|
|
195
|
+
}
|
|
196
|
+
if (!task.artifacts.trace)
|
|
197
|
+
recorder.traceState({ state: "not-requested", reason: "capture-disabled" });
|
|
198
|
+
else if (signal.aborted)
|
|
199
|
+
recorder.traceState({ state: "capture-interrupted", reason: "run-aborted" });
|
|
200
|
+
else if (!page || failure)
|
|
201
|
+
recorder.traceState({ state: "not-attempted", reason: "browser-unavailable" });
|
|
202
|
+
else {
|
|
203
|
+
try {
|
|
204
|
+
await executionDeadline.observe(() => page.context().tracing.start({ screenshots: true, snapshots: true, sources: false }));
|
|
205
|
+
traceStarted = true;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
await storage.emit({ type: "artifact.warning", kind: "trace" });
|
|
209
|
+
recorder.traceState({ state: "capture-failed", reason: "trace-start-failed" });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const activePage = page;
|
|
213
|
+
if (activePage && !failure) {
|
|
214
|
+
const executeAction = async (step, index, extra = {}) => {
|
|
215
|
+
signal.throwIfAborted();
|
|
216
|
+
location = { phase: "step", index, action: step.action };
|
|
217
|
+
const target = "target" in step && step.target.by === "role"
|
|
218
|
+
? { by: step.target.by, role: step.target.role }
|
|
219
|
+
: "target" in step ? { by: "label" } : undefined;
|
|
220
|
+
await storage.emit({
|
|
221
|
+
type: "step.started", index, action: step.action, url: recorder.url(activePage.url()),
|
|
222
|
+
...(target ? { target } : {}),
|
|
223
|
+
});
|
|
224
|
+
policyContext = { ...policyContext, stepIndex: index };
|
|
225
|
+
const outcome = await perform(activePage, location, async (deadline) => {
|
|
226
|
+
await extra.before?.(deadline);
|
|
227
|
+
await executeStep(activePage, executionTask, step, deadline, (observation) => {
|
|
228
|
+
targetObservation = observation;
|
|
229
|
+
// A deterministic fill or keypress can reach the page only once its target resolved to one element.
|
|
230
|
+
// A target that was never found typed nothing, so its failure evidence keeps the pre-input policy.
|
|
231
|
+
if ((step.action === "fill" || step.action === "press") && observation.matchCount === 1)
|
|
232
|
+
recorder.privacy.inputAttempted();
|
|
233
|
+
}, extra.guard, extra.applied, { nearMatches: task.mode === "deterministic" });
|
|
234
|
+
});
|
|
235
|
+
const result = { index, action: step.action, ...outcome };
|
|
236
|
+
steps.push(result);
|
|
237
|
+
await storage.emit({ type: "step.finished", step: result });
|
|
238
|
+
return outcome;
|
|
239
|
+
};
|
|
240
|
+
/** Execution-time element guard. It can only tighten the proposal-time decision, never relax it. */
|
|
241
|
+
const guardFor = (step, entry) => policy && entry && policy.guards(step)
|
|
242
|
+
? async (element) => {
|
|
243
|
+
const check = await policy.guard(activePage, step, element, new Deadline(1000, signal));
|
|
244
|
+
if (check.decision === "allowed")
|
|
245
|
+
return;
|
|
246
|
+
if (entry.decision === "allowed" || check.decision === "unevaluated") {
|
|
247
|
+
Object.assign(entry, { ruleIds: check.ruleIds, decision: check.decision, checkpoint: check.checkpoint, reason: check.reason });
|
|
248
|
+
}
|
|
249
|
+
if (check.decision === "blocked" || (check.decision === "unevaluated" && policy.enforce)) {
|
|
250
|
+
entry.execution = "blocked";
|
|
251
|
+
throw policyBlocked(check.ruleIds);
|
|
252
|
+
}
|
|
253
|
+
} : undefined;
|
|
254
|
+
const blocks = (check) => check.decision === "blocked" || (check.decision === "unevaluated" && policy?.enforce === true);
|
|
255
|
+
const settle = (entry, status) => {
|
|
256
|
+
if (entry && entry.execution !== "blocked")
|
|
257
|
+
entry.execution = status === "passed" ? "executed" : "failed";
|
|
258
|
+
};
|
|
259
|
+
if (task.mode === "autonomous" && task.agent) {
|
|
260
|
+
location = { phase: "agent", index: 0 };
|
|
261
|
+
let lastApplied;
|
|
262
|
+
const recent = [];
|
|
263
|
+
const withSession = async (deadline, read) => {
|
|
264
|
+
const session = await deadline.observe(() => activePage.context().newCDPSession(activePage));
|
|
265
|
+
try {
|
|
266
|
+
return await read(session);
|
|
267
|
+
}
|
|
268
|
+
finally {
|
|
269
|
+
await new Deadline(1000, new AbortController().signal).observe(() => session.detach()).catch(() => { });
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const semanticRole = (target) => semanticLocator(activePage, {
|
|
273
|
+
by: "role", role: target.role, name: target.locatorName,
|
|
274
|
+
});
|
|
275
|
+
const confirm = async (binding, deadline) => {
|
|
276
|
+
if (snapshot?.navigation !== navigation)
|
|
277
|
+
throw staleReference(binding.ref, "expired");
|
|
278
|
+
return withSession(deadline, (session) => confirmControl(session, binding, deadline));
|
|
279
|
+
};
|
|
280
|
+
const liveTarget = async (step, binding) => {
|
|
281
|
+
if (!snapshot || snapshot.navigation !== navigation || !("target" in step))
|
|
282
|
+
return;
|
|
283
|
+
const observed = snapshot;
|
|
284
|
+
const query = step.target;
|
|
285
|
+
const locator = semanticLocator(activePage, query);
|
|
286
|
+
const deadline = new Deadline(Math.min(250, task.browser.timeoutMs), signal);
|
|
287
|
+
try {
|
|
288
|
+
if (await deadline.observe(() => locator.count()) !== 1)
|
|
289
|
+
return;
|
|
290
|
+
let matches = observed.targets;
|
|
291
|
+
if (binding)
|
|
292
|
+
matches = matches.filter((target) => target.id === binding.backendNodeId);
|
|
293
|
+
else if (query.by === "role")
|
|
294
|
+
matches = matches.filter((target) => target.role === query.role && target.locatorName === query.name);
|
|
295
|
+
else {
|
|
296
|
+
const controls = new Set([...observed.refs.values()].map((control) => control.backendNodeId));
|
|
297
|
+
const aliases = await Promise.all(matches.filter((target) => controls.has(target.id))
|
|
298
|
+
.map(async (target) => await deadline.observe(() => locator.and(semanticRole(target)).count()) === 1 ? target : undefined));
|
|
299
|
+
matches = aliases.filter((target) => target !== undefined);
|
|
300
|
+
}
|
|
301
|
+
const target = matches.length === 1 ? matches[0] : undefined;
|
|
302
|
+
if (!target || await deadline.observe(() => semanticRole(target).count()) !== 1)
|
|
303
|
+
return;
|
|
304
|
+
const enabled = await withSession(deadline, (session) => confirmTarget(session, target, deadline));
|
|
305
|
+
return enabled !== undefined && observed.navigation === navigation ? target : undefined;
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
signal.throwIfAborted();
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
const matchesHandle = (target, element, deadline) => deadline.observe(() => semanticRole(target).evaluateAll((matches, handle) => ({
|
|
312
|
+
count: matches.length, found: matches.some((match) => match === handle),
|
|
313
|
+
}), element));
|
|
314
|
+
const performAgentAction = async (action, allowExecution) => {
|
|
315
|
+
const decision = agentEntries.at(-1);
|
|
316
|
+
decision.feedback = { action: action.action, outcome: "failed", change: "unknown" };
|
|
317
|
+
let resolution;
|
|
318
|
+
try {
|
|
319
|
+
resolution = resolveAgentAction(action);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
if (allowExecution)
|
|
323
|
+
throw error;
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const { step, binding } = resolution;
|
|
327
|
+
if (step.action === "fill")
|
|
328
|
+
recorder.privacy.addValue(step.value);
|
|
329
|
+
const proposedTarget = await liveTarget(step, binding);
|
|
330
|
+
const key = proposedTarget && `${navigation}:${proposedTarget.id}:${step.action}`;
|
|
331
|
+
const history = key ? recent.filter((sample) => sample.key === key &&
|
|
332
|
+
decision.sequence - sample.sequence <= OBSERVATION_LIMITS.repetitionWindow) : [];
|
|
333
|
+
const unchanged = history.filter((sample) => sample.outcome === "unchanged");
|
|
334
|
+
const repeated = history.at(-1);
|
|
335
|
+
if (repeated)
|
|
336
|
+
decision.repeated = true;
|
|
337
|
+
if (unchanged.length)
|
|
338
|
+
decision.repetition = {
|
|
339
|
+
previousDecision: unchanged.at(-1).sequence, priorNoChange: unchanged.length,
|
|
340
|
+
};
|
|
341
|
+
const stop = unchanged.length >= 2;
|
|
342
|
+
let entry;
|
|
343
|
+
if (policy) {
|
|
344
|
+
policyContext = { source: "agent", agentSequence: decision.sequence };
|
|
345
|
+
const check = await policy.check(activePage, step, new Deadline(task.browser.timeoutMs, signal));
|
|
346
|
+
if (blocks(check)) {
|
|
347
|
+
// Rejected before any browser side effect: never planned, executed or counted as an action.
|
|
348
|
+
policy.record(step, check, policyContext, "blocked");
|
|
349
|
+
decision.policy = { decision: "blocked", ruleIds: check.ruleIds };
|
|
350
|
+
decision.feedback = { action: action.action, outcome: "rejected" };
|
|
351
|
+
lastApplied = { entry: decision, key };
|
|
352
|
+
await saveAgentTrace(false);
|
|
353
|
+
await savePolicy(false);
|
|
354
|
+
if (allowExecution && history.filter((sample) => sample.outcome === "rejected").length >= 3)
|
|
355
|
+
throw new AgentLoopError("repetition");
|
|
356
|
+
return "rejected";
|
|
357
|
+
}
|
|
358
|
+
if (check.decision === "permitted-violation")
|
|
359
|
+
decision.policy = { decision: "permitted-violation", ruleIds: check.ruleIds };
|
|
360
|
+
// Every evaluated proposal needs a record, even when an execution bound stopped an allowed action.
|
|
361
|
+
entry = policy.record(step, check, allowExecution && !stop ? { ...policyContext, stepIndex: plan.length } : policyContext, "not-executed");
|
|
362
|
+
}
|
|
363
|
+
if (!allowExecution || stop) {
|
|
364
|
+
delete decision.feedback;
|
|
365
|
+
if (allowExecution && stop) {
|
|
366
|
+
decision.repetition.stopped = true;
|
|
367
|
+
throw new AgentLoopError("repetition");
|
|
368
|
+
}
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
let target;
|
|
372
|
+
const policyGuard = guardFor(step, entry);
|
|
373
|
+
// Add population sampling to an existing exact-handle guard. Ordinary semantic actions keep
|
|
374
|
+
// Playwright's locator retry behavior when a page replaces a node during actionability checks.
|
|
375
|
+
const trackFill = step.action === "fill" && (binding || policyGuard)
|
|
376
|
+
? binding ?? [...(snapshot?.refs.values() ?? [])].find((control) => control.backendNodeId === proposedTarget?.id)
|
|
377
|
+
: undefined;
|
|
378
|
+
let initialPopulation;
|
|
379
|
+
let actionDeadline;
|
|
380
|
+
const startedIn = navigation;
|
|
381
|
+
plan.push(step);
|
|
382
|
+
decision.stepIndex = plan.length - 1;
|
|
383
|
+
await saveAgentTrace(false);
|
|
384
|
+
await storage.write("plan.json", { ...recordPlan(executionTask, recorder), mode: task.mode });
|
|
385
|
+
const outcome = await executeAction(step, plan.length - 1, {
|
|
386
|
+
before: async (deadline) => {
|
|
387
|
+
actionDeadline = deadline;
|
|
388
|
+
if (binding)
|
|
389
|
+
validateControlAction(binding, action.action, await confirm(binding, deadline));
|
|
390
|
+
},
|
|
391
|
+
guard: binding || proposedTarget || policyGuard ? async (element) => {
|
|
392
|
+
if (proposedTarget && !binding && startedIn === navigation) {
|
|
393
|
+
try {
|
|
394
|
+
const identity = await matchesHandle(proposedTarget, element, actionDeadline);
|
|
395
|
+
if (identity.count === 1 && identity.found &&
|
|
396
|
+
await withSession(actionDeadline, (session) => confirmTarget(session, proposedTarget, actionDeadline)) !== undefined &&
|
|
397
|
+
startedIn === navigation)
|
|
398
|
+
target = proposedTarget;
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
signal.throwIfAborted();
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const observedBinding = binding ?? trackFill;
|
|
405
|
+
if (observedBinding) {
|
|
406
|
+
try {
|
|
407
|
+
const enabled = await confirm(observedBinding, actionDeadline);
|
|
408
|
+
const locator = semanticLocator(activePage, { by: "role", role: observedBinding.role, name: observedBinding.locatorName });
|
|
409
|
+
const identity = await actionDeadline.observe(() => locator.evaluateAll((matches, handle) => ({
|
|
410
|
+
count: matches.length, found: matches.some((match) => match === handle),
|
|
411
|
+
}), element));
|
|
412
|
+
if (binding && identity.count > 1)
|
|
413
|
+
throw ambiguousTarget(identity.count);
|
|
414
|
+
if (binding && !identity.found)
|
|
415
|
+
throw staleReference(binding.ref);
|
|
416
|
+
if (binding)
|
|
417
|
+
validateControlAction(binding, action.action, enabled);
|
|
418
|
+
if (binding && identity.count === 1 && identity.found)
|
|
419
|
+
target = {
|
|
420
|
+
...binding, id: binding.backendNodeId,
|
|
421
|
+
};
|
|
422
|
+
if (trackFill && identity.count === 1 && identity.found)
|
|
423
|
+
initialPopulation = await readPopulation(element, actionDeadline);
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
if (binding)
|
|
427
|
+
throw error;
|
|
428
|
+
// An optional state sample must not invalidate an ordinary semantic action.
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
await policyGuard?.(element);
|
|
432
|
+
} : undefined,
|
|
433
|
+
applied: trackFill ? async (element) => {
|
|
434
|
+
if (initialPopulation === undefined || startedIn !== navigation)
|
|
435
|
+
return;
|
|
436
|
+
const after = await readPopulation(element, actionDeadline);
|
|
437
|
+
if (after !== undefined && after !== initialPopulation && startedIn === navigation)
|
|
438
|
+
agentChanged.add(trackFill.backendNodeId);
|
|
439
|
+
} : undefined,
|
|
440
|
+
});
|
|
441
|
+
settle(entry, outcome.status);
|
|
442
|
+
await savePolicy(false);
|
|
443
|
+
if (outcome.status !== "passed")
|
|
444
|
+
throw new RunFailure(failure ?? {
|
|
445
|
+
category: "UNKNOWN", expected: "A completed browser action.", observed: "Action was interrupted.", observation: {},
|
|
446
|
+
});
|
|
447
|
+
decision.feedback = {
|
|
448
|
+
action: action.action, outcome: "completed", change: "unknown",
|
|
449
|
+
...(target ? { target: { role: target.role, ...(binding ? { ref: binding.ref } : {}) } } : {}),
|
|
450
|
+
};
|
|
451
|
+
lastApplied = { entry: decision, target, key: target ? key : undefined };
|
|
452
|
+
return "completed";
|
|
453
|
+
};
|
|
454
|
+
const session = await runAgentLoop({
|
|
455
|
+
goal: task.goal, initialUrl: task.baseUrl, allowedHosts: task.allowedHosts,
|
|
456
|
+
settings: task.agent, signal,
|
|
457
|
+
actionIdentity(action) {
|
|
458
|
+
return action.action === "navigate" ? action.url : undefined;
|
|
459
|
+
},
|
|
460
|
+
async onStoppedProposal(action) { await performAgentAction(action, false); },
|
|
461
|
+
async onDecision(entry, action) {
|
|
462
|
+
location = { phase: "agent", index: entry.sequence };
|
|
463
|
+
if (action?.action === "fill")
|
|
464
|
+
recorder.privacy.addValue(action.value);
|
|
465
|
+
const controls = snapshot?.observation.controls;
|
|
466
|
+
const controlStates = controls?.slice(0, OBSERVATION_LIMITS.stateEvidence).map((control) => agentControlStateEvidenceSchema.parse({
|
|
467
|
+
ref: control.ref, role: control.role, kind: control.kind, enabled: control.enabled, supports: control.supports,
|
|
468
|
+
hasValue: control.hasValue, isChecked: control.isChecked, wasChangedByAgent: control.wasChangedByAgent,
|
|
469
|
+
expanded: control.expanded, selectedCount: control.choices?.filter((choice) => choice.selected).length,
|
|
470
|
+
}));
|
|
471
|
+
const completion = entry.tool === "complete" && snapshot ? {
|
|
472
|
+
actionableCount: snapshot.targets.filter((target) => target.enabled).length,
|
|
473
|
+
statusCount: snapshot.statuses.size, gaps: observationGaps(snapshot),
|
|
474
|
+
previousAction: agentEntries.findLast((prior) => prior.feedback)?.feedback,
|
|
475
|
+
} : undefined;
|
|
476
|
+
agentEntries.push({ ...entry, controlStates, completion, message: entry.message ? recorder.redact(entry.message) : undefined });
|
|
477
|
+
await saveAgentTrace(false);
|
|
478
|
+
},
|
|
479
|
+
onProgress: async (progress) => {
|
|
480
|
+
if (!progress.declaredCompletion)
|
|
481
|
+
location = { phase: "agent", index: agentEntries.length };
|
|
482
|
+
decisionCount = progress.decision;
|
|
483
|
+
chargedTokens = progress.chargedTokens;
|
|
484
|
+
declaredCompletion = progress.declaredCompletion;
|
|
485
|
+
await saveAgentTrace(false);
|
|
486
|
+
},
|
|
487
|
+
browser: {
|
|
488
|
+
async observe() {
|
|
489
|
+
return withSession(executionDeadline, async (session) => {
|
|
490
|
+
const sample = () => collectObservation(session, executionDeadline, {
|
|
491
|
+
url: recorder.url(activePage.url()), redact: (value) => recorder.redact(value),
|
|
492
|
+
suppressStaticText: recorder.privacy.suppressScreenshots, navigation,
|
|
493
|
+
nextRef: () => `c${++referenceSequence}`, agentChanged,
|
|
494
|
+
});
|
|
495
|
+
let collected = await sample();
|
|
496
|
+
const last = lastApplied;
|
|
497
|
+
if (snapshot && last?.entry.feedback?.outcome === "completed" &&
|
|
498
|
+
actionFeedback(snapshot, collected, last.entry.feedback, last.target).change !== "observed" &&
|
|
499
|
+
executionDeadline.remaining() > 200) {
|
|
500
|
+
// Give a short delayed UI update one more sample. No browser or model action is retried.
|
|
501
|
+
await delay(120, undefined, { signal });
|
|
502
|
+
collected = await sample();
|
|
503
|
+
}
|
|
504
|
+
if (collected.navigation !== navigation) {
|
|
505
|
+
// The AX tree and control inspection may span an intervening navigation.
|
|
506
|
+
collected.refs.clear();
|
|
507
|
+
collected.targets = [];
|
|
508
|
+
collected.statuses.clear();
|
|
509
|
+
collected.navigation = navigation;
|
|
510
|
+
collected.observation = { url: recorder.url(activePage.url()), accessibility: [], truncated: true };
|
|
511
|
+
}
|
|
512
|
+
for (const ref of collected.refs.keys())
|
|
513
|
+
issuedRefs.add(ref);
|
|
514
|
+
if (snapshot && last?.entry.feedback) {
|
|
515
|
+
const feedback = actionFeedback(snapshot, collected, last.entry.feedback, last.target);
|
|
516
|
+
last.entry.feedback = feedback;
|
|
517
|
+
collected.observation.lastAction = feedback;
|
|
518
|
+
if (feedback.change === "observed" || feedback.change === "unknown" || feedback.targetReplaced)
|
|
519
|
+
recent.length = 0;
|
|
520
|
+
if (last.key && !feedback.navigated && !feedback.targetReplaced && !feedback.targetDisappeared &&
|
|
521
|
+
(feedback.outcome === "rejected" || feedback.change === "observed" || feedback.change === "none-observed")) {
|
|
522
|
+
recent.push({ key: last.key, sequence: last.entry.sequence,
|
|
523
|
+
outcome: feedback.outcome === "rejected" ? "rejected" : feedback.change === "observed" ? "changed" : "unchanged" });
|
|
524
|
+
if (recent.length > OBSERVATION_LIMITS.repetitionWindow)
|
|
525
|
+
recent.shift();
|
|
526
|
+
}
|
|
527
|
+
await saveAgentTrace(false);
|
|
528
|
+
}
|
|
529
|
+
else if (snapshot && recent.length &&
|
|
530
|
+
actionFeedback(snapshot, collected, { action: "click", outcome: "completed" }).change !== "none-observed") {
|
|
531
|
+
recent.length = 0;
|
|
532
|
+
}
|
|
533
|
+
lastApplied = undefined;
|
|
534
|
+
snapshot = collected;
|
|
535
|
+
return collected.observation;
|
|
536
|
+
});
|
|
537
|
+
},
|
|
538
|
+
perform: (action) => performAgentAction(action, true),
|
|
539
|
+
},
|
|
540
|
+
});
|
|
541
|
+
declaredCompletion = session.declaredCompletion;
|
|
542
|
+
}
|
|
543
|
+
else {
|
|
544
|
+
for (const [index, step] of plan.entries()) {
|
|
545
|
+
let entry;
|
|
546
|
+
if (policy) {
|
|
547
|
+
policyContext = { source: "step", stepIndex: index };
|
|
548
|
+
const check = await policy.check(activePage, step, new Deadline(task.browser.timeoutMs, signal));
|
|
549
|
+
entry = policy.record(step, check, policyContext, blocks(check) ? "blocked" : "not-executed");
|
|
550
|
+
if (blocks(check)) {
|
|
551
|
+
location = { phase: "step", index, action: step.action };
|
|
552
|
+
failure = policyBlocked(check.ruleIds).details;
|
|
553
|
+
break;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const outcome = await executeAction(step, index, { guard: guardFor(step, entry) });
|
|
557
|
+
settle(entry, outcome.status);
|
|
558
|
+
if (outcome.status !== "passed")
|
|
559
|
+
break;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
for (const [index, assertion] of task.assertions.entries()) {
|
|
563
|
+
if (signal.aborted || failure)
|
|
564
|
+
break;
|
|
565
|
+
location = { phase: "assertion", index, assertion: assertion.assert };
|
|
566
|
+
await storage.emit({
|
|
567
|
+
type: "assertion.started", index, assertion: assertion.assert, url: recorder.url(activePage.url()),
|
|
568
|
+
});
|
|
569
|
+
const outcome = await perform(activePage, location, (deadline) => verifyAssertion(activePage, assertion, deadline, (observation) => { targetObservation = observation; }, task.browser.timeoutMs));
|
|
570
|
+
const result = { index, assertion: assertion.assert, ...outcome };
|
|
571
|
+
assertions.push(result);
|
|
572
|
+
await storage.emit({ type: "assertion.finished", assertion: result });
|
|
573
|
+
if (outcome.status !== "passed")
|
|
574
|
+
break;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
if (error instanceof AgentLoopError || error instanceof ProviderError)
|
|
580
|
+
agentFailureKind = error.kind;
|
|
581
|
+
if (!signal.aborted)
|
|
582
|
+
failure ??= interruptedFailure() ?? (error instanceof AgentLoopError || error instanceof ProviderError ? {
|
|
583
|
+
category: error instanceof ProviderError ? "PROVIDER_ERROR"
|
|
584
|
+
: error.kind === "invalid_response" ? "AGENT_RESPONSE_INVALID"
|
|
585
|
+
: error.kind === "unable" ? "AGENT_STOPPED" : "AGENT_BUDGET_EXHAUSTED",
|
|
586
|
+
expected: "A valid bounded model decision and completed browser journey.",
|
|
587
|
+
observed: error.message, observation: { errorKind: "unclassified" },
|
|
588
|
+
} : classifyError(error, location, browser?.isConnected() === false));
|
|
589
|
+
}
|
|
590
|
+
finally {
|
|
591
|
+
clearTimeout(timer);
|
|
592
|
+
cancellation.removeEventListener("abort", cancel);
|
|
593
|
+
signal.removeEventListener("abort", interrupt);
|
|
594
|
+
failure = interruptedFailure() ?? failure;
|
|
595
|
+
cleaning = true;
|
|
596
|
+
const cleanupDeadline = new Deadline(5_000, new AbortController().signal);
|
|
597
|
+
try {
|
|
598
|
+
const closing = closingPage;
|
|
599
|
+
if (closing)
|
|
600
|
+
await cleanupDeadline.observe(() => closing);
|
|
601
|
+
}
|
|
602
|
+
catch { /* Continue cleanup after abnormal page termination. */ }
|
|
603
|
+
if (context && traceStarted) {
|
|
604
|
+
const activeContext = context;
|
|
605
|
+
try {
|
|
606
|
+
await recorder.stopTrace(activeContext, Math.min(2000, cleanupDeadline.remaining()));
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
await storage.emit({ type: "artifact.warning", kind: "trace" });
|
|
610
|
+
recorder.traceState({ state: "capture-interrupted", reason: "trace-stop-failed" });
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
const activeContext = context;
|
|
615
|
+
if (activeContext)
|
|
616
|
+
await cleanupDeadline.observe(() => activeContext.close());
|
|
617
|
+
}
|
|
618
|
+
catch { /* A context may be gone after a renderer or browser crash. */ }
|
|
619
|
+
try {
|
|
620
|
+
const server = browserServer;
|
|
621
|
+
// The server close has its own budget, so a slow trace flush above cannot leave it an expired deadline
|
|
622
|
+
// and force-kill a healthy browser.
|
|
623
|
+
if (server)
|
|
624
|
+
await new Deadline(3_000, new AbortController().signal).observe(() => server.close());
|
|
625
|
+
}
|
|
626
|
+
catch {
|
|
627
|
+
cleanup = "forced";
|
|
628
|
+
const server = browserServer;
|
|
629
|
+
if (server) {
|
|
630
|
+
try {
|
|
631
|
+
await new Deadline(2_000, new AbortController().signal).observe(() => server.kill());
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
cleanup = "unconfirmed";
|
|
635
|
+
// This child belongs exclusively to the current run.
|
|
636
|
+
server.process().kill("SIGKILL");
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
finally {
|
|
641
|
+
await sinkhole.close();
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const url = recorder.url(page?.url() ?? "about:blank");
|
|
645
|
+
await storage.write("environment.json", environmentSchema.parse({
|
|
646
|
+
schemaVersion: SCHEMA_VERSION, engine: "chromium", browserVersion,
|
|
647
|
+
nodeVersion: process.version, platform: process.platform, arch: process.arch,
|
|
648
|
+
browser: { ...task.browser, runTimeoutMs }, artifacts: task.artifacts,
|
|
649
|
+
}));
|
|
650
|
+
storage.add("environment", "environment.json");
|
|
651
|
+
const interpretedFailure = failure && await persistFailure(location, failure, url);
|
|
652
|
+
const verdict = interpretedFailure
|
|
653
|
+
? { status: "failed", failure: interpretedFailure }
|
|
654
|
+
: signal.aborted
|
|
655
|
+
? { status: "cancelled" }
|
|
656
|
+
: { status: "passed" };
|
|
657
|
+
if (task.mode === "autonomous" && task.agent) {
|
|
658
|
+
await storage.write("metadata.json", runMetadataSchema.parse({
|
|
659
|
+
schemaVersion: SCHEMA_VERSION, runId: storage.runId, taskId: task.id,
|
|
660
|
+
fingerprintVersion: 1, hashAlgorithm: "sha256", privacyPolicy: "minimal-after-input-v1",
|
|
661
|
+
...fingerprint, stepCount: plan.length,
|
|
662
|
+
}));
|
|
663
|
+
const verification = verdict.status === "passed" ? "passed"
|
|
664
|
+
: failure?.category === "ASSERTION_FAILED" && location.phase === "assertion" ? "failed"
|
|
665
|
+
: declaredCompletion ? "unavailable" : "not-run";
|
|
666
|
+
const kind = verdict.status === "cancelled" ? "cancelled"
|
|
667
|
+
: verification === "passed" ? "verified"
|
|
668
|
+
: declaredCompletion ? verification === "failed" ? "premature-completion" : "verification-unavailable"
|
|
669
|
+
: agentFailureKind === "unable" ? "unable"
|
|
670
|
+
: agentFailureKind === "repetition" ? "repetition"
|
|
671
|
+
: agentFailureKind?.endsWith("_budget") || stopReason === "run_timeout" ? "budget-exhausted"
|
|
672
|
+
: location.phase === "step" || agentEntries.at(-1)?.feedback?.outcome === "failed" ? "action-failure"
|
|
673
|
+
: "unknown";
|
|
674
|
+
termination = { kind, verification };
|
|
675
|
+
await saveAgentTrace(verdict.status === "passed");
|
|
676
|
+
storage.add("agent", "agent.json");
|
|
677
|
+
}
|
|
678
|
+
if (policy) {
|
|
679
|
+
await savePolicy(true);
|
|
680
|
+
storage.add("policy", "policy.json");
|
|
681
|
+
}
|
|
682
|
+
const result = runResultSchema.parse({
|
|
683
|
+
schemaVersion: SCHEMA_VERSION, runId: storage.runId, taskId: task.id, mode: task.mode,
|
|
684
|
+
startedAt, finishedAt: new Date().toISOString(), durationMs: duration(started),
|
|
685
|
+
steps, assertions, artifacts: storage.artifacts, ...verdict,
|
|
686
|
+
});
|
|
687
|
+
await storage.write("operations.json", operationObservationsSchema.parse({
|
|
688
|
+
schemaVersion: SCHEMA_VERSION, runId: storage.runId, operations: observations,
|
|
689
|
+
}));
|
|
690
|
+
const blocked = guard.blockedHosts(BLOCKED_HOST_LIMIT);
|
|
691
|
+
await storage.write("browser-observations.json", browserObservationsSchema.parse({
|
|
692
|
+
schemaVersion: SCHEMA_VERSION, pageErrors, consoleErrors, cleanup,
|
|
693
|
+
...(blocked.hosts.length ? { blockedHosts: blocked.hosts } : {}),
|
|
694
|
+
...(blocked.truncated ? { blockedHostsTruncated: true } : {}),
|
|
695
|
+
...requestFailures.record(),
|
|
696
|
+
}));
|
|
697
|
+
for (let index = steps.length; index < plan.length; index++)
|
|
698
|
+
recorder.notAttempted("step", index);
|
|
699
|
+
for (let index = assertions.length; index < task.assertions.length; index++)
|
|
700
|
+
recorder.notAttempted("assertion", index);
|
|
701
|
+
await storage.write("capture-state.json", captureStateRecordSchema.parse({
|
|
702
|
+
schemaVersion: SCHEMA_VERSION, runId: storage.runId, entries: recorder.captureStates,
|
|
703
|
+
}));
|
|
704
|
+
await storage.write("result.json", result);
|
|
705
|
+
// Seal every finalized file before the terminal event exposes the verdict.
|
|
706
|
+
await storage.write(INTEGRITY_FILE, await sealRun(storage.directory, storage.runId));
|
|
707
|
+
await storage.emit({
|
|
708
|
+
type: "run.finished", status: result.status, durationMs: result.durationMs,
|
|
709
|
+
...(result.status === "failed" ? { failure: result.failure } : {}),
|
|
710
|
+
});
|
|
711
|
+
await repository.recordInIndex(storage.runId);
|
|
712
|
+
return { directory: storage.directory, result };
|
|
713
|
+
/**
|
|
714
|
+
* Evidence after a deterministic failure, by observation only: page messages, a detached label,
|
|
715
|
+
* the failed assertion's text when capture is on, and a bounded late check of the same condition.
|
|
716
|
+
*/
|
|
717
|
+
async function afterFailure(activePage, where, details, startedAt) {
|
|
718
|
+
const extra = {};
|
|
719
|
+
const quick = () => new Deadline(1_000, signal);
|
|
720
|
+
const step = where.phase === "step" ? plan[where.index] : undefined;
|
|
721
|
+
const assertion = where.phase === "assertion" ? task.assertions[where.index] : undefined;
|
|
722
|
+
const messages = await pageMessages(activePage, quick(), options.captureText === true, recorder.privacy);
|
|
723
|
+
if (messages)
|
|
724
|
+
extra.pageMessages = messages;
|
|
725
|
+
const target = step && "target" in step ? step.target : assertion && "target" in assertion ? assertion.target : undefined;
|
|
726
|
+
if (details.category === "TARGET_NOT_FOUND" && target?.by === "label" && await detachedLabel(activePage, target.label, quick())) {
|
|
727
|
+
extra.labelState = "detached";
|
|
728
|
+
}
|
|
729
|
+
if (options.captureText && assertion?.assert === "text" && details.category === "ASSERTION_FAILED") {
|
|
730
|
+
Object.assign(extra, await observedText(activePage, semanticLocator(activePage, assertion.target), quick(), recorder.privacy));
|
|
731
|
+
}
|
|
732
|
+
const lateCategories = ["TARGET_NOT_FOUND", "TIMEOUT", "ASSERTION_FAILED", "TARGET_NOT_INTERACTABLE"];
|
|
733
|
+
let remaining = 0;
|
|
734
|
+
try {
|
|
735
|
+
remaining = executionDeadline.remaining();
|
|
736
|
+
}
|
|
737
|
+
catch { /* No time left for a late check. */ }
|
|
738
|
+
const windowMs = lateWindow(task.browser.timeoutMs, remaining);
|
|
739
|
+
// The late check may only re-test the condition that failed. For an action step that is a missing target, or
|
|
740
|
+
// a target recorded as hidden, disabled or (for a fill) read-only. Anything else, such as a click blocked by
|
|
741
|
+
// an overlay, a disabled option or a control of the wrong type, is a condition it cannot observe, so it
|
|
742
|
+
// records nothing rather than claim the page was merely slow.
|
|
743
|
+
const recorded = details.observation;
|
|
744
|
+
const observable = !step || step.action === "wait" || details.category === "TARGET_NOT_FOUND" ||
|
|
745
|
+
recorded.visible === false || recorded.enabled === false || (step.action === "fill" && recorded.editable === false);
|
|
746
|
+
if (lateCategories.includes(details.category) && recorded.timeoutScope !== "run" && windowMs > 0 && observable) {
|
|
747
|
+
const holds = assertion
|
|
748
|
+
? (deadline) => assertionHolds(activePage, assertion, deadline)
|
|
749
|
+
: step && "target" in step ? async (deadline) => {
|
|
750
|
+
const locator = semanticLocator(activePage, step.target);
|
|
751
|
+
const count = await deadline.observe(() => locator.count());
|
|
752
|
+
if (step.action === "wait") {
|
|
753
|
+
if (step.state === "hidden")
|
|
754
|
+
return count === 0 || (count === 1 && !await deadline.observe(() => locator.isVisible()));
|
|
755
|
+
return count === 1 && await deadline.observe(() => locator.isVisible());
|
|
756
|
+
}
|
|
757
|
+
return count === 1 && await deadline.observe(() => locator.isVisible()) &&
|
|
758
|
+
await deadline.observe(() => locator.isEnabled({ timeout: deadline.remaining() })) &&
|
|
759
|
+
(step.action !== "fill" || await deadline.observe(() => locator.isEditable({ timeout: deadline.remaining() })));
|
|
760
|
+
} : undefined;
|
|
761
|
+
if (holds)
|
|
762
|
+
extra.lateCheck = await lateCheck(holds, startedAt, windowMs, signal);
|
|
763
|
+
}
|
|
764
|
+
return extra;
|
|
765
|
+
}
|
|
766
|
+
async function perform(activePage, where, operation) {
|
|
767
|
+
const name = `${where.phase}-${where.index}`;
|
|
768
|
+
const operationStartedAt = new Date().toISOString();
|
|
769
|
+
const evidence = where.phase === "step"
|
|
770
|
+
? await recorder.capture(activePage, `${name}-before`, false, signal, { phase: where.phase, index: where.index, point: "before" })
|
|
771
|
+
: [];
|
|
772
|
+
const operationStarted = performance.now();
|
|
773
|
+
targetObservation = {};
|
|
774
|
+
try {
|
|
775
|
+
signal.throwIfAborted();
|
|
776
|
+
if (crash)
|
|
777
|
+
throw new RunFailure(interruptedFailure());
|
|
778
|
+
navigable(activePage, guard);
|
|
779
|
+
const step = where.phase === "step" ? plan[where.index] : undefined;
|
|
780
|
+
// Autonomous actions are marked before they run; deterministic ones when their target resolves (above).
|
|
781
|
+
if (task.mode !== "deterministic" && (step?.action === "fill" || step?.action === "press"))
|
|
782
|
+
recorder.privacy.inputAttempted();
|
|
783
|
+
await executionDeadline.observe(() => operation(new Deadline(task.browser.timeoutMs, signal)));
|
|
784
|
+
if (crash)
|
|
785
|
+
throw new RunFailure(interruptedFailure());
|
|
786
|
+
navigable(activePage, guard);
|
|
787
|
+
}
|
|
788
|
+
catch (error) {
|
|
789
|
+
try {
|
|
790
|
+
executionDeadline.remaining();
|
|
791
|
+
}
|
|
792
|
+
catch {
|
|
793
|
+
if (!signal.aborted)
|
|
794
|
+
stop("run_timeout");
|
|
795
|
+
}
|
|
796
|
+
if (!signal.aborted) {
|
|
797
|
+
const blocked = guard.check(activePage);
|
|
798
|
+
const closed = Boolean(crash) || activePage.isClosed() || browser?.isConnected() === false;
|
|
799
|
+
const step = where.phase === "step" ? plan[where.index] : undefined;
|
|
800
|
+
const state = !blocked && !closed && !(error instanceof RunFailure) && step && "target" in step
|
|
801
|
+
? { ...await observeTarget(activePage, step.target, new Deadline(300, signal), step.action === "fill"), timeoutMs: task.browser.timeoutMs }
|
|
802
|
+
: undefined;
|
|
803
|
+
if (!signal.aborted) {
|
|
804
|
+
failure = interruptedFailure() ?? (blocked ? navigationFailure(blocked).details : classifyError(error, where, closed, state));
|
|
805
|
+
if (task.mode === "deterministic" && !blocked && !closed && !signal.aborted) {
|
|
806
|
+
failure = afterLateCheck({ ...failure, observation: { ...failure.observation, ...await afterFailure(activePage, where, failure, operationStarted) } });
|
|
807
|
+
}
|
|
808
|
+
// Page-provided names in the stored failure pass through the same privacy policy as other evidence.
|
|
809
|
+
failure = { ...failure, observation: recorder.observation(failure.observation) };
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
failure ??= interruptedFailure();
|
|
814
|
+
observations.push({
|
|
815
|
+
phase: where.phase, index: where.index,
|
|
816
|
+
observation: recorder.observation(failure?.observation ?? targetObservation),
|
|
817
|
+
});
|
|
818
|
+
const durationMs = duration(operationStarted);
|
|
819
|
+
const status = failure ? "failed" : signal.aborted ? "cancelled" : "passed";
|
|
820
|
+
evidence.push(...await recorder.capture(activePage, `${name}-after`, status === "failed", signal, { phase: where.phase, index: where.index, point: "after" }));
|
|
821
|
+
return {
|
|
822
|
+
startedAt: operationStartedAt, durationMs, status, url: recorder.url(activePage.url()), evidence,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
async function saveAgentTrace(verifiedCompletion) {
|
|
826
|
+
if (task.mode !== "autonomous" || !task.agent)
|
|
827
|
+
return;
|
|
828
|
+
await storage.write("agent.json", agentTraceSchema.parse({
|
|
829
|
+
schemaVersion: 1, runId: storage.runId, provider: task.agent.provider,
|
|
830
|
+
model: recorder.redact(task.agent.model), limits: {
|
|
831
|
+
maxActions: task.agent.maxActions, maxDecisions: task.agent.maxDecisions,
|
|
832
|
+
maxOutputTokens: task.agent.maxOutputTokens, maxTokenBudget: task.agent.maxTokenBudget,
|
|
833
|
+
requestTimeoutMs: task.agent.requestTimeoutMs,
|
|
834
|
+
}, endpointOrigin: new URL(task.agent.endpoint).origin, observationVersion: 4,
|
|
835
|
+
...([task.agent.temperature, task.agent.ollamaThink, task.agent.ollamaFormat].some((value) => value !== undefined)
|
|
836
|
+
? { inference: { temperature: task.agent.temperature, ollamaThink: task.agent.ollamaThink, ollamaFormat: task.agent.ollamaFormat } } : {}),
|
|
837
|
+
declaredCompletion, verifiedCompletion, actionCount: steps.length,
|
|
838
|
+
decisionCount: Math.max(decisionCount, agentEntries.length), chargedTokens,
|
|
839
|
+
failureKind: agentFailureKind, termination, entries: agentEntries,
|
|
840
|
+
}));
|
|
841
|
+
}
|
|
842
|
+
async function savePolicy(final) {
|
|
843
|
+
if (!policy)
|
|
844
|
+
return;
|
|
845
|
+
// Until finalization, a record is incomplete by definition.
|
|
846
|
+
const interrupted = !final || signal.aborted || crash !== undefined || !page;
|
|
847
|
+
await storage.write("policy.json", policy.finalize(storage.runId, interrupted));
|
|
848
|
+
}
|
|
849
|
+
/** Resolves a reference without falling back to a different element. */
|
|
850
|
+
function resolveAgentAction(action) {
|
|
851
|
+
if (action.action === "navigate")
|
|
852
|
+
return { step: action };
|
|
853
|
+
const target = action.action === "select" ? action.control : action.target;
|
|
854
|
+
let binding;
|
|
855
|
+
let locator;
|
|
856
|
+
if (target.by === "ref") {
|
|
857
|
+
binding = snapshot?.refs.get(target.ref);
|
|
858
|
+
if (!binding || snapshot?.navigation !== navigation)
|
|
859
|
+
throw staleReference(target.ref, issuedRefs.has(target.ref) ? "expired" : "never-issued");
|
|
860
|
+
locator = { by: "role", role: binding.role, name: binding.locatorName };
|
|
861
|
+
}
|
|
862
|
+
else
|
|
863
|
+
locator = target;
|
|
864
|
+
switch (action.action) {
|
|
865
|
+
case "click":
|
|
866
|
+
if (locator.by !== "role")
|
|
867
|
+
throw new RunFailure({ category: "TARGET_NOT_FOUND", expected: "A role and name target for click.", observed: "The click target was not a role locator.", observation: {} });
|
|
868
|
+
return { step: { action: "click", target: locator }, binding };
|
|
869
|
+
case "fill": return { step: { action: "fill", target: locator, value: action.value }, binding };
|
|
870
|
+
case "select": return { step: { action: "select", target: locator, option: action.option }, binding };
|
|
871
|
+
case "press": return { step: { action: "press", target: locator, key: action.key }, binding };
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
function validateControlAction(binding, action, enabled) {
|
|
875
|
+
if (!enabled || !binding.enabled)
|
|
876
|
+
throw new RunFailure({
|
|
877
|
+
category: "TARGET_NOT_INTERACTABLE",
|
|
878
|
+
expected: "An enabled control for the proposed action.",
|
|
879
|
+
observed: "The referenced control is disabled.",
|
|
880
|
+
observation: { enabled: false, errorKind: "control_disabled" },
|
|
881
|
+
});
|
|
882
|
+
if (action === "navigate" || binding.supports.includes(action))
|
|
883
|
+
return;
|
|
884
|
+
const wrongType = (action === "select" && binding.kind !== "custom-combobox") ||
|
|
885
|
+
(action === "fill" && binding.kind !== "text-input");
|
|
886
|
+
throw new RunFailure({
|
|
887
|
+
category: wrongType ? "TARGET_NOT_INTERACTABLE" : "UNSUPPORTED_CONTROL",
|
|
888
|
+
expected: "A control that supports the proposed action.",
|
|
889
|
+
observed: "The referenced control does not support that action.",
|
|
890
|
+
observation: { errorKind: wrongType ? "wrong_control_type" : "unsupported_control" },
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
async function persistFailure(where, details, finalUrl) {
|
|
894
|
+
const safeDetails = { ...details, observation: recorder.observation(details.observation) };
|
|
895
|
+
const payload = failureEvidenceSchema.parse({
|
|
896
|
+
schemaVersion: SCHEMA_VERSION, url: finalUrl, location: where, ...safeDetails,
|
|
897
|
+
});
|
|
898
|
+
await storage.write("evidence/failure.json", payload);
|
|
899
|
+
const ref = storage.add("failure", "evidence/failure.json");
|
|
900
|
+
const related = where.phase === "step" ? steps[where.index]?.evidence
|
|
901
|
+
: where.phase === "assertion" ? assertions[where.index]?.evidence : undefined;
|
|
902
|
+
return { ...safeDetails, location: where, evidence: [ref, ...(related ?? [])] };
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
export async function chromiumAvailability() {
|
|
906
|
+
try {
|
|
907
|
+
await access(chromium.executablePath(), constants.X_OK);
|
|
908
|
+
return "installed";
|
|
909
|
+
}
|
|
910
|
+
catch {
|
|
911
|
+
return "missing";
|
|
912
|
+
}
|
|
913
|
+
}
|