@devicecloud.dev/dcd 5.14.1 → 5.16.0-beta.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.
Files changed (44) hide show
  1. package/README.md +25 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/device.d.ts +39 -0
  5. package/dist/commands/device.js +479 -101
  6. package/dist/e2e/index.d.ts +4 -0
  7. package/dist/e2e/index.js +41 -0
  8. package/dist/e2e/provider.d.ts +80 -0
  9. package/dist/e2e/provider.js +233 -0
  10. package/dist/gateways/api-gateway.d.ts +25 -3
  11. package/dist/gateways/api-gateway.js +68 -6
  12. package/dist/gateways/device-gateway.d.ts +34 -10
  13. package/dist/gateways/device-gateway.js +72 -17
  14. package/dist/mcp/bridge.d.ts +30 -16
  15. package/dist/mcp/bridge.js +201 -64
  16. package/dist/mcp/local-files.d.ts +14 -0
  17. package/dist/mcp/local-files.js +75 -0
  18. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  19. package/dist/mcp/tools/download-artifacts.js +44 -17
  20. package/dist/services/report-download.service.d.ts +32 -0
  21. package/dist/services/report-download.service.js +51 -2
  22. package/dist/services/telemetry.service.d.ts +20 -1
  23. package/dist/services/telemetry.service.js +27 -6
  24. package/dist/types/domain/device-session.types.d.ts +73 -3
  25. package/dist/types/domain/device-session.types.js +2 -0
  26. package/dist/utils/api-url.d.ts +20 -0
  27. package/dist/utils/api-url.js +49 -0
  28. package/dist/utils/app-upload.d.ts +6 -0
  29. package/dist/utils/app-upload.js +19 -0
  30. package/dist/utils/config-store.d.ts +5 -1
  31. package/dist/utils/config-store.js +18 -2
  32. package/dist/utils/device-artifacts.d.ts +5 -0
  33. package/dist/utils/device-artifacts.js +22 -0
  34. package/dist/utils/device-bundle.d.ts +39 -9
  35. package/dist/utils/device-bundle.js +153 -51
  36. package/dist/utils/device-flags.d.ts +17 -0
  37. package/dist/utils/device-flags.js +145 -0
  38. package/dist/utils/device-output.d.ts +53 -7
  39. package/dist/utils/device-output.js +148 -21
  40. package/dist/utils/device-run.d.ts +8 -3
  41. package/dist/utils/device-run.js +85 -8
  42. package/dist/utils/zip-integrity.d.ts +21 -0
  43. package/dist/utils/zip-integrity.js +45 -0
  44. package/package.json +10 -1
@@ -5,15 +5,16 @@ import { resolve as resolvePath } from 'node:path';
5
5
  import { apiFlags } from '../config/flags/api.flags.js';
6
6
  import { jsonFlag } from '../config/flags/output.flags.js';
7
7
  import { DeviceApiError, DeviceGateway, START_RECOVERY_WINDOW_MS, startOutcomeUnknown, } from '../gateways/device-gateway.js';
8
- import { DEVICE_KEYS, ENDED_STATES, SWIPE_DIRECTIONS, } from '../types/domain/device-session.types.js';
9
- import { platformOfAppFile, uploadLocalApp } from '../utils/app-upload.js';
8
+ import { DEVICE_KEYS, ENDED_STATES, LOG_LEVELS, SWIPE_DIRECTIONS, } from '../types/domain/device-session.types.js';
9
+ import { platformOfAppFile, platformOfAppUrl, uploadLocalApp } from '../utils/app-upload.js';
10
10
  import { refreshAuth, resolveAuth } from '../utils/auth.js';
11
11
  import { openBrowser } from '../utils/browser.js';
12
- import { uploadFlowBundle } from '../utils/device-bundle.js';
13
- import { downloadArtifactFiles, fetchAllArtifacts, pendingArtifacts, pendingArtifactsWarning, planArtifactFiles, } from '../utils/device-artifacts.js';
12
+ import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bundle.js';
13
+ import { downloadArtifactFiles, downloadFile, fetchAllArtifacts, pendingArtifacts, pendingArtifactsWarning, planArtifactFiles, } from '../utils/device-artifacts.js';
14
14
  import { CliError, logger, validateEnum } from '../utils/cli.js';
15
15
  import { resolveApiUrl } from '../utils/config-store.js';
16
- import { deviceProgress, humanFields, printSession, resolveSessionId, runDeviceCommand, } from '../utils/device-output.js';
16
+ import { strictFlags } from '../utils/device-flags.js';
17
+ import { checkSessionId, DEVICE_EXIT, deviceProgress, humanFields, printable, printSession, printWarnings, resolveRecentSessionId, resolveSessionId, runDeviceCommand, } from '../utils/device-output.js';
17
18
  import { parseRunReport, printRunResult, runFailureMessage } from '../utils/device-run.js';
18
19
  import { isUrl } from '../utils/expo.js';
19
20
  import { colors, formatUrl } from '../utils/styling.js';
@@ -21,9 +22,18 @@ import { ui } from '../utils/ui.js';
21
22
  const PLATFORMS = ['android', 'ios'];
22
23
  /** What `--name` defaults to: shown in the console and the session timeline. */
23
24
  const DEFAULT_CLIENT_LABEL = 'dcd-cli';
24
- const WAIT_POLL_MS = 2000;
25
25
  /** Longer than the API's own queue timeout, so that one is what ends a wait. */
26
26
  const WAIT_TIMEOUT_MS = 20 * 60 * 1000;
27
+ /** The longest a session can run (60 minutes), and a little more: a flow can't run past its session. */
28
+ const MAX_SESSION_MS = 65 * 60 * 1000;
29
+ /**
30
+ * How the waits poll. `retryMs` is how long a wait keeps asking through
31
+ * failed requests before it gives up, and `retryBaseMs` the first pause
32
+ * between tries (doubled each time, up to 15s). `runGraceMs` is how long a
33
+ * wait for a flow goes on past its session's maximum duration, for the API
34
+ * to end the session. Changed by tests only.
35
+ */
36
+ export const deviceTiming = { pollMs: 2000, retryBaseMs: 2000, retryMs: 90_000, runGraceMs: 60_000 };
27
37
  /** States in which a session takes commands. */
28
38
  const USABLE_STATES = new Set(['active', 'needs_human', 'ready']);
29
39
  /** Every `dcd device` subcommand takes these. */
@@ -31,7 +41,17 @@ const commonArgs = { ...apiFlags, json: jsonFlag };
31
41
  const idArg = {
32
42
  type: 'positional',
33
43
  required: false,
34
- description: 'Session id, e.g. brave-teal-otter. Optional when exactly one session is open.',
44
+ description: 'Session id, e.g. brave-teal-otter. Optional when you have exactly one open session.',
45
+ };
46
+ /**
47
+ * For the commands that change a session: one someone else started (another
48
+ * person or another API key) is refused with LIVE_NOT_YOURS unless this is
49
+ * given. A teammate's agent may be using it.
50
+ */
51
+ const forceArg = {
52
+ type: 'boolean',
53
+ default: false,
54
+ description: 'Change a session someone else started (another person or API key)',
35
55
  };
36
56
  async function context(args) {
37
57
  const json = Boolean(args.json);
@@ -57,6 +77,44 @@ async function freshAuth(ctx) {
57
77
  function sleep(ms) {
58
78
  return new Promise((resolve) => setTimeout(resolve, ms));
59
79
  }
80
+ /**
81
+ * A failure worth asking again: no answer came (a dropped connection, an
82
+ * unreadable reply), or the API or a proxy in front of it was busy or briefly
83
+ * down. A refusal (a 4xx other than 408 and 429) is final.
84
+ */
85
+ export function transientFailure(error) {
86
+ if (error instanceof DeviceApiError)
87
+ return [408, 429, 500, 502, 503, 504].includes(error.status);
88
+ return !(error instanceof CliError);
89
+ }
90
+ /**
91
+ * One request of a wait, asked again while it fails for a reason that passes
92
+ * (transientFailure), for up to deviceTiming.retryMs. A wait of many minutes
93
+ * must not end, and lose what it was waiting for, on one failed poll.
94
+ */
95
+ async function pollOnce(ctx, call) {
96
+ const giveUpAt = Date.now() + deviceTiming.retryMs;
97
+ for (let attempt = 0;; attempt++) {
98
+ try {
99
+ return await call(await freshAuth(ctx));
100
+ }
101
+ catch (error) {
102
+ if (!transientFailure(error) || Date.now() >= giveUpAt)
103
+ throw error;
104
+ const asked = error instanceof DeviceApiError ? Number(error.details.retry_after_s) : Number.NaN;
105
+ const pause = Number.isFinite(asked) && asked > 0
106
+ ? Math.min(asked * 1000, 60_000)
107
+ : Math.min(deviceTiming.retryBaseMs * 2 ** attempt, 15_000);
108
+ const reason = (error instanceof Error ? error.message : String(error)).split('\n')[0];
109
+ ctx.progress(` ${colors.dim(`a request failed (${reason}); asking again in ${Math.ceil(pause / 1000)}s`)}`);
110
+ await sleep(pause);
111
+ }
112
+ }
113
+ }
114
+ /** A session that has ended, as the error that exits 4. */
115
+ function sessionEnded(id, session, while_, details = {}) {
116
+ return new DeviceApiError(`Device session ${id} ended ${while_} (${session.release_reason ?? session.state}). An ended session is final: start a new one.`, 410, 'LIVE_SESSION_ENDED', session, false, details);
117
+ }
60
118
  /**
61
119
  * Poll until the session takes commands. Reports each change of state (and
62
120
  * queue position) as progress. A session that ends while waiting is exit 4.
@@ -65,12 +123,11 @@ async function waitUntilUsable(ctx, id) {
65
123
  const deadline = Date.now() + WAIT_TIMEOUT_MS;
66
124
  let last = '';
67
125
  for (;;) {
68
- const { session } = await DeviceGateway.status(ctx.apiUrl, await freshAuth(ctx), id);
126
+ const { session } = await pollOnce(ctx, (auth) => DeviceGateway.status(ctx.apiUrl, auth, id));
69
127
  if (USABLE_STATES.has(session.state))
70
128
  return session;
71
- if (ENDED_STATES.includes(session.state)) {
72
- throw new DeviceApiError(`Device session ${id} ended while starting (${session.release_reason ?? session.state}).`, 410, 'LIVE_SESSION_ENDED', session);
73
- }
129
+ if (ENDED_STATES.includes(session.state))
130
+ throw sessionEnded(id, session, 'while waiting for it to be ready');
74
131
  const position = session.queue?.position;
75
132
  const line = position ? `${session.state} (position ${position} in the queue)` : session.state;
76
133
  if (line !== last) {
@@ -80,7 +137,7 @@ async function waitUntilUsable(ctx, id) {
80
137
  if (Date.now() >= deadline) {
81
138
  throw new DeviceApiError(`Timed out after ${WAIT_TIMEOUT_MS / 60_000} minutes waiting for ${id} (state: ${session.state}). It is still open: check it with \`dcd device status ${id}\`.`, 408, null, session);
82
139
  }
83
- await sleep(WAIT_POLL_MS);
140
+ await sleep(deviceTiming.pollMs);
84
141
  }
85
142
  }
86
143
  /**
@@ -92,11 +149,10 @@ async function waitUntilUsable(ctx, id) {
92
149
  async function waitForInstall(ctx, id, binaryId) {
93
150
  const deadline = Date.now() + WAIT_TIMEOUT_MS;
94
151
  for (;;) {
95
- const { session } = await DeviceGateway.status(ctx.apiUrl, await freshAuth(ctx), id);
152
+ const { session } = await pollOnce(ctx, (auth) => DeviceGateway.status(ctx.apiUrl, auth, id));
96
153
  const install = session.install;
97
- if (ENDED_STATES.includes(session.state)) {
98
- throw new DeviceApiError(`Device session ${id} ended while installing (${session.release_reason ?? session.state}).`, 410, 'LIVE_SESSION_ENDED', session);
99
- }
154
+ if (ENDED_STATES.includes(session.state))
155
+ throw sessionEnded(id, session, 'while installing');
100
156
  // Done, failed, superseded by another install, or an API too old to say.
101
157
  if (!install || install.binary_upload_id !== binaryId || install.status !== 'installing') {
102
158
  return session;
@@ -104,7 +160,7 @@ async function waitForInstall(ctx, id, binaryId) {
104
160
  if (Date.now() >= deadline) {
105
161
  throw new DeviceApiError(`Timed out after ${WAIT_TIMEOUT_MS / 60_000} minutes waiting for the install on ${id}. It may still finish: check it with \`dcd device status ${id}\`.`, 408, null, session);
106
162
  }
107
- await sleep(WAIT_POLL_MS);
163
+ await sleep(deviceTiming.pollMs);
108
164
  }
109
165
  }
110
166
  /** A failed install as a command failure (exit 2); the session stays open. */
@@ -256,10 +312,16 @@ const startSub = defineCommand({
256
312
  await runDeviceCommand(json, async () => {
257
313
  const app = args.app;
258
314
  const binaryId = args['app-binary-id'];
315
+ // `--app "$BUILD"` with BUILD unset would start a billed session with no app.
316
+ for (const [flag, value] of [['app', app], ['app-binary-id', binaryId]]) {
317
+ if (value !== undefined && !String(value).trim()) {
318
+ throw new CliError(`--${flag} is empty (a variable that was not set?). Give the build, or leave the flag out.`);
319
+ }
320
+ }
259
321
  if (app && binaryId)
260
322
  throw new CliError('Pass --app or --app-binary-id, not both.');
261
323
  const model = args.model;
262
- const appPlatform = app && !isUrl(app) ? platformOfAppFile(app) : undefined;
324
+ const appPlatform = app ? (isUrl(app) ? platformOfAppUrl(app) : platformOfAppFile(app)) : undefined;
263
325
  let platform = validateEnum(args.platform, PLATFORMS, 'platform') ?? appPlatform;
264
326
  if (!platform && !model) {
265
327
  throw new CliError('Pass --platform ios or android, or a --model or --app that says which.');
@@ -300,6 +362,12 @@ const startSub = defineCommand({
300
362
  throw await failedStartError(ctx, error);
301
363
  }
302
364
  ctx.progress(ui.success(`Session ${session.id} started`));
365
+ // Under --json nothing else is printed until the wait ends, which can
366
+ // be many minutes. A caller that gives up before then must still know
367
+ // which session it started, to use or stop it.
368
+ if (json && args.wait) {
369
+ process.stderr.write(`Session ${session.id} started; waiting until it is ready. Stop it with \`dcd device stop ${session.id}\` if you stop waiting.\n`);
370
+ }
303
371
  // The session exists and bills from here on: every later failure must
304
372
  // still name it, so the caller can stop it.
305
373
  let installedId;
@@ -375,7 +443,9 @@ const listSub = defineCommand({
375
443
  logger.log(ui.section(`Device sessions (${sessions.length})`));
376
444
  logger.log(ui.branch(ui.fields(sessions.map((s) => [
377
445
  colors.highlight(s.id),
378
- [s.state, s.platform, s.model, s.client_label].filter(Boolean).join(' '),
446
+ printable([s.state, s.platform, s.model, s.client_label].filter(Boolean).join(' '), {
447
+ oneLine: true,
448
+ }),
379
449
  ]))));
380
450
  },
381
451
  };
@@ -384,12 +454,28 @@ const listSub = defineCommand({
384
454
  });
385
455
  const statusSub = defineCommand({
386
456
  meta: { name: 'status', description: "A session's state, time left and cost" },
387
- args: { ...commonArgs, id: idArg },
457
+ args: {
458
+ ...commonArgs,
459
+ id: idArg,
460
+ wait: {
461
+ type: 'boolean',
462
+ default: false,
463
+ description: 'Wait until the session is ready for commands and its app is installed (exit 4 if it ends first)',
464
+ },
465
+ },
388
466
  async run({ args }) {
389
467
  const json = Boolean(args.json);
390
468
  await runDeviceCommand(json, async () => {
391
469
  const ctx = await context(args);
392
470
  const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
471
+ if (args.wait) {
472
+ ctx.progress(ui.running(`Waiting for ${colors.highlight(id)}…`));
473
+ const ready = await waitUntilUsable(ctx, id);
474
+ if (ready.install?.status === 'installing') {
475
+ ctx.progress(ui.running('Waiting for the app to install…'));
476
+ await waitForInstall(ctx, id, ready.install.binary_upload_id);
477
+ }
478
+ }
393
479
  // The summary does not say whether a person handed the session back,
394
480
  // so ask. An API without the route (or a failure) just leaves it out.
395
481
  const [{ session }, human] = await Promise.all([
@@ -403,11 +489,11 @@ const statusSub = defineCommand({
403
489
  logger.log(ui.section('Device session'));
404
490
  printSession(session);
405
491
  if (human?.handed_back) {
406
- logger.log(ui.info(`A person handed it back${human.note ? `: ${human.note}` : ' (no note).'}`));
492
+ logger.log(ui.info(`A person handed it back${human.note ? `: ${printable(human.note, { oneLine: true })}` : ' (no note).'}`));
407
493
  }
408
494
  // The API's own warning already says a person has control and how
409
495
  // to wait; only add ours when an older API leaves it out.
410
- const apiSaysWaiting = (session.warnings ?? []).some((w) => w.startsWith('Waiting for a human'));
496
+ const apiSaysWaiting = (session.warnings ?? []).some((w) => w.startsWith('Waiting for a human') || w.startsWith('A person has control'));
411
497
  if (human?.human_in_control && !apiSaysWaiting) {
412
498
  logger.log(ui.warn(`A person has control. Wait with \`dcd device human ${session.id} --wait\`.`));
413
499
  }
@@ -417,11 +503,12 @@ const statusSub = defineCommand({
417
503
  },
418
504
  });
419
505
  const stopSub = defineCommand({
420
- meta: { name: 'stop', description: 'Stop a session, or every open one with --all' },
506
+ meta: { name: 'stop', description: 'Stop a session, or every open one of yours with --all' },
421
507
  args: {
422
508
  ...commonArgs,
423
509
  id: idArg,
424
- all: { type: 'boolean', default: false, description: "Stop every open session in your org" },
510
+ all: { type: 'boolean', default: false, description: 'Stop every open session of yours (with --force, everyone\'s)' },
511
+ force: forceArg,
425
512
  },
426
513
  async run({ args }) {
427
514
  const json = Boolean(args.json);
@@ -431,22 +518,30 @@ const stopSub = defineCommand({
431
518
  if (args.id)
432
519
  throw new CliError('Pass a session id or --all, not both.');
433
520
  const { sessions } = await DeviceGateway.list(ctx.apiUrl, ctx.auth);
521
+ // Yours, or every one with --force: another's may be a teammate's
522
+ // agent at work. An API that does not say whose is read as before.
523
+ const force = Boolean(args.force);
524
+ const mine = sessions.filter((s) => force || !s.started_by || s.started_by.you);
525
+ const others = sessions.filter((s) => !mine.includes(s));
434
526
  const stopped = [];
435
- for (const s of sessions) {
436
- stopped.push((await DeviceGateway.stop(ctx.apiUrl, ctx.auth, s.id)).session);
527
+ for (const s of mine) {
528
+ stopped.push((await DeviceGateway.stop(ctx.apiUrl, ctx.auth, s.id, force)).session);
437
529
  }
438
530
  return {
439
531
  session: undefined,
440
- data: { stopped },
532
+ data: { left: others.map((s) => s.id), stopped },
441
533
  print() {
442
534
  logger.log(stopped.length === 0
443
- ? ui.info('No open device sessions to stop.')
535
+ ? ui.info('No open device sessions of yours to stop.')
444
536
  : ui.success(`Stopped ${stopped.map((s) => s.id).join(', ')}`));
537
+ if (others.length > 0) {
538
+ logger.log(ui.info(`Left ${others.map((s) => s.id).join(', ')}, started by someone else. Add --force to stop those too.`));
539
+ }
445
540
  },
446
541
  };
447
542
  }
448
543
  const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
449
- const { session } = await DeviceGateway.stop(ctx.apiUrl, ctx.auth, id);
544
+ const { session } = await DeviceGateway.stop(ctx.apiUrl, ctx.auth, id, Boolean(args.force));
450
545
  return {
451
546
  session,
452
547
  data: null,
@@ -469,6 +564,7 @@ const installSub = defineCommand({
469
564
  meta: { name: 'install', description: 'Install a build: a local file (uploaded first) or an https URL' },
470
565
  args: {
471
566
  ...commonArgs,
567
+ force: forceArg,
472
568
  id: idArg,
473
569
  app: {
474
570
  type: 'positional',
@@ -497,7 +593,7 @@ const installSub = defineCommand({
497
593
  id = await resolveSessionId(ctx.apiUrl, ctx.auth, id);
498
594
  const body = binaryId ? { binaryUploadId: binaryId } : await resolveApp(ctx, app);
499
595
  ctx.progress(ui.running(`Installing on ${colors.highlight(id)}…`));
500
- const installed = await DeviceGateway.install(ctx.apiUrl, ctx.auth, id, body);
596
+ const installed = await DeviceGateway.install(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force));
501
597
  let { session } = installed;
502
598
  if (args.wait) {
503
599
  ctx.progress(ui.running('Waiting for the device…'));
@@ -525,6 +621,7 @@ const installSub = defineCommand({
525
621
  if (!args.wait) {
526
622
  logger.log(ui.note('The device installs it next. Commands answer "not ready" until it is done.'));
527
623
  }
624
+ printWarnings(session);
528
625
  },
529
626
  };
530
627
  });
@@ -538,6 +635,7 @@ const launchSub = defineCommand({
538
635
  meta: { name: 'launch', description: 'Launch an app: the installed one, or a bundle id / package name' },
539
636
  args: {
540
637
  ...commonArgs,
638
+ force: forceArg,
541
639
  id: idArg,
542
640
  appId: {
543
641
  type: 'positional',
@@ -562,7 +660,7 @@ const launchSub = defineCommand({
562
660
  const { result, session } = await DeviceGateway.launch(ctx.apiUrl, ctx.auth, id, {
563
661
  ...(appId && { appId }),
564
662
  ...(args['clear-state'] ? { clearState: true } : {}),
565
- });
663
+ }, Boolean(args.force));
566
664
  return {
567
665
  session,
568
666
  data: { result },
@@ -574,7 +672,8 @@ const launchSub = defineCommand({
574
672
  ? ui.success(`Launched ${appId ?? 'the app'}`)
575
673
  : `${ui.statusSymbol('FAILED')} Launch failed`);
576
674
  if (result.error)
577
- logger.log(colors.error(result.error));
675
+ logger.log(colors.error(printable(result.error)));
676
+ printWarnings(session);
578
677
  },
579
678
  };
580
679
  });
@@ -590,9 +689,9 @@ const maestroArg = {
590
689
  default: false,
591
690
  description: 'Deprecated: has no effect. Device sessions have a single engine',
592
691
  };
593
- /** A percentage of the screen from a flag value, or a usage error. */
692
+ /** A percentage of the screen from a flag value (`50` or `50%`), or a usage error. */
594
693
  function percentArg(value, flag) {
595
- const n = typeof value === 'number' ? value : Number(value);
694
+ const n = typeof value === 'number' ? value : Number(typeof value === 'string' ? value.trim().replace(/%$/, '') : value);
596
695
  if (typeof value === 'boolean' || value === '' || !Number.isFinite(n) || n < 0 || n > 100) {
597
696
  throw new CliError(`--${flag} must be a number from 0 to 100 (a percentage of the screen).`, 1);
598
697
  }
@@ -629,28 +728,34 @@ const LINK = /^[A-Za-z][A-Za-z0-9+.-]*:\S+$/;
629
728
  function pointArg(value, flag) {
630
729
  const parts = typeof value === 'string' ? value.split(',') : [];
631
730
  if (parts.length !== 2) {
632
- throw new CliError(`--${flag} must be "x,y", percentages of the screen, e.g. --${flag} 50,80.`, 1);
731
+ throw new CliError(`--${flag} must be "x,y", percentages of the screen, e.g. --${flag} 50,80 or 50%,80%.`, 1);
633
732
  }
634
733
  return { x: percentArg(parts[0].trim(), flag), y: percentArg(parts[1].trim(), flag) };
635
734
  }
636
735
  /**
637
736
  * Send one typed action and print its outcome, the way `launch` does: exit 2
638
737
  * with the result when the device could not do it.
738
+ *
739
+ * `labels.done` and `labels.failed` are what a person reads, and may name
740
+ * what was typed or opened. `labels.failure` is the failure's message when
741
+ * the device gave no reason: fixed text, as it goes into the --json envelope
742
+ * and the command's failure record, and must never carry typed text.
639
743
  */
640
744
  async function performAction(args, id, body, labels) {
641
745
  const ctx = await context(args);
642
746
  const sessionId = await resolveSessionId(ctx.apiUrl, ctx.auth, id);
643
- const { result, session } = await DeviceGateway.action(ctx.apiUrl, ctx.auth, sessionId, body);
747
+ const { result, session } = await DeviceGateway.action(ctx.apiUrl, ctx.auth, sessionId, body, Boolean(args.force));
644
748
  return {
645
749
  session,
646
750
  data: { result },
647
751
  ...(!result.success && {
648
- failure: { code: null, message: result.error || labels.failed },
752
+ failure: { code: null, message: result.error || labels.failure },
649
753
  }),
650
754
  print() {
651
755
  logger.log(result.success ? ui.success(labels.done) : `${ui.statusSymbol('FAILED')} ${labels.failed}`);
652
756
  if (result.error)
653
- logger.log(colors.error(result.error));
757
+ logger.log(colors.error(printable(result.error)));
758
+ printWarnings(session);
654
759
  },
655
760
  };
656
761
  }
@@ -658,6 +763,7 @@ const tapSub = defineCommand({
658
763
  meta: { name: 'tap', description: 'Tap an element by text or id, or a point on the screen' },
659
764
  args: {
660
765
  ...commonArgs,
766
+ force: forceArg,
661
767
  id: idArg,
662
768
  text: { type: 'string', description: 'The element\'s text, label or hint, matched whole, ignoring case' },
663
769
  rid: { type: 'string', description: 'The element\'s resource id (rid in `dcd device inspect`)' },
@@ -698,6 +804,7 @@ const tapSub = defineCommand({
698
804
  return performAction(args, args.id, body, {
699
805
  done: `Tapped ${what}`,
700
806
  failed: `Tap ${what} failed`,
807
+ failure: 'The tap failed.',
701
808
  });
702
809
  });
703
810
  },
@@ -706,10 +813,16 @@ const typeSub = defineCommand({
706
813
  meta: { name: 'type', description: 'Type text into the focused field' },
707
814
  args: {
708
815
  ...commonArgs,
816
+ force: forceArg,
709
817
  id: idArg,
710
818
  // Not `required`: citty would reject a missing value before runDeviceCommand,
711
819
  // and --json would then print the top-level error instead of the envelope.
712
820
  text: { type: 'string', description: 'What to type' },
821
+ 'text-stdin': {
822
+ type: 'boolean',
823
+ default: false,
824
+ description: 'Read the text from standard input instead of --text, so a secret stays out of the shell history and the process list',
825
+ },
713
826
  sensitive: {
714
827
  type: 'boolean',
715
828
  default: false,
@@ -720,19 +833,36 @@ const typeSub = defineCommand({
720
833
  async run({ args }) {
721
834
  const json = Boolean(args.json);
722
835
  await runDeviceCommand(json, async () => {
723
- const text = String(args.text ?? '');
836
+ if (args['text-stdin'] && args.text !== undefined) {
837
+ throw new CliError('Pass --text or --text-stdin, not both.', 1);
838
+ }
839
+ const text = args['text-stdin'] ? await readStdinText() : String(args.text ?? '');
724
840
  if (!text)
725
- throw new CliError('--text must not be empty.', 1);
726
- const shown = args.sensitive ? `${text.length} character(s)` : `"${text}"`;
727
- return performAction(args, args.id, { type: 'type', text, ...(args.sensitive ? { sensitive: true } : {}) }, { done: `Typed ${shown}`, failed: `Typing ${shown} failed` });
841
+ throw new CliError(args['text-stdin'] ? 'Standard input was empty: nothing to type.' : '--text must not be empty.', 1);
842
+ const shown = args.sensitive ? `${text.length} character(s)` : `"${printable(text, { oneLine: true })}"`;
843
+ return performAction(args, args.id, { type: 'type', text, ...(args.sensitive ? { sensitive: true } : {}) }, { done: `Typed ${shown}`, failed: `Typing ${shown} failed`, failure: 'Typing failed.' });
728
844
  });
729
845
  },
730
846
  });
847
+ /**
848
+ * The text piped to this command, without the one line break a shell's
849
+ * `echo` adds. Refused at a terminal, where it would wait for typing.
850
+ */
851
+ export async function readStdinText(stdin = process.stdin) {
852
+ if (stdin.isTTY) {
853
+ throw new CliError('--text-stdin reads the text from standard input: pipe it in, e.g. printf %s "$PASSWORD" | dcd device type --text-stdin --sensitive', 1);
854
+ }
855
+ const chunks = [];
856
+ for await (const chunk of stdin)
857
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
858
+ return Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, '');
859
+ }
731
860
  const isDirection = (value) => typeof value === 'string' && SWIPE_DIRECTIONS.includes(value);
732
861
  const swipeSub = defineCommand({
733
862
  meta: { name: 'swipe', description: 'Swipe up, down, left or right, or from one point to another' },
734
863
  args: {
735
864
  ...commonArgs,
865
+ force: forceArg,
736
866
  id: idArg,
737
867
  direction: {
738
868
  type: 'positional',
@@ -768,7 +898,11 @@ const swipeSub = defineCommand({
768
898
  body = { type: 'swipe', from: pointArg(args.from, 'from'), to: pointArg(args.to, 'to') };
769
899
  what = `${String(args.from)} to ${String(args.to)}`;
770
900
  }
771
- return performAction(args, id, body, { done: `Swiped ${what}`, failed: `Swipe ${what} failed` });
901
+ return performAction(args, id, body, {
902
+ done: `Swiped ${what}`,
903
+ failed: `Swipe ${what} failed`,
904
+ failure: 'The swipe failed.',
905
+ });
772
906
  });
773
907
  },
774
908
  });
@@ -776,6 +910,7 @@ const pressKeySub = defineCommand({
776
910
  meta: { name: 'press-key', description: `Press a key: ${DEVICE_KEYS.join(', ')}` },
777
911
  args: {
778
912
  ...commonArgs,
913
+ force: forceArg,
779
914
  id: idArg,
780
915
  key: { type: 'positional', required: false, description: `One of ${DEVICE_KEYS.join(', ')}` },
781
916
  maestro: maestroArg,
@@ -791,7 +926,7 @@ const pressKeySub = defineCommand({
791
926
  if (!key || !DEVICE_KEYS.includes(key)) {
792
927
  throw new CliError(`key must be one of ${DEVICE_KEYS.join(', ')}.`, 1);
793
928
  }
794
- return performAction(args, id, { type: 'press_key', key }, { done: `Pressed ${key}`, failed: `Press ${key} failed` });
929
+ return performAction(args, id, { type: 'press_key', key }, { done: `Pressed ${key}`, failed: `Press ${key} failed`, failure: 'The key press failed.' });
795
930
  });
796
931
  },
797
932
  });
@@ -799,6 +934,7 @@ const openLinkSub = defineCommand({
799
934
  meta: { name: 'open-link', description: 'Open a link on the device: a deep link into an app, or a web link' },
800
935
  args: {
801
936
  ...commonArgs,
937
+ force: forceArg,
802
938
  id: idArg,
803
939
  // Not `required`, as with `type --text`: a missing link fails inside the envelope.
804
940
  url: {
@@ -824,7 +960,7 @@ const openLinkSub = defineCommand({
824
960
  throw new CliError('open-link takes a link with its scheme and no spaces, e.g. myapp://path or https://example.com.', 1);
825
961
  }
826
962
  const shown = args.sensitive ? 'a link' : url;
827
- return performAction(args, id, { type: 'open_link', url, ...(args.sensitive ? { sensitive: true } : {}) }, { done: `Opened ${shown}`, failed: `Opening ${shown} failed` });
963
+ return performAction(args, id, { type: 'open_link', url, ...(args.sensitive ? { sensitive: true } : {}) }, { done: `Opened ${shown}`, failed: `Opening ${shown} failed`, failure: 'Opening the link failed.' });
828
964
  });
829
965
  },
830
966
  });
@@ -832,6 +968,7 @@ const setLocationSub = defineCommand({
832
968
  meta: { name: 'set-location', description: "Set the device's GPS position, in decimal degrees" },
833
969
  args: {
834
970
  ...commonArgs,
971
+ force: forceArg,
835
972
  id: idArg,
836
973
  latitude: { type: 'string', description: 'Decimal degrees, north positive (-90 to 90)' },
837
974
  longitude: { type: 'string', description: 'Decimal degrees, east positive (-180 to 180)' },
@@ -842,7 +979,11 @@ const setLocationSub = defineCommand({
842
979
  // South and west are negative. citty keeps a value that is a number, minus sign and all.
843
980
  const latitude = degreesArg(args.latitude, 'latitude', 90);
844
981
  const longitude = degreesArg(args.longitude, 'longitude', 180);
845
- return performAction(args, args.id, { type: 'set_location', latitude, longitude }, { done: `Location set to ${latitude}, ${longitude}`, failed: 'Setting the location failed' });
982
+ return performAction(args, args.id, { type: 'set_location', latitude, longitude }, {
983
+ done: `Location set to ${latitude}, ${longitude}`,
984
+ failed: 'Setting the location failed',
985
+ failure: 'Setting the location failed.',
986
+ });
846
987
  });
847
988
  },
848
989
  });
@@ -912,6 +1053,7 @@ const inspectSub = defineCommand({
912
1053
  }
913
1054
  if (notes.length > 0)
914
1055
  logger.log(ui.note(notes.join(' ')));
1056
+ printWarnings(session);
915
1057
  },
916
1058
  };
917
1059
  });
@@ -919,15 +1061,18 @@ const inspectSub = defineCommand({
919
1061
  });
920
1062
  /** One element on one line: what to target it by, then its bounds. */
921
1063
  export function formatElement(el) {
1064
+ // An element's text is whatever the app or a web page shows: never let it
1065
+ // drive the terminal.
1066
+ const show = (value) => printable(value, { oneLine: true });
922
1067
  const parts = [];
923
1068
  if (el.txt)
924
- parts.push(`"${el.txt}"`);
1069
+ parts.push(`"${show(el.txt)}"`);
925
1070
  if (el.a11y && el.a11y !== el.txt)
926
- parts.push(`a11y:"${el.a11y}"`);
1071
+ parts.push(`a11y:"${show(el.a11y)}"`);
927
1072
  if (el.rid)
928
- parts.push(`id:${el.rid}`);
1073
+ parts.push(`id:${show(el.rid)}`);
929
1074
  if (el.hint)
930
- parts.push(`hint:"${el.hint}"`);
1075
+ parts.push(`hint:"${show(el.hint)}"`);
931
1076
  for (const state of ['checked', 'selected', 'focused']) {
932
1077
  if (el[state])
933
1078
  parts.push(state);
@@ -951,7 +1096,11 @@ const screenshotSub = defineCommand({
951
1096
  output: {
952
1097
  type: 'string',
953
1098
  alias: ['o'],
954
- description: 'Where to save it (default: ./<session>-<time>.jpg)',
1099
+ description: 'Where to save it (default: ./<session>-<time>.jpg, or .png with --full)',
1100
+ },
1101
+ full: {
1102
+ type: 'boolean',
1103
+ description: "A PNG at the device's own resolution, instead of the smaller JPEG frame (for baseline images). Takes a few seconds. A device busy running a flow can't take it: after 30 seconds the request fails, so take it once the flow has finished",
955
1104
  },
956
1105
  },
957
1106
  async run({ args }) {
@@ -959,6 +1108,28 @@ const screenshotSub = defineCommand({
959
1108
  await runDeviceCommand(json, async () => {
960
1109
  const ctx = await context(args);
961
1110
  const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
1111
+ if (args.full) {
1112
+ const { screenshot, session } = await DeviceGateway.fullScreenshot(ctx.apiUrl, ctx.auth, id);
1113
+ const file = args.output ||
1114
+ `${session.id}-${new Date().toISOString().replaceAll(/[:.]/g, '-')}.png`;
1115
+ await downloadFile(screenshot.url, file);
1116
+ const filePath = resolvePath(file);
1117
+ const size = screenshot.width && screenshot.height ? `${screenshot.width}x${screenshot.height}` : null;
1118
+ return {
1119
+ session,
1120
+ data: {
1121
+ path: filePath,
1122
+ captured_at: screenshot.captured_at,
1123
+ width: screenshot.width,
1124
+ height: screenshot.height,
1125
+ bytes: screenshot.bytes,
1126
+ },
1127
+ print() {
1128
+ logger.log(ui.success(`Saved ${filePath}${size ? ` (${size})` : ''}`));
1129
+ printWarnings(session);
1130
+ },
1131
+ };
1132
+ }
962
1133
  const { screenshot, session } = await DeviceGateway.screenshot(ctx.apiUrl, ctx.auth, id);
963
1134
  const { bytes, ext } = decodeDataUrl(screenshot.data_url);
964
1135
  const file = args.output ||
@@ -972,6 +1143,7 @@ const screenshotSub = defineCommand({
972
1143
  logger.log(ui.success(`Saved ${filePath}`));
973
1144
  if (!screenshot.fresh)
974
1145
  logger.log(ui.note('No new frame came in time; this is the latest.'));
1146
+ printWarnings(session);
975
1147
  },
976
1148
  };
977
1149
  });
@@ -980,6 +1152,39 @@ const screenshotSub = defineCommand({
980
1152
  function isDirectory(p) {
981
1153
  return existsSync(p) && statSync(p).isDirectory();
982
1154
  }
1155
+ /**
1156
+ * `--env-file`: KEY=VALUE lines, as a .env file has them. Blank lines and
1157
+ * `#` comments are skipped, `export ` is allowed, and one pair of quotes
1158
+ * around a value is removed. A bad line is named by its number only: the
1159
+ * line may hold a secret.
1160
+ */
1161
+ export function parseEnvFile(file) {
1162
+ let text;
1163
+ try {
1164
+ text = readFileSync(file, 'utf8');
1165
+ }
1166
+ catch (error) {
1167
+ throw new CliError(`Could not read --env-file ${file}: ${error.message}`);
1168
+ }
1169
+ const env = {};
1170
+ for (const [index, raw] of text.split(/\r?\n/).entries()) {
1171
+ const line = raw.trim();
1172
+ if (!line || line.startsWith('#'))
1173
+ continue;
1174
+ const pair = line.startsWith('export ') ? line.slice(7).trimStart() : line;
1175
+ const eq = pair.indexOf('=');
1176
+ const key = eq > 0 ? pair.slice(0, eq).trim() : '';
1177
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
1178
+ throw new CliError(`--env-file ${file}, line ${index + 1}: expected KEY=VALUE.`);
1179
+ }
1180
+ let value = pair.slice(eq + 1).trim();
1181
+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) {
1182
+ value = value.slice(1, -1);
1183
+ }
1184
+ env[key] = value;
1185
+ }
1186
+ return env;
1187
+ }
983
1188
  /** `--env KEY=VALUE`, given once or several times. */
984
1189
  export function parseEnvFlags(value) {
985
1190
  if (value === undefined || value === false)
@@ -994,21 +1199,57 @@ export function parseEnvFlags(value) {
994
1199
  }
995
1200
  return env;
996
1201
  }
997
- /** Wait for a flow that outlasted the API's own wait. */
998
- async function waitForCommand(ctx, id, commandId) {
1202
+ /** The latest a flow can still be running: its session's maximum duration, and a little time for the API to end it. */
1203
+ function runDeadline(session, now = Date.now()) {
1204
+ const left = session.time_remaining_s;
1205
+ return typeof left === 'number' && left >= 0 ? now + left * 1000 + deviceTiming.runGraceMs : now + MAX_SESSION_MS;
1206
+ }
1207
+ /**
1208
+ * Wait for a flow that outlasted the API's own wait. It ends with the flow,
1209
+ * or with the session: a flow can't outlive its session, so one that ends
1210
+ * (exit 4), or runs past its maximum duration, stops the wait.
1211
+ */
1212
+ async function waitForCommand(ctx, id, first) {
1213
+ const commandId = first.command_id;
1214
+ let response = first;
1215
+ let deadline = runDeadline(first.session);
999
1216
  let last = '';
1000
1217
  for (;;) {
1001
- await sleep(WAIT_POLL_MS);
1002
- const response = await DeviceGateway.command(ctx.apiUrl, await freshAuth(ctx), id, commandId);
1003
1218
  if (response.status !== 'running')
1004
1219
  return response;
1005
- const line = `still running (${response.session.state})`;
1220
+ const { session } = response;
1221
+ if (ENDED_STATES.includes(session.state)) {
1222
+ throw sessionEnded(id, session, 'before the flow finished', { command_id: commandId });
1223
+ }
1224
+ if (Date.now() >= deadline) {
1225
+ throw new DeviceApiError(`Gave up waiting for the flow: session ${id} has run past its maximum duration, yet still says ${session.state}. Check it with \`dcd device status ${id}\`.`, 408, null, session, false, { command_id: commandId });
1226
+ }
1227
+ const line = `still running (${session.state})`;
1006
1228
  if (line !== last) {
1007
1229
  last = line;
1008
1230
  ctx.progress(` ${colors.dim(line)}`);
1009
1231
  }
1232
+ await sleep(deviceTiming.pollMs);
1233
+ response = await pollOnce(ctx, (auth) => DeviceGateway.command(ctx.apiUrl, auth, id, commandId));
1234
+ deadline = Math.min(deadline, runDeadline(response.session));
1010
1235
  }
1011
1236
  }
1237
+ /**
1238
+ * An error from waiting on a flow, with the flow's command id kept: the
1239
+ * flow may still be running, and the id is how to find out.
1240
+ */
1241
+ function withCommandId(error, id, commandId) {
1242
+ if (error instanceof DeviceApiError && error.details.command_id)
1243
+ return error;
1244
+ const message = `${error instanceof Error ? error.message : String(error)} The flow may still be running on ${id}: its command id is ${commandId}.`;
1245
+ if (error instanceof DeviceApiError) {
1246
+ return new DeviceApiError(message, error.status, error.code, error.session, error.fromApi, {
1247
+ ...error.details,
1248
+ command_id: commandId,
1249
+ });
1250
+ }
1251
+ return new DeviceApiError(message, 502, null, null, false, { command_id: commandId });
1252
+ }
1012
1253
  const runSub = defineCommand({
1013
1254
  meta: {
1014
1255
  name: 'run',
@@ -1017,6 +1258,7 @@ const runSub = defineCommand({
1017
1258
  },
1018
1259
  args: {
1019
1260
  ...commonArgs,
1261
+ force: forceArg,
1020
1262
  id: idArg,
1021
1263
  flow: {
1022
1264
  type: 'positional',
@@ -1033,7 +1275,11 @@ const runSub = defineCommand({
1033
1275
  },
1034
1276
  env: {
1035
1277
  type: 'string',
1036
- description: 'A variable for the flow, KEY=VALUE, used as ${KEY}. Repeatable. Sent sealed, never stored in plain text',
1278
+ description: 'A variable for the flow, KEY=VALUE, used as ${KEY}. Repeatable. Stored encrypted, never shown, and masked in the output. A value given here is in your shell history: use --env-file for secrets',
1279
+ },
1280
+ 'env-file': {
1281
+ type: 'string',
1282
+ description: 'Variables for the flow from a file of KEY=VALUE lines (a .env file). --env wins over it for the same name',
1037
1283
  },
1038
1284
  },
1039
1285
  async run({ args, rawArgs }) {
@@ -1054,8 +1300,12 @@ const runSub = defineCommand({
1054
1300
  if (entry && (path.isAbsolute(entry) || entry.split(/[\\/]/).includes('..'))) {
1055
1301
  throw new CliError('--entry is a path inside the directory, e.g. flows/login.yaml.');
1056
1302
  }
1303
+ // A flow file that uses other files (runFlow, runScript, addMedia and
1304
+ // the like) is uploaded with them, as a bundle. Sent alone, the device
1305
+ // could not find them.
1306
+ const bundled = flow && !dir && existsSync(flow) ? flowFileBundle(flow) : null;
1057
1307
  let yaml = inline;
1058
- if (flow && !dir) {
1308
+ if (flow && !dir && !bundled) {
1059
1309
  try {
1060
1310
  yaml = readFileSync(flow, 'utf8');
1061
1311
  }
@@ -1064,11 +1314,26 @@ const runSub = defineCommand({
1064
1314
  }
1065
1315
  }
1066
1316
  const repeated = collectFlagValues('--env', rawArgs);
1067
- const env = parseEnvFlags(repeated.length > 0 ? repeated : args.env);
1317
+ const envFile = args['env-file'];
1318
+ const fromFile = envFile ? parseEnvFile(envFile) : undefined;
1319
+ const fromFlags = parseEnvFlags(repeated.length > 0 ? repeated : args.env);
1320
+ const env = fromFile || fromFlags ? { ...fromFile, ...fromFlags } : undefined;
1068
1321
  const ctx = await context(args);
1069
1322
  id = await resolveSessionId(ctx.apiUrl, ctx.auth, id);
1070
1323
  let body;
1071
- if (dir) {
1324
+ if (bundled) {
1325
+ ctx.progress(ui.running(`${flow} uses other files: uploading it with them, from ${colors.highlight(bundled.dir)}…`));
1326
+ const bundle = await uploadFlowBundle({
1327
+ apiUrl: ctx.apiUrl,
1328
+ auth: ctx.auth,
1329
+ dir: bundled.dir,
1330
+ entry: bundled.entry,
1331
+ log: ctx.progress,
1332
+ });
1333
+ ctx.progress(ui.success(`Uploaded ${bundle.files} files`));
1334
+ body = { flowUploadId: bundle.id, flow: bundlePath(bundled.entry), ...(env && { env }) };
1335
+ }
1336
+ else if (dir) {
1072
1337
  ctx.progress(ui.running(`Uploading the flows in ${colors.highlight(dir)}…`));
1073
1338
  const bundle = await uploadFlowBundle({
1074
1339
  apiUrl: ctx.apiUrl,
@@ -1080,7 +1345,7 @@ const runSub = defineCommand({
1080
1345
  ctx.progress(ui.success(`Uploaded ${bundle.files} files`));
1081
1346
  body = {
1082
1347
  flowUploadId: bundle.id,
1083
- ...(entry && { flow: entry.split(path.sep).join('/') }),
1348
+ ...(entry && { flow: bundlePath(path.normalize(entry)) }),
1084
1349
  ...(env && { env }),
1085
1350
  };
1086
1351
  }
@@ -1088,9 +1353,15 @@ const runSub = defineCommand({
1088
1353
  body = { yaml: yaml, ...(env && { env }) };
1089
1354
  }
1090
1355
  ctx.progress(ui.running(`Running ${entry ?? flow ?? 'the flow'} on ${colors.highlight(id)}…`));
1091
- let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body);
1092
- if (response.status === 'running')
1093
- response = await waitForCommand(ctx, id, response.command_id);
1356
+ let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force));
1357
+ if (response.status === 'running') {
1358
+ try {
1359
+ response = await waitForCommand(ctx, id, response);
1360
+ }
1361
+ catch (error) {
1362
+ throw withCommandId(error, id, response.command_id);
1363
+ }
1364
+ }
1094
1365
  const result = response.result ?? { success: false };
1095
1366
  const passed = response.status === 'passed';
1096
1367
  return {
@@ -1101,6 +1372,7 @@ const runSub = defineCommand({
1101
1372
  }),
1102
1373
  print() {
1103
1374
  printRunResult(logger.log, passed, result, entry ?? (flow ? path.basename(flow) : 'flow'));
1375
+ printWarnings(response.session);
1104
1376
  },
1105
1377
  };
1106
1378
  });
@@ -1152,12 +1424,22 @@ export function newLogLines(prev, next) {
1152
1424
  return next;
1153
1425
  }
1154
1426
  const LOGS_FOLLOW_MS = 3000;
1427
+ /** What the API's answer cap is, for the note that says it cut the answer. */
1428
+ const LOGS_CAP = '24 KB';
1155
1429
  const logsSub = defineCommand({
1156
1430
  meta: { name: 'logs', description: "The installed app's recent device log lines" },
1157
1431
  args: {
1158
1432
  ...commonArgs,
1159
1433
  id: idArg,
1160
1434
  lines: { type: 'string', default: '200', description: 'How many lines, up to 2000' },
1435
+ level: {
1436
+ type: 'string',
1437
+ description: `Only lines at this level and above: ${LOG_LEVELS.join(' or ')}`,
1438
+ },
1439
+ grep: {
1440
+ type: 'string',
1441
+ description: 'Only lines that contain this text, ignoring case',
1442
+ },
1161
1443
  follow: {
1162
1444
  type: 'boolean',
1163
1445
  alias: ['f'],
@@ -1177,34 +1459,49 @@ const logsSub = defineCommand({
1177
1459
  await runDeviceCommand(json, async () => {
1178
1460
  if (!Number.isInteger(lines) || lines < 1)
1179
1461
  throw new CliError('--lines must be a whole number.');
1462
+ const level = validateEnum(args.level, LOG_LEVELS, 'level');
1463
+ const grep = args.grep?.trim() || undefined;
1464
+ const filter = { ...(level && { level }), ...(grep && { grep }) };
1180
1465
  const ctx = await context(args);
1181
1466
  const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
1182
- const first = await DeviceGateway.logs(ctx.apiUrl, ctx.auth, id, lines);
1467
+ const first = await DeviceGateway.logs(ctx.apiUrl, ctx.auth, id, lines, filter);
1468
+ const cutNote = `Only the newest lines that fit in ${LOGS_CAP} are shown. Ask for fewer with --lines, or narrow them with --level or --grep.`;
1183
1469
  if (!args.follow) {
1184
1470
  return {
1185
1471
  session: first.session,
1186
1472
  data: { logs: first.logs },
1187
1473
  print() {
1188
1474
  if (first.logs.lines.length === 0) {
1189
- logger.log(ui.info(first.logs.source === 'none' ? 'No app installed yet, so no app logs.' : 'No log lines yet.'));
1475
+ const none = level || grep ? 'No log lines match.' : 'No log lines yet.';
1476
+ logger.log(ui.info(first.logs.source === 'none' ? 'No app installed yet, so no app logs.' : none));
1477
+ printWarnings(first.session);
1190
1478
  return;
1191
1479
  }
1192
1480
  for (const line of first.logs.lines)
1193
- logger.log(line);
1481
+ logger.log(printable(line));
1482
+ if (first.logs.truncated)
1483
+ logger.log(ui.note(cutNote));
1484
+ printWarnings(first.session);
1194
1485
  },
1195
1486
  };
1196
1487
  }
1197
1488
  // --follow: print as lines arrive. Ends when the session does.
1198
1489
  for (const line of first.logs.lines)
1199
- logger.log(line);
1490
+ logger.log(printable(line));
1200
1491
  let shown = first.logs.lines;
1201
1492
  let { session } = first;
1202
1493
  for (;;) {
1203
1494
  await sleep(LOGS_FOLLOW_MS);
1204
1495
  try {
1205
- const next = await DeviceGateway.logs(ctx.apiUrl, await freshAuth(ctx), id, lines);
1206
- for (const line of newLogLines(shown, next.logs.lines))
1207
- logger.log(line);
1496
+ const next = await pollOnce(ctx, (auth) => DeviceGateway.logs(ctx.apiUrl, auth, id, lines, filter));
1497
+ const fresh = newLogLines(shown, next.logs.lines);
1498
+ // Nothing in common with the last answer: more lines came in
1499
+ // between than one answer holds, and some were never shown.
1500
+ if (shown.length > 0 && fresh.length > 0 && fresh.length === next.logs.lines.length) {
1501
+ logger.log(colors.dim(`… some lines were missed: more arrived in ${LOGS_FOLLOW_MS / 1000}s than one read returns (--lines ${lines}, at most ${LOGS_CAP}).`));
1502
+ }
1503
+ for (const line of fresh)
1504
+ logger.log(printable(line));
1208
1505
  shown = next.logs.lines;
1209
1506
  session = next.session;
1210
1507
  }
@@ -1268,7 +1565,7 @@ async function waitForHandBack(ctx, id, first) {
1268
1565
  if (!withPerson(current.human))
1269
1566
  return current;
1270
1567
  await sleep(HUMAN_POLL_MS);
1271
- current = await DeviceGateway.human(ctx.apiUrl, await freshAuth(ctx), id);
1568
+ current = await pollOnce(ctx, (auth) => DeviceGateway.human(ctx.apiUrl, auth, id));
1272
1569
  }
1273
1570
  }
1274
1571
  /** A person's part in a session, for `human` and `request-human`. */
@@ -1286,6 +1583,15 @@ const waitForPersonArg = {
1286
1583
  default: false,
1287
1584
  description: `Wait until the person hands the session back (checks every ${HUMAN_POLL_MS / 1000}s; Ctrl-C stops waiting)`,
1288
1585
  };
1586
+ /** Whether text has a session id's shape (it is never a sentence). */
1587
+ function isSessionIdShaped(text) {
1588
+ try {
1589
+ return checkSessionId(text) !== undefined;
1590
+ }
1591
+ catch {
1592
+ return false;
1593
+ }
1594
+ }
1289
1595
  const requestHumanSub = defineCommand({
1290
1596
  meta: {
1291
1597
  name: 'request-human',
@@ -1293,26 +1599,51 @@ const requestHumanSub = defineCommand({
1293
1599
  },
1294
1600
  args: {
1295
1601
  ...commonArgs,
1296
- reason: {
1602
+ force: forceArg,
1603
+ message: {
1297
1604
  type: 'positional',
1298
1605
  // Checked in run, so a missing reason still fails with the --json envelope.
1299
1606
  required: false,
1300
- description: 'What the person should do, e.g. "Enter the 2FA code sent to the test phone"',
1607
+ description: 'What the person should do, e.g. "Enter the 2FA code sent to the test phone". With --reason, this is the session id',
1301
1608
  },
1302
1609
  id: idArg,
1610
+ reason: {
1611
+ type: 'string',
1612
+ description: 'What the person should do; then the session id may come first, as in every other command',
1613
+ },
1303
1614
  wait: waitForPersonArg,
1304
1615
  },
1305
1616
  async run({ args }) {
1306
1617
  const json = Boolean(args.json);
1307
1618
  await runDeviceCommand(json, async () => {
1308
- const reason = String(args.reason ?? '').trim();
1619
+ // `<reason> [id]`, or `[id] --reason <reason>`.
1620
+ const byFlag = typeof args.reason === 'string' ? args.reason : undefined;
1621
+ let given = args.message;
1622
+ let sessionId = args.id;
1623
+ if (byFlag !== undefined) {
1624
+ if (given !== undefined && sessionId !== undefined) {
1625
+ throw new CliError('With --reason, give at most one argument: the session id.');
1626
+ }
1627
+ sessionId ??= given;
1628
+ given = byFlag;
1629
+ }
1630
+ const reason = String(given ?? '').trim();
1309
1631
  if (!reason)
1310
1632
  throw new CliError('Say what the person should do, e.g. dcd device request-human "Enter the 2FA code".');
1311
1633
  if (reason.length > 500)
1312
1634
  throw new CliError('The reason is too long: keep it to 500 characters.');
1313
1635
  const ctx = await context(args);
1314
- const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
1315
- let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason);
1636
+ // `request-human brave-teal-otter` meant the session, not a reason:
1637
+ // sent, it would ask a person to "brave-teal-otter" and hold the
1638
+ // session for them.
1639
+ if (byFlag === undefined && sessionId === undefined && isSessionIdShaped(reason)) {
1640
+ const { sessions } = await DeviceGateway.list(ctx.apiUrl, ctx.auth);
1641
+ if (sessions.some((s) => s.id === reason)) {
1642
+ throw new CliError(`"${reason}" is a session id, not what the person should do. Say what they should do: dcd device request-human ${reason} --reason "Enter the 2FA code".`, DEVICE_EXIT.usage);
1643
+ }
1644
+ }
1645
+ const id = await resolveSessionId(ctx.apiUrl, ctx.auth, sessionId);
1646
+ let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason, Boolean(args.force));
1316
1647
  ctx.progress(ui.success(`Asked for a person on ${id}`));
1317
1648
  if (args.wait)
1318
1649
  response = await waitForHandBack(ctx, id, response);
@@ -1356,7 +1687,10 @@ const artifactsSub = defineCommand({
1356
1687
  },
1357
1688
  args: {
1358
1689
  ...commonArgs,
1359
- id: idArg,
1690
+ id: {
1691
+ ...idArg,
1692
+ description: 'Session id, e.g. brave-teal-otter. Optional: your most recent session, open or ended.',
1693
+ },
1360
1694
  output: {
1361
1695
  type: 'string',
1362
1696
  alias: ['o'],
@@ -1372,7 +1706,8 @@ const artifactsSub = defineCommand({
1372
1706
  const json = Boolean(args.json);
1373
1707
  await runDeviceCommand(json, async () => {
1374
1708
  const ctx = await context(args);
1375
- const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
1709
+ // Most often run just after `stop`: your latest session, ended or not.
1710
+ const id = await resolveRecentSessionId(ctx.apiUrl, ctx.auth, args.id);
1376
1711
  const { pages, session } = await fetchAllArtifacts(ctx.apiUrl, ctx.auth, id);
1377
1712
  const files = planArtifactFiles(pages);
1378
1713
  const pending = pendingArtifacts(pages);
@@ -1429,32 +1764,75 @@ const artifactsSub = defineCommand({
1429
1764
  });
1430
1765
  },
1431
1766
  });
1767
+ const subCommands = {
1768
+ start: strictFlags(startSub),
1769
+ list: strictFlags(listSub),
1770
+ status: strictFlags(statusSub),
1771
+ stop: strictFlags(stopSub),
1772
+ install: strictFlags(installSub),
1773
+ launch: strictFlags(launchSub),
1774
+ tap: strictFlags(tapSub),
1775
+ type: strictFlags(typeSub),
1776
+ swipe: strictFlags(swipeSub),
1777
+ 'press-key': strictFlags(pressKeySub),
1778
+ 'open-link': strictFlags(openLinkSub),
1779
+ 'set-location': strictFlags(setLocationSub),
1780
+ models: strictFlags(modelsSub),
1781
+ inspect: strictFlags(inspectSub),
1782
+ screenshot: strictFlags(screenshotSub),
1783
+ run: strictFlags(runSub),
1784
+ logs: strictFlags(logsSub),
1785
+ open: strictFlags(openSub),
1786
+ artifacts: strictFlags(artifactsSub),
1787
+ 'request-human': strictFlags(requestHumanSub),
1788
+ human: strictFlags(humanSub),
1789
+ };
1790
+ /** The MCP and API names of things `dcd device` calls by another name. */
1791
+ const OTHER_NAMES = {
1792
+ get_device_status: 'status',
1793
+ get_human_status: 'human',
1794
+ get_logs: 'logs',
1795
+ input_text: 'type',
1796
+ inspect_screen: 'inspect',
1797
+ install_app: 'install',
1798
+ launch_app: 'launch',
1799
+ list_devices: 'list',
1800
+ start_device: 'start',
1801
+ stop_device: 'stop',
1802
+ take_screenshot: 'screenshot',
1803
+ tap_on: 'tap',
1804
+ };
1805
+ /**
1806
+ * The usage error for `dcd device <name>` when there is no such subcommand,
1807
+ * with the one meant: `press_key` is `press-key` here.
1808
+ */
1809
+ export function unknownSubcommandError(name) {
1810
+ const names = Object.keys(subCommands);
1811
+ if (name === undefined) {
1812
+ return new CliError(`Name a command: ${names.join(', ')}. See \`dcd device --help\`.`, DEVICE_EXIT.usage);
1813
+ }
1814
+ const dashed = name.replaceAll('_', '-').toLowerCase();
1815
+ const meant = OTHER_NAMES[name] ?? (names.includes(dashed) ? dashed : undefined);
1816
+ return new CliError(`Unknown command "${name}".${meant ? ` Did you mean \`dcd device ${meant}\`?` : ''} The commands are: ${names.join(', ')}.`, DEVICE_EXIT.usage);
1817
+ }
1432
1818
  export const deviceCommand = defineCommand({
1433
1819
  meta: {
1434
1820
  name: 'device',
1435
1821
  description: 'Cloud devices you (or an AI agent) can lease, drive and release [beta]',
1436
1822
  },
1437
- subCommands: {
1438
- start: startSub,
1439
- list: listSub,
1440
- status: statusSub,
1441
- stop: stopSub,
1442
- install: installSub,
1443
- launch: launchSub,
1444
- tap: tapSub,
1445
- type: typeSub,
1446
- swipe: swipeSub,
1447
- 'press-key': pressKeySub,
1448
- 'open-link': openLinkSub,
1449
- 'set-location': setLocationSub,
1450
- models: modelsSub,
1451
- inspect: inspectSub,
1452
- screenshot: screenshotSub,
1453
- run: runSub,
1454
- logs: logsSub,
1455
- open: openSub,
1456
- artifacts: artifactsSub,
1457
- 'request-human': requestHumanSub,
1458
- human: humanSub,
1823
+ // Before citty looks the subcommand up: an unknown one under --json gets
1824
+ // the device envelope (exit 1), not the top-level `{ status, error }`.
1825
+ async setup({ rawArgs }) {
1826
+ const name = rawArgs.find((arg) => !arg.startsWith('-'));
1827
+ if (name !== undefined && name in subCommands)
1828
+ return;
1829
+ const json = rawArgs.includes('--json') || rawArgs.includes('--json=true');
1830
+ // A person who typed just `dcd device` gets citty's usage, with the list.
1831
+ if (name === undefined && !json)
1832
+ return;
1833
+ await runDeviceCommand(json, async () => {
1834
+ throw unknownSubcommandError(name);
1835
+ });
1459
1836
  },
1837
+ subCommands,
1460
1838
  });