@aixnn/aixautots 0.6.4 → 0.6.6

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.
Files changed (51) hide show
  1. package/dist/{automation-queue-BxrSIkG3.d.ts → automation-queue-aYRO9JLj.d.ts} +2 -2
  2. package/dist/{chunk-JTFZSFFA.js → chunk-7H4CYM42.js} +414 -5
  3. package/dist/{chunk-UJO7BJUV.js → chunk-A2CKXQ7U.js} +876 -106
  4. package/dist/{chunk-SAB5CH2K.js → chunk-AVRM42RS.js} +578 -141
  5. package/dist/{chunk-M4DO7SSZ.js → chunk-D7J4EQTA.js} +1 -1
  6. package/dist/{chunk-B2BOVLI6.js → chunk-F76N3GOA.js} +1077 -313
  7. package/dist/{chunk-Q63FQ7B5.js → chunk-LWTL4AIC.js} +254 -13
  8. package/dist/chunk-QZ3XJS2W.js +102 -0
  9. package/dist/{chunk-NGW34POA.js → chunk-SF5R25DU.js} +318 -15
  10. package/dist/{chunk-YFF7VLNT.js → chunk-SKTL6ACT.js} +40 -2
  11. package/dist/{chunk-T3QVYTOT.js → chunk-WUT5OUBG.js} +418 -0
  12. package/dist/{chunk-BYL2S2H6.js → chunk-X5KVYWUK.js} +4 -5
  13. package/dist/{config-CLi5IhmO.d.ts → config-B7t1Ln3w.d.ts} +177 -8
  14. package/dist/core/index.d.ts +21 -16
  15. package/dist/core/index.js +2 -4
  16. package/dist/{device-normalize-BaThgnH7.d.ts → device-normalize-CuGflfZA.d.ts} +1 -1
  17. package/dist/device-session-OFGN4KUD.js +1 -0
  18. package/dist/i18n/index.js +1 -1
  19. package/dist/{mirror-session-BP7Rd3Jk.d.ts → mirror-session-DK0OQvA3.d.ts} +11 -3
  20. package/dist/react/index.d.ts +10 -8
  21. package/dist/react/index.js +3 -6
  22. package/dist/{script-debugger-DtUGxK9i.d.ts → script-debugger-6hoLEwEz.d.ts} +1 -1
  23. package/dist/{task-agent-runner-DzV_OUZ7.d.ts → task-agent-runner-BwRW88rl.d.ts} +5 -3
  24. package/dist/{types-C2WXVcam.d.ts → types-BbtVr3QM.d.ts} +34 -3
  25. package/dist/ui/billing.d.ts +1 -1
  26. package/dist/ui/billing.js +5 -9
  27. package/dist/ui/device-create.d.ts +4 -3
  28. package/dist/ui/device-create.js +7 -9
  29. package/dist/ui/device-mirror.d.ts +16 -2
  30. package/dist/ui/device-mirror.js +6 -8
  31. package/dist/ui/devices.d.ts +5 -5
  32. package/dist/ui/devices.js +10 -13
  33. package/dist/ui/editor.d.ts +2 -2
  34. package/dist/ui/editor.js +7 -11
  35. package/dist/ui/index.d.ts +4 -4
  36. package/dist/ui/index.js +9 -15
  37. package/dist/ui/inspector.js +5 -9
  38. package/dist/ui/market.js +4 -7
  39. package/dist/ui/mirror.d.ts +3 -3
  40. package/dist/ui/primitives/index.d.ts +1 -1
  41. package/dist/ui/primitives/index.js +1 -2
  42. package/dist/ui/script-studio.js +6 -10
  43. package/dist/ui/scripts.d.ts +1 -1
  44. package/dist/ui/scripts.js +5 -9
  45. package/dist/ui/tasks.js +10 -13
  46. package/package.json +1 -1
  47. package/dist/chunk-A5VNENHD.js +0 -229
  48. package/dist/chunk-BUW45GM2.js +0 -341
  49. package/dist/chunk-H37NHOYU.js +0 -44
  50. package/dist/chunk-LAZ3RQ7X.js +0 -668
  51. package/dist/device-session-CVT7OY4H.js +0 -2
@@ -36,11 +36,13 @@ var AixError = class extends Error {
36
36
  this.code = code;
37
37
  this.status = opts?.status;
38
38
  this.detail = opts?.detail;
39
+ this.apiCode = opts?.apiCode;
40
+ this.requestState = opts?.requestState;
39
41
  }
40
42
  };
41
43
  var AixAuthError = class extends AixError {
42
- constructor(m) {
43
- super(m, "auth");
44
+ constructor(m, opts) {
45
+ super(m, "auth", opts);
44
46
  }
45
47
  };
46
48
  var AixTimeout = class extends AixError {
@@ -54,8 +56,8 @@ var AixDeviceOffline = class extends AixError {
54
56
  }
55
57
  };
56
58
  var AixLocked = class extends AixError {
57
- constructor(m) {
58
- super(m, "locked");
59
+ constructor(m, opts) {
60
+ super(m, "locked", opts);
59
61
  }
60
62
  };
61
63
  var AixProtocolError = class extends AixError {
@@ -69,43 +71,6 @@ function errorFromRet(error) {
69
71
  return new AixError(error);
70
72
  }
71
73
 
72
- // src/core/protocol.ts
73
- function parseIncoming(text) {
74
- let v;
75
- try {
76
- v = JSON.parse(text);
77
- } catch (e) {
78
- throw new AixProtocolError(`bad json frame: ${String(e)}`);
79
- }
80
- if (typeof v !== "object" || v === null) throw new AixProtocolError("frame must be an object");
81
- const o = v;
82
- const hasT = typeof o.t === "string";
83
- const hasExec = typeof o.run_id === "string" && o.event !== void 0;
84
- if (!hasT && !hasExec) throw new AixProtocolError("frame missing string `t`");
85
- return v;
86
- }
87
- function isRetFrame(f) {
88
- return f.t === "ret";
89
- }
90
- function isFridaEventFrame(f) {
91
- return f.t === "frida_event";
92
- }
93
- function isScriptletEventFrame(f) {
94
- return f.t === "scriptlet_event";
95
- }
96
- function isStatusFrame(f) {
97
- return f.t === "status";
98
- }
99
- function isExecutionFrame(f) {
100
- const e = f.event;
101
- return typeof f.run_id === "string" && typeof f.device_id === "string" && typeof e === "object" && e !== null && typeof e.kind === "string";
102
- }
103
- function isEnvEventFrame(f) {
104
- if (typeof f !== "object" || f === null) return false;
105
- const k = f.kind;
106
- return k === "started" || k === "step" || k === "log" || k === "finished";
107
- }
108
-
109
74
  // src/core/resources/auth-provider.ts
110
75
  var PROJECT_KEY_HEADER = "X-Project-Key";
111
76
  var PROJECT_SECRET_HEADER = "X-Project-Secret";
@@ -309,243 +274,26 @@ var ReconnectingSocket = class {
309
274
  }
310
275
  };
311
276
 
312
- // src/core/env-run.ts
313
- function envBody(action, input) {
314
- const os = input.os ?? "mac";
315
- const body = { os };
316
- if (action === "setup" && input.route) body.route = input.route;
317
- if (action === "teardown" && input.purge) body.purge = true;
318
- return body;
319
- }
320
- var EnvRun = class _EnvRun {
321
- constructor(reqId, stream, socket) {
322
- this.reqId = reqId;
323
- this.stream = stream;
324
- this.socket = socket;
325
- this.eventListeners = /* @__PURE__ */ new Set();
326
- this.doneListeners = /* @__PURE__ */ new Set();
327
- this.doneFired = false;
328
- this.last = null;
329
- this.cursor = 0;
330
- this.pollTimer = null;
331
- this.closed = false;
332
- // `start()` opens the socket before callers can register listeners. Keep
333
- // frames received in that small window so the first Started/Step events do
334
- // not disappear and leave progress UIs stuck at 0%.
335
- this.pendingEvents = [];
336
- }
337
- /** Trigger an env action on an owned node and start streaming its progress. */
338
- static async start(cfg, nodeId, action, input = {}) {
339
- const resolved = "fetchFn" in cfg ? cfg : resolveConfig(cfg);
340
- const url = joinUrl(resolved.baseUrl, `/api/nodes/${encodeURIComponent(nodeId)}/env/${action}`);
341
- const headers = { ...await resolved.auth.headers("caller"), "content-type": "application/json" };
342
- const resp = await resolved.fetchFn(url, {
343
- method: "POST",
344
- headers,
345
- body: JSON.stringify(envBody(action, input))
346
- });
347
- if (!resp.ok) {
348
- const t2 = await resp.text().catch(() => "");
349
- if (resp.status === 401 || resp.status === 403) throw new AixAuthError(`env ${action} ${resp.status}: ${t2}`);
350
- throw new AixError(`env ${action} ${resp.status}: ${t2}`);
351
- }
352
- const data = await resp.json();
353
- let run = null;
354
- let cursor = 0;
355
- let processing = Promise.resolve();
356
- const applyFrame = (frame) => {
357
- if (frame.run_id !== data.req_id) return;
358
- if (typeof frame.cursor !== "number") {
359
- run?.onMessage(JSON.stringify(frame.event));
360
- return;
361
- }
362
- if (frame.cursor <= cursor) return;
363
- cursor = frame.cursor;
364
- run?.onMessage(JSON.stringify({ cursor: frame.cursor, ...frame.event }));
365
- };
366
- const fetchCatchup = async (after) => {
367
- let nextAfter = after;
368
- do {
369
- const page = await executionStreamEventsAfter(resolved, data.req_id, nextAfter);
370
- for (const event of page.events) applyFrame(event);
371
- nextAfter = page.next_cursor ?? cursor;
372
- if (!page.has_more) break;
373
- } while (true);
374
- };
375
- const processFrame = async (frame) => {
376
- if (frame.run_id !== data.req_id) return;
377
- if (typeof frame.cursor !== "number") {
378
- run?.onMessage(JSON.stringify(frame.event));
379
- return;
380
- }
381
- if (frame.cursor <= cursor) return;
382
- if (frame.cursor > cursor + 1) {
383
- await fetchCatchup(cursor);
384
- }
385
- applyFrame(frame);
386
- };
387
- const socket = new ReconnectingSocket({
388
- // Fetch a new one-time ticket after every stream reconnect and resume
389
- // after the latest durable event cursor.
390
- urlProvider: async () => executionWsTicketUrl(resolved, data.req_id, cursor),
391
- wsFactory: resolved.wsFactory,
392
- onMessage: (text) => {
393
- let frame;
394
- try {
395
- frame = JSON.parse(text);
396
- } catch {
397
- return;
398
- }
399
- if (!frame.run_id || !frame.event) {
400
- run?.onMessage(text);
401
- return;
402
- }
403
- processing = processing.then(() => processFrame(frame)).catch(() => void 0);
404
- }
405
- });
406
- run = new _EnvRun(data.req_id, data.stream ?? `/ws/execution/${data.req_id}`, socket);
407
- const currentRun = run;
408
- let failures = 0;
409
- const poll = async () => {
410
- if (currentRun.closed) return;
411
- try {
412
- await (processing = processing.catch(() => void 0).then(() => fetchCatchup(cursor)));
413
- failures = 0;
414
- } catch (error) {
415
- if (++failures >= 3 && !currentRun.closed) {
416
- currentRun.onMessage(JSON.stringify({
417
- kind: "finished",
418
- ok: false,
419
- error: `Environment progress connection failed: ${String(error)}`,
420
- hint: "The node may still be installing. Check its status before starting setup again."
421
- }));
422
- }
423
- }
424
- if (!currentRun.closed) currentRun.pollTimer = setTimeout(() => {
425
- void poll();
426
- }, 3e3);
427
- };
428
- currentRun.pollTimer = setTimeout(() => {
429
- void poll();
430
- }, 3e3);
431
- try {
432
- await socket.start();
433
- } catch {
434
- }
435
- return run;
436
- }
437
- on(event, cb) {
438
- if (event === "event") {
439
- const fn2 = cb;
440
- this.eventListeners.add(fn2);
441
- if (this.pendingEvents.length > 0) {
442
- const pending = this.pendingEvents;
443
- this.pendingEvents = [];
444
- for (const ev of pending) fn2(ev);
445
- }
446
- return () => this.eventListeners.delete(fn2);
447
- }
448
- const fn = cb;
449
- this.doneListeners.add(fn);
450
- if (this.doneFired && this.last) {
451
- const f = this.last;
452
- queueMicrotask(() => fn(f));
453
- }
454
- return () => this.doneListeners.delete(fn);
455
- }
456
- onMessage(text) {
457
- let frame;
458
- try {
459
- frame = JSON.parse(text);
460
- } catch {
461
- return;
462
- }
463
- if (!isEnvEventFrame(frame)) return;
464
- const cursor = frame.cursor;
465
- if (typeof cursor === "number") {
466
- if (cursor <= this.cursor) return;
467
- this.cursor = cursor;
468
- }
469
- const ev = frame;
470
- if (this.eventListeners.size === 0) this.pendingEvents.push(ev);
471
- else for (const cb of this.eventListeners) cb(ev);
472
- if (ev.kind === "finished" && !this.doneFired) {
473
- this.doneFired = true;
474
- this.last = ev;
475
- for (const cb of this.doneListeners) cb(this.last);
476
- this.close();
477
- }
478
- }
479
- close() {
480
- this.closed = true;
481
- if (this.pollTimer !== null) {
482
- clearTimeout(this.pollTimer);
483
- this.pollTimer = null;
484
- }
485
- this.socket.close();
486
- }
487
- };
488
- var ENV_OK_STATES = /* @__PURE__ */ new Set(["ok", "skipped", "present", "done"]);
489
- var ENV_BAD_STATES = /* @__PURE__ */ new Set(["failed", "error"]);
490
- function summarizeEnv(events) {
491
- const meta = /* @__PURE__ */ new Map();
492
- const steps = /* @__PURE__ */ new Map();
493
- const logs = [];
494
- let total = 0;
495
- let finished = null;
496
- for (const e of events) {
497
- if (e.kind === "started") {
498
- total = e.total;
499
- e.steps.forEach((s, i) => {
500
- meta.set(i, s);
501
- const existing = steps.get(i);
502
- steps.set(i, existing ? { ...existing, label: s.label } : {
503
- index: i,
504
- id: s.id,
505
- label: s.label,
506
- state: "pending",
507
- pct: 0
508
- });
509
- });
510
- } else if (e.kind === "step") {
511
- const m = meta.get(e.index);
512
- steps.set(e.index, {
513
- index: e.index,
514
- id: e.id,
515
- label: m?.label ?? e.id,
516
- state: e.state,
517
- pct: e.pct,
518
- detail: e.detail
519
- });
520
- } else if (e.kind === "log") {
521
- logs.push(`${e.id}: ${e.line}`);
522
- } else if (e.kind === "finished") {
523
- finished = e;
524
- }
277
+ // src/core/webrtc-rest.ts
278
+ async function getIceServers(cfg) {
279
+ const url = joinUrl(cfg.baseUrl, "/api/ice");
280
+ const resp = await cfg.fetchFn(url, { headers: { ...await cfg.auth.headers("caller") } });
281
+ if (!resp.ok) {
282
+ if (resp.status === 401 || resp.status === 403) throw new AixAuthError(`ice ${resp.status}`);
283
+ throw new AixError(`ice ${resp.status}`);
525
284
  }
526
- const list = [...steps.values()].sort((a, b) => a.index - b.index);
527
- const anyBad = list.some((s) => ENV_BAD_STATES.has(s.state));
528
- const allGood = list.length > 0 && list.every((s) => ENV_OK_STATES.has(s.state));
529
- const ready = finished ? finished.ok && !anyBad && (allGood || !!finished.result?.docker_socket) : false;
530
- return { total: total || list.length, steps: list, logs, finished, ready, running: !finished && events.length > 0 };
531
- }
532
- function envBlocker(finished) {
533
- if (finished && !finished.ok && finished.code === "WSL_UNAVAILABLE") return "wsl-missing";
534
- return null;
285
+ const data = await resp.json();
286
+ return data.iceServers ?? [];
535
287
  }
536
- function detectEnvOs() {
537
- const ua = typeof navigator !== "undefined" && (navigator.userAgent || navigator.platform) || "";
538
- if (/win/i.test(ua)) return "win";
539
- if (/mac|darwin|iphone|ipad/i.test(ua)) return "mac";
540
- return null;
541
- }
542
- async function runEnvToFinish(cfg, nodeId, action, input = {}) {
543
- const run = await EnvRun.start(cfg, nodeId, action, input);
544
- const events = [];
545
- return new Promise((resolve) => {
546
- run.on("event", (e) => events.push(e));
547
- run.on("done", () => resolve(summarizeEnv(events)));
548
- });
288
+ async function mintViewerToken(cfg, session) {
289
+ const url = joinUrl(cfg.baseUrl, "/api/signal/tokens");
290
+ const headers = { ...await cfg.auth.headers("caller"), "content-type": "application/json" };
291
+ const resp = await cfg.fetchFn(url, { method: "POST", headers, body: JSON.stringify({ session }) });
292
+ if (!resp.ok) {
293
+ if (resp.status === 401 || resp.status === 403) throw new AixAuthError(`signal token ${resp.status}`);
294
+ throw new AixError(`signal token ${resp.status}`);
295
+ }
296
+ return (await resp.json()).token;
549
297
  }
550
298
 
551
299
  // src/core/resources/http.ts
@@ -579,7 +327,7 @@ var RestClient = class {
579
327
  }
580
328
  let resp;
581
329
  try {
582
- resp = await this.cfg.fetchFn(url, { method, headers, body });
330
+ resp = await this.cfg.fetchFn(url, { method, headers, body, ...opts.signal ? { signal: opts.signal } : {} });
583
331
  } catch (e) {
584
332
  if (e instanceof AixError) throw e;
585
333
  throw new AixError(`${method} ${path} request failed: ${String(e)}`, "offline");
@@ -587,15 +335,24 @@ var RestClient = class {
587
335
  if (!resp.ok) {
588
336
  const text = await resp.text().catch(() => "");
589
337
  let detail;
338
+ let apiCode;
339
+ let requestState;
590
340
  try {
591
341
  const j = JSON.parse(text);
592
- const m = typeof j.message === "string" ? j.message : typeof j.error === "string" ? j.error : void 0;
342
+ const error = j.error && typeof j.error === "object" ? j.error : j;
343
+ const m = typeof error.message === "string" ? error.message : typeof j.error === "string" ? j.error : void 0;
593
344
  detail = m || void 0;
345
+ apiCode = typeof error.code === "string" ? error.code : void 0;
346
+ const state = error.request_state ?? j.request_state;
347
+ requestState = state === "rejected" || state === "unknown" ? state : void 0;
594
348
  } catch {
595
349
  }
596
- if (resp.status === 401 || resp.status === 403) throw new AixAuthError(`${method} ${path} ${resp.status}: ${text}`);
597
- if (resp.status === 423) throw new AixLocked(`${method} ${path} 423: ${text}`);
598
- throw new AixError(detail ?? `${method} ${path} ${resp.status}: ${text}`, "unknown", { status: resp.status, detail });
350
+ const requestHeader = resp.headers.get?.("X-Proxy-Request-State");
351
+ if (requestHeader === "rejected" || requestHeader === "unknown") requestState = requestHeader;
352
+ const details = { status: resp.status, detail, apiCode, requestState };
353
+ if (resp.status === 401 || resp.status === 403) throw new AixAuthError(detail ?? `${method} ${path} ${resp.status}: ${text}`, details);
354
+ if (resp.status === 423) throw new AixLocked(detail ?? `${method} ${path} 423: ${text}`, details);
355
+ throw new AixError(detail ?? `${method} ${path} ${resp.status}: ${text}`, "unknown", details);
599
356
  }
600
357
  if (resp.status === 204) return void 0;
601
358
  const ct = resp.headers.get?.("content-type") ?? "";
@@ -683,8 +440,8 @@ var DevicesApi = class {
683
440
  constructor(c) {
684
441
  this.c = c;
685
442
  }
686
- list() {
687
- return this.c.get("/api/devices");
443
+ list(options) {
444
+ return this.c.get("/api/devices", options);
688
445
  }
689
446
  /** Register/upsert a device (`POST /api/devices`). */
690
447
  register(body) {
@@ -704,8 +461,8 @@ var DevicesApi = class {
704
461
  /** The single generic live-op entry point, proxied to the owning node. Any
705
462
  * node-supported op works here without a dedicated method; the typed helpers
706
463
  * below are thin wrappers over it. */
707
- op(deviceId, op) {
708
- return this.c.post(`/api/devices/${encodeURIComponent(deviceId)}/op`, op);
464
+ op(deviceId, op, options) {
465
+ return this.c.post(`/api/devices/${encodeURIComponent(deviceId)}/op`, op, options);
709
466
  }
710
467
  screenshot(deviceId) {
711
468
  return this.op(deviceId, { op: "screenshot" });
@@ -721,6 +478,21 @@ var DevicesApi = class {
721
478
  power(deviceId, action, extra) {
722
479
  return this.c.post(`/api/devices/${encodeURIComponent(deviceId)}/power`, { action, ...extra });
723
480
  }
481
+ /** List all user data snapshots, including while the device is offline. */
482
+ listSnapshots(deviceId) {
483
+ return this.c.get(`/api/devices/${encodeURIComponent(deviceId)}/snapshots`);
484
+ }
485
+ /** Save current data under a new server-generated identifier. */
486
+ createSnapshot(deviceId, input) {
487
+ return this.c.post(`/api/devices/${encodeURIComponent(deviceId)}/snapshots`, input);
488
+ }
489
+ /** Load saved data; replaces unsaved working data and restarts the device. */
490
+ loadSnapshot(deviceId, name) {
491
+ return this.c.post(`/api/devices/${encodeURIComponent(deviceId)}/snapshots/${encodeURIComponent(name)}/load`, {});
492
+ }
493
+ deleteSnapshot(deviceId, name) {
494
+ return this.c.del(`/api/devices/${encodeURIComponent(deviceId)}/snapshots/${encodeURIComponent(name)}`);
495
+ }
724
496
  /** Typed device-control op via the power lane (install / inject / screen-record). */
725
497
  control(deviceId, op) {
726
498
  return this.power(deviceId, "control", { op });
@@ -778,10 +550,9 @@ var DevicesApi = class {
778
550
  return this.c.del("/api/devices/recycle");
779
551
  }
780
552
  /** Update mutable device fields — `PATCH /api/devices/:id`.
781
- * `ios_transport` switches an iOS device's live-mirror VIDEO source
782
- * (`replaykit` device-app WebRTC, default | `iosusbadapter` host screenshot
783
- * over usbmux, driven by go-ios); control is always host-mediated and
784
- * unaffected. (Legacy value `pymobiledevice3` was renamed to `iosusbadapter`.)
553
+ * `ios_transport` is a legacy stored preference, not an active video-source
554
+ * switch. Changes return 501 until runtime selection is implemented;
555
+ * sending the already stored value is an idempotent no-op.
785
556
  * `sleep_timeout_min` sets the inactivity sleep timeout (0 = disabled). */
786
557
  update(deviceId, patch) {
787
558
  return this.c.patch(`/api/devices/${encodeURIComponent(deviceId)}`, patch);
@@ -866,7 +637,283 @@ var DevicesApi = class {
866
637
  dcSession(deviceId) {
867
638
  return this.c.post(`/api/devices/${encodeURIComponent(deviceId)}/dc-session`, {});
868
639
  }
869
- };
640
+ };
641
+
642
+ // src/core/protocol.ts
643
+ function parseIncoming(text) {
644
+ let v;
645
+ try {
646
+ v = JSON.parse(text);
647
+ } catch (e) {
648
+ throw new AixProtocolError(`bad json frame: ${String(e)}`);
649
+ }
650
+ if (typeof v !== "object" || v === null) throw new AixProtocolError("frame must be an object");
651
+ const o = v;
652
+ const hasT = typeof o.t === "string";
653
+ const hasExec = typeof o.run_id === "string" && o.event !== void 0;
654
+ if (!hasT && !hasExec) throw new AixProtocolError("frame missing string `t`");
655
+ return v;
656
+ }
657
+ function isRetFrame(f) {
658
+ return f.t === "ret";
659
+ }
660
+ function isFridaEventFrame(f) {
661
+ return f.t === "frida_event";
662
+ }
663
+ function isScriptletEventFrame(f) {
664
+ return f.t === "scriptlet_event";
665
+ }
666
+ function isStatusFrame(f) {
667
+ return f.t === "status";
668
+ }
669
+ function isExecutionFrame(f) {
670
+ const e = f.event;
671
+ return typeof f.run_id === "string" && typeof f.device_id === "string" && typeof e === "object" && e !== null && typeof e.kind === "string";
672
+ }
673
+ function isEnvEventFrame(f) {
674
+ if (typeof f !== "object" || f === null) return false;
675
+ const k = f.kind;
676
+ return k === "started" || k === "step" || k === "log" || k === "finished";
677
+ }
678
+
679
+ // src/core/env-run.ts
680
+ function envBody(action, input) {
681
+ const os = input.os ?? "mac";
682
+ const body = { os };
683
+ if (action === "setup" && input.route) body.route = input.route;
684
+ if (action === "teardown" && input.purge) body.purge = true;
685
+ return body;
686
+ }
687
+ var EnvRun = class _EnvRun {
688
+ constructor(reqId, stream, socket) {
689
+ this.reqId = reqId;
690
+ this.stream = stream;
691
+ this.socket = socket;
692
+ this.eventListeners = /* @__PURE__ */ new Set();
693
+ this.doneListeners = /* @__PURE__ */ new Set();
694
+ this.doneFired = false;
695
+ this.last = null;
696
+ this.cursor = 0;
697
+ this.pollTimer = null;
698
+ this.closed = false;
699
+ // `start()` opens the socket before callers can register listeners. Keep
700
+ // frames received in that small window so the first Started/Step events do
701
+ // not disappear and leave progress UIs stuck at 0%.
702
+ this.pendingEvents = [];
703
+ }
704
+ /** Trigger an env action on an owned node and start streaming its progress. */
705
+ static async start(cfg, nodeId, action, input = {}) {
706
+ const resolved = "fetchFn" in cfg ? cfg : resolveConfig(cfg);
707
+ const url = joinUrl(resolved.baseUrl, `/api/nodes/${encodeURIComponent(nodeId)}/env/${action}`);
708
+ const headers = { ...await resolved.auth.headers("caller"), "content-type": "application/json" };
709
+ const resp = await resolved.fetchFn(url, {
710
+ method: "POST",
711
+ headers,
712
+ body: JSON.stringify(envBody(action, input))
713
+ });
714
+ if (!resp.ok) {
715
+ const t2 = await resp.text().catch(() => "");
716
+ if (resp.status === 401 || resp.status === 403) throw new AixAuthError(`env ${action} ${resp.status}: ${t2}`);
717
+ throw new AixError(`env ${action} ${resp.status}: ${t2}`);
718
+ }
719
+ const data = await resp.json();
720
+ let run = null;
721
+ let cursor = 0;
722
+ let processing = Promise.resolve();
723
+ const applyFrame = (frame) => {
724
+ if (frame.run_id !== data.req_id) return;
725
+ if (typeof frame.cursor !== "number") {
726
+ run?.onMessage(JSON.stringify(frame.event));
727
+ return;
728
+ }
729
+ if (frame.cursor <= cursor) return;
730
+ cursor = frame.cursor;
731
+ run?.onMessage(JSON.stringify({ cursor: frame.cursor, ...frame.event }));
732
+ };
733
+ const fetchCatchup = async (after) => {
734
+ let nextAfter = after;
735
+ do {
736
+ const page = await executionStreamEventsAfter(resolved, data.req_id, nextAfter);
737
+ for (const event of page.events) applyFrame(event);
738
+ nextAfter = page.next_cursor ?? cursor;
739
+ if (!page.has_more) break;
740
+ } while (true);
741
+ };
742
+ const processFrame = async (frame) => {
743
+ if (frame.run_id !== data.req_id) return;
744
+ if (typeof frame.cursor !== "number") {
745
+ run?.onMessage(JSON.stringify(frame.event));
746
+ return;
747
+ }
748
+ if (frame.cursor <= cursor) return;
749
+ if (frame.cursor > cursor + 1) {
750
+ await fetchCatchup(cursor);
751
+ }
752
+ applyFrame(frame);
753
+ };
754
+ const socket = new ReconnectingSocket({
755
+ // Fetch a new one-time ticket after every stream reconnect and resume
756
+ // after the latest durable event cursor.
757
+ urlProvider: async () => executionWsTicketUrl(resolved, data.req_id, cursor),
758
+ wsFactory: resolved.wsFactory,
759
+ onMessage: (text) => {
760
+ let frame;
761
+ try {
762
+ frame = JSON.parse(text);
763
+ } catch {
764
+ return;
765
+ }
766
+ if (!frame.run_id || !frame.event) {
767
+ run?.onMessage(text);
768
+ return;
769
+ }
770
+ processing = processing.then(() => processFrame(frame)).catch(() => void 0);
771
+ }
772
+ });
773
+ run = new _EnvRun(data.req_id, data.stream ?? `/ws/execution/${data.req_id}`, socket);
774
+ const currentRun = run;
775
+ let failures = 0;
776
+ const poll = async () => {
777
+ if (currentRun.closed) return;
778
+ try {
779
+ await (processing = processing.catch(() => void 0).then(() => fetchCatchup(cursor)));
780
+ failures = 0;
781
+ } catch (error) {
782
+ if (++failures >= 3 && !currentRun.closed) {
783
+ currentRun.onMessage(JSON.stringify({
784
+ kind: "finished",
785
+ ok: false,
786
+ error: `Environment progress connection failed: ${String(error)}`,
787
+ hint: "The node may still be installing. Check its status before starting setup again."
788
+ }));
789
+ }
790
+ }
791
+ if (!currentRun.closed) currentRun.pollTimer = setTimeout(() => {
792
+ void poll();
793
+ }, 3e3);
794
+ };
795
+ currentRun.pollTimer = setTimeout(() => {
796
+ void poll();
797
+ }, 3e3);
798
+ try {
799
+ await socket.start();
800
+ } catch {
801
+ }
802
+ return run;
803
+ }
804
+ on(event, cb) {
805
+ if (event === "event") {
806
+ const fn2 = cb;
807
+ this.eventListeners.add(fn2);
808
+ if (this.pendingEvents.length > 0) {
809
+ const pending = this.pendingEvents;
810
+ this.pendingEvents = [];
811
+ for (const ev of pending) fn2(ev);
812
+ }
813
+ return () => this.eventListeners.delete(fn2);
814
+ }
815
+ const fn = cb;
816
+ this.doneListeners.add(fn);
817
+ if (this.doneFired && this.last) {
818
+ const f = this.last;
819
+ queueMicrotask(() => fn(f));
820
+ }
821
+ return () => this.doneListeners.delete(fn);
822
+ }
823
+ onMessage(text) {
824
+ let frame;
825
+ try {
826
+ frame = JSON.parse(text);
827
+ } catch {
828
+ return;
829
+ }
830
+ if (!isEnvEventFrame(frame)) return;
831
+ const cursor = frame.cursor;
832
+ if (typeof cursor === "number") {
833
+ if (cursor <= this.cursor) return;
834
+ this.cursor = cursor;
835
+ }
836
+ const ev = frame;
837
+ if (this.eventListeners.size === 0) this.pendingEvents.push(ev);
838
+ else for (const cb of this.eventListeners) cb(ev);
839
+ if (ev.kind === "finished" && !this.doneFired) {
840
+ this.doneFired = true;
841
+ this.last = ev;
842
+ for (const cb of this.doneListeners) cb(this.last);
843
+ this.close();
844
+ }
845
+ }
846
+ close() {
847
+ this.closed = true;
848
+ if (this.pollTimer !== null) {
849
+ clearTimeout(this.pollTimer);
850
+ this.pollTimer = null;
851
+ }
852
+ this.socket.close();
853
+ }
854
+ };
855
+ var ENV_OK_STATES = /* @__PURE__ */ new Set(["ok", "skipped", "present", "done"]);
856
+ var ENV_BAD_STATES = /* @__PURE__ */ new Set(["failed", "error"]);
857
+ function summarizeEnv(events) {
858
+ const meta = /* @__PURE__ */ new Map();
859
+ const steps = /* @__PURE__ */ new Map();
860
+ const logs = [];
861
+ let total = 0;
862
+ let finished = null;
863
+ for (const e of events) {
864
+ if (e.kind === "started") {
865
+ total = e.total;
866
+ e.steps.forEach((s, i) => {
867
+ meta.set(i, s);
868
+ const existing = steps.get(i);
869
+ steps.set(i, existing ? { ...existing, label: s.label } : {
870
+ index: i,
871
+ id: s.id,
872
+ label: s.label,
873
+ state: "pending",
874
+ pct: 0
875
+ });
876
+ });
877
+ } else if (e.kind === "step") {
878
+ const m = meta.get(e.index);
879
+ steps.set(e.index, {
880
+ index: e.index,
881
+ id: e.id,
882
+ label: m?.label ?? e.id,
883
+ state: e.state,
884
+ pct: e.pct,
885
+ detail: e.detail
886
+ });
887
+ } else if (e.kind === "log") {
888
+ logs.push(`${e.id}: ${e.line}`);
889
+ } else if (e.kind === "finished") {
890
+ finished = e;
891
+ }
892
+ }
893
+ const list = [...steps.values()].sort((a, b) => a.index - b.index);
894
+ const anyBad = list.some((s) => ENV_BAD_STATES.has(s.state));
895
+ const allGood = list.length > 0 && list.every((s) => ENV_OK_STATES.has(s.state));
896
+ const ready = finished ? finished.ok && !anyBad && (allGood || !!finished.result?.docker_socket) : false;
897
+ return { total: total || list.length, steps: list, logs, finished, ready, running: !finished && events.length > 0 };
898
+ }
899
+ function envBlocker(finished) {
900
+ if (finished && !finished.ok && finished.code === "WSL_UNAVAILABLE") return "wsl-missing";
901
+ return null;
902
+ }
903
+ function detectEnvOs() {
904
+ const ua = typeof navigator !== "undefined" && (navigator.userAgent || navigator.platform) || "";
905
+ if (/win/i.test(ua)) return "win";
906
+ if (/mac|darwin|iphone|ipad/i.test(ua)) return "mac";
907
+ return null;
908
+ }
909
+ async function runEnvToFinish(cfg, nodeId, action, input = {}) {
910
+ const run = await EnvRun.start(cfg, nodeId, action, input);
911
+ const events = [];
912
+ return new Promise((resolve) => {
913
+ run.on("event", (e) => events.push(e));
914
+ run.on("done", () => resolve(summarizeEnv(events)));
915
+ });
916
+ }
870
917
 
871
918
  // src/core/resources/nodes.ts
872
919
  var NodesApi = class {
@@ -967,6 +1014,29 @@ var NodesApi = class {
967
1014
  iosWifi(nodeId, udid, enable) {
968
1015
  return this.c.post(`/api/nodes/${nodeId}/ios/control`, { op: "wifi", udid, enable });
969
1016
  }
1017
+ /** Read current device stages; transport reachability is distinct from WDA readiness. */
1018
+ iosDiagnostics(nodeId, udid) {
1019
+ return this.iosLifecycle(nodeId, udid, "diagnostics", 7e4);
1020
+ }
1021
+ /** Explicit preparation can install configured signed assets. Never auto-retried. */
1022
+ iosWdaPrepare(nodeId, udid) {
1023
+ return this.iosLifecycle(nodeId, udid, "wda_prepare", 915e3);
1024
+ }
1025
+ iosWdaStart(nodeId, udid) {
1026
+ return this.iosLifecycle(nodeId, udid, "wda_start", 105e3);
1027
+ }
1028
+ iosWdaStop(nodeId, udid) {
1029
+ return this.iosLifecycle(nodeId, udid, "wda_stop", 105e3);
1030
+ }
1031
+ async iosLifecycle(nodeId, udid, op, timeoutMs) {
1032
+ const controller = new AbortController();
1033
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1034
+ try {
1035
+ return await this.c.post(`/api/nodes/${encodeURIComponent(nodeId)}/ios/control`, { op, udid }, { signal: controller.signal });
1036
+ } finally {
1037
+ clearTimeout(timer);
1038
+ }
1039
+ }
970
1040
  // ── iOS App Store account + library ──
971
1041
  /** 节点 iOS App Store 账号状态(`{op:'account_info'}`)。 */
972
1042
  iosAccount(nodeId) {
@@ -1247,6 +1317,10 @@ var AdminApi = class {
1247
1317
  constructor(c) {
1248
1318
  this.c = c;
1249
1319
  }
1320
+ /** Read-only partner credential identity and catalog health; never returns a token. */
1321
+ proxyIntegration() {
1322
+ return this.c.get("/api/admin/proxies/integration", { scope: "admin" });
1323
+ }
1250
1324
  // rates
1251
1325
  listRates() {
1252
1326
  return this.c.get("/api/admin/rates", { scope: "admin" });
@@ -1336,6 +1410,52 @@ var BillingApi = class {
1336
1410
  }
1337
1411
  };
1338
1412
 
1413
+ // src/core/resources/proxies.ts
1414
+ var ManagedProxiesApi = class {
1415
+ constructor(c) {
1416
+ this.c = c;
1417
+ }
1418
+ creationQuote(input, opts) {
1419
+ return this.c.post("/api/proxies/creation-quotes", input, opts);
1420
+ }
1421
+ create(input, opts) {
1422
+ return this.c.post("/api/proxies/creations", input, opts);
1423
+ }
1424
+ creations(opts) {
1425
+ return this.c.get("/api/proxies/creations", { ...opts, query: { active: true } });
1426
+ }
1427
+ creationByRequest(requestId, opts) {
1428
+ return this.c.get(`/api/proxies/creations/by-request/${encodeURIComponent(requestId)}`, opts);
1429
+ }
1430
+ catalog(opts) {
1431
+ return this.c.get("/api/proxies/catalog", opts);
1432
+ }
1433
+ quote(input) {
1434
+ return this.c.post("/api/proxies/quotes", input);
1435
+ }
1436
+ purchase(input) {
1437
+ return this.c.post("/api/proxies/orders", input);
1438
+ }
1439
+ list(deviceId, options = {}) {
1440
+ return this.c.get("/api/proxies/orders", { query: { device_id: deviceId, active: options.active } });
1441
+ }
1442
+ byRequest(deviceId, requestId) {
1443
+ return this.c.get(`/api/proxies/orders/by-request/${encodeURIComponent(requestId)}`, { query: { device_id: deviceId } });
1444
+ }
1445
+ get(id) {
1446
+ return this.c.get(`/api/proxies/orders/${encodeURIComponent(id)}`);
1447
+ }
1448
+ rotate(id, requestId) {
1449
+ return this.c.post(`/api/proxies/orders/${encodeURIComponent(id)}/rotate`, { request_id: requestId });
1450
+ }
1451
+ apply(id, requestId) {
1452
+ return this.c.post(`/api/proxies/orders/${encodeURIComponent(id)}/apply`, { request_id: requestId });
1453
+ }
1454
+ release(id, requestId) {
1455
+ return this.c.post(`/api/proxies/orders/${encodeURIComponent(id)}/release`, { request_id: requestId });
1456
+ }
1457
+ };
1458
+
1339
1459
  // src/core/resources/tokens.ts
1340
1460
  var ApiTokensApi = class {
1341
1461
  constructor(c) {
@@ -1359,6 +1479,26 @@ var ApiTokensApi = class {
1359
1479
  }
1360
1480
  };
1361
1481
 
1482
+ // src/core/resources/app-templates.ts
1483
+ var AppTemplatesApi = class {
1484
+ constructor(c) {
1485
+ this.c = c;
1486
+ }
1487
+ list(platform) {
1488
+ const q = platform ? `?platform=${platform}` : "";
1489
+ return this.c.get(`/api/app-templates${q}`);
1490
+ }
1491
+ create(body) {
1492
+ return this.c.post("/api/app-templates", body);
1493
+ }
1494
+ update(id, body) {
1495
+ return this.c.put(`/api/app-templates/${encodeURIComponent(id)}`, body);
1496
+ }
1497
+ remove(id) {
1498
+ return this.c.del(`/api/app-templates/${encodeURIComponent(id)}`);
1499
+ }
1500
+ };
1501
+
1362
1502
  // src/core/local-node.ts
1363
1503
  function validatedBackendUrl(base) {
1364
1504
  base = base.trim();
@@ -1503,26 +1643,6 @@ var LocalNodeController = class {
1503
1643
  }
1504
1644
  };
1505
1645
 
1506
- // src/core/resources/app-templates.ts
1507
- var AppTemplatesApi = class {
1508
- constructor(c) {
1509
- this.c = c;
1510
- }
1511
- list(platform) {
1512
- const q = platform ? `?platform=${platform}` : "";
1513
- return this.c.get(`/api/app-templates${q}`);
1514
- }
1515
- create(body) {
1516
- return this.c.post("/api/app-templates", body);
1517
- }
1518
- update(id, body) {
1519
- return this.c.put(`/api/app-templates/${encodeURIComponent(id)}`, body);
1520
- }
1521
- remove(id) {
1522
- return this.c.del(`/api/app-templates/${encodeURIComponent(id)}`);
1523
- }
1524
- };
1525
-
1526
1646
  // src/core/resources/client.ts
1527
1647
  var AixClient = class {
1528
1648
  constructor(cfg) {
@@ -1544,6 +1664,7 @@ var AixClient = class {
1544
1664
  this.admin = new AdminApi(this.http);
1545
1665
  this.images = new ImagesApi(this.http);
1546
1666
  this.billing = new BillingApi(this.http);
1667
+ this.proxies = new ManagedProxiesApi(this.http);
1547
1668
  this.tokens = new ApiTokensApi(this.http);
1548
1669
  this.appTemplates = new AppTemplatesApi(this.http);
1549
1670
  if (this.cfg.localNode) {
@@ -1561,12 +1682,655 @@ var AixClient = class {
1561
1682
  * 即可,不必回依赖 client 实例)。
1562
1683
  */
1563
1684
  async deviceSession(deviceId, opts = {}) {
1564
- const { DeviceSession } = await import('./device-session-CVT7OY4H.js');
1565
- return DeviceSession.open(this.cfg, deviceId, opts);
1685
+ const { DeviceSession: DeviceSession2 } = await import('./device-session-OFGN4KUD.js');
1686
+ return DeviceSession2.open(this.cfg, deviceId, opts);
1566
1687
  }
1567
1688
  };
1568
1689
  function createClient(cfg) {
1569
1690
  return new AixClient(cfg);
1570
1691
  }
1571
1692
 
1572
- export { AdminApi, AixAuthError, AixClient, AixDeviceOffline, AixError, AixLocked, AixProtocolError, AixTimeout, ApiTokensApi, AuthApi, BillingApi, ClustersApi, DevicesApi, EnvRun, FleetApi, ImagesApi, LlmApi, LocalNodeController, LocatorsApi, NodesApi, ProjectsApi, ReconnectingSocket, RestClient, ScriptsApi, ShortcutsApi, TasksApi, UsersApi, WebhooksApi, authHeader, buildAuthProvider, createCachedUserCredential, createClient, detectEnvOs, envBlocker, errorFromRet, executionStreamEventsAfter, executionWsTicketUrl, executionWsUrl, getLocale, isEnvEventFrame, isExecutionFrame, isFleetRunTerminal, isFridaEventFrame, isRetFrame, isScriptletEventFrame, isStatusFrame, joinUrl, parseIncoming, resolveConfig, restClient, runEnvToFinish, setLocale, summarizeEnv, t };
1693
+ // src/core/device-session.ts
1694
+ var CHUNK_SIZE = 64 * 1024;
1695
+ var BUFFER_HIGH = 4 * 1024 * 1024;
1696
+ var BUFFER_LOW = 1 * 1024 * 1024;
1697
+ var DC_CONNECT_TIMEOUT_MS = 15e3;
1698
+ function toCtx(source) {
1699
+ if (source instanceof AixClient) {
1700
+ return { cfg: source.cfg, devices: source.devices };
1701
+ }
1702
+ const cfg = "fetchFn" in source && typeof source.fetchFn === "function" ? source : resolveConfig(source);
1703
+ return { cfg, devices: new DevicesApi(new RestClient(cfg)) };
1704
+ }
1705
+ function asBytes(data) {
1706
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
1707
+ }
1708
+ function asArrayBuffer(bytes) {
1709
+ if (bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength) {
1710
+ return bytes.buffer;
1711
+ }
1712
+ return bytes.slice().buffer;
1713
+ }
1714
+ async function sha256Hex(bytes) {
1715
+ const subtle = globalThis.crypto?.subtle;
1716
+ if (!subtle) throw new AixError("crypto.subtle unavailable: cannot hash file (need browser or Node 18+)");
1717
+ const digest = await subtle.digest("SHA-256", asArrayBuffer(bytes));
1718
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1719
+ }
1720
+ var B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1721
+ function bytesToBase64(bytes) {
1722
+ const B = globalThis.Buffer;
1723
+ if (B) return B.from(bytes).toString("base64");
1724
+ const c = (n) => B64_CHARS[n & 63];
1725
+ let out = "";
1726
+ let i = 0;
1727
+ for (; i + 2 < bytes.length; i += 3) {
1728
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
1729
+ out += c(n >> 18) + c(n >> 12) + c(n >> 6) + c(n);
1730
+ }
1731
+ const rem = bytes.length - i;
1732
+ if (rem === 1) {
1733
+ const n = bytes[i] << 16;
1734
+ out += c(n >> 18) + c(n >> 12) + "==";
1735
+ } else if (rem === 2) {
1736
+ const n = bytes[i] << 16 | bytes[i + 1] << 8;
1737
+ out += c(n >> 18) + c(n >> 12) + c(n >> 6) + "=";
1738
+ }
1739
+ return out;
1740
+ }
1741
+ var B64_LOOKUP = (() => {
1742
+ const t2 = new Int16Array(256).fill(-1);
1743
+ for (let i = 0; i < B64_CHARS.length; i++) t2[B64_CHARS.charCodeAt(i)] = i;
1744
+ return t2;
1745
+ })();
1746
+ function base64ToBytes(b64) {
1747
+ const B = globalThis.Buffer;
1748
+ if (B) return Uint8Array.from(B.from(b64, "base64"));
1749
+ let len = b64.length;
1750
+ while (len > 0 && b64[len - 1] === "=") len--;
1751
+ const outLen = len * 3 >> 2;
1752
+ const out = new Uint8Array(outLen);
1753
+ let acc = 0;
1754
+ let bits = 0;
1755
+ let o = 0;
1756
+ for (let i = 0; i < len; i++) {
1757
+ const v = B64_LOOKUP[b64.charCodeAt(i)] ?? -1;
1758
+ if (v < 0) continue;
1759
+ acc = acc << 6 | v;
1760
+ bits += 6;
1761
+ if (bits >= 8) {
1762
+ bits -= 8;
1763
+ out[o++] = acc >> bits & 255;
1764
+ }
1765
+ }
1766
+ return out;
1767
+ }
1768
+ function waitForDrain(dc) {
1769
+ const cur = dc.bufferedAmount;
1770
+ if (cur == null || cur <= BUFFER_LOW) return Promise.resolve();
1771
+ if (!("onbufferedamountlow" in dc)) return Promise.resolve();
1772
+ return new Promise((resolve) => {
1773
+ dc.bufferedAmountLowThreshold = BUFFER_LOW;
1774
+ dc.onbufferedamountlow = () => {
1775
+ dc.onbufferedamountlow = null;
1776
+ resolve();
1777
+ };
1778
+ });
1779
+ }
1780
+ async function openCtrlChannel(cfg, session, timeoutMs) {
1781
+ const iceServers = await getIceServers(cfg);
1782
+ const token = await mintViewerToken(cfg, session);
1783
+ const pc = cfg.rtcFactory({ iceServers });
1784
+ let selfPeer = null;
1785
+ let remotePeer = null;
1786
+ let ctrl = null;
1787
+ let remoteDescriptionReady = false;
1788
+ const pendingIce = [];
1789
+ const signalUrl = joinUrl(cfg.baseUrl, "/ws/signal").replace(/^http/, "ws");
1790
+ let socket;
1791
+ const send = (msg) => {
1792
+ try {
1793
+ socket.send(JSON.stringify(msg));
1794
+ } catch {
1795
+ }
1796
+ };
1797
+ pc.onicecandidate = (ev) => {
1798
+ if (ev.candidate && remotePeer) send({ type: "ice", session, to: remotePeer, candidate: ev.candidate });
1799
+ };
1800
+ pc.ondatachannel = (ev) => {
1801
+ if (ev.channel.label === "ctrl" || !ctrl) {
1802
+ ctrl = ev.channel;
1803
+ ctrl.binaryType = "arraybuffer";
1804
+ }
1805
+ };
1806
+ const onSignal = async (text) => {
1807
+ let m;
1808
+ try {
1809
+ m = JSON.parse(text);
1810
+ } catch {
1811
+ return;
1812
+ }
1813
+ switch (m.type) {
1814
+ case "welcome":
1815
+ selfPeer = m.peer_id ?? null;
1816
+ break;
1817
+ case "peers": {
1818
+ const node = (m.members ?? []).find((p) => p !== selfPeer);
1819
+ if (node && !remotePeer) remotePeer = node;
1820
+ break;
1821
+ }
1822
+ case "offer":
1823
+ if (m.sdp && m.from) {
1824
+ remotePeer = m.from;
1825
+ await pc.setRemoteDescription({ type: "offer", sdp: m.sdp });
1826
+ remoteDescriptionReady = true;
1827
+ for (const candidate of pendingIce.splice(0)) await pc.addIceCandidate(candidate);
1828
+ const answer = await pc.createAnswer();
1829
+ await pc.setLocalDescription(answer);
1830
+ send({ type: "answer", session, to: m.from, sdp: answer.sdp });
1831
+ }
1832
+ break;
1833
+ case "ice":
1834
+ if (m.candidate) {
1835
+ if (!remoteDescriptionReady) pendingIce.push(m.candidate);
1836
+ else await pc.addIceCandidate(m.candidate);
1837
+ }
1838
+ break;
1839
+ }
1840
+ };
1841
+ socket = new ReconnectingSocket({
1842
+ urlProvider: async () => signalUrl,
1843
+ wsFactory: cfg.wsFactory,
1844
+ onOpen: () => send({ type: "join", session, role: "viewer", token }),
1845
+ onMessage: (t2) => void onSignal(t2)
1846
+ });
1847
+ const dispose = () => {
1848
+ try {
1849
+ socket.send(JSON.stringify({ type: "leave", session }));
1850
+ } catch {
1851
+ }
1852
+ try {
1853
+ ctrl?.close();
1854
+ } catch {
1855
+ }
1856
+ try {
1857
+ pc.close();
1858
+ } catch {
1859
+ }
1860
+ socket.close();
1861
+ };
1862
+ await socket.start();
1863
+ try {
1864
+ const opened = await new Promise((resolve, reject) => {
1865
+ let settled = false;
1866
+ const finish = (dc, err) => {
1867
+ if (settled) return;
1868
+ settled = true;
1869
+ clearTimeout(timer);
1870
+ clearInterval(poll);
1871
+ if (err) reject(err);
1872
+ else resolve(dc);
1873
+ };
1874
+ const timer = setTimeout(() => finish(void 0, new Error("DataChannel \u5EFA\u94FE\u8D85\u65F6")), timeoutMs);
1875
+ const poll = setInterval(() => {
1876
+ if (!ctrl) return;
1877
+ const dc = ctrl;
1878
+ if (dc.readyState === "open") return finish(dc);
1879
+ dc.onopen = () => finish(dc);
1880
+ }, 30);
1881
+ pc.onconnectionstatechange = () => {
1882
+ if (pc.connectionState === "failed" || pc.connectionState === "closed") {
1883
+ finish(void 0, new Error(`PeerConnection ${pc.connectionState}`));
1884
+ }
1885
+ };
1886
+ });
1887
+ return { dc: opened, dispose };
1888
+ } catch (err) {
1889
+ dispose();
1890
+ throw err;
1891
+ }
1892
+ }
1893
+ var DeviceSession = class _DeviceSession {
1894
+ constructor(session, dc, dispose) {
1895
+ this.session = session;
1896
+ this.dc = dc;
1897
+ this.dispose = dispose;
1898
+ this.nextId = 1;
1899
+ /** id → 该操作的响应路由回调(多路复用核心)。 */
1900
+ this.pending = /* @__PURE__ */ new Map();
1901
+ this.closed = false;
1902
+ this.dc.onmessage = (ev) => {
1903
+ if (typeof ev.data !== "string") return;
1904
+ let m;
1905
+ try {
1906
+ m = JSON.parse(ev.data);
1907
+ } catch {
1908
+ return;
1909
+ }
1910
+ const h = this.pending.get(String(m.id));
1911
+ if (h) h(m);
1912
+ };
1913
+ }
1914
+ /**
1915
+ * 打开一个设备会话:dcSession 握手 → answerer 建链 → 等 "ctrl" 通道 open。
1916
+ * @param source `AixClient` 或 `AixConfig | ResolvedConfig`
1917
+ * @param deviceId 设备 id
1918
+ * @param opts.dcTimeoutMs 建链超时(ms),默认 15000
1919
+ */
1920
+ static async open(source, deviceId, opts = {}) {
1921
+ const ctx = toCtx(source);
1922
+ const timeoutMs = opts.dcTimeoutMs ?? DC_CONNECT_TIMEOUT_MS;
1923
+ const { session_id } = await ctx.devices.dcSession(deviceId);
1924
+ const { dc, dispose } = await openCtrlChannel(ctx.cfg, session_id, timeoutMs);
1925
+ return new _DeviceSession(session_id, dc, dispose);
1926
+ }
1927
+ allocId() {
1928
+ return String(this.nextId++);
1929
+ }
1930
+ ensureOpen() {
1931
+ if (this.closed) throw new AixError("DeviceSession already closed");
1932
+ if (this.dc.readyState !== "open") throw new AixError(`DeviceSession DataChannel not open (${this.dc.readyState})`);
1933
+ }
1934
+ sendReq(req) {
1935
+ this.dc.send(JSON.stringify(req));
1936
+ }
1937
+ // ---- 文件管理 ----------------------------------------------------------
1938
+ /** 列目录:返回 entries。节点 `ls -la` 解析后回 `list_ok`。 */
1939
+ listFiles(path) {
1940
+ this.ensureOpen();
1941
+ const id = this.allocId();
1942
+ return new Promise((resolve, reject) => {
1943
+ this.pending.set(id, (m) => {
1944
+ if (m.t === "list_ok") {
1945
+ this.pending.delete(id);
1946
+ resolve(m.entries);
1947
+ } else if (m.t === "err") {
1948
+ this.pending.delete(id);
1949
+ reject(new AixError(m.message));
1950
+ }
1951
+ });
1952
+ this.sendReq({ id, t: "list", path });
1953
+ });
1954
+ }
1955
+ /** 删除文件/目录(recursive=true 走 `rm -rf`)。 */
1956
+ deleteFile(path, recursive = false) {
1957
+ return this.simpleOk((id) => ({ id, t: "delete", path, recursive }));
1958
+ }
1959
+ /** 新建目录(`mkdir -p`)。 */
1960
+ mkdir(path) {
1961
+ return this.simpleOk((id) => ({ id, t: "mkdir", path }));
1962
+ }
1963
+ /** 重命名/移动(`mv from to`)。 */
1964
+ rename(from, to) {
1965
+ return this.simpleOk((id) => ({ id, t: "rename", from, to }));
1966
+ }
1967
+ /** 共享:发一条请求(由 id 构造完整帧),等节点回 `ok` / `err`。 */
1968
+ simpleOk(makeReq) {
1969
+ this.ensureOpen();
1970
+ const id = this.allocId();
1971
+ return new Promise((resolve, reject) => {
1972
+ this.pending.set(id, (m) => {
1973
+ if (m.t === "ok") {
1974
+ this.pending.delete(id);
1975
+ resolve();
1976
+ } else if (m.t === "err") {
1977
+ this.pending.delete(id);
1978
+ reject(new AixError(m.message));
1979
+ }
1980
+ });
1981
+ this.sendReq(makeReq(id));
1982
+ });
1983
+ }
1984
+ // ---- 终端 --------------------------------------------------------------
1985
+ /** 执行命令并收齐输出:返回 `{stdout, stderr, exitCode}`。 */
1986
+ async exec(cmd) {
1987
+ let stdout = "";
1988
+ let stderr = "";
1989
+ const code = await this.execStream(cmd, {
1990
+ onStdout: (d) => {
1991
+ stdout += d;
1992
+ },
1993
+ onStderr: (d) => {
1994
+ stderr += d;
1995
+ }
1996
+ });
1997
+ return { stdout, stderr, exitCode: code };
1998
+ }
1999
+ /** 流式执行命令:stdout/stderr 分块回调,resolve 退出码。 */
2000
+ execStream(cmd, hooks = {}) {
2001
+ this.ensureOpen();
2002
+ const id = this.allocId();
2003
+ return new Promise((resolve, reject) => {
2004
+ this.pending.set(id, (m) => {
2005
+ switch (m.t) {
2006
+ case "stdout":
2007
+ hooks.onStdout?.(m.data);
2008
+ break;
2009
+ case "stderr":
2010
+ hooks.onStderr?.(m.data);
2011
+ break;
2012
+ case "exit":
2013
+ this.pending.delete(id);
2014
+ resolve(m.code);
2015
+ break;
2016
+ case "err":
2017
+ this.pending.delete(id);
2018
+ reject(new AixError(m.message));
2019
+ break;
2020
+ }
2021
+ });
2022
+ this.sendReq({ id, t: "exec", cmd });
2023
+ });
2024
+ }
2025
+ // ---- 文件传输 ----------------------------------------------------------
2026
+ /** 推字节到设备 `dest`:put → chunk... → eof,节点逐块回 `ack` 推进进度。 */
2027
+ async pushFile(input, onProgress) {
2028
+ this.ensureOpen();
2029
+ const id = this.allocId();
2030
+ const bytes = asBytes(input.data);
2031
+ const total = bytes.length;
2032
+ const sha256 = await sha256Hex(bytes);
2033
+ let ackResolve = null;
2034
+ let failed = null;
2035
+ this.pending.set(id, (m) => {
2036
+ if (m.t === "ack") {
2037
+ onProgress?.({ loaded: Math.min(m.offset, total), total, channel: "dc" });
2038
+ ackResolve?.();
2039
+ } else if (m.t === "done" || m.t === "ok") {
2040
+ this.pending.delete(id);
2041
+ ackResolve?.();
2042
+ } else if (m.t === "err") {
2043
+ failed = new AixError(m.message);
2044
+ this.pending.delete(id);
2045
+ ackResolve?.();
2046
+ }
2047
+ });
2048
+ try {
2049
+ this.sendReq({ id, t: "put", name: input.filename, size: total, sha256, dest: input.dest });
2050
+ for (let offset = 0; offset < total; offset += CHUNK_SIZE) {
2051
+ if (failed) throw failed;
2052
+ const slice = bytes.subarray(offset, Math.min(offset + CHUNK_SIZE, total));
2053
+ this.sendReq({ id, t: "chunk", offset, bytes: bytesToBase64(slice) });
2054
+ if ((this.dc.bufferedAmount ?? 0) > BUFFER_HIGH) await waitForDrain(this.dc);
2055
+ }
2056
+ this.sendReq({ id, t: "eof" });
2057
+ await new Promise((resolve) => {
2058
+ ackResolve = resolve;
2059
+ setTimeout(resolve, 1e4);
2060
+ });
2061
+ if (failed) throw failed;
2062
+ onProgress?.({ loaded: total, total, channel: "dc" });
2063
+ } finally {
2064
+ this.pending.delete(id);
2065
+ }
2066
+ }
2067
+ /** 从设备 `src` 拉字节,收齐后返回 Uint8Array。节点流式回 chunk + done。 */
2068
+ pullFile(src, onProgress) {
2069
+ this.ensureOpen();
2070
+ const id = this.allocId();
2071
+ return new Promise((resolve, reject) => {
2072
+ const chunks = [];
2073
+ let total = 0;
2074
+ let loaded = 0;
2075
+ this.pending.set(id, (m) => {
2076
+ switch (m.t) {
2077
+ case "chunk": {
2078
+ const b = base64ToBytes(m.bytes);
2079
+ chunks.push(b);
2080
+ loaded += b.length;
2081
+ if (m.size && !total) total = m.size;
2082
+ onProgress?.({ loaded, total: total || loaded, channel: "dc" });
2083
+ break;
2084
+ }
2085
+ case "done": {
2086
+ this.pending.delete(id);
2087
+ const out = new Uint8Array(loaded);
2088
+ let off = 0;
2089
+ for (const c of chunks) {
2090
+ out.set(c, off);
2091
+ off += c.length;
2092
+ }
2093
+ onProgress?.({ loaded, total: m.size || total || loaded, channel: "dc" });
2094
+ resolve(out);
2095
+ break;
2096
+ }
2097
+ case "err":
2098
+ this.pending.delete(id);
2099
+ reject(new AixError(m.message));
2100
+ break;
2101
+ }
2102
+ });
2103
+ this.sendReq({ id, t: "get", src });
2104
+ });
2105
+ }
2106
+ // ---- 通用流:openStream / shell / 端口转发 ------------------------------
2107
+ /**
2108
+ * 打开一条通用双工字节流(多路复用,沿用同一 DC)。
2109
+ * - `{kind:'tcp',host,port}`:节点 `TcpStream::connect(host:port)`,host 是
2110
+ * **节点可达**的地址(设备 adb-forward 出的端口、节点本机/局域网服务等)。
2111
+ * - `{kind:'exec',cmd}`:节点 spawn `adb shell <cmd>`(交互式:write→stdin,
2112
+ * stdout/stderr 合并→onData)。
2113
+ * 返回的 `DcStream` 在收到节点 `opened` 后即可用;若节点回 `err` 则 reject。
2114
+ */
2115
+ openStream(target) {
2116
+ this.ensureOpen();
2117
+ const id = this.allocId();
2118
+ return new Promise((resolve, reject) => {
2119
+ let opened = false;
2120
+ const dataCbs = [];
2121
+ const closeCbs = [];
2122
+ let streamClosed = false;
2123
+ const finalize = () => {
2124
+ if (streamClosed) return;
2125
+ streamClosed = true;
2126
+ this.pending.delete(id);
2127
+ for (const cb of closeCbs) {
2128
+ try {
2129
+ cb();
2130
+ } catch {
2131
+ }
2132
+ }
2133
+ };
2134
+ const stream = {
2135
+ write: (bytes) => {
2136
+ if (streamClosed) return;
2137
+ this.sendReq({ id, t: "data", bytes: bytesToBase64(asBytes(bytes)) });
2138
+ },
2139
+ onData: (cb) => {
2140
+ dataCbs.push(cb);
2141
+ },
2142
+ onClose: (cb) => {
2143
+ if (streamClosed) {
2144
+ try {
2145
+ cb();
2146
+ } catch {
2147
+ }
2148
+ } else {
2149
+ closeCbs.push(cb);
2150
+ }
2151
+ },
2152
+ close: () => {
2153
+ if (streamClosed) return;
2154
+ try {
2155
+ this.sendReq({ id, t: "close" });
2156
+ } catch {
2157
+ }
2158
+ finalize();
2159
+ }
2160
+ };
2161
+ this.pending.set(id, (m) => {
2162
+ switch (m.t) {
2163
+ case "opened":
2164
+ if (!opened) {
2165
+ opened = true;
2166
+ resolve(stream);
2167
+ }
2168
+ break;
2169
+ case "data": {
2170
+ const b = base64ToBytes(m.bytes);
2171
+ for (const cb of dataCbs) {
2172
+ try {
2173
+ cb(b);
2174
+ } catch {
2175
+ }
2176
+ }
2177
+ break;
2178
+ }
2179
+ case "close":
2180
+ finalize();
2181
+ break;
2182
+ case "err":
2183
+ if (!opened) {
2184
+ this.pending.delete(id);
2185
+ reject(new AixError(m.message));
2186
+ } else {
2187
+ finalize();
2188
+ }
2189
+ break;
2190
+ }
2191
+ });
2192
+ this.sendReq(
2193
+ target.kind === "tcp" ? { id, t: "open", kind: "tcp", host: target.host, port: target.port } : { id, t: "open", kind: "exec", cmd: target.cmd }
2194
+ );
2195
+ });
2196
+ }
2197
+ /** 交互式终端:`= openStream({kind:'exec',cmd})`,cmd 默认 `sh`(交互式 shell)。 */
2198
+ shell(cmd = "sh") {
2199
+ return this.openStream({ kind: "exec", cmd });
2200
+ }
2201
+ /**
2202
+ * 本地端口转发(**仅 Node 环境**):用 `node:net` 监听 `localPort`,每个进来的
2203
+ * 连接都开一条 `openStream({kind:'tcp',host,port})` 并双向 pipe。返回停止函数
2204
+ * (关闭监听 + 现有连接)。浏览器环境无 `node:net`,调用会抛"仅 node 可用"。
2205
+ *
2206
+ * 用动态 import('node:net') + try,避免把 node:net 打进浏览器 bundle
2207
+ * (frontend 不会调用本方法)。
2208
+ */
2209
+ async forwardLocalPort(localPort, remote) {
2210
+ this.ensureOpen();
2211
+ let net;
2212
+ try {
2213
+ const mod = "node:net";
2214
+ net = await import(
2215
+ /* @vite-ignore */
2216
+ /* webpackIgnore: true */
2217
+ mod
2218
+ );
2219
+ } catch {
2220
+ throw new AixError("forwardLocalPort \u4EC5 node \u53EF\u7528(\u5F53\u524D\u73AF\u5883\u65E0 node:net)");
2221
+ }
2222
+ const sockets = /* @__PURE__ */ new Set();
2223
+ const server = net.createServer((socket) => {
2224
+ sockets.add(socket);
2225
+ void (async () => {
2226
+ let stream;
2227
+ try {
2228
+ stream = await this.openStream({ kind: "tcp", host: remote.host, port: remote.port });
2229
+ } catch {
2230
+ socket.destroy();
2231
+ sockets.delete(socket);
2232
+ return;
2233
+ }
2234
+ stream.onData((b) => {
2235
+ socket.write(b.slice());
2236
+ });
2237
+ stream.onClose(() => {
2238
+ socket.end();
2239
+ });
2240
+ socket.on("data", (chunk) => {
2241
+ stream.write(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
2242
+ });
2243
+ socket.on("close", () => {
2244
+ stream.close();
2245
+ sockets.delete(socket);
2246
+ });
2247
+ socket.on("error", () => {
2248
+ stream.close();
2249
+ sockets.delete(socket);
2250
+ });
2251
+ })();
2252
+ });
2253
+ await new Promise((resolve, reject) => {
2254
+ server.once("error", reject);
2255
+ server.listen(localPort, () => {
2256
+ server.off?.("error", reject);
2257
+ resolve();
2258
+ });
2259
+ });
2260
+ return () => {
2261
+ try {
2262
+ server.close();
2263
+ } catch {
2264
+ }
2265
+ for (const s of sockets) {
2266
+ try {
2267
+ s.destroy();
2268
+ } catch {
2269
+ }
2270
+ }
2271
+ sockets.clear();
2272
+ };
2273
+ }
2274
+ /** 关闭会话:断开 DC + pc + 信令 socket,清空 pending。 */
2275
+ close() {
2276
+ if (this.closed) return;
2277
+ this.closed = true;
2278
+ this.pending.clear();
2279
+ this.dispose();
2280
+ }
2281
+ };
2282
+ async function pushViaR2(ctx, deviceId, input, onProgress) {
2283
+ const bytes = asBytes(input.data);
2284
+ const total = bytes.length;
2285
+ onProgress?.({ loaded: 0, total, channel: "r2" });
2286
+ const { key, upload_url } = await ctx.devices.filesUploadUrl(deviceId, input.filename);
2287
+ const put = await ctx.cfg.fetchFn(upload_url, { method: "PUT", body: asArrayBuffer(bytes) });
2288
+ if (!put.ok) throw new AixError(`R2 \u4E0A\u4F20\u5931\u8D25 ${put.status}`);
2289
+ onProgress?.({ loaded: total, total, channel: "r2" });
2290
+ await ctx.devices.filesPush(deviceId, key, input.dest);
2291
+ }
2292
+ async function pullViaR2(ctx, deviceId, src, onProgress) {
2293
+ const filename = src.split("/").pop() || "download.bin";
2294
+ onProgress?.({ loaded: 0, total: 0, channel: "r2" });
2295
+ const { download_url } = await ctx.devices.filesPull(deviceId, src, filename);
2296
+ const resp = await ctx.cfg.fetchFn(download_url);
2297
+ if (!resp.ok) throw new AixError(`R2 \u4E0B\u8F7D\u5931\u8D25 ${resp.status}`);
2298
+ const data = new Uint8Array(await resp.arrayBuffer());
2299
+ onProgress?.({ loaded: data.length, total: data.length, channel: "r2" });
2300
+ return { data, filename };
2301
+ }
2302
+ async function pushFile(source, deviceId, input, opts = {}) {
2303
+ const ctx = toCtx(source);
2304
+ try {
2305
+ const s = await DeviceSession.open(ctx.cfg, deviceId, { dcTimeoutMs: opts.dcTimeoutMs });
2306
+ try {
2307
+ await s.pushFile(input, opts.onProgress);
2308
+ } finally {
2309
+ s.close();
2310
+ }
2311
+ return { channel: "dc", fellBack: false };
2312
+ } catch (err) {
2313
+ if (typeof console !== "undefined") console.warn("[device-session] push \u901A\u9053 A \u5931\u8D25,\u56DE\u9000 R2:", err);
2314
+ await pushViaR2(ctx, deviceId, input, opts.onProgress);
2315
+ return { channel: "r2", fellBack: true };
2316
+ }
2317
+ }
2318
+ async function pullFile(source, deviceId, src, opts = {}) {
2319
+ const ctx = toCtx(source);
2320
+ const filename = src.split("/").pop() || "download.bin";
2321
+ try {
2322
+ const s = await DeviceSession.open(ctx.cfg, deviceId, { dcTimeoutMs: opts.dcTimeoutMs });
2323
+ try {
2324
+ const data = await s.pullFile(src, opts.onProgress);
2325
+ return { channel: "dc", fellBack: false, data, filename };
2326
+ } finally {
2327
+ s.close();
2328
+ }
2329
+ } catch (err) {
2330
+ if (typeof console !== "undefined") console.warn("[device-session] pull \u901A\u9053 A \u5931\u8D25,\u56DE\u9000 R2:", err);
2331
+ const r = await pullViaR2(ctx, deviceId, src, opts.onProgress);
2332
+ return { channel: "r2", fellBack: true, data: r.data, filename: r.filename };
2333
+ }
2334
+ }
2335
+
2336
+ export { AdminApi, AixAuthError, AixClient, AixDeviceOffline, AixError, AixLocked, AixProtocolError, AixTimeout, ApiTokensApi, AuthApi, BillingApi, ClustersApi, DeviceSession, DevicesApi, EnvRun, FleetApi, ImagesApi, LlmApi, LocalNodeController, LocatorsApi, ManagedProxiesApi, NodesApi, ProjectsApi, ReconnectingSocket, RestClient, ScriptsApi, ShortcutsApi, TasksApi, UsersApi, WebhooksApi, authHeader, buildAuthProvider, createCachedUserCredential, createClient, detectEnvOs, envBlocker, errorFromRet, executionStreamEventsAfter, executionWsTicketUrl, executionWsUrl, getIceServers, getLocale, isEnvEventFrame, isExecutionFrame, isFleetRunTerminal, isFridaEventFrame, isRetFrame, isScriptletEventFrame, isStatusFrame, joinUrl, mintViewerToken, parseIncoming, pullFile, pushFile, resolveConfig, restClient, runEnvToFinish, setLocale, summarizeEnv, t };