@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.
- package/LICENSE +204 -0
- package/NOTICE +7 -0
- package/THIRD_PARTY.md +13 -0
- package/THIRD_PARTY_NOTICES.md +11 -0
- package/package.json +68 -4
- package/scripts/bundle.d.ts +7 -0
- package/scripts/bundle.js +78 -0
- package/src/auth.d.ts +10 -0
- package/src/auth.js +26 -0
- package/src/blackboard-tools.d.ts +2 -0
- package/src/blackboard-tools.js +46 -0
- package/src/config.d.ts +61 -0
- package/src/config.js +64 -0
- package/src/discord-api.d.ts +47 -0
- package/src/discord-api.js +151 -0
- package/src/discord-surface.d.ts +4 -0
- package/src/discord-surface.js +218 -0
- package/src/drivers.d.ts +21 -0
- package/src/drivers.js +12 -0
- package/src/email-message.d.ts +22 -0
- package/src/email-message.js +114 -0
- package/src/email-surface.d.ts +4 -0
- package/src/email-surface.js +140 -0
- package/src/event-log.d.ts +18 -0
- package/src/event-log.js +46 -0
- package/src/expect-engine.d.ts +15 -0
- package/src/expect-engine.js +114 -0
- package/src/expect-evidence.d.ts +7 -0
- package/src/expect-evidence.js +68 -0
- package/src/flow-tools.d.ts +2 -0
- package/src/flow-tools.js +26 -0
- package/src/http-expect.d.ts +4 -0
- package/src/http-expect.js +68 -0
- package/src/index.d.ts +13 -0
- package/src/index.js +37 -0
- package/src/main.d.ts +1 -0
- package/src/main.js +51 -0
- package/src/mcp.d.ts +14 -0
- package/src/mcp.js +23 -0
- package/src/observation-tools.d.ts +3 -0
- package/src/observation-tools.js +39 -0
- package/src/page-diagnostics.d.ts +19 -0
- package/src/page-diagnostics.js +53 -0
- package/src/page-pixels.d.ts +35 -0
- package/src/page-pixels.js +73 -0
- package/src/page-policy.d.ts +48 -0
- package/src/page-policy.js +125 -0
- package/src/page-recording.d.ts +39 -0
- package/src/page-recording.js +532 -0
- package/src/page-replay.d.ts +7 -0
- package/src/page-replay.js +69 -0
- package/src/page-views.d.ts +85 -0
- package/src/page-views.js +338 -0
- package/src/rendered.d.ts +6 -0
- package/src/rendered.js +135 -0
- package/src/replay-artifacts.d.ts +2 -0
- package/src/replay-artifacts.js +100 -0
- package/src/replay-assets.d.ts +21 -0
- package/src/replay-assets.js +106 -0
- package/src/replay-budget.d.ts +22 -0
- package/src/replay-budget.js +47 -0
- package/src/replay-files.d.ts +3 -0
- package/src/replay-files.js +18 -0
- package/src/replay-privacy.d.ts +10 -0
- package/src/replay-privacy.js +48 -0
- package/src/replay-script.d.ts +2 -0
- package/src/replay-script.js +65 -0
- package/src/replay-warnings.d.ts +6 -0
- package/src/replay-warnings.js +16 -0
- package/src/replay-writer.d.ts +24 -0
- package/src/replay-writer.js +92 -0
- package/src/screen-tools.d.ts +5 -0
- package/src/screen-tools.js +168 -0
- package/src/server.d.ts +50 -0
- package/src/server.js +537 -0
- package/src/signed-artifacts.d.ts +21 -0
- package/src/signed-artifacts.js +127 -0
- package/src/sqlite-parser.d.ts +3 -0
- package/src/stage-clock.d.ts +2 -0
- package/src/stage-clock.js +7 -0
- package/src/surface-adapter.d.ts +65 -0
- package/src/surface-adapter.js +0 -0
- package/src/system-common.d.ts +34 -0
- package/src/system-common.js +123 -0
- package/src/system-db.d.ts +9 -0
- package/src/system-db.js +143 -0
- package/src/system-github.d.ts +6 -0
- package/src/system-github.js +73 -0
- package/src/system-http.d.ts +4 -0
- package/src/system-http.js +86 -0
- package/src/system-logs.d.ts +6 -0
- package/src/system-logs.js +78 -0
- package/src/telegram-api.d.ts +162 -0
- package/src/telegram-api.js +170 -0
- package/src/telegram-markup.d.ts +4 -0
- package/src/telegram-markup.js +129 -0
- package/src/telegram-surface.d.ts +39 -0
- package/src/telegram-surface.js +448 -0
- package/src/tool-gateway.d.ts +41 -0
- package/src/tool-gateway.js +696 -0
- package/src/tool-limits.d.ts +12 -0
- package/src/tool-limits.js +41 -0
- package/src/tool-secrets.d.ts +8 -0
- package/src/tool-secrets.js +38 -0
- package/src/vendor/gmail.d.ts +45 -0
- package/src/vendor/gmail.js +193 -0
- package/src/watch.d.ts +11 -0
- package/src/watch.js +30 -0
- package/src/web-expect.d.ts +5 -0
- package/src/web-expect.js +130 -0
- package/src/web-tools.d.ts +15 -0
- package/src/web-tools.js +340 -0
- package/README.md +0 -3
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
constants,
|
|
5
|
+
fstatSync,
|
|
6
|
+
lstatSync,
|
|
7
|
+
openSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
readdirSync
|
|
10
|
+
} from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { StageError } from "./drivers.js";
|
|
13
|
+
function invalid() {
|
|
14
|
+
return new StageError(400, "unsafe_artifact", "Invalid signed artifact inventory");
|
|
15
|
+
}
|
|
16
|
+
function capture(source) {
|
|
17
|
+
const files = /* @__PURE__ */ new Map();
|
|
18
|
+
let total = 0;
|
|
19
|
+
function collect(path) {
|
|
20
|
+
const full = join(source, path);
|
|
21
|
+
let stat;
|
|
22
|
+
try {
|
|
23
|
+
stat = lstatSync(full);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return;
|
|
26
|
+
throw invalid();
|
|
27
|
+
}
|
|
28
|
+
if (stat.isSymbolicLink()) throw invalid();
|
|
29
|
+
if (stat.isDirectory()) {
|
|
30
|
+
for (const name of readdirSync(full).sort()) collect(`${path}/${name}`);
|
|
31
|
+
} else if (stat.isFile() && !path.endsWith(".tmp")) {
|
|
32
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(path) || path.split("/").some((p) => p.startsWith(".")))
|
|
33
|
+
throw invalid();
|
|
34
|
+
if (stat.size > 64 * 1024 * 1024 || total + stat.size > 256 * 1024 * 1024 || files.size >= 1e4)
|
|
35
|
+
throw invalid();
|
|
36
|
+
const fd = openSync(full, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
37
|
+
try {
|
|
38
|
+
if (!fstatSync(fd).isFile()) throw invalid();
|
|
39
|
+
const data = readFileSync(fd);
|
|
40
|
+
total += data.length;
|
|
41
|
+
if (data.length > 64 * 1024 * 1024 || total > 256 * 1024 * 1024) throw invalid();
|
|
42
|
+
files.set(path, data);
|
|
43
|
+
} finally {
|
|
44
|
+
closeSync(fd);
|
|
45
|
+
}
|
|
46
|
+
} else if (!stat.isFile()) throw invalid();
|
|
47
|
+
}
|
|
48
|
+
for (const name of ["manifest.json", "events.ndjson", "views", "assets", "shots"]) collect(name);
|
|
49
|
+
return files;
|
|
50
|
+
}
|
|
51
|
+
function inventory(files) {
|
|
52
|
+
return [...files].map(([path, data]) => ({
|
|
53
|
+
path,
|
|
54
|
+
bytes: data.length,
|
|
55
|
+
contentType: path.endsWith(".gz") ? "application/gzip" : path.endsWith(".json") ? "application/json" : path.endsWith(".ndjson") ? "application/x-ndjson" : path.endsWith(".png") ? "image/png" : "application/octet-stream"
|
|
56
|
+
}));
|
|
57
|
+
}
|
|
58
|
+
class SignedArtifactSnapshots {
|
|
59
|
+
current;
|
|
60
|
+
uploading = false;
|
|
61
|
+
clear() {
|
|
62
|
+
this.current = void 0;
|
|
63
|
+
}
|
|
64
|
+
prepare(source) {
|
|
65
|
+
if (this.uploading)
|
|
66
|
+
throw new StageError(409, "upload_in_progress", "Signed artifact upload in progress");
|
|
67
|
+
this.current = void 0;
|
|
68
|
+
this.current = { id: randomUUID(), files: capture(source) };
|
|
69
|
+
return { snapshot: this.current.id, artifacts: inventory(this.current.files) };
|
|
70
|
+
}
|
|
71
|
+
async upload(snapshot, urls, signal, send = fetch) {
|
|
72
|
+
const current = this.current;
|
|
73
|
+
if (!snapshot || current?.id !== snapshot)
|
|
74
|
+
throw new StageError(409, "snapshot_unavailable", "Signed artifact snapshot unavailable");
|
|
75
|
+
if (this.uploading)
|
|
76
|
+
throw new StageError(409, "upload_in_progress", "Signed artifact upload in progress");
|
|
77
|
+
const files = current.files;
|
|
78
|
+
const entries = Object.entries(urls);
|
|
79
|
+
if (entries.length && entries.length !== files.size) throw invalid();
|
|
80
|
+
for (const [path, url] of entries) {
|
|
81
|
+
if (!files.has(path)) throw invalid();
|
|
82
|
+
let parsed;
|
|
83
|
+
try {
|
|
84
|
+
parsed = new URL(url);
|
|
85
|
+
} catch {
|
|
86
|
+
throw invalid();
|
|
87
|
+
}
|
|
88
|
+
if (parsed.protocol !== "https:" || parsed.hostname !== "storage.googleapis.com" || parsed.port || parsed.username || parsed.password || parsed.hash || !/^\/[a-z0-9._-]+\/open-qa-runs\//.test(parsed.pathname))
|
|
89
|
+
throw invalid();
|
|
90
|
+
}
|
|
91
|
+
this.uploading = true;
|
|
92
|
+
try {
|
|
93
|
+
for (const [path, url] of entries) {
|
|
94
|
+
let response;
|
|
95
|
+
try {
|
|
96
|
+
signal.throwIfAborted();
|
|
97
|
+
response = await send(url, {
|
|
98
|
+
method: "PUT",
|
|
99
|
+
redirect: "error",
|
|
100
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(3e4)]),
|
|
101
|
+
headers: {
|
|
102
|
+
"Content-Type": "application/octet-stream",
|
|
103
|
+
"Cache-Control": "private, no-store",
|
|
104
|
+
"x-goog-if-generation-match": "0"
|
|
105
|
+
},
|
|
106
|
+
body: new Uint8Array(files.get(path))
|
|
107
|
+
});
|
|
108
|
+
await response.body?.cancel();
|
|
109
|
+
} catch {
|
|
110
|
+
throw new StageError(502, "upload_failed", "Signed artifact upload failed");
|
|
111
|
+
}
|
|
112
|
+
if (!response.ok && response.status !== 412)
|
|
113
|
+
throw new StageError(
|
|
114
|
+
response.status === 403 ? 403 : 502,
|
|
115
|
+
"upload_failed",
|
|
116
|
+
"Signed artifact upload failed"
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return { snapshot, artifacts: inventory(files) };
|
|
120
|
+
} finally {
|
|
121
|
+
this.uploading = false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export {
|
|
126
|
+
SignedArtifactSnapshots
|
|
127
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ReplayRequest, ActionTarget, JsonObject, OpenViewResponse, SetStepRequest, ToolResult } from "@open-qa/qa-engine/protocol";
|
|
2
|
+
import type { z } from "zod";
|
|
3
|
+
import type { PixelCoordinates } from "./page-pixels.js";
|
|
4
|
+
import type { StageDrivers } from "./drivers.js";
|
|
5
|
+
import type { ActorSession } from "./mcp.js";
|
|
6
|
+
export interface ToolImage {
|
|
7
|
+
data: string;
|
|
8
|
+
mimeType: "image/png" | "image/jpeg" | "image/webp";
|
|
9
|
+
}
|
|
10
|
+
export interface ViewObservation {
|
|
11
|
+
shot: string;
|
|
12
|
+
pixels?: Uint8Array;
|
|
13
|
+
thumbnail: Uint8Array;
|
|
14
|
+
fingerprint: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ToolContext {
|
|
17
|
+
readonly replay?: ReplayRequest["commands"][number];
|
|
18
|
+
readonly actor: string;
|
|
19
|
+
readonly view?: string;
|
|
20
|
+
readonly step?: string;
|
|
21
|
+
readonly level?: SetStepRequest["level"];
|
|
22
|
+
readonly signal?: AbortSignal;
|
|
23
|
+
readonly emit?: ActorSession["emit"];
|
|
24
|
+
}
|
|
25
|
+
export interface ToolOutput {
|
|
26
|
+
data: JsonObject;
|
|
27
|
+
evidence?: JsonObject;
|
|
28
|
+
image?: ToolImage;
|
|
29
|
+
target?: ActionTarget;
|
|
30
|
+
error?: {
|
|
31
|
+
code: string;
|
|
32
|
+
message: string;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export type GatewayResult = ToolResult & {
|
|
36
|
+
image?: ToolImage;
|
|
37
|
+
};
|
|
38
|
+
export interface ToolCommand<Input extends JsonObject = JsonObject> {
|
|
39
|
+
name: string;
|
|
40
|
+
description: string;
|
|
41
|
+
scope: "view" | "actor";
|
|
42
|
+
allowRendered?: boolean;
|
|
43
|
+
/** Additional view-ID arguments that share ownership checks and serialization. */
|
|
44
|
+
viewArgs?: readonly string[];
|
|
45
|
+
inputSchema: z.ZodType<Input>;
|
|
46
|
+
captureTarget?(input: Input, context: ToolContext): Promise<ActionTarget | undefined>;
|
|
47
|
+
execute(input: Input, context: ToolContext): Promise<ToolOutput>;
|
|
48
|
+
}
|
|
49
|
+
export interface ViewDriver {
|
|
50
|
+
list(): readonly OpenViewResponse[];
|
|
51
|
+
observe(view: string, context: ToolContext): Promise<ViewObservation>;
|
|
52
|
+
snapshot(view: string, context: ToolContext): Promise<string>;
|
|
53
|
+
screenshot(view: string, context: ToolContext): Promise<ToolImage & {
|
|
54
|
+
coordinates?: PixelCoordinates;
|
|
55
|
+
}>;
|
|
56
|
+
text(view: string, context: ToolContext): Promise<string>;
|
|
57
|
+
}
|
|
58
|
+
export interface SurfaceAdapter {
|
|
59
|
+
name: string;
|
|
60
|
+
tools: readonly ToolCommand[];
|
|
61
|
+
views?: ViewDriver;
|
|
62
|
+
expectPollIntervalMs?: number;
|
|
63
|
+
retryableExpectError?: (error: unknown) => boolean;
|
|
64
|
+
expect?: StageDrivers["expect"];
|
|
65
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import type { JsonObject, ExpectResult } from "@open-qa/qa-engine/protocol";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import type { ToolOutput } from "./surface-adapter.js";
|
|
5
|
+
export type Fetcher = (url: string, init?: RequestInit) => Promise<Response>;
|
|
6
|
+
export declare const systemTimeoutMs = 10000;
|
|
7
|
+
export declare const systemLimitBytes: number;
|
|
8
|
+
export declare const conditionContext: {
|
|
9
|
+
view: z.ZodOptional<z.ZodString>;
|
|
10
|
+
within: z.ZodOptional<z.ZodString>;
|
|
11
|
+
};
|
|
12
|
+
export declare const equal: typeof isDeepStrictEqual;
|
|
13
|
+
declare const failureReasons: {
|
|
14
|
+
readonly result_too_large: "System result exceeds 1 MiB";
|
|
15
|
+
readonly rate_limited: "System backend rate limit exceeded (HTTP 429)";
|
|
16
|
+
readonly backend_failed: "System backend request failed";
|
|
17
|
+
readonly invalid_json: "Response is not valid JSON";
|
|
18
|
+
readonly url_forbidden: "HTTP URL is outside the allowed origins";
|
|
19
|
+
readonly row_limit: "DB result exceeds 1000 rows; add LIMIT";
|
|
20
|
+
};
|
|
21
|
+
export declare class SystemReadError extends Error {
|
|
22
|
+
readonly code: keyof typeof failureReasons;
|
|
23
|
+
constructor(code: keyof typeof failureReasons);
|
|
24
|
+
}
|
|
25
|
+
export declare function systemFailure(error: unknown): ExpectResult | undefined;
|
|
26
|
+
export declare function parseJsonBody(body: string): unknown;
|
|
27
|
+
export declare function fullEvidence(data: JsonObject, secrets?: readonly string[]): JsonObject;
|
|
28
|
+
export declare function systemOutput(data: JsonObject, secrets?: readonly string[]): ToolOutput;
|
|
29
|
+
export declare function checked(passed: boolean, evidence: JsonObject): ExpectResult;
|
|
30
|
+
export declare function invalidSystemExpectation(): ExpectResult;
|
|
31
|
+
export declare function requestSignal(signal?: AbortSignal): AbortSignal;
|
|
32
|
+
export declare function readBody(response: Response): Promise<string>;
|
|
33
|
+
export declare function readJson(response: Response): Promise<JsonObject[string]>;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { redactExpectEvidence } from "./expect-evidence.js";
|
|
4
|
+
import { fitsJson } from "./tool-limits.js";
|
|
5
|
+
const systemTimeoutMs = 1e4;
|
|
6
|
+
const systemLimitBytes = 1024 * 1024;
|
|
7
|
+
const conditionContext = { view: z.string().optional(), within: z.string().optional() };
|
|
8
|
+
const equal = isDeepStrictEqual;
|
|
9
|
+
const failureReasons = {
|
|
10
|
+
result_too_large: "System result exceeds 1 MiB",
|
|
11
|
+
rate_limited: "System backend rate limit exceeded (HTTP 429)",
|
|
12
|
+
backend_failed: "System backend request failed",
|
|
13
|
+
invalid_json: "Response is not valid JSON",
|
|
14
|
+
url_forbidden: "HTTP URL is outside the allowed origins",
|
|
15
|
+
row_limit: "DB result exceeds 1000 rows; add LIMIT"
|
|
16
|
+
};
|
|
17
|
+
class SystemReadError extends Error {
|
|
18
|
+
constructor(code) {
|
|
19
|
+
super(failureReasons[code]);
|
|
20
|
+
this.code = code;
|
|
21
|
+
}
|
|
22
|
+
code;
|
|
23
|
+
}
|
|
24
|
+
function systemFailure(error) {
|
|
25
|
+
if (!(error instanceof SystemReadError)) return void 0;
|
|
26
|
+
return {
|
|
27
|
+
passed: false,
|
|
28
|
+
reason: failureReasons[error.code],
|
|
29
|
+
evidence: {
|
|
30
|
+
failure: error.code,
|
|
31
|
+
...!["backend_failed", "invalid_json"].includes(error.code) && { invalid: true }
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function parseJsonBody(body) {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(body);
|
|
38
|
+
} catch {
|
|
39
|
+
throw new SystemReadError("invalid_json");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function fullEvidence(data, secrets = []) {
|
|
43
|
+
const safe = redactExpectEvidence(data, secrets, { full: true });
|
|
44
|
+
if (!fitsJson(safe, systemLimitBytes)) throw new SystemReadError("result_too_large");
|
|
45
|
+
return safe;
|
|
46
|
+
}
|
|
47
|
+
function systemOutput(data, secrets = []) {
|
|
48
|
+
const evidence = fullEvidence(data, secrets);
|
|
49
|
+
let truncated = false;
|
|
50
|
+
const preview = (value) => {
|
|
51
|
+
if (typeof value === "string") {
|
|
52
|
+
truncated ||= value.length > 1e3;
|
|
53
|
+
return value.slice(0, 1e3);
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(value)) {
|
|
56
|
+
truncated ||= value.length > 20;
|
|
57
|
+
return value.slice(0, 20).map(preview);
|
|
58
|
+
}
|
|
59
|
+
if (value !== null && typeof value === "object")
|
|
60
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, preview(child)]));
|
|
61
|
+
return value;
|
|
62
|
+
};
|
|
63
|
+
const dataPreview = preview(evidence);
|
|
64
|
+
return {
|
|
65
|
+
evidence,
|
|
66
|
+
data: fitsJson(dataPreview, 48 * 1024) ? { ...dataPreview, truncated } : { text: JSON.stringify(dataPreview).slice(0, 12e3), truncated: true }
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function checked(passed, evidence) {
|
|
70
|
+
return {
|
|
71
|
+
passed,
|
|
72
|
+
...!passed && { reason: "System expectation did not match" },
|
|
73
|
+
evidence: fullEvidence(evidence)
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function invalidSystemExpectation() {
|
|
77
|
+
return { passed: false, reason: "Invalid system expectation", evidence: { invalid: true } };
|
|
78
|
+
}
|
|
79
|
+
function requestSignal(signal) {
|
|
80
|
+
return AbortSignal.any([...signal ? [signal] : [], AbortSignal.timeout(systemTimeoutMs)]);
|
|
81
|
+
}
|
|
82
|
+
async function readBody(response) {
|
|
83
|
+
const reader = response.body?.getReader();
|
|
84
|
+
if (!reader) return "";
|
|
85
|
+
const chunks = [];
|
|
86
|
+
let bytes = 0;
|
|
87
|
+
try {
|
|
88
|
+
while (true) {
|
|
89
|
+
const part = await reader.read();
|
|
90
|
+
if (part.done) break;
|
|
91
|
+
bytes += part.value.byteLength;
|
|
92
|
+
if (bytes > systemLimitBytes) throw new SystemReadError("result_too_large");
|
|
93
|
+
chunks.push(part.value);
|
|
94
|
+
}
|
|
95
|
+
} finally {
|
|
96
|
+
await reader.cancel();
|
|
97
|
+
reader.releaseLock();
|
|
98
|
+
}
|
|
99
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
100
|
+
}
|
|
101
|
+
async function readJson(response) {
|
|
102
|
+
if (!response.ok) {
|
|
103
|
+
await response.body?.cancel();
|
|
104
|
+
throw new SystemReadError(response.status === 429 ? "rate_limited" : "backend_failed");
|
|
105
|
+
}
|
|
106
|
+
return z.json().parse(parseJsonBody(await readBody(response)));
|
|
107
|
+
}
|
|
108
|
+
export {
|
|
109
|
+
SystemReadError,
|
|
110
|
+
checked,
|
|
111
|
+
conditionContext,
|
|
112
|
+
equal,
|
|
113
|
+
fullEvidence,
|
|
114
|
+
invalidSystemExpectation,
|
|
115
|
+
parseJsonBody,
|
|
116
|
+
readBody,
|
|
117
|
+
readJson,
|
|
118
|
+
requestSignal,
|
|
119
|
+
systemFailure,
|
|
120
|
+
systemLimitBytes,
|
|
121
|
+
systemOutput,
|
|
122
|
+
systemTimeoutMs
|
|
123
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { JsonObject } from "@open-qa/qa-engine/protocol";
|
|
2
|
+
import type { SurfaceAdapter } from "./surface-adapter.js";
|
|
3
|
+
export declare function assertSelect(sql: string): void;
|
|
4
|
+
export type DbQuery = (sql: string, signal?: AbortSignal) => Promise<JsonObject[]>;
|
|
5
|
+
export declare function libsqlQuery(config: {
|
|
6
|
+
url: string;
|
|
7
|
+
token: string;
|
|
8
|
+
}): DbQuery;
|
|
9
|
+
export declare function dbSurface(target: "dev" | "staging" | "prod", query: DbQuery): SurfaceAdapter;
|
package/src/system-db.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { createClient } from "@libsql/client/http";
|
|
2
|
+
import parse from "sqlite-parser";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import {
|
|
5
|
+
checked,
|
|
6
|
+
conditionContext,
|
|
7
|
+
equal,
|
|
8
|
+
invalidSystemExpectation,
|
|
9
|
+
requestSignal,
|
|
10
|
+
systemOutput,
|
|
11
|
+
SystemReadError
|
|
12
|
+
} from "./system-common.js";
|
|
13
|
+
const input = z.strictObject({ sql: z.string().min(1).max(16e3) });
|
|
14
|
+
const astSchema = z.object({
|
|
15
|
+
type: z.literal("statement"),
|
|
16
|
+
variant: z.literal("list"),
|
|
17
|
+
statement: z.array(z.record(z.string(), z.unknown())).length(1)
|
|
18
|
+
});
|
|
19
|
+
const safeFunctions = /* @__PURE__ */ new Set([
|
|
20
|
+
"count",
|
|
21
|
+
"sum",
|
|
22
|
+
"avg",
|
|
23
|
+
"min",
|
|
24
|
+
"max",
|
|
25
|
+
"total",
|
|
26
|
+
"coalesce",
|
|
27
|
+
"ifnull",
|
|
28
|
+
"nullif",
|
|
29
|
+
"lower",
|
|
30
|
+
"upper",
|
|
31
|
+
"length",
|
|
32
|
+
"substr",
|
|
33
|
+
"substring",
|
|
34
|
+
"trim",
|
|
35
|
+
"round",
|
|
36
|
+
"abs",
|
|
37
|
+
"date",
|
|
38
|
+
"datetime",
|
|
39
|
+
"strftime",
|
|
40
|
+
"json_extract",
|
|
41
|
+
"json_array_length",
|
|
42
|
+
"json_valid",
|
|
43
|
+
"group_concat",
|
|
44
|
+
"hex",
|
|
45
|
+
"typeof"
|
|
46
|
+
]);
|
|
47
|
+
function assertSelect(sql) {
|
|
48
|
+
input.parse({ sql });
|
|
49
|
+
const ast = astSchema.parse(parse(sql));
|
|
50
|
+
const visit = (node, ctes = []) => {
|
|
51
|
+
if (node === null || typeof node !== "object") return;
|
|
52
|
+
if (Array.isArray(node)) {
|
|
53
|
+
node.forEach((child) => visit(child, ctes));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const item = node;
|
|
57
|
+
if (item.type === "statement" && !["select", "compound"].includes(String(item.variant)))
|
|
58
|
+
throw new Error("Only SELECT statements are allowed");
|
|
59
|
+
if (item.type === "expression" && item.variant === "recursive")
|
|
60
|
+
throw new Error("Recursive queries are not allowed");
|
|
61
|
+
if (item.type === "identifier" && item.variant === "table" && typeof item.name === "string" && ctes.includes(item.name.toLowerCase()))
|
|
62
|
+
throw new Error("Recursive queries are not allowed");
|
|
63
|
+
if (item.type === "expression" && item.variant === "common") {
|
|
64
|
+
const { name } = z.object({ name: z.string() }).parse(item.target);
|
|
65
|
+
visit(item.expression, [...ctes, name.toLowerCase()]);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (item.type === "function") {
|
|
69
|
+
const name = z.object({ name: z.string() }).parse(item.name).name;
|
|
70
|
+
if (!safeFunctions.has(name.toLowerCase())) throw new Error("SQL function is not allowed");
|
|
71
|
+
}
|
|
72
|
+
Object.values(item).forEach((child) => visit(child, ctes));
|
|
73
|
+
};
|
|
74
|
+
visit(ast.statement[0]);
|
|
75
|
+
}
|
|
76
|
+
function libsqlQuery(config) {
|
|
77
|
+
return async (sql, signal) => {
|
|
78
|
+
const client = createClient({
|
|
79
|
+
url: config.url,
|
|
80
|
+
authToken: config.token,
|
|
81
|
+
intMode: "bigint",
|
|
82
|
+
fetch: (request, init) => fetch(request, { ...init, signal: requestSignal(signal) })
|
|
83
|
+
});
|
|
84
|
+
try {
|
|
85
|
+
const [result] = await client.batch([sql], "read");
|
|
86
|
+
if (result.rows.length > 1e3) throw new SystemReadError("row_limit");
|
|
87
|
+
return result.rows.map(
|
|
88
|
+
(row) => Object.fromEntries(
|
|
89
|
+
result.columns.map((column) => {
|
|
90
|
+
const value = row[column];
|
|
91
|
+
return [
|
|
92
|
+
column,
|
|
93
|
+
typeof value === "bigint" ? value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value.toString() : value instanceof ArrayBuffer ? Buffer.from(value).toString("base64") : value
|
|
94
|
+
];
|
|
95
|
+
})
|
|
96
|
+
)
|
|
97
|
+
);
|
|
98
|
+
} finally {
|
|
99
|
+
client.close();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function dbSurface(target, query) {
|
|
104
|
+
const read = async (sql, signal) => {
|
|
105
|
+
if (target === "prod") throw new Error("DB surface is unavailable on prod");
|
|
106
|
+
assertSelect(sql);
|
|
107
|
+
signal?.throwIfAborted();
|
|
108
|
+
const rows = await query(sql, signal);
|
|
109
|
+
return { rows, total: rows.length };
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
name: "db",
|
|
113
|
+
tools: [
|
|
114
|
+
{
|
|
115
|
+
name: "db_query",
|
|
116
|
+
description: "Read staging data using a single SELECT",
|
|
117
|
+
scope: "actor",
|
|
118
|
+
inputSchema: input,
|
|
119
|
+
execute: async ({ sql }, context) => systemOutput(await read(String(sql), context.signal))
|
|
120
|
+
}
|
|
121
|
+
],
|
|
122
|
+
expect: async (request, context) => {
|
|
123
|
+
const parsed = z.strictObject({
|
|
124
|
+
...conditionContext,
|
|
125
|
+
type: z.enum(["db.row", "db.count"]),
|
|
126
|
+
sql: input.shape.sql,
|
|
127
|
+
equals: z.union([z.number().int().nonnegative(), z.record(z.string(), z.json())])
|
|
128
|
+
}).safeParse(request.condition);
|
|
129
|
+
if (!parsed.success) return invalidSystemExpectation();
|
|
130
|
+
const { rows, total } = await read(parsed.data.sql, context.signal);
|
|
131
|
+
const expected = parsed.data.equals;
|
|
132
|
+
const passed = typeof expected === "number" ? total === expected : rows.some(
|
|
133
|
+
(row) => Object.entries(expected).every(([key, value]) => equal(row[key], value))
|
|
134
|
+
);
|
|
135
|
+
return checked(passed, { rows, total });
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
export {
|
|
140
|
+
assertSelect,
|
|
141
|
+
dbSurface,
|
|
142
|
+
libsqlQuery
|
|
143
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import {
|
|
3
|
+
checked,
|
|
4
|
+
conditionContext,
|
|
5
|
+
invalidSystemExpectation,
|
|
6
|
+
readJson,
|
|
7
|
+
requestSignal,
|
|
8
|
+
systemOutput,
|
|
9
|
+
fullEvidence
|
|
10
|
+
} from "./system-common.js";
|
|
11
|
+
const input = z.strictObject({
|
|
12
|
+
repo: z.string().regex(/^[a-zA-Z0-9_-][\w.-]*\/[a-zA-Z0-9_-][\w.-]*$/),
|
|
13
|
+
kind: z.enum(["pr", "issue", "check"]),
|
|
14
|
+
number: z.number().int().positive().optional(),
|
|
15
|
+
ref: z.string().regex(/^[a-zA-Z0-9._/-]+$/).refine((value) => value !== "." && value !== "..").optional()
|
|
16
|
+
});
|
|
17
|
+
function githubSurface(config, fetcher = fetch) {
|
|
18
|
+
const read = async (raw, signal) => {
|
|
19
|
+
const args = input.parse(raw);
|
|
20
|
+
if (!config.repos.includes(args.repo)) throw new Error("GitHub repository is not allowed");
|
|
21
|
+
if (args.kind === "check" && !args.ref) throw new Error("Check reads require a commit ref");
|
|
22
|
+
const path = args.kind === "check" ? `commits/${encodeURIComponent(args.ref)}/check-runs?per_page=30` : `${args.kind === "pr" ? "pulls" : "issues"}${args.number ? `/${args.number}` : "?state=all&per_page=30"}`;
|
|
23
|
+
const response = await fetcher(`https://api.github.com/repos/${args.repo}/${path}`, {
|
|
24
|
+
method: "GET",
|
|
25
|
+
redirect: "error",
|
|
26
|
+
signal: requestSignal(signal),
|
|
27
|
+
headers: {
|
|
28
|
+
authorization: `Bearer ${config.token}`,
|
|
29
|
+
accept: "application/vnd.github+json",
|
|
30
|
+
"x-github-api-version": "2022-11-28"
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
const data = await readJson(response);
|
|
34
|
+
return fullEvidence(
|
|
35
|
+
{ result: data, hasMore: /rel="next"/.test(response.headers.get("link") ?? "") },
|
|
36
|
+
[config.token]
|
|
37
|
+
);
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
name: "github",
|
|
41
|
+
expectPollIntervalMs: 5e3,
|
|
42
|
+
tools: [
|
|
43
|
+
{
|
|
44
|
+
name: "github_read",
|
|
45
|
+
description: "Read PRs, issues or checks in QA repositories",
|
|
46
|
+
scope: "actor",
|
|
47
|
+
inputSchema: input,
|
|
48
|
+
execute: async (args, context) => systemOutput(await read(args, context.signal))
|
|
49
|
+
}
|
|
50
|
+
],
|
|
51
|
+
expect: async (request, context) => {
|
|
52
|
+
const parsed = z.strictObject({
|
|
53
|
+
...conditionContext,
|
|
54
|
+
type: z.literal("github.pr"),
|
|
55
|
+
repo: input.shape.repo,
|
|
56
|
+
title_contains: z.string().optional(),
|
|
57
|
+
state: z.enum(["open", "closed", "merged"]).optional()
|
|
58
|
+
}).safeParse(request.condition);
|
|
59
|
+
if (!parsed.success) return invalidSystemExpectation();
|
|
60
|
+
const data = await read({ repo: parsed.data.repo, kind: "pr" }, context.signal);
|
|
61
|
+
const prs = z.array(z.object({ title: z.string(), state: z.string(), merged_at: z.string().nullable() })).parse(data.result);
|
|
62
|
+
return checked(
|
|
63
|
+
prs.some(
|
|
64
|
+
(pr) => (!parsed.data.title_contains || pr.title.includes(parsed.data.title_contains)) && (!parsed.data.state || (parsed.data.state === "merged" ? !!pr.merged_at : pr.state === parsed.data.state))
|
|
65
|
+
),
|
|
66
|
+
data
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export {
|
|
72
|
+
githubSurface
|
|
73
|
+
};
|