Repository navigation
Expand file tree
/
Copy pathcommand-input.ts
More file actions
587 lines (527 loc) · 18.3 KB
/
Copy pathcommand-input.ts
File metadata and controls
587 lines (527 loc) · 18.3 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
import type {
AgentDeviceRequestOverrides,
AgentDeviceSelectionOptions,
ElementTarget,
InteractionTarget,
} from '@agent-device/contracts/client';
import {
readOptionalInteger as optionalInteger,
readOptionalNumber as optionalNumberValue,
type CliFlags,
} from '@agent-device/contracts/command';
import { getFlagDefinitionsForKey } from '@agent-device/command-registry/flag-registry';
import type { FlagDefinition, FlagKey } from '@agent-device/command-registry/flag-types';
import { AppError } from '@agent-device/kernel/errors';
import type { RepeatedInput } from '@agent-device/contracts/interaction';
import type { JsonSchema } from './command-contract.ts';
import {
commonProperties,
commonToClientOptions,
readCommonInput,
type CommonCommandInput,
} from './common-input-fields.ts';
import type { InputAudience, InputAudienceMap, OperatorInputSource } from './input-audience.ts';
import {
compactRecord,
optionalAnyString,
optionalBoolean,
optionalEnum,
optionalRecord,
optionalString,
optionalStringArray,
readInputRecord,
readRecordField,
requiredEnum,
requiredNumber,
requiredString,
} from './input-readers.ts';
const INTERACTION_TARGET_KINDS = ['ref', 'selector', 'point'] as const;
export type InteractionTargetInput =
| { kind: 'ref'; ref: string; label?: string }
| { kind: 'selector'; selector: string }
| { kind: 'point'; x: number; y: number };
export type ElementTargetInput =
| { kind: 'ref'; ref: string; label?: string }
| { kind: 'selector'; selector: string };
export type SelectorSnapshotInput = {
depth?: number;
scope?: string;
raw?: boolean;
};
export type PointInput = { x: number; y: number };
function commandInputSchema(
properties: Record<string, JsonSchema>,
required: readonly string[] = [],
): JsonSchema {
return {
type: 'object',
properties: {
...commonProperties(),
...properties,
},
...(required.length > 0 ? { required } : {}),
additionalProperties: false,
};
}
/**
* A non-strict object shape, for what a command RETURNS. It deliberately omits
* `additionalProperties: false` and never injects the common device-selection fields, so
* additive response fields such as `cost` keep validating. An advertised INPUT object is
* built by `commandInputSchema` instead, which is strict and carries those fields.
*/
export function objectSchema(
properties: Record<string, JsonSchema>,
required: readonly string[] = [],
description?: string,
): JsonSchema {
return {
type: 'object',
...(description ? { description } : {}),
properties,
...(required.length > 0 ? { required } : {}),
};
}
function pointSchema(description: string): JsonSchema {
return {
type: 'object',
description,
properties: {
x: { type: 'number' },
y: { type: 'number' },
},
required: ['x', 'y'],
additionalProperties: false,
};
}
export function enumSchema(values: readonly string[], description?: string): JsonSchema {
return { type: 'string', enum: values, ...(description ? { description } : {}) };
}
/** A single-valued string schema, for a discriminant field an output shape always fixes. */
export function constSchema(value: string): JsonSchema {
return { type: 'string', const: value };
}
export function stringSchema(description?: string): JsonSchema {
return { type: 'string', ...(description ? { description } : {}) };
}
export function nullableStringSchema(description?: string): JsonSchema {
return { type: ['string', 'null'], ...(description ? { description } : {}) };
}
export function numberSchema(
description?: string,
options: { min?: number; max?: number } = {},
): JsonSchema {
return {
type: 'number',
...(description ? { description } : {}),
...(options.min === undefined ? {} : { minimum: options.min }),
...(options.max === undefined ? {} : { maximum: options.max }),
};
}
function integerSchema(description?: string): JsonSchema {
return { type: 'integer', ...(description ? { description } : {}) };
}
export function booleanSchema(description?: string): JsonSchema {
return { type: 'boolean', ...(description ? { description } : {}) };
}
export function stringArraySchema(description?: string): JsonSchema {
return {
type: 'array',
items: { type: 'string' },
...(description ? { description } : {}),
};
}
export function looseObjectSchema(description?: string): JsonSchema {
return {
type: 'object',
additionalProperties: true,
...(description ? { description } : {}),
};
}
type FieldReader<T> = (record: Record<string, unknown>, key: string) => T | undefined;
export type CommandField<T> = {
schema: JsonSchema;
required: boolean;
read: FieldReader<T>;
/** Who may write the key. Absent means the model — see `input-audience.ts`. */
audience?: InputAudience;
};
export type CommandFieldMap = Record<string, CommandField<unknown>>;
export type InferCommandFields<TFields extends CommandFieldMap> = {
[
TKey in keyof TFields as TFields[TKey]['required'] extends true ? TKey : never
]: TFields[TKey] extends CommandField<infer TValue> ? TValue : never;
} & {
[
TKey in keyof TFields as TFields[TKey]['required'] extends true ? never : TKey
]?: TFields[TKey] extends CommandField<infer TValue> ? TValue : never;
};
export type InferCommandInput<TFields extends CommandFieldMap> = InferCommandFields<TFields> &
CommonCommandInput &
AgentDeviceRequestOverrides &
AgentDeviceSelectionOptions;
export function requiredField<T>(
field: CommandField<T>,
): CommandField<Exclude<T, undefined>> & { required: true } {
return { ...field, required: true } as CommandField<Exclude<T, undefined>> & {
required: true;
};
}
export function stringField(
description?: string,
options: { allowEmpty?: boolean } = {},
): CommandField<string> {
return optionalField(
stringSchema(description),
options.allowEmpty === true ? optionalAnyString : optionalString,
);
}
/**
* A released input key that was removed. Declared in the field map so the
* projection seam (`readFieldInput`) refuses it with migration guidance
* instead of silently dropping it; excluded from the JSON schema so tools no
* longer advertise it.
*/
export function retiredField(message: string): CommandField<never> {
return {
schema: { type: 'null' },
required: false,
audience: { kind: 'retired', message },
read: (record, key) => {
if (Object.hasOwn(record, key)) {
throw new AppError('INVALID_ARGS', message);
}
return undefined;
},
};
}
/**
* A key the CLI and the Node client accept but no model-facing tool schema may
* advertise or admit — a credential, an endpoint a credential is sent to, or an
* operator infrastructure path. `source` names how the operator supplies it, and
* the refusal is rendered from that.
*/
export function operatorField<T>(
field: CommandField<T>,
source: OperatorInputSource,
): CommandField<T> {
return { ...field, audience: { kind: 'operator', source } };
}
export function numberField(
description?: string,
options: { min?: number; max?: number } = {},
): CommandField<number> {
return optionalField(numberSchema(description, options), (record, key) =>
optionalNumberValue(record, key, options),
);
}
export function integerField(
description?: string,
options: { min?: number; max?: number } = {},
): CommandField<number> {
return optionalField(integerSchemaWithBounds(description, options), (record, key) =>
optionalInteger(record, key, options),
);
}
export function booleanField(description?: string): CommandField<boolean> {
return optionalField(booleanSchema(description), optionalBoolean);
}
/**
* Builds a command's input field from the option's ONE declaration.
*
* A hand-written field — `booleanField('Include an initial interactive
* snapshot…')` — restates two facts the option already declared: its value type
* (`type: 'boolean'` on the `FlagDefinition`) and its description, as a second,
* differently-worded copy of the same sentence. Neither copy decides anything
* and both drift: `open --foreground` had one description rewritten across four
* files at once because no file owned it.
*
* Derived here instead:
* - the JSON schema shape and its bounds come from the declaration's `type`,
* `enumValues`, `min` and `max`;
* - the description comes from the declaration's `inputDescription`;
* - the TypeScript value type comes from `CliFlags[key]`, which is already
* where that flag's type is declared.
*
* So an option's description is one edit, and a command cannot advertise an
* input its own CLI flag does not parse.
*/
export function optionField<TKey extends FlagKey>(
key: TKey,
): CommandField<NonNullable<CliFlags[TKey]>> {
return buildOptionField(optionDeclaration(key)) as CommandField<NonNullable<CliFlags[TKey]>>;
}
/**
* Fails closed: a command may derive a field only from an option that actually
* declares a tool/SDK audience, rather than publishing an undescribed input.
*/
function optionDeclaration(key: FlagKey): FlagDefinition {
const declared = getFlagDefinitionsForKey(key).filter(
(definition) => definition.inputDescription !== undefined,
);
const [definition, ...extra] = declared;
if (!definition) {
throw new Error(`Flag ${key} declares no inputDescription; optionField cannot derive a field`);
}
if (extra.length > 0) {
throw new Error(`Flag ${key} declares inputDescription more than once`);
}
return definition;
}
function buildOptionField(definition: FlagDefinition): CommandField<unknown> {
const description = definition.inputDescription;
const bounds = { min: definition.min, max: definition.max };
switch (definition.type) {
case 'boolean':
return booleanField(description) as CommandField<unknown>;
case 'int':
return integerField(description, bounds) as CommandField<unknown>;
case 'number':
return numberField(description, bounds) as CommandField<unknown>;
case 'string':
return stringField(description) as CommandField<unknown>;
case 'enum':
return enumField(optionEnumValues(definition), description) as CommandField<unknown>;
case 'booleanOrString':
throw new Error(
`Flag ${definition.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`,
);
}
}
function optionEnumValues(definition: FlagDefinition): readonly string[] {
const values = definition.enumValues;
if (!values) {
throw new Error(`Flag ${definition.key} is an enum with no enumValues`);
}
return values;
}
export function enumField<const TValues extends readonly string[]>(
values: TValues,
description?: string,
): CommandField<TValues[number]> {
return optionalField(enumSchema(values, description), (record, key) =>
optionalEnum(record, key, values),
);
}
export function looseObjectField(description?: string): CommandField<Record<string, unknown>> {
return optionalField(looseObjectSchema(description), optionalRecord);
}
export function stringArrayField(description?: string): CommandField<string[]> {
return optionalField(stringArraySchema(description), optionalStringArray);
}
export function jsonSchemaField<T>(schema: JsonSchema): CommandField<T> {
return optionalField(schema, (record, key) => record[key] as T | undefined);
}
export function customField<T>(
schema: JsonSchema,
read: (record: Record<string, unknown>, key: string) => T | undefined,
): CommandField<T> {
return optionalField(schema, read);
}
export function interactionTargetField(): CommandField<InteractionTargetInput> {
return optionalField(interactionTargetSchema(), (record, key) =>
record[key] === undefined ? undefined : readInteractionTarget(record, key),
);
}
export function elementTargetField(): CommandField<ElementTargetInput> {
return optionalField(elementTargetSchema(), (record, key) =>
record[key] === undefined ? undefined : readElementTarget(record, key),
);
}
export function pointField(description: string): CommandField<PointInput> {
return optionalField(pointSchema(description), (record, key) =>
record[key] === undefined ? undefined : readPoint(record, key),
);
}
export function selectorSnapshotFields() {
return {
depth: integerField('Snapshot traversal depth.', { min: 0 }),
scope: stringField('Snapshot scope selector used before resolution.'),
raw: booleanField('Use raw snapshot data during selector resolution.'),
};
}
export function repeatedFields() {
return {
count: integerField('Number of press/click repetitions.', { min: 1 }),
intervalMs: integerField('Delay between repeated press/click actions.', { min: 0 }),
holdMs: integerField('Hold duration for each action.', { min: 0 }),
jitterPx: integerField('Randomization radius in pixels.', { min: 0 }),
doubleTap: booleanField('Request a double-tap action.'),
};
}
export function fieldsInputSchema(fields: CommandFieldMap): JsonSchema {
return commandInputSchema(fieldProperties(fields), requiredFieldNames(fields));
}
export function readFieldInput<TFields extends CommandFieldMap>(
input: unknown,
fields: TFields,
): InferCommandInput<TFields> {
const record = readInputRecord(input);
const commandOptions = Object.fromEntries(
Object.entries(fields).flatMap(([key, field]) => {
const value = field.read(record, key);
if (field.required && value === undefined) {
throw new AppError('INVALID_ARGS', `Expected ${key} to be set.`);
}
return value === undefined ? [] : [[key, value]];
}),
);
const commonInput = readCommonInput(record, {
readTargetAlias: !Object.hasOwn(fields, 'target'),
});
return compactRecord({
...commonInput,
...commonToClientOptions(commonInput),
...commandOptions,
}) as InferCommandInput<TFields>;
}
function readInteractionTarget(
record: Record<string, unknown>,
key: string,
): InteractionTargetInput {
const target = readRecordField(record, key);
const kind = requiredEnum(target, 'kind', INTERACTION_TARGET_KINDS);
switch (kind) {
case 'ref':
return {
kind,
ref: requiredString(target, 'ref'),
label: optionalString(target, 'label'),
};
case 'selector':
return { kind, selector: requiredString(target, 'selector') };
case 'point':
return {
kind,
x: requiredNumber(target, 'x'),
y: requiredNumber(target, 'y'),
};
}
}
function readElementTarget(record: Record<string, unknown>, key: string): ElementTargetInput {
const target = readRecordField(record, key);
const kind = requiredEnum(target, 'kind', ['ref', 'selector'] as const);
if (kind === 'ref') {
return {
kind,
ref: requiredString(target, 'ref'),
label: optionalString(target, 'label'),
};
}
return { kind, selector: requiredString(target, 'selector') };
}
function readPoint(record: Record<string, unknown>, key: string): PointInput {
const point = readRecordField(record, key);
return { x: requiredNumber(point, 'x'), y: requiredNumber(point, 'y') };
}
export function toClientInteractionTarget(target: InteractionTargetInput): InteractionTarget {
switch (target.kind) {
case 'ref':
return { ref: target.ref, label: target.label };
case 'selector':
return { selector: target.selector };
case 'point':
return { x: target.x, y: target.y };
}
}
export function toClientElementTarget(target: ElementTargetInput): ElementTarget {
switch (target.kind) {
case 'ref':
return { ref: target.ref, label: target.label };
case 'selector':
return { selector: target.selector };
}
}
export function toRepeatedOptions(input: RepeatedInput): RepeatedInput {
return {
count: input.count,
intervalMs: input.intervalMs,
holdMs: input.holdMs,
jitterPx: input.jitterPx,
doubleTap: input.doubleTap,
};
}
export function toSelectorSnapshotOptions(input: SelectorSnapshotInput): SelectorSnapshotInput {
return {
depth: input.depth,
scope: input.scope,
raw: input.raw,
};
}
function optionalField<T>(schema: JsonSchema, read: FieldReader<T>): CommandField<T> {
return { schema, required: false, read };
}
function integerSchemaWithBounds(
description: string | undefined,
options: { min?: number; max?: number },
): JsonSchema {
return {
...integerSchema(description),
...(options.min === undefined ? {} : { minimum: options.min }),
...(options.max === undefined ? {} : { maximum: options.max }),
};
}
function fieldProperties(fields: CommandFieldMap): Record<string, JsonSchema> {
return Object.fromEntries(
Object.entries(fields)
.filter(([, field]) => field.audience?.kind !== 'retired')
.map(([key, field]) => [key, field.schema]),
);
}
function requiredFieldNames(fields: CommandFieldMap): string[] {
return Object.entries(fields).flatMap(([key, field]) => (field.required ? [key] : []));
}
/** Non-model audiences declared by a command's own fields, for the surface boundaries to honor. */
export function fieldAudiences(fields: CommandFieldMap): InputAudienceMap {
return Object.fromEntries(
Object.entries(fields).flatMap(([key, field]) =>
field.audience ? [[key, field.audience]] : [],
),
);
}
function interactionTargetSchema(): JsonSchema {
return {
oneOf: [
...elementTargetSchemaVariants(),
{
type: 'object',
properties: {
kind: { type: 'string', const: 'point' },
x: { type: 'number' },
y: { type: 'number' },
},
required: ['kind', 'x', 'y'],
additionalProperties: false,
},
],
description: 'UI target. This is separate from deviceTarget, which selects the device form.',
};
}
function elementTargetSchema(): JsonSchema {
return {
oneOf: elementTargetSchemaVariants(),
description: 'UI element target by snapshot ref or selector expression.',
};
}
function elementTargetSchemaVariants(): JsonSchema[] {
return [
{
type: 'object',
properties: {
kind: { type: 'string', const: 'ref' },
ref: { type: 'string', description: 'Snapshot element ref such as @e12.' },
label: { type: 'string', description: 'Optional human label for the ref.' },
},
required: ['kind', 'ref'],
additionalProperties: false,
},
{
type: 'object',
properties: {
kind: { type: 'string', const: 'selector' },
selector: { type: 'string', description: 'Agent-device selector expression.' },
},
required: ['kind', 'selector'],
additionalProperties: false,
},
];
}