@axn-dev/cmd-flow 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/adapter-dispose.test.d.ts +2 -0
- package/dist/adapter-dispose.test.d.ts.map +1 -0
- package/dist/adapter-dispose.test.js +105 -0
- package/dist/adapter-dispose.test.js.map +1 -0
- package/dist/adapter-routing.test.d.ts +2 -0
- package/dist/adapter-routing.test.d.ts.map +1 -0
- package/dist/adapter-routing.test.js +97 -0
- package/dist/adapter-routing.test.js.map +1 -0
- package/dist/adapter-video.test.d.ts +2 -0
- package/dist/adapter-video.test.d.ts.map +1 -0
- package/dist/adapter-video.test.js +80 -0
- package/dist/adapter-video.test.js.map +1 -0
- package/dist/adapters/adapterRegistry.d.ts +14 -0
- package/dist/adapters/adapterRegistry.d.ts.map +1 -0
- package/dist/adapters/adapterRegistry.js +25 -0
- package/dist/adapters/adapterRegistry.js.map +1 -0
- package/dist/adapters/http.d.ts +19 -0
- package/dist/adapters/http.d.ts.map +1 -0
- package/dist/adapters/http.js +47 -0
- package/dist/adapters/http.js.map +1 -0
- package/dist/completion.test.d.ts +2 -0
- package/dist/completion.test.d.ts.map +1 -0
- package/dist/completion.test.js +60 -0
- package/dist/completion.test.js.map +1 -0
- package/dist/env-expand.d.ts +17 -0
- package/dist/env-expand.d.ts.map +1 -0
- package/dist/env-expand.js +56 -0
- package/dist/env-expand.js.map +1 -0
- package/dist/env-expand.test.d.ts +2 -0
- package/dist/env-expand.test.d.ts.map +1 -0
- package/dist/env-expand.test.js +38 -0
- package/dist/env-expand.test.js.map +1 -0
- package/dist/flow.d.ts +157 -0
- package/dist/flow.d.ts.map +1 -0
- package/dist/flow.js +2466 -0
- package/dist/flow.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/interactive-host.d.ts +17 -0
- package/dist/interactive-host.d.ts.map +1 -0
- package/dist/interactive-host.js +64 -0
- package/dist/interactive-host.js.map +1 -0
- package/dist/interactive-ui.test.d.ts +2 -0
- package/dist/interactive-ui.test.d.ts.map +1 -0
- package/dist/interactive-ui.test.js +228 -0
- package/dist/interactive-ui.test.js.map +1 -0
- package/dist/interactive.d.ts +53 -0
- package/dist/interactive.d.ts.map +1 -0
- package/dist/interactive.js +78 -0
- package/dist/interactive.js.map +1 -0
- package/dist/interactive.test.d.ts +2 -0
- package/dist/interactive.test.d.ts.map +1 -0
- package/dist/interactive.test.js +161 -0
- package/dist/interactive.test.js.map +1 -0
- package/dist/live-session.d.ts +32 -0
- package/dist/live-session.d.ts.map +1 -0
- package/dist/live-session.js +115 -0
- package/dist/live-session.js.map +1 -0
- package/dist/llm-judge.d.ts +7 -0
- package/dist/llm-judge.d.ts.map +1 -0
- package/dist/llm-judge.js +190 -0
- package/dist/llm-judge.js.map +1 -0
- package/dist/orchestrator-host.d.ts +2 -0
- package/dist/orchestrator-host.d.ts.map +1 -0
- package/dist/orchestrator-host.js +190 -0
- package/dist/orchestrator-host.js.map +1 -0
- package/dist/orchestrator-host.test.d.ts +2 -0
- package/dist/orchestrator-host.test.d.ts.map +1 -0
- package/dist/orchestrator-host.test.js +201 -0
- package/dist/orchestrator-host.test.js.map +1 -0
- package/dist/pw/pw-runner.d.ts +11 -0
- package/dist/pw/pw-runner.d.ts.map +1 -0
- package/dist/pw/pw-runner.js +150 -0
- package/dist/pw/pw-runner.js.map +1 -0
- package/dist/pw/pw-spec.d.ts +2 -0
- package/dist/pw/pw-spec.d.ts.map +1 -0
- package/dist/pw/pw-spec.js +379 -0
- package/dist/pw/pw-spec.js.map +1 -0
- package/dist/repeat-llm.test.d.ts +2 -0
- package/dist/repeat-llm.test.d.ts.map +1 -0
- package/dist/repeat-llm.test.js +137 -0
- package/dist/repeat-llm.test.js.map +1 -0
- package/dist/screenshot.d.ts +83 -0
- package/dist/screenshot.d.ts.map +1 -0
- package/dist/screenshot.js +197 -0
- package/dist/screenshot.js.map +1 -0
- package/dist/screenshot.test.d.ts +2 -0
- package/dist/screenshot.test.d.ts.map +1 -0
- package/dist/screenshot.test.js +276 -0
- package/dist/screenshot.test.js.map +1 -0
- package/package.json +100 -3
- package/skills/axn-dev-flow/SKILL.md +464 -0
- package/README.md +0 -3
package/dist/flow.js
ADDED
|
@@ -0,0 +1,2466 @@
|
|
|
1
|
+
import { existsSync, readdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { createInterface } from "node:readline";
|
|
8
|
+
import { StartCommand } from "@axn-dev/core";
|
|
9
|
+
import { StopCommand } from "@axn-dev/core";
|
|
10
|
+
import { CleanCommand } from "@axn-dev/core";
|
|
11
|
+
import { ScenarioDiscoveryService, resolveDeviceEnv } from "@axn-dev/core";
|
|
12
|
+
import { getComposeProjectName, getServiceEndpoints, getRunningScenarioPort, isScenarioRunning, resolveEndpoints, substituteEnvVars } from "@axn-dev/core";
|
|
13
|
+
import { INTERACTIVE_ENV, browserSettings, disposeFlowAdapters, flowAdapter, flowAdaptersForTag, flowAdapterSpecs, hasFlowAdapter, flowMetric, hasFlowMetric, } from "@axn-dev/core";
|
|
14
|
+
import { loadFlowsFromFile, discoverAllFlows, writeFlowReport, evidenceDirFor, normalizeRunnerName, toJUnitXml, gitInfoFor, extractEmittedMetrics } from "@axn-dev/flow-format";
|
|
15
|
+
import { ManualFlowRunner } from "@axn-dev/flow-format";
|
|
16
|
+
import { evaluateScreenshotAssertion } from "./screenshot.js";
|
|
17
|
+
import { evaluateLlmAssertion } from "./llm-judge.js";
|
|
18
|
+
import { AdapterRegistry } from "./adapters/adapterRegistry.js";
|
|
19
|
+
import { loadAxnDevConfig, configSection } from "@axn-dev/core";
|
|
20
|
+
import { listFlowFiles } from "@axn-dev/flow-format";
|
|
21
|
+
import { runFlowWithPlaywright } from "./pw/pw-runner.js";
|
|
22
|
+
import { expandEnvVars, expandFlowEnv, expandStepArgs } from "./env-expand.js";
|
|
23
|
+
import { combineGates, terminalGate } from "./interactive.js";
|
|
24
|
+
import { LiveSession } from "./live-session.js";
|
|
25
|
+
import { parsePort, resolveInteractivePort, startInteractiveHost } from "./interactive-host.js";
|
|
26
|
+
const FLOW_FLAGS = [
|
|
27
|
+
"--file", "-f", "--model", "-m", "--filter", "-t", "--suite",
|
|
28
|
+
"--no-stop", "--no-build", "--clean-start", "--manual", "--interactive", "--interactive-ui", "--adapter",
|
|
29
|
+
"--report", "--report-format", "--quiet", "-q", "--fail-on-unavailable-metric",
|
|
30
|
+
"--infra", "-i", "--base-url", "--global", "-g", "--workbase", "--auto-port",
|
|
31
|
+
"--port", "--pwd", "-c", "--yes", "-y", "-B", "--runner", "--label",
|
|
32
|
+
"--metric", "--help", "-h",
|
|
33
|
+
];
|
|
34
|
+
function stepLabel(step) {
|
|
35
|
+
return step.description ?? step.name ?? step.args?.name ?? step.src ??
|
|
36
|
+
(step.value?.trim().split("\n")[0].slice(0, 60) || `<${step.type}>`);
|
|
37
|
+
}
|
|
38
|
+
export class FlowCommand {
|
|
39
|
+
gateFactory;
|
|
40
|
+
name = "flow";
|
|
41
|
+
description = "Run XML-defined agentic flow tests against scenarios";
|
|
42
|
+
complete(words) {
|
|
43
|
+
const prev = words[words.length - 2] ?? "";
|
|
44
|
+
const cur = words[words.length - 1] ?? "";
|
|
45
|
+
const valueFlag = cur === "-f" || cur === "--file";
|
|
46
|
+
if (prev === "-f" || prev === "--file" || valueFlag) {
|
|
47
|
+
return listFlowFiles(valueFlag ? "" : cur);
|
|
48
|
+
}
|
|
49
|
+
return FLOW_FLAGS.filter((f) => f.startsWith(cur) && f !== cur);
|
|
50
|
+
}
|
|
51
|
+
constructor(gateFactory = () => terminalGate()) {
|
|
52
|
+
this.gateFactory = gateFactory;
|
|
53
|
+
}
|
|
54
|
+
_resolvedFilePath = null;
|
|
55
|
+
/** --interactive: holds the run before each top-level step. */
|
|
56
|
+
gate = null;
|
|
57
|
+
/** --interactive-ui: the web stage following the run. */
|
|
58
|
+
observer = null;
|
|
59
|
+
/** Top-level step running now — progress lines belong to it on the stage. */
|
|
60
|
+
liveStep = null;
|
|
61
|
+
/** Product URL waiting for its step to pass: "ready" can come before the
|
|
62
|
+
* app answers, and a frame loaded then shows an error page for good. */
|
|
63
|
+
pendingProduct = null;
|
|
64
|
+
/** The product shows in a browser window of its own this flow. */
|
|
65
|
+
productWindow = false;
|
|
66
|
+
/** Adapter flows: scenario lifecycle for adapters declaring wantsScenario,
|
|
67
|
+
* prepared once per scenario and reused by every later step. */
|
|
68
|
+
adapterScenarioRun = null;
|
|
69
|
+
runnerMode = process.env.AXN_FLOW_RUNNER ?? null;
|
|
70
|
+
adapterRegistry = null;
|
|
71
|
+
orchestratorProcesses = new Map();
|
|
72
|
+
/** --quiet: suppress routine progress output (CI). */
|
|
73
|
+
quietMode = false;
|
|
74
|
+
/** --report-format: 'json' or 'junit'. */
|
|
75
|
+
reportFormat = "json";
|
|
76
|
+
/** --fail-on-unavailable-metric: error instead of skipping when a
|
|
77
|
+
* <metric> collector is missing or reports null. */
|
|
78
|
+
failOnUnavailableMetric = false;
|
|
79
|
+
reportPath = null;
|
|
80
|
+
/** --label: tag stored on the report so `flow compare`/`history` can
|
|
81
|
+
* address this run later. */
|
|
82
|
+
reportLabel = null;
|
|
83
|
+
help() {
|
|
84
|
+
return `
|
|
85
|
+
axn-dev flow [list] -f <file> [-m <model>] [-t <flow-name>]
|
|
86
|
+
|
|
87
|
+
Run XML flow tests against Docker Compose scenarios.
|
|
88
|
+
|
|
89
|
+
Subcommands:
|
|
90
|
+
list List all discovered flows (global + project repos)
|
|
91
|
+
list-adapters List registered flow adapters (plugin-contributed)
|
|
92
|
+
compare -f <file> A B Compare the latest reports labeled A and B —
|
|
93
|
+
aligns recorded metrics by name, shows delta
|
|
94
|
+
history -f <file> List every recorded metric across stored reports
|
|
95
|
+
[--metric <name>] [-t <flow>] [--label <l>]
|
|
96
|
+
|
|
97
|
+
Options:
|
|
98
|
+
-f, --file <path> Path to the XML flow file (required)
|
|
99
|
+
-m, --model <model> Run only the specified model (e.g. llama3.1:latest)
|
|
100
|
+
-t, --filter <name> Run only flows whose name contains the given string
|
|
101
|
+
-i, --infra <device> Run the flow against a deployed device (tsAdapter only)
|
|
102
|
+
--base-url <url> Run the flow against an already-deployed base URL —
|
|
103
|
+
any deployment (k8s, VM, …); no scenario is started.
|
|
104
|
+
Overrides url= on <scenario>; applies to all
|
|
105
|
+
scenarios in the run. env gets BASE_URL=<url>.
|
|
106
|
+
-p, --port <port> Single-port scenario: override the SCENARIO_PORT
|
|
107
|
+
--auto-port Resolve port conflicts by picking a free port from the configured range
|
|
108
|
+
--adapter <name=path> Register a custom adapter for this run (overrides config)
|
|
109
|
+
--manual Run the flow manually: show each step/assertion and
|
|
110
|
+
prompt for pass/fail verdicts, then write a report
|
|
111
|
+
--interactive Execute the flow one top-level step at a time: wait
|
|
112
|
+
for a key before each step (Enter run, s skip,
|
|
113
|
+
q abort); a failed step offers retry or skip.
|
|
114
|
+
Adapter flows only, for now
|
|
115
|
+
--interactive-ui [port] --interactive plus a web stage on 127.0.0.1: step
|
|
116
|
+
rail, product frame, Next/Skip/Retry (keys: Right,
|
|
117
|
+
PageDown, Space, S, R). Port: this flag, else
|
|
118
|
+
AXN_DEV_INTERACTIVE_PORT, else interactive.port in
|
|
119
|
+
config, else a free one. Terminal keys keep working
|
|
120
|
+
--clean-start Stop and remove volumes before starting the flow
|
|
121
|
+
-y, --yes Skip confirmation prompts (for --clean-start)
|
|
122
|
+
--no-stop Do not stop scenarios after the run
|
|
123
|
+
-q, --quiet CI mode: suppress scenario lifecycle and progress
|
|
124
|
+
noise; keep warnings, failures and the result
|
|
125
|
+
summary. Compose logs are only printed when a
|
|
126
|
+
scenario command fails.
|
|
127
|
+
--report <path> Additionally write the run report to <path>
|
|
128
|
+
(the default flows/.reports/*.json is always kept)
|
|
129
|
+
--label <name> Tag this run's report (report.label + filename):
|
|
130
|
+
'flow compare -f <file> A B' and 'flow history'
|
|
131
|
+
address stored runs by label
|
|
132
|
+
--report-format <fmt> Format for --report: json (default) or junit
|
|
133
|
+
(JUnit XML for CI test reports, e.g. GitLab)
|
|
134
|
+
--fail-on-unavailable-metric
|
|
135
|
+
Fail the flow when a <metric collect="..."> name
|
|
136
|
+
has no registered collector, or the collector
|
|
137
|
+
reports the metric unavailable (default: warn and
|
|
138
|
+
skip that metric)
|
|
139
|
+
--runner <axn|pw> Execution engine override: 'axn' (default) runs steps
|
|
140
|
+
through the orchestrator/script engine; 'pw' runs the
|
|
141
|
+
flow as a Playwright spec (test.step()s, traces,
|
|
142
|
+
standard reporters). Overrides the flow's runner=
|
|
143
|
+
attribute; AXN_FLOW_RUNNER does the same.
|
|
144
|
+
-h, --help Show this help
|
|
145
|
+
|
|
146
|
+
Flow XML:
|
|
147
|
+
<flow runner="axn|pw"> selects the execution engine for that flow;
|
|
148
|
+
<flows runner="pw"> sets the file-level default.
|
|
149
|
+
Note: runner= on a <step> is display metadata only
|
|
150
|
+
(serve UI) — it does not select an engine per step.
|
|
151
|
+
|
|
152
|
+
Reusable step files:
|
|
153
|
+
A .xml file containing exactly one step element (e.g. steps/login.xml
|
|
154
|
+
holding <step src="ft-login.ts"/>) can be bound from any flow:
|
|
155
|
+
<step action="login"/> finds login.xml in the flow dir, steps/,
|
|
156
|
+
and dirs listed via include="a,b" on
|
|
157
|
+
<flows>, <flow> or <steps>
|
|
158
|
+
<step file="steps/login.xml"/> explicit path relative to the flow file
|
|
159
|
+
Ambiguous names fail with a hint to use file=. Extra attributes on the
|
|
160
|
+
referencing step merge into the bound step's args (caller wins). file= and
|
|
161
|
+
action= cannot be combined; reserved names (engine elements, file/action/
|
|
162
|
+
include/src) cannot be custom tags or step-file names — flows are
|
|
163
|
+
validated at load.
|
|
164
|
+
|
|
165
|
+
Adapters decide how steps run:
|
|
166
|
+
tsAdapter Built-in: execute a TypeScript/Playwright script
|
|
167
|
+
against a service (default for <step>/<script>)
|
|
168
|
+
<name> Plugin adapters registered via axn-dev.flowAdapters
|
|
169
|
+
in a plugin package's manifest (e.g. 'axn-dev flow
|
|
170
|
+
list-adapters'). Custom step tags like <my-tag> are
|
|
171
|
+
dispatched to the adapter declaring that tag.
|
|
172
|
+
<name>=<path> Script-file adapters: run via tsx with the step
|
|
173
|
+
passed as AXN_STEP JSON in process.env. Resolved in
|
|
174
|
+
order: --adapter <name=path>, 'adapters:' in
|
|
175
|
+
.axn-dev/config.yaml, the step's src attribute,
|
|
176
|
+
then adapters/<name>.ts|.js next to the flow file.
|
|
177
|
+
|
|
178
|
+
Assertions:
|
|
179
|
+
<assert that="contains|num_responses|exitCode|screenshot|llm|duration|script|metric" .../>
|
|
180
|
+
Placement:
|
|
181
|
+
- bare <assert/> between steps — evaluates the output accumulated so far;
|
|
182
|
+
add fresh="true" to see only output produced since the previous assert
|
|
183
|
+
- <assertions desc="..."> — a named report group: desc= labels all its
|
|
184
|
+
asserts in reports, fresh="true" applies to the whole group
|
|
185
|
+
- nested inside a producing step (<step>, <usermessage>, <extract>,
|
|
186
|
+
custom tags) — evaluates THAT step's own output: the step is the
|
|
187
|
+
subject under test
|
|
188
|
+
that="llm" Judge the captured output with an LLM or a binary
|
|
189
|
+
judge service. Rubric comes from 'prompt', 'value'
|
|
190
|
+
or the element body; 'judge' selects the evaluator:
|
|
191
|
+
'ollama/<model>' (OLLAMA_BASE_URL), 'openai/<model>'
|
|
192
|
+
(OPENAI_API_KEY, OPENAI_BASE_URL), or an http(s)://
|
|
193
|
+
endpoint POSTed {prompt, response} that must return
|
|
194
|
+
a binary verdict ({pass:true|false} or PASS/FAIL).
|
|
195
|
+
Defaults to $AXN_JUDGE.
|
|
196
|
+
that="duration" Step wall-clock time in ms — min=/max= bounds, or
|
|
197
|
+
numeric 'value' as shorthand max. Needs a step
|
|
198
|
+
context (nested on a producing step).
|
|
199
|
+
that="script" A ts/js assertion script (src= or value=) run via
|
|
200
|
+
tsx; gets the output under test as $AXN_OUTPUT and
|
|
201
|
+
the assert as $AXN_ASSERT; exit 0 = pass.
|
|
202
|
+
that="metric" Bound a recorded metric: name= required, min=/max=
|
|
203
|
+
bounds (numeric 'value' is shorthand max). Checks
|
|
204
|
+
the latest record — emitted or collected.
|
|
205
|
+
that="llm" (see above)
|
|
206
|
+
|
|
207
|
+
Flakiness / non-determinism:
|
|
208
|
+
<repeat num="N" success="R"> wraps steps: the children run N times and the
|
|
209
|
+
block passes when at least R (a rate "0.8" or a percent "80%") of the
|
|
210
|
+
iterations pass. An iteration fails on a failed inner assertion or a step
|
|
211
|
+
error; failed iterations do not stop the block. Assertions inside a repeat
|
|
212
|
+
see only that iteration's output. Repeats nest; the block reports as a
|
|
213
|
+
'repeat' assertion with per-run stats in the JSON report.
|
|
214
|
+
<metric id="name" collect="duration,..."> wraps steps: records named
|
|
215
|
+
measurements of the block under flows[].metrics[]
|
|
216
|
+
in the report — pure measurement, never a
|
|
217
|
+
pass/fail verdict (use that="duration" to bound a
|
|
218
|
+
single step). 'duration' is built in; other names
|
|
219
|
+
resolve to plugin collectors (axn-dev.flowMetrics).
|
|
220
|
+
<stopwatch id="n"> is sugar for
|
|
221
|
+
<metric id="n" collect="duration">.
|
|
222
|
+
Emitted metrics: a step can also report its own measurements —
|
|
223
|
+
any output line 'AXN_METRIC {"name":"x","value":1,
|
|
224
|
+
"unit":"ms","samples":[...],"better":"lower"}' is
|
|
225
|
+
lifted out of the output into metrics[] (asserts
|
|
226
|
+
never see it; plugin adapters may call
|
|
227
|
+
ctx.emitMetric instead). Everything emitted is
|
|
228
|
+
recorded — bound it with that="metric".
|
|
229
|
+
<extract selector="..." [attr="text|value|html|<name>"]/> reads a DOM
|
|
230
|
+
element's content into the output stream — e.g. the
|
|
231
|
+
last message of an interactive HTML chat — so
|
|
232
|
+
contains/llm assertions can judge it. Runs on the
|
|
233
|
+
live page (orchestrator) or the PW runner.
|
|
234
|
+
that="screenshot" Capture the page (or the 'selector' element) at 'url'
|
|
235
|
+
(default: BASE_URL) with headless Chromium and compare
|
|
236
|
+
it against the reference PNG at 'value' (relative to
|
|
237
|
+
the flow file). Antialiasing is tolerated; layout and
|
|
238
|
+
shape changes fail. An element capture is cropped to
|
|
239
|
+
the element — select a container element (or omit
|
|
240
|
+
'selector') to also catch position changes. Extra
|
|
241
|
+
attributes:
|
|
242
|
+
selector="css" fullPage="true" maxDiff="0.02"
|
|
243
|
+
threshold="0.1" viewport="1280x800" wait="500|css".
|
|
244
|
+
Diffs land in flows/.reports/screenshots/.
|
|
245
|
+
AXN_FLOW_UPDATE_SCREENSHOTS=1 rewrites the reference.
|
|
246
|
+
|
|
247
|
+
Examples:
|
|
248
|
+
axn-dev flow -f flows/example.xml
|
|
249
|
+
axn-dev flow -f flows/example.xml -m llama3.1:latest
|
|
250
|
+
axn-dev flow -f flows/example.xml -t "app loads"
|
|
251
|
+
axn-dev flow -f flows/example.xml -t "app loads" --manual
|
|
252
|
+
axn-dev flow -f flows/example.xml --base-url https://staging.example.com
|
|
253
|
+
# or pin the deployment in XML: <scenario name="staging" url="https://…" adapter="…"/>
|
|
254
|
+
`;
|
|
255
|
+
}
|
|
256
|
+
async execute(args) {
|
|
257
|
+
const runStartedAt = Date.now();
|
|
258
|
+
if (args[0] === "list") {
|
|
259
|
+
this.listFlows();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (args[0] === "list-adapters") {
|
|
263
|
+
this.listAdapters();
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (args[0] === "compare" || args[0] === "history") {
|
|
267
|
+
this.metricReportCommand(args[0], args.slice(1));
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
let filePath = null;
|
|
271
|
+
let modelFilter = null;
|
|
272
|
+
let flowFilter = null;
|
|
273
|
+
let infra = null;
|
|
274
|
+
let baseUrlFlag = null;
|
|
275
|
+
const adapterOverrides = {};
|
|
276
|
+
let autoPort = false;
|
|
277
|
+
let portFlag = null;
|
|
278
|
+
let stopAfter = true;
|
|
279
|
+
let cleanStart = false;
|
|
280
|
+
let yes = false;
|
|
281
|
+
let manual = false;
|
|
282
|
+
let interactive = false;
|
|
283
|
+
let interactiveUi = false;
|
|
284
|
+
let interactiveUiPort = null;
|
|
285
|
+
let liveSession = null;
|
|
286
|
+
let liveSessionPort = 0;
|
|
287
|
+
for (let i = 0; i < args.length; i++) {
|
|
288
|
+
const arg = args[i];
|
|
289
|
+
if (arg === "-f" || arg === "--file") {
|
|
290
|
+
filePath = args[++i];
|
|
291
|
+
if (!filePath)
|
|
292
|
+
throw new Error("--file requires a value");
|
|
293
|
+
}
|
|
294
|
+
else if (arg === "-m" || arg === "--model") {
|
|
295
|
+
modelFilter = args[++i];
|
|
296
|
+
if (!modelFilter)
|
|
297
|
+
throw new Error("--model requires a value");
|
|
298
|
+
}
|
|
299
|
+
else if (arg === "-t" || arg === "--filter") {
|
|
300
|
+
flowFilter = args[++i];
|
|
301
|
+
if (!flowFilter)
|
|
302
|
+
throw new Error("--filter requires a value");
|
|
303
|
+
}
|
|
304
|
+
else if (arg === "-i" || arg === "--infra") {
|
|
305
|
+
infra = args[++i];
|
|
306
|
+
if (!infra)
|
|
307
|
+
throw new Error("--infra requires a value");
|
|
308
|
+
}
|
|
309
|
+
else if (arg === "--base-url") {
|
|
310
|
+
const value = args[++i];
|
|
311
|
+
if (!value)
|
|
312
|
+
throw new Error("--base-url requires a value");
|
|
313
|
+
try {
|
|
314
|
+
const proto = new URL(value).protocol;
|
|
315
|
+
if (proto !== "http:" && proto !== "https:")
|
|
316
|
+
throw new Error();
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
throw new Error("--base-url requires an http(s) URL");
|
|
320
|
+
}
|
|
321
|
+
baseUrlFlag = value.replace(/\/+$/, "");
|
|
322
|
+
}
|
|
323
|
+
else if (arg === "--runner") {
|
|
324
|
+
this.runnerMode = normalizeRunnerName(args[++i]) ?? null;
|
|
325
|
+
if (!this.runnerMode)
|
|
326
|
+
throw new Error("--runner requires a value");
|
|
327
|
+
}
|
|
328
|
+
else if (arg === "--adapter") {
|
|
329
|
+
const adapterArg = args[++i];
|
|
330
|
+
if (!adapterArg)
|
|
331
|
+
throw new Error("--adapter requires a value");
|
|
332
|
+
const eq = adapterArg.indexOf("=");
|
|
333
|
+
if (eq <= 0 || eq === adapterArg.length - 1) {
|
|
334
|
+
throw new Error("--adapter value must be in the form <name>=<path>");
|
|
335
|
+
}
|
|
336
|
+
const name = adapterArg.slice(0, eq);
|
|
337
|
+
const path = adapterArg.slice(eq + 1);
|
|
338
|
+
adapterOverrides[name] = resolve(path);
|
|
339
|
+
}
|
|
340
|
+
else if (arg === "--port" || arg === "-p") {
|
|
341
|
+
const value = args[++i];
|
|
342
|
+
const parsed = value ? parseInt(value, 10) : NaN;
|
|
343
|
+
if (isNaN(parsed) || parsed <= 0 || parsed > 65535) {
|
|
344
|
+
throw new Error("--port requires a valid port number (1-65535)");
|
|
345
|
+
}
|
|
346
|
+
portFlag = parsed;
|
|
347
|
+
}
|
|
348
|
+
else if (arg === "--auto-port") {
|
|
349
|
+
autoPort = true;
|
|
350
|
+
}
|
|
351
|
+
else if (arg === "--no-stop") {
|
|
352
|
+
stopAfter = false;
|
|
353
|
+
}
|
|
354
|
+
else if (arg === "--quiet" || arg === "-q") {
|
|
355
|
+
this.quietMode = true;
|
|
356
|
+
}
|
|
357
|
+
else if (arg === "--fail-on-unavailable-metric") {
|
|
358
|
+
this.failOnUnavailableMetric = true;
|
|
359
|
+
}
|
|
360
|
+
else if (arg === "--label") {
|
|
361
|
+
this.reportLabel = args[++i];
|
|
362
|
+
if (!this.reportLabel)
|
|
363
|
+
throw new Error("--label requires a value");
|
|
364
|
+
}
|
|
365
|
+
else if (arg === "--report") {
|
|
366
|
+
this.reportPath = args[++i];
|
|
367
|
+
if (!this.reportPath)
|
|
368
|
+
throw new Error("--report requires a path");
|
|
369
|
+
}
|
|
370
|
+
else if (arg === "--report-format") {
|
|
371
|
+
const fmt = args[++i];
|
|
372
|
+
if (fmt !== "json" && fmt !== "junit") {
|
|
373
|
+
throw new Error("--report-format must be 'json' or 'junit'");
|
|
374
|
+
}
|
|
375
|
+
this.reportFormat = fmt;
|
|
376
|
+
}
|
|
377
|
+
else if (arg === "--manual") {
|
|
378
|
+
manual = true;
|
|
379
|
+
}
|
|
380
|
+
else if (arg === "--interactive") {
|
|
381
|
+
interactive = true;
|
|
382
|
+
}
|
|
383
|
+
else if (arg === "--interactive-ui") {
|
|
384
|
+
interactive = true;
|
|
385
|
+
interactiveUi = true;
|
|
386
|
+
if (/^\d+$/.test(args[i + 1] ?? ""))
|
|
387
|
+
interactiveUiPort = parsePort(args[++i], "--interactive-ui");
|
|
388
|
+
}
|
|
389
|
+
else if (arg === "--clean-start") {
|
|
390
|
+
cleanStart = true;
|
|
391
|
+
}
|
|
392
|
+
else if (arg === "--yes" || arg === "-y") {
|
|
393
|
+
yes = true;
|
|
394
|
+
}
|
|
395
|
+
else if (arg === "-h" || arg === "--help") {
|
|
396
|
+
console.log(this.help());
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (!filePath) {
|
|
401
|
+
throw new Error("--file is required. Run 'axn-dev flow --help' for examples.");
|
|
402
|
+
}
|
|
403
|
+
if (baseUrlFlag) {
|
|
404
|
+
if (infra)
|
|
405
|
+
throw new Error("--base-url cannot be combined with --infra");
|
|
406
|
+
if (cleanStart)
|
|
407
|
+
throw new Error("--base-url cannot be combined with --clean-start (deployment targets have no local volumes)");
|
|
408
|
+
if (portFlag !== null)
|
|
409
|
+
throw new Error("--base-url cannot be combined with --port");
|
|
410
|
+
if (autoPort)
|
|
411
|
+
throw new Error("--base-url cannot be combined with --auto-port");
|
|
412
|
+
}
|
|
413
|
+
const axnConfig = loadAxnDevConfig();
|
|
414
|
+
this.adapterRegistry = new AdapterRegistry(configSection(axnConfig, "adapters") ?? {}, adapterOverrides);
|
|
415
|
+
this._resolvedFilePath = resolve(process.cwd(), filePath);
|
|
416
|
+
const flows = loadFlowsFromFile(this._resolvedFilePath);
|
|
417
|
+
const selectedFlows = flowFilter
|
|
418
|
+
? flows.filter((f) => f.name.toLowerCase().includes(flowFilter.toLowerCase()))
|
|
419
|
+
: flows;
|
|
420
|
+
if (selectedFlows.length === 0) {
|
|
421
|
+
throw new Error(`No flows matched filter '${flowFilter}'`);
|
|
422
|
+
}
|
|
423
|
+
this.warnForDeployments(selectedFlows, { infra, baseUrlFlag, portFlag, autoPort, stopAfter });
|
|
424
|
+
if (interactive) {
|
|
425
|
+
if (manual)
|
|
426
|
+
throw new Error("--interactive cannot be used with --manual");
|
|
427
|
+
if (infra)
|
|
428
|
+
throw new Error("--interactive cannot be used with --infra");
|
|
429
|
+
// Before any scenario starts: a run nobody can drive fails here.
|
|
430
|
+
if (interactiveUi) {
|
|
431
|
+
const session = new LiveSession();
|
|
432
|
+
liveSession = session;
|
|
433
|
+
// Resolved now so a bad port fails before anything starts.
|
|
434
|
+
liveSessionPort = resolveInteractivePort(interactiveUiPort, process.env, configSection(axnConfig, "interactive")?.port);
|
|
435
|
+
// The web stage is a controller on its own; the terminal joins when there is one.
|
|
436
|
+
let terminal = null;
|
|
437
|
+
try {
|
|
438
|
+
terminal = this.gateFactory();
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
terminal = null;
|
|
442
|
+
}
|
|
443
|
+
this.gate = combineGates(terminal ? [session, terminal] : [session]);
|
|
444
|
+
this.observer = session;
|
|
445
|
+
}
|
|
446
|
+
else {
|
|
447
|
+
this.gate = this.gateFactory();
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (manual) {
|
|
451
|
+
if (selectedFlows.length > 1) {
|
|
452
|
+
throw new Error("--manual requires a single flow; use -t to select one");
|
|
453
|
+
}
|
|
454
|
+
if (infra) {
|
|
455
|
+
throw new Error("--manual cannot be used with --infra");
|
|
456
|
+
}
|
|
457
|
+
if (cleanStart) {
|
|
458
|
+
throw new Error("--manual cannot be used with --clean-start");
|
|
459
|
+
}
|
|
460
|
+
const flow = selectedFlows[0];
|
|
461
|
+
const startedScenarios = new Set();
|
|
462
|
+
try {
|
|
463
|
+
// Deployment-targeted scenarios (url= or --base-url) need no start.
|
|
464
|
+
const localScenarios = flow.scenarios.filter((s) => !this.deploymentUrl(s, flow, baseUrlFlag));
|
|
465
|
+
if (localScenarios.length > 0) {
|
|
466
|
+
const startScenario = await this.confirm(`Start scenario(s) automatically for manual run? [y/N] `);
|
|
467
|
+
if (startScenario) {
|
|
468
|
+
for (const scenario of localScenarios) {
|
|
469
|
+
await this.prepareScenario(scenario, flow, startedScenarios, autoPort, portFlag);
|
|
470
|
+
console.log(`Scenario '${scenario.name}' is ready.`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
else {
|
|
474
|
+
console.log("Continuing manual run without starting scenarios.");
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const runner = new ManualFlowRunner(flow, this._resolvedFilePath);
|
|
478
|
+
const result = await runner.runInteractive();
|
|
479
|
+
if (!result.passed) {
|
|
480
|
+
throw new Error("Manual flow did not pass");
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
finally {
|
|
484
|
+
if (stopAfter) {
|
|
485
|
+
for (const scenario of startedScenarios) {
|
|
486
|
+
try {
|
|
487
|
+
await this.quietly(() => new StopCommand().execute(["-s", scenario], { quiet: this.quietMode }));
|
|
488
|
+
}
|
|
489
|
+
catch (err) {
|
|
490
|
+
console.error(`\x1b[33mWarning: failed to stop scenario '${scenario}': ${err instanceof Error ? err.message : err}\x1b[0m`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (cleanStart && infra) {
|
|
498
|
+
throw new Error("--clean-start cannot be used with --infra");
|
|
499
|
+
}
|
|
500
|
+
if (cleanStart) {
|
|
501
|
+
const scenarioNames = new Set();
|
|
502
|
+
for (const flow of selectedFlows) {
|
|
503
|
+
for (const scenario of flow.scenarios) {
|
|
504
|
+
// Deployment targets have no local volumes to wipe.
|
|
505
|
+
if (!this.deploymentUrl(scenario, flow, null))
|
|
506
|
+
scenarioNames.add(scenario.name);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (scenarioNames.size > 0 && !yes) {
|
|
510
|
+
const confirmed = await this.confirm(`This will wipe all data for the scenario(s) used by this flow. Continue? [y/N] `);
|
|
511
|
+
if (!confirmed) {
|
|
512
|
+
console.log("Aborted.");
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
for (const name of scenarioNames) {
|
|
517
|
+
await this.quietly(() => new CleanCommand().execute(["-s", name, "-y"], { quiet: this.quietMode }));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const startedScenarios = new Set();
|
|
521
|
+
const results = [];
|
|
522
|
+
// A finally does not run on Ctrl-C: without this, an adapter's browser or
|
|
523
|
+
// session outlives the run, and the process never exits.
|
|
524
|
+
// Steps, adapters and their subprocesses see the run mode, e.g. for a
|
|
525
|
+
// visible browser (AXN_DEV_BROWSER_HEADED=auto). Set and the host started
|
|
526
|
+
// inside the try below, so every exit restores and closes them.
|
|
527
|
+
const interactiveEnvBefore = process.env[INTERACTIVE_ENV];
|
|
528
|
+
let host = null;
|
|
529
|
+
let current = null;
|
|
530
|
+
const onSignal = (signal) => {
|
|
531
|
+
console.error(`\n${signal}: tearing down flow adapters…`);
|
|
532
|
+
void this.disposeAdapters(current).finally(() => process.exit(signal === "SIGINT" ? 130 : 143));
|
|
533
|
+
};
|
|
534
|
+
process.once("SIGINT", onSignal);
|
|
535
|
+
process.once("SIGTERM", onSignal);
|
|
536
|
+
try {
|
|
537
|
+
if (interactive)
|
|
538
|
+
process.env[INTERACTIVE_ENV] = "1";
|
|
539
|
+
if (liveSession) {
|
|
540
|
+
host = await startInteractiveHost(liveSession, liveSessionPort);
|
|
541
|
+
console.log(`\nInteractive driver: ${host.driverUrl}\nInteractive stage: ${host.stageUrl}\n`);
|
|
542
|
+
}
|
|
543
|
+
for (const flow of selectedFlows) {
|
|
544
|
+
current = flow;
|
|
545
|
+
try {
|
|
546
|
+
const flowResults = await this.runFlow(flow, modelFilter, startedScenarios, infra, autoPort, portFlag, baseUrlFlag);
|
|
547
|
+
results.push(...flowResults);
|
|
548
|
+
this.observer?.finished(flowResults.every((r) => r.passed));
|
|
549
|
+
}
|
|
550
|
+
catch (err) {
|
|
551
|
+
this.observer?.finished(false);
|
|
552
|
+
throw err;
|
|
553
|
+
}
|
|
554
|
+
finally {
|
|
555
|
+
await this.disposeAdapters(flow);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
finally {
|
|
560
|
+
process.removeListener("SIGINT", onSignal);
|
|
561
|
+
process.removeListener("SIGTERM", onSignal);
|
|
562
|
+
await host?.close();
|
|
563
|
+
if (interactive) {
|
|
564
|
+
if (interactiveEnvBefore === undefined)
|
|
565
|
+
delete process.env[INTERACTIVE_ENV];
|
|
566
|
+
else
|
|
567
|
+
process.env[INTERACTIVE_ENV] = interactiveEnvBefore;
|
|
568
|
+
}
|
|
569
|
+
for (const [key, proc] of this.orchestratorProcesses) {
|
|
570
|
+
try {
|
|
571
|
+
await proc.stop();
|
|
572
|
+
}
|
|
573
|
+
catch (err) {
|
|
574
|
+
console.error(`\x1b[33mWarning: failed to stop orchestrator for '${key}': ${err instanceof Error ? err.message : err}\x1b[0m`);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
this.orchestratorProcesses.clear();
|
|
578
|
+
if (stopAfter) {
|
|
579
|
+
for (const scenario of startedScenarios) {
|
|
580
|
+
try {
|
|
581
|
+
await this.quietly(() => new StopCommand().execute(["-s", scenario], { quiet: this.quietMode }));
|
|
582
|
+
}
|
|
583
|
+
catch (err) {
|
|
584
|
+
console.error(`\x1b[33mWarning: failed to stop scenario '${scenario}': ${err instanceof Error ? err.message : err}\x1b[0m`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
const durationMs = Date.now() - runStartedAt;
|
|
590
|
+
if (this._resolvedFilePath) {
|
|
591
|
+
writeFlowReport(this._resolvedFilePath, results, {
|
|
592
|
+
durationMs,
|
|
593
|
+
label: this.reportLabel ?? undefined,
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
this.writeExtraReport(results, durationMs);
|
|
597
|
+
this.printSummary(results);
|
|
598
|
+
if (results.some((r) => !r.passed)) {
|
|
599
|
+
throw new Error("One or more flow assertions failed");
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* `flow compare -f <file> <labelA> <labelB> [-t flow]` and
|
|
604
|
+
* `flow history -f <file> [--metric n] [-t flow] [--label l]` —
|
|
605
|
+
* query the stored .reports/*.json of a flow file. Reports are the
|
|
606
|
+
* metrics store: compare aligns two labeled runs' metrics by name,
|
|
607
|
+
* history lists every recorded metric over time.
|
|
608
|
+
*/
|
|
609
|
+
metricReportCommand(cmd, args) {
|
|
610
|
+
let file = null;
|
|
611
|
+
let flowFilter = null;
|
|
612
|
+
let metricFilter = null;
|
|
613
|
+
let labelFilter = null;
|
|
614
|
+
const positional = [];
|
|
615
|
+
for (let i = 0; i < args.length; i++) {
|
|
616
|
+
const a = args[i];
|
|
617
|
+
if (a === "-f" || a === "--file")
|
|
618
|
+
file = args[++i];
|
|
619
|
+
else if (a === "-t" || a === "--filter")
|
|
620
|
+
flowFilter = args[++i];
|
|
621
|
+
else if (a === "--metric")
|
|
622
|
+
metricFilter = args[++i];
|
|
623
|
+
else if (a === "--label")
|
|
624
|
+
labelFilter = args[++i];
|
|
625
|
+
else if (!a.startsWith("-"))
|
|
626
|
+
positional.push(a);
|
|
627
|
+
}
|
|
628
|
+
if (!file)
|
|
629
|
+
throw new Error(`${cmd} needs -f <flow-file>`);
|
|
630
|
+
const reportsDir = join(dirname(resolve(process.cwd(), file)), ".reports");
|
|
631
|
+
if (!existsSync(reportsDir))
|
|
632
|
+
throw new Error(`No reports found for ${file} (${reportsDir} does not exist)`);
|
|
633
|
+
const reports = readdirSync(reportsDir)
|
|
634
|
+
.filter((n) => n.startsWith("flow-report-") && n.endsWith(".json"))
|
|
635
|
+
.map((n) => {
|
|
636
|
+
try {
|
|
637
|
+
return JSON.parse(readFileSync(join(reportsDir, n), "utf-8"));
|
|
638
|
+
}
|
|
639
|
+
catch {
|
|
640
|
+
return null;
|
|
641
|
+
}
|
|
642
|
+
})
|
|
643
|
+
.filter((r) => !!r)
|
|
644
|
+
.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
645
|
+
if (reports.length === 0)
|
|
646
|
+
throw new Error(`No reports found in ${reportsDir}`);
|
|
647
|
+
/** Latest metric record per name within one flow result. */
|
|
648
|
+
const metricsOf = (r, flowName) => {
|
|
649
|
+
const out = new Map();
|
|
650
|
+
for (const f of r.flows ?? []) {
|
|
651
|
+
if (flowName && f.flow !== flowName)
|
|
652
|
+
continue;
|
|
653
|
+
if (flowFilter && !f.flow.includes(flowFilter))
|
|
654
|
+
continue;
|
|
655
|
+
for (const m of f.metrics ?? [])
|
|
656
|
+
out.set(`${f.flow}::${m.name}`, { metric: m, flow: f.flow });
|
|
657
|
+
}
|
|
658
|
+
return out;
|
|
659
|
+
};
|
|
660
|
+
if (cmd === "compare") {
|
|
661
|
+
const [labelA, labelB] = positional;
|
|
662
|
+
if (!labelA || !labelB)
|
|
663
|
+
throw new Error("compare needs two labels: flow compare -f <file> <A> <B>");
|
|
664
|
+
const find = (l) => [...reports].reverse().find((r) => r.label === l);
|
|
665
|
+
const repA = find(labelA);
|
|
666
|
+
const repB = find(labelB);
|
|
667
|
+
if (!repA)
|
|
668
|
+
throw new Error(`No report labeled '${labelA}' — run with --label ${labelA}`);
|
|
669
|
+
if (!repB)
|
|
670
|
+
throw new Error(`No report labeled '${labelB}' — run with --label ${labelB}`);
|
|
671
|
+
const mA = metricsOf(repA);
|
|
672
|
+
const mB = metricsOf(repB);
|
|
673
|
+
console.log(`\nComparing '${labelA}' (${repA.timestamp}) → '${labelB}' (${repB.timestamp})\n`);
|
|
674
|
+
const keys = [...new Set([...mA.keys(), ...mB.keys()])].sort();
|
|
675
|
+
for (const k of keys) {
|
|
676
|
+
const a = mA.get(k)?.metric;
|
|
677
|
+
const b = mB.get(k)?.metric;
|
|
678
|
+
const flow = mA.get(k)?.flow ?? mB.get(k)?.flow ?? "";
|
|
679
|
+
if (!a || !b) {
|
|
680
|
+
console.log(` ${k.split("::")[1]} [${flow}] ${a ? a.value : "—"} → ${b ? b.value : "—"} (only in ${a ? labelA : labelB})`);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
const delta = b.value - a.value;
|
|
684
|
+
const pct = a.value !== 0 ? (delta / a.value) * 100 : 0;
|
|
685
|
+
const unit = a.unit ?? b.unit ?? "";
|
|
686
|
+
const better = b.better ?? a.better;
|
|
687
|
+
let verdict = "";
|
|
688
|
+
if (better === "lower" || better === "higher") {
|
|
689
|
+
const improved = better === "lower" ? delta < 0 : delta > 0;
|
|
690
|
+
if (delta !== 0)
|
|
691
|
+
verdict = improved ? " improved" : " regressed";
|
|
692
|
+
}
|
|
693
|
+
console.log(` ${k.split("::")[1]} [${flow}] ${a.value} → ${b.value} ${unit} ` +
|
|
694
|
+
`(${delta >= 0 ? "+" : ""}${delta}${unit}, ${pct >= 0 ? "+" : ""}${pct.toFixed(1)}%)${verdict}`);
|
|
695
|
+
}
|
|
696
|
+
console.log("");
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
// history
|
|
700
|
+
console.log(`\nMetric history for ${file}\n`);
|
|
701
|
+
for (const r of reports) {
|
|
702
|
+
if (labelFilter && r.label !== labelFilter)
|
|
703
|
+
continue;
|
|
704
|
+
const tag = r.label ? ` [${r.label}]` : "";
|
|
705
|
+
const git = r.git ? ` ${r.git.commit.slice(0, 8)}${r.git.clean ? "" : "*"}` : "";
|
|
706
|
+
for (const f of r.flows ?? []) {
|
|
707
|
+
if (flowFilter && !f.flow.includes(flowFilter))
|
|
708
|
+
continue;
|
|
709
|
+
for (const m of f.metrics ?? []) {
|
|
710
|
+
if (metricFilter && m.name !== metricFilter)
|
|
711
|
+
continue;
|
|
712
|
+
console.log(` ${r.timestamp}${tag}${git} ${f.flow} ${m.name} = ${m.value}${m.unit ?? ""}`);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
console.log("");
|
|
717
|
+
}
|
|
718
|
+
listAdapters() {
|
|
719
|
+
const specs = flowAdapterSpecs();
|
|
720
|
+
console.log("Built-in:");
|
|
721
|
+
console.log(" tsAdapter script engine (tsx subprocess, orchestrator batching)");
|
|
722
|
+
if (specs.length === 0) {
|
|
723
|
+
console.log("\nNo plugin flow adapters registered.");
|
|
724
|
+
console.log("Install one via 'axn-dev install --plugin <pkg>' (axn-dev.flowAdapters manifest).");
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
console.log("\nPlugin adapters:");
|
|
728
|
+
for (const s of specs) {
|
|
729
|
+
const tags = s.tags.length ? `tags: ${s.tags.join(", ")}` : "by name only";
|
|
730
|
+
const ext = s.extends ? `, extends ${s.extends}` : "";
|
|
731
|
+
const scen = s.wantsScenario ? ", starts scenario" : "";
|
|
732
|
+
console.log(` ${s.name.padEnd(20)} ${tags}${ext}${scen}`);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
printFlow(f, indent = " ") {
|
|
736
|
+
const adapters = f.adapters.length > 0 ? ` [${f.adapters.join(", ")}]` : "";
|
|
737
|
+
const desc = f.description ? ` — ${f.description}` : "";
|
|
738
|
+
console.log(`${indent}${f.name.padEnd(44)} ${f.fileName}${adapters}${desc}`);
|
|
739
|
+
}
|
|
740
|
+
listFlows() {
|
|
741
|
+
const config = new ScenarioDiscoveryService(process.cwd()).getConfig();
|
|
742
|
+
const flows = discoverAllFlows(config);
|
|
743
|
+
const globalFlows = flows.filter((f) => f.scope === "global");
|
|
744
|
+
const projectFlows = flows.filter((f) => f.scope === "project");
|
|
745
|
+
if (globalFlows.length === 0 && projectFlows.length === 0) {
|
|
746
|
+
console.log("No flows found. Add flows/*.xml to an integration repo or a configured repo.");
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (globalFlows.length > 0) {
|
|
750
|
+
console.log("Global flows:");
|
|
751
|
+
for (const f of globalFlows)
|
|
752
|
+
this.printFlow(f);
|
|
753
|
+
console.log("");
|
|
754
|
+
}
|
|
755
|
+
if (projectFlows.length > 0) {
|
|
756
|
+
console.log("Project flows:");
|
|
757
|
+
const byRepo = new Map();
|
|
758
|
+
for (const f of projectFlows) {
|
|
759
|
+
const list = byRepo.get(f.rootName) ?? [];
|
|
760
|
+
list.push(f);
|
|
761
|
+
byRepo.set(f.rootName, list);
|
|
762
|
+
}
|
|
763
|
+
for (const [repo, repoFlows] of [...byRepo.entries()].sort(([a], [b]) => a.localeCompare(b))) {
|
|
764
|
+
console.log(` ${repo}:`);
|
|
765
|
+
for (const f of repoFlows)
|
|
766
|
+
this.printFlow(f, " ");
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
async runFlow(flow, modelFilter, startedScenarios, infra = null, autoPort = false, portFlag = null, deployUrl = null) {
|
|
771
|
+
const isCustomUnit = (s) =>
|
|
772
|
+
// <script adapter="x"> routed to a non-message adapter (plugin or file)
|
|
773
|
+
(s.type === "script" &&
|
|
774
|
+
!!s.adapter &&
|
|
775
|
+
s.adapter !== "tsAdapter" &&
|
|
776
|
+
!this.servesMessage(s.adapter)) ||
|
|
777
|
+
// custom step tags dispatch to the adapter owning the tag; <repeat>,
|
|
778
|
+
// <metric> and <video> are containers — their children are checked
|
|
779
|
+
// individually; a <picture> alone needs an orchestrator
|
|
780
|
+
(s.type !== "script" && s.type !== "message" && s.type !== "assertions" && s.type !== "repeat" &&
|
|
781
|
+
s.type !== "extract" && s.type !== "metric" && s.type !== "video" && s.type !== "picture");
|
|
782
|
+
const anyCustomUnit = (steps) => steps.some((s) => isCustomUnit(s) || anyCustomUnit(s.children ?? []));
|
|
783
|
+
const hasCustomAdapterStep = anyCustomUnit(flow.steps);
|
|
784
|
+
// Scenario-less flow with an explicit deployment target — a synthetic
|
|
785
|
+
// tsAdapter scenario carries the URL; orchestrator/readiness can come
|
|
786
|
+
// from the <flow> attributes. Not for a flow of plugin-adapter steps:
|
|
787
|
+
// the adapter path below resolves the deployment URL itself.
|
|
788
|
+
const tsScenario = flow.scenarios.find((s) => s.adapter === "tsAdapter") ??
|
|
789
|
+
(flow.scenarios.length === 0 && !hasCustomAdapterStep && (deployUrl ?? flow.baseUrl)
|
|
790
|
+
? { name: "deployment", service: "", adapter: "tsAdapter", readiness: [] }
|
|
791
|
+
: undefined);
|
|
792
|
+
if (tsScenario) {
|
|
793
|
+
if (this.gate)
|
|
794
|
+
throw new Error("--interactive supports adapter flows only, not browser flows yet");
|
|
795
|
+
return [await this.runTsAdapterFlow(flow, tsScenario, startedScenarios, infra, autoPort, portFlag, deployUrl)];
|
|
796
|
+
}
|
|
797
|
+
if (hasCustomAdapterStep) {
|
|
798
|
+
// Custom-adapter steps get BASE_URL when the run targets a deployment.
|
|
799
|
+
// The stub lookup also resolves a scenario-less <flow base-url>.
|
|
800
|
+
const target = flow.scenarios
|
|
801
|
+
.map((s) => this.deploymentUrl(s, flow, deployUrl))
|
|
802
|
+
.find((u) => u !== null) ??
|
|
803
|
+
this.deploymentUrl({ name: flow.name }, flow, null);
|
|
804
|
+
this.adapterScenarioRun = { started: startedScenarios, autoPort, portFlag, prepared: new Map() };
|
|
805
|
+
return [await this.runCustomAdapterFlow(flow, target)];
|
|
806
|
+
}
|
|
807
|
+
if (this.gate)
|
|
808
|
+
throw new Error("--interactive supports adapter flows only, not script or message flows yet");
|
|
809
|
+
if (infra) {
|
|
810
|
+
throw new Error("--infra is currently only supported with tsAdapter flows");
|
|
811
|
+
}
|
|
812
|
+
const models = modelFilter
|
|
813
|
+
? flow.models.filter((m) => m.name === modelFilter || `${m.provider}/${m.name}` === modelFilter)
|
|
814
|
+
: flow.models;
|
|
815
|
+
if (models.length === 0) {
|
|
816
|
+
throw new Error(`No matching model for flow '${flow.name}'`);
|
|
817
|
+
}
|
|
818
|
+
// The scenario adapter must be a registered plugin adapter serving
|
|
819
|
+
// <usermessage> (e.g. restAdapter, cliAdapter).
|
|
820
|
+
const msgScenario = flow.scenarios.find((s) => this.servesMessage(s.adapter));
|
|
821
|
+
if (!msgScenario) {
|
|
822
|
+
const serving = flowAdaptersForTag("usermessage").map((a) => a.name);
|
|
823
|
+
throw new Error(`Flow '${flow.name}' has no scenario adapter serving <usermessage>. ` +
|
|
824
|
+
`Registered: ${serving.join(", ") || "(none)"}. ` +
|
|
825
|
+
`Install a plugin package declaring one via axn-dev.flowAdapters, ` +
|
|
826
|
+
`or set adapter= on the <usermessage>/<scenario>.`);
|
|
827
|
+
}
|
|
828
|
+
const hasMessageStep = flow.steps.some((s) => s.type === "message" ||
|
|
829
|
+
((s.type === "repeat" || s.type === "metric") &&
|
|
830
|
+
(s.children ?? []).some((c) => c.type === "message")));
|
|
831
|
+
const messageStep = flow.steps.find((s) => s.type === "message");
|
|
832
|
+
const message = messageStep?.value || flow.userMessage;
|
|
833
|
+
if (!message && !hasMessageStep) {
|
|
834
|
+
throw new Error(`Flow '${flow.name}' is missing <usermessage>`);
|
|
835
|
+
}
|
|
836
|
+
const results = [];
|
|
837
|
+
for (const model of models) {
|
|
838
|
+
const start = Date.now();
|
|
839
|
+
const flowResult = {
|
|
840
|
+
flow: flow.name,
|
|
841
|
+
model,
|
|
842
|
+
passed: false,
|
|
843
|
+
assertions: [],
|
|
844
|
+
durationMs: 0,
|
|
845
|
+
};
|
|
846
|
+
try {
|
|
847
|
+
const activeScenario = msgScenario;
|
|
848
|
+
const assertCtx = {
|
|
849
|
+
flowDir: dirname(this._resolvedFilePath),
|
|
850
|
+
env: this.expandEnvVars({ ...process.env, ...flow.env }),
|
|
851
|
+
flowName: flow.name,
|
|
852
|
+
metrics: (flowResult.metrics ??= []),
|
|
853
|
+
};
|
|
854
|
+
let responseText = "";
|
|
855
|
+
const scope = { stopped: false, sink: flowResult.assertions, stdoutBase: 0 };
|
|
856
|
+
const runUnit = async (u, sc, inRepeat = false) => {
|
|
857
|
+
if (u.type === "extract") {
|
|
858
|
+
throw new Error(`<extract> needs a browser page — use a tsAdapter flow with orchestrator= or runner="pw"`);
|
|
859
|
+
}
|
|
860
|
+
if (inRepeat && u.type !== "message" && u.type !== "assertions" && u.type !== "repeat" && u.type !== "metric") {
|
|
861
|
+
throw new Error(`<${u.type}> inside <repeat> is not supported in a '${activeScenario.adapter}' flow — ` +
|
|
862
|
+
`repeat children must be <usermessage>, <assertions> or <metric>`);
|
|
863
|
+
}
|
|
864
|
+
if (u.type === "message") {
|
|
865
|
+
const t0 = Date.now();
|
|
866
|
+
const r = this.absorbEmittedMetrics(await this.runMessageStep(flow, u, model, activeScenario, startedScenarios, null, undefined, undefined, autoPort, portFlag, deployUrl, flowResult), flowResult, u.name ?? u.description ?? "usermessage");
|
|
867
|
+
responseText += (responseText ? "\n" : "") + r;
|
|
868
|
+
await this.evalStepAsserts(u, r, sc, assertCtx, 0, Date.now() - t0);
|
|
869
|
+
}
|
|
870
|
+
else if (u.type === "assertions") {
|
|
871
|
+
for (const a of u.assertions ?? []) {
|
|
872
|
+
const base = a.fresh ? (sc.cursor ?? sc.stdoutBase) : sc.stdoutBase;
|
|
873
|
+
const result = await this.evaluateAssertion(a, responseText.slice(base), undefined, assertCtx);
|
|
874
|
+
sc.sink.push(result);
|
|
875
|
+
if (!result.passed)
|
|
876
|
+
sc.stopped = true;
|
|
877
|
+
}
|
|
878
|
+
sc.cursor = responseText.length;
|
|
879
|
+
}
|
|
880
|
+
else if (u.type === "repeat") {
|
|
881
|
+
const summary = await this.runRepeatUnit(u, async () => {
|
|
882
|
+
const iterScope = { stopped: false, sink: [], stdoutBase: responseText.length };
|
|
883
|
+
for (const c of u.children ?? []) {
|
|
884
|
+
if (iterScope.stopped)
|
|
885
|
+
break;
|
|
886
|
+
await runUnit(c, iterScope, true);
|
|
887
|
+
}
|
|
888
|
+
return iterScope.sink.every((r) => r.passed)
|
|
889
|
+
? { ok: true }
|
|
890
|
+
: { ok: false, why: this.scopeFailureWhy(iterScope) };
|
|
891
|
+
});
|
|
892
|
+
sc.sink.push(summary);
|
|
893
|
+
if (!summary.passed)
|
|
894
|
+
sc.stopped = true;
|
|
895
|
+
}
|
|
896
|
+
else if (u.type === "metric") {
|
|
897
|
+
await this.runMetricBlock(u, flowResult, {
|
|
898
|
+
env: assertCtx.env,
|
|
899
|
+
flowDir: assertCtx.flowDir,
|
|
900
|
+
cwd: process.cwd(),
|
|
901
|
+
flowName: flow.name,
|
|
902
|
+
scenario: { ...activeScenario },
|
|
903
|
+
baseUrl: deployUrl ?? undefined,
|
|
904
|
+
}, async () => {
|
|
905
|
+
for (const c of u.children ?? []) {
|
|
906
|
+
if (sc.stopped)
|
|
907
|
+
break;
|
|
908
|
+
await runUnit(c, sc, inRepeat);
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
// other step types can't run in a message-adapter flow — skipped
|
|
913
|
+
};
|
|
914
|
+
for (const u of flow.steps) {
|
|
915
|
+
if (scope.stopped)
|
|
916
|
+
break;
|
|
917
|
+
await runUnit(u, scope);
|
|
918
|
+
}
|
|
919
|
+
flowResult.response = responseText;
|
|
920
|
+
flowResult.passed = flowResult.assertions.every((a) => a.passed);
|
|
921
|
+
}
|
|
922
|
+
catch (err) {
|
|
923
|
+
flowResult.error = err instanceof Error ? err.message : String(err);
|
|
924
|
+
}
|
|
925
|
+
flowResult.durationMs = Date.now() - start;
|
|
926
|
+
results.push(flowResult);
|
|
927
|
+
}
|
|
928
|
+
return results;
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* Run a <repeat num="N" success="R"> block: `runIteration` executes the
|
|
932
|
+
* children once; the block passes when at least ceil(N·R) iterations
|
|
933
|
+
* succeed. A failed iteration does not stop the loop — that's the point
|
|
934
|
+
* (tolerance for flaky/non-deterministic parts). Exits early once the
|
|
935
|
+
* threshold can no longer be reached. Returns the summary assertion.
|
|
936
|
+
*/
|
|
937
|
+
async runRepeatUnit(unit, runIteration) {
|
|
938
|
+
const num = unit.num ?? 1;
|
|
939
|
+
const rate = unit.success ?? 1;
|
|
940
|
+
const needed = Math.ceil(num * rate);
|
|
941
|
+
let ok = 0;
|
|
942
|
+
const failures = [];
|
|
943
|
+
for (let i = 0; i < num; i++) {
|
|
944
|
+
if (ok + (num - i) < needed)
|
|
945
|
+
break;
|
|
946
|
+
this.progress(` repeat run ${i + 1}/${num} (${ok} ok, need ${needed})`);
|
|
947
|
+
try {
|
|
948
|
+
const r = await runIteration();
|
|
949
|
+
if (r.ok)
|
|
950
|
+
ok++;
|
|
951
|
+
else
|
|
952
|
+
failures.push(`run ${i + 1}: ${r.why ?? "failed"}`);
|
|
953
|
+
}
|
|
954
|
+
catch (err) {
|
|
955
|
+
failures.push(`run ${i + 1}: ${err instanceof Error ? err.message : String(err)}`);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
const passed = ok >= needed;
|
|
959
|
+
return {
|
|
960
|
+
that: "repeat",
|
|
961
|
+
value: `${num}× ≥${Math.round(rate * 100)}%`,
|
|
962
|
+
actual: `${ok}/${num}`,
|
|
963
|
+
passed,
|
|
964
|
+
description: unit.description,
|
|
965
|
+
repeat: { runs: num, succeeded: ok, needed, failures },
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Run a <metric>/<stopwatch> block: resolve the collect= collectors,
|
|
970
|
+
* run the children, then record each measured value under
|
|
971
|
+
* result.metrics[]. A collector missing from the registry or returning
|
|
972
|
+
* null is "unavailable" — skipped with a note, or an error under
|
|
973
|
+
* --fail-on-unavailable-metric. Collection runs in finally so
|
|
974
|
+
* measurements land even when a child fails.
|
|
975
|
+
*/
|
|
976
|
+
async runMetricBlock(step, result, ctx, runChildren) {
|
|
977
|
+
const id = step.name ?? "metric";
|
|
978
|
+
const collectors = [];
|
|
979
|
+
for (const n of step.collect ?? ["duration"]) {
|
|
980
|
+
if (!hasFlowMetric(n)) {
|
|
981
|
+
if (this.failOnUnavailableMetric) {
|
|
982
|
+
throw new Error(`<metric id="${id}"> requested metric '${n}' but no collector is ` +
|
|
983
|
+
`registered under that name — install a plugin declaring it via ` +
|
|
984
|
+
`axn-dev.flowMetrics, or remove it from collect=`);
|
|
985
|
+
}
|
|
986
|
+
this.progress(` metric '${n}' unavailable — skipped`);
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
collectors.push(await flowMetric(n));
|
|
990
|
+
}
|
|
991
|
+
const states = await Promise.all(collectors.map((c) => c.begin?.(ctx)));
|
|
992
|
+
try {
|
|
993
|
+
await runChildren();
|
|
994
|
+
}
|
|
995
|
+
finally {
|
|
996
|
+
for (let i = 0; i < collectors.length; i++) {
|
|
997
|
+
const c = collectors[i];
|
|
998
|
+
let value = null;
|
|
999
|
+
let failed;
|
|
1000
|
+
try {
|
|
1001
|
+
value = await c.collect(ctx, states[i]);
|
|
1002
|
+
}
|
|
1003
|
+
catch (err) {
|
|
1004
|
+
failed = err;
|
|
1005
|
+
}
|
|
1006
|
+
if (value !== null) {
|
|
1007
|
+
(result.metrics ??= []).push({ id, name: c.name, value, unit: c.unit });
|
|
1008
|
+
this.progress(` metric '${id}' ${c.name}: ${value}${c.unit ?? ""}`);
|
|
1009
|
+
}
|
|
1010
|
+
else if (this.failOnUnavailableMetric) {
|
|
1011
|
+
throw new Error(`metric '${c.name}' unavailable for <metric id="${id}">` +
|
|
1012
|
+
(failed ? ` — ${failed instanceof Error ? failed.message : String(failed)}` : ""));
|
|
1013
|
+
}
|
|
1014
|
+
else {
|
|
1015
|
+
this.progress(` metric '${c.name}' unavailable — skipped` +
|
|
1016
|
+
(failed ? ` (${failed instanceof Error ? failed.message : String(failed)})` : ""));
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Lift `AXN_METRIC {json}` lines out of step output: each becomes a
|
|
1023
|
+
* MetricRecord in result.metrics (deduped by name within the chunk —
|
|
1024
|
+
* last wins; a step emitting per iteration carries its series in
|
|
1025
|
+
* `samples`) and is removed from the output so `contains` and friends
|
|
1026
|
+
* never see it. Every emitted metric is recorded — asserts give it a
|
|
1027
|
+
* verdict, the report keeps them all.
|
|
1028
|
+
*/
|
|
1029
|
+
absorbEmittedMetrics(output, result, id) {
|
|
1030
|
+
const { output: clean, metrics } = extractEmittedMetrics(output);
|
|
1031
|
+
for (const m of metrics) {
|
|
1032
|
+
(result.metrics ??= []).push({ id, ...m });
|
|
1033
|
+
this.progress(` metric '${m.name}': ${m.value}${m.unit ?? ""} (emitted)`);
|
|
1034
|
+
}
|
|
1035
|
+
return clean;
|
|
1036
|
+
}
|
|
1037
|
+
/** Nested <assert> children of a step — evaluate against that step's own
|
|
1038
|
+
* output (and, for duration asserts, its wall-clock time). */
|
|
1039
|
+
async evalStepAsserts(step, output, scope, ctx, exitCode, durationMs) {
|
|
1040
|
+
for (const a of step.assertions ?? []) {
|
|
1041
|
+
const r = await this.evaluateAssertion(a, output, exitCode, ctx, durationMs);
|
|
1042
|
+
scope.sink.push(r);
|
|
1043
|
+
if (!r.passed)
|
|
1044
|
+
scope.stopped = true;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
/** Compact reason an iteration failed — the failed assertions inside it. */
|
|
1048
|
+
scopeFailureWhy(scope) {
|
|
1049
|
+
const why = scope.sink
|
|
1050
|
+
.filter((r) => !r.passed)
|
|
1051
|
+
.map((r) => `${r.that}=${r.value}${r.actual ? ` (${r.actual.slice(0, 80)})` : ""}`)
|
|
1052
|
+
.join("; ");
|
|
1053
|
+
return why || "failed";
|
|
1054
|
+
}
|
|
1055
|
+
async runCustomAdapterFlow(flow, deployUrl = null) {
|
|
1056
|
+
const start = Date.now();
|
|
1057
|
+
const flowResult = {
|
|
1058
|
+
flow: flow.name,
|
|
1059
|
+
model: { provider: "custom", name: "adapter" },
|
|
1060
|
+
passed: false,
|
|
1061
|
+
assertions: [],
|
|
1062
|
+
durationMs: 0,
|
|
1063
|
+
};
|
|
1064
|
+
try {
|
|
1065
|
+
const env = this.expandEnvVars({
|
|
1066
|
+
...process.env,
|
|
1067
|
+
...flow.env,
|
|
1068
|
+
...(deployUrl ? this.deploymentEnv(deployUrl) : {}),
|
|
1069
|
+
});
|
|
1070
|
+
let allStdout = "";
|
|
1071
|
+
let lastExitCode = 0;
|
|
1072
|
+
const outerScope = { stopped: false, sink: flowResult.assertions, stdoutBase: 0 };
|
|
1073
|
+
let evidenceDir = null;
|
|
1074
|
+
const processStep = async (step, scope) => {
|
|
1075
|
+
if (step.type === "video") {
|
|
1076
|
+
// The page belongs to the adapter, not the engine: the adapter of
|
|
1077
|
+
// the block's steps records it, around those steps.
|
|
1078
|
+
const name = step.name ?? "video";
|
|
1079
|
+
const adapterName = (step.children ?? []).map((c) => this.adapterForStep(c)).find(Boolean);
|
|
1080
|
+
const adapter = adapterName && hasFlowAdapter(adapterName) ? await flowAdapter(adapterName) : undefined;
|
|
1081
|
+
if (!adapter?.videoStart || !adapter.videoStop) {
|
|
1082
|
+
throw new Error(`<video name="${name}">: adapter '${adapterName ?? "(none)"}' cannot record video — ` +
|
|
1083
|
+
`it needs videoStart/videoStop, or use a browser orchestrator (tsAdapter)`);
|
|
1084
|
+
}
|
|
1085
|
+
evidenceDir ??= evidenceDirFor(this._resolvedFilePath, flow.name);
|
|
1086
|
+
const ctx = this.makeAdapterCtx(flow, step, env, { result: flowResult, scenario: flow.scenarios[0] });
|
|
1087
|
+
await adapter.videoStart(name, evidenceDir, ctx);
|
|
1088
|
+
try {
|
|
1089
|
+
for (const child of step.children ?? []) {
|
|
1090
|
+
if (scope.stopped)
|
|
1091
|
+
break;
|
|
1092
|
+
await processStep(child, scope);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
finally {
|
|
1096
|
+
const path = await adapter.videoStop(name, ctx);
|
|
1097
|
+
if (typeof path === "string")
|
|
1098
|
+
(flowResult.evidence ??= []).push({ kind: "video", name, path });
|
|
1099
|
+
}
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
if (step.type === "picture") {
|
|
1103
|
+
throw new Error(`<picture> evidence requires a browser orchestrator (tsAdapter) — ` +
|
|
1104
|
+
`adapter '${step.adapter ?? "custom"}' steps cannot capture pictures yet`);
|
|
1105
|
+
}
|
|
1106
|
+
if (step.type === "extract") {
|
|
1107
|
+
throw new Error(`<extract> needs a browser page — use a tsAdapter flow with orchestrator= or runner="pw"`);
|
|
1108
|
+
}
|
|
1109
|
+
if (step.type === "repeat") {
|
|
1110
|
+
const summary = await this.runRepeatUnit(step, async () => {
|
|
1111
|
+
const iterScope = { stopped: false, sink: [], stdoutBase: allStdout.length };
|
|
1112
|
+
for (const child of step.children ?? []) {
|
|
1113
|
+
if (iterScope.stopped)
|
|
1114
|
+
break;
|
|
1115
|
+
await processStep(child, iterScope);
|
|
1116
|
+
}
|
|
1117
|
+
return iterScope.sink.every((r) => r.passed)
|
|
1118
|
+
? { ok: true }
|
|
1119
|
+
: { ok: false, why: this.scopeFailureWhy(iterScope) };
|
|
1120
|
+
});
|
|
1121
|
+
scope.sink.push(summary);
|
|
1122
|
+
if (!summary.passed)
|
|
1123
|
+
scope.stopped = true;
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
if (step.type === "metric") {
|
|
1127
|
+
await this.runMetricBlock(step, flowResult, {
|
|
1128
|
+
env,
|
|
1129
|
+
flowDir: dirname(this._resolvedFilePath),
|
|
1130
|
+
cwd: process.cwd(),
|
|
1131
|
+
flowName: flow.name,
|
|
1132
|
+
scenario: flow.scenarios[0] ? { ...flow.scenarios[0] } : undefined,
|
|
1133
|
+
baseUrl: deployUrl ?? undefined,
|
|
1134
|
+
}, async () => {
|
|
1135
|
+
for (const child of step.children ?? []) {
|
|
1136
|
+
if (scope.stopped)
|
|
1137
|
+
break;
|
|
1138
|
+
await processStep(child, scope);
|
|
1139
|
+
}
|
|
1140
|
+
});
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
if ((step.type === "script" &&
|
|
1144
|
+
!!step.adapter &&
|
|
1145
|
+
step.adapter !== "tsAdapter" &&
|
|
1146
|
+
!this.servesMessage(step.adapter)) ||
|
|
1147
|
+
(step.type !== "script" && step.type !== "message" && step.type !== "assertions")) {
|
|
1148
|
+
const t0 = Date.now();
|
|
1149
|
+
const response = this.absorbEmittedMetrics(await this.runCustomAdapterStep(flow, step, env, flowResult), flowResult, step.name ?? step.description ?? "step");
|
|
1150
|
+
allStdout += (allStdout ? "\n" : "") + response;
|
|
1151
|
+
const assertCtx = {
|
|
1152
|
+
flowDir: dirname(this._resolvedFilePath),
|
|
1153
|
+
env,
|
|
1154
|
+
flowName: flow.name,
|
|
1155
|
+
metrics: (flowResult.metrics ??= []),
|
|
1156
|
+
};
|
|
1157
|
+
await this.evalStepAsserts(step, response, scope, assertCtx, 0, Date.now() - t0);
|
|
1158
|
+
}
|
|
1159
|
+
else if (step.type === "assertions") {
|
|
1160
|
+
const assertCtx = {
|
|
1161
|
+
flowDir: dirname(this._resolvedFilePath),
|
|
1162
|
+
env,
|
|
1163
|
+
flowName: flow.name,
|
|
1164
|
+
metrics: (flowResult.metrics ??= []),
|
|
1165
|
+
};
|
|
1166
|
+
for (const a of step.assertions ?? []) {
|
|
1167
|
+
const base = a.fresh ? (scope.cursor ?? scope.stdoutBase) : scope.stdoutBase;
|
|
1168
|
+
const result = await this.evaluateAssertion(a, allStdout.slice(base), lastExitCode, assertCtx);
|
|
1169
|
+
scope.sink.push(result);
|
|
1170
|
+
if (!result.passed)
|
|
1171
|
+
scope.stopped = true;
|
|
1172
|
+
}
|
|
1173
|
+
scope.cursor = allStdout.length;
|
|
1174
|
+
}
|
|
1175
|
+
else {
|
|
1176
|
+
// Never drop a step: a silently skipped step makes the flow (and
|
|
1177
|
+
// any <repeat> around it) report green without having run it.
|
|
1178
|
+
const label = stepLabel(step);
|
|
1179
|
+
throw new Error(`step '${label}' has no adapter that can run it in this adapter flow` +
|
|
1180
|
+
(step.adapter ? ` (adapter="${step.adapter}")` : "") +
|
|
1181
|
+
` — set adapter="…" on it, or <flow adapter="…">`);
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
const gate = this.gate;
|
|
1185
|
+
const observer = this.observer;
|
|
1186
|
+
// A visible or attached browser already shows the product; framing it
|
|
1187
|
+
// too would show a second, unrelated session.
|
|
1188
|
+
let productWindow = false;
|
|
1189
|
+
try {
|
|
1190
|
+
const browser = browserSettings(env);
|
|
1191
|
+
productWindow = browser.headed || !!browser.attach;
|
|
1192
|
+
}
|
|
1193
|
+
catch {
|
|
1194
|
+
// Invalid browser settings fail in the step that launches a browser.
|
|
1195
|
+
}
|
|
1196
|
+
this.productWindow = productWindow;
|
|
1197
|
+
observer?.begin(flow.name, flow.steps.flatMap((step, index) => step.type === "assertions"
|
|
1198
|
+
? []
|
|
1199
|
+
: [{
|
|
1200
|
+
index,
|
|
1201
|
+
label: stepLabel(step),
|
|
1202
|
+
...(step.args && Object.keys(step.args).length ? { args: step.args } : {}),
|
|
1203
|
+
...(step.value?.trim() ? { text: step.value.trim() } : {}),
|
|
1204
|
+
...(step.args?.interactive === "auto" ? { auto: true } : {}),
|
|
1205
|
+
}]), productWindow);
|
|
1206
|
+
// One attempt at a top-level step as the stage sees it: running, its
|
|
1207
|
+
// output tied to it, then how it ended.
|
|
1208
|
+
const observed = async (index, step, scope) => {
|
|
1209
|
+
if (!observer || step.type === "assertions")
|
|
1210
|
+
return processStep(step, scope);
|
|
1211
|
+
const from = allStdout.length;
|
|
1212
|
+
this.liveStep = index;
|
|
1213
|
+
observer.stepStarted(index);
|
|
1214
|
+
try {
|
|
1215
|
+
await processStep(step, scope);
|
|
1216
|
+
}
|
|
1217
|
+
catch (err) {
|
|
1218
|
+
observer.stepEnded(index, "failed", err instanceof Error ? err.message : String(err));
|
|
1219
|
+
throw err;
|
|
1220
|
+
}
|
|
1221
|
+
finally {
|
|
1222
|
+
for (const line of allStdout.slice(from).split("\n"))
|
|
1223
|
+
if (line.trim())
|
|
1224
|
+
observer.output(index, line);
|
|
1225
|
+
this.liveStep = null;
|
|
1226
|
+
}
|
|
1227
|
+
if (scope.stopped) {
|
|
1228
|
+
observer.stepEnded(index, "failed", this.scopeFailureWhy(scope));
|
|
1229
|
+
}
|
|
1230
|
+
else {
|
|
1231
|
+
observer.stepEnded(index, "passed");
|
|
1232
|
+
if (this.pendingProduct)
|
|
1233
|
+
observer.product(this.pendingProduct);
|
|
1234
|
+
this.pendingProduct = null;
|
|
1235
|
+
}
|
|
1236
|
+
};
|
|
1237
|
+
await this.startAdapters(flow, env);
|
|
1238
|
+
for (const [index, step] of flow.steps.entries()) {
|
|
1239
|
+
if (outerScope.stopped)
|
|
1240
|
+
break;
|
|
1241
|
+
if (!gate || step.type === "assertions" || step.args?.interactive === "auto") {
|
|
1242
|
+
await observed(index, step, outerScope);
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
// Gated step: a failure stops at the gate for retry/skip instead of
|
|
1246
|
+
// ending the run. A failed attempt is rolled back (its output and
|
|
1247
|
+
// assertion results), so a retry is judged on its own output only.
|
|
1248
|
+
const record = { index, label: stepLabel(step), outcome: "ran", failedAttempts: [] };
|
|
1249
|
+
(flowResult.interactive ??= []).push(record);
|
|
1250
|
+
for (;;) {
|
|
1251
|
+
const failed = record.failedAttempts.at(-1);
|
|
1252
|
+
const cmd = await gate.wait({ index, total: flow.steps.length, label: record.label, step, failed });
|
|
1253
|
+
if (cmd === "abort")
|
|
1254
|
+
throw new Error(`interactive run aborted at step ${index + 1} (${record.label})`);
|
|
1255
|
+
if (cmd === "skip") {
|
|
1256
|
+
record.outcome = "skipped";
|
|
1257
|
+
observer?.stepEnded(index, "skipped");
|
|
1258
|
+
break;
|
|
1259
|
+
}
|
|
1260
|
+
const mark = { out: allStdout.length, sink: outerScope.sink.length };
|
|
1261
|
+
let why;
|
|
1262
|
+
try {
|
|
1263
|
+
await observed(index, step, outerScope);
|
|
1264
|
+
if (outerScope.stopped)
|
|
1265
|
+
why = this.scopeFailureWhy({ ...outerScope, sink: outerScope.sink.slice(mark.sink) });
|
|
1266
|
+
}
|
|
1267
|
+
catch (err) {
|
|
1268
|
+
why = err instanceof Error ? err.message : String(err);
|
|
1269
|
+
}
|
|
1270
|
+
if (why === undefined)
|
|
1271
|
+
break;
|
|
1272
|
+
record.failedAttempts.push(why);
|
|
1273
|
+
allStdout = allStdout.slice(0, mark.out);
|
|
1274
|
+
outerScope.sink.length = mark.sink;
|
|
1275
|
+
outerScope.stopped = false;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
flowResult.response = allStdout;
|
|
1279
|
+
flowResult.passed = flowResult.assertions.every((a) => a.passed);
|
|
1280
|
+
if (!flowResult.passed && !flowResult.error) {
|
|
1281
|
+
flowResult.error = "One or more assertions failed";
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
catch (err) {
|
|
1285
|
+
flowResult.error = err instanceof Error ? err.message : String(err);
|
|
1286
|
+
}
|
|
1287
|
+
flowResult.durationMs = Date.now() - start;
|
|
1288
|
+
return flowResult;
|
|
1289
|
+
}
|
|
1290
|
+
async runTsAdapterFlow(flow, scenario, startedScenarios, infra = null, autoPort = false, portFlag = null, deployUrl = null) {
|
|
1291
|
+
const start = Date.now();
|
|
1292
|
+
const flowResult = {
|
|
1293
|
+
flow: flow.name,
|
|
1294
|
+
model: { provider: "ts", name: "script" },
|
|
1295
|
+
passed: false,
|
|
1296
|
+
assertions: [],
|
|
1297
|
+
durationMs: 0,
|
|
1298
|
+
};
|
|
1299
|
+
const tmpDirs = [];
|
|
1300
|
+
const pendingEvidence = [];
|
|
1301
|
+
try {
|
|
1302
|
+
let baseUrl;
|
|
1303
|
+
let env;
|
|
1304
|
+
// -i targets a device — deployment urls are never consulted, not even
|
|
1305
|
+
// for validation (an unresolved ${VAR} there must not fail the run).
|
|
1306
|
+
const deploymentUrl = infra ? null : this.deploymentUrl(scenario, flow, deployUrl);
|
|
1307
|
+
if (infra) {
|
|
1308
|
+
const deviceEnv = await this.buildDeviceEnv(infra);
|
|
1309
|
+
baseUrl = deviceEnv.BASE_URL;
|
|
1310
|
+
await this.waitForProbe(baseUrl, "GET", "ok", 120000);
|
|
1311
|
+
env = this.expandEnvVars({ ...deviceEnv, ...flow.env });
|
|
1312
|
+
}
|
|
1313
|
+
else if (deploymentUrl) {
|
|
1314
|
+
// Deployment target — no scenario lifecycle; BASE_URL is the
|
|
1315
|
+
// deployment's URL, declared <readiness> probes address it directly.
|
|
1316
|
+
baseUrl = deploymentUrl;
|
|
1317
|
+
console.log(`\x1b[32mTarget deployment: ${baseUrl}\x1b[0m`);
|
|
1318
|
+
await this.waitForDeploymentReadiness(scenario, baseUrl);
|
|
1319
|
+
env = this.expandEnvVars({
|
|
1320
|
+
...process.env,
|
|
1321
|
+
...flow.env,
|
|
1322
|
+
...this.deploymentEnv(baseUrl),
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
else {
|
|
1326
|
+
const prepared = await this.prepareScenario(scenario, flow, startedScenarios, autoPort, portFlag);
|
|
1327
|
+
baseUrl = prepared.baseUrl;
|
|
1328
|
+
await this.waitForReadiness(scenario, prepared.scenarioPath, prepared.env, prepared.endpoints);
|
|
1329
|
+
env = this.expandEnvVars({ ...prepared.env, ...flow.env, BASE_URL: baseUrl });
|
|
1330
|
+
}
|
|
1331
|
+
const flowDir = dirname(this._resolvedFilePath);
|
|
1332
|
+
// Execution engine: --runner / AXN_FLOW_RUNNER override the flow's own
|
|
1333
|
+
// runner= attribute (<flow runner="pw"> or <flows runner="pw">);
|
|
1334
|
+
// default is the axn orchestrator engine. 'pw' runs steps as
|
|
1335
|
+
// test.step()s in a PW worker (traces, retries, standard reporters).
|
|
1336
|
+
const runner = normalizeRunnerName(this.runnerMode) ?? flow.runner ?? "axn";
|
|
1337
|
+
if (runner === "pw") {
|
|
1338
|
+
const adapterPathFor = (step) => {
|
|
1339
|
+
if (!step.adapter)
|
|
1340
|
+
return null;
|
|
1341
|
+
const registered = this.adapterRegistry?.resolve(step.adapter) ?? null;
|
|
1342
|
+
const candidates = [
|
|
1343
|
+
registered?.path ?? null,
|
|
1344
|
+
step.src ? resolve(flowDir, step.src) : null,
|
|
1345
|
+
resolve(flowDir, "adapters", `${step.adapter}.ts`),
|
|
1346
|
+
resolve(flowDir, "adapters", `${step.adapter}.js`),
|
|
1347
|
+
];
|
|
1348
|
+
return candidates.find((p) => p && existsSync(p)) ?? null;
|
|
1349
|
+
};
|
|
1350
|
+
return await runFlowWithPlaywright({
|
|
1351
|
+
flow,
|
|
1352
|
+
filePath: this._resolvedFilePath,
|
|
1353
|
+
baseUrl,
|
|
1354
|
+
env,
|
|
1355
|
+
tsxBin: this.resolveTsx(),
|
|
1356
|
+
adapterPathFor,
|
|
1357
|
+
failOnUnavailableMetric: this.failOnUnavailableMetric,
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
// Ordered execution units: consecutive script steps batch into one
|
|
1361
|
+
// orchestrator run; each <assertions> block is a verification step
|
|
1362
|
+
// evaluated against the output accumulated so far. A failed verification
|
|
1363
|
+
// stops the flow (later steps are skipped).
|
|
1364
|
+
const units = flow.steps;
|
|
1365
|
+
// <video>/<repeat>/<metric> children are steps too — flatten for
|
|
1366
|
+
// the checks below.
|
|
1367
|
+
const flatUnits = units.flatMap((u) => (u.type === "video" || u.type === "repeat" || u.type === "metric")
|
|
1368
|
+
? [u, ...(u.children ?? [])]
|
|
1369
|
+
: [u]);
|
|
1370
|
+
const tsScriptSteps = flatUnits.filter((s) => s.type === "script" && (!s.adapter || s.adapter === "tsAdapter"));
|
|
1371
|
+
const hasMessageStep = flatUnits.some((s) => s.type === "message" ||
|
|
1372
|
+
(s.type === "script" && !!s.adapter && s.adapter !== "tsAdapter"));
|
|
1373
|
+
const hasEvidence = flatUnits.some((s) => s.type === "picture" || s.type === "video");
|
|
1374
|
+
if (tsScriptSteps.length === 0 && !hasMessageStep) {
|
|
1375
|
+
throw new Error(`Flow '${flow.name}' has no <script>, <step>, or <usermessage> elements`);
|
|
1376
|
+
}
|
|
1377
|
+
const stepPathFor = (step) => {
|
|
1378
|
+
if (step.src) {
|
|
1379
|
+
const scriptPath = resolve(flowDir, step.src);
|
|
1380
|
+
if (!existsSync(scriptPath)) {
|
|
1381
|
+
throw new Error(`Script not found: ${scriptPath}`);
|
|
1382
|
+
}
|
|
1383
|
+
return scriptPath;
|
|
1384
|
+
}
|
|
1385
|
+
if (step.value) {
|
|
1386
|
+
const dir = mkdtempSync(join(flowDir, ".axn-flow-"));
|
|
1387
|
+
const scriptPath = join(dir, "flow.ts");
|
|
1388
|
+
writeFileSync(scriptPath, step.value);
|
|
1389
|
+
tmpDirs.push(dir);
|
|
1390
|
+
return scriptPath;
|
|
1391
|
+
}
|
|
1392
|
+
throw new Error("A <script>/<step> must have a 'src' attribute or inline text");
|
|
1393
|
+
};
|
|
1394
|
+
const orchestrator = flow.orchestrator ?? scenario.orchestrator;
|
|
1395
|
+
// Evidence steps require a browser — without an orchestrator there is
|
|
1396
|
+
// no page to capture from.
|
|
1397
|
+
let evidenceDir = null;
|
|
1398
|
+
if (hasEvidence) {
|
|
1399
|
+
if (!orchestrator) {
|
|
1400
|
+
throw new Error(`Flow '${flow.name}' uses <picture>/<video> evidence but has no orchestrator — ` +
|
|
1401
|
+
`evidence capture requires a browser orchestrator (set orchestrator= on the <flow> or <scenario>)`);
|
|
1402
|
+
}
|
|
1403
|
+
evidenceDir = evidenceDirFor(this._resolvedFilePath, flow.name);
|
|
1404
|
+
}
|
|
1405
|
+
let allStdout = "";
|
|
1406
|
+
let lastStderr = "";
|
|
1407
|
+
let lastExitCode = 0;
|
|
1408
|
+
const outerScope = { stopped: false, sink: flowResult.assertions, stdoutBase: 0 };
|
|
1409
|
+
const assertCtx = { flowDir, env, flowName: flow.name, metrics: (flowResult.metrics ??= []) };
|
|
1410
|
+
const evalBlock = async (assertions, scope) => {
|
|
1411
|
+
for (const a of assertions) {
|
|
1412
|
+
const base = a.fresh ? (scope.cursor ?? scope.stdoutBase) : scope.stdoutBase;
|
|
1413
|
+
const result = await this.evaluateAssertion(a, allStdout.slice(base), lastExitCode, assertCtx);
|
|
1414
|
+
scope.sink.push(result);
|
|
1415
|
+
if (!result.passed)
|
|
1416
|
+
scope.stopped = true;
|
|
1417
|
+
}
|
|
1418
|
+
scope.cursor = allStdout.length;
|
|
1419
|
+
};
|
|
1420
|
+
if (orchestrator) {
|
|
1421
|
+
const orchestratorPath = resolve(flowDir, orchestrator);
|
|
1422
|
+
if (!existsSync(orchestratorPath)) {
|
|
1423
|
+
throw new Error(`Orchestrator not found: ${orchestratorPath}`);
|
|
1424
|
+
}
|
|
1425
|
+
const hostPath = this.resolveOrchestratorHost();
|
|
1426
|
+
const isFlowOverride = !!flow.orchestrator;
|
|
1427
|
+
const processKey = isFlowOverride ? `flow:${flow.name}` : `scenario:${scenario.name}`;
|
|
1428
|
+
let proc;
|
|
1429
|
+
if (isFlowOverride || !this.orchestratorProcesses.has(processKey)) {
|
|
1430
|
+
proc = new OrchestratorProcess(this.resolveTsx(), hostPath);
|
|
1431
|
+
await proc.start(orchestratorPath, env, flowDir);
|
|
1432
|
+
if (!isFlowOverride) {
|
|
1433
|
+
this.orchestratorProcesses.set(processKey, proc);
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
else {
|
|
1437
|
+
proc = this.orchestratorProcesses.get(processKey);
|
|
1438
|
+
}
|
|
1439
|
+
// Run script batches, message steps, and assertion blocks in document order.
|
|
1440
|
+
// <picture> becomes a generated capture script that runs through the
|
|
1441
|
+
// same (page, baseUrl) step convention the orchestrator already uses.
|
|
1442
|
+
let evidenceCounter = 0;
|
|
1443
|
+
const videoStepIndex = new Map();
|
|
1444
|
+
const artifactSlug = (s) => s.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-|-$/g, "") || "artifact";
|
|
1445
|
+
const captureScriptFor = (step, stepIndex) => {
|
|
1446
|
+
const artifactName = step.name ?? "picture";
|
|
1447
|
+
const fileName = `${String(evidenceCounter++).padStart(3, "0")}-${artifactSlug(artifactName)}.png`;
|
|
1448
|
+
const artifactPath = join(evidenceDir, fileName);
|
|
1449
|
+
pendingEvidence.push({ kind: "picture", name: artifactName, path: artifactPath, stepIndex });
|
|
1450
|
+
const dir = mkdtempSync(join(flowDir, ".axn-flow-"));
|
|
1451
|
+
tmpDirs.push(dir);
|
|
1452
|
+
const scriptPath = join(dir, "capture.ts");
|
|
1453
|
+
const body = step.selector
|
|
1454
|
+
? `await page.locator(${JSON.stringify(step.selector)}).screenshot({ path: ${JSON.stringify(artifactPath)} });`
|
|
1455
|
+
: `await page.screenshot({ path: ${JSON.stringify(artifactPath)}${step.fullPage ? ", fullPage: true" : ""} });`;
|
|
1456
|
+
writeFileSync(scriptPath, `export default async function capture(page: any) {\n ${body}\n return "captured ${artifactName}";\n}\n`);
|
|
1457
|
+
return scriptPath;
|
|
1458
|
+
};
|
|
1459
|
+
/** <extract selector attr> — generated step reading a DOM element's
|
|
1460
|
+
* text/attr on the live orchestrator page; the value lands in stdout
|
|
1461
|
+
* so assertions and llm judges evaluate it like any step output. */
|
|
1462
|
+
const extractScriptFor = (unit) => {
|
|
1463
|
+
const dir = mkdtempSync(join(flowDir, ".axn-flow-"));
|
|
1464
|
+
tmpDirs.push(dir);
|
|
1465
|
+
const scriptPath = join(dir, "extract.ts");
|
|
1466
|
+
const sel = JSON.stringify(unit.selector);
|
|
1467
|
+
const attr = unit.attr ?? "text";
|
|
1468
|
+
const read = attr === "text" ? "innerText()" :
|
|
1469
|
+
attr === "html" ? "innerHTML()" :
|
|
1470
|
+
attr === "value" ? "inputValue()" :
|
|
1471
|
+
`getAttribute(${JSON.stringify(attr)})`;
|
|
1472
|
+
writeFileSync(scriptPath, `export default async function extract(page: any) {\n const v = await page.locator(${sel}).${read};\n return typeof v === "string" ? v : (v ?? "");\n}\n`);
|
|
1473
|
+
return scriptPath;
|
|
1474
|
+
};
|
|
1475
|
+
let batch = [];
|
|
1476
|
+
const flush = async () => {
|
|
1477
|
+
if (batch.length === 0)
|
|
1478
|
+
return;
|
|
1479
|
+
const { stdout, stderr, exitCode, videos } = await proc.run(batch);
|
|
1480
|
+
batch = [];
|
|
1481
|
+
allStdout += (allStdout ? "\n" : "") +
|
|
1482
|
+
this.absorbEmittedMetrics(stdout, flowResult, "step");
|
|
1483
|
+
lastStderr = stderr;
|
|
1484
|
+
lastExitCode = exitCode;
|
|
1485
|
+
for (const v of videos ?? []) {
|
|
1486
|
+
pendingEvidence.push({
|
|
1487
|
+
kind: "video",
|
|
1488
|
+
name: v.name,
|
|
1489
|
+
path: v.path ?? join(evidenceDir, `${artifactSlug(v.name)}.webm`),
|
|
1490
|
+
stepIndex: videoStepIndex.get(v.name),
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
if (exitCode !== 0) {
|
|
1494
|
+
throw new Error(`Orchestrator exited with ${exitCode}: ${stderr || stdout}`);
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
const processUnit = async (unit, stepIndex, scope) => {
|
|
1498
|
+
if (unit.type === "script" && (!unit.adapter || unit.adapter === "tsAdapter")) {
|
|
1499
|
+
if (unit.assertions?.length)
|
|
1500
|
+
await flush();
|
|
1501
|
+
const mark = allStdout.length;
|
|
1502
|
+
const t0 = Date.now();
|
|
1503
|
+
const path = stepPathFor(unit);
|
|
1504
|
+
if (unit.args && Object.keys(unit.args).length > 0) {
|
|
1505
|
+
batch.push({ path, args: this.expandStepArgs(unit.args, env) });
|
|
1506
|
+
}
|
|
1507
|
+
else {
|
|
1508
|
+
batch.push(path);
|
|
1509
|
+
}
|
|
1510
|
+
if (unit.assertions?.length) {
|
|
1511
|
+
await flush();
|
|
1512
|
+
await this.evalStepAsserts(unit, allStdout.slice(mark), scope, assertCtx, lastExitCode, Date.now() - t0);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
else if (unit.type === "picture") {
|
|
1516
|
+
if (unit.assertions?.length)
|
|
1517
|
+
await flush();
|
|
1518
|
+
const mark = allStdout.length;
|
|
1519
|
+
const t0 = Date.now();
|
|
1520
|
+
batch.push(captureScriptFor(unit, stepIndex));
|
|
1521
|
+
if (unit.assertions?.length) {
|
|
1522
|
+
await flush();
|
|
1523
|
+
await this.evalStepAsserts(unit, allStdout.slice(mark), scope, assertCtx, lastExitCode, Date.now() - t0);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
else if (unit.type === "video") {
|
|
1527
|
+
const videoName = unit.name ?? "video";
|
|
1528
|
+
videoStepIndex.set(videoName, stepIndex);
|
|
1529
|
+
batch.push({ __axnVideo: "start", name: videoName, dir: evidenceDir });
|
|
1530
|
+
for (const inner of unit.children ?? []) {
|
|
1531
|
+
if (scope.stopped)
|
|
1532
|
+
break;
|
|
1533
|
+
await processUnit(inner, stepIndex, scope);
|
|
1534
|
+
}
|
|
1535
|
+
batch.push({ __axnVideo: "stop", name: videoName });
|
|
1536
|
+
}
|
|
1537
|
+
else if (unit.type === "extract") {
|
|
1538
|
+
if (unit.assertions?.length)
|
|
1539
|
+
await flush();
|
|
1540
|
+
const mark = allStdout.length;
|
|
1541
|
+
const t0 = Date.now();
|
|
1542
|
+
batch.push(extractScriptFor(unit));
|
|
1543
|
+
if (unit.assertions?.length) {
|
|
1544
|
+
await flush();
|
|
1545
|
+
await this.evalStepAsserts(unit, allStdout.slice(mark), scope, assertCtx, lastExitCode, Date.now() - t0);
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
else if (unit.type === "repeat") {
|
|
1549
|
+
await flush();
|
|
1550
|
+
const summary = await this.runRepeatUnit(unit, async () => {
|
|
1551
|
+
const iterScope = { stopped: false, sink: [], stdoutBase: allStdout.length };
|
|
1552
|
+
for (const [j, child] of (unit.children ?? []).entries()) {
|
|
1553
|
+
if (iterScope.stopped)
|
|
1554
|
+
break;
|
|
1555
|
+
await processUnit(child, j, iterScope);
|
|
1556
|
+
}
|
|
1557
|
+
if (iterScope.stopped) {
|
|
1558
|
+
batch = []; // drop scripts queued by the aborted iteration
|
|
1559
|
+
}
|
|
1560
|
+
else {
|
|
1561
|
+
await flush();
|
|
1562
|
+
}
|
|
1563
|
+
return iterScope.sink.every((r) => r.passed)
|
|
1564
|
+
? { ok: true }
|
|
1565
|
+
: { ok: false, why: this.scopeFailureWhy(iterScope) };
|
|
1566
|
+
});
|
|
1567
|
+
scope.sink.push(summary);
|
|
1568
|
+
if (!summary.passed)
|
|
1569
|
+
scope.stopped = true;
|
|
1570
|
+
}
|
|
1571
|
+
else if (unit.type === "metric") {
|
|
1572
|
+
// Flush before and after so the measurement covers the batch
|
|
1573
|
+
// that actually ran the children — script steps execute at
|
|
1574
|
+
// flush time, not when queued.
|
|
1575
|
+
await flush();
|
|
1576
|
+
await this.runMetricBlock(unit, flowResult, {
|
|
1577
|
+
env,
|
|
1578
|
+
flowDir,
|
|
1579
|
+
cwd: process.cwd(),
|
|
1580
|
+
flowName: flow.name,
|
|
1581
|
+
scenario: { ...scenario },
|
|
1582
|
+
baseUrl,
|
|
1583
|
+
}, async () => {
|
|
1584
|
+
for (const [j, child] of (unit.children ?? []).entries()) {
|
|
1585
|
+
if (scope.stopped)
|
|
1586
|
+
break;
|
|
1587
|
+
await processUnit(child, j, scope);
|
|
1588
|
+
}
|
|
1589
|
+
if (scope.stopped)
|
|
1590
|
+
batch = [];
|
|
1591
|
+
else
|
|
1592
|
+
await flush();
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
else if (unit.type === "assertions") {
|
|
1596
|
+
await flush();
|
|
1597
|
+
await evalBlock(unit.assertions ?? [], scope);
|
|
1598
|
+
}
|
|
1599
|
+
else if (unit.type === "message" || (unit.type === "script" && this.servesMessage(unit.adapter))) {
|
|
1600
|
+
await flush();
|
|
1601
|
+
const model = flow.models[0];
|
|
1602
|
+
if (!model) {
|
|
1603
|
+
throw new Error(`Flow '${flow.name}' has a message step but no <model> in <setup>`);
|
|
1604
|
+
}
|
|
1605
|
+
const t0 = Date.now();
|
|
1606
|
+
const response = this.absorbEmittedMetrics(await this.runMessageStep(flow, unit, model, scenario, startedScenarios, infra, baseUrl, env, autoPort, portFlag, deploymentUrl, flowResult), flowResult, unit.name ?? unit.description ?? "usermessage");
|
|
1607
|
+
allStdout += (allStdout ? "\n" : "") + response;
|
|
1608
|
+
await this.evalStepAsserts(unit, response, scope, assertCtx, 0, Date.now() - t0);
|
|
1609
|
+
}
|
|
1610
|
+
else {
|
|
1611
|
+
await flush();
|
|
1612
|
+
const t0 = Date.now();
|
|
1613
|
+
const stdout = this.absorbEmittedMetrics(await this.runCustomAdapterStep(flow, unit, env, flowResult), flowResult, unit.name ?? unit.description ?? "step");
|
|
1614
|
+
allStdout += (allStdout ? "\n" : "") + stdout;
|
|
1615
|
+
lastStderr = "";
|
|
1616
|
+
lastExitCode = 0;
|
|
1617
|
+
await this.evalStepAsserts(unit, stdout, scope, assertCtx, 0, Date.now() - t0);
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
for (const [i, unit] of units.entries()) {
|
|
1621
|
+
if (outerScope.stopped)
|
|
1622
|
+
break;
|
|
1623
|
+
await processUnit(unit, i, outerScope);
|
|
1624
|
+
}
|
|
1625
|
+
if (!outerScope.stopped)
|
|
1626
|
+
await flush();
|
|
1627
|
+
if (isFlowOverride) {
|
|
1628
|
+
await proc.stop();
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
else {
|
|
1632
|
+
if (tsScriptSteps.length > 1) {
|
|
1633
|
+
throw new Error(`Flow '${flow.name}' has multiple <step> elements but no orchestrator. ` +
|
|
1634
|
+
`Set an orchestrator on the <flow> or <scenario> to run multi-step flows.`);
|
|
1635
|
+
}
|
|
1636
|
+
const processSeq = async (unit, scope) => {
|
|
1637
|
+
if (unit.type === "script" && (!unit.adapter || unit.adapter === "tsAdapter")) {
|
|
1638
|
+
const t0 = Date.now();
|
|
1639
|
+
const { stdout: rawOut, stderr, exitCode } = await this.runTsScript(stepPathFor(unit), env, flowDir);
|
|
1640
|
+
const stdout = this.absorbEmittedMetrics(rawOut, flowResult, unit.name ?? unit.description ?? "script");
|
|
1641
|
+
allStdout += (allStdout ? "\n" : "") + stdout;
|
|
1642
|
+
lastStderr = stderr;
|
|
1643
|
+
lastExitCode = exitCode;
|
|
1644
|
+
if (exitCode !== 0) {
|
|
1645
|
+
throw new Error(`TS script exited with ${exitCode}: ${stderr || stdout}`);
|
|
1646
|
+
}
|
|
1647
|
+
await this.evalStepAsserts(unit, stdout, scope, assertCtx, exitCode, Date.now() - t0);
|
|
1648
|
+
}
|
|
1649
|
+
else if (unit.type === "assertions") {
|
|
1650
|
+
await evalBlock(unit.assertions ?? [], scope);
|
|
1651
|
+
}
|
|
1652
|
+
else if (unit.type === "metric") {
|
|
1653
|
+
await this.runMetricBlock(unit, flowResult, {
|
|
1654
|
+
env,
|
|
1655
|
+
flowDir,
|
|
1656
|
+
cwd: process.cwd(),
|
|
1657
|
+
flowName: flow.name,
|
|
1658
|
+
scenario: { ...scenario },
|
|
1659
|
+
baseUrl,
|
|
1660
|
+
}, async () => {
|
|
1661
|
+
for (const child of unit.children ?? []) {
|
|
1662
|
+
if (scope.stopped)
|
|
1663
|
+
break;
|
|
1664
|
+
await processSeq(child, scope);
|
|
1665
|
+
}
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
else if (unit.type === "extract") {
|
|
1669
|
+
throw new Error(`<extract> needs a browser page — use a tsAdapter flow with orchestrator= or runner="pw"`);
|
|
1670
|
+
}
|
|
1671
|
+
else if (unit.type === "repeat") {
|
|
1672
|
+
const summary = await this.runRepeatUnit(unit, async () => {
|
|
1673
|
+
const iterScope = { stopped: false, sink: [], stdoutBase: allStdout.length };
|
|
1674
|
+
for (const child of unit.children ?? []) {
|
|
1675
|
+
if (iterScope.stopped)
|
|
1676
|
+
break;
|
|
1677
|
+
await processSeq(child, iterScope);
|
|
1678
|
+
}
|
|
1679
|
+
return iterScope.sink.every((r) => r.passed)
|
|
1680
|
+
? { ok: true }
|
|
1681
|
+
: { ok: false, why: this.scopeFailureWhy(iterScope) };
|
|
1682
|
+
});
|
|
1683
|
+
scope.sink.push(summary);
|
|
1684
|
+
if (!summary.passed)
|
|
1685
|
+
scope.stopped = true;
|
|
1686
|
+
}
|
|
1687
|
+
else if (unit.type === "message" || (unit.type === "script" && this.servesMessage(unit.adapter))) {
|
|
1688
|
+
const model = flow.models[0];
|
|
1689
|
+
if (!model) {
|
|
1690
|
+
throw new Error(`Flow '${flow.name}' has a message step but no <model> in <setup>`);
|
|
1691
|
+
}
|
|
1692
|
+
const t0 = Date.now();
|
|
1693
|
+
const response = this.absorbEmittedMetrics(await this.runMessageStep(flow, unit, model, scenario, startedScenarios, infra, baseUrl, env, autoPort, portFlag, deploymentUrl, flowResult), flowResult, unit.name ?? unit.description ?? "usermessage");
|
|
1694
|
+
allStdout += (allStdout ? "\n" : "") + response;
|
|
1695
|
+
await this.evalStepAsserts(unit, response, scope, assertCtx, 0, Date.now() - t0);
|
|
1696
|
+
}
|
|
1697
|
+
else {
|
|
1698
|
+
const t0 = Date.now();
|
|
1699
|
+
const stdout = this.absorbEmittedMetrics(await this.runCustomAdapterStep(flow, unit, env, flowResult), flowResult, unit.name ?? unit.description ?? "step");
|
|
1700
|
+
allStdout += (allStdout ? "\n" : "") + stdout;
|
|
1701
|
+
lastStderr = "";
|
|
1702
|
+
lastExitCode = 0;
|
|
1703
|
+
await this.evalStepAsserts(unit, stdout, scope, assertCtx, 0, Date.now() - t0);
|
|
1704
|
+
}
|
|
1705
|
+
};
|
|
1706
|
+
for (const unit of units) {
|
|
1707
|
+
if (outerScope.stopped)
|
|
1708
|
+
break;
|
|
1709
|
+
await processSeq(unit, outerScope);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
flowResult.response = allStdout;
|
|
1713
|
+
flowResult.exitCode = lastExitCode;
|
|
1714
|
+
flowResult.passed = flowResult.assertions.every((a) => a.passed);
|
|
1715
|
+
if (!flowResult.passed && !flowResult.error) {
|
|
1716
|
+
flowResult.error = lastStderr || "One or more assertions failed";
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
catch (err) {
|
|
1720
|
+
flowResult.error = err instanceof Error ? err.message : String(err);
|
|
1721
|
+
}
|
|
1722
|
+
finally {
|
|
1723
|
+
for (const dir of tmpDirs) {
|
|
1724
|
+
try {
|
|
1725
|
+
rmSync(dir, { recursive: true, force: true });
|
|
1726
|
+
}
|
|
1727
|
+
catch {
|
|
1728
|
+
/* best effort */
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
const evidence = pendingEvidence.filter((e) => existsSync(e.path));
|
|
1733
|
+
if (evidence.length > 0) {
|
|
1734
|
+
flowResult.evidence = evidence;
|
|
1735
|
+
}
|
|
1736
|
+
flowResult.durationMs = Date.now() - start;
|
|
1737
|
+
return flowResult;
|
|
1738
|
+
}
|
|
1739
|
+
async buildDeviceEnv(device) {
|
|
1740
|
+
const resolved = await resolveDeviceEnv(device);
|
|
1741
|
+
if (!resolved) {
|
|
1742
|
+
throw new Error(`No device-env resolver could handle '${device}'. ` +
|
|
1743
|
+
"Install a plugin that provides device definitions (e.g. an infra plugin), " +
|
|
1744
|
+
"or check the device name.");
|
|
1745
|
+
}
|
|
1746
|
+
return { ...process.env, ...resolved };
|
|
1747
|
+
}
|
|
1748
|
+
/** In --quiet mode, silence routine console.log output while fn runs —
|
|
1749
|
+
* lifecycle commands (start/stop/clean) are chatty; console.error and
|
|
1750
|
+
* console.warn still print, and compose output is silenced at fd level
|
|
1751
|
+
* via options.quiet → runCompose silent. */
|
|
1752
|
+
async quietly(fn) {
|
|
1753
|
+
if (!this.quietMode)
|
|
1754
|
+
return fn();
|
|
1755
|
+
const orig = console.log;
|
|
1756
|
+
console.log = () => { };
|
|
1757
|
+
try {
|
|
1758
|
+
return await fn();
|
|
1759
|
+
}
|
|
1760
|
+
finally {
|
|
1761
|
+
console.log = orig;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
/** Progress output that --quiet suppresses. */
|
|
1765
|
+
progress(message) {
|
|
1766
|
+
if (!this.quietMode)
|
|
1767
|
+
console.log(message);
|
|
1768
|
+
if (this.observer && this.liveStep !== null) {
|
|
1769
|
+
this.observer.output(this.liveStep, message.replace(/\x1b\[[0-9;]*m/g, "").trim());
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
/** --report: write an additional machine-readable report at the
|
|
1773
|
+
* requested path — JSON or JUnit XML for CI test reporting. */
|
|
1774
|
+
writeExtraReport(results, durationMs) {
|
|
1775
|
+
if (!this.reportPath)
|
|
1776
|
+
return;
|
|
1777
|
+
const path = resolve(process.cwd(), this.reportPath);
|
|
1778
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1779
|
+
const git = this._resolvedFilePath ? gitInfoFor(dirname(this._resolvedFilePath)) : null;
|
|
1780
|
+
const content = this.reportFormat === "junit"
|
|
1781
|
+
? toJUnitXml(results)
|
|
1782
|
+
: JSON.stringify({
|
|
1783
|
+
timestamp: new Date().toISOString(),
|
|
1784
|
+
durationMs,
|
|
1785
|
+
...(git ? { git } : {}),
|
|
1786
|
+
flows: results,
|
|
1787
|
+
}, null, 2);
|
|
1788
|
+
writeFileSync(path, content);
|
|
1789
|
+
console.log(`Report written to ${path}`);
|
|
1790
|
+
}
|
|
1791
|
+
/** Warn once per scenario about flag/attribute combinations that are
|
|
1792
|
+
* accepted but ignored or surprising — runs before any flow executes so
|
|
1793
|
+
* dead config is visible up front. */
|
|
1794
|
+
warnForDeployments(flows, opts) {
|
|
1795
|
+
const warn = (msg) => console.log(`\x1b[33mWarning: ${msg}\x1b[0m`);
|
|
1796
|
+
if (opts.infra) {
|
|
1797
|
+
if (opts.portFlag !== null)
|
|
1798
|
+
warn("--port has no effect with --infra");
|
|
1799
|
+
if (opts.autoPort)
|
|
1800
|
+
warn("--auto-port has no effect with --infra");
|
|
1801
|
+
}
|
|
1802
|
+
if (opts.baseUrlFlag && !opts.stopAfter) {
|
|
1803
|
+
warn("--no-stop has no effect with --base-url — nothing is started");
|
|
1804
|
+
}
|
|
1805
|
+
const warned = new Set();
|
|
1806
|
+
for (const flow of flows) {
|
|
1807
|
+
for (const scenario of flow.scenarios) {
|
|
1808
|
+
const url = this.deploymentUrlRaw(scenario, flow, opts.baseUrlFlag);
|
|
1809
|
+
if (!url || warned.has(scenario.name))
|
|
1810
|
+
continue;
|
|
1811
|
+
warned.add(scenario.name);
|
|
1812
|
+
if (opts.infra) {
|
|
1813
|
+
warn(`scenario '${scenario.name}': deployment url is ignored — --infra targets a device`);
|
|
1814
|
+
continue;
|
|
1815
|
+
}
|
|
1816
|
+
if (scenario.service) {
|
|
1817
|
+
warn(`scenario '${scenario.name}': 'service' is ignored for deployment targets`);
|
|
1818
|
+
}
|
|
1819
|
+
if (scenario.readiness.some((r) => r.service || r.port)) {
|
|
1820
|
+
warn(`scenario '${scenario.name}': readiness service=/port= are ignored for deployment targets`);
|
|
1821
|
+
}
|
|
1822
|
+
if (opts.portFlag !== null) {
|
|
1823
|
+
warn(`--port has no effect on deployment target '${scenario.name}'`);
|
|
1824
|
+
}
|
|
1825
|
+
if (opts.autoPort) {
|
|
1826
|
+
warn(`--auto-port has no effect on deployment target '${scenario.name}'`);
|
|
1827
|
+
}
|
|
1828
|
+
try {
|
|
1829
|
+
if (flow.env.SCENARIO_PORT && !new URL(url).port) {
|
|
1830
|
+
warn(`flow '${flow.name}': SCENARIO_PORT in <env> is kept, but the deployment URL has no explicit port`);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
catch { /* invalid url — the run reports it */ }
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
/** The deployment URL a scenario would target, without validating it —
|
|
1838
|
+
* null when the scenario uses the local lifecycle. Used to classify
|
|
1839
|
+
* scenarios (warnings, skip-lists) without failing on a bad value. */
|
|
1840
|
+
deploymentUrlRaw(scenario, flow, override) {
|
|
1841
|
+
const raw = override ?? scenario.url ?? flow.baseUrl;
|
|
1842
|
+
if (!raw)
|
|
1843
|
+
return null;
|
|
1844
|
+
return substituteEnvVars(raw, {
|
|
1845
|
+
...process.env,
|
|
1846
|
+
...flow.env,
|
|
1847
|
+
}).replace(/\/+$/, "");
|
|
1848
|
+
}
|
|
1849
|
+
/** Resolve an explicit deployment URL for the scenario — --base-url wins
|
|
1850
|
+
* over url= which wins over <flow base-url>; ${VAR} references expand
|
|
1851
|
+
* against process + flow env. Returns null when the scenario uses the
|
|
1852
|
+
* local lifecycle. Throws on anything that is not an http(s) URL. */
|
|
1853
|
+
deploymentUrl(scenario, flow, override) {
|
|
1854
|
+
const raw = override ?? scenario.url ?? flow.baseUrl;
|
|
1855
|
+
const url = this.deploymentUrlRaw(scenario, flow, override);
|
|
1856
|
+
if (!url)
|
|
1857
|
+
return null;
|
|
1858
|
+
try {
|
|
1859
|
+
const proto = new URL(url).protocol;
|
|
1860
|
+
if (proto !== "http:" && proto !== "https:")
|
|
1861
|
+
throw new Error();
|
|
1862
|
+
}
|
|
1863
|
+
catch {
|
|
1864
|
+
throw new Error(`Scenario '${scenario.name}': deployment url '${url}' is not a valid http(s) URL` +
|
|
1865
|
+
(raw !== url ? ` (expanded from '${raw}')` : ""));
|
|
1866
|
+
}
|
|
1867
|
+
return url;
|
|
1868
|
+
}
|
|
1869
|
+
/** env a deployment target exposes to steps — BASE_URL, plus SCENARIO_PORT
|
|
1870
|
+
* when the URL carries an explicit port (flows use it for sibling URLs). */
|
|
1871
|
+
deploymentEnv(baseUrl) {
|
|
1872
|
+
const env = { BASE_URL: baseUrl };
|
|
1873
|
+
const port = new URL(baseUrl).port;
|
|
1874
|
+
if (port)
|
|
1875
|
+
env.SCENARIO_PORT = port;
|
|
1876
|
+
return env;
|
|
1877
|
+
}
|
|
1878
|
+
resolveTsx() {
|
|
1879
|
+
try {
|
|
1880
|
+
const require = createRequire(import.meta.url);
|
|
1881
|
+
const tsxPackagePath = require.resolve("tsx/package.json");
|
|
1882
|
+
const tsxPackageJson = JSON.parse(readFileSync(tsxPackagePath, "utf-8"));
|
|
1883
|
+
return resolve(dirname(tsxPackagePath), tsxPackageJson.bin);
|
|
1884
|
+
}
|
|
1885
|
+
catch (err) {
|
|
1886
|
+
throw new Error("tsx is not available. Install tsx to use the tsAdapter.");
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
resolveOrchestratorHost() {
|
|
1890
|
+
const current = fileURLToPath(import.meta.url);
|
|
1891
|
+
const ext = current.endsWith(".ts") ? ".ts" : ".js";
|
|
1892
|
+
return resolve(dirname(current), `orchestrator-host${ext}`);
|
|
1893
|
+
}
|
|
1894
|
+
/** True when `name` is a registered plugin adapter serving the
|
|
1895
|
+
* <usermessage> tag — those adapters receive message steps, not scripts. */
|
|
1896
|
+
servesMessage(name) {
|
|
1897
|
+
if (!name)
|
|
1898
|
+
return false;
|
|
1899
|
+
return flowAdaptersForTag("usermessage").some((s) => s.name === name);
|
|
1900
|
+
}
|
|
1901
|
+
/** The adapter that should handle a step: explicit adapter= wins, else a
|
|
1902
|
+
* custom step tag resolves to the adapter declaring that tag. */
|
|
1903
|
+
adapterForStep(step) {
|
|
1904
|
+
if (step.adapter)
|
|
1905
|
+
return step.adapter;
|
|
1906
|
+
if (step.type === "script" || step.type === "message" || step.type === "assertions")
|
|
1907
|
+
return null;
|
|
1908
|
+
return flowAdaptersForTag(step.type)[0]?.name ?? null;
|
|
1909
|
+
}
|
|
1910
|
+
/** Calls `start` once on every plugin adapter the flow's steps use, in
|
|
1911
|
+
* first-use order, before any step (and so before any scenario) runs. */
|
|
1912
|
+
async startAdapters(flow, env) {
|
|
1913
|
+
const firstStep = new Map();
|
|
1914
|
+
const walk = (steps) => {
|
|
1915
|
+
for (const step of steps) {
|
|
1916
|
+
const name = this.adapterForStep(step);
|
|
1917
|
+
if (name && hasFlowAdapter(name) && !firstStep.has(name))
|
|
1918
|
+
firstStep.set(name, step);
|
|
1919
|
+
walk(step.children ?? []);
|
|
1920
|
+
}
|
|
1921
|
+
};
|
|
1922
|
+
walk(flow.steps);
|
|
1923
|
+
for (const [name, step] of firstStep) {
|
|
1924
|
+
const adapter = await flowAdapter(name);
|
|
1925
|
+
await adapter.start?.(this.makeAdapterCtx(flow, step, env, { scenario: flow.scenarios[0] }));
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
/** Teardown errors are warnings: the flow's own result already stands. */
|
|
1929
|
+
async disposeAdapters(flow) {
|
|
1930
|
+
const env = this.expandEnvVars({ ...process.env, ...(flow?.env ?? {}) });
|
|
1931
|
+
const errors = await disposeFlowAdapters(() => this.makeAdapterCtx(flow, { type: "dispose" }, env));
|
|
1932
|
+
for (const err of errors)
|
|
1933
|
+
console.error(`\x1b[33mWarning: ${err.message}\x1b[0m`);
|
|
1934
|
+
}
|
|
1935
|
+
/** Build the context handed to a plugin adapter. */
|
|
1936
|
+
makeAdapterCtx(flow, step, env, extra) {
|
|
1937
|
+
const flowDir = this._resolvedFilePath ? dirname(this._resolvedFilePath) : process.cwd();
|
|
1938
|
+
const result = extra?.result;
|
|
1939
|
+
return {
|
|
1940
|
+
env,
|
|
1941
|
+
flowDir,
|
|
1942
|
+
cwd: process.cwd(),
|
|
1943
|
+
flowName: flow?.name ?? "",
|
|
1944
|
+
flow: (flow ?? { name: "", env: {} }),
|
|
1945
|
+
scenario: extra?.scenario,
|
|
1946
|
+
model: extra?.model,
|
|
1947
|
+
baseUrl: extra?.baseUrl,
|
|
1948
|
+
runScript: (path, scriptEnv, cwd) => this.runTsScript(path, scriptEnv ?? env, cwd ?? flowDir),
|
|
1949
|
+
emitMetric: (m) => {
|
|
1950
|
+
if (result) {
|
|
1951
|
+
(result.metrics ??= []).push({ id: step.name ?? step.description ?? "step", ...m });
|
|
1952
|
+
}
|
|
1953
|
+
this.progress(` metric '${m.name}': ${m.value}${m.unit ?? ""} (emitted)`);
|
|
1954
|
+
},
|
|
1955
|
+
log: (message) => this.progress(` ${message}`),
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
async runCustomAdapterStep(flow, step, env, result) {
|
|
1959
|
+
const name = this.adapterForStep(step);
|
|
1960
|
+
if (!name) {
|
|
1961
|
+
throw new Error(`No adapter found for <${step.type}> — pass adapter="..." or install ` +
|
|
1962
|
+
`a plugin adapter declaring the tag via axn-dev.flowAdapters`);
|
|
1963
|
+
}
|
|
1964
|
+
const expandedStep = step.args
|
|
1965
|
+
? { ...step, args: this.expandStepArgs(step.args, env) }
|
|
1966
|
+
: step;
|
|
1967
|
+
// Registered plugin adapters run in-process.
|
|
1968
|
+
if (hasFlowAdapter(name)) {
|
|
1969
|
+
this.progress(` Adapter '${name}' resolved via plugin registry`);
|
|
1970
|
+
const { scenario, baseUrl, env: stepEnv } = await this.adapterScenario(flow, name, env);
|
|
1971
|
+
const adapter = await flowAdapter(name);
|
|
1972
|
+
const out = await adapter.run(expandedStep, this.makeAdapterCtx(flow, expandedStep, stepEnv, { result, scenario, baseUrl }));
|
|
1973
|
+
return typeof out === "string" ? out : "";
|
|
1974
|
+
}
|
|
1975
|
+
// File-path adapters run as tsx subprocesses.
|
|
1976
|
+
if (expandedStep.type !== "script") {
|
|
1977
|
+
throw new Error(`<${expandedStep.type}> requires a plugin adapter named '${name}' — not registered`);
|
|
1978
|
+
}
|
|
1979
|
+
const { exitCode, stdout, stderr } = await this.runExternalAdapter(expandedStep, env, dirname(this._resolvedFilePath));
|
|
1980
|
+
if (exitCode !== 0) {
|
|
1981
|
+
throw new Error(`External adapter '${name}' exited with ${exitCode}: ${stderr || stdout}`);
|
|
1982
|
+
}
|
|
1983
|
+
return stdout;
|
|
1984
|
+
}
|
|
1985
|
+
/** For an adapter declaring wantsScenario: the flow's first scenario,
|
|
1986
|
+
* started and ready, with its base URL — the same engine-side lifecycle
|
|
1987
|
+
* message adapters get. Deployment targets keep their own BASE_URL. */
|
|
1988
|
+
async adapterScenario(flow, adapterName, env) {
|
|
1989
|
+
const scenario = flow?.scenarios[0];
|
|
1990
|
+
const run = this.adapterScenarioRun;
|
|
1991
|
+
const wants = flowAdapterSpecs().find((s) => s.name === adapterName)?.wantsScenario;
|
|
1992
|
+
if (!flow || !scenario || !run || !wants || this.deploymentUrl(scenario, flow, null)) {
|
|
1993
|
+
return { scenario, env };
|
|
1994
|
+
}
|
|
1995
|
+
let prepared = run.prepared.get(scenario.name);
|
|
1996
|
+
if (!prepared) {
|
|
1997
|
+
const p = await this.prepareScenario(scenario, flow, run.started, run.autoPort, run.portFlag);
|
|
1998
|
+
await this.waitForReadiness(scenario, p.scenarioPath, p.env, p.endpoints);
|
|
1999
|
+
prepared = { baseUrl: p.baseUrl, env: p.env };
|
|
2000
|
+
run.prepared.set(scenario.name, prepared);
|
|
2001
|
+
}
|
|
2002
|
+
if (prepared.baseUrl && this.observer && !this.productWindow)
|
|
2003
|
+
this.pendingProduct = prepared.baseUrl;
|
|
2004
|
+
return { scenario, baseUrl: prepared.baseUrl, env: { ...env, ...prepared.env } };
|
|
2005
|
+
}
|
|
2006
|
+
async runExternalAdapter(step, env, flowDir) {
|
|
2007
|
+
const adapter = step.adapter;
|
|
2008
|
+
const registered = this.adapterRegistry?.resolve(adapter) ?? null;
|
|
2009
|
+
const candidates = [
|
|
2010
|
+
{ via: registered?.via ?? "", path: registered?.path ?? null },
|
|
2011
|
+
{ via: "step 'src' attribute", path: step.src ? resolve(flowDir, step.src) : null },
|
|
2012
|
+
{ via: "flow directory", path: resolve(flowDir, "adapters", `${adapter}.ts`) },
|
|
2013
|
+
{ via: "flow directory", path: resolve(flowDir, "adapters", `${adapter}.js`) },
|
|
2014
|
+
];
|
|
2015
|
+
let adapterPath = null;
|
|
2016
|
+
let adapterVia = "";
|
|
2017
|
+
for (const c of candidates) {
|
|
2018
|
+
if (c.path && existsSync(c.path)) {
|
|
2019
|
+
adapterPath = c.path;
|
|
2020
|
+
adapterVia = c.via;
|
|
2021
|
+
break;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
if (!adapterPath) {
|
|
2025
|
+
const searched = candidates.map((c) => c.path).filter(Boolean).join(", ");
|
|
2026
|
+
throw new Error(`External adapter '${adapter}' not found. Searched: ${searched}`);
|
|
2027
|
+
}
|
|
2028
|
+
this.progress(` Adapter '${adapter}' resolved via ${adapterVia}: ${adapterPath}`);
|
|
2029
|
+
return new Promise((resolve, reject) => {
|
|
2030
|
+
const tsxBin = this.resolveTsx();
|
|
2031
|
+
const child = spawn(process.execPath, [tsxBin, adapterPath], {
|
|
2032
|
+
env: { ...env, AXN_STEP: JSON.stringify(step), AXN_FLOW_DIR: flowDir },
|
|
2033
|
+
cwd: flowDir,
|
|
2034
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
2035
|
+
});
|
|
2036
|
+
let stdout = "";
|
|
2037
|
+
let stderr = "";
|
|
2038
|
+
child.stdout.on("data", (data) => {
|
|
2039
|
+
stdout += data.toString();
|
|
2040
|
+
});
|
|
2041
|
+
child.stderr.on("data", (data) => {
|
|
2042
|
+
stderr += data.toString();
|
|
2043
|
+
});
|
|
2044
|
+
child.on("error", (err) => reject(err));
|
|
2045
|
+
child.on("close", (code) => {
|
|
2046
|
+
resolve({ exitCode: code ?? 1, stdout, stderr });
|
|
2047
|
+
});
|
|
2048
|
+
});
|
|
2049
|
+
}
|
|
2050
|
+
runTsScript(scriptPath, env, cwd) {
|
|
2051
|
+
return new Promise((resolve, reject) => {
|
|
2052
|
+
const tsxBin = this.resolveTsx();
|
|
2053
|
+
const child = spawn(process.execPath, [tsxBin, scriptPath], {
|
|
2054
|
+
env,
|
|
2055
|
+
cwd,
|
|
2056
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
2057
|
+
});
|
|
2058
|
+
let stdout = "";
|
|
2059
|
+
let stderr = "";
|
|
2060
|
+
child.stdout.on("data", (data) => {
|
|
2061
|
+
stdout += data.toString();
|
|
2062
|
+
});
|
|
2063
|
+
child.stderr.on("data", (data) => {
|
|
2064
|
+
stderr += data.toString();
|
|
2065
|
+
});
|
|
2066
|
+
child.on("error", (err) => reject(err));
|
|
2067
|
+
child.on("close", (code) => {
|
|
2068
|
+
resolve({
|
|
2069
|
+
exitCode: code ?? 1,
|
|
2070
|
+
stdout,
|
|
2071
|
+
stderr,
|
|
2072
|
+
});
|
|
2073
|
+
});
|
|
2074
|
+
});
|
|
2075
|
+
}
|
|
2076
|
+
async runMessageStep(flow, step, model, scenario, startedScenarios, infra = null, deviceBaseUrl, env, autoPort = false, portFlag = null, deployUrl = null, result) {
|
|
2077
|
+
const adapterName = step.adapter ?? scenario.adapter;
|
|
2078
|
+
const spec = adapterName
|
|
2079
|
+
? flowAdapterSpecs().find((s) => s.name === adapterName)
|
|
2080
|
+
: undefined;
|
|
2081
|
+
if (!adapterName || adapterName === "tsAdapter" || !spec) {
|
|
2082
|
+
const serving = flowAdaptersForTag("usermessage").map((s) => s.name);
|
|
2083
|
+
throw new Error(`Message step in flow '${flow.name}' has no usable adapter ` +
|
|
2084
|
+
`(registered <usermessage> adapters: ${serving.join(", ") || "(none)"}) — ` +
|
|
2085
|
+
`set adapter= on the <usermessage> or the <scenario>`);
|
|
2086
|
+
}
|
|
2087
|
+
let stepEnv = env ?? this.expandEnvVars({ ...process.env, ...flow.env });
|
|
2088
|
+
let baseUrl;
|
|
2089
|
+
// -i targets a device — deployment urls are never consulted, not even
|
|
2090
|
+
// for validation.
|
|
2091
|
+
const deploymentUrl = infra ? null : this.deploymentUrl(scenario, flow, deployUrl);
|
|
2092
|
+
if (infra) {
|
|
2093
|
+
const deviceEnv = await this.buildDeviceEnv(infra);
|
|
2094
|
+
stepEnv = this.expandEnvVars({ ...deviceEnv, ...flow.env });
|
|
2095
|
+
baseUrl = deviceBaseUrl ?? deviceEnv.BASE_URL;
|
|
2096
|
+
}
|
|
2097
|
+
else if (deploymentUrl) {
|
|
2098
|
+
// Deployment target — no scenario lifecycle; BASE_URL is the
|
|
2099
|
+
// deployment's URL (url= attribute or --base-url).
|
|
2100
|
+
const target = deviceBaseUrl ?? deploymentUrl;
|
|
2101
|
+
stepEnv = env ?? this.expandEnvVars({
|
|
2102
|
+
...process.env,
|
|
2103
|
+
...flow.env,
|
|
2104
|
+
...this.deploymentEnv(target),
|
|
2105
|
+
});
|
|
2106
|
+
baseUrl = target;
|
|
2107
|
+
}
|
|
2108
|
+
else if (spec.wantsScenario) {
|
|
2109
|
+
// Engine-side lifecycle: start the scenario, probe readiness, hand the
|
|
2110
|
+
// adapter the service's base URL.
|
|
2111
|
+
const prepared = await this.prepareScenario(scenario, flow, startedScenarios, autoPort, portFlag);
|
|
2112
|
+
await this.waitForReadiness(scenario, prepared.scenarioPath, prepared.env, prepared.endpoints);
|
|
2113
|
+
stepEnv = prepared.env;
|
|
2114
|
+
baseUrl = prepared.baseUrl;
|
|
2115
|
+
}
|
|
2116
|
+
const adapter = await flowAdapter(adapterName);
|
|
2117
|
+
const out = await adapter.run(step, this.makeAdapterCtx(flow, step, stepEnv, { scenario, model, baseUrl, result }));
|
|
2118
|
+
return typeof out === "string" ? out : "";
|
|
2119
|
+
}
|
|
2120
|
+
/** Expand ${VAR} / ${VAR:-default} references in step args against the
|
|
2121
|
+
* merged env — enables parameterized reusable steps like
|
|
2122
|
+
* <step action="login" TEST_USER="${MOM_USER}"/>. */
|
|
2123
|
+
expandStepArgs(args, env) {
|
|
2124
|
+
return expandStepArgs(args, env);
|
|
2125
|
+
}
|
|
2126
|
+
async prepareScenario(scenario, flow, startedScenarios, autoPort = false, portFlag = null) {
|
|
2127
|
+
const discovery = new ScenarioDiscoveryService(process.cwd());
|
|
2128
|
+
const workspace = discovery.getWorkspaceConfig();
|
|
2129
|
+
const resolution = discovery.resolveScenario(scenario.name);
|
|
2130
|
+
const scenarioPath = resolution.scenario.path;
|
|
2131
|
+
const env = {
|
|
2132
|
+
...process.env,
|
|
2133
|
+
...workspace.repoEnv,
|
|
2134
|
+
...resolution.scenario.env,
|
|
2135
|
+
...flow.env,
|
|
2136
|
+
};
|
|
2137
|
+
// Same rule as `axn-dev start`: with an explicit --port only the copy on that port counts as
|
|
2138
|
+
// running — another port's copy may be a different checkout or branch.
|
|
2139
|
+
const portProject = portFlag !== null
|
|
2140
|
+
? getComposeProjectName(scenarioPath, { ...env, SCENARIO_PORT: String(portFlag) }) ?? undefined
|
|
2141
|
+
: undefined;
|
|
2142
|
+
if (!isScenarioRunning(scenarioPath, portProject)) {
|
|
2143
|
+
const startArgs = ["-s", scenario.name];
|
|
2144
|
+
if (autoPort)
|
|
2145
|
+
startArgs.push("--auto-port");
|
|
2146
|
+
if (portFlag !== null) {
|
|
2147
|
+
startArgs.push("--port", String(portFlag));
|
|
2148
|
+
}
|
|
2149
|
+
let startLog = "";
|
|
2150
|
+
try {
|
|
2151
|
+
await this.quietly(() => new StartCommand().execute(startArgs, {
|
|
2152
|
+
env: expandFlowEnv(flow.env),
|
|
2153
|
+
quiet: this.quietMode,
|
|
2154
|
+
onOutput: this.quietMode ? (c) => { startLog += c; } : undefined,
|
|
2155
|
+
}));
|
|
2156
|
+
}
|
|
2157
|
+
catch (err) {
|
|
2158
|
+
// Quiet mode swallowed the compose output — replay it so the
|
|
2159
|
+
// failure is still diagnosable.
|
|
2160
|
+
if (startLog) {
|
|
2161
|
+
console.error(`\n--- scenario '${scenario.name}' start output ---\n${startLog}`);
|
|
2162
|
+
}
|
|
2163
|
+
throw err;
|
|
2164
|
+
}
|
|
2165
|
+
startedScenarios.add(scenario.name);
|
|
2166
|
+
}
|
|
2167
|
+
else if (!this.quietMode) {
|
|
2168
|
+
console.log(`\x1b[32mScenario '${scenario.name}' is already running\x1b[0m`);
|
|
2169
|
+
}
|
|
2170
|
+
const runningPort = portFlag ?? getRunningScenarioPort(scenarioPath);
|
|
2171
|
+
if (runningPort !== null) {
|
|
2172
|
+
env.SCENARIO_PORT = String(runningPort);
|
|
2173
|
+
}
|
|
2174
|
+
// Compose-published ports first; in single-port (Caddy) scenarios the
|
|
2175
|
+
// individual services only exist as name → URL entries in axn-dev.yaml
|
|
2176
|
+
// (frontend-services / backend-services / proxies), so merge those in too.
|
|
2177
|
+
const named = resolveEndpoints({
|
|
2178
|
+
...(resolution.scenario.proxies ?? {}),
|
|
2179
|
+
...(resolution.scenario.frontendServices ?? {}),
|
|
2180
|
+
...(resolution.scenario.backendServices ?? {}),
|
|
2181
|
+
}, env);
|
|
2182
|
+
const endpoints = [
|
|
2183
|
+
...getServiceEndpoints(scenarioPath, env),
|
|
2184
|
+
...Object.entries(named).map(([service, ep]) => ({ service, port: ep.port, url: ep.url })),
|
|
2185
|
+
];
|
|
2186
|
+
const server = endpoints.find((e) => e.service === scenario.service);
|
|
2187
|
+
if (!server) {
|
|
2188
|
+
throw new Error(`Service '${scenario.service}' not found in scenario '${scenario.name}'`);
|
|
2189
|
+
}
|
|
2190
|
+
return { baseUrl: server.url, scenarioPath, env, endpoints };
|
|
2191
|
+
}
|
|
2192
|
+
/**
|
|
2193
|
+
* Expand ${VAR} and ${VAR:-default} references inside env values against the
|
|
2194
|
+
* env itself (e.g. KC_URL=http://keycloak.localhost:${SCENARIO_PORT}).
|
|
2195
|
+
* Unresolved references without a default are left as-is. Iterates so values
|
|
2196
|
+
* may reference other env vars; bounded to avoid infinite loops on cycles.
|
|
2197
|
+
*/
|
|
2198
|
+
expandEnvVars(env) {
|
|
2199
|
+
return expandEnvVars(env);
|
|
2200
|
+
}
|
|
2201
|
+
async waitForReadiness(scenario, scenarioPath, env, endpoints) {
|
|
2202
|
+
if (!scenario.readiness || scenario.readiness.length === 0)
|
|
2203
|
+
return;
|
|
2204
|
+
const resolvedEndpoints = endpoints ?? getServiceEndpoints(scenarioPath, env);
|
|
2205
|
+
for (const r of scenario.readiness) {
|
|
2206
|
+
const targetService = r.service ?? scenario.service;
|
|
2207
|
+
const endpoint = resolvedEndpoints.find((e) => e.service === targetService);
|
|
2208
|
+
const port = r.port ? parseInt(r.port, 10) : endpoint?.port;
|
|
2209
|
+
if (!port && !endpoint?.url) {
|
|
2210
|
+
throw new Error(`Readiness probe for service '${targetService}' cannot resolve a port. ` +
|
|
2211
|
+
`Either publish a port in the compose file or set the 'port' attribute on <readiness>.`);
|
|
2212
|
+
}
|
|
2213
|
+
const path = r.path ?? "/";
|
|
2214
|
+
// Named (frontend-services) endpoints resolve to a full URL — required
|
|
2215
|
+
// for host-based routing in single-port Caddy scenarios.
|
|
2216
|
+
const url = r.port || !endpoint?.url
|
|
2217
|
+
? `http://localhost:${port}${path}`
|
|
2218
|
+
: `${endpoint.url}${path}`;
|
|
2219
|
+
const method = r.method ?? "GET";
|
|
2220
|
+
const expected = r.expected ?? "ok";
|
|
2221
|
+
const timeout = r.timeout ? parseInt(r.timeout, 10) : 120000;
|
|
2222
|
+
await this.waitForProbe(url, method, expected, timeout);
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
/** Readiness probes for a deployment target — there is no endpoint map to
|
|
2226
|
+
* resolve service/port against, so every declared probe addresses the
|
|
2227
|
+
* deployment's base URL (service/port attributes are ignored). */
|
|
2228
|
+
async waitForDeploymentReadiness(scenario, baseUrl) {
|
|
2229
|
+
for (const r of scenario.readiness ?? []) {
|
|
2230
|
+
await this.waitForProbe(`${baseUrl}${r.path ?? "/"}`, r.method ?? "GET", r.expected ?? "ok", r.timeout ? parseInt(r.timeout, 10) : 120000);
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
async waitForProbe(url, method = "GET", expected = "ok", timeoutMs = 120000) {
|
|
2234
|
+
const start = Date.now();
|
|
2235
|
+
const expectedStatus = parseInt(expected, 10);
|
|
2236
|
+
const checkByStatus = !isNaN(expectedStatus);
|
|
2237
|
+
while (Date.now() - start < timeoutMs) {
|
|
2238
|
+
try {
|
|
2239
|
+
const response = await fetch(url, { method, signal: AbortSignal.timeout(1000) });
|
|
2240
|
+
if (checkByStatus ? response.status === expectedStatus : response.ok) {
|
|
2241
|
+
return;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
catch { /* not ready yet */ }
|
|
2245
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
2246
|
+
}
|
|
2247
|
+
throw new Error(`Timed out waiting for ${url} to respond with ${expected}`);
|
|
2248
|
+
}
|
|
2249
|
+
async evaluateAssertion(assertion, response, exitCode, ctx, durationMs) {
|
|
2250
|
+
const result = { that: assertion.that, value: assertion.value, passed: false };
|
|
2251
|
+
if (assertion.that === "screenshot") {
|
|
2252
|
+
const outcome = await evaluateScreenshotAssertion(assertion, ctx ?? {
|
|
2253
|
+
flowDir: dirname(this._resolvedFilePath ?? process.cwd()),
|
|
2254
|
+
env: this.expandEnvVars(process.env),
|
|
2255
|
+
});
|
|
2256
|
+
result.passed = outcome.passed;
|
|
2257
|
+
result.actual = outcome.detail;
|
|
2258
|
+
return result;
|
|
2259
|
+
}
|
|
2260
|
+
if (assertion.that === "llm") {
|
|
2261
|
+
const env = ctx?.env ?? this.expandEnvVars(process.env);
|
|
2262
|
+
const outcome = await evaluateLlmAssertion(assertion, response, env);
|
|
2263
|
+
result.passed = outcome.passed;
|
|
2264
|
+
result.actual = outcome.actual;
|
|
2265
|
+
return result;
|
|
2266
|
+
}
|
|
2267
|
+
if (assertion.that === "duration") {
|
|
2268
|
+
const max = assertion.max ?? (assertion.value.trim() !== "" && !isNaN(Number(assertion.value)) ? Number(assertion.value) : undefined);
|
|
2269
|
+
const min = assertion.min;
|
|
2270
|
+
if (durationMs === undefined) {
|
|
2271
|
+
result.passed = false;
|
|
2272
|
+
result.actual = "no timing available";
|
|
2273
|
+
}
|
|
2274
|
+
else {
|
|
2275
|
+
result.actual = `${durationMs}ms`;
|
|
2276
|
+
result.passed =
|
|
2277
|
+
(min === undefined || durationMs >= min) &&
|
|
2278
|
+
(max === undefined || durationMs <= max);
|
|
2279
|
+
}
|
|
2280
|
+
return result;
|
|
2281
|
+
}
|
|
2282
|
+
if (assertion.that === "metric") {
|
|
2283
|
+
// Bound the latest recorded metric of this name — emitted (AXN_METRIC
|
|
2284
|
+
// line / ctx.emitMetric) or collected (<metric> block). Step-level
|
|
2285
|
+
// asserts run right after the step emitted, so the last record is
|
|
2286
|
+
// that step's; block asserts see the flow's latest record.
|
|
2287
|
+
const rec = ctx?.metrics?.filter((m) => m.name === assertion.name).pop();
|
|
2288
|
+
const max = assertion.max ?? (assertion.value.trim() !== "" && !isNaN(Number(assertion.value)) ? Number(assertion.value) : undefined);
|
|
2289
|
+
const min = assertion.min;
|
|
2290
|
+
if (!rec) {
|
|
2291
|
+
result.passed = false;
|
|
2292
|
+
result.actual = `metric '${assertion.name}' not recorded`;
|
|
2293
|
+
}
|
|
2294
|
+
else {
|
|
2295
|
+
result.actual = `${rec.value}${rec.unit ?? ""}`;
|
|
2296
|
+
result.passed =
|
|
2297
|
+
(min === undefined || rec.value >= min) &&
|
|
2298
|
+
(max === undefined || rec.value <= max);
|
|
2299
|
+
}
|
|
2300
|
+
return result;
|
|
2301
|
+
}
|
|
2302
|
+
if (assertion.that === "script") {
|
|
2303
|
+
const env = ctx?.env ?? this.expandEnvVars(process.env);
|
|
2304
|
+
const flowDir = ctx?.flowDir ?? process.cwd();
|
|
2305
|
+
const src = assertion.src ?? assertion.value;
|
|
2306
|
+
const r = await this.runTsScript(resolve(flowDir, src), { ...env, AXN_OUTPUT: response, AXN_ASSERT: JSON.stringify(assertion) }, flowDir);
|
|
2307
|
+
result.passed = r.exitCode === 0;
|
|
2308
|
+
result.actual = r.stdout.trim() || r.stderr.trim() || `exit ${r.exitCode}`;
|
|
2309
|
+
return result;
|
|
2310
|
+
}
|
|
2311
|
+
if (assertion.that === "contains") {
|
|
2312
|
+
const actual = response.toLowerCase();
|
|
2313
|
+
const expected = assertion.value.toLowerCase();
|
|
2314
|
+
result.passed = actual.includes(expected);
|
|
2315
|
+
if (!result.passed)
|
|
2316
|
+
result.actual = response;
|
|
2317
|
+
}
|
|
2318
|
+
else if (assertion.that === "num_responses") {
|
|
2319
|
+
const expected = parseInt(assertion.value, 10);
|
|
2320
|
+
const count = response.trim() ? 1 : 0;
|
|
2321
|
+
result.passed = count === expected;
|
|
2322
|
+
result.actual = String(count);
|
|
2323
|
+
}
|
|
2324
|
+
else if (assertion.that === "exitCode") {
|
|
2325
|
+
const expected = parseInt(assertion.value, 10);
|
|
2326
|
+
if (exitCode === undefined) {
|
|
2327
|
+
result.passed = false;
|
|
2328
|
+
result.actual = "undefined";
|
|
2329
|
+
}
|
|
2330
|
+
else {
|
|
2331
|
+
result.passed = exitCode === expected;
|
|
2332
|
+
result.actual = String(exitCode);
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
else {
|
|
2336
|
+
throw new Error(`Unknown assertion type: ${assertion.that}`);
|
|
2337
|
+
}
|
|
2338
|
+
return result;
|
|
2339
|
+
}
|
|
2340
|
+
printSummary(results) {
|
|
2341
|
+
console.log("\n== Flow Results ==\n");
|
|
2342
|
+
for (const r of results) {
|
|
2343
|
+
const status = r.passed ? "\x1b[32mPASS\x1b[0m" : "\x1b[31mFAIL\x1b[0m";
|
|
2344
|
+
const duration = r.durationMs !== undefined ? ` (${r.durationMs}ms)` : "";
|
|
2345
|
+
console.log(`${status} ${r.flow} :: ${r.model.provider}/${r.model.name}${duration}`);
|
|
2346
|
+
if (r.error)
|
|
2347
|
+
console.log(` error: ${r.error}`);
|
|
2348
|
+
for (const a of r.assertions) {
|
|
2349
|
+
const aStatus = a.passed ? "\x1b[32mPASS\x1b[0m" : "\x1b[31mFAIL\x1b[0m";
|
|
2350
|
+
const label = a.description ? `${a.description} — ` : "";
|
|
2351
|
+
console.log(` ${aStatus} ${label}${a.that}=${a.value}`);
|
|
2352
|
+
if (a.actual)
|
|
2353
|
+
console.log(` actual: ${a.actual}`);
|
|
2354
|
+
if (a.repeat) {
|
|
2355
|
+
for (const f of a.repeat.failures.slice(0, 10)) {
|
|
2356
|
+
console.log(` ${f}`);
|
|
2357
|
+
}
|
|
2358
|
+
if (a.repeat.failures.length > 10) {
|
|
2359
|
+
console.log(` … +${a.repeat.failures.length - 10} more failed runs`);
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
confirm(prompt) {
|
|
2366
|
+
return new Promise((resolve) => {
|
|
2367
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
2368
|
+
rl.question(prompt, (answer) => {
|
|
2369
|
+
rl.close();
|
|
2370
|
+
resolve(answer.trim().toLowerCase() === "y");
|
|
2371
|
+
});
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
class OrchestratorProcess {
|
|
2376
|
+
tsxBin;
|
|
2377
|
+
hostPath;
|
|
2378
|
+
child;
|
|
2379
|
+
nextId = 1;
|
|
2380
|
+
pending = new Map();
|
|
2381
|
+
constructor(tsxBin, hostPath) {
|
|
2382
|
+
this.tsxBin = tsxBin;
|
|
2383
|
+
this.hostPath = hostPath;
|
|
2384
|
+
}
|
|
2385
|
+
async start(orchestratorPath, env, cwd) {
|
|
2386
|
+
const fullEnv = {
|
|
2387
|
+
...env,
|
|
2388
|
+
AXN_FLOW_ORCHESTRATOR: orchestratorPath,
|
|
2389
|
+
};
|
|
2390
|
+
this.child = spawn(process.execPath, [this.tsxBin, this.hostPath], {
|
|
2391
|
+
env: fullEnv,
|
|
2392
|
+
cwd,
|
|
2393
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
2394
|
+
});
|
|
2395
|
+
const rl = createInterface({ input: this.child.stdout });
|
|
2396
|
+
rl.on("line", (line) => this.handleLine(line));
|
|
2397
|
+
this.child.stderr?.on("data", (data) => {
|
|
2398
|
+
process.stderr.write(String(data));
|
|
2399
|
+
});
|
|
2400
|
+
this.child.on("error", (err) => {
|
|
2401
|
+
for (const resolve of this.pending.values()) {
|
|
2402
|
+
resolve({ error: err.message });
|
|
2403
|
+
}
|
|
2404
|
+
this.pending.clear();
|
|
2405
|
+
});
|
|
2406
|
+
this.child.on("exit", (code, signal) => {
|
|
2407
|
+
for (const resolve of this.pending.values()) {
|
|
2408
|
+
resolve(Promise.reject(new Error(`Orchestrator exited (code=${code}, signal=${signal})`)));
|
|
2409
|
+
}
|
|
2410
|
+
this.pending.clear();
|
|
2411
|
+
});
|
|
2412
|
+
await this.send("start", {});
|
|
2413
|
+
}
|
|
2414
|
+
async run(steps) {
|
|
2415
|
+
return this.send("run", { steps });
|
|
2416
|
+
}
|
|
2417
|
+
async stop() {
|
|
2418
|
+
if (!this.child)
|
|
2419
|
+
return;
|
|
2420
|
+
try {
|
|
2421
|
+
await this.send("stop", {});
|
|
2422
|
+
}
|
|
2423
|
+
catch {
|
|
2424
|
+
/* best effort */
|
|
2425
|
+
}
|
|
2426
|
+
this.child.kill();
|
|
2427
|
+
}
|
|
2428
|
+
handleLine(line) {
|
|
2429
|
+
if (!line.startsWith("__AXN__")) {
|
|
2430
|
+
console.log(line);
|
|
2431
|
+
return;
|
|
2432
|
+
}
|
|
2433
|
+
const json = line.slice("__AXN__".length);
|
|
2434
|
+
let msg;
|
|
2435
|
+
try {
|
|
2436
|
+
msg = JSON.parse(json);
|
|
2437
|
+
}
|
|
2438
|
+
catch {
|
|
2439
|
+
return;
|
|
2440
|
+
}
|
|
2441
|
+
if (!msg || typeof msg.id !== "number")
|
|
2442
|
+
return;
|
|
2443
|
+
const resolve = this.pending.get(msg.id);
|
|
2444
|
+
if (!resolve)
|
|
2445
|
+
return;
|
|
2446
|
+
this.pending.delete(msg.id);
|
|
2447
|
+
if (msg.error) {
|
|
2448
|
+
resolve(Promise.reject(new Error(msg.error)));
|
|
2449
|
+
}
|
|
2450
|
+
else {
|
|
2451
|
+
resolve(msg);
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
async send(method, args) {
|
|
2455
|
+
if (!this.child || !this.child.stdin) {
|
|
2456
|
+
throw new Error("Orchestrator process is not running");
|
|
2457
|
+
}
|
|
2458
|
+
const id = this.nextId++;
|
|
2459
|
+
const request = { id, method, ...args };
|
|
2460
|
+
return new Promise((resolve) => {
|
|
2461
|
+
this.pending.set(id, resolve);
|
|
2462
|
+
this.child.stdin.write(JSON.stringify(request) + "\n");
|
|
2463
|
+
});
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
//# sourceMappingURL=flow.js.map
|