@devicecloud.dev/dcd 5.14.0 → 5.15.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.
Files changed (46) hide show
  1. package/README.md +4 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/cloud.d.ts +1 -1
  5. package/dist/commands/cloud.js +2 -2
  6. package/dist/commands/device.d.ts +39 -0
  7. package/dist/commands/device.js +479 -101
  8. package/dist/commands/live.js +1 -1
  9. package/dist/config/flags/device.flags.d.ts +1 -1
  10. package/dist/config/flags/device.flags.js +1 -1
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/gateways/api-gateway.d.ts +25 -3
  13. package/dist/gateways/api-gateway.js +68 -6
  14. package/dist/gateways/device-gateway.d.ts +34 -10
  15. package/dist/gateways/device-gateway.js +72 -17
  16. package/dist/mcp/bridge.d.ts +30 -16
  17. package/dist/mcp/bridge.js +201 -64
  18. package/dist/mcp/local-files.d.ts +14 -0
  19. package/dist/mcp/local-files.js +75 -0
  20. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  21. package/dist/mcp/tools/download-artifacts.js +44 -17
  22. package/dist/services/report-download.service.d.ts +32 -0
  23. package/dist/services/report-download.service.js +51 -2
  24. package/dist/services/telemetry.service.d.ts +20 -1
  25. package/dist/services/telemetry.service.js +27 -6
  26. package/dist/types/domain/device-session.types.d.ts +73 -3
  27. package/dist/types/domain/device-session.types.js +2 -0
  28. package/dist/utils/api-url.d.ts +20 -0
  29. package/dist/utils/api-url.js +49 -0
  30. package/dist/utils/app-upload.d.ts +6 -0
  31. package/dist/utils/app-upload.js +19 -0
  32. package/dist/utils/config-store.d.ts +5 -1
  33. package/dist/utils/config-store.js +18 -2
  34. package/dist/utils/device-artifacts.d.ts +5 -0
  35. package/dist/utils/device-artifacts.js +22 -0
  36. package/dist/utils/device-bundle.d.ts +39 -9
  37. package/dist/utils/device-bundle.js +153 -51
  38. package/dist/utils/device-flags.d.ts +17 -0
  39. package/dist/utils/device-flags.js +145 -0
  40. package/dist/utils/device-output.d.ts +53 -7
  41. package/dist/utils/device-output.js +148 -21
  42. package/dist/utils/device-run.d.ts +8 -3
  43. package/dist/utils/device-run.js +85 -8
  44. package/dist/utils/zip-integrity.d.ts +21 -0
  45. package/dist/utils/zip-integrity.js +45 -0
  46. package/package.json +3 -2
@@ -3,17 +3,45 @@ import type { DeviceFlowBundle } from '../types/domain/device-session.types.js';
3
3
  /** The API's limit on a bundle (dcd plan 2.5b). */
4
4
  export declare const MAX_BUNDLE_BYTES: number;
5
5
  /**
6
- * The files under `dir` a bundle needs, relative to it, in a stable order:
7
- * every YAML file (flows, subflows, config), the files the flows use
8
- * (runScript, addMedia, assertScreenshot and the like), and config's
9
- * includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk
10
- * and .zip files with its flows.
6
+ * The files a flow reaches: the flow, the files it uses (runFlow, runScript,
7
+ * addMedia, assertScreenshot and the like), and the files those use in turn.
8
+ * Absolute paths, the flow first. `problems` are the files it names that do
9
+ * not exist. A flow that can't be read throws; a YAML file it uses that is
10
+ * not a flow (a data file) is taken as it is.
11
+ */
12
+ export declare function reachableFiles(flow: string): {
13
+ files: string[];
14
+ problems: string[];
15
+ };
16
+ /**
17
+ * For a single flow file that uses other files (runFlow, runScript, addMedia
18
+ * and the like): the folder to upload as a bundle, and the file's path
19
+ * inside it. Sent as yaml on its own, the flow would fail on the device with
20
+ * an invalid file path, because the files it uses would not be there. The
21
+ * folder is the closest one that holds every file the flow reaches; only
22
+ * those files are uploaded. Null when the flow uses no other files, or can't
23
+ * be read (the device reports that itself).
24
+ */
25
+ export declare function flowFileBundle(file: string): {
26
+ dir: string;
27
+ entry: string;
28
+ } | null;
29
+ /** A path inside a bundle as the API takes it: forward slashes on every platform. */
30
+ export declare function bundlePath(relative: string): string;
31
+ /**
32
+ * The files under `dir` a bundle needs, relative to it, in a stable order.
33
+ *
34
+ * With an `entry`, the one flow that will run: that flow and the files it
35
+ * reaches (reachableFiles), which must all be inside `dir`. Nothing else is
36
+ * read or sent, so a folder high above the flow (a home directory, say)
37
+ * costs nothing and gives nothing away.
11
38
  *
12
- * `entry` is the one flow that will run. Its files must all be inside `dir`.
13
- * Without an entry every flow may run, so that goes for all of them. Another
14
- * flow's missing file doesn't stop the entry running, so it is left out.
39
+ * Without one, every flow may run: every YAML file (flows, subflows, config)
40
+ * and the files they use. Either way, config's includedPaths too, and nothing
41
+ * else: an agent's samples folder sent 265 MB of .apk and .zip files with
42
+ * its flows.
15
43
  */
16
- export declare function bundleFiles(dir: string, entry?: string, warn?: (message: string) => void): string[];
44
+ export declare function bundleFiles(dir: string, entry?: string, warn?: (message: string) => void, confineTo?: string): string[];
17
45
  export interface UploadFlowBundleOptions {
18
46
  apiUrl: string;
19
47
  auth: AuthContext;
@@ -21,6 +49,8 @@ export interface UploadFlowBundleOptions {
21
49
  /** The one flow that will run, a path inside `dir`. Omitted, all of them. */
22
50
  entry?: string;
23
51
  log: (message: string) => void;
52
+ /** Send nothing that resolves outside this folder (links included). */
53
+ confineTo?: string;
24
54
  }
25
55
  /**
26
56
  * Zip the files a directory's flows need (bundleFiles) and upload them as a
@@ -1,48 +1,126 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readdirSync } from 'node:fs';
2
+ import { existsSync, readdirSync, realpathSync } from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { DeviceGateway } from '../gateways/device-gateway.js';
5
5
  import { compressFilesFromRelativePath } from '../methods.js';
6
6
  import { resolveIncludedPaths } from '../services/execution-plan.service.js';
7
+ import { computeCommonRoot } from '../services/flow-paths.js';
7
8
  import { isWorkspaceConfigFile, loadWorkspaceConfig, processDependencies, readTestYamlFileAsJson, } from '../services/execution-plan.utils.js';
8
9
  import { CliError } from './cli.js';
9
10
  import { fetchCompatibilityData } from './compatibility.js';
10
11
  import { checkKekForEncryption, encryptFlowBuffer, resolveEncryption, resolveKekPublicKey, } from './envelope.js';
11
12
  /** The API's limit on a bundle (dcd plan 2.5b). */
12
13
  export const MAX_BUNDLE_BYTES = 50 * 1024 * 1024;
13
- /** Never bundled: version control, dependencies, and other dot-folders. */
14
- function skipped(relativePath) {
15
- return relativePath
16
- .split(path.sep)
17
- .some((part) => part === 'node_modules' || (part.startsWith('.') && part !== '.'));
14
+ /**
15
+ * Never walked for flows: dependencies, version control and other tools'
16
+ * dot-folders and dot-files. `.maestro`, where Maestro keeps flows by
17
+ * convention, is walked.
18
+ */
19
+ function skipped(name) {
20
+ return name === 'node_modules' || (name.startsWith('.') && name !== '.maestro');
18
21
  }
19
22
  const YAML_FILE = /\.ya?ml$/i;
20
- /** Every file under `dir`, relative to it. */
23
+ /** Every file under `dir`, relative to it, without going into the folders `skipped` names. */
21
24
  function allFiles(dir) {
22
- return readdirSync(dir, { recursive: true, withFileTypes: true })
23
- .filter((entry) => entry.isFile())
24
- .map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)))
25
- .filter((file) => !skipped(file));
25
+ const files = [];
26
+ const walk = (relative) => {
27
+ for (const entry of readdirSync(path.join(dir, relative), { withFileTypes: true })) {
28
+ if (skipped(entry.name))
29
+ continue;
30
+ const child = relative ? path.join(relative, entry.name) : entry.name;
31
+ if (entry.isDirectory())
32
+ walk(child);
33
+ else if (entry.isFile())
34
+ files.push(child);
35
+ }
36
+ };
37
+ walk('');
38
+ return files;
39
+ }
40
+ /**
41
+ * The files a flow reaches: the flow, the files it uses (runFlow, runScript,
42
+ * addMedia, assertScreenshot and the like), and the files those use in turn.
43
+ * Absolute paths, the flow first. `problems` are the files it names that do
44
+ * not exist. A flow that can't be read throws; a YAML file it uses that is
45
+ * not a flow (a data file) is taken as it is.
46
+ */
47
+ export function reachableFiles(flow) {
48
+ const first = path.resolve(flow);
49
+ const files = [];
50
+ const problems = [];
51
+ const queue = [first];
52
+ const seen = new Set();
53
+ while (queue.length > 0) {
54
+ const file = queue.shift();
55
+ if (seen.has(file))
56
+ continue;
57
+ seen.add(file);
58
+ files.push(file);
59
+ if (!YAML_FILE.test(file) || (file !== first && isWorkspaceConfigFile(file)))
60
+ continue;
61
+ let deps;
62
+ try {
63
+ const { config, testSteps } = readTestYamlFileAsJson(file);
64
+ deps = processDependencies({ config, input: file, testSteps });
65
+ }
66
+ catch (error) {
67
+ if (file === first)
68
+ throw new CliError(error.message);
69
+ continue;
70
+ }
71
+ problems.push(...deps.allErrors);
72
+ for (const dep of deps.allFiles) {
73
+ if (existsSync(dep))
74
+ queue.push(path.normalize(dep));
75
+ }
76
+ }
77
+ return { files, problems };
78
+ }
79
+ /**
80
+ * For a single flow file that uses other files (runFlow, runScript, addMedia
81
+ * and the like): the folder to upload as a bundle, and the file's path
82
+ * inside it. Sent as yaml on its own, the flow would fail on the device with
83
+ * an invalid file path, because the files it uses would not be there. The
84
+ * folder is the closest one that holds every file the flow reaches; only
85
+ * those files are uploaded. Null when the flow uses no other files, or can't
86
+ * be read (the device reports that itself).
87
+ */
88
+ export function flowFileBundle(file) {
89
+ const absolute = path.resolve(file);
90
+ let reached;
91
+ try {
92
+ reached = reachableFiles(absolute);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ // A missing file goes this way too, so the upload names it.
98
+ if (reached.files.length === 1 && reached.problems.length === 0)
99
+ return null;
100
+ const dir = computeCommonRoot([absolute], reached.files.slice(1)) || path.dirname(absolute);
101
+ return { dir, entry: path.relative(dir, absolute) };
102
+ }
103
+ /** A path inside a bundle as the API takes it: forward slashes on every platform. */
104
+ export function bundlePath(relative) {
105
+ return relative.split(path.sep).join('/');
26
106
  }
27
107
  /**
28
- * The files under `dir` a bundle needs, relative to it, in a stable order:
29
- * every YAML file (flows, subflows, config), the files the flows use
30
- * (runScript, addMedia, assertScreenshot and the like), and config's
31
- * includedPaths. Nothing else: an agent's samples folder sent 265 MB of .apk
32
- * and .zip files with its flows.
108
+ * The files under `dir` a bundle needs, relative to it, in a stable order.
33
109
  *
34
- * `entry` is the one flow that will run. Its files must all be inside `dir`.
35
- * Without an entry every flow may run, so that goes for all of them. Another
36
- * flow's missing file doesn't stop the entry running, so it is left out.
110
+ * With an `entry`, the one flow that will run: that flow and the files it
111
+ * reaches (reachableFiles), which must all be inside `dir`. Nothing else is
112
+ * read or sent, so a folder high above the flow (a home directory, say)
113
+ * costs nothing and gives nothing away.
114
+ *
115
+ * Without one, every flow may run: every YAML file (flows, subflows, config)
116
+ * and the files they use. Either way, config's includedPaths too, and nothing
117
+ * else: an agent's samples folder sent 265 MB of .apk and .zip files with
118
+ * its flows.
37
119
  */
38
- export function bundleFiles(dir, entry, warn = () => { }) {
120
+ export function bundleFiles(dir, entry, warn = () => { }, confineTo) {
39
121
  const root = path.resolve(dir);
40
- const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file));
41
- const entryFile = entry === undefined ? undefined : path.normalize(entry);
42
- if (entryFile !== undefined && !yamlFiles.includes(entryFile)) {
43
- throw new CliError(`No flow ${entry} in ${dir}.`);
44
- }
45
- const needed = new Set(yamlFiles);
122
+ const configs = ['config.yaml', 'config.yml'].filter((name) => existsSync(path.join(root, name)));
123
+ const needed = new Set();
46
124
  const problems = [];
47
125
  const add = (absolute, strict, from) => {
48
126
  const relative = path.relative(root, absolute);
@@ -53,36 +131,60 @@ export function bundleFiles(dir, entry, warn = () => { }) {
53
131
  }
54
132
  needed.add(relative);
55
133
  };
56
- for (const file of yamlFiles) {
57
- const absolute = path.join(root, file);
58
- const strict = entryFile === undefined || entryFile === file;
59
- if (isWorkspaceConfigFile(absolute))
60
- continue;
61
- let deps;
62
- try {
63
- const { config, testSteps } = readTestYamlFileAsJson(absolute);
64
- deps = processDependencies({ config, input: absolute, testSteps });
65
- }
66
- catch (error) {
67
- // Not a flow (a data file, say), or one Maestro will report itself.
68
- if (entryFile === file)
69
- throw new CliError(error.message);
70
- continue;
71
- }
72
- if (strict)
134
+ if (entry === undefined) {
135
+ const yamlFiles = allFiles(dir).filter((file) => YAML_FILE.test(file));
136
+ for (const file of yamlFiles)
137
+ needed.add(file);
138
+ for (const file of yamlFiles) {
139
+ const absolute = path.join(root, file);
140
+ if (isWorkspaceConfigFile(absolute))
141
+ continue;
142
+ let deps;
143
+ try {
144
+ const { config, testSteps } = readTestYamlFileAsJson(absolute);
145
+ deps = processDependencies({ config, input: absolute, testSteps });
146
+ }
147
+ catch {
148
+ // Not a flow (a data file, say), or one Maestro will report itself.
149
+ continue;
150
+ }
73
151
  problems.push(...deps.allErrors);
74
- for (const dep of deps.allFiles) {
75
- if (existsSync(dep))
76
- add(dep, strict, file);
152
+ for (const dep of deps.allFiles) {
153
+ if (existsSync(dep))
154
+ add(dep, true, file);
155
+ }
77
156
  }
78
157
  }
79
- for (const name of ['config.yaml', 'config.yml']) {
80
- if (!yamlFiles.includes(name))
81
- continue;
158
+ else {
159
+ const entryFile = path.resolve(root, path.normalize(entry));
160
+ const inside = path.relative(root, entryFile);
161
+ if (inside.startsWith('..') || path.isAbsolute(inside) || !YAML_FILE.test(entryFile) || !existsSync(entryFile)) {
162
+ throw new CliError(`No flow ${entry} in ${dir}.`);
163
+ }
164
+ const reached = reachableFiles(entryFile);
165
+ problems.push(...reached.problems);
166
+ for (const file of reached.files)
167
+ add(file, true, entry);
168
+ for (const name of configs)
169
+ needed.add(name);
170
+ }
171
+ for (const name of configs) {
82
172
  const config = loadWorkspaceConfig(path.join(root, name), warn);
83
173
  for (const file of resolveIncludedPaths(config, root, warn))
84
174
  add(file, true, name);
85
175
  }
176
+ // For an agent's call (the dcd mcp bridge): a file that is a link to one
177
+ // outside the folder it may read would send that file's contents.
178
+ if (confineTo !== undefined) {
179
+ const allowed = realpathSync(confineTo);
180
+ for (const file of needed) {
181
+ const real = realpathSync(path.join(root, file));
182
+ const relative = path.relative(allowed, real);
183
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
184
+ problems.push(`${file} is a link to a file outside ${confineTo}, which is not sent.`);
185
+ }
186
+ }
187
+ }
86
188
  if (problems.length > 0)
87
189
  throw new CliError(problems.join('\n'));
88
190
  return [...needed].sort();
@@ -118,8 +220,8 @@ async function put(url, body) {
118
220
  * `flow` is a path inside it, e.g. `login.yaml`.
119
221
  */
120
222
  export async function uploadFlowBundle(opts) {
121
- const { apiUrl, auth, dir, entry, log } = opts;
122
- const files = bundleFiles(dir, entry, log);
223
+ const { apiUrl, auth, confineTo, dir, entry, log } = opts;
224
+ const files = bundleFiles(dir, entry, log, confineTo);
123
225
  if (!files.some((f) => YAML_FILE.test(f))) {
124
226
  throw new CliError(`No flow files (.yaml) in ${dir}.`);
125
227
  }
@@ -0,0 +1,17 @@
1
+ import type { ArgsDef, CommandDef } from 'citty';
2
+ import { CliError } from './cli.js';
3
+ /** The edit distance between two words, a swap of neighbours counting as one edit. */
4
+ export declare function editDistance(a: string, b: string): number;
5
+ /**
6
+ * The flags in `rawArgs` that `args` does not define, each as typed. A
7
+ * value after a flag that takes one is skipped, so `--yaml "- launchApp"`
8
+ * and `--longitude -0.1278` are read as values. `--` ends the flags.
9
+ */
10
+ export declare function unknownFlags(rawArgs: string[], args: ArgsDef): string[];
11
+ /** The usage error for unknown flags, or null when there are none. */
12
+ export declare function unknownFlagsError(rawArgs: string[], args: ArgsDef): CliError | null;
13
+ /**
14
+ * A `dcd device` subcommand that refuses unknown flags before it runs: with
15
+ * --json the refusal is the usual envelope, exit 1.
16
+ */
17
+ export declare function strictFlags<T extends ArgsDef>(sub: CommandDef<T>): CommandDef<T>;
@@ -0,0 +1,145 @@
1
+ import { CliError } from './cli.js';
2
+ import { DEVICE_EXIT, runDeviceCommand } from './device-output.js';
3
+ /*
4
+ * citty accepts any flag and ignores the ones a command does not define. For
5
+ * `dcd device` that is unsafe: `type --text hunter2 --sensetive` typed a
6
+ * password in plain text and exited 0, and `--wiat` started a session
7
+ * without waiting. So every `dcd device` subcommand refuses a flag it does
8
+ * not know, and suggests the one that was meant.
9
+ */
10
+ const camel = (name) => name.replaceAll(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
11
+ const kebab = (name) => name.replaceAll(/([a-z0-9])([A-Z])/g, '$1-$2').replaceAll(/([A-Z])([A-Z][a-z])/g, '$1-$2').toLowerCase();
12
+ function flagSpecs(args) {
13
+ return Object.entries(args)
14
+ .filter(([, def]) => def.type !== 'positional')
15
+ .map(([name, def]) => {
16
+ const alias = def.alias;
17
+ const aliases = Array.isArray(alias) ? alias : alias ? [alias] : [];
18
+ const names = new Set();
19
+ for (const n of [name, ...aliases]) {
20
+ names.add(n);
21
+ names.add(camel(n));
22
+ names.add(kebab(n));
23
+ }
24
+ return { names, primary: name, takesValue: def.type === 'string' || def.type === 'enum' };
25
+ });
26
+ }
27
+ /** The edit distance between two words, a swap of neighbours counting as one edit. */
28
+ export function editDistance(a, b) {
29
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
30
+ for (let i = 1; i <= a.length; i++) {
31
+ for (let j = 1; j <= b.length; j++) {
32
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
33
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
34
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
35
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
36
+ }
37
+ }
38
+ }
39
+ return d[a.length][b.length];
40
+ }
41
+ /** Words other tools use for a flag of ours. */
42
+ const SYNONYMS = { secret: 'sensitive', secure: 'sensitive' };
43
+ /** Flags people carry over from `dcd live` and the MCP tools, for the session id. */
44
+ const SESSION_FLAGS = new Set(['id', 'session', 'session-id', 'sessionId', 'session_id']);
45
+ /** What to say about one unknown flag: the flag meant, when it is clear. */
46
+ function hint(given, specs, positionals) {
47
+ const bare = given.replace(/^-+/, '').replace(/=.*$/, '');
48
+ if (SESSION_FLAGS.has(bare) && positionals.includes('id')) {
49
+ return ' The session id is an argument, not a flag: `dcd device <command> <id>`.';
50
+ }
51
+ const negated = bare.startsWith('no-');
52
+ const base = kebab(negated ? bare.slice(3) : bare);
53
+ const synonym = SYNONYMS[base];
54
+ if (synonym && specs.some((s) => s.primary === synonym))
55
+ return ` Did you mean --${negated ? 'no-' : ''}${synonym}?`;
56
+ let best = null;
57
+ for (const spec of specs) {
58
+ const distance = editDistance(base, spec.primary);
59
+ if (!best || distance < best.distance)
60
+ best = { distance, name: spec.primary };
61
+ }
62
+ // Close enough to be a slip of the keys, not another word.
63
+ if (best && best.distance <= 2 && best.distance < base.length / 2) {
64
+ return ` Did you mean --${negated ? 'no-' : ''}${best.name}?`;
65
+ }
66
+ return '';
67
+ }
68
+ /**
69
+ * The flags in `rawArgs` that `args` does not define, each as typed. A
70
+ * value after a flag that takes one is skipped, so `--yaml "- launchApp"`
71
+ * and `--longitude -0.1278` are read as values. `--` ends the flags.
72
+ */
73
+ export function unknownFlags(rawArgs, args) {
74
+ const specs = flagSpecs(args);
75
+ const find = (name) => specs.find((s) => s.names.has(name) || s.names.has(camel(name)));
76
+ const unknown = [];
77
+ for (let i = 0; i < rawArgs.length; i++) {
78
+ const token = rawArgs[i];
79
+ if (token === '--')
80
+ break;
81
+ if (!token.startsWith('-') || token === '-' || /^-\d/.test(token))
82
+ continue;
83
+ const eq = token.indexOf('=');
84
+ const name = (eq === -1 ? token : token.slice(0, eq)).replace(/^-{1,2}/, '');
85
+ if (token.startsWith('--')) {
86
+ const spec = find(name) ?? (name.startsWith('no-') ? find(name.slice(3)) : undefined);
87
+ if (!spec)
88
+ unknown.push(token.slice(0, eq === -1 ? undefined : eq));
89
+ else if (spec.takesValue && eq === -1 && !name.startsWith('no-'))
90
+ i++;
91
+ continue;
92
+ }
93
+ // Short flags, e.g. -o file or -f: each letter must be one of ours, and
94
+ // one that takes a value ends the group (its value is the rest, or the
95
+ // next token).
96
+ for (let k = 0; k < name.length; k++) {
97
+ const spec = find(name[k]);
98
+ if (!spec) {
99
+ unknown.push(`-${name[k]}`);
100
+ break;
101
+ }
102
+ if (spec.takesValue) {
103
+ if (k === name.length - 1 && eq === -1)
104
+ i++;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ return unknown;
110
+ }
111
+ /** The usage error for unknown flags, or null when there are none. */
112
+ export function unknownFlagsError(rawArgs, args) {
113
+ const unknown = unknownFlags(rawArgs, args);
114
+ if (unknown.length === 0)
115
+ return null;
116
+ const specs = flagSpecs(args);
117
+ const positionals = Object.entries(args)
118
+ .filter(([, def]) => def.type === 'positional')
119
+ .map(([name]) => name);
120
+ const lines = unknown.map((flag) => `Unknown flag ${flag}.${hint(flag, specs, positionals)}`);
121
+ return new CliError(`${lines.join(' ')} See --help for the flags this command takes.`, DEVICE_EXIT.usage);
122
+ }
123
+ /**
124
+ * A `dcd device` subcommand that refuses unknown flags before it runs: with
125
+ * --json the refusal is the usual envelope, exit 1.
126
+ */
127
+ export function strictFlags(sub) {
128
+ const { run } = sub;
129
+ if (!run)
130
+ return sub;
131
+ return {
132
+ ...sub,
133
+ async run(context) {
134
+ const args = (sub.args ?? {});
135
+ const problem = unknownFlagsError(context.rawArgs ?? [], args);
136
+ if (problem) {
137
+ await runDeviceCommand(Boolean(context.args.json), async () => {
138
+ throw problem;
139
+ });
140
+ return;
141
+ }
142
+ return run(context);
143
+ },
144
+ };
145
+ }
@@ -1,5 +1,5 @@
1
1
  import type { AuthContext } from '../types/domain/auth.types.js';
2
- import type { DeviceHumanStatus, DeviceSession } from '../types/domain/device-session.types.js';
2
+ import type { DeviceHumanStatus, DeviceSession, DeviceSessionStarter } from '../types/domain/device-session.types.js';
3
3
  import { type Field } from './ui.js';
4
4
  /**
5
5
  * Exit codes for `dcd device` (dcd docs/device-v1-plan.md, section 4.2).
@@ -11,7 +11,7 @@ export declare const DEVICE_EXIT: {
11
11
  readonly usage: 1;
12
12
  /** It ran and failed: a flow or action failed, or the API could not do it. */
13
13
  readonly failed: 2;
14
- /** A limit: concurrency, spend cap or rate limit. */
14
+ /** A limit: concurrency, a spend cap or usage limit, or a rate limit. */
15
15
  readonly limit: 3;
16
16
  /** The session has ended, or there is no such session. */
17
17
  readonly gone: 4;
@@ -26,10 +26,15 @@ export interface DeviceEnvelope<T> {
26
26
  ok: boolean;
27
27
  session?: DeviceSession | null;
28
28
  data: T | null;
29
- error: {
29
+ /**
30
+ * With `code` and `message`, whatever else the API said that a script can
31
+ * act on: `retry_after_s`, `limit`, `spent`, `phase`, and `command_id` when
32
+ * a wait for a flow gave up.
33
+ */
34
+ error: ({
30
35
  code: null | string;
31
36
  message: string;
32
- } | null;
37
+ } & Record<string, unknown>) | null;
33
38
  }
34
39
  export interface DeviceOutcome<T> {
35
40
  /** The session the command was about; undefined when it is not about one. */
@@ -60,16 +65,57 @@ export declare function runDeviceCommand<T>(json: boolean, fn: () => Promise<Dev
60
65
  */
61
66
  export declare function deviceProgress(json: boolean): (message: string) => void;
62
67
  /**
63
- * The default-session rule: `<id>` may be left out when the org has exactly
64
- * one open session. With none, or several, the command is a usage error and
65
- * lists what there is to choose from.
68
+ * The default-session rule: `<id>` may be left out when you have exactly one
69
+ * open session. Other people's sessions are never the default: a teammate's
70
+ * agent may be using one. With none of yours, or several, the command is a
71
+ * usage error that lists what there is to choose from.
72
+ *
73
+ * An API that does not say who started each session (no `started_by`) is
74
+ * read the old way: the org's only open session.
66
75
  */
67
76
  export declare function resolveSessionId(apiUrl: string, auth: AuthContext, given: string | undefined): Promise<string>;
77
+ /**
78
+ * The id given, trimmed, or undefined when none was. A value that cannot be
79
+ * a session id is a usage error, never sent: `undefined` from a script's
80
+ * unset variable would otherwise reach the API as a session name.
81
+ */
82
+ export declare function checkSessionId(given: string | undefined): string | undefined;
83
+ /**
84
+ * For commands that read what a session left behind (`artifacts`): the
85
+ * session given, or else your most recent one, ended or not. Others' sessions
86
+ * are never the default. An API that does not say who started each is read
87
+ * the old way: the only session in the list.
88
+ */
89
+ export declare function resolveRecentSessionId(apiUrl: string, auth: AuthContext, given: string | undefined): Promise<string>;
90
+ /** Who started a session, in a few words: "you", an email, or an API key's name. */
91
+ export declare function startedByLabel(starter: DeviceSessionStarter): string;
92
+ /**
93
+ * Text from the device, the app or another client, made safe to print in a
94
+ * terminal: escape sequences and control characters removed, so an element's
95
+ * label, a log line or a note can't retitle the terminal, move the cursor or
96
+ * draw a fake result line. `oneLine` also folds line breaks into spaces, for
97
+ * text shown inside a row. --json output keeps the text exactly as it came.
98
+ */
99
+ export declare function printable(text: string, opts?: {
100
+ oneLine?: boolean;
101
+ }): string;
102
+ /**
103
+ * Dollars for a person. Sessions are billed in units of $0.015, so a cost
104
+ * is shown to the half cent when it has one: $0.015, not $0.01.
105
+ */
106
+ export declare function formatCost(usd: number): string;
68
107
  export declare function formatSeconds(seconds: number): string;
69
108
  /** The rows that describe a session, for {@link ui.fields}. */
70
109
  export declare function sessionFields(session: DeviceSession): Field[];
71
110
  /** A session as a branch group, with its warnings after it. */
72
111
  export declare function printSession(session: DeviceSession): void;
112
+ /**
113
+ * The session's warnings (a crash, the idle timeout or the end of its time
114
+ * coming up, an install still going), after a command's own result: a
115
+ * person or an agent driving it without --json must see them before the
116
+ * session ends under them.
117
+ */
118
+ export declare function printWarnings(session: DeviceSession | null | undefined): void;
73
119
  /**
74
120
  * An API timestamp for a person: how far off it is and the local time, e.g.
75
121
  * "in 12m (14:32)" or "3m ago (14:17)". The text as given when unreadable.