@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,493 @@
1
+ import { RunSetupError } from "./run-setup-error.js";
2
+ import { isProtectedTarget } from "@open-qa/qa-engine";
3
+ import { confirmRunEstimate } from "./budget-confirmation.js";
4
+ import { writeWatchState, removeWatchState } from "./watch-state.js";
5
+ import { e2bConfig } from "./adapters/e2b-client.js";
6
+ import { notifyHeals, healNotificationChannel } from "./heal-notification.js";
7
+ import { loadPersonas } from "./personas.js";
8
+ import { gmailCredentialsSchema } from "./vendor/gmail.js";
9
+ import { randomUUID } from "node:crypto";
10
+ import { readFile, stat } from "node:fs/promises";
11
+ import { join, resolve } from "node:path";
12
+ import {
13
+ compile,
14
+ sumRunUsage,
15
+ SecretRedactor,
16
+ selectAgentPlacement,
17
+ targetAllowsUrl
18
+ } from "@open-qa/qa-engine";
19
+ import { actorPermissions, resolveSystems, systemSecretValues } from "./system-config.js";
20
+ import { createEngine, FlowStatusWriteError } from "./engine.js";
21
+ import { findQaRoot, loadConfig, loadFlowDocument, loadFlowDocuments } from "./flow-loader.js";
22
+ import { FileRunStore } from "./adapters/file-run-store.js";
23
+ import { hasCode, runDirectory } from "./adapters/local-files.js";
24
+ import { readLocalEnv } from "./adapters/local-env.js";
25
+ import { generateReport } from "./report/generate.js";
26
+ import { captureExecutionSnapshot, sourceVersions } from "./execution-snapshot.js";
27
+ import { readConsumerManifest } from "./hooks/consumer.js";
28
+ import { TerminalReporter } from "./terminal-reporter.js";
29
+ import { scanRunArtifacts } from "./artifact-scan.js";
30
+ import { QaDatabase } from "./db/database.js";
31
+ import { PgFlowStatus } from "./db/flow-status.js";
32
+ import { printRepeat } from "./quarantine-command.js";
33
+ import { selectByLifecycle } from "./flow-lifecycle.js";
34
+ async function runCommand(path, options, adapters = {}) {
35
+ const repeat = options.repeat ?? 1;
36
+ if (!Number.isInteger(repeat) || repeat < 1 || repeat > 100)
37
+ throw new Error("--repeat must be an integer between 1 and 100");
38
+ if (options.executor && options.executor !== "local-host" && options.executor !== "e2b")
39
+ throw new Error("--executor must be local-host or e2b");
40
+ const placement = options.executor === "e2b" ? "e2b" : "local-host";
41
+ const notificationChannel = healNotificationChannel(process.env);
42
+ if (options.runtime && options.runtime !== "claude-code" && options.runtime !== "codex")
43
+ throw new Error("--runtime must be claude-code or codex");
44
+ const runtimeId = options.runtime === "codex" ? "codex" : "claude-code";
45
+ if (options.agentAt && options.agentAt !== "host" && options.agentAt !== "stage")
46
+ throw new Error("--agent-at must be host or stage");
47
+ if (options.modelAccess && options.modelAccess !== "login" && options.modelAccess !== "env")
48
+ throw new Error("--model-access must be login or env");
49
+ const modelAccess = options.modelAccess === "env" ? "env" : "login";
50
+ const agentAt = selectAgentPlacement({
51
+ stage: placement,
52
+ origin: "cli",
53
+ requested: options.agentAt === "host" || options.agentAt === "stage" ? options.agentAt : void 0,
54
+ modelAccess
55
+ });
56
+ if (modelAccess === "env" && runtimeId === "codex")
57
+ throw new Error("Codex supports host subscription login only");
58
+ const modelCredentials = modelAccess === "env" ? {
59
+ mode: "env",
60
+ env: Object.fromEntries(
61
+ ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"].flatMap(
62
+ (key) => process.env[key] ? [[key, process.env[key]]] : []
63
+ )
64
+ )
65
+ } : void 0;
66
+ if (modelCredentials && !adapters.credentials && !modelCredentials.env.ANTHROPIC_API_KEY && !modelCredentials.env.ANTHROPIC_AUTH_TOKEN)
67
+ throw new Error(
68
+ "--model-access env requires ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN; host subscription tokens are not forwarded"
69
+ );
70
+ const cloud = placement === "e2b" ? e2bConfig(process.env) : void 0;
71
+ const retries = options.retries ?? 1;
72
+ if (retries !== 0 && retries !== 1) throw new Error("--retries must be 0 or 1 in P1");
73
+ if (options.level !== void 0 && options.level !== "pixel")
74
+ throw new Error("--level only accepts pixel");
75
+ if (options.replay !== void 0 && options.replay !== "off")
76
+ throw new Error("--replay only accepts off");
77
+ const root = options.root ? resolve(options.root) : findQaRoot(path);
78
+ const config = await loadConfig(root);
79
+ if (!config.projectId)
80
+ throw new Error(
81
+ "Missing projectId in config.yaml; configure a persistent opaque projectId once and commit it with the project"
82
+ );
83
+ const targetName = options.target ?? "local";
84
+ const target = config.targets && Object.hasOwn(config.targets, targetName) ? config.targets[targetName] : void 0;
85
+ if (!target)
86
+ throw new Error(
87
+ `Unknown target ${targetName}; available targets: ${Object.keys(config.targets ?? {}).join(", ") || "none"}. Configure ${join(root, "config.yaml")}`
88
+ );
89
+ if (!targetAllowsUrl(target, target.url))
90
+ throw new Error(`Target ${targetName} URL is outside its allow list`);
91
+ const trigger = (await stat(path)).isDirectory() ? "suite" : "manual";
92
+ let flows = trigger === "suite" ? await loadFlowDocuments(root, path) : [await loadFlowDocument(path, root)];
93
+ if (adapters.studio) {
94
+ if (trigger !== "manual" || isProtectedTarget(targetName, target) || flows.length !== 1)
95
+ throw new Error("Target unavailable in Studio");
96
+ adapters.studio.verify(config, flows[0]);
97
+ }
98
+ if (options.tag) flows = flows.filter(({ flow }) => flow.tags?.includes(options.tag));
99
+ if (!flows.length) throw new Error("No flows match the selection");
100
+ const loaded = flows;
101
+ flows = await withLifecycle(
102
+ adapters,
103
+ config.projectId,
104
+ (lifecycle) => selectByLifecycle(loaded, trigger, lifecycle, adapters.output ?? console.log)
105
+ );
106
+ if (!flows.length) throw new Error("No flows match the selection");
107
+ if (options.repeat !== void 0 && flows.length !== 1)
108
+ throw new Error("--repeat requires exactly one selected flow");
109
+ const plans = flows.map(
110
+ ({ flow }) => compile({
111
+ ...flow,
112
+ ...cloud ? { budget: { ...flow.budget, minutes: flow.budget?.minutes ?? 15 } } : {},
113
+ actors: Object.fromEntries(
114
+ Object.entries(flow.actors).map(([name, actor]) => [
115
+ name,
116
+ {
117
+ ...actor,
118
+ ...actor.kind !== "system" ? { persona: options.persona ?? actor.persona ?? "default" } : {}
119
+ }
120
+ ])
121
+ )
122
+ })
123
+ );
124
+ const personas = await loadPersonas(
125
+ root,
126
+ plans.flatMap(
127
+ (plan) => plan.lanes.filter((lane) => lane.kind === "user").map((lane) => lane.spec.persona)
128
+ )
129
+ );
130
+ for (const plan of plans) {
131
+ if (isProtectedTarget(targetName, target) && plan.prod !== "safe")
132
+ throw new Error(`Flow ${plan.key} must declare prod: safe for target ${targetName}`);
133
+ for (const view of Object.values(plan.views)) {
134
+ if (!["web", "telegram", "discord", "email"].includes(view.surface))
135
+ throw new RunSetupError(
136
+ "unsupported-surface",
137
+ `Unsupported local view surface: ${view.surface}`
138
+ );
139
+ if (view.surface === "telegram" && isProtectedTarget(targetName, target))
140
+ throw new Error("Telegram requires a non-production target");
141
+ }
142
+ }
143
+ const store = adapters.runStore ?? new FileRunStore(root);
144
+ await confirmRunEstimate({
145
+ ...adapters,
146
+ flows: plans.map((plan) => plan.key),
147
+ recentUsage: store.recentUsage?.bind(store),
148
+ thresholds: config.confirmAbove,
149
+ subscription: modelAccess === "login",
150
+ acceptEstimate: options.acceptEstimate,
151
+ attempts: (retries + 1) * repeat
152
+ });
153
+ const env = await optionalEnv(root);
154
+ const stageTarget = isProtectedTarget(targetName, target) ? "prod" : targetName === "local" ? "dev" : "staging";
155
+ const systems = new Map(
156
+ plans.map((plan) => [plan, resolveSystems(stageTarget, target.systems, env, plan)])
157
+ );
158
+ let access;
159
+ if (target.access === "cloudflare") {
160
+ if (!env.QA_CF_ACCESS_CLIENT_ID || !env.QA_CF_ACCESS_CLIENT_SECRET)
161
+ throw new RunSetupError(
162
+ "access-credentials",
163
+ `Cloudflare Access requires QA_CF_ACCESS_CLIENT_ID and QA_CF_ACCESS_CLIENT_SECRET in ${join(root, ".env.local")}`
164
+ );
165
+ if (new URL(target.url).protocol !== "https:")
166
+ throw new RunSetupError("access-https", "Cloudflare Access requires an HTTPS target");
167
+ access = {
168
+ origin: new URL(target.url).origin,
169
+ clientId: env.QA_CF_ACCESS_CLIENT_ID,
170
+ clientSecret: env.QA_CF_ACCESS_CLIENT_SECRET
171
+ };
172
+ }
173
+ const output = adapters.output ?? console.log;
174
+ const subscriptionToken = modelAccess === "login" && runtimeId === "claude-code" ? process.env.CLAUDE_CODE_OAUTH_TOKEN : void 0;
175
+ if (subscriptionToken) output("Using CLAUDE_CODE_OAUTH_TOKEN for subscription login");
176
+ const versions = await sourceVersions(root);
177
+ const batchId = `batch_${randomUUID()}`;
178
+ const brief = { qaMd: await optionalText(join(root, "qa.md")), personas };
179
+ output(
180
+ `${batchId} \xB7 ${plans.length} flow(s) \xB7 target ${targetName} \xB7 ${runtimeId} (${modelAccess === "login" ? "subscription login" : "env"}) \xB7 stage ${placement} \xB7 agent ${agentAt}`
181
+ );
182
+ const controller = new AbortController();
183
+ const cancel = () => controller.abort(new Error("Run canceled"));
184
+ process.on("SIGINT", cancel);
185
+ process.on("SIGTERM", cancel);
186
+ process.on("SIGHUP", cancel);
187
+ const signal = adapters.signal ? AbortSignal.any([controller.signal, adapters.signal]) : controller.signal;
188
+ const localStore = store instanceof FileRunStore;
189
+ const context = { runtime: runtimeId, modelAccess, agentAt };
190
+ const reports = /* @__PURE__ */ new Map();
191
+ let code = 0;
192
+ let database;
193
+ const repeatResult = {
194
+ startedAt: Date.now(),
195
+ finishedAt: Date.now(),
196
+ target: targetName,
197
+ requested: repeat,
198
+ runs: []
199
+ };
200
+ const usage = [];
201
+ try {
202
+ database = !adapters.flowStatus && process.env.QA_DATABASE_URL ? new QaDatabase(process.env.QA_DATABASE_URL) : void 0;
203
+ const flowStatus = adapters.flowStatus ?? (database ? new PgFlowStatus(database, config.projectId) : void 0);
204
+ for (const plan of plans.flatMap((plan2) => Array.from({ length: repeat }, () => plan2))) {
205
+ if (signal.aborted && !adapters.studio) {
206
+ code = Math.max(code, 1);
207
+ break;
208
+ }
209
+ const reporter = new TerminalReporter(plan, output);
210
+ const redactor = new SecretRedactor();
211
+ const blocked = /* @__PURE__ */ new Set();
212
+ const scans = /* @__PURE__ */ new Map();
213
+ const healEvents = /* @__PURE__ */ new Map();
214
+ const snapshot = captureExecutionSnapshot({
215
+ config,
216
+ definitions: flows[plans.indexOf(plan)].definitions,
217
+ plan,
218
+ targetName,
219
+ runtime: runtimeId,
220
+ placement,
221
+ agentAt,
222
+ modelAccess,
223
+ retries,
224
+ headed: options.headed,
225
+ level: options.level,
226
+ versions,
227
+ env,
228
+ publicEnv: readConsumerManifest(root)?.publicEnv,
229
+ subscriptionToken,
230
+ systemSecrets: systemSecretValues(systems.get(plan))
231
+ });
232
+ const runStore = {
233
+ ...store.listRuns && { listRuns: store.listRuns.bind(store) },
234
+ createRun: async (run) => {
235
+ Object.assign(engine.observation, snapshot.observed);
236
+ await store.createRun(
237
+ redactor.json({
238
+ ...run,
239
+ metadata: {
240
+ ...run.metadata,
241
+ batchId,
242
+ target: targetName,
243
+ ...context,
244
+ executionSnapshot: { ...snapshot, capturedAt: run.startedAt }
245
+ }
246
+ })
247
+ );
248
+ adapters.studio?.created();
249
+ output(` ${plan.key} \xB7 ${run.id}`);
250
+ },
251
+ appendEvents: async (id, events) => {
252
+ await store.appendEvents(
253
+ id,
254
+ events.map(
255
+ (event) => event.kind === "run_phase" && event.phase === "queued" ? { ...event, ...context } : event
256
+ )
257
+ );
258
+ for (const event of events) {
259
+ reporter.event(event);
260
+ if (event.kind === "heal_result") {
261
+ const entries = healEvents.get(id) ?? [];
262
+ entries.push(event);
263
+ healEvents.set(id, entries);
264
+ }
265
+ }
266
+ },
267
+ finishRun: async (id, result2) => {
268
+ if (localStore) await removeWatchState(root, id);
269
+ await store.finishRun(id, { ...result2, executionObservation: { ...engine.observation } });
270
+ adapters.studio?.saved();
271
+ if (localStore) {
272
+ try {
273
+ reports.set(id, await generateReport(root, id));
274
+ } catch {
275
+ output(
276
+ ` Report not generated for ${id}; run result saved. Use open-qa open ${id} to inspect the run directory.`
277
+ );
278
+ }
279
+ const scan = await scanRunArtifacts(root, id, redactor);
280
+ await store.recordArtifactScan(id, scan);
281
+ scans.set(id, scan);
282
+ if (scan.status !== "passed") {
283
+ blocked.add(id);
284
+ reports.delete(id);
285
+ code = 2;
286
+ output(
287
+ ` secret-leak \xB7 ${id} \xB7 artifact sharing blocked; inspect artifactScan in run.json locally`
288
+ );
289
+ }
290
+ }
291
+ }
292
+ };
293
+ const engine = createEngine({
294
+ runId: adapters.studio?.runId,
295
+ batchId,
296
+ heal: config.heal,
297
+ replay: options.repeat !== void 0 ? "off" : options.replay,
298
+ judgeConfig: config.judge,
299
+ reviewerConfig: config.reviewer,
300
+ classifierConfig: config.classifier,
301
+ classifications: adapters.classifications ?? (localStore ? store : void 0),
302
+ targetRevision: adapters.targetRevision ?? (target.revision ? async () => target.revision : void 0),
303
+ flowRevision: flows[plans.indexOf(plan)].definitions.flow.sha256,
304
+ ...adapters,
305
+ flowStatus,
306
+ onStage: async (id, handle) => {
307
+ await adapters.onStage?.(id, handle);
308
+ if (localStore && handle.screenAccess)
309
+ await writeWatchState(root, id, handle.screenAccess);
310
+ },
311
+ redactor,
312
+ root,
313
+ placement,
314
+ agentAt,
315
+ modelAccess,
316
+ modelCredentials,
317
+ healCredentials: config.heal?.runtime === "pi" ? {
318
+ mode: "env",
319
+ env: Object.fromEntries(
320
+ ["OPENAI_API_KEY", "OPENAI_BASE_URL", "ANTHROPIC_API_KEY"].flatMap(
321
+ (key) => process.env[key] ? [[key, process.env[key]]] : []
322
+ )
323
+ )
324
+ } : void 0,
325
+ ...cloud ? {
326
+ e2b: {
327
+ projectId: config.projectId,
328
+ batchId,
329
+ imageTag: cloud.imageTag,
330
+ budgetMs: Math.ceil(plan.budget.minutes * 6e4)
331
+ }
332
+ } : {},
333
+ target,
334
+ brief,
335
+ env,
336
+ subscriptionToken,
337
+ runtimeId,
338
+ retries,
339
+ level: options.level,
340
+ runStore,
341
+ stage: {
342
+ ...Object.values(plan.views).some((view) => view.surface === "email") ? { email: requiredEmail(env) } : {},
343
+ systems: systems.get(plan),
344
+ headed: options.headed,
345
+ ...Object.values(plan.views).some((view) => view.surface === "discord") ? { discord: { botToken: requiredDiscordToken(env) } } : {},
346
+ page: {
347
+ target: stageTarget,
348
+ allowedOrigins: [],
349
+ allowedHosts: target.allow,
350
+ targetOrigin: new URL(target.url).origin,
351
+ access,
352
+ permissions: actorPermissions(plan)
353
+ }
354
+ }
355
+ });
356
+ let result;
357
+ try {
358
+ result = await engine.run(plan, signal);
359
+ } catch (error) {
360
+ if (!(error instanceof FlowStatusWriteError)) throw error;
361
+ const completed = error.result;
362
+ output(error.message);
363
+ if (!blocked.has(completed.runId))
364
+ output(
365
+ ` ${completed.verdict} \xB7 ${localStore ? reports.get(completed.runId) ?? runDirectory(root, completed.runId) : completed.runId}`
366
+ );
367
+ if (options.repeat !== void 0) {
368
+ repeatResult.runs.push({
369
+ runId: completed.runId,
370
+ verdict: completed.verdict,
371
+ category: completed.category
372
+ });
373
+ repeatResult.finishedAt = Date.now();
374
+ try {
375
+ await flowStatus?.saveRepeat(plan.key, repeatResult);
376
+ } catch {
377
+ output(
378
+ "Repeat result was not saved to QA PostgreSQL; inspect the completed runs locally"
379
+ );
380
+ }
381
+ printRepeat(repeatResult, output);
382
+ }
383
+ return 2;
384
+ }
385
+ repeatResult.runs.push({
386
+ runId: result.runId,
387
+ verdict: result.verdict,
388
+ category: result.category
389
+ });
390
+ if (!result.quarantined && localStore && notificationChannel)
391
+ for (const [id, notifications] of healEvents) {
392
+ const scan = scans.get(id);
393
+ if (scan?.status !== "passed" || !notifications.length) continue;
394
+ try {
395
+ await notifyHeals({
396
+ root,
397
+ runId: id,
398
+ events: notifications,
399
+ channel: notificationChannel,
400
+ token: requiredDiscordToken(env),
401
+ redactor,
402
+ scan
403
+ });
404
+ } catch {
405
+ output(" Discord self-heal notification failed; inspect the local report");
406
+ }
407
+ }
408
+ usage.push(...result.runs.flatMap((run) => run.usage ? [run.usage] : []));
409
+ if (localStore)
410
+ for (const run of result.runs) {
411
+ const classification = (await store.getClassification(run.runId))?.classification;
412
+ if (classification)
413
+ output(` ${run.runId} \xB7 ${classification.category} \xB7 ${classification.reason}`);
414
+ }
415
+ if (signal.aborted || result.verdict === "canceled") code = Math.max(code, 1);
416
+ else if (!result.quarantined)
417
+ code = Math.max(code, result.verdict === "error" ? 2 : result.verdict === "passed" ? 0 : 1);
418
+ if (result.quarantined) output(` ${plan.key} \xB7 quarantined \xB7 result is non-blocking`);
419
+ if (!blocked.has(result.runId))
420
+ output(
421
+ ` ${result.verdict} \xB7 ${localStore ? reports.get(result.runId) ?? runDirectory(root, result.runId) : result.runId}`
422
+ );
423
+ }
424
+ if (options.repeat !== void 0) {
425
+ repeatResult.finishedAt = Date.now();
426
+ await flowStatus?.saveRepeat(plans[0].key, repeatResult);
427
+ printRepeat(repeatResult, output);
428
+ if (!flowStatus)
429
+ output(
430
+ "Repeat result was not saved to QA PostgreSQL; configure QA_DATABASE_URL to show it during release"
431
+ );
432
+ }
433
+ output(`Batch usage: ${JSON.stringify(sumRunUsage(usage))}`);
434
+ return signal.aborted ? Math.max(code, 1) : code;
435
+ } catch (error) {
436
+ if (database) {
437
+ throw new Error("QA run failed; check QA PostgreSQL connectivity and applied migrations");
438
+ }
439
+ throw error;
440
+ } finally {
441
+ process.off("SIGINT", cancel);
442
+ process.off("SIGTERM", cancel);
443
+ process.off("SIGHUP", cancel);
444
+ await database?.close();
445
+ }
446
+ }
447
+ function requiredDiscordToken(env) {
448
+ if (!env.QA_DISCORD_BOT_TOKEN)
449
+ throw new Error("Discord views require QA_DISCORD_BOT_TOKEN in the QA inventory");
450
+ return env.QA_DISCORD_BOT_TOKEN;
451
+ }
452
+ async function optionalText(path) {
453
+ try {
454
+ return await readFile(path, "utf8");
455
+ } catch (error) {
456
+ if (hasCode(error, "ENOENT")) return "";
457
+ throw error;
458
+ }
459
+ }
460
+ async function optionalEnv(root) {
461
+ try {
462
+ await stat(join(root, ".env.local"));
463
+ } catch (error) {
464
+ if (hasCode(error, "ENOENT")) return {};
465
+ throw error;
466
+ }
467
+ return readLocalEnv(root);
468
+ }
469
+ function requiredEmail(env) {
470
+ const parsed = gmailCredentialsSchema.safeParse({
471
+ clientId: env.QA_GMAIL_CLIENT_ID,
472
+ clientSecret: env.QA_GMAIL_CLIENT_SECRET,
473
+ refreshToken: env.QA_GMAIL_REFRESH_TOKEN
474
+ });
475
+ if (!parsed.success)
476
+ throw new Error(
477
+ "Email requires QA_GMAIL_CLIENT_ID, QA_GMAIL_CLIENT_SECRET and QA_GMAIL_REFRESH_TOKEN"
478
+ );
479
+ return parsed.data;
480
+ }
481
+ async function withLifecycle(adapters, projectId, use) {
482
+ const injected = adapters.lifecycle ?? (adapters.flowStatus && "states" in adapters.flowStatus ? adapters.flowStatus : void 0);
483
+ if (injected || adapters.flowStatus || !process.env.QA_DATABASE_URL) return use(injected);
484
+ const database = new QaDatabase(process.env.QA_DATABASE_URL);
485
+ try {
486
+ return await use(new PgFlowStatus(database, projectId));
487
+ } finally {
488
+ await database.close();
489
+ }
490
+ }
491
+ export {
492
+ runCommand
493
+ };
@@ -0,0 +1,11 @@
1
+ export declare const setupReasons: {
2
+ readonly "unsupported-surface": "This flow uses an unsupported local view surface. Choose web, Telegram, Discord or email.";
3
+ readonly "access-credentials": "Configure the Cloudflare Access client ID and client secret in the project’s .env.local file.";
4
+ readonly "access-https": "Configure an HTTPS URL for this Cloudflare Access environment.";
5
+ readonly "review-changed": "The configuration or estimate changed. Review the flow again before starting.";
6
+ readonly configuration: "Check the flow, environment and systems configuration. Run open-qa doctor for details.";
7
+ };
8
+ export declare class RunSetupError extends Error {
9
+ readonly code: keyof typeof setupReasons;
10
+ constructor(code: keyof typeof setupReasons, detail: string);
11
+ }
@@ -0,0 +1,18 @@
1
+ const setupReasons = {
2
+ "unsupported-surface": "This flow uses an unsupported local view surface. Choose web, Telegram, Discord or email.",
3
+ "access-credentials": "Configure the Cloudflare Access client ID and client secret in the project\u2019s .env.local file.",
4
+ "access-https": "Configure an HTTPS URL for this Cloudflare Access environment.",
5
+ "review-changed": "The configuration or estimate changed. Review the flow again before starting.",
6
+ configuration: "Check the flow, environment and systems configuration. Run open-qa doctor for details."
7
+ };
8
+ class RunSetupError extends Error {
9
+ constructor(code, detail) {
10
+ super(detail);
11
+ this.code = code;
12
+ }
13
+ code;
14
+ }
15
+ export {
16
+ RunSetupError,
17
+ setupReasons
18
+ };
@@ -0,0 +1,9 @@
1
+ import { type QaE2bClient } from "./adapters/e2b-client.js";
2
+ export declare function sandboxesPruneCommand(options: {
3
+ root?: string;
4
+ dryRun?: boolean;
5
+ }, adapters?: {
6
+ client?: QaE2bClient;
7
+ output?: (line: string) => void;
8
+ env?: NodeJS.ProcessEnv;
9
+ }): Promise<1 | 0>;
@@ -0,0 +1,29 @@
1
+ import { resolve } from "node:path";
2
+ import { loadConfig } from "./flow-loader.js";
3
+ import { FileRunStore } from "./adapters/file-run-store.js";
4
+ import { createQaE2bClient } from "./adapters/e2b-client.js";
5
+ import { pruneQaSandboxes } from "./adapters/e2b-prune.js";
6
+ async function sandboxesPruneCommand(options, adapters = {}) {
7
+ const root = resolve(options.root ?? ".qa");
8
+ const config = await loadConfig(root);
9
+ if (!config.projectId) throw new Error("QA sandbox pruning requires config.projectId");
10
+ const env = adapters.env ?? process.env;
11
+ const client = adapters.client ?? createQaE2bClient(env.QA_E2B_API_KEY ?? "");
12
+ const store = new FileRunStore(root);
13
+ const result = await pruneQaSandboxes({
14
+ client,
15
+ projectId: config.projectId,
16
+ dryRun: options.dryRun,
17
+ isFinished: async (id, batchId) => {
18
+ const run = await store.getRun(id);
19
+ return !!run?.result && run.run.metadata?.batchId === batchId;
20
+ }
21
+ });
22
+ (adapters.output ?? console.log)(
23
+ `QA sandboxes: inspected=${result.inspected} eligible=${result.eligible} killed=${result.killed} skipped=${result.skipped} failed=${result.failed}${options.dryRun ? " (dry run)" : ""}`
24
+ );
25
+ return result.failed ? 1 : 0;
26
+ }
27
+ export {
28
+ sandboxesPruneCommand
29
+ };
@@ -0,0 +1,5 @@
1
+ export interface ScreenProxy {
2
+ url: string;
3
+ close(): Promise<void>;
4
+ }
5
+ export declare function startScreenProxy(frames: (signal: AbortSignal) => Promise<unknown>): Promise<ScreenProxy>;
@@ -0,0 +1,79 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { serve } from "@hono/node-server";
3
+ import { Hono } from "hono";
4
+ import { screenFramesSchema } from "./screen-url.js";
5
+ const shell = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>QA stage screen</title><style>
6
+ :root{color-scheme:light dark;font-family:system-ui,sans-serif}body{margin:0;padding:24px;background:light-dark(#f5f6f8,#17191d);color:light-dark(#20242c,#e7e9ee)}h1{font-size:24px;margin:0}#status{font-size:14px;opacity:.7}main{display:grid;gap:20px}section{min-width:0;padding:16px;border:1px solid light-dark(#d8dce3,#363b45);border-radius:12px;background:light-dark(white,#20242b)}h2{font-size:16px;margin:0 0 12px}img{display:block;max-width:100%;height:auto}
7
+ </style></head><body><h1>QA stage screen</h1><p id="status" role="status">Connecting\u2026</p><main></main><script>
8
+ async function refresh(){try{const r=await fetch('/frames',{cache:'no-store'});if(!r.ok)throw Error();const frames=await r.json();document.querySelector('main').replaceChildren(...frames.map(f=>{const box=document.createElement('section');const title=document.createElement('h2');title.textContent=f.view;const img=document.createElement('img');img.src='data:image/png;base64,'+f.png;box.append(title,img);return box}));document.querySelector('#status').textContent=frames.length?'Live \xB7 refreshes every 2 seconds':'Waiting for views';}catch{document.querySelector('#status').textContent='Stage unavailable or screen access expired';}setTimeout(refresh,2000)}
9
+ fetch('/session',{method:'POST'}).then(r=>{if(!r.ok)throw Error();refresh()}).catch(()=>{document.querySelector('#status').textContent='Screen session unavailable'});
10
+ <\/script></body></html>`;
11
+ async function startScreenProxy(frames) {
12
+ const app = new Hono();
13
+ const controller = new AbortController();
14
+ const cookieName = `qa_watch_${randomBytes(16).toString("hex")}`;
15
+ const session = randomBytes(32).toString("hex");
16
+ let origin = "";
17
+ let active = false;
18
+ app.use("*", async (c, next) => {
19
+ c.header("Cache-Control", "no-store");
20
+ c.header("Referrer-Policy", "no-referrer");
21
+ c.header("X-Content-Type-Options", "nosniff");
22
+ c.header(
23
+ "Content-Security-Policy",
24
+ "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; frame-ancestors 'none'; form-action 'none'"
25
+ );
26
+ if (!origin || c.req.header("host") !== new URL(origin).host)
27
+ return c.json({ error: "Forbidden" }, 403);
28
+ await next();
29
+ });
30
+ app.get("/", (c) => c.html(shell));
31
+ app.post("/session", (c) => {
32
+ if (c.req.header("origin") !== origin || c.req.header("sec-fetch-site") !== "same-origin")
33
+ return c.json({ error: "Forbidden" }, 403);
34
+ c.header("Set-Cookie", `${cookieName}=${session}; HttpOnly; SameSite=Strict; Path=/`);
35
+ return c.body(null, 204);
36
+ });
37
+ app.get("/frames", async (c) => {
38
+ const value = (c.req.header("cookie") ?? "").split(";").map((s) => s.trim()).find((s) => s.startsWith(`${cookieName}=`))?.slice(cookieName.length + 1) ?? "";
39
+ if (c.req.header("sec-fetch-site") !== "same-origin" || Buffer.byteLength(value) !== Buffer.byteLength(session) || !timingSafeEqual(Buffer.from(value), Buffer.from(session)))
40
+ return c.json({ error: "Unauthorized" }, 401);
41
+ if (active) return c.json({ error: "Screen busy" }, 429);
42
+ active = true;
43
+ try {
44
+ return c.json(
45
+ screenFramesSchema.parse(
46
+ await frames(
47
+ AbortSignal.any([c.req.raw.signal, controller.signal, AbortSignal.timeout(15e3)])
48
+ )
49
+ )
50
+ );
51
+ } catch {
52
+ return c.json({ error: "Screen unavailable or access expired" }, 503);
53
+ } finally {
54
+ active = false;
55
+ }
56
+ });
57
+ const server = serve({ fetch: app.fetch, hostname: "127.0.0.1", port: 0 });
58
+ await new Promise((resolve, reject) => {
59
+ server.once("listening", resolve);
60
+ server.once("error", reject);
61
+ });
62
+ const address = server.address();
63
+ if (!address || typeof address === "string") throw new Error("Screen proxy failed to start");
64
+ origin = `http://127.0.0.1:${address.port}`;
65
+ let closing;
66
+ return {
67
+ url: `${origin}/`,
68
+ close: () => closing ??= (async () => {
69
+ controller.abort();
70
+ await new Promise((resolve, reject) => {
71
+ server.close((error) => error ? reject(error) : resolve());
72
+ if ("closeAllConnections" in server) server.closeAllConnections();
73
+ });
74
+ })()
75
+ };
76
+ }
77
+ export {
78
+ startScreenProxy
79
+ };
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ export declare const screenUrlSchema: z.ZodURL;
3
+ export declare const screenAccessSchema: z.ZodObject<{
4
+ url: z.ZodURL;
5
+ token: z.ZodString;
6
+ }, z.core.$strict>;
7
+ export type ScreenAccess = z.infer<typeof screenAccessSchema>;
8
+ export declare const screenResponseSchema: z.ZodObject<{
9
+ available: z.ZodBoolean;
10
+ }, z.core.$strict>;
11
+ export declare const screenFramesSchema: z.ZodArray<z.ZodObject<{
12
+ view: z.ZodString;
13
+ png: z.ZodString;
14
+ }, z.core.$strict>>;
15
+ export declare function readScreenFrames(access: ScreenAccess, signal: AbortSignal): Promise<{
16
+ view: string;
17
+ png: string;
18
+ }[]>;