Repository navigation
Expand file tree
/
Copy pathclient-normalizers.ts
More file actions
470 lines (440 loc) · 15.9 KB
/
Copy pathclient-normalizers.ts
File metadata and controls
470 lines (440 loc) · 15.9 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
import type { DaemonWireRequest, InternalRequestOptions } from '@agent-device/contracts/command';
import type {
LaunchConfirmation,
LaunchConfirmationAbsent,
LaunchConfirmationOutcome,
LaunchConfirmationProbeFailure,
LaunchConfirmationUnansweredReason,
} from '@agent-device/contracts/application-lifecycle-runtime';
import type {
AgentDeviceDevice,
AgentDeviceSession,
AgentDeviceSessionDevice,
AppDeployResult,
AppInstallFromSourceResult,
MaterializationReleaseResult,
StartupPerfSample,
DeviceSelectionMetadata,
} from '@agent-device/contracts/client';
import type { TargetShutdownResult } from '@agent-device/contracts/device';
import {
isAppleOs,
isApplePlatform,
isPublicPlatform,
isSerialAddressablePlatform,
type AppleOS,
} from '@agent-device/kernel/device';
import { isSessionRuntimePlatform, type SessionRuntimeHints } from '@agent-device/kernel/contracts';
import { AppError, type DaemonError } from '@agent-device/kernel/errors';
import { sanitizeErrorCause } from '@agent-device/kernel/redaction';
import type { SnapshotNode } from '@agent-device/kernel/snapshot';
import {
leaseScopeFromOptions,
leaseScopeToRequestMeta,
} from '@agent-device/contracts/lease-scope';
import {
asRecord,
isRecord,
readDeviceTarget,
readNullableString,
readOptionalString,
readRequiredDeviceKind,
readRequiredNumber,
readRequiredPlatform,
readRequiredString,
stripUndefined,
} from '@agent-device/kernel/record';
import { buildAppIdentifiers, buildDeviceIdentifiers } from './client-identifiers.ts';
export { readOptionalString, readRequiredString } from '@agent-device/kernel/record';
const DEFAULT_SESSION_NAME = 'default';
export function normalizeDeployResult(
data: Record<string, unknown>,
session?: string,
): AppDeployResult {
const bundleId = readOptionalString(data, 'bundleId');
const pkg = readOptionalString(data, 'package');
return {
app: readRequiredString(data, 'app'),
appPath: readRequiredString(data, 'appPath'),
platform: readRequiredPlatform(data, 'platform'),
appId: bundleId ?? pkg,
bundleId,
package: pkg,
identifiers: buildAppIdentifiers({ session, bundleId, packageName: pkg }),
};
}
export function normalizeInstallFromSourceResult(
data: Record<string, unknown>,
session?: string,
): AppInstallFromSourceResult {
const bundleId = readOptionalString(data, 'bundleId');
const packageName = readOptionalString(data, 'packageName');
const appId = bundleId ?? packageName ?? readOptionalString(data, 'appId');
const launchTarget = readOptionalString(data, 'launchTarget') ?? packageName ?? bundleId ?? appId;
if (!launchTarget) {
throw new AppError('COMMAND_FAILED', 'Daemon response is missing "launchTarget".', {
response: data,
});
}
return {
appName: readOptionalString(data, 'appName'),
appId,
bundleId,
packageName,
launchTarget,
installablePath: readOptionalString(data, 'installablePath'),
archivePath: readOptionalString(data, 'archivePath'),
materializationId: readOptionalString(data, 'materializationId'),
materializationExpiresAt: readOptionalString(data, 'materializationExpiresAt'),
identifiers: buildAppIdentifiers({ session, bundleId, packageName, appId }),
};
}
export function normalizeMaterializationReleaseResult(
data: Record<string, unknown>,
): MaterializationReleaseResult {
return {
released: data.released === true,
materializationId: readRequiredString(data, 'materializationId'),
identifiers: {},
};
}
export function normalizeDevice(value: unknown): AgentDeviceDevice {
const { record, platform, id, name, target } = readClientDeviceIdentity(value, 'name');
const appleOs = readAppleOs(record);
return {
platform,
target,
kind: readRequiredDeviceKind(record, 'kind'),
id,
name,
booted: typeof record.booted === 'boolean' ? record.booted : undefined,
// Additive Apple-OS discriminant; Apple platforms only — gate on the platform so
// a non-Apple record with a stray appleOs value is not preserved.
...(isApplePlatform(platform) && appleOs ? { appleOs } : {}),
...readDeviceDescription(record),
identifiers: buildDeviceIdentifiers(platform, id, name),
...readClaimedBy(record),
...buildClientDevicePlatformFields(platform, id),
};
}
/** Reads the optional presentation-only hardware model and OS version of a listed device. */
function readDeviceDescription(
record: Record<string, unknown>,
): Pick<AgentDeviceDevice, 'model' | 'osVersion'> {
const model = readOptionalString(record, 'model');
const osVersion = readOptionalString(record, 'osVersion');
return {
...(model ? { model } : {}),
...(osVersion ? { osVersion } : {}),
};
}
function readClaimedBy(record: Record<string, unknown>): Pick<AgentDeviceDevice, 'claimedBy'> {
const value = record.claimedBy;
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
const claimedBy = value as Record<string, unknown>;
const session = claimedBy.session;
const workspace = claimedBy.workspace;
if (typeof session !== 'string' || typeof workspace !== 'string') return {};
return { claimedBy: { session, workspace } };
}
export function normalizeSession(value: unknown): AgentDeviceSession {
const { record, platform, id, name, target } = readClientDeviceIdentity(value, 'name');
const deviceName = readRequiredString(record, 'device');
const appleOs = readAppleOs(record);
const identifiers = {
session: name,
...buildDeviceIdentifiers(platform, id, deviceName),
};
return {
name,
address: readOptionalString(record, 'address'),
createdAt: readRequiredNumber(record, 'createdAt'),
sessionStateDir: readOptionalString(record, 'sessionStateDir'),
runnerLogPath: readOptionalString(record, 'runnerLogPath'),
device: {
platform,
target,
id,
name: deviceName,
// Additive Apple-OS discriminant; present only when the daemon emits it (Apple devices).
...(appleOs ? { appleOs } : {}),
identifiers,
...buildClientDevicePlatformFields(platform, id, {
simulatorSetPath: readNullableString(record, 'ios_simulator_device_set'),
}),
},
identifiers,
};
}
function readAppleOs(record: Record<string, unknown>): AppleOS | undefined {
const value = record.appleOs;
return isAppleOs(value) ? value : undefined;
}
function readClientDeviceIdentity(value: unknown, nameField: string) {
const record = asRecord(value);
return {
record,
platform: readRequiredPlatform(record, 'platform'),
id: readRequiredString(record, 'id'),
name: readRequiredString(record, nameField),
target: readDeviceTarget(record, 'target'),
};
}
function buildClientDevicePlatformFields(
platform: AgentDeviceDevice['platform'],
id: string,
options: { simulatorSetPath?: string | null; serial?: string } = {},
): Pick<AgentDeviceSessionDevice, 'ios' | 'android' | 'harmonyos' | 'vega'> {
if (platform === 'ios') {
return {
ios: {
udid: id,
...(options.simulatorSetPath !== undefined
? { simulatorSetPath: options.simulatorSetPath }
: {}),
},
};
}
if (!isSerialAddressablePlatform(platform)) return {};
const serial = options.serial ?? id;
if (platform === 'android') return { android: { serial } };
if (platform === 'harmonyos') return { harmonyos: { serial } };
return { vega: { serial } };
}
export function normalizeRuntimeHints(value: unknown): SessionRuntimeHints | undefined {
if (!isRecord(value)) return undefined;
const platform = value.platform;
const metroHost = readOptionalString(value, 'metroHost');
const metroPort = typeof value.metroPort === 'number' ? value.metroPort : undefined;
const bundleUrl = readOptionalString(value, 'bundleUrl');
const launchUrl = readOptionalString(value, 'launchUrl');
return {
platform: isSessionRuntimePlatform(platform) ? platform : undefined,
metroHost,
metroPort,
bundleUrl,
launchUrl,
};
}
export function normalizeOpenDevice(
value: Record<string, unknown>,
): AgentDeviceSessionDevice | undefined {
const platform = value.platform;
const id = readOptionalString(value, 'id');
const name = readOptionalString(value, 'device');
if (!isPublicPlatform(platform) || !id || !name) {
return undefined;
}
const target = readDeviceTarget(value, 'target');
const serial = isSerialAddressablePlatform(platform)
? (readOptionalString(value, 'serial') ?? id)
: undefined;
const identifiers = {
...buildDeviceIdentifiers(platform, id, name),
...(serial ? { serial } : {}),
};
return {
platform,
target,
id,
name,
identifiers,
...buildClientDevicePlatformFields(
platform,
platform === 'ios' ? (readOptionalString(value, 'device_udid') ?? id) : id,
{
simulatorSetPath: readNullableString(value, 'ios_simulator_device_set'),
serial,
},
),
};
}
const DEVICE_SELECTION_REASONS: readonly DeviceSelectionMetadata['reason'][] = [
'explicit-selector',
'existing-session',
'single-booted-local',
'single-bootable-local',
'single-app-installed-local',
'preferred-local',
'single-provider-device',
];
const DEVICE_SELECTION_SOURCES: readonly DeviceSelectionMetadata['source'][] = [
'session',
'local',
'provider',
];
export function normalizeDeviceSelection(value: unknown): DeviceSelectionMetadata | undefined {
if (!isRecord(value)) return undefined;
const { reason, source, candidateCount, bootOccurred } = value;
if (
!DEVICE_SELECTION_REASONS.includes(reason as DeviceSelectionMetadata['reason']) ||
!DEVICE_SELECTION_SOURCES.includes(source as DeviceSelectionMetadata['source']) ||
typeof candidateCount !== 'number' ||
!Number.isInteger(candidateCount) ||
candidateCount < 0 ||
typeof bootOccurred !== 'boolean'
) {
return undefined;
}
return {
reason: reason as DeviceSelectionMetadata['reason'],
source: source as DeviceSelectionMetadata['source'],
candidateCount,
bootOccurred,
};
}
export function normalizeStartupSample(value: unknown): StartupPerfSample | undefined {
if (!isRecord(value)) return undefined;
if (
typeof value.durationMs !== 'number' ||
typeof value.measuredAt !== 'string' ||
typeof value.method !== 'string'
) {
return undefined;
}
return {
durationMs: value.durationMs,
measuredAt: value.measuredAt,
method: value.method,
appTarget: readOptionalString(value, 'appTarget'),
appBundleId: readOptionalString(value, 'appBundleId'),
};
}
export function normalizeTargetShutdownResult(value: unknown): TargetShutdownResult | undefined {
if (!isRecord(value)) return undefined;
if (
typeof value.success !== 'boolean' ||
typeof value.exitCode !== 'number' ||
typeof value.stdout !== 'string' ||
typeof value.stderr !== 'string'
) {
return undefined;
}
const error = normalizeDaemonError(value.error);
return {
success: value.success,
exitCode: value.exitCode,
stdout: value.stdout,
stderr: value.stderr,
...(error ? { error } : {}),
};
}
/**
* The one normalizer for daemon errors riding inside otherwise-ok results
* (target-shutdown reports, the open --foreground initial-snapshot failure).
* Preserves the FULL shape — hint/details/diagnosticId/logPath plus the
* additive retriable/supportedOn signals — never a code+message truncation,
* so recovery guidance survives to Node/CLI JSON callers.
*/
const DAEMON_ERROR_STRING_FIELDS = ['hint', 'diagnosticId', 'logPath', 'supportedOn'] as const;
function normalizeDaemonError(value: unknown): DaemonError | undefined {
if (!isRecord(value)) return undefined;
if (typeof value.code !== 'string' || typeof value.message !== 'string') return undefined;
const error: DaemonError = { code: value.code, message: value.message };
Object.assign(error, normalizeDaemonErrorCause(value.cause));
for (const field of DAEMON_ERROR_STRING_FIELDS) {
const candidate = value[field];
if (typeof candidate === 'string') error[field] = candidate;
}
if (isRecord(value.details)) error.details = value.details;
if (typeof value.retriable === 'boolean') error.retriable = value.retriable;
return error;
}
function normalizeDaemonErrorCause(value: unknown): Pick<DaemonError, 'cause'> | undefined {
const cause = sanitizeErrorCause(value);
return cause ? { cause } : undefined;
}
/**
* open --foreground composition extras on an ok open response: the initial
* snapshot when the foreground-attach capture succeeded, or the FULL capture
* error (never a code+message truncation) when open succeeded and the
* composed snapshot did not — the session is open and usable either way.
*/
export function normalizeOpenForegroundComposition(data: Record<string, unknown>): {
snapshot?: Record<string, unknown>;
initialSnapshotError?: DaemonError;
} {
const initialSnapshotError = normalizeDaemonError(data.initialSnapshotError);
return {
...(data.snapshot && typeof data.snapshot === 'object'
? { snapshot: data.snapshot as Record<string, unknown> }
: {}),
...(initialSnapshotError ? { initialSnapshotError } : {}),
};
}
/**
* The launch confirmation an open response reports, keyed on the typed outcome. The daemon pairs
* an `unanswered` outcome with its reason, so an outcome or reason it does not recognize is dropped
* rather than guessed, as is a probe step outside the typed set; warnings travel separately and
* still reach the caller. With no outcome, the only report left is the typed probe-failure step.
*/
export function normalizeLaunchConfirmation(
data: Record<string, unknown>,
): LaunchConfirmationOutcome | LaunchConfirmationAbsent {
const outcome = readLaunchConfirmationOutcome(data.launchConfirmation);
if (outcome === 'accepted') return { launchConfirmation: 'accepted' };
if (outcome === 'unanswered') {
const reason = readLaunchConfirmationReason(data.launchConfirmationReason);
return reason ? { launchConfirmation: 'unanswered', launchConfirmationReason: reason } : {};
}
const probeFailure = readLaunchConfirmationProbeFailure(data.launchConfirmationProbeFailure);
return probeFailure ? { launchConfirmationProbeFailure: probeFailure } : {};
}
function readLaunchConfirmationOutcome(value: unknown): LaunchConfirmation | undefined {
switch (value) {
case 'accepted':
case 'unanswered':
return value;
default:
return undefined;
}
}
function readLaunchConfirmationReason(
value: unknown,
): LaunchConfirmationUnansweredReason | undefined {
switch (value) {
case 'alert-unrecognized':
case 'url-owner-unresolved':
return value;
default:
return undefined;
}
}
function readLaunchConfirmationProbeFailure(
value: unknown,
): LaunchConfirmationProbeFailure | undefined {
switch (value) {
case 'alert-read':
case 'alert-accept':
case 'runner':
return value;
default:
return undefined;
}
}
export function readSnapshotNodes(value: unknown): SnapshotNode[] {
// Snapshot nodes are produced by the daemon snapshot pipeline and treated as trusted here.
return Array.isArray(value) ? (value as SnapshotNode[]) : [];
}
export function buildMeta(options: InternalRequestOptions): DaemonWireRequest['meta'] {
const leaseScope = leaseScopeFromOptions(options);
return stripUndefined({
requestId: options.requestId,
cwd: options.cwd,
sessionExplicit: options.session !== undefined,
debug: options.debug,
includeCost: options.cost,
responseLevel: options.responseLevel,
lockPolicy: options.lockPolicy,
lockPlatform: options.lockPlatform,
...leaseScopeToRequestMeta(leaseScope),
sessionIsolation: options.sessionIsolation,
installSource: options.installSource,
retainMaterializedPaths: options.retainMaterializedPaths,
materializedPathRetentionMs: options.materializedPathRetentionMs,
materializationId: options.materializationId,
});
}
export function resolveSessionName(session: string | undefined): string {
return session ?? DEFAULT_SESSION_NAME;
}