@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,94 @@
1
+ async function launchE2bAgent(sandbox, start, signal) {
2
+ signal?.throwIfAborted();
3
+ const chunks = [];
4
+ let size = 0;
5
+ let ended = false;
6
+ let failed = false;
7
+ let wake;
8
+ let terminate = void 0;
9
+ const stop = () => {
10
+ ended = true;
11
+ wake?.();
12
+ };
13
+ const handle = await sandbox.commands.run("node /opt/open-qa-stage/stage.mjs --agent", {
14
+ background: true,
15
+ stdin: true,
16
+ timeoutMs: 0,
17
+ signal,
18
+ envs: { QA_AGENT_CONFIG: JSON.stringify(start) },
19
+ onStdout(chunk) {
20
+ if (ended) return;
21
+ size += chunk.length;
22
+ if (size > 4 * 1048576) {
23
+ failed = true;
24
+ stop();
25
+ void terminate?.().catch(() => {
26
+ });
27
+ } else {
28
+ chunks.push(chunk);
29
+ wake?.();
30
+ }
31
+ },
32
+ // Native stderr is deliberately discarded: SDK/CLI errors may contain credentials.
33
+ onStderr() {
34
+ }
35
+ });
36
+ let closing;
37
+ terminate = () => closing ??= (async () => {
38
+ stop();
39
+ try {
40
+ await handle.closeStdin({ requestTimeoutMs: 5e3 });
41
+ } catch {
42
+ }
43
+ let timer;
44
+ try {
45
+ await Promise.race([
46
+ handle.wait(),
47
+ new Promise((_, reject) => {
48
+ timer = setTimeout(() => reject(new Error("Agent shutdown timed out")), 15e3);
49
+ timer.unref();
50
+ })
51
+ ]);
52
+ } catch {
53
+ await handle.kill();
54
+ } finally {
55
+ clearTimeout(timer);
56
+ }
57
+ })();
58
+ void handle.wait().then(stop, () => {
59
+ failed = true;
60
+ stop();
61
+ });
62
+ if (failed || signal?.aborted) await terminate();
63
+ return {
64
+ output: {
65
+ async *[Symbol.asyncIterator]() {
66
+ while (true) {
67
+ const chunk = chunks.shift();
68
+ if (chunk !== void 0) {
69
+ size -= chunk.length;
70
+ yield chunk;
71
+ continue;
72
+ }
73
+ if (ended) {
74
+ if (failed) throw new Error("Stage agent process failed");
75
+ return;
76
+ }
77
+ await new Promise((resolve) => {
78
+ wake = resolve;
79
+ });
80
+ wake = void 0;
81
+ }
82
+ }
83
+ },
84
+ async send(message) {
85
+ if (ended || message.length > 1048576)
86
+ throw new Error("Stage agent input unavailable or too large");
87
+ await handle.sendStdin(message, { requestTimeoutMs: 1e4 });
88
+ },
89
+ close: terminate
90
+ };
91
+ }
92
+ export {
93
+ launchE2bAgent
94
+ };
@@ -0,0 +1,3 @@
1
+ import type { HttpStageClient } from "../http-stage-client.js";
2
+ import { type QaSandbox } from "./e2b-client.js";
3
+ export declare function attachE2bArtifacts(client: HttpStageClient, sandbox: QaSandbox): HttpStageClient;
@@ -0,0 +1,66 @@
1
+ import { join } from "node:path";
2
+ import { atomicWrite, ensureDirectory } from "./local-files.js";
3
+ import { e2bOperation, exportDirectory } from "./e2b-client.js";
4
+ function attachE2bArtifacts(client, sandbox) {
5
+ const flush = client.flushArtifacts;
6
+ client.flushArtifacts = async (request, signal) => {
7
+ if (request.destination.type === "signed-urls") return flush(request, signal);
8
+ const destination = request.destination.path;
9
+ const deadline = AbortSignal.any([...signal ? [signal] : [], AbortSignal.timeout(3e4)]);
10
+ const response = await flush(
11
+ { destination: { type: "directory", path: exportDirectory } },
12
+ deadline
13
+ );
14
+ let total = 0;
15
+ const names = /* @__PURE__ */ new Set();
16
+ for (const artifact of response.artifacts) {
17
+ const parts = artifact.path.split("/");
18
+ if (!/^(?:manifest\.json|events\.ndjson|(?:views|assets|shots)\/.+)$/.test(artifact.path) || parts.some(
19
+ (part) => !part || part === "." || part === ".." || part.includes("\\") || [...part].some((char) => char.charCodeAt(0) < 32)
20
+ ) || names.has(artifact.path) || !Number.isSafeInteger(artifact.bytes) || artifact.bytes < 0 || artifact.bytes > 64 * 1024 * 1024 || (total += artifact.bytes) > 256 * 1024 * 1024 || names.size >= 1e4)
21
+ throw new Error("QA_E2B_ARTIFACT_INVALID: unsafe artifact path or size");
22
+ names.add(artifact.path);
23
+ }
24
+ await ensureDirectory(destination);
25
+ for (const artifact of response.artifacts) {
26
+ deadline.throwIfAborted();
27
+ const data = await e2bOperation("QA_E2B_ARTIFACT_FAILED", async () => {
28
+ const stream = await sandbox.read(`${exportDirectory}/${artifact.path}`, deadline);
29
+ const reader = stream.getReader();
30
+ const chunks = [];
31
+ let bytes = 0;
32
+ const abort = () => {
33
+ void reader.cancel().catch(() => {
34
+ });
35
+ };
36
+ deadline.addEventListener("abort", abort, { once: true });
37
+ try {
38
+ while (true) {
39
+ deadline.throwIfAborted();
40
+ const chunk = await reader.read();
41
+ deadline.throwIfAborted();
42
+ if (chunk.done) break;
43
+ bytes += chunk.value.byteLength;
44
+ if (bytes > artifact.bytes) throw new Error("Artifact exceeds declared size");
45
+ chunks.push(chunk.value);
46
+ }
47
+ if (bytes !== artifact.bytes) throw new Error("Artifact size mismatch");
48
+ return Buffer.concat(chunks);
49
+ } finally {
50
+ deadline.removeEventListener("abort", abort);
51
+ await reader.cancel();
52
+ reader.releaseLock();
53
+ }
54
+ });
55
+ const directories = artifact.path.split("/").slice(0, -1);
56
+ for (let i = 1; i <= directories.length; i++)
57
+ await ensureDirectory(join(destination, ...directories.slice(0, i)));
58
+ await atomicWrite(join(destination, artifact.path), data);
59
+ }
60
+ return response;
61
+ };
62
+ return client;
63
+ }
64
+ export {
65
+ attachE2bArtifacts
66
+ };
@@ -0,0 +1 @@
1
+ export declare function bounded<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
@@ -0,0 +1,19 @@
1
+ async function bounded(promise, signal) {
2
+ signal.throwIfAborted();
3
+ let abort;
4
+ try {
5
+ return await Promise.race([
6
+ promise,
7
+ new Promise((_, reject) => {
8
+ abort = () => reject(new Error("QA_E2B_TIMEOUT: operation canceled or timed out"));
9
+ signal.addEventListener("abort", abort, { once: true });
10
+ if (signal.aborted) abort();
11
+ })
12
+ ]);
13
+ } finally {
14
+ signal.removeEventListener("abort", abort);
15
+ }
16
+ }
17
+ export {
18
+ bounded
19
+ };
@@ -0,0 +1,33 @@
1
+ import type { AgentStartOptions } from "@open-qa/qa-engine";
2
+ import type { AgentProcess } from "@open-qa/qa-agents";
3
+ export declare const stageDirectory = "/home/user/open-qa-stage";
4
+ export declare const exportDirectory = "/home/user/open-qa-export";
5
+ export interface QaSandbox {
6
+ id: string;
7
+ endpoint: string;
8
+ start(config: Record<string, unknown>, desktop: boolean, signal: AbortSignal): Promise<void>;
9
+ startAgent?(start: AgentStartOptions & {
10
+ runtime?: "pi";
11
+ }, signal?: AbortSignal): Promise<AgentProcess>;
12
+ read(path: string, signal: AbortSignal): Promise<ReadableStream<Uint8Array>>;
13
+ setTimeout(timeoutMs: number): Promise<void>;
14
+ kill(): Promise<void>;
15
+ }
16
+ export interface QaSandboxInfo {
17
+ id: string;
18
+ metadata: Record<string, string>;
19
+ }
20
+ export interface QaE2bClient {
21
+ create(template: string, options: {
22
+ timeoutMs: number;
23
+ metadata: Record<string, string>;
24
+ }): Promise<QaSandbox>;
25
+ list(projectId: string): AsyncIterable<QaSandboxInfo>;
26
+ kill(id: string): Promise<void>;
27
+ }
28
+ export declare function e2bConfig(env: NodeJS.ProcessEnv): {
29
+ apiKey: string;
30
+ imageTag: string;
31
+ };
32
+ export declare function e2bOperation<T>(code: string, action: () => Promise<T>): Promise<T>;
33
+ export declare function createQaE2bClient(apiKey: string): QaE2bClient;
@@ -0,0 +1,114 @@
1
+ import { launchE2bAgent } from "./e2b-agent.js";
2
+ import { AuthenticationError, RateLimitError, Sandbox, ServiceBusyError, TimeoutError } from "e2b";
3
+ import { z } from "zod";
4
+ const stageDirectory = "/home/user/open-qa-stage";
5
+ const exportDirectory = "/home/user/open-qa-export";
6
+ function e2bConfig(env) {
7
+ const result = z.object({
8
+ QA_E2B_API_KEY: z.string().trim().min(1),
9
+ QA_STAGE_IMAGE_TAG: z.string().regex(/^[a-f0-9]{20}$/)
10
+ }).safeParse(env);
11
+ if (!result.success)
12
+ throw new Error("QA_E2B_CONFIG: set QA_E2B_API_KEY and a 20-character QA_STAGE_IMAGE_TAG");
13
+ return { apiKey: result.data.QA_E2B_API_KEY, imageTag: result.data.QA_STAGE_IMAGE_TAG };
14
+ }
15
+ class QaE2bError extends Error {
16
+ }
17
+ async function e2bOperation(code, action) {
18
+ try {
19
+ return await action();
20
+ } catch (error) {
21
+ if (error instanceof QaE2bError) throw error;
22
+ const status = error && typeof error === "object" && "statusCode" in error ? error.statusCode : void 0;
23
+ if (error instanceof AuthenticationError || status === 401 || status === 403)
24
+ throw new QaE2bError("QA_E2B_AUTH_FAILED: QA credentials were rejected");
25
+ if (error instanceof RateLimitError || status === 429)
26
+ throw new QaE2bError("QA_E2B_RATE_LIMITED: provider rate limit reached; wait and retry");
27
+ if (error instanceof ServiceBusyError || status === 503)
28
+ throw new QaE2bError("QA_E2B_UNAVAILABLE: provider temporarily unavailable; wait and retry");
29
+ if (error instanceof TimeoutError)
30
+ throw new QaE2bError("QA_E2B_TIMEOUT: E2B request timed out");
31
+ throw new QaE2bError(`${code}: QA sandbox operation failed`);
32
+ }
33
+ }
34
+ function createQaE2bClient(apiKey) {
35
+ if (!apiKey.trim()) throw new Error("QA_E2B_CONFIG: QA_E2B_API_KEY is required");
36
+ const connection = {
37
+ apiKey,
38
+ domain: "e2b.app",
39
+ apiUrl: "https://api.e2b.app",
40
+ sandboxUrl: "https://sandbox.e2b.app",
41
+ debug: false,
42
+ requestTimeoutMs: 3e4,
43
+ retries: 0
44
+ };
45
+ return {
46
+ create: (template, options) => e2bOperation("QA_E2B_CREATE_FAILED", async () => {
47
+ const sandbox = await Sandbox.create(template, {
48
+ ...connection,
49
+ ...options,
50
+ lifecycle: { onTimeout: "kill" }
51
+ });
52
+ return {
53
+ id: sandbox.sandboxId,
54
+ endpoint: `https://${sandbox.getHost(4101)}`,
55
+ async start(config, desktop, signal) {
56
+ if (desktop) {
57
+ await sandbox.commands.run("Xvfb :99 -screen 0 1280x720x24 -nolisten tcp", {
58
+ background: true,
59
+ timeoutMs: 0,
60
+ signal
61
+ });
62
+ await sandbox.commands.run(
63
+ "for i in $(seq 1 50); do xdpyinfo -display :99 >/dev/null 2>&1 && exit 0; sleep 0.1; done; exit 1",
64
+ { timeoutMs: 1e4, signal }
65
+ );
66
+ await sandbox.commands.run("dbus-run-session -- startxfce4", {
67
+ background: true,
68
+ timeoutMs: 0,
69
+ envs: { DISPLAY: ":99" },
70
+ signal
71
+ });
72
+ }
73
+ await sandbox.commands.run("node /opt/open-qa-stage/stage.mjs", {
74
+ background: true,
75
+ timeoutMs: 0,
76
+ signal,
77
+ envs: {
78
+ QA_STAGE_CONFIG: JSON.stringify(config),
79
+ ...desktop ? { DISPLAY: ":99" } : {}
80
+ }
81
+ });
82
+ },
83
+ startAgent: (start, signal) => launchE2bAgent(sandbox, start, signal),
84
+ read: (path, signal) => sandbox.files.read(path, { format: "stream", signal, requestTimeoutMs: 3e4 }),
85
+ setTimeout: (timeoutMs) => sandbox.setTimeout(timeoutMs, { requestTimeoutMs: 1e4 }),
86
+ async kill() {
87
+ await sandbox.kill({ requestTimeoutMs: 1e4 });
88
+ }
89
+ };
90
+ }),
91
+ async *list(projectId) {
92
+ for (const owner of ["open-qa"]) {
93
+ const pages = Sandbox.list({
94
+ ...connection,
95
+ query: { metadata: { owner, projectId }, state: ["running", "paused"] }
96
+ });
97
+ while (pages.hasNext) {
98
+ const entries = await e2bOperation("QA_E2B_LIST_FAILED", () => pages.nextItems());
99
+ for (const entry of entries) yield { id: entry.sandboxId, metadata: entry.metadata };
100
+ }
101
+ }
102
+ },
103
+ kill: (id) => e2bOperation("QA_E2B_KILL_FAILED", async () => {
104
+ await Sandbox.kill(id, { ...connection, requestTimeoutMs: 1e4 });
105
+ })
106
+ };
107
+ }
108
+ export {
109
+ createQaE2bClient,
110
+ e2bConfig,
111
+ e2bOperation,
112
+ exportDirectory,
113
+ stageDirectory
114
+ };
@@ -0,0 +1,26 @@
1
+ import { RemoteAgentRuntime } from "@open-qa/qa-agents";
2
+ import { z } from "zod";
3
+ import type { Executor, ProvisionSpec, StageClient, StageHandle } from "@open-qa/qa-engine";
4
+ import type { HealthResponse } from "@open-qa/qa-engine/protocol";
5
+ import type { LocalHostExecutorOptions } from "../local-host-executor.js";
6
+ import { type QaE2bClient } from "./e2b-client.js";
7
+ export declare const qaId: z.ZodString;
8
+ export interface E2bExecutorOptions {
9
+ client: QaE2bClient;
10
+ projectId: string;
11
+ batchId: string;
12
+ imageTag: string;
13
+ budgetMs: number;
14
+ stage?: LocalHostExecutorOptions;
15
+ startupTimeoutMs?: number;
16
+ health?: (handle: StageHandle, signal: AbortSignal) => Promise<HealthResponse>;
17
+ }
18
+ export declare class E2bExecutor implements Executor {
19
+ private readonly options;
20
+ private readonly sandboxes;
21
+ private readonly clients;
22
+ constructor(options: E2bExecutorOptions);
23
+ connectStage(handle: StageHandle): StageClient;
24
+ agentRuntime(handle: StageHandle, id: string): RemoteAgentRuntime;
25
+ provision(spec: ProvisionSpec, signal?: AbortSignal): Promise<StageHandle>;
26
+ }
@@ -0,0 +1,194 @@
1
+ import { RemoteAgentRuntime } from "@open-qa/qa-agents";
2
+ import { bounded } from "./e2b-bounded.js";
3
+ import { randomBytes } from "node:crypto";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { z } from "zod";
6
+ import { HttpStageClient } from "../http-stage-client.js";
7
+ import { e2bOperation, stageDirectory } from "./e2b-client.js";
8
+ import { attachE2bArtifacts } from "./e2b-artifacts.js";
9
+ import {
10
+ E2bLifetime,
11
+ E2B_LEASE_MS,
12
+ E2B_FINALIZATION_MS,
13
+ E2B_MAX_LIFETIME_MS
14
+ } from "./e2b-lifetime.js";
15
+ const qaId = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/);
16
+ class E2bExecutor {
17
+ constructor(options) {
18
+ this.options = options;
19
+ const parsed = z.object({
20
+ projectId: qaId,
21
+ batchId: qaId,
22
+ imageTag: z.string().regex(/^[a-f0-9]{20}$/),
23
+ budgetMs: z.number().int().positive().max(E2B_MAX_LIFETIME_MS - E2B_FINALIZATION_MS)
24
+ }).safeParse(options);
25
+ if (!parsed.success)
26
+ throw new Error("QA_E2B_CONFIG: invalid project, batch, image tag or run budget");
27
+ }
28
+ options;
29
+ sandboxes = /* @__PURE__ */ new WeakMap();
30
+ clients = /* @__PURE__ */ new WeakMap();
31
+ connectStage(handle) {
32
+ const client = this.clients.get(handle);
33
+ if (!client) throw new Error("Unknown QA E2B stage handle");
34
+ return client;
35
+ }
36
+ agentRuntime(handle, id) {
37
+ if (id !== "claude-code" && id !== "pi")
38
+ throw new Error(
39
+ "Stage CLI runtime unavailable; supported stage adapters are Claude Code and Pi"
40
+ );
41
+ const sandbox = this.sandboxes.get(handle);
42
+ if (!sandbox?.startAgent) throw new Error("Stage agent transport unavailable");
43
+ return new RemoteAgentRuntime(id, (start, signal) => {
44
+ if (handle.actorTokens[start.actor] !== start.mcp.token || start.mcp.url !== `${handle.endpoint}/mcp`)
45
+ throw new Error("Stage agent requires its own actor MCP capability");
46
+ return sandbox.startAgent(
47
+ {
48
+ ...start,
49
+ ...id === "pi" ? { runtime: "pi" } : {},
50
+ mcp: { ...start.mcp, url: "http://127.0.0.1:4101/mcp" }
51
+ },
52
+ signal
53
+ );
54
+ });
55
+ }
56
+ async provision(spec, signal) {
57
+ signal?.throwIfAborted();
58
+ if (spec.placement !== "e2b") throw new Error("e2b cannot provision another placement");
59
+ if (!qaId.safeParse(spec.runId).success) throw new Error("Invalid QA run ID");
60
+ if (!spec.actors.length || spec.actors.some((actor) => !actor.trim()) || new Set(spec.actors).size !== spec.actors.length)
61
+ throw new Error("At least one unique, nonempty actor is required");
62
+ if ((spec.views?.length ?? 0) > 6) throw new Error("QA E2B supports at most six views");
63
+ const provisionedAt = performance.now();
64
+ const lifetimeMs = this.options.budgetMs + E2B_FINALIZATION_MS;
65
+ const timeoutMs = E2B_LEASE_MS;
66
+ const size = (spec.views?.length ?? 1) <= 1 ? "s" : (spec.views?.length ?? 1) <= 3 ? "m" : "l";
67
+ const template = `open-qa-stage-${size}:${this.options.imageTag}`;
68
+ const startup = AbortSignal.any([
69
+ ...signal ? [signal] : [],
70
+ AbortSignal.timeout(this.options.startupTimeoutMs ?? 6e4)
71
+ ]);
72
+ let sandbox;
73
+ let disposal;
74
+ let lifetime;
75
+ const dispose = () => disposal ??= (async () => {
76
+ signal?.removeEventListener("abort", abort);
77
+ if (lifetime) await lifetime.dispose();
78
+ else if (sandbox)
79
+ await e2bOperation(
80
+ "QA_E2B_KILL_FAILED",
81
+ () => bounded(sandbox.kill(), AbortSignal.timeout(1e4))
82
+ );
83
+ })();
84
+ const abort = () => {
85
+ void dispose().catch(() => {
86
+ });
87
+ };
88
+ const creating = e2bOperation(
89
+ "QA_E2B_CREATE_FAILED",
90
+ () => this.options.client.create(template, {
91
+ timeoutMs,
92
+ metadata: {
93
+ owner: "open-qa",
94
+ schema: "2",
95
+ projectId: this.options.projectId,
96
+ runId: spec.runId,
97
+ batchId: this.options.batchId,
98
+ template,
99
+ expiresAt: String(Date.now() + lifetimeMs)
100
+ }
101
+ })
102
+ );
103
+ void creating.then(async (late) => {
104
+ if (startup.aborted && !sandbox)
105
+ await e2bOperation(
106
+ "QA_E2B_KILL_FAILED",
107
+ () => bounded(late.kill(), AbortSignal.timeout(1e4))
108
+ );
109
+ }).catch(() => {
110
+ });
111
+ try {
112
+ sandbox = await bounded(creating, startup);
113
+ lifetime = new E2bLifetime(
114
+ sandbox,
115
+ Math.max(0, lifetimeMs - (performance.now() - provisionedAt))
116
+ );
117
+ signal?.addEventListener("abort", abort, { once: true });
118
+ startup.throwIfAborted();
119
+ const watchToken = randomBytes(32).toString("hex");
120
+ const conductorToken = randomBytes(32).toString("hex");
121
+ const actorTokens = Object.fromEntries(
122
+ spec.actors.map((actor) => [actor, randomBytes(32).toString("hex")])
123
+ );
124
+ const stage = this.options.stage;
125
+ const desktop = !!stage?.headed || !!spec.views?.some((view) => view.surface === "desktop");
126
+ await bounded(
127
+ e2bOperation(
128
+ "QA_E2B_START_FAILED",
129
+ () => sandbox.start(
130
+ {
131
+ host: "0.0.0.0",
132
+ port: 4101,
133
+ dir: stageDirectory,
134
+ conductorToken,
135
+ watchToken,
136
+ actorTokens,
137
+ headed: desktop,
138
+ page: stage?.page,
139
+ discord: stage?.discord,
140
+ email: stage?.email,
141
+ systems: stage?.systems,
142
+ redactions: stage?.redactions
143
+ },
144
+ desktop,
145
+ startup
146
+ )
147
+ ),
148
+ startup
149
+ );
150
+ const handle = {
151
+ endpoint: sandbox.endpoint,
152
+ ...new URL(sandbox.endpoint).protocol === "https:" ? { screenAccess: { url: `${sandbox.endpoint}/watch`, token: watchToken } } : {},
153
+ placement: "e2b",
154
+ conductorToken,
155
+ actorTokens,
156
+ asyncDispose: dispose
157
+ };
158
+ const client = new HttpStageClient(handle);
159
+ while (true) {
160
+ startup.throwIfAborted();
161
+ try {
162
+ const health = await bounded(
163
+ this.options.health ? this.options.health(handle, startup) : client.health(startup),
164
+ startup
165
+ );
166
+ if (health.status === "ready") break;
167
+ } catch {
168
+ startup.throwIfAborted();
169
+ }
170
+ await delay(100, void 0, { signal: startup });
171
+ }
172
+ startup.throwIfAborted();
173
+ this.sandboxes.set(handle, sandbox);
174
+ this.clients.set(handle, attachE2bArtifacts(client, sandbox));
175
+ return handle;
176
+ } catch (error) {
177
+ const safe = startup.aborted ? new Error(
178
+ "QA_E2B_TIMEOUT: provisioning canceled, stage startup failed or health never became ready"
179
+ ) : error;
180
+ try {
181
+ await dispose();
182
+ } catch (cleanup) {
183
+ throw new AggregateError([safe, cleanup], "Stage provisioning failed and cleanup failed", {
184
+ cause: cleanup
185
+ });
186
+ }
187
+ throw safe;
188
+ }
189
+ }
190
+ }
191
+ export {
192
+ E2bExecutor,
193
+ qaId
194
+ };
@@ -0,0 +1,20 @@
1
+ import { type QaSandbox } from "./e2b-client.js";
2
+ export declare const E2B_LEASE_MS = 120000;
3
+ export declare const E2B_RENEW_MS = 30000;
4
+ export declare const E2B_FINALIZATION_MS: number;
5
+ export declare const E2B_MAX_LIFETIME_MS: number;
6
+ export declare class E2bLifetime {
7
+ private readonly sandbox;
8
+ private readonly limitMs;
9
+ private readonly started;
10
+ private timer?;
11
+ private readonly deadline;
12
+ private renewing?;
13
+ private disposal?;
14
+ private failure?;
15
+ private stopped;
16
+ constructor(sandbox: QaSandbox, limitMs: number);
17
+ private schedule;
18
+ private renew;
19
+ dispose(): Promise<void>;
20
+ }
@@ -0,0 +1,73 @@
1
+ import { e2bOperation } from "./e2b-client.js";
2
+ import { bounded } from "./e2b-bounded.js";
3
+ const E2B_LEASE_MS = 12e4;
4
+ const E2B_RENEW_MS = 3e4;
5
+ const E2B_FINALIZATION_MS = 60 * 6e4;
6
+ const E2B_MAX_LIFETIME_MS = 24 * 60 * 6e4;
7
+ class E2bLifetime {
8
+ constructor(sandbox, limitMs) {
9
+ this.sandbox = sandbox;
10
+ this.limitMs = limitMs;
11
+ this.deadline = setTimeout(() => {
12
+ this.failure = new Error("QA_E2B_TIMEOUT: total sandbox lifetime exceeded");
13
+ void this.dispose().catch(() => {
14
+ });
15
+ }, limitMs);
16
+ this.deadline.unref();
17
+ this.schedule();
18
+ }
19
+ sandbox;
20
+ limitMs;
21
+ started = performance.now();
22
+ timer;
23
+ deadline;
24
+ renewing;
25
+ disposal;
26
+ failure;
27
+ stopped = false;
28
+ schedule() {
29
+ this.timer = setTimeout(() => {
30
+ this.renewing = this.renew();
31
+ }, E2B_RENEW_MS);
32
+ this.timer.unref();
33
+ }
34
+ async renew() {
35
+ try {
36
+ const remaining = Math.floor(this.limitMs - (performance.now() - this.started));
37
+ if (remaining <= 0 || this.stopped) return;
38
+ await e2bOperation(
39
+ "QA_E2B_RENEW_FAILED",
40
+ () => bounded(
41
+ this.sandbox.setTimeout(Math.min(E2B_LEASE_MS, remaining)),
42
+ AbortSignal.timeout(1e4)
43
+ )
44
+ );
45
+ if (!this.stopped) this.schedule();
46
+ } catch {
47
+ this.failure = new Error("QA_E2B_RENEW_FAILED: sandbox lifetime renewal failed");
48
+ void this.dispose().catch(() => {
49
+ });
50
+ }
51
+ }
52
+ dispose() {
53
+ if (this.disposal) return this.disposal;
54
+ this.stopped = true;
55
+ clearTimeout(this.timer);
56
+ clearTimeout(this.deadline);
57
+ return this.disposal = (async () => {
58
+ await this.renewing;
59
+ await e2bOperation(
60
+ "QA_E2B_KILL_FAILED",
61
+ () => bounded(this.sandbox.kill(), AbortSignal.timeout(1e4))
62
+ );
63
+ if (this.failure) throw this.failure;
64
+ })();
65
+ }
66
+ }
67
+ export {
68
+ E2B_FINALIZATION_MS,
69
+ E2B_LEASE_MS,
70
+ E2B_MAX_LIFETIME_MS,
71
+ E2B_RENEW_MS,
72
+ E2bLifetime
73
+ };
@@ -0,0 +1,13 @@
1
+ import { type QaE2bClient } from "./e2b-client.js";
2
+ export declare function pruneQaSandboxes(options: {
3
+ client: QaE2bClient;
4
+ projectId: string;
5
+ isFinished: (runId: string, batchId: string) => Promise<boolean>;
6
+ dryRun?: boolean;
7
+ }): Promise<{
8
+ inspected: number;
9
+ eligible: number;
10
+ killed: number;
11
+ skipped: number;
12
+ failed: number;
13
+ }>;