Repository navigation
Expand file tree
/
Copy pathcontracts.ts
More file actions
371 lines (330 loc) · 11.6 KB
/
Copy pathcontracts.ts
File metadata and controls
371 lines (330 loc) · 11.6 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
import type { DaemonError } from './errors.ts';
export type { AppErrorCode } from './errors.ts';
export { defaultHintForCode, normalizeError } from './errors.ts';
import type { PlatformSelector } from './device.ts';
const SESSION_RUNTIME_PLATFORMS = ['ios', 'android', 'harmonyos'] as const;
export type SessionRuntimePlatform = (typeof SESSION_RUNTIME_PLATFORMS)[number];
export function isSessionRuntimePlatform(value: unknown): value is SessionRuntimePlatform {
return SESSION_RUNTIME_PLATFORMS.some((platform) => platform === value);
}
export type SessionRuntimeHints = {
platform?: SessionRuntimePlatform;
metroHost?: string;
metroPort?: number;
bundleUrl?: string;
launchUrl?: string;
};
export type DaemonInstallSource =
| {
kind: 'url';
url: string;
headers?: Record<string, string>;
}
| {
kind: 'path';
path: string;
}
| ({
kind: 'github-actions-artifact';
owner: string;
repo: string;
} & (
| {
artifactId: number;
}
| {
runId: number;
artifactName: string;
}
| {
artifactName: string;
}
));
/** Install sources that can be materialized by a local daemon. */
export type LocalInstallSource = Extract<DaemonInstallSource, { kind: 'url' | 'path' }>;
const DAEMON_LOCK_POLICIES = ['reject', 'strip'] as const;
export type DaemonLockPolicy = (typeof DAEMON_LOCK_POLICIES)[number];
const LEASE_BACKENDS = [
'ios-simulator',
'ios-instance',
'android-instance',
'harmonyos-instance',
] as const;
export type LeaseBackend = (typeof LEASE_BACKENDS)[number];
const DAEMON_SERVER_MODES = ['socket', 'http', 'dual'] as const;
export type DaemonServerMode = (typeof DAEMON_SERVER_MODES)[number];
const DAEMON_TRANSPORT_PREFERENCES = ['auto', 'socket', 'http'] as const;
export type DaemonTransportPreference = (typeof DAEMON_TRANSPORT_PREFERENCES)[number];
const SESSION_ISOLATION_MODES = ['none', 'tenant'] as const;
export type SessionIsolationMode = (typeof SESSION_ISOLATION_MODES)[number];
export const NETWORK_INCLUDE_MODES = ['summary', 'headers', 'body', 'all'] as const;
export type NetworkIncludeMode = (typeof NETWORK_INCLUDE_MODES)[number];
// Agent-cost leveled response views (Phase 4). `default` == today's exact wire
// shape (Maestro `.ad` recompare safe); `digest` is a token-cheap view; `full`
// is the richest view (== default until a command surfaces extra detail).
export const RESPONSE_LEVELS = ['digest', 'default', 'full'] as const;
export type ResponseLevel = (typeof RESPONSE_LEVELS)[number];
/**
* Whether a response level changes the wire shape from today's default. Used by
* the client/CLI/MCP rendering boundaries to pass a leveled payload through
* verbatim instead of running it through default-shape formatters.
*/
export function isNonDefaultResponseLevel(level: ResponseLevel | undefined): boolean {
return level !== undefined && level !== 'default';
}
export type DaemonRequestMeta = {
requestId?: string;
debug?: boolean;
includeCost?: boolean;
responseLevel?: ResponseLevel;
cwd?: string;
sessionExplicit?: boolean;
tenantId?: string;
runId?: string;
leaseId?: string;
leaseTtlMs?: number;
leaseBackend?: LeaseBackend;
leaseProvider?: string;
deviceKey?: string;
clientId?: string;
sessionIsolation?: SessionIsolationMode;
uploadedArtifactId?: string;
clientArtifactPaths?: Record<string, string>;
installSource?: DaemonInstallSource;
retainMaterializedPaths?: boolean;
materializedPathRetentionMs?: number;
materializationId?: string;
lockPolicy?: DaemonLockPolicy;
lockPlatform?: PlatformSelector;
requestProgress?: 'replay-test' | 'command';
};
export type DaemonRequest = {
token?: string;
session?: string;
command: string;
positionals: string[];
input?: Record<string, unknown>;
flags?: Record<string, unknown>;
runtime?: SessionRuntimeHints;
meta?: DaemonRequestMeta;
};
export type DaemonArtifactKnownType =
| 'screenshot'
| 'screenshot-diff'
| 'screen-recording'
| 'screen-recording-chunk'
| 'screen-recording-telemetry'
| 'trace-log'
| 'test-artifacts';
export type DaemonArtifactType = DaemonArtifactKnownType | (string & {});
export type DaemonArtifact = {
field: string;
// Optional on the wire: missing metadata is valid, JSON drops undefined, and
// remote/older daemons may omit the field entirely. Producer-owned APIs
// (reserveOutput, trackDownloadableArtifact) keep the required
// `DaemonArtifactType | undefined` form so artifact owners must decide.
artifactType?: DaemonArtifactType;
artifactId?: string;
fileName?: string;
localPath?: string;
path?: string;
};
export type ResponseCost = {
wallClockMs: number;
// Number of real iOS-runner round-trips made while serving the request (the
// `ios_runner_command_send` + `ios_runner_readiness_preflight` diagnostic
// phases). Always present when cost is included; 0 when no runner was hit.
runnerRoundTrips: number;
// Number of UI/accessibility nodes in the response, when the command returns a
// node tree (e.g. snapshot). Absent for commands that produce no nodes, so an
// agent can size a snapshot before re-fetching at a different depth/scope.
nodeCount?: number;
};
export type DaemonResponseData = Record<string, unknown> & {
artifacts?: DaemonArtifact[];
cost?: ResponseCost;
};
export type DaemonResponse =
| {
ok: true;
data?: DaemonResponseData;
}
| {
ok: false;
error: DaemonError;
};
export type DaemonFailureResponse = Extract<DaemonResponse, { ok: false }>;
/**
* The one `DaemonResponse` failure constructor. Declared beside the response type so a
* command-side port that returns — rather than throws — a dispatch failure builds the same
* wire shape as a daemon handler without importing the daemon.
*/
export function errorResponse(
code: string,
message: string,
details?: Record<string, unknown>,
options?: { hint?: string; retriable?: boolean },
): DaemonFailureResponse {
return {
ok: false,
error: {
code,
message,
...(options?.hint ? { hint: options.hint } : {}),
...(options?.retriable === undefined ? {} : { retriable: options.retriable }),
...(details ? { details } : {}),
},
};
}
export const NO_ACTIVE_SESSION_MESSAGE = 'No active session. Run open first.';
/**
* Shared "No active session. Run open first." failure used by handlers that require
* an open session before dispatching.
*/
export function noActiveSessionError(): DaemonFailureResponse {
return errorResponse('SESSION_NOT_FOUND', NO_ACTIVE_SESSION_MESSAGE);
}
export type JsonRpcId = string | number | null;
export type JsonRpcRequestEnvelope<TParams = unknown> = {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: TParams;
};
export { centerOfRect } from './snapshot.ts';
export type { Rect, SnapshotNode } from './snapshot.ts';
type RuntimeSchema<T> = {
parse(input: unknown): T;
};
// Keep the public contracts entrypoint dependency-free. These schemas exist so bridge/cloud
// consumers can validate shared payloads without pulling in an additional runtime library.
function schema<T>(parse: (input: unknown, path: string) => T): RuntimeSchema<T> {
return {
parse(input: unknown): T {
return parse(input, '$');
},
};
}
function fail(path: string, message: string): never {
throw new Error(`${path}: ${message}`);
}
function expectObject(input: unknown, path: string): Record<string, unknown> {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
fail(path, 'Expected an object');
}
return input as Record<string, unknown>;
}
function expectString(input: unknown, path: string): string {
if (typeof input !== 'string') {
fail(path, 'Expected a string');
}
return input;
}
function expectInteger(input: unknown, path: string): number {
if (!Number.isInteger(input)) {
fail(path, 'Expected an integer');
}
return input as number;
}
function expectArray(input: unknown, path: string): unknown[] {
if (!Array.isArray(input)) {
fail(path, 'Expected an array');
}
return input;
}
function optionalString(
record: Record<string, unknown>,
key: string,
path: string,
): string | undefined {
const value = record[key];
return value === undefined ? undefined : expectString(value, `${path}.${key}`);
}
function optionalStringArray(
record: Record<string, unknown>,
key: string,
path: string,
): string[] | undefined {
const value = record[key];
if (value === undefined) return undefined;
const items = expectArray(value, `${path}.${key}`);
return items.map((item, index) => expectString(item, `${path}.${key}[${String(index)}]`));
}
function optionalInteger(
record: Record<string, unknown>,
key: string,
path: string,
): number | undefined {
const value = record[key];
return value === undefined ? undefined : expectInteger(value, `${path}.${key}`);
}
function optionalObject(
record: Record<string, unknown>,
key: string,
path: string,
): Record<string, unknown> | undefined {
const value = record[key];
return value === undefined ? undefined : expectObject(value, `${path}.${key}`);
}
function optionalEnum<T extends string>(
record: Record<string, unknown>,
key: string,
allowed: readonly T[],
path: string,
): T | undefined {
const value = record[key];
if (value === undefined) return undefined;
if (typeof value !== 'string' || !allowed.includes(value as T)) {
fail(`${path}.${key}`, `Expected one of: ${allowed.join(', ')}`);
}
return value as T;
}
export const daemonRuntimeSchema = schema<SessionRuntimeHints>((input, path) => {
const record = expectObject(input, path);
return {
platform: optionalEnum(record, 'platform', SESSION_RUNTIME_PLATFORMS, path),
metroHost: optionalString(record, 'metroHost', path),
metroPort: optionalInteger(record, 'metroPort', path),
bundleUrl: optionalString(record, 'bundleUrl', path),
launchUrl: optionalString(record, 'launchUrl', path),
};
});
function parseJsonRpcId(
record: Record<string, unknown>,
path: string,
): string | number | null | undefined {
const value = record.id;
if (value === undefined || value === null) return value as null | undefined;
if (typeof value !== 'string' && typeof value !== 'number') {
fail(`${path}.id`, 'Expected a string, number, or null');
}
return value;
}
export const jsonRpcRequestSchema = schema<JsonRpcRequestEnvelope>((input, path) => {
const record = expectObject(input, path);
return {
jsonrpc: optionalString(record, 'jsonrpc', path),
id: parseJsonRpcId(record, path),
method: optionalString(record, 'method', path),
params: record.params,
};
});
export type CommandRpcParams = Partial<DaemonRequest>;
// Validates the `params` object of a command JSON-RPC request at the daemon's HTTP
// boundary so attacker-controlled wire input is parsed instead of force-cast. The
// control fields (token/session/command/positionals) are checked here; the richer
// flags/runtime/meta shapes are only confirmed to be objects and validated in depth
// by the session open handler downstream.
export const commandRpcParamsSchema = schema<CommandRpcParams>((input, path) => {
const record = expectObject(input, path);
return {
token: optionalString(record, 'token', path),
session: optionalString(record, 'session', path),
command: optionalString(record, 'command', path),
positionals: optionalStringArray(record, 'positionals', path),
input: optionalObject(record, 'input', path),
flags: optionalObject(record, 'flags', path),
runtime: optionalObject(record, 'runtime', path) as SessionRuntimeHints | undefined,
meta: optionalObject(record, 'meta', path) as DaemonRequestMeta | undefined,
};
});