@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.
- package/README.md +25 -2
- package/dist/commands/artifacts.d.ts +13 -0
- package/dist/commands/artifacts.js +43 -5
- package/dist/commands/device.d.ts +39 -0
- package/dist/commands/device.js +479 -101
- package/dist/e2e/index.d.ts +4 -0
- package/dist/e2e/index.js +41 -0
- package/dist/e2e/provider.d.ts +80 -0
- package/dist/e2e/provider.js +233 -0
- package/dist/gateways/api-gateway.d.ts +25 -3
- package/dist/gateways/api-gateway.js +68 -6
- package/dist/gateways/device-gateway.d.ts +34 -10
- package/dist/gateways/device-gateway.js +72 -17
- package/dist/mcp/bridge.d.ts +30 -16
- package/dist/mcp/bridge.js +201 -64
- package/dist/mcp/local-files.d.ts +14 -0
- package/dist/mcp/local-files.js +75 -0
- package/dist/mcp/tools/download-artifacts.d.ts +4 -1
- package/dist/mcp/tools/download-artifacts.js +44 -17
- package/dist/services/report-download.service.d.ts +32 -0
- package/dist/services/report-download.service.js +51 -2
- package/dist/services/telemetry.service.d.ts +20 -1
- package/dist/services/telemetry.service.js +27 -6
- package/dist/types/domain/device-session.types.d.ts +73 -3
- package/dist/types/domain/device-session.types.js +2 -0
- package/dist/utils/api-url.d.ts +20 -0
- package/dist/utils/api-url.js +49 -0
- package/dist/utils/app-upload.d.ts +6 -0
- package/dist/utils/app-upload.js +19 -0
- package/dist/utils/config-store.d.ts +5 -1
- package/dist/utils/config-store.js +18 -2
- package/dist/utils/device-artifacts.d.ts +5 -0
- package/dist/utils/device-artifacts.js +22 -0
- package/dist/utils/device-bundle.d.ts +39 -9
- package/dist/utils/device-bundle.js +153 -51
- package/dist/utils/device-flags.d.ts +17 -0
- package/dist/utils/device-flags.js +145 -0
- package/dist/utils/device-output.d.ts +53 -7
- package/dist/utils/device-output.js +148 -21
- package/dist/utils/device-run.d.ts +8 -3
- package/dist/utils/device-run.js +85 -8
- package/dist/utils/zip-integrity.d.ts +21 -0
- package/dist/utils/zip-integrity.js +45 -0
- package/package.json +10 -1
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
135
|
-
|
|
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
|
};
|
package/dist/mcp/bridge.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
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;
|
package/dist/mcp/bridge.js
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
* runs (createServer), reached over an in-memory transport.
|
|
6
6
|
* - The device tools, proxied from the hosted endpoint at `<api>/mcp`, so
|
|
7
7
|
* they are defined (and contract-tested) once, in the API. The bridge adds
|
|
8
|
-
* what a remote server can't do: `install_app`
|
|
9
|
-
* and `run` takes a local `path` (a flow file, or a
|
|
10
|
-
* a bundle)
|
|
8
|
+
* what a remote server can't do: `start_device` and `install_app` take a
|
|
9
|
+
* local `app_path`, and `run` takes a local `path` (a flow file, or a
|
|
10
|
+
* directory uploaded as a bundle), which must be inside the working
|
|
11
|
+
* directory (local-files.ts).
|
|
11
12
|
*
|
|
12
13
|
* Auth is the CLI's: an API key or a `dcd login` session (getContext). The
|
|
13
14
|
* hosted endpoint accepts both. A session is renewed before it expires; the
|
|
@@ -15,22 +16,25 @@
|
|
|
15
16
|
*
|
|
16
17
|
* stdout is the JSON-RPC channel: everything else goes to stderr.
|
|
17
18
|
*/
|
|
19
|
+
import { randomBytes } from 'node:crypto';
|
|
20
|
+
import { realpathSync } from 'node:fs';
|
|
18
21
|
import { readFile, stat } from 'node:fs/promises';
|
|
19
|
-
import * as path from 'node:path';
|
|
20
22
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
21
23
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
22
24
|
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
|
|
23
25
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
24
26
|
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
25
27
|
import { DeviceGateway, START_RECOVERY_WINDOW_MS } from '../gateways/device-gateway.js';
|
|
26
|
-
import { processDependencies, readTestYamlFileAsJson } from '../services/execution-plan.utils.js';
|
|
27
|
-
import { computeCommonRoot } from '../services/flow-paths.js';
|
|
28
28
|
import { uploadLocalApp } from '../utils/app-upload.js';
|
|
29
29
|
import { getCliVersion } from '../utils/cli.js';
|
|
30
|
-
import {
|
|
30
|
+
import { downloadFile } from '../utils/device-artifacts.js';
|
|
31
|
+
import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bundle.js';
|
|
31
32
|
import { getContext, isReadOnly, logStderr } from './context.js';
|
|
32
33
|
import { errorResult, runTool } from './helpers.js';
|
|
34
|
+
import { isInside, localInput, localOutput, markWritten, workingDirectory } from './local-files.js';
|
|
33
35
|
import { createServer } from './server.js';
|
|
36
|
+
// Moved to utils/device-bundle.ts, where `dcd device run` uses it too.
|
|
37
|
+
export { flowFileBundle } from '../utils/device-bundle.js';
|
|
34
38
|
/*
|
|
35
39
|
* Sent at initialize, before this server knows which hosted tools the
|
|
36
40
|
* account has: the hosted server only serves its tools to organizations that
|
|
@@ -38,6 +42,14 @@ import { createServer } from './server.js';
|
|
|
38
42
|
* themselves in their own descriptions.
|
|
39
43
|
*/
|
|
40
44
|
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.';
|
|
45
|
+
/** The header the API reads a connection's name from. */
|
|
46
|
+
export const CLIENT_INSTANCE_HEADER = 'x-dcd-client-instance';
|
|
47
|
+
/**
|
|
48
|
+
* This process's name for its connection to the hosted tools, the same for
|
|
49
|
+
* as long as it runs: one `dcd mcp` is one agent's connection, and a
|
|
50
|
+
* reconnect must not make its sessions someone else's.
|
|
51
|
+
*/
|
|
52
|
+
export const BRIDGE_INSTANCE = `dcd-mcp-${randomBytes(8).toString('hex')}`;
|
|
41
53
|
/**
|
|
42
54
|
* How long one forwarded call may take. Longer than dcd_run_cloud_test's
|
|
43
55
|
* longest wait (3600s) plus an upload. The MCP client calling this server
|
|
@@ -47,25 +59,45 @@ export const CALL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
|
|
|
47
59
|
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
60
|
/** The inputs this bridge adds to hosted tools, and what they say. */
|
|
49
61
|
const LOCAL_INPUTS = {
|
|
62
|
+
start_device: {
|
|
63
|
+
description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz) inside the working directory this server runs in: it is uploaded before the session starts, so no device time is spent on the upload.',
|
|
64
|
+
properties: {
|
|
65
|
+
app_path: {
|
|
66
|
+
type: 'string',
|
|
67
|
+
description: 'A build on this machine to upload and install when the device is ready, relative to the working directory or inside it. Pass this or app_binary_id.',
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
50
71
|
install_app: {
|
|
51
|
-
description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz), which is uploaded first.',
|
|
72
|
+
description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz) inside the working directory this server runs in, which is uploaded first.',
|
|
52
73
|
properties: {
|
|
53
74
|
app_path: {
|
|
54
75
|
type: 'string',
|
|
55
|
-
description: 'A build on this machine to upload and install. Pass this, app_binary_id or app_url.',
|
|
76
|
+
description: 'A build on this machine to upload and install, relative to the working directory or inside it. Pass this, app_binary_id or app_url.',
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
take_screenshot: {
|
|
81
|
+
description: ' With full_size, also pass path to save the PNG on this machine, inside the working directory this server runs in.',
|
|
82
|
+
properties: {
|
|
83
|
+
path: {
|
|
84
|
+
type: 'string',
|
|
85
|
+
description: 'Where to save the full-size PNG, relative to the working directory or inside it. Only with full_size: true. Not over a file this server did not write.',
|
|
56
86
|
},
|
|
57
87
|
},
|
|
58
88
|
},
|
|
59
89
|
run: {
|
|
60
|
-
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
|
|
90
|
+
description: ' Or pass path: a flow file (.yaml or .yml) on this machine, or a directory of flows (flow picks the entry file inside it), inside the working directory this server runs in. A file that uses other files (runFlow, runScript, addMedia and the like) is uploaded with them; one that uses none is sent as yaml. Only the flows and the files they use (scripts, media) are uploaded, not builds or anything else in the directory.',
|
|
61
91
|
properties: {
|
|
62
92
|
path: {
|
|
63
93
|
type: 'string',
|
|
64
|
-
description: 'A
|
|
94
|
+
description: 'A flow file or a directory of flows, relative to the working directory or inside it. Pass this, yaml or flow_upload_id.',
|
|
65
95
|
},
|
|
66
96
|
},
|
|
67
97
|
},
|
|
68
98
|
};
|
|
99
|
+
/** A flow file the device runs. */
|
|
100
|
+
const FLOW_FILE = /\.ya?ml$/i;
|
|
69
101
|
/** A hosted tool with this bridge's local inputs added. */
|
|
70
102
|
export function withLocalInputs(tool) {
|
|
71
103
|
const extra = LOCAL_INPUTS[tool.name];
|
|
@@ -80,71 +112,111 @@ export function withLocalInputs(tool) {
|
|
|
80
112
|
},
|
|
81
113
|
};
|
|
82
114
|
}
|
|
83
|
-
/**
|
|
84
|
-
* For a single flow file that uses other files (runFlow, runScript, addMedia
|
|
85
|
-
* and the like): the folder to upload as a bundle, and the file's path
|
|
86
|
-
* inside it. Sent as yaml on its own, the flow would fail on the device with
|
|
87
|
-
* an invalid file path, because the files it uses would not be there. Null
|
|
88
|
-
* when the flow uses no other files, or can't be read (the device reports
|
|
89
|
-
* that itself).
|
|
90
|
-
*/
|
|
91
|
-
export function flowFileBundle(file) {
|
|
92
|
-
const absolute = path.resolve(file);
|
|
93
|
-
let deps;
|
|
94
|
-
try {
|
|
95
|
-
const { config, testSteps } = readTestYamlFileAsJson(absolute);
|
|
96
|
-
deps = processDependencies({ config, input: absolute, testSteps });
|
|
97
|
-
}
|
|
98
|
-
catch {
|
|
99
|
-
return null;
|
|
100
|
-
}
|
|
101
|
-
// A missing file goes this way too, so the upload names it.
|
|
102
|
-
if (deps.allFiles.length === 0 && deps.allErrors.length === 0)
|
|
103
|
-
return null;
|
|
104
|
-
const dir = computeCommonRoot([absolute], deps.allFiles) || path.dirname(absolute);
|
|
105
|
-
return { dir, entry: path.relative(dir, absolute) };
|
|
106
|
-
}
|
|
107
115
|
/**
|
|
108
116
|
* Do the local part of a call (uploads, reading a file) and return the
|
|
109
117
|
* arguments the hosted tool takes.
|
|
110
118
|
*/
|
|
111
|
-
export async function resolveLocalInputs(name, args, ctx) {
|
|
112
|
-
if (name === 'install_app' && typeof args.app_path === 'string') {
|
|
119
|
+
export async function resolveLocalInputs(name, args, ctx, root = workingDirectory()) {
|
|
120
|
+
if ((name === 'install_app' || name === 'start_device') && typeof args.app_path === 'string') {
|
|
113
121
|
const { app_path: filePath, ...rest } = args;
|
|
114
|
-
|
|
122
|
+
if (rest.app_binary_id !== undefined || rest.app_url !== undefined) {
|
|
123
|
+
throw new Error('Pass app_path or app_binary_id (or app_url), not both.');
|
|
124
|
+
}
|
|
125
|
+
// Only inside the working directory, as run's path: an agent's call is
|
|
126
|
+
// not the user typing a path (local-files.ts), and a build from anywhere
|
|
127
|
+
// on disk would be uploaded to the team's storage.
|
|
128
|
+
const appFile = localInput(filePath, root);
|
|
129
|
+
logStderr(`Uploading ${appFile}…`);
|
|
115
130
|
const binaryId = await uploadLocalApp({
|
|
116
131
|
...ctx,
|
|
117
|
-
filePath:
|
|
132
|
+
filePath: appFile,
|
|
118
133
|
log: logStderr,
|
|
119
134
|
showProgress: false,
|
|
120
135
|
});
|
|
121
136
|
return { ...rest, app_binary_id: binaryId };
|
|
122
137
|
}
|
|
138
|
+
if (name === 'take_screenshot' && args.path !== undefined) {
|
|
139
|
+
// The hosted tool takes no path: the bridge saves the file
|
|
140
|
+
// (saveFullScreenshot) once the link comes back.
|
|
141
|
+
const { path: _saveTo, ...rest } = args;
|
|
142
|
+
return rest;
|
|
143
|
+
}
|
|
123
144
|
if (name === 'run' && typeof args.path === 'string') {
|
|
124
|
-
const { path:
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
145
|
+
const { path: given, ...rest } = args;
|
|
146
|
+
// Only inside the working directory: an agent's call is not the user
|
|
147
|
+
// typing a path (local-files.ts).
|
|
148
|
+
const flowPath = localInput(given, root);
|
|
149
|
+
const info = await stat(flowPath);
|
|
150
|
+
// The API takes forward slashes; a path typed on Windows has backslashes.
|
|
151
|
+
const entry = typeof rest.flow === 'string' ? rest.flow.replaceAll('\\', '/') : undefined;
|
|
128
152
|
if (info.isDirectory()) {
|
|
129
153
|
logStderr(`Uploading the flows in ${flowPath}…`);
|
|
130
|
-
const bundle = await uploadFlowBundle({
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
});
|
|
136
|
-
return { ...rest, flow_upload_id: bundle.id };
|
|
154
|
+
const bundle = await uploadFlowBundle({ ...ctx, confineTo: root, dir: flowPath, entry, log: logStderr });
|
|
155
|
+
return { ...rest, ...(entry !== undefined && { flow: entry }), flow_upload_id: bundle.id };
|
|
156
|
+
}
|
|
157
|
+
if (!FLOW_FILE.test(flowPath)) {
|
|
158
|
+
throw new Error(`${given} is not a flow file: path takes a .yaml or .yml file, or a directory of flows.`);
|
|
137
159
|
}
|
|
138
160
|
const bundled = flowFileBundle(flowPath);
|
|
139
161
|
if (bundled) {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
162
|
+
// The files it uses go too, so they must be inside as well.
|
|
163
|
+
if (!isInside(realpathSync(bundled.dir), root)) {
|
|
164
|
+
throw new Error(`${given} uses files outside the working directory (${root}). This server uploads only from there: start it in a folder that holds the flow and every file it uses.`);
|
|
165
|
+
}
|
|
166
|
+
logStderr(`${given} uses other files; uploading it with them, from ${bundled.dir}…`);
|
|
167
|
+
const bundle = await uploadFlowBundle({ ...ctx, ...bundled, confineTo: root, log: logStderr });
|
|
168
|
+
return { ...rest, flow: bundlePath(bundled.entry), flow_upload_id: bundle.id };
|
|
143
169
|
}
|
|
144
170
|
return { ...rest, yaml: await readFile(flowPath, 'utf8') };
|
|
145
171
|
}
|
|
146
172
|
return args;
|
|
147
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Where a take_screenshot call asks for the full-size PNG to be saved, checked
|
|
176
|
+
* before the call is made: inside the working directory, not over a file this
|
|
177
|
+
* server did not write. Null when it asks for no file.
|
|
178
|
+
*/
|
|
179
|
+
export function screenshotTarget(args, root = workingDirectory()) {
|
|
180
|
+
if (args.path === undefined)
|
|
181
|
+
return null;
|
|
182
|
+
if (typeof args.path !== 'string' || args.path.trim() === '') {
|
|
183
|
+
throw new Error('path is where to save the full-size PNG, a file name inside the working directory.');
|
|
184
|
+
}
|
|
185
|
+
if (args.full_size !== true) {
|
|
186
|
+
throw new Error('path saves a full-size screenshot: pass full_size: true with it.');
|
|
187
|
+
}
|
|
188
|
+
return localOutput(args.path, root);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Save the full-size PNG a take_screenshot call linked to, and say so in its
|
|
192
|
+
* result. The link stays in the result whatever happens here: a download
|
|
193
|
+
* that fails says why, and the agent can still use the link.
|
|
194
|
+
*/
|
|
195
|
+
export async function saveFullScreenshot(result, target, download = downloadFile) {
|
|
196
|
+
if (result.isError)
|
|
197
|
+
return result;
|
|
198
|
+
const note = (text) => ({ ...result, content: [...result.content, { type: 'text', text }] });
|
|
199
|
+
const first = result.content.find((c) => c.type === 'text');
|
|
200
|
+
let url;
|
|
201
|
+
try {
|
|
202
|
+
url = JSON.parse(first && first.type === 'text' ? first.text : '{}')
|
|
203
|
+
.full_size?.url;
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
url = undefined;
|
|
207
|
+
}
|
|
208
|
+
if (typeof url !== 'string' || !/^https?:\/\//.test(url)) {
|
|
209
|
+
return note('Not saved: the answer had no link to a full-size screenshot.');
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
await download(url, target);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
return note(`Not saved to ${target}: ${error instanceof Error ? error.message : String(error)}. The link above still works for an hour.`);
|
|
216
|
+
}
|
|
217
|
+
markWritten(target);
|
|
218
|
+
return note(`Saved to ${target}.`);
|
|
219
|
+
}
|
|
148
220
|
/**
|
|
149
221
|
* What to tell the agent when a start_device call failed without an answer
|
|
150
222
|
* (the connection dropped, or the server never replied). The request may
|
|
@@ -182,6 +254,8 @@ export async function explainFailedStart(message, ctx, now = Date.now()) {
|
|
|
182
254
|
class RemoteDevices {
|
|
183
255
|
connecting = null;
|
|
184
256
|
tools = null;
|
|
257
|
+
/** Why the last listing gave no device tools, while it did not. */
|
|
258
|
+
unavailable = null;
|
|
185
259
|
/** Calls that arrive together share one connect. A failed one is retried by the next call. */
|
|
186
260
|
connect() {
|
|
187
261
|
this.connecting ??= this.open().catch((error) => {
|
|
@@ -203,18 +277,38 @@ class RemoteDevices {
|
|
|
203
277
|
const headers = new Headers(init?.headers);
|
|
204
278
|
for (const [key, value] of Object.entries(auth.headers))
|
|
205
279
|
headers.set(key, value);
|
|
280
|
+
// This process, by name: the sessions it starts are its own
|
|
281
|
+
// (started_by.this_client), and a call that names no session takes
|
|
282
|
+
// one of them, never a session another process started.
|
|
283
|
+
headers.set(CLIENT_INSTANCE_HEADER, BRIDGE_INSTANCE);
|
|
206
284
|
return fetch(url, { ...init, headers });
|
|
207
285
|
},
|
|
208
286
|
}));
|
|
209
287
|
return client;
|
|
210
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* The hosted device tools. A list that came back empty is not kept, nor is
|
|
291
|
+
* a failure: the next call asks again, so signing in or the organization
|
|
292
|
+
* being enabled later is picked up without a restart.
|
|
293
|
+
*/
|
|
211
294
|
async list() {
|
|
212
295
|
if (this.tools)
|
|
213
296
|
return this.tools;
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
297
|
+
try {
|
|
298
|
+
const client = await this.connect();
|
|
299
|
+
const { tools } = await client.listTools();
|
|
300
|
+
if (tools.length === 0) {
|
|
301
|
+
this.unavailable = NO_DEVICE_TOOLS;
|
|
302
|
+
return tools;
|
|
303
|
+
}
|
|
304
|
+
this.tools = tools;
|
|
305
|
+
this.unavailable = null;
|
|
306
|
+
return tools;
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
this.unavailable = error instanceof Error ? error.message : String(error);
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
218
312
|
}
|
|
219
313
|
has(name) {
|
|
220
314
|
return this.tools?.some((t) => t.name === name) ?? false;
|
|
@@ -224,10 +318,25 @@ class RemoteDevices {
|
|
|
224
318
|
return this.tools?.find((t) => t.name === name)?.annotations?.readOnlyHint === true;
|
|
225
319
|
}
|
|
226
320
|
}
|
|
321
|
+
/** Why an account sees no device tools when the endpoint answered. */
|
|
322
|
+
const NO_DEVICE_TOOLS = 'the hosted server offers no device tools to this account: Agent Devices may not be enabled for your organization';
|
|
323
|
+
/**
|
|
324
|
+
* Listed in place of the device tools while they can't be loaded, so the
|
|
325
|
+
* agent sees why (in its description) and can load them once that is fixed.
|
|
326
|
+
*/
|
|
327
|
+
export const LOAD_DEVICE_TOOLS = 'load_device_tools';
|
|
328
|
+
function loadDeviceToolsTool(reason) {
|
|
329
|
+
return {
|
|
330
|
+
name: LOAD_DEVICE_TOOLS,
|
|
331
|
+
description: `The device tools (start_device and the rest, for driving a cloud phone) could not be loaded: ${reason}. Once that is fixed (for example after \`dcd login\`), call this to load them.`,
|
|
332
|
+
inputSchema: { type: 'object', properties: {} },
|
|
333
|
+
annotations: { readOnlyHint: true },
|
|
334
|
+
};
|
|
335
|
+
}
|
|
227
336
|
/**
|
|
228
337
|
* Build the `dcd mcp` server. Without a reachable hosted endpoint (no
|
|
229
|
-
* credentials yet, or an API without it), it still serves the dcd_* tools
|
|
230
|
-
*
|
|
338
|
+
* credentials yet, or an API without it), it still serves the dcd_* tools,
|
|
339
|
+
* says why on stderr, and lists load_device_tools, which says why too.
|
|
231
340
|
*/
|
|
232
341
|
export async function createBridgeServer(opts = {}) {
|
|
233
342
|
const callTimeoutMs = opts.callTimeoutMs ?? CALL_TIMEOUT_MS;
|
|
@@ -239,7 +348,8 @@ export async function createBridgeServer(opts = {}) {
|
|
|
239
348
|
const remote = new RemoteDevices();
|
|
240
349
|
const readOnly = isReadOnly();
|
|
241
350
|
const server = new Server({ name: 'devicecloud', version: getCliVersion() }, {
|
|
242
|
-
|
|
351
|
+
// listChanged: the device tools can arrive after the first listing.
|
|
352
|
+
capabilities: { tools: { listChanged: true } },
|
|
243
353
|
instructions: readOnly ? READ_ONLY_INSTRUCTIONS : INSTRUCTIONS,
|
|
244
354
|
});
|
|
245
355
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
@@ -251,8 +361,12 @@ export async function createBridgeServer(opts = {}) {
|
|
|
251
361
|
.filter((t) => !readOnly || t.annotations?.readOnlyHint === true)
|
|
252
362
|
.map((t) => withLocalInputs(t));
|
|
253
363
|
}
|
|
254
|
-
catch
|
|
255
|
-
|
|
364
|
+
catch {
|
|
365
|
+
// remote.unavailable says why.
|
|
366
|
+
}
|
|
367
|
+
if (remote.unavailable) {
|
|
368
|
+
logStderr(`Device tools unavailable: ${remote.unavailable}. Serving the dcd_* tools only.`);
|
|
369
|
+
return { tools: [...localTools, loadDeviceToolsTool(remote.unavailable)] };
|
|
256
370
|
}
|
|
257
371
|
return { tools: [...localTools, ...deviceTools] };
|
|
258
372
|
});
|
|
@@ -265,8 +379,28 @@ export async function createBridgeServer(opts = {}) {
|
|
|
265
379
|
if (localNames.has(name)) {
|
|
266
380
|
return (await local.callTool({ name, arguments: args }, undefined, options));
|
|
267
381
|
}
|
|
382
|
+
if (name === LOAD_DEVICE_TOOLS) {
|
|
383
|
+
return runTool(`device ${name}`, async () => {
|
|
384
|
+
const tools = await remote.list().catch(() => []);
|
|
385
|
+
if (tools.length === 0) {
|
|
386
|
+
return errorResult(`The device tools are still unavailable: ${remote.unavailable ?? 'no answer'}.`);
|
|
387
|
+
}
|
|
388
|
+
await server.sendToolListChanged();
|
|
389
|
+
return {
|
|
390
|
+
content: [
|
|
391
|
+
{
|
|
392
|
+
type: 'text',
|
|
393
|
+
text: `Loaded the device tools: ${tools.map((t) => t.name).join(', ')}. List the tools again to see them.`,
|
|
394
|
+
},
|
|
395
|
+
],
|
|
396
|
+
};
|
|
397
|
+
});
|
|
398
|
+
}
|
|
268
399
|
return runTool(`device ${name}`, async () => {
|
|
269
|
-
await remote.list();
|
|
400
|
+
await remote.list().catch(() => []);
|
|
401
|
+
if (remote.unavailable) {
|
|
402
|
+
return errorResult(`${name} is not available: the device tools could not be loaded (${remote.unavailable}).`);
|
|
403
|
+
}
|
|
270
404
|
if (!remote.has(name)) {
|
|
271
405
|
// In read-only mode the hosted server lists only its read-only tools,
|
|
272
406
|
// so a device tool that changes something is unknown here as well.
|
|
@@ -280,9 +414,12 @@ export async function createBridgeServer(opts = {}) {
|
|
|
280
414
|
}
|
|
281
415
|
const client = await remote.connect();
|
|
282
416
|
const ctx = await getContext();
|
|
417
|
+
// Checked before the device is asked: a bad path is refused at once.
|
|
418
|
+
const saveTo = name === 'take_screenshot' ? screenshotTarget(args) : null;
|
|
283
419
|
const remoteArgs = await resolveLocalInputs(name, args, ctx);
|
|
284
420
|
try {
|
|
285
|
-
|
|
421
|
+
const result = (await client.callTool({ name, arguments: remoteArgs }, undefined, options));
|
|
422
|
+
return saveTo ? await saveFullScreenshot(result, saveTo) : result;
|
|
286
423
|
}
|
|
287
424
|
catch (error) {
|
|
288
425
|
// A tool's own refusal comes back as a result. A throw means no answer
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** The working directory, as the file system names it (symbolic links resolved). */
|
|
2
|
+
export declare function workingDirectory(): string;
|
|
3
|
+
/** Whether `child` is `parent` or inside it. Both absolute and resolved. */
|
|
4
|
+
export declare function isInside(child: string, parent: string): boolean;
|
|
5
|
+
/** An existing file or folder the agent named, resolved, inside the working directory. */
|
|
6
|
+
export declare function localInput(given: string, root?: string): string;
|
|
7
|
+
/**
|
|
8
|
+
* Where to write a file the agent asked for, resolved: inside the working
|
|
9
|
+
* directory, and not over a file this server did not write. Folders that do
|
|
10
|
+
* not exist yet are allowed; the writer makes them.
|
|
11
|
+
*/
|
|
12
|
+
export declare function localOutput(given: string, root?: string): string;
|
|
13
|
+
/** Record a file this server wrote, so a later call may write it again. */
|
|
14
|
+
export declare function markWritten(file: string): void;
|