@devicecloud.dev/dcd 5.13.0 → 5.14.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.
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.
@@ -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) {
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;
@@ -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,
@@ -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 {};
@@ -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
@@ -68,7 +68,7 @@
68
68
  "test:unit": "node scripts/test-runner.mjs --unit",
69
69
  "typecheck": "tsc --noEmit -p tsconfig.test.json"
70
70
  },
71
- "version": "5.13.0",
71
+ "version": "5.14.0-beta.1",
72
72
  "bugs": {
73
73
  "url": "https://discord.gg/gm3mJwcNw8"
74
74
  },