@qawolf/cli 2.7.0 → 2.8.1

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/dist/cli.js CHANGED
@@ -8404,6 +8404,7 @@ var agentMessages = {
8404
8404
  answerPrompt: "Your answer",
8405
8405
  conflictingSessionList: "Pass --sessions alone, without --session or a session argument.",
8406
8406
  emptySessionList: "Pass at least one session id with --sessions.",
8407
+ tooManySessions: (limit) => `Pass at most ${limit} session ids with --sessions.`,
8407
8408
  sessionListNeedsFollow: "Pass --follow when using --sessions.",
8408
8409
  answerSendFailed: (reason) => `The answer could not be sent: ${reason.replace(/\.$/, "")}. The session is still waiting, so try again.`,
8409
8410
  blocked: (sessionId) => `QA Wolf asked a question and cannot continue until it is answered. Answer it with qawolf agent send "<your answer>" --session ${sessionId}.`,
@@ -8586,6 +8587,18 @@ var authMessages = {
8586
8587
  errors: authErrorMessages,
8587
8588
  whoami: whoamiMessages
8588
8589
  };
8590
+ // src/core/messages/build.ts
8591
+ var withoutPeriod = (reason) => reason.replace(/\.$/, "");
8592
+ var buildMessages = {
8593
+ createFailed: (buildId, reason) => `The file is uploaded as build ${buildId}, but the build could not be created: ${withoutPeriod(reason)}. If the cause was temporary, finish it with qawolf build create --build-id ${buildId} and the same environment, branch, commit and workspace flags.`,
8594
+ fileUnreadable: (path) => `${path} is not a readable file.`,
8595
+ storageRefused: (status, reason) => `storage refused it (HTTP ${status}${reason === undefined ? "" : `: ${reason}`})`,
8596
+ storageTimedOut: (timeoutMs) => `it did not finish within ${formatSeconds(timeoutMs)}`,
8597
+ storageUnreachable: (cause) => `could not reach storage${cause === undefined ? "" : ` (${cause})`}`,
8598
+ uploaded: (build) => `Build ${build.id} (${build.appId}, ${build.platform}${build.version === undefined ? "" : ` ${build.version}`}) uploaded: ${build.url}`,
8599
+ uploadFailed: (buildId, reason) => `The upload of build ${buildId} failed: ${reason}. Run qawolf build upload again: it creates a new build.`,
8600
+ uploading: (fileName, sizeBytes) => `Uploading ${fileName} (${sizeBytes} bytes)`
8601
+ };
8589
8602
  // src/core/messages/toolNotFound.ts
8590
8603
  var installRemedy = "Run `qawolf install` to install the runtime dependencies.";
8591
8604
  function toolNotInstalled(tool, path) {
@@ -15315,6 +15328,24 @@ function flagKind(schema) {
15315
15328
  reason: `type ${schema.type ?? "unknown"} cannot be expressed as a flag`
15316
15329
  };
15317
15330
  }
15331
+ var isObjectSchema = (schema) => {
15332
+ const members = schema.allOf ?? schema.oneOf ?? schema.anyOf;
15333
+ if (members)
15334
+ return members.every(isObjectSchema);
15335
+ return schema.type === "object";
15336
+ };
15337
+ var isObjectList = (schema) => schema.type === "array" && !!schema.items && isObjectSchema(schema.items);
15338
+ var withoutNull = (schema) => {
15339
+ const members = schema.anyOf?.filter((member) => member.type !== "null");
15340
+ if (!members?.length || members.length === schema.anyOf?.length) {
15341
+ return schema;
15342
+ }
15343
+ return members.length === 1 && members[0] ? members[0] : { anyOf: members };
15344
+ };
15345
+ var holdsObjects = (schema) => {
15346
+ const value = withoutNull(schema);
15347
+ return isObjectSchema(value) || isObjectList(value);
15348
+ };
15318
15349
 
15319
15350
  // src/core/publicApi/objectShape.ts
15320
15351
  var asObjectShape = (schema) => schema.type === "object" && schema.properties ? { properties: schema.properties, required: new Set(schema.required) } : undefined;
@@ -15673,20 +15704,24 @@ async function requestWithRetry(args) {
15673
15704
  if (result.ok)
15674
15705
  return { ok: true, value: result.data };
15675
15706
  const backoff = args.backoffMs[attempt];
15676
- const retryable = result.error.kind === "network" || result.error.kind === "timeout";
15677
- if (backoff === undefined || !retryable) {
15707
+ const retryable = (args.retryable ?? isTransient)(result.error);
15708
+ if (backoff === undefined || !retryable || args.canRetry?.() === false) {
15678
15709
  const mayHaveArrived = result.error.kind !== "http";
15679
15710
  const unreachable = result.error.kind === "network" || result.error.kind === "timeout";
15680
15711
  return {
15681
15712
  ok: false,
15682
15713
  ...mayHaveArrived ? { mayHaveArrived } : {},
15683
15714
  ...unreachable ? { unreachable } : {},
15715
+ ...result.error.kind === "timeout" ? { timedOut: true } : {},
15684
15716
  ...args.describe(result.error)
15685
15717
  };
15686
15718
  }
15687
15719
  await sleep2(backoff);
15688
15720
  }
15689
15721
  }
15722
+ function isTransient(err) {
15723
+ return err.kind === "network" || err.kind === "timeout";
15724
+ }
15690
15725
 
15691
15726
  // src/shell/platform/callPublicApi.ts
15692
15727
  function callPublicApi(trpc, contract, input, options) {
@@ -15703,17 +15738,24 @@ var notSentCodes = new Set([
15703
15738
  "ENOTFOUND",
15704
15739
  "UND_ERR_CONNECT_TIMEOUT"
15705
15740
  ]);
15706
- function makeCallPublicApiMethod(trpc, deps, readBackoffMs) {
15741
+ function wasNeverSent(err) {
15742
+ if (err.kind !== "network")
15743
+ return false;
15744
+ const code = errorCode(err.cause.cause) ?? errorCode(err.cause);
15745
+ return code !== undefined && notSentCodes.has(code);
15746
+ }
15747
+ function makeCallPublicApiMethod(trpc, deps, backoffMs) {
15707
15748
  return async (contract, input, options) => {
15708
15749
  const sent = applyWorkspaceId(contract.input, input, deps.workspaceId);
15709
15750
  const subject = notFoundSubject(contract.name, sent);
15710
15751
  return requestWithRetry({
15711
15752
  call: () => callPublicApi(trpc, contract, sent, options),
15712
- backoffMs: contract.kind === "read" ? readBackoffMs : [],
15753
+ backoffMs,
15754
+ canRetry: () => options?.signal?.aborted !== true && options?.canRetry?.() !== false,
15755
+ ...contract.kind === "write" ? { retryable: wasNeverSent } : {},
15713
15756
  describe: (err) => {
15714
15757
  const failure = describeRequestError(err, deps.baseUrl, contract.name, subject);
15715
- const code = err.kind === "network" ? errorCode(err.cause.cause) ?? errorCode(err.cause) : undefined;
15716
- if (contract.kind !== "write" || !code || !notSentCodes.has(code))
15758
+ if (contract.kind !== "write" || !wasNeverSent(err))
15717
15759
  return failure;
15718
15760
  return {
15719
15761
  ...failure,
@@ -16528,7 +16570,7 @@ async function sendWireRequest(fetchFn, url, init, schema, timeoutMs) {
16528
16570
  try {
16529
16571
  response = await fetchFn(url, {
16530
16572
  ...init,
16531
- signal: AbortSignal.timeout(timeoutMs)
16573
+ signal: init.signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), init.signal]) : AbortSignal.timeout(timeoutMs)
16532
16574
  });
16533
16575
  } catch (error) {
16534
16576
  if (isTimeoutError(error)) {
@@ -16595,7 +16637,11 @@ function createTrpcClient(apiKey, deps) {
16595
16637
  query: (path, input, schema, options) => {
16596
16638
  const encoded = encodeURIComponent(JSON.stringify(dist_default.serialize(input)));
16597
16639
  const url = `${deps.baseUrl}/api/trpc/${path}?input=${encoded}`;
16598
- return withLogging(path, () => sendWireRequest(deps.fetch, url, { headers: authHeader, method: "GET" }, schema, options?.timeoutMs ?? defaultTimeoutMs));
16640
+ return withLogging(path, () => sendWireRequest(deps.fetch, url, {
16641
+ headers: authHeader,
16642
+ method: "GET",
16643
+ ...options?.signal ? { signal: options.signal } : {}
16644
+ }, schema, options?.timeoutMs ?? defaultTimeoutMs));
16599
16645
  },
16600
16646
  mutation: (path, input, schema, options) => {
16601
16647
  const url = `${deps.baseUrl}/api/trpc/${path}`;
@@ -16604,7 +16650,8 @@ function createTrpcClient(apiKey, deps) {
16604
16650
  body,
16605
16651
  headers: { ...authHeader, "content-type": "application/json" },
16606
16652
  method: "POST",
16607
- redirect: "error"
16653
+ redirect: "error",
16654
+ ...options?.signal ? { signal: options.signal } : {}
16608
16655
  }, schema, options?.timeoutMs ?? defaultTimeoutMs));
16609
16656
  }
16610
16657
  };
@@ -16958,7 +17005,6 @@ var makeActivityWaitContract = (ids) => {
16958
17005
  output
16959
17006
  };
16960
17007
  };
16961
-
16962
17008
  // node_modules/@qawolf/api-contracts/dist/v1/deployment/didNotRunReason.js
16963
17009
  var didNotRunReasonSchema = _enum([
16964
17010
  "billing-prevented",
@@ -17089,7 +17135,7 @@ var makeRequestFileUploadContract = (ids) => {
17089
17135
  const output = object({
17090
17136
  contentType: string2().describe("Send this as the PUT's `Content-Type` header, exactly. The URL is signed for it and refuses any other value."),
17091
17137
  expiresAt: exports_iso.datetime().describe("When uploadUrl stops working. Request another one after it."),
17092
- filePath: string2().describe("Where the file lives in team storage. Send it as filePath to file.requestDownload, or in agent.send's filePaths so the AI fetches it from there."),
17138
+ filePath: string2().describe("Where the file lives in team storage. Send it as filePath to file.requestDownload, in agent.send's filePaths so the AI fetches it from there, or as an image's source in an issue description."),
17093
17139
  path: string2().describe("Deprecated: the same value as filePath. Read filePath instead."),
17094
17140
  uploadUrl: string2().describe(`Send the file's bytes here with a single HTTP PUT carrying the returned contentType, for example \`curl -H 'Content-Type: application/octet-stream' --upload-file "journeys.csv" "<uploadUrl>"\`. Upload the bytes from the shell rather than through this API, so a large file never has to be written out as text.`)
17095
17141
  });
@@ -17182,6 +17228,11 @@ var defaultIdSchemas = {
17182
17228
  };
17183
17229
  var workspaceForEnvironmentRef = (workspace) => workspace.optional().describe("The workspace the environment belongs to, which an alias resolves in. Read it from whoami.");
17184
17230
 
17231
+ // node_modules/@qawolf/api-contracts/dist/v1/issue/description.js
17232
+ var maxInlineImageSizeBytes = 2000000;
17233
+ var maxInlineImagesPerDescription = 10;
17234
+ var issueDescriptionDescription = "The issue description in Markdown, which is stored as rich text. Text without Markdown is stored as written, one paragraph per line. " + "To show an image in the description, upload it with file.requestUpload, PUT its bytes with curl, then write `![what it shows](<filePath>)` where the image belongs, with the returned filePath between the angle brackets. " + `The image is stored in the description itself: a GIF, JPEG, PNG or WebP of at most ${maxInlineImageSizeBytes / 1e6} MB. ` + `A description shows at most ${maxInlineImagesPerDescription} such images, each outside any link. ` + "An image at an http(s) URL is stored as a link instead. " + "If an image's path has no file, is not one of those images, is too large or is inside a link, or there are too many images, nothing is written and the error says why.";
17235
+
17185
17236
  // node_modules/@qawolf/api-contracts/dist/v1/issue/files.js
17186
17237
  var maxAttachedFilesPerRequest = 10;
17187
17238
  var attachedFilePathsSchema = array(teamStoragePathSchema).min(1).max(maxAttachedFilesPerRequest).refine((filePaths) => new Set(filePaths).size === filePaths.length, "filePaths must be unique");
@@ -18642,6 +18693,7 @@ var makeAgentGetContract = (ids) => {
18642
18693
  // node_modules/@qawolf/api-contracts/dist/v1/agent/send.js
18643
18694
  var makeAgentSendContract = (ids) => {
18644
18695
  const input = object({
18696
+ builds: array(buildIdSchema).min(1).max(20).optional().describe("Builds this request is about, from build.create, at most one per app and platform. The runs of the session install them over the environment's builds of the same app and platform, and record them. Create them without an environment, so the environment's own runs keep their builds."),
18645
18697
  environmentId: ids.environmentRef.optional().describe("The environment to work in. Omit to use the team's default environment. Ignored when sessionId is given, because a session keeps the environment it opened in."),
18646
18698
  filePaths: array(teamStoragePathSchema).max(20).optional().describe("Paths of files this request is about, from file.requestUpload. The AI reads them from storage rather than the message, so a plan of hundreds of journeys costs nothing to send."),
18647
18699
  message: string2().trim().min(1).max(1e4).describe("What you want QA Wolf to do, in plain language. Name the journey, the part of the app it covers, and anything the AI cannot discover for itself, such as a test account, a feature flag, or how to reach a staging environment. When answering a question from agent.get, send the answer here."),
@@ -20396,7 +20448,7 @@ var makeCommentOnIssueContract = (ids) => {
20396
20448
  // node_modules/@qawolf/api-contracts/dist/v1/issue/create.js
20397
20449
  var makeCreateIssueContract = (ids) => {
20398
20450
  const commonFields = {
20399
- description: string2().optional().describe("The issue description in Markdown, which is stored as rich text. Text without Markdown is stored as written, one paragraph per line."),
20451
+ description: string2().optional().describe(issueDescriptionDescription),
20400
20452
  name: string2().trim().min(1).max(255),
20401
20453
  priority: issuePrioritySchema.optional().describe(`${issuePrioritySchema.description} Defaults to "unprioritized" for bug reports and coverage requests.`),
20402
20454
  workspaceId: ids.workspace.optional().describe("The workspace to create the issue in. Required when authenticating with an organization or user API key.")
@@ -20596,7 +20648,7 @@ var makeRemoveFlowsFromIssueContract = (ids) => {
20596
20648
 
20597
20649
  // node_modules/@qawolf/api-contracts/dist/v1/issue/update.js
20598
20650
  var makeUpdateIssueContract = (ids) => {
20599
- const descriptionSchema = string2().describe("The issue description in Markdown, which is stored as rich text. Text without Markdown is stored as written, one paragraph per line.");
20651
+ const descriptionSchema = string2().describe(issueDescriptionDescription);
20600
20652
  const nameSchema = string2().trim().min(1).max(255);
20601
20653
  const input = object({
20602
20654
  description: descriptionSchema.optional(),
@@ -21560,6 +21612,7 @@ var unchangedFilesSchema = record(string2(), string2().min(1)).superRefine((hash
21560
21612
  });
21561
21613
  var makeRunFlowOnRunnerContract = (ids) => {
21562
21614
  const input = object({
21615
+ builds: array(buildIdSchema).min(1).max(20).optional().describe("Builds to install in this run, at most one per app and platform. Each replaces the named environment's latest build of its app and platform. The run sees them in `QAWOLF_BUILDS`, which `launch({ app: { id } })` reads."),
21563
21616
  entryPointPath: runFilePathSchema.describe("Path of the flow file to run, as it appears in `files`."),
21564
21617
  env: runEnvironmentSchema.optional().describe("Environment variables to make available to the run. With `environmentId`, they are added on top of that environment's variables for this run only, replacing any of the same name; the environment itself is not changed."),
21565
21618
  environmentId: ids.environmentRef.optional().describe("A QA Wolf environment whose variables the run is given, by id or alias. QA Wolf reads and decrypts them itself, so they never travel in the request and the count and length limits on `env` do not apply to them. The run also gets `QAWOLF_ENVIRONMENT_ID`, `QAWOLF_ENVIRONMENT_NAME` and `QAWOLF_TEAM_API_KEY`, as a cloud run on that environment does, so a flow can save environment variables with `@qawolf/testkit`; `env` cannot replace these three."),
@@ -24390,7 +24443,7 @@ function startUpdateCheck(deps) {
24390
24443
  // package.json
24391
24444
  var package_default = {
24392
24445
  name: "@qawolf/cli",
24393
- version: "2.7.0",
24446
+ version: "2.8.1",
24394
24447
  description: "Run and manage QA Wolf flows from the terminal, CI, or an AI agent",
24395
24448
  keywords: [
24396
24449
  "automation",
@@ -24462,17 +24515,14 @@ var package_default = {
24462
24515
  "@clack/prompts": "1.5.1",
24463
24516
  "@napi-rs/keyring": "1.3.0",
24464
24517
  "@oxc-node/core": "0.1.0",
24465
- "@qawolf/api-contracts": "0.114.0",
24518
+ "@qawolf/api-contracts": "0.116.0",
24466
24519
  "@qawolf/emails": "1.1.1",
24467
24520
  "@qawolf/flow-targets": "2.0.0",
24468
- "@qawolf/flows": "0.3.0",
24469
- "@qawolf/testkit": "1.2.1",
24470
24521
  commander: "14.0.3",
24471
24522
  "env-paths": "4.0.0",
24472
24523
  jszip: "3.10.1",
24473
24524
  picomatch: "4.0.4",
24474
24525
  pino: "10.3.1",
24475
- playwright: "1.62.0",
24476
24526
  superjson: "2.2.6",
24477
24527
  tar: "7.5.21",
24478
24528
  tinyglobby: "0.2.17",
@@ -24481,6 +24531,8 @@ var package_default = {
24481
24531
  },
24482
24532
  devDependencies: {
24483
24533
  "@changesets/cli": "2.31.0",
24534
+ "@qawolf/flows": "0.3.0",
24535
+ "@qawolf/testkit": "1.2.1",
24484
24536
  "@tsconfig/bun": "1.0.10",
24485
24537
  "@tsconfig/strictest": "2.0.8",
24486
24538
  "@types/bun": "1.4.1",
@@ -24494,6 +24546,7 @@ var package_default = {
24494
24546
  oxfmt: "0.54.0",
24495
24547
  oxlint: "1.69.0",
24496
24548
  "oxlint-tsgolint": "0.23.0",
24549
+ playwright: "1.62.0",
24497
24550
  webdriverio: "9.27.1"
24498
24551
  },
24499
24552
  engines: {
@@ -24720,14 +24773,91 @@ async function handleQuestion(ctx, options) {
24720
24773
  return outcome;
24721
24774
  }
24722
24775
 
24776
+ // src/domains/agent/withinDeadline.ts
24777
+ var answerMarginMs = 15000;
24778
+ var readTimeoutMs = 15000;
24779
+ var retryBackoffMs = [500, 1500];
24780
+ var maxConsecutiveTimeouts = 3;
24781
+ function planAttempt(remainingMs, holds, signal) {
24782
+ const waitSeconds = holds ? Math.min(maxAgentWaitSeconds, Math.max(1, Math.ceil(remainingMs / 1000))) : 0;
24783
+ const timeoutMs = Math.min(holds ? waitSeconds * 1000 + answerMarginMs : readTimeoutMs, remainingMs);
24784
+ return {
24785
+ requestOptions: {
24786
+ canRetry: () => false,
24787
+ timeoutMs,
24788
+ ...signal ? { signal } : {}
24789
+ },
24790
+ waitSeconds
24791
+ };
24792
+ }
24793
+ async function callWithinDeadline(deadline, holds, send) {
24794
+ for (let retry = 0;; retry++) {
24795
+ const remainingMs = deadline.remainingMs();
24796
+ if (remainingMs <= 0)
24797
+ return { type: "deadline" };
24798
+ const result = await send(planAttempt(remainingMs, holds, deadline.signal));
24799
+ if (result.ok)
24800
+ return { type: "answered", value: result.value };
24801
+ if (deadline.remainingMs() <= 0)
24802
+ return { type: "deadline" };
24803
+ const backoffMs = retryBackoffMs[retry];
24804
+ const retryable = result.unreachable === true && !(holds && result.timedOut === true);
24805
+ if (backoffMs === undefined || !retryable || deadline.signal?.aborted)
24806
+ return { failure: result, type: "failed" };
24807
+ await deadline.sleep(Math.min(backoffMs, deadline.remainingMs()));
24808
+ if (deadline.signal?.aborted)
24809
+ return { failure: result, type: "failed" };
24810
+ }
24811
+ }
24812
+ function readWithinDeadline(deadline, send) {
24813
+ return callWithinDeadline(deadline, false, send);
24814
+ }
24815
+ async function holdWithinDeadline(deadline, send) {
24816
+ for (let timeouts = 1;; timeouts++) {
24817
+ const held = await callWithinDeadline(deadline, true, send);
24818
+ if (held.type !== "failed" || held.failure.timedOut !== true || timeouts >= maxConsecutiveTimeouts)
24819
+ return held;
24820
+ }
24821
+ }
24822
+ function endedBy(ended, timedOut) {
24823
+ if (ended.type === "deadline")
24824
+ return timedOut;
24825
+ return { exitCode: exitCodes.network, ...failureFields(ended.failure) };
24826
+ }
24827
+
24828
+ // src/domains/agent/hold.ts
24829
+ function readSession(ctx, deadline, sessionId) {
24830
+ return readWithinDeadline(deadline, (plan) => ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId, waitSeconds: 0 }, plan.requestOptions));
24831
+ }
24832
+ async function waitForActivity(ctx, deadline, options) {
24833
+ for (;; ) {
24834
+ const held = await holdWithinDeadline(deadline, (plan) => ctx.platformClient.callPublicApi(publicContractsV1.agent.get, {
24835
+ cursor: options.cursor,
24836
+ sessionId: options.sessionId,
24837
+ waitSeconds: plan.waitSeconds
24838
+ }, plan.requestOptions));
24839
+ if (held.type !== "answered")
24840
+ return held;
24841
+ if (held.value.wokeOn !== "timeout")
24842
+ return { type: "activity" };
24843
+ }
24844
+ }
24845
+
24723
24846
  // src/domains/agent/followSession.ts
24724
- var pollIntervalMs = 5000;
24725
24847
  async function followSession(ctx, options, deps) {
24726
24848
  const { sessionId, workspaceId } = options;
24727
24849
  const canPrompt = ctx.ui.mode === "human" && ctx.isInteractive;
24728
24850
  const startedAt = deps.now();
24729
24851
  let promptedMs = 0;
24730
- const timedOut = () => deps.now() - startedAt - promptedMs >= options.timeoutSeconds * 1000;
24852
+ const deadline = {
24853
+ remainingMs: () => options.timeoutSeconds * 1000 - (deps.now() - startedAt - promptedMs),
24854
+ signal: undefined,
24855
+ sleep: deps.sleep
24856
+ };
24857
+ const timedOut = () => ({
24858
+ error: agentMessages.followTimedOut(sessionId, options.timeoutSeconds),
24859
+ exitCode: exitCodes.timeout
24860
+ });
24731
24861
  let pending = options.initial;
24732
24862
  let printed = 0;
24733
24863
  let { repliesAtAnswer } = options;
@@ -24748,10 +24878,9 @@ async function followSession(ctx, options, deps) {
24748
24878
  session = pending;
24749
24879
  pending = undefined;
24750
24880
  } else {
24751
- const read = await ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId });
24752
- if (!read.ok) {
24753
- return { exitCode: exitCodes.network, ...failureFields(read) };
24754
- }
24881
+ const read = await readSession(ctx, deadline, sessionId);
24882
+ if (read.type !== "answered")
24883
+ return endedBy(read, timedOut());
24755
24884
  session = read.value;
24756
24885
  }
24757
24886
  const { replies, status } = session;
@@ -24794,13 +24923,12 @@ async function followSession(ctx, options, deps) {
24794
24923
  ctx.ui.info(agentMessages.detachHint);
24795
24924
  }
24796
24925
  waiting ??= ctx.ui.wait(agentMessages.waiting);
24797
- await deps.sleep(pollIntervalMs);
24798
- if (timedOut()) {
24799
- return {
24800
- error: agentMessages.followTimedOut(sessionId, options.timeoutSeconds),
24801
- exitCode: exitCodes.timeout
24802
- };
24803
- }
24926
+ const wake = await waitForActivity(ctx, deadline, {
24927
+ cursor: session.nextCursor,
24928
+ sessionId
24929
+ });
24930
+ if (wake.type !== "activity")
24931
+ return endedBy(wake, timedOut());
24804
24932
  }
24805
24933
  } finally {
24806
24934
  stopWaiting();
@@ -24809,9 +24937,16 @@ async function followSession(ctx, options, deps) {
24809
24937
  }
24810
24938
 
24811
24939
  // src/domains/agent/followSessions.ts
24940
+ var maxSessionsPerWait = 20;
24941
+ function splitIntoWaits(sessionIds) {
24942
+ return [
24943
+ ...Array(Math.ceil(sessionIds.length / maxSessionsPerWait)).keys()
24944
+ ].map((index) => sessionIds.slice(index * maxSessionsPerWait, (index + 1) * maxSessionsPerWait));
24945
+ }
24812
24946
  async function followSessions(options) {
24813
24947
  const { ctx, deps, sessionIds, timeoutSeconds } = options;
24814
- const deadline = deps.now() + timeoutSeconds * 1000;
24948
+ const deadlineAt = deps.now() + timeoutSeconds * 1000;
24949
+ const remainingMs = () => deadlineAt - deps.now();
24815
24950
  const timedOut = () => ({
24816
24951
  error: agentMessages.followSessionsTimedOut({
24817
24952
  seconds: timeoutSeconds,
@@ -24821,18 +24956,41 @@ async function followSessions(options) {
24821
24956
  });
24822
24957
  const waiting = ctx.ui.wait(agentMessages.waiting);
24823
24958
  const detach = ctx.signals.register(() => waiting.stop());
24959
+ const abort = new AbortController;
24960
+ const deadline = {
24961
+ remainingMs,
24962
+ signal: abort.signal,
24963
+ sleep: deps.sleep
24964
+ };
24965
+ const waits = splitIntoWaits(sessionIds);
24966
+ const cursorsByWait = new Map;
24967
+ const holdWait = (index, waitSessionIds) => holdWithinDeadline(deadline, (plan) => ctx.platformClient.callPublicApi(publicContractsV1.activity.wait, {
24968
+ cursors: cursorsByWait.get(index) ?? {},
24969
+ sessionIds: waitSessionIds,
24970
+ waitSeconds: plan.waitSeconds
24971
+ }, plan.requestOptions)).then((held) => ({ held, index }));
24972
+ const holds = new Map;
24824
24973
  try {
24825
24974
  for (;; ) {
24826
- for (const sessionId of sessionIds) {
24827
- const remainingMs = deadline - deps.now();
24828
- if (remainingMs <= 0)
24829
- return timedOut();
24830
- const read = await ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId, waitSeconds: 0 }, { timeoutMs: Math.min(15000, remainingMs) });
24831
- if (!read.ok) {
24832
- if (deps.now() >= deadline)
24833
- return timedOut();
24834
- return { exitCode: exitCodes.network, ...failureFields(read) };
24835
- }
24975
+ if (remainingMs() <= 0)
24976
+ return timedOut();
24977
+ waits.forEach((waitSessionIds, index) => {
24978
+ if (!holds.has(index))
24979
+ holds.set(index, holdWait(index, waitSessionIds));
24980
+ });
24981
+ const { held, index } = await Promise.race(holds.values());
24982
+ holds.delete(index);
24983
+ if (held.type !== "answered")
24984
+ return endedBy(held, timedOut());
24985
+ cursorsByWait.set(index, Object.fromEntries(held.value.sessions.map((watched) => [
24986
+ watched.sessionId,
24987
+ watched.nextCursor
24988
+ ])));
24989
+ const stirred = held.value.sessions.filter((watched) => watched.status !== "working");
24990
+ for (const { sessionId } of stirred) {
24991
+ const read = await readSession(ctx, deadline, sessionId);
24992
+ if (read.type !== "answered")
24993
+ return endedBy(read, timedOut());
24836
24994
  const session = read.value;
24837
24995
  const question = pendingQuestion(session.status, session.replies);
24838
24996
  if (!isSettled(session.status) && question === undefined)
@@ -24861,12 +25019,9 @@ async function followSessions(options) {
24861
25019
  return result.result;
24862
25020
  }
24863
25021
  }
24864
- const remainingMs = deadline - deps.now();
24865
- if (remainingMs <= 0)
24866
- return timedOut();
24867
- await deps.sleep(Math.min(5000, remainingMs));
24868
25022
  }
24869
25023
  } finally {
25024
+ abort.abort();
24870
25025
  waiting.stop();
24871
25026
  detach();
24872
25027
  }
@@ -24934,10 +25089,16 @@ async function handleAgentGet(ctx, options, deps) {
24934
25089
  error: agentMessages.emptySessionList,
24935
25090
  exitCode: exitCodes.invalidArgs
24936
25091
  };
25092
+ const sessionIds = [...new Set(options.sessions)];
25093
+ if (sessionIds.length > maxActivityWaitItems)
25094
+ return {
25095
+ error: agentMessages.tooManySessions(maxActivityWaitItems),
25096
+ exitCode: exitCodes.invalidArgs
25097
+ };
24937
25098
  return followSessions({
24938
25099
  ctx,
24939
25100
  deps,
24940
- sessionIds: [...new Set(options.sessions)],
25101
+ sessionIds,
24941
25102
  timeoutSeconds: timeout.seconds
24942
25103
  });
24943
25104
  }
@@ -24952,7 +25113,7 @@ async function handleAgentGet(ctx, options, deps) {
24952
25113
  if (sessionId === undefined) {
24953
25114
  return { error: agentMessages.noSession, exitCode: exitCodes.invalidArgs };
24954
25115
  }
24955
- const read = await ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId });
25116
+ const read = await ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId, waitSeconds: 0 });
24956
25117
  if (!read.ok)
24957
25118
  return { exitCode: exitCodes.network, ...failureFields(read) };
24958
25119
  if (!options.follow) {
@@ -25088,6 +25249,7 @@ var chatSessionIdEnvironmentVariable = "QAWOLF_CHAT_SESSION_ID";
25088
25249
  function parseInput(options) {
25089
25250
  return publicContractsV1.agent.send.input.safeParse({
25090
25251
  message: options.message,
25252
+ ...options.builds === undefined ? {} : { builds: options.builds },
25091
25253
  ...options.environmentId === undefined ? {} : { environmentId: options.environmentId },
25092
25254
  ...options.filePaths === undefined ? {} : { filePaths: options.filePaths },
25093
25255
  ...options.parentSessionId === undefined ? {} : { parentSessionId: options.parentSessionId },
@@ -25120,7 +25282,7 @@ async function handleAgentSend(ctx, options, deps) {
25120
25282
  }
25121
25283
  let repliesAtAnswer;
25122
25284
  if (options.follow && options.session !== undefined) {
25123
- const before = await ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId: options.session });
25285
+ const before = await ctx.platformClient.callPublicApi(publicContractsV1.agent.get, { sessionId: options.session, waitSeconds: 0 });
25124
25286
  if (before.ok)
25125
25287
  repliesAtAnswer = before.value.replies.length;
25126
25288
  }
@@ -25149,9 +25311,11 @@ Examples:
25149
25311
  $ qawolf agent send "cover the checkout journey" --follow
25150
25312
  $ qawolf agent send "use the staging login test@example.com" --session <id>
25151
25313
  $ qawolf agent send "cover signup" --environment-id staging --follow
25152
- $ qawolf agent send "cover every journey in the sheet" --file-paths uploads/journeys.csv --follow`;
25314
+ $ qawolf agent send "cover every journey in the sheet" --file-paths uploads/journeys.csv --follow
25315
+ $ qawolf agent send "test the new admin build" --builds <buildId>`;
25153
25316
  function registerAgentSendCommand(agent, signals) {
25154
- declareCommandKind(agent.command("send <message>"), "write").description("Ask the QA Wolf AI to do a piece of work, such as covering a journey or fixing a broken flow").option("--follow", "Stay and report what QA Wolf says until the session settles, answering its questions as they come", false).option("--session <id>", "Continue this session instead of opening a new one. Send an answer, or add context to work already running").addOption(new Option2("--environment-id <env>", "QA Wolf environment to work in, by id or alias. Ignored with --session, because a session keeps the environment it opened in").env(environmentIdEnvironmentVariable)).option("--workspace-id <id>", "The workspace to work in. Required when authenticating with an organization or user API key").option("--file-paths <path...>", "Team-storage paths of files this request is about, from qawolf file requestUpload. The AI reads them from storage rather than the message, so a plan of hundreds of journeys costs nothing to send. Up to 20").option("--timeout <seconds>", timeoutFlagDescription, String(defaultAgentFollowTimeoutSeconds)).addHelpText("after", sendExamples).action((message, opts, command) => withAuthContext(signals, (ctx) => handleAgentSend(ctx, {
25317
+ declareCommandKind(agent.command("send <message>"), "write").description("Ask the QA Wolf AI to do a piece of work, such as covering a journey or fixing a broken flow").option("--follow", "Stay and report what QA Wolf says until the session settles, answering its questions as they come", false).option("--session <id>", "Continue this session instead of opening a new one. Send an answer, or add context to work already running").addOption(new Option2("--environment-id <env>", "QA Wolf environment to work in, by id or alias. Ignored with --session, because a session keeps the environment it opened in").env(environmentIdEnvironmentVariable)).option("--workspace-id <id>", "The workspace to work in. Required when authenticating with an organization or user API key").option("--file-paths <path...>", "Team-storage paths of files this request is about, from qawolf file requestUpload. The AI reads them from storage rather than the message, so a plan of hundreds of journeys costs nothing to send. Up to 20").option("--builds <ids...>", "Builds this request is about, from qawolf build create, one per app and platform. The session's runs install them over the environment's builds of the same app and platform. Put the message before this flag").option("--timeout <seconds>", timeoutFlagDescription, String(defaultAgentFollowTimeoutSeconds)).addHelpText("after", sendExamples).action((message, opts, command) => withAuthContext(signals, (ctx) => handleAgentSend(ctx, {
25318
+ builds: opts.builds,
25155
25319
  environmentId: opts.environmentId,
25156
25320
  filePaths: opts.filePaths,
25157
25321
  follow: opts.follow,
@@ -26399,6 +26563,192 @@ function registerAuthCommand(program, signals) {
26399
26563
  });
26400
26564
  }
26401
26565
 
26566
+ // src/domains/build/uploadFileName.ts
26567
+ import { basename } from "node:path";
26568
+ var maxLength = 255;
26569
+ function uploadFileName(filePath) {
26570
+ const safe = basename(filePath).replaceAll(/[^A-Za-z0-9._-]+/g, "-");
26571
+ if (safe.length <= maxLength)
26572
+ return safe;
26573
+ const extension = safe.slice(safe.lastIndexOf("."));
26574
+ return safe.slice(0, maxLength - extension.length) + extension;
26575
+ }
26576
+
26577
+ // src/domains/build/uploadInput.ts
26578
+ var definedOnly = (fields) => Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
26579
+ function environmentSelector(options) {
26580
+ const environment = definedOnly({
26581
+ baseEphemeralEnvironment: options.environmentBaseEphemeralEnvironment,
26582
+ ephemeral: options.environmentEphemeral,
26583
+ id: options.environmentId,
26584
+ name: options.environmentName
26585
+ });
26586
+ return Object.keys(environment).length === 0 ? {} : { environment };
26587
+ }
26588
+ var storageReasonMaxLength = 200;
26589
+ function storageReason(body) {
26590
+ const code = /<Code>([^<]+)<\/Code>/.exec(body)?.[1];
26591
+ const message = /<Message>([^<]+)<\/Message>/.exec(body)?.[1];
26592
+ const reason = code === undefined ? body.replace(/\s+/g, " ").trim() : [code, message].filter((part) => part !== undefined).join(": ");
26593
+ if (reason.length === 0)
26594
+ return;
26595
+ return reason.length > storageReasonMaxLength ? `${reason.slice(0, storageReasonMaxLength)}…` : reason;
26596
+ }
26597
+ function describePutFailure(error) {
26598
+ if (error.kind === "http")
26599
+ return buildMessages.storageRefused(error.status, storageReason(error.body));
26600
+ if (error.kind === "timeout")
26601
+ return buildMessages.storageTimedOut(error.timeoutMs);
26602
+ return buildMessages.storageUnreachable(error.kind === "network" ? describeFetchCause(error.cause) : undefined);
26603
+ }
26604
+ var idForFlagCheck = "000000000000000000000000obld";
26605
+ function parseCreateFlags(options) {
26606
+ const parsed = publicContractsV1.build.create.input.safeParse({
26607
+ ...definedOnly({
26608
+ branch: options.branch,
26609
+ commitSha: options.commitSha,
26610
+ workspaceId: options.workspaceId
26611
+ }),
26612
+ ...environmentSelector(options),
26613
+ buildId: idForFlagCheck
26614
+ });
26615
+ if (!parsed.success)
26616
+ return { ok: false, error: parsed.error };
26617
+ const { buildId: _idForFlagCheck, ...flags } = parsed.data;
26618
+ return { ok: true, value: flags };
26619
+ }
26620
+ var requestUploadFields = (options) => definedOnly(options);
26621
+
26622
+ // src/domains/build/upload.ts
26623
+ var platformFailure = (failure) => ({
26624
+ ...failure.unreachable === true ? { exitCode: exitCodes.network } : {},
26625
+ ...failureFields(failure)
26626
+ });
26627
+ var invalid = (error) => ({
26628
+ error: prettifyError(error),
26629
+ exitCode: exitCodes.invalidArgs
26630
+ });
26631
+ async function handleBuildUpload(ctx, options, deps) {
26632
+ const flags = parseCreateFlags(options);
26633
+ if (!flags.ok)
26634
+ return invalid(flags.error);
26635
+ const file = await deps.openFile(options.filePath);
26636
+ if (file === undefined) {
26637
+ return {
26638
+ error: buildMessages.fileUnreadable(options.filePath),
26639
+ exitCode: exitCodes.invalidArgs
26640
+ };
26641
+ }
26642
+ const fileName = uploadFileName(options.filePath);
26643
+ const requestInput = publicContractsV1.build.requestUpload.input.safeParse(requestUploadFields({
26644
+ fileName,
26645
+ fileSizeBytes: file.size,
26646
+ workspaceId: options.workspaceId
26647
+ }));
26648
+ if (!requestInput.success)
26649
+ return invalid(requestInput.error);
26650
+ const requested = await ctx.platformClient.callPublicApi(publicContractsV1.build.requestUpload, requestInput.data);
26651
+ if (!requested.ok)
26652
+ return platformFailure(requested);
26653
+ const { buildId, uploadHeaders, uploadUrl } = requested.value;
26654
+ const waiting = ctx.ui.wait(buildMessages.uploading(fileName, file.size));
26655
+ const uploaded = await deps.putFile({
26656
+ body: file,
26657
+ headers: uploadHeaders,
26658
+ url: uploadUrl
26659
+ });
26660
+ waiting.stop();
26661
+ if (!uploaded.ok) {
26662
+ return {
26663
+ error: buildMessages.uploadFailed(buildId, describePutFailure(uploaded.error)),
26664
+ exitCode: exitCodes.network
26665
+ };
26666
+ }
26667
+ const created = await ctx.platformClient.callPublicApi(publicContractsV1.build.create, { ...flags.value, buildId });
26668
+ if (!created.ok) {
26669
+ return {
26670
+ ...platformFailure(created),
26671
+ error: buildMessages.createFailed(buildId, created.error)
26672
+ };
26673
+ }
26674
+ const { build } = created.value;
26675
+ ctx.ui.output(build, buildMessages.uploaded(build));
26676
+ return;
26677
+ }
26678
+
26679
+ // src/shell/platform/putSignedUrl.ts
26680
+ import { constants, openAsBlob } from "node:fs";
26681
+ import { access } from "node:fs/promises";
26682
+ var defaultUploadTimeoutMs = 30 * 60 * 1000;
26683
+ async function openFileAsBlob(fs, path) {
26684
+ try {
26685
+ const stats = await fs.stat(path);
26686
+ if (!stats.isFile())
26687
+ return;
26688
+ await access(path, constants.R_OK);
26689
+ return await openAsBlob(path);
26690
+ } catch {
26691
+ return;
26692
+ }
26693
+ }
26694
+ async function putSignedUrl(args, deps = { fetch: globalThis.fetch }) {
26695
+ const timeoutMs = deps.timeoutMs ?? defaultUploadTimeoutMs;
26696
+ let response;
26697
+ try {
26698
+ response = await deps.fetch(args.url, {
26699
+ body: args.body,
26700
+ headers: args.headers,
26701
+ method: "PUT",
26702
+ signal: AbortSignal.timeout(timeoutMs)
26703
+ });
26704
+ } catch (error) {
26705
+ if (isTimeoutError(error)) {
26706
+ return { ok: false, error: { kind: "timeout", timeoutMs } };
26707
+ }
26708
+ return { ok: false, error: { cause: toError(error), kind: "network" } };
26709
+ }
26710
+ if (!response.ok) {
26711
+ const body = await response.text().catch(() => "");
26712
+ return {
26713
+ ok: false,
26714
+ error: { body, kind: "http", status: response.status }
26715
+ };
26716
+ }
26717
+ return { ok: true, data: undefined };
26718
+ }
26719
+
26720
+ // src/commands/build/upload.register.ts
26721
+ var uploadExamples = `
26722
+ Examples:
26723
+ $ qawolf build upload app-release.apk
26724
+ $ qawolf build upload App.ipa --environment-id <id>
26725
+ $ qawolf build upload app-release.aab --environment-name pr-42 --environment-ephemeral --environment-base-ephemeral-environment staging --branch feat/login --commit-sha 1a2b3c4
26726
+
26727
+ Without an environment flag, the build belongs to no environment: only a run
26728
+ created with it installs it.`;
26729
+ var toUploadOptions = (filePath, opts) => ({
26730
+ branch: opts.branch,
26731
+ commitSha: opts.commitSha,
26732
+ environmentBaseEphemeralEnvironment: opts.environmentBaseEphemeralEnvironment,
26733
+ environmentEphemeral: opts.environmentEphemeral,
26734
+ environmentId: opts.environmentId,
26735
+ environmentName: opts.environmentName,
26736
+ filePath,
26737
+ workspaceId: opts.workspaceId
26738
+ });
26739
+ function registerBuildUploadCommand(build, signals) {
26740
+ declareCommandKind(build.command("upload <file>"), "write").description("Upload an app file (.apk, .aab or .ipa, up to 500 MB) and create a build from it. Runs build requestUpload, the PUT and build create in one step").option("--environment-id <id>", "Put the build on this existing environment: its runs install it from now on, until a newer build of the same app and platform arrives").option("--environment-name <name>", "Put the build on the environment with this alias or name, and create the environment when none matches").option("--environment-ephemeral", "With --environment-name, create an ephemeral environment when the name creates one, such as a pull request's").option("--environment-base-ephemeral-environment <name>", "With --environment-ephemeral, the alias or name of the environment a created ephemeral environment copies from").option("--branch <branch>", "The branch the build came from").option("--commit-sha <sha>", "The commit the build came from").option("--workspace-id <id>", "The workspace to upload into. Required when authenticating with an organization or user API key").addHelpText("after", uploadExamples).action((filePath, opts, command) => withAuthContext(signals, (ctx) => handleBuildUpload(ctx, toUploadOptions(filePath, opts), {
26741
+ openFile: (path) => openFileAsBlob(ctx.fs, path),
26742
+ putFile: (args) => putSignedUrl(args)
26743
+ }))(opts, command));
26744
+ }
26745
+
26746
+ // src/commands/build/index.ts
26747
+ function registerBuildCommand(program, signals) {
26748
+ const build = program.command("build").description("Upload app builds and manage the builds runs install");
26749
+ registerBuildUploadCommand(build, signals);
26750
+ }
26751
+
26402
26752
  // node_modules/@qawolf/flow-targets/dist/presets/android/androidPixel2Android14.js
26403
26753
  var androidPixel2Android14Target = {
26404
26754
  meta: {
@@ -28467,7 +28817,7 @@ import { fileURLToPath } from "url";
28467
28817
 
28468
28818
  // node_modules/fdir/dist/index.mjs
28469
28819
  import { createRequire as createRequire2 } from "module";
28470
- import { basename, dirname as dirname5, normalize as normalize2, relative as relative2, resolve, sep as sep3 } from "path";
28820
+ import { basename as basename2, dirname as dirname5, normalize as normalize2, relative as relative2, resolve, sep as sep3 } from "path";
28471
28821
  import * as nativeFs from "fs";
28472
28822
  var __require2 = /* @__PURE__ */ createRequire2(import.meta.url);
28473
28823
  function cleanPath(path) {
@@ -28834,7 +29184,7 @@ var Walker = class {
28834
29184
  this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk);
28835
29185
  } else {
28836
29186
  resolvedPath = useRealPaths ? resolvedPath : path;
28837
- const filename = basename(resolvedPath);
29187
+ const filename = basename2(resolvedPath);
28838
29188
  const directoryPath$1 = normalizePath(dirname5(resolvedPath), this.state.options);
28839
29189
  resolvedPath = this.joinPath(filename, directoryPath$1);
28840
29190
  this.pushFile(resolvedPath, files, this.state.counts, filters);
@@ -29287,7 +29637,7 @@ async function glob(globInput, options) {
29287
29637
  }
29288
29638
 
29289
29639
  // src/core/flowMeta.ts
29290
- import { basename as basename2 } from "node:path";
29640
+ import { basename as basename3 } from "node:path";
29291
29641
 
29292
29642
  // src/core/stringLiteral.ts
29293
29643
  var lineTerminator = /[\n\r\u2028\u2029]/;
@@ -29392,7 +29742,7 @@ function parseFlowCall(source) {
29392
29742
 
29393
29743
  // src/core/flowMeta.ts
29394
29744
  function flowBasename(file) {
29395
- return basename2(file).replace(/\.flow\.(ts|js)$/, "");
29745
+ return basename3(file).replace(/\.flow\.(ts|js)$/, "");
29396
29746
  }
29397
29747
  var browserNameToPlaywright = {
29398
29748
  chrome: "chromium",
@@ -30068,13 +30418,13 @@ function matchesSelectors(flow, selectors) {
30068
30418
  }
30069
30419
 
30070
30420
  // src/core/repoRelativePath.ts
30071
- import { basename as basename3, dirname as dirname6, relative as relative3 } from "node:path";
30421
+ import { basename as basename4, dirname as dirname6, relative as relative3 } from "node:path";
30072
30422
  var toPosix = (path) => path.replaceAll("\\", "/");
30073
30423
  function findPulledEnvDir(flowAbsPath) {
30074
30424
  let current = dirname6(flowAbsPath);
30075
30425
  while (current !== dirname6(current)) {
30076
30426
  const parent = dirname6(current);
30077
- if (basename3(parent) === ".qawolf")
30427
+ if (basename4(parent) === ".qawolf")
30078
30428
  return current;
30079
30429
  current = parent;
30080
30430
  }
@@ -30337,12 +30687,12 @@ async function readCachedTags(files, fs = makeDefaultFs()) {
30337
30687
  }
30338
30688
 
30339
30689
  // src/domains/flows/readEnvLabel.ts
30340
- import { basename as basename4 } from "node:path";
30690
+ import { basename as basename5 } from "node:path";
30341
30691
  async function readEnvLabel(envDir, fs = makeDefaultFs()) {
30342
30692
  const manifest = await readManifest(envDir, fs);
30343
30693
  if (typeof manifest === "string")
30344
- return basename4(envDir);
30345
- return manifest.envSlug ?? manifest.envName ?? basename4(envDir);
30694
+ return basename5(envDir);
30695
+ return manifest.envSlug ?? manifest.envName ?? basename5(envDir);
30346
30696
  }
30347
30697
 
30348
30698
  // src/domains/flows/listDefaults.ts
@@ -34246,7 +34596,7 @@ async function carriedTags(envDir, fs) {
34246
34596
  // src/domains/flows/pull/handler.ts
34247
34597
  async function handleFlowsPull(ctx, opts, deps) {
34248
34598
  const resolvedDeps = deps ?? {
34249
- flowsVersion: package_default.dependencies["@qawolf/flows"],
34599
+ flowsVersion,
34250
34600
  fs: ctx.fs
34251
34601
  };
34252
34602
  const validation = validateEnvId(opts.env);
@@ -35607,16 +35957,16 @@ async function listStagedSourceFiles(options) {
35607
35957
 
35608
35958
  // src/domains/runtimeEnv/stageFlowFiles.ts
35609
35959
  import { createHash as createHash3 } from "node:crypto";
35610
- import { basename as basename6, dirname as dirname12, join as join40, sep as sep4 } from "node:path";
35960
+ import { basename as basename7, dirname as dirname12, join as join40, sep as sep4 } from "node:path";
35611
35961
 
35612
35962
  // src/shell/copyDir.ts
35613
35963
  import { cp, readdir as readdir2 } from "node:fs/promises";
35614
- import { basename as basename5, join as join39 } from "node:path";
35964
+ import { basename as basename6, join as join39 } from "node:path";
35615
35965
  async function copyDirExcluding(source, destination, excludedNames) {
35616
35966
  const entries = await readdir2(source, { withFileTypes: true });
35617
35967
  await Promise.all(entries.filter((entry) => !excludedNames.has(entry.name)).map((entry) => cp(join39(source, entry.name), join39(destination, entry.name), {
35618
35968
  recursive: true,
35619
- filter: (path) => !excludedNames.has(basename5(path))
35969
+ filter: (path) => !excludedNames.has(basename6(path))
35620
35970
  })));
35621
35971
  }
35622
35972
 
@@ -35631,14 +35981,14 @@ async function stageFlowFiles(args) {
35631
35981
  if (files.length > 1) {
35632
35982
  return Promise.all(files.map((f) => stageOneFile(f, execDir, fs)));
35633
35983
  }
35634
- await Promise.all(files.map((f) => fs.copyFile(f, join40(execDir, basename6(f)))));
35635
- return files.map((f) => join40(execDir, basename6(f)));
35984
+ await Promise.all(files.map((f) => fs.copyFile(f, join40(execDir, basename7(f)))));
35985
+ return files.map((f) => join40(execDir, basename7(f)));
35636
35986
  }
35637
35987
  async function stageOneFile(file, execDir, fs) {
35638
35988
  const dirHash = createHash3("sha256").update(dirname12(file)).digest("hex").slice(0, 8);
35639
35989
  const subDir = join40(execDir, dirHash);
35640
35990
  await fs.mkdir(subDir, { recursive: true });
35641
- const dest = join40(subDir, basename6(file));
35991
+ const dest = join40(subDir, basename7(file));
35642
35992
  await fs.copyFile(file, dest);
35643
35993
  return dest;
35644
35994
  }
@@ -36024,7 +36374,7 @@ var defaultAdb = async (args) => {
36024
36374
 
36025
36375
  // src/shell/appium/createAndroidEmulator.ts
36026
36376
  var defaultBootTimeoutMs = 120000;
36027
- var pollIntervalMs2 = 2000;
36377
+ var pollIntervalMs = 2000;
36028
36378
  var defaultSpawnEmulator = (bin, args) => {
36029
36379
  const child = spawn3(bin, args, { stdio: "ignore" });
36030
36380
  child.unref();
@@ -36042,7 +36392,7 @@ async function bootSequence(adb, serial, cancelled) {
36042
36392
  ]).catch(() => ({ stdout: "" }));
36043
36393
  if (stdout.trim() === "1")
36044
36394
  return;
36045
- await new Promise((r) => setTimeout(r, pollIntervalMs2));
36395
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
36046
36396
  }
36047
36397
  }
36048
36398
  function waitForBoot(adb, serial, timeoutMs) {
@@ -37191,14 +37541,14 @@ async function runWebFlow({
37191
37541
 
37192
37542
  // src/shell/embeddedWorkerCli.ts
37193
37543
  import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
37194
- import { basename as basename7, join as join44 } from "node:path";
37544
+ import { basename as basename8, join as join44 } from "node:path";
37195
37545
  var embeddedCliPathEnv = "QAWOLF_EMBEDDED_CLI_PATH";
37196
37546
  function extractEmbeddedWorkerCli() {
37197
37547
  const assetPath = process.env[embeddedCliPathEnv];
37198
37548
  if (assetPath === undefined || assetPath === "")
37199
37549
  return;
37200
37550
  const dir = join44(getDataDir(), "worker");
37201
- const dest = join44(dir, basename7(assetPath));
37551
+ const dest = join44(dir, basename8(assetPath));
37202
37552
  if (existsSync3(dest))
37203
37553
  return dest;
37204
37554
  mkdirSync3(dir, { recursive: true });
@@ -38605,7 +38955,7 @@ Examples:
38605
38955
  }
38606
38956
 
38607
38957
  // src/domains/investigation/handle.ts
38608
- import { basename as basename8 } from "node:path";
38958
+ import { basename as basename9 } from "node:path";
38609
38959
 
38610
38960
  // src/domains/investigation/download.ts
38611
38961
  var traceLimit = 75 * 1024 * 1024;
@@ -38923,7 +39273,7 @@ async function outputInvestigationInspection(ctx, options, parsed) {
38923
39273
  };
38924
39274
  const output = { ...result, outputFile: options.outputFile };
38925
39275
  ctx.ui.output(output, `${renderText(result)}
38926
- Saved ${binary.extension}: ${basename8(options.outputFile)}`);
39276
+ Saved ${binary.extension}: ${basename9(options.outputFile)}`);
38927
39277
  return;
38928
39278
  }
38929
39279
  if (binary?.extension === "html") {
@@ -38985,6 +39335,19 @@ function registerAttemptCommand(program, signals) {
38985
39335
  });
38986
39336
  }
38987
39337
 
39338
+ // src/core/publicApi/flagDescription.ts
39339
+ var jsonSources = "Takes JSON inline, @<path> to read it from a file, or - to read it from stdin.";
39340
+ var joinSentences = (sentences) => sentences.filter((sentence) => sentence !== "").join(" ");
39341
+ function describeFlag(schema, kind) {
39342
+ const description = schema.description ?? "";
39343
+ if (kind === "json")
39344
+ return joinSentences([description, jsonSources]);
39345
+ const values = schema.enum ?? schema.items?.enum;
39346
+ if (!values?.length)
39347
+ return description;
39348
+ return joinSentences([description, `One of: ${values.join(", ")}`]);
39349
+ }
39350
+
38988
39351
  // src/core/publicApi/flagNames.ts
38989
39352
  var kebabCase = (segment) => segment.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
38990
39353
  var capitalize = (segment) => `${segment.slice(0, 1).toUpperCase()}${segment.slice(1)}`;
@@ -39000,18 +39363,12 @@ function flagUsage(path, kind) {
39000
39363
  return `${name} <values...>`;
39001
39364
  if (kind === "key-value-record")
39002
39365
  return `${name} <KEY=VALUE...>`;
39366
+ if (kind === "json")
39367
+ return `${name} <json>`;
39003
39368
  return `${name} <value>`;
39004
39369
  }
39005
39370
 
39006
39371
  // src/core/publicApi/flagSpecs.ts
39007
- function describeFlag(schema) {
39008
- const description = schema.description ?? "";
39009
- const values = schema.enum ?? schema.items?.enum;
39010
- if (!values?.length)
39011
- return description;
39012
- const choices = `One of: ${values.join(", ")}`;
39013
- return description ? `${description} ${choices}` : choices;
39014
- }
39015
39372
  function walkableShape(schema) {
39016
39373
  const isCombinator = Boolean(schema.allOf ?? schema.oneOf ?? schema.anyOf);
39017
39374
  if (!schema.properties && !isCombinator)
@@ -39019,31 +39376,38 @@ function walkableShape(schema) {
39019
39376
  const result = toObjectShape(schema);
39020
39377
  return result.ok ? result.shape : undefined;
39021
39378
  }
39379
+ function fieldFlags(fieldSchema, fieldPath, required) {
39380
+ const nested = walkableShape(fieldSchema);
39381
+ if (nested)
39382
+ return collectFlags(nested, fieldPath, required);
39383
+ const kind = flagKind(fieldSchema);
39384
+ if (!kind.ok)
39385
+ return { ok: false, field: fieldPath.join("."), reason: kind.reason };
39386
+ return {
39387
+ ok: true,
39388
+ flags: [leafFlag(fieldSchema, fieldPath, required, kind.kind)]
39389
+ };
39390
+ }
39391
+ function leafFlag(fieldSchema, fieldPath, required, kind) {
39392
+ return {
39393
+ path: fieldPath,
39394
+ optionKey: optionKeyOf(fieldPath),
39395
+ flag: flagUsage(fieldPath, kind),
39396
+ description: describeFlag(fieldSchema, kind),
39397
+ required,
39398
+ kind
39399
+ };
39400
+ }
39022
39401
  function collectFlags(shape, path, parentRequired) {
39023
39402
  const flags = [];
39024
39403
  for (const [field, fieldSchema] of Object.entries(shape.properties)) {
39025
39404
  const fieldPath = [...path, field];
39026
39405
  const required = parentRequired && shape.required.has(field);
39027
- const nested = walkableShape(fieldSchema);
39028
- if (nested) {
39029
- const result = collectFlags(nested, fieldPath, required);
39030
- if (!result.ok)
39031
- return result;
39032
- flags.push(...result.flags);
39033
- continue;
39034
- }
39035
- const kind = flagKind(fieldSchema);
39036
- if (!kind.ok) {
39037
- return { ok: false, field: fieldPath.join("."), reason: kind.reason };
39038
- }
39039
- flags.push({
39040
- path: fieldPath,
39041
- optionKey: optionKeyOf(fieldPath),
39042
- flag: flagUsage(fieldPath, kind.kind),
39043
- description: describeFlag(fieldSchema),
39044
- required,
39045
- kind: kind.kind
39046
- });
39406
+ const result = fieldFlags(fieldSchema, fieldPath, required);
39407
+ const json = path.length === 0 && holdsObjects(fieldSchema);
39408
+ if (!result.ok && !json)
39409
+ return result;
39410
+ flags.push(...result.ok ? result.flags : [leafFlag(fieldSchema, fieldPath, required, "json")]);
39047
39411
  }
39048
39412
  return { ok: true, flags };
39049
39413
  }
@@ -39111,7 +39475,17 @@ function buildCommandSpecs(tree, options = {}) {
39111
39475
  return walk(tree, []);
39112
39476
  }
39113
39477
 
39114
- // src/domains/publicApi/handle.ts
39478
+ // src/shell/stdin.ts
39479
+ async function readStdin2() {
39480
+ if (process.stdin.isTTY === true)
39481
+ return "";
39482
+ const chunks = [];
39483
+ for await (const chunk of process.stdin)
39484
+ chunks.push(chunk);
39485
+ return Buffer.concat(chunks).toString("utf8");
39486
+ }
39487
+
39488
+ // src/domains/publicApi/flagValues.ts
39115
39489
  var flagName = (flag) => flag.flag.split(" ", 1)[0] ?? flag.flag;
39116
39490
  var isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
39117
39491
  function parseKeyValueRecord(flag, pairs) {
@@ -39128,6 +39502,75 @@ function parseKeyValueRecord(flag, pairs) {
39128
39502
  }
39129
39503
  return { ok: true, record };
39130
39504
  }
39505
+ function parseJson2(flag, value) {
39506
+ if (typeof value !== "string") {
39507
+ return {
39508
+ ok: false,
39509
+ error: `Invalid ${flagName(flag)} value: expected a JSON value.`
39510
+ };
39511
+ }
39512
+ try {
39513
+ return { ok: true, value: JSON.parse(value) };
39514
+ } catch {
39515
+ return {
39516
+ ok: false,
39517
+ error: `Invalid ${flagName(flag)} value: expected a JSON value.`
39518
+ };
39519
+ }
39520
+ }
39521
+
39522
+ // src/domains/publicApi/jsonFlagSources.ts
39523
+ var stdinSource = "-";
39524
+ var fileSourcePrefix = "@";
39525
+ async function readFileSource(flag, path, deps) {
39526
+ try {
39527
+ return { ok: true, text: await deps.readFile(path) };
39528
+ } catch (error) {
39529
+ const reason = isNoEntError(error) ? "does not exist" : `could not be read (${errorMessage(error)})`;
39530
+ return {
39531
+ ok: false,
39532
+ error: `Invalid ${flagName(flag)} value: file "${path}" ${reason}.`
39533
+ };
39534
+ }
39535
+ }
39536
+ async function readSource(flag, value, deps) {
39537
+ if (value.startsWith(fileSourcePrefix)) {
39538
+ return readFileSource(flag, value.slice(fileSourcePrefix.length), deps);
39539
+ }
39540
+ if (value !== stdinSource)
39541
+ return { ok: true, text: value };
39542
+ const text = await deps.readStdin();
39543
+ if (text.trim() === "") {
39544
+ return {
39545
+ ok: false,
39546
+ error: `Invalid ${flagName(flag)} value: nothing was piped to stdin.`
39547
+ };
39548
+ }
39549
+ return { ok: true, text };
39550
+ }
39551
+ async function readJsonFlagSources(flags, options, deps) {
39552
+ const jsonFlags = flags.filter((flag) => flag.kind === "json");
39553
+ const stdinFlags = jsonFlags.filter((flag) => options[flag.optionKey] === stdinSource);
39554
+ if (stdinFlags.length > 1) {
39555
+ return {
39556
+ ok: false,
39557
+ error: `Only one flag can read stdin, but ${stdinFlags.map(flagName).join(" and ")} are each set to -.`
39558
+ };
39559
+ }
39560
+ const resolved = { ...options };
39561
+ for (const flag of jsonFlags) {
39562
+ const value = options[flag.optionKey];
39563
+ if (typeof value !== "string")
39564
+ continue;
39565
+ const read = await readSource(flag, value, deps);
39566
+ if (!read.ok)
39567
+ return read;
39568
+ resolved[flag.optionKey] = read.text;
39569
+ }
39570
+ return { ok: true, options: resolved };
39571
+ }
39572
+
39573
+ // src/domains/publicApi/handle.ts
39131
39574
  var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39132
39575
  function setAtPath(input, path, value) {
39133
39576
  const leaf = path[path.length - 1];
@@ -39158,6 +39601,11 @@ function assembleInput(flags, options) {
39158
39601
  if (!parsed.ok)
39159
39602
  return parsed;
39160
39603
  setAtPath(input, flag.path, parsed.record);
39604
+ } else if (flag.kind === "json") {
39605
+ const parsed = parseJson2(flag, value);
39606
+ if (!parsed.ok)
39607
+ return parsed;
39608
+ setAtPath(input, flag.path, parsed.value);
39161
39609
  } else if (flag.kind === "number") {
39162
39610
  setAtPath(input, flag.path, Number(value));
39163
39611
  } else {
@@ -39173,8 +39621,14 @@ function renderHuman(value) {
39173
39621
  }
39174
39622
  return JSON.stringify(value);
39175
39623
  }
39176
- async function handlePublicApiCommand(ctx, spec, options) {
39177
- const assembled = assembleInput(spec.flags, options);
39624
+ async function handlePublicApiCommand(ctx, spec, options, stdin = { readStdin: readStdin2 }) {
39625
+ const sourced = await readJsonFlagSources(spec.flags, options, {
39626
+ readFile: (path) => ctx.fs.readFile(path),
39627
+ readStdin: stdin.readStdin
39628
+ });
39629
+ if (!sourced.ok)
39630
+ return { error: sourced.error };
39631
+ const assembled = assembleInput(spec.flags, sourced.options);
39178
39632
  if (!assembled.ok)
39179
39633
  return { error: assembled.error };
39180
39634
  const parsed = spec.contract.input.safeParse(assembled.input);
@@ -40094,16 +40548,6 @@ function makeRunnerStore(options) {
40094
40548
  };
40095
40549
  }
40096
40550
 
40097
- // src/shell/stdin.ts
40098
- async function readStdin2() {
40099
- if (process.stdin.isTTY === true)
40100
- return "";
40101
- const chunks = [];
40102
- for await (const chunk of process.stdin)
40103
- chunks.push(chunk);
40104
- return Buffer.concat(chunks).toString("utf8");
40105
- }
40106
-
40107
40551
  // src/domains/interactiveRunner/deps.ts
40108
40552
  function makeInteractiveRunnerDeps(options) {
40109
40553
  return {
@@ -41756,6 +42200,27 @@ function parseEventsOptions(options) {
41756
42200
  };
41757
42201
  }
41758
42202
 
42203
+ // src/domains/interactiveRunner/followPace.ts
42204
+ var firstDelayMs = 1000;
42205
+ var longestDelayMs = 5000;
42206
+ function createFollowPace(options) {
42207
+ let idleReads = 0;
42208
+ let waitedMs = 0;
42209
+ return {
42210
+ wait: async (sawEntries) => {
42211
+ idleReads = sawEntries ? 0 : idleReads + 1;
42212
+ const remainingMs = options.timeoutMs - waitedMs;
42213
+ if (remainingMs <= 0)
42214
+ return "timed-out";
42215
+ const delayMs = Math.min(longestDelayMs, firstDelayMs * (idleReads + 1), remainingMs);
42216
+ await options.sleep(delayMs);
42217
+ waitedMs += delayMs;
42218
+ return "waited";
42219
+ },
42220
+ waitedMs: () => waitedMs
42221
+ };
42222
+ }
42223
+
41759
42224
  // src/domains/interactiveRunner/journalCursor.ts
41760
42225
  function createJournalCursor(ctx, runner, request) {
41761
42226
  let sinceSequence = request.sinceSequence;
@@ -41797,19 +42262,20 @@ function createPrintingCursor(ctx, runner, request, format) {
41797
42262
  };
41798
42263
  }
41799
42264
  var unreachableGraceMs = 60000;
41800
- function createUnreachableBudget(pollIntervalMs) {
41801
- const limit = Math.ceil(unreachableGraceMs / pollIntervalMs);
41802
- let consecutive = 0;
42265
+ function createUnreachableBudget() {
42266
+ let outageStartedAtMs;
41803
42267
  return {
41804
- exhausted: () => ++consecutive >= limit,
42268
+ exhausted: (waitedMs) => {
42269
+ outageStartedAtMs ??= waitedMs;
42270
+ return waitedMs - outageStartedAtMs >= unreachableGraceMs;
42271
+ },
41805
42272
  reset: () => {
41806
- consecutive = 0;
42273
+ outageStartedAtMs = undefined;
41807
42274
  }
41808
42275
  };
41809
42276
  }
41810
42277
 
41811
42278
  // src/domains/interactiveRunner/events.ts
41812
- var pollIntervalMs3 = 1000;
41813
42279
  async function handleRunnerEvents(ctx, options, deps) {
41814
42280
  const parsed = parseEventsOptions(options);
41815
42281
  if (!parsed.ok)
@@ -41827,14 +42293,17 @@ async function handleRunnerEvents(ctx, options, deps) {
41827
42293
  ctx.ui.warn(interactiveRunnerMessages.unknownStream(parsed.value.stream, known));
41828
42294
  }
41829
42295
  const read = createJournalCursor(ctx, resolved, parsed.value);
41830
- const unreachable = createUnreachableBudget(pollIntervalMs3);
41831
- const maxPolls = Math.max(1, Math.ceil(timeout.seconds * 1000 / pollIntervalMs3));
41832
- for (let poll = 1;; poll++) {
42296
+ const unreachable = createUnreachableBudget();
42297
+ const pace = createFollowPace({
42298
+ sleep: deps.sleep,
42299
+ timeoutMs: timeout.seconds * 1000
42300
+ });
42301
+ for (;; ) {
41833
42302
  const window = await read();
41834
42303
  if (window.type === "failed")
41835
42304
  return journalReadFailure(window);
41836
42305
  if (window.type === "unreachable") {
41837
- if (!options.follow || unreachable.exhausted()) {
42306
+ if (!options.follow || unreachable.exhausted(pace.waitedMs())) {
41838
42307
  return { ...unreachableFailure };
41839
42308
  }
41840
42309
  } else {
@@ -41848,13 +42317,13 @@ async function handleRunnerEvents(ctx, options, deps) {
41848
42317
  if (!options.follow)
41849
42318
  return;
41850
42319
  }
41851
- if (poll >= maxPolls) {
42320
+ const sawEntries = window.type === "entries" && window.entries.length > 0;
42321
+ if (await pace.wait(sawEntries) === "timed-out") {
41852
42322
  return {
41853
42323
  error: interactiveRunnerMessages.followEventsTimedOut(parsed.value.stream, timeout.seconds),
41854
42324
  exitCode: exitCodes.timeout
41855
42325
  };
41856
42326
  }
41857
- await deps.sleep(pollIntervalMs3);
41858
42327
  }
41859
42328
  }
41860
42329
 
@@ -41885,8 +42354,8 @@ async function resolveRecorderAnchor(ctx, resolved, deps) {
41885
42354
  return anchorRecorderCursor(ctx, resolved, deps);
41886
42355
  }
41887
42356
  async function anchorRecorderCursor(ctx, runner, deps) {
41888
- const unreachable = createUnreachableBudget(anchorPollIntervalMs);
41889
- for (;; ) {
42357
+ const unreachable = createUnreachableBudget();
42358
+ for (let waitedMs = 0;; waitedMs += anchorPollIntervalMs) {
41890
42359
  const anchor = await readJournal(ctx, runner, {
41891
42360
  stream: "recorder",
41892
42361
  tail: 1
@@ -41897,7 +42366,7 @@ async function anchorRecorderCursor(ctx, runner, deps) {
41897
42366
  if (anchor.type === "failed") {
41898
42367
  return { failure: journalReadFailure(anchor), ok: false };
41899
42368
  }
41900
- if (unreachable.exhausted()) {
42369
+ if (unreachable.exhausted(waitedMs)) {
41901
42370
  return { failure: { ...unreachableFailure }, ok: false };
41902
42371
  }
41903
42372
  await deps.sleep(anchorPollIntervalMs);
@@ -41917,9 +42386,18 @@ function createFollowPrinters(ctx, options) {
41917
42386
  }
41918
42387
  return printers;
41919
42388
  }
42389
+ async function printEach(printers) {
42390
+ let sawEntries = false;
42391
+ for (const print of printers) {
42392
+ const window = await print();
42393
+ if (window.type !== "entries")
42394
+ return { interrupted: window, sawEntries };
42395
+ sawEntries ||= window.entries.length > 0;
42396
+ }
42397
+ return { interrupted: undefined, sawEntries };
42398
+ }
41920
42399
 
41921
42400
  // src/domains/interactiveRunner/followRun.ts
41922
- var pollIntervalMs4 = 1000;
41923
42401
  function reportSettlement2(ctx, settlement) {
41924
42402
  if (settlement.type === "passed") {
41925
42403
  ctx.ui.success(interactiveRunnerMessages.runPassed);
@@ -41936,15 +42414,11 @@ async function followRun(ctx, options, deps) {
41936
42414
  runId: options.runId,
41937
42415
  stream: "run-status"
41938
42416
  });
41939
- const unreachable = createUnreachableBudget(pollIntervalMs4);
41940
- const printAll = async () => {
41941
- for (const print of printers) {
41942
- const window = await print();
41943
- if (window.type !== "entries")
41944
- return window;
41945
- }
41946
- return;
41947
- };
42417
+ const unreachable = createUnreachableBudget();
42418
+ const pace = createFollowPace({
42419
+ sleep: deps.sleep,
42420
+ timeoutMs: options.timeoutSeconds * 1000
42421
+ });
41948
42422
  let progressReported = false;
41949
42423
  const printProgress = (entries) => {
41950
42424
  if (printers.length > 0 || progressReported)
@@ -41955,35 +42429,36 @@ async function followRun(ctx, options, deps) {
41955
42429
  progressReported = true;
41956
42430
  ctx.ui.stream(entry, interactiveRunnerMessages.runInProgress);
41957
42431
  };
41958
- const maxPolls = Math.max(1, Math.ceil(options.timeoutSeconds * 1000 / pollIntervalMs4));
41959
- for (let poll = 1;; poll++) {
41960
- const interrupted = await printAll();
42432
+ for (;; ) {
42433
+ const printed = await printEach(printers);
42434
+ const { interrupted } = printed;
41961
42435
  if (interrupted?.type === "failed")
41962
42436
  return journalReadFailure(interrupted);
41963
42437
  const status = interrupted?.type === "unreachable" ? interrupted : await readStatus();
41964
42438
  if (status.type === "failed")
41965
42439
  return journalReadFailure(status);
41966
42440
  if (status.type === "unreachable") {
41967
- if (unreachable.exhausted())
42441
+ if (unreachable.exhausted(pace.waitedMs())) {
41968
42442
  return { ...unreachableFailure };
42443
+ }
41969
42444
  } else {
41970
42445
  unreachable.reset();
41971
42446
  printProgress(status.entries);
41972
42447
  const settlement = findSettlement(status.entries);
41973
42448
  if (settlement !== undefined) {
41974
- if (await printAll() !== undefined) {
42449
+ if ((await printEach(printers)).interrupted !== undefined) {
41975
42450
  ctx.ui.warn(interactiveRunnerMessages.followEndCutShort);
41976
42451
  }
41977
42452
  return reportSettlement2(ctx, settlement);
41978
42453
  }
41979
42454
  }
41980
- if (poll >= maxPolls) {
42455
+ const sawEntries = printed.sawEntries || status.type === "entries" && status.entries.length > 0;
42456
+ if (await pace.wait(sawEntries) === "timed-out") {
41981
42457
  return {
41982
42458
  error: interactiveRunnerMessages.followTimedOut(options.runId, options.runner.runnerId, options.timeoutSeconds),
41983
42459
  exitCode: exitCodes.timeout
41984
42460
  };
41985
42461
  }
41986
- await deps.sleep(pollIntervalMs4);
41987
42462
  }
41988
42463
  }
41989
42464
 
@@ -42012,6 +42487,17 @@ function buildRunSelection(options) {
42012
42487
  return { ok: true, selection: parsed.data };
42013
42488
  }
42014
42489
 
42490
+ // src/core/interactiveRunner/runBuilds.ts
42491
+ function parseRunBuilds(values) {
42492
+ if (values.length === 0)
42493
+ return { builds: undefined, ok: true };
42494
+ const checked = publicContractsV1.runner.runFlow.input.shape.builds.safeParse(values);
42495
+ if (!checked.success) {
42496
+ return { error: prettifyError(checked.error), ok: false };
42497
+ }
42498
+ return { builds: checked.data, ok: true };
42499
+ }
42500
+
42015
42501
  // src/core/interactiveRunner/runEnvironment.ts
42016
42502
  function buildRunEnvironment(content) {
42017
42503
  let parsed;
@@ -42087,6 +42573,9 @@ async function prepareRun(options, deps) {
42087
42573
  const fromVars = parseRunVariables(options.vars);
42088
42574
  if (!fromVars.ok)
42089
42575
  return refused(fromVars.error, exitCodes.invalidArgs);
42576
+ const builds = parseRunBuilds(options.builds);
42577
+ if (!builds.ok)
42578
+ return refused(builds.error, exitCodes.invalidArgs);
42090
42579
  const fromEnvVar = deps.env["QAWOLF_ENVIRONMENT"]?.trim();
42091
42580
  const environmentId = explicitEnvId ?? (options.envFile === undefined && fromEnvVar ? fromEnvVar : undefined);
42092
42581
  const linesFilePath = options.linesFile === undefined ? undefined : toCollectedPath(deps.cwd, options.linesFile);
@@ -42110,28 +42599,22 @@ async function prepareRun(options, deps) {
42110
42599
  if (combined !== undefined && !combined.ok) {
42111
42600
  return refused(combined.error, exitCodes.invalidArgs);
42112
42601
  }
42113
- const given = combined?.environment;
42602
+ const ready = {
42603
+ builds: builds.builds,
42604
+ environment: combined?.environment,
42605
+ environmentId,
42606
+ files,
42607
+ ok: true
42608
+ };
42114
42609
  if (options.lines === undefined) {
42115
- return options.linesFile === undefined ? {
42116
- environment: given,
42117
- environmentId,
42118
- files,
42119
- ok: true,
42120
- selection: undefined
42121
- } : refused(interactiveRunnerMessages.linesFileWithoutLines, exitCodes.invalidArgs);
42610
+ return options.linesFile === undefined ? { ...ready, selection: undefined } : refused(interactiveRunnerMessages.linesFileWithoutLines, exitCodes.invalidArgs);
42122
42611
  }
42123
42612
  const path = linesFilePath ?? options.entryPointPath;
42124
42613
  if (!Object.hasOwn(files, path)) {
42125
42614
  return refused(interactiveRunnerMessages.fileNotCollected(path), exitCodes.invalidArgs);
42126
42615
  }
42127
42616
  const built = buildRunSelection({ lines: options.lines, path });
42128
- return built.ok ? {
42129
- environment: given,
42130
- environmentId,
42131
- files,
42132
- ok: true,
42133
- selection: built.selection
42134
- } : refused(built.error, exitCodes.invalidArgs);
42617
+ return built.ok ? { ...ready, selection: built.selection } : refused(built.error, exitCodes.invalidArgs);
42135
42618
  }
42136
42619
  async function readEnvironment(envFile, deps) {
42137
42620
  if (envFile === undefined)
@@ -42208,6 +42691,7 @@ function describeRunSubmitFailure(failure) {
42208
42691
  // src/domains/interactiveRunner/sendRunFlowRequest.ts
42209
42692
  async function sendRunFlowRequest(ctx, options, delta) {
42210
42693
  const result = await ctx.platformClient.callPublicApi(publicContractsV1.runner.runFlow, {
42694
+ ...options.builds === undefined ? {} : { builds: options.builds },
42211
42695
  entryPointPath: options.entryPointPath,
42212
42696
  files: delta.files,
42213
42697
  id: options.resolved.runnerId,
@@ -42301,6 +42785,7 @@ async function handleRunnerRun(ctx, options, deps) {
42301
42785
  }
42302
42786
  const entryPointPath = toCollectedPath(deps.cwd, options.entryPoint);
42303
42787
  const prepared = await prepareRun({
42788
+ builds: options.builds,
42304
42789
  entryPointPath,
42305
42790
  envFile: options.envFile,
42306
42791
  envId: options.envId,
@@ -42327,6 +42812,7 @@ async function handleRunnerRun(ctx, options, deps) {
42327
42812
  recorderSinceSequence = anchor.sinceSequence;
42328
42813
  }
42329
42814
  const submitted = await submitRun(ctx, {
42815
+ builds: prepared.builds,
42330
42816
  entryPointPath,
42331
42817
  environment: prepared.environment,
42332
42818
  environmentId: prepared.environmentId,
@@ -42370,9 +42856,11 @@ Examples:
42370
42856
  $ qawolf runner run flows/checkout.flow.ts --lines 12-40
42371
42857
  $ qawolf runner run flows/checkout.flow.ts --lines 4-9 --lines-file pages/login.ts
42372
42858
  $ qawolf runner run flows/checkout.flow.ts --env-id staging
42373
- $ qawolf runner run flows/checkout.flow.ts --env-var RUN_INPUT_PATH=uploads/app.apk`;
42859
+ $ qawolf runner run flows/checkout.flow.ts --env-var RUN_INPUT_PATH=uploads/app.apk
42860
+ $ qawolf runner run flows/checkout.flow.ts --builds <buildId> <buildId>`;
42374
42861
  function registerRunCommand(runner, signals) {
42375
- declareCommandKind(runner.command("run <flowFile>"), "write").description("Run a flow on an interactive runner, shipping the flow and what it imports").option("--follow", "Report the run's status until it settles: in progress, then passed or failed", false).option("--logs", "Stream every log line the run produces while following. Implies --follow", false).option("--run-events", "Stream the run's progress events as JSON lines while following. Implies --follow", false).option("--recorder-events", "Stream the browser actions the runner records as JSON lines while following, from an anchor taken just before submission: the recorder is runner-wide, not run-scoped. Implies --follow", false).option("--env-id <env>", "QA Wolf environment whose variables the run is given, by id or alias. Defaults to QAWOLF_ENVIRONMENT unless --env-file is passed. QA Wolf reads and decrypts them itself, so they never leave the server and no size limit applies to them").option("--env-file <path>", "Dotenv file on this machine whose variables the run is given. With --env-id, they go on top of that environment's").option("--var, --env-var <name=value>", "One variable for this run only, on top of the environment and --env-file; repeat for several", collectValue, []).option("--lines <start-end>", "Run only these 1-indexed lines against the browser as it stands, instead of the whole flow from a fresh one").option("--lines-file <path>", "File the --lines range lives in. Defaults to <flowFile>; pass it only when the lines are in another file, such as a page object").option("--runner <id>", runnerFlagDescription).option("--timeout <seconds>", "Give up following after this long. Following keeps the runner alive, so a run that never settles would otherwise bill until the terminal closed", String(defaultFollowTimeoutSeconds)).addHelpText("after", runExamples2).addHelpText("after", runnerGuides.run).action((flowFile, opts, command) => withRunnerContext(signals, (ctx) => handleRunnerRun(ctx, {
42862
+ declareCommandKind(runner.command("run <flowFile>"), "write").description("Run a flow on an interactive runner, shipping the flow and what it imports").option("--follow", "Report the run's status until it settles: in progress, then passed or failed", false).option("--logs", "Stream every log line the run produces while following. Implies --follow", false).option("--run-events", "Stream the run's progress events as JSON lines while following. Implies --follow", false).option("--recorder-events", "Stream the browser actions the runner records as JSON lines while following, from an anchor taken just before submission: the recorder is runner-wide, not run-scoped. Implies --follow", false).option("--env-id <env>", "QA Wolf environment whose variables the run is given, by id or alias. Defaults to QAWOLF_ENVIRONMENT unless --env-file is passed. QA Wolf reads and decrypts them itself, so they never leave the server and no size limit applies to them").option("--env-file <path>", "Dotenv file on this machine whose variables the run is given. With --env-id, they go on top of that environment's").option("--var, --env-var <name=value>", "One variable for this run only, on top of the environment and --env-file; repeat for several", collectValue, []).option("--builds <ids...>", "Builds to install in this run, from build.create, one per app and platform. Each replaces the environment's latest build of its app and platform. Put the flow file before this flag", []).option("--lines <start-end>", "Run only these 1-indexed lines against the browser as it stands, instead of the whole flow from a fresh one").option("--lines-file <path>", "File the --lines range lives in. Defaults to <flowFile>; pass it only when the lines are in another file, such as a page object").option("--runner <id>", runnerFlagDescription).option("--timeout <seconds>", "Give up following after this long. Following keeps the runner alive, so a run that never settles would otherwise bill until the terminal closed", String(defaultFollowTimeoutSeconds)).addHelpText("after", runExamples2).addHelpText("after", runnerGuides.run).action((flowFile, opts, command) => withRunnerContext(signals, (ctx) => handleRunnerRun(ctx, {
42863
+ builds: opts.builds,
42376
42864
  entryPoint: flowFile,
42377
42865
  envFile: opts.envFile,
42378
42866
  envId: opts.envId,
@@ -42615,6 +43103,7 @@ function createProgram({
42615
43103
  });
42616
43104
  registerAgentCommand(program, signals);
42617
43105
  registerAuthCommand(program, signals);
43106
+ registerBuildCommand(program, signals);
42618
43107
  registerDoctorCommand(program, signals);
42619
43108
  registerFlowsCommand(program, signals);
42620
43109
  registerInitCommand(program, signals);
@@ -42636,4 +43125,4 @@ createProgram({ signals }).parseAsync().catch(() => {
42636
43125
  process.exitCode = 1;
42637
43126
  }).finally(() => exitWhenIdle(typeof process.exitCode === "number" ? process.exitCode : 0));
42638
43127
 
42639
- //# debugId=4123DE9F7A00111E64756E2164756E21
43128
+ //# debugId=CAB39E5AAA5540DA64756E2164756E21