Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 62 additions & 16 deletions src/commands/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,18 @@ const commonArgs = { ...apiFlags, json: jsonFlag } as const;
const idArg = {
type: 'positional',
required: false,
description: 'Session id, e.g. brave-teal-otter. Optional when exactly one session is open.',
description: 'Session id, e.g. brave-teal-otter. Optional when you have exactly one open session.',
} as const;

/**
* For the commands that change a session: one someone else started (another
* person or another API key) is refused with LIVE_NOT_YOURS unless this is
* given. A teammate's agent may be using it.
*/
const forceArg = {
type: 'boolean',
default: false,
description: 'Change a session someone else started (another person or API key)',
} as const;

interface Ctx {
Expand Down Expand Up @@ -538,11 +549,12 @@ const statusSub = defineCommand({
});

const stopSub = defineCommand({
meta: { name: 'stop', description: 'Stop a session, or every open one with --all' },
meta: { name: 'stop', description: 'Stop a session, or every open one of yours with --all' },
args: {
...commonArgs,
id: idArg,
all: { type: 'boolean', default: false, description: "Stop every open session in your org" },
all: { type: 'boolean', default: false, description: 'Stop every open session of yours (with --force, everyone\'s)' },
force: forceArg,
},
async run({ args }) {
const json = Boolean(args.json);
Expand All @@ -551,26 +563,38 @@ const stopSub = defineCommand({
if (args.all) {
if (args.id) throw new CliError('Pass a session id or --all, not both.');
const { sessions } = await DeviceGateway.list(ctx.apiUrl, ctx.auth);
// Yours, or every one with --force: another's may be a teammate's
// agent at work. An API that does not say whose is read as before.
const force = Boolean(args.force);
const mine = sessions.filter((s) => force || !s.started_by || s.started_by.you);
const others = sessions.filter((s) => !mine.includes(s));
const stopped: DeviceSession[] = [];
for (const s of sessions) {
stopped.push((await DeviceGateway.stop(ctx.apiUrl, ctx.auth, s.id)).session);
for (const s of mine) {
stopped.push((await DeviceGateway.stop(ctx.apiUrl, ctx.auth, s.id, force)).session);
}

return {
session: undefined,
data: { stopped },
data: { left: others.map((s) => s.id), stopped },
print() {
logger.log(
stopped.length === 0
? ui.info('No open device sessions to stop.')
? ui.info('No open device sessions of yours to stop.')
: ui.success(`Stopped ${stopped.map((s) => s.id).join(', ')}`),
);
if (others.length > 0) {
logger.log(
ui.info(
`Left ${others.map((s) => s.id).join(', ')}, started by someone else. Add --force to stop those too.`,
),
);
}
},
};
}

const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined);
const { session } = await DeviceGateway.stop(ctx.apiUrl, ctx.auth, id);
const { session } = await DeviceGateway.stop(ctx.apiUrl, ctx.auth, id, Boolean(args.force));
return {
session,
data: null,
Expand All @@ -595,6 +619,7 @@ const installSub = defineCommand({
meta: { name: 'install', description: 'Install a build: a local file (uploaded first) or an https URL' },
args: {
...commonArgs,
force: forceArg,
id: idArg,
app: {
type: 'positional',
Expand Down Expand Up @@ -623,7 +648,7 @@ const installSub = defineCommand({
id = await resolveSessionId(ctx.apiUrl, ctx.auth, id);
const body = binaryId ? { binaryUploadId: binaryId } : await resolveApp(ctx, app!);
ctx.progress(ui.running(`Installing on ${colors.highlight(id)}…`));
const installed = await DeviceGateway.install(ctx.apiUrl, ctx.auth, id, body);
const installed = await DeviceGateway.install(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force));
let { session } = installed;
if (args.wait) {
ctx.progress(ui.running('Waiting for the device…'));
Expand Down Expand Up @@ -674,6 +699,7 @@ const launchSub = defineCommand({
meta: { name: 'launch', description: 'Launch an app: the installed one, or a bundle id / package name' },
args: {
...commonArgs,
force: forceArg,
id: idArg,
appId: {
type: 'positional',
Expand All @@ -695,10 +721,16 @@ const launchSub = defineCommand({

const ctx = await context(args);
id = await resolveSessionId(ctx.apiUrl, ctx.auth, id);
const { result, session } = await DeviceGateway.launch(ctx.apiUrl, ctx.auth, id, {
...(appId && { appId }),
...(args['clear-state'] ? { clearState: true } : {}),
});
const { result, session } = await DeviceGateway.launch(
ctx.apiUrl,
ctx.auth,
id,
{
...(appId && { appId }),
...(args['clear-state'] ? { clearState: true } : {}),
},
Boolean(args.force),
);
return {
session,
data: { result } as { result: DeviceCommandResult },
Expand Down Expand Up @@ -791,7 +823,13 @@ async function performAction(
) {
const ctx = await context(args);
const sessionId = await resolveSessionId(ctx.apiUrl, ctx.auth, id);
const { result, session } = await DeviceGateway.action(ctx.apiUrl, ctx.auth, sessionId, body);
const { result, session } = await DeviceGateway.action(
ctx.apiUrl,
ctx.auth,
sessionId,
body,
Boolean(args.force),
);
return {
session,
data: { result } as { result: DeviceCommandResult },
Expand All @@ -809,6 +847,7 @@ const tapSub = defineCommand({
meta: { name: 'tap', description: 'Tap an element by text or id, or a point on the screen' },
args: {
...commonArgs,
force: forceArg,
id: idArg,
text: { type: 'string', description: 'The element\'s text, label or hint, matched whole, ignoring case' },
rid: { type: 'string', description: 'The element\'s resource id (rid in `dcd device inspect`)' },
Expand Down Expand Up @@ -860,6 +899,7 @@ const typeSub = defineCommand({
meta: { name: 'type', description: 'Type text into the focused field' },
args: {
...commonArgs,
force: forceArg,
id: idArg,
// Not `required`: citty would reject a missing value before runDeviceCommand,
// and --json would then print the top-level error instead of the envelope.
Expand Down Expand Up @@ -894,6 +934,7 @@ const swipeSub = defineCommand({
meta: { name: 'swipe', description: 'Swipe up, down, left or right, or from one point to another' },
args: {
...commonArgs,
force: forceArg,
id: idArg,
direction: {
type: 'positional',
Expand Down Expand Up @@ -936,6 +977,7 @@ const pressKeySub = defineCommand({
meta: { name: 'press-key', description: `Press a key: ${DEVICE_KEYS.join(', ')}` },
args: {
...commonArgs,
force: forceArg,
id: idArg,
key: { type: 'positional', required: false, description: `One of ${DEVICE_KEYS.join(', ')}` },
maestro: maestroArg,
Expand All @@ -959,6 +1001,7 @@ const openLinkSub = defineCommand({
meta: { name: 'open-link', description: 'Open a link on the device: a deep link into an app, or a web link' },
args: {
...commonArgs,
force: forceArg,
id: idArg,
// Not `required`, as with `type --text`: a missing link fails inside the envelope.
url: {
Expand Down Expand Up @@ -1000,6 +1043,7 @@ const setLocationSub = defineCommand({
meta: { name: 'set-location', description: "Set the device's GPS position, in decimal degrees" },
args: {
...commonArgs,
force: forceArg,
id: idArg,
latitude: { type: 'string', description: 'Decimal degrees, north positive (-90 to 90)' },
longitude: { type: 'string', description: 'Decimal degrees, east positive (-180 to 180)' },
Expand Down Expand Up @@ -1202,6 +1246,7 @@ const runSub = defineCommand({
},
args: {
...commonArgs,
force: forceArg,
id: idArg,
flow: {
type: 'positional',
Expand Down Expand Up @@ -1274,7 +1319,7 @@ const runSub = defineCommand({
}

ctx.progress(ui.running(`Running ${entry ?? flow ?? 'the flow'} on ${colors.highlight(id)}…`));
let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body);
let response = await DeviceGateway.run(ctx.apiUrl, ctx.auth, id, body, Boolean(args.force));
if (response.status === 'running') response = await waitForCommand(ctx, id, response.command_id);

const result = response.result ?? { success: false };
Expand Down Expand Up @@ -1496,6 +1541,7 @@ const requestHumanSub = defineCommand({
},
args: {
...commonArgs,
force: forceArg,
reason: {
type: 'positional',
// Checked in run, so a missing reason still fails with the --json envelope.
Expand All @@ -1513,7 +1559,7 @@ const requestHumanSub = defineCommand({
if (reason.length > 500) throw new CliError('The reason is too long: keep it to 500 characters.');
const ctx = await context(args);
const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined);
let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason);
let response = await DeviceGateway.requestHuman(ctx.apiUrl, ctx.auth, id, reason, Boolean(args.force));
ctx.progress(ui.success(`Asked for a person on ${id}`));
if (args.wait) response = await waitForHandBack(ctx, id, response);
const { human, session } = response;
Expand Down
27 changes: 20 additions & 7 deletions src/gateways/device-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,14 @@ async function request<T>(
const sessionPath = (id: string) => `/device/sessions/${encodeURIComponent(id)}`;

/** The Agent Devices session API (dcd docs/device-v1-plan.md, section 4.1). */
/**
* A changing request's body, with `force` when asked: the API refuses an
* agent changing a session someone else started (LIVE_NOT_YOURS) unless it
* says so. Left out otherwise, so an older API sees the body it always did.
*/
const withForce = <T extends object>(body: T, force: boolean): T | (T & { force: true }) =>
force ? { ...body, force: true } : body;

export const DeviceGateway = {
artifacts(
baseUrl: string,
Expand Down Expand Up @@ -202,17 +210,19 @@ export const DeviceGateway = {
auth: AuthContext,
id: string,
app: { binaryUploadId: string } | { url: string },
force = false,
): Promise<{ app: DeviceInstalledApp; session: DeviceSession }> {
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, app);
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, withForce(app, force));
},

launch(
baseUrl: string,
auth: AuthContext,
id: string,
body: { appId?: string; clearState?: boolean },
force = false,
): Promise<{ result: DeviceCommandResult; session: DeviceSession }> {
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/launch`, body);
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/launch`, withForce(body, force));
},

list(
Expand Down Expand Up @@ -274,8 +284,9 @@ export const DeviceGateway = {
auth: AuthContext,
id: string,
reason: string,
force = false,
): Promise<{ human: DeviceHumanStatus; session: DeviceSession }> {
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, { reason });
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/request-human`, withForce({ reason }, force));
},

/** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */
Expand All @@ -284,8 +295,9 @@ export const DeviceGateway = {
auth: AuthContext,
id: string,
body: DeviceActionRequest,
force = false,
): Promise<{ result: DeviceCommandResult; session: DeviceSession }> {
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, body);
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/actions`, withForce(body, force));
},

run(
Expand All @@ -295,8 +307,9 @@ export const DeviceGateway = {
body:
| { env?: Record<string, string>; flow?: string; flowUploadId: string }
| { env?: Record<string, string>; yaml: string },
force = false,
): Promise<DeviceRunResponse> {
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/run`, body);
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/run`, withForce(body, force));
},

screenshot(
Expand All @@ -319,7 +332,7 @@ export const DeviceGateway = {
return request(baseUrl, auth, 'GET', sessionPath(id));
},

stop(baseUrl: string, auth: AuthContext, id: string): Promise<{ session: DeviceSession }> {
return request(baseUrl, auth, 'DELETE', sessionPath(id));
stop(baseUrl: string, auth: AuthContext, id: string, force = false): Promise<{ session: DeviceSession }> {
return request(baseUrl, auth, 'DELETE', `${sessionPath(id)}${force ? '?force=true' : ''}`);
},
};
15 changes: 15 additions & 0 deletions src/mcp/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*
* stdout is the JSON-RPC channel: everything else goes to stderr.
*/
import { randomBytes } from 'node:crypto';
import { readFile, stat } from 'node:fs/promises';
import * as path from 'node:path';

Expand Down Expand Up @@ -49,6 +50,16 @@ import { createServer } from './server.js';
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.';

/** The header the API reads a connection's name from. */
export const CLIENT_INSTANCE_HEADER = 'x-dcd-client-instance';

/**
* This process's name for its connection to the hosted tools, the same for
* as long as it runs: one `dcd mcp` is one agent's connection, and a
* reconnect must not make its sessions someone else's.
*/
export const BRIDGE_INSTANCE = `dcd-mcp-${randomBytes(8).toString('hex')}`;

/**
* How long one forwarded call may take. Longer than dcd_run_cloud_test's
* longest wait (3600s) plus an upload. The MCP client calling this server
Expand Down Expand Up @@ -237,6 +248,10 @@ class RemoteDevices {
const { auth } = await getContext();
const headers = new Headers(init?.headers);
for (const [key, value] of Object.entries(auth.headers)) headers.set(key, value);
// This process, by name: the sessions it starts are its own
// (started_by.this_client), and a call that names no session takes
// one of them, never a session another process started.
headers.set(CLIENT_INSTANCE_HEADER, BRIDGE_INSTANCE);
return fetch(url, { ...init, headers });
},
}),
Expand Down
18 changes: 18 additions & 0 deletions src/types/domain/device-session.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,24 @@ export interface DeviceSession {
} | null;
warnings: string[];
monitor_url: string;
/**
* Who started the session, and how that stands to you. Absent from an API
* that predates it.
*/
started_by?: DeviceSessionStarter;
}

/** Who started a session. */
export interface DeviceSessionStarter {
/** The name of the API key that started it, when one did: its label, never the key. */
key_name: null | string;
client_label: null | string;
/** The person who started it, when a person did. */
email: null | string;
/** Started from this connection (the same `dcd mcp` process). */
this_client: boolean;
/** Started by you: this person, or this API key. */
you: boolean;
}

/**
Expand Down
Loading
Loading