Repository navigation
Expand file tree
/
Copy pathconnection.ts
More file actions
620 lines (589 loc) · 20.7 KB
/
Copy pathconnection.ts
File metadata and controls
620 lines (589 loc) · 20.7 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
import type { HostEnvironment } from '@agent-device/kernel/source-value';
import type { CloudProviderSessionResult } from '@agent-device/contracts/observability';
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config';
import {
readActiveConnectionState,
requireLeasedConnectionSession,
sessionLeaseScope,
buildRemoteConnectionRequestMetadata,
mergeRemoteConnectionRequestMetadata,
readRemoteConnectionState,
remoteConnectionLeaseIdentityMatches,
removeRemoteConnectionState,
connectionPlatformMatchesSelection,
narrowConnectionPlatform,
writeRemoteConnectionState,
type RemoteConnectionState,
type RemoteConnectionRequestMetadata,
} from '@agent-device/remote/remote-connection-state';
import { AppError, errorMessage } from '@agent-device/kernel/errors';
import { isInactiveLeaseError } from '@agent-device/contracts/lease-scope';
import {
connectProviderNamesForError,
connectionProviderCapabilities,
isConnectProviderName,
primeProviderConnection,
unavailableConnectPluginError,
type ConnectProvider,
} from '../connection/provider-policy.ts';
import {
resolveConnectProviderProfile,
verifyResolvedConnectProvider,
} from '../connection/connect-provider-adapters.ts';
import {
connectionPlatformConflict,
releaseRemoteConnectionLease,
resolveRequestedLeaseBackend,
} from './connection-lease-transaction.ts';
import { hasDeferredMetroConfig, stopMetroCleanup } from './connection-metro-runtime.ts';
import { releasePreviousLease } from './connection-previous-lease.ts';
import { removeGeneratedRemoteConfigIfUnused } from '../connection/generated-config.ts';
import { writeCommandOutput } from './shared.ts';
import { formatDeliveredArtifactLines } from '@agent-device/command-output';
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,
host,
}) => {
const stateDir = resolveDaemonPaths(flags.stateDir, {
cwd: host.cwd,
env: host.env,
}).baseDir;
await primeProviderConnection(positionals[0], host.env);
const provider = readConnectProvider(positionals, host.env);
assertConnectProviderUsage(provider, flags);
const resolved = await resolveConnectProviderProfile({
provider,
flags,
stateDir,
cwd: host.cwd,
env: host.env,
});
const { flags: connectFlags, connection: connectionMetadata } = scopeConnectProfile(
flags,
resolved,
host,
);
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, host.env);
const state = buildConnectedState({
flags: connectFlags,
scope,
connectionMetadata,
context,
remoteConfigPath: resolved.remoteConfigPath,
});
writeRemoteConnectionState({ stateDir, state });
const previousLeaseNotice = await cleanupForcedPreviousConnection(
client,
connectFlags,
context.previous,
state,
host,
);
const runtimePreparation = buildRuntimePreparationNotice(connectFlags, state, host);
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,
context.session,
);
return {
version: 1,
session: context.session,
remoteConfigPath,
remoteConfigHash: context.remoteConfigHash,
daemon: context.daemon,
tenant: scope.tenant,
runId: scope.runId,
...leaseBinding,
...runtimeBinding,
updatedAt: now,
};
}
type ConnectionLeaseBinding = Pick<
RemoteConnectionState,
'clientId' | 'deviceKey' | 'leaseBackend' | 'leaseId' | 'leaseProvider'
>;
function buildConnectionLeaseBinding(
flags: CliFlags,
previous: RemoteConnectionState | null,
connectionMetadata: RemoteConnectionRequestMetadata | undefined,
): ConnectionLeaseBinding {
const connection = mergeRemoteConnectionRequestMetadata(connectionMetadata ?? {}, previous ?? {});
const leaseBackend = previous?.leaseBackend ?? resolveRequestedLeaseBackend(flags);
if (leaseBackend === 'macos-app') {
return buildHostAllocatedLeaseBinding(flags, previous, connection);
}
return {
leaseId: previous?.leaseId,
leaseBackend,
...connection,
deviceKey: previous?.deviceKey ?? connection.deviceKey,
};
}
function buildHostAllocatedLeaseBinding(
flags: CliFlags,
previous: RemoteConnectionState | null,
connection: RemoteConnectionRequestMetadata,
): ConnectionLeaseBinding {
return {
leaseId: flags.leaseId ?? previous?.leaseId,
leaseBackend: 'macos-app',
...connection,
};
}
/**
* 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'>,
session: string,
): Pick<RemoteConnectionState, 'connectedAt' | 'metro' | 'platform' | 'runtime' | 'target'> {
const platform = narrowConnectionPlatform({
leaseBackend: leaseBinding.leaseBackend,
recordedPlatform: previous?.platform,
requestedPlatform: flags.platform,
});
if (!platform.ok) {
throw connectionPlatformConflict({
session,
leaseBackend: leaseBinding.leaseBackend,
boundPlatform: platform.boundPlatform,
requestedPlatform: platform.requestedPlatform,
detail: previous ? 'bound-connection' : 'requested-backend',
});
}
return {
platform: platform.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'],
flags: CliFlags,
previous: RemoteConnectionState | null,
next: RemoteConnectionState,
host: HostEnvironment,
): Promise<PreviousLeaseReleaseNotice | undefined> {
if (!previous || !flags.force) return undefined;
await stopMetroCleanup(previous.metro);
if (previous.leaseId && previous.leaseId === next.leaseId) return undefined;
return await releasePreviousLease(client, previous, {
nextDaemonBaseUrl: next.daemon?.baseUrl,
ambientDaemonAuthToken: flags.daemonAuthToken,
cwd: host.cwd,
env: host.env,
});
}
/**
* The flags and lease metadata `connect` binds a profile to. A leased profile the caller supplies is
* shared by every session that names it, so each session connects under a client and run of its own
* (#3931); a provider-generated profile already derives both from the session.
*/
function scopeConnectProfile(
flags: CliFlags,
resolved: { flags: CliFlags; remoteConfigPath: string },
host: HostEnvironment,
): { flags: CliFlags; connection: RemoteConnectionRequestMetadata | undefined } {
const profile = resolveRemoteConfigProfile({
configPath: resolved.remoteConfigPath,
cwd: host.cwd,
env: host.env,
}).profile;
if (!flags.remoteConfig || flags.session === undefined) {
return { flags: resolved.flags, connection: buildRemoteConnectionRequestMetadata(profile) };
}
const scope = sessionLeaseScope(
{ ...profile, leaseId: resolved.flags.leaseId, runId: profile.runId },
flags.session,
);
return {
flags:
resolved.flags.runId === profile.runId
? { ...resolved.flags, runId: scope.runId }
: resolved.flags,
connection: buildRemoteConnectionRequestMetadata({ ...profile, clientId: scope.clientId }),
};
}
export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => {
const { session, stateDir, state } = readRequestedConnectionState(flags, host);
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);
let released = false;
let releaseError: string | undefined;
if (state.leaseId) {
try {
const release = await releaseRemoteConnectionLease(client, state, flags.daemonAuthToken);
released = release.released;
providerData ??= release.provider;
} catch (error) {
// An inactive lease is already gone. Any other failure leaves a live lease whose only local
// record is removed below, so the output must name it.
if (!isInactiveLeaseError(error)) releaseError = errorMessage(error);
}
}
removeRemoteConnectionState({ stateDir, session: connectedSession });
// A failed release keeps the profile: retrying that release needs it.
if (!releaseError) {
removeGeneratedRemoteConfigIfUnused({ stateDir, remoteConfigPath: state.remoteConfigPath });
}
await writeCommandOutput(
flags,
{
connected: false,
session: connectedSession,
released,
...(releaseError ? { leaseId: state.leaseId, releaseError } : {}),
...(providerData ? { provider: providerData } : {}),
},
() => renderDisconnectOutput(state, providerData, releaseError),
);
return true;
};
export const connectionCommand: ClientCommandHandler = async ({ positionals, flags, host }) => {
if (positionals[0] !== 'status') {
throw new AppError('INVALID_ARGS', 'connection accepts only: status');
}
const { session, state } = readRequestedConnectionState(flags, host);
if (!state) {
await writeNoRemoteConnectionOutput(flags, session);
return true;
}
await primeProviderConnection(state.leaseProvider);
const leasePreparation = buildLeasePreparationNotice(state);
const runtimePreparation = buildRuntimePreparationNoticeFromState(state, host);
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(
state: RemoteConnectionState,
providerData: CloudProviderSessionResult | undefined,
releaseError: string | undefined,
): string {
return [
`Disconnected remote session "${state.session}".`,
...(releaseError
? [
`Could not release lease ${state.leaseId} (tenant ${state.tenant}, run ${state.runId}) ` +
`at ${state.daemon?.baseUrl ?? 'its daemon'}: ${releaseError}. ` +
'It was left in place — release it manually if it is still active.',
]
: []),
...formatProviderReleaseWarnings(providerData),
...formatDeliveredArtifactLines(providerData?.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 readConnectProvider(
positionals: string[],
env: NodeJS.ProcessEnv,
): 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, env)) {
return provider;
}
const pluginError = unavailableConnectPluginError(provider, env);
if (pluginError) throw pluginError;
throw new AppError(
'INVALID_ARGS',
`Unknown connect provider: ${provider}. Supported providers: ${connectProviderNamesForError(env)}.`,
);
}
function readRequestedConnectionState(
flags: CliFlags,
host: HostEnvironment,
): {
session: string;
stateDir: string;
state: RemoteConnectionState | null;
} {
const session = flags.session ?? 'default';
const stateDir = resolveDaemonPaths(flags.stateDir, {
cwd: host.cwd,
env: host.env,
}).baseDir;
const state =
readRemoteConnectionState({ stateDir, session }) ??
(flags.session ? null : readActiveConnectionState({ stateDir }));
if (state) requireLeasedConnectionSession(state, flags.session);
return { session, stateDir, state };
}
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 &&
macosAppLeaseIdMatches(state, options.flags.leaseId) &&
remoteConnectionLeaseIdentityMatches(state, options.connection)
);
}
function macosAppLeaseIdMatches(
state: RemoteConnectionState,
leaseId: string | undefined,
): boolean {
return state.leaseBackend !== 'macos-app' || leaseId === undefined || leaseId === state.leaseId;
}
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,
host: HostEnvironment,
): RuntimePreparationNotice | undefined {
if (state.runtime) return undefined;
if (
!hasDeferredMetroConfig(flags) &&
!remoteConfigHasMetroSettings(state.remoteConfigPath, host)
) {
return undefined;
}
return buildDeferredRuntimeNotice(state);
}
function buildRuntimePreparationNoticeFromState(
state: RemoteConnectionState,
host: HostEnvironment,
): RuntimePreparationNotice | undefined {
if (state.runtime || !remoteConfigHasMetroSettings(state.remoteConfigPath, host))
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, host: HostEnvironment): boolean {
try {
const remoteConfig = resolveRemoteConfigProfile({
configPath: remoteConfigPath,
cwd: host.cwd,
env: host.env,
});
const profile = remoteConfig.profile;
return Boolean(
profile.metroPublicBaseUrl ||
profile.metroProxyBaseUrl ||
profile.metroProjectRoot ||
profile.metroKind,
);
} catch {
return false;
}
}