@lynx-js/devtool-connector 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/az.js ADDED
@@ -0,0 +1,616 @@
1
+ import { ReadableStream } from "node:stream/web";
2
+ import { isGetGlobalSwitchResponse, isInitializeResponse, AppResponseTransformStream, GlobalSwitchRequestTransformStream, isListSessionResponse, createCorrelatedFilter, isSetGlobalSwitchResponse, CDPResponseTransformStream, CDPOutputTransformStream, CustomizedResponseTransformStream, CDPRequestTransformStream, CustomizedRequestTransformStream, SessionGuardTransformStream, FilterTransformStream, InspectStream, CustomizedClientIdTransformStream } from "./h.js";
3
+ import { ansi_createDebug, isDaemonLifecycleError } from "./2.js";
4
+ import { nextRequestId } from "./3.js";
5
+ import { DaemonTransport, HDTTransport, ClientId, withTransports } from "./f1.js";
6
+ function throwClientDiscoveryFailures(failures) {
7
+ if (1 === failures.length) throw failures[0];
8
+ const details = failures.map((failure)=>failure instanceof Error ? failure.message : String(failure)).join("; ");
9
+ throw new AggregateError(failures, `All client discovery transports failed: ${details}`);
10
+ }
11
+ function _ts_add_disposable_resource(env, value, async) {
12
+ if (null != value) {
13
+ if ("object" != typeof value && "function" != typeof value) throw new TypeError("Object expected.");
14
+ var dispose, inner;
15
+ if (async) {
16
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
17
+ dispose = value[Symbol.asyncDispose];
18
+ }
19
+ if (void 0 === dispose) {
20
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
21
+ dispose = value[Symbol.dispose];
22
+ if (async) inner = dispose;
23
+ }
24
+ if ("function" != typeof dispose) throw new TypeError("Object not disposable.");
25
+ if (inner) dispose = function() {
26
+ try {
27
+ inner.call(this);
28
+ } catch (e) {
29
+ return Promise.reject(e);
30
+ }
31
+ };
32
+ env.stack.push({
33
+ value: value,
34
+ dispose: dispose,
35
+ async: async
36
+ });
37
+ } else if (async) env.stack.push({
38
+ async: true
39
+ });
40
+ return value;
41
+ }
42
+ function _ts_dispose_resources(env) {
43
+ function fail(e) {
44
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
45
+ env.hasError = true;
46
+ }
47
+ var r, s = 0;
48
+ function next() {
49
+ while(r = env.stack.pop())try {
50
+ if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
51
+ if (r.dispose) {
52
+ var result = r.dispose.call(r.value);
53
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
54
+ fail(e);
55
+ return next();
56
+ });
57
+ } else s |= 1;
58
+ } catch (e) {
59
+ fail(e);
60
+ }
61
+ if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
62
+ if (env.hasError) throw env.error;
63
+ }
64
+ return next();
65
+ }
66
+ const debug = ansi_createDebug("devtool-mcp-server:connector");
67
+ const openAppClientWaitTimeoutMs = 55000;
68
+ const clientSetupSwitches = [
69
+ {
70
+ key: "enable_devtool",
71
+ value: true,
72
+ required: true
73
+ },
74
+ {
75
+ key: "enable_quickjs_debug",
76
+ value: true,
77
+ required: true
78
+ }
79
+ ];
80
+ function hasClientList(transport) {
81
+ return "function" == typeof transport.listClients;
82
+ }
83
+ function describeRequest(input) {
84
+ if ("object" != typeof input || null === input) return "request";
85
+ const message = input;
86
+ if ("string" == typeof message["method"]) return `method ${message["method"]}`;
87
+ if ("string" != typeof message["event"]) return "request";
88
+ const data = "object" == typeof message["data"] && null !== message["data"] ? message["data"] : void 0;
89
+ if ("string" == typeof data?.["type"]) return `${message["event"]} ${data["type"]}`;
90
+ return `${message["event"]} event`;
91
+ }
92
+ function isNonEmptyListSessionResponse(response) {
93
+ return isListSessionResponse(response) && response.data.data.length > 0;
94
+ }
95
+ class Connector {
96
+ #transports;
97
+ #hdtTransports;
98
+ #daemonTransports;
99
+ constructor(transports){
100
+ this.#transports = transports;
101
+ this.#hdtTransports = transports.filter((t)=>t instanceof HDTTransport);
102
+ this.#daemonTransports = transports.filter((t)=>t instanceof DaemonTransport);
103
+ }
104
+ async listClients() {
105
+ const discoveryFailures = [];
106
+ const daemonClientResults = await Promise.allSettled(this.#daemonTransports.map(async (transport)=>{
107
+ const clients = await transport.listClients();
108
+ await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
109
+ return clients;
110
+ }));
111
+ const fulfilledDaemonClientResults = daemonClientResults.filter((r)=>"fulfilled" === r.status);
112
+ discoveryFailures.push(...daemonClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
113
+ const daemonClients = fulfilledDaemonClientResults.flatMap((r)=>r.value);
114
+ if (fulfilledDaemonClientResults.length > 0) {
115
+ debug("Using clients from daemon transport: %o", daemonClients);
116
+ return withTransports(daemonClients, fulfilledDaemonClientResults.flatMap((r)=>r.value.transports ?? [
117
+ "daemon"
118
+ ]));
119
+ }
120
+ const daemonLifecycleFailure = daemonClientResults.filter((result)=>"rejected" === result.status).map((result)=>result.reason).find(isDaemonLifecycleError);
121
+ if (daemonLifecycleFailure) throw daemonLifecycleFailure;
122
+ const hdtClientResults = await Promise.allSettled(this.#hdtTransports.map(async (transport)=>{
123
+ const clients = await transport.listClients();
124
+ await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
125
+ return {
126
+ clients,
127
+ id: transport.id
128
+ };
129
+ }));
130
+ const fulfilledHDTClientResults = hdtClientResults.filter((r)=>"fulfilled" === r.status);
131
+ discoveryFailures.push(...hdtClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
132
+ const hdtClients = fulfilledHDTClientResults.flatMap((r)=>r.value.clients);
133
+ if (fulfilledHDTClientResults.length > 0) {
134
+ debug("Using clients from HDT transport: %o", hdtClients);
135
+ return withTransports(hdtClients, fulfilledHDTClientResults.map((r)=>r.value.id));
136
+ }
137
+ const directTransports = this.#transports.filter((t)=>!(t instanceof DaemonTransport));
138
+ const clientListTransports = directTransports.filter((t)=>!(t instanceof HDTTransport)).filter(hasClientList);
139
+ const deviceProbeTransports = directTransports.filter((t)=>!hasClientList(t));
140
+ const [clientListResults, transportDevices] = await Promise.all([
141
+ Promise.allSettled(clientListTransports.map(async (transport)=>{
142
+ const clients = await transport.listClients();
143
+ await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
144
+ return {
145
+ clients,
146
+ id: transport.id
147
+ };
148
+ })),
149
+ Promise.allSettled(deviceProbeTransports.map(async (transport)=>({
150
+ transport,
151
+ devices: await transport.listDevices()
152
+ })))
153
+ ]);
154
+ for (const result of clientListResults)if ("rejected" === result.status) {
155
+ discoveryFailures.push(result.reason);
156
+ debug("listClients: listClients failed on one transport: %O", result.reason);
157
+ }
158
+ for (const result of transportDevices)if ("rejected" === result.status) {
159
+ discoveryFailures.push(result.reason);
160
+ debug("listClients: listDevices failed on one transport: %O", result.reason);
161
+ }
162
+ const fulfilledClientListResults = clientListResults.filter((result)=>"fulfilled" === result.status);
163
+ const fulfilledTransportDevices = transportDevices.filter((result)=>"fulfilled" === result.status);
164
+ if (0 === fulfilledClientListResults.length && 0 === fulfilledTransportDevices.length && discoveryFailures.length > 0) throwClientDiscoveryFailures(discoveryFailures);
165
+ const results = await Promise.allSettled(fulfilledTransportDevices.map((r)=>r.value).flatMap(({ transport, devices })=>devices.flatMap(({ id })=>this.#listClientsForDevice(transport, id))));
166
+ const fulfilledClientResults = results.filter((r)=>"fulfilled" === r.status);
167
+ if (0 === fulfilledClientListResults.length && 0 === fulfilledClientResults.length && results.length > 0) throwClientDiscoveryFailures([
168
+ ...discoveryFailures,
169
+ ...results.filter((result)=>"rejected" === result.status).map((result)=>result.reason)
170
+ ]);
171
+ const fulfilledTransports = [
172
+ ...fulfilledClientListResults.map((r)=>r.value.id),
173
+ ...fulfilledTransportDevices.map((r)=>r.value.transport.id)
174
+ ];
175
+ return withTransports([
176
+ ...fulfilledClientListResults.flatMap((r)=>r.value.clients),
177
+ ...fulfilledClientResults.flatMap((r)=>r.value)
178
+ ], fulfilledTransports.length > 0 ? fulfilledTransports : void 0);
179
+ }
180
+ async listDevices() {
181
+ const results = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
182
+ return results.filter((result)=>"fulfilled" === result.status).flatMap(({ value })=>value);
183
+ }
184
+ async listAvailableApps(deviceId) {
185
+ const transport = await this.#findTransportWithDeviceId(deviceId);
186
+ return await transport.listAvailableApps(deviceId);
187
+ }
188
+ async openApp(deviceId, packageName, options) {
189
+ const transport = await this.#findTransportWithDeviceId(deviceId);
190
+ await transport.openApp(deviceId, packageName, options);
191
+ const signal = AbortSignal.any([
192
+ options?.signal,
193
+ AbortSignal.timeout(openAppClientWaitTimeoutMs)
194
+ ].filter((i)=>void 0 !== i));
195
+ const { setTimeout } = await import("node:timers/promises");
196
+ while(!signal.aborted){
197
+ try {
198
+ const clients = hasClientList(transport) ? (await transport.listClients()).filter(({ id })=>ClientId.deserialize(id)?.deviceId === deviceId) : await this.#listClientsForDevice(transport, deviceId);
199
+ const appClient = clients.find(({ info })=>info.AppProcessName === packageName || info.bundleId === packageName || info.bundleName === packageName);
200
+ if (void 0 !== appClient) return appClient.id;
201
+ } catch (err) {
202
+ debug(`openApp ${deviceId} ${packageName} client not found %o`, err);
203
+ }
204
+ try {
205
+ await setTimeout(1000, void 0, {
206
+ signal
207
+ });
208
+ } catch {
209
+ break;
210
+ }
211
+ }
212
+ throw new Error(`Timed out waiting for app client ${packageName} on device ${deviceId}.`);
213
+ }
214
+ async sendMessage(clientId, message, pipeline = {
215
+ input: [],
216
+ output: []
217
+ }) {
218
+ return this.#sendMessage(clientId, message, pipeline);
219
+ }
220
+ async sendAppMessage(clientId, method, params) {
221
+ const id = nextRequestId();
222
+ return await this.#sendMessage(clientId, {
223
+ method,
224
+ params: {
225
+ ...params
226
+ }
227
+ }, {
228
+ input: [
229
+ new CustomizedRequestTransformStream({
230
+ type: "App",
231
+ sessionId: -1,
232
+ messageBuilder: (message)=>({
233
+ id,
234
+ ...message
235
+ })
236
+ })
237
+ ],
238
+ output: [
239
+ new CustomizedResponseTransformStream("App", id),
240
+ new AppResponseTransformStream(method)
241
+ ]
242
+ });
243
+ }
244
+ async openPage(clientId, url, signal) {
245
+ return await this.#sendMessage(clientId, {
246
+ event: "Customized",
247
+ data: {
248
+ type: "OpenCard",
249
+ data: {
250
+ type: "url",
251
+ url
252
+ },
253
+ sender: -1
254
+ },
255
+ from: -1
256
+ }, {
257
+ input: [],
258
+ output: [
259
+ new FilterTransformStream(isNonEmptyListSessionResponse)
260
+ ]
261
+ }, signal);
262
+ }
263
+ async sendCDPMessage(clientId, sessionId, method, params, isMainThread = false) {
264
+ const id = nextRequestId();
265
+ const SUPPORTED_DOMAIN = [
266
+ "Debugger",
267
+ "Runtime",
268
+ "HeapProfiler",
269
+ "Profiler"
270
+ ];
271
+ if (isMainThread && !SUPPORTED_DOMAIN.some((domain)=>method.startsWith(domain + "."))) throw new Error(`Method ${method} is not supported for main thread. Supported domains: ${SUPPORTED_DOMAIN.join(", ")}`);
272
+ return await this.#sendMessage(clientId, {
273
+ method,
274
+ params,
275
+ sessionId: isMainThread ? "Main" : void 0
276
+ }, {
277
+ input: [
278
+ new CDPRequestTransformStream(sessionId, id)
279
+ ],
280
+ output: [
281
+ new CDPResponseTransformStream(id),
282
+ new CDPOutputTransformStream()
283
+ ]
284
+ });
285
+ }
286
+ async sendListSessionMessage(clientId) {
287
+ return await this.#sendListSessionMessage(clientId);
288
+ }
289
+ async #sendListSessionMessage(clientId) {
290
+ const id = nextRequestId();
291
+ const { data: { data: sessions } } = await this.#sendMessage(clientId, {
292
+ event: "Customized",
293
+ data: {
294
+ type: "ListSession",
295
+ data: {},
296
+ id
297
+ }
298
+ }, {
299
+ input: [],
300
+ output: [
301
+ new FilterTransformStream(createCorrelatedFilter(isListSessionResponse, id))
302
+ ]
303
+ });
304
+ return sessions.map((session)=>({
305
+ ...session,
306
+ type: "" === session.type ? "lynx" : session.type
307
+ }));
308
+ }
309
+ async getGlobalSwitch(clientId, key) {
310
+ const { data: { data: { message } } } = await this.#sendMessage(clientId, {
311
+ key
312
+ }, {
313
+ input: [
314
+ new GlobalSwitchRequestTransformStream("GetGlobalSwitch")
315
+ ],
316
+ output: [
317
+ new FilterTransformStream(isGetGlobalSwitchResponse)
318
+ ]
319
+ });
320
+ if ("object" == typeof message) return message?.global_value === "true" || message?.global_value === true;
321
+ else return "true" === message || true === message;
322
+ }
323
+ async setGlobalSwitch(clientId, key, value) {
324
+ await this.#sendMessage(clientId, {
325
+ key,
326
+ value
327
+ }, {
328
+ input: [
329
+ new GlobalSwitchRequestTransformStream("SetGlobalSwitch")
330
+ ],
331
+ output: [
332
+ new FilterTransformStream(isSetGlobalSwitchResponse)
333
+ ]
334
+ });
335
+ }
336
+ async sendStream(clientId, inputStream, { signal, pipeline } = {}) {
337
+ const { transportId, deviceId, port } = this.#resolveClientId(clientId);
338
+ const transport = await this.#findTransportWithDeviceId(deviceId, transportId);
339
+ return await this.#connect(transport, {
340
+ transportId,
341
+ deviceId,
342
+ port,
343
+ signal
344
+ }, inputStream, pipeline ?? {
345
+ input: [],
346
+ output: []
347
+ });
348
+ }
349
+ async sendCDPStream(clientId, sessionId, inputStream, { signal } = {}) {
350
+ return await this.sendStream(clientId, inputStream, {
351
+ signal,
352
+ pipeline: {
353
+ input: [
354
+ new CDPRequestTransformStream(sessionId)
355
+ ],
356
+ output: [
357
+ new SessionGuardTransformStream(sessionId),
358
+ new CDPResponseTransformStream()
359
+ ]
360
+ }
361
+ });
362
+ }
363
+ #resolveClientId(clientId) {
364
+ const parsed = ClientId.deserialize(clientId);
365
+ if (!parsed) throw new Error(`Invalid clientId: ${clientId}`);
366
+ return parsed;
367
+ }
368
+ async #findTransportWithDeviceId(deviceId, transportId) {
369
+ const [onlyTransport] = this.#transports;
370
+ if (1 === this.#transports.length && onlyTransport instanceof DaemonTransport) return onlyTransport;
371
+ const daemonTransport = await this.#findTransportWithDeviceIdInPool(this.#daemonTransports, deviceId);
372
+ if (daemonTransport) return daemonTransport;
373
+ const nonDaemonTransports = this.#transports.filter((t)=>!(t instanceof DaemonTransport));
374
+ if (void 0 !== transportId) {
375
+ const matchedById = nonDaemonTransports.find((t)=>t.id === transportId);
376
+ if (matchedById) return matchedById;
377
+ throw new Error(`Transport with id: ${transportId} not found`);
378
+ }
379
+ const transport = await this.#findTransportWithDeviceIdInPool(nonDaemonTransports, deviceId);
380
+ if (transport) return transport;
381
+ throw new Error(`Device with id: ${deviceId} not found`);
382
+ }
383
+ async #findTransportWithDeviceIdInPool(transports, deviceId) {
384
+ try {
385
+ return await Promise.any(transports.map(async (transport)=>{
386
+ const devices = await transport.listDevices();
387
+ if (devices.some(({ id })=>id === deviceId)) return transport;
388
+ throw new Error("Not found in this transport");
389
+ }));
390
+ } catch (error) {
391
+ if (error instanceof AggregateError) {
392
+ const daemonLifecycleFailure = error.errors.find(isDaemonLifecycleError);
393
+ if (daemonLifecycleFailure) throw daemonLifecycleFailure;
394
+ }
395
+ return null;
396
+ }
397
+ }
398
+ async #connect(transport, options, inputStream, pipeline) {
399
+ const { deviceId, port } = options;
400
+ const conn = transport instanceof DaemonTransport ? await transport.connect(options) : await transport.connect({
401
+ deviceId,
402
+ port,
403
+ signal: options.signal
404
+ });
405
+ const inputAbortController = new AbortController();
406
+ const inputAbortReason = new Error("Connector input stream disposed");
407
+ const inputClosed = [
408
+ ...pipeline.input,
409
+ new CustomizedClientIdTransformStream(port),
410
+ new InspectStream((msg)=>debug(`connect ${deviceId}:${port} input stream send %o`, JSON.stringify(msg)))
411
+ ].reduce((stream, transform)=>stream.pipeThrough(transform), inputStream).pipeTo(conn.writable, {
412
+ preventClose: true,
413
+ signal: inputAbortController.signal
414
+ }).catch((err)=>{
415
+ if (err === inputAbortReason) return;
416
+ debug(`connect ${deviceId}:${port} input stream err %O`, err);
417
+ throw err;
418
+ });
419
+ const inputSettled = inputClosed.catch(()=>{});
420
+ const outputStream = [
421
+ new InspectStream((msg)=>debug(`connect ${deviceId}:${port} output stream receive %O`, msg)),
422
+ ...pipeline.output
423
+ ].reduce((stream, transform)=>stream.pipeThrough(transform), conn.readable);
424
+ return Object.assign(outputStream, {
425
+ inputClosed,
426
+ async [Symbol.asyncDispose] () {
427
+ debug(`connect ${deviceId}:${port} close connection`);
428
+ inputAbortController.abort(inputAbortReason);
429
+ const connectionDisposed = Promise.resolve().then(()=>conn[Symbol.asyncDispose]());
430
+ connectionDisposed.catch(()=>{});
431
+ await inputSettled;
432
+ return connectionDisposed;
433
+ }
434
+ });
435
+ }
436
+ async #sendMessage(clientId, input, pipeline = {
437
+ input: [],
438
+ output: []
439
+ }, signal) {
440
+ const { transportId, deviceId, port } = this.#resolveClientId(clientId);
441
+ const transport = await this.#findTransportWithDeviceId(deviceId, transportId);
442
+ return this.#sendMessageWithTransport(transport, {
443
+ transportId,
444
+ deviceId,
445
+ port,
446
+ signal: signal ?? AbortSignal.timeout(10000)
447
+ }, input, pipeline, describeRequest(input));
448
+ }
449
+ async #sendMessageWithTransport(transport, options, input, pipeline, request = "request") {
450
+ const outputStream = await this.#connect(transport, options, ReadableStream.from([
451
+ input
452
+ ]), pipeline);
453
+ const reader = outputStream.getReader();
454
+ let failed = false;
455
+ let primaryError;
456
+ let result;
457
+ try {
458
+ const read = reader.read();
459
+ await Promise.race([
460
+ read,
461
+ outputStream.inputClosed
462
+ ]);
463
+ const response = await read;
464
+ await outputStream.inputClosed;
465
+ if (response.done) {
466
+ options.signal?.throwIfAborted();
467
+ const clientId = ClientId.serialize(options.transportId, options.deviceId, options.port);
468
+ throw new Error(`Transport ${transport.constructor.name} ended cleanly (EOF) while waiting for a response to ${request} on clientId: ${clientId}.`);
469
+ } else result = response.value;
470
+ } catch (err) {
471
+ failed = true;
472
+ primaryError = err;
473
+ } finally{
474
+ await reader.cancel(primaryError).catch(()=>{});
475
+ reader.releaseLock();
476
+ }
477
+ try {
478
+ await outputStream[Symbol.asyncDispose]();
479
+ } catch (err) {
480
+ if (failed) debug("connection cleanup suppressed after request failure %O", err);
481
+ else {
482
+ failed = true;
483
+ primaryError = err;
484
+ }
485
+ }
486
+ if (failed) throw primaryError;
487
+ return result;
488
+ }
489
+ async #listClientsForDevice(transport, deviceId) {
490
+ const MIN_PORT = 8901;
491
+ const PORTS = Array.from({
492
+ length: 10
493
+ }, (_, i)=>MIN_PORT + i);
494
+ const discoverySignal = AbortSignal.timeout(5000);
495
+ const results = await Promise.allSettled(PORTS.map(async (port)=>{
496
+ const info = await this.#discoverAndSetupClient(transport, deviceId, port, discoverySignal);
497
+ return {
498
+ id: ClientId.serialize(transport.id, deviceId, port),
499
+ info,
500
+ port
501
+ };
502
+ }));
503
+ const clients = results.filter((result)=>"fulfilled" === result.status).map((result)=>result.value);
504
+ if (0 === clients.length) discoverySignal.throwIfAborted();
505
+ return clients;
506
+ }
507
+ async #discoverAndSetupClient(transport, deviceId, port, discoverySignal) {
508
+ const env = {
509
+ stack: [],
510
+ error: void 0,
511
+ hasError: false
512
+ };
513
+ try {
514
+ const lifetime = new AbortController();
515
+ const forwardStageSignal = (signal)=>{
516
+ const abort = ()=>lifetime.abort(signal.reason);
517
+ signal.addEventListener("abort", abort, {
518
+ once: true
519
+ });
520
+ if (signal.aborted) abort();
521
+ try {
522
+ lifetime.signal.throwIfAborted();
523
+ } catch (err) {
524
+ signal.removeEventListener("abort", abort);
525
+ throw err;
526
+ }
527
+ return ()=>signal.removeEventListener("abort", abort);
528
+ };
529
+ const exchange = async (connection, message, predicate, signal)=>{
530
+ const stopForwardingSignal = forwardStageSignal(signal);
531
+ try {
532
+ signal.throwIfAborted();
533
+ const writer = connection.writable.getWriter();
534
+ debug("connect input stream send %o", JSON.stringify(message));
535
+ await writer.write(message).finally(()=>writer.releaseLock());
536
+ signal.throwIfAborted();
537
+ for await (const value of connection.readable.values({
538
+ preventCancel: true
539
+ })){
540
+ signal.throwIfAborted();
541
+ debug("connect output stream receive %O", value);
542
+ if (predicate(value)) return value;
543
+ }
544
+ signal.throwIfAborted();
545
+ throw new Error("Connection closed before receiving the expected response");
546
+ } catch (err) {
547
+ signal.throwIfAborted();
548
+ throw err;
549
+ } finally{
550
+ stopForwardingSignal();
551
+ }
552
+ };
553
+ const stopForwardingDiscovery = forwardStageSignal(discoverySignal);
554
+ const connection = _ts_add_disposable_resource(env, await transport.connect({
555
+ deviceId,
556
+ port,
557
+ signal: lifetime.signal
558
+ }).finally(stopForwardingDiscovery), true);
559
+ const register = await exchange(connection, {
560
+ event: "Initialize",
561
+ data: port
562
+ }, isInitializeResponse, discoverySignal);
563
+ for (const { key, value, required } of clientSetupSwitches)try {
564
+ await exchange(connection, {
565
+ event: "Customized",
566
+ data: {
567
+ type: "SetGlobalSwitch",
568
+ data: {
569
+ client_id: port,
570
+ session_id: -1,
571
+ message: {
572
+ global_key: key,
573
+ global_value: value
574
+ }
575
+ },
576
+ sender: port
577
+ }
578
+ }, isSetGlobalSwitchResponse, AbortSignal.timeout(3000));
579
+ } catch (err) {
580
+ debug(`setupClient ${deviceId}:${port} ${key} failed %O`, err);
581
+ if (required) throw err;
582
+ }
583
+ return register.data.info;
584
+ } catch (e) {
585
+ env.error = e;
586
+ env.hasError = true;
587
+ } finally{
588
+ const result = _ts_dispose_resources(env);
589
+ if (result) await result;
590
+ }
591
+ }
592
+ async #setupClient(transport, clientId) {
593
+ const { transportId, deviceId, port } = this.#resolveClientId(clientId);
594
+ for (const { key, value } of clientSetupSwitches)try {
595
+ await this.#sendMessageWithTransport(transport, {
596
+ transportId,
597
+ deviceId,
598
+ port,
599
+ signal: AbortSignal.timeout(3000)
600
+ }, {
601
+ key,
602
+ value
603
+ }, {
604
+ input: [
605
+ new GlobalSwitchRequestTransformStream("SetGlobalSwitch")
606
+ ],
607
+ output: [
608
+ new FilterTransformStream(isSetGlobalSwitchResponse)
609
+ ]
610
+ });
611
+ } catch (err) {
612
+ debug(`setupClient ${deviceId}:${port} ${key} failed %O`, err);
613
+ }
614
+ }
615
+ }
616
+ export { Connector, throwClientDiscoveryFailures };
@@ -2,10 +2,11 @@ import promises from "node:fs/promises";
2
2
  import node_os from "node:os";
3
3
  import node_path from "node:path";
4
4
  import { parseArgs } from "node:util";
5
- import { AndroidTransport, DesktopTransport, iOSTransport } from "../h.js";
5
+ import { AndroidTransport, iOSTransport } from "../a.js";
6
+ import { DesktopTransport, LynxSimulatorTransport } from "../h6.js";
6
7
  import { HDTTransport } from "../f1.js";
7
8
  import "../2.js";
8
- import { DevtoolDaemon } from "../t.js";
9
+ import { DevtoolDaemon } from "../tw.js";
9
10
  const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), ".DebugRouterConnector");
10
11
  const PIDFILE = node_path.join(DEBUG_ROUTER_DIR, "daemon.pid");
11
12
  const { values } = parseArgs({
@@ -22,7 +23,8 @@ const daemon = new DevtoolDaemon([
22
23
  new AndroidTransport(),
23
24
  new iOSTransport(),
24
25
  new DesktopTransport(),
25
- ...HDTTransport.createTransports()
26
+ ...HDTTransport.createTransports(),
27
+ new LynxSimulatorTransport()
26
28
  ], {
27
29
  onIdle: ()=>{
28
30
  daemon.close().then(()=>{
@@ -4,5 +4,5 @@ var daemon_DAEMON_CONVERGENCE_TIMEOUT_MS = 15000;
4
4
  var daemon_DAEMON_LIFECYCLE_PROTOCOL_VERSION = 1;
5
5
  var daemon_DEFAULT_DAEMON_PORT = 21783;
6
6
  export { DAEMON_COMMAND_PATH_PREFIX, DAEMON_INSPECTOR_PATH, DAEMON_PRODUCT, DAEMON_SHUTDOWN_PATH, DAEMON_VERSION_PATH, DAEMON_WS_PATH, DaemonLifecycle, DaemonLifecycleError, DaemonManager, createDaemonProcessEnvironment, isControlRequest, isCustomizedMessage, isDaemonLifecycleError, isListClientsRequest, isPingEvent, isRegisterEvent, resolveDaemonEntryPath } from "../2.js";
7
- export { DeviceConnection, DevtoolDaemon, HDT_RES_PATH_PREFIX, InspectorAssets, StaticServer, TarballCache } from "../t.js";
7
+ export { DeviceConnection, DevtoolDaemon, HDT_RES_PATH_PREFIX, InspectorAssets, StaticServer, TarballCache } from "../tw.js";
8
8
  export { daemon_DAEMON_BROWSER_PREVIEW_PROTOCOL_VERSION as DAEMON_BROWSER_PREVIEW_PROTOCOL_VERSION, daemon_DAEMON_COMMAND_PROTOCOL_VERSION as DAEMON_COMMAND_PROTOCOL_VERSION, daemon_DAEMON_CONVERGENCE_TIMEOUT_MS as DAEMON_CONVERGENCE_TIMEOUT_MS, daemon_DAEMON_LIFECYCLE_PROTOCOL_VERSION as DAEMON_LIFECYCLE_PROTOCOL_VERSION, daemon_DEFAULT_DAEMON_PORT as DEFAULT_DAEMON_PORT };
package/dist/f.js CHANGED
@@ -2074,7 +2074,7 @@ function result_fail(action, message, options = {}) {
2074
2074
  };
2075
2075
  }
2076
2076
  const noClientsSummary = "No Lynx DevTool clients were found.";
2077
- const noClientsHelp = "Try these steps:\n1. Make sure the target device/simulator and app are running.\n2. If the app just launched, wait a moment and rerun `list-clients`.\n3. If this is unexpected, rerun with `DEBUG='devtool-mcp-server:connector*'` or try `--no-daemon` (HDT/Aiden discovery still takes precedence).\n\nRun `agent-lynx skills get lynx-devtool`, then read `references/troubleshooting/symptoms.md#list-clients-returns-` relative to the reported Skill directory.";
2077
+ const noClientsHelp = "Try these steps:\n1. Make sure the target device/simulator and app are running.\n2. If the app is still launching, run `agent-lynx wait-for-client` instead of polling `list-clients`.\n3. If this is unexpected, rerun with `DEBUG='devtool-mcp-server:connector*'` or try `--no-daemon` (HDT/Aiden discovery still takes precedence).\n\nRun `agent-lynx skills get lynx-devtool`, then read `references/troubleshooting/symptoms.md#list-clients-returns-` relative to the reported Skill directory.";
2078
2078
  const NO_CLIENTS_FOUND_MESSAGE = [
2079
2079
  noClientsSummary,
2080
2080
  noClientsHelp
@@ -2094,7 +2094,7 @@ async function listClientsAction(connector) {
2094
2094
  reason: "no-clients",
2095
2095
  recoverable: true,
2096
2096
  nextActions: [
2097
- "Make sure the target device/simulator and app are running, then retry.",
2097
+ "Make sure the target device/simulator and app are running, or run `agent-lynx wait-for-client` while launching.",
2098
2098
  "Retry with `--no-daemon` to run discovery in-process; HDT/Aiden still takes precedence over direct discovery."
2099
2099
  ]
2100
2100
  });
@@ -3207,7 +3207,7 @@ class ReactLynxController {
3207
3207
  throw new ReactLynxActionError(`No ReactLynx component mapping was returned for DOM uniqueId ${uniqueId} after ${result.framesSeen} frame(s) (types=${controller_envelopeTypes(result)}). The element may not be React-owned, or the App-side identity mapping may not be ready.`, {
3208
3208
  reason: "reactlynx-component-not-found",
3209
3209
  nextActions: [
3210
- "Retry after the page has settled, or run `agent-lynx reactlynx tree --refresh`."
3210
+ "Retry after the page has settled, or run `agent-lynx reactlynx tree`."
3211
3211
  ]
3212
3212
  });
3213
3213
  }
@@ -4715,7 +4715,7 @@ async function resolveTarget(action, params, connector, requirement) {
4715
4715
  if (!firstClient) return {
4716
4716
  ok: false,
4717
4717
  result: targetFailure(action, "No available clients found.", [
4718
- "Connect a Lynx client, then retry the command.",
4718
+ "Connect a Lynx client or run `agent-lynx wait-for-client` while launching.",
4719
4719
  "Run `agent-lynx list-clients` to verify discovery."
4720
4720
  ])
4721
4721
  };