@devicecloud.dev/dcd 5.12.1 → 5.13.0-beta.2

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.
@@ -12,10 +12,11 @@ import * as path from 'node:path';
12
12
  import { CliError } from './cli.js';
13
13
  /** The server's name in every client's config. */
14
14
  export const SERVER_NAME = 'devicecloud';
15
- export const MCP_CLIENTS = ['claude-code', 'claude-desktop', 'cursor', 'vscode'];
15
+ export const MCP_CLIENTS = ['claude-code', 'claude-desktop', 'codex', 'cursor', 'vscode'];
16
16
  export const CLIENT_LABELS = {
17
17
  'claude-code': 'Claude Code',
18
18
  'claude-desktop': 'Claude Desktop',
19
+ codex: 'Codex',
19
20
  cursor: 'Cursor',
20
21
  vscode: 'VS Code',
21
22
  };
@@ -66,7 +67,8 @@ export function stableNodePath(execPath, pathEnv = process.env.PATH, platform =
66
67
  }
67
68
  /**
68
69
  * The JSON config file a client reads, or undefined when it is configured
69
- * through its own CLI (Claude Code, VS Code) or has no known location here.
70
+ * through its own CLI (Claude Code, Codex, VS Code) or has no known location
71
+ * here.
70
72
  */
71
73
  export function clientConfigPath(client, platform = process.platform, home = os.homedir(), env = process.env) {
72
74
  if (client === 'cursor')
@@ -122,6 +124,14 @@ export function writeClientConfig(file, launch) {
122
124
  export function claudeCodeAddArgs(launch) {
123
125
  return ['mcp', 'add', '--scope', 'user', SERVER_NAME, '--', launch.command, ...launch.args];
124
126
  }
127
+ /**
128
+ * `codex mcp add` arguments. Codex keeps MCP servers in ~/.codex/config.toml,
129
+ * which its CLI, IDE extension and desktop app share, so its own CLI writes
130
+ * the entry rather than this one parsing TOML.
131
+ */
132
+ export function codexAddArgs(launch) {
133
+ return ['mcp', 'add', SERVER_NAME, '--', launch.command, ...launch.args];
134
+ }
125
135
  /** `code --add-mcp` arguments, which add the server to the VS Code user profile. */
126
136
  export function vscodeAddArgs(launch) {
127
137
  return ['--add-mcp', JSON.stringify({ name: SERVER_NAME, ...launch })];
@@ -0,0 +1,21 @@
1
+ export interface ToolSpawn {
2
+ command: string;
3
+ args: string[];
4
+ /** Pass the arguments to cmd.exe as written, already quoted. */
5
+ windowsVerbatimArguments?: boolean;
6
+ }
7
+ /**
8
+ * What to spawn for `command args`, or undefined when Windows has no such
9
+ * command on PATH. Elsewhere the command is spawned as given, and a missing
10
+ * one shows up as ENOENT.
11
+ */
12
+ export declare function toolSpawn(command: string, args: string[], platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, exists?: (file: string) => boolean): ToolSpawn | undefined;
13
+ /** The file Windows would run for `command`: each PATH folder, each PATHEXT extension. */
14
+ export declare function findOnWindowsPath(command: string, env: NodeJS.ProcessEnv, exists: (file: string) => boolean): string | undefined;
15
+ /**
16
+ * One argument for a batch file started by cmd.exe. First quote it the way
17
+ * the program's own parser expects (CommandLineToArgvW), then caret-escape
18
+ * every cmd character twice: once for the `cmd /c` line, and once more
19
+ * because the batch file passes it on with %*, which cmd parses again.
20
+ */
21
+ export declare function cmdArgument(arg: string): string;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * How to start another tool's CLI (`code`, `claude`) without a shell.
3
+ *
4
+ * On Windows these are often batch files (`code.cmd`, and npm's `claude.cmd`
5
+ * shim). Node's spawn searches PATH only for .com and .exe, and refuses to
6
+ * start a .cmd or .bat at all without a shell (CVE-2024-27980). So we find the
7
+ * file ourselves and, for a batch file, run it through cmd.exe with every
8
+ * argument escaped for cmd. This doesn't lean on how Node or Bun resolve
9
+ * commands, so the npm install and the standalone binary behave the same.
10
+ */
11
+ import { existsSync } from 'node:fs';
12
+ import * as path from 'node:path';
13
+ import { CliError } from './cli.js';
14
+ /** Characters cmd.exe treats specially, each escaped with a caret. */
15
+ const CMD_META = /([ !"%&()*,;<>?[\]^`|])/g;
16
+ /**
17
+ * What to spawn for `command args`, or undefined when Windows has no such
18
+ * command on PATH. Elsewhere the command is spawned as given, and a missing
19
+ * one shows up as ENOENT.
20
+ */
21
+ export function toolSpawn(command, args, platform = process.platform, env = process.env, exists = existsSync) {
22
+ if (platform !== 'win32')
23
+ return { command, args };
24
+ const file = findOnWindowsPath(command, env, exists);
25
+ if (!file)
26
+ return undefined;
27
+ if (!/\.(cmd|bat)$/i.test(file))
28
+ return { command: file, args };
29
+ // A line break ends cmd's line, and no escaping can stop that.
30
+ if (args.some((arg) => /[\0\n\r]/.test(arg))) {
31
+ throw new CliError(`Can't pass a line break to ${path.win32.basename(file)} through cmd.exe.`);
32
+ }
33
+ // /s strips the outer quotes and runs the rest as one line.
34
+ const line = [file.replace(CMD_META, '^$1'), ...args.map((arg) => cmdArgument(arg))].join(' ');
35
+ return {
36
+ command: env.ComSpec ?? env.COMSPEC ?? 'cmd.exe',
37
+ args: ['/d', '/s', '/c', `"${line}"`],
38
+ windowsVerbatimArguments: true,
39
+ };
40
+ }
41
+ /** The file Windows would run for `command`: each PATH folder, each PATHEXT extension. */
42
+ export function findOnWindowsPath(command, env, exists) {
43
+ const exts = (env.PATHEXT ?? env.Pathext ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
44
+ const dirs = (env.PATH ?? env.Path ?? '').split(';').filter(Boolean);
45
+ const hasExt = exts.some((ext) => command.toLowerCase().endsWith(ext.toLowerCase()));
46
+ const names = hasExt ? [command] : exts.map((ext) => command + ext.toLowerCase());
47
+ for (const dir of dirs) {
48
+ for (const name of names) {
49
+ const candidate = path.win32.join(dir.replaceAll('"', ''), name);
50
+ if (exists(candidate))
51
+ return candidate;
52
+ }
53
+ }
54
+ return undefined;
55
+ }
56
+ /**
57
+ * One argument for a batch file started by cmd.exe. First quote it the way
58
+ * the program's own parser expects (CommandLineToArgvW), then caret-escape
59
+ * every cmd character twice: once for the `cmd /c` line, and once more
60
+ * because the batch file passes it on with %*, which cmd parses again.
61
+ */
62
+ export function cmdArgument(arg) {
63
+ const quoted = `"${arg.replaceAll(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1')}"`;
64
+ return quoted.replace(CMD_META, '^$1').replace(CMD_META, '^$1');
65
+ }
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.12.1",
71
+ "version": "5.13.0-beta.2",
72
72
  "bugs": {
73
73
  "url": "https://discord.gg/gm3mJwcNw8"
74
74
  },
@@ -1,39 +0,0 @@
1
- import { type DcdEnvName } from '../config/environments.js';
2
- export interface RealtimeResultsSubscription {
3
- /**
4
- * Whether the channel is currently subscribed and receiving pushes. False
5
- * until the socket subscribes, and again if it errors/closes — the backstop
6
- * poll always covers the gap.
7
- */
8
- isConnected(): boolean;
9
- /** Tear down the channel and close the socket. Best-effort, never throws. */
10
- unsubscribe(): Promise<void>;
11
- /**
12
- * Hand the socket a refreshed JWT. RLS authorises the channel with the token
13
- * it joined with, and the server drops the channel once that expires — so a
14
- * poll that outlives the token passes the new one on. Best-effort, never
15
- * throws.
16
- */
17
- updateAccessToken(accessToken: string): void;
18
- }
19
- export interface RealtimeSubscribeOptions {
20
- /** Supabase JWT (AuthContext.accessToken) — authorises the socket for RLS. */
21
- accessToken: string;
22
- debug?: boolean;
23
- env: DcdEnvName;
24
- /** Stderr-safe logger; stdout is reserved by some callers (MCP). */
25
- log?: (message: string) => void;
26
- /** Fired when a result row for this upload changes. */
27
- onChange: () => void;
28
- /** Fired whenever the connection state flips (subscribed ↔ disconnected). */
29
- onConnectionChange?: (connected: boolean) => void;
30
- orgId: string;
31
- uploadId: string;
32
- }
33
- export declare class RealtimeResultsGateway {
34
- /**
35
- * Open a realtime subscription to `results` changes for the given upload.
36
- * Construction never throws — on any failure the caller simply keeps polling.
37
- */
38
- static subscribe(options: RealtimeSubscribeOptions): RealtimeResultsSubscription;
39
- }
@@ -1,128 +0,0 @@
1
- /**
2
- * Supabase Realtime subscription to test-result status changes.
3
- *
4
- * This is a *latency optimisation* layered on top of HTTP polling, not a
5
- * replacement for it. A logged-in (bearer) user's JWT authorises a
6
- * `postgres_changes` subscription on the `results` table (RLS scopes rows to
7
- * the user's org via `app_metadata.org_ids`). Each relevant change fires
8
- * `onChange`, which the polling loop uses to fetch immediately instead of
9
- * waiting out the full backstop interval.
10
- *
11
- * We deliberately only read the `new` row's `test_upload_id` — Postgres always
12
- * ships the full new tuple on INSERT/UPDATE regardless of REPLICA IDENTITY, so
13
- * no DB change is required. Mirrors the frontend pattern in
14
- * dcd/frontend/app/stores/Results.store.ts.
15
- */
16
- import { createClient, REALTIME_SUBSCRIBE_STATES, } from '@supabase/supabase-js';
17
- import { ENVIRONMENTS } from '../config/environments.js';
18
- import { getSupabaseKey } from '../config/supabase-key.js';
19
- export class RealtimeResultsGateway {
20
- /**
21
- * Open a realtime subscription to `results` changes for the given upload.
22
- * Construction never throws — on any failure the caller simply keeps polling.
23
- */
24
- static subscribe(options) {
25
- const { accessToken, debug, env, log, onChange, onConnectionChange, orgId, uploadId } = options;
26
- const dbg = (message) => {
27
- if (debug && log)
28
- log(`[DEBUG] [realtime] ${message}`);
29
- };
30
- let connected = false;
31
- const setConnected = (next) => {
32
- if (next === connected)
33
- return;
34
- connected = next;
35
- onConnectionChange?.(next);
36
- };
37
- let client;
38
- let channel;
39
- let closed = false;
40
- // The latest JWT, so a refresh that lands while the key is still being
41
- // fetched is the one the socket joins with.
42
- let token = accessToken;
43
- // The publishable key comes from the API (dcd#1112), so the socket opens
44
- // asynchronously. `subscribe` stays synchronous for the caller: until it
45
- // connects, `isConnected` is false and the backstop poll covers the gap.
46
- const ready = getSupabaseKey(env)
47
- .then((supabaseKey) => {
48
- if (closed)
49
- return;
50
- const sb = createClient(ENVIRONMENTS[env].supabase.url, supabaseKey, {
51
- // Match SupabaseClientGateway / the frontend; no session persistence —
52
- // we set the token explicitly below.
53
- auth: { autoRefreshToken: false, persistSession: false },
54
- realtime: { params: { eventsPerSecond: 10 } },
55
- });
56
- client = sb;
57
- // Attach the user's JWT to the socket so RLS is enforced on the channel.
58
- sb.realtime.setAuth(token);
59
- channel = sb
60
- .channel(`results-cli-${uploadId}`)
61
- .on(
62
- // The typings don't cover the postgres_changes overload cleanly.
63
- 'postgres_changes', {
64
- event: '*',
65
- schema: 'public',
66
- table: 'results',
67
- filter: `org_id=eq.${orgId}`,
68
- }, (payload) => {
69
- if (payload.new?.test_upload_id === uploadId) {
70
- dbg(`change for upload ${uploadId}`);
71
- onChange();
72
- }
73
- })
74
- .subscribe((status) => {
75
- if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
76
- dbg('subscribed');
77
- setConnected(true);
78
- }
79
- else if (status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR ||
80
- status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT ||
81
- status === REALTIME_SUBSCRIBE_STATES.CLOSED) {
82
- // Don't try to recover — the backstop poll covers us. Surface in
83
- // debug so a network-blocked websocket is diagnosable.
84
- dbg(`channel ${status}; relying on backstop poll`);
85
- setConnected(false);
86
- }
87
- });
88
- })
89
- .catch((error) => {
90
- dbg(`failed to subscribe: ${error instanceof Error ? error.message : String(error)}`);
91
- // Best-effort cleanup of a half-built client, then degrade to polling.
92
- try {
93
- client?.realtime.disconnect();
94
- }
95
- catch {
96
- /* ignore */
97
- }
98
- client = undefined;
99
- channel = undefined;
100
- });
101
- return {
102
- isConnected: () => connected,
103
- async unsubscribe() {
104
- closed = true;
105
- setConnected(false);
106
- await ready;
107
- if (!client)
108
- return;
109
- try {
110
- if (channel)
111
- await client.removeChannel(channel);
112
- await client.realtime.disconnect();
113
- }
114
- catch {
115
- /* best effort — process is exiting anyway */
116
- }
117
- },
118
- updateAccessToken(nextToken) {
119
- token = nextToken;
120
- // setAuth updates the join payload and pushes the token to joined
121
- // channels. A failure only costs realtime; the backstop poll stays.
122
- client?.realtime.setAuth(nextToken).catch((error) => {
123
- dbg(`failed to update the socket's token: ${error instanceof Error ? error.message : String(error)}`);
124
- });
125
- },
126
- };
127
- }
128
- }