@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.
- package/LICENSE +204 -0
- package/NOTICE +7 -0
- package/THIRD_PARTY.md +12 -0
- package/THIRD_PARTY_NOTICES.md +11 -0
- package/drizzle/0000_qa_core.sql +158 -0
- package/drizzle/0001_run_health.sql +3 -0
- package/drizzle/0002_bounded_cleanup.sql +5 -0
- package/drizzle/0003_step_replay_cache.sql +9 -0
- package/drizzle/0004_credential_expiry.sql +1 -0
- package/drizzle/0005_server_api.sql +19 -0
- package/drizzle/0006_submission_created.sql +3 -0
- package/drizzle/0007_findings.sql +19 -0
- package/drizzle/0008_classification_labels.sql +14 -0
- package/drizzle/0009_job_queue.sql +20 -0
- package/drizzle/0010_result_notifications.sql +13 -0
- package/drizzle/0011_result_notification_retries.sql +5 -0
- package/drizzle/0012_result_notification_flows.sql +44 -0
- package/drizzle/0013_flow_quarantine.sql +35 -0
- package/drizzle/0014_run_budgets.sql +2 -0
- package/drizzle/0015_flow_lifecycle.sql +9 -0
- package/drizzle/0016_open_qa_classification.sql +28 -0
- package/drizzle/meta/0000_snapshot.json +1002 -0
- package/drizzle/meta/0001_snapshot.json +1021 -0
- package/drizzle/meta/0002_snapshot.json +1027 -0
- package/drizzle/meta/0003_snapshot.json +1081 -0
- package/drizzle/meta/0004_snapshot.json +1087 -0
- package/drizzle/meta/0005_snapshot.json +1210 -0
- package/drizzle/meta/0006_snapshot.json +1244 -0
- package/drizzle/meta/0007_snapshot.json +1353 -0
- package/drizzle/meta/0008_snapshot.json +1435 -0
- package/drizzle/meta/0009_snapshot.json +1587 -0
- package/drizzle/meta/0010_snapshot.json +1675 -0
- package/drizzle/meta/0011_snapshot.json +1692 -0
- package/drizzle/meta/0012_snapshot.json +1818 -0
- package/drizzle/meta/0013_snapshot.json +2016 -0
- package/drizzle/meta/0014_snapshot.json +2028 -0
- package/drizzle/meta/0015_snapshot.json +2064 -0
- package/drizzle/meta/0016_snapshot.json +2076 -0
- package/drizzle/meta/_journal.json +125 -0
- package/package.json +118 -4
- package/problem-matcher.json +32 -0
- package/src/adapters/db-lease-pool.d.ts +25 -0
- package/src/adapters/db-lease-pool.js +293 -0
- package/src/adapters/dir-artifact-store.d.ts +9 -0
- package/src/adapters/dir-artifact-store.js +64 -0
- package/src/adapters/e2b-agent.d.ts +7 -0
- package/src/adapters/e2b-agent.js +94 -0
- package/src/adapters/e2b-artifacts.d.ts +3 -0
- package/src/adapters/e2b-artifacts.js +66 -0
- package/src/adapters/e2b-bounded.d.ts +1 -0
- package/src/adapters/e2b-bounded.js +19 -0
- package/src/adapters/e2b-client.d.ts +33 -0
- package/src/adapters/e2b-client.js +114 -0
- package/src/adapters/e2b-executor.d.ts +26 -0
- package/src/adapters/e2b-executor.js +194 -0
- package/src/adapters/e2b-lifetime.d.ts +20 -0
- package/src/adapters/e2b-lifetime.js +73 -0
- package/src/adapters/e2b-prune.d.ts +13 -0
- package/src/adapters/e2b-prune.js +42 -0
- package/src/adapters/file-replay-cache.d.ts +14 -0
- package/src/adapters/file-replay-cache.js +120 -0
- package/src/adapters/file-run-store.d.ts +175 -0
- package/src/adapters/file-run-store.js +280 -0
- package/src/adapters/fixed-lease-pool.d.ts +10 -0
- package/src/adapters/fixed-lease-pool.js +237 -0
- package/src/adapters/gcs/artifact-store.d.ts +49 -0
- package/src/adapters/gcs/artifact-store.js +247 -0
- package/src/adapters/gcs/client.d.ts +22 -0
- package/src/adapters/gcs/client.js +106 -0
- package/src/adapters/gcs/download.d.ts +9 -0
- package/src/adapters/gcs/download.js +43 -0
- package/src/adapters/gcs/index.d.ts +8 -0
- package/src/adapters/gcs/index.js +23 -0
- package/src/adapters/gcs/periodic-flush.d.ts +5 -0
- package/src/adapters/gcs/periodic-flush.js +16 -0
- package/src/adapters/gcs/pg-catalog.d.ts +16 -0
- package/src/adapters/gcs/pg-catalog.js +149 -0
- package/src/adapters/gcs/replay-completeness.d.ts +1 -0
- package/src/adapters/gcs/replay-completeness.js +65 -0
- package/src/adapters/gcs/scan-upload.d.ts +10 -0
- package/src/adapters/gcs/scan-upload.js +26 -0
- package/src/adapters/index.d.ts +5 -0
- package/src/adapters/index.js +12 -0
- package/src/adapters/lease-transaction.d.ts +2 -0
- package/src/adapters/lease-transaction.js +61 -0
- package/src/adapters/local-credential-resolver.d.ts +5 -0
- package/src/adapters/local-credential-resolver.js +15 -0
- package/src/adapters/local-env.d.ts +1 -0
- package/src/adapters/local-env.js +37 -0
- package/src/adapters/local-files.d.ts +17 -0
- package/src/adapters/local-files.js +150 -0
- package/src/adapters/pg-classification-store.d.ts +58 -0
- package/src/adapters/pg-classification-store.js +112 -0
- package/src/adapters/pg-replay-cache.d.ts +16 -0
- package/src/adapters/pg-replay-cache.js +111 -0
- package/src/adapters/pg-run-store.d.ts +58 -0
- package/src/adapters/pg-run-store.js +399 -0
- package/src/adapters/resource-pools.d.ts +2 -0
- package/src/adapters/resource-pools.js +28 -0
- package/src/adapters/secret-manager-credential-resolver.d.ts +44 -0
- package/src/adapters/secret-manager-credential-resolver.js +102 -0
- package/src/artifact-scan.d.ts +21 -0
- package/src/artifact-scan.js +139 -0
- package/src/budget-confirmation.d.ts +23 -0
- package/src/budget-confirmation.js +43 -0
- package/src/cache-command.d.ts +7 -0
- package/src/cache-command.js +107 -0
- package/src/classification-command.d.ts +14 -0
- package/src/classification-command.js +72 -0
- package/src/classification-diff.d.ts +10 -0
- package/src/classification-diff.js +47 -0
- package/src/classification-model.d.ts +17 -0
- package/src/classification-model.js +51 -0
- package/src/classification-notifier.d.ts +21 -0
- package/src/classification-notifier.js +34 -0
- package/src/classify-runs.d.ts +31 -0
- package/src/classify-runs.js +138 -0
- package/src/cli-program.d.ts +9 -0
- package/src/cli-program.js +172 -0
- package/src/cli.d.ts +2 -0
- package/src/cli.js +12 -0
- package/src/commands.d.ts +7 -0
- package/src/commands.js +17 -0
- package/src/credential-references.d.ts +24 -0
- package/src/credential-references.js +33 -0
- package/src/db/commands.d.ts +1 -0
- package/src/db/commands.js +34 -0
- package/src/db/credentials.d.ts +16 -0
- package/src/db/credentials.js +73 -0
- package/src/db/database.d.ts +12 -0
- package/src/db/database.js +135 -0
- package/src/db/event-chunks.d.ts +405 -0
- package/src/db/event-chunks.js +74 -0
- package/src/db/fencing.d.ts +8 -0
- package/src/db/fencing.js +16 -0
- package/src/db/flow-status.d.ts +41 -0
- package/src/db/flow-status.js +208 -0
- package/src/db/index.d.ts +12 -0
- package/src/db/index.js +24 -0
- package/src/db/queries.d.ts +73 -0
- package/src/db/queries.js +122 -0
- package/src/db/resources.d.ts +14 -0
- package/src/db/resources.js +61 -0
- package/src/db/schema.d.ts +3532 -0
- package/src/db/schema.js +501 -0
- package/src/demo-command.d.ts +1 -0
- package/src/demo-command.js +50 -0
- package/src/doctor-command.d.ts +15 -0
- package/src/doctor-command.js +275 -0
- package/src/doctor-summary.d.ts +2 -0
- package/src/doctor-summary.js +31 -0
- package/src/draft-api.d.ts +460 -0
- package/src/draft-api.js +333 -0
- package/src/draft-command.d.ts +10 -0
- package/src/draft-command.js +73 -0
- package/src/draft-hooks.d.ts +3 -0
- package/src/draft-hooks.js +33 -0
- package/src/draft-pages.d.ts +11 -0
- package/src/draft-pages.js +82 -0
- package/src/engine.d.ts +105 -0
- package/src/engine.js +323 -0
- package/src/execution-snapshot.d.ts +21 -0
- package/src/execution-snapshot.js +141 -0
- package/src/flow-check.d.ts +9 -0
- package/src/flow-check.js +68 -0
- package/src/flow-lifecycle.d.ts +6 -0
- package/src/flow-lifecycle.js +61 -0
- package/src/flow-lint.d.ts +8 -0
- package/src/flow-lint.js +73 -0
- package/src/flow-loader.d.ts +219 -0
- package/src/flow-loader.js +236 -0
- package/src/flow-source.d.ts +2 -0
- package/src/flow-source.js +6 -0
- package/src/flows-api.d.ts +1 -0
- package/src/flows-api.js +12 -0
- package/src/heal-notification.d.ts +16 -0
- package/src/heal-notification.js +62 -0
- package/src/hooks/api.d.ts +29 -0
- package/src/hooks/api.js +15 -0
- package/src/hooks/consumer.d.ts +18 -0
- package/src/hooks/consumer.js +98 -0
- package/src/hooks/loader.d.ts +6 -0
- package/src/hooks/loader.js +28 -0
- package/src/hooks/registry.d.ts +22 -0
- package/src/hooks/registry.js +23 -0
- package/src/hooks/runner.d.ts +19 -0
- package/src/hooks/runner.js +279 -0
- package/src/hooks/session-cache.d.ts +16 -0
- package/src/hooks/session-cache.js +42 -0
- package/src/hooks/session-store.d.ts +20 -0
- package/src/hooks/session-store.js +95 -0
- package/src/hooks/worker.d.ts +1 -0
- package/src/hooks/worker.js +84 -0
- package/src/http-stage-client.d.ts +367 -0
- package/src/http-stage-client.js +190 -0
- package/src/independent-model.d.ts +22 -0
- package/src/independent-model.js +215 -0
- package/src/lifecycle-command.d.ts +15 -0
- package/src/lifecycle-command.js +190 -0
- package/src/local-command.d.ts +3 -0
- package/src/local-command.js +27 -0
- package/src/local-host-executor.d.ts +38 -0
- package/src/local-host-executor.js +196 -0
- package/src/open-command.d.ts +7 -0
- package/src/open-command.js +39 -0
- package/src/operations-api.d.ts +2 -0
- package/src/operations-api.js +6 -0
- package/src/personas.d.ts +2 -0
- package/src/personas.js +61 -0
- package/src/program-runner.d.ts +3 -0
- package/src/program-runner.js +263 -0
- package/src/program-sandbox.py +75 -0
- package/src/program-scratch.d.ts +2 -0
- package/src/program-scratch.js +48 -0
- package/src/program-worker.mjs +101 -0
- package/src/public-id.d.ts +2 -0
- package/src/public-id.js +5 -0
- package/src/public-report-url.d.ts +1 -0
- package/src/public-report-url.js +18 -0
- package/src/publication-check.d.ts +1 -0
- package/src/publication-check.js +31 -0
- package/src/quarantine-command.d.ts +9 -0
- package/src/quarantine-command.js +69 -0
- package/src/remote-command.d.ts +30 -0
- package/src/remote-command.js +156 -0
- package/src/replay-image.d.ts +1 -0
- package/src/replay-image.js +35 -0
- package/src/report/assets.d.ts +1 -0
- package/src/report/assets.js +5 -0
- package/src/report/browser.css +414 -0
- package/src/report/browser.d.ts +1 -0
- package/src/report/browser.js +219 -0
- package/src/report/data.d.ts +1 -0
- package/src/report/data.js +4 -0
- package/src/report/generate.d.ts +1 -0
- package/src/report/generate.js +54 -0
- package/src/report/load.d.ts +870 -0
- package/src/report/load.js +139 -0
- package/src/report/resource-table.d.ts +2 -0
- package/src/report/resource-table.js +4 -0
- package/src/report/status-icon.d.ts +2 -0
- package/src/report/status-icon.js +20 -0
- package/src/report/style.css +413 -0
- package/src/result-notifier.d.ts +121 -0
- package/src/result-notifier.js +230 -0
- package/src/result-transports.d.ts +12 -0
- package/src/result-transports.js +150 -0
- package/src/run-command.d.ts +32 -0
- package/src/run-command.js +493 -0
- package/src/run-setup-error.d.ts +11 -0
- package/src/run-setup-error.js +18 -0
- package/src/sandboxes-command.d.ts +9 -0
- package/src/sandboxes-command.js +29 -0
- package/src/screen-proxy.d.ts +5 -0
- package/src/screen-proxy.js +79 -0
- package/src/screen-url.d.ts +18 -0
- package/src/screen-url.js +54 -0
- package/src/server/app.d.ts +29 -0
- package/src/server/app.js +350 -0
- package/src/server/auth.d.ts +33 -0
- package/src/server/auth.js +113 -0
- package/src/server/credentials.d.ts +30 -0
- package/src/server/credentials.js +77 -0
- package/src/server/errors.d.ts +9 -0
- package/src/server/errors.js +26 -0
- package/src/server/index.d.ts +35 -0
- package/src/server/index.js +96 -0
- package/src/server/maintenance.d.ts +13 -0
- package/src/server/maintenance.js +54 -0
- package/src/server/repository.d.ts +534 -0
- package/src/server/repository.js +219 -0
- package/src/setup-command.d.ts +10 -0
- package/src/setup-command.js +52 -0
- package/src/stage-environment.d.ts +1 -0
- package/src/stage-environment.js +35 -0
- package/src/stage-supervisor.mjs +95 -0
- package/src/studio-command.d.ts +7 -0
- package/src/studio-command.js +47 -0
- package/src/studio-control.d.ts +5 -0
- package/src/studio-control.js +207 -0
- package/src/studio-review.d.ts +24 -0
- package/src/studio-review.js +64 -0
- package/src/studio-worker.d.ts +1 -0
- package/src/studio-worker.js +48 -0
- package/src/system-config.d.ts +7 -0
- package/src/system-config.js +70 -0
- package/src/terminal-reporter.d.ts +13 -0
- package/src/terminal-reporter.js +93 -0
- package/src/vendor/gmail.d.ts +45 -0
- package/src/vendor/gmail.js +193 -0
- package/src/watch-command.d.ts +16 -0
- package/src/watch-command.js +93 -0
- package/src/watch-state.d.ts +4 -0
- package/src/watch-state.js +53 -0
- package/src/worker/execution-error.d.ts +5 -0
- package/src/worker/execution-error.js +10 -0
- package/src/worker/execution.d.ts +24 -0
- package/src/worker/execution.js +190 -0
- package/src/worker/index.d.ts +8 -0
- package/src/worker/index.js +40 -0
- package/src/worker/prune.d.ts +3 -0
- package/src/worker/prune.js +22 -0
- package/src/worker/quarantine-notifications.d.ts +8 -0
- package/src/worker/quarantine-notifications.js +89 -0
- package/src/worker/queue.d.ts +65 -0
- package/src/worker/queue.js +438 -0
- package/src/worker/result-notifications.d.ts +28 -0
- package/src/worker/result-notifications.js +347 -0
- package/src/worker/store.d.ts +4 -0
- package/src/worker/store.js +46 -0
- package/src/worker/worker.d.ts +21 -0
- package/src/worker/worker.js +140 -0
- package/README.md +0 -3
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { parseUniqueJson, omitImageAttachments, usageSchema } from "@open-qa/qa-engine";
|
|
3
|
+
const completionSchema = z.object({
|
|
4
|
+
choices: z.array(
|
|
5
|
+
z.object({
|
|
6
|
+
finish_reason: z.literal("stop"),
|
|
7
|
+
message: z.object({
|
|
8
|
+
content: z.string().min(1).max(32e3),
|
|
9
|
+
tool_calls: z.array(z.unknown()).max(0).optional(),
|
|
10
|
+
function_call: z.never().optional(),
|
|
11
|
+
refusal: z.null().optional()
|
|
12
|
+
})
|
|
13
|
+
})
|
|
14
|
+
).length(1)
|
|
15
|
+
});
|
|
16
|
+
function unsupportedImages(message) {
|
|
17
|
+
return /(?:does not|doesn't|do not|cannot|can't|not) support.{0,60}(?:image|vision)|(?:image|vision|image_url).{0,60}(?:not supported|unsupported|only supported|not support)|unsupported.{0,30}(?:image|vision)/i.test(
|
|
18
|
+
message
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
class UnsupportedImages extends Error {
|
|
22
|
+
}
|
|
23
|
+
async function readBounded(response) {
|
|
24
|
+
if (!response.body) throw new Error("Missing model response");
|
|
25
|
+
const reader = response.body.getReader();
|
|
26
|
+
let body = "";
|
|
27
|
+
const decoder = new TextDecoder();
|
|
28
|
+
let bytes = 0;
|
|
29
|
+
try {
|
|
30
|
+
for (; ; ) {
|
|
31
|
+
const chunk = await reader.read();
|
|
32
|
+
if (chunk.done) break;
|
|
33
|
+
bytes += chunk.value.byteLength;
|
|
34
|
+
if (bytes > 128e3) throw new Error("Model response too large");
|
|
35
|
+
body += decoder.decode(chunk.value, { stream: true });
|
|
36
|
+
}
|
|
37
|
+
return body + decoder.decode();
|
|
38
|
+
} finally {
|
|
39
|
+
await reader.cancel();
|
|
40
|
+
reader.releaseLock();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
class IndependentModelCaller {
|
|
44
|
+
constructor(options) {
|
|
45
|
+
this.options = options;
|
|
46
|
+
}
|
|
47
|
+
options;
|
|
48
|
+
async complete(request, signal) {
|
|
49
|
+
const purpose = this.options.purpose ?? "judge";
|
|
50
|
+
try {
|
|
51
|
+
signal?.throwIfAborted();
|
|
52
|
+
const access = await this.options.credentials.resolve({
|
|
53
|
+
runtime: "pi",
|
|
54
|
+
actor: purpose,
|
|
55
|
+
purpose
|
|
56
|
+
});
|
|
57
|
+
signal?.throwIfAborted();
|
|
58
|
+
if (access.mode === "env") {
|
|
59
|
+
this.options.redactor.add(
|
|
60
|
+
Object.values(access.env).filter((value) => value !== access.env.OPENAI_BASE_URL)
|
|
61
|
+
);
|
|
62
|
+
const endpoint = new URL(access.env.OPENAI_BASE_URL ?? "");
|
|
63
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || !access.env.OPENAI_API_KEY || !this.options.model)
|
|
64
|
+
throw new Error("Invalid independent model configuration");
|
|
65
|
+
for (const imageFallback of [false, true]) {
|
|
66
|
+
const input = imageFallback ? omitImageAttachments(request.input) : request.input;
|
|
67
|
+
const response = await (this.options.fetch ?? fetch)(
|
|
68
|
+
`${endpoint.href.replace(/\/$/, "")}/chat/completions`,
|
|
69
|
+
{
|
|
70
|
+
method: "POST",
|
|
71
|
+
redirect: "manual",
|
|
72
|
+
signal,
|
|
73
|
+
headers: {
|
|
74
|
+
authorization: `Bearer ${access.env.OPENAI_API_KEY}`,
|
|
75
|
+
"content-type": "application/json"
|
|
76
|
+
},
|
|
77
|
+
body: JSON.stringify({
|
|
78
|
+
model: this.options.model,
|
|
79
|
+
messages: [
|
|
80
|
+
{ role: "system", content: this.options.redactor.text(request.system) },
|
|
81
|
+
{
|
|
82
|
+
role: "user",
|
|
83
|
+
content: request.images?.length && !imageFallback ? [
|
|
84
|
+
{
|
|
85
|
+
type: "text",
|
|
86
|
+
text: JSON.stringify(this.options.redactor.json(input))
|
|
87
|
+
},
|
|
88
|
+
...request.images.map((image) => ({
|
|
89
|
+
type: "image_url",
|
|
90
|
+
image_url: {
|
|
91
|
+
url: `data:${image.mimeType};base64,${image.data}`
|
|
92
|
+
}
|
|
93
|
+
}))
|
|
94
|
+
] : JSON.stringify(this.options.redactor.json(input))
|
|
95
|
+
}
|
|
96
|
+
],
|
|
97
|
+
tools: [],
|
|
98
|
+
tool_choice: "none",
|
|
99
|
+
stream: false,
|
|
100
|
+
response_format: {
|
|
101
|
+
type: "json_schema",
|
|
102
|
+
json_schema: { name: purpose, strict: true, schema: request.responseSchema }
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
);
|
|
107
|
+
if (!response.ok) {
|
|
108
|
+
if (!imageFallback && request.images?.length && [400, 415, 422].includes(response.status)) {
|
|
109
|
+
const body2 = parseUniqueJson(await readBounded(response));
|
|
110
|
+
const message = body2?.error?.message;
|
|
111
|
+
const code = body2?.error?.code;
|
|
112
|
+
if (typeof message === "string" && unsupportedImages(message) || typeof code === "string" && unsupportedImages(code.replaceAll("_", " "))) {
|
|
113
|
+
signal?.throwIfAborted();
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
} else await response.body?.cancel();
|
|
117
|
+
throw new Error("Model unavailable");
|
|
118
|
+
}
|
|
119
|
+
const body = await readBounded(response);
|
|
120
|
+
const parsed = parseUniqueJson(body);
|
|
121
|
+
const reported = z.object({
|
|
122
|
+
usage: z.object({
|
|
123
|
+
prompt_tokens: z.number().int().nonnegative(),
|
|
124
|
+
completion_tokens: z.number().int().nonnegative(),
|
|
125
|
+
prompt_tokens_details: z.object({ cached_tokens: z.number().int().nonnegative().optional() }).optional(),
|
|
126
|
+
cost: z.number().finite().nonnegative().optional()
|
|
127
|
+
}).optional()
|
|
128
|
+
}).parse(parsed).usage;
|
|
129
|
+
if (reported) {
|
|
130
|
+
const headerCost = response.headers.get("x-litellm-response-cost");
|
|
131
|
+
const cost = headerCost === null ? reported.cost : Number(headerCost);
|
|
132
|
+
request.onUsage?.(
|
|
133
|
+
usageSchema.parse({
|
|
134
|
+
inputTokens: reported.prompt_tokens,
|
|
135
|
+
outputTokens: reported.completion_tokens,
|
|
136
|
+
...reported.prompt_tokens_details?.cached_tokens !== void 0 && {
|
|
137
|
+
cacheReadTokens: reported.prompt_tokens_details.cached_tokens
|
|
138
|
+
},
|
|
139
|
+
...cost !== void 0 && Number.isFinite(cost) && cost >= 0 && { costUsd: cost }
|
|
140
|
+
})
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
signal?.throwIfAborted();
|
|
144
|
+
const result = completionSchema.parse(parsed);
|
|
145
|
+
return {
|
|
146
|
+
text: this.options.redactor.text(result.choices[0].message.content),
|
|
147
|
+
source: `team-litellm:${this.options.model}`,
|
|
148
|
+
...imageFallback && { imageFallback: true }
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
throw new Error("Model unavailable");
|
|
152
|
+
}
|
|
153
|
+
if (this.options.requireTeam) throw new Error("Server assessments require team credentials");
|
|
154
|
+
for (const imageFallback of [false, true]) {
|
|
155
|
+
const input = imageFallback ? omitImageAttachments(request.input) : request.input;
|
|
156
|
+
const session = await this.options.runtime.start(
|
|
157
|
+
{
|
|
158
|
+
actor: purpose,
|
|
159
|
+
toolMode: "none",
|
|
160
|
+
mcp: { url: "", token: "" },
|
|
161
|
+
system: `${request.system}
|
|
162
|
+
Return JSON matching this response schema exactly:
|
|
163
|
+
${JSON.stringify(request.responseSchema)}`,
|
|
164
|
+
access: this.options.localAccess ?? (this.options.runtime.id === "claude-code" && this.options.subscriptionToken ? { mode: "env", env: { CLAUDE_CODE_OAUTH_TOKEN: this.options.subscriptionToken } } : { mode: "inherit-login" })
|
|
165
|
+
},
|
|
166
|
+
signal
|
|
167
|
+
);
|
|
168
|
+
try {
|
|
169
|
+
let text = "";
|
|
170
|
+
let finished = false;
|
|
171
|
+
for await (const event of session.turn(
|
|
172
|
+
JSON.stringify(this.options.redactor.json(input)),
|
|
173
|
+
signal,
|
|
174
|
+
imageFallback ? void 0 : request.images
|
|
175
|
+
)) {
|
|
176
|
+
if (event.kind === "usage") {
|
|
177
|
+
const { kind: _kind, ...usage } = event;
|
|
178
|
+
request.onUsage?.(usage);
|
|
179
|
+
}
|
|
180
|
+
signal?.throwIfAborted();
|
|
181
|
+
if (finished || event.kind === "tool_call")
|
|
182
|
+
throw new Error("Independent session attempted a tool or continued after completion");
|
|
183
|
+
if (event.kind === "text") text += event.text;
|
|
184
|
+
if (text.length > 32e3) throw new Error("Model response too large");
|
|
185
|
+
if (event.kind === "turn_end") {
|
|
186
|
+
if (event.reason !== "done") {
|
|
187
|
+
if (!imageFallback && request.images?.length && event.reason === "error" && unsupportedImages(event.message ?? ""))
|
|
188
|
+
throw new UnsupportedImages();
|
|
189
|
+
throw new Error("Independent session did not complete");
|
|
190
|
+
}
|
|
191
|
+
finished = true;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!finished) throw new Error("Independent session did not complete");
|
|
195
|
+
return {
|
|
196
|
+
text: this.options.redactor.text(text),
|
|
197
|
+
source: `local-runtime:${this.options.runtime.id}`,
|
|
198
|
+
...imageFallback && { imageFallback: true }
|
|
199
|
+
};
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (!(error instanceof UnsupportedImages)) throw error;
|
|
202
|
+
signal?.throwIfAborted();
|
|
203
|
+
} finally {
|
|
204
|
+
await session.close();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
throw new Error("Model unavailable");
|
|
208
|
+
} catch {
|
|
209
|
+
throw new Error("Independent model call failed");
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
export {
|
|
214
|
+
IndependentModelCaller
|
|
215
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type FlowLifecycleStore } from "@open-qa/qa-engine";
|
|
2
|
+
export interface LifecycleOptions {
|
|
3
|
+
root?: string;
|
|
4
|
+
project?: string;
|
|
5
|
+
baseline?: string;
|
|
6
|
+
by?: string;
|
|
7
|
+
yes?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface LifecycleAdapters {
|
|
10
|
+
store?: FlowLifecycleStore;
|
|
11
|
+
output?: (line: string) => void;
|
|
12
|
+
interactive?: boolean;
|
|
13
|
+
confirm?: (message: string) => Promise<boolean>;
|
|
14
|
+
}
|
|
15
|
+
export declare function lifecycleCommand(action: "accept" | "retire", flow: string | undefined, options?: LifecycleOptions, adapters?: LifecycleAdapters): Promise<number>;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { lstat } from "node:fs/promises";
|
|
2
|
+
import { userInfo } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { stdin, stdout } from "node:process";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { lifecycleOf } from "@open-qa/qa-engine";
|
|
7
|
+
import { FileRunStore } from "./adapters/file-run-store.js";
|
|
8
|
+
import { runDirectory } from "./adapters/local-files.js";
|
|
9
|
+
import { QaDatabase, publicId } from "./db/database.js";
|
|
10
|
+
import { PgFlowStatus } from "./db/flow-status.js";
|
|
11
|
+
import { fileDraft } from "./flow-lifecycle.js";
|
|
12
|
+
import {
|
|
13
|
+
loadConfig,
|
|
14
|
+
loadFlowDocument,
|
|
15
|
+
loadFlowDocuments,
|
|
16
|
+
loadFlowKeys
|
|
17
|
+
} from "./flow-loader.js";
|
|
18
|
+
const reasons = {
|
|
19
|
+
draft: (flow) => `${flow} \xB7 draft \xB7 no first run for its current definition. Run it once with pnpm qa run <flow file>, review the replay, then accept.`,
|
|
20
|
+
changed: (flow) => `${flow} \xB7 draft \xB7 the flow file changed after its first run. Run it again and review the new replay before accepting.`,
|
|
21
|
+
active: (flow) => `${flow} \xB7 already active`,
|
|
22
|
+
quarantined: (flow) => `${flow} \xB7 quarantined \xB7 it was accepted earlier; use pnpm qa quarantine release ${flow} after fixing it.`,
|
|
23
|
+
retired: (flow) => `${flow} \xB7 retired \xB7 it no longer runs; a new key starts a new draft.`
|
|
24
|
+
};
|
|
25
|
+
async function lifecycleCommand(action, flow, options = {}, adapters = {}) {
|
|
26
|
+
const output = adapters.output ?? console.log;
|
|
27
|
+
const root = resolve(options.root ?? ".qa");
|
|
28
|
+
if (action === "accept" && !!flow === !!options.baseline)
|
|
29
|
+
throw new LifecycleInputError("accept requires either a flow key or --baseline <directory>");
|
|
30
|
+
if (action === "retire" && !flow) throw new LifecycleInputError("retire requires a flow key");
|
|
31
|
+
const confirm = async (message, allowYes) => {
|
|
32
|
+
if (allowYes && options.yes) return true;
|
|
33
|
+
if (!(adapters.interactive ?? Boolean(stdin.isTTY && stdout.isTTY)))
|
|
34
|
+
throw new LifecycleInputError(
|
|
35
|
+
allowYes ? "Confirmation required; pass --yes in non-interactive mode" : "Accepting a flow requires an interactive terminal: a person must watch its first run"
|
|
36
|
+
);
|
|
37
|
+
return (adapters.confirm ?? prompt)(message);
|
|
38
|
+
};
|
|
39
|
+
const by = options.by ?? userInfo().username;
|
|
40
|
+
const definitions = action === "retire" ? [] : options.baseline ? (await loadFlowDocuments(root, resolve(options.baseline))).filter(
|
|
41
|
+
(item) => !fileDraft(item)
|
|
42
|
+
) : [await findFlow(root, flow)];
|
|
43
|
+
let database;
|
|
44
|
+
try {
|
|
45
|
+
let store = adapters.store;
|
|
46
|
+
if (!store) {
|
|
47
|
+
const project = options.project ?? process.env.QA_PROJECT_ID ?? (await loadConfig(root)).projectId;
|
|
48
|
+
if (!publicId.safeParse(project).success)
|
|
49
|
+
throw new LifecycleInputError("Flow lifecycle requires a valid QA project ID");
|
|
50
|
+
if (!process.env.QA_DATABASE_URL)
|
|
51
|
+
throw new LifecycleInputError(
|
|
52
|
+
"Flow lifecycle requires QA_DATABASE_URL; its state lives in QA PostgreSQL"
|
|
53
|
+
);
|
|
54
|
+
database = new QaDatabase(process.env.QA_DATABASE_URL);
|
|
55
|
+
store = new PgFlowStatus(database, project);
|
|
56
|
+
}
|
|
57
|
+
if (options.baseline) return await baseline(store, definitions, by, output, confirm);
|
|
58
|
+
if (action === "retire") return await retire(store, flow, output, confirm);
|
|
59
|
+
return await accept(store, root, definitions[0], by, output, confirm);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error instanceof LifecycleInputError) throw error;
|
|
62
|
+
throw new Error(
|
|
63
|
+
"QA flow lifecycle command failed; check the project ID, QA_DATABASE_URL and applied migrations"
|
|
64
|
+
);
|
|
65
|
+
} finally {
|
|
66
|
+
await database?.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
class LifecycleInputError extends Error {
|
|
70
|
+
}
|
|
71
|
+
async function accept(store, root, definition, by, output, confirm) {
|
|
72
|
+
const key = definition.flow.key;
|
|
73
|
+
const revision = definition.definitions.flow.sha256;
|
|
74
|
+
const current = await store.get(key);
|
|
75
|
+
const status = lifecycleOf(current, revision);
|
|
76
|
+
if (status !== "review" || !current?.firstRun) {
|
|
77
|
+
const changed = current?.status === "review" && status === "draft";
|
|
78
|
+
output(reasons[changed ? "changed" : status === "review" ? "draft" : status](key));
|
|
79
|
+
return status === "active" ? 0 : 1;
|
|
80
|
+
}
|
|
81
|
+
const run = current.firstRun;
|
|
82
|
+
output(`${key} \xB7 review \xB7 first run ${run.runId} \xB7 ${new Date(run.at).toISOString()}`);
|
|
83
|
+
output(`Replay: ${await replayLocation(root, run.runId)}`);
|
|
84
|
+
const verdict = await localVerdict(root, run.runId);
|
|
85
|
+
if (verdict) output(`First run verdict: ${verdict}`);
|
|
86
|
+
if (!await confirm(
|
|
87
|
+
"Did you watch this replay and confirm the flow tests the intended behavior? [y/N] ",
|
|
88
|
+
false
|
|
89
|
+
)) {
|
|
90
|
+
output(`${key} \xB7 still in review`);
|
|
91
|
+
return 1;
|
|
92
|
+
}
|
|
93
|
+
const result = await store.accept(key, { revision, by });
|
|
94
|
+
if (!result.ok) {
|
|
95
|
+
output(reasons[result.reason](key));
|
|
96
|
+
return 1;
|
|
97
|
+
}
|
|
98
|
+
output(`${key} \xB7 active \xB7 accepted by ${by}; suite runs include it from now on`);
|
|
99
|
+
if (fileDraft(definition))
|
|
100
|
+
output(
|
|
101
|
+
`Its file is under drafts/ or marked status: draft. Move it out and drop the marker, keeping the key, so runs without QA_DATABASE_URL include it too.`
|
|
102
|
+
);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
async function retire(store, flow, output, confirm) {
|
|
106
|
+
const current = await store.get(flow);
|
|
107
|
+
if (current?.status !== "active" && current?.status !== "quarantined") {
|
|
108
|
+
output(describeRefusal(flow, current));
|
|
109
|
+
return current?.status === "retired" ? 0 : 1;
|
|
110
|
+
}
|
|
111
|
+
if (!await confirm(
|
|
112
|
+
`Retire ${flow}? It will never run again, and only a new key starts it over. [y/N] `,
|
|
113
|
+
true
|
|
114
|
+
)) {
|
|
115
|
+
output(`${flow} \xB7 ${current.status} \xB7 not retired`);
|
|
116
|
+
return 1;
|
|
117
|
+
}
|
|
118
|
+
const result = await store.retire(flow);
|
|
119
|
+
if (!result.ok) {
|
|
120
|
+
output(describeRefusal(flow, await store.get(flow)));
|
|
121
|
+
return 1;
|
|
122
|
+
}
|
|
123
|
+
output(`${flow} \xB7 retired`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
function describeRefusal(flow, current) {
|
|
127
|
+
if (current?.status === "retired") return `${flow} \xB7 already retired`;
|
|
128
|
+
return `${flow} \xB7 ${current?.status ?? "draft"} \xB7 only active or quarantined flows can be retired; leave an unaccepted flow out of the suite instead.`;
|
|
129
|
+
}
|
|
130
|
+
async function baseline(store, definitions, by, output, confirm) {
|
|
131
|
+
const keys = definitions.map(({ flow }) => flow.key).sort();
|
|
132
|
+
const states = await store.states(keys);
|
|
133
|
+
const adopt = keys.filter((key) => (states.get(key)?.status ?? "draft") === "draft");
|
|
134
|
+
if (!adopt.length) {
|
|
135
|
+
output(`Baseline \xB7 nothing to adopt; all ${keys.length} flow(s) are past draft`);
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
output(`Baseline \xB7 ${adopt.length} draft flow(s) become active without a first-run review:`);
|
|
139
|
+
for (const key of adopt) output(` ${key}`);
|
|
140
|
+
if (keys.length > adopt.length)
|
|
141
|
+
output(`${keys.length - adopt.length} flow(s) past draft keep their current state.`);
|
|
142
|
+
if (!await confirm(
|
|
143
|
+
"Use this only once, to adopt flows that already ran before lifecycle tracking. Continue? [y/N] ",
|
|
144
|
+
true
|
|
145
|
+
)) {
|
|
146
|
+
output("Baseline canceled");
|
|
147
|
+
return 1;
|
|
148
|
+
}
|
|
149
|
+
const adopted = await store.baseline(adopt, `baseline:${by}`);
|
|
150
|
+
output(`Baseline \xB7 ${adopted.length} flow(s) active`);
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
async function findFlow(root, key) {
|
|
154
|
+
const file = (await loadFlowKeys(root)).get(key);
|
|
155
|
+
if (!file)
|
|
156
|
+
throw new LifecycleInputError(`Flow ${key} not found under ${root}; pass its flow key`);
|
|
157
|
+
return loadFlowDocument(file, root);
|
|
158
|
+
}
|
|
159
|
+
async function replayLocation(root, runId) {
|
|
160
|
+
const directory = runDirectory(root, runId);
|
|
161
|
+
for (const [path, found] of [
|
|
162
|
+
[join(directory, "report.html"), "isFile"],
|
|
163
|
+
[directory, "isDirectory"]
|
|
164
|
+
]) {
|
|
165
|
+
try {
|
|
166
|
+
if ((await lstat(path))[found]())
|
|
167
|
+
return found === "isFile" ? `${path} (or pnpm qa open ${runId})` : `${path} (report not generated; pnpm qa open ${runId} opens the run directory)`;
|
|
168
|
+
} catch {
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return `run ${runId} is not in ${root}/runs; open its report on the machine that ran it`;
|
|
172
|
+
}
|
|
173
|
+
async function localVerdict(root, runId) {
|
|
174
|
+
try {
|
|
175
|
+
return (await new FileRunStore(root).getRun(runId))?.result?.verdict;
|
|
176
|
+
} catch {
|
|
177
|
+
return void 0;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async function prompt(message) {
|
|
181
|
+
const reader = createInterface({ input: stdin, output: stdout });
|
|
182
|
+
try {
|
|
183
|
+
return /^(y|yes)$/i.test((await reader.question(message)).trim());
|
|
184
|
+
} finally {
|
|
185
|
+
reader.close();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
export {
|
|
189
|
+
lifecycleCommand
|
|
190
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
const localCommand = async (command, args, timeoutMs = 3e4) => {
|
|
6
|
+
try {
|
|
7
|
+
await promisify(execFile)(command, args, {
|
|
8
|
+
timeout: timeoutMs,
|
|
9
|
+
killSignal: "SIGKILL",
|
|
10
|
+
maxBuffer: 1024 * 1024
|
|
11
|
+
});
|
|
12
|
+
} catch {
|
|
13
|
+
throw new Error("Local command failed or timed out");
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
function playwrightCli() {
|
|
17
|
+
return join(
|
|
18
|
+
dirname(
|
|
19
|
+
createRequire(import.meta.resolve("@open-qa/qa-stage/cli")).resolve("playwright/package.json")
|
|
20
|
+
),
|
|
21
|
+
"cli.js"
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
export {
|
|
25
|
+
localCommand,
|
|
26
|
+
playwrightCli
|
|
27
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { GmailCredentials } from "./vendor/gmail.js";
|
|
2
|
+
import type { Executor, ProvisionSpec, StageHandle } from "@open-qa/qa-engine";
|
|
3
|
+
import type { SystemConfig } from "@open-qa/qa-engine/protocol";
|
|
4
|
+
export interface LocalHostExecutorOptions {
|
|
5
|
+
redactions?: readonly string[];
|
|
6
|
+
systems?: SystemConfig;
|
|
7
|
+
headed?: boolean;
|
|
8
|
+
discord?: {
|
|
9
|
+
botToken: string;
|
|
10
|
+
};
|
|
11
|
+
email?: GmailCredentials;
|
|
12
|
+
page?: {
|
|
13
|
+
target: "dev" | "staging" | "prod";
|
|
14
|
+
allowedOrigins: string[];
|
|
15
|
+
allowedHosts?: string[];
|
|
16
|
+
targetOrigin?: string;
|
|
17
|
+
access?: {
|
|
18
|
+
origin: string;
|
|
19
|
+
clientId: string;
|
|
20
|
+
clientSecret: string;
|
|
21
|
+
};
|
|
22
|
+
permissions: Record<string, string[]>;
|
|
23
|
+
};
|
|
24
|
+
startupTimeoutMs?: number;
|
|
25
|
+
shutdownGraceMs?: number;
|
|
26
|
+
shutdownTimeoutMs?: number;
|
|
27
|
+
tempPrefix?: string;
|
|
28
|
+
command?: readonly [string, ...string[]];
|
|
29
|
+
}
|
|
30
|
+
export interface LocalHostStageHandle extends StageHandle, AsyncDisposable {
|
|
31
|
+
readonly pid: number;
|
|
32
|
+
readonly directory: string;
|
|
33
|
+
}
|
|
34
|
+
export declare class LocalHostExecutor implements Executor {
|
|
35
|
+
private readonly options;
|
|
36
|
+
constructor(options?: LocalHostExecutorOptions);
|
|
37
|
+
provision(spec: ProvisionSpec, signal?: AbortSignal): Promise<LocalHostStageHandle>;
|
|
38
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { HttpStageClient } from "./http-stage-client.js";
|
|
9
|
+
import { stageEnvironment } from "./stage-environment.js";
|
|
10
|
+
class LocalHostExecutor {
|
|
11
|
+
constructor(options = {}) {
|
|
12
|
+
this.options = options;
|
|
13
|
+
}
|
|
14
|
+
options;
|
|
15
|
+
async provision(spec, signal) {
|
|
16
|
+
signal?.throwIfAborted();
|
|
17
|
+
if (process.platform === "win32") throw new Error("local-host requires POSIX process groups");
|
|
18
|
+
if (spec.placement !== "local-host")
|
|
19
|
+
throw new Error("local-host cannot provision another placement");
|
|
20
|
+
if (spec.views?.some((view) => view.surface === "desktop"))
|
|
21
|
+
throw new Error("local-host does not support desktop views; use the e2b executor");
|
|
22
|
+
if (!spec.actors.length || spec.actors.some((actor) => !actor.trim()) || new Set(spec.actors).size !== spec.actors.length) {
|
|
23
|
+
throw new Error("At least one unique, nonempty actor is required");
|
|
24
|
+
}
|
|
25
|
+
const command = this.options.command ?? [
|
|
26
|
+
process.execPath,
|
|
27
|
+
"--import",
|
|
28
|
+
import.meta.resolve("tsx"),
|
|
29
|
+
fileURLToPath(import.meta.resolve("@open-qa/qa-stage/cli"))
|
|
30
|
+
];
|
|
31
|
+
const graceMs = this.options.shutdownGraceMs ?? 1e3;
|
|
32
|
+
const shutdownTimeoutMs = this.options.shutdownTimeoutMs ?? 5e3;
|
|
33
|
+
const deadline = AbortSignal.timeout(this.options.startupTimeoutMs ?? 3e4);
|
|
34
|
+
const startup = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
35
|
+
const directory = await mkdtemp(this.options.tempPrefix ?? join(tmpdir(), "open-qa-stage-"));
|
|
36
|
+
const conductorToken = randomBytes(32).toString("hex");
|
|
37
|
+
const actorTokens = Object.fromEntries(
|
|
38
|
+
spec.actors.map((actor) => [actor, randomBytes(32).toString("hex")])
|
|
39
|
+
);
|
|
40
|
+
const supervisor = spawn(
|
|
41
|
+
process.execPath,
|
|
42
|
+
[
|
|
43
|
+
fileURLToPath(new URL("./stage-supervisor.mjs", import.meta.url)),
|
|
44
|
+
JSON.stringify(command),
|
|
45
|
+
String(graceMs),
|
|
46
|
+
String(shutdownTimeoutMs)
|
|
47
|
+
],
|
|
48
|
+
{
|
|
49
|
+
cwd: directory,
|
|
50
|
+
env: {
|
|
51
|
+
...stageEnvironment(),
|
|
52
|
+
QA_STAGE_CONFIG: JSON.stringify({
|
|
53
|
+
host: "127.0.0.1",
|
|
54
|
+
port: 0,
|
|
55
|
+
dir: directory,
|
|
56
|
+
conductorToken,
|
|
57
|
+
actorTokens,
|
|
58
|
+
headed: this.options.headed ?? false,
|
|
59
|
+
page: this.options.page,
|
|
60
|
+
discord: this.options.discord,
|
|
61
|
+
email: this.options.email,
|
|
62
|
+
systems: this.options.systems,
|
|
63
|
+
redactions: this.options.redactions
|
|
64
|
+
})
|
|
65
|
+
},
|
|
66
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"]
|
|
67
|
+
}
|
|
68
|
+
);
|
|
69
|
+
let stagePid;
|
|
70
|
+
const trackStage = (value) => {
|
|
71
|
+
if (value && typeof value === "object" && "pid" in value && typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0) {
|
|
72
|
+
stagePid = value.pid;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
supervisor.on("message", trackStage);
|
|
76
|
+
let failure;
|
|
77
|
+
const exited = new Promise((resolve) => {
|
|
78
|
+
supervisor.once("error", () => {
|
|
79
|
+
failure = new Error("Cannot start the stage supervisor");
|
|
80
|
+
resolve();
|
|
81
|
+
});
|
|
82
|
+
supervisor.once("exit", (code) => {
|
|
83
|
+
if (code !== 0) failure ??= new Error("Stage supervisor cleanup failed");
|
|
84
|
+
resolve();
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
let disposal;
|
|
88
|
+
const dispose = () => disposal ??= (async () => {
|
|
89
|
+
signal?.removeEventListener("abort", abort);
|
|
90
|
+
if (supervisor.connected) supervisor.send({ type: "stop" }, () => {
|
|
91
|
+
});
|
|
92
|
+
if (!await settlesWithin(exited, graceMs + shutdownTimeoutMs + 1e3)) {
|
|
93
|
+
failure = new Error("Stage supervisor cleanup timed out");
|
|
94
|
+
if (stagePid) {
|
|
95
|
+
try {
|
|
96
|
+
process.kill(-stagePid, "SIGKILL");
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error.code !== "ESRCH") throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
supervisor.kill("SIGKILL");
|
|
102
|
+
await settlesWithin(exited, 1e3);
|
|
103
|
+
}
|
|
104
|
+
await rm(directory, { recursive: true, force: true });
|
|
105
|
+
if (failure) throw failure;
|
|
106
|
+
})();
|
|
107
|
+
const abort = () => {
|
|
108
|
+
void dispose().catch(() => {
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
112
|
+
void exited.then(() => {
|
|
113
|
+
signal?.removeEventListener("abort", abort);
|
|
114
|
+
supervisor.removeListener("message", trackStage);
|
|
115
|
+
});
|
|
116
|
+
try {
|
|
117
|
+
startup.throwIfAborted();
|
|
118
|
+
let ready;
|
|
119
|
+
let removeListeners = () => {
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
ready = await new Promise((resolve, reject) => {
|
|
123
|
+
const canceled = () => reject(new Error("Stage provisioning was canceled or timed out"));
|
|
124
|
+
const message = (value) => {
|
|
125
|
+
if (value && typeof value === "object" && "endpoint" in value && typeof value.endpoint === "string" && /^http:\/\/127\.0\.0\.1:\d+$/.test(value.endpoint) && "pid" in value && typeof value.pid === "number") {
|
|
126
|
+
resolve({ endpoint: value.endpoint, pid: value.pid });
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
removeListeners = () => {
|
|
130
|
+
startup.removeEventListener("abort", canceled);
|
|
131
|
+
supervisor.removeListener("message", message);
|
|
132
|
+
};
|
|
133
|
+
startup.addEventListener("abort", canceled, { once: true });
|
|
134
|
+
supervisor.on("message", message);
|
|
135
|
+
void exited.then(
|
|
136
|
+
() => reject(failure ?? new Error("Stage exited before becoming ready"))
|
|
137
|
+
);
|
|
138
|
+
if (startup.aborted) canceled();
|
|
139
|
+
});
|
|
140
|
+
} finally {
|
|
141
|
+
removeListeners();
|
|
142
|
+
}
|
|
143
|
+
const client = new HttpStageClient({ endpoint: ready.endpoint, conductorToken });
|
|
144
|
+
while (true) {
|
|
145
|
+
startup.throwIfAborted();
|
|
146
|
+
const health = await Promise.race([
|
|
147
|
+
client.health(startup),
|
|
148
|
+
exited.then(() => {
|
|
149
|
+
throw new Error("Stage exited before becoming ready");
|
|
150
|
+
})
|
|
151
|
+
]);
|
|
152
|
+
if (health.status === "ready") break;
|
|
153
|
+
await delay(25, void 0, { signal: startup });
|
|
154
|
+
}
|
|
155
|
+
startup.throwIfAborted();
|
|
156
|
+
return {
|
|
157
|
+
...ready,
|
|
158
|
+
directory,
|
|
159
|
+
placement: "local-host",
|
|
160
|
+
conductorToken,
|
|
161
|
+
actorTokens,
|
|
162
|
+
asyncDispose: dispose,
|
|
163
|
+
[Symbol.asyncDispose]: dispose
|
|
164
|
+
};
|
|
165
|
+
} catch (error) {
|
|
166
|
+
const failures = [error];
|
|
167
|
+
try {
|
|
168
|
+
await dispose();
|
|
169
|
+
} catch (cleanupError) {
|
|
170
|
+
failures.push(cleanupError);
|
|
171
|
+
}
|
|
172
|
+
if (failures.length > 1) {
|
|
173
|
+
throw new AggregateError(failures, "Stage provisioning failed and cleanup failed", {
|
|
174
|
+
cause: error
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
async function settlesWithin(promise, timeoutMs) {
|
|
182
|
+
let timer;
|
|
183
|
+
try {
|
|
184
|
+
return await Promise.race([
|
|
185
|
+
promise.then(() => true),
|
|
186
|
+
new Promise((resolve) => {
|
|
187
|
+
timer = setTimeout(() => resolve(false), timeoutMs);
|
|
188
|
+
})
|
|
189
|
+
]);
|
|
190
|
+
} finally {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
export {
|
|
195
|
+
LocalHostExecutor
|
|
196
|
+
};
|