Repository navigation
Expand file tree
/
Copy pathsnapshot-settings.ts
More file actions
436 lines (416 loc) · 16.3 KB
/
Copy pathsnapshot-settings.ts
File metadata and controls
436 lines (416 loc) · 16.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
import {
isApplePlatform,
isHandheldAppleSimulator,
isMacOs,
resolveDeviceAppleOs,
} from '@agent-device/kernel/device';
import {
APPLE_TEXT_SIZE_LEAF_REFUSAL,
describeSettingRead,
describeSettingWrite,
getUnsupportedMacOsSettingMessage,
isMacOsSettingSupported,
invalidTextSizeMessage,
readTextSizeCategory,
settingsAppNotConsumedRefusal,
settingsAppScope,
SETTINGS_INVALID_ARGS_MESSAGE,
type ReadableSetting,
type SettingsTargetFamily,
type SettingOptions,
} from '@agent-device/contracts/settings';
import type { SetSettingInput } from '@agent-device/contracts/settings-runtime';
import {
resolveSettingsRuntimePlan,
settingReadUse,
settingsRuntimeUse,
} from '@agent-device/contracts/platform-runtime-operations';
import type { BoundDeviceRuntime } from '@agent-device/contracts/platform-runtime';
import { contextFromFlags } from '../context.ts';
import { SessionStore } from '../session-store.ts';
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
import type { SessionState } from '../session-state.ts';
import { recordIfSession } from '../snapshot-session.ts';
import { expireRefFrame } from '../ref-frame.ts';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { readLocationCoordinate } from '@agent-device/kernel/location-coordinates';
import { sessionAppRequiredDetails } from '@agent-device/kernel/errors';
import { successText, withSuccessText } from '@agent-device/kernel/success-text';
import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from '../request-runtime-binding.ts';
import { admitRuntimeUse } from '../runtime-admission.ts';
import { runtimeExecutionFromContext } from '../snapshot-runtime-capture-input.ts';
import { type DaemonFailureResponse, errorResponse } from '@agent-device/kernel/contracts';
type ParsedSettingsArgs = {
setting: string;
state: string;
appBundleId?: string;
permissionTarget?: string;
permissionMode?: string;
latitude?: string;
longitude?: string;
};
/**
* Which half of the settings surface a request asks for. A bare `settings <setting>` names a
* setting the command vocabulary declares readable and runs the owner's read leg; everything else
* is the mutation it has always been. The legs are separate because an owner admits one without the
* other — the macOS host sets an appearance it has no ladder to read back.
*/
export type ParsedSettingsRequest =
| Readonly<{ leg: 'read'; setting: ReadableSetting }>
| Readonly<{ leg: 'write'; args: ParsedSettingsArgs }>;
type HandleSettingsCommandParams = {
req: DaemonRequest;
logPath: string;
sessionStore: SessionStore;
session: SessionState | undefined;
device: SessionState['device'];
parsed: ParsedSettingsRequest;
inspectFacts?: InspectDeviceRuntimeFacts;
bindDevice?: BindDeviceRuntime;
};
export function parseSettingsArgs(
req: DaemonRequest,
): { ok: true; parsed: ParsedSettingsRequest } | DaemonFailureResponse {
const setting = req.positionals?.[0]?.toLowerCase();
const state = req.positionals?.[1]?.toLowerCase();
const permissionTarget = req.positionals?.[2]?.toLowerCase();
if (setting === 'clear-app-state') {
const appBundleId = state === 'clear' ? req.positionals?.[2] : req.positionals?.[1];
return {
ok: true,
parsed: {
leg: 'write',
args: {
setting,
state: 'clear',
appBundleId,
},
},
};
}
const plan = resolveSettingsRuntimePlan(req.positionals);
if (plan.kind === 'read') {
return { ok: true, parsed: { leg: 'read', setting: plan.setting } };
}
if (
!setting ||
!state ||
(setting === 'permission' && !permissionTarget) ||
(setting === 'location' &&
state === 'set' &&
(!req.positionals?.[2] || !req.positionals?.[3])) ||
(setting === 'reset-keychain' && req.positionals?.[2] !== undefined)
) {
return errorResponse('INVALID_ARGS', SETTINGS_INVALID_ARGS_MESSAGE);
}
// A text size that is not on the ladder is refused here, ahead of admission and of any device
// call: `simctl` answers an unknown category with exit 0, so a write that reached the tool with
// it would have reported success while changing nothing. The refusal carries the whole ladder.
let validatedState = state;
if (setting === 'text-size') {
const category = readTextSizeCategory(state);
if (category === undefined) {
return errorResponse('INVALID_ARGS', invalidTextSizeMessage(state));
}
validatedState = category;
}
return {
ok: true,
parsed: {
leg: 'write',
args: {
setting,
state: validatedState,
permissionTarget,
permissionMode: req.positionals?.[3],
latitude: req.positionals?.[2],
longitude: req.positionals?.[3],
},
},
};
}
/**
* The owner-facing options for one mutation. `permission` and `location set` are the two settings
* whose payload is not just `(setting, state)`; everything else sends none. Coordinate typing
* happens here rather than in the owner: `readLocationCoordinate` is input validation, and it
* throws the same `INVALID_ARGS` the retired dispatcher threw from the same point in the
* sequence — after admission, after the frame expiry and the diagnostic, immediately before the
* device call.
*/
function buildSettingOptions(parsed: ParsedSettingsArgs): SettingOptions | undefined {
if (parsed.setting === 'permission') {
return { permissionTarget: parsed.permissionTarget, permissionMode: parsed.permissionMode };
}
if (parsed.setting === 'location' && parsed.state === 'set') {
return {
latitude: readLocationCoordinate(parsed.latitude, 'latitude'),
longitude: readLocationCoordinate(parsed.longitude, 'longitude'),
};
}
return undefined;
}
/** The `settings_apply` payload the retired dispatcher emitted, kept byte-for-byte. */
function settingsDiagnosticData(
parsed: ParsedSettingsArgs,
appBundleId: string | undefined,
platform: string,
): Record<string, unknown> {
const { setting, state } = parsed;
if (setting === 'clear-app-state') {
return { setting: 'clear-app-state', state: 'clear', appBundleId, platform };
}
if (setting === 'location' && state === 'set') {
return { setting, state, latitude: parsed.latitude, longitude: parsed.longitude, platform };
}
if (setting === 'permission') {
return {
setting,
state,
permissionTarget: parsed.permissionTarget,
permissionMode: parsed.permissionMode,
platform,
};
}
return { setting, state, appBundleId, platform };
}
function readResultMessage(result: Record<string, unknown>): string | undefined {
return typeof result.message === 'string' && result.message.length > 0
? result.message
: undefined;
}
/**
* The ONE place a bound `settings` executes (R58). The owner answers with its own payload or
* nothing; either way the response carries the requested `setting`/`state` and a message the
* owner may override, exactly as the retired leaf composed it.
*/
async function executeSetSetting(
runtime: BoundDeviceRuntime<typeof settingsRuntimeUse>,
input: SetSettingInput,
fallbackMessage: string,
): Promise<Record<string, unknown>> {
const { setting, state } = input;
const result = await runtime.operations.setSetting(input);
return result && typeof result === 'object'
? withSuccessText({ setting, state, ...result }, readResultMessage(result) ?? fallbackMessage)
: { setting, state, ...successText(fallbackMessage) };
}
export async function handleSettingsCommand(
params: HandleSettingsCommandParams,
): Promise<DaemonResponse> {
if (params.parsed.leg === 'read') return await executeSettingsRead(params, params.parsed.setting);
return await executeSettingsWrite(params, params.parsed.args);
}
/**
* The ONE place `settings <setting>` reads a device (ADR 0019 §9). It admits the owner's read fact
* rather than its write fact, so a leaf that can change a value it cannot report — or the reverse —
* refuses with its own cell instead of running the wrong leg. Nothing here expires the session ref
* frame or mutates anything: the read is the reason that leg exists.
*/
async function executeSettingsRead(
params: HandleSettingsCommandParams,
setting: ReadableSetting,
): Promise<DaemonResponse> {
const { req, logPath, sessionStore, session, device, inspectFacts, bindDevice } = params;
const refusal = settingsRequestRefusal(device, setting);
if (refusal !== undefined) return refusal;
const admission = await admitRuntimeUse({
command: `settings ${setting}`,
device,
use: settingReadUse,
inspectFacts,
bindDevice,
readiness: !session,
});
if (admission.type === 'response') return admission.response;
emitDiagnostic({
level: 'debug',
phase: 'settings_read',
data: { setting, platform: device.platform },
});
const context = contextFromFlags(
logPath,
req.flags,
session?.appBundleId,
session?.trace?.outPath,
);
const payload = await admission.runtime.operations.readSetting({
setting,
execution: runtimeExecutionFromContext(context),
});
const data = {
...payload,
...successText(describeSettingRead(payload)),
};
recordIfSession(sessionStore, session, req, data);
return { ok: true, data };
}
async function executeSettingsWrite(
params: HandleSettingsCommandParams,
parsed: ParsedSettingsArgs,
): Promise<DaemonResponse> {
const { req, logPath, sessionStore, session, device, inspectFacts, bindDevice } = params;
const { setting, state } = parsed;
const refusal = settingsRequestRefusal(device, setting);
if (refusal !== undefined) return refusal;
const appRefusal = settingsAppRefusal(device, req, setting, state);
if (appRefusal !== undefined) return appRefusal;
const admission = await admitRuntimeUse({
command: 'settings',
device,
use: settingsRuntimeUse,
inspectFacts,
bindDevice,
readiness: !session,
});
const appBundleId = settingsWriteAppId(req, parsed, session, device);
if (admission.type === 'response') return admission.response;
const writeRefusal = settingsWriteRefusal(parsed, appBundleId);
if (writeRefusal !== undefined) return writeRefusal;
// ADR 0014 side-effect seam: a settings mutation changes device state; expire the frame before
// the bound call (settings is always classified may-invalidate). It runs here, ahead of the
// diagnostic and the coordinate typing, because that is where the retired daemon route expired
// it — a request that later fails on a bad coordinate expired the frame then and expires it now.
if (session) expireRefFrame(session);
emitDiagnostic({
level: 'debug',
phase: 'settings_apply',
data: settingsDiagnosticData(parsed, appBundleId, device.platform),
});
const data = await executeSetSetting(
admission.runtime,
settingsWriteInput(
parsed,
appBundleId,
contextFromFlags(logPath, req.flags, appBundleId, session?.trace?.outPath),
),
describeSettingWrite(setting, state, appBundleId),
);
recordIfSession(sessionStore, session, req, data);
return { ok: true, data };
}
/**
* The refusals both legs make before a device is touched, so one target answers a read and a write of
* the same setting with the same code. They key on the requested setting, which an operation fact
* cannot express: macOS serves `settings` and still refuses `wifi`, and the Apple ladder needs a
* narrower leaf than the simulator-family write fact admits. Both are daemon-side stops ahead of
* admission — the mutation leg expires the session ref frame as soon as it is admitted, and a request
* this surface refuses must not expire it.
*/
function settingsRequestRefusal(
device: SessionState['device'],
setting: string,
): DaemonResponse | undefined {
if (isMacOs(device) && !isMacOsSettingSupported(setting)) {
return errorResponse('INVALID_ARGS', getUnsupportedMacOsSettingMessage(setting));
}
// The Apple write fact is one claim covering every simulator, while the content-size ladder is
// confined to iPhone and iPad simulators. The refusal has to land before admission, because a
// settings mutation expires the session ref frame before the bound call, and a request that never
// reached a device must not take a live frame down with it.
if (
setting === 'text-size' &&
isApplePlatform(device.platform) &&
!isHandheldAppleSimulator(device)
) {
return errorResponse(
'UNSUPPORTED_OPERATION',
APPLE_TEXT_SIZE_LEAF_REFUSAL.message,
{
deviceKind: device.kind,
appleOs: resolveDeviceAppleOs(device),
reason: APPLE_TEXT_SIZE_LEAF_REFUSAL.reason,
},
{ hint: APPLE_TEXT_SIZE_LEAF_REFUSAL.hint },
);
}
return undefined;
}
/**
* The app a request names outside its positionals: the `app` of the request input, which the CLI
* writes from `--app` and the client and MCP surfaces write from their `app` option. Read as a
* non-empty string or nothing, because an empty `--app` was never a request to grant anything.
*/
function settingsRequestApp(req: DaemonRequest): string | undefined {
const app = req.input?.app;
if (typeof app !== 'string') return undefined;
const trimmed = app.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/**
* The device fact the app-scope table is keyed on, answered with the kernel's own predicates so the
* legacy Apple leaf platforms settle exactly where the predicates do.
*/
function settingsTargetFamily(device: SessionState['device']): SettingsTargetFamily {
if (isMacOs(device)) return 'macos-host';
return isApplePlatform(device.platform) ? 'apple' : 'mobile';
}
/**
* The refusal for naming an app on a mutation whose target consumes none: Android's on/off `location`
* writes the global `location_mode`, and a macOS permission is a TCC grant to the host process. It
* runs before admission because a request this surface refuses must not bind a runtime, and it stays
* silent for `unknown`, where the owner's own fact answers the setting rather than the app.
*/
function settingsAppRefusal(
device: SessionState['device'],
req: DaemonRequest,
setting: string,
state: string,
): DaemonResponse | undefined {
const app = settingsRequestApp(req);
if (app === undefined) return undefined;
if (settingsAppScope(settingsTargetFamily(device), setting, state) !== 'device-level') {
return undefined;
}
const refusal = settingsAppNotConsumedRefusal(setting, state, app);
return errorResponse(refusal.code, refusal.message, refusal.details, { hint: refusal.hint });
}
/**
* The app a mutation targets: the explicit positional wins, then the request's explicit `app`, then
* the Maestro adapter's daemon-internal `settingsAppBundleId`, which aims one request at another app
* than the session carries, and last the app the session is bound to. The request's `app` is only
* consumed where the scope table says the mutation can carry one; elsewhere it was already refused or
* belongs to an owner that never reads it.
*/
function settingsWriteAppId(
req: DaemonRequest,
parsed: ParsedSettingsArgs,
session: SessionState | undefined,
device: SessionState['device'],
): string | undefined {
const explicitApp =
settingsAppScope(settingsTargetFamily(device), parsed.setting, parsed.state) === 'app-scoped'
? settingsRequestApp(req)
: undefined;
return (
parsed.appBundleId ?? explicitApp ?? req.internal?.settingsAppBundleId ?? session?.appBundleId
);
}
/** The refusal a mutation adds on top of the shared one: an app the session may not carry. */
function settingsWriteRefusal(
parsed: ParsedSettingsArgs,
appBundleId: string | undefined,
): DaemonResponse | undefined {
if (parsed.setting === 'clear-app-state' && !appBundleId) {
return errorResponse(
'INVALID_ARGS',
'settings clear-app-state requires an app id when no app is bound to the session',
sessionAppRequiredDetails(),
);
}
return undefined;
}
/** The owner-facing input for one mutation: the named setting and state, plus only the extras it carries. */
function settingsWriteInput(
parsed: ParsedSettingsArgs,
appBundleId: string | undefined,
context: Parameters<typeof runtimeExecutionFromContext>[0],
): SetSettingInput {
const options = buildSettingOptions(parsed);
return {
setting: parsed.setting,
state: parsed.state,
...(appBundleId === undefined ? {} : { appBundleId }),
...(options === undefined ? {} : { options }),
execution: runtimeExecutionFromContext(context),
};
}