Repository navigation
Expand file tree
/
Copy pathconnection.ts
More file actions
509 lines (480 loc) · 17.1 KB
/
Copy pathconnection.ts
File metadata and controls
509 lines (480 loc) · 17.1 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
import type {
CloudArtifact,
CloudProviderSessionResult,
} from '@agent-device/contracts/observability';
import { resolveDaemonPaths } from '../../daemon-resolution.ts';
import { resolveRemoteConfigProfile } from '../../remote/remote-config.ts';
import {
readActiveConnectionState,
buildRemoteConnectionRequestMetadata,
mergeRemoteConnectionRequestMetadata,
readRemoteConnectionState,
remoteConnectionLeaseIdentityMatches,
removeRemoteConnectionState,
connectionPlatformMatchesSelection,
narrowConnectionPlatform,
writeRemoteConnectionState,
type RemoteConnectionState,
type RemoteConnectionRequestMetadata,
} from '../../remote/remote-connection-state.ts';
import { AppError } from '@agent-device/kernel/errors';
import {
connectProviderNamesForError,
connectionProviderCapabilities,
isConnectProviderName,
type ConnectProvider,
} from '../connection/provider-policy.ts';
import {
resolveConnectProviderProfile,
verifyResolvedConnectProvider,
} from '../connection/connect-provider-adapters.ts';
import {
hasDeferredMetroConfig,
releaseRemoteConnectionLease,
releasePreviousLease,
resolveRequestedLeaseBackend,
stopMetroCleanup,
stopReactDevtoolsCleanup,
} from './connection-runtime.ts';
import { writeCommandOutput } from './shared.ts';
import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell';
import type { LeaseBackend } from '@agent-device/kernel/contracts';
import type { CliFlags } from '@agent-device/contracts/command';
import type { ClientCommandHandler } from './router-types.ts';
import { resolveConnectContext, type ConnectContext } from './connection-context.ts';
import {
buildLeasePreparationNotice,
presentConnectReadiness,
renderConnectSuccess,
scopeCommand,
serializeConnectionState,
type PreviousLeaseReleaseNotice,
type RuntimePreparationNotice,
} from './connection-presentation.ts';
export const connectCommand: ClientCommandHandler = async ({ positionals, flags, client }) => {
const stateDir = resolveDaemonPaths(flags.stateDir).baseDir;
const provider = readConnectProvider(positionals);
assertConnectProviderUsage(provider, flags);
const resolved = await resolveConnectProviderProfile({ provider, flags, stateDir });
const connectFlags = resolved.flags;
const connectionMetadata = readRemoteConfigConnectionMetadata(resolved.remoteConfigPath);
const scope = readRequiredConnectScope(connectFlags, connectionMetadata);
const context = resolveConnectContext({
stateDir,
flags: connectFlags,
remoteConfigPath: resolved.remoteConfigPath,
});
assertCompatibleConnectionOrForce(context.previous, {
flags: connectFlags,
session: context.session,
remoteConfigPath: resolved.remoteConfigPath,
remoteConfigHash: context.remoteConfigHash,
desiredLeaseBackend: resolveRequestedLeaseBackend(connectFlags),
connection: connectionMetadata,
daemon: context.daemon,
});
const verification = await verifyResolvedConnectProvider(resolved);
const state = buildConnectedState({
flags: connectFlags,
scope,
connectionMetadata,
context,
remoteConfigPath: resolved.remoteConfigPath,
});
writeRemoteConnectionState({ stateDir, state });
const previousLeaseNotice = await cleanupForcedPreviousConnection(
client,
stateDir,
connectFlags,
context.previous,
state.daemon?.baseUrl,
);
const runtimePreparation = buildRuntimePreparationNotice(connectFlags, state);
const readiness = presentConnectReadiness(state, verification);
await writeCommandOutput(
connectFlags,
serializeConnectionState({ state, runtimePreparation, readiness, previousLeaseNotice }),
() => renderConnectSuccess({ state, runtimePreparation, readiness, previousLeaseNotice }),
);
return true;
};
function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags: CliFlags): void {
if (!provider || !flags.remoteConfig) return;
throw new AppError(
'INVALID_ARGS',
'connect provider positional and --remote-config are mutually exclusive.',
);
}
function readRequiredConnectScope(
flags: CliFlags,
connectionMetadata: RemoteConnectionRequestMetadata | undefined,
): { tenant: string; runId: string } {
if (!flags.tenant) {
throw new AppError(
'INVALID_ARGS',
'connect requires tenant in remote config or via --tenant <id>.',
);
}
if (!flags.runId) {
throw new AppError(
'INVALID_ARGS',
'connect requires runId in remote config or via --run-id <id>.',
);
}
if (
!flags.daemonBaseUrl &&
connectionProviderCapabilities(connectionMetadata?.leaseProvider).requiresRemoteDaemon
) {
throw new AppError(
'INVALID_ARGS',
'connect requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.',
);
}
return { tenant: flags.tenant, runId: flags.runId };
}
function assertCompatibleConnectionOrForce(
previous: RemoteConnectionState | null,
options: Parameters<typeof isCompatibleConnection>[1],
): void {
if (!previous || isCompatibleConnection(previous, options)) return;
if (options.flags.force) return;
throw new AppError(
'INVALID_ARGS',
'A different remote connection is already active for this session. Re-run connect with --force to replace it.',
{ session: options.session, remoteConfig: previous.remoteConfigPath },
);
}
function buildConnectedState(options: {
flags: CliFlags;
scope: { tenant: string; runId: string };
connectionMetadata?: RemoteConnectionRequestMetadata;
context: ConnectContext;
remoteConfigPath: string;
}): RemoteConnectionState {
const { flags, scope, connectionMetadata, context, remoteConfigPath } = options;
const previous = shouldReusePreviousConnectionState(flags, context.previous)
? context.previous
: null;
const now = new Date().toISOString();
const leaseBinding = buildConnectionLeaseBinding(flags, previous, connectionMetadata);
const runtimeBinding = buildConnectionRuntimeBinding(flags, previous, now, leaseBinding);
return {
version: 1,
session: context.session,
remoteConfigPath,
remoteConfigHash: context.remoteConfigHash,
daemon: context.daemon,
tenant: scope.tenant,
runId: scope.runId,
...leaseBinding,
...runtimeBinding,
updatedAt: now,
};
}
function buildConnectionLeaseBinding(
flags: CliFlags,
previous: RemoteConnectionState | null,
connectionMetadata: RemoteConnectionRequestMetadata | undefined,
): Pick<
RemoteConnectionState,
'clientId' | 'deviceKey' | 'leaseBackend' | 'leaseId' | 'leaseProvider'
> {
const connection = mergeRemoteConnectionRequestMetadata(connectionMetadata ?? {}, previous ?? {});
return {
leaseId: previous?.leaseId,
leaseBackend: previous?.leaseBackend ?? resolveRequestedLeaseBackend(flags),
...connection,
deviceKey: previous?.deviceKey ?? connection.deviceKey,
};
}
/**
* Writes what a reused connection is bound to on the platform axis.
*
* `--platform apple` on a connection whose backend rents iOS instances is the family being named
* again, not a request to widen the record back to the family: once a lease is bound the leaf is the
* truth, and a record that loses it lets the next command ask for any Apple leaf and be served on
* this one (#2962). The lease binding is asked first because the backend is what decides a family.
*/
function buildConnectionRuntimeBinding(
flags: CliFlags,
previous: RemoteConnectionState | null,
now: string,
leaseBinding: Pick<RemoteConnectionState, 'leaseBackend'>,
): Pick<RemoteConnectionState, 'connectedAt' | 'metro' | 'platform' | 'runtime' | 'target'> {
const platform = narrowConnectionPlatform({
leaseBackend: leaseBinding.leaseBackend,
recordedPlatform: previous?.platform,
requestedPlatform: flags.platform,
});
return {
platform: platform.ok ? platform.platform : flags.platform,
target: flags.target ?? previous?.target,
runtime: previous?.runtime,
metro: previous?.metro,
connectedAt: previous?.connectedAt ?? now,
};
}
function shouldReusePreviousConnectionState(
flags: CliFlags,
previous: RemoteConnectionState | null,
): previous is RemoteConnectionState {
return Boolean(previous && !flags.force);
}
async function cleanupForcedPreviousConnection(
client: Parameters<ClientCommandHandler>[0]['client'],
stateDir: string,
flags: CliFlags,
previous: RemoteConnectionState | null,
nextDaemonBaseUrl: string | undefined,
): Promise<PreviousLeaseReleaseNotice | undefined> {
if (!previous || !flags.force) return undefined;
await stopMetroCleanup(previous.metro);
await stopReactDevtoolsCleanup({ stateDir, state: previous });
return await releasePreviousLease(client, previous, {
nextDaemonBaseUrl,
ambientDaemonAuthToken: flags.daemonAuthToken,
cwd: process.cwd(),
env: process.env,
});
}
function readRemoteConfigConnectionMetadata(
remoteConfigPath: string,
): RemoteConnectionRequestMetadata | undefined {
const profile = resolveRemoteConfigProfile({
configPath: remoteConfigPath,
cwd: process.cwd(),
env: process.env,
}).profile;
return buildRemoteConnectionRequestMetadata(profile);
}
export const disconnectCommand: ClientCommandHandler = async ({ flags, client }) => {
const { session, stateDir, state } = readRequestedConnectionState(flags);
if (!state) {
await writeNoRemoteConnectionOutput(flags, session);
return true;
}
const connectedSession = state.session;
let providerData: CloudProviderSessionResult | undefined;
if (state.leaseId || state.runtime || state.metro) {
try {
providerData = (
await client.sessions.close({ session: connectedSession, shutdown: flags.shutdown })
).provider;
} catch {
// Disconnect is idempotent; the session may already be closed.
}
}
await stopMetroCleanup(state.metro);
await stopReactDevtoolsCleanup({ stateDir, state });
let released = false;
if (state.leaseId) {
try {
const release = await releaseRemoteConnectionLease(client, state, flags.daemonAuthToken);
released = release.released;
providerData ??= release.provider;
} catch {
// Bridges may release on close or be unreachable; local state still needs cleanup.
}
}
removeRemoteConnectionState({ stateDir, session: connectedSession });
await writeCommandOutput(
flags,
{
connected: false,
session: connectedSession,
released,
...(providerData ? { provider: providerData } : {}),
},
() => renderDisconnectOutput(connectedSession, providerData),
);
return true;
};
export const connectionCommand: ClientCommandHandler = async ({ positionals, flags }) => {
if (positionals[0] !== 'status') {
throw new AppError('INVALID_ARGS', 'connection accepts only: status');
}
const { session, state } = readRequestedConnectionState(flags);
if (!state) {
await writeNoRemoteConnectionOutput(flags, session);
return true;
}
const leasePreparation = buildLeasePreparationNotice(state);
const runtimePreparation = buildRuntimePreparationNoticeFromState(state);
await writeCommandOutput(flags, serializeConnectionState({ state, runtimePreparation }), () =>
[
`Configured remote session "${state.session}".`,
`tenant=${state.tenant} runId=${state.runId} leaseId=${state.leaseId ?? 'pending'} backend=${state.leaseBackend ?? 'pending'}`,
`remoteConfig=${state.remoteConfigPath}`,
state.runtime ? 'metro=prepared' : 'metro=not-prepared',
leasePreparation?.message,
runtimePreparation?.message,
]
.filter((line): line is string => Boolean(line))
.join('\n'),
);
return true;
};
function renderDisconnectOutput(
session: string,
providerData: CloudProviderSessionResult | undefined,
): string {
return [
`Disconnected remote session "${session}".`,
...formatProviderReleaseWarnings(providerData),
...formatReadyArtifactLinks(providerData?.cloudArtifacts?.cloudArtifacts),
].join('\n');
}
function formatProviderReleaseWarnings(
providerData: CloudProviderSessionResult | undefined,
): string[] {
const warnings = Array.isArray(providerData?.warnings) ? providerData.warnings : [];
return warnings.flatMap((warning) => {
const formatted = formatProviderReleaseWarning(warning);
return formatted ? [formatted] : [];
});
}
function formatProviderReleaseWarning(warning: unknown): string | undefined {
if (!warning || typeof warning !== 'object') return undefined;
const entry = warning as { code?: unknown; message?: unknown };
if (typeof entry.message !== 'string' || entry.message.length === 0) return undefined;
const code = typeof entry.code === 'string' && entry.code.length > 0 ? ` (${entry.code})` : '';
return `Provider release warning${code}: ${entry.message}`;
}
function formatReadyArtifactLinks(artifacts: CloudArtifact[] | undefined): string[] {
return (artifacts ?? [])
.filter((artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url)
.slice(0, 3)
.map((artifact) => `${artifact.name}: ${artifact.url}`);
}
function readConnectProvider(positionals: string[]): ConnectProvider | undefined {
const provider = positionals[0];
if (provider === undefined) return undefined;
if (positionals.length > 1) {
throw new AppError('INVALID_ARGS', 'connect accepts at most one provider positional.');
}
if (isConnectProviderName(provider)) {
return provider;
}
throw new AppError(
'INVALID_ARGS',
`Unknown connect provider: ${provider}. Supported providers: ${connectProviderNamesForError()}.`,
);
}
function readRequestedConnectionState(flags: CliFlags): {
session: string;
stateDir: string;
state: RemoteConnectionState | null;
} {
const session = flags.session ?? 'default';
const stateDir = resolveDaemonPaths(flags.stateDir).baseDir;
return {
session,
stateDir,
state:
readRemoteConnectionState({ stateDir, session }) ??
(flags.session ? null : readActiveConnectionState({ stateDir })),
};
}
async function writeNoRemoteConnectionOutput(flags: CliFlags, session: string): Promise<void> {
await writeCommandOutput(
flags,
{ connected: false, session },
() => `No remote connection for "${session}".`,
);
}
function isCompatibleConnection(
state: RemoteConnectionState,
options: {
flags: CliFlags;
session: string;
remoteConfigPath: string;
remoteConfigHash: string;
desiredLeaseBackend?: LeaseBackend;
connection?: RemoteConnectionRequestMetadata;
daemon: RemoteConnectionState['daemon'];
},
): boolean {
return (
requiredConnectionFieldsMatch(state, options) &&
optionalConnectionFieldsMatch(state, options) &&
isSameDaemonState(state.daemon, options.daemon)
);
}
function requiredConnectionFieldsMatch(
state: RemoteConnectionState,
options: Parameters<typeof isCompatibleConnection>[1],
): boolean {
return [
[state.remoteConfigPath, options.remoteConfigPath],
[state.remoteConfigHash, options.remoteConfigHash],
[state.session, options.session],
[state.tenant, options.flags.tenant],
[state.runId, options.flags.runId],
].every(([left, right]) => left === right);
}
function optionalConnectionFieldsMatch(
state: RemoteConnectionState,
options: Parameters<typeof isCompatibleConnection>[1],
): boolean {
if (!connectionPlatformMatchesSelection(state, options.flags.platform)) return false;
const fieldsMatch = [
[state.leaseBackend, options.desiredLeaseBackend],
[state.target, options.flags.target],
].every(([left, right]) => right === undefined || left === right);
return fieldsMatch && remoteConnectionLeaseIdentityMatches(state, options.connection);
}
function isSameDaemonState(
a: RemoteConnectionState['daemon'],
b: RemoteConnectionState['daemon'],
): boolean {
return (['baseUrl', 'transport', 'serverMode'] as const).every(
(key) => (a?.[key] ?? undefined) === (b?.[key] ?? undefined),
);
}
function buildRuntimePreparationNotice(
flags: CliFlags,
state: RemoteConnectionState,
): RuntimePreparationNotice | undefined {
if (state.runtime) return undefined;
if (!hasDeferredMetroConfig(flags) && !remoteConfigHasMetroSettings(state.remoteConfigPath)) {
return undefined;
}
return buildDeferredRuntimeNotice(state);
}
function buildRuntimePreparationNoticeFromState(
state: RemoteConnectionState,
): RuntimePreparationNotice | undefined {
if (state.runtime || !remoteConfigHasMetroSettings(state.remoteConfigPath)) return undefined;
return buildDeferredRuntimeNotice(state);
}
function buildDeferredRuntimeNotice(state: RemoteConnectionState): RuntimePreparationNotice {
const nextStep = scopeCommand(
state,
`agent-device metro prepare --remote-config ${shellQuoteIfNeeded(state.remoteConfigPath)}`,
);
return {
status: 'deferred',
nextStep,
message:
`Metro runtime is not prepared yet; it will be prepared automatically on first open, ` +
`or run "${nextStep}" to inspect it before launch.`,
};
}
function remoteConfigHasMetroSettings(remoteConfigPath: string): boolean {
try {
const remoteConfig = resolveRemoteConfigProfile({
configPath: remoteConfigPath,
cwd: process.cwd(),
env: process.env,
});
const profile = remoteConfig.profile;
return Boolean(
profile.metroPublicBaseUrl ||
profile.metroProxyBaseUrl ||
profile.metroProjectRoot ||
profile.metroKind,
);
} catch {
return false;
}
}