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,41 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import { errors } from "playwright";
|
|
3
|
+
export class Deadline {
|
|
4
|
+
signal;
|
|
5
|
+
#end;
|
|
6
|
+
constructor(timeoutMs, signal) {
|
|
7
|
+
this.signal = signal;
|
|
8
|
+
this.#end = performance.now() + timeoutMs;
|
|
9
|
+
}
|
|
10
|
+
remaining() {
|
|
11
|
+
this.signal.throwIfAborted();
|
|
12
|
+
const remaining = Math.ceil(this.#end - performance.now());
|
|
13
|
+
if (remaining <= 0)
|
|
14
|
+
throw new errors.TimeoutError("AgentPath operation deadline elapsed");
|
|
15
|
+
return remaining;
|
|
16
|
+
}
|
|
17
|
+
async observe(operation) {
|
|
18
|
+
const controller = new AbortController();
|
|
19
|
+
const timeoutMs = this.remaining();
|
|
20
|
+
const timeout = delay(timeoutMs, undefined, {
|
|
21
|
+
signal: AbortSignal.any([controller.signal, this.signal]),
|
|
22
|
+
}).then(() => {
|
|
23
|
+
throw new errors.TimeoutError("AgentPath observation deadline elapsed");
|
|
24
|
+
});
|
|
25
|
+
try {
|
|
26
|
+
// Start the operation inside a promise: if it throws before returning one (for example a deadline read in its
|
|
27
|
+
// arguments), the race still owns the timeout, so aborting the timeout below never becomes an unhandled rejection.
|
|
28
|
+
return await Promise.race([new Promise((resolve) => resolve(operation())), timeout]);
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
controller.abort();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async pause() {
|
|
35
|
+
const remaining = this.#end - performance.now();
|
|
36
|
+
if (remaining <= 0)
|
|
37
|
+
return false;
|
|
38
|
+
await delay(Math.min(50, remaining), undefined, { signal: this.signal });
|
|
39
|
+
return performance.now() < this.#end;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
4
|
+
import { browserObservationsSchema, evidenceDirection, failureGuidance, watchStateSchema } from "#agentpath/contracts";
|
|
5
|
+
import { RunRepository } from "./run-repository.js";
|
|
6
|
+
import { runTask } from "./runner.js";
|
|
7
|
+
const MAX_STATE_BYTES = 1024 * 1024;
|
|
8
|
+
/** How many of a task's newest finished runs a rebuild looks through for a verdict. */
|
|
9
|
+
const REBUILD_SCAN = 20;
|
|
10
|
+
/**
|
|
11
|
+
* Reads the watch state file. Run directories stay the source of truth: a missing, unreadable or unknown-version
|
|
12
|
+
* state file is rebuilt from each task's latest passed or failed run, and an unreadable one is reported, never fatal.
|
|
13
|
+
*/
|
|
14
|
+
export async function loadWatchState(path, taskIds, runs) {
|
|
15
|
+
let unreadable = false;
|
|
16
|
+
try {
|
|
17
|
+
const raw = await readFile(path);
|
|
18
|
+
if (raw.byteLength > MAX_STATE_BYTES)
|
|
19
|
+
throw new Error("too large");
|
|
20
|
+
const parsed = watchStateSchema.safeParse(JSON.parse(raw.toString("utf8")));
|
|
21
|
+
if (parsed.success)
|
|
22
|
+
return { state: parsed.data, source: "read" };
|
|
23
|
+
unreadable = true;
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code !== "ENOENT")
|
|
27
|
+
unreadable = true;
|
|
28
|
+
}
|
|
29
|
+
const state = { schemaVersion: 1, tasks: {} };
|
|
30
|
+
for (const taskId of new Set(taskIds)) {
|
|
31
|
+
// Newest first; a startup browser failure is not a verdict, so it is skipped as it was when recorded.
|
|
32
|
+
for (const summary of (await runs.list({ taskId, status: ["passed", "failed"], limit: REBUILD_SCAN })).runs) {
|
|
33
|
+
if ((summary.status !== "passed" && summary.status !== "failed") || !summary.startedAt)
|
|
34
|
+
continue;
|
|
35
|
+
if (summary.status === "failed") {
|
|
36
|
+
const result = await runs.detail(summary.runId).then((detail) => detail.result, () => undefined);
|
|
37
|
+
if (!result || isInfrastructureFailure(result))
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
state.tasks[taskId] = { verdict: summary.status, runId: summary.runId, at: summary.startedAt };
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (unreadable)
|
|
45
|
+
return { state, source: "rebuilt-unreadable" };
|
|
46
|
+
return { state, source: Object.keys(state.tasks).length ? "rebuilt" : "new" };
|
|
47
|
+
}
|
|
48
|
+
/** Writes the state file atomically, readable only by its owner. */
|
|
49
|
+
export async function saveWatchState(path, state) {
|
|
50
|
+
await mkdir(dirname(path), { recursive: true });
|
|
51
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
52
|
+
await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
53
|
+
await rename(temporary, path);
|
|
54
|
+
}
|
|
55
|
+
/** A run that never reached the site because the browser could not start here: an infrastructure fact, not a verdict. */
|
|
56
|
+
export function isInfrastructureFailure(result) {
|
|
57
|
+
return result.status === "failed" && result.failure.category === "BROWSER_ERROR" && result.failure.location.phase === "startup";
|
|
58
|
+
}
|
|
59
|
+
/** Where a failed run's recorded evidence points, from the same failure guidance the CLI prints. */
|
|
60
|
+
export function watchEvidence(task, result, browser) {
|
|
61
|
+
if (result.status !== "failed")
|
|
62
|
+
return undefined;
|
|
63
|
+
return evidenceDirection(failureGuidance(task, result.failure, browser).findings);
|
|
64
|
+
}
|
|
65
|
+
/** A short reason without paths or raw messages: the error code when there is one. */
|
|
66
|
+
function unrecordedReason(error) {
|
|
67
|
+
const code = error?.code;
|
|
68
|
+
return typeof code === "string" && /^[A-Z_]{2,32}$/.test(code) ? `The run could not be recorded (${code}).` : "The run could not be recorded.";
|
|
69
|
+
}
|
|
70
|
+
async function readBrowserObservations(directory) {
|
|
71
|
+
try {
|
|
72
|
+
const parsed = browserObservationsSchema.safeParse(JSON.parse(await readFile(join(directory, "browser-observations.json"), "utf8")));
|
|
73
|
+
return parsed.success ? parsed.data : undefined;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Applies one round of results to the state. An alert is a verdict transition only: a first verdict sets a baseline,
|
|
81
|
+
* a cancelled run or a startup browser failure changes nothing, and a new failure category while a task keeps
|
|
82
|
+
* failing is not an alert.
|
|
83
|
+
*/
|
|
84
|
+
export function applyRound(state, results, at) {
|
|
85
|
+
const next = { schemaVersion: 1, tasks: { ...state.tasks } };
|
|
86
|
+
const alerts = [];
|
|
87
|
+
for (const entry of results) {
|
|
88
|
+
const { result, evidence } = "result" in entry ? entry : { result: entry, evidence: undefined };
|
|
89
|
+
if (result.status === "cancelled" || isInfrastructureFailure(result))
|
|
90
|
+
continue;
|
|
91
|
+
const previous = next.tasks[result.taskId];
|
|
92
|
+
if (previous && previous.verdict !== result.status) {
|
|
93
|
+
alerts.push({
|
|
94
|
+
taskId: result.taskId, from: previous.verdict, to: result.status, runId: result.runId, previousRunId: previous.runId,
|
|
95
|
+
...(result.status === "failed" ? { category: result.failure.category, ...(evidence ? { evidence } : {}) } : {}),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
next.tasks[result.taskId] = { verdict: result.status, runId: result.runId, at };
|
|
99
|
+
}
|
|
100
|
+
return { state: next, alerts };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Runs every task once per round, one after another, and starts the next round `everyMs` after the previous one
|
|
104
|
+
* finished, so rounds never overlap. The state file is written after each round, before `onRound`.
|
|
105
|
+
*/
|
|
106
|
+
export async function watchTasks(tasks, options) {
|
|
107
|
+
const runs = new RunRepository(options.runsDirectory);
|
|
108
|
+
const loaded = await loadWatchState(options.statePath, tasks.map(({ task }) => task.id), runs);
|
|
109
|
+
let state = loaded.state;
|
|
110
|
+
let round = 0;
|
|
111
|
+
while (!options.signal?.aborted && (options.rounds === undefined || round < options.rounds)) {
|
|
112
|
+
if (round > 0) {
|
|
113
|
+
try {
|
|
114
|
+
await sleep(options.everyMs, undefined, { signal: options.signal });
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
round += 1;
|
|
121
|
+
const startedAt = new Date().toISOString();
|
|
122
|
+
const entries = [];
|
|
123
|
+
const results = [];
|
|
124
|
+
const notRun = [];
|
|
125
|
+
for (const { file, task } of tasks) {
|
|
126
|
+
if (options.signal?.aborted)
|
|
127
|
+
break;
|
|
128
|
+
let run;
|
|
129
|
+
try {
|
|
130
|
+
run = await runTask(task, { runsDirectory: options.runsDirectory, signal: options.signal, captureText: options.captureText === true });
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
// One run that cannot be recorded must not end a scheduled monitor or lose the round's other verdicts.
|
|
134
|
+
notRun.push({ file, taskId: task.id, reason: unrecordedReason(error) });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const { result } = run;
|
|
138
|
+
const infrastructure = isInfrastructureFailure(result);
|
|
139
|
+
const evidence = result.status === "failed" && !infrastructure ? watchEvidence(task, result, await readBrowserObservations(run.directory)) : undefined;
|
|
140
|
+
results.push({ result, ...(evidence ? { evidence } : {}) });
|
|
141
|
+
entries.push({ file, taskId: result.taskId, runId: result.runId, status: result.status,
|
|
142
|
+
...(result.status === "failed" ? { category: result.failure.category } : {}),
|
|
143
|
+
...(evidence ? { evidence } : {}), ...(infrastructure ? { infrastructure: true } : {}) });
|
|
144
|
+
await options.onRun?.(file, run);
|
|
145
|
+
}
|
|
146
|
+
const finishedAt = new Date().toISOString();
|
|
147
|
+
const applied = applyRound(state, results, finishedAt);
|
|
148
|
+
state = applied.state;
|
|
149
|
+
let saveError;
|
|
150
|
+
try {
|
|
151
|
+
await saveWatchState(options.statePath, state);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
saveError = error;
|
|
155
|
+
}
|
|
156
|
+
// The round, and above all its alerts, is reported even when the state could not be saved; then watch stops.
|
|
157
|
+
await options.onRound({
|
|
158
|
+
schemaVersion: 1, round, startedAt, finishedAt, ...(round === 1 ? { state: loaded.source } : {}), tasks: entries, alerts: applied.alerts,
|
|
159
|
+
...(notRun.length ? { notRun } : {}), ...(saveError ? { stateNotSaved: true } : {}),
|
|
160
|
+
});
|
|
161
|
+
if (saveError)
|
|
162
|
+
throw saveError;
|
|
163
|
+
}
|
|
164
|
+
return round;
|
|
165
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { lstat, mkdir } from "node:fs/promises";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import fastify from "fastify";
|
|
4
|
+
import fastifyStatic from "@fastify/static";
|
|
5
|
+
import { artifactPathSchema, compareRequestSchema, errorResponseSchema, healthSchema, integrityReportSchema, runDetailSchema, runEventsSchema, runListQuerySchema, runListSchema, runPathSchema, runRequestSchema, runSummarySchema, taskListSchema, taskPathSchema, taskSchema, } from "#agentpath/contracts";
|
|
6
|
+
import { chromiumAvailability, compareRuns, ComparisonUnavailable, InvalidCursor, isInvalidRecord, isMissing, RunRepository, runTask, } from "#agentpath/core";
|
|
7
|
+
import { TaskStore, taskBytesLimit } from "./task-store.js";
|
|
8
|
+
export const studioPort = 4317;
|
|
9
|
+
class ApiError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
constructor(status, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.status = status;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
class InvalidRequest extends Error {
|
|
17
|
+
issues;
|
|
18
|
+
constructor(issues) {
|
|
19
|
+
super("Invalid request.");
|
|
20
|
+
this.issues = issues;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function input(schema, value) {
|
|
24
|
+
const parsed = schema.safeParse(value);
|
|
25
|
+
if (!parsed.success)
|
|
26
|
+
throw new InvalidRequest(parsed.error.issues.map((issue) => ({
|
|
27
|
+
path: issue.path.map(String).join("."), message: issue.message,
|
|
28
|
+
})));
|
|
29
|
+
return parsed.data;
|
|
30
|
+
}
|
|
31
|
+
function send(reply, schema, value, code = 200) {
|
|
32
|
+
return reply.code(code).send(schema.parse(value));
|
|
33
|
+
}
|
|
34
|
+
export function createLocalApi(options = {}) {
|
|
35
|
+
const workspace = resolve(options.workspace ?? ".");
|
|
36
|
+
const dataDirectory = join(workspace, ".agentpath");
|
|
37
|
+
const taskStore = new TaskStore(join(dataDirectory, "tasks"));
|
|
38
|
+
const runs = new RunRepository(join(dataDirectory, "runs"));
|
|
39
|
+
// preClose aborts and awaits evidence writes before Fastify closes lingering local HTTP connections.
|
|
40
|
+
const server = fastify({ bodyLimit: taskBytesLimit, requestTimeout: 30_000, forceCloseConnections: true });
|
|
41
|
+
const active = new Map();
|
|
42
|
+
const pending = new Set();
|
|
43
|
+
const concurrency = 1;
|
|
44
|
+
let closing = false;
|
|
45
|
+
server.addHook("onReady", async () => {
|
|
46
|
+
await mkdir(dataDirectory, { recursive: true, mode: 0o700 });
|
|
47
|
+
if (!(await lstat(dataDirectory)).isDirectory())
|
|
48
|
+
throw new Error("The workspace storage directory must be a real directory.");
|
|
49
|
+
});
|
|
50
|
+
server.addHook("onRequest", async (request, reply) => {
|
|
51
|
+
reply.headers({
|
|
52
|
+
"cache-control": "no-store",
|
|
53
|
+
"x-content-type-options": "nosniff",
|
|
54
|
+
"referrer-policy": "no-referrer",
|
|
55
|
+
"cross-origin-resource-policy": "same-origin",
|
|
56
|
+
"content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
57
|
+
});
|
|
58
|
+
const bound = server.server.address();
|
|
59
|
+
const port = bound && typeof bound === "object" ? bound.port : options.port ?? studioPort;
|
|
60
|
+
const host = `127.0.0.1:${port}`;
|
|
61
|
+
if (request.headers.host !== host) {
|
|
62
|
+
// Someone who typed localhost is sent to the fixed loopback address. The target never comes from the
|
|
63
|
+
// request, and API requests are still refused.
|
|
64
|
+
const page = request.routeOptions.url !== undefined && !request.routeOptions.url.startsWith("/api/");
|
|
65
|
+
if (page && request.method === "GET" && request.headers.host === `localhost:${port}`) {
|
|
66
|
+
return reply.redirect(`http://${host}/`, 307);
|
|
67
|
+
}
|
|
68
|
+
throw new ApiError(403, `Unrecognized local Host. Open http://${host}/ instead.`);
|
|
69
|
+
}
|
|
70
|
+
if (request.headers.origin !== undefined && request.headers.origin !== `http://${host}`) {
|
|
71
|
+
throw new ApiError(403, "Unrecognized Origin.");
|
|
72
|
+
}
|
|
73
|
+
// Use the matched route, not the raw URL, so percent-encoded paths such as /%61pi/ cannot skip
|
|
74
|
+
// these checks. Unmatched paths are treated like API paths.
|
|
75
|
+
const route = request.routeOptions.url;
|
|
76
|
+
const apiRequest = route === undefined || route.startsWith("/api/");
|
|
77
|
+
const fetchSite = request.headers["sec-fetch-site"];
|
|
78
|
+
if (apiRequest && fetchSite && !["none", "same-origin"].includes(String(fetchSite))) {
|
|
79
|
+
throw new ApiError(403, "Cross-origin API requests are blocked.");
|
|
80
|
+
}
|
|
81
|
+
if (apiRequest && !(await lstat(dataDirectory)).isDirectory()) {
|
|
82
|
+
throw new ApiError(403, "The workspace storage directory must be a real directory.");
|
|
83
|
+
}
|
|
84
|
+
if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && request.headers["x-agentpath-client"] !== "studio") {
|
|
85
|
+
throw new ApiError(403, "State changes require the X-AgentPath-Client header.");
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
server.setErrorHandler((error, _request, reply) => {
|
|
89
|
+
if (error instanceof InvalidRequest) {
|
|
90
|
+
return send(reply, errorResponseSchema, { error: error.message, issues: error.issues }, 400);
|
|
91
|
+
}
|
|
92
|
+
if (error instanceof InvalidCursor)
|
|
93
|
+
return send(reply, errorResponseSchema, { error: error.message }, 400);
|
|
94
|
+
if (error instanceof ApiError || error instanceof ComparisonUnavailable) {
|
|
95
|
+
return send(reply, errorResponseSchema, { error: error.message }, error instanceof ApiError ? error.status : 409);
|
|
96
|
+
}
|
|
97
|
+
if (isMissing(error))
|
|
98
|
+
return send(reply, errorResponseSchema, { error: "Local record or artifact unavailable." }, 404);
|
|
99
|
+
if (isInvalidRecord(error)) {
|
|
100
|
+
return send(reply, errorResponseSchema, {
|
|
101
|
+
error: "The stored record is unreadable or uses an unsupported format.",
|
|
102
|
+
}, 422);
|
|
103
|
+
}
|
|
104
|
+
const status = error.statusCode;
|
|
105
|
+
if (status && status >= 400 && status < 500) {
|
|
106
|
+
return send(reply, errorResponseSchema, { error: status === 413 ? "Request exceeds the size limit." : "Invalid HTTP request." }, status);
|
|
107
|
+
}
|
|
108
|
+
return send(reply, errorResponseSchema, { error: "AgentPath could not read or write the local record." }, 500);
|
|
109
|
+
});
|
|
110
|
+
server.setNotFoundHandler((_request, reply) => send(reply, errorResponseSchema, { error: "Route not found." }, 404));
|
|
111
|
+
if (options.studioDirectory) {
|
|
112
|
+
server.register(fastifyStatic, { root: options.studioDirectory, wildcard: false, index: false });
|
|
113
|
+
server.get("/", (_request, reply) => reply.sendFile("index.html"));
|
|
114
|
+
}
|
|
115
|
+
server.get("/api/health", async (_request, reply) => send(reply, healthSchema, {
|
|
116
|
+
status: "ready", runtime: process.version, platform: `${process.platform} / ${process.arch}`,
|
|
117
|
+
chromium: await chromiumAvailability(), activeRuns: pending.size, concurrency,
|
|
118
|
+
}));
|
|
119
|
+
server.get("/api/tasks", async (_request, reply) => {
|
|
120
|
+
const { tasks, unreadable } = await taskStore.list();
|
|
121
|
+
return send(reply.header("x-agentpath-unreadable-tasks", String(unreadable)), taskListSchema, tasks);
|
|
122
|
+
});
|
|
123
|
+
server.get("/api/tasks/:taskId", async (request, reply) => {
|
|
124
|
+
const { taskId } = input(taskPathSchema, request.params);
|
|
125
|
+
return send(reply, taskSchema, await requireTask(taskId));
|
|
126
|
+
});
|
|
127
|
+
server.post("/api/tasks", async (request, reply) => {
|
|
128
|
+
const task = input(taskSchema, request.body);
|
|
129
|
+
if (!await taskStore.save(task, true))
|
|
130
|
+
throw new ApiError(409, "A task already has that ID.");
|
|
131
|
+
return send(reply, taskSchema, task, 201);
|
|
132
|
+
});
|
|
133
|
+
server.put("/api/tasks/:taskId", async (request, reply) => {
|
|
134
|
+
const { taskId } = input(taskPathSchema, request.params);
|
|
135
|
+
const task = input(taskSchema, request.body);
|
|
136
|
+
if (task.id !== taskId)
|
|
137
|
+
throw new ApiError(400, "A saved task ID cannot be changed.");
|
|
138
|
+
if (!await taskStore.save(task, false))
|
|
139
|
+
throw new ApiError(404, "Task not found.");
|
|
140
|
+
return send(reply, taskSchema, task);
|
|
141
|
+
});
|
|
142
|
+
server.delete("/api/tasks/:taskId", async (request, reply) => {
|
|
143
|
+
const { taskId } = input(taskPathSchema, request.params);
|
|
144
|
+
if (!await taskStore.remove(taskId))
|
|
145
|
+
throw new ApiError(404, "Task not found.");
|
|
146
|
+
return reply.code(204).send();
|
|
147
|
+
});
|
|
148
|
+
server.post("/api/runs", async (request, reply) => {
|
|
149
|
+
const { taskId } = input(runRequestSchema, request.body);
|
|
150
|
+
const task = await requireTask(taskId);
|
|
151
|
+
if (task.mode === "autonomous" && !task.agent)
|
|
152
|
+
throw new ApiError(409, "Configure a model endpoint and model before running.");
|
|
153
|
+
if (closing || pending.size >= concurrency)
|
|
154
|
+
throw new ApiError(409, "A browser run is already in progress.");
|
|
155
|
+
if (task.allowedHosts.includes(request.headers.host ?? "")) {
|
|
156
|
+
throw new ApiError(400, "Use a separate site origin for browser runs.");
|
|
157
|
+
}
|
|
158
|
+
const controller = new AbortController();
|
|
159
|
+
const started = Promise.withResolvers();
|
|
160
|
+
const job = { controller, done: Promise.resolve() };
|
|
161
|
+
pending.add(job);
|
|
162
|
+
let id;
|
|
163
|
+
job.done = runTask(task, {
|
|
164
|
+
runsDirectory: runs.root, signal: controller.signal,
|
|
165
|
+
onEvent(event) {
|
|
166
|
+
if (event.type !== "run.started")
|
|
167
|
+
return;
|
|
168
|
+
id = event.runId;
|
|
169
|
+
active.set(id, job);
|
|
170
|
+
started.resolve({ runId: id, taskId, startedAt: event.at, status: "running" });
|
|
171
|
+
},
|
|
172
|
+
}).catch(started.reject).finally(() => {
|
|
173
|
+
pending.delete(job);
|
|
174
|
+
if (id)
|
|
175
|
+
active.delete(id);
|
|
176
|
+
});
|
|
177
|
+
const summary = await started.promise;
|
|
178
|
+
return send(reply.header("location", `/api/runs/${summary.runId}`), runSummarySchema, summary, 202);
|
|
179
|
+
});
|
|
180
|
+
// The body stays a summary array. Pagination state travels in headers, like the unreadable-task count.
|
|
181
|
+
server.get("/api/runs", async (request, reply) => {
|
|
182
|
+
const query = input(runListQuerySchema, request.query);
|
|
183
|
+
const page = await runs.list({ ...query, state: runState });
|
|
184
|
+
if (page.nextCursor)
|
|
185
|
+
reply.header("x-agentpath-next-cursor", page.nextCursor);
|
|
186
|
+
return send(reply.header("x-agentpath-run-source", page.source), runListSchema, page.runs);
|
|
187
|
+
});
|
|
188
|
+
server.get("/api/runs/:runId/integrity", async (request, reply) => {
|
|
189
|
+
const { runId } = input(runPathSchema, request.params);
|
|
190
|
+
await existingEvents(runId);
|
|
191
|
+
return send(reply, integrityReportSchema, await runs.integrity(runId));
|
|
192
|
+
});
|
|
193
|
+
server.get("/api/runs/:runId", async (request, reply) => {
|
|
194
|
+
const { runId } = input(runPathSchema, request.params);
|
|
195
|
+
const events = await existingEvents(runId);
|
|
196
|
+
return send(reply, runDetailSchema, await detail(runId, events));
|
|
197
|
+
});
|
|
198
|
+
server.get("/api/runs/:runId/events", async (request, reply) => {
|
|
199
|
+
const { runId } = input(runPathSchema, request.params);
|
|
200
|
+
return send(reply, runEventsSchema, await existingEvents(runId));
|
|
201
|
+
});
|
|
202
|
+
server.get("/api/runs/:runId/artifacts/:index", async (request, reply) => {
|
|
203
|
+
const { runId, index } = input(artifactPathSchema, request.params);
|
|
204
|
+
const { ref, data } = await runs.artifact(runId, index);
|
|
205
|
+
if (ref.kind === "trace") {
|
|
206
|
+
return reply.type("application/zip").header("content-disposition", 'attachment; filename="trace.zip"').send(data);
|
|
207
|
+
}
|
|
208
|
+
return reply.type(ref.kind === "screenshot" ? "image/png" : "application/json").send(data);
|
|
209
|
+
});
|
|
210
|
+
server.post("/api/runs/:runId/cancel", async (request, reply) => {
|
|
211
|
+
const { runId } = input(runPathSchema, request.params);
|
|
212
|
+
const events = await existingEvents(runId);
|
|
213
|
+
const job = active.get(runId);
|
|
214
|
+
// Runs owned by another process, such as a direct CLI run, are observed but never signalled from here.
|
|
215
|
+
if (!job || events.at(-1)?.type === "run.finished")
|
|
216
|
+
throw new ApiError(409, "This run is no longer active in this Studio server.");
|
|
217
|
+
job.controller.abort();
|
|
218
|
+
return send(reply, runDetailSchema, await detail(runId), 202);
|
|
219
|
+
});
|
|
220
|
+
server.get("/api/compare", async (request) => {
|
|
221
|
+
const { baseline, candidate, mode } = input(compareRequestSchema, request.query);
|
|
222
|
+
const [a, b] = await Promise.all([existingEvents(baseline), existingEvents(candidate)]);
|
|
223
|
+
if (a.at(-1)?.type !== "run.finished" || b.at(-1)?.type !== "run.finished") {
|
|
224
|
+
throw new ComparisonUnavailable("Comparison requires two finalized runs.");
|
|
225
|
+
}
|
|
226
|
+
return compareRuns(await runs.comparisonDetail(baseline), await runs.comparisonDetail(candidate), mode);
|
|
227
|
+
});
|
|
228
|
+
server.addHook("preClose", async () => {
|
|
229
|
+
closing = true;
|
|
230
|
+
for (const job of pending)
|
|
231
|
+
job.controller.abort();
|
|
232
|
+
await Promise.all([...pending].map((job) => job.done));
|
|
233
|
+
});
|
|
234
|
+
async function requireTask(id) {
|
|
235
|
+
const task = await taskStore.get(id);
|
|
236
|
+
if (!task)
|
|
237
|
+
throw new ApiError(404, "Task not found.");
|
|
238
|
+
return task;
|
|
239
|
+
}
|
|
240
|
+
async function existingEvents(id) {
|
|
241
|
+
const events = await runs.events(id);
|
|
242
|
+
if (!events.length && !(await runs.ids()).includes(id))
|
|
243
|
+
throw new ApiError(404, "Run not found.");
|
|
244
|
+
return events;
|
|
245
|
+
}
|
|
246
|
+
function runState(id) {
|
|
247
|
+
const job = active.get(id);
|
|
248
|
+
return { active: Boolean(job), cancelling: job?.controller.signal.aborted ?? false };
|
|
249
|
+
}
|
|
250
|
+
function detail(id, events) {
|
|
251
|
+
return runs.detail(id, runState(id), events);
|
|
252
|
+
}
|
|
253
|
+
return server;
|
|
254
|
+
}
|
|
255
|
+
export async function listenLocalApi(options = {}) {
|
|
256
|
+
const server = createLocalApi(options);
|
|
257
|
+
try {
|
|
258
|
+
const url = await server.listen({ host: "127.0.0.1", port: options.port ?? studioPort });
|
|
259
|
+
return { server, url };
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
await server.close().catch(() => { });
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { lstat, mkdir, readdir, unlink } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { taskIdSchema, taskSchema } from "#agentpath/contracts";
|
|
4
|
+
import { isInvalidRecord, isMissing, parseRecord, readLocalFile, StoredRecordInvalid, writeLocalJson } from "#agentpath/core";
|
|
5
|
+
export const taskBytesLimit = 8 * 1024 * 1024;
|
|
6
|
+
export class TaskStore {
|
|
7
|
+
directory;
|
|
8
|
+
#mutation = Promise.resolve();
|
|
9
|
+
constructor(directory) {
|
|
10
|
+
this.directory = directory;
|
|
11
|
+
}
|
|
12
|
+
/** Lists valid tasks. One malformed file is counted instead of hiding every other task. */
|
|
13
|
+
async list() {
|
|
14
|
+
await this.prepare();
|
|
15
|
+
const entries = await readdir(this.directory, { withFileTypes: true });
|
|
16
|
+
const tasks = [];
|
|
17
|
+
let unreadable = 0;
|
|
18
|
+
for (const entry of entries) {
|
|
19
|
+
if (!entry.isFile() || !entry.name.endsWith(".json"))
|
|
20
|
+
continue;
|
|
21
|
+
const id = entry.name.slice(0, -5);
|
|
22
|
+
if (!taskIdSchema.safeParse(id).success)
|
|
23
|
+
continue;
|
|
24
|
+
try {
|
|
25
|
+
const task = await this.get(id);
|
|
26
|
+
if (task)
|
|
27
|
+
tasks.push(task);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (!isInvalidRecord(error))
|
|
31
|
+
throw error;
|
|
32
|
+
unreadable++;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { tasks: tasks.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id)), unreadable };
|
|
36
|
+
}
|
|
37
|
+
async get(id) {
|
|
38
|
+
const filename = this.filename(id);
|
|
39
|
+
try {
|
|
40
|
+
const bytes = await readLocalFile(this.directory, filename, taskBytesLimit);
|
|
41
|
+
const task = parseRecord(() => taskSchema.parse(JSON.parse(bytes.toString())));
|
|
42
|
+
if (task.id !== id)
|
|
43
|
+
throw new StoredRecordInvalid("The saved task ID differs from its filename.");
|
|
44
|
+
return task;
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (!isMissing(error))
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
save(task, create) {
|
|
52
|
+
return this.mutate(async () => {
|
|
53
|
+
await this.prepare();
|
|
54
|
+
const filename = join(this.directory, this.filename(task.id));
|
|
55
|
+
// Existence, not validity: an update overwrites a malformed file, which is how it is repaired.
|
|
56
|
+
const exists = await this.exists(task.id);
|
|
57
|
+
if (create ? exists : !exists)
|
|
58
|
+
return false;
|
|
59
|
+
await writeLocalJson(filename, task);
|
|
60
|
+
return true;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
remove(id) {
|
|
64
|
+
return this.mutate(async () => {
|
|
65
|
+
// A malformed file can be deleted too; it is only counted as unreadable in listings.
|
|
66
|
+
if (!await this.exists(id))
|
|
67
|
+
return false;
|
|
68
|
+
await unlink(join(this.directory, this.filename(id)));
|
|
69
|
+
return true;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Whether a task file exists, valid or not. Any entry under the name counts, so a create never replaces it;
|
|
74
|
+
* an entry that is not a regular file (a link or a directory) is refused, never followed or replaced.
|
|
75
|
+
*/
|
|
76
|
+
async exists(id) {
|
|
77
|
+
let info;
|
|
78
|
+
try {
|
|
79
|
+
info = await lstat(join(this.directory, this.filename(id)));
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (isMissing(error))
|
|
83
|
+
return false;
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
if (!info.isFile())
|
|
87
|
+
throw new StoredRecordInvalid("The saved task is not a regular file.");
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
filename(id) {
|
|
91
|
+
return `${taskIdSchema.parse(id)}.json`;
|
|
92
|
+
}
|
|
93
|
+
async prepare() {
|
|
94
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
95
|
+
if (!(await lstat(this.directory)).isDirectory())
|
|
96
|
+
throw new Error("Invalid local task directory.");
|
|
97
|
+
}
|
|
98
|
+
mutate(operation) {
|
|
99
|
+
const next = this.#mutation.then(operation);
|
|
100
|
+
this.#mutation = next.catch(() => { });
|
|
101
|
+
return next;
|
|
102
|
+
}
|
|
103
|
+
}
|
package/quickstart.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Quickstart
|
|
2
|
+
|
|
3
|
+
This guide runs the bundled demo and walks you through a passing run, a failing run, a comparison, and a verified recovery. It takes about five minutes and needs no model, API key or network access beyond installing the package and Chromium.
|
|
4
|
+
|
|
5
|
+
## 1. Install and check
|
|
6
|
+
|
|
7
|
+
Follow [Installation](installation.md) for details. The short version:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --global --ignore-scripts ./agentpath-0.1.0-alpha.2.tgz
|
|
11
|
+
agentpath browser install
|
|
12
|
+
agentpath doctor
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`doctor` launches sandboxed Chromium against a synthetic page, checks that the workspace is writable, and checks that Studio can start. Up to two warnings about optional model services are normal: the demo does not use a model.
|
|
16
|
+
|
|
17
|
+
## 2. Start the demo
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
agentpath demo
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The demo starts a synthetic shop and Studio on loopback addresses, and creates a temporary workspace. It then records four real deterministic runs:
|
|
24
|
+
|
|
25
|
+
| Run | What it shows |
|
|
26
|
+
|---|---|
|
|
27
|
+
| Passing cart | Adds two mugs to the cart. Every action completes and every independent assertion passes. |
|
|
28
|
+
| Missing-label evidence | The same scenario on a page whose quantity select has no accessible name. The run stops at step 4. |
|
|
29
|
+
| Workshop before | Reserves a seat while the synthetic reservation service is broken. The independent assertion fails. |
|
|
30
|
+
| Workshop after | The identical task after the demo repairs the service. It passes. |
|
|
31
|
+
|
|
32
|
+
Open the Studio URL it prints. Press Ctrl+C when you are finished. The workspace path is printed at startup, so you can reopen it later with `agentpath studio --workspace "<demo workspace>"`.
|
|
33
|
+
|
|
34
|
+
## 3. Follow the guided demo
|
|
35
|
+
|
|
36
|
+
The Overview shows a **Guided demo** with four steps. Each button opens a real recording from this workspace.
|
|
37
|
+
|
|
38
|
+

|
|
39
|
+
|
|
40
|
+
### Step 1: see a verified pass
|
|
41
|
+
|
|
42
|
+
Choose **Open run**. The result reads *All recorded actions and independent assertions passed*. Below it, separate verdicts report:
|
|
43
|
+
|
|
44
|
+
- the goal, decided by the independent assertions
|
|
45
|
+
- the action policy (none was configured, so it reads *Not evaluated*)
|
|
46
|
+
- the evidence integrity
|
|
47
|
+
|
|
48
|
+
### Step 2: find the broken control
|
|
49
|
+
|
|
50
|
+
Choose **Diagnose**. The failure diagnosis names the failed location and what was planned:
|
|
51
|
+
|
|
52
|
+
> Step 4 failed: select · combobox "Quantity"
|
|
53
|
+
|
|
54
|
+
It also puts **Expected** next to **Observed**. The step expected one combobox named "Quantity". It observed only a combobox with an empty accessible name.
|
|
55
|
+
|
|
56
|
+

|
|
57
|
+
|
|
58
|
+
Choose **Jump to failed step**. The evidence for step 4 is beside the timeline:
|
|
59
|
+
|
|
60
|
+
- **Screenshot.** The page after the step. Form controls are masked in magenta when they are captured, so the quantity control appears as a magenta box.
|
|
61
|
+
- **Accessible page.** The recorded accessibility tree, filtered to the target's role. The one combobox on the page has *(empty accessible name)*, which is why a name-based target could not find it.
|
|
62
|
+
|
|
63
|
+
The **Root cause** line says *Unconfirmed by the recorded evidence*. The browser shows the symptom, an unnamed control. It cannot show which source change removed the label.
|
|
64
|
+
|
|
65
|
+
### Step 3: compare the failure with the pass
|
|
66
|
+
|
|
67
|
+
Choose **Compare**. Studio opens the comparison with both runs selected. The first meaningful divergence is **Step 4 · failed → passed**.
|
|
68
|
+
|
|
69
|
+
The two cart tasks have different definitions: one targets the broken page and one targets the fixed page. So the interpretation is **Observed improvement**, which is useful direction but not proof that the same task now works.
|
|
70
|
+
|
|
71
|
+

|
|
72
|
+
|
|
73
|
+
### Step 4: verify a recovery
|
|
74
|
+
|
|
75
|
+
Choose **Verify**. This comparison uses the identical workshop task, run before and after the service was repaired. The task contract is *identical*, the baseline failed, and the candidate passed every action and independent assertion. So the interpretation is **Verified task recovery**.
|
|
76
|
+
|
|
77
|
+

|
|
78
|
+
|
|
79
|
+
Choose **Inspect evidence** to see the recorded values on both sides. Each observation links to the file and JSON pointer it came from. Verified recovery means the task contract recovered. It does not claim which code change caused it.
|
|
80
|
+
|
|
81
|
+
## 4. Next steps
|
|
82
|
+
|
|
83
|
+
- Read [Concepts](concepts.md) for the vocabulary used above.
|
|
84
|
+
- Write a task for your own test site with [Writing tasks](writing-tasks.md).
|
|
85
|
+
- Learn every part of Run Explorer and Compare in [Understanding results](understanding-results.md).
|