@devicecloud.dev/dcd 5.11.0-beta.9 → 5.11.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.
@@ -9,6 +9,18 @@ import type { AuthContext } from '../types/domain/auth.types.js';
9
9
  export declare const CALL_TIMEOUT_MS: number;
10
10
  /** A hosted tool with this bridge's local inputs added. */
11
11
  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;
12
24
  /**
13
25
  * Do the local part of a call (uploads, reading a file) and return the
14
26
  * arguments the hosted tool takes.
@@ -17,6 +29,19 @@ export declare function resolveLocalInputs(name: string, args: Record<string, un
17
29
  apiUrl: string;
18
30
  auth: AuthContext;
19
31
  }): Promise<Record<string, unknown>>;
32
+ /** How recent an open session must be to count as one a failed start may have made. */
33
+ export declare const START_RECOVERY_WINDOW_MS: number;
34
+ /**
35
+ * What to tell the agent when a start_device call failed without an answer
36
+ * (the connection dropped, or the server never replied). The request may
37
+ * still have started a session, which is billed while it runs, and an agent
38
+ * that just retries would end up with two. So list the open sessions started
39
+ * in the last couple of minutes, and say to check before starting again.
40
+ */
41
+ export declare function explainFailedStart(message: string, ctx: {
42
+ apiUrl: string;
43
+ auth: AuthContext;
44
+ }, now?: number): Promise<string>;
20
45
  /**
21
46
  * Build the `dcd mcp` server. Without a reachable hosted endpoint (no
22
47
  * credentials yet, or an API without it), it still serves the dcd_* tools
@@ -16,11 +16,15 @@
16
16
  * stdout is the JSON-RPC channel: everything else goes to stderr.
17
17
  */
18
18
  import { readFile, stat } from 'node:fs/promises';
19
+ import * as path from 'node:path';
19
20
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
20
21
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
21
22
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
22
23
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
23
24
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
25
+ import { DeviceGateway } from '../gateways/device-gateway.js';
26
+ import { processDependencies, readTestYamlFileAsJson } from '../services/execution-plan.utils.js';
27
+ import { computeCommonRoot } from '../services/flow-paths.js';
24
28
  import { uploadLocalApp } from '../utils/app-upload.js';
25
29
  import { getCliVersion } from '../utils/cli.js';
26
30
  import { uploadFlowBundle } from '../utils/device-bundle.js';
@@ -47,7 +51,7 @@ const LOCAL_INPUTS = {
47
51
  },
48
52
  },
49
53
  run: {
50
- description: ' Or pass path: a flow file on this machine (sent as yaml), or a directory of flows (flow picks the entry file inside it). Only the YAML files and the files the flows use (scripts, media) are uploaded, not builds or anything else in the directory.',
54
+ description: ' Or pass path: a flow file on this machine, or a directory of flows (flow picks the entry file inside it). A file that uses other files (runFlow, runScript, addMedia and the like) is uploaded with its folder; one that uses none is sent as yaml. Only the YAML files and the files the flows use (scripts, media) are uploaded, not builds or anything else in the directory.',
51
55
  properties: {
52
56
  path: {
53
57
  type: 'string',
@@ -70,6 +74,30 @@ export function withLocalInputs(tool) {
70
74
  },
71
75
  };
72
76
  }
77
+ /**
78
+ * For a single flow file that uses other files (runFlow, runScript, addMedia
79
+ * and the like): the folder to upload as a bundle, and the file's path
80
+ * inside it. Sent as yaml on its own, the flow would fail on the device with
81
+ * an invalid file path, because the files it uses would not be there. Null
82
+ * when the flow uses no other files, or can't be read (the device reports
83
+ * that itself).
84
+ */
85
+ export function flowFileBundle(file) {
86
+ const absolute = path.resolve(file);
87
+ let deps;
88
+ try {
89
+ const { config, testSteps } = readTestYamlFileAsJson(absolute);
90
+ deps = processDependencies({ config, input: absolute, testSteps });
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ // A missing file goes this way too, so the upload names it.
96
+ if (deps.allFiles.length === 0 && deps.allErrors.length === 0)
97
+ return null;
98
+ const dir = computeCommonRoot([absolute], deps.allFiles) || path.dirname(absolute);
99
+ return { dir, entry: path.relative(dir, absolute) };
100
+ }
73
101
  /**
74
102
  * Do the local part of a call (uploads, reading a file) and return the
75
103
  * arguments the hosted tool takes.
@@ -101,10 +129,46 @@ export async function resolveLocalInputs(name, args, ctx) {
101
129
  });
102
130
  return { ...rest, flow_upload_id: bundle.id };
103
131
  }
132
+ const bundled = flowFileBundle(flowPath);
133
+ if (bundled) {
134
+ logStderr(`${flowPath} uses other files; uploading it with ${bundled.dir}…`);
135
+ const bundle = await uploadFlowBundle({ ...ctx, ...bundled, log: logStderr });
136
+ return { ...rest, flow: bundled.entry, flow_upload_id: bundle.id };
137
+ }
104
138
  return { ...rest, yaml: await readFile(flowPath, 'utf8') };
105
139
  }
106
140
  return args;
107
141
  }
142
+ /** How recent an open session must be to count as one a failed start may have made. */
143
+ export const START_RECOVERY_WINDOW_MS = 2 * 60 * 1000;
144
+ /**
145
+ * What to tell the agent when a start_device call failed without an answer
146
+ * (the connection dropped, or the server never replied). The request may
147
+ * still have started a session, which is billed while it runs, and an agent
148
+ * that just retries would end up with two. So list the open sessions started
149
+ * in the last couple of minutes, and say to check before starting again.
150
+ */
151
+ export async function explainFailedStart(message, ctx, now = Date.now()) {
152
+ const head = `start_device failed: ${message}. The request may still have started a session, and a session is billed while it runs.`;
153
+ let recent;
154
+ try {
155
+ const { sessions } = await DeviceGateway.list(ctx.apiUrl, ctx.auth);
156
+ recent = sessions.filter((s) => now - Date.parse(s.created_at) <= START_RECOVERY_WINDOW_MS);
157
+ }
158
+ catch {
159
+ return `${head} Call list_devices to check for one before you call start_device again.`;
160
+ }
161
+ if (recent.length === 0) {
162
+ return `${head} No session was started in the last ${START_RECOVERY_WINDOW_MS / 60_000} minutes, so it is safe to call start_device again.`;
163
+ }
164
+ const listed = recent.map((s) => ({
165
+ client_label: s.client_label,
166
+ created_at: s.created_at,
167
+ id: s.id,
168
+ state: s.state,
169
+ }));
170
+ return `${head} Open sessions started in the last ${START_RECOVERY_WINDOW_MS / 60_000} minutes: ${JSON.stringify(listed)}. If one is yours, use it (get_device_status with wait: true until it is ready) instead of starting another. Otherwise stop it with stop_device. Check list_devices before you call start_device again.`;
171
+ }
108
172
  /**
109
173
  * The hosted device tools, over one connection made on first use and shared
110
174
  * by every call.
@@ -206,8 +270,18 @@ export async function createBridgeServer(opts = {}) {
206
270
  return errorResult(`${name} is not available in read-only mode.`);
207
271
  }
208
272
  const client = await remote.connect();
209
- const remoteArgs = await resolveLocalInputs(name, args, await getContext());
210
- return (await client.callTool({ name, arguments: remoteArgs }, undefined, options));
273
+ const ctx = await getContext();
274
+ const remoteArgs = await resolveLocalInputs(name, args, ctx);
275
+ try {
276
+ return (await client.callTool({ name, arguments: remoteArgs }, undefined, options));
277
+ }
278
+ catch (error) {
279
+ // A tool's own refusal comes back as a result. A throw means no answer
280
+ // arrived, so for a start the session's fate is unknown.
281
+ if (name !== 'start_device' || extra.signal.aborted)
282
+ throw error;
283
+ return errorResult(await explainFailedStart(error instanceof Error ? error.message : String(error), ctx));
284
+ }
211
285
  });
212
286
  });
213
287
  return server;
@@ -1,4 +1,17 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type IExecutionPlan } from '../../services/execution-plan.service.js';
3
+ import { type FlowMetadataEntry } from '../../services/flow-paths.js';
4
+ /**
5
+ * The flows a dry run lists: the ones a real run would submit, after the
6
+ * include/exclude tags and excludeFlows, as `dcd cloud --dry-run` lists
7
+ * them. `flowMetadata` holds every flow in the folder, filtered out or not,
8
+ * so it can't be the list.
9
+ */
10
+ export declare function dryRunFlows(executionPlan: Pick<IExecutionPlan, 'flowsToRun' | 'sequence'>, testMetadataMap: Record<string, FlowMetadataEntry>, commonRoot: string): {
11
+ file: string;
12
+ flowName: string;
13
+ tags: string[];
14
+ }[];
2
15
  /**
3
16
  * Submit a Maestro flow (or directory of flows) to devicecloud.dev.
4
17
  *
@@ -3,7 +3,7 @@ import { z } from 'zod';
3
3
  import { ApiGateway } from '../../gateways/api-gateway.js';
4
4
  import { plan } from '../../services/execution-plan.service.js';
5
5
  import { isSubmitEndpointMissing, submitWithRetry, } from '../../services/flow-submit.service.js';
6
- import { computeCommonRoot, buildTestMetadataMap } from '../../services/flow-paths.js';
6
+ import { computeCommonRoot, buildTestMetadataMap, } from '../../services/flow-paths.js';
7
7
  import { DeviceValidationService } from '../../services/device-validation.service.js';
8
8
  import { platformFromAppFile } from '../../services/notices.service.js';
9
9
  import { TestSubmissionService } from '../../services/test-submission.service.js';
@@ -13,6 +13,7 @@ import { refreshAuth } from '../../utils/auth.js';
13
13
  import { getCliVersion } from '../../utils/cli.js';
14
14
  import { fetchCompatibilityData } from '../../utils/compatibility.js';
15
15
  import { checkKekForEncryption, resolveEncryption } from '../../utils/envelope.js';
16
+ import { toPortableRelativePath } from '../../utils/paths.js';
16
17
  import { getConsoleUrl } from '../../utils/styling.js';
17
18
  import { getContext, logStderr } from '../context.js';
18
19
  import { jsonResult, runTool } from '../helpers.js';
@@ -20,6 +21,19 @@ const SUPPORTED_APP_EXTENSIONS = ['.apk', '.app', '.zip'];
20
21
  const POLL_INTERVAL_MS = 10_000;
21
22
  const TERMINAL_STATUSES = new Set(['PASSED', 'FAILED', 'CANCELLED', 'ERROR']);
22
23
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+ /**
25
+ * The flows a dry run lists: the ones a real run would submit, after the
26
+ * include/exclude tags and excludeFlows, as `dcd cloud --dry-run` lists
27
+ * them. `flowMetadata` holds every flow in the folder, filtered out or not,
28
+ * so it can't be the list.
29
+ */
30
+ export function dryRunFlows(executionPlan, testMetadataMap, commonRoot) {
31
+ return [...executionPlan.flowsToRun, ...(executionPlan.sequence?.flows ?? [])].map((absolute) => {
32
+ const file = toPortableRelativePath(absolute, commonRoot);
33
+ const meta = testMetadataMap[file];
34
+ return { file, flowName: meta?.flowName ?? path.parse(absolute).name, tags: meta?.tags ?? [] };
35
+ });
36
+ }
23
37
  /**
24
38
  * Submit a Maestro flow (or directory of flows) to devicecloud.dev.
25
39
  *
@@ -143,11 +157,7 @@ export function registerRunCloudTest(server) {
143
157
  if (args.dryRun) {
144
158
  return jsonResult({
145
159
  dryRun: true,
146
- flows: Object.entries(testMetadataMap).map(([file, meta]) => ({
147
- file,
148
- flowName: meta.flowName,
149
- tags: meta.tags,
150
- })),
160
+ flows: dryRunFlows(executionPlan, testMetadataMap, commonRoot),
151
161
  sequentialFlowCount: executionPlan.sequence?.flows.length ?? 0,
152
162
  });
153
163
  }
@@ -190,8 +190,11 @@ export function humanFields(human, now = Date.now()) {
190
190
  const fields = [['state', humanState(human)]];
191
191
  if (human.reason)
192
192
  fields.push(['reason', human.reason]);
193
+ // A person who took control unasked: the reason is "<email> took control",
194
+ // and nobody asked for anything.
195
+ const tookControl = human.human_in_control && !!human.reason?.endsWith(' took control');
193
196
  if (human.since)
194
- fields.push(['asked', formatWhen(human.since, now)]);
197
+ fields.push([tookControl ? 'since' : 'asked', formatWhen(human.since, now)]);
195
198
  if (human.waiting && human.expires_at) {
196
199
  fields.push(['ends', `${formatWhen(human.expires_at, now)} unless they hand it back`]);
197
200
  }
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.11.0-beta.9",
71
+ "version": "5.11.0",
72
72
  "bugs": {
73
73
  "url": "https://discord.gg/gm3mJwcNw8"
74
74
  },