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

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 (313) hide show
  1. package/LICENSE +204 -0
  2. package/NOTICE +7 -0
  3. package/THIRD_PARTY.md +12 -0
  4. package/THIRD_PARTY_NOTICES.md +11 -0
  5. package/drizzle/0000_qa_core.sql +158 -0
  6. package/drizzle/0001_run_health.sql +3 -0
  7. package/drizzle/0002_bounded_cleanup.sql +5 -0
  8. package/drizzle/0003_step_replay_cache.sql +9 -0
  9. package/drizzle/0004_credential_expiry.sql +1 -0
  10. package/drizzle/0005_server_api.sql +19 -0
  11. package/drizzle/0006_submission_created.sql +3 -0
  12. package/drizzle/0007_findings.sql +19 -0
  13. package/drizzle/0008_classification_labels.sql +14 -0
  14. package/drizzle/0009_job_queue.sql +20 -0
  15. package/drizzle/0010_result_notifications.sql +13 -0
  16. package/drizzle/0011_result_notification_retries.sql +5 -0
  17. package/drizzle/0012_result_notification_flows.sql +44 -0
  18. package/drizzle/0013_flow_quarantine.sql +35 -0
  19. package/drizzle/0014_run_budgets.sql +2 -0
  20. package/drizzle/0015_flow_lifecycle.sql +9 -0
  21. package/drizzle/0016_open_qa_classification.sql +28 -0
  22. package/drizzle/meta/0000_snapshot.json +1002 -0
  23. package/drizzle/meta/0001_snapshot.json +1021 -0
  24. package/drizzle/meta/0002_snapshot.json +1027 -0
  25. package/drizzle/meta/0003_snapshot.json +1081 -0
  26. package/drizzle/meta/0004_snapshot.json +1087 -0
  27. package/drizzle/meta/0005_snapshot.json +1210 -0
  28. package/drizzle/meta/0006_snapshot.json +1244 -0
  29. package/drizzle/meta/0007_snapshot.json +1353 -0
  30. package/drizzle/meta/0008_snapshot.json +1435 -0
  31. package/drizzle/meta/0009_snapshot.json +1587 -0
  32. package/drizzle/meta/0010_snapshot.json +1675 -0
  33. package/drizzle/meta/0011_snapshot.json +1692 -0
  34. package/drizzle/meta/0012_snapshot.json +1818 -0
  35. package/drizzle/meta/0013_snapshot.json +2016 -0
  36. package/drizzle/meta/0014_snapshot.json +2028 -0
  37. package/drizzle/meta/0015_snapshot.json +2064 -0
  38. package/drizzle/meta/0016_snapshot.json +2076 -0
  39. package/drizzle/meta/_journal.json +125 -0
  40. package/package.json +118 -4
  41. package/problem-matcher.json +32 -0
  42. package/src/adapters/db-lease-pool.d.ts +25 -0
  43. package/src/adapters/db-lease-pool.js +293 -0
  44. package/src/adapters/dir-artifact-store.d.ts +9 -0
  45. package/src/adapters/dir-artifact-store.js +64 -0
  46. package/src/adapters/e2b-agent.d.ts +7 -0
  47. package/src/adapters/e2b-agent.js +94 -0
  48. package/src/adapters/e2b-artifacts.d.ts +3 -0
  49. package/src/adapters/e2b-artifacts.js +66 -0
  50. package/src/adapters/e2b-bounded.d.ts +1 -0
  51. package/src/adapters/e2b-bounded.js +19 -0
  52. package/src/adapters/e2b-client.d.ts +33 -0
  53. package/src/adapters/e2b-client.js +114 -0
  54. package/src/adapters/e2b-executor.d.ts +26 -0
  55. package/src/adapters/e2b-executor.js +194 -0
  56. package/src/adapters/e2b-lifetime.d.ts +20 -0
  57. package/src/adapters/e2b-lifetime.js +73 -0
  58. package/src/adapters/e2b-prune.d.ts +13 -0
  59. package/src/adapters/e2b-prune.js +42 -0
  60. package/src/adapters/file-replay-cache.d.ts +14 -0
  61. package/src/adapters/file-replay-cache.js +120 -0
  62. package/src/adapters/file-run-store.d.ts +175 -0
  63. package/src/adapters/file-run-store.js +280 -0
  64. package/src/adapters/fixed-lease-pool.d.ts +10 -0
  65. package/src/adapters/fixed-lease-pool.js +237 -0
  66. package/src/adapters/gcs/artifact-store.d.ts +49 -0
  67. package/src/adapters/gcs/artifact-store.js +247 -0
  68. package/src/adapters/gcs/client.d.ts +22 -0
  69. package/src/adapters/gcs/client.js +106 -0
  70. package/src/adapters/gcs/download.d.ts +9 -0
  71. package/src/adapters/gcs/download.js +43 -0
  72. package/src/adapters/gcs/index.d.ts +8 -0
  73. package/src/adapters/gcs/index.js +23 -0
  74. package/src/adapters/gcs/periodic-flush.d.ts +5 -0
  75. package/src/adapters/gcs/periodic-flush.js +16 -0
  76. package/src/adapters/gcs/pg-catalog.d.ts +16 -0
  77. package/src/adapters/gcs/pg-catalog.js +149 -0
  78. package/src/adapters/gcs/replay-completeness.d.ts +1 -0
  79. package/src/adapters/gcs/replay-completeness.js +65 -0
  80. package/src/adapters/gcs/scan-upload.d.ts +10 -0
  81. package/src/adapters/gcs/scan-upload.js +26 -0
  82. package/src/adapters/index.d.ts +5 -0
  83. package/src/adapters/index.js +12 -0
  84. package/src/adapters/lease-transaction.d.ts +2 -0
  85. package/src/adapters/lease-transaction.js +61 -0
  86. package/src/adapters/local-credential-resolver.d.ts +5 -0
  87. package/src/adapters/local-credential-resolver.js +15 -0
  88. package/src/adapters/local-env.d.ts +1 -0
  89. package/src/adapters/local-env.js +37 -0
  90. package/src/adapters/local-files.d.ts +17 -0
  91. package/src/adapters/local-files.js +150 -0
  92. package/src/adapters/pg-classification-store.d.ts +58 -0
  93. package/src/adapters/pg-classification-store.js +112 -0
  94. package/src/adapters/pg-replay-cache.d.ts +16 -0
  95. package/src/adapters/pg-replay-cache.js +111 -0
  96. package/src/adapters/pg-run-store.d.ts +58 -0
  97. package/src/adapters/pg-run-store.js +399 -0
  98. package/src/adapters/resource-pools.d.ts +2 -0
  99. package/src/adapters/resource-pools.js +28 -0
  100. package/src/adapters/secret-manager-credential-resolver.d.ts +44 -0
  101. package/src/adapters/secret-manager-credential-resolver.js +102 -0
  102. package/src/artifact-scan.d.ts +21 -0
  103. package/src/artifact-scan.js +139 -0
  104. package/src/budget-confirmation.d.ts +23 -0
  105. package/src/budget-confirmation.js +43 -0
  106. package/src/cache-command.d.ts +7 -0
  107. package/src/cache-command.js +107 -0
  108. package/src/classification-command.d.ts +14 -0
  109. package/src/classification-command.js +72 -0
  110. package/src/classification-diff.d.ts +10 -0
  111. package/src/classification-diff.js +47 -0
  112. package/src/classification-model.d.ts +17 -0
  113. package/src/classification-model.js +51 -0
  114. package/src/classification-notifier.d.ts +21 -0
  115. package/src/classification-notifier.js +34 -0
  116. package/src/classify-runs.d.ts +31 -0
  117. package/src/classify-runs.js +138 -0
  118. package/src/cli-program.d.ts +9 -0
  119. package/src/cli-program.js +172 -0
  120. package/src/cli.d.ts +2 -0
  121. package/src/cli.js +12 -0
  122. package/src/commands.d.ts +7 -0
  123. package/src/commands.js +17 -0
  124. package/src/credential-references.d.ts +24 -0
  125. package/src/credential-references.js +33 -0
  126. package/src/db/commands.d.ts +1 -0
  127. package/src/db/commands.js +34 -0
  128. package/src/db/credentials.d.ts +16 -0
  129. package/src/db/credentials.js +73 -0
  130. package/src/db/database.d.ts +12 -0
  131. package/src/db/database.js +135 -0
  132. package/src/db/event-chunks.d.ts +405 -0
  133. package/src/db/event-chunks.js +74 -0
  134. package/src/db/fencing.d.ts +8 -0
  135. package/src/db/fencing.js +16 -0
  136. package/src/db/flow-status.d.ts +41 -0
  137. package/src/db/flow-status.js +208 -0
  138. package/src/db/index.d.ts +12 -0
  139. package/src/db/index.js +24 -0
  140. package/src/db/queries.d.ts +73 -0
  141. package/src/db/queries.js +122 -0
  142. package/src/db/resources.d.ts +14 -0
  143. package/src/db/resources.js +61 -0
  144. package/src/db/schema.d.ts +3532 -0
  145. package/src/db/schema.js +501 -0
  146. package/src/demo-command.d.ts +1 -0
  147. package/src/demo-command.js +50 -0
  148. package/src/doctor-command.d.ts +15 -0
  149. package/src/doctor-command.js +275 -0
  150. package/src/doctor-summary.d.ts +2 -0
  151. package/src/doctor-summary.js +31 -0
  152. package/src/draft-api.d.ts +460 -0
  153. package/src/draft-api.js +333 -0
  154. package/src/draft-command.d.ts +10 -0
  155. package/src/draft-command.js +73 -0
  156. package/src/draft-hooks.d.ts +3 -0
  157. package/src/draft-hooks.js +33 -0
  158. package/src/draft-pages.d.ts +11 -0
  159. package/src/draft-pages.js +82 -0
  160. package/src/engine.d.ts +105 -0
  161. package/src/engine.js +323 -0
  162. package/src/execution-snapshot.d.ts +21 -0
  163. package/src/execution-snapshot.js +141 -0
  164. package/src/flow-check.d.ts +9 -0
  165. package/src/flow-check.js +68 -0
  166. package/src/flow-lifecycle.d.ts +6 -0
  167. package/src/flow-lifecycle.js +61 -0
  168. package/src/flow-lint.d.ts +8 -0
  169. package/src/flow-lint.js +73 -0
  170. package/src/flow-loader.d.ts +219 -0
  171. package/src/flow-loader.js +236 -0
  172. package/src/flow-source.d.ts +2 -0
  173. package/src/flow-source.js +6 -0
  174. package/src/flows-api.d.ts +1 -0
  175. package/src/flows-api.js +12 -0
  176. package/src/heal-notification.d.ts +16 -0
  177. package/src/heal-notification.js +62 -0
  178. package/src/hooks/api.d.ts +29 -0
  179. package/src/hooks/api.js +15 -0
  180. package/src/hooks/consumer.d.ts +18 -0
  181. package/src/hooks/consumer.js +98 -0
  182. package/src/hooks/loader.d.ts +6 -0
  183. package/src/hooks/loader.js +28 -0
  184. package/src/hooks/registry.d.ts +22 -0
  185. package/src/hooks/registry.js +23 -0
  186. package/src/hooks/runner.d.ts +19 -0
  187. package/src/hooks/runner.js +279 -0
  188. package/src/hooks/session-cache.d.ts +16 -0
  189. package/src/hooks/session-cache.js +42 -0
  190. package/src/hooks/session-store.d.ts +20 -0
  191. package/src/hooks/session-store.js +95 -0
  192. package/src/hooks/worker.d.ts +1 -0
  193. package/src/hooks/worker.js +84 -0
  194. package/src/http-stage-client.d.ts +367 -0
  195. package/src/http-stage-client.js +190 -0
  196. package/src/independent-model.d.ts +22 -0
  197. package/src/independent-model.js +215 -0
  198. package/src/lifecycle-command.d.ts +15 -0
  199. package/src/lifecycle-command.js +190 -0
  200. package/src/local-command.d.ts +3 -0
  201. package/src/local-command.js +27 -0
  202. package/src/local-host-executor.d.ts +38 -0
  203. package/src/local-host-executor.js +196 -0
  204. package/src/open-command.d.ts +7 -0
  205. package/src/open-command.js +39 -0
  206. package/src/operations-api.d.ts +2 -0
  207. package/src/operations-api.js +6 -0
  208. package/src/personas.d.ts +2 -0
  209. package/src/personas.js +61 -0
  210. package/src/program-runner.d.ts +3 -0
  211. package/src/program-runner.js +263 -0
  212. package/src/program-sandbox.py +75 -0
  213. package/src/program-scratch.d.ts +2 -0
  214. package/src/program-scratch.js +48 -0
  215. package/src/program-worker.mjs +101 -0
  216. package/src/public-id.d.ts +2 -0
  217. package/src/public-id.js +5 -0
  218. package/src/public-report-url.d.ts +1 -0
  219. package/src/public-report-url.js +18 -0
  220. package/src/publication-check.d.ts +1 -0
  221. package/src/publication-check.js +31 -0
  222. package/src/quarantine-command.d.ts +9 -0
  223. package/src/quarantine-command.js +69 -0
  224. package/src/remote-command.d.ts +30 -0
  225. package/src/remote-command.js +156 -0
  226. package/src/replay-image.d.ts +1 -0
  227. package/src/replay-image.js +35 -0
  228. package/src/report/assets.d.ts +1 -0
  229. package/src/report/assets.js +5 -0
  230. package/src/report/browser.css +414 -0
  231. package/src/report/browser.d.ts +1 -0
  232. package/src/report/browser.js +219 -0
  233. package/src/report/data.d.ts +1 -0
  234. package/src/report/data.js +4 -0
  235. package/src/report/generate.d.ts +1 -0
  236. package/src/report/generate.js +54 -0
  237. package/src/report/load.d.ts +870 -0
  238. package/src/report/load.js +139 -0
  239. package/src/report/resource-table.d.ts +2 -0
  240. package/src/report/resource-table.js +4 -0
  241. package/src/report/status-icon.d.ts +2 -0
  242. package/src/report/status-icon.js +20 -0
  243. package/src/report/style.css +413 -0
  244. package/src/result-notifier.d.ts +121 -0
  245. package/src/result-notifier.js +230 -0
  246. package/src/result-transports.d.ts +12 -0
  247. package/src/result-transports.js +150 -0
  248. package/src/run-command.d.ts +32 -0
  249. package/src/run-command.js +493 -0
  250. package/src/run-setup-error.d.ts +11 -0
  251. package/src/run-setup-error.js +18 -0
  252. package/src/sandboxes-command.d.ts +9 -0
  253. package/src/sandboxes-command.js +29 -0
  254. package/src/screen-proxy.d.ts +5 -0
  255. package/src/screen-proxy.js +79 -0
  256. package/src/screen-url.d.ts +18 -0
  257. package/src/screen-url.js +54 -0
  258. package/src/server/app.d.ts +29 -0
  259. package/src/server/app.js +350 -0
  260. package/src/server/auth.d.ts +33 -0
  261. package/src/server/auth.js +113 -0
  262. package/src/server/credentials.d.ts +30 -0
  263. package/src/server/credentials.js +77 -0
  264. package/src/server/errors.d.ts +9 -0
  265. package/src/server/errors.js +26 -0
  266. package/src/server/index.d.ts +35 -0
  267. package/src/server/index.js +96 -0
  268. package/src/server/maintenance.d.ts +13 -0
  269. package/src/server/maintenance.js +54 -0
  270. package/src/server/repository.d.ts +534 -0
  271. package/src/server/repository.js +219 -0
  272. package/src/setup-command.d.ts +10 -0
  273. package/src/setup-command.js +52 -0
  274. package/src/stage-environment.d.ts +1 -0
  275. package/src/stage-environment.js +35 -0
  276. package/src/stage-supervisor.mjs +95 -0
  277. package/src/studio-command.d.ts +7 -0
  278. package/src/studio-command.js +47 -0
  279. package/src/studio-control.d.ts +5 -0
  280. package/src/studio-control.js +207 -0
  281. package/src/studio-review.d.ts +24 -0
  282. package/src/studio-review.js +64 -0
  283. package/src/studio-worker.d.ts +1 -0
  284. package/src/studio-worker.js +48 -0
  285. package/src/system-config.d.ts +7 -0
  286. package/src/system-config.js +70 -0
  287. package/src/terminal-reporter.d.ts +13 -0
  288. package/src/terminal-reporter.js +93 -0
  289. package/src/vendor/gmail.d.ts +45 -0
  290. package/src/vendor/gmail.js +193 -0
  291. package/src/watch-command.d.ts +16 -0
  292. package/src/watch-command.js +93 -0
  293. package/src/watch-state.d.ts +4 -0
  294. package/src/watch-state.js +53 -0
  295. package/src/worker/execution-error.d.ts +5 -0
  296. package/src/worker/execution-error.js +10 -0
  297. package/src/worker/execution.d.ts +24 -0
  298. package/src/worker/execution.js +190 -0
  299. package/src/worker/index.d.ts +8 -0
  300. package/src/worker/index.js +40 -0
  301. package/src/worker/prune.d.ts +3 -0
  302. package/src/worker/prune.js +22 -0
  303. package/src/worker/quarantine-notifications.d.ts +8 -0
  304. package/src/worker/quarantine-notifications.js +89 -0
  305. package/src/worker/queue.d.ts +65 -0
  306. package/src/worker/queue.js +438 -0
  307. package/src/worker/result-notifications.d.ts +28 -0
  308. package/src/worker/result-notifications.js +347 -0
  309. package/src/worker/store.d.ts +4 -0
  310. package/src/worker/store.js +46 -0
  311. package/src/worker/worker.d.ts +21 -0
  312. package/src/worker/worker.js +140 -0
  313. package/README.md +0 -3
@@ -0,0 +1,7 @@
1
+ import { type LocalCommand } from "./local-command.js";
2
+ export declare function openCommand(id: string, options: {
3
+ root?: string;
4
+ }, command?: LocalCommand, output?: {
5
+ (...data: any[]): void;
6
+ (message?: any, ...optionalParams: any[]): void;
7
+ }): Promise<number>;
@@ -0,0 +1,39 @@
1
+ import { lstat } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { FileRunStore } from "./adapters/file-run-store.js";
4
+ import { hasCode, runDirectory } from "./adapters/local-files.js";
5
+ import { localCommand } from "./local-command.js";
6
+ async function openCommand(id, options, command = localCommand, output = console.log) {
7
+ const root = resolve(options.root ?? ".qa");
8
+ const run = await new FileRunStore(root).getRun(id);
9
+ if (!run) throw new Error(`Run not found: ${id}`);
10
+ const scan = run.run.metadata?.artifactScan;
11
+ if (scan && typeof scan === "object" && !Array.isArray(scan) && scan.status === "secret-leak")
12
+ throw new Error(
13
+ "Report opening blocked: secret-leak; inspect the run locally and rerun after fixing the leak"
14
+ );
15
+ const directory = runDirectory(root, id);
16
+ let path = directory;
17
+ try {
18
+ const report = join(directory, "report.html");
19
+ const info = await lstat(report);
20
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("Report must be a regular file");
21
+ path = report;
22
+ } catch (error) {
23
+ if (!hasCode(error, "ENOENT")) throw error;
24
+ }
25
+ output(
26
+ path === directory ? `Report not generated yet; opening run directory: ${path}` : `Opening report: ${path}`
27
+ );
28
+ if (process.platform !== "linux" && process.platform !== "darwin")
29
+ throw new Error(`Open this path in your file browser: ${path}`);
30
+ try {
31
+ await command(process.platform === "darwin" ? "open" : "xdg-open", [path]);
32
+ } catch {
33
+ throw new Error(`Cannot open a desktop browser. Open this path manually: ${path}`);
34
+ }
35
+ return 0;
36
+ }
37
+ export {
38
+ openCommand
39
+ };
@@ -0,0 +1,2 @@
1
+ export { setupCommand } from "./setup-command.js";
2
+ export { doctorCommand } from "./doctor-command.js";
@@ -0,0 +1,6 @@
1
+ import { setupCommand } from "./setup-command.js";
2
+ import { doctorCommand } from "./doctor-command.js";
3
+ export {
4
+ doctorCommand,
5
+ setupCommand
6
+ };
@@ -0,0 +1,2 @@
1
+ export declare const BUILTIN_PERSONAS: Readonly<Record<string, string>>;
2
+ export declare function loadPersonas(root: string, names: readonly string[]): Promise<Record<string, string>>;
@@ -0,0 +1,61 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { hasCode } from "./adapters/local-files.js";
5
+ const MAX_PERSONA_BYTES = 16 * 1024;
6
+ const BUILTIN_PERSONAS = {
7
+ default: "Use the product at a normal pace. Follow the current step carefully and describe anything confusing.",
8
+ impatient: "Act like an impatient user. Click an enabled control repeatedly when it seems slow, and refresh when progress appears stuck. Stay within the current step and never repeat destructive or irreversible actions.",
9
+ "multi-tab": "Act like a user who switches between the available views to compare information and check whether updates stay consistent. Use only views and tab tools provided by the stage; do not invent unavailable tools.",
10
+ newcomer: "Act like a first-time user. Read labels and help text, explore the visible navigation, and describe confusing wording. Do not assume prior product knowledge.",
11
+ keyboard: "Operate using only the keyboard through the provided tools: Tab, Shift+Tab, Enter, Space and arrow keys. Describe inaccessible controls instead of switching to mouse clicks."
12
+ };
13
+ async function loadPersonas(root, names) {
14
+ const personas = {};
15
+ for (const name of new Set(names)) {
16
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) throw new Error("Invalid persona name");
17
+ let text;
18
+ try {
19
+ const directory = join(root, "personas");
20
+ const file = join(directory, `${name}.md`);
21
+ if ((await lstat(directory)).isSymbolicLink())
22
+ throw new Error("Persona symlinks are not supported");
23
+ const handle = await open(
24
+ file,
25
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
26
+ );
27
+ try {
28
+ const stat = await handle.stat();
29
+ if (!stat.isFile()) throw new Error("Persona must be a regular file");
30
+ if (stat.size > MAX_PERSONA_BYTES)
31
+ throw new Error(`Persona must not exceed ${MAX_PERSONA_BYTES} bytes`);
32
+ const buffer = Buffer.alloc(MAX_PERSONA_BYTES + 1);
33
+ let bytes = 0;
34
+ while (bytes < buffer.length) {
35
+ const { bytesRead } = await handle.read(buffer, bytes, buffer.length - bytes);
36
+ if (bytesRead === 0) break;
37
+ bytes += bytesRead;
38
+ }
39
+ if (bytes > MAX_PERSONA_BYTES)
40
+ throw new Error(`Persona must not exceed ${MAX_PERSONA_BYTES} bytes`);
41
+ text = buffer.subarray(0, bytes).toString("utf8");
42
+ } finally {
43
+ await handle.close();
44
+ }
45
+ } catch (error) {
46
+ if (hasCode(error, "ELOOP"))
47
+ throw new Error("Persona symlinks are not supported", { cause: error });
48
+ if (!hasCode(error, "ENOENT")) throw error;
49
+ if (!Object.hasOwn(BUILTIN_PERSONAS, name))
50
+ throw new Error(`Unknown persona: ${name}`, { cause: error });
51
+ text = BUILTIN_PERSONAS[name];
52
+ }
53
+ if (!text.trim()) throw new Error(`Persona ${name} is empty`);
54
+ personas[name] = text.trim();
55
+ }
56
+ return personas;
57
+ }
58
+ export {
59
+ BUILTIN_PERSONAS,
60
+ loadPersonas
61
+ };
@@ -0,0 +1,3 @@
1
+ import type { ProgramContext } from "@open-qa/qa-engine";
2
+ export declare const DEFAULT_PROGRAM_MINUTES = 15;
3
+ export declare function runProgram(source: string, context: ProgramContext, timeoutMs?: number): Promise<void>;
@@ -0,0 +1,263 @@
1
+ import enginePackage from "@open-qa/qa-engine/package.json" with { type: "json" };
2
+ import { spawn } from "node:child_process";
3
+ import { fileURLToPath } from "node:url";
4
+ import ts from "typescript";
5
+ import { z } from "zod";
6
+ import { jsonObjectSchema } from "@open-qa/qa-engine/protocol";
7
+ import { createProgramScratch, removeProgramScratch } from "./program-scratch.js";
8
+ const DEFAULT_PROGRAM_MINUTES = 15;
9
+ const maxLineBytes = 1024 * 1024;
10
+ const maxStringLength = 64 * 1024;
11
+ const maxInflightCalls = 128;
12
+ const maxPendingWriteBytes = 8 * 1024 * 1024;
13
+ const name = z.string().min(1).max(128);
14
+ const id = z.number().int().positive().safe();
15
+ const call = z.discriminatedUnion("method", [
16
+ z.object({
17
+ type: z.literal("call"),
18
+ id,
19
+ method: z.literal("tool"),
20
+ actor: name,
21
+ tool: name,
22
+ args: jsonObjectSchema
23
+ }).strict(),
24
+ z.object({
25
+ type: z.literal("call"),
26
+ id,
27
+ method: z.literal("do"),
28
+ actor: name,
29
+ instruction: z.string().max(maxStringLength)
30
+ }).strict(),
31
+ z.object({
32
+ type: z.literal("call"),
33
+ id,
34
+ method: z.literal("expect"),
35
+ surface: name,
36
+ name,
37
+ params: jsonObjectSchema
38
+ }).strict(),
39
+ z.object({
40
+ type: z.literal("call"),
41
+ id,
42
+ method: z.literal("together"),
43
+ calls: z.array(z.object({ actor: name, tool: name, args: jsonObjectSchema }).strict()).min(1).max(32)
44
+ }).strict()
45
+ ]);
46
+ const messageSchema = z.union([
47
+ call,
48
+ z.object({ type: z.literal("ready") }).strict(),
49
+ z.object({
50
+ type: z.literal("done"),
51
+ error: z.string().max(2048).optional(),
52
+ callId: id.optional()
53
+ }).strict()
54
+ ]);
55
+ async function runProgram(source, context, timeoutMs = DEFAULT_PROGRAM_MINUTES * 6e4) {
56
+ const [major, minor] = process.versions.node.split(".").map(Number);
57
+ if (major < 22 || major === 22 && minor < 13)
58
+ throw new Error(`Program flows require Node.js 22.13 or newer; found ${process.versions.node}`);
59
+ if (process.platform !== "linux") throw new Error("Program flows require Linux with seccomp");
60
+ context.signal.throwIfAborted();
61
+ const code = ts.transpileModule(source, {
62
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
63
+ }).outputText;
64
+ const directory = await createProgramScratch();
65
+ try {
66
+ context.signal.throwIfAborted();
67
+ await execute(
68
+ code,
69
+ directory,
70
+ context,
71
+ AbortSignal.any([context.signal, AbortSignal.timeout(timeoutMs)])
72
+ );
73
+ } finally {
74
+ await removeProgramScratch(directory);
75
+ }
76
+ }
77
+ async function execute(code, directory, context, signal) {
78
+ const worker = fileURLToPath(new URL("./program-worker.mjs", import.meta.url));
79
+ const child = spawn(
80
+ "/usr/bin/python3",
81
+ [
82
+ "-I",
83
+ "-S",
84
+ fileURLToPath(new URL("./program-sandbox.py", import.meta.url)),
85
+ String(process.pid),
86
+ process.execPath,
87
+ "--permission",
88
+ "--no-experimental-sqlite",
89
+ "--max-old-space-size=256",
90
+ `--allow-fs-read=${worker}`,
91
+ `--allow-fs-read=${directory}`,
92
+ `--allow-fs-write=${directory}`,
93
+ worker
94
+ ],
95
+ {
96
+ cwd: directory,
97
+ env: { LANG: "C.UTF-8", TZ: "UTC" },
98
+ stdio: ["pipe", "ignore", "pipe", "pipe"]
99
+ }
100
+ );
101
+ const actors = Object.keys(context).filter(
102
+ (key) => !["expect", "together", "signal"].includes(key)
103
+ );
104
+ const expectations = Object.fromEntries(
105
+ Object.entries(context.expect).map(([surface, methods]) => [surface, Object.keys(methods)])
106
+ );
107
+ const errors = /* @__PURE__ */ new Map();
108
+ const seen = /* @__PURE__ */ new Set();
109
+ let done = false;
110
+ let failure;
111
+ let abortTimer;
112
+ let stderr = "";
113
+ let ready = false;
114
+ let inflight = 0;
115
+ child.stderr.on("data", (data) => {
116
+ if (!ready) stderr = (stderr + data.toString()).slice(0, 2048);
117
+ });
118
+ function stop(error) {
119
+ if (done) return;
120
+ done = true;
121
+ failure ??= error;
122
+ child.kill("SIGKILL");
123
+ }
124
+ function send(message) {
125
+ if (done) return;
126
+ try {
127
+ const line = JSON.stringify(message) + "\n";
128
+ if (child.stdin.writableLength + Buffer.byteLength(line) > maxPendingWriteBytes) {
129
+ stop(new Error("Program worker is not reading replies (8 MiB pending write limit)"));
130
+ return;
131
+ }
132
+ child.stdin.write(line, (error) => {
133
+ if (error) stop(new Error("Program worker pipe disconnected"));
134
+ });
135
+ } catch {
136
+ stop(new Error("Program worker reply could not be serialized"));
137
+ }
138
+ }
139
+ child.stdin.on("error", () => stop(new Error("Program worker pipe disconnected")));
140
+ const abort = () => {
141
+ send({ type: "abort" });
142
+ failure = signal.reason ?? new Error("Program flow canceled");
143
+ abortTimer = setTimeout(() => stop(failure), 50);
144
+ };
145
+ const exited = new Promise((resolve, reject) => {
146
+ child.once("error", (error) => {
147
+ failure = new Error(`Program worker could not start: ${error.message}`);
148
+ });
149
+ child.once("close", (code2, exitSignal) => {
150
+ if (!done)
151
+ failure ??= new Error(
152
+ `Program worker exited unexpectedly (${exitSignal ?? code2})${!ready && stderr ? `: ${stderr.trim()}` : ""}`
153
+ );
154
+ if (failure !== void 0) reject(failure);
155
+ else resolve();
156
+ });
157
+ });
158
+ const invalid = () => stop(new Error("Invalid program worker IPC message"));
159
+ let partial = Buffer.alloc(0);
160
+ const output = child.stdio[3];
161
+ output.on("end", () => {
162
+ if (partial.length && !done) invalid();
163
+ });
164
+ output.on("error", invalid);
165
+ output.on("data", (chunk) => {
166
+ if (done) return;
167
+ let offset = 0;
168
+ while (offset < chunk.length && !done) {
169
+ const newline = chunk.indexOf(10, offset);
170
+ const end = newline < 0 ? chunk.length : newline;
171
+ if (partial.length + end - offset > maxLineBytes) return invalid();
172
+ partial = Buffer.concat([partial, chunk.subarray(offset, end)]);
173
+ if (newline < 0) return;
174
+ const line = partial;
175
+ partial = Buffer.alloc(0);
176
+ try {
177
+ const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line));
178
+ checkStructure(raw);
179
+ const message = messageSchema.parse(raw);
180
+ receive(message);
181
+ } catch {
182
+ return invalid();
183
+ }
184
+ offset = newline + 1;
185
+ }
186
+ });
187
+ function receive(message) {
188
+ if (message.type === "ready") {
189
+ if (ready) return invalid();
190
+ ready = true;
191
+ send({ type: "start", code, actors, expectations, engineModule: enginePackage.name });
192
+ return;
193
+ }
194
+ if (!ready) return invalid();
195
+ if (message.type === "done") {
196
+ stop(
197
+ message.error === void 0 ? void 0 : errors.get(message.callId ?? 0) ?? new Error(`Program flow failed: ${message.error}`)
198
+ );
199
+ return;
200
+ }
201
+ if (seen.has(message.id)) return invalid();
202
+ if (inflight >= maxInflightCalls) {
203
+ stop(new Error("Program worker exceeded the 128 in-flight call limit"));
204
+ return;
205
+ }
206
+ seen.add(message.id);
207
+ inflight++;
208
+ void (async () => {
209
+ let reply;
210
+ try {
211
+ let value;
212
+ if (message.method === "together") value = await context.together(message.calls);
213
+ else if (message.method === "expect") {
214
+ if (!Object.hasOwn(expectations, message.surface) || !expectations[message.surface].includes(message.name))
215
+ throw new Error("Unknown program expectation");
216
+ const methods = context.expect[message.surface];
217
+ value = await methods[message.name](message.params);
218
+ } else {
219
+ if (!actors.includes(message.actor))
220
+ throw new Error(`Unknown program actor ${message.actor}`);
221
+ value = message.method === "tool" ? await context[message.actor].tool(message.tool, message.args) : await context[message.actor].do(message.instruction);
222
+ }
223
+ reply = { type: "reply", id: message.id, ok: true, value: value ?? null };
224
+ } catch (error) {
225
+ errors.set(message.id, error);
226
+ reply = {
227
+ type: "reply",
228
+ id: message.id,
229
+ ok: false,
230
+ error: error instanceof Error ? error.message : "Program call failed"
231
+ };
232
+ }
233
+ send(reply);
234
+ })().catch(() => stop(new Error("Program worker call failed"))).finally(() => inflight--);
235
+ }
236
+ signal.addEventListener("abort", abort, { once: true });
237
+ if (signal.aborted) abort();
238
+ try {
239
+ await exited;
240
+ } finally {
241
+ clearTimeout(abortTimer);
242
+ signal.removeEventListener("abort", abort);
243
+ child.kill("SIGKILL");
244
+ }
245
+ }
246
+ function checkStructure(value) {
247
+ const stack = [{ value, depth: 0 }];
248
+ while (stack.length) {
249
+ const { value: value2, depth } = stack.pop();
250
+ if (depth > 32 || typeof value2 === "string" && value2.length > maxStringLength)
251
+ throw new Error("Invalid structure");
252
+ if (value2 !== null && typeof value2 === "object") {
253
+ for (const [key, child] of Object.entries(value2)) {
254
+ if (key.length > 128) throw new Error("Invalid key");
255
+ stack.push({ value: child, depth: depth + 1 });
256
+ }
257
+ }
258
+ }
259
+ }
260
+ export {
261
+ DEFAULT_PROGRAM_MINUTES,
262
+ runProgram
263
+ };
@@ -0,0 +1,75 @@
1
+ """Install Linux restrictions before replacing this process with Node."""
2
+
3
+ import ctypes
4
+ import errno
5
+ import os
6
+ import platform
7
+ import resource
8
+ import signal
9
+ import sys
10
+
11
+
12
+ class Filter(ctypes.Structure):
13
+ _fields_ = [("code", ctypes.c_ushort), ("jt", ctypes.c_ubyte),
14
+ ("jf", ctypes.c_ubyte), ("k", ctypes.c_uint)]
15
+
16
+
17
+ class Program(ctypes.Structure):
18
+ _fields_ = [("length", ctypes.c_ushort), ("filters", ctypes.POINTER(Filter))]
19
+
20
+
21
+ def launch():
22
+ architectures = {
23
+ "x86_64": (0xC000003E, [
24
+ 41, 42, 53, 62, 200, 234, 86, 88, 265, 266, 425, 426, 427,
25
+ 101, 310, 311, 434, 424, 129, 297, 165, 166, 272, 308, 155, 161,
26
+ 321, 298, 250, 248, 249, 323, 246, 320, 175, 313, 176, 141,
27
+ ]),
28
+ "aarch64": (0xC00000B7, [
29
+ 198, 203, 199, 129, 130, 131, 36, 37, 425, 426, 427,
30
+ 117, 270, 271, 434, 424, 138, 240, 40, 39, 97, 268, 41, 51,
31
+ 280, 241, 219, 217, 218, 282, 104, 294, 105, 273, 106, 140,
32
+ ]),
33
+ }
34
+ architecture, denied = architectures[platform.machine()]
35
+ resource.setrlimit(resource.RLIMIT_NOFILE, (128, 128))
36
+ resource.setrlimit(resource.RLIMIT_FSIZE, (64 * 1024**2, 64 * 1024**2))
37
+ resource.setrlimit(resource.RLIMIT_AS, (2 * 1024**3, 2 * 1024**3))
38
+ libc = ctypes.CDLL(None, use_errno=True)
39
+
40
+ def prctl(option, argument):
41
+ if libc.prctl(option, argument, 0, 0, 0) != 0:
42
+ raise OSError(ctypes.get_errno(), "Program sandbox setup failed")
43
+
44
+ # Unlike an IPC disconnect handler, this also stops a synchronous infinite loop.
45
+ prctl(1, signal.SIGKILL) # PR_SET_PDEATHSIG
46
+ if os.getppid() != int(sys.argv[1]):
47
+ raise RuntimeError("Program parent exited during sandbox setup")
48
+ prctl(38, 1) # PR_SET_NO_NEW_PRIVS
49
+ instructions = [
50
+ Filter(0x20, 0, 0, 4), # seccomp_data.arch
51
+ Filter(0x15, 1, 0, architecture),
52
+ Filter(0x06, 0, 0, 0x80000000), # kill on an unexpected syscall ABI
53
+ Filter(0x20, 0, 0, 0), # seccomp_data.nr
54
+ ]
55
+ # Deny sockets, signals, links, io_uring, process inspection, setpriority,
56
+ # mount/umount2/unshare/setns/pivot_root/chroot, kernel instrumentation/keys/
57
+ # modules and cross-process memory access. clone/clone3/execve remain available
58
+ # for Node startup/threads; clone namespace flags are not filtered.
59
+ if platform.machine() == "x86_64":
60
+ instructions += [Filter(0x35, 0, 1, 0x40000000), Filter(0x06, 0, 0, 0x80000000)]
61
+ for syscall in denied:
62
+ instructions += [Filter(0x15, 0, 1, syscall), Filter(0x06, 0, 0, 0x50000 | errno.EPERM)]
63
+ instructions.append(Filter(0x06, 0, 0, 0x7FFF0000)) # SECCOMP_RET_ALLOW
64
+ filters = (Filter * len(instructions))(*instructions)
65
+ program = Program(len(instructions), filters)
66
+ if libc.prctl(22, 2, ctypes.byref(program), 0, 0) != 0:
67
+ raise OSError(ctypes.get_errno(), "Program network restrictions unavailable")
68
+ os.execve(sys.argv[2], sys.argv[2:], dict(os.environ))
69
+
70
+
71
+ try:
72
+ launch()
73
+ except Exception as error:
74
+ print("Program sandbox unavailable: Linux x86_64/aarch64, Python 3, rlimits and seccomp are required: " + str(error), file=sys.stderr)
75
+ sys.exit(1)
@@ -0,0 +1,2 @@
1
+ export declare function createProgramScratch(root?: string): Promise<string>;
2
+ export declare function removeProgramScratch(path: string): Promise<void>;
@@ -0,0 +1,48 @@
1
+ import { chmod, lstat, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ const maxAgeMs = 24 * 60 * 6e4;
5
+ async function createProgramScratch(root = join(homedir(), ".cache", "open-qa")) {
6
+ await mkdir(root, { recursive: true, mode: 448 });
7
+ const stat = await lstat(root);
8
+ if (!stat.isDirectory() || stat.uid !== process.getuid())
9
+ throw new Error("Program scratch root must be an owned directory");
10
+ await chmod(root, 448);
11
+ for (const entry of await readdir(root)) {
12
+ const match = /^program-(\d+)-[A-Za-z0-9]+$/.exec(entry);
13
+ if (!match) continue;
14
+ const path = join(root, entry);
15
+ try {
16
+ const stat2 = await lstat(path);
17
+ if (stat2.mtimeMs > Date.now() - maxAgeMs || stat2.uid !== process.getuid()) continue;
18
+ try {
19
+ process.kill(Number(match[1]), 0);
20
+ continue;
21
+ } catch (error) {
22
+ if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) continue;
23
+ }
24
+ await removeProgramScratch(path);
25
+ } catch {
26
+ console.warn("Program stale scratch cleanup failed");
27
+ }
28
+ }
29
+ return mkdtemp(join(root, `program-${process.pid}-`));
30
+ }
31
+ async function removeProgramScratch(path) {
32
+ try {
33
+ await restoreDirectories(path);
34
+ await rm(path, { recursive: true, force: true });
35
+ } catch {
36
+ console.warn("Program scratch cleanup failed");
37
+ }
38
+ }
39
+ async function restoreDirectories(path) {
40
+ const stat = await lstat(path);
41
+ if (!stat.isDirectory()) return;
42
+ await chmod(path, 448);
43
+ for (const entry of await readdir(path)) await restoreDirectories(join(path, entry));
44
+ }
45
+ export {
46
+ createProgramScratch,
47
+ removeProgramScratch
48
+ };
@@ -0,0 +1,101 @@
1
+ import process from "node:process";
2
+ import { Buffer } from "node:buffer";
3
+ import { writeSync } from "node:fs";
4
+ import { createInterface } from "node:readline";
5
+
6
+ const controller = new globalThis.AbortController();
7
+ const pending = new Set();
8
+ const replies = new Map();
9
+ let sequence = 0;
10
+ let started = false;
11
+ let closed = false;
12
+ const pause = new Int32Array(new SharedArrayBuffer(4));
13
+ function send(message) {
14
+ const bytes = Buffer.from(JSON.stringify(message) + "\n");
15
+ let offset = 0;
16
+ // Flush before returning to flow code, which may immediately block the event loop.
17
+ while (offset < bytes.length) {
18
+ try {
19
+ offset += writeSync(3, bytes, offset);
20
+ } catch (error) {
21
+ if (error.code !== "EAGAIN" && error.code !== "EWOULDBLOCK") process.exit(1);
22
+ Atomics.wait(pause, 0, 0, 1);
23
+ }
24
+ }
25
+ }
26
+ process.stdin.once("end", () => process.exit(1));
27
+
28
+ function request(call) {
29
+ if (closed) return Promise.reject(new Error("Program flow has already returned"));
30
+ controller.signal.throwIfAborted();
31
+ const id = ++sequence;
32
+ const promise = new Promise((resolve, reject) => {
33
+ replies.set(id, { resolve, reject });
34
+ send({ type: "call", id, ...call });
35
+ });
36
+ pending.add(promise);
37
+ void promise.catch(() => {}).finally(() => pending.delete(promise));
38
+ return promise;
39
+ }
40
+
41
+ createInterface({ input: process.stdin }).on("line", (line) => {
42
+ const message = JSON.parse(line);
43
+ if (message.type === "abort") {
44
+ controller.abort();
45
+ } else if (message.type === "reply") {
46
+ const reply = replies.get(message.id);
47
+ replies.delete(message.id);
48
+ if (message.ok) reply?.resolve(message.value);
49
+ else {
50
+ const error = new Error(message.error);
51
+ error.callId = message.id;
52
+ reply?.reject(error);
53
+ }
54
+ } else if (message.type === "start" && !started) {
55
+ started = true;
56
+ void run(message);
57
+ }
58
+ });
59
+
60
+ async function run({ code, actors, expectations, engineModule }) {
61
+ const context = Object.assign(Object.create(null), {
62
+ signal: controller.signal,
63
+ together: (calls) => request({ method: "together", calls }),
64
+ expect: Object.create(null),
65
+ });
66
+ for (const actor of actors) {
67
+ context[actor] = {
68
+ tool: (tool, args) => request({ method: "tool", actor, tool, args }),
69
+ do: (instruction) => request({ method: "do", actor, instruction }),
70
+ };
71
+ }
72
+ for (const [surface, names] of Object.entries(expectations)) {
73
+ context.expect[surface] = Object.fromEntries(
74
+ names.map((name) => [name, (params) => request({ method: "expect", surface, name, params })])
75
+ );
76
+ }
77
+ let failure;
78
+ try {
79
+ const module = { exports: {} };
80
+ const require = (name) => {
81
+ if (name !== engineModule) throw new Error("Program imports are disallowed");
82
+ return { defineFlow: (flow) => flow };
83
+ };
84
+ new Function("require", "module", "exports", code)(require, module, module.exports);
85
+ await module.exports.default.run(context);
86
+ } catch (error) {
87
+ failure = {
88
+ error: (error instanceof Error
89
+ ? error.message
90
+ : "Program flow threw a non-Error value"
91
+ ).slice(0, 2048),
92
+ ...(Number.isSafeInteger(error?.callId) ? { callId: error.callId } : {}),
93
+ };
94
+ } finally {
95
+ closed = true;
96
+ await Promise.allSettled(pending);
97
+ }
98
+ send({ type: "done", ...failure });
99
+ }
100
+
101
+ send({ type: "ready" });
@@ -0,0 +1,2 @@
1
+ import { z } from "zod";
2
+ export declare const publicId: z.ZodString;
@@ -0,0 +1,5 @@
1
+ import { z } from "zod";
2
+ const publicId = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/);
3
+ export {
4
+ publicId
5
+ };
@@ -0,0 +1 @@
1
+ export declare function publicReportUrl(value: string | undefined, origins: readonly string[]): string | undefined;
@@ -0,0 +1,18 @@
1
+ function publicReportUrl(value, origins) {
2
+ if (!value) return void 0;
3
+ try {
4
+ const url = new URL(value);
5
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !/^\/[a-z\d/_.-]*$/i.test(url.pathname) || /(?:^|\/)(?:token|tokens|secret|secrets|internal|private|tmp|home|etc|\.ssh|\.env)(?:\/|\.|$)/i.test(
6
+ url.pathname
7
+ ) || !/^[a-z\d-]+(?:\.[a-z\d-]+)+$/i.test(url.hostname) || /(?:^|\.)(?:localhost|local|internal|lan|home|corp|arpa|onion|test|invalid)$|^[\d.]+$/i.test(
8
+ url.hostname
9
+ ) || !origins.includes(url.origin))
10
+ return void 0;
11
+ return url.href;
12
+ } catch {
13
+ return void 0;
14
+ }
15
+ }
16
+ export {
17
+ publicReportUrl
18
+ };
@@ -0,0 +1 @@
1
+ export declare function assertPublishableRuns(root: string, secrets: Iterable<string>): Promise<void>;