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,203 @@
|
|
|
1
|
+
import { FAILED_REQUEST_LIMIT, FAILED_REQUEST_PATH_LIMIT, PAGE_MESSAGE_LIMIT, PAGE_TEXT_LIMIT } from "#agentpath/contracts";
|
|
2
|
+
import { Deadline } from "./timing.js";
|
|
3
|
+
/**
|
|
4
|
+
* Failure evidence. Everything here observes the page after a failure; nothing acts on it,
|
|
5
|
+
* and nothing here changes a verdict.
|
|
6
|
+
*/
|
|
7
|
+
/** Removes control characters, collapses whitespace and bounds page-provided text. */
|
|
8
|
+
export function boundedText(value, limit = PAGE_TEXT_LIMIT) {
|
|
9
|
+
const text = value.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
|
|
10
|
+
return text.length > limit ? { text: text.slice(0, limit - 1) + "…", truncated: true } : { text, truncated: false };
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Visible alert and status messages. Their text is recorded only when the operator enabled text capture,
|
|
14
|
+
* and then with every task-supplied input value replaced.
|
|
15
|
+
*/
|
|
16
|
+
export async function pageMessages(page, deadline, captureText, privacy) {
|
|
17
|
+
const messages = [];
|
|
18
|
+
for (const role of ["alert", "status"]) {
|
|
19
|
+
let count = 0;
|
|
20
|
+
try {
|
|
21
|
+
count = await deadline.observe(() => page.getByRole(role).count());
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
for (let index = 0; index < count && messages.length < PAGE_MESSAGE_LIMIT; index++) {
|
|
27
|
+
try {
|
|
28
|
+
const element = page.getByRole(role).nth(index);
|
|
29
|
+
if (!await deadline.observe(() => element.isVisible()))
|
|
30
|
+
continue;
|
|
31
|
+
const raw = await deadline.observe(() => element.innerText({ timeout: Math.min(200, deadline.remaining()) }));
|
|
32
|
+
// Empty live regions are placeholders that most pages keep; they say nothing about the failure.
|
|
33
|
+
if (!boundedText(raw).text)
|
|
34
|
+
continue;
|
|
35
|
+
if (!captureText) {
|
|
36
|
+
messages.push({ role, textState: "not-captured" });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const safe = privacy.redactText(raw);
|
|
40
|
+
if (safe === undefined) {
|
|
41
|
+
messages.push({ role, textState: "withheld" });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
messages.push({ role, text: boundedText(safe).text });
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// A message that disappears while it is read is simply not recorded.
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return messages.length ? messages : undefined;
|
|
52
|
+
}
|
|
53
|
+
/** The visible text of a failed text assertion's single matched element, under the same capture rules. */
|
|
54
|
+
export async function observedText(page, locator, deadline, privacy) {
|
|
55
|
+
try {
|
|
56
|
+
if (await deadline.observe(() => locator.count()) !== 1)
|
|
57
|
+
return {};
|
|
58
|
+
const raw = await deadline.observe(() => locator.innerText({ timeout: Math.min(200, deadline.remaining()) }));
|
|
59
|
+
const safe = privacy.redactText(raw);
|
|
60
|
+
if (safe === undefined)
|
|
61
|
+
return {};
|
|
62
|
+
const { text, truncated } = boundedText(safe);
|
|
63
|
+
// An empty element is a finding too: the expected text never arrived.
|
|
64
|
+
return { observedText: text, ...(truncated ? { observedTextTruncated: true } : {}) };
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return {};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Whether a <label> whose own text equals the requested label exists while labelling no control. A fixed,
|
|
72
|
+
* read-only page inspection; no page-provided code runs.
|
|
73
|
+
*/
|
|
74
|
+
export async function detachedLabel(page, label, deadline) {
|
|
75
|
+
try {
|
|
76
|
+
return await deadline.observe(() => page.evaluate((wanted) => {
|
|
77
|
+
const normalize = (value) => value.replace(/\s+/g, " ").trim();
|
|
78
|
+
const own = (element) => normalize(Array.from(element.childNodes)
|
|
79
|
+
.filter((node) => node.nodeType === Node.TEXT_NODE).map((node) => node.textContent ?? "").join(" "));
|
|
80
|
+
const labels = Array.from(document.querySelectorAll("label")).filter((element) => own(element) === wanted);
|
|
81
|
+
return labels.length > 0 && labels.every((element) => element.control === null);
|
|
82
|
+
}, label));
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Repeats a failed check without acting, for a bounded window, to separate a timeout that was too short
|
|
90
|
+
* from a condition that never held.
|
|
91
|
+
*/
|
|
92
|
+
export async function lateCheck(check, startedAt, windowMs, signal) {
|
|
93
|
+
const deadline = new Deadline(windowMs, signal);
|
|
94
|
+
try {
|
|
95
|
+
do {
|
|
96
|
+
if (await check(deadline)) {
|
|
97
|
+
return { outcome: "passed-later", afterMs: Math.round(performance.now() - startedAt), windowMs };
|
|
98
|
+
}
|
|
99
|
+
} while (await deadline.pause());
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// The window elapsed or the page went away; either way the check did not pass.
|
|
103
|
+
}
|
|
104
|
+
return { outcome: "still-failing", windowMs };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The late-check window: the operation timeout, at least 2 s and at most 5 s, so a failing run costs at
|
|
108
|
+
* most 5 s more. Never past the run deadline.
|
|
109
|
+
*/
|
|
110
|
+
export function lateWindow(timeoutMs, remainingMs) {
|
|
111
|
+
return Math.max(0, Math.min(Math.max(timeoutMs, 2_000), 5_000, remainingMs - 1_000));
|
|
112
|
+
}
|
|
113
|
+
/** Counts allowed-host requests that returned HTTP 400 or above or failed at the network level. */
|
|
114
|
+
export class RequestFailures {
|
|
115
|
+
allowedHosts;
|
|
116
|
+
privacy;
|
|
117
|
+
ignore;
|
|
118
|
+
#entries = new Map();
|
|
119
|
+
#truncated = false;
|
|
120
|
+
constructor(allowedHosts, privacy, ignore = () => false) {
|
|
121
|
+
this.allowedHosts = allowedHosts;
|
|
122
|
+
this.privacy = privacy;
|
|
123
|
+
this.ignore = ignore;
|
|
124
|
+
}
|
|
125
|
+
watch(page) {
|
|
126
|
+
page.on("response", (response) => {
|
|
127
|
+
if (response.status() >= 400)
|
|
128
|
+
this.#add(response.request(), { status: response.status() });
|
|
129
|
+
});
|
|
130
|
+
page.on("requestfailed", (request) => {
|
|
131
|
+
// Navigations and teardown abort in-flight requests; those are not failures of the site. Neither are
|
|
132
|
+
// AgentPath's own blocks (BlockedByClient), such as the redirect guard failing an allowed-host request
|
|
133
|
+
// that redirects outside allowedHosts; those are recorded as blocked hosts and navigation failures.
|
|
134
|
+
const reason = request.failure()?.errorText ?? "";
|
|
135
|
+
if (reason.includes("ERR_ABORTED") || reason.includes("ERR_BLOCKED_BY_CLIENT") || this.ignore(request))
|
|
136
|
+
return;
|
|
137
|
+
this.#add(request, { failure: "network" });
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
#add(request, outcome) {
|
|
141
|
+
let url;
|
|
142
|
+
try {
|
|
143
|
+
url = new URL(request.url());
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
// Hosts outside the allowlist are reported as blocked hosts, never as failures of the site.
|
|
149
|
+
if (!["http:", "https:"].includes(url.protocol) || !this.allowedHosts.includes(url.host))
|
|
150
|
+
return;
|
|
151
|
+
const host = this.privacy.host(url.host);
|
|
152
|
+
const path = boundedText(this.privacy.path(url.pathname), FAILED_REQUEST_PATH_LIMIT).text || "/";
|
|
153
|
+
const key = `${request.method()} ${host}${path} ${"status" in outcome ? outcome.status : "network"}`;
|
|
154
|
+
const existing = this.#entries.get(key);
|
|
155
|
+
if (existing) {
|
|
156
|
+
existing.count++;
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (this.#entries.size >= FAILED_REQUEST_LIMIT) {
|
|
160
|
+
this.#truncated = true;
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
this.#entries.set(key, { host, path, method: request.method().slice(0, 16), resourceType: request.resourceType().slice(0, 32), ...outcome, count: 1 });
|
|
164
|
+
}
|
|
165
|
+
record() {
|
|
166
|
+
return {
|
|
167
|
+
...(this.#entries.size ? { failedRequests: [...this.#entries.values()] } : {}),
|
|
168
|
+
...(this.#truncated ? { failedRequestsTruncated: true } : {}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Elements with the requested role whose visible text equals the requested name while their accessible name
|
|
174
|
+
* differs, such as a button showing "Add to cart" that is named "Add Trail Mug to cart" by aria-label.
|
|
175
|
+
* Bounded to the first 50 candidates; observation only.
|
|
176
|
+
*/
|
|
177
|
+
export async function visibleTextMatches(page, role, name, deadline) {
|
|
178
|
+
const found = [];
|
|
179
|
+
const wanted = name.replace(/\s+/g, " ").trim();
|
|
180
|
+
try {
|
|
181
|
+
const candidates = page.getByRole(role);
|
|
182
|
+
const count = Math.min(await deadline.observe(() => candidates.count()), 50);
|
|
183
|
+
for (let index = 0; index < count && found.length < 5; index++) {
|
|
184
|
+
const candidate = candidates.nth(index);
|
|
185
|
+
if (!await deadline.observe(() => candidate.isVisible()))
|
|
186
|
+
continue;
|
|
187
|
+
const text = boundedText(await deadline.observe(() => candidate.innerText({ timeout: Math.min(200, deadline.remaining()) })), 160).text;
|
|
188
|
+
if (text !== wanted)
|
|
189
|
+
continue;
|
|
190
|
+
const snapshot = await deadline.observe(() => candidate.ariaSnapshot({ timeout: Math.min(300, deadline.remaining()) }));
|
|
191
|
+
const accessible = /^- [a-z]+ "((?:[^"\\]|\\.)*)"/.exec(snapshot.split("\n")[0] ?? "");
|
|
192
|
+
if (!accessible)
|
|
193
|
+
continue;
|
|
194
|
+
const accessibleName = boundedText(JSON.parse(`"${accessible[1]}"`), 160).text;
|
|
195
|
+
if (accessibleName && accessibleName !== wanted && !found.some((entry) => entry.name === accessibleName))
|
|
196
|
+
found.push({ role, name: accessibleName });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
// Optional context.
|
|
201
|
+
}
|
|
202
|
+
return found;
|
|
203
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export { runTask, UnsupportedExecutionModeError } from "./runner.js";
|
|
2
|
+
export { readRunResult } from "./storage.js";
|
|
3
|
+
export { RunRepository } from "./run-repository.js";
|
|
4
|
+
export { readLocalFile, isInvalidRecord, isMissing, LocalFileUnavailable, parseRecord, StoredRecordInvalid } from "./local-files.js";
|
|
5
|
+
export { writeLocalJson } from "./storage.js";
|
|
6
|
+
export { compareRuns, ComparisonUnavailable } from "./compare.js";
|
|
7
|
+
export { chromiumAvailability } from "./runner.js";
|
|
8
|
+
export { firefoxEgressPrefs, proxyBypassRules } from "./browser.js";
|
|
9
|
+
export { DEFAULT_PAGE_SIZE, InvalidCursor, MAX_PAGE_SIZE } from "./run-repository.js";
|
|
10
|
+
export { RunIndex } from "./run-index.js";
|
|
11
|
+
export { evaluateLiveness, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TTL_MS, hostDigest, probeProcess, RunHeartbeat } from "./liveness.js";
|
|
12
|
+
export { sealRun, verifyRunIntegrity } from "./integrity.js";
|
|
13
|
+
export { executePrune, parseAge, planPrune, TRASH_DIRECTORY } from "./retention.js";
|
|
14
|
+
export { applyRound, isInfrastructureFailure, loadWatchState, saveWatchState, watchEvidence, watchTasks } from "./watch.js";
|
|
15
|
+
export { createModelProvider, ProviderError } from "./model-provider.js";
|
|
16
|
+
export { runAgentLoop, AgentLoopError } from "./agent-loop.js";
|
|
17
|
+
export { inspectPage, InspectionFailure } from "./inspect.js";
|
|
18
|
+
export { failureGuidance, fitChanges, guidanceFor, suggestedTimeout, taskOperation } from "#agentpath/contracts";
|
|
19
|
+
export { explainFailedTest, explainPlaywrightResults, matchesInSnapshot, parseErrorContext, parseFailedLocator, readLiveFinding, readZipEntries, traceFailedRequests } from "./playwright-results.js";
|
|
20
|
+
export { comparableTarget, failedLocatorLine, observeLiveFailure, parseLocatorChain, valueTarget, watchFailedRequests } from "./playwright-live.js";
|
|
21
|
+
export { compareParameterised, compareTest, compareTestFiles, conditionallySkipped, isParameterised, disabledState, matchBrackets, MAX_SOURCE_BYTES, plainText, readTests, runsSerially, controlTestLine, tokenize, UnreadableSource, usesSnapshotFiles } from "./test-changes.js";
|
|
22
|
+
export { classifyRerun, RERUN_COPY, rerunCopyName, rerunSide } from "./test-change-rerun.js";
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { BLOCKED_HOST_LIMIT, INSPECTION_LIMITS, INSPECTION_VERSION, inspectionRequestSchema, pageInspectionSchema } from "#agentpath/contracts";
|
|
2
|
+
import { chromium, errors } from "playwright";
|
|
3
|
+
import { reportUrl } from "./artifacts.js";
|
|
4
|
+
import { browserContextOptions, EgressSinkhole, launchGuardedBrowser, NavigationGuard } from "./browser.js";
|
|
5
|
+
import { navigationFailure } from "./diagnostics.js";
|
|
6
|
+
import { embeddedFrameCount, semanticLocator, snapshotRoleEntries } from "./locators.js";
|
|
7
|
+
import { Deadline } from "./timing.js";
|
|
8
|
+
/** Why a page could not be inspected. The message never includes raw browser errors. */
|
|
9
|
+
export class InspectionFailure extends Error {
|
|
10
|
+
observation;
|
|
11
|
+
blockedHosts;
|
|
12
|
+
blockedHostsTruncated;
|
|
13
|
+
investigation;
|
|
14
|
+
constructor(message, observation = {}, blockedHosts = [], blockedHostsTruncated = false, investigation) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.observation = observation;
|
|
17
|
+
this.blockedHosts = blockedHosts;
|
|
18
|
+
this.blockedHostsTruncated = blockedHostsTruncated;
|
|
19
|
+
this.investigation = investigation;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
23
|
+
const NAVIGATION_TIMEOUT_MS = 15_000;
|
|
24
|
+
const SETTLE_TIMEOUT_MS = 3_000;
|
|
25
|
+
const CONFIRM_TIMEOUT_MS = 10_000;
|
|
26
|
+
/** Snapshots past this size are cut, and the target list is reported as truncated. */
|
|
27
|
+
const SNAPSHOT_CHARS = 2_000_000;
|
|
28
|
+
/** Form controls and label strings read from the page before deduplication. */
|
|
29
|
+
const CONTROL_SCAN = 500;
|
|
30
|
+
const VIEWPORT = { width: 1280, height: 800 };
|
|
31
|
+
const PHONE_VIEWPORT = { width: 390, height: 844 };
|
|
32
|
+
/** Removes control and format characters, collapses whitespace and bounds untrusted page text. */
|
|
33
|
+
function pageText(value) {
|
|
34
|
+
return value.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
|
|
35
|
+
}
|
|
36
|
+
const bounded = (text) => Array.from(text).slice(0, INSPECTION_LIMITS.text).join("").slice(0, INSPECTION_LIMITS.text);
|
|
37
|
+
/** Role and name pairs and unnamed role counts from an aria snapshot, bounded for output. */
|
|
38
|
+
export function summarizeSnapshot(snapshot) {
|
|
39
|
+
const truncatedSnapshot = snapshot.length > SNAPSHOT_CHARS;
|
|
40
|
+
// Drop the last, possibly partial, line of a cut snapshot.
|
|
41
|
+
const source = truncatedSnapshot ? snapshot.slice(0, snapshot.lastIndexOf("\n", SNAPSHOT_CHARS)) : snapshot;
|
|
42
|
+
const named = new Map();
|
|
43
|
+
const unnamed = new Map();
|
|
44
|
+
let more = false;
|
|
45
|
+
for (const entry of snapshotRoleEntries(source)) {
|
|
46
|
+
if (entry.name === undefined) {
|
|
47
|
+
unnamed.set(entry.role, (unnamed.get(entry.role) ?? 0) + 1);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const key = JSON.stringify([entry.role, entry.name]);
|
|
51
|
+
if (named.has(key))
|
|
52
|
+
continue;
|
|
53
|
+
if (named.size >= INSPECTION_LIMITS.targets)
|
|
54
|
+
more = true;
|
|
55
|
+
else
|
|
56
|
+
named.set(key, { role: entry.role, name: entry.name });
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
targets: [...named.values()],
|
|
60
|
+
targetsTruncated: more || truncatedSnapshot,
|
|
61
|
+
unnamed: [...unnamed].map(([role, count]) => ({ role, count })),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Distinct label texts for form controls, bounded and sanitized in Node whatever the page returned. */
|
|
65
|
+
export function summarizeLabels(raw) {
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
let truncated = false;
|
|
68
|
+
const values = Array.isArray(raw) ? raw.slice(0, CONTROL_SCAN * 3) : [];
|
|
69
|
+
if (Array.isArray(raw) && raw.length > CONTROL_SCAN * 3)
|
|
70
|
+
truncated = true;
|
|
71
|
+
for (const value of values) {
|
|
72
|
+
if (typeof value !== "string")
|
|
73
|
+
continue;
|
|
74
|
+
const text = pageText(value.slice(0, 4_000));
|
|
75
|
+
if (!text || seen.has(text))
|
|
76
|
+
continue;
|
|
77
|
+
if (seen.size >= INSPECTION_LIMITS.labels) {
|
|
78
|
+
truncated = true;
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
seen.add(text);
|
|
82
|
+
}
|
|
83
|
+
return { labels: [...seen], truncated };
|
|
84
|
+
}
|
|
85
|
+
function matchState(matches) {
|
|
86
|
+
return matches === undefined ? "unconfirmed" : matches === 1 ? "unique" : matches > 1 ? "ambiguous" : "not-matched";
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Lists the role and name pairs, unnamed roles and form labels a deterministic task can target on one page.
|
|
90
|
+
* The browser runs behind the same per-run sinkhole and navigation guards as a run, performs no actions and
|
|
91
|
+
* writes no run records. Everything returned is page-provided data, sanitized and bounded.
|
|
92
|
+
*/
|
|
93
|
+
export async function inspectPage(input, options = {}) {
|
|
94
|
+
const request = inspectionRequestSchema.parse(input);
|
|
95
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
96
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
97
|
+
const deadline = new Deadline(timeoutMs, signal);
|
|
98
|
+
const guard = new NavigationGuard(request.allowedHosts);
|
|
99
|
+
const sinkhole = new EgressSinkhole();
|
|
100
|
+
let server;
|
|
101
|
+
let context;
|
|
102
|
+
const blocked = () => guard.blockedHosts(BLOCKED_HOST_LIMIT);
|
|
103
|
+
const fail = (message, observation = {}, investigation) => {
|
|
104
|
+
const hosts = blocked();
|
|
105
|
+
return new InspectionFailure(message, observation, hosts.hosts, hosts.truncated, investigation);
|
|
106
|
+
};
|
|
107
|
+
const refuse = (observation) => fail(navigationFailure(observation).details.observed, observation, observation.disallowedHost === undefined ? undefined
|
|
108
|
+
: "If the page redirects to this host and you trust it, allow that host too or inspect it directly.");
|
|
109
|
+
try {
|
|
110
|
+
try {
|
|
111
|
+
signal.throwIfAborted();
|
|
112
|
+
server = await launchGuardedBrowser(request.allowedHosts, sinkhole, () => Math.min(10_000, deadline.remaining()));
|
|
113
|
+
const browser = await chromium.connect({ wsEndpoint: server.wsEndpoint(), timeout: deadline.remaining() });
|
|
114
|
+
context = await deadline.observe(() => browser.newContext(options.mobile ? browserContextOptions(PHONE_VIEWPORT, true) : browserContextOptions(VIEWPORT)));
|
|
115
|
+
const activeContext = context;
|
|
116
|
+
await deadline.observe(() => guard.install(activeContext));
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (signal.aborted || error instanceof errors.TimeoutError)
|
|
120
|
+
throw error;
|
|
121
|
+
throw fail("Chromium could not be started.", {}, "Run agentpath doctor. Install the managed browser with agentpath browser install.");
|
|
122
|
+
}
|
|
123
|
+
const page = await deadline.observe(() => context.newPage());
|
|
124
|
+
await deadline.observe(() => guard.installRedirectGuard(page));
|
|
125
|
+
let status;
|
|
126
|
+
try {
|
|
127
|
+
const response = await deadline.observe(() => page.goto(request.url, {
|
|
128
|
+
waitUntil: "domcontentloaded", timeout: Math.min(NAVIGATION_TIMEOUT_MS, deadline.remaining()),
|
|
129
|
+
}));
|
|
130
|
+
status = response?.status();
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
const violation = guard.check(page);
|
|
134
|
+
if (violation)
|
|
135
|
+
throw refuse(violation);
|
|
136
|
+
if (signal.aborted)
|
|
137
|
+
throw error;
|
|
138
|
+
if (error instanceof errors.TimeoutError)
|
|
139
|
+
throw fail(`The page did not load within ${Math.min(NAVIGATION_TIMEOUT_MS, timeoutMs)} ms.`, { errorKind: "timeout" });
|
|
140
|
+
throw refuse({ errorKind: "navigation" });
|
|
141
|
+
}
|
|
142
|
+
const violation = guard.check(page);
|
|
143
|
+
if (violation)
|
|
144
|
+
throw refuse(violation);
|
|
145
|
+
if (status !== undefined && status >= 400)
|
|
146
|
+
throw refuse({ httpStatus: status });
|
|
147
|
+
// Give scripted content a bounded chance to render. A page that keeps the network busy is inspected as it is.
|
|
148
|
+
try {
|
|
149
|
+
await deadline.observe(() => page.waitForLoadState("networkidle", { timeout: Math.min(SETTLE_TIMEOUT_MS, deadline.remaining()) }));
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (signal.aborted)
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
const snapshot = await deadline.observe(() => page.locator("body").ariaSnapshot({ timeout: deadline.remaining() }));
|
|
156
|
+
const summary = summarizeSnapshot(snapshot);
|
|
157
|
+
const rawLabels = await deadline.observe(() => page.locator("input:not([type=hidden]), select, textarea").evaluateAll((elements, limit) => {
|
|
158
|
+
// Runs in the page. Its result is untrusted and is validated again in Node.
|
|
159
|
+
const texts = [];
|
|
160
|
+
const read = (value) => { if (value)
|
|
161
|
+
texts.push(value.slice(0, 4_000)); };
|
|
162
|
+
for (const element of elements.slice(0, limit)) {
|
|
163
|
+
for (const label of Array.from(element.labels ?? []))
|
|
164
|
+
read(label.textContent);
|
|
165
|
+
const ids = element.getAttribute("aria-labelledby")?.split(/\s+/).filter(Boolean) ?? [];
|
|
166
|
+
if (ids.length)
|
|
167
|
+
read(ids.map((id) => document.getElementById(id)?.textContent ?? "").join(" "));
|
|
168
|
+
read(element.getAttribute("aria-label"));
|
|
169
|
+
}
|
|
170
|
+
return texts;
|
|
171
|
+
}, CONTROL_SCAN));
|
|
172
|
+
const labelSummary = summarizeLabels(rawLabels);
|
|
173
|
+
// Confirm every entry with the exact locator a run would use. Out of time, the rest stay unconfirmed.
|
|
174
|
+
const confirm = new Deadline(Math.min(CONFIRM_TIMEOUT_MS, deadline.remaining()), signal);
|
|
175
|
+
let confirming = true;
|
|
176
|
+
const count = async (locator) => {
|
|
177
|
+
if (!confirming)
|
|
178
|
+
return undefined;
|
|
179
|
+
try {
|
|
180
|
+
return await confirm.observe(() => locator().count());
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
if (signal.aborted)
|
|
184
|
+
throw error;
|
|
185
|
+
confirming = false;
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const targets = [];
|
|
190
|
+
for (const { role, name } of summary.targets) {
|
|
191
|
+
const matches = await count(() => semanticLocator(page, { by: "role", role, name }));
|
|
192
|
+
const truncated = name.length > INSPECTION_LIMITS.text;
|
|
193
|
+
targets.push({
|
|
194
|
+
role, name: truncated ? bounded(name) : name, ...(truncated ? { nameTruncated: true } : {}),
|
|
195
|
+
match: matchState(matches), ...(matches === undefined ? {} : { matches }),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const unnamed = [];
|
|
199
|
+
for (const { role, count: unnamedCount } of summary.unnamed) {
|
|
200
|
+
const roleMatches = await count(() => page.getByRole(role));
|
|
201
|
+
unnamed.push({ role, count: unnamedCount, ...(roleMatches === undefined ? {} : { roleMatches }) });
|
|
202
|
+
}
|
|
203
|
+
const labels = [];
|
|
204
|
+
for (const label of labelSummary.labels) {
|
|
205
|
+
const matches = await count(() => semanticLocator(page, { by: "label", label }));
|
|
206
|
+
const truncated = label.length > INSPECTION_LIMITS.text;
|
|
207
|
+
labels.push({
|
|
208
|
+
label: truncated ? bounded(label) : label, ...(truncated ? { labelTruncated: true } : {}),
|
|
209
|
+
match: matchState(matches), ...(matches === undefined ? {} : { matches }),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
// A page that left the allowlist while it was read is refused rather than reported.
|
|
213
|
+
const late = guard.check(page);
|
|
214
|
+
if (late)
|
|
215
|
+
throw refuse(late);
|
|
216
|
+
const hosts = blocked();
|
|
217
|
+
return pageInspectionSchema.parse({
|
|
218
|
+
schemaVersion: INSPECTION_VERSION, url: reportUrl(page.url()),
|
|
219
|
+
targets, targetsTruncated: summary.targetsTruncated,
|
|
220
|
+
unnamed, labels, labelsTruncated: labelSummary.truncated,
|
|
221
|
+
embeddedFrames: embeddedFrameCount(page),
|
|
222
|
+
blockedHosts: hosts.hosts, blockedHostsTruncated: hosts.truncated,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (error instanceof InspectionFailure || signal.aborted)
|
|
227
|
+
throw error;
|
|
228
|
+
if (error instanceof errors.TimeoutError)
|
|
229
|
+
throw fail(`The inspection did not finish within ${timeoutMs} ms.`, { errorKind: "timeout" });
|
|
230
|
+
throw fail("The page could not be inspected. The browser or page closed or failed unexpectedly.", { errorKind: "unclassified" });
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
const cleanup = new Deadline(5_000, new AbortController().signal);
|
|
234
|
+
try {
|
|
235
|
+
if (context)
|
|
236
|
+
await cleanup.observe(() => context.close());
|
|
237
|
+
}
|
|
238
|
+
catch { /* The context may already be gone. */ }
|
|
239
|
+
try {
|
|
240
|
+
if (server)
|
|
241
|
+
await cleanup.observe(() => server.close());
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
const owned = server;
|
|
245
|
+
// This child belongs exclusively to this inspection.
|
|
246
|
+
if (owned) {
|
|
247
|
+
try {
|
|
248
|
+
await new Deadline(2_000, new AbortController().signal).observe(() => owned.kill());
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
owned.process().kill("SIGKILL");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
await sinkhole.close();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { lstat, open, readdir } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { integrityRecordSchema, runEventSchema, runIdSchema, SCHEMA_VERSION } from "#agentpath/contracts";
|
|
6
|
+
import { isMissing, parseRecord, readLocalFile } from "./local-files.js";
|
|
7
|
+
import { LIVENESS_FILE } from "./liveness.js";
|
|
8
|
+
export const INTEGRITY_FILE = "integrity.json";
|
|
9
|
+
const EVENTS_FILE = "events.jsonl";
|
|
10
|
+
/** Files that are mutable by design or covered specially, so they are not individually digested. */
|
|
11
|
+
const UNSEALED = new Set([INTEGRITY_FILE, LIVENESS_FILE, EVENTS_FILE]);
|
|
12
|
+
// Digests stream in 1 MiB chunks, so these bound time, not memory. They are far above any capped artifact:
|
|
13
|
+
// a seal that throws leaves a run without its terminal event, so the limits must never be reached in practice.
|
|
14
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024 * 1024;
|
|
15
|
+
const MAX_EVENTS_BYTES = 256 * 1024 * 1024;
|
|
16
|
+
const MAX_FILES = 2000;
|
|
17
|
+
export function sha256(bytes) {
|
|
18
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
19
|
+
}
|
|
20
|
+
/** Lists the run directory without following symbolic links. */
|
|
21
|
+
async function walk(directory, prefix = "", depth = 0) {
|
|
22
|
+
const entries = [];
|
|
23
|
+
for (const item of await readdir(join(directory, prefix), { withFileTypes: true })) {
|
|
24
|
+
const path = prefix ? `${prefix}/${item.name}` : item.name;
|
|
25
|
+
if (item.isDirectory() && depth < 4) {
|
|
26
|
+
entries.push({ path, kind: "directory" }, ...await walk(directory, path, depth + 1));
|
|
27
|
+
}
|
|
28
|
+
else
|
|
29
|
+
entries.push({ path, kind: item.isFile() ? "file" : "other" });
|
|
30
|
+
if (entries.length > MAX_FILES)
|
|
31
|
+
throw new Error("The run directory has too many entries to seal.");
|
|
32
|
+
}
|
|
33
|
+
return entries;
|
|
34
|
+
}
|
|
35
|
+
async function digestFile(path, limit = MAX_FILE_BYTES) {
|
|
36
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
37
|
+
try {
|
|
38
|
+
const info = await file.stat();
|
|
39
|
+
if (!info.isFile() || info.size > limit)
|
|
40
|
+
throw new Error("The file cannot be sealed.");
|
|
41
|
+
const hash = createHash("sha256");
|
|
42
|
+
const buffer = Buffer.alloc(1024 * 1024);
|
|
43
|
+
let bytes = 0;
|
|
44
|
+
for (;;) {
|
|
45
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, bytes);
|
|
46
|
+
if (!bytesRead)
|
|
47
|
+
break;
|
|
48
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
49
|
+
bytes += bytesRead;
|
|
50
|
+
}
|
|
51
|
+
return { bytes, sha256: hash.digest("hex") };
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
await file.close();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Records digests for every finalized file. Call before the terminal event is appended. */
|
|
58
|
+
export async function sealRun(directory, runId) {
|
|
59
|
+
const files = [];
|
|
60
|
+
for (const entry of await walk(directory)) {
|
|
61
|
+
if (entry.kind !== "file" || UNSEALED.has(entry.path) || entry.path.endsWith(".tmp"))
|
|
62
|
+
continue;
|
|
63
|
+
files.push({ path: entry.path, ...await digestFile(join(directory, entry.path)) });
|
|
64
|
+
}
|
|
65
|
+
return integrityRecordSchema.parse({
|
|
66
|
+
schemaVersion: SCHEMA_VERSION, runId, algorithm: "sha256", state: "sealed", sealedAt: new Date().toISOString(),
|
|
67
|
+
files: files.sort((a, b) => a.path.localeCompare(b.path)),
|
|
68
|
+
events: await digestFile(join(directory, EVENTS_FILE), MAX_EVENTS_BYTES),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
export function pendingIntegrity(runId) {
|
|
72
|
+
return { schemaVersion: SCHEMA_VERSION, runId, algorithm: "sha256", state: "pending" };
|
|
73
|
+
}
|
|
74
|
+
/** Reads the sidecar. Returns undefined when absent and throws StoredRecordInvalid when malformed. */
|
|
75
|
+
export async function readIntegrity(root, id) {
|
|
76
|
+
try {
|
|
77
|
+
const bytes = await readLocalFile(root, `${runIdSchema.parse(id)}/${INTEGRITY_FILE}`, 1024 * 1024);
|
|
78
|
+
const record = parseRecord(() => integrityRecordSchema.parse(JSON.parse(bytes.toString())));
|
|
79
|
+
return record.runId === id ? record : undefined;
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (isMissing(error))
|
|
83
|
+
return undefined;
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function exists(path) {
|
|
88
|
+
try {
|
|
89
|
+
await lstat(path);
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (isMissing(error))
|
|
94
|
+
return false;
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Compares a run directory with its sealed digests. A consistent result means the files match the recorded
|
|
100
|
+
* manifest. It does not establish who wrote either.
|
|
101
|
+
*/
|
|
102
|
+
export async function verifyRunIntegrity(root, id) {
|
|
103
|
+
const directory = join(root, runIdSchema.parse(id));
|
|
104
|
+
const report = (status, issues = [], checkedFiles = 0, sealedAt) => ({ runId: id, status, algorithm: "sha256", checkedFiles, issues, ...(sealedAt ? { sealedAt } : {}) });
|
|
105
|
+
let record;
|
|
106
|
+
try {
|
|
107
|
+
record = await readIntegrity(root, id);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return report("sidecar-invalid", [{ path: INTEGRITY_FILE, problem: "unreadable" }]);
|
|
111
|
+
}
|
|
112
|
+
if (!record) {
|
|
113
|
+
// Writers that record liveness create a liveness lease and a pending sidecar together, so a lease without a sidecar
|
|
114
|
+
// means the sidecar was removed. Older recordings have neither.
|
|
115
|
+
return await exists(join(directory, LIVENESS_FILE))
|
|
116
|
+
? report("sidecar-missing", [{ path: INTEGRITY_FILE, problem: "missing" }])
|
|
117
|
+
: report("legacy");
|
|
118
|
+
}
|
|
119
|
+
if (record.state === "pending")
|
|
120
|
+
return report("unsealed");
|
|
121
|
+
const issues = [];
|
|
122
|
+
const sealed = new Map(record.files.map((file) => [file.path, file]));
|
|
123
|
+
for (const file of record.files) {
|
|
124
|
+
try {
|
|
125
|
+
const actual = await digestFile(join(directory, file.path));
|
|
126
|
+
if (actual.sha256 !== file.sha256) {
|
|
127
|
+
issues.push({ path: file.path, problem: actual.bytes < file.bytes ? "truncated" : "modified" });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
issues.push({ path: file.path, problem: isMissing(error) ? "missing" : "unreadable" });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const events = await eventsProblem(directory, record);
|
|
135
|
+
if (events)
|
|
136
|
+
issues.push({ path: EVENTS_FILE, problem: events });
|
|
137
|
+
for (const entry of await walk(directory)) {
|
|
138
|
+
if (entry.kind === "directory" || (entry.kind === "file" && (sealed.has(entry.path) || UNSEALED.has(entry.path))))
|
|
139
|
+
continue;
|
|
140
|
+
issues.push({ path: entry.path, problem: "unexpected" });
|
|
141
|
+
}
|
|
142
|
+
return report(issues.length ? "mismatch" : "consistent", issues, record.files.length + 1, record.sealedAt);
|
|
143
|
+
}
|
|
144
|
+
/** The sealed prefix must be unchanged and followed by exactly one terminal event line. */
|
|
145
|
+
async function eventsProblem(directory, record) {
|
|
146
|
+
let bytes;
|
|
147
|
+
try {
|
|
148
|
+
bytes = await readLocalFile(directory, EVENTS_FILE, 16 * 1024 * 1024);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
return isMissing(error) ? "missing" : "unreadable";
|
|
152
|
+
}
|
|
153
|
+
if (bytes.length < record.events.bytes)
|
|
154
|
+
return "truncated";
|
|
155
|
+
if (sha256(bytes.subarray(0, record.events.bytes)) !== record.events.sha256)
|
|
156
|
+
return "modified";
|
|
157
|
+
const rest = bytes.subarray(record.events.bytes).toString();
|
|
158
|
+
const lines = rest.split("\n");
|
|
159
|
+
if (lines.length !== 2 || lines[1] !== "")
|
|
160
|
+
return "modified";
|
|
161
|
+
try {
|
|
162
|
+
const event = runEventSchema.parse(JSON.parse(lines[0] ?? ""));
|
|
163
|
+
if (event.type !== "run.finished" || event.runId !== record.runId)
|
|
164
|
+
return "modified";
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return "modified";
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** Checks one artifact's bytes against the sealed digest, for validation on read. */
|
|
171
|
+
export function artifactMatchesSeal(record, path, bytes) {
|
|
172
|
+
if (!record || record.state !== "sealed")
|
|
173
|
+
return true;
|
|
174
|
+
const sealed = record.files.find((file) => file.path === path);
|
|
175
|
+
return sealed !== undefined && sealed.bytes === bytes.length && sealed.sha256 === sha256(bytes);
|
|
176
|
+
}
|