@open-qa/qa-stage 0.0.0-stage → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE +204 -0
  2. package/NOTICE +7 -0
  3. package/THIRD_PARTY.md +13 -0
  4. package/THIRD_PARTY_NOTICES.md +11 -0
  5. package/package.json +68 -4
  6. package/scripts/bundle.d.ts +7 -0
  7. package/scripts/bundle.js +78 -0
  8. package/src/auth.d.ts +10 -0
  9. package/src/auth.js +26 -0
  10. package/src/blackboard-tools.d.ts +2 -0
  11. package/src/blackboard-tools.js +46 -0
  12. package/src/config.d.ts +61 -0
  13. package/src/config.js +64 -0
  14. package/src/discord-api.d.ts +47 -0
  15. package/src/discord-api.js +151 -0
  16. package/src/discord-surface.d.ts +4 -0
  17. package/src/discord-surface.js +218 -0
  18. package/src/drivers.d.ts +21 -0
  19. package/src/drivers.js +12 -0
  20. package/src/email-message.d.ts +22 -0
  21. package/src/email-message.js +114 -0
  22. package/src/email-surface.d.ts +4 -0
  23. package/src/email-surface.js +140 -0
  24. package/src/event-log.d.ts +18 -0
  25. package/src/event-log.js +46 -0
  26. package/src/expect-engine.d.ts +15 -0
  27. package/src/expect-engine.js +114 -0
  28. package/src/expect-evidence.d.ts +7 -0
  29. package/src/expect-evidence.js +68 -0
  30. package/src/flow-tools.d.ts +2 -0
  31. package/src/flow-tools.js +26 -0
  32. package/src/http-expect.d.ts +4 -0
  33. package/src/http-expect.js +68 -0
  34. package/src/index.d.ts +13 -0
  35. package/src/index.js +37 -0
  36. package/src/main.d.ts +1 -0
  37. package/src/main.js +51 -0
  38. package/src/mcp.d.ts +14 -0
  39. package/src/mcp.js +23 -0
  40. package/src/observation-tools.d.ts +3 -0
  41. package/src/observation-tools.js +39 -0
  42. package/src/page-diagnostics.d.ts +19 -0
  43. package/src/page-diagnostics.js +53 -0
  44. package/src/page-pixels.d.ts +35 -0
  45. package/src/page-pixels.js +73 -0
  46. package/src/page-policy.d.ts +48 -0
  47. package/src/page-policy.js +125 -0
  48. package/src/page-recording.d.ts +39 -0
  49. package/src/page-recording.js +532 -0
  50. package/src/page-replay.d.ts +7 -0
  51. package/src/page-replay.js +69 -0
  52. package/src/page-views.d.ts +85 -0
  53. package/src/page-views.js +338 -0
  54. package/src/rendered.d.ts +6 -0
  55. package/src/rendered.js +135 -0
  56. package/src/replay-artifacts.d.ts +2 -0
  57. package/src/replay-artifacts.js +100 -0
  58. package/src/replay-assets.d.ts +21 -0
  59. package/src/replay-assets.js +106 -0
  60. package/src/replay-budget.d.ts +22 -0
  61. package/src/replay-budget.js +47 -0
  62. package/src/replay-files.d.ts +3 -0
  63. package/src/replay-files.js +18 -0
  64. package/src/replay-privacy.d.ts +10 -0
  65. package/src/replay-privacy.js +48 -0
  66. package/src/replay-script.d.ts +2 -0
  67. package/src/replay-script.js +65 -0
  68. package/src/replay-warnings.d.ts +6 -0
  69. package/src/replay-warnings.js +16 -0
  70. package/src/replay-writer.d.ts +24 -0
  71. package/src/replay-writer.js +92 -0
  72. package/src/screen-tools.d.ts +5 -0
  73. package/src/screen-tools.js +168 -0
  74. package/src/server.d.ts +50 -0
  75. package/src/server.js +537 -0
  76. package/src/signed-artifacts.d.ts +21 -0
  77. package/src/signed-artifacts.js +127 -0
  78. package/src/sqlite-parser.d.ts +3 -0
  79. package/src/stage-clock.d.ts +2 -0
  80. package/src/stage-clock.js +7 -0
  81. package/src/surface-adapter.d.ts +65 -0
  82. package/src/surface-adapter.js +0 -0
  83. package/src/system-common.d.ts +34 -0
  84. package/src/system-common.js +123 -0
  85. package/src/system-db.d.ts +9 -0
  86. package/src/system-db.js +143 -0
  87. package/src/system-github.d.ts +6 -0
  88. package/src/system-github.js +73 -0
  89. package/src/system-http.d.ts +4 -0
  90. package/src/system-http.js +86 -0
  91. package/src/system-logs.d.ts +6 -0
  92. package/src/system-logs.js +78 -0
  93. package/src/telegram-api.d.ts +162 -0
  94. package/src/telegram-api.js +170 -0
  95. package/src/telegram-markup.d.ts +4 -0
  96. package/src/telegram-markup.js +129 -0
  97. package/src/telegram-surface.d.ts +39 -0
  98. package/src/telegram-surface.js +448 -0
  99. package/src/tool-gateway.d.ts +41 -0
  100. package/src/tool-gateway.js +696 -0
  101. package/src/tool-limits.d.ts +12 -0
  102. package/src/tool-limits.js +41 -0
  103. package/src/tool-secrets.d.ts +8 -0
  104. package/src/tool-secrets.js +38 -0
  105. package/src/vendor/gmail.d.ts +45 -0
  106. package/src/vendor/gmail.js +193 -0
  107. package/src/watch.d.ts +11 -0
  108. package/src/watch.js +30 -0
  109. package/src/web-expect.d.ts +5 -0
  110. package/src/web-expect.js +130 -0
  111. package/src/web-tools.d.ts +15 -0
  112. package/src/web-tools.js +340 -0
  113. package/README.md +0 -3
@@ -0,0 +1,12 @@
1
+ export declare const MAX_TOOL_ARGS_BYTES: number;
2
+ export declare const MAX_TOOL_NAME_CHARS = 128;
3
+ export declare const MAX_TOOL_TEXT_CHARS = 16000;
4
+ export declare const MAX_TOOL_IMAGE_CHARS: number;
5
+ export declare const MAX_FLOW_TEXT_CHARS = 2000;
6
+ export declare const MAX_BLACKBOARD_VARS = 100;
7
+ export declare const MAX_VIEW_QUEUE_DEPTH = 32;
8
+ export declare function fitsJson(value: unknown, maxBytes?: number): boolean;
9
+ export declare function boundedToolText(value: string): {
10
+ text: string;
11
+ truncated: boolean;
12
+ };
@@ -0,0 +1,41 @@
1
+ const MAX_TOOL_ARGS_BYTES = 64 * 1024;
2
+ const MAX_TOOL_NAME_CHARS = 128;
3
+ const MAX_TOOL_TEXT_CHARS = 16e3;
4
+ const MAX_TOOL_IMAGE_CHARS = 4 * 1024 * 1024;
5
+ const MAX_FLOW_TEXT_CHARS = 2e3;
6
+ const MAX_BLACKBOARD_VARS = 100;
7
+ const MAX_VIEW_QUEUE_DEPTH = 32;
8
+ function fitsJson(value, maxBytes = MAX_TOOL_ARGS_BYTES) {
9
+ try {
10
+ const serialized = JSON.stringify(value);
11
+ return serialized !== void 0 && Buffer.byteLength(serialized, "utf8") <= maxBytes;
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+ function boundedToolText(value) {
17
+ let end = Math.min(value.length, MAX_TOOL_TEXT_CHARS);
18
+ if (!fitsJson(value.slice(0, end), 48 * 1024)) {
19
+ let low = 0;
20
+ let high = end;
21
+ while (low < high) {
22
+ const middle = Math.ceil((low + high) / 2);
23
+ if (fitsJson(value.slice(0, middle), 48 * 1024)) low = middle;
24
+ else high = middle - 1;
25
+ }
26
+ end = low;
27
+ }
28
+ if (end < value.length && /[\uD800-\uDBFF]/.test(value.charAt(end - 1))) end--;
29
+ return { text: value.slice(0, end), truncated: end < value.length };
30
+ }
31
+ export {
32
+ MAX_BLACKBOARD_VARS,
33
+ MAX_FLOW_TEXT_CHARS,
34
+ MAX_TOOL_ARGS_BYTES,
35
+ MAX_TOOL_IMAGE_CHARS,
36
+ MAX_TOOL_NAME_CHARS,
37
+ MAX_TOOL_TEXT_CHARS,
38
+ MAX_VIEW_QUEUE_DEPTH,
39
+ boundedToolText,
40
+ fitsJson
41
+ };
@@ -0,0 +1,8 @@
1
+ import { type JsonObject } from "@open-qa/qa-engine/protocol";
2
+ import { SecretRedactor } from "@open-qa/qa-engine";
3
+ export declare function createToolSecrets(secrets: Readonly<Record<string, string>>, tokens: readonly string[], redactor?: SecretRedactor): {
4
+ redactor: SecretRedactor;
5
+ redactText: (text: string) => string;
6
+ redact: (value: JsonObject) => Record<string, import("zod").JSONType>;
7
+ resolve: (value: JsonObject) => Record<string, import("zod").JSONType>;
8
+ };
@@ -0,0 +1,38 @@
1
+ import { secretReferencePattern } from "@open-qa/qa-engine/protocol";
2
+ import { SecretRedactor } from "@open-qa/qa-engine";
3
+ function mapStrings(value, map, mapKeys = true) {
4
+ function visit(item) {
5
+ if (typeof item === "string") return map(item);
6
+ if (Array.isArray(item)) return item.map(visit);
7
+ if (item !== null && typeof item === "object") {
8
+ return Object.fromEntries(
9
+ Object.entries(item).map(([key, child]) => [mapKeys ? map(key) : key, visit(child)])
10
+ );
11
+ }
12
+ return item;
13
+ }
14
+ return visit(value);
15
+ }
16
+ function createToolSecrets(secrets, tokens, redactor = new SecretRedactor("***")) {
17
+ if (Object.values(secrets).some((value) => value.length < 3 || value.length > 4096))
18
+ throw new Error("Secret values must contain between 3 and 4096 characters");
19
+ redactor.add([...Object.values(secrets), ...tokens]);
20
+ const redactText = (text) => redactor.text(text.replace(secretReferencePattern, "***"));
21
+ return {
22
+ redactor,
23
+ redactText,
24
+ redact: (value) => redactor.json(
25
+ mapStrings(value, (text) => text.replace(secretReferencePattern, "***"), false)
26
+ ),
27
+ resolve: (value) => mapStrings(
28
+ value,
29
+ (text) => text.replace(secretReferencePattern, (_match, name) => {
30
+ if (!Object.hasOwn(secrets, name)) throw new Error("Unknown secret reference");
31
+ return secrets[name];
32
+ })
33
+ )
34
+ };
35
+ }
36
+ export {
37
+ createToolSecrets
38
+ };
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+ export declare const gmailCredentialsSchema: z.ZodObject<{
3
+ clientId: z.ZodString;
4
+ clientSecret: z.ZodString;
5
+ refreshToken: z.ZodString;
6
+ }, z.core.$strict>;
7
+ export type GmailCredentials = z.infer<typeof gmailCredentialsSchema>;
8
+ export interface InboxMessage {
9
+ id: string;
10
+ to: string;
11
+ from: string;
12
+ subject: string;
13
+ date: number;
14
+ text: string;
15
+ html: string;
16
+ }
17
+ declare const querySchema: z.ZodObject<{
18
+ to: z.ZodEmail;
19
+ from: z.ZodOptional<z.ZodEmail>;
20
+ afterMs: z.ZodNumber;
21
+ metadata: z.ZodOptional<z.ZodBoolean>;
22
+ }, z.core.$strict>;
23
+ declare const reasons: {
24
+ readonly authorization: "Email authorization failed";
25
+ readonly rate: "Email rate limited";
26
+ readonly unavailable: "Email unavailable";
27
+ readonly invalid: "Email response invalid";
28
+ };
29
+ export declare class EmailInboxError extends Error {
30
+ readonly reason: keyof typeof reasons;
31
+ constructor(reason: keyof typeof reasons);
32
+ }
33
+ /** Host/stage-only inbox. Provider bodies and credentials never appear in errors. */
34
+ export declare class GmailInbox {
35
+ private readonly credentials;
36
+ private readonly transport;
37
+ private token?;
38
+ private retryAt;
39
+ private readonly checked;
40
+ constructor(credentials: GmailCredentials, transport?: typeof fetch);
41
+ private request;
42
+ authorize(signal?: AbortSignal): Promise<string>;
43
+ read(input: z.infer<typeof querySchema>, signal?: AbortSignal): Promise<InboxMessage[]>;
44
+ }
45
+ export {};
@@ -0,0 +1,193 @@
1
+ import { z } from "zod";
2
+ const gmailCredentialsSchema = z.strictObject({
3
+ clientId: z.string().min(1).max(4096),
4
+ clientSecret: z.string().min(1).max(4096),
5
+ refreshToken: z.string().min(1).max(4096)
6
+ });
7
+ const querySchema = z.strictObject({
8
+ to: z.email(),
9
+ from: z.email().optional(),
10
+ afterMs: z.number().nonnegative().finite(),
11
+ metadata: z.boolean().optional()
12
+ });
13
+ const partSchema = z.object({
14
+ mimeType: z.string().optional(),
15
+ headers: z.array(z.object({ name: z.string(), value: z.string() })).default([]),
16
+ body: z.object({ data: z.string().optional() }).optional(),
17
+ get parts() {
18
+ return z.array(partSchema).optional();
19
+ }
20
+ });
21
+ function boundedMime(value) {
22
+ const pending = [{ value, depth: 0 }];
23
+ let count = 0;
24
+ while (pending.length) {
25
+ const item = pending.pop();
26
+ if (++count > 1e4 || item.depth > 30) return false;
27
+ if (item.value && typeof item.value === "object")
28
+ for (const child of Object.values(item.value))
29
+ pending.push({ value: child, depth: item.depth + 1 });
30
+ }
31
+ return true;
32
+ }
33
+ const messageSchema = z.object({ internalDate: z.string(), payload: partSchema });
34
+ const listSchema = z.object({
35
+ messages: z.array(z.object({ id: z.string().min(1).max(256) })).max(20).default([])
36
+ });
37
+ const endpoint = "https://gmail.googleapis.com/gmail/v1/users/me/messages";
38
+ const reasons = {
39
+ authorization: "Email authorization failed",
40
+ rate: "Email rate limited",
41
+ unavailable: "Email unavailable",
42
+ invalid: "Email response invalid"
43
+ };
44
+ class EmailInboxError extends Error {
45
+ constructor(reason) {
46
+ super(reasons[reason]);
47
+ this.reason = reason;
48
+ }
49
+ reason;
50
+ }
51
+ class GmailInbox {
52
+ constructor(credentials, transport = fetch) {
53
+ this.credentials = credentials;
54
+ this.transport = transport;
55
+ if (!gmailCredentialsSchema.safeParse(credentials).success)
56
+ throw new EmailInboxError("authorization");
57
+ }
58
+ credentials;
59
+ transport;
60
+ token;
61
+ retryAt = 0;
62
+ checked = /* @__PURE__ */ new Map();
63
+ async request(url, init, signal) {
64
+ try {
65
+ signal?.throwIfAborted();
66
+ if (Date.now() < this.retryAt) throw new EmailInboxError("rate");
67
+ const bounded = AbortSignal.any([...signal ? [signal] : [], AbortSignal.timeout(15e3)]);
68
+ const response = await this.transport(url, { ...init, redirect: "manual", signal: bounded });
69
+ if (!response.ok) {
70
+ await response.body?.cancel();
71
+ if (response.status === 429) {
72
+ const seconds = Number(response.headers.get("retry-after") ?? 1);
73
+ this.retryAt = Date.now() + Math.min(60, Math.max(1, seconds || 1)) * 1e3;
74
+ throw new EmailInboxError("rate");
75
+ }
76
+ throw new EmailInboxError(
77
+ [401, 403].includes(response.status) ? "authorization" : "unavailable"
78
+ );
79
+ }
80
+ const reader = response.body?.getReader();
81
+ if (!reader) throw new EmailInboxError("invalid");
82
+ const chunks = [];
83
+ let bytes = 0;
84
+ while (true) {
85
+ bounded.throwIfAborted();
86
+ const chunk = await reader.read();
87
+ if (chunk.done) break;
88
+ bytes += chunk.value.byteLength;
89
+ if (bytes > 2e6) {
90
+ await reader.cancel();
91
+ throw new EmailInboxError("invalid");
92
+ }
93
+ chunks.push(chunk.value);
94
+ }
95
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
96
+ } catch (error) {
97
+ signal?.throwIfAborted();
98
+ if (error instanceof EmailInboxError) throw error;
99
+ throw new EmailInboxError("unavailable");
100
+ }
101
+ }
102
+ async authorize(signal) {
103
+ if (this.token && this.token.expires > Date.now()) return this.token.value;
104
+ const raw = await this.request(
105
+ "https://oauth2.googleapis.com/token",
106
+ {
107
+ method: "POST",
108
+ body: new URLSearchParams({
109
+ client_id: this.credentials.clientId,
110
+ client_secret: this.credentials.clientSecret,
111
+ refresh_token: this.credentials.refreshToken,
112
+ grant_type: "refresh_token"
113
+ })
114
+ },
115
+ signal
116
+ );
117
+ const parsed = z.object({ access_token: z.string().min(1), expires_in: z.number().positive().default(3600) }).safeParse(raw);
118
+ if (!parsed.success) throw new EmailInboxError("invalid");
119
+ this.token = {
120
+ value: parsed.data.access_token,
121
+ expires: Date.now() + Math.max(0, parsed.data.expires_in - 60) * 1e3
122
+ };
123
+ return this.token.value;
124
+ }
125
+ async read(input, signal) {
126
+ const parsed = querySchema.safeParse(input);
127
+ if (!parsed.success) throw new Error("Invalid inbox query");
128
+ const query = parsed.data;
129
+ const token = await this.authorize(signal);
130
+ const headers = { authorization: `Bearer ${token}` };
131
+ const params = new URLSearchParams({
132
+ q: `to:${query.to}${query.from ? ` from:${query.from}` : ""} after:${Math.floor(query.afterMs / 1e3)}`,
133
+ maxResults: "20"
134
+ });
135
+ const list = listSchema.safeParse(
136
+ await this.request(`${endpoint}?${params}`, { headers }, signal)
137
+ );
138
+ if (!list.success) throw new EmailInboxError("invalid");
139
+ const results = [];
140
+ for (const { id } of list.data.messages) {
141
+ signal?.throwIfAborted();
142
+ const key = JSON.stringify([id, query]);
143
+ if (!this.checked.has(key)) {
144
+ const format = query.metadata ? "metadata&metadataHeaders=Subject&metadataHeaders=To&metadataHeaders=From" : "full";
145
+ const raw = await this.request(
146
+ `${endpoint}/${encodeURIComponent(id)}?format=${format}`,
147
+ { headers },
148
+ signal
149
+ );
150
+ if (!boundedMime(raw)) throw new EmailInboxError("invalid");
151
+ const parsed2 = messageSchema.safeParse(raw);
152
+ if (!parsed2.success) throw new EmailInboxError("invalid");
153
+ const { payload, internalDate } = parsed2.data;
154
+ const header = (name) => payload.headers.find((field) => field.name.toLowerCase() === name.toLowerCase())?.value ?? "";
155
+ const exact = (value, expected) => (/^[^<>]*<([^<>]+)>$/.exec(value)?.[1] ?? value).toLowerCase() === expected.toLowerCase();
156
+ const date = Number(internalDate);
157
+ let message2 = null;
158
+ if (Number.isFinite(date) && date >= query.afterMs && exact(header("To"), query.to) && (!query.from || exact(header("From"), query.from))) {
159
+ const content = { text: "", html: "" };
160
+ const decode = (part, depth) => {
161
+ if (depth > 20) throw new EmailInboxError("invalid");
162
+ if (part.body?.data && ["text/plain", "text/html"].includes(part.mimeType ?? "")) {
163
+ const key2 = part.mimeType === "text/html" ? "html" : "text";
164
+ content[key2] += Buffer.from(part.body.data, "base64url").toString("utf8");
165
+ }
166
+ for (const child of part.parts ?? []) decode(child, depth + 1);
167
+ };
168
+ decode(payload, 0);
169
+ if (content.text.length + content.html.length > 256e3)
170
+ throw new EmailInboxError("invalid");
171
+ message2 = {
172
+ id,
173
+ date,
174
+ to: query.to,
175
+ from: header("From"),
176
+ subject: header("Subject"),
177
+ ...content
178
+ };
179
+ }
180
+ this.checked.set(key, message2);
181
+ if (this.checked.size > 20) this.checked.delete(this.checked.keys().next().value);
182
+ }
183
+ const message = this.checked.get(key);
184
+ if (message) results.push(message);
185
+ }
186
+ return results.sort((a, b) => b.date - a.date);
187
+ }
188
+ }
189
+ export {
190
+ EmailInboxError,
191
+ GmailInbox,
192
+ gmailCredentialsSchema
193
+ };
package/src/watch.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { Hono } from "hono";
2
+ import type { Principal } from "./auth.js";
3
+ /** Read-only capability, separate from conductor/actor tokens; never grants MCP/control access. */
4
+ export declare function registerWatch(app: Hono<{
5
+ Variables: {
6
+ principal: Principal;
7
+ };
8
+ }>, token: string | undefined, frames: (signal: AbortSignal) => Promise<{
9
+ view: string;
10
+ png: string;
11
+ }[]>): void;
package/src/watch.js ADDED
@@ -0,0 +1,30 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ function registerWatch(app, token, frames) {
3
+ if (!token) return;
4
+ app.get("/watch", (c) => {
5
+ c.header("cache-control", "no-store");
6
+ c.header("referrer-policy", "no-referrer");
7
+ c.header("content-security-policy", "default-src 'none'; frame-ancestors 'none'");
8
+ return c.text("Use qa watch to open an authenticated local screen session.");
9
+ });
10
+ let active = false;
11
+ app.get("/watch/frames", async (c) => {
12
+ c.header("cache-control", "no-store");
13
+ const supplied = c.req.header("authorization") ?? "";
14
+ const expected = `Bearer ${token}`;
15
+ if (Buffer.byteLength(supplied) !== Buffer.byteLength(expected) || !timingSafeEqual(Buffer.from(supplied), Buffer.from(expected)))
16
+ return c.json({ error: "Unauthorized" }, 401);
17
+ if (active) return c.json({ error: "Screen busy" }, 429);
18
+ active = true;
19
+ try {
20
+ return c.json(await frames(AbortSignal.any([c.req.raw.signal, AbortSignal.timeout(1e4)])));
21
+ } catch {
22
+ return c.json({ error: "Screen unavailable" }, 503);
23
+ } finally {
24
+ active = false;
25
+ }
26
+ });
27
+ }
28
+ export {
29
+ registerWatch
30
+ };
@@ -0,0 +1,5 @@
1
+ import type { ExpectResult } from "@open-qa/qa-engine/protocol";
2
+ import type { StageDrivers } from "./drivers.js";
3
+ import type { PageViews } from "./page-views.js";
4
+ export declare const invalidExpectation: (reason?: string) => ExpectResult;
5
+ export declare function webExpect(pages: PageViews): StageDrivers["expect"];
@@ -0,0 +1,130 @@
1
+ import { z } from "zod";
2
+ const text = z.string().min(1).max(4e3);
3
+ const timed = { view: text.optional(), within: text.optional() };
4
+ const parameters = z.discriminatedUnion("type", [
5
+ z.strictObject({ type: z.literal("web.url"), ...timed, matches: text }),
6
+ z.strictObject({
7
+ type: z.literal("web.visible"),
8
+ ...timed,
9
+ text: text.optional(),
10
+ role: text.optional(),
11
+ name: text.optional()
12
+ }),
13
+ z.strictObject({ type: z.literal("web.images_loaded"), ...timed }),
14
+ z.strictObject({
15
+ type: z.literal("web.no_console_errors"),
16
+ ...timed,
17
+ ignore: z.array(text).max(100).optional()
18
+ })
19
+ ]);
20
+ const invalidExpectation = (reason = "Invalid expectation condition") => ({
21
+ passed: false,
22
+ reason,
23
+ evidence: { invalid: true }
24
+ });
25
+ function webExpect(pages) {
26
+ return async (request, context) => {
27
+ const parsed = parameters.safeParse(request.condition);
28
+ if (!request.view || !parsed.success || parsed.data.view && parsed.data.view !== request.view)
29
+ return invalidExpectation();
30
+ const condition = parsed.data;
31
+ const entry = pages.entry(request.view, request.actor);
32
+ return pages.run(
33
+ request.view,
34
+ { actor: request.actor, step: request.step, signal: context.signal },
35
+ async (page, operation) => {
36
+ pages.rememberState(await entry.context.storageState());
37
+ if (condition.type === "web.no_console_errors") {
38
+ const recorded2 = request.step === void 0 ? void 0 : entry.diagnostics.read(request.step);
39
+ if (!recorded2)
40
+ return {
41
+ passed: false,
42
+ reason: "Step diagnostics are unavailable",
43
+ evidence: { invalid: true }
44
+ };
45
+ const failures2 = recorded2.failures.filter(
46
+ (failure) => !(condition.ignore ?? []).some(
47
+ (pattern) => failure.message.includes(pattern) || failure.url?.includes(pattern)
48
+ )
49
+ );
50
+ return {
51
+ passed: failures2.length === 0 && !recorded2.overflow,
52
+ ...failures2.length || recorded2.overflow ? { reason: "Console errors or failed requests occurred during the step" } : {},
53
+ evidence: {
54
+ failures: failures2.slice(0, 50).map((failure) => ({ ...failure })),
55
+ count: failures2.length,
56
+ truncated: recorded2.overflow || failures2.length > 50
57
+ }
58
+ };
59
+ }
60
+ if (condition.type === "web.url") {
61
+ const url = new URL(page.url());
62
+ const passed = condition.matches.startsWith("/") ? url.pathname.includes(condition.matches) : url.href.includes(condition.matches);
63
+ return {
64
+ passed,
65
+ ...!passed && { reason: "Current URL does not match" },
66
+ evidence: { url: url.href, matches: condition.matches }
67
+ };
68
+ }
69
+ if (condition.type === "web.visible") {
70
+ if (!condition.text && !(condition.role && condition.name)) return invalidExpectation();
71
+ const locator = condition.text ? page.getByText(condition.text) : page.getByRole(condition.role, {
72
+ name: condition.name
73
+ });
74
+ const candidates = await locator.all();
75
+ for (const candidate of candidates) {
76
+ if (await candidate.isVisible()) {
77
+ const box = await candidate.boundingBox({ signal: operation.signal });
78
+ const viewport = page.viewportSize();
79
+ if (box && viewport && box.x < viewport.width && box.y < viewport.height && box.x + box.width > 0 && box.y + box.height > 0)
80
+ return { passed: true, evidence: { visible: true } };
81
+ }
82
+ }
83
+ return {
84
+ passed: false,
85
+ reason: "No matching element is visible in the viewport",
86
+ evidence: { visible: false, matches: candidates.length }
87
+ };
88
+ }
89
+ const images = await page.locator("img").evaluateAll(
90
+ (elements) => elements.map((element) => {
91
+ const image = element;
92
+ const box = image.getBoundingClientRect();
93
+ const offscreen = box.bottom <= 0 || box.right <= 0 || box.top >= innerHeight || box.left >= innerWidth;
94
+ return {
95
+ skipped: image.loading === "lazy" && !image.complete && offscreen,
96
+ src: image.currentSrc || image.src,
97
+ complete: image.complete,
98
+ width: image.naturalWidth
99
+ };
100
+ })
101
+ );
102
+ const failures = images.filter(
103
+ (image) => !image.skipped && (!image.complete || image.width === 0)
104
+ );
105
+ const recorded = entry.diagnostics.read();
106
+ return {
107
+ passed: failures.length === 0,
108
+ ...failures.length > 0 && { reason: "Page images have not loaded successfully" },
109
+ evidence: {
110
+ total: images.length,
111
+ skipped: images.filter((image) => image.skipped).length,
112
+ failed: failures.length,
113
+ truncated: failures.length > 50,
114
+ images: failures.slice(0, 50).map((image) => {
115
+ const failure = recorded?.failures.slice().reverse().find((failure2) => failure2.url === image.src);
116
+ return {
117
+ src: image.src,
118
+ error: failure?.message ?? (image.complete ? "Image decode failed" : "Image is still loading")
119
+ };
120
+ })
121
+ }
122
+ };
123
+ }
124
+ );
125
+ };
126
+ }
127
+ export {
128
+ invalidExpectation,
129
+ webExpect
130
+ };
@@ -0,0 +1,15 @@
1
+ import { type Locator, type Page } from "playwright";
2
+ import { type ActionTarget, type JsonObject } from "@open-qa/qa-engine/protocol";
3
+ import type { PageViews } from "./page-views.js";
4
+ import type { ToolCommand, ToolContext, ToolOutput } from "./surface-adapter.js";
5
+ export interface PixelFallback {
6
+ execute(action: {
7
+ tool: string;
8
+ args: JsonObject;
9
+ target: ActionTarget;
10
+ }, page: Page, context: ToolContext): Promise<ToolOutput>;
11
+ }
12
+ export declare function describeTarget(locator: Locator, ref: string | undefined, context: ToolContext): Promise<Extract<ActionTarget, {
13
+ layer: "semantic";
14
+ }>>;
15
+ export declare function webTools(views: PageViews, fallback?: PixelFallback): ToolCommand[];