@devicecloud.dev/dcd 5.14.1 → 5.15.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.
Files changed (40) hide show
  1. package/README.md +4 -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/gateways/api-gateway.d.ts +25 -3
  7. package/dist/gateways/api-gateway.js +68 -6
  8. package/dist/gateways/device-gateway.d.ts +34 -10
  9. package/dist/gateways/device-gateway.js +72 -17
  10. package/dist/mcp/bridge.d.ts +30 -16
  11. package/dist/mcp/bridge.js +201 -64
  12. package/dist/mcp/local-files.d.ts +14 -0
  13. package/dist/mcp/local-files.js +75 -0
  14. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  15. package/dist/mcp/tools/download-artifacts.js +44 -17
  16. package/dist/services/report-download.service.d.ts +32 -0
  17. package/dist/services/report-download.service.js +51 -2
  18. package/dist/services/telemetry.service.d.ts +20 -1
  19. package/dist/services/telemetry.service.js +27 -6
  20. package/dist/types/domain/device-session.types.d.ts +73 -3
  21. package/dist/types/domain/device-session.types.js +2 -0
  22. package/dist/utils/api-url.d.ts +20 -0
  23. package/dist/utils/api-url.js +49 -0
  24. package/dist/utils/app-upload.d.ts +6 -0
  25. package/dist/utils/app-upload.js +19 -0
  26. package/dist/utils/config-store.d.ts +5 -1
  27. package/dist/utils/config-store.js +18 -2
  28. package/dist/utils/device-artifacts.d.ts +5 -0
  29. package/dist/utils/device-artifacts.js +22 -0
  30. package/dist/utils/device-bundle.d.ts +39 -9
  31. package/dist/utils/device-bundle.js +153 -51
  32. package/dist/utils/device-flags.d.ts +17 -0
  33. package/dist/utils/device-flags.js +145 -0
  34. package/dist/utils/device-output.d.ts +53 -7
  35. package/dist/utils/device-output.js +148 -21
  36. package/dist/utils/device-run.d.ts +8 -3
  37. package/dist/utils/device-run.js +85 -8
  38. package/dist/utils/zip-integrity.d.ts +21 -0
  39. package/dist/utils/zip-integrity.js +45 -0
  40. package/package.json +1 -1
@@ -4,6 +4,16 @@ import type { AuthContext } from '../types/domain/auth.types.js';
4
4
  import type { LiveCommandStatus, LiveExecResult, LiveSession, LiveSessionSummary } from '../types/domain/live.types.js';
5
5
  import type { TeamSettings } from '../types/domain/team-settings.types.js';
6
6
  import { components, paths } from '../types/generated/schema.types.js';
7
+ /** Extra checks a bundle download makes before it trusts the manifest. */
8
+ interface BundleDownloadOptions {
9
+ /**
10
+ * The manifest's `filename` must start with this, or the download throws
11
+ * `unsupportedMessage` instead of falling back: how a filtered request
12
+ * tells an API that applied the filter from an older one that ignored it.
13
+ */
14
+ requiredFilenamePrefix?: string;
15
+ unsupportedMessage?: string;
16
+ }
7
17
  /** What went wrong in a bundle attempt, minus the route/timing added later. */
8
18
  type BundleFailure = Omit<BundleFallbackTelemetry, 'duration_ms' | 'route' | 'upload_id'>;
9
19
  /**
@@ -68,12 +78,19 @@ export declare const ApiGateway: {
68
78
  * back to the inline download endpoint. Definitive errors (e.g. not found)
69
79
  * surface through that inline path instead.
70
80
  */
71
- tryBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string): Promise<boolean>;
81
+ tryBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string, options?: BundleDownloadOptions): Promise<boolean>;
72
82
  /**
73
83
  * One bundle-download attempt. Resolves `true` once the ZIP is on disk, or
74
84
  * with the reason it fell through, for {@link tryBundleDownload} to record.
75
85
  */
76
- attemptBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string): Promise<BundleFailure | true>;
86
+ attemptBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string, options?: BundleDownloadOptions): Promise<BundleFailure | true>;
87
+ /**
88
+ * Fail an inline ZIP download that ended before its central directory: the
89
+ * API streams the ZIP as it builds it, so a failure after the headers can
90
+ * still close the response cleanly. Deletes the partial file, so nothing
91
+ * downstream (a CI artifact upload, say) picks up a corrupt ZIP.
92
+ */
93
+ assertInlineZipComplete(destinationPath: string, operation: string, route: string, uploadId: string): Promise<void>;
77
94
  /**
78
95
  * Look for an already-uploaded binary to skip re-uploading.
79
96
  *
@@ -99,7 +116,12 @@ export declare const ApiGateway: {
99
116
  } & {
100
117
  encrypted?: boolean;
101
118
  }>;
102
- downloadArtifactsZip(baseUrl: string, auth: AuthContext, uploadId: string, results: "ALL" | "FAILED", artifactsPath?: string): Promise<void>;
119
+ /**
120
+ * Download an upload's artifacts ZIP. With `resultId`, only the attempts of
121
+ * the flow run that result belongs to; the parameter is sent only when set,
122
+ * so an unfiltered request is exactly what it always was.
123
+ */
124
+ downloadArtifactsZip(baseUrl: string, auth: AuthContext, uploadId: string, results: "ALL" | "FAILED", artifactsPath?: string, resultId?: number): Promise<void>;
103
125
  finaliseUpload(config: {
104
126
  auth: AuthContext;
105
127
  backblazeSuccess: boolean;
@@ -1,9 +1,11 @@
1
1
  import { createWriteStream, mkdirSync } from 'node:fs';
2
+ import { rm } from 'node:fs/promises';
2
3
  import { homedir } from 'node:os';
3
4
  import * as path from 'node:path';
4
5
  import { Readable } from 'node:stream';
5
6
  import { pipeline } from 'node:stream/promises';
6
7
  import { telemetry, } from '../services/telemetry.service.js';
8
+ import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js';
7
9
  /** Expand a leading `~` to the home directory, as the download paths allow. */
8
10
  function expandHome(p) {
9
11
  return p.replace(/^~(?=$|\/|\\)/, homedir());
@@ -202,9 +204,9 @@ export const ApiGateway = {
202
204
  * back to the inline download endpoint. Definitive errors (e.g. not found)
203
205
  * surface through that inline path instead.
204
206
  */
205
- async tryBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation) {
207
+ async tryBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation, options = {}) {
206
208
  const startedAt = Date.now();
207
- const outcome = await this.attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation);
209
+ const outcome = await this.attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation, options);
208
210
  if (outcome === true)
209
211
  return true;
210
212
  // The fallback is silent to the user (the inline download still delivers
@@ -223,7 +225,7 @@ export const ApiGateway = {
223
225
  * One bundle-download attempt. Resolves `true` once the ZIP is on disk, or
224
226
  * with the reason it fell through, for {@link tryBundleDownload} to record.
225
227
  */
226
- async attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation) {
228
+ async attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation, options = {}) {
227
229
  let manifestRes;
228
230
  try {
229
231
  manifestRes = await fetch(`${baseUrl}${manifestEndpoint}`, {
@@ -249,6 +251,13 @@ export const ApiGateway = {
249
251
  if (!bundle?.bundleUrl || !bundle?.manifest || !bundle?.sig) {
250
252
  return failure('manifest_incomplete');
251
253
  }
254
+ // An API that predates a filter ignores it and bundles the whole upload,
255
+ // named as such. Thrown, not a fallback: the inline route would ignore the
256
+ // filter just the same and save the wrong ZIP.
257
+ const prefix = options.requiredFilenamePrefix;
258
+ if (prefix !== undefined && !bundle.filename?.startsWith(prefix)) {
259
+ throw new Error(options.unsupportedMessage ?? `${operation}: the API ignored the request filter`);
260
+ }
252
261
  let zipRes;
253
262
  try {
254
263
  zipRes = await fetch(bundle.bundleUrl, {
@@ -287,8 +296,43 @@ export const ApiGateway = {
287
296
  bytes_received: bytesReceived,
288
297
  });
289
298
  }
299
+ // A bundle that fails after its 200 headers still ends cleanly, so the
300
+ // stream above succeeds and leaves a ZIP with no central directory. Check
301
+ // before calling it done; the inline path then overwrites the file.
302
+ try {
303
+ await assertCompleteZip(expandHome(destinationPath));
304
+ }
305
+ catch (error) {
306
+ return failure('bundle_truncated', {
307
+ ...errorDetail(error),
308
+ bytes_received: bytesReceived,
309
+ });
310
+ }
290
311
  return true;
291
312
  },
313
+ /**
314
+ * Fail an inline ZIP download that ended before its central directory: the
315
+ * API streams the ZIP as it builds it, so a failure after the headers can
316
+ * still close the response cleanly. Deletes the partial file, so nothing
317
+ * downstream (a CI artifact upload, say) picks up a corrupt ZIP.
318
+ */
319
+ async assertInlineZipComplete(destinationPath, operation, route, uploadId) {
320
+ const file = expandHome(destinationPath);
321
+ try {
322
+ await assertCompleteZip(file);
323
+ }
324
+ catch (error) {
325
+ if (!(error instanceof IncompleteZipError))
326
+ throw error;
327
+ await rm(file, { force: true }).catch(() => { });
328
+ telemetry.recordDownloadIncomplete({
329
+ bytes: error.bytes,
330
+ route,
331
+ upload_id: uploadId,
332
+ });
333
+ throw new Error(`${operation}: the download ended early and ${error.message}. Please retry.`, { cause: error });
334
+ }
335
+ },
292
336
  /**
293
337
  * Look for an already-uploaded binary to skip re-uploading.
294
338
  *
@@ -328,14 +372,27 @@ export const ApiGateway = {
328
372
  throw error;
329
373
  }
330
374
  },
331
- async downloadArtifactsZip(baseUrl, auth, uploadId, results, artifactsPath = './artifacts.zip') {
375
+ /**
376
+ * Download an upload's artifacts ZIP. With `resultId`, only the attempts of
377
+ * the flow run that result belongs to; the parameter is sent only when set,
378
+ * so an unfiltered request is exactly what it always was.
379
+ */
380
+ async downloadArtifactsZip(baseUrl, auth, uploadId, results, artifactsPath = './artifacts.zip', resultId) {
381
+ const filtered = resultId !== undefined;
332
382
  // Prefer bundle delivery; fall back to the inline download below.
333
- if (await this.tryBundleDownload(baseUrl, auth, `/results/${uploadId}/artifacts-bundle?results=${results}`, artifactsPath, 'Failed to download artifacts')) {
383
+ if (await this.tryBundleDownload(baseUrl, auth, `/results/${uploadId}/artifacts-bundle?results=${results}` +
384
+ (filtered ? `&resultId=${resultId}` : ''), artifactsPath, 'Failed to download artifacts', filtered
385
+ ? {
386
+ // What the API names a bundle it narrowed to one result.
387
+ requiredFilenamePrefix: 'artifacts-result-',
388
+ unsupportedMessage: 'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.',
389
+ }
390
+ : {})) {
334
391
  return;
335
392
  }
336
393
  try {
337
394
  const res = await fetch(`${baseUrl}/results/${uploadId}/download`, {
338
- body: JSON.stringify({ results }),
395
+ body: JSON.stringify(filtered ? { results, resultId } : { results }),
339
396
  headers: {
340
397
  'content-type': 'application/json',
341
398
  ...auth.headers,
@@ -346,6 +403,7 @@ export const ApiGateway = {
346
403
  await this.handleApiError(res, 'Failed to download artifacts');
347
404
  }
348
405
  await this.streamResponseToFile(res, artifactsPath, 'Failed to download artifacts');
406
+ await this.assertInlineZipComplete(artifactsPath, 'Failed to download artifacts', 'download', uploadId);
349
407
  }
350
408
  catch (error) {
351
409
  if (error instanceof TypeError && error.message === 'fetch failed') {
@@ -772,6 +830,10 @@ export const ApiGateway = {
772
830
  throw new Error(`${errorPrefix}: ${res.status} ${errorText}`);
773
831
  }
774
832
  await this.streamResponseToFile(res, finalReportPath, errorPrefix);
833
+ // Only the HTML report is a ZIP; junit is XML and allure is one HTML file.
834
+ if (reportType === 'html') {
835
+ await this.assertInlineZipComplete(finalReportPath, errorPrefix, 'html-report', uploadId);
836
+ }
775
837
  }
776
838
  catch (error) {
777
839
  if (error instanceof TypeError && error.message === 'fetch failed') {
@@ -1,5 +1,5 @@
1
1
  import type { AuthContext } from '../types/domain/auth.types.js';
2
- import type { DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls, DeviceCatalogue, DeviceCommandResult, DeviceFlowBundle, DeviceHumanStatus, DeviceInstalledApp, DeviceLogs, DeviceRunResponse, DeviceScreen, DeviceScreenshot, DeviceSession, StartDeviceSessionRequest } from '../types/domain/device-session.types.js';
2
+ import type { DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls, DeviceCatalogue, DeviceCommandResult, DeviceFlowBundle, DeviceFullScreenshot, DeviceHumanStatus, DeviceInstalledApp, DeviceLogLevel, DeviceLogs, DeviceRunResponse, DeviceScreen, DeviceScreenshot, DeviceSession, StartDeviceSessionRequest } from '../types/domain/device-session.types.js';
3
3
  /**
4
4
  * An error answer from /device/sessions. Unlike ApiError it keeps the API's
5
5
  * machine code (`LIVE_NOT_FOUND`, `LIVE_SPEND_CAP`, …) and the `session`
@@ -8,6 +8,13 @@ import type { DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls,
8
8
  */
9
9
  export declare class DeviceApiError extends Error {
10
10
  code: null | string;
11
+ /**
12
+ * What else the answer said that a script can act on: how long to wait
13
+ * (`retry_after_s`), the limit that was hit (`limit`, `spent`), how far
14
+ * the device got (`phase`), or the command a wait was for (`command_id`).
15
+ * Printed in the --json envelope's `error` beside `code` and `message`.
16
+ */
17
+ details: Record<string, unknown>;
11
18
  /**
12
19
  * The API itself answered (its `{ statusCode, message }` envelope), not a
13
20
  * proxy in front of it. A proxy's 502 can come after the API did the work.
@@ -15,8 +22,14 @@ export declare class DeviceApiError extends Error {
15
22
  fromApi: boolean;
16
23
  session: DeviceSession | null;
17
24
  status: number;
18
- constructor(message: string, status: number, code: null | string, session: DeviceSession | null, fromApi?: boolean);
25
+ constructor(message: string, status: number, code: null | string, session: DeviceSession | null, fromApi?: boolean, details?: Record<string, unknown>);
19
26
  }
27
+ /**
28
+ * The message for an answer that is not the API's JSON: a proxy's page or
29
+ * plain text. An HTML page is cut to its title, as a whole page in a
30
+ * terminal, an envelope or a log says nothing a person can read.
31
+ */
32
+ export declare function plainErrorText(text: string, status: number): string;
20
33
  /** How recent an open session must be to count as one a failed start may have made. */
21
34
  export declare const START_RECOVERY_WINDOW_MS: number;
22
35
  /**
@@ -26,7 +39,6 @@ export declare const START_RECOVERY_WINDOW_MS: number;
26
39
  * before any session exists.
27
40
  */
28
41
  export declare function startOutcomeUnknown(error: unknown): boolean;
29
- /** The Agent Devices session API (dcd docs/device-v1-plan.md, section 4.1). */
30
42
  export declare const DeviceGateway: {
31
43
  artifacts(baseUrl: string, auth: AuthContext, id: string, before?: string): Promise<DeviceArtifactsPage>;
32
44
  bundleUploadUrls(baseUrl: string, auth: AuthContext, bytes: number): Promise<DeviceBundleUploadUrls>;
@@ -44,21 +56,25 @@ export declare const DeviceGateway: {
44
56
  binaryUploadId: string;
45
57
  } | {
46
58
  url: string;
47
- }): Promise<{
59
+ }, force?: boolean): Promise<{
48
60
  app: DeviceInstalledApp;
49
61
  session: DeviceSession;
50
62
  }>;
51
63
  launch(baseUrl: string, auth: AuthContext, id: string, body: {
52
64
  appId?: string;
53
65
  clearState?: boolean;
54
- }): Promise<{
66
+ }, force?: boolean): Promise<{
55
67
  result: DeviceCommandResult;
56
68
  session: DeviceSession;
57
69
  }>;
58
70
  list(baseUrl: string, auth: AuthContext, all?: boolean): Promise<{
59
71
  sessions: DeviceSession[];
60
72
  }>;
61
- logs(baseUrl: string, auth: AuthContext, id: string, lines: number): Promise<{
73
+ /** The app's recent log lines; `level` and `grep` narrow them (the API ignores both before it knew them). */
74
+ logs(baseUrl: string, auth: AuthContext, id: string, lines: number, filter?: {
75
+ grep?: string;
76
+ level?: DeviceLogLevel;
77
+ }): Promise<{
62
78
  logs: DeviceLogs;
63
79
  session: DeviceSession;
64
80
  }>;
@@ -79,12 +95,12 @@ export declare const DeviceGateway: {
79
95
  bundle: DeviceFlowBundle;
80
96
  }>;
81
97
  /** Ask a person for help: the session moves to needs_human until they hand it back. */
82
- requestHuman(baseUrl: string, auth: AuthContext, id: string, reason: string): Promise<{
98
+ requestHuman(baseUrl: string, auth: AuthContext, id: string, reason: string, force?: boolean): Promise<{
83
99
  human: DeviceHumanStatus;
84
100
  session: DeviceSession;
85
101
  }>;
86
102
  /** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */
87
- action(baseUrl: string, auth: AuthContext, id: string, body: DeviceActionRequest): Promise<{
103
+ action(baseUrl: string, auth: AuthContext, id: string, body: DeviceActionRequest, force?: boolean): Promise<{
88
104
  result: DeviceCommandResult;
89
105
  session: DeviceSession;
90
106
  }>;
@@ -95,18 +111,26 @@ export declare const DeviceGateway: {
95
111
  } | {
96
112
  env?: Record<string, string>;
97
113
  yaml: string;
98
- }): Promise<DeviceRunResponse>;
114
+ }, force?: boolean): Promise<DeviceRunResponse>;
99
115
  screenshot(baseUrl: string, auth: AuthContext, id: string): Promise<{
100
116
  screenshot: DeviceScreenshot;
101
117
  session: DeviceSession;
102
118
  }>;
119
+ /**
120
+ * A PNG at the device's own resolution, as a link. A device whose runner
121
+ * is too old for it answers LIVE_NOT_SUPPORTED.
122
+ */
123
+ fullScreenshot(baseUrl: string, auth: AuthContext, id: string): Promise<{
124
+ screenshot: DeviceFullScreenshot;
125
+ session: DeviceSession;
126
+ }>;
103
127
  start(baseUrl: string, auth: AuthContext, body: StartDeviceSessionRequest): Promise<{
104
128
  session: DeviceSession;
105
129
  }>;
106
130
  status(baseUrl: string, auth: AuthContext, id: string): Promise<{
107
131
  session: DeviceSession;
108
132
  }>;
109
- stop(baseUrl: string, auth: AuthContext, id: string): Promise<{
133
+ stop(baseUrl: string, auth: AuthContext, id: string, force?: boolean): Promise<{
110
134
  session: DeviceSession;
111
135
  }>;
112
136
  };
@@ -7,6 +7,13 @@ import { ApiGateway } from './api-gateway.js';
7
7
  */
8
8
  export class DeviceApiError extends Error {
9
9
  code;
10
+ /**
11
+ * What else the answer said that a script can act on: how long to wait
12
+ * (`retry_after_s`), the limit that was hit (`limit`, `spent`), how far
13
+ * the device got (`phase`), or the command a wait was for (`command_id`).
14
+ * Printed in the --json envelope's `error` beside `code` and `message`.
15
+ */
16
+ details;
10
17
  /**
11
18
  * The API itself answered (its `{ statusCode, message }` envelope), not a
12
19
  * proxy in front of it. A proxy's 502 can come after the API did the work.
@@ -14,15 +21,36 @@ export class DeviceApiError extends Error {
14
21
  fromApi;
15
22
  session;
16
23
  status;
17
- constructor(message, status, code, session, fromApi = false) {
24
+ constructor(message, status, code, session, fromApi = false, details = {}) {
18
25
  super(message);
19
26
  this.name = 'DeviceApiError';
20
27
  this.status = status;
21
28
  this.code = code;
22
29
  this.session = session;
23
30
  this.fromApi = fromApi;
31
+ this.details = details;
24
32
  }
25
33
  }
34
+ /** The fields of an error answer passed on to the caller, when the API sends them. */
35
+ const ERROR_DETAILS = ['retry_after_s', 'limit', 'spent', 'phase'];
36
+ /** The longest error text kept from an answer that is not the API's JSON. */
37
+ const MAX_PLAIN_ERROR = 300;
38
+ /**
39
+ * The message for an answer that is not the API's JSON: a proxy's page or
40
+ * plain text. An HTML page is cut to its title, as a whole page in a
41
+ * terminal, an envelope or a log says nothing a person can read.
42
+ */
43
+ export function plainErrorText(text, status) {
44
+ const trimmed = text.trim();
45
+ if (!trimmed)
46
+ return `HTTP ${status}`;
47
+ if (/^<(?:!doctype|html|head|body)\b/i.test(trimmed) || /<\/html>\s*$/i.test(trimmed)) {
48
+ const title = /<title[^>]*>([^<]*)<\/title>/i.exec(trimmed)?.[1]?.replaceAll(/\s+/g, ' ').trim();
49
+ return `HTTP ${status}: ${title || 'an error page'} (an HTML page, not the API's answer)`;
50
+ }
51
+ const oneLine = trimmed.replaceAll(/\s+/g, ' ');
52
+ return oneLine.length > MAX_PLAIN_ERROR ? `${oneLine.slice(0, MAX_PLAIN_ERROR)}…` : oneLine;
53
+ }
26
54
  /** How recent an open session must be to count as one a failed start may have made. */
27
55
  export const START_RECOVERY_WINDOW_MS = 2 * 60 * 1000;
28
56
  /**
@@ -51,7 +79,7 @@ async function toDeviceApiError(res, path) {
51
79
  // Not JSON: a proxy page or plain text. The text is the message.
52
80
  }
53
81
  const raw = Array.isArray(body.message) ? body.message.join('; ') : body.message;
54
- let message = typeof raw === 'string' && raw ? raw : text.trim() || `HTTP ${res.status}`;
82
+ let message = typeof raw === 'string' && raw ? raw : plainErrorText(text, res.status);
55
83
  if (res.status === 401) {
56
84
  message =
57
85
  'Authentication failed — your credentials are invalid or expired. ' +
@@ -70,7 +98,15 @@ async function toDeviceApiError(res, path) {
70
98
  // Nest's envelope always has a numeric statusCode. Railway's proxy answers
71
99
  // `{ status, code, message }`, or a page that isn't JSON at all.
72
100
  const fromApi = typeof body.statusCode === 'number';
73
- return new DeviceApiError(message, res.status, code, session, fromApi);
101
+ const details = {};
102
+ if (fromApi) {
103
+ for (const key of ERROR_DETAILS) {
104
+ const value = body[key];
105
+ if (typeof value === 'number' || typeof value === 'string')
106
+ details[key] = value;
107
+ }
108
+ }
109
+ return new DeviceApiError(message, res.status, code, session, fromApi, details);
74
110
  }
75
111
  async function request(baseUrl, auth, method, path, body) {
76
112
  const url = `${baseUrl}${path}`;
@@ -104,6 +140,12 @@ async function request(baseUrl, auth, method, path, body) {
104
140
  }
105
141
  const sessionPath = (id) => `/device/sessions/${encodeURIComponent(id)}`;
106
142
  /** The Agent Devices session API (dcd docs/device-v1-plan.md, section 4.1). */
143
+ /**
144
+ * A changing request's body, with `force` when asked: the API refuses an
145
+ * agent changing a session someone else started (LIVE_NOT_YOURS) unless it
146
+ * says so. Left out otherwise, so an older API sees the body it always did.
147
+ */
148
+ const withForce = (body, force) => force ? { ...body, force: true } : body;
107
149
  export const DeviceGateway = {
108
150
  artifacts(baseUrl, auth, id, before) {
109
151
  const query = new URLSearchParams({ limit: '200', ...(before && { before }) });
@@ -122,17 +164,23 @@ export const DeviceGateway = {
122
164
  inspect(baseUrl, auth, id, all = false) {
123
165
  return request(baseUrl, auth, 'GET', `${sessionPath(id)}/inspect${all ? '?all=true' : ''}`);
124
166
  },
125
- install(baseUrl, auth, id, app) {
126
- return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, app);
167
+ install(baseUrl, auth, id, app, force = false) {
168
+ return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, withForce(app, force));
127
169
  },
128
- launch(baseUrl, auth, id, body) {
129
- return request(baseUrl, auth, 'POST', `${sessionPath(id)}/launch`, body);
170
+ launch(baseUrl, auth, id, body, force = false) {
171
+ return request(baseUrl, auth, 'POST', `${sessionPath(id)}/launch`, withForce(body, force));
130
172
  },
131
173
  list(baseUrl, auth, all = false) {
132
174
  return request(baseUrl, auth, 'GET', `/device/sessions${all ? '?all=true' : ''}`);
133
175
  },
134
- logs(baseUrl, auth, id, lines) {
135
- return request(baseUrl, auth, 'GET', `${sessionPath(id)}/logs?lines=${lines}`);
176
+ /** The app's recent log lines; `level` and `grep` narrow them (the API ignores both before it knew them). */
177
+ logs(baseUrl, auth, id, lines, filter = {}) {
178
+ const query = new URLSearchParams({
179
+ lines: String(lines),
180
+ ...(filter.level && { level: filter.level }),
181
+ ...(filter.grep && { grep: filter.grep }),
182
+ });
183
+ return request(baseUrl, auth, 'GET', `${sessionPath(id)}/logs?${query}`);
136
184
  },
137
185
  models(baseUrl, auth) {
138
186
  return request(baseUrl, auth, 'GET', '/device/models');
@@ -154,26 +202,33 @@ export const DeviceGateway = {
154
202
  return request(baseUrl, auth, 'POST', '/device/bundles', body);
155
203
  },
156
204
  /** Ask a person for help: the session moves to needs_human until they hand it back. */
157
- requestHuman(baseUrl, auth, id, reason) {
158
- return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, { reason });
205
+ requestHuman(baseUrl, auth, id, reason, force = false) {
206
+ return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, withForce({ reason }, force));
159
207
  },
160
208
  /** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */
161
- action(baseUrl, auth, id, body) {
162
- return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, body);
209
+ action(baseUrl, auth, id, body, force = false) {
210
+ return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, withForce(body, force));
163
211
  },
164
- run(baseUrl, auth, id, body) {
165
- return request(baseUrl, auth, 'POST', `${sessionPath(id)}/run`, body);
212
+ run(baseUrl, auth, id, body, force = false) {
213
+ return request(baseUrl, auth, 'POST', `${sessionPath(id)}/run`, withForce(body, force));
166
214
  },
167
215
  screenshot(baseUrl, auth, id) {
168
216
  return request(baseUrl, auth, 'GET', `${sessionPath(id)}/screenshot`);
169
217
  },
218
+ /**
219
+ * A PNG at the device's own resolution, as a link. A device whose runner
220
+ * is too old for it answers LIVE_NOT_SUPPORTED.
221
+ */
222
+ fullScreenshot(baseUrl, auth, id) {
223
+ return request(baseUrl, auth, 'GET', `${sessionPath(id)}/screenshot?full=true`);
224
+ },
170
225
  start(baseUrl, auth, body) {
171
226
  return request(baseUrl, auth, 'POST', '/device/sessions', body);
172
227
  },
173
228
  status(baseUrl, auth, id) {
174
229
  return request(baseUrl, auth, 'GET', sessionPath(id));
175
230
  },
176
- stop(baseUrl, auth, id) {
177
- return request(baseUrl, auth, 'DELETE', sessionPath(id));
231
+ stop(baseUrl, auth, id, force = false) {
232
+ return request(baseUrl, auth, 'DELETE', `${sessionPath(id)}${force ? '?force=true' : ''}`);
178
233
  },
179
234
  };
@@ -1,6 +1,15 @@
1
1
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
- import { type Tool } from '@modelcontextprotocol/sdk/types.js';
2
+ import { type CallToolResult, type Tool } from '@modelcontextprotocol/sdk/types.js';
3
3
  import type { AuthContext } from '../types/domain/auth.types.js';
4
+ export { flowFileBundle } from '../utils/device-bundle.js';
5
+ /** The header the API reads a connection's name from. */
6
+ export declare const CLIENT_INSTANCE_HEADER = "x-dcd-client-instance";
7
+ /**
8
+ * This process's name for its connection to the hosted tools, the same for
9
+ * as long as it runs: one `dcd mcp` is one agent's connection, and a
10
+ * reconnect must not make its sessions someone else's.
11
+ */
12
+ export declare const BRIDGE_INSTANCE: string;
4
13
  /**
5
14
  * How long one forwarded call may take. Longer than dcd_run_cloud_test's
6
15
  * longest wait (3600s) plus an upload. The MCP client calling this server
@@ -9,18 +18,6 @@ import type { AuthContext } from '../types/domain/auth.types.js';
9
18
  export declare const CALL_TIMEOUT_MS: number;
10
19
  /** A hosted tool with this bridge's local inputs added. */
11
20
  export declare function withLocalInputs(tool: Tool): Tool;
12
- /**
13
- * For a single flow file that uses other files (runFlow, runScript, addMedia
14
- * and the like): the folder to upload as a bundle, and the file's path
15
- * inside it. Sent as yaml on its own, the flow would fail on the device with
16
- * an invalid file path, because the files it uses would not be there. Null
17
- * when the flow uses no other files, or can't be read (the device reports
18
- * that itself).
19
- */
20
- export declare function flowFileBundle(file: string): {
21
- dir: string;
22
- entry: string;
23
- } | null;
24
21
  /**
25
22
  * Do the local part of a call (uploads, reading a file) and return the
26
23
  * arguments the hosted tool takes.
@@ -28,7 +25,19 @@ export declare function flowFileBundle(file: string): {
28
25
  export declare function resolveLocalInputs(name: string, args: Record<string, unknown>, ctx: {
29
26
  apiUrl: string;
30
27
  auth: AuthContext;
31
- }): Promise<Record<string, unknown>>;
28
+ }, root?: string): Promise<Record<string, unknown>>;
29
+ /**
30
+ * Where a take_screenshot call asks for the full-size PNG to be saved, checked
31
+ * before the call is made: inside the working directory, not over a file this
32
+ * server did not write. Null when it asks for no file.
33
+ */
34
+ export declare function screenshotTarget(args: Record<string, unknown>, root?: string): null | string;
35
+ /**
36
+ * Save the full-size PNG a take_screenshot call linked to, and say so in its
37
+ * result. The link stays in the result whatever happens here: a download
38
+ * that fails says why, and the agent can still use the link.
39
+ */
40
+ export declare function saveFullScreenshot(result: CallToolResult, target: string, download?: (url: string, file: string) => Promise<void>): Promise<CallToolResult>;
32
41
  /**
33
42
  * What to tell the agent when a start_device call failed without an answer
34
43
  * (the connection dropped, or the server never replied). The request may
@@ -40,10 +49,15 @@ export declare function explainFailedStart(message: string, ctx: {
40
49
  apiUrl: string;
41
50
  auth: AuthContext;
42
51
  }, now?: number): Promise<string>;
52
+ /**
53
+ * Listed in place of the device tools while they can't be loaded, so the
54
+ * agent sees why (in its description) and can load them once that is fixed.
55
+ */
56
+ export declare const LOAD_DEVICE_TOOLS = "load_device_tools";
43
57
  /**
44
58
  * Build the `dcd mcp` server. Without a reachable hosted endpoint (no
45
- * credentials yet, or an API without it), it still serves the dcd_* tools
46
- * and says why on stderr.
59
+ * credentials yet, or an API without it), it still serves the dcd_* tools,
60
+ * says why on stderr, and lists load_device_tools, which says why too.
47
61
  */
48
62
  export declare function createBridgeServer(opts?: {
49
63
  callTimeoutMs?: number;