@devicecloud.dev/dcd 5.13.0 → 5.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -117,6 +117,7 @@ It signs in the same way as the CLI: with your `dcd login` session, which it ren
117
117
  | `dcd_list_runs` | List recent test runs (filter by name/date, paginated) |
118
118
  | `dcd_get_status` | Get the status + per-test results of a run |
119
119
  | `dcd_download_artifacts` | Download a run's artifacts/report to disk |
120
+ | `dcd_get_team_settings` | Read your team's settings: concurrency, test runtime, integrations and more |
120
121
  | `dcd_run_cloud_test` | Submit a flow to run on the cloud (**billable**) |
121
122
 
122
123
  By default `dcd_run_cloud_test` is async: it returns an `uploadId` immediately, which you poll with `dcd_get_status`. Pass `wait: true` (bounded by `waitTimeoutSeconds`) to block until completion, or `dryRun: true` to preview the flows without submitting.
@@ -598,6 +598,33 @@ function percentArg(value, flag) {
598
598
  }
599
599
  return n;
600
600
  }
601
+ /** The longest a tap may wait for its target, as the API allows. */
602
+ const MAX_TAP_TIMEOUT_SECONDS = 60;
603
+ /** Seconds from a flag value, from 0 to `max`, or a usage error. Undefined when the flag was not given. */
604
+ function secondsArg(value, flag, max) {
605
+ if (value === undefined)
606
+ return undefined;
607
+ const n = typeof value === 'number' ? value : Number(value);
608
+ if (typeof value === 'boolean' || value === '' || !Number.isFinite(n) || n < 0 || n > max) {
609
+ throw new CliError(`--${flag} must be a number of seconds from 0 to ${max}.`, 1);
610
+ }
611
+ return n;
612
+ }
613
+ /** Decimal degrees from a flag value, within `limit` either way, or a usage error. */
614
+ function degreesArg(value, flag, limit) {
615
+ const n = typeof value === 'number' ? value : Number(value);
616
+ if (value === undefined ||
617
+ typeof value === 'boolean' ||
618
+ (typeof value === 'string' && value.trim() === '') ||
619
+ !Number.isFinite(n) ||
620
+ n < -limit ||
621
+ n > limit) {
622
+ throw new CliError(`--${flag} must be a number from -${limit} to ${limit} (decimal degrees).`, 1);
623
+ }
624
+ return n;
625
+ }
626
+ /** A link with a scheme and nothing a shell or a URL would split on. A session id has no colon. */
627
+ const LINK = /^[A-Za-z][A-Za-z0-9+.-]*:\S+$/;
601
628
  /** "x,y" (percentages) from a flag value, or a usage error. */
602
629
  function pointArg(value, flag) {
603
630
  const parts = typeof value === 'string' ? value.split(',') : [];
@@ -636,6 +663,10 @@ const tapSub = defineCommand({
636
663
  rid: { type: 'string', description: 'The element\'s resource id (rid in `dcd device inspect`)' },
637
664
  x: { type: 'string', description: 'With --y: a point, as percentages of the screen (0-100)' },
638
665
  y: { type: 'string', description: 'See --x' },
666
+ timeout: {
667
+ type: 'string',
668
+ description: `With --text or --rid: seconds to wait for it to appear before failing (0-${MAX_TAP_TIMEOUT_SECONDS}, default 17; 0 looks once)`,
669
+ },
639
670
  maestro: maestroArg,
640
671
  },
641
672
  async run({ args }) {
@@ -649,10 +680,15 @@ const tapSub = defineCommand({
649
680
  if (targets !== 1) {
650
681
  throw new CliError('tap takes exactly one target: --text, --rid, or --x and --y.', 1);
651
682
  }
683
+ const timeoutSeconds = secondsArg(args.timeout, 'timeout', MAX_TAP_TIMEOUT_SECONDS);
684
+ if (timeoutSeconds !== undefined && args.text === undefined && args.rid === undefined) {
685
+ throw new CliError('tap --timeout goes with --text or --rid: a point has nothing to wait for.', 1);
686
+ }
687
+ const wait = timeoutSeconds === undefined ? {} : { timeoutSeconds };
652
688
  const body = args.text !== undefined
653
- ? { type: 'tap', text: String(args.text) }
689
+ ? { type: 'tap', text: String(args.text), ...wait }
654
690
  : args.rid !== undefined
655
- ? { type: 'tap', id: String(args.rid) }
691
+ ? { type: 'tap', id: String(args.rid), ...wait }
656
692
  : { type: 'tap', x: percentArg(args.x, 'x'), y: percentArg(args.y, 'y') };
657
693
  const what = args.text !== undefined
658
694
  ? `"${String(args.text)}"`
@@ -759,6 +795,57 @@ const pressKeySub = defineCommand({
759
795
  });
760
796
  },
761
797
  });
798
+ const openLinkSub = defineCommand({
799
+ meta: { name: 'open-link', description: 'Open a link on the device: a deep link into an app, or a web link' },
800
+ args: {
801
+ ...commonArgs,
802
+ id: idArg,
803
+ // Not `required`, as with `type --text`: a missing link fails inside the envelope.
804
+ url: {
805
+ type: 'positional',
806
+ required: false,
807
+ description: 'The link with its scheme, e.g. myapp://path or https://example.com',
808
+ },
809
+ sensitive: {
810
+ type: 'boolean',
811
+ default: false,
812
+ description: 'The link is a secret (it carries a token): stored encrypted, never shown',
813
+ },
814
+ },
815
+ async run({ args }) {
816
+ const json = Boolean(args.json);
817
+ await runDeviceCommand(json, async () => {
818
+ let id = args.id;
819
+ let url = args.url;
820
+ // `dcd device open-link myapp://path`: the one positional is the link, not a session.
821
+ if (id && !url && id.includes(':'))
822
+ [id, url] = [undefined, id];
823
+ if (!url || !LINK.test(url)) {
824
+ throw new CliError('open-link takes a link with its scheme and no spaces, e.g. myapp://path or https://example.com.', 1);
825
+ }
826
+ 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` });
828
+ });
829
+ },
830
+ });
831
+ const setLocationSub = defineCommand({
832
+ meta: { name: 'set-location', description: "Set the device's GPS position, in decimal degrees" },
833
+ args: {
834
+ ...commonArgs,
835
+ id: idArg,
836
+ latitude: { type: 'string', description: 'Decimal degrees, north positive (-90 to 90)' },
837
+ longitude: { type: 'string', description: 'Decimal degrees, east positive (-180 to 180)' },
838
+ },
839
+ async run({ args }) {
840
+ const json = Boolean(args.json);
841
+ await runDeviceCommand(json, async () => {
842
+ // South and west are negative. citty keeps a value that is a number, minus sign and all.
843
+ const latitude = degreesArg(args.latitude, 'latitude', 90);
844
+ 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' });
846
+ });
847
+ },
848
+ });
762
849
  const modelsSub = defineCommand({
763
850
  meta: { name: 'models', description: 'The devices a session can ask for' },
764
851
  args: {
@@ -1358,6 +1445,8 @@ export const deviceCommand = defineCommand({
1358
1445
  type: typeSub,
1359
1446
  swipe: swipeSub,
1360
1447
  'press-key': pressKeySub,
1448
+ 'open-link': openLinkSub,
1449
+ 'set-location': setLocationSub,
1361
1450
  models: modelsSub,
1362
1451
  inspect: inspectSub,
1363
1452
  screenshot: screenshotSub,
@@ -0,0 +1,20 @@
1
+ import type { TeamSettings } from '../types/domain/team-settings.types.js';
2
+ /** Human-readable output; one section per area, as in the console. */
3
+ export declare function renderTeamSettings(settings: TeamSettings): string[];
4
+ export declare const settingsCommand: import("citty").CommandDef<{
5
+ readonly json: {
6
+ readonly type: "boolean";
7
+ readonly description: "Output the result as a single JSON object on stdout";
8
+ };
9
+ readonly 'api-key': {
10
+ readonly type: "string";
11
+ readonly alias: ["apiKey"];
12
+ readonly description: "API key for devicecloud.dev (find this in the console UI). You can also set the DEVICE_CLOUD_API_KEY environment variable.";
13
+ };
14
+ readonly 'api-url': {
15
+ readonly type: "string";
16
+ readonly alias: ["apiURL", "apiUrl"];
17
+ readonly description: "API base URL (defaults to the URL stored by `dcd login`, else prod)";
18
+ };
19
+ }>;
20
+ export default settingsCommand;
@@ -0,0 +1,145 @@
1
+ /**
2
+ * `dcd settings` — prints the active team's settings: concurrency, test
3
+ * runtime, sign-in requirement, retry escalation, overage limit and which
4
+ * integrations are connected. Read-only; change settings in the console.
5
+ *
6
+ * Owner/admin settings come back null for a standard member (the API sets
7
+ * `restricted`), and are shown as such rather than as "off".
8
+ */
9
+ import { defineCommand } from 'citty';
10
+ import { apiFlags } from '../config/flags/api.flags.js';
11
+ import { jsonFlag } from '../config/flags/output.flags.js';
12
+ import { ApiGateway } from '../gateways/api-gateway.js';
13
+ import { resolveAuth } from '../utils/auth.js';
14
+ import { logger } from '../utils/cli.js';
15
+ import { resolveApiUrl } from '../utils/config-store.js';
16
+ import { colors, formatId } from '../utils/styling.js';
17
+ import { ui } from '../utils/ui.js';
18
+ const OWNER_OR_ADMIN = colors.dim('owner or admin only');
19
+ const PLATFORM_LABELS = { android: 'Android', ios: 'iOS' };
20
+ // The console's wording for each level.
21
+ const SIGN_IN_LABELS = {
22
+ off: 'off',
23
+ passkey: 'a passkey',
24
+ passkey_and_code: 'a passkey and a code',
25
+ two_factor: 'two-factor',
26
+ };
27
+ const ESCALATION_TARGET_LABELS = { gpu1: 'GPU', m1: 'M1' };
28
+ function limit(min, max) {
29
+ return max <= 0 ? colors.dim('not enabled') : `min ${min} · max ${max}`;
30
+ }
31
+ function connected(value) {
32
+ return value ? 'connected' : colors.dim('not connected');
33
+ }
34
+ function signInRequirement(settings) {
35
+ if (settings.signInRequirement === null)
36
+ return OWNER_OR_ADMIN;
37
+ return SIGN_IN_LABELS[settings.signInRequirement] ?? settings.signInRequirement;
38
+ }
39
+ function retryEscalation(settings) {
40
+ const escalation = settings.retryEscalation;
41
+ if (escalation === null)
42
+ return OWNER_OR_ADMIN;
43
+ if (!escalation.available || !escalation.target)
44
+ return colors.dim('not available');
45
+ const target = ESCALATION_TARGET_LABELS[escalation.target] ?? escalation.target;
46
+ return `${escalation.enabled ? 'on' : 'off'} · Android retries move to ${target} runners`;
47
+ }
48
+ function overage(settings) {
49
+ const value = settings.overage;
50
+ if (value === null)
51
+ return OWNER_OR_ADMIN;
52
+ if (!value.hasSubscription)
53
+ return colors.dim('no active subscription');
54
+ if (value.limitUsd === null)
55
+ return 'uncapped';
56
+ return `$${value.limitUsd} per billing period, on top of included credits`;
57
+ }
58
+ function concurrencyRows(settings) {
59
+ const { pools, runners } = settings.concurrency;
60
+ const fields = [
61
+ ...runners.map(({ max, min, platform, runnerType }) => [
62
+ `${PLATFORM_LABELS[platform] ?? platform} ${runnerType}`,
63
+ limit(min, max),
64
+ ]),
65
+ ...pools.map(({ max, min, name }) => [`${name} pool`, limit(min, max)]),
66
+ ];
67
+ if (fields.length === 0)
68
+ return [colors.dim('none')];
69
+ const shared = pools.map(({ members, name }) => `${name} pool is shared by ${members
70
+ .map((m) => `${PLATFORM_LABELS[m.platform] ?? m.platform} ${m.runnerType}`)
71
+ .join(' and ')}`);
72
+ return [
73
+ ...ui.fields(fields),
74
+ ...shared.map((line) => ui.note(line)),
75
+ ui.note('min: always available · max: when capacity allows'),
76
+ ];
77
+ }
78
+ /** Human-readable output; one section per area, as in the console. */
79
+ export function renderTeamSettings(settings) {
80
+ const { extendedMinutes, defaultMinutes } = settings.testRuntime;
81
+ const lines = [
82
+ ui.section('Team'),
83
+ ui.branch(ui.fields([
84
+ ['name', settings.name ?? colors.dim('(unnamed)')],
85
+ ['org id', formatId(String(settings.orgId))],
86
+ ['sign-in requirement', signInRequirement(settings)],
87
+ ])),
88
+ ui.section('Concurrency'),
89
+ ui.branch(concurrencyRows(settings)),
90
+ ui.section('Test Runtime'),
91
+ ui.branch(ui.fields([
92
+ ['default', `${defaultMinutes} min per flow`],
93
+ [
94
+ 'extended',
95
+ extendedMinutes === null
96
+ ? colors.dim('off')
97
+ : `${extendedMinutes} min per flow with EXTENDED_RUNTIME, charged at twice the rate`,
98
+ ],
99
+ ])),
100
+ ui.section('Retries & Billing'),
101
+ ui.branch(ui.fields([
102
+ ['retry escalation', retryEscalation(settings)],
103
+ ['overage limit', overage(settings)],
104
+ ])),
105
+ ui.section('Integrations'),
106
+ ui.branch(ui.fields([
107
+ ['webhook', connected(settings.integrations.webhook)],
108
+ ['slack', connected(settings.integrations.slack)],
109
+ ['github', connected(settings.integrations.github)],
110
+ ])),
111
+ ];
112
+ if (settings.restricted) {
113
+ lines.push('', ui.note('Some settings are shown to team owners and admins only.'));
114
+ }
115
+ return lines;
116
+ }
117
+ export const settingsCommand = defineCommand({
118
+ meta: {
119
+ name: 'settings',
120
+ description: "Show your team's settings (read-only)",
121
+ },
122
+ args: {
123
+ ...apiFlags,
124
+ json: jsonFlag,
125
+ },
126
+ async run({ args }) {
127
+ const apiKeyFlag = args['api-key'];
128
+ const apiUrl = resolveApiUrl(args['api-url']);
129
+ const json = Boolean(args.json);
130
+ try {
131
+ const auth = await resolveAuth({ apiKeyFlag });
132
+ const settings = await ApiGateway.getTeamSettings(apiUrl, auth);
133
+ if (json) {
134
+ logger.json(settings);
135
+ return;
136
+ }
137
+ for (const line of renderTeamSettings(settings))
138
+ logger.log(line);
139
+ }
140
+ catch (error) {
141
+ logger.error(error, { exit: 1, json });
142
+ }
143
+ },
144
+ });
145
+ export default settingsCommand;
@@ -1,7 +1,7 @@
1
1
  import { defineCommand } from 'citty';
2
2
  import { apiFlags } from '../config/flags/api.flags.js';
3
3
  import { resolveFrontendUrl } from '../config/environments.js';
4
- import { ApiGateway } from '../gateways/api-gateway.js';
4
+ import { ApiError, ApiGateway } from '../gateways/api-gateway.js';
5
5
  import { formatDurationSeconds } from '../methods.js';
6
6
  import { resolveAuth } from '../utils/auth.js';
7
7
  import { CliError, logger } from '../utils/cli.js';
@@ -13,6 +13,9 @@ import { ui } from '../utils/ui.js';
13
13
  function isClientApiError(error) {
14
14
  if (!error)
15
15
  return false;
16
+ if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
17
+ return true;
18
+ }
16
19
  return (error.message.includes('Invalid request:') ||
17
20
  error.message.includes('Resource not found') ||
18
21
  error.message.includes('Authentication failed') ||
@@ -1,15 +1,27 @@
1
+ import { type BundleFallbackTelemetry } from '../services/telemetry.service.js';
1
2
  import { TAppMetadata } from '../types.js';
2
3
  import type { AuthContext } from '../types/domain/auth.types.js';
3
4
  import type { LiveCommandStatus, LiveExecResult, LiveSession, LiveSessionSummary } from '../types/domain/live.types.js';
5
+ import type { TeamSettings } from '../types/domain/team-settings.types.js';
4
6
  import { components, paths } from '../types/generated/schema.types.js';
7
+ /** What went wrong in a bundle attempt, minus the route/timing added later. */
8
+ type BundleFailure = Omit<BundleFallbackTelemetry, 'duration_ms' | 'route' | 'upload_id'>;
5
9
  /**
6
10
  * Error thrown for non-OK API responses, carrying the HTTP status so callers
7
11
  * can branch on auth failures etc. without string matching.
8
12
  */
9
13
  export declare class ApiError extends Error {
10
14
  status: number;
11
- constructor(message: string, status: number);
15
+ /** The API's machine-readable error code, such as `API_KEY_SCOPE`, when it sent one. */
16
+ code?: string;
17
+ constructor(message: string, status: number, code?: string);
12
18
  }
19
+ /**
20
+ * API errors no retry can clear: an API key whose access doesn't cover the
21
+ * call (`API_KEY_SCOPE`), or an upload the key can't see (`UPLOAD_NOT_FOUND`).
22
+ * A key's access is fixed when it is created.
23
+ */
24
+ export declare function isPermanentApiError(error: unknown): error is ApiError;
13
25
  type ResultsResponse = paths['/results/{uploadId}']['get']['responses']['200']['content']['application/json'];
14
26
  /**
15
27
  * The last results body a poll loop received and the ETag it came with, so
@@ -57,6 +69,11 @@ export declare const ApiGateway: {
57
69
  * surface through that inline path instead.
58
70
  */
59
71
  tryBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string): Promise<boolean>;
72
+ /**
73
+ * One bundle-download attempt. Resolves `true` once the ZIP is on disk, or
74
+ * with the reason it fell through, for {@link tryBundleDownload} to record.
75
+ */
76
+ attemptBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string): Promise<BundleFailure | true>;
60
77
  /**
61
78
  * Look for an already-uploaded binary to skip re-uploading.
62
79
  *
@@ -144,6 +161,11 @@ export declare const ApiGateway: {
144
161
  status: "CANCELLED" | "FAILED" | "PASSED" | "PENDING";
145
162
  }>;
146
163
  }>;
164
+ /**
165
+ * The team's settings (`GET /org/settings`). A 404 means the API predates
166
+ * the endpoint, so it gets a message that says so rather than "not found".
167
+ */
168
+ getTeamSettings(baseUrl: string, auth: AuthContext): Promise<TeamSettings>;
147
169
  listUploads(baseUrl: string, auth: AuthContext, options?: {
148
170
  from?: string;
149
171
  limit?: number;
@@ -3,18 +3,49 @@ import { homedir } from 'node:os';
3
3
  import * as path from 'node:path';
4
4
  import { Readable } from 'node:stream';
5
5
  import { pipeline } from 'node:stream/promises';
6
+ import { telemetry, } from '../services/telemetry.service.js';
7
+ /** Expand a leading `~` to the home directory, as the download paths allow. */
8
+ function expandHome(p) {
9
+ return p.replace(/^~(?=$|\/|\\)/, homedir());
10
+ }
11
+ /** Name, message and low-level code (e.g. ECONNRESET) of a thrown error. */
12
+ function errorDetail(error) {
13
+ const err = error instanceof Error ? error : new Error(String(error));
14
+ const cause = err.cause;
15
+ const code = cause?.code ?? err.code;
16
+ return {
17
+ error_code: typeof code === 'string' ? code : undefined,
18
+ error_message: err.message.slice(0, 300),
19
+ error_name: err.name,
20
+ };
21
+ }
22
+ function failure(reason, extra = {}) {
23
+ return { reason, ...extra };
24
+ }
6
25
  /**
7
26
  * Error thrown for non-OK API responses, carrying the HTTP status so callers
8
27
  * can branch on auth failures etc. without string matching.
9
28
  */
10
29
  export class ApiError extends Error {
11
30
  status;
12
- constructor(message, status) {
31
+ /** The API's machine-readable error code, such as `API_KEY_SCOPE`, when it sent one. */
32
+ code;
33
+ constructor(message, status, code) {
13
34
  super(message);
14
35
  this.name = 'ApiError';
15
36
  this.status = status;
37
+ this.code = code;
16
38
  }
17
39
  }
40
+ /**
41
+ * API errors no retry can clear: an API key whose access doesn't cover the
42
+ * call (`API_KEY_SCOPE`), or an upload the key can't see (`UPLOAD_NOT_FOUND`).
43
+ * A key's access is fixed when it is created.
44
+ */
45
+ export function isPermanentApiError(error) {
46
+ return (error instanceof ApiError &&
47
+ (error.code === 'API_KEY_SCOPE' || error.code === 'UPLOAD_NOT_FOUND'));
48
+ }
18
49
  /**
19
50
  * Parses a successful response body as JSON, wrapping parse failures in a
20
51
  * descriptive error (a 200 with an HTML body otherwise surfaces as a bare
@@ -71,10 +102,16 @@ export const ApiGateway = {
71
102
  async handleApiError(res, operation) {
72
103
  const errorText = await res.text();
73
104
  let userMessage;
105
+ let code;
74
106
  // Parse common API error formats
75
107
  try {
76
108
  const errorData = JSON.parse(errorText);
77
109
  userMessage = errorData.message || errorData.error || errorText;
110
+ // The API's own codes are UPPER_SNAKE_CASE. Its framework fills `error`
111
+ // with the HTTP reason ("Forbidden") otherwise, which is not a code.
112
+ if (typeof errorData.error === 'string' && /^[A-Z][A-Z0-9_]+$/.test(errorData.error)) {
113
+ code = errorData.error;
114
+ }
78
115
  }
79
116
  catch {
80
117
  userMessage = errorText;
@@ -82,7 +119,7 @@ export const ApiGateway = {
82
119
  // Add context and improve readability
83
120
  switch (res.status) {
84
121
  case 400: {
85
- throw new ApiError(`Invalid request: ${userMessage}`, 400);
122
+ throw new ApiError(`Invalid request: ${userMessage}`, 400, code);
86
123
  }
87
124
  case 401: {
88
125
  // Auth-mode-neutral: the CLI accepts both API keys and Bearer sessions.
@@ -92,9 +129,16 @@ export const ApiGateway = {
92
129
  if (userMessage) {
93
130
  message += `\nServer response: ${userMessage}`;
94
131
  }
95
- throw new ApiError(message, 401);
132
+ throw new ApiError(message, 401, code);
96
133
  }
97
134
  case 403: {
135
+ // A valid key whose access is limited, such as a CI-only key. The
136
+ // revoked-key advice below would send the user looking in the wrong
137
+ // place, and the server's message already names what to use instead.
138
+ if (code === 'API_KEY_SCOPE') {
139
+ throw new ApiError(`Access denied. ${userMessage}\n` +
140
+ `An API key's access is chosen when the key is created, under Settings → API keys in the console.`, 403, code);
141
+ }
98
142
  // For 403, use the server's error message directly as it's now detailed
99
143
  // If the message suggests an API key issue, provide additional guidance
100
144
  if (userMessage.toLowerCase().includes('api key')) {
@@ -102,23 +146,23 @@ export const ApiGateway = {
102
146
  ` 1. Verify DEVICE_CLOUD_API_KEY environment variable is set\n` +
103
147
  ` 2. Check you're using the correct API key for this environment\n` +
104
148
  ` 3. Ensure the API key hasn't been deleted or revoked\n` +
105
- ` 4. Confirm you're connecting to the correct API URL`, 403);
149
+ ` 4. Confirm you're connecting to the correct API URL`, 403, code);
106
150
  }
107
- throw new ApiError(`Access denied. ${userMessage}`, 403);
151
+ throw new ApiError(`Access denied. ${userMessage}`, 403, code);
108
152
  }
109
153
  case 404: {
110
- throw new ApiError(`Resource not found. ${userMessage}`, 404);
154
+ throw new ApiError(`Resource not found. ${userMessage}`, 404, code);
111
155
  }
112
156
  case 429: {
113
- throw new ApiError(`Rate limit exceeded. Please try again later. (${operation})`, 429);
157
+ throw new ApiError(`Rate limit exceeded. Please try again later. (${operation})`, 429, code);
114
158
  }
115
159
  case 500: {
116
- throw new ApiError(`Server error occurred. Please try again or contact support. (${operation})`, 500);
160
+ throw new ApiError(`Server error occurred. Please try again or contact support. (${operation})`, 500, code);
117
161
  }
118
162
  default: {
119
163
  // `operation` is already phrased as "Failed to …", so don't append
120
164
  // another "failed" here (avoids "Failed to execute test failed: …").
121
- throw new ApiError(`${operation}: ${userMessage} (HTTP ${res.status})`, res.status);
165
+ throw new ApiError(`${operation}: ${userMessage} (HTTP ${res.status})`, res.status, code);
122
166
  }
123
167
  }
124
168
  },
@@ -132,7 +176,7 @@ export const ApiGateway = {
132
176
  throw new Error(`${operation}: server response contained no body to download`);
133
177
  }
134
178
  // Handle tilde expansion for home directory
135
- const expandedPath = destinationPath.replace(/^~(?=$|\/|\\)/, homedir());
179
+ const expandedPath = expandHome(destinationPath);
136
180
  // Create directory structure if it doesn't exist
137
181
  const directory = path.dirname(expandedPath);
138
182
  if (directory !== '.') {
@@ -159,6 +203,27 @@ export const ApiGateway = {
159
203
  * surface through that inline path instead.
160
204
  */
161
205
  async tryBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation) {
206
+ const startedAt = Date.now();
207
+ const outcome = await this.attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation);
208
+ if (outcome === true)
209
+ return true;
210
+ // The fallback is silent to the user (the inline download still delivers
211
+ // the file), so this event is the only record of why the bundle path was
212
+ // skipped.
213
+ const route = /\/results\/([^/?]+)\/([a-z-]+)/.exec(manifestEndpoint);
214
+ telemetry.recordBundleFallback({
215
+ ...outcome,
216
+ duration_ms: Date.now() - startedAt,
217
+ route: route?.[2] ?? manifestEndpoint.split('?')[0],
218
+ upload_id: route?.[1],
219
+ });
220
+ return false;
221
+ },
222
+ /**
223
+ * One bundle-download attempt. Resolves `true` once the ZIP is on disk, or
224
+ * with the reason it fell through, for {@link tryBundleDownload} to record.
225
+ */
226
+ async attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation) {
162
227
  let manifestRes;
163
228
  try {
164
229
  manifestRes = await fetch(`${baseUrl}${manifestEndpoint}`, {
@@ -166,23 +231,23 @@ export const ApiGateway = {
166
231
  method: 'GET',
167
232
  });
168
233
  }
169
- catch {
170
- return false;
234
+ catch (error) {
235
+ return failure('manifest_request_failed', errorDetail(error));
171
236
  }
172
237
  // 501 => this deployment has no bundle delivery; any other non-OK => let
173
238
  // the inline path re-request and surface the real error.
174
239
  if (!manifestRes.ok) {
175
- return false;
240
+ return failure(manifestRes.status === 501 ? 'manifest_unavailable' : 'manifest_http_error', { status: manifestRes.status });
176
241
  }
177
242
  let bundle;
178
243
  try {
179
244
  bundle = (await manifestRes.json());
180
245
  }
181
- catch {
182
- return false;
246
+ catch (error) {
247
+ return failure('manifest_invalid_json', errorDetail(error));
183
248
  }
184
249
  if (!bundle?.bundleUrl || !bundle?.manifest || !bundle?.sig) {
185
- return false;
250
+ return failure('manifest_incomplete');
186
251
  }
187
252
  let zipRes;
188
253
  try {
@@ -193,21 +258,34 @@ export const ApiGateway = {
193
258
  method: 'POST',
194
259
  });
195
260
  }
196
- catch {
197
- return false;
261
+ catch (error) {
262
+ return failure('bundle_request_failed', errorDetail(error));
198
263
  }
199
264
  if (!zipRes.ok) {
200
- return false;
265
+ return failure('bundle_http_error', { status: zipRes.status });
201
266
  }
202
267
  // A mid-stream failure (dropped/truncated connection) or a null body on an
203
268
  // otherwise-OK response throws here — fall back to the inline path rather
204
269
  // than let it escape past the caller's fallback. The inline path re-opens
205
270
  // the destination with flags: 'w', truncating any partial file left behind.
271
+ // Count bytes as they arrive, so a broken stream records how far it got.
272
+ // (The file's size on disk understates it: the write stream is torn down
273
+ // with buffered bytes still unflushed.)
274
+ let bytesReceived = 0;
275
+ const counted = zipRes.body?.pipeThrough(new TransformStream({
276
+ transform(chunk, controller) {
277
+ bytesReceived += chunk.byteLength;
278
+ controller.enqueue(chunk);
279
+ },
280
+ }));
206
281
  try {
207
- await this.streamResponseToFile(zipRes, destinationPath, operation);
282
+ await this.streamResponseToFile(counted ? new Response(counted) : zipRes, destinationPath, operation);
208
283
  }
209
- catch {
210
- return false;
284
+ catch (error) {
285
+ return failure('bundle_stream_failed', {
286
+ ...errorDetail(error),
287
+ bytes_received: bytesReceived,
288
+ });
211
289
  }
212
290
  return true;
213
291
  },
@@ -449,6 +527,29 @@ export const ApiGateway = {
449
527
  throw error;
450
528
  }
451
529
  },
530
+ /**
531
+ * The team's settings (`GET /org/settings`). A 404 means the API predates
532
+ * the endpoint, so it gets a message that says so rather than "not found".
533
+ */
534
+ async getTeamSettings(baseUrl, auth) {
535
+ const url = `${baseUrl}/org/settings`;
536
+ try {
537
+ const response = await fetch(url, { headers: { ...auth.headers } });
538
+ if (response.status === 404) {
539
+ throw new ApiError("This DeviceCloud API doesn't support reading team settings yet.", 404);
540
+ }
541
+ if (!response.ok) {
542
+ await this.handleApiError(response, 'Failed to get team settings');
543
+ }
544
+ return await parseJsonResponse(response, 'Failed to get team settings');
545
+ }
546
+ catch (error) {
547
+ if (error instanceof TypeError && error.message === 'fetch failed') {
548
+ throw this.enhanceFetchError(error, url);
549
+ }
550
+ throw error;
551
+ }
552
+ },
452
553
  async listUploads(baseUrl, auth, options = {}) {
453
554
  const queryParams = new URLSearchParams();
454
555
  if (options.name) {
@@ -1,9 +1,15 @@
1
- import type { DcdEnvName } from '../config/environments.js';
1
+ /**
2
+ * Refreshes a `dcd login` session through the dcd API's
3
+ * `POST /cli-login/refresh`, which calls Supabase Auth on the CLI's behalf.
4
+ * The CLI holds no Supabase key for this.
5
+ *
6
+ * The login itself is the PKCE rendezvous in src/commands/login.ts.
7
+ */
2
8
  import type { StoredSession } from '../utils/config-store.js';
3
9
  /**
4
- * Thrown when a session refresh fails. `definitive` distinguishes "Supabase
5
- * rejected this refresh token" (revoked, already used, malformed — re-login
6
- * is the only fix) from transient failures (network, GoTrue 5xx) where the
10
+ * Thrown when a session refresh fails. `definitive` distinguishes "this
11
+ * refresh token was rejected" (revoked, already used, expired — re-login is
12
+ * the only fix) from transient failures (network, 5xx, rate limit) where the
7
13
  * stored session may still be good on the next attempt.
8
14
  */
9
15
  export declare class SessionRefreshError extends Error {
@@ -23,5 +29,10 @@ export interface RefreshedSession {
23
29
  user_id: string;
24
30
  }
25
31
  export declare const CliAuthGateway: {
26
- refresh(supabaseUrl: string, env: DcdEnvName, session: StoredSession): Promise<RefreshedSession>;
32
+ /**
33
+ * @param apiUrl The API the session was minted by (the stored `api_url`)
34
+ * @param session The stored session, whose refresh token is spent on success
35
+ * @param headers Extra headers, such as the CLI's identity headers
36
+ */
37
+ refresh(apiUrl: string, session: StoredSession, headers?: Record<string, string>): Promise<RefreshedSession>;
27
38
  };
@@ -1,16 +1,7 @@
1
1
  /**
2
- * Supabase session operations for the CLI: refresh an expired access token
3
- * and sign-out (best-effort revocation on the Supabase side).
4
- *
5
- * Does not talk to the dcd API — the dcd-side session exchange lives in the
6
- * login command's PKCE rendezvous flow (see src/commands/login.ts).
7
- */
8
- import { createClient, isAuthApiError, isAuthSessionMissingError } from '@supabase/supabase-js';
9
- import { getSupabaseKey } from '../config/supabase-key.js';
10
- /**
11
- * Thrown when a session refresh fails. `definitive` distinguishes "Supabase
12
- * rejected this refresh token" (revoked, already used, malformed — re-login
13
- * is the only fix) from transient failures (network, GoTrue 5xx) where the
2
+ * Thrown when a session refresh fails. `definitive` distinguishes "this
3
+ * refresh token was rejected" (revoked, already used, expired — re-login is
4
+ * the only fix) from transient failures (network, 5xx, rate limit) where the
14
5
  * stored session may still be good on the next attempt.
15
6
  */
16
7
  export class SessionRefreshError extends Error {
@@ -39,52 +30,62 @@ const REFRESH_REFUSAL_MESSAGES = new Map([
39
30
  ['session_not_found', SIGNED_OUT],
40
31
  ['refresh_token_not_found', SIGNED_OUT],
41
32
  ]);
42
- function client(supabaseUrl, supabaseKey) {
43
- return createClient(supabaseUrl, supabaseKey, {
44
- auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
45
- });
46
- }
47
33
  export const CliAuthGateway = {
48
- async refresh(supabaseUrl, env, session) {
49
- let supabaseKey;
34
+ /**
35
+ * @param apiUrl The API the session was minted by (the stored `api_url`)
36
+ * @param session The stored session, whose refresh token is spent on success
37
+ * @param headers Extra headers, such as the CLI's identity headers
38
+ */
39
+ async refresh(apiUrl, session, headers = {}) {
40
+ let res;
50
41
  try {
51
- supabaseKey = await getSupabaseKey(env);
42
+ res = await fetch(`${apiUrl.replace(/\/$/, '')}/cli-login/refresh`, {
43
+ body: JSON.stringify({ refresh_token: session.refresh_token }),
44
+ headers: { ...headers, 'content-type': 'application/json' },
45
+ method: 'POST',
46
+ });
52
47
  }
53
48
  catch (error) {
54
- // Never definitive: the refresh token was not even tried, so the stored
55
- // session must survive for the next attempt.
49
+ // Never definitive: the token was not even tried.
56
50
  throw new SessionRefreshError(`Failed to refresh session: ${error.message}`, false);
57
51
  }
58
- const sb = client(supabaseUrl, supabaseKey);
59
- const { data, error } = await sb.auth.refreshSession({
60
- refresh_token: session.refresh_token,
61
- });
62
- if (error || !data.session || !data.user) {
63
- // 4xx from GoTrue means the token itself was rejected; anything else
64
- // (fetch failure, 5xx) could succeed on retry with the same token.
65
- // supabase-js turns GoTrue's `session_not_found` into an
66
- // AuthSessionMissingError rather than an AuthApiError (it throws the same
67
- // for an empty refresh token); only `dcd login` fixes either.
68
- const apiError = error != null && isAuthApiError(error) ? error : undefined;
69
- const sessionMissing = error != null && isAuthSessionMissingError(error);
70
- const definitive = sessionMissing ||
71
- (apiError !== undefined && apiError.status >= 400 && apiError.status < 500);
72
- const code = apiError?.code ?? (sessionMissing ? 'session_not_found' : undefined);
73
- const known = definitive && code ? REFRESH_REFUSAL_MESSAGES.get(code) : undefined;
74
- throw new SessionRefreshError(known ??
75
- `Failed to refresh session: ${error?.message ?? 'no session returned'}. ` +
76
- `Run \`dcd login\` again.`, definitive, code);
52
+ if (res.ok) {
53
+ let s;
54
+ try {
55
+ s = (await res.json());
56
+ }
57
+ catch {
58
+ // A 200 that is not JSON (a proxy page, say). The token may not have
59
+ // been spent, so keep the session and try again next time.
60
+ throw new SessionRefreshError('Failed to refresh session: response was not JSON', false);
61
+ }
62
+ if (!s.access_token || !s.refresh_token || !s.expires_at || !s.user_id) {
63
+ throw new SessionRefreshError('Failed to refresh session: incomplete response', false);
64
+ }
65
+ return {
66
+ access_token: s.access_token,
67
+ refresh_token: s.refresh_token,
68
+ expires_at: s.expires_at,
69
+ user_email: s.user_email || session.user_email,
70
+ user_id: s.user_id,
71
+ };
72
+ }
73
+ let body = {};
74
+ try {
75
+ body = (await res.json());
76
+ }
77
+ catch {
78
+ // Not JSON (a proxy page, say). The status alone decides.
77
79
  }
78
- const s = data.session;
79
- const u = data.user;
80
- if (!s.expires_at)
81
- throw new Error('Refreshed session is missing expires_at');
82
- return {
83
- access_token: s.access_token,
84
- refresh_token: s.refresh_token,
85
- expires_at: s.expires_at,
86
- user_email: u.email ?? session.user_email,
87
- user_id: u.id,
88
- };
80
+ const code = typeof body.error === 'string' ? body.error : undefined;
81
+ const reason = typeof body.message === 'string' && body.message ? body.message : `HTTP ${res.status}`;
82
+ // 401: Supabase Auth refused the token, and `error` is its code. 400: the
83
+ // API refused the request itself (an empty token). Only `dcd login` fixes
84
+ // either. Anything else (404 from an API without this route, 429, 5xx)
85
+ // may work later with the same token, so it must survive.
86
+ const definitive = res.status === 401 || res.status === 400;
87
+ const known = definitive && code ? REFRESH_REFUSAL_MESSAGES.get(code) : undefined;
88
+ throw new SessionRefreshError(known ??
89
+ `Failed to refresh session: ${reason}.` + (definitive ? ' Run `dcd login` again.' : ''), definitive, definitive ? code : undefined);
89
90
  },
90
91
  };
@@ -83,7 +83,7 @@ export declare const DeviceGateway: {
83
83
  human: DeviceHumanStatus;
84
84
  session: DeviceSession;
85
85
  }>;
86
- /** One typed action: tap, type, swipe or press_key. Synchronous: answers with the outcome. */
86
+ /** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */
87
87
  action(baseUrl: string, auth: AuthContext, id: string, body: DeviceActionRequest): Promise<{
88
88
  result: DeviceCommandResult;
89
89
  session: DeviceSession;
@@ -157,7 +157,7 @@ export const DeviceGateway = {
157
157
  requestHuman(baseUrl, auth, id, reason) {
158
158
  return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, { reason });
159
159
  },
160
- /** One typed action: tap, type, swipe or press_key. Synchronous: answers with the outcome. */
160
+ /** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */
161
161
  action(baseUrl, auth, id, body) {
162
162
  return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, body);
163
163
  },
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { liveCommand } from './commands/live.js';
9
9
  import { loginCommand } from './commands/login.js';
10
10
  import { logoutCommand } from './commands/logout.js';
11
11
  import { mcpCommand } from './commands/mcp.js';
12
+ import { settingsCommand } from './commands/settings.js';
12
13
  import { statusCommand } from './commands/status.js';
13
14
  import { switchOrgCommand } from './commands/switch-org.js';
14
15
  import { upgradeCommand } from './commands/upgrade.js';
@@ -31,6 +32,7 @@ const main = defineCommand({
31
32
  upload: uploadCommand,
32
33
  list: listCommand,
33
34
  status: statusCommand,
35
+ settings: settingsCommand,
34
36
  artifacts: artifactsCommand,
35
37
  device: deviceCommand,
36
38
  live: liveCommand,
@@ -37,14 +37,14 @@ import { createServer } from './server.js';
37
37
  * have them. So these name only the dcd_* tools, and the hosted tools explain
38
38
  * themselves in their own descriptions.
39
39
  */
40
- const INSTRUCTIONS = 'DeviceCloud tools. dcd_* tools run Maestro test suites in the cloud: dcd_list_devices shows what you can test on, dcd_run_cloud_test submits flows (billable), and dcd_get_status follows a run. Any other tools describe their own use. Where a tool takes a path to a local file (an app build, a flow file or a directory), this server uploads it for you.';
40
+ const INSTRUCTIONS = 'DeviceCloud tools. dcd_* tools run Maestro test suites in the cloud: dcd_list_devices shows what you can test on, dcd_run_cloud_test submits flows (billable), and dcd_get_status follows a run. dcd_get_team_settings reads the team settings and limits. Any other tools describe their own use. Where a tool takes a path to a local file (an app build, a flow file or a directory), this server uploads it for you.';
41
41
  /**
42
42
  * How long one forwarded call may take. Longer than dcd_run_cloud_test's
43
43
  * longest wait (3600s) plus an upload. The MCP client calling this server
44
44
  * still applies its own timeout, and its cancel is passed through.
45
45
  */
46
46
  export const CALL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
47
- const READ_ONLY_INSTRUCTIONS = 'DeviceCloud tools, read-only: nothing here runs a test or changes anything. dcd_* tools read cloud test runs and their results. Any other tools describe their own use.';
47
+ const READ_ONLY_INSTRUCTIONS = 'DeviceCloud tools, read-only: nothing here runs a test or changes anything. dcd_* tools read cloud test runs and their results, and the team settings. Any other tools describe their own use.';
48
48
  /** The inputs this bridge adds to hosted tools, and what they say. */
49
49
  const LOCAL_INPUTS = {
50
50
  install_app: {
@@ -3,6 +3,7 @@ import { getCliVersion } from '../utils/cli.js';
3
3
  import { isReadOnly } from './context.js';
4
4
  import { registerDownloadArtifacts } from './tools/download-artifacts.js';
5
5
  import { registerGetStatus } from './tools/get-status.js';
6
+ import { registerGetTeamSettings } from './tools/get-team-settings.js';
6
7
  import { registerListDevices } from './tools/list-devices.js';
7
8
  import { registerListRuns } from './tools/list-runs.js';
8
9
  import { registerRunCloudTest } from './tools/run-cloud-test.js';
@@ -20,6 +21,7 @@ export function createServer() {
20
21
  registerListRuns(server);
21
22
  registerGetStatus(server);
22
23
  registerDownloadArtifacts(server);
24
+ registerGetTeamSettings(server);
23
25
  if (!isReadOnly()) {
24
26
  registerRunCloudTest(server);
25
27
  }
@@ -0,0 +1,7 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ /**
3
+ * Read-only: the team's settings, the same object `dcd settings --json`
4
+ * prints. Lets an agent check limits (concurrency, test runtime) before it
5
+ * plans a run, and see how the team is set up without the console.
6
+ */
7
+ export declare function registerGetTeamSettings(server: McpServer): void;
@@ -0,0 +1,24 @@
1
+ import { ApiGateway } from '../../gateways/api-gateway.js';
2
+ import { getContext } from '../context.js';
3
+ import { jsonResult, runTool } from '../helpers.js';
4
+ /**
5
+ * Read-only: the team's settings, the same object `dcd settings --json`
6
+ * prints. Lets an agent check limits (concurrency, test runtime) before it
7
+ * plans a run, and see how the team is set up without the console.
8
+ */
9
+ export function registerGetTeamSettings(server) {
10
+ server.registerTool('dcd_get_team_settings', {
11
+ title: 'Get team settings',
12
+ description: "Read the devicecloud.dev team's settings. Changes nothing. " +
13
+ 'Returns: { orgId, name, restricted, concurrency: { runners, pools }, testRuntime: { defaultMinutes, extendedMinutes }, ' +
14
+ 'integrations: { webhook, slack, github }, signInRequirement, retryEscalation, overage }. ' +
15
+ 'concurrency gives each runner type\'s min/max tests at once; a pooled runner type is listed under its pool. ' +
16
+ 'extendedMinutes is null when extended runtime is off. ' +
17
+ 'When restricted is true (a standard team member), signInRequirement, retryEscalation and overage are null; owners, admins and API keys see them.',
18
+ inputSchema: {},
19
+ annotations: { readOnlyHint: true, openWorldHint: true },
20
+ }, async () => runTool('dcd_get_team_settings', async () => {
21
+ const { apiUrl, auth } = await getContext();
22
+ return jsonResult(await ApiGateway.getTeamSettings(apiUrl, auth));
23
+ }));
24
+ }
@@ -1,5 +1,5 @@
1
1
  import * as path from 'node:path';
2
- import { ApiGateway } from '../gateways/api-gateway.js';
2
+ import { ApiGateway, isPermanentApiError, } from '../gateways/api-gateway.js';
3
3
  import { formatDurationSeconds } from '../methods.js';
4
4
  import { isDefinitiveAuthFailure, refreshAuth } from '../utils/auth.js';
5
5
  import { checkInternetConnectivity } from '../utils/connectivity.js';
@@ -198,8 +198,11 @@ export class ResultsPollingService {
198
198
  }
199
199
  catch (error) {
200
200
  // Re-throw RunFailedError immediately (test failures, not polling
201
- // errors), and an expired login no retry can fix.
202
- if (error instanceof RunFailedError || error instanceof PollingAuthError) {
201
+ // errors), and an expired login or a key without access to this run,
202
+ // which no retry can fix.
203
+ if (error instanceof RunFailedError ||
204
+ error instanceof PollingAuthError ||
205
+ isPermanentApiError(error)) {
203
206
  throw error;
204
207
  }
205
208
  sequentialPollFailures++;
@@ -8,6 +8,27 @@ export interface EncryptionTelemetry {
8
8
  flow: boolean;
9
9
  source: EncryptionSource;
10
10
  }
11
+ /**
12
+ * Why a bundle download fell back to the inline endpoint. `manifest_unavailable`
13
+ * (a 501) is the expected answer from a deployment without bundle delivery;
14
+ * the rest are failures worth counting.
15
+ */
16
+ export type BundleFallbackReason = 'bundle_http_error' | 'bundle_request_failed' | 'bundle_stream_failed' | 'manifest_http_error' | 'manifest_incomplete' | 'manifest_invalid_json' | 'manifest_request_failed' | 'manifest_unavailable';
17
+ export interface BundleFallbackTelemetry {
18
+ /** Bytes of the ZIP received before the stream failed. */
19
+ bytes_received?: number;
20
+ duration_ms: number;
21
+ /** Low-level error code from the cause, e.g. `ECONNRESET`. */
22
+ error_code?: string;
23
+ error_message?: string;
24
+ error_name?: string;
25
+ reason: BundleFallbackReason;
26
+ /** The manifest route, e.g. `artifacts-bundle`. */
27
+ route: string;
28
+ /** HTTP status, for the `*_http_error` / `manifest_unavailable` reasons. */
29
+ status?: number;
30
+ upload_id?: string;
31
+ }
11
32
  declare class Telemetry {
12
33
  private buffer;
13
34
  private config;
@@ -54,6 +75,12 @@ declare class Telemetry {
54
75
  * what to count when judging how often the API stalls under the CLI.
55
76
  */
56
77
  recordSubmitAttempts(attempts: number): void;
78
+ /**
79
+ * Record that a bundle download fell back to the inline endpoint, and why.
80
+ * The user never sees the fallback (the inline download still delivers the
81
+ * file), so without this the reason is lost.
82
+ */
83
+ recordBundleFallback(detail: BundleFallbackTelemetry): void;
57
84
  recordCommandSuccess(): void;
58
85
  recordCommandFailure(opts: {
59
86
  error: Error | string;
@@ -72,5 +99,22 @@ declare class Telemetry {
72
99
  flushSync(): void;
73
100
  private buildMeta;
74
101
  }
102
+ /**
103
+ * The argv a command was run with, as telemetry may keep it: without the
104
+ * values of the flags above, and without what two `dcd device` subcommands
105
+ * are given that no flag name marks as a secret.
106
+ *
107
+ * - `device open-link` takes its link as a positional. A sign-in link is a
108
+ * credential, and `--sensitive` promises it is never shown, so everything
109
+ * after `open-link` that is not a flag is taken for the link, and the value
110
+ * of any flag but the API URL goes too. That costs the session id, and
111
+ * keeps a link too malformed to send from being kept either.
112
+ * - `device type` takes `--text`, which is a password or a code as often as
113
+ * not. `device tap` has a `--text` as well, an element's label, and keeps it.
114
+ *
115
+ * The subcommand is found by its name anywhere after `device`, not as the
116
+ * first positional: a flag's value in between must not hide it.
117
+ */
118
+ export declare function scrubArgv(args: string[]): string[];
75
119
  export declare const telemetry: Telemetry;
76
120
  export {};
@@ -104,6 +104,14 @@ class Telemetry {
104
104
  recordSubmitAttempts(attempts) {
105
105
  this.submitAttempts = attempts;
106
106
  }
107
+ /**
108
+ * Record that a bundle download fell back to the inline endpoint, and why.
109
+ * The user never sees the fallback (the inline download still delivers the
110
+ * file), so without this the reason is lost.
111
+ */
112
+ recordBundleFallback(detail) {
113
+ this.enqueue(detail.reason === 'manifest_unavailable' ? 'info' : 'warn', 'cli.download', 'bundle download fell back', { ...detail });
114
+ }
107
115
  recordCommandSuccess() {
108
116
  this.enqueue('info', 'cli.lifecycle', 'command completed', {
109
117
  duration_ms: Date.now() - this.startedAt,
@@ -237,24 +245,55 @@ const SENSITIVE_FLAG_NAMES = new Set([
237
245
  '-e',
238
246
  '--env',
239
247
  ]);
240
- function scrubArgv(args) {
248
+ const REDACTED = '<redacted>';
249
+ /**
250
+ * The argv a command was run with, as telemetry may keep it: without the
251
+ * values of the flags above, and without what two `dcd device` subcommands
252
+ * are given that no flag name marks as a secret.
253
+ *
254
+ * - `device open-link` takes its link as a positional. A sign-in link is a
255
+ * credential, and `--sensitive` promises it is never shown, so everything
256
+ * after `open-link` that is not a flag is taken for the link, and the value
257
+ * of any flag but the API URL goes too. That costs the session id, and
258
+ * keeps a link too malformed to send from being kept either.
259
+ * - `device type` takes `--text`, which is a password or a code as often as
260
+ * not. `device tap` has a `--text` as well, an element's label, and keeps it.
261
+ *
262
+ * The subcommand is found by its name anywhere after `device`, not as the
263
+ * first positional: a flag's value in between must not hide it.
264
+ */
265
+ export function scrubArgv(args) {
266
+ const device = args.indexOf('device');
267
+ const subcommand = (name) => (device === -1 ? -1 : args.indexOf(name, device + 1));
268
+ const openLink = subcommand('open-link');
269
+ const type = subcommand('type');
270
+ const keeps = (flag) => API_URL_FLAGS.includes(flag);
241
271
  const scrubbed = [];
242
272
  for (let i = 0; i < args.length; i++) {
243
273
  const arg = args[i];
274
+ const isFlag = arg.startsWith('-');
244
275
  const eqIndex = arg.indexOf('=');
245
276
  const flagName = eqIndex === -1 ? arg : arg.slice(0, eqIndex);
246
- if (arg.startsWith('-') && SENSITIVE_FLAG_NAMES.has(flagName)) {
277
+ const afterOpenLink = openLink !== -1 && i > openLink;
278
+ const secretFlag = SENSITIVE_FLAG_NAMES.has(flagName) ||
279
+ (type !== -1 && i > type && flagName === '--text') ||
280
+ // `--anything=value` after open-link: no flag of the command needs its value kept.
281
+ (afterOpenLink && eqIndex !== -1 && !keeps(flagName));
282
+ if (isFlag && secretFlag) {
247
283
  if (eqIndex === -1) {
248
284
  scrubbed.push(arg);
249
285
  if (i + 1 < args.length) {
250
- scrubbed.push('<redacted>');
286
+ scrubbed.push(REDACTED);
251
287
  i++;
252
288
  }
253
289
  }
254
290
  else {
255
- scrubbed.push(`${flagName}=<redacted>`);
291
+ scrubbed.push(`${flagName}=${REDACTED}`);
256
292
  }
257
293
  }
294
+ else if (afterOpenLink && !isFlag) {
295
+ scrubbed.push(keeps(args[i - 1]) ? arg : REDACTED);
296
+ }
258
297
  else {
259
298
  scrubbed.push(arg);
260
299
  }
@@ -114,6 +114,8 @@ export type DeviceActionRequest = {
114
114
  id?: string;
115
115
  mode?: 'maestro';
116
116
  text?: string;
117
+ /** With `text` or `id`: seconds to wait for it to appear (0 to 60; 0 looks once). */
118
+ timeoutSeconds?: number;
117
119
  type: 'tap';
118
120
  x?: number;
119
121
  y?: number;
@@ -132,6 +134,14 @@ export type DeviceActionRequest = {
132
134
  mode?: 'maestro';
133
135
  to?: DevicePoint;
134
136
  type: 'swipe';
137
+ } | {
138
+ sensitive?: boolean;
139
+ type: 'open_link';
140
+ url: string;
141
+ } | {
142
+ latitude: number;
143
+ longitude: number;
144
+ type: 'set_location';
135
145
  };
136
146
  /** The keys press_key takes, as the API names them. */
137
147
  export declare const DEVICE_KEYS: readonly ["back", "home", "enter", "backspace", "tab", "volume_up", "volume_down", "lock", "power"];
@@ -0,0 +1,53 @@
1
+ export type Platform = 'android' | 'ios';
2
+ export type SignInRequirement = 'off' | 'passkey' | 'passkey_and_code' | 'two_factor';
3
+ export interface TeamSettings {
4
+ orgId: number;
5
+ name: null | string;
6
+ /**
7
+ * True when the caller is a standard member: `signInRequirement`,
8
+ * `retryEscalation` and `overage` are then null. Owners, admins and org API
9
+ * keys see them.
10
+ */
11
+ restricted: boolean;
12
+ concurrency: {
13
+ /** Runner types with their own limit. A pooled runner type is listed under its pool. */
14
+ runners: Array<{
15
+ max: number;
16
+ min: number;
17
+ platform: Platform;
18
+ runnerType: string;
19
+ }>;
20
+ /** Limits shared by several runner types. */
21
+ pools: Array<{
22
+ max: number;
23
+ members: Array<{
24
+ platform: Platform;
25
+ runnerType: string;
26
+ }>;
27
+ min: number;
28
+ name: string;
29
+ }>;
30
+ };
31
+ testRuntime: {
32
+ defaultMinutes: number;
33
+ /** With the EXTENDED_RUNTIME override; null when extended runtime is off. */
34
+ extendedMinutes: null | number;
35
+ };
36
+ integrations: {
37
+ github: boolean;
38
+ slack: boolean;
39
+ webhook: boolean;
40
+ };
41
+ signInRequirement: null | SignInRequirement;
42
+ retryEscalation: {
43
+ available: boolean;
44
+ enabled: boolean;
45
+ /** Runner type an Android test is retried on after an infrastructure failure. */
46
+ target: 'gpu1' | 'm1' | null;
47
+ } | null;
48
+ overage: {
49
+ hasSubscription: boolean;
50
+ /** US dollars per billing period on top of included credits; null when uncapped. */
51
+ limitUsd: null | number;
52
+ } | null;
53
+ }
@@ -0,0 +1,4 @@
1
+ // Hand-defined: GET /org/settings is newer than the swagger spec the CLI
2
+ // generates schema.types.ts from. It mirrors OrgSettingsResponseDto in the
3
+ // API (dcd/api/src/apps/org-settings/dto/org-settings.dto.ts).
4
+ export {};
@@ -170,7 +170,7 @@ async function refreshSessionWithLock(initial) {
170
170
  // forced a fresh login when an upgrade alone would have fixed it. The
171
171
  // error tells the user to log in again; only `dcd logout` (or the next
172
172
  // `dcd login`) replaces the stored session.
173
- const refreshed = await CliAuthGateway.refresh(current.supabase_url, current.env, session);
173
+ const refreshed = await CliAuthGateway.refresh(current.api_url, session, clientHeaders());
174
174
  // Re-read again and merge only `session` so a concurrent `switch-org`
175
175
  // write (org fields) isn't reverted by our pre-refresh snapshot.
176
176
  const merged = { ...(readConfig() ?? current), session: refreshed };
@@ -1,3 +1,4 @@
1
+ import { ApiGateway } from '../gateways/api-gateway.js';
1
2
  let cachedCompatibilityData = null;
2
3
  /**
3
4
  * The CLI / CI identity the API version-filters and targets notices by rides
@@ -16,7 +17,9 @@ export async function fetchCompatibilityData(apiUrl, auth) {
16
17
  method: 'GET',
17
18
  });
18
19
  if (!response.ok) {
19
- throw new Error(`HTTP error! status: ${response.status}`);
20
+ // Says why, such as a key whose access doesn't cover running tests,
21
+ // rather than only the status code.
22
+ await ApiGateway.handleApiError(response, 'Failed to fetch compatibility data');
20
23
  }
21
24
  const result = await response.json();
22
25
  if (result.statusCode !== 200 || !result.data) {
package/package.json CHANGED
@@ -23,21 +23,19 @@
23
23
  "devDependencies": {
24
24
  "@eslint/js": "^10.0.1",
25
25
  "@types/chai": "^5.2.3",
26
- "@types/js-yaml": "^4.0.9",
27
26
  "@types/mocha": "^10.0.10",
28
27
  "@types/node": "^26.0.0",
29
28
  "@types/yazl": "^3.3.1",
30
29
  "chai": "^6.2.2",
31
- "eslint": "^10.5.0",
30
+ "eslint": "^10.15.0",
32
31
  "eslint-config-prettier": "^10.1.8",
33
32
  "eslint-plugin-unicorn": "^79.0.0",
34
33
  "husky": "^9.1.7",
35
34
  "mocha": "^12.0.0",
36
35
  "prettier": "^3.8.4",
37
- "shx": "^0.4.0",
38
36
  "tsx": "^4.22.4",
39
37
  "typescript": "^6.0.3",
40
- "typescript-eslint": "^8.61.1"
38
+ "typescript-eslint": "^8.73.0"
41
39
  },
42
40
  "engines": {
43
41
  "node": ">=22.0.0"
@@ -60,7 +58,7 @@
60
58
  },
61
59
  "scripts": {
62
60
  "dcd": "tsx src/index.ts",
63
- "build": "shx rm -rf dist && tsc -b && shx chmod +x dist/index.js dist/mcp/index.js",
61
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -b && node -e \"for (const f of ['dist/index.js','dist/mcp/index.js']) require('node:fs').chmodSync(f,0o755)\"",
64
62
  "build:binaries": "node scripts/build-binaries.mjs",
65
63
  "lint": "eslint src test --ext .ts",
66
64
  "prepare": "pnpm build && husky",
@@ -68,7 +66,7 @@
68
66
  "test:unit": "node scripts/test-runner.mjs --unit",
69
67
  "typecheck": "tsc --noEmit -p tsconfig.test.json"
70
68
  },
71
- "version": "5.13.0",
69
+ "version": "5.14.0",
72
70
  "bugs": {
73
71
  "url": "https://discord.gg/gm3mJwcNw8"
74
72
  },
@@ -84,37 +82,8 @@
84
82
  "packageManager": "pnpm@10.17.1",
85
83
  "pnpm": {
86
84
  "overrides": {
87
- "js-yaml@<3.14.2": ">=3.14.2",
88
- "js-yaml@>=4.0.0 <4.2.0": ">=4.2.0",
89
- "js-yaml@>=5.0.0 <5.2.2": ">=5.2.2",
90
- "tar@<7.5.16": ">=7.5.16",
91
- "@isaacs/brace-expansion": ">=5.0.1",
92
- "fast-xml-parser": ">=5.5.7",
93
- "flatted": ">=3.4.2",
94
- "lodash": ">=4.18.0",
95
- "@xmldom/xmldom": ">=0.9.12",
96
- "minimatch@<3.1.4": "3.1.4",
97
- "minimatch@>=5.0.0 <5.1.8": "5.1.8",
98
- "minimatch@>=9.0.0 <9.0.7": "9.0.7",
99
85
  "minimatch@>=10.0.0 <11.0.1": "11.0.1",
100
- "glob@>=9.0.0 <14.0.2": "14.0.2",
101
- "picomatch@<2.3.2": "2.3.2",
102
- "picomatch@>=4.0.0 <4.0.4": "4.0.4",
103
- "serialize-javascript": ">=7.0.5",
104
- "ajv@<7.0.0": "6.14.0",
105
- "diff@>=4.0.0 <6.0.0": "4.0.4",
106
- "diff@>=6.0.0": "8.0.3",
107
- "brace-expansion@<1.1.16": "1.1.16",
108
- "brace-expansion@>=2.0.0 <2.0.3": "2.0.3",
109
- "brace-expansion@>=3.0.0 <5.0.12": "5.0.12",
110
- "ws@>=8.0.0 <8.21.0": "8.21.0",
111
- "esbuild@<0.28.1": ">=0.28.1",
112
- "qs@<6.16.1": "6.16.1",
113
- "fast-uri@>=3.0.0 <3.1.9": "3.1.9",
114
- "hono@>=4.0.0 <4.13.16": "4.13.16",
115
- "source-map-js@<1.2.2": "1.2.2",
116
- "micromatch>picomatch": "^2.3.2",
117
- "tinyglobby>picomatch": "^4.0.4"
86
+ "glob@>=9.0.0 <14.0.2": "14.0.2"
118
87
  },
119
88
  "auditConfig": {
120
89
  "ignoreGhsas": [