@devicecloud.dev/dcd 5.14.1 → 5.16.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +25 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/device.d.ts +39 -0
  5. package/dist/commands/device.js +479 -101
  6. package/dist/e2e/index.d.ts +4 -0
  7. package/dist/e2e/index.js +41 -0
  8. package/dist/e2e/provider.d.ts +80 -0
  9. package/dist/e2e/provider.js +233 -0
  10. package/dist/gateways/api-gateway.d.ts +25 -3
  11. package/dist/gateways/api-gateway.js +68 -6
  12. package/dist/gateways/device-gateway.d.ts +34 -10
  13. package/dist/gateways/device-gateway.js +72 -17
  14. package/dist/mcp/bridge.d.ts +30 -16
  15. package/dist/mcp/bridge.js +201 -64
  16. package/dist/mcp/local-files.d.ts +14 -0
  17. package/dist/mcp/local-files.js +75 -0
  18. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  19. package/dist/mcp/tools/download-artifacts.js +44 -17
  20. package/dist/services/report-download.service.d.ts +32 -0
  21. package/dist/services/report-download.service.js +51 -2
  22. package/dist/services/telemetry.service.d.ts +20 -1
  23. package/dist/services/telemetry.service.js +27 -6
  24. package/dist/types/domain/device-session.types.d.ts +73 -3
  25. package/dist/types/domain/device-session.types.js +2 -0
  26. package/dist/utils/api-url.d.ts +20 -0
  27. package/dist/utils/api-url.js +49 -0
  28. package/dist/utils/app-upload.d.ts +6 -0
  29. package/dist/utils/app-upload.js +19 -0
  30. package/dist/utils/config-store.d.ts +5 -1
  31. package/dist/utils/config-store.js +18 -2
  32. package/dist/utils/device-artifacts.d.ts +5 -0
  33. package/dist/utils/device-artifacts.js +22 -0
  34. package/dist/utils/device-bundle.d.ts +39 -9
  35. package/dist/utils/device-bundle.js +153 -51
  36. package/dist/utils/device-flags.d.ts +17 -0
  37. package/dist/utils/device-flags.js +145 -0
  38. package/dist/utils/device-output.d.ts +53 -7
  39. package/dist/utils/device-output.js +148 -21
  40. package/dist/utils/device-run.d.ts +8 -3
  41. package/dist/utils/device-run.js +85 -8
  42. package/dist/utils/zip-integrity.d.ts +21 -0
  43. package/dist/utils/zip-integrity.js +45 -0
  44. package/package.json +10 -1
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The local files an MCP tool may read or write for the agent: only inside
3
+ * the working directory the server was started in (the agent's project), and
4
+ * a write never replaces a file this server did not write. An agent's tool
5
+ * call is not the user typing a path: without these limits a tool could
6
+ * send `~/.aws/credentials` as a flow, or write a report over `~/.zshrc`.
7
+ * Symbolic links are followed before the check, so a link can't lead out.
8
+ */
9
+ import { existsSync, lstatSync, realpathSync } from 'node:fs';
10
+ import * as path from 'node:path';
11
+ /** The working directory, as the file system names it (symbolic links resolved). */
12
+ export function workingDirectory() {
13
+ return realpathSync(process.cwd());
14
+ }
15
+ /** Whether `child` is `parent` or inside it. Both absolute and resolved. */
16
+ export function isInside(child, parent) {
17
+ const relative = path.relative(parent, child);
18
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
19
+ }
20
+ function outside(given, root) {
21
+ return new Error(`${given} is outside the working directory (${root}). This server reads and writes files only there: start it in the folder that holds them, or copy them in.`);
22
+ }
23
+ /** An existing file or folder the agent named, resolved, inside the working directory. */
24
+ export function localInput(given, root = workingDirectory()) {
25
+ let real;
26
+ try {
27
+ real = realpathSync(path.resolve(root, given));
28
+ }
29
+ catch {
30
+ throw new Error(`No such file or directory: ${given}`);
31
+ }
32
+ if (!isInside(real, root))
33
+ throw outside(given, root);
34
+ return real;
35
+ }
36
+ /** Files this server wrote, which it may write again. */
37
+ const written = new Set();
38
+ /**
39
+ * Where to write a file the agent asked for, resolved: inside the working
40
+ * directory, and not over a file this server did not write. Folders that do
41
+ * not exist yet are allowed; the writer makes them.
42
+ */
43
+ export function localOutput(given, root = workingDirectory()) {
44
+ const absolute = path.resolve(root, given);
45
+ // The deepest folder that exists, resolved; the rest is appended to it.
46
+ let existing = path.dirname(absolute);
47
+ const rest = [path.basename(absolute)];
48
+ while (!existsSync(existing)) {
49
+ rest.unshift(path.basename(existing));
50
+ const parent = path.dirname(existing);
51
+ if (parent === existing)
52
+ break;
53
+ existing = parent;
54
+ }
55
+ const target = path.join(realpathSync(existing), ...rest);
56
+ if (!isInside(target, root) || target === root)
57
+ throw outside(given, root);
58
+ // lstat, not exists: a dangling symbolic link is a file there too.
59
+ let present;
60
+ try {
61
+ lstatSync(target);
62
+ present = true;
63
+ }
64
+ catch {
65
+ present = false;
66
+ }
67
+ if (present && !written.has(target)) {
68
+ throw new Error(`${given} already exists, and this server did not write it. Pass a new path, or remove the file first.`);
69
+ }
70
+ return target;
71
+ }
72
+ /** Record a file this server wrote, so a later call may write it again. */
73
+ export function markWritten(file) {
74
+ written.add(file);
75
+ }
@@ -2,7 +2,10 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  /**
3
3
  * Download a completed run's artifacts (zip) and/or a formatted report to local
4
4
  * disk. This reads cloud state and writes files locally — it does not change
5
- * anything cloud-side, so it stays available in read-only mode.
5
+ * anything cloud-side, so it stays available in read-only mode. It does write
6
+ * files, so it is not annotated read-only: the files go inside the working
7
+ * directory only, and never over a file this server did not write
8
+ * (local-files.ts).
6
9
  *
7
10
  * The underlying service swallows download failures into `warnLogger` rather
8
11
  * than throwing (a missing-artifacts 404 isn't fatal), so we collect those
@@ -1,12 +1,16 @@
1
- import * as path from 'node:path';
1
+ import { existsSync } from 'node:fs';
2
2
  import { z } from 'zod';
3
3
  import { ReportDownloadService } from '../../services/report-download.service.js';
4
4
  import { getContext, logStderr } from '../context.js';
5
5
  import { jsonResult, runTool } from '../helpers.js';
6
+ import { localOutput, markWritten } from '../local-files.js';
6
7
  /**
7
8
  * Download a completed run's artifacts (zip) and/or a formatted report to local
8
9
  * disk. This reads cloud state and writes files locally — it does not change
9
- * anything cloud-side, so it stays available in read-only mode.
10
+ * anything cloud-side, so it stays available in read-only mode. It does write
11
+ * files, so it is not annotated read-only: the files go inside the working
12
+ * directory only, and never over a file this server did not write
13
+ * (local-files.ts).
10
14
  *
11
15
  * The underlying service swallows download failures into `warnLogger` rather
12
16
  * than throwing (a missing-artifacts 404 isn't fatal), so we collect those
@@ -16,6 +20,7 @@ export function registerDownloadArtifacts(server) {
16
20
  server.registerTool('dcd_download_artifacts', {
17
21
  title: 'Download run artifacts',
18
22
  description: 'Download a completed test run\'s artifacts (videos/logs zip) and/or a formatted report to local disk. ' +
23
+ 'Paths are relative to the working directory this server runs in, and must stay inside it; an existing file this server did not write is never replaced. ' +
19
24
  'Returns the resolved output paths and any warnings (a non-empty warnings array means a download could not be produced, e.g. no results yet).',
20
25
  inputSchema: {
21
26
  uploadId: z.string().describe('UUID of the upload to download artifacts for'),
@@ -26,7 +31,18 @@ export function registerDownloadArtifacts(server) {
26
31
  artifactsPath: z
27
32
  .string()
28
33
  .optional()
29
- .describe('Local path to write the artifacts zip (default ./artifacts.zip)'),
34
+ .describe('Where to write the artifacts zip, inside the working directory (default ./artifacts.zip)'),
35
+ resultId: z
36
+ .number()
37
+ .int()
38
+ .positive()
39
+ .optional()
40
+ .describe("Only this result's artifacts: its flow's attempts on that one device. Leave unset with flow."),
41
+ flow: z
42
+ .string()
43
+ .min(1)
44
+ .optional()
45
+ .describe('Only the artifacts of the flow with this file path or name (e.g. flows/login.yaml or login). A name matching several results (one per device) gives a warning listing their ids; pass one as resultId.'),
30
46
  report: z
31
47
  .enum(['junit', 'allure', 'html'])
32
48
  .optional()
@@ -34,10 +50,14 @@ export function registerDownloadArtifacts(server) {
34
50
  reportPath: z
35
51
  .string()
36
52
  .optional()
37
- .describe('Local path for the report file (default ./report.xml for junit, ./report.html for allure, ./report.zip for html, which is a ZIP of report.html and its assets)'),
53
+ .describe('Where to write the report, inside the working directory (default ./report.xml for junit, ./report.html for allure, ./report.zip for html, which is a ZIP of report.html and its assets)'),
38
54
  },
39
- annotations: { readOnlyHint: true, openWorldHint: true },
55
+ // It writes local files (nothing in the cloud), and never over one it did not write.
56
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
40
57
  }, async (args) => runTool('dcd_download_artifacts', async () => {
58
+ if (args.resultId !== undefined && args.flow !== undefined) {
59
+ throw new Error('Pass resultId or flow, not both');
60
+ }
41
61
  const { apiUrl, auth } = await getContext();
42
62
  const service = new ReportDownloadService();
43
63
  const warnings = [];
@@ -45,26 +65,31 @@ export function registerDownloadArtifacts(server) {
45
65
  warnings.push(m);
46
66
  logStderr(m);
47
67
  };
48
- const artifactsPath = args.artifactsPath ?? './artifacts.zip';
68
+ // Both checked before anything is downloaded.
69
+ const artifactsPath = localOutput(args.artifactsPath ?? './artifacts.zip');
70
+ const defaultReportPath = args.report
71
+ ? { allure: 'report.html', html: 'report.zip', junit: 'report.xml' }[args.report]
72
+ : undefined;
73
+ const reportPath = defaultReportPath ? localOutput(args.reportPath || defaultReportPath) : undefined;
74
+ if (reportPath && reportPath === artifactsPath) {
75
+ throw new Error('artifactsPath and reportPath name the same file. Give them different paths.');
76
+ }
49
77
  await service.downloadArtifacts({
50
78
  apiUrl,
51
79
  auth,
52
80
  uploadId: args.uploadId,
53
81
  downloadType: args.type ?? 'ALL',
54
82
  artifactsPath,
83
+ flow: args.flow,
84
+ resultId: args.resultId,
55
85
  logger: logStderr,
56
86
  warnLogger,
57
87
  });
58
- let reportPath;
59
- if (args.report) {
60
- // The HTML report is a ZIP of report.html plus assets; Allure's is
61
- // a single HTML file.
62
- const defaultReportPath = {
63
- allure: 'report.html',
64
- html: 'report.zip',
65
- junit: 'report.xml',
66
- }[args.report];
67
- reportPath = path.resolve(args.reportPath || defaultReportPath);
88
+ if (existsSync(artifactsPath))
89
+ markWritten(artifactsPath);
90
+ // The HTML report is a ZIP of report.html plus assets; Allure's is a
91
+ // single HTML file.
92
+ if (args.report && reportPath) {
68
93
  await service.downloadReports({
69
94
  apiUrl,
70
95
  auth,
@@ -76,10 +101,12 @@ export function registerDownloadArtifacts(server) {
76
101
  logger: logStderr,
77
102
  warnLogger,
78
103
  });
104
+ if (existsSync(reportPath))
105
+ markWritten(reportPath);
79
106
  }
80
107
  return jsonResult({
81
108
  uploadId: args.uploadId,
82
- artifactsPath: path.resolve(artifactsPath),
109
+ artifactsPath,
83
110
  reportPath,
84
111
  warnings,
85
112
  });
@@ -10,7 +10,34 @@ export interface DownloadOptions {
10
10
  export interface ArtifactsDownloadOptions extends DownloadOptions {
11
11
  artifactsPath?: string;
12
12
  downloadType: 'ALL' | 'FAILED';
13
+ /**
14
+ * Only this flow's artifacts, by its file path or name: resolved to one
15
+ * result with {@link matchFlowResult}. Leave unset with `resultId`.
16
+ */
17
+ flow?: string;
18
+ /**
19
+ * Only the artifacts of the flow run this result belongs to: its first
20
+ * attempt and every retry, on that one device.
21
+ */
22
+ resultId?: number;
23
+ }
24
+ /** A result row as the flow lookup needs it. */
25
+ export interface FlowResultRow {
26
+ config?: unknown;
27
+ id: number;
28
+ retry_of?: null | number;
29
+ simulator_name?: null | string;
30
+ test_file_name: string;
13
31
  }
32
+ /**
33
+ * The one run in an upload whose flow file matches `flow`: its full path as
34
+ * submitted (`flows/login.yaml`, with or without `./`), its file name
35
+ * (`login.yaml`) or its name without the extension (`login`). Only first
36
+ * attempts are candidates; the API adds the retries. Throws when nothing
37
+ * matches, or when several runs do (a device matrix runs one flow per
38
+ * device), listing the result ids to pick from with --result-id.
39
+ */
40
+ export declare function matchFlowResult(rows: FlowResultRow[], flow: string): number;
14
41
  export interface ReportDownloadOptions extends DownloadOptions {
15
42
  allurePath?: string;
16
43
  htmlPath?: string;
@@ -31,6 +58,11 @@ export interface DownloadResult {
31
58
  path: string;
32
59
  type: 'allure' | 'artifacts' | 'html' | 'junit';
33
60
  }
61
+ /**
62
+ * Whether every requested download succeeded. `dcd artifacts` exits 1 when
63
+ * not; `dcd cloud` only warns, so a download never changes a test-run exit.
64
+ */
65
+ export declare function downloadsSucceeded(downloads: DownloadResult[]): boolean;
34
66
  /**
35
67
  * Service for downloading test artifacts and reports
36
68
  */
@@ -1,6 +1,37 @@
1
1
  import * as path from 'node:path';
2
2
  import { ApiGateway } from '../gateways/api-gateway.js';
3
3
  import { refreshAuth } from '../utils/auth.js';
4
+ import { deviceFromResultRow } from './results-polling.service.js';
5
+ /** `./flows/login.yaml` -> `flows/login.yaml`, so the forms compare equal. */
6
+ const normaliseFlowPath = (p) => p.trim().replace(/^(\.\/)+/, '');
7
+ /**
8
+ * The one run in an upload whose flow file matches `flow`: its full path as
9
+ * submitted (`flows/login.yaml`, with or without `./`), its file name
10
+ * (`login.yaml`) or its name without the extension (`login`). Only first
11
+ * attempts are candidates; the API adds the retries. Throws when nothing
12
+ * matches, or when several runs do (a device matrix runs one flow per
13
+ * device), listing the result ids to pick from with --result-id.
14
+ */
15
+ export function matchFlowResult(rows, flow) {
16
+ const wanted = normaliseFlowPath(flow);
17
+ const roots = rows.filter((r) => r.retry_of === null || r.retry_of === undefined);
18
+ const matches = roots.filter((r) => {
19
+ const file = normaliseFlowPath(r.test_file_name);
20
+ const base = file.split('/').pop() ?? file;
21
+ return file === wanted || base === wanted || base.replace(/\.ya?ml$/i, '') === wanted;
22
+ });
23
+ if (matches.length === 1)
24
+ return matches[0].id;
25
+ if (matches.length === 0) {
26
+ throw new Error(`No flow matching '${flow}' in this upload`);
27
+ }
28
+ const candidates = matches.map((r) => {
29
+ const device = deviceFromResultRow(r);
30
+ const label = [device?.name, device?.osVersion].filter(Boolean).join(' ');
31
+ return `${r.id} (${r.test_file_name}${label ? `, ${label}` : ''})`;
32
+ });
33
+ throw new Error(`'${flow}' matches ${matches.length} results in this upload; pick one with --result-id: ${candidates.join(', ')}`);
34
+ }
4
35
  /**
5
36
  * The report formats retired on 7 December 2026, and what each one
6
37
  * does from that date. `dcd cloud` users are told by the API's submit message
@@ -20,6 +51,13 @@ export function reportFormatDeprecation(report) {
20
51
  }
21
52
  }
22
53
  }
54
+ /**
55
+ * Whether every requested download succeeded. `dcd artifacts` exits 1 when
56
+ * not; `dcd cloud` only warns, so a download never changes a test-run exit.
57
+ */
58
+ export function downloadsSucceeded(downloads) {
59
+ return downloads.length > 0 && downloads.every((d) => d.ok);
60
+ }
23
61
  /**
24
62
  * Service for downloading test artifacts and reports
25
63
  */
@@ -30,14 +68,25 @@ export class ReportDownloadService {
30
68
  * @returns What the download did
31
69
  */
32
70
  async downloadArtifacts(options) {
33
- const { apiUrl, auth, uploadId, downloadType, artifactsPath = './artifacts.zip', debug = false, logger, warnLogger, } = options;
71
+ const { apiUrl, auth, uploadId, downloadType, artifactsPath = './artifacts.zip', debug = false, flow, logger, warnLogger, } = options;
34
72
  try {
35
73
  if (debug && logger) {
36
74
  logger(`[DEBUG] Downloading artifacts: ${downloadType}`);
37
75
  }
38
76
  // `dcd cloud` downloads after polling, which can outlast a `dcd login`
39
77
  // token; a failed refresh lands in the warning below like any failure.
40
- await ApiGateway.downloadArtifactsZip(apiUrl, await refreshAuth(auth), uploadId, downloadType, artifactsPath);
78
+ const freshAuth = await refreshAuth(auth);
79
+ // A flow name becomes the result id the API filters on. A name that
80
+ // matches nothing, or several runs, lands in the warning below.
81
+ let { resultId } = options;
82
+ if (flow !== undefined) {
83
+ const { results } = (await ApiGateway.getResultsForUpload(apiUrl, freshAuth, uploadId));
84
+ resultId = matchFlowResult(results ?? [], flow);
85
+ if (debug && logger) {
86
+ logger(`[DEBUG] Flow '${flow}' is result ${resultId}`);
87
+ }
88
+ }
89
+ await ApiGateway.downloadArtifactsZip(apiUrl, freshAuth, uploadId, downloadType, artifactsPath, resultId);
41
90
  if (logger) {
42
91
  logger('\n');
43
92
  logger(`Test artifacts have been downloaded to ${artifactsPath}`);
@@ -13,7 +13,9 @@ export interface EncryptionTelemetry {
13
13
  * (a 501) is the expected answer from a deployment without bundle delivery;
14
14
  * the rest are failures worth counting.
15
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';
16
+ export type BundleFallbackReason = 'bundle_http_error' | 'bundle_request_failed' | 'bundle_stream_failed'
17
+ /** The stream ended cleanly but the ZIP has no complete central directory. */
18
+ | 'bundle_truncated' | 'manifest_http_error' | 'manifest_incomplete' | 'manifest_invalid_json' | 'manifest_request_failed' | 'manifest_unavailable';
17
19
  export interface BundleFallbackTelemetry {
18
20
  /** Bytes of the ZIP received before the stream failed. */
19
21
  bytes_received?: number;
@@ -81,6 +83,16 @@ declare class Telemetry {
81
83
  * file), so without this the reason is lost.
82
84
  */
83
85
  recordBundleFallback(detail: BundleFallbackTelemetry): void;
86
+ /**
87
+ * Record an inline ZIP download that ended before its central directory.
88
+ * The user sees the failure; this keeps a count of how often it happens.
89
+ */
90
+ recordDownloadIncomplete(detail: {
91
+ bytes: number;
92
+ /** The inline route, e.g. `download` or `html-report`. */
93
+ route: string;
94
+ upload_id?: string;
95
+ }): void;
84
96
  recordCommandSuccess(): void;
85
97
  recordCommandFailure(opts: {
86
98
  error: Error | string;
@@ -99,6 +111,13 @@ declare class Telemetry {
99
111
  flushSync(): void;
100
112
  private buildMeta;
101
113
  }
114
+ /**
115
+ * Links in `text` without their query, fragment and user info. A signed
116
+ * download link's query is its credential (`?X-Amz-Signature=…`), and `dcd
117
+ * device start --app <url>` and `install <url>` take one as a plain value.
118
+ * Where the link points stays, for telling failures apart.
119
+ */
120
+ export declare function redactUrls(text: string): string;
102
121
  /**
103
122
  * The argv a command was run with, as telemetry may keep it: without the
104
123
  * values of the flags above, and without what two `dcd device` subcommands
@@ -17,6 +17,7 @@ import { randomUUID } from 'node:crypto';
17
17
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
18
18
  import { tmpdir } from 'node:os';
19
19
  import { join } from 'node:path';
20
+ import { checkApiUrl } from '../utils/api-url.js';
20
21
  import { getCliVersion, getInstallMethod } from '../utils/cli.js';
21
22
  const DEFAULT_API_URL = 'https://api.devicecloud.dev';
22
23
  class Telemetry {
@@ -73,7 +74,7 @@ class Telemetry {
73
74
  this.enqueue('error', 'cli.mcp', 'mcp tool failed', {
74
75
  tool,
75
76
  duration_ms: durationMs,
76
- error_message: error instanceof Error ? error.message : String(error),
77
+ error_message: redactUrls(error instanceof Error ? error.message : String(error)),
77
78
  error_name: error instanceof Error ? error.name : 'Error',
78
79
  ...extra,
79
80
  });
@@ -112,6 +113,13 @@ class Telemetry {
112
113
  recordBundleFallback(detail) {
113
114
  this.enqueue(detail.reason === 'manifest_unavailable' ? 'info' : 'warn', 'cli.download', 'bundle download fell back', { ...detail });
114
115
  }
116
+ /**
117
+ * Record an inline ZIP download that ended before its central directory.
118
+ * The user sees the failure; this keeps a count of how often it happens.
119
+ */
120
+ recordDownloadIncomplete(detail) {
121
+ this.enqueue('warn', 'cli.download', 'download incomplete', { ...detail });
122
+ }
115
123
  recordCommandSuccess() {
116
124
  this.enqueue('info', 'cli.lifecycle', 'command completed', {
117
125
  duration_ms: Date.now() - this.startedAt,
@@ -125,9 +133,10 @@ class Telemetry {
125
133
  this.enqueue('error', 'cli.lifecycle', 'command failed', {
126
134
  duration_ms: Date.now() - this.startedAt,
127
135
  exit_code: opts.exitCode,
128
- error_message: message,
136
+ // A failed install from a signed link says the link.
137
+ error_message: redactUrls(message),
129
138
  error_name: opts.error instanceof Error ? opts.error.name : 'CliError',
130
- error_stack: opts.error instanceof Error ? opts.error.stack : undefined,
139
+ error_stack: opts.error instanceof Error && opts.error.stack ? redactUrls(opts.error.stack) : undefined,
131
140
  ...this.encryptionExtra(),
132
141
  ...this.submitExtra(),
133
142
  });
@@ -246,6 +255,15 @@ const SENSITIVE_FLAG_NAMES = new Set([
246
255
  '--env',
247
256
  ]);
248
257
  const REDACTED = '<redacted>';
258
+ /**
259
+ * Links in `text` without their query, fragment and user info. A signed
260
+ * download link's query is its credential (`?X-Amz-Signature=…`), and `dcd
261
+ * device start --app <url>` and `install <url>` take one as a plain value.
262
+ * Where the link points stays, for telling failures apart.
263
+ */
264
+ export function redactUrls(text) {
265
+ return text.replaceAll(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/?#]*@)?([^\s?#]*)(\?[^\s#]*)?(#\S*)?/gi, (_match, scheme, user, rest, query, fragment) => `${scheme}${user ? `${REDACTED}@` : ''}${rest}${query ? `?${REDACTED}` : ''}${fragment ? `#${REDACTED}` : ''}`);
266
+ }
249
267
  /**
250
268
  * The argv a command was run with, as telemetry may keep it: without the
251
269
  * values of the flags above, and without what two `dcd device` subcommands
@@ -298,7 +316,7 @@ export function scrubArgv(args) {
298
316
  scrubbed.push(arg);
299
317
  }
300
318
  }
301
- return scrubbed;
319
+ return scrubbed.map((arg) => redactUrls(arg));
302
320
  }
303
321
  // argv layout: node|tsx, script, command, ...flags. The first non-flag after
304
322
  // the script is the subcommand. Falls back to 'help' for `--help`/`--version`
@@ -319,13 +337,16 @@ function inferCommandFromArgv() {
319
337
  const API_URL_FLAGS = ['--api-url', '--apiURL', '--apiUrl'];
320
338
  function inferApiUrlFromArgv() {
321
339
  const args = process.argv.slice(2);
340
+ // Only a URL the command itself would send credentials to: these events
341
+ // carry them too, and may be sent before the command checks its flag.
342
+ const usable = (url) => (checkApiUrl(url.trim()).ok ? url.trim() : DEFAULT_API_URL);
322
343
  for (let i = 0; i < args.length; i++) {
323
344
  const arg = args[i];
324
345
  for (const flag of API_URL_FLAGS) {
325
346
  if (arg === flag && args[i + 1])
326
- return args[i + 1];
347
+ return usable(args[i + 1]);
327
348
  if (arg.startsWith(`${flag}=`))
328
- return arg.slice(flag.length + 1);
349
+ return usable(arg.slice(flag.length + 1));
329
350
  }
330
351
  }
331
352
  return DEFAULT_API_URL;
@@ -15,10 +15,23 @@ export interface DeviceSession {
15
15
  model: null | string;
16
16
  client_label: null | string;
17
17
  created_at: string;
18
+ /** When a device was assigned (billing starts); null while queued. Absent from older APIs. */
19
+ started_at?: null | string;
20
+ /** When it ended; null while open. Absent from older APIs. */
21
+ released_at?: null | string;
22
+ /** When its maximum duration ends it; null while queued and once ended. Absent from older APIs. */
23
+ expires_at?: null | string;
18
24
  queue: {
19
25
  eta_s: null | number;
20
26
  position: null | number;
21
- reason: 'fleet_busy' | 'waiting_for_device';
27
+ /**
28
+ * Why it waits. org_concurrency_full: the org's tests and sessions hold
29
+ * every slot it has; fleet_busy: the platform is at its fleet-wide cap;
30
+ * waiting_for_device: waiting for a free device.
31
+ */
32
+ reason: 'fleet_busy' | 'org_concurrency_full' | 'waiting_for_device';
33
+ /** Seconds since the session was created. Absent from older APIs. */
34
+ waited_s?: null | number;
22
35
  } | null;
23
36
  time_remaining_s: null | number;
24
37
  idle_remaining_s: null | number;
@@ -38,6 +51,23 @@ export interface DeviceSession {
38
51
  } | null;
39
52
  warnings: string[];
40
53
  monitor_url: string;
54
+ /**
55
+ * Who started the session, and how that stands to you. Absent from an API
56
+ * that predates it.
57
+ */
58
+ started_by?: DeviceSessionStarter;
59
+ }
60
+ /** Who started a session. */
61
+ export interface DeviceSessionStarter {
62
+ /** The name of the API key that started it, when one did: its label, never the key. */
63
+ key_name: null | string;
64
+ client_label: null | string;
65
+ /** The person who started it, when a person did. */
66
+ email: null | string;
67
+ /** Started from this connection (the same `dcd mcp` process). */
68
+ this_client: boolean;
69
+ /** Started by you: this person, or this API key. */
70
+ you: boolean;
41
71
  }
42
72
  /**
43
73
  * GET .../human and POST .../request-human (ILiveHumanStatus in the API):
@@ -92,8 +122,28 @@ export interface DeviceInstalledApp {
92
122
  binary_upload_id: string;
93
123
  reused: boolean;
94
124
  }
125
+ /**
126
+ * Where a flow failed, as the device worked it out from the flow files.
127
+ * Absent from older APIs, and when only a position is known.
128
+ */
129
+ export interface DeviceFailureLocation {
130
+ /** The runFlow lines that led there, outermost first, e.g. `main.yaml:4`. */
131
+ call_chain: string[];
132
+ /** The command as written, on one line; null when only a line is known. */
133
+ command: null | string;
134
+ /** The file, as a path inside the bundle; `flow.yaml` for a flow sent inline. */
135
+ file: string;
136
+ /** 1-based line in that file. */
137
+ line: number;
138
+ }
139
+ /** Where a failure was: one place, or several that all fit the error. */
140
+ export interface DeviceFailedAt {
141
+ failed_at?: DeviceFailureLocation;
142
+ /** Two or more commands fit the error, and any of them may have failed. */
143
+ failed_at_candidates?: DeviceFailureLocation[];
144
+ }
95
145
  /** One flow of a run, as newer APIs report it in `result.flows`. */
96
- export interface DeviceFlowResult {
146
+ export interface DeviceFlowResult extends DeviceFailedAt {
97
147
  error: null | string;
98
148
  /** The flow's path inside the bundle; null for a single flow. */
99
149
  file: null | string;
@@ -147,7 +197,7 @@ export type DeviceActionRequest = {
147
197
  export declare const DEVICE_KEYS: readonly ["back", "home", "enter", "backspace", "tab", "volume_up", "volume_down", "lock", "power"];
148
198
  export declare const SWIPE_DIRECTIONS: readonly DeviceSwipeDirection[];
149
199
  /** The result of a typed action, a launch or a run. */
150
- export interface DeviceCommandResult {
200
+ export interface DeviceCommandResult extends DeviceFailedAt {
151
201
  error?: string;
152
202
  /** Each flow of a run. Absent from APIs older than this field. */
153
203
  flows?: DeviceFlowResult[];
@@ -193,6 +243,19 @@ export interface DeviceScreenshot {
193
243
  data_url: string;
194
244
  fresh: boolean;
195
245
  }
246
+ /** GET .../screenshot?full=true: a PNG at the device's own resolution, as a link. */
247
+ export interface DeviceFullScreenshot {
248
+ bytes: null | number;
249
+ captured_at: string;
250
+ content_type: string;
251
+ /** How long `url` works, in seconds. */
252
+ expires_in_s: number;
253
+ full: true;
254
+ /** In the device's own pixels; null when the device could not say. */
255
+ height: null | number;
256
+ url: string;
257
+ width: null | number;
258
+ }
196
259
  /** POST .../run and GET .../commands/:id. */
197
260
  export interface DeviceRunResponse {
198
261
  command_id: string;
@@ -205,9 +268,16 @@ export interface DeviceRunResponse {
205
268
  export interface DeviceLogs {
206
269
  app_id: null | string;
207
270
  lines: string[];
271
+ /** How many lines were looked through before the filters. Absent from older APIs. */
272
+ scanned?: number;
208
273
  /** logcat, ios-unified-log, or none before an app is installed. */
209
274
  source: string;
275
+ /** The answer's size cap (24 KB) dropped older lines. Absent when it did not. */
276
+ truncated?: true;
210
277
  }
278
+ /** The filters GET .../logs takes. */
279
+ export declare const LOG_LEVELS: readonly ["warning", "error"];
280
+ export type DeviceLogLevel = (typeof LOG_LEVELS)[number];
211
281
  /** A short-lived download link for one stored artifact. */
212
282
  export interface DeviceArtifactLink {
213
283
  bytes: null | number;
@@ -16,3 +16,5 @@ export const DEVICE_KEYS = [
16
16
  'power',
17
17
  ];
18
18
  export const SWIPE_DIRECTIONS = ['up', 'down', 'left', 'right'];
19
+ /** The filters GET .../logs takes. */
20
+ export const LOG_LEVELS = ['warning', 'error'];
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Checks for an API URL given by hand (`--api-url`, `DCD_API_URL`), before
3
+ * any credential is sent to it: the API key or login session goes with every
4
+ * request, and a repository's MCP config can set DCD_API_URL. No imports, so
5
+ * the telemetry service can use it too.
6
+ */
7
+ export type ApiUrlCheck = {
8
+ ok: false;
9
+ reason: string;
10
+ } | {
11
+ ok: true;
12
+ origin: string;
13
+ warning: null | string;
14
+ };
15
+ /**
16
+ * Whether credentials may be sent to `raw`: an http(s) URL with no user name
17
+ * or password in it, and plain http only to this machine. A host that is not
18
+ * devicecloud.dev passes with a warning (a staging or self-run API).
19
+ */
20
+ export declare function checkApiUrl(raw: string): ApiUrlCheck;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Checks for an API URL given by hand (`--api-url`, `DCD_API_URL`), before
3
+ * any credential is sent to it: the API key or login session goes with every
4
+ * request, and a repository's MCP config can set DCD_API_URL. No imports, so
5
+ * the telemetry service can use it too.
6
+ */
7
+ /** This machine: plain http is fine, for a local API. */
8
+ function isLocalHost(host) {
9
+ return host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1' || host === '[::1]';
10
+ }
11
+ /** DeviceCloud's own hosts. */
12
+ function isDeviceCloudHost(host) {
13
+ return host === 'devicecloud.dev' || host.endsWith('.devicecloud.dev');
14
+ }
15
+ /**
16
+ * Whether credentials may be sent to `raw`: an http(s) URL with no user name
17
+ * or password in it, and plain http only to this machine. A host that is not
18
+ * devicecloud.dev passes with a warning (a staging or self-run API).
19
+ */
20
+ export function checkApiUrl(raw) {
21
+ let url;
22
+ try {
23
+ url = new URL(raw);
24
+ }
25
+ catch {
26
+ return { ok: false, reason: `The API URL "${raw}" is not a URL. Use one like https://api.devicecloud.dev.` };
27
+ }
28
+ const host = url.hostname.toLowerCase();
29
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
30
+ return { ok: false, reason: `The API URL must start with https://, not ${url.protocol}//.` };
31
+ }
32
+ if (url.username || url.password) {
33
+ return { ok: false, reason: 'The API URL must not contain a user name or password.' };
34
+ }
35
+ if (url.protocol === 'http:' && !isLocalHost(host)) {
36
+ return {
37
+ ok: false,
38
+ reason: `Refusing to send your API key or login session to ${url.origin} over plain http, where anyone on the way can read it. Use https.`,
39
+ };
40
+ }
41
+ const trusted = isDeviceCloudHost(host) || isLocalHost(host);
42
+ return {
43
+ ok: true,
44
+ origin: url.origin,
45
+ warning: trusted
46
+ ? null
47
+ : `The API URL ${url.origin} is not a devicecloud.dev host. Your API key or login session is sent to it with every request.`,
48
+ };
49
+ }