Repository navigation
Expand file tree
/
Copy pathconnection-runtime.ts
More file actions
1051 lines (1002 loc) · 35.3 KB
/
Copy pathconnection-runtime.ts
File metadata and controls
1051 lines (1002 loc) · 35.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
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { MetroBridgeScope } from '@agent-device/contracts/remote';
import { resolveDaemonPaths } from '../../daemon-resolution.ts';
import { stopReactDevtoolsCompanion } from '../../client/client-react-devtools-companion.ts';
import { stopMetroTunnel } from '../../metro/metro.ts';
import { resolveRemoteConfigProfile } from '../../remote/remote-config.ts';
// Provenance-preserving file-only read (no ambient env defaults merged in) —
// see resolvePreviousOwnDaemonAuthToken below for why this must not be
// resolveRemoteConfigProfile.
import { readRemoteConfigFile } from '../../remote/remote-config-core.ts';
import {
deviceFieldsFromPublicPlatform,
resolveDevice,
type DeviceInfo,
} from '@agent-device/kernel/device';
import { shouldAgentCdpUseRemoteBridgeUrl } from './agent-cdp.ts';
import {
narrowConnectionPlatform,
buildConnectionDeviceKey,
buildRemoteConnectionDaemonState,
buildRemoteConnectionRequestMetadata,
hashRemoteConfigFile,
mergeRemoteConnectionRequestMetadata,
readRemoteConnectionState,
resolveConnectionDeviceScope,
writeRemoteConnectionState,
type RemoteConnectionState,
type RemoteConnectionRequestMetadata,
} from '../../remote/remote-connection-state.ts';
import { profileToCliFlags } from '../remote-config-flags.ts';
import type { BatchStep } from '@agent-device/contracts/client';
import { AppError } from '@agent-device/kernel/errors';
import {
isSessionRuntimePlatform,
leaseBackendForPlatform,
type LeaseBackend,
type SessionRuntimeHints,
} from '@agent-device/kernel/contracts';
import type { CliFlags } from '@agent-device/contracts/command';
import type { AgentDeviceClient, Lease } from '../../agent-device-client.ts';
import type { CloudProviderSessionResult } from '@agent-device/contracts/observability';
import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog';
import { readMetroPrepareKind } from '../../commands/metro/prepare-kind.ts';
import { connectionProviderCapabilities } from '../connection/provider-policy.ts';
import { readCloudDeviceFeatureProfileFields } from '../connection/profile-fields.ts';
import type { PreviousLeaseReleaseNotice } from './connection-presentation.ts';
const leaseDeferredCommands = new Set([
'artifacts',
'connect',
'connection',
'close',
'disconnect',
'metro',
'session',
]);
const runtimeDeferredCommands = new Set(['open']);
const proxyLeaseAllocatingCommands: ReadonlySet<string> = new Set([
PUBLIC_COMMANDS.open,
PUBLIC_COMMANDS.install,
PUBLIC_COMMANDS.reinstall,
INTERNAL_COMMANDS.installSource,
]);
export const PROXY_REMOTE_LEASE_TTL_MS = 5 * 60 * 1000;
export const CLOUD_WEBDRIVER_REMOTE_LEASE_TTL_MS = 10 * 60 * 1000;
export async function materializeRemoteConnectionForCommand(options: {
command: string;
flags: CliFlags;
client: AgentDeviceClient;
runtime?: SessionRuntimeHints;
positionals?: string[];
batchSteps?: BatchStep[];
forceRuntimePrepare?: boolean;
}): Promise<{
flags: CliFlags;
runtime?: SessionRuntimeHints;
connection?: RemoteConnectionRequestMetadata;
}> {
const { command, flags, client } = options;
if (!flags.remoteConfig) {
return { flags, runtime: options.runtime };
}
const stateDir = resolveDaemonPaths(flags.stateDir).baseDir;
const remoteConfig = resolveRemoteConfigProfile({
configPath: flags.remoteConfig,
cwd: process.cwd(),
env: process.env,
});
const profileFlags = profileToCliFlags(remoteConfig.profile);
const mergedFlags = {
...profileFlags,
...flags,
remoteConfig: remoteConfig.resolvedPath,
};
const existingState = readRemoteConnectionState({
stateDir,
session: mergedFlags.session ?? 'default',
});
if (existingState && existingState.remoteConfigPath !== remoteConfig.resolvedPath) {
throw new AppError(
'INVALID_ARGS',
'A different remote connection is already active for this session. Run connect --force or disconnect before using a different --remote-config.',
{
session: existingState.session,
activeRemoteConfig: existingState.remoteConfigPath,
requestedRemoteConfig: remoteConfig.resolvedPath,
},
);
}
const state =
existingState ??
createRemoteConnectionStateFromFlags(
mergedFlags,
remoteConfig.resolvedPath,
remoteConfig.profile,
);
const nextFlags = { ...mergedFlags, session: state.session };
const deferredAppSelection = connectionProviderCapabilities(
state.leaseProvider,
).supportsDeferredAppSelection;
const initialApp =
deferredAppSelection && command === PUBLIC_COMMANDS.open ? options.positionals?.[0] : undefined;
if (deferredAppSelection) delete nextFlags.providerApp;
let nextRuntime = selectCompatibleRuntime(state.runtime, nextFlags.platform) ?? options.runtime;
let nextState = state;
let changed = !existingState;
let acquiredLeaseForCleanup: Lease | undefined;
const leasePolicy = connectionLeasePolicyForState(nextState);
if (leasePolicy.shouldAllocate(command)) {
const materializedLease = await materializeLeaseForCommand({
command,
client,
state,
nextState,
nextFlags,
initialApp,
policy: leasePolicy,
});
nextState = materializedLease.state;
changed = changed || materializedLease.changed;
acquiredLeaseForCleanup = materializedLease.acquiredLeaseForCleanup;
}
// A command that allocates no lease still returns flags and a record on the platform axis, and the
// record can carry an alias the request asked to narrow. Same rule as the binding path above, so a
// connection whose backend rents one leaf cannot serve another leaf simply because this command
// never reached the allocator.
const carriedPlatform = narrowConnectionPlatform({
leaseBackend: nextState.leaseBackend,
recordedPlatform: nextState.platform,
requestedPlatform: nextFlags.platform,
});
if (!carriedPlatform.ok) {
throw connectionPlatformConflict({
session: state.session,
leaseBackend: nextState.leaseBackend,
boundPlatform: carriedPlatform.boundPlatform,
requestedPlatform: carriedPlatform.requestedPlatform,
detail: 'bound-connection',
});
}
nextState = { ...nextState, platform: carriedPlatform.platform };
nextFlags.platform = carriedPlatform.platform;
const runtimePreparation = await prepareRuntimeForCommand({
command,
flags: nextFlags,
client,
state,
nextState,
runtime: nextRuntime,
positionals: options.positionals,
batchSteps: options.batchSteps,
forceRuntimePrepare: options.forceRuntimePrepare,
});
nextState = runtimePreparation.state;
nextRuntime = runtimePreparation.runtime;
changed = changed || runtimePreparation.changed;
await persistMaterializedConnection({
changed,
stateDir,
state: nextState,
client,
acquiredLeaseForCleanup,
preparedMetroCleanupOnFailure: runtimePreparation.preparedMetroCleanupOnFailure,
metroCleanupToStop: runtimePreparation.metroCleanupToStop,
});
return {
flags: {
...nextFlags,
session: nextState.session,
leaseId: nextState.leaseId,
leaseBackend: nextState.leaseBackend,
platform: nextState.platform ?? nextFlags.platform,
target: nextState.target ?? nextFlags.target,
},
runtime: nextRuntime,
connection: buildRemoteConnectionRequestMetadata(nextState),
};
}
async function prepareRuntimeForCommand(options: {
command: string;
flags: CliFlags;
client: AgentDeviceClient;
state: RemoteConnectionState;
nextState: RemoteConnectionState;
runtime?: SessionRuntimeHints;
positionals?: string[];
batchSteps?: BatchStep[];
forceRuntimePrepare?: boolean;
}): Promise<{
state: RemoteConnectionState;
runtime?: SessionRuntimeHints;
changed: boolean;
metroCleanupToStop?: RemoteConnectionState['metro'];
preparedMetroCleanupOnFailure?: RemoteConnectionState['metro'];
}> {
const { command, flags, state, client } = options;
let nextState = ensureRuntimeLeaseState(options.nextState, flags);
const nextRuntime = options.runtime;
if (
!shouldPrepareRuntimeForCommand(command, flags, options.batchSteps, options.positionals) ||
!hasDeferredMetroConfig(flags) ||
!shouldPrepareRuntime(options.forceRuntimePrepare, nextRuntime, flags.platform)
) {
return { state: nextState, runtime: nextRuntime, changed: false };
}
if (!nextState.leaseId) {
throw new AppError(
'INVALID_ARGS',
`${command} requires a resolved remote lease before Metro runtime can be prepared.`,
);
}
const prepared = await prepareConnectedMetro(
flags,
client,
state.remoteConfigPath,
state.session,
{
tenantId: state.tenant,
runId: state.runId,
leaseId: nextState.leaseId,
},
);
const replacesExistingMetroCleanup = !isSameMetroCleanup(nextState.metro, prepared.cleanup);
nextState = {
...nextState,
runtime: prepared.runtime,
metro: prepared.cleanup,
updatedAt: new Date().toISOString(),
};
return {
state: nextState,
runtime: prepared.runtime,
changed: true,
metroCleanupToStop: replacesExistingMetroCleanup ? options.nextState.metro : undefined,
preparedMetroCleanupOnFailure: replacesExistingMetroCleanup ? prepared.cleanup : undefined,
};
}
function ensureRuntimeLeaseState(
state: RemoteConnectionState,
flags: CliFlags,
): RemoteConnectionState {
if (state.leaseId || !flags.leaseId) return state;
return {
...state,
leaseId: flags.leaseId,
leaseBackend: flags.leaseBackend,
};
}
function shouldPrepareRuntime(
forceRuntimePrepare: boolean | undefined,
runtime: SessionRuntimeHints | undefined,
platform: CliFlags['platform'],
): boolean {
return (
forceRuntimePrepare === true || !runtime || !isRuntimeCompatibleWithPlatform(runtime, platform)
);
}
async function persistMaterializedConnection(options: {
changed: boolean;
stateDir: string;
state: RemoteConnectionState;
client: AgentDeviceClient;
acquiredLeaseForCleanup?: Lease;
preparedMetroCleanupOnFailure?: RemoteConnectionState['metro'];
metroCleanupToStop?: RemoteConnectionState['metro'];
}): Promise<void> {
if (options.changed) {
try {
writeRemoteConnectionState({ stateDir: options.stateDir, state: options.state });
} catch (error) {
await stopMetroCleanup(options.preparedMetroCleanupOnFailure);
await releaseAcquiredLeaseOnWriteFailure(
options.client,
options.state,
options.acquiredLeaseForCleanup,
);
throw error;
}
}
await stopMetroCleanup(options.metroCleanupToStop);
}
async function materializeLeaseForCommand(options: {
command: string;
client: AgentDeviceClient;
state: RemoteConnectionState;
nextState: RemoteConnectionState;
nextFlags: CliFlags;
initialApp?: string;
policy: ConnectionLeasePolicy;
}): Promise<{
state: RemoteConnectionState;
changed: boolean;
acquiredLeaseForCleanup?: Lease;
}> {
const { command, client, state, nextFlags, policy } = options;
const preliminaryLeaseBackend = state.leaseBackend ?? resolveRequestedLeaseBackend(nextFlags);
let nextState = options.nextState;
const resolvedLeaseState = await policy.resolveLeaseState({
command,
client,
state: nextState,
flags: nextFlags,
leaseBackend: preliminaryLeaseBackend,
});
nextState = resolvedLeaseState.state;
if (resolvedLeaseState.device) {
applyResolvedDeviceSelector(nextFlags, resolvedLeaseState.device);
}
const leaseBackend =
nextState.leaseBackend ??
preliminaryLeaseBackend ??
requireRequestedLeaseBackend(nextFlags, command);
assertRequestedConnectionBackend(state, leaseBackend);
// One decision for one axis. Whichever of the backend, the record, and the request names the
// narrowest platform, that is what this command records, sends, allocates, and returns; two that
// cannot name the same device are refused here rather than resolved later by whoever read first.
const platform = narrowConnectionPlatform({
leaseBackend,
recordedPlatform: nextState.platform,
requestedPlatform: nextFlags.platform,
});
if (!platform.ok) {
throw connectionPlatformConflict({
session: state.session,
leaseBackend,
boundPlatform: platform.boundPlatform,
requestedPlatform: platform.requestedPlatform,
detail: 'bound-connection',
});
}
// Read after the platform is settled: a request that asks for another Apple leaf also asks for a
// different target, and the platform is the reason it is being refused.
assertRequestedConnectionTarget(state, nextFlags);
nextState = { ...nextState, platform: platform.platform };
nextFlags.platform = platform.platform;
const materializedLease = await allocateOrReuseLease(
client,
nextState,
leaseBackend,
policy,
nextFlags,
options.initialApp,
);
const lease = materializedLease.lease;
nextFlags.leaseId = lease.leaseId;
nextFlags.leaseBackend = leaseBackend;
nextFlags.target = nextState.target ?? nextFlags.target;
if (leaseStateMatches(nextState, lease, leaseBackend)) {
return {
state: nextState,
changed: false,
acquiredLeaseForCleanup: materializedLease.acquired ? lease : undefined,
};
}
return {
state: buildMaterializedLeaseState(nextState, lease, leaseBackend, nextFlags),
changed: true,
acquiredLeaseForCleanup: materializedLease.acquired ? lease : undefined,
};
}
function leaseStateMatches(
state: RemoteConnectionState,
lease: Lease,
leaseBackend: LeaseBackend,
): boolean {
return (
state.leaseId === lease.leaseId &&
state.leaseBackend === leaseBackend &&
state.deviceKey === (lease.deviceKey ?? state.deviceKey)
);
}
function buildMaterializedLeaseState(
state: RemoteConnectionState,
lease: Lease,
leaseBackend: LeaseBackend,
flags: CliFlags,
): RemoteConnectionState {
const connection = mergeRemoteConnectionRequestMetadata(lease, state);
return {
...state,
leaseId: lease.leaseId,
leaseBackend,
...connection,
platform: state.platform ?? flags.platform,
target: state.target ?? flags.target,
updatedAt: new Date().toISOString(),
};
}
type ConnectionLeasePolicy = {
shouldAllocate(command: string): boolean;
ttlMs(state: RemoteConnectionState): number | undefined;
resolveLeaseState(options: {
command: string;
client: AgentDeviceClient;
state: RemoteConnectionState;
flags: CliFlags;
leaseBackend?: LeaseBackend;
}): Promise<{ state: RemoteConnectionState; device?: DeviceInfo }>;
};
function connectionLeasePolicyForState(state: RemoteConnectionState): ConnectionLeasePolicy {
const capabilities = connectionProviderCapabilities(state.leaseProvider);
if (capabilities.leaseKind === 'proxy') {
return PROXY_CONNECTION_LEASE_POLICY;
}
if (capabilities.supportsDeferredAppSelection) {
return DEFERRED_APP_SELECTION_CONNECTION_LEASE_POLICY;
}
if (capabilities.usesCloudWebDriverLease) {
return CLOUD_WEBDRIVER_CONNECTION_LEASE_POLICY;
}
return DEFAULT_CONNECTION_LEASE_POLICY;
}
const DEFERRED_APP_SELECTION_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
shouldAllocate: (command) =>
command !== PUBLIC_COMMANDS.apps && !leaseDeferredCommands.has(command),
ttlMs: () => undefined,
resolveLeaseState: async (options) => ({ state: options.state }),
};
const DEFAULT_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
shouldAllocate: (command) => !leaseDeferredCommands.has(command),
ttlMs: () => undefined,
resolveLeaseState: async (options) => ({ state: options.state }),
};
const PROXY_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
shouldAllocate: (command) => command !== 'devices' && !leaseDeferredCommands.has(command),
ttlMs: () => PROXY_REMOTE_LEASE_TTL_MS,
resolveLeaseState: resolveProxyLeaseState,
};
const CLOUD_WEBDRIVER_CONNECTION_LEASE_POLICY: ConnectionLeasePolicy = {
shouldAllocate: (command) => !leaseDeferredCommands.has(command),
ttlMs: () => CLOUD_WEBDRIVER_REMOTE_LEASE_TTL_MS,
resolveLeaseState: async (options) => ({ state: options.state }),
};
async function prepareConnectedMetro(
flags: CliFlags,
client: AgentDeviceClient,
remoteConfigPath: string,
session: string,
bridgeScope: MetroBridgeScope,
): Promise<{
runtime?: SessionRuntimeHints;
cleanup?: NonNullable<RemoteConnectionState['metro']>;
}> {
if (!flags.metroProjectRoot && !flags.metroPublicBaseUrl && !flags.metroProxyBaseUrl) {
return {};
}
if (flags.platform !== 'ios' && flags.platform !== 'android') {
throw new AppError(
'INVALID_ARGS',
'Deferred Metro preparation requires platform "ios" or "android".',
);
}
if (!flags.metroPublicBaseUrl && !flags.metroProxyBaseUrl) {
throw new AppError(
'INVALID_ARGS',
'Deferred Metro preparation requires metroPublicBaseUrl or metroProxyBaseUrl when Metro settings are provided.',
);
}
const prepared = await client.metro.prepare({
projectRoot: flags.metroProjectRoot,
kind: readMetroPrepareKind(flags.metroKind),
publicBaseUrl: flags.metroPublicBaseUrl,
proxyBaseUrl: flags.metroProxyBaseUrl,
bearerToken: flags.metroBearerToken,
bridgeScope,
launchUrl: flags.launchUrl,
companionProfileKey: remoteConfigPath,
companionConsumerKey: session,
port: flags.metroPreparePort,
listenHost: flags.metroListenHost,
statusHost: flags.metroStatusHost,
startupTimeoutMs: flags.metroStartupTimeoutMs,
probeTimeoutMs: flags.metroProbeTimeoutMs,
reuseExisting: flags.metroNoReuseExisting ? false : undefined,
installDependenciesIfNeeded: flags.metroNoInstallDeps ? false : undefined,
runtimeFilePath: flags.metroRuntimeFile,
});
return {
runtime: flags.platform === 'ios' ? prepared.iosRuntime : prepared.androidRuntime,
cleanup: flags.metroProxyBaseUrl
? {
projectRoot: prepared.projectRoot,
profileKey: remoteConfigPath,
consumerKey: session,
}
: undefined,
};
}
export async function stopMetroCleanup(
cleanup: RemoteConnectionState['metro'] | undefined,
): Promise<void> {
if (!cleanup) return;
try {
await stopMetroTunnel(cleanup);
} catch {
// Connection lifecycle cleanup must stay best-effort.
}
}
export async function stopReactDevtoolsCleanup(options: {
stateDir: string;
state: Pick<RemoteConnectionState, 'remoteConfigPath' | 'session'>;
}): Promise<void> {
try {
await stopReactDevtoolsCompanion({
projectRoot: process.cwd(),
stateDir: options.stateDir,
profileKey: options.state.remoteConfigPath,
consumerKey: options.state.session,
});
} catch {
// Connection lifecycle cleanup must stay best-effort.
}
}
export async function releaseRemoteConnectionLease(
client: AgentDeviceClient,
state: RemoteConnectionState,
// The daemon bearer token is never persisted on `state` (ADR 0007); callers
// pass the token already resolved via the flag/env/CLI-session chain.
daemonAuthToken?: string,
): Promise<{ released: boolean; provider?: CloudProviderSessionResult }> {
if (!state.leaseId) return { released: false };
const result = await client.leases.release({
tenant: state.tenant,
runId: state.runId,
leaseId: state.leaseId,
leaseBackend: state.leaseBackend,
daemonBaseUrl: state.daemon?.baseUrl,
daemonAuthToken,
daemonTransport: state.daemon?.transport,
daemonServerMode: state.daemon?.serverMode,
...buildRemoteConnectionRequestMetadata(state),
});
return result;
}
// A forced reconnect releases the *previous* connection's lease, which must be
// authenticated against the *previous* endpoint's own credential — never the
// new connection's token (that would send an unrelated endpoint's secret to
// an endpoint it was never issued for). See plans/007 for the full rule.
type PreviousLeaseAuthResolution =
| { canAuthenticate: true; daemonAuthToken?: string }
| { canAuthenticate: false };
function resolvePreviousLeaseAuth(options: {
previous: RemoteConnectionState;
nextDaemonBaseUrl?: string;
ambientDaemonAuthToken?: string;
cwd: string;
env: Record<string, string | undefined>;
}): PreviousLeaseAuthResolution {
const ownToken = resolvePreviousOwnDaemonAuthToken(options.previous, options.cwd, options.env);
if (ownToken) return { canAuthenticate: true, daemonAuthToken: ownToken };
if (options.previous.daemon?.baseUrl === options.nextDaemonBaseUrl) {
// Same endpoint: the ambient credential plausibly belongs to it too.
return { canAuthenticate: true, daemonAuthToken: options.ambientDaemonAuthToken };
}
return { canAuthenticate: false };
}
function resolvePreviousOwnDaemonAuthToken(
previous: RemoteConnectionState,
cwd: string,
env: Record<string, string | undefined>,
): string | undefined {
try {
// readRemoteConfigFile, not resolveRemoteConfigProfile: the latter merges
// ambient environment defaults (e.g. AGENT_DEVICE_DAEMON_AUTH_TOKEN) into
// the profile, which would let the *new* connection's env-sourced token
// masquerade as a credential that provably belongs to the *previous*
// endpoint. Only a token the previous config file itself declares counts
// here; the env fallback is rule 2's job, gated on matching endpoints.
const { profile } = readRemoteConfigFile({
configPath: previous.remoteConfigPath,
cwd,
env,
});
if (!profile.daemonAuthToken) return undefined;
// The path alone is not provenance. `remoteConfigPath` names a file *now*,
// while the claim being made is about what that file declared when the
// previous connection was established — and a config path is routinely
// reused (edited in place, re-pointed at a second environment) between the
// two. Without this check, "connect to A from ./remote.json, re-point
// ./remote.json at B, connect --force" reads B's token as A's own and
// sends it to A during lease release: the same cross-endpoint leak the
// env-merge fix closed, arriving through the file instead.
return previousConfigStillSpeaksForPreviousEndpoint(previous, profile.daemonBaseUrl)
? profile.daemonAuthToken
: undefined;
} catch {
// A missing/unparseable previous config is the "cannot authenticate"
// case handled by the caller, not an error to propagate here.
return undefined;
}
}
/**
* Whether the previous connection's config file can still vouch for a token as
* belonging to the previous connection's endpoint.
*
* The file must explicitly declare the same endpoint recorded in the previous
* connection state. A matching file hash proves only that the file itself did
* not change; it does not prove that its endpoint/token were effective when
* CLI flags may have overridden them. Endpoint equality is the provenance
* boundary and also preserves the benign rotated-credential case.
*
* The endpoint comparison runs both sides through
* `buildRemoteConnectionDaemonState`, the same normalizer that produced the
* stored `daemon.baseUrl`, so it compares like with like rather than raw
* strings that differ only by a trailing slash.
*
* A file that changed and no longer declares an endpoint at all cannot vouch
* for anything: the caller then falls back to rule 2 (matching endpoints) or
* reports the lease as unreleasable, which is a warning and an orphaned lease
* — the correct price for not sending a credential somewhere it may not belong.
*/
function previousConfigStillSpeaksForPreviousEndpoint(
previous: RemoteConnectionState,
declaredDaemonBaseUrl: string | undefined,
): boolean {
const declared = buildRemoteConnectionDaemonState({
daemonBaseUrl: declaredDaemonBaseUrl,
})?.baseUrl;
return declared !== undefined && declared === previous.daemon?.baseUrl;
}
export async function releasePreviousLease(
client: AgentDeviceClient,
previous: RemoteConnectionState,
options: {
nextDaemonBaseUrl?: string;
ambientDaemonAuthToken?: string;
cwd: string;
env: Record<string, string | undefined>;
},
): Promise<PreviousLeaseReleaseNotice | undefined> {
if (!previous.leaseId) return undefined;
const auth = resolvePreviousLeaseAuth({
previous,
nextDaemonBaseUrl: options.nextDaemonBaseUrl,
ambientDaemonAuthToken: options.ambientDaemonAuthToken,
cwd: options.cwd,
env: options.env,
});
if (!auth.canAuthenticate) {
return buildUnreleasedPreviousLeaseNotice(
previous,
'no credential known to belong to that endpoint was available',
);
}
try {
await releaseRemoteConnectionLease(client, previous, auth.daemonAuthToken);
return undefined;
} catch {
// Reconnect must still succeed; surface the failure instead of hiding it.
return buildUnreleasedPreviousLeaseNotice(previous, 'the release request failed');
}
}
function buildUnreleasedPreviousLeaseNotice(
previous: RemoteConnectionState,
reason: string,
): PreviousLeaseReleaseNotice {
return {
status: 'unreleased',
message:
`Could not release the previous lease ${previous.leaseId} ` +
`(tenant ${previous.tenant}, run ${previous.runId}) ` +
`at ${previous.daemon?.baseUrl ?? 'its daemon'}: ${reason}. ` +
'It was left in place — release it manually if it is still active.',
};
}
async function releaseAcquiredLeaseOnWriteFailure(
client: AgentDeviceClient,
state: RemoteConnectionState,
lease: Lease | undefined,
): Promise<void> {
if (!lease) return;
try {
const connection = mergeRemoteConnectionRequestMetadata(state, lease);
await client.leases.release({
tenant: state.tenant,
runId: state.runId,
leaseId: lease.leaseId,
leaseBackend: state.leaseBackend ?? lease.backend,
...connection,
});
} catch {
// Preserve the state-write failure; cleanup is best-effort.
}
}
export function resolveRequestedLeaseBackend(flags: CliFlags): LeaseBackend | undefined {
return flags.leaseBackend ?? leaseBackendForPlatform(flags.platform);
}
function requireRequestedLeaseBackend(flags: CliFlags, command: string): LeaseBackend {
const leaseBackend = resolveRequestedLeaseBackend(flags);
if (leaseBackend) return leaseBackend;
throw new AppError(
'INVALID_ARGS',
`${command} requires --platform ios|android|harmonyos or --lease-backend when the remote connection has not resolved a lease yet.`,
);
}
function shouldPrepareRuntimeForCommand(
command: string,
flags: CliFlags,
batchSteps?: BatchStep[],
positionals: string[] = [],
): boolean {
if (command === 'cdp') {
return shouldAgentCdpUseRemoteBridgeUrl(positionals) && Boolean(flags.metroPublicBaseUrl);
}
if (runtimeDeferredCommands.has(command)) {
return true;
}
if (command !== 'batch' || !batchSteps) {
return false;
}
return batchSteps.some((step) => {
const stepCommand = step.command.trim().toLowerCase();
return runtimeDeferredCommands.has(stepCommand) && step.runtime === undefined;
});
}
export function hasDeferredMetroConfig(flags: CliFlags): boolean {
const metroKind = flags.metroKind;
return Boolean(
flags.metroPublicBaseUrl || flags.metroProxyBaseUrl || flags.metroProjectRoot || metroKind,
);
}
function isRuntimeCompatibleWithPlatform(
runtime: SessionRuntimeHints,
platform: CliFlags['platform'],
): boolean {
if (!runtime.platform || !platform || !isSessionRuntimePlatform(platform)) {
return true;
}
return runtime.platform === platform;
}
function isSameMetroCleanup(
left: RemoteConnectionState['metro'] | undefined,
right: RemoteConnectionState['metro'] | undefined,
): boolean {
return (
left?.projectRoot === right?.projectRoot &&
left?.profileKey === right?.profileKey &&
left?.consumerKey === right?.consumerKey
);
}
function selectCompatibleRuntime(
runtime: SessionRuntimeHints | undefined,
platform: CliFlags['platform'],
): SessionRuntimeHints | undefined {
if (!runtime) return undefined;
return isRuntimeCompatibleWithPlatform(runtime, platform) ? runtime : undefined;
}
function createRemoteConnectionStateFromFlags(
flags: CliFlags,
remoteConfigPath: string,
profile: Pick<RemoteConnectionState, 'leaseProvider' | 'clientId' | 'deviceKey'> = {},
): RemoteConnectionState {
if (!flags.tenant) {
throw new AppError(
'INVALID_ARGS',
'remote command requires tenant in remote config or via --tenant <id>.',
);
}
if (!flags.runId) {
throw new AppError(
'INVALID_ARGS',
'remote command requires runId in remote config or via --run-id <id>.',
);
}
if (
!flags.daemonBaseUrl &&
connectionProviderCapabilities(profile.leaseProvider).requiresRemoteDaemon
) {
throw new AppError(
'INVALID_ARGS',
'remote command requires daemonBaseUrl in remote config, config, env, or --daemon-base-url.',
);
}
const now = new Date().toISOString();
return {
version: 1,
session: flags.session ?? 'default',
remoteConfigPath,
remoteConfigHash: hashRemoteConfigFile(remoteConfigPath),
daemon: buildRemoteConnectionDaemonState(flags),
tenant: flags.tenant,
runId: flags.runId,
leaseId: flags.leaseId,
leaseBackend: flags.leaseBackend ?? resolveRequestedLeaseBackend(flags),
leaseProvider: profile.leaseProvider,
clientId: profile.clientId,
deviceKey: profile.deviceKey,
platform: flags.platform,
target: flags.target,
connectedAt: now,
updatedAt: now,
};
}
async function allocateOrReuseLease(
client: AgentDeviceClient,
state: RemoteConnectionState,
leaseBackend: LeaseBackend,
policy: ConnectionLeasePolicy,
flags: CliFlags,
initialApp?: string,
): Promise<{ lease: Lease; acquired: boolean }> {
const connection = buildRemoteConnectionRequestMetadata(state);
if (state.leaseId && state.leaseBackend === leaseBackend) {
const existing = await heartbeatOrAllocateLease(client, state.leaseId, {
tenant: state.tenant,
runId: state.runId,
leaseBackend,
...connection,
ttlMs: policy.ttlMs(state),
});
if (existing) return { lease: existing, acquired: false };
}
const lease = await client.leases.allocate({
tenant: state.tenant,
runId: state.runId,
leaseBackend,
...connection,
ttlMs: policy.ttlMs(state),
platform: state.platform ?? flags.platform,
target: state.target ?? flags.target,
device: flags.device,
udid: flags.udid,
serial: flags.serial,
providerApp: initialApp ?? flags.providerApp,
providerOsVersion: flags.providerOsVersion,
providerProject: flags.providerProject,
providerBuild: flags.providerBuild,
providerSessionName: flags.providerSessionName,
...readCloudDeviceFeatureProfileFields(flags),
awsProjectArn: flags.awsProjectArn,
awsDeviceArn: flags.awsDeviceArn,
awsAppArn: flags.awsAppArn,
awsRegion: flags.awsRegion,
awsInteractionMode: flags.awsInteractionMode,
});
return { lease, acquired: true };
}
async function resolveProxyLeaseState(options: {
command: string;
client: AgentDeviceClient;
state: RemoteConnectionState;
flags: CliFlags;
leaseBackend?: LeaseBackend;
}): Promise<{ state: RemoteConnectionState; device?: DeviceInfo }> {
if (!proxyLeaseAllocatingCommands.has(options.command)) {
if (options.state.leaseId && options.state.deviceKey) return { state: options.state };
throw new AppError(
'INVALID_ARGS',
'No active proxy device lease for this session; run open first.',
);
}
const device = await resolveSelectedDevice(options.client, options.flags);
const scope = resolveConnectionDeviceScope(device);
return {
state: {
...options.state,
deviceKey: buildConnectionDeviceKey(scope),
leaseBackend: options.state.leaseBackend ?? options.leaseBackend ?? scope.leaseBackend,
platform: scope.platform,
target: options.state.target ?? scope.target,
updatedAt: new Date().toISOString(),
},
device,
};
}
function applyResolvedDeviceSelector(flags: CliFlags, device: DeviceInfo): void {
const scope = resolveConnectionDeviceScope(device);
flags.platform = scope.platform;
flags.target = scope.target ?? flags.target;
if (scope.identityFlag === 'udid') flags.udid = scope.id;
if (scope.identityFlag === 'serial') flags.serial = scope.id;
}
async function resolveSelectedDevice(
client: AgentDeviceClient,
flags: CliFlags,
): Promise<DeviceInfo> {
const devices = await client.devices.list({
platform: flags.platform,
target: flags.target,
device: flags.device,
udid: flags.udid,
serial: flags.serial,
iosSimulatorDeviceSet: flags.iosSimulatorDeviceSet,
androidDeviceAllowlist: flags.androidDeviceAllowlist,
});
return await resolveDevice(
devices.map((device) => ({
...deviceFieldsFromPublicPlatform(device.platform),
id: device.id,
name: device.name,
kind: device.kind,
target: device.target,
booted: device.booted,
})),
{
platform: flags.platform,
target: flags.target,
deviceName: flags.device,
udid: flags.udid,
serial: flags.serial,
},
);
}
/**
* The refusal raised when the platform axis cannot be decided: two of the backend, the record, and
* the request name devices that are not the same device. `detail` says which of the three disagreed,
* because the advice differs — a bound connection is replaced with `--force`, and a request that
* contradicts itself has no `--force` to reach.
*/
export function connectionPlatformConflict(
options: Readonly<{
session: string;
leaseBackend: LeaseBackend | undefined;
boundPlatform?: CliFlags['platform'];
requestedPlatform?: CliFlags['platform'];
detail: 'bound-connection' | 'requested-backend';
}>,
): AppError {
return new AppError(
'INVALID_ARGS',
options.detail === 'bound-connection'
? 'Active remote connection is already bound to a different platform. Re-run connect --force to replace it.'
: 'The requested platform does not match the device this lease backend rents.',
{
session: options.session,
leaseBackend: options.leaseBackend,
platform: options.boundPlatform,
requestedPlatform: options.requestedPlatform,
reason: 'CONNECTION_PLATFORM_CONFLICT',
},
);
}
function assertRequestedConnectionBackend(
state: RemoteConnectionState,
requestedLeaseBackend: LeaseBackend,
): void {