-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathcommand-schema.ts
More file actions
629 lines (597 loc) · 16.8 KB
/
command-schema.ts
File metadata and controls
629 lines (597 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
export type CliFlags = {
json: boolean;
platform?: 'ios' | 'android';
device?: string;
udid?: string;
serial?: string;
out?: string;
session?: string;
verbose?: boolean;
snapshotInteractiveOnly?: boolean;
snapshotCompact?: boolean;
snapshotDepth?: number;
snapshotScope?: string;
snapshotRaw?: boolean;
snapshotBackend?: 'ax' | 'xctest';
appsFilter?: 'launchable' | 'user-installed' | 'all';
appsMetadata?: boolean;
count?: number;
intervalMs?: number;
holdMs?: number;
jitterPx?: number;
pauseMs?: number;
pattern?: 'one-way' | 'ping-pong';
activity?: string;
saveScript?: boolean;
relaunch?: boolean;
noRecord?: boolean;
replayUpdate?: boolean;
help: boolean;
version: boolean;
};
export type FlagKey = keyof CliFlags;
export type FlagType = 'boolean' | 'int' | 'enum' | 'string';
export type FlagDefinition = {
key: FlagKey;
names: readonly string[];
type: FlagType;
enumValues?: readonly string[];
min?: number;
max?: number;
setValue?: CliFlags[FlagKey];
usageLabel?: string;
usageDescription?: string;
};
export type CommandSchema = {
description: string;
positionalArgs: readonly string[];
allowsExtraPositionals?: boolean;
allowedFlags: readonly FlagKey[];
defaults?: Partial<CliFlags>;
skipCapabilityCheck?: boolean;
usageOverride?: string;
};
const SNAPSHOT_FLAGS = [
'snapshotInteractiveOnly',
'snapshotCompact',
'snapshotDepth',
'snapshotScope',
'snapshotRaw',
'snapshotBackend',
] as const satisfies readonly FlagKey[];
const SELECTOR_SNAPSHOT_FLAGS = [
'snapshotDepth',
'snapshotScope',
'snapshotRaw',
'snapshotBackend',
] as const satisfies readonly FlagKey[];
const FIND_SNAPSHOT_FLAGS = ['snapshotDepth', 'snapshotRaw', 'snapshotBackend'] as const satisfies readonly FlagKey[];
export const FLAG_DEFINITIONS: readonly FlagDefinition[] = [
{
key: 'platform',
names: ['--platform'],
type: 'enum',
enumValues: ['ios', 'android'],
usageLabel: '--platform ios|android',
usageDescription: 'Platform to target',
},
{
key: 'device',
names: ['--device'],
type: 'string',
usageLabel: '--device <name>',
usageDescription: 'Device name to target',
},
{
key: 'udid',
names: ['--udid'],
type: 'string',
usageLabel: '--udid <udid>',
usageDescription: 'iOS device UDID',
},
{
key: 'serial',
names: ['--serial'],
type: 'string',
usageLabel: '--serial <serial>',
usageDescription: 'Android device serial',
},
{
key: 'activity',
names: ['--activity'],
type: 'string',
usageLabel: '--activity <component>',
usageDescription: 'Android app launch activity (package/Activity); not for URL opens',
},
{
key: 'session',
names: ['--session'],
type: 'string',
usageLabel: '--session <name>',
usageDescription: 'Named session',
},
{
key: 'count',
names: ['--count'],
type: 'int',
min: 1,
max: 200,
usageLabel: '--count <n>',
usageDescription: 'Repeat count for press/swipe series',
},
{
key: 'intervalMs',
names: ['--interval-ms'],
type: 'int',
min: 0,
max: 10_000,
usageLabel: '--interval-ms <ms>',
usageDescription: 'Delay between press iterations',
},
{
key: 'holdMs',
names: ['--hold-ms'],
type: 'int',
min: 0,
max: 10_000,
usageLabel: '--hold-ms <ms>',
usageDescription: 'Press hold duration for each iteration',
},
{
key: 'jitterPx',
names: ['--jitter-px'],
type: 'int',
min: 0,
max: 100,
usageLabel: '--jitter-px <n>',
usageDescription: 'Deterministic coordinate jitter radius for press',
},
{
key: 'pauseMs',
names: ['--pause-ms'],
type: 'int',
min: 0,
max: 10_000,
usageLabel: '--pause-ms <ms>',
usageDescription: 'Delay between swipe iterations',
},
{
key: 'pattern',
names: ['--pattern'],
type: 'enum',
enumValues: ['one-way', 'ping-pong'],
usageLabel: '--pattern one-way|ping-pong',
usageDescription: 'Swipe repeat pattern',
},
{
key: 'verbose',
names: ['--verbose', '-v'],
type: 'boolean',
usageLabel: '--verbose',
usageDescription: 'Stream daemon/runner logs',
},
{
key: 'json',
names: ['--json'],
type: 'boolean',
usageLabel: '--json',
usageDescription: 'JSON output',
},
{
key: 'help',
names: ['--help', '-h'],
type: 'boolean',
usageLabel: '--help, -h',
usageDescription: 'Print help and exit',
},
{
key: 'version',
names: ['--version', '-V'],
type: 'boolean',
usageLabel: '--version, -V',
usageDescription: 'Print version and exit',
},
{
key: 'saveScript',
names: ['--save-script'],
type: 'boolean',
usageLabel: '--save-script',
usageDescription: 'Save session script (.ad) on close',
},
{
key: 'relaunch',
names: ['--relaunch'],
type: 'boolean',
usageLabel: '--relaunch',
usageDescription: 'open: terminate app process before launching it',
},
{
key: 'noRecord',
names: ['--no-record'],
type: 'boolean',
usageLabel: '--no-record',
usageDescription: 'Do not record this action',
},
{
key: 'replayUpdate',
names: ['--update', '-u'],
type: 'boolean',
usageLabel: '--update, -u',
usageDescription: 'Replay: update selectors and rewrite replay file in place',
},
{
key: 'appsFilter',
names: ['--user-installed'],
type: 'enum',
setValue: 'user-installed',
usageLabel: '--user-installed',
usageDescription: 'Apps: list user-installed packages (Android only)',
},
{
key: 'appsFilter',
names: ['--all'],
type: 'enum',
setValue: 'all',
usageLabel: '--all',
usageDescription: 'Apps: list all packages (Android only)',
},
{
key: 'appsMetadata',
names: ['--metadata'],
type: 'boolean',
usageLabel: '--metadata',
usageDescription: 'Apps: return metadata objects',
},
{
key: 'snapshotInteractiveOnly',
names: ['-i'],
type: 'boolean',
usageLabel: '-i',
usageDescription: 'Snapshot: interactive elements only',
},
{
key: 'snapshotCompact',
names: ['-c'],
type: 'boolean',
usageLabel: '-c',
usageDescription: 'Snapshot: compact output (drop empty structure)',
},
{
key: 'snapshotDepth',
names: ['--depth', '-d'],
type: 'int',
min: 0,
usageLabel: '--depth, -d <depth>',
usageDescription: 'Snapshot: limit snapshot depth',
},
{
key: 'snapshotScope',
names: ['--scope', '-s'],
type: 'string',
usageLabel: '--scope, -s <scope>',
usageDescription: 'Snapshot: scope snapshot to label/identifier',
},
{
key: 'snapshotRaw',
names: ['--raw'],
type: 'boolean',
usageLabel: '--raw',
usageDescription: 'Snapshot: raw node output',
},
{
key: 'snapshotBackend',
names: ['--backend'],
type: 'enum',
enumValues: ['ax', 'xctest'],
usageLabel: '--backend ax|xctest',
usageDescription: 'Snapshot backend (iOS): ax or xctest',
},
{
key: 'out',
names: ['--out'],
type: 'string',
usageLabel: '--out <path>',
usageDescription: 'Output path',
},
];
export const GLOBAL_FLAG_KEYS = new Set<FlagKey>([
'json',
'help',
'version',
'verbose',
'platform',
'device',
'udid',
'serial',
'session',
'noRecord',
]);
export const COMMAND_SCHEMAS: Record<string, CommandSchema> = {
boot: {
description: 'Ensure target device/simulator is booted and ready',
positionalArgs: [],
allowedFlags: [],
},
open: {
description: 'Boot device/simulator; optionally launch app or deep link URL',
positionalArgs: ['appOrUrl?'],
allowedFlags: ['activity', 'saveScript', 'relaunch'],
},
close: {
description: 'Close app or just end session',
positionalArgs: ['app?'],
allowedFlags: ['saveScript'],
},
reinstall: {
description: 'Uninstall + install app from binary path',
positionalArgs: ['app', 'path'],
allowedFlags: [],
},
snapshot: {
description: 'Capture accessibility tree',
positionalArgs: [],
allowedFlags: [...SNAPSHOT_FLAGS],
},
devices: {
description: 'List available devices',
positionalArgs: [],
allowedFlags: [],
skipCapabilityCheck: true,
},
apps: {
description: 'List installed apps (Android launchable by default, iOS simulator)',
positionalArgs: [],
allowedFlags: ['appsFilter', 'appsMetadata'],
},
appstate: {
description: 'Show foreground app/activity',
positionalArgs: [],
allowedFlags: [],
skipCapabilityCheck: true,
},
back: {
description: 'Navigate back (where supported)',
positionalArgs: [],
allowedFlags: [],
},
home: {
description: 'Go to home screen (where supported)',
positionalArgs: [],
allowedFlags: [],
},
'app-switcher': {
description: 'Open app switcher (where supported)',
positionalArgs: [],
allowedFlags: [],
},
wait: {
usageOverride: 'wait <ms>|text <text>|@ref|<selector> [timeoutMs]',
description: 'Wait for duration, text, ref, or selector to appear',
positionalArgs: ['durationOrSelector', 'timeoutMs?'],
allowsExtraPositionals: true,
allowedFlags: [...SELECTOR_SNAPSHOT_FLAGS],
},
alert: {
usageOverride: 'alert [get|accept|dismiss|wait] [timeout]',
description: 'Inspect or handle alert (iOS simulator)',
positionalArgs: ['action?', 'timeout?'],
allowedFlags: [],
},
click: {
usageOverride: 'click <@ref|selector>',
description: 'Click element by snapshot ref or selector',
positionalArgs: ['target'],
allowedFlags: [...SELECTOR_SNAPSHOT_FLAGS],
},
get: {
usageOverride: 'get text|attrs <@ref|selector>',
description: 'Return element text/attributes by ref or selector',
positionalArgs: ['subcommand', 'target'],
allowedFlags: [...SELECTOR_SNAPSHOT_FLAGS],
},
replay: {
description: 'Replay a recorded session',
positionalArgs: ['path'],
allowedFlags: ['replayUpdate'],
skipCapabilityCheck: true,
},
press: {
description: 'Tap/press at coordinates (supports repeated gesture series)',
positionalArgs: ['x', 'y'],
allowedFlags: ['count', 'intervalMs', 'holdMs', 'jitterPx'],
},
'long-press': {
description: 'Long press (where supported)',
positionalArgs: ['x', 'y', 'durationMs?'],
allowedFlags: [],
},
swipe: {
description: 'Swipe coordinates with optional repeat pattern',
positionalArgs: ['x1', 'y1', 'x2', 'y2', 'durationMs?'],
allowedFlags: ['count', 'pauseMs', 'pattern'],
},
focus: {
description: 'Focus input at coordinates',
positionalArgs: ['x', 'y'],
allowedFlags: [],
},
type: {
description: 'Type text in focused field',
positionalArgs: ['text'],
allowsExtraPositionals: true,
allowedFlags: [],
},
fill: {
usageOverride: 'fill <x> <y> <text> | fill <@ref|selector> <text>',
description: 'Tap then type',
positionalArgs: ['targetOrX', 'yOrText', 'text?'],
allowsExtraPositionals: true,
allowedFlags: [...SELECTOR_SNAPSHOT_FLAGS],
},
scroll: {
description: 'Scroll in direction (0-1 amount)',
positionalArgs: ['direction', 'amount?'],
allowedFlags: [],
},
scrollintoview: {
description: 'Scroll until text appears',
positionalArgs: ['text'],
allowedFlags: [],
},
pinch: {
description: 'Pinch/zoom gesture (iOS simulator)',
positionalArgs: ['scale', 'x?', 'y?'],
allowedFlags: [],
},
screenshot: {
description: 'Capture screenshot',
positionalArgs: ['path?'],
allowedFlags: ['out'],
},
record: {
usageOverride: 'record start [path] | record stop',
description: 'Start/stop screen recording',
positionalArgs: ['start|stop', 'path?'],
allowedFlags: [],
},
trace: {
usageOverride: 'trace start [path] | trace stop [path]',
description: 'Start/stop trace log capture',
positionalArgs: ['start|stop', 'path?'],
allowedFlags: [],
skipCapabilityCheck: true,
},
find: {
usageOverride: 'find <locator|text> <action> [value]',
description: 'Find by text/label/value/role/id and run action',
positionalArgs: ['query', 'action', 'value?'],
allowsExtraPositionals: true,
allowedFlags: [...FIND_SNAPSHOT_FLAGS],
},
is: {
description: 'Assert UI state (visible|hidden|exists|editable|selected|text)',
positionalArgs: ['predicate', 'selector', 'value?'],
allowsExtraPositionals: true,
allowedFlags: [...SELECTOR_SNAPSHOT_FLAGS],
},
settings: {
description: 'Toggle OS settings (simulators)',
positionalArgs: ['setting', 'state'],
allowedFlags: [],
},
session: {
usageOverride: 'session list',
description: 'List active sessions',
positionalArgs: ['list?'],
allowedFlags: [],
skipCapabilityCheck: true,
},
};
const flagDefinitionByName = new Map<string, FlagDefinition>();
const flagDefinitionsByKey = new Map<FlagKey, FlagDefinition[]>();
for (const definition of FLAG_DEFINITIONS) {
for (const name of definition.names) {
flagDefinitionByName.set(name, definition);
}
const list = flagDefinitionsByKey.get(definition.key);
if (list) list.push(definition);
else flagDefinitionsByKey.set(definition.key, [definition]);
}
export function getFlagDefinition(token: string): FlagDefinition | undefined {
return flagDefinitionByName.get(token);
}
export function getCommandSchema(command: string | null): CommandSchema | undefined {
if (!command) return undefined;
return COMMAND_SCHEMAS[command];
}
export function getCliCommandNames(): string[] {
return Object.keys(COMMAND_SCHEMAS);
}
export function getSchemaCapabilityKeys(): string[] {
return Object.entries(COMMAND_SCHEMAS)
.filter(([, schema]) => !schema.skipCapabilityCheck)
.map(([name]) => name)
.sort();
}
export function isStrictFlagModeEnabled(value: string | undefined): boolean {
if (!value) return false;
const normalized = value.trim().toLowerCase();
return normalized === '1' || normalized === 'true' || normalized === 'yes' || normalized === 'on';
}
function formatPositionalArg(arg: string): string {
const optional = arg.endsWith('?');
const name = optional ? arg.slice(0, -1) : arg;
return optional ? `[${name}]` : `<${name}>`;
}
function buildCommandUsage(commandName: string, schema: CommandSchema): string {
if (schema.usageOverride) return schema.usageOverride;
const positionals = schema.positionalArgs.map(formatPositionalArg);
const flagLabels = schema.allowedFlags.flatMap((key) =>
(flagDefinitionsByKey.get(key) ?? []).map((definition) => definition.usageLabel ?? definition.names[0]),
);
const optionalFlags = flagLabels.map((label) => `[${label}]`);
return [commandName, ...positionals, ...optionalFlags].join(' ');
}
function renderUsageText(): string {
const header = `agent-device <command> [args] [--json]
CLI to control iOS and Android devices for AI agents.
`;
const commands = getCliCommandNames().map((name) => {
const schema = COMMAND_SCHEMAS[name];
if (!schema) throw new Error(`Missing command schema for ${name}`);
return { name, schema, usage: buildCommandUsage(name, schema) };
});
const maxUsage = Math.max(...commands.map((command) => command.usage.length)) + 2;
const commandLines: string[] = ['Commands:'];
for (const command of commands) {
commandLines.push(` ${command.usage.padEnd(maxUsage)}${command.schema.description}`);
}
const helpFlags = FLAG_DEFINITIONS
.filter((definition) => definition.usageLabel && definition.usageDescription);
const flagsSection = renderFlagSection('Flags:', helpFlags);
return `${header}
${commandLines.join('\n')}
${flagsSection}
`;
}
const USAGE_TEXT = renderUsageText();
export function buildUsageText(): string {
return USAGE_TEXT;
}
function listHelpFlags(keys: ReadonlySet<FlagKey>): FlagDefinition[] {
return FLAG_DEFINITIONS.filter(
(definition) =>
keys.has(definition.key) &&
definition.usageLabel !== undefined &&
definition.usageDescription !== undefined,
);
}
function renderFlagSection(title: string, definitions: FlagDefinition[]): string {
if (definitions.length === 0) {
return `${title}\n (none)`;
}
const maxFlagLabel = Math.max(...definitions.map((flag) => (flag.usageLabel ?? '').length)) + 2;
const lines = [title];
for (const flag of definitions) {
lines.push(` ${(flag.usageLabel ?? '').padEnd(maxFlagLabel)}${flag.usageDescription ?? ''}`);
}
return lines.join('\n');
}
export function buildCommandUsageText(commandName: string): string | null {
const schema = getCommandSchema(commandName);
if (!schema) return null;
const usage = buildCommandUsage(commandName, schema);
const commandFlags = listHelpFlags(new Set<FlagKey>(schema.allowedFlags));
const globalFlags = listHelpFlags(GLOBAL_FLAG_KEYS);
const sections: string[] = [];
if (commandFlags.length > 0) {
sections.push(renderFlagSection('Command flags:', commandFlags));
}
sections.push(renderFlagSection('Global flags:', globalFlags));
return `agent-device ${usage}
${schema.description}
Usage:
agent-device ${usage}
${sections.join('\n\n')}
`;
}