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

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,140 @@
1
+ import { z } from "zod";
2
+ import { EmailInboxError } from "./vendor/gmail.js";
3
+ import { emailToolNames, idSchema, jsonObjectSchema } from "@open-qa/qa-engine/protocol";
4
+ import { projectEmail } from "./email-message.js";
5
+ import { StageError } from "./drivers.js";
6
+ import { assertPageUrl } from "./page-policy.js";
7
+ import { invalidExpectation } from "./web-expect.js";
8
+ const text = z.string().min(1).max(1e3);
9
+ const schemas = {
10
+ email_read: z.strictObject({ view: idSchema }),
11
+ email_open_link: z.strictObject({ view: idSchema, sourceView: idSchema, message: text, text })
12
+ };
13
+ const condition = z.strictObject({
14
+ type: z.literal("email.received"),
15
+ view: idSchema.optional(),
16
+ to: z.email(),
17
+ subject: text.optional(),
18
+ subject_contains: text.optional(),
19
+ contains: text.optional(),
20
+ within: text.optional()
21
+ });
22
+ function emailSurface(pages, inbox, known, remember, afterMs = Math.max(0, Date.now() - 6e4)) {
23
+ const cache = /* @__PURE__ */ new WeakMap();
24
+ function bound(view, actor) {
25
+ const entry = pages.entry(view, actor);
26
+ if (entry.template !== "email" || !entry.email)
27
+ throw new StageError(400, "email_view_required", "An actor-bound email view is required");
28
+ return entry;
29
+ }
30
+ async function refresh(view, context) {
31
+ const entry = bound(view, context.actor);
32
+ const previous = cache.get(entry);
33
+ if (previous && Date.now() - previous.at < 1e3) return previous.messages;
34
+ try {
35
+ const raw = await inbox.read({ to: entry.email.address, afterMs }, context.signal);
36
+ const messages = raw.slice(0, 5).map((message) => projectEmail(message, known));
37
+ remember(messages.flatMap((message) => message.secrets));
38
+ const safe = raw.slice(0, 5).map((message) => projectEmail(message, known));
39
+ const latest = safe[0];
40
+ if (latest)
41
+ await pages.render(
42
+ {
43
+ view,
44
+ content: {
45
+ template: "email",
46
+ from: latest.safe.from || "Unknown sender",
47
+ subject: latest.safe.subject || "(No subject)",
48
+ html: latest.html
49
+ }
50
+ },
51
+ { signal: context.signal ?? AbortSignal.timeout(15e3), emit: entry.emit }
52
+ );
53
+ cache.set(entry, { at: Date.now(), messages: safe });
54
+ return safe;
55
+ } catch (error) {
56
+ context.signal?.throwIfAborted();
57
+ if (error instanceof EmailInboxError)
58
+ throw new StageError(502, `email_${error.reason}`, error.message);
59
+ throw error;
60
+ }
61
+ }
62
+ return {
63
+ name: "email",
64
+ views: {
65
+ list: () => pages.list().filter((view) => !!pages.entry(view.view).email),
66
+ observe: pages.observe.bind(pages),
67
+ snapshot: pages.snapshot.bind(pages),
68
+ screenshot: pages.screenshot.bind(pages),
69
+ text: pages.text.bind(pages)
70
+ },
71
+ tools: emailToolNames.map((name) => ({
72
+ name,
73
+ inputSchema: schemas[name],
74
+ scope: "view",
75
+ allowRendered: name === "email_read",
76
+ ...name === "email_open_link" ? { viewArgs: ["sourceView"] } : {},
77
+ description: name === "email_read" ? "Read the actor's leased inbox and render its newest message. Codes and link tokens are masked." : "Open a cached email link by its exact visible text and message ID from sourceView into an owned web page view. No URL argument is accepted.",
78
+ execute: async (input, context) => {
79
+ if (name === "email_read") {
80
+ const args2 = schemas.email_read.parse(input);
81
+ return {
82
+ data: jsonObjectSchema.parse({
83
+ messages: (await refresh(args2.view, context)).map((message2) => message2.safe)
84
+ })
85
+ };
86
+ }
87
+ const args = schemas.email_open_link.parse(input);
88
+ const source = bound(args.sourceView, context.actor);
89
+ const target = pages.entry(args.view, context.actor);
90
+ if (target.info.type !== "page")
91
+ throw new StageError(400, "email_target", "A web page target is required");
92
+ const message = cache.get(source)?.messages.find((message2) => message2.safe.id === args.message);
93
+ const candidates = message?.safe.links.flatMap(
94
+ (link, index) => link.text === args.text ? [message.links[index]] : []
95
+ ) ?? [];
96
+ if (candidates.length !== 1)
97
+ throw new StageError(400, "email_link", "Email link must match exactly one cached link");
98
+ const url = candidates[0].url;
99
+ assertPageUrl(url, pages.config);
100
+ await pages.run(args.view, context, async (page, operation) => {
101
+ await page.goto(url, { waitUntil: "domcontentloaded", signal: operation.signal });
102
+ });
103
+ return { data: { opened: true, message: args.message, text: args.text } };
104
+ }
105
+ })),
106
+ expectPollIntervalMs: 1e3,
107
+ retryableExpectError: (error) => error instanceof StageError && ["email_rate", "email_unavailable"].includes(error.code),
108
+ expect: async (request, context) => {
109
+ const parsed = condition.safeParse(request.condition);
110
+ if (!request.view || !parsed.success || parsed.data.view && parsed.data.view !== request.view)
111
+ return invalidExpectation();
112
+ const entry = bound(request.view, request.actor);
113
+ if (parsed.data.to.toLowerCase() !== entry.email.address.toLowerCase())
114
+ return invalidExpectation("Condition recipient must match the actor's leased inbox");
115
+ let messages;
116
+ try {
117
+ messages = await refresh(request.view, {
118
+ actor: request.actor,
119
+ signal: context.expectDeadline ? AbortSignal.any([context.signal, context.expectDeadline]) : context.signal
120
+ });
121
+ } catch (error) {
122
+ context.signal.throwIfAborted();
123
+ if (context.expectDeadline?.aborted)
124
+ throw new StageError(502, "email_unavailable", "Email request timed out");
125
+ throw error;
126
+ }
127
+ const filter = parsed.data;
128
+ const found = messages.filter(
129
+ ({ safe }) => (!filter.subject || safe.subject.includes(filter.subject)) && (!filter.subject_contains || safe.subject.includes(filter.subject_contains)) && (!filter.contains || safe.text.includes(filter.contains))
130
+ );
131
+ return {
132
+ passed: found.length > 0,
133
+ evidence: { ids: found.map((message) => message.safe.id), count: found.length }
134
+ };
135
+ }
136
+ };
137
+ }
138
+ export {
139
+ emailSurface
140
+ };
@@ -0,0 +1,18 @@
1
+ import { SecretRedactor, type Clock } from "@open-qa/qa-engine";
2
+ import { type RunEvent } from "@open-qa/qa-engine/protocol";
3
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
4
+ export type EventInput = DistributiveOmit<RunEvent, "seq" | "t">;
5
+ export type EventListener = (event: RunEvent) => void;
6
+ export declare class EventLog {
7
+ readonly file: string;
8
+ private readonly clock;
9
+ readonly redactor: SecretRedactor;
10
+ private readonly events;
11
+ private readonly listeners;
12
+ constructor(file: string, clock: Clock);
13
+ get seq(): number;
14
+ append(input: EventInput): RunEvent;
15
+ after(seq: number, limit?: number): RunEvent[];
16
+ subscribe(listener: EventListener): () => void;
17
+ }
18
+ export {};
@@ -0,0 +1,46 @@
1
+ import { appendFileSync, existsSync, statSync } from "node:fs";
2
+ import { SecretRedactor } from "@open-qa/qa-engine";
3
+ import { runEventSchema } from "@open-qa/qa-engine/protocol";
4
+ class EventLog {
5
+ constructor(file, clock) {
6
+ this.file = file;
7
+ this.clock = clock;
8
+ if (existsSync(file) && statSync(file).size > 0) {
9
+ throw new Error(`Event log already has events: ${file}`);
10
+ }
11
+ }
12
+ file;
13
+ clock;
14
+ redactor = new SecretRedactor("***");
15
+ events = [];
16
+ listeners = /* @__PURE__ */ new Set();
17
+ get seq() {
18
+ return this.events.length;
19
+ }
20
+ append(input) {
21
+ const event = runEventSchema.parse(
22
+ this.redactor.json({
23
+ ...input,
24
+ seq: this.events.length + 1,
25
+ t: this.clock.now()
26
+ })
27
+ );
28
+ appendFileSync(this.file, `${JSON.stringify(event)}
29
+ `);
30
+ this.events.push(event);
31
+ for (const listener of this.listeners) listener(structuredClone(event));
32
+ return structuredClone(event);
33
+ }
34
+ // seq starts at 1 and has no gaps, so the events after n are the slice from n.
35
+ after(seq, limit = Infinity) {
36
+ const start = Math.max(0, seq);
37
+ return this.events.slice(start, start + limit).map((event) => structuredClone(event));
38
+ }
39
+ subscribe(listener) {
40
+ this.listeners.add(listener);
41
+ return () => this.listeners.delete(listener);
42
+ }
43
+ }
44
+ export {
45
+ EventLog
46
+ };
@@ -0,0 +1,15 @@
1
+ import type { Clock } from "@open-qa/qa-engine";
2
+ import { type JsonObject } from "@open-qa/qa-engine/protocol";
3
+ import type { RedactionOptions } from "./expect-evidence.js";
4
+ import { type StageDrivers } from "./drivers.js";
5
+ import type { SurfaceAdapter } from "./surface-adapter.js";
6
+ export declare class ExpectEngine {
7
+ private readonly options;
8
+ constructor(options: {
9
+ surfaces: readonly SurfaceAdapter[];
10
+ clock: Clock;
11
+ redact?: (value: JsonObject[string], options?: RedactionOptions) => JsonObject[string];
12
+ });
13
+ readonly expect: StageDrivers["expect"];
14
+ private within;
15
+ }
@@ -0,0 +1,114 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import {
3
+ expectResultSchema,
4
+ jsonObjectSchema
5
+ } from "@open-qa/qa-engine/protocol";
6
+ import { StageError } from "./drivers.js";
7
+ import { systemFailure } from "./system-common.js";
8
+ class ExpectEngine {
9
+ constructor(options) {
10
+ this.options = options;
11
+ }
12
+ options;
13
+ expect = async (request, context) => {
14
+ context.signal.throwIfAborted();
15
+ const surface = this.options.surfaces.find(
16
+ (surface2) => surface2.name === request.condition.type.split(".")[0]
17
+ );
18
+ let result;
19
+ const within = this.within(request);
20
+ if (within === void 0)
21
+ result = { passed: false, reason: "Invalid expectation duration", evidence: {} };
22
+ else if (!surface?.expect)
23
+ result = { passed: false, reason: "Unsupported expectation type", evidence: {} };
24
+ else {
25
+ if (surface.views && !surface.views.list().some((view) => view.view === request.view && view.actor === request.actor))
26
+ throw new StageError(403, "view_forbidden", "View is not available to this actor");
27
+ const deadline = this.options.clock.now() + within;
28
+ const expectDeadline = within > 0 && surface.retryableExpectError ? AbortSignal.timeout(Math.ceil(within)) : void 0;
29
+ let interval = surface.expectPollIntervalMs ?? 50;
30
+ const maxInterval = Math.max(interval, 500);
31
+ let checked;
32
+ let lastError;
33
+ do {
34
+ context.signal.throwIfAborted();
35
+ try {
36
+ checked = expectResultSchema.parse(
37
+ await surface.expect(request, { ...context, expectDeadline })
38
+ );
39
+ lastError = void 0;
40
+ } catch (error) {
41
+ context.signal.throwIfAborted();
42
+ if (surface.retryableExpectError?.(error)) {
43
+ if (!expectDeadline?.aborted || lastError === void 0) lastError = error;
44
+ checked = void 0;
45
+ } else {
46
+ if (error instanceof StageError) throw error;
47
+ checked = systemFailure(error) ?? {
48
+ passed: false,
49
+ reason: "Expectation check failed",
50
+ evidence: {}
51
+ };
52
+ lastError = void 0;
53
+ }
54
+ }
55
+ const remaining = deadline - this.options.clock.now();
56
+ if (checked?.passed || remaining <= 0 || checked?.evidence.invalid === true || checked?.evidence.terminal === true)
57
+ break;
58
+ await delay(Math.min(interval, remaining), void 0, { signal: context.signal });
59
+ interval = Math.min(interval * 2, maxInterval);
60
+ } while (this.options.clock.now() < deadline);
61
+ if (!checked) throw lastError;
62
+ result = checked;
63
+ }
64
+ context.signal.throwIfAborted();
65
+ const redact = this.options.redact ?? ((value) => value);
66
+ const safe = expectResultSchema.parse({
67
+ passed: result.passed,
68
+ evidence: redact(result.evidence, { full: !surface?.views }),
69
+ ...result.reason !== void 0 && { reason: redact(result.reason) }
70
+ });
71
+ const condition = {
72
+ ...jsonObjectSchema.parse(redact(request.condition, { condition: true })),
73
+ type: [
74
+ "web.url",
75
+ "web.visible",
76
+ "web.images_loaded",
77
+ "web.no_console_errors",
78
+ "http.status",
79
+ "telegram.message",
80
+ "telegram.no_message",
81
+ "discord.message",
82
+ "email.received",
83
+ "http.json",
84
+ "db.row",
85
+ "db.count",
86
+ "logs.entry",
87
+ "logs.contains",
88
+ "github.pr"
89
+ ].includes(request.condition.type) ? request.condition.type : "***"
90
+ };
91
+ context.emit({
92
+ kind: "expect_result",
93
+ by: "conductor",
94
+ actor: request.actor,
95
+ view: request.view,
96
+ ...request.step !== void 0 && { step: request.step },
97
+ condition,
98
+ result: safe
99
+ });
100
+ return { ...safe, condition };
101
+ };
102
+ within(request) {
103
+ const value = request.condition.within;
104
+ if (value === void 0) return 0;
105
+ if (typeof value !== "string") return void 0;
106
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(value);
107
+ if (!match) return void 0;
108
+ const ms = Number(match[1]) * ({ ms: 1, s: 1e3, m: 6e4, h: 36e5 }[match[2]] ?? 0);
109
+ return Number.isFinite(ms) && ms > 0 && ms <= 2147483647 ? ms : void 0;
110
+ }
111
+ }
112
+ export {
113
+ ExpectEngine
114
+ };
@@ -0,0 +1,7 @@
1
+ import type { JsonObject } from "@open-qa/qa-engine/protocol";
2
+ export interface RedactionOptions {
3
+ condition?: boolean;
4
+ full?: boolean;
5
+ }
6
+ export declare function browserStateSecrets(value: string): string[];
7
+ export declare function redactExpectEvidence(value: JsonObject[string], secrets: Iterable<string>, options?: RedactionOptions): JsonObject[string];
@@ -0,0 +1,68 @@
1
+ function browserStateSecrets(value) {
2
+ const values = /* @__PURE__ */ new Set();
3
+ if (value.length >= 8) values.add(value);
4
+ const visit = (item, depth) => {
5
+ if (typeof item === "string" && item.length >= 8) values.add(item);
6
+ if (depth >= 16 || item === null || typeof item !== "object") return;
7
+ for (const child of Object.values(item)) visit(child, depth + 1);
8
+ };
9
+ try {
10
+ visit(JSON.parse(value), 0);
11
+ } catch {
12
+ }
13
+ return [...values];
14
+ }
15
+ const credentialKey = /token|cookie|password|secret|authorization|storageState|api[_-]?key|session|jwt|sid|credential/i;
16
+ function redactExpectEvidence(value, secrets, options = {}) {
17
+ const values = [...new Set(secrets)].filter(Boolean).flatMap((value2) => {
18
+ const forms = [value2, JSON.stringify(value2).slice(1, -1)];
19
+ try {
20
+ forms.push(encodeURIComponent(value2));
21
+ } catch {
22
+ }
23
+ return forms;
24
+ }).sort((a, b) => b.length - a.length);
25
+ const text = (value2) => {
26
+ let safe = value2.replace(/https?:\/\/[^\s"'<>]+/g, (raw) => {
27
+ try {
28
+ const url = new URL(raw);
29
+ url.username = "";
30
+ url.password = "";
31
+ if (options.condition) {
32
+ for (const key of [...url.searchParams.keys()])
33
+ if (credentialKey.test(key)) url.searchParams.set(key, "***");
34
+ } else {
35
+ url.search = "";
36
+ url.hash = "";
37
+ }
38
+ return url.href;
39
+ } catch {
40
+ return "[URL omitted]";
41
+ }
42
+ });
43
+ for (const secret of values) safe = safe.replaceAll(secret, "***");
44
+ safe = safe.replace(/\{\{secrets\.[^{}]+\}\}/g, "***").replace(
45
+ /\b(?:bearer\s+\S+|(?:[\w-]*(?:token|cookie|password|secret|authorization|api[_-]?key|session|jwt|sid|credential)|storageState)["']?\s*[=:]\s*(?:bearer\s+)?(?:"[^"]*"|'[^']*'|[^\s,;}]+))/gi,
46
+ "[credentials omitted]"
47
+ );
48
+ return options.condition || options.full ? safe : safe.slice(0, 1e3);
49
+ };
50
+ const visit = (item) => {
51
+ if (typeof item === "string") return text(item);
52
+ if (Array.isArray(item))
53
+ return (options.condition || options.full ? item : item.slice(0, 50)).map(visit);
54
+ if (item !== null && typeof item === "object")
55
+ return Object.fromEntries(
56
+ Object.entries(item).map(([key, child]) => [
57
+ text(key),
58
+ credentialKey.test(key) ? "***" : visit(child)
59
+ ])
60
+ );
61
+ return item;
62
+ };
63
+ return visit(value);
64
+ }
65
+ export {
66
+ browserStateSecrets,
67
+ redactExpectEvidence
68
+ };
@@ -0,0 +1,2 @@
1
+ import type { ToolCommand } from "./surface-adapter.js";
2
+ export declare function flowTools(): ToolCommand[];
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+ import { flowToolNames } from "@open-qa/qa-engine/protocol";
3
+ import { MAX_FLOW_TEXT_CHARS } from "./tool-limits.js";
4
+ function flowTools() {
5
+ return [
6
+ {
7
+ name: flowToolNames[0],
8
+ description: "Signal that the current step is ready for conductor checks",
9
+ scope: "actor",
10
+ inputSchema: z.strictObject({
11
+ note: z.string().max(MAX_FLOW_TEXT_CHARS).trim().min(1).optional()
12
+ }),
13
+ execute: async (args) => ({ data: { status: "done", ...args } })
14
+ },
15
+ {
16
+ name: flowToolNames[1],
17
+ description: "Signal that the current step cannot continue; provide a reason",
18
+ scope: "actor",
19
+ inputSchema: z.strictObject({ reason: z.string().max(MAX_FLOW_TEXT_CHARS).trim().min(1) }),
20
+ execute: async (args) => ({ data: { status: "blocked", ...args } })
21
+ }
22
+ ];
23
+ }
24
+ export {
25
+ flowTools
26
+ };
@@ -0,0 +1,4 @@
1
+ import type { StageDrivers } from "./drivers.js";
2
+ import { type PageConfig } from "./page-policy.js";
3
+ import type { Fetcher } from "./system-common.js";
4
+ export declare function httpExpect(config: PageConfig, fetcher?: Fetcher): StageDrivers["expect"];
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+ import { assertPageUrl } from "./page-policy.js";
3
+ import { invalidExpectation } from "./web-expect.js";
4
+ const conditionSchema = z.strictObject({
5
+ type: z.literal("http.status"),
6
+ view: z.string().optional(),
7
+ within: z.string().optional(),
8
+ url: z.url().refine(
9
+ (value) => URL.canParse(value) && ["http:", "https:"].includes(new URL(value).protocol)
10
+ ),
11
+ equals: z.number().int().min(100).max(599)
12
+ });
13
+ function httpExpect(config, fetcher = fetch) {
14
+ return async (request, context) => {
15
+ const parsed = conditionSchema.safeParse(request.condition);
16
+ if (!parsed.success) {
17
+ if (parsed.error.issues.some((issue) => issue.path[0] === "url"))
18
+ return invalidExpectation(
19
+ "Invalid http.status condition: url must be an absolute HTTP(S) URL"
20
+ );
21
+ return invalidExpectation(
22
+ "Invalid http.status condition: check type, view, within, url and equals"
23
+ );
24
+ }
25
+ if (parsed.data.view && parsed.data.view !== request.view)
26
+ return invalidExpectation("Invalid http.status condition: view must match the request view");
27
+ const condition = parsed.data;
28
+ let url = condition.url;
29
+ const signal = AbortSignal.any([context.signal, AbortSignal.timeout(config.timeoutMs)]);
30
+ try {
31
+ for (let redirects = 0; redirects <= 5; redirects++) {
32
+ assertPageUrl(url, config);
33
+ const headers = new Headers();
34
+ if (config.access && new URL(url).origin === config.access.origin) {
35
+ headers.set("cf-access-client-id", config.access.clientId);
36
+ headers.set("cf-access-client-secret", config.access.clientSecret);
37
+ }
38
+ const response = await fetcher(url, { method: "GET", redirect: "manual", signal, headers });
39
+ await response.body?.cancel();
40
+ const location = response.headers.get("location");
41
+ if (location && [301, 302, 303, 307, 308].includes(response.status)) {
42
+ const next = new URL(location, url);
43
+ if (config.access && new URL(url).origin === config.access.origin && next.origin !== config.access.origin)
44
+ throw new Error("Cross-origin redirect is blocked");
45
+ url = next.href;
46
+ continue;
47
+ }
48
+ const passed = response.status === condition.equals;
49
+ return {
50
+ passed,
51
+ ...!passed && { reason: "HTTP status does not equal the expected value" },
52
+ evidence: { url, expected: condition.equals, actual: response.status }
53
+ };
54
+ }
55
+ return { passed: false, reason: "HTTP redirect limit exceeded", evidence: {} };
56
+ } catch {
57
+ context.signal.throwIfAborted();
58
+ return {
59
+ passed: false,
60
+ reason: "HTTP request failed or was blocked by the origin policy",
61
+ evidence: { url }
62
+ };
63
+ }
64
+ };
65
+ }
66
+ export {
67
+ httpExpect
68
+ };
package/src/index.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export { createAuthenticator, type Principal } from "./auth.js";
2
+ export { loadStageConfig, stageConfigSchema, type StageConfig, type StageConfigInput, } from "./config.js";
3
+ export { StageError, type DriverContext, type DriverMethod, type StageDrivers } from "./drivers.js";
4
+ export { EventLog, type EventInput, type EventListener } from "./event-log.js";
5
+ export type { ActorEventInput, ActorSession, RegisterTools } from "./mcp.js";
6
+ export { createStageApp, startStageServer, type RunningStage, type StageApp, type StageAppOptions, type StageExtensions, } from "./server.js";
7
+ export { createStageClock } from "./stage-clock.js";
8
+ export { PageViews, PAGE_VIEWPORT } from "./page-views.js";
9
+ export { pageConfigSchema, type PageConfig } from "./page-policy.js";
10
+ export type { PixelFallback } from "./web-tools.js";
11
+ export { ToolGateway, type ToolGatewayOptions } from "./tool-gateway.js";
12
+ export type { GatewayResult, SurfaceAdapter, ToolCommand, ToolContext, ToolImage, ToolOutput, ViewDriver, ViewObservation, } from "./surface-adapter.js";
13
+ export { renderedContentSchema, renderViewRequestSchema, renderViewResponseSchema, type RenderedContent, type RenderViewRequest, type RenderViewResponse, } from "@open-qa/qa-engine/protocol";
package/src/index.js ADDED
@@ -0,0 +1,37 @@
1
+ import { createAuthenticator } from "./auth.js";
2
+ import {
3
+ loadStageConfig,
4
+ stageConfigSchema
5
+ } from "./config.js";
6
+ import { StageError } from "./drivers.js";
7
+ import { EventLog } from "./event-log.js";
8
+ import {
9
+ createStageApp,
10
+ startStageServer
11
+ } from "./server.js";
12
+ import { createStageClock } from "./stage-clock.js";
13
+ import { PageViews, PAGE_VIEWPORT } from "./page-views.js";
14
+ import { pageConfigSchema } from "./page-policy.js";
15
+ import { ToolGateway } from "./tool-gateway.js";
16
+ import {
17
+ renderedContentSchema,
18
+ renderViewRequestSchema,
19
+ renderViewResponseSchema
20
+ } from "@open-qa/qa-engine/protocol";
21
+ export {
22
+ EventLog,
23
+ PAGE_VIEWPORT,
24
+ PageViews,
25
+ StageError,
26
+ ToolGateway,
27
+ createAuthenticator,
28
+ createStageApp,
29
+ createStageClock,
30
+ loadStageConfig,
31
+ pageConfigSchema,
32
+ renderViewRequestSchema,
33
+ renderViewResponseSchema,
34
+ renderedContentSchema,
35
+ stageConfigSchema,
36
+ startStageServer
37
+ };
package/src/main.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/src/main.js ADDED
@@ -0,0 +1,51 @@
1
+ import { ClaudeCodeRuntime, PiRuntime, serveAgentWorker } from "@open-qa/qa-agents";
2
+ import { z } from "zod";
3
+ import { parseArgs } from "node:util";
4
+ import { loadStageConfig, loadStageEnvironment } from "./config.js";
5
+ import { startStageServer } from "./server.js";
6
+ const { values } = parseArgs({
7
+ options: { config: { type: "string" }, headed: { type: "boolean" }, agent: { type: "boolean" } }
8
+ });
9
+ if (values.agent) {
10
+ const raw = process.env.QA_AGENT_CONFIG;
11
+ delete process.env.QA_AGENT_CONFIG;
12
+ const controller = new AbortController();
13
+ for (const signal of ["SIGINT", "SIGTERM"])
14
+ process.once(signal, () => controller.abort());
15
+ try {
16
+ const { runtime, ...start } = z.object({ runtime: z.enum(["claude-code", "pi"]).default("claude-code") }).passthrough().parse(JSON.parse(raw ?? ""));
17
+ await serveAgentWorker(
18
+ runtime === "pi" ? new PiRuntime() : new ClaudeCodeRuntime(),
19
+ start,
20
+ process.stdin,
21
+ process.stdout,
22
+ controller.signal
23
+ );
24
+ } catch {
25
+ console.error("QA stage agent failed");
26
+ process.exitCode = 2;
27
+ }
28
+ } else {
29
+ if (!values.config && !process.env.QA_STAGE_CONFIG) {
30
+ console.error(
31
+ "Usage: qa-stage --config <stage.json> [--headed] | QA_STAGE_CONFIG=<json> qa-stage [--headed]"
32
+ );
33
+ process.exit(2);
34
+ }
35
+ try {
36
+ const config = values.config ? await loadStageConfig(values.config) : loadStageEnvironment();
37
+ delete process.env.QA_STAGE_CONFIG;
38
+ if (values.headed) config.headed = true;
39
+ const stage = await startStageServer(config);
40
+ console.log(`QA stage listening on ${stage.url}`);
41
+ for (const signal of ["SIGINT", "SIGTERM"]) {
42
+ process.once(signal, () => {
43
+ void stage.close().then(() => process.exit(0));
44
+ });
45
+ }
46
+ } catch {
47
+ delete process.env.QA_STAGE_CONFIG;
48
+ console.error("QA stage failed to start; check configuration and local browser availability");
49
+ process.exit(2);
50
+ }
51
+ }
package/src/mcp.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { RunEvent } from "@open-qa/qa-engine/protocol";
3
+ import type { EventInput, EventLog } from "./event-log.js";
4
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
5
+ export type ActorEventInput = DistributiveOmit<EventInput, "actor" | "by">;
6
+ export interface ActorSession {
7
+ replay?: import("./surface-adapter.js").ToolContext["replay"];
8
+ readonly actor: string;
9
+ readonly signal?: AbortSignal;
10
+ emit(event: ActorEventInput): RunEvent;
11
+ }
12
+ export type RegisterTools = (server: McpServer, session: ActorSession) => void;
13
+ export declare function handleMcpRequest(request: Request, actor: string, log: Pick<EventLog, "append">, registerTools: RegisterTools | undefined): Promise<Response>;
14
+ export {};
package/src/mcp.js ADDED
@@ -0,0 +1,23 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
3
+ async function handleMcpRequest(request, actor, log, registerTools) {
4
+ const server = new McpServer({ name: "open-qa-stage", version: "0.0.0" });
5
+ registerTools?.(server, {
6
+ actor,
7
+ signal: request.signal,
8
+ emit: (event) => log.append({ ...event, actor, by: "agent" })
9
+ });
10
+ const transport = new WebStandardStreamableHTTPServerTransport({
11
+ sessionIdGenerator: void 0,
12
+ enableJsonResponse: true
13
+ });
14
+ await server.connect(transport);
15
+ try {
16
+ return await transport.handleRequest(request);
17
+ } finally {
18
+ await server.close();
19
+ }
20
+ }
21
+ export {
22
+ handleMcpRequest
23
+ };
@@ -0,0 +1,3 @@
1
+ import { type JsonObject } from "@open-qa/qa-engine/protocol";
2
+ import type { ToolCommand, ViewDriver } from "./surface-adapter.js";
3
+ export declare function observationTools(list: (actor: string) => JsonObject[], driver: (view: string, actor: string) => ViewDriver): ToolCommand[];