Repository navigation
Expand file tree
/
Copy pathruntime.ts
More file actions
776 lines (725 loc) · 28.1 KB
/
Copy pathruntime.ts
File metadata and controls
776 lines (725 loc) · 28.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
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
import Limrun from '@limrun/api';
import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types';
import type {
DeviceInventoryProvider,
DeviceLease,
LeaseLifecycleProvider,
LeaseLifecycleContext,
ProviderAppCatalogHandler,
ProviderDeviceInstallOptions,
ProviderDeviceInstallResult,
ProviderDeviceRuntime,
ProviderExpiredLeaseRecovery,
ProviderPortReverseOptions,
} from '@agent-device/contracts/device';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import {
cleanupLimrunAndroidAdbTunnel,
configureLimrunAndroidPortReverse,
createLimrunAndroidInteractor,
createLimrunAndroidSession,
installLimrunAndroidApp,
type LimrunAndroidSession,
} from './android.ts';
import {
attachedLimrunInstanceId,
buildLimrunDevice,
LIMRUN_PROVIDER,
parseLimrunDeviceId,
platformForLimrunLeaseBackend,
type LimrunPlatform,
} from './device.ts';
import {
createLimrunIosInteractor,
createLimrunIosSession,
installLimrunIosApp,
type LimrunIosSession,
} from './ios.ts';
import { createLimrunDeviceSession, type LimrunDeviceSession } from './device-session.ts';
import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts';
import type {
PlatformRuntimeHost,
PlatformRuntimeOwner,
PlatformRuntimeProviderModule,
} from '@agent-device/contracts/platform-runtime-operations';
import { providerRuntimeOwner } from '@agent-device/contracts/platform-runtime';
import type { LimrunAppLogDescriptor } from './app-log-descriptor.ts';
import type { LimrunAppLogReader } from './app-log-runtime.ts';
import { LIMRUN_CLIENT_ID, limrunUserAgent, requireLimrunOrgClient } from './client-options.ts';
import { resolveLimrunRuntimeInstance } from './runtime-instance.ts';
import type { LimrunRequestOperationDrain } from './request-cancellation.ts';
import type { LimrunAppAsset } from './app-catalog.ts';
import type { LimrunInstanceAccess } from './instance-access.ts';
import type {
CloudArtifactProvider,
CloudArtifactsQuery,
CloudArtifactsResult,
} from '@agent-device/contracts/observability';
import type {
LimrunHarCapture,
LimrunHarCaptureFailure,
LimrunTunnelFailureReport,
} from './network-har.ts';
import path from 'node:path';
type LimrunRuntimeSession = LimrunIosSession | LimrunAndroidSession;
const KEEP_ALIVE_INTERVAL_MS = 30_000;
export type LimrunRuntimeOptions = {
/** Organization API key. It creates and deletes instances for platforms without `instances`. */
apiKey?: string;
region?: string;
/** Pings each leased instance every 30 s so Limrun's inactivity timeout does not end idle sessions. */
keepAlive?: boolean;
runtimeInstance?: string;
instances?: LimrunInstanceAccess;
/**
* Where `--provider-network-logs` writes each session's live HAR file. The composition root
* resolves it under the daemon state dir; without it the opt-in reports a typed refusal.
*/
networkHarDir?: string;
};
export type LimrunRuntime = ProviderDeviceRuntime & {
recoverExpiredLease: ProviderExpiredLeaseRecovery;
getDeviceSession(device: DeviceInfo): LimrunDeviceSession | undefined;
};
export type LimrunRuntimeRegistration = Readonly<{
runtime: LimrunRuntime;
platformModule: PlatformRuntimeProviderModule;
}>;
export function createLimrunRuntime(
options: LimrunRuntimeOptions,
dependencies: LimrunRuntimeDependencies,
mode: Readonly<{ includePlatformModule: true }>,
): LimrunRuntimeRegistration;
export function createLimrunRuntime(
options: LimrunRuntimeOptions,
dependencies: LimrunRuntimeDependencies,
): LimrunRuntime;
export function createLimrunRuntime(
options: LimrunRuntimeOptions,
dependencies: LimrunRuntimeDependencies,
mode?: Readonly<{ includePlatformModule: true }>,
): LimrunRuntime | LimrunRuntimeRegistration {
const runtime = new LimrunRuntimeImplementation(options, dependencies);
if (!mode?.includePlatformModule) return runtime;
const owner = providerRuntimeOwner(LIMRUN_PROVIDER, resolveLimrunRuntimeInstance(options));
if (owner.kind !== 'provider-runtime') throw new TypeError('Invalid Limrun runtime owner');
return Object.freeze({
runtime,
platformModule: Object.freeze({
owner,
loadRuntime: async (host: PlatformRuntimeHost) =>
await loadLimrunPlatformRuntime(runtime, owner.instance, host),
}),
});
}
class LimrunRuntimeImplementation implements ProviderDeviceRuntime {
private readonly limrun: Limrun | undefined;
private readonly sessions = new Map<string, LimrunRuntimeSession>();
private readonly keepAliveTimers = new Map<string, NodeJS.Timeout>();
/** Each lease's `--provider-network-logs` capture: live, stopped at release, or never started. */
private readonly networkCaptures = new Map<string, NetworkCaptureState>();
private readonly appAliases = new Map<
string,
Readonly<{ assetName: string; installedAppId: string }>
>();
private readonly options: LimrunRuntimeOptions;
private readonly dependencies: LimrunRuntimeDependencies;
readonly provider = LIMRUN_PROVIDER;
readonly leaseLifecycle: LeaseLifecycleProvider = {
allocate: async (lease, context) => await this.allocate(lease, context),
release: async (lease) => await this.release(lease),
};
readonly appCatalog: ProviderAppCatalogHandler = async (query, signal) => {
const { assertLimrunUploadedAppAccess, listLimrunAppAssets } = await import('./app-catalog.ts');
assertLimrunUploadedAppAccess(query.publicNetworkOnly);
const limrun = this.orgClient(
'Listing uploaded apps',
'Run open <bundle-or-package-id> first; apps then lists the apps installed on the instance.',
);
return (await listLimrunAppAssets(limrun, query.platform, signal)).map((asset) => asset.name);
};
readonly recoverExpiredLease: ProviderExpiredLeaseRecovery = async (lease) => {
if (lease.leaseProvider !== this.provider || !platformForLimrunLeaseBackend(lease.backend)) {
throw new AppError('UNSUPPORTED_OPERATION', 'Limrun cannot recover this expired lease.', {
leaseId: lease.leaseId,
leaseProvider: lease.leaseProvider,
leaseBackend: lease.backend,
});
}
await this.release(lease);
};
readonly deviceInventoryProvider: DeviceInventoryProvider = async (request) => {
if (request.leaseProvider !== this.provider || !request.leaseId) return null;
const session = this.sessions.get(request.leaseId);
if (!session) return null;
if (request.platform && request.platform !== session.platform) return [];
return [session.device];
};
constructor(options: LimrunRuntimeOptions, dependencies: LimrunRuntimeDependencies) {
if (!options.apiKey && !options.instances?.ios && !options.instances?.android) {
throw new TypeError('Limrun runtime requires an apiKey or instance access');
}
this.options = options;
this.dependencies = dependencies;
this.limrun = options.apiKey
? new Limrun({
apiKey: options.apiKey,
userAgent: limrunUserAgent(dependencies.clientVersion),
})
: undefined;
}
ownsDevice(device: DeviceInfo): boolean {
return parseLimrunDeviceId(device.id) !== undefined;
}
hasLiveSession(device: DeviceInfo): boolean {
return this.getSessionForDevice(device) !== undefined;
}
getInteractor(device: DeviceInfo, _runner?: RunnerContext): Interactor | undefined {
const session = this.getSessionForDevice(device);
if (!session) return undefined;
return session.platform === 'ios'
? createLimrunIosInteractor(session)
: createLimrunAndroidInteractor(session);
}
getDeviceSession(device: DeviceInfo): LimrunDeviceSession | undefined {
const session = this.getSessionForDevice(device);
return session ? createLimrunDeviceSession(session) : undefined;
}
async installApp(
device: DeviceInfo,
app: string,
appPath: string,
options?: ProviderDeviceInstallOptions,
signal?: AbortSignal,
operationDrain?: LimrunRequestOperationDrain,
): Promise<ProviderDeviceInstallResult | undefined> {
return await this.installInstallablePath(
device,
appPath,
{
...options,
appIdentifierHint: options?.appIdentifierHint ?? app,
packageNameHint: options?.packageNameHint ?? app,
},
signal,
operationDrain,
);
}
async installInstallablePath(
device: DeviceInfo,
installablePath: string,
options?: ProviderDeviceInstallOptions,
signal?: AbortSignal,
operationDrain?: LimrunRequestOperationDrain,
): Promise<ProviderDeviceInstallResult | undefined> {
const session = this.getSessionForDevice(device);
if (!session) return undefined;
const limrun = this.orgClient('Uploading an app');
return session.platform === 'ios'
? await installLimrunIosApp(limrun, session, installablePath, options, signal, operationDrain)
: await installLimrunAndroidApp(
limrun,
session,
installablePath,
options,
signal,
operationDrain,
);
}
async configurePortReverse(
options: ProviderPortReverseOptions,
): Promise<Record<string, unknown> | undefined> {
const session = this.requireAndroidPortReverseSession(options.leaseId);
if (!session) return undefined;
await configureLimrunAndroidPortReverse(session, options);
return portReverseResult(options);
}
async shutdown(): Promise<void> {
const sessions = [...this.sessions.values()];
await Promise.allSettled(sessions.map(async (session) => await this.terminateSession(session)));
this.sessions.clear();
this.appAliases.clear();
}
private async allocate(
lease: DeviceLease,
context?: LeaseLifecycleContext,
): Promise<Record<string, unknown> | undefined> {
if (lease.leaseProvider !== this.provider) return undefined;
const platform = platformForLimrunLeaseBackend(lease.backend);
if (!platform) return undefined;
const { rejectRefusedLimrunProfileFields } = await import('./session-allocation.ts');
// Before the reuse below, since a repeat allocation of a live lease carries flags of its own, and
// ahead of attach as well as create, since an attached instance reads none of them either.
rejectRefusedLimrunProfileFields(context);
const existing = this.sessions.get(lease.leaseId);
if (existing) {
// A repeat allocation can opt into the capture the first one did not ask for, or retry one
// that could not start.
const networkHar =
context?.flags?.providerNetworkLogs === true &&
(this.networkCaptures.get(lease.leaseId)?.phase ?? 'unavailable') === 'unavailable'
? await this.startNetworkCapture(lease, existing, context)
: undefined;
return {
limrunInstanceId: existing.instanceId,
device: existing.device,
...(networkHar ? { networkHar } : {}),
};
}
const session =
(await this.attachSession(platform, lease)) ??
(await this.createSession(platform, lease, context));
this.sessions.set(lease.leaseId, session);
if (this.options.keepAlive) this.startKeepAlive(lease.leaseId, session);
const networkHar =
context?.flags?.providerNetworkLogs === true
? await this.startNetworkCapture(lease, session, context)
: undefined;
return {
limrunInstanceId: session.instanceId,
providerSessionId: session.instanceId,
device: session.device,
...(networkHar ? { networkHar } : {}),
};
}
private async attachSession(
platform: LimrunPlatform,
lease: DeviceLease,
): Promise<LimrunRuntimeSession | undefined> {
const { ios, android } = this.options.instances ?? {};
const target = (apiUrl: string) => {
const instanceId = attachedLimrunInstanceId(apiUrl);
const device = buildLimrunDevice(platform, lease, instanceId);
return { lease, instanceId, ownership: 'attached' as const, device };
};
if (platform === 'android') {
return (
android &&
(await createLimrunAndroidSession(
{ ...target(android.apiUrl), ...android },
this.dependencies,
))
);
}
return (
ios && (await createLimrunIosSession({ ...target(ios.apiUrl), ...ios }, this.dependencies))
);
}
private async createSession(
platform: LimrunPlatform,
lease: DeviceLease,
context?: LeaseLifecycleContext,
): Promise<LimrunRuntimeSession> {
const {
allocateLimrunAndroidSession,
allocateLimrunIosSession,
resolvePreinstalledAppId,
resolveRequestedLimrunAppAsset,
} = await import('./session-allocation.ts');
const limrun = this.orgClient('Creating an instance');
const requestedAsset = await resolveRequestedLimrunAppAsset(limrun, platform, context);
const params = this.sessionAllocationParams(limrun, lease, requestedAsset);
const session =
platform === 'ios'
? await allocateLimrunIosSession(params)
: await allocateLimrunAndroidSession(params);
if (requestedAsset) {
try {
const installedAppId = await resolvePreinstalledAppId(session, requestedAsset);
this.appAliases.set(lease.leaseId, {
assetName: requestedAsset.name,
installedAppId,
});
} catch (error) {
await this.terminateSession(session);
throw error;
}
}
return session;
}
private sessionAllocationParams(limrun: Limrun, lease: DeviceLease, app?: LimrunAppAsset) {
return {
limrun,
lease,
metadata: this.buildInstanceMetadata(lease),
region: this.options.region,
app,
dependencies: this.dependencies,
};
}
private buildInstanceMetadata(lease: DeviceLease) {
return {
displayName: `agent-device-${lease.tenantId}-${lease.runId}`,
labels: {
tenantId: lease.tenantId,
runId: lease.runId,
leaseId: lease.leaseId,
provider: lease.leaseProvider ?? LIMRUN_PROVIDER,
source: LIMRUN_CLIENT_ID,
},
};
}
private async release(lease: DeviceLease): Promise<Record<string, unknown> | undefined> {
const session = this.sessions.get(lease.leaseId);
if (!session) return await this.releaseRecoveredSession(lease);
// A retry after a failed termination finds the capture already stopped and reports it again.
const networkCapture = await this.stopNetworkCapture(lease.leaseId);
await this.terminateSession(session);
this.sessions.delete(lease.leaseId);
this.appAliases.delete(lease.leaseId);
return {
limrunInstanceId: session.instanceId,
providerSessionId: session.instanceId,
...(networkCapture ? { cloudArtifacts: networkCaptureArtifacts(networkCapture) } : {}),
};
}
/**
* `--provider-network-logs`: opens the instance's one destination tunnel with inspection and
* keeps a live HAR file under the state dir. The Metro/companion route rides this tunnel.
*/
private async startNetworkCapture(
lease: DeviceLease,
session: LimrunRuntimeSession,
context?: LeaseLifecycleContext,
): Promise<Record<string, unknown>> {
const instanceId = session.instanceId;
const harDir = this.options.networkHarDir;
const result = harDir
? await import('./network-har.ts').then(({ startLimrunHarCapture }) =>
startLimrunHarCapture(session.client, {
// One file per lease: an attached instance serves many sessions.
harPath: path.join(harDir, `${instanceId}-${fileSafe(lease.leaseId)}.har`),
selectors: readProviderNetworkHosts(context?.flags?.providerNetworkHosts),
}),
)
: ({
ok: false,
reason: 'capture-dir-unset',
message: 'The runtime has no directory for network capture files.',
} as const);
await this.forgetStoppedNetworkCaptures();
if (!result.ok) {
const { reason, message } = result;
this.networkCaptures.set(lease.leaseId, {
phase: 'unavailable',
instanceId,
reason,
message,
});
return { status: 'unavailable', reason, message };
}
this.networkCaptures.set(lease.leaseId, {
phase: 'capturing',
instanceId,
capture: result.capture,
});
return { status: 'capturing', harPath: result.capture.harPath };
}
private async stopNetworkCapture(leaseId: string): Promise<SettledNetworkCapture | undefined> {
const state = this.networkCaptures.get(leaseId);
if (state?.phase !== 'capturing') return state;
// Read the tunnel's last dial failure while the tunnel is still open.
const failures = await state.capture.failures();
await state.capture.close();
const stopped = {
phase: 'stopped',
instanceId: state.instanceId,
harPath: state.capture.harPath,
failures,
} as const;
this.networkCaptures.set(leaseId, stopped);
return stopped;
}
/** Keeps released captures listable for a while without growing for the daemon's lifetime. */
private async forgetStoppedNetworkCaptures(): Promise<void> {
const settled = [...this.networkCaptures].filter(([, state]) => state.phase !== 'capturing');
const { discardLimrunHar } = await import('./network-har.ts');
for (const [leaseId, state] of settled.slice(0, -SETTLED_NETWORK_CAPTURE_LIMIT)) {
this.networkCaptures.delete(leaseId);
// The file holds raw traffic, so it lives exactly as long as the record that reports it.
if (state.phase === 'stopped') await discardLimrunHar(state.harPath).catch(() => undefined);
}
}
readonly cloudArtifacts: CloudArtifactProvider = {
listCloudArtifacts: async (
query: CloudArtifactsQuery,
): Promise<CloudArtifactsResult | undefined> => {
const state = query.leaseId ? this.networkCaptures.get(query.leaseId) : undefined;
if (state?.phase !== 'capturing') return state ? networkCaptureArtifacts(state) : undefined;
return networkCaptureArtifacts({
phase: 'stopped',
instanceId: state.instanceId,
harPath: state.capture.harPath,
failures: await state.capture.failures(),
});
},
};
private async releaseRecoveredSession(
lease: DeviceLease,
): Promise<Record<string, unknown> | undefined> {
const platform = platformForLimrunLeaseBackend(lease.backend);
const limrun = this.limrun;
if (!platform || !limrun) return undefined;
const labelSelector = `provider=${LIMRUN_PROVIDER},leaseId=${lease.leaseId}`;
const instances =
platform === 'ios'
? await limrun.iosInstances.list({ labelSelector })
: await limrun.androidInstances.list({ labelSelector });
const instanceIds = instances.getPaginatedItems().map((instance) => instance.metadata.id);
for (const instanceId of instanceIds) {
if (platform === 'ios') {
await limrun.iosInstances.delete(instanceId);
} else {
await limrun.androidInstances.delete(instanceId);
}
}
if (instanceIds.length === 0) return undefined;
return { limrunInstanceId: instanceIds[0], limrunInstanceCount: instanceIds.length };
}
private startKeepAlive(leaseId: string, session: LimrunRuntimeSession): void {
const timer = setInterval(() => {
try {
session.client.keepAlive();
} catch {
// A dead connection surfaces on the next real command.
}
}, KEEP_ALIVE_INTERVAL_MS);
timer.unref();
this.keepAliveTimers.set(leaseId, timer);
}
private async terminateSession(session: LimrunRuntimeSession): Promise<void> {
const leaseId = session.lease.leaseId;
clearInterval(this.keepAliveTimers.get(leaseId));
this.keepAliveTimers.delete(leaseId);
// A capture rides the instance's one tunnel; close it before the client disconnects.
const networkCapture = this.networkCaptures.get(leaseId);
if (networkCapture?.phase === 'capturing') {
this.networkCaptures.delete(leaseId);
// The client disconnect below ends the tunnel even when its own close fails.
await networkCapture.capture.close().catch(() => undefined);
}
session.client.disconnect();
if (session.platform === 'android') await cleanupLimrunAndroidAdbTunnel(session);
if (session.ownership === 'attached') return;
const limrun = this.orgClient('Deleting an instance');
if (session.platform === 'ios') {
await limrun.iosInstances.delete(session.instanceId);
} else {
await limrun.androidInstances.delete(session.instanceId);
}
}
private orgClient(operation: string, hint?: string): Limrun {
return requireLimrunOrgClient(this.limrun, operation, hint);
}
private getSessionForDevice(device: DeviceInfo): LimrunRuntimeSession | undefined {
const parsed = parseLimrunDeviceId(device.id);
if (!parsed) return undefined;
const session = this.sessions.get(parsed.leaseId);
return session?.platform === parsed.platform ? session : undefined;
}
resolveAppReference(device: DeviceInfo, app: string): string {
const parsed = parseLimrunDeviceId(device.id);
if (!parsed) return app;
const alias = this.appAliases.get(parsed.leaseId);
return alias?.assetName === app ? alias.installedAppId : app;
}
currentAppLogReader(device: DeviceInfo): LimrunAppLogReader | undefined {
const session = this.getSessionForDevice(device);
if (!session) return undefined;
const publicSession = createLimrunDeviceSession(session);
return {
platform: session.platform,
leaseId: session.lease.leaseId,
instanceId: session.instanceId,
ownership: session.ownership,
readLogs: async (appBundleId, lineLimit) =>
publicSession.platform === 'ios'
? await publicSession.readLogs(appBundleId, lineLimit)
: await publicSession.readLogs(lineLimit),
[Symbol.asyncDispose]: async () => undefined,
};
}
async reconnectAppLogReader(descriptor: LimrunAppLogDescriptor, signal?: AbortSignal) {
const { reconnectLimrunAppLogReader } = await import('./app-log-reconnect.ts');
return await reconnectLimrunAppLogReader({
limrun: this.limrun,
instances: this.options.instances,
descriptor,
dependencies: this.dependencies,
signal,
});
}
private requireAndroidPortReverseSession(leaseId: string): LimrunAndroidSession | undefined {
const session = this.sessions.get(leaseId);
if (!session || session.platform === 'android') return session;
throw unsupported(
'port reverse',
'Direct Limrun iOS sessions cannot reach local host ports; use a bridge public URL.',
);
}
}
async function loadLimrunPlatformRuntime(
runtime: LimrunRuntimeImplementation,
runtimeInstance: string,
host: PlatformRuntimeHost,
): Promise<PlatformRuntimeOwner> {
const { createLimrunPlatformRuntimeOwner } = await import('./app-log-runtime.ts');
return createLimrunPlatformRuntimeOwner({
host,
runtimeInstance,
ownsDevice: (device) => runtime.ownsDevice(device),
hasLiveSession: (device) => runtime.hasLiveSession(device),
getInteractor: (device, runner) => runtime.getInteractor(device, runner),
getDeviceSession: (device) => runtime.getDeviceSession(device),
resolveAppReference: (device, app) => runtime.resolveAppReference(device, app),
openCurrent: async (device) => runtime.currentAppLogReader(device),
reconnect: async (descriptor, signal) =>
await runtime.reconnectAppLogReader(descriptor, signal),
listApps: async (device, filter, signal) => {
signal.throwIfAborted();
const session = runtime.getDeviceSession(device);
if (!session) {
throw new AppError('DEVICE_NOT_FOUND', 'Limrun app inventory session is unavailable', {
deviceId: device.id,
});
}
return (await session.listApps(filter)).map((app) => ({
id: app.id,
name: app.name ?? app.id,
}));
},
getAppState: async (device, signal) => {
signal.throwIfAborted();
const session = runtime.getDeviceSession(device);
if (session?.platform !== 'android') {
throw new AppError(
'UNSUPPORTED_OPERATION',
'Limrun Android appstate requires an active provider session',
);
}
const state = await session.getForegroundApp(signal);
signal.throwIfAborted();
return { package: state?.appId, activity: state?.activity };
},
deployApp: async (device, input, signal, operationDrain) =>
await runtime.installApp(
device,
input.app,
input.appPath,
{
relaunch: input.replaceExisting,
appIdentifierHint: input.app,
packageNameHint: input.app,
},
signal,
operationDrain,
),
deployMaterializedApp: async (device, input, signal, operationDrain) =>
await runtime.installInstallablePath(
device,
input.artifact.installablePath,
{
appIdentifierHint: input.artifact.bundleId,
packageNameHint: input.artifact.packageName,
},
signal,
operationDrain,
),
configurePortReverse: async (options) => await runtime.configurePortReverse(options),
});
}
function portReverseResult(options: ProviderPortReverseOptions): Record<string, unknown> {
return {
leaseId: options.leaseId,
devicePort: options.devicePort,
hostPort: options.hostPort,
name: options.name,
};
}
function unsupported(command: string, message: string): never {
throw new AppError('UNSUPPORTED_OPERATION', message, { command });
}
function fileSafe(value: string): string {
return value.replaceAll(/[^\w.-]/g, '_');
}
/** The `--provider-network-hosts` comma list, or undefined to keep the default selectors. */
function readProviderNetworkHosts(value: unknown): readonly string[] | undefined {
if (typeof value !== 'string') return undefined;
const hosts = value
.split(',')
.map((host) => host.trim())
.filter((host) => host.length > 0);
return hosts.length > 0 ? hosts : undefined;
}
const SETTLED_NETWORK_CAPTURE_LIMIT = 32;
type SettledNetworkCapture =
| Readonly<{
phase: 'stopped';
instanceId: string;
harPath: string;
failures: LimrunTunnelFailureReport;
}>
| Readonly<{ phase: 'unavailable'; instanceId: string } & LimrunHarCaptureFailure>;
type NetworkCaptureState =
| SettledNetworkCapture
| Readonly<{ phase: 'capturing'; instanceId: string; capture: LimrunHarCapture }>;
const NETWORK_ARTIFACT_NAME = 'Network traffic (HAR, live file on the daemon host)';
/**
* One HAR file, stated as a provider artifact whose `url` is its path on this host. The tunnel
* failure report rides the artifact's metadata, and its summary is the result's message. A capture
* that never started is an unavailable artifact carrying the typed reason.
*/
function networkCaptureArtifacts(capture: SettledNetworkCapture): CloudArtifactsResult {
if (capture.phase === 'unavailable') {
return {
provider: LIMRUN_PROVIDER,
status: 'unavailable',
providerSessionId: capture.instanceId,
message: `Network capture did not start (${capture.reason}): ${capture.message}`,
cloudArtifacts: [
{
provider: LIMRUN_PROVIDER,
kind: 'network',
name: NETWORK_ARTIFACT_NAME,
availability: 'unavailable',
metadata: { reason: capture.reason },
},
],
};
}
const { harPath, instanceId, failures } = capture;
return {
provider: LIMRUN_PROVIDER,
status: 'ready',
providerSessionId: instanceId,
...(failures.total > 0 || failures.lastDialFailure
? { message: summarizeTunnelFailures(failures) }
: {}),
cloudArtifacts: [
{
provider: LIMRUN_PROVIDER,
kind: 'network',
name: NETWORK_ARTIFACT_NAME,
url: harPath,
extension: 'har',
contentType: 'application/json',
availability: 'ready',
metadata: { tunnelFailures: failures },
},
],
};
}
function summarizeTunnelFailures(failures: LimrunTunnelFailureReport): string {
const kinds = Object.entries(failures.byKind).map(([kind, entry]) => {
const failure = entry.latest.at(-1);
const endpoint = failure?.host
? ` ${failure.host}${failure.port ? `:${failure.port}` : ''}`
: '';
return `${kind} ${entry.count}, latest${endpoint} (${failure?.message})`;
});
const dial = failures.lastDialFailure
? [`last dial failure ${failures.lastDialFailure.reason}`]
: [];
return `Network capture failures: ${failures.total}; ${[...kinds, ...dial].join('; ')}`;
}