@devicecloud.dev/dcd 5.11.1 → 5.11.2-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.
@@ -4,7 +4,7 @@ import * as path from 'node:path';
4
4
  import { resolve as resolvePath } from 'node:path';
5
5
  import { apiFlags } from '../config/flags/api.flags.js';
6
6
  import { jsonFlag } from '../config/flags/output.flags.js';
7
- import { DeviceApiError, DeviceGateway } from '../gateways/device-gateway.js';
7
+ import { DeviceApiError, DeviceGateway, START_RECOVERY_WINDOW_MS, startOutcomeUnknown, } from '../gateways/device-gateway.js';
8
8
  import { ENDED_STATES, } from '../types/domain/device-session.types.js';
9
9
  import { platformOfAppFile, uploadLocalApp } from '../utils/app-upload.js';
10
10
  import { refreshAuth, resolveAuth } from '../utils/auth.js';
@@ -135,6 +135,31 @@ async function resolveApp(ctx, app) {
135
135
  });
136
136
  return { binaryUploadId };
137
137
  }
138
+ /**
139
+ * A start that got no answer, or a proxy's 5xx in the API's place, may still
140
+ * have made a session, which is billed while it runs. Someone who just runs
141
+ * `dcd device start` again would have two. So name the sessions started in
142
+ * the last couple of minutes, and say to check before starting again.
143
+ */
144
+ async function failedStartError(ctx, error) {
145
+ const reason = error instanceof Error ? error.message : String(error);
146
+ const status = error instanceof DeviceApiError ? error.status : 502;
147
+ const head = 'Starting the session failed, but the request may still have started a session, and a session is billed while it runs.';
148
+ // What to do first: a network error's message runs to a dozen lines.
149
+ const failed = (advice, session = null) => new DeviceApiError(`${head} ${advice}\n\nThe error: ${reason}`, status, null, session);
150
+ const minutes = START_RECOVERY_WINDOW_MS / 60_000;
151
+ const recent = await DeviceGateway.recentlyStarted(ctx.apiUrl, ctx.auth);
152
+ if (recent === null) {
153
+ return failed('Check for one with `dcd device list` before you start another.');
154
+ }
155
+ if (recent.length === 0) {
156
+ return failed(`No session was started in the last ${minutes} minutes, so it is safe to start one again.`);
157
+ }
158
+ const listed = recent
159
+ .map((s) => `${s.id} (${s.client_label ?? 'no label'}, ${s.state}, started ${s.created_at})`)
160
+ .join(', ');
161
+ return failed(`Open sessions started in the last ${minutes} minutes: ${listed}. If one is yours, use it instead of starting another; check it with \`dcd device status <id>\`. Otherwise stop it with \`dcd device stop <id>\`.`, recent.length === 1 ? recent[0] : null);
162
+ }
138
163
  function parsePositiveInt(value, flag) {
139
164
  if (value === undefined || value === '')
140
165
  return undefined;
@@ -265,7 +290,15 @@ const startSub = defineCommand({
265
290
  if (ttl)
266
291
  body.maxDurationMin = ttl;
267
292
  ctx.progress(ui.running(`Starting ${platform} device session…`));
268
- let { session } = await DeviceGateway.start(ctx.apiUrl, ctx.auth, body);
293
+ let session;
294
+ try {
295
+ ({ session } = await DeviceGateway.start(ctx.apiUrl, ctx.auth, body));
296
+ }
297
+ catch (error) {
298
+ if (!startOutcomeUnknown(error))
299
+ throw error;
300
+ throw await failedStartError(ctx, error);
301
+ }
269
302
  ctx.progress(ui.success(`Session ${session.id} started`));
270
303
  // The session exists and bills from here on: every later failure must
271
304
  // still name it, so the caller can stop it.
@@ -8,10 +8,24 @@ import type { DeviceArtifactsPage, DeviceBundleUploadUrls, DeviceFlowBundle, Dev
8
8
  */
9
9
  export declare class DeviceApiError extends Error {
10
10
  code: null | string;
11
+ /**
12
+ * The API itself answered (its `{ statusCode, message }` envelope), not a
13
+ * proxy in front of it. A proxy's 502 can come after the API did the work.
14
+ */
15
+ fromApi: boolean;
11
16
  session: DeviceSession | null;
12
17
  status: number;
13
- constructor(message: string, status: number, code: null | string, session: DeviceSession | null);
18
+ constructor(message: string, status: number, code: null | string, session: DeviceSession | null, fromApi?: boolean);
14
19
  }
20
+ /** How recent an open session must be to count as one a failed start may have made. */
21
+ export declare const START_RECOVERY_WINDOW_MS: number;
22
+ /**
23
+ * Whether a failed start may still have made a session: no answer arrived
24
+ * (the connection failed, or the reply was unreadable), or a proxy answered
25
+ * with a 5xx in the API's place. The API's own errors are refusals made
26
+ * before any session exists.
27
+ */
28
+ export declare function startOutcomeUnknown(error: unknown): boolean;
15
29
  /** The Agent Devices session API (dcd docs/device-v1-plan.md, section 4.1). */
16
30
  export declare const DeviceGateway: {
17
31
  artifacts(baseUrl: string, auth: AuthContext, id: string, before?: string): Promise<DeviceArtifactsPage>;
@@ -49,6 +63,11 @@ export declare const DeviceGateway: {
49
63
  session: DeviceSession;
50
64
  }>;
51
65
  models(baseUrl: string, auth: AuthContext): Promise<DeviceCatalogue>;
66
+ /**
67
+ * The open sessions started in the last START_RECOVERY_WINDOW_MS: the ones
68
+ * a start that got no answer may have made. Null when they can't be read.
69
+ */
70
+ recentlyStarted(baseUrl: string, auth: AuthContext, now?: number): Promise<DeviceSession[] | null>;
52
71
  registerBundle(baseUrl: string, auth: AuthContext, body: {
53
72
  backblaze: boolean;
54
73
  bytes: number;
@@ -7,16 +7,35 @@ import { ApiGateway } from './api-gateway.js';
7
7
  */
8
8
  export class DeviceApiError extends Error {
9
9
  code;
10
+ /**
11
+ * The API itself answered (its `{ statusCode, message }` envelope), not a
12
+ * proxy in front of it. A proxy's 502 can come after the API did the work.
13
+ */
14
+ fromApi;
10
15
  session;
11
16
  status;
12
- constructor(message, status, code, session) {
17
+ constructor(message, status, code, session, fromApi = false) {
13
18
  super(message);
14
19
  this.name = 'DeviceApiError';
15
20
  this.status = status;
16
21
  this.code = code;
17
22
  this.session = session;
23
+ this.fromApi = fromApi;
18
24
  }
19
25
  }
26
+ /** How recent an open session must be to count as one a failed start may have made. */
27
+ export const START_RECOVERY_WINDOW_MS = 2 * 60 * 1000;
28
+ /**
29
+ * Whether a failed start may still have made a session: no answer arrived
30
+ * (the connection failed, or the reply was unreadable), or a proxy answered
31
+ * with a 5xx in the API's place. The API's own errors are refusals made
32
+ * before any session exists.
33
+ */
34
+ export function startOutcomeUnknown(error) {
35
+ if (!(error instanceof DeviceApiError))
36
+ return true;
37
+ return error.status >= 500 && !error.fromApi;
38
+ }
20
39
  /**
21
40
  * The API's error envelope: `{ statusCode, message, error? }`, where `error`
22
41
  * is either Nest's status text or a machine code such as LIVE_NOT_FOUND.
@@ -48,7 +67,10 @@ async function toDeviceApiError(res, path) {
48
67
  `Wait for that with \`dcd device human ${name} --wait\`.`;
49
68
  }
50
69
  const session = body.session && typeof body.session === 'object' ? body.session : null;
51
- return new DeviceApiError(message, res.status, code, session);
70
+ // Nest's envelope always has a numeric statusCode. Railway's proxy answers
71
+ // `{ status, code, message }`, or a page that isn't JSON at all.
72
+ const fromApi = typeof body.statusCode === 'number';
73
+ return new DeviceApiError(message, res.status, code, session, fromApi);
52
74
  }
53
75
  async function request(baseUrl, auth, method, path, body) {
54
76
  const url = `${baseUrl}${path}`;
@@ -115,6 +137,19 @@ export const DeviceGateway = {
115
137
  models(baseUrl, auth) {
116
138
  return request(baseUrl, auth, 'GET', '/device/models');
117
139
  },
140
+ /**
141
+ * The open sessions started in the last START_RECOVERY_WINDOW_MS: the ones
142
+ * a start that got no answer may have made. Null when they can't be read.
143
+ */
144
+ async recentlyStarted(baseUrl, auth, now = Date.now()) {
145
+ try {
146
+ const { sessions } = await DeviceGateway.list(baseUrl, auth);
147
+ return sessions.filter((s) => now - Date.parse(s.created_at) <= START_RECOVERY_WINDOW_MS);
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ },
118
153
  registerBundle(baseUrl, auth, body) {
119
154
  return request(baseUrl, auth, 'POST', '/device/bundles', body);
120
155
  },
@@ -29,8 +29,6 @@ export declare function resolveLocalInputs(name: string, args: Record<string, un
29
29
  apiUrl: string;
30
30
  auth: AuthContext;
31
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
32
  /**
35
33
  * What to tell the agent when a start_device call failed without an answer
36
34
  * (the connection dropped, or the server never replied). The request may
@@ -22,7 +22,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
22
22
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
23
23
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
24
24
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
25
- import { DeviceGateway } from '../gateways/device-gateway.js';
25
+ import { DeviceGateway, START_RECOVERY_WINDOW_MS } from '../gateways/device-gateway.js';
26
26
  import { processDependencies, readTestYamlFileAsJson } from '../services/execution-plan.utils.js';
27
27
  import { computeCommonRoot } from '../services/flow-paths.js';
28
28
  import { uploadLocalApp } from '../utils/app-upload.js';
@@ -139,8 +139,6 @@ export async function resolveLocalInputs(name, args, ctx) {
139
139
  }
140
140
  return args;
141
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
142
  /**
145
143
  * What to tell the agent when a start_device call failed without an answer
146
144
  * (the connection dropped, or the server never replied). The request may
@@ -150,12 +148,8 @@ export const START_RECOVERY_WINDOW_MS = 2 * 60 * 1000;
150
148
  */
151
149
  export async function explainFailedStart(message, ctx, now = Date.now()) {
152
150
  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 {
151
+ const recent = await DeviceGateway.recentlyStarted(ctx.apiUrl, ctx.auth, now);
152
+ if (recent === null) {
159
153
  return `${head} Call list_devices to check for one before you call start_device again.`;
160
154
  }
161
155
  if (recent.length === 0) {
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.1",
71
+ "version": "5.11.2-beta.1",
72
72
  "bugs": {
73
73
  "url": "https://discord.gg/gm3mJwcNw8"
74
74
  },