Skip to content

Commit 738bc1c

Browse files
committed
refactor(commands): one audience table for common input fields
"Who may write this input field, on which surface" was expressed three times, each a separate name-keyed mechanism: `retiredField()` in the command field maps, `ALWAYS_HIDDEN_FIELDS` in the AI SDK adapter, and `OPERATOR_INPUT_GUIDANCE` / `CONFIG_LOADER_GUIDANCE` at the MCP admission boundary -- twelve hand-written refusal sentences keyed by name, far from the fields they govern. The root cause was that the ~19 shared common fields existed only as parallel enumerations by name -- `commonProperties()`, `readCommonInput()`, `commonToClientOptions()`, and the `CommonCommandInput` type -- carrying no metadata, so any policy about a field forced a new name-keyed map elsewhere. Declare each common field once, in `commands/common-input-fields.ts`, keyed by its input key and carrying `{ schema?, read?, clientKey?, audience? }`. The JSON schema, the readers, the client-options projection, and the model-facing audience boundary all derive from that one table, and `satisfies Record<keyof CommonCommandInput | 'target', ...>` makes a row without a field, or a field without a row, a type error in both directions. `audience` is the unified vocabulary (`commands/input-audience.ts`): `operator` keys stay in the CLI and Node schemas but are hidden from and refused by every model-facing tool schema; `retired` keys are absent from every schema yet still recognized, so they answer with migration guidance. `retiredField()` now sets `audience: 'retired'`, metro's `bearerToken`/`proxyBaseUrl` declare `audience: 'operator'` at the field, and `stateDir` declares it in the new `mcp/tool-control-fields.ts` beside the other MCP-only tool arguments. Refusal guidance is rendered from each declaration's operator path -- env var names via `buildPrimaryEnvVarName`, the operator config file, or an explicit sentence -- rather than hand-written per key, and `OperatorInputSource` is shaped so a declaration naming no path at all does not typecheck. `#2076`'s nested-step admission recurses through the same derived `findInadmissibleInput`, so a batch step's refusals come from this audience map rather than a second filter; its suite passes against this unchanged. A field-level audience only reaches the boundaries through its command's metadata, so that wiring is closed structurally rather than by convention: `inputAudience` is required on `CommandMetadata`, and `defineFieldCommandMetadata` -- which now takes an optional custom reader, so `batch` and `gesture` go through it too -- is the only construction path for a field-map command. At the boundary, a command's own audiences merge before the global operator classifications, so an `operator` key outranks a colliding per-command `retired` one and a name collision fails closed. `command-input.ts` was 705 lines and over the 300-line target; the record readers move to `commands/input-readers.ts` so the table can use them without an import cycle. `click`/`press`/`fill` move onto `defineFieldCommandMetadata` -- they were that helper inlined. `COMMON_COMMAND_SUPPORTED_FLAG_KEYS` stays hand-maintained: it is the CLI parser's axis, and 25 of its 42 keys never become structured command input while the table's `cwd` and `debug` are not flags. The reasoning is recorded above the constant. Purely internal: `listCommandTools()`, the CLI command schemas, and every command `inputSchema` are byte-identical, verified by diffing the serialized surfaces before and after. Refs #2027
1 parent c794c11 commit 738bc1c

26 files changed

Lines changed: 907 additions & 498 deletions

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ Read the declaration rather than maintaining a prose copy:
5353
- interaction paths and guarantees: `packages/contracts/src/interaction-guarantees.ts`
5454
- canonical command names: `src/command-catalog.ts`
5555
- device capability admission: `src/core/capabilities.ts`
56+
- common command input fields, and which surface may write an input key (model, operator, retired):
57+
`src/commands/common-input-fields.ts` and `src/commands/input-audience.ts`
5658

5759
Shared selector parsing and matching belongs in `@agent-device/selectors`; request cancellation and
5860
progress in `src/request`; cross-layer contracts in `src/contracts`; CLI flags in

‎docs/agents/cli-flags.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ mattering — threading it further is the common failure, not stopping too early
1717
3. `src/commands/command-projection.ts` and command-family projection helpers: write the input into
1818
the daemon request only if the flag affects daemon execution.
1919
4. `src/commands/*-command-contracts.ts`: add to the command input schema only if the option should
20-
be available through Node.js or MCP as structured input.
20+
be available through Node.js or MCP as structured input. An input key that names a credential,
21+
an endpoint a credential is sent to, or operator infrastructure declares `operatorField(...)`
22+
(`src/commands/command-input.ts`), which is what keeps the MCP and AI SDK tool schemas from
23+
offering the model a parameter to write it into. One of the shared common keys declares the same
24+
audience in its `src/commands/common-input-fields.ts` row instead.
2125
5. `src/client/client-types.ts`: update the public typed client option only when the Node.js
2226
interface exposes it.
2327
6. `src/client/client-normalizers.ts`: update daemon flag normalization only when the request still

‎src/__tests__/eager-closure-budgets.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,12 @@ export const HUB_BUDGETS: Readonly<Record<string, number>> = Object.freeze({
332332
// (`resolveLocalDaemonCodeSignature`) rather than appearing here.
333333
// #2054 splits daemon cleanup and managed web backend into separate neutral contract entries;
334334
// the CLI already loads both command modules, so the second one-module contract is deliberate.
335-
'src/cli.ts': 365,
335+
// #2027 splits the 705-line `commands/command-input.ts` into the three leaf modules the
336+
// common-field table needs to exist without an import cycle: `input-readers.ts` (record
337+
// readers), `input-audience.ts` (who may write a key), and `common-input-fields.ts` (the table
338+
// itself). Every command schema already evaluated all three concerns; the growth is three more
339+
// module records for the same code, with no new subtree behind any of them.
340+
'src/cli.ts': 368,
336341
'src/platform-runtime.ts': 47,
337342
'src/core/capabilities.ts': 73,
338343
'src/core/command-descriptor/registry.ts': 67,

‎src/ai-sdk/index.ts‎

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { AgentDeviceClient } from '../client/client-types.ts';
66
import type { JsonSchema } from '../commands/command-contract.ts';
77
import { resolveCommandFrameworkTier } from '../core/command-descriptor/registry.ts';
88
import { createCommandToolExecutor, listCommandTools } from '../mcp/command-tools.ts';
9+
import { MCP_TOOL_CONFIG_KEYS } from '../mcp/tool-control-fields.ts';
910
import { formatToolErrorText } from '../mcp/tool-error.ts';
1011

1112
/**
@@ -53,22 +54,13 @@ export type AgentDeviceTools = {
5354
// `execute` forwards to the shared executor:
5455
// - `session` is always pinned by this factory — the whole point is that a
5556
// tool call can never target a session other than the one passed in.
56-
// - `stateDir` selects which daemon state directory (and therefore which
57-
// daemon/session namespace) a call resolves against. Left model-visible,
58-
// it would let a call escape the pinned session into another daemon's
59-
// state entirely, defeating that guarantee.
60-
// - `mcpOutputFormat`, `includeCost`, `responseLevel` are MCP tool-config
61-
// knobs, not command arguments; irrelevant here since `execute` below
62-
// returns structuredContent directly and never reads a tool's rendered
63-
// text, and shaping the response is this factory's decision, not the
64-
// model's.
65-
const ALWAYS_HIDDEN_FIELDS = [
66-
'session',
67-
'stateDir',
68-
'mcpOutputFormat',
69-
'includeCost',
70-
'responseLevel',
71-
] as const;
57+
// - every MCP tool-config key: `stateDir` selects which daemon state directory
58+
// (and therefore which daemon/session namespace) a call resolves against, so
59+
// left model-visible it would let a call escape the pinned session into
60+
// another daemon's state entirely; the rest shape the response, which is this
61+
// factory's decision, not the model's (`execute` below returns
62+
// structuredContent directly and never reads a tool's rendered text).
63+
const ALWAYS_HIDDEN_FIELDS: readonly string[] = ['session', ...MCP_TOOL_CONFIG_KEYS];
7264

7365
// The registry's hand-rolled JsonSchema type and `jsonSchema()`'s expected
7466
// JSONSchema7 (re-exported from @ai-sdk/provider, not from `ai` itself) are

‎src/cli/batch-steps.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
BATCH_AVAILABLE_COMMANDS_HINT,
1111
readStructuredBatchCommandName,
1212
} from '../core/batch-policy.ts';
13-
import { assertAllowedKeys } from '../commands/command-input.ts';
13+
import { assertAllowedKeys } from '../commands/input-readers.ts';
1414

1515
/**
1616
* The terminal half of the step-shape refusal. `@agent-device/contracts` states the shape for
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import {
4+
COMMON_INPUT_AUDIENCE,
5+
commonProperties,
6+
commonToClientOptions,
7+
readCommonInput,
8+
} from '../common-input-fields.ts';
9+
import { operatorInputRefusal } from '../input-audience.ts';
10+
11+
// The guidance a refused operator key answers with is rendered from the key's
12+
// declared source, not written per key. These pin the four shapes the
13+
// declarations use, so a change to the template or to `buildPrimaryEnvVarName`
14+
// fails here instead of silently degrading every operator refusal at once.
15+
test('an operator refusal names the environment variable and the config key', () => {
16+
assert.equal(
17+
operatorInputRefusal('daemonAuthToken', { operatorConfig: true }),
18+
'daemonAuthToken is not accepted as a tool argument. Set the AGENT_DEVICE_DAEMON_AUTH_TOKEN environment variable (or daemonAuthToken in ~/.agent-device/config.json) for the process serving these tools.',
19+
);
20+
});
21+
22+
test('an operator refusal names every environment variable that carries the value', () => {
23+
assert.equal(
24+
operatorInputRefusal('bearerToken', { envFlagKeys: ['metroBearerToken', 'daemonAuthToken'] }),
25+
'bearerToken is not accepted as a tool argument. Set the AGENT_DEVICE_METRO_BEARER_TOKEN or AGENT_DEVICE_DAEMON_AUTH_TOKEN environment variable for the process serving these tools.',
26+
);
27+
});
28+
29+
test('a key with no environment variable points at the operator config file alone', () => {
30+
assert.equal(
31+
operatorInputRefusal('iosSimulatorDeviceSet', { envFlagKeys: [], operatorConfig: true }),
32+
'iosSimulatorDeviceSet is not accepted as a tool argument. Set iosSimulatorDeviceSet in ~/.agent-device/config.json for the process serving these tools.',
33+
);
34+
});
35+
36+
test('a key neither env nor config resolves states its own operator path', () => {
37+
assert.equal(
38+
operatorInputRefusal('cwd', { operatorPath: 'Start the process elsewhere.' }),
39+
'cwd is not accepted as a tool argument. Start the process elsewhere.',
40+
);
41+
});
42+
43+
// `audience` narrows the MODEL-facing surfaces only. The CLI and the Node client
44+
// still accept an operator key as ordinary input -- that is how an operator
45+
// supplies it, and how env/config defaults reach the command route. A
46+
// classification that also narrowed `commonProperties()` would break both
47+
// without failing the MCP tests, which only assert absence.
48+
// (Which keys are operator-owned is pinned at the boundary that enforces it,
49+
// in `mcp/__tests__/command-tools-operator-inputs.test.ts`.)
50+
test('an operator-owned common key stays in the CLI and Node input schema', () => {
51+
const advertised = commonProperties();
52+
const operatorKeys = Object.keys(COMMON_INPUT_AUDIENCE);
53+
assert.ok(operatorKeys.length > 0, 'the table declares operator-owned common keys');
54+
for (const key of operatorKeys) {
55+
assert.equal(COMMON_INPUT_AUDIENCE[key]?.kind, 'operator');
56+
assert.ok(key in advertised, `${key} must stay readable by the CLI and Node client`);
57+
}
58+
});
59+
60+
// Schema, readers, and projection are three derivations of one table. A row
61+
// that loses its reader or its projection entry drops the key silently at the
62+
// seam nothing else covers, which is the failure `--no-record` hit twice
63+
// (#1304/#1305). Round-tripping every advertised key catches it.
64+
test('every advertised common key is read and projected onto the client options', () => {
65+
const advertised = Object.keys(commonProperties());
66+
const record = Object.fromEntries(
67+
advertised.map((key) => [key, commonInputValueFor(key)]),
68+
) as Record<string, unknown>;
69+
record.noRecord = true;
70+
71+
const input = readCommonInput(record);
72+
const options = commonToClientOptions(input) as Record<string, unknown>;
73+
74+
for (const key of advertised) {
75+
// `deviceTarget` and its `target` alias are one value under two spellings;
76+
// the projection emits the client-facing `target`.
77+
const projected = key === 'deviceTarget' ? 'target' : key;
78+
assert.ok(projected in options, `${key} is dropped between reader and projection`);
79+
}
80+
assert.equal(options.noRecord, true, 'noRecord rides the common seam with no schema of its own');
81+
assert.equal(options.target, 'mobile');
82+
});
83+
84+
function commonInputValueFor(key: string): unknown {
85+
if (key === 'platform') return 'ios';
86+
if (key === 'deviceTarget' || key === 'target') return 'mobile';
87+
if (key === 'debug') return true;
88+
return `value-${key}`;
89+
}

‎src/commands/batch/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { commonInputFromFlags } from '../cli-grammar/common.ts';
44
import type { CliReader } from '../cli-grammar/types.ts';
55
import { defineCommandFacet, defineCommandFamilyFromFacets } from '../family/types.ts';
66
import { defineExecutableCommand } from '../command-contract.ts';
7-
import { commonToClientOptions } from '../command-input.ts';
7+
import { commonToClientOptions } from '../common-input-fields.ts';
88
import { batchCliOutputFormatters } from './output.ts';
99
import { createBatchCommandMetadata, type BatchCommandStep, type BatchInput } from './metadata.ts';
1010
import { STRUCTURED_BATCH_COMMAND_NAMES } from '../../core/batch-policy.ts';

‎src/commands/batch/metadata.ts‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,19 @@ import {
1313
STRUCTURED_BATCH_COMMAND_NAMES,
1414
readStructuredBatchCommandName,
1515
} from '../../core/batch-policy.ts';
16+
import { type CommandMetadata, type JsonSchema } from '../command-contract.ts';
1617
import {
17-
defineCommandMetadata,
18-
type CommandMetadata,
19-
type JsonSchema,
20-
} from '../command-contract.ts';
21-
import {
22-
assertAllowedKeys,
2318
customField,
2419
enumField,
25-
fieldsInputSchema,
2620
integerField,
2721
readFieldInput,
2822
requiredField,
2923
stringField,
3024
type CommandFieldMap,
3125
type InferCommandInput,
3226
} from '../command-input.ts';
27+
import { defineFieldCommandMetadata } from '../field-command-contract.ts';
28+
import { assertAllowedKeys } from '../input-readers.ts';
3329

3430
export type BatchCommandStep = {
3531
command: string;
@@ -48,12 +44,12 @@ export function createBatchCommandMetadata(
4844
nestedCommands: readonly string[] = STRUCTURED_BATCH_COMMAND_NAMES,
4945
): CommandMetadata<'batch', BatchInput> {
5046
const fields = batchFields(nestedCommands);
51-
return defineCommandMetadata({
52-
name: 'batch',
53-
description: 'Execute multiple commands in one daemon request.',
54-
inputSchema: fieldsInputSchema(fields),
55-
readInput: (input) => readBatchInput(input, fields),
56-
});
47+
return defineFieldCommandMetadata(
48+
'batch',
49+
'Execute multiple commands in one daemon request.',
50+
fields,
51+
{ readInput: (input) => readBatchInput(input, fields) },
52+
);
5753
}
5854

5955
function batchFields(nestedCommands: readonly string[]) {

‎src/commands/capture/alert.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { ALERT_ACTIONS, type AlertAction } from '@agent-device/contracts/alert-contract';
22
import { PUBLIC_COMMANDS } from '../../command-catalog.ts';
33
import type { AlertCommandOptions } from '@agent-device/contracts/client';
4-
import { compactRecord, enumField, integerField } from '../command-input.ts';
4+
import { enumField, integerField } from '../command-input.ts';
5+
import { compactRecord } from '../input-readers.ts';
56
import { defineExecutableCommand } from '../command-contract.ts';
67
import {
78
commonInputFromFlags,

‎src/commands/capture/wait.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,8 @@ import { parseWaitPositionals } from '../../core/wait-positionals.ts';
55
import { SELECTOR_SNAPSHOT_FLAGS } from '../cli-grammar/flag-groups.ts';
66
import { AppError } from '@agent-device/kernel/errors';
77
import { isValidSelectorExpression } from '@agent-device/selectors';
8-
import {
9-
booleanField,
10-
enumField,
11-
integerField,
12-
optionalEnum,
13-
stringField,
14-
} from '../command-input.ts';
8+
import { booleanField, enumField, integerField, stringField } from '../command-input.ts';
9+
import { optionalEnum } from '../input-readers.ts';
1510
import { defineExecutableCommand } from '../command-contract.ts';
1611
import {
1712
direct,

0 commit comments

Comments
 (0)