@agimon-ai/po-ios 0.0.1-alpha.2 → 0.0.1-alpha.21

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.
@@ -1,18 +1,21 @@
1
- import { E as SIMCTL_TIMEOUT_MS, O as WAIT_MAX_POLL_MS, _ as IOS_PACKAGE, a as HELPER_BUILD_LOCK, b as IOS_TOOL_PATH, c as HELPER_NATIVE_DIRECTORY, d as HELPER_SOURCES, g as IOS_ERROR_CODES, h as IOS_DEVICE_SET_DIRECTORY, i as CONSOLE_MAX_MS, l as HELPER_PRODUCT, m as IOS_DEVICE_NAME_PREFIX, n as BOOT_TIMEOUT_MS, o as HELPER_BUILD_TIMEOUT_MS, t as IOS_POOL_CONTRACT, u as HELPER_RESTART_WINDOW_MS, v as IOS_POOL_DEFAULTS, w as SCREENSHOT_MAX_PIXELS, y as IOS_POOL_SERVICE } from "../contracts-DH0gdDYT.mjs";
2
- import { composeRootHooks, composeRootInjects, defineResource, defineRoot } from "@agimon-ai/po-core/extensionFile";
3
- import { PO_GLOBAL_SERVICES_SERVICE, composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource, readPoGlobalServices } from "@agimon-ai/po-core/serverPlugin";
1
+ import { D as SIMCTL_TIMEOUT_MS, T as SCREENSHOT_MAX_PIXELS, _ as IOS_ERROR_CODES, a as CONSOLE_MAX_MS, b as IOS_POOL_SERVICE, d as HELPER_RESTART_WINDOW_MS, f as HELPER_SOURCES, g as IOS_DEVICE_SET_DIRECTORY, h as IOS_DEVICE_NAME_PREFIX, k as WAIT_MAX_POLL_MS, l as HELPER_NATIVE_DIRECTORY, n as IOS_SETTINGS_CONTRACT, o as HELPER_BUILD_LOCK, r as BOOT_TIMEOUT_MS, s as HELPER_BUILD_TIMEOUT_MS, t as IOS_POOL_CONTRACT, u as HELPER_PRODUCT, v as IOS_PACKAGE, x as IOS_TOOL_PATH, y as IOS_POOL_DEFAULTS } from "../contracts-BQjfOjy0.mjs";
2
+ import { composeRootHooks, composeRootInjects, defineChannel, defineMethod, defineResource, defineRoot, defineRoutedContribution } from "@agimon-ai/po-core/extensionFile";
3
+ import { PO_GLOBAL_SERVICES_SERVICE, PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerMethod, defineServerPlugin, packageResourcePath, readPackageResource, readPoGlobalServices, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
4
4
  import { PO_DB_CONTRACT, PO_DB_SERVICE, requirePoDb } from "@agimon-ai/po-db";
5
5
  import path from "node:path";
6
6
  import { parsePoConfig } from "@agimon-ai/po-config";
7
7
  import { poHomeDirectory } from "@agimon-ai/po-core/piSettings";
8
- import { BACKGROUND_CONTEXT, PO_FS_SERVICE, PO_SHELL_SERVICE, getOrThrow, requirePoFs, requirePoShell, withAbortSignal } from "@agimon-ai/po-core/platform";
8
+ import { BACKGROUND_CONTEXT, PO_FS_SERVICE, PO_SESSION_FILES_SERVICE, PO_SHELL_SERVICE, getOrThrow, requirePoFs, requirePoShell, withAbortSignal } from "@agimon-ai/po-core/platform";
9
9
  import { createHash, randomBytes, randomUUID } from "node:crypto";
10
10
  import { spawn } from "node:child_process";
11
11
  import { createConnection } from "node:net";
12
+ import { openArtifactDownload } from "@agimon-ai/po-artifact/artifactFiles";
12
13
  import { resolveRootSessionId } from "@agimon-ai/po-core/childProcess";
13
14
  import { PO_CODEMODE_SERVICE, readPoCodemode } from "@agimon-ai/po-core/codemode";
15
+ import { PO_SHARE_FILE_REMOTE_OFF_MESSAGE } from "@agimon-ai/po-core/packageApi";
14
16
  import { Check, Errors } from "typebox/value";
15
17
  import { Type } from "typebox";
18
+ import { definePoPluginMethod } from "@agimon-ai/po-core/pluginProtocol";
16
19
  //#region src/services/iosError/index.ts
17
20
  /** Every failure a script can branch on carries a stable `code`; the message says what to do next. */
18
21
  var IosError = class extends Error {
@@ -792,6 +795,7 @@ function resolvePoolConfig(raw) {
792
795
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
793
796
  function createDevicePool(options) {
794
797
  const { store, simctl, probe, config, serverId } = options;
798
+ const availability = { ...options.availability };
795
799
  const now = options.now ?? Date.now;
796
800
  const pollMs = options.pollMs ?? 750;
797
801
  const notice = (message) => options.onNotice?.(`iOS pool: ${message}`);
@@ -1201,6 +1205,7 @@ function createDevicePool(options) {
1201
1205
  const lease = leases.get(device.udid);
1202
1206
  return {
1203
1207
  ...device,
1208
+ availability: availability[device.udid] ?? "available",
1204
1209
  leased: lease !== void 0,
1205
1210
  ...lease !== void 0 && lease.owner_root === owner ? { leaseId: lease.lease_id } : {}
1206
1211
  };
@@ -1210,6 +1215,9 @@ function createDevicePool(options) {
1210
1215
  requireSupported();
1211
1216
  if (stopped) throw new IosError("IOS_POOL_BUSY", "The iOS pool is stopping.");
1212
1217
  signal?.throwIfAborted();
1218
+ const existing = (await store.leasesOf(owner)).find((lease) => lease.kind === "device" && lease.udid === udid);
1219
+ if (existing !== void 0) return view(existing);
1220
+ if (availability[udid] === "excluded") throw new IosError("IOS_INVALID_ARGUMENT", "This phone is excluded from Po in the active global iOS settings.");
1213
1221
  const devicectl = requireDevicectl();
1214
1222
  const device = (await devicectl.listDevices(signal)).find((candidate) => candidate.udid === udid);
1215
1223
  if (device === void 0) throw new IosError("IOS_INVALID_ARGUMENT", `No physical device ${udid} is visible. Call ios.devices() to list them.`);
@@ -1269,11 +1277,11 @@ function createDevicePool(options) {
1269
1277
  }
1270
1278
  //#endregion
1271
1279
  //#region src/services/simHelper/index.ts
1272
- const unavailable$1 = (message) => new IosError("IOS_HELPER_UNAVAILABLE", message);
1280
+ const unavailable$2 = (message) => new IosError("IOS_HELPER_UNAVAILABLE", message);
1273
1281
  function replyError(error) {
1274
1282
  const code = typeof error?.code === "string" ? error.code : "";
1275
1283
  const message = typeof error?.message === "string" ? error.message : "The iOS helper failed.";
1276
- return IOS_ERROR_CODES.includes(code) ? new IosError(code, message) : unavailable$1(`${code ? `${code}: ` : ""}${message}`);
1284
+ return IOS_ERROR_CODES.includes(code) ? new IosError(code, message) : unavailable$2(`${code ? `${code}: ` : ""}${message}`);
1277
1285
  }
1278
1286
  /**
1279
1287
  * Client for the resident Swift helper. Requests dispatch in order, matched by id. A timeout stops the process;
@@ -1301,7 +1309,7 @@ function createSimHelper(options) {
1301
1309
  const failAll = (error, target) => {
1302
1310
  for (const [id, entry] of pending) if (target === void 0 || entry.target === target) take(id)?.reject(error);
1303
1311
  };
1304
- const stop = (target, error = unavailable$1("The iOS helper stopped; it restarts on the next call.")) => {
1312
+ const stop = (target, error = unavailable$2("The iOS helper stopped; it restarts on the next call.")) => {
1305
1313
  if (current === target) {
1306
1314
  current = void 0;
1307
1315
  dispatch = Promise.resolve();
@@ -1312,7 +1320,7 @@ function createSimHelper(options) {
1312
1320
  };
1313
1321
  const send = (target, op, udid, params, signal) => new Promise((resolve, reject) => {
1314
1322
  if (disposed || current !== target) {
1315
- reject(unavailable$1("The iOS helper is not running."));
1323
+ reject(unavailable$2("The iOS helper is not running."));
1316
1324
  return;
1317
1325
  }
1318
1326
  if (signal?.aborted) {
@@ -1323,7 +1331,7 @@ function createSimHelper(options) {
1323
1331
  const aborted = () => take(id)?.reject(signal?.reason);
1324
1332
  const timer = setTimeout(() => {
1325
1333
  if (current === target) starting = void 0;
1326
- stop(target, unavailable$1(`The iOS helper did not answer ${op} within ${String(timeoutMs)} ms. It restarts on the next call.`));
1334
+ stop(target, unavailable$2(`The iOS helper did not answer ${op} within ${String(timeoutMs)} ms. It restarts on the next call.`));
1327
1335
  }, timeoutMs);
1328
1336
  pending.set(id, {
1329
1337
  target,
@@ -1353,10 +1361,10 @@ function createSimHelper(options) {
1353
1361
  const launch = async (rebuild) => {
1354
1362
  const recent = starts.filter((started) => now() - started < HELPER_RESTART_WINDOW_MS);
1355
1363
  starts.splice(0, starts.length, ...recent);
1356
- if (starts.length >= 3) throw unavailable$1("The iOS helper keeps failing; it restarted three times in five minutes. Try again later.");
1364
+ if (starts.length >= 3) throw unavailable$2("The iOS helper keeps failing; it restarted three times in five minutes. Try again later.");
1357
1365
  starts.push(now());
1358
1366
  const binary = await options.binary(rebuild);
1359
- if (disposed) throw unavailable$1("The iOS helper is shut down.");
1367
+ if (disposed) throw unavailable$2("The iOS helper is shut down.");
1360
1368
  const spawned = options.spawn(binary);
1361
1369
  current = spawned;
1362
1370
  spawned.onLine((line) => {
@@ -1380,12 +1388,12 @@ function createSimHelper(options) {
1380
1388
  starting = void 0;
1381
1389
  dispatch = Promise.resolve();
1382
1390
  }
1383
- failAll(unavailable$1(`The iOS helper exited (code ${String(code)}); it restarts on the next call.`), spawned);
1391
+ failAll(unavailable$2(`The iOS helper exited (code ${String(code)}); it restarts on the next call.`), spawned);
1384
1392
  });
1385
1393
  let probe;
1386
1394
  try {
1387
1395
  const result = await send(spawned, "probe", void 0, {});
1388
- if (result === null || typeof result !== "object" || !("protocolVersion" in result) || !Number.isInteger(result.protocolVersion) || !("missing" in result) || !Array.isArray(result.missing) || !result.missing.every((capability) => typeof capability === "string")) throw unavailable$1("The iOS helper returned an invalid probe.");
1396
+ if (result === null || typeof result !== "object" || !("protocolVersion" in result) || !Number.isInteger(result.protocolVersion) || !("missing" in result) || !Array.isArray(result.missing) || !result.missing.every((capability) => typeof capability === "string")) throw unavailable$2("The iOS helper returned an invalid probe.");
1389
1397
  probe = result;
1390
1398
  } catch (error) {
1391
1399
  await stop(spawned);
@@ -1393,7 +1401,7 @@ function createSimHelper(options) {
1393
1401
  }
1394
1402
  if (probe.protocolVersion !== 1) {
1395
1403
  await stop(spawned);
1396
- if (rebuild) throw unavailable$1(`The iOS helper speaks protocol ${String(probe.protocolVersion)}, not ${String(1)}, even after a rebuild.`);
1404
+ if (rebuild) throw unavailable$2(`The iOS helper speaks protocol ${String(probe.protocolVersion)}, not ${String(1)}, even after a rebuild.`);
1397
1405
  return launch(true);
1398
1406
  }
1399
1407
  return {
@@ -1403,7 +1411,7 @@ function createSimHelper(options) {
1403
1411
  };
1404
1412
  const ready = async () => {
1405
1413
  await stopping;
1406
- if (disposed) throw unavailable$1("The iOS helper is shut down.");
1414
+ if (disposed) throw unavailable$2("The iOS helper is shut down.");
1407
1415
  if (starting === void 0) {
1408
1416
  const attempt = launch(false).catch((error) => {
1409
1417
  if (starting === attempt) starting = void 0;
@@ -1432,7 +1440,7 @@ function createSimHelper(options) {
1432
1440
  },
1433
1441
  async dispose() {
1434
1442
  disposed = true;
1435
- if (current !== void 0) await stop(current, unavailable$1("The iOS helper is shut down."));
1443
+ if (current !== void 0) await stop(current, unavailable$2("The iOS helper is shut down."));
1436
1444
  else await stopping;
1437
1445
  }
1438
1446
  };
@@ -1443,7 +1451,7 @@ const PORT = 47100;
1443
1451
  const RUNNER_BUNDLE = "ai.agimon.po.iosrunner";
1444
1452
  const BUILD_TIMEOUT_MS = 3e5;
1445
1453
  const RUN_TIMEOUT_MS = 6048e5;
1446
- const unavailable = (message) => new IosError("IOS_HELPER_UNAVAILABLE", message);
1454
+ const unavailable$1 = (message) => new IosError("IOS_HELPER_UNAVAILABLE", message);
1447
1455
  /** Signed XCUITest sessions, one per leased physical device. Host access stays injected. */
1448
1456
  function createDeviceRunner(options) {
1449
1457
  const sessions = /* @__PURE__ */ new Map();
@@ -1456,7 +1464,7 @@ function createDeviceRunner(options) {
1456
1464
  };
1457
1465
  const stopSession = (udid, session) => {
1458
1466
  session.stopping ??= Promise.resolve().then(async () => {
1459
- session.controller.abort(unavailable("The device runner stopped."));
1467
+ session.controller.abort(unavailable$1("The device runner stopped."));
1460
1468
  await session.socket?.kill();
1461
1469
  await session.command?.catch(() => void 0);
1462
1470
  await uninstall(udid, session);
@@ -1471,7 +1479,7 @@ function createDeviceRunner(options) {
1471
1479
  };
1472
1480
  const clean = (udid, session) => {
1473
1481
  session.cleanup ??= Promise.resolve().then(async () => {
1474
- session.controller.abort(unavailable("The device runner stopped."));
1482
+ session.controller.abort(unavailable$1("The device runner stopped."));
1475
1483
  const helper = session.helper;
1476
1484
  session.helper = void 0;
1477
1485
  if (helper) await helper.dispose();
@@ -1487,15 +1495,15 @@ function createDeviceRunner(options) {
1487
1495
  launched.delete(udid);
1488
1496
  const session = sessions.get(udid);
1489
1497
  if (!session) return;
1490
- session.controller.abort(unavailable("The device runner was released."));
1498
+ session.controller.abort(unavailable$1("The device runner was released."));
1491
1499
  await session.ready.catch(() => void 0);
1492
1500
  await clean(udid, session);
1493
1501
  };
1494
1502
  const start = async (udid, session) => {
1495
1503
  const { signal } = session.controller;
1496
- const timeout = setTimeout(() => session.controller.abort(unavailable("The device runner startup timed out.")), options.startupTimeoutMs ?? 42e4);
1504
+ const timeout = setTimeout(() => session.controller.abort(unavailable$1("The device runner startup timed out.")), options.startupTimeoutMs ?? 42e4);
1497
1505
  try {
1498
- if (!options.developmentTeam?.trim()) throw unavailable("Configure ios.device.developmentTeam before using accessibility on a physical device.");
1506
+ if (!options.developmentTeam?.trim()) throw unavailable$1("Configure ios.device.developmentTeam before using accessibility on a physical device.");
1499
1507
  signal.throwIfAborted();
1500
1508
  const directory = `${options.cacheRoot}/${randomUUID()}`;
1501
1509
  await options.files.createDir(directory);
@@ -1527,11 +1535,11 @@ function createDeviceRunner(options) {
1527
1535
  session.command = building.then(() => void 0);
1528
1536
  session.command.catch(() => void 0);
1529
1537
  const built = await building;
1530
- if (built.exitCode !== 0) throw unavailable(`The device runner failed to build:\n${(built.stderr || built.stdout).slice(-2e3)}`);
1538
+ if (built.exitCode !== 0) throw unavailable$1(`The device runner failed to build:\n${(built.stderr || built.stdout).slice(-2e3)}`);
1531
1539
  signal.throwIfAborted();
1532
1540
  const products = `${derived}/Build/Products`;
1533
1541
  const testRuns = (await options.files.list(products)).filter((name) => name.endsWith(".xctestrun"));
1534
- if (testRuns.length !== 1) throw unavailable("Expected one built XCUITest run configuration.");
1542
+ if (testRuns.length !== 1) throw unavailable$1("Expected one built XCUITest run configuration.");
1535
1543
  const token = randomBytes(32).toString("hex");
1536
1544
  let host;
1537
1545
  let ready = false;
@@ -1577,7 +1585,7 @@ function createDeviceRunner(options) {
1577
1585
  });
1578
1586
  while (true) {
1579
1587
  signal.throwIfAborted();
1580
- if (session.exited) throw unavailable("xcodebuild exited before the device runner was ready.");
1588
+ if (session.exited) throw unavailable$1("xcodebuild exited before the device runner was ready.");
1581
1589
  status(await options.readStatus(resultBundle));
1582
1590
  signal.throwIfAborted();
1583
1591
  if (host && ready) break;
@@ -1620,7 +1628,7 @@ function createDeviceRunner(options) {
1620
1628
  const helper = createSimHelper({
1621
1629
  binary: async () => {
1622
1630
  signal.throwIfAborted();
1623
- if (used) throw unavailable("The device runner disconnected; release and acquire the device again.");
1631
+ if (used) throw unavailable$1("The device runner disconnected; release and acquire the device again.");
1624
1632
  used = true;
1625
1633
  return "device-runner";
1626
1634
  },
@@ -1632,7 +1640,7 @@ function createDeviceRunner(options) {
1632
1640
  session.helper = helper;
1633
1641
  await helper.probe(signal);
1634
1642
  signal.throwIfAborted();
1635
- if (session.exited) throw unavailable("xcodebuild exited during the device runner handshake.");
1643
+ if (session.exited) throw unavailable$1("xcodebuild exited during the device runner handshake.");
1636
1644
  return {
1637
1645
  probe: (requestSignal) => helper.probe(requestSignal),
1638
1646
  observe: (target, requestSignal) => helper.observe(target, requestSignal),
@@ -1652,7 +1660,7 @@ function createDeviceRunner(options) {
1652
1660
  };
1653
1661
  const service = {
1654
1662
  get(udid, signal) {
1655
- if (disposed) return Promise.reject(unavailable("The device runner service is shut down."));
1663
+ if (disposed) return Promise.reject(unavailable$1("The device runner service is shut down."));
1656
1664
  if (signal?.aborted) return Promise.reject(signal.reason);
1657
1665
  const existing = sessions.get(udid);
1658
1666
  if (existing?.cleanupError !== void 0) return Promise.reject(existing.cleanupError);
@@ -1932,17 +1940,24 @@ async function connectTcp(options) {
1932
1940
  async function readIosSettings(fs, poHome, onNotice) {
1933
1941
  const file = path.join(poHome, "config.yaml");
1934
1942
  const text = await fs.readTextFile(file, BACKGROUND_CONTEXT);
1935
- if (!text.ok) return { pool: resolvePoolConfig(void 0) };
1943
+ if (!text.ok) return {
1944
+ pool: resolvePoolConfig(void 0),
1945
+ availability: {}
1946
+ };
1936
1947
  try {
1937
1948
  const ios = parsePoConfig(text.value, file, { lenient: true }).config.ios;
1938
1949
  return {
1939
1950
  pool: resolvePoolConfig(ios?.pool),
1940
1951
  ...ios?.helperPath ? { helperPath: ios.helperPath } : {},
1941
- ...ios?.device?.developmentTeam ? { developmentTeam: ios.device.developmentTeam } : {}
1952
+ ...ios?.device?.developmentTeam ? { developmentTeam: ios.device.developmentTeam } : {},
1953
+ availability: ios?.device?.availability ?? {}
1942
1954
  };
1943
1955
  } catch (error) {
1944
1956
  onNotice(`iOS pool: ignoring ios settings in ${file}: ${error.message}`);
1945
- return { pool: resolvePoolConfig(void 0) };
1957
+ return {
1958
+ pool: resolvePoolConfig(void 0),
1959
+ availability: {}
1960
+ };
1946
1961
  }
1947
1962
  }
1948
1963
  /** The resident accessibility helper, built on first use from the package's Swift sources. */
@@ -1983,6 +1998,7 @@ async function activatePool(activation) {
1983
1998
  const deviceSet = path.join(poHome, "ios", IOS_DEVICE_SET_DIRECTORY);
1984
1999
  const onNotice = (message) => activation.host.context.onNotice(message);
1985
2000
  let pool;
2001
+ let runtime;
1986
2002
  const provider = activation.context.inject([
1987
2003
  PO_DB_SERVICE,
1988
2004
  PO_FS_SERVICE,
@@ -1996,6 +2012,14 @@ async function activatePool(activation) {
1996
2012
  const run = createShellRunner(requirePoShell(injected), environment);
1997
2013
  const store = createPoolStore(db.database);
1998
2014
  const settings = await readIosSettings(fs, poHome, onNotice);
2015
+ runtime = {
2016
+ configFile: path.join(poHome, "config.yaml"),
2017
+ applied: {
2018
+ pool: settings.pool,
2019
+ ...settings.developmentTeam ? { developmentTeam: settings.developmentTeam } : {},
2020
+ availability: settings.availability
2021
+ }
2022
+ };
1999
2023
  const serverId = crypto.randomUUID();
2000
2024
  const devicectl = createDeviceCtl({
2001
2025
  run,
@@ -2041,6 +2065,7 @@ async function activatePool(activation) {
2041
2065
  simctl: createSimctl(run, deviceSet),
2042
2066
  probe: createNodeProcessProbe(run),
2043
2067
  config: settings.pool,
2068
+ availability: runtime.applied.availability,
2044
2069
  serverId,
2045
2070
  helper: createHelper({
2046
2071
  run,
@@ -2059,7 +2084,12 @@ async function activatePool(activation) {
2059
2084
  });
2060
2085
  await pool.start();
2061
2086
  }
2062
- return activation.provide(IOS_POOL_CONTRACT, pool);
2087
+ const releasePool = await activation.provide(IOS_POOL_CONTRACT, pool);
2088
+ const releaseSettings = await activation.provide(IOS_SETTINGS_CONTRACT, runtime);
2089
+ return async () => {
2090
+ await releaseSettings();
2091
+ await releasePool();
2092
+ };
2063
2093
  });
2064
2094
  try {
2065
2095
  await provider.await();
@@ -2074,9 +2104,23 @@ async function activatePool(activation) {
2074
2104
  };
2075
2105
  }
2076
2106
  /** Every non-session installation offers its pool to the host's existing global ownership registry. */
2077
- function createIosGlobalRoot(plugin, level = "global") {
2107
+ async function createIosGlobalRoot(plugin, level = "global") {
2108
+ let scope;
2109
+ const binding = plugin.context.inject([PO_SERVER_SCOPE_SERVICE], (injected) => {
2110
+ scope = requirePoServerScope(injected);
2111
+ return () => {
2112
+ scope = void 0;
2113
+ };
2114
+ });
2115
+ await binding.await();
2078
2116
  return {
2079
- value: void 0,
2117
+ value: { resolveIosServices: () => ({
2118
+ pool: scope?.resolve(IOS_POOL_CONTRACT),
2119
+ runtime: scope?.resolve(IOS_SETTINGS_CONTRACT)
2120
+ }) },
2121
+ onDispose: async () => {
2122
+ await binding.dispose();
2123
+ },
2080
2124
  onStart: () => {
2081
2125
  if (plugin.host.scope !== level) return;
2082
2126
  plugin.context.inject([PO_GLOBAL_SERVICES_SERVICE], (injected) => readPoGlobalServices(injected)?.register(plugin.host, {
@@ -2093,6 +2137,277 @@ var root_server_default$2 = defineRoot(createIosGlobalRoot, { inject: [PO_DB_CON
2093
2137
  //#region src/extensions/workspaces/(backend)/root.server.ts
2094
2138
  var root_server_default$1 = defineRoot((plugin) => createIosGlobalRoot(plugin, "workspace"), { inject: [PO_DB_CONTRACT] });
2095
2139
  //#endregion
2140
+ //#region src/services/iosActivity/index.ts
2141
+ const MAX_FRAME_BYTES = 4194304;
2142
+ const PNG_SIGNATURE = [
2143
+ 137,
2144
+ 80,
2145
+ 78,
2146
+ 71,
2147
+ 13,
2148
+ 10,
2149
+ 26,
2150
+ 10
2151
+ ];
2152
+ /** Reads only the root session's leases. Frame files are private scratch, never artifacts. */
2153
+ function createIosActivity(options) {
2154
+ const aborter = new AbortController();
2155
+ const pending = /* @__PURE__ */ new Map();
2156
+ const capture = async (leaseId, signal) => {
2157
+ const pool = options.pool();
2158
+ if (!pool || aborter.signal.aborted) return { state: "released" };
2159
+ const activeSignal = signal ? AbortSignal.any([aborter.signal, signal]) : aborter.signal;
2160
+ try {
2161
+ return await pool.withLease(options.owner, leaseId, async (lease) => {
2162
+ activeSignal.throwIfAborted();
2163
+ if (lease.kind !== "simulator") return {
2164
+ state: "capture-unavailable",
2165
+ message: "Physical iPhone screen capture is not available on this host."
2166
+ };
2167
+ const directory = await options.files.directory();
2168
+ if (!directory) return {
2169
+ state: "capture-unavailable",
2170
+ message: "This host has no private session frame storage."
2171
+ };
2172
+ const filePath = path.join(directory, `frame-${randomUUID()}.png`);
2173
+ let bytes;
2174
+ try {
2175
+ await pool.simctl.screenshot(lease.udid, filePath, SCREENSHOT_MAX_PIXELS, activeSignal);
2176
+ activeSignal.throwIfAborted();
2177
+ bytes = await options.files.read(filePath, MAX_FRAME_BYTES);
2178
+ if (!PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)) throw new Error("Invalid frame image.");
2179
+ } finally {
2180
+ await options.files.remove(filePath);
2181
+ }
2182
+ activeSignal.throwIfAborted();
2183
+ if (options.pool() !== pool) return { state: "released" };
2184
+ await pool.resolveLease(options.owner, leaseId);
2185
+ activeSignal.throwIfAborted();
2186
+ if (options.pool() !== pool) return { state: "released" };
2187
+ const hash = createHash("sha256").update(bytes).digest("hex");
2188
+ return {
2189
+ state: "ok",
2190
+ src: `data:image/png;base64,${Buffer.from(bytes).toString("base64")}`,
2191
+ hash,
2192
+ capturedAt: Date.now()
2193
+ };
2194
+ });
2195
+ } catch (error) {
2196
+ if (aborter.signal.aborted || activeSignal.aborted) return { state: "released" };
2197
+ if (error instanceof IosError && ["IOS_NO_LEASE", "IOS_LEASE_LOST"].includes(error.code)) return { state: "released" };
2198
+ return {
2199
+ state: "error",
2200
+ message: "Po could not capture this simulator screen."
2201
+ };
2202
+ }
2203
+ };
2204
+ return {
2205
+ async read() {
2206
+ const pool = options.pool();
2207
+ if (!pool || aborter.signal.aborted) return {
2208
+ supported: false,
2209
+ devices: [],
2210
+ error: "The iOS pool is not running on this host."
2211
+ };
2212
+ const [status, phones, build] = await Promise.all([
2213
+ pool.status(options.owner),
2214
+ pool.devices(options.owner),
2215
+ options.latestBuild?.()
2216
+ ]);
2217
+ if (aborter.signal.aborted || options.pool() !== pool) return {
2218
+ supported: false,
2219
+ devices: []
2220
+ };
2221
+ const devices = status.devices.map((device) => ({
2222
+ id: device.udid,
2223
+ name: device.label ?? device.name,
2224
+ kind: "simulator",
2225
+ detail: device.state,
2226
+ state: device.leaseId ? "owned" : device.leased ? "other-session" : "available",
2227
+ ...device.leaseId ? { leaseId: device.leaseId } : {},
2228
+ capture: "available"
2229
+ }));
2230
+ devices.push(...phones.map((phone) => ({
2231
+ id: phone.udid,
2232
+ name: phone.name,
2233
+ kind: "device",
2234
+ detail: `${phone.model} · ${phone.osVersion}`,
2235
+ state: phone.leaseId ? "owned" : phone.leased ? "other-session" : phone.connected ? "available" : "disconnected",
2236
+ ...phone.leaseId ? { leaseId: phone.leaseId } : {},
2237
+ capture: "unsupported"
2238
+ })));
2239
+ return {
2240
+ supported: status.supported,
2241
+ devices,
2242
+ ...build ? { build } : {}
2243
+ };
2244
+ },
2245
+ async frame(leaseId, since, signal) {
2246
+ if (signal?.aborted || aborter.signal.aborted) return { state: "released" };
2247
+ let work = pending.get(leaseId);
2248
+ if (!work) {
2249
+ work = capture(leaseId, signal);
2250
+ pending.set(leaseId, work);
2251
+ }
2252
+ try {
2253
+ const reply = await work;
2254
+ if (signal?.aborted || aborter.signal.aborted) return { state: "released" };
2255
+ return reply.state === "ok" && reply.hash === since ? {
2256
+ state: "unchanged",
2257
+ hash: reply.hash,
2258
+ capturedAt: reply.capturedAt
2259
+ } : reply;
2260
+ } finally {
2261
+ if (pending.get(leaseId) === work) pending.delete(leaseId);
2262
+ }
2263
+ },
2264
+ async dispose() {
2265
+ aborter.abort();
2266
+ await Promise.allSettled(pending.values());
2267
+ pending.clear();
2268
+ }
2269
+ };
2270
+ }
2271
+ //#endregion
2272
+ //#region src/services/iosBuilds/index.ts
2273
+ function validPath(value) {
2274
+ return typeof value === "string" && value.length > 0 && !value.split("").some((character) => character === "\\" || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127) && value.split("/").every((part) => part !== "" && part !== "." && part !== ".." && !part.includes(":"));
2275
+ }
2276
+ function invalidName(name) {
2277
+ return name.split("").some((character) => character === "/" || character === "\\" || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
2278
+ }
2279
+ function view(build) {
2280
+ return {
2281
+ id: build.id,
2282
+ name: build.name,
2283
+ size: build.size,
2284
+ artifactPath: build.artifactPath,
2285
+ registeredAt: build.registeredAt
2286
+ };
2287
+ }
2288
+ function records(value, sessionId) {
2289
+ if (value === void 0 || value === null) return [];
2290
+ if (!Array.isArray(value)) throw new Error("Invalid iOS build registry.");
2291
+ return value.map((entry) => {
2292
+ const build = entry;
2293
+ if (!build || build.sessionId !== sessionId || typeof build.id !== "string" || !/^[a-zA-Z0-9_-]{16,128}$/u.test(build.id) || !validPath(build.artifactPath) || typeof build.name !== "string" || !build.name || invalidName(build.name) || typeof build.registeredAt !== "string" || !Number.isFinite(Date.parse(build.registeredAt)) || typeof build.identity !== "string" || !build.identity || !Number.isSafeInteger(build.size) || (build.size ?? -1) < 0) throw new Error("Invalid or foreign iOS build registry.");
2294
+ return build;
2295
+ });
2296
+ }
2297
+ /** Registration is a trusted code-mode producer action, not inferred from artifact inventory. */
2298
+ function createIosBuilds(options) {
2299
+ let pending = Promise.resolve();
2300
+ const load = async () => records(await options.registry.read(), options.sessionId);
2301
+ const open = async (build) => {
2302
+ const opened = await options.openArtifact(build.artifactPath);
2303
+ if (opened.identity !== build.identity || opened.size !== build.size) {
2304
+ await opened.close();
2305
+ throw new Error("Registered iOS build changed.");
2306
+ }
2307
+ return opened;
2308
+ };
2309
+ return {
2310
+ artifactDirectory: options.artifactDirectory,
2311
+ async latest() {
2312
+ await pending;
2313
+ const build = (await load()).at(-1);
2314
+ if (build === void 0) return void 0;
2315
+ try {
2316
+ await (await open(build)).close();
2317
+ return view(build);
2318
+ } catch {
2319
+ return;
2320
+ }
2321
+ },
2322
+ register(input) {
2323
+ const work = pending.then(async () => {
2324
+ if (!validPath(input.artifactPath) || Object.keys(input).some((key) => key !== "artifactPath" && key !== "name")) throw new Error("Register an artifact-relative build path only.");
2325
+ const name = input.name ?? input.artifactPath.split("/").at(-1);
2326
+ if (typeof name !== "string" || !name.trim() || name.length > 255 || invalidName(name)) throw new Error("Invalid build name.");
2327
+ const opened = await options.openArtifact(input.artifactPath);
2328
+ const { size, identity } = opened;
2329
+ await opened.close();
2330
+ if (!Number.isSafeInteger(size) || size < 0 || !identity) throw new Error("Build must be a regular file.");
2331
+ const build = {
2332
+ id: crypto.randomUUID(),
2333
+ sessionId: options.sessionId,
2334
+ artifactPath: input.artifactPath,
2335
+ name,
2336
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
2337
+ size,
2338
+ identity
2339
+ };
2340
+ await options.registry.write([build]);
2341
+ return view(build);
2342
+ });
2343
+ pending = work.catch(() => void 0);
2344
+ return work;
2345
+ },
2346
+ async share(buildId) {
2347
+ await pending;
2348
+ const build = (await load()).find((entry) => entry.id === buildId);
2349
+ if (build === void 0) return {
2350
+ ok: false,
2351
+ reason: "missing",
2352
+ message: "This build is not registered in this session."
2353
+ };
2354
+ try {
2355
+ await (await open(build)).close();
2356
+ } catch {
2357
+ return {
2358
+ ok: false,
2359
+ reason: "changed",
2360
+ message: "This build changed, was removed, or is no longer accessible. Register a new build."
2361
+ };
2362
+ }
2363
+ if (options.shareRegisteredFile === void 0) return {
2364
+ ok: false,
2365
+ reason: "unavailable",
2366
+ message: "This host cannot share registered builds."
2367
+ };
2368
+ try {
2369
+ const shared = await options.shareRegisteredFile({
2370
+ fileName: build.name,
2371
+ open: () => open(build)
2372
+ });
2373
+ return {
2374
+ ok: true,
2375
+ url: shared.url,
2376
+ expiresAt: shared.expiresAt
2377
+ };
2378
+ } catch (error) {
2379
+ return error instanceof Error && error.message === PO_SHARE_FILE_REMOTE_OFF_MESSAGE ? {
2380
+ ok: false,
2381
+ reason: "remote-off",
2382
+ message: "Remote access is off. Turn it on to download this build."
2383
+ } : {
2384
+ ok: false,
2385
+ reason: "unavailable",
2386
+ message: "This build cannot be shared right now."
2387
+ };
2388
+ }
2389
+ }
2390
+ };
2391
+ }
2392
+ /** Durable latest-build slot in the existing shared DB, never in producer-writable artifacts. */
2393
+ async function createIosBuildRegistry(db, sessionId) {
2394
+ await db.migrate("ios_builds", [{
2395
+ version: 1,
2396
+ statements: ["CREATE TABLE ios_builds_latest (session_id TEXT PRIMARY KEY, registration_json TEXT NOT NULL)"]
2397
+ }]);
2398
+ return {
2399
+ async read() {
2400
+ const row = await db.database.get("SELECT registration_json FROM ios_builds_latest WHERE session_id = ?", sessionId);
2401
+ return row === void 0 ? void 0 : JSON.parse(row.registration_json);
2402
+ },
2403
+ async write(value) {
2404
+ const validated = records(value, sessionId);
2405
+ if (validated.length !== 1) throw new Error("Expected one latest registered iOS build.");
2406
+ await db.database.run("INSERT INTO ios_builds_latest (session_id, registration_json) VALUES (?, ?) ON CONFLICT(session_id) DO UPDATE SET registration_json = excluded.registration_json", sessionId, JSON.stringify(validated));
2407
+ }
2408
+ };
2409
+ }
2410
+ //#endregion
2096
2411
  //#region src/schemas/ios.ts
2097
2412
  const BundleId = Type.String({ pattern: "^[A-Za-z0-9.-]{1,155}$" });
2098
2413
  const LeaseId = Type.String({
@@ -2461,6 +2776,10 @@ interface ElementRef extends ElementQuery { ref?: string; nth?: number }
2461
2776
  type Target = ElementRef | Point;
2462
2777
 
2463
2778
  declare const ios: {
2779
+ /** Host-owned artifact destination. Save a completed build here before registerBuild. */
2780
+ buildDirectory(): Promise<{ path: string }>;
2781
+ /** Explicit producer registration, artifact-relative path only. Does not publish a URL or prove install eligibility. */
2782
+ registerBuild(input: { artifactPath: string; name?: string }): Promise<{ id: string; name: string; size: number; artifactPath: string; registeredAt: string }>;
2464
2783
  /** The shared simulator pool: caps, devices, who holds them, and the queue. */
2465
2784
  status(): Promise<IosStatus>;
2466
2785
  /**
@@ -2574,6 +2893,30 @@ function createIosNamespace(options) {
2574
2893
  return live.devicectl;
2575
2894
  };
2576
2895
  const members = Object.create(null);
2896
+ members.buildDirectory = async () => {
2897
+ run.signal.throwIfAborted();
2898
+ if (disposed) throw new Error("iOS namespace run is disposed.");
2899
+ const builds = await options.builds?.();
2900
+ run.signal.throwIfAborted();
2901
+ if (disposed) throw new Error("iOS namespace run is disposed.");
2902
+ if (builds === void 0) throw new IosError("IOS_UNSUPPORTED_HOST", "This host keeps no registered iOS builds.");
2903
+ return { path: builds.artifactDirectory };
2904
+ };
2905
+ members.registerBuild = async (input) => {
2906
+ run.signal.throwIfAborted();
2907
+ if (disposed) throw new Error("iOS namespace run is disposed.");
2908
+ const builds = await options.builds?.();
2909
+ run.signal.throwIfAborted();
2910
+ if (disposed) throw new Error("iOS namespace run is disposed.");
2911
+ if (builds === void 0) throw new IosError("IOS_UNSUPPORTED_HOST", "This host keeps no registered iOS builds.");
2912
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new IosError("IOS_INVALID_ARGUMENT", "ios.registerBuild needs artifactPath and optional name.");
2913
+ const params = input;
2914
+ if (typeof params.artifactPath !== "string" || params.name !== void 0 && typeof params.name !== "string" || Object.keys(params).some((key) => key !== "artifactPath" && key !== "name")) throw new IosError("IOS_INVALID_ARGUMENT", "ios.registerBuild needs artifactPath and optional name only.");
2915
+ return builds.register({
2916
+ artifactPath: params.artifactPath,
2917
+ ...params.name === void 0 ? {} : { name: params.name }
2918
+ });
2919
+ };
2577
2920
  members.status = async () => pool().status(options.owner);
2578
2921
  members.acquire = async (input) => {
2579
2922
  const params = parse(AcquireSchema, input, "acquire");
@@ -2856,18 +3199,25 @@ function createIosNamespace(options) {
2856
3199
  };
2857
3200
  }
2858
3201
  //#endregion
3202
+ //#region src/types/iosUi.ts
3203
+ /** JSON-only iOS UI contracts. Lease ownership and paths are resolved by the server. */
3204
+ const iosActivityChannel = "ios_activity";
3205
+ const iosActivityReaderEvent = "po-ios:activity-reader";
3206
+ //#endregion
2859
3207
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
2860
3208
  const SCREENSHOTS_DIRECTORY = "ios-screenshots";
2861
- /**
2862
- * Contributes `ios` to code mode over the global pool. Leases belong to the root session, so subagents share
2863
- * their parent's simulator; only the root's own disposal releases them. The pool, code mode and artifacts are
2864
- * injected softly, so a session without them still mounts.
2865
- */
3209
+ /** Leases belong to the root session; build artifacts remain owned by their host session. */
2866
3210
  var root_server_default = defineRoot(async ({ context, host }) => {
2867
3211
  const { sessionId, environment } = host.context;
2868
- if (!sessionId) return { value: {} };
3212
+ if (!sessionId) throw new Error("The iOS session UI requires a session identity.");
2869
3213
  const owner = resolveRootSessionId(sessionId, environment ?? {});
3214
+ let disposed = false;
2870
3215
  let pool;
3216
+ let artifacts;
3217
+ let db;
3218
+ let temporaryDirectory;
3219
+ let builds;
3220
+ let preparingBuilds;
2871
3221
  context.inject([IOS_POOL_SERVICE], (scoped) => {
2872
3222
  const live = scoped.get(IOS_POOL_SERVICE);
2873
3223
  pool = live;
@@ -2875,18 +3225,89 @@ var root_server_default = defineRoot(async ({ context, host }) => {
2875
3225
  if (pool === live) pool = void 0;
2876
3226
  };
2877
3227
  });
2878
- let artifacts;
2879
3228
  context.inject(["po/artifacts"], (scoped) => {
2880
3229
  const storage = scoped.get("po/artifacts");
2881
3230
  artifacts = storage;
2882
3231
  return () => {
2883
- if (artifacts === storage) artifacts = void 0;
3232
+ if (artifacts === storage) {
3233
+ artifacts = void 0;
3234
+ builds = void 0;
3235
+ }
3236
+ };
3237
+ });
3238
+ context.inject([PO_DB_SERVICE], (scoped) => {
3239
+ const live = requirePoDb(scoped);
3240
+ db = live;
3241
+ return () => {
3242
+ if (db === live) {
3243
+ db = void 0;
3244
+ builds = void 0;
3245
+ }
3246
+ };
3247
+ });
3248
+ context.inject([PO_SESSION_FILES_SERVICE], (scoped) => {
3249
+ const directory = scoped.get(PO_SESSION_FILES_SERVICE).temporaryDirectory;
3250
+ temporaryDirectory = directory;
3251
+ return () => {
3252
+ if (temporaryDirectory === directory) temporaryDirectory = void 0;
2884
3253
  };
2885
3254
  });
3255
+ const getBuilds = async () => {
3256
+ if (disposed || !artifacts || !db) return void 0;
3257
+ if (builds) return builds;
3258
+ if (preparingBuilds) return preparingBuilds;
3259
+ const storage = artifacts;
3260
+ const database = db;
3261
+ const work = (async () => {
3262
+ const artifactDirectory = await storage.rootForSession(sessionId, environment ?? {});
3263
+ if (!artifactDirectory) return void 0;
3264
+ const registry = await createIosBuildRegistry(database, sessionId);
3265
+ if (disposed || artifacts !== storage || db !== database) return void 0;
3266
+ builds = createIosBuilds({
3267
+ sessionId,
3268
+ artifactDirectory,
3269
+ registry,
3270
+ openArtifact: (relativePath) => openArtifactDownload(artifactDirectory, relativePath),
3271
+ ...host.context.shareRegisteredFile ? { shareRegisteredFile: (input) => host.context.shareRegisteredFile(input) } : {}
3272
+ });
3273
+ return builds;
3274
+ })();
3275
+ preparingBuilds = work;
3276
+ try {
3277
+ return await work;
3278
+ } finally {
3279
+ if (preparingBuilds === work) preparingBuilds = void 0;
3280
+ }
3281
+ };
3282
+ const ui = createIosActivity({
3283
+ owner,
3284
+ pool: () => pool,
3285
+ latestBuild: async () => (await getBuilds())?.latest(),
3286
+ files: {
3287
+ async directory() {
3288
+ if (!temporaryDirectory) return void 0;
3289
+ const directory = path.join(temporaryDirectory, "ios-frames");
3290
+ getOrThrow(await requirePoFs(context).createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));
3291
+ return directory;
3292
+ },
3293
+ async read(filePath, maxBytes) {
3294
+ const fs = requirePoFs(context);
3295
+ if (getOrThrow(await fs.fileInfo(filePath, BACKGROUND_CONTEXT)).size > maxBytes) throw new Error("Simulator frame is too large.");
3296
+ const bytes = getOrThrow(await fs.readBinaryFile(filePath, BACKGROUND_CONTEXT));
3297
+ if (bytes.length > maxBytes) throw new Error("Simulator frame changed while reading.");
3298
+ return bytes;
3299
+ },
3300
+ async remove(filePath) {
3301
+ getOrThrow(await requirePoFs(context).remove(filePath, { force: true }, BACKGROUND_CONTEXT));
3302
+ }
3303
+ }
3304
+ });
3305
+ host.context.directEvents?.publish(iosActivityReaderEvent, sessionId, ui);
2886
3306
  const namespace = createIosNamespace({
2887
3307
  sessionId,
2888
3308
  owner,
2889
3309
  pool: () => pool,
3310
+ builds: getBuilds,
2890
3311
  files: {
2891
3312
  async exists(filePath) {
2892
3313
  return getOrThrow(await requirePoFs(context).exists(filePath, BACKGROUND_CONTEXT));
@@ -2897,7 +3318,7 @@ var root_server_default = defineRoot(async ({ context, host }) => {
2897
3318
  async screenshotsDirectory() {
2898
3319
  const root = await artifacts?.rootForSession(sessionId, environment ?? {});
2899
3320
  if (root === void 0) return void 0;
2900
- const directory = `${root}/${SCREENSHOTS_DIRECTORY}`;
3321
+ const directory = path.join(root, SCREENSHOTS_DIRECTORY);
2901
3322
  getOrThrow(await requirePoFs(context).createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));
2902
3323
  return directory;
2903
3324
  }
@@ -2908,13 +3329,310 @@ var root_server_default = defineRoot(async ({ context, host }) => {
2908
3329
  return () => registration?.dispose();
2909
3330
  });
2910
3331
  return {
2911
- value: {},
3332
+ value: {
3333
+ ui,
3334
+ getBuilds
3335
+ },
2912
3336
  onDispose: async () => {
3337
+ disposed = true;
3338
+ host.context.directEvents?.publish(iosActivityReaderEvent, sessionId, void 0);
3339
+ await ui.dispose();
2913
3340
  if (owner === sessionId) await pool?.releaseAll(owner);
2914
3341
  }
2915
3342
  };
2916
3343
  });
2917
3344
  //#endregion
3345
+ //#region src/schemas/iosSettingsMethods.ts
3346
+ const Availability = Type.Union([Type.Literal("available"), Type.Literal("excluded")]);
3347
+ const Pool = Type.Object({
3348
+ minBooted: Type.Number(),
3349
+ maxBooted: Type.Number(),
3350
+ maxDevices: Type.Number(),
3351
+ idleShutdownMinutes: Type.Number(),
3352
+ waitTimeoutSeconds: Type.Number(),
3353
+ deviceType: Type.Optional(Type.String()),
3354
+ runtime: Type.Optional(Type.String())
3355
+ });
3356
+ /** Read-only activation snapshot and discovered inventory. Never starts signing, leases or runtimes. */
3357
+ const iosSettingsMethod = definePoPluginMethod({
3358
+ service: "ios",
3359
+ method: "settings",
3360
+ scope: "global",
3361
+ direction: "client-to-server",
3362
+ input: Type.Object({}, { additionalProperties: false }),
3363
+ output: Type.Object({
3364
+ active: Type.Boolean(),
3365
+ configFile: Type.String(),
3366
+ applied: Type.Optional(Type.Object({
3367
+ pool: Pool,
3368
+ developmentTeam: Type.Optional(Type.String()),
3369
+ availability: Type.Record(Type.String(), Availability)
3370
+ })),
3371
+ phones: Type.Array(Type.Object({
3372
+ udid: Type.String(),
3373
+ name: Type.String(),
3374
+ paired: Type.Boolean(),
3375
+ connected: Type.Boolean(),
3376
+ leased: Type.Boolean(),
3377
+ availability: Availability
3378
+ })),
3379
+ runtimes: Type.Array(Type.Object({
3380
+ identifier: Type.String(),
3381
+ name: Type.String(),
3382
+ isAvailable: Type.Boolean(),
3383
+ models: Type.Array(Type.Object({
3384
+ identifier: Type.String(),
3385
+ name: Type.String()
3386
+ }))
3387
+ })),
3388
+ inventoryError: Type.Optional(Type.String()),
3389
+ runtimeError: Type.Optional(Type.String())
3390
+ })
3391
+ });
3392
+ //#endregion
3393
+ //#region src/extensions/(backend)/_lib/settingsMethod.server.ts
3394
+ function createIosSettingsMethod(host, root) {
3395
+ return defineServerMethod(iosSettingsMethod, async () => {
3396
+ const { pool, runtime } = root.resolveIosServices();
3397
+ const result = {
3398
+ active: pool !== void 0 && runtime !== void 0,
3399
+ configFile: runtime?.configFile ?? (host.context.homeDirectory ? `${poHomeDirectory(host.context.homeDirectory, host.context.environment ?? {})}/config.yaml` : ""),
3400
+ ...runtime ? { applied: runtime.applied } : {},
3401
+ phones: [],
3402
+ runtimes: []
3403
+ };
3404
+ if (!pool) return {
3405
+ ...result,
3406
+ inventoryError: "The iOS service is not active.",
3407
+ runtimeError: "The iOS service is not active."
3408
+ };
3409
+ await Promise.all([pool.devices().then((phones) => {
3410
+ result.phones = phones.map(({ udid, name, paired, connected, leased, availability }) => ({
3411
+ udid,
3412
+ name,
3413
+ paired,
3414
+ connected,
3415
+ leased,
3416
+ availability
3417
+ }));
3418
+ }).catch(() => {
3419
+ result.inventoryError = "Physical phone inventory is unavailable on this host.";
3420
+ }), pool.simctl.listRuntimes().then((runtimes) => {
3421
+ result.runtimes = runtimes.filter((runtime) => runtime.platform === "iOS").map((runtime) => ({
3422
+ identifier: runtime.identifier,
3423
+ name: runtime.name,
3424
+ isAvailable: runtime.isAvailable,
3425
+ models: runtime.supportedDeviceTypes.map(({ identifier, name }) => ({
3426
+ identifier,
3427
+ name
3428
+ }))
3429
+ }));
3430
+ }).catch(() => {
3431
+ result.runtimeError = "Simulator models and runtimes could not be discovered on this host.";
3432
+ })]);
3433
+ return result;
3434
+ });
3435
+ }
3436
+ //#endregion
3437
+ //#region src/extensions/(backend)/method/settings.server.ts
3438
+ var settings_server_default = defineRoutedContribution(({ host, root }) => host.scope === "global" ? createIosSettingsMethod(host, root) : void 0, { cardinality: "optional" });
3439
+ //#endregion
3440
+ //#region src/extensions/workspaces/sessions/(backend)/channel/_lib/ios-activity.server.ts
3441
+ const POLL_INTERVAL_MS = 2e3;
3442
+ const unavailable = {
3443
+ supported: false,
3444
+ devices: [],
3445
+ error: "The iOS pool is not connected."
3446
+ };
3447
+ /** Metadata only. Screen capture is a separate authenticated, session-bound request. */
3448
+ function createIosActivityChannel(intervalMs = POLL_INTERVAL_MS) {
3449
+ return {
3450
+ frameType: iosActivityChannel,
3451
+ start(host) {
3452
+ const sessions = /* @__PURE__ */ new Map();
3453
+ let closed = false;
3454
+ const poll = async (session) => {
3455
+ if (closed || session.pending || !session.reader) return;
3456
+ const reader = session.reader;
3457
+ session.pending = true;
3458
+ try {
3459
+ const payload = await reader.read();
3460
+ if (closed || sessions.get(session.scope.sessionId) !== session || session.reader !== reader) return;
3461
+ if (JSON.stringify(session.payload) !== JSON.stringify(payload)) {
3462
+ session.payload = payload;
3463
+ host.publish(session.scope.sessionId, payload);
3464
+ }
3465
+ } catch {
3466
+ if (!closed && sessions.get(session.scope.sessionId) === session && session.reader === reader) {
3467
+ session.payload = {
3468
+ supported: false,
3469
+ devices: [],
3470
+ error: "Po could not read this session’s iOS devices."
3471
+ };
3472
+ host.publish(session.scope.sessionId, session.payload);
3473
+ host.onNotice("iOS Activity could not read the session device inventory.");
3474
+ }
3475
+ } finally {
3476
+ session.pending = false;
3477
+ }
3478
+ };
3479
+ const timer = setInterval(() => {
3480
+ for (const session of sessions.values()) poll(session);
3481
+ }, intervalMs);
3482
+ timer.unref?.();
3483
+ return {
3484
+ payloadFor(scope) {
3485
+ return sessions.get(scope.sessionId)?.payload;
3486
+ },
3487
+ sessionAdded(scope) {
3488
+ if (sessions.has(scope.sessionId)) return;
3489
+ const session = {
3490
+ scope,
3491
+ payload: unavailable,
3492
+ pending: false,
3493
+ unsubscribe: () => void 0
3494
+ };
3495
+ sessions.set(scope.sessionId, session);
3496
+ session.unsubscribe = host.directEvents.subscribe(iosActivityReaderEvent, scope.sessionId, (value) => {
3497
+ if (sessions.get(scope.sessionId) !== session) return;
3498
+ session.reader = value && typeof value === "object" && typeof value.read === "function" ? value : void 0;
3499
+ if (session.reader) poll(session);
3500
+ else {
3501
+ session.payload = unavailable;
3502
+ host.publish(scope.sessionId, unavailable);
3503
+ }
3504
+ }, { replayLatest: true });
3505
+ poll(session);
3506
+ },
3507
+ sessionRemoved(sessionId) {
3508
+ sessions.get(sessionId)?.unsubscribe();
3509
+ sessions.delete(sessionId);
3510
+ },
3511
+ close() {
3512
+ closed = true;
3513
+ clearInterval(timer);
3514
+ for (const session of sessions.values()) session.unsubscribe();
3515
+ sessions.clear();
3516
+ }
3517
+ };
3518
+ }
3519
+ };
3520
+ }
3521
+ //#endregion
3522
+ //#region src/extensions/workspaces/sessions/(backend)/channel/ios-activity.server.ts
3523
+ var ios_activity_server_default = defineChannel(createIosActivityChannel);
3524
+ //#endregion
3525
+ //#region src/schemas/iosUiMethods.ts
3526
+ const address = {
3527
+ service: "ios",
3528
+ scope: "session",
3529
+ direction: "client-to-server"
3530
+ };
3531
+ const Hash = Type.String({ pattern: "^[a-f0-9]{64}$" });
3532
+ const CapturedAt = Type.Number({ minimum: 0 });
3533
+ const IosActivitySchema = Type.Object({
3534
+ supported: Type.Boolean(),
3535
+ devices: Type.Array(Type.Object({
3536
+ id: Type.String(),
3537
+ name: Type.String(),
3538
+ kind: Type.Union([Type.Literal("simulator"), Type.Literal("device")]),
3539
+ detail: Type.String(),
3540
+ state: Type.Union([
3541
+ Type.Literal("owned"),
3542
+ Type.Literal("other-session"),
3543
+ Type.Literal("available"),
3544
+ Type.Literal("disconnected")
3545
+ ]),
3546
+ leaseId: Type.Optional(Type.String()),
3547
+ capture: Type.Union([Type.Literal("available"), Type.Literal("unsupported")])
3548
+ })),
3549
+ build: Type.Optional(Type.Object({
3550
+ id: Type.String(),
3551
+ name: Type.String(),
3552
+ size: Type.Integer({ minimum: 0 }),
3553
+ artifactPath: Type.String(),
3554
+ registeredAt: Type.String()
3555
+ })),
3556
+ error: Type.Optional(Type.String())
3557
+ });
3558
+ const iosStatusMethod = definePoPluginMethod({
3559
+ ...address,
3560
+ method: "status",
3561
+ input: Type.Object({}, { additionalProperties: false }),
3562
+ output: IosActivitySchema
3563
+ });
3564
+ const iosFrameMethod = definePoPluginMethod({
3565
+ ...address,
3566
+ method: "frame",
3567
+ input: Type.Object({
3568
+ leaseId: Type.String({
3569
+ minLength: 1,
3570
+ maxLength: 128
3571
+ }),
3572
+ since: Type.Optional(Hash)
3573
+ }, { additionalProperties: false }),
3574
+ output: Type.Union([
3575
+ Type.Object({
3576
+ state: Type.Literal("ok"),
3577
+ src: Type.String({ maxLength: 6291456 }),
3578
+ hash: Hash,
3579
+ capturedAt: CapturedAt
3580
+ }),
3581
+ Type.Object({
3582
+ state: Type.Literal("unchanged"),
3583
+ hash: Hash,
3584
+ capturedAt: CapturedAt
3585
+ }),
3586
+ Type.Object({ state: Type.Literal("released") }),
3587
+ Type.Object({
3588
+ state: Type.Literal("capture-unavailable"),
3589
+ message: Type.String()
3590
+ }),
3591
+ Type.Object({
3592
+ state: Type.Literal("error"),
3593
+ message: Type.String()
3594
+ })
3595
+ ])
3596
+ });
3597
+ const iosShareBuildMethod = definePoPluginMethod({
3598
+ ...address,
3599
+ method: "shareBuild",
3600
+ input: Type.Object({ buildId: Type.String({
3601
+ minLength: 16,
3602
+ maxLength: 128
3603
+ }) }, { additionalProperties: false }),
3604
+ output: Type.Union([Type.Object({
3605
+ ok: Type.Literal(true),
3606
+ url: Type.String(),
3607
+ expiresAt: Type.Number()
3608
+ }), Type.Object({
3609
+ ok: Type.Literal(false),
3610
+ reason: Type.Union([
3611
+ Type.Literal("remote-off"),
3612
+ Type.Literal("changed"),
3613
+ Type.Literal("missing"),
3614
+ Type.Literal("unavailable")
3615
+ ]),
3616
+ message: Type.String()
3617
+ })])
3618
+ });
3619
+ //#endregion
3620
+ //#region src/extensions/workspaces/sessions/(backend)/method/frame.server.ts
3621
+ var frame_server_default = defineMethod(({ root }) => defineServerMethod(iosFrameMethod, ({ leaseId, since }, caller) => root.ui.frame(leaseId, since, caller.signal)));
3622
+ //#endregion
3623
+ //#region src/extensions/workspaces/sessions/(backend)/method/share-build.server.ts
3624
+ var share_build_server_default = defineMethod(({ root }) => defineServerMethod(iosShareBuildMethod, async ({ buildId }) => {
3625
+ const builds = await root.getBuilds();
3626
+ return builds ? builds.share(buildId) : {
3627
+ ok: false,
3628
+ reason: "unavailable",
3629
+ message: "Session build storage is not available."
3630
+ };
3631
+ }));
3632
+ //#endregion
3633
+ //#region src/extensions/workspaces/sessions/(backend)/method/status.server.ts
3634
+ var status_server_default = defineMethod(({ root }) => defineServerMethod(iosStatusMethod, () => root.ui.read()));
3635
+ //#endregion
2918
3636
  //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-ios.server.ts
2919
3637
  var codemode_how_to_ios_server_default = defineResource({
2920
3638
  name: "codemode-how-to-ios",
@@ -2927,6 +3645,12 @@ var codemode_how_to_ios_server_default = defineResource({
2927
3645
  //#endregion
2928
3646
  //#region generated/server.ts
2929
3647
  const at = (value, context) => typeof value === "function" ? value(context) : value;
3648
+ /* v8 ignore next -- generated normalization branch */
3649
+ const defined = (values) => values.filter((value) => value !== void 0);
3650
+ const via = (identity, value) => value === void 0 ? void 0 : {
3651
+ ...identity,
3652
+ ...value
3653
+ };
2930
3654
  const serverPlugin = defineServerPlugin({
2931
3655
  name: "@agimon-ai/po-ios",
2932
3656
  providerOverrides: composeServerProviderOverrides(root_server_default$2, root_server_default$1, root_server_default),
@@ -2941,8 +3665,15 @@ const serverPlugin = defineServerPlugin({
2941
3665
  }),
2942
3666
  global: async (context) => {
2943
3667
  const scopeGlobal = await context.scopeRoot("global", root_server_default$2, context);
3668
+ const contextGlobal = {
3669
+ ...context,
3670
+ root: scopeGlobal.value
3671
+ };
2944
3672
  return {
2945
3673
  ...composeRootHooks(scopeGlobal),
3674
+ get methods() {
3675
+ return defined([at(settings_server_default, contextGlobal)]);
3676
+ },
2946
3677
  services: [...scopeGlobal.services ?? []]
2947
3678
  };
2948
3679
  },
@@ -2955,6 +3686,9 @@ const serverPlugin = defineServerPlugin({
2955
3686
  const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, contextGlobal);
2956
3687
  return {
2957
3688
  ...composeRootHooks(scopeGlobal, scopeWorkspace),
3689
+ get methods() {
3690
+ return defined([context.hosted("global") ? void 0 : at(settings_server_default, contextGlobal)]);
3691
+ },
2958
3692
  services: [...scopeGlobal.services ?? [], ...scopeWorkspace.services ?? []]
2959
3693
  };
2960
3694
  },
@@ -2976,6 +3710,17 @@ const serverPlugin = defineServerPlugin({
2976
3710
  };
2977
3711
  return {
2978
3712
  ...composeRootHooks(scopeGlobal, scopeWorkspace, scopeSession),
3713
+ get channels() {
3714
+ return [() => via({ frameType: "ios_activity" }, at(ios_activity_server_default, contextSession))];
3715
+ },
3716
+ get methods() {
3717
+ return defined([
3718
+ context.hosted("global") ? void 0 : at(settings_server_default, contextGlobal),
3719
+ at(frame_server_default, contextSession),
3720
+ at(share_build_server_default, contextSession),
3721
+ at(status_server_default, contextSession)
3722
+ ]);
3723
+ },
2979
3724
  get resources() {
2980
3725
  return [at(codemode_how_to_ios_server_default, contextSession)];
2981
3726
  },