@codingfrees/uap-device-control 0.1.9 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,6 +72,8 @@ npx @codingfrees/uap-device-control@latest install-service
72
72
 
73
73
  The same runtime is persisted using the platform adapter (Windows scheduled startup, Linux systemd user service, macOS launchd).
74
74
 
75
+ The `install-service` command refuses to install a second persistent Remote if an installed Runner V2 is detected on Windows or Linux; temporary `remote` mode remains independent. Service installation stages the runtime atomically and retains a `.previous` copy for rollback if registration fails. This is not a signed automatic update channel; npm publishing and OS-service updating remain separate lifecycles.
76
+
75
77
  ## npm client versus ChatGPT MCP
76
78
 
77
79
  The npm client does **not** use MCP as its device transport. It needs the public UAP origin for OAuth and the outbound Device Control routes under `/device-control/remote/*`.
@@ -92,4 +94,6 @@ pnpm publish:public
92
94
 
93
95
  Validate the exact release without publishing with `pnpm publish:public -- --dry-run`.
94
96
 
97
+ For `npm whoami` HTTP 401 in Linux/WSL, renew authentication locally using `npm login --registry=https://registry.npmjs.org/ --auth-type=web`, then confirm `npm whoami`. Do not paste credentials into issue reports or logs. npm versions are immutable: bump the package version and commit a clean tree before publishing.
98
+
95
99
  The script requires a clean repository, refuses an already-published version, builds and dry-runs the package, then calls npm publish and verifies the registry version plus the `latest` dist-tag. npm account 2FA remains mandatory and is handled by npm during the publish step.
@@ -407,7 +407,7 @@ import path4 from "node:path";
407
407
  // package.json
408
408
  var package_default = {
409
409
  name: "@codingfrees/uap-device-control",
410
- version: "0.1.9",
410
+ version: "0.1.12",
411
411
  description: "Cross-platform outbound UAP Device Control client",
412
412
  type: "module",
413
413
  bin: {
@@ -1507,6 +1507,7 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
1507
1507
  let pairingCode = pairing ? void 0 : createPairingCode();
1508
1508
  let pairingExpiresAt = pairingCode ? Date.now() + 10 * 6e4 : 0;
1509
1509
  let lastSeen = 0;
1510
+ let permissionsGranted = false;
1510
1511
  let waiter;
1511
1512
  const queue = [];
1512
1513
  const pending = /* @__PURE__ */ new Map();
@@ -1538,12 +1539,13 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
1538
1539
  return send(response, 200, { token, port: actualPort(server) }, origin);
1539
1540
  }
1540
1541
  const current = authorize(request2, origin, pairing);
1541
- if (url.pathname === "/browser/status" && request2.method === "POST") return send(response, 200, { paired: true, online: Date.now() - lastSeen < 45e3 }, current.origin);
1542
+ if (url.pathname === "/browser/status" && request2.method === "POST") return send(response, 200, { paired: true, online: Date.now() - lastSeen < 45e3, permissionsGranted }, current.origin);
1542
1543
  if (url.pathname === "/browser/unpair" && request2.method === "POST") {
1543
1544
  pairing = void 0;
1544
1545
  pairingCode = createPairingCode();
1545
1546
  pairingExpiresAt = Date.now() + 10 * 6e4;
1546
1547
  lastSeen = 0;
1548
+ permissionsGranted = false;
1547
1549
  await writeFile3(statePath, JSON.stringify({ version: 1 }) + "\n", { mode: 384 });
1548
1550
  rejectAll(pending, "browser bridge was unpaired");
1549
1551
  log?.({ event: "browser.bridge", status: "unpaired" });
@@ -1551,9 +1553,13 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
1551
1553
  return send(response, 200, { unpaired: true }, current.origin);
1552
1554
  }
1553
1555
  if (url.pathname === "/browser/poll" && request2.method === "POST") {
1556
+ const body = await jsonBody(request2);
1554
1557
  const wasOffline = Date.now() - lastSeen >= 45e3;
1558
+ const previousPermissions = permissionsGranted;
1559
+ permissionsGranted = body.permissionsGranted === true;
1555
1560
  lastSeen = Date.now();
1556
1561
  if (wasOffline) log?.({ event: "browser.bridge", status: "connected" });
1562
+ if (previousPermissions !== permissionsGranted) log?.({ event: "browser.bridge", status: permissionsGranted ? "permissions-granted" : "permissions-required" });
1557
1563
  const command = queue.shift() ?? await new Promise((resolve) => {
1558
1564
  const timer = setTimeout(() => {
1559
1565
  if (waiter === done) waiter = void 0;
@@ -1601,11 +1607,11 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
1601
1607
  return pairingCode;
1602
1608
  },
1603
1609
  available() {
1604
- return Boolean(pairing);
1610
+ return Boolean(pairing && permissionsGranted && Date.now() - lastSeen < 45e3);
1605
1611
  },
1606
1612
  execute(capability, parameters) {
1607
1613
  if (!BROWSER_CONTROL_CAPABILITIES.includes(capability)) throw new TypeError("browser capability is unavailable");
1608
- if (!pairing || Date.now() - lastSeen >= 45e3) return Promise.reject(new TypeError("browser control extension is unavailable"));
1614
+ if (!pairing || !permissionsGranted || Date.now() - lastSeen >= 45e3) return Promise.reject(new TypeError("browser control extension is unavailable or missing permissions"));
1609
1615
  const requestId = randomUUID3();
1610
1616
  const command = { requestId, capability, parameters };
1611
1617
  const completion = new Promise((resolve, reject) => {
@@ -1734,7 +1740,7 @@ async function runRemote(options) {
1734
1740
  };
1735
1741
  const browserLog = (event) => {
1736
1742
  options.log?.(event);
1737
- if (event.event === "browser.bridge" && (event.status === "paired" || event.status === "unpaired")) refreshSession();
1743
+ if (event.event === "browser.bridge" && ["paired", "unpaired", "connected", "permissions-granted", "permissions-required"].includes(String(event.status))) refreshSession();
1738
1744
  };
1739
1745
  const browser = options.browserControl === false ? void 0 : await createBrowserBridge(options.stateDirectory, options.browserPort ?? 8800, browserLog).catch((error) => {
1740
1746
  if (!optionalBrowserBridgeFailure(error)) throw error;
@@ -1772,13 +1778,14 @@ async function runRemote(options) {
1772
1778
  continue;
1773
1779
  }
1774
1780
  if (error instanceof RemoteAuthorizationError) throw new TypeError("Device Control authorization was rejected after refresh; run login again");
1775
- if (!(error instanceof RemoteUnavailableError)) throw error;
1781
+ if (!(error instanceof RemoteUnavailableError || error instanceof RemoteSessionExpiredError)) throw error;
1782
+ const httpStatus = error instanceof RemoteSessionExpiredError ? 409 : error.httpStatus;
1776
1783
  options.log?.({
1777
1784
  event: "remote.session",
1778
1785
  status: "reconnecting",
1779
1786
  deviceId,
1780
1787
  retryMs: delay,
1781
- ...error.httpStatus === void 0 ? {} : { httpStatus: error.httpStatus },
1788
+ ...httpStatus === void 0 ? {} : { httpStatus },
1782
1789
  ...error.pathname === void 0 ? {} : { pathname: error.pathname }
1783
1790
  });
1784
1791
  await sleep2(delay, options.signal);
@@ -1802,7 +1809,7 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
1802
1809
  const invoke2 = (pathname, body, requestSignal = signal, timeoutMs = 15e3, requestLog = log) => authorizedRequest(fetcher, origin, stateDirectory, pathname, body, requestSignal, timeoutMs, requestLog, deviceId);
1803
1810
  const connected = await invoke2("/device-control/remote/connect", { device: engine.info() });
1804
1811
  const sessionId = bounded2(connected.sessionId, "remote session id");
1805
- log?.({ event: "remote.session", status: "connected", deviceId });
1812
+ log?.({ event: "remote.session", status: "connected", deviceId, agentVersion: UAP_DEVICE_CONTROL_AGENT_VERSION });
1806
1813
  try {
1807
1814
  while (!signal?.aborted) {
1808
1815
  const next = await invoke2("/device-control/remote/poll", { sessionId, deviceId }, signal, 35e3);
@@ -1853,6 +1860,10 @@ async function request(fetcher, origin, pathname, token, body, signal, timeoutMs
1853
1860
  throw new RemoteUnavailableError(void 0, pathname);
1854
1861
  }
1855
1862
  if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError(response.status, pathname);
1863
+ if (response.status === 409 && pathname === "/device-control/remote/poll") {
1864
+ const body2 = await response.json().catch(() => void 0);
1865
+ if (body2 && typeof body2 === "object" && !Array.isArray(body2) && "error" in body2 && body2.error === "session_expired") throw new RemoteSessionExpiredError(pathname);
1866
+ }
1856
1867
  if (!response.ok) throw new RemoteUnavailableError(response.status, pathname);
1857
1868
  const raw = await response.json();
1858
1869
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("remote response is invalid");
@@ -1873,6 +1884,13 @@ async function remoteStatus(origin, stateDirectory, deviceId, fetcher = fetch) {
1873
1884
  function defaultRemoteRoots(cwd = process.cwd()) {
1874
1885
  return [{ id: "cwd", label: "Current directory", path: path4.resolve(cwd), readOnly: false }];
1875
1886
  }
1887
+ var RemoteSessionExpiredError = class extends Error {
1888
+ constructor(pathname) {
1889
+ super("remote broker session expired");
1890
+ this.pathname = pathname;
1891
+ }
1892
+ pathname;
1893
+ };
1876
1894
  var RemoteUnavailableError = class extends Error {
1877
1895
  constructor(httpStatus, pathname) {
1878
1896
  super("remote endpoint is unavailable");
@@ -1932,35 +1950,80 @@ function safeError(error) {
1932
1950
  }
1933
1951
  function sleep2(ms, signal) {
1934
1952
  return new Promise((resolve) => {
1935
- const timer = setTimeout(resolve, ms);
1936
- const abort = () => {
1953
+ const finish = () => {
1937
1954
  clearTimeout(timer);
1955
+ signal?.removeEventListener("abort", finish);
1938
1956
  resolve();
1939
1957
  };
1940
- signal?.addEventListener("abort", abort, { once: true });
1958
+ const timer = setTimeout(finish, ms);
1959
+ signal?.addEventListener("abort", finish, { once: true });
1960
+ if (signal?.aborted) finish();
1941
1961
  });
1942
1962
  }
1943
1963
 
1944
1964
  // src/service.ts
1945
1965
  import os4 from "node:os";
1946
1966
  import path5 from "node:path";
1947
- import { chmod, copyFile, mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
1967
+ import { chmod, copyFile, mkdir as mkdir4, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
1968
+ import { existsSync } from "node:fs";
1948
1969
  import { execFile as execFile4 } from "node:child_process";
1949
1970
  import { promisify as promisify4 } from "node:util";
1950
1971
  var execute4 = promisify4(execFile4);
1951
1972
  async function installRemoteService(origin, stateDirectory) {
1973
+ if (await runnerV2Installed()) throw new TypeError("Runner V2 is installed; use its Device Control provider instead of installing a duplicate Remote service");
1952
1974
  const command = process.execPath;
1953
1975
  const source = process.argv[1];
1954
1976
  if (!source) throw new TypeError("CLI executable path is unavailable");
1955
1977
  await mkdir4(stateDirectory, { recursive: true, mode: 448 });
1956
1978
  const script = path5.join(stateDirectory, "uap-device-control.mjs");
1957
- await copyFile(source, script);
1958
- if (process.platform !== "win32") await chmod(script, 448);
1979
+ const staged = script + ".pending-" + process.pid;
1980
+ const previous = script + ".previous";
1959
1981
  const args = [script, "remote", "--origin", origin, "--state-dir", stateDirectory, "--service"];
1960
- if (process.platform === "linux") return installSystemd(command, args);
1961
- if (process.platform === "darwin") return installLaunchd(command, args);
1962
- if (process.platform === "win32") return installWindowsTask(command, args);
1963
- throw new TypeError("service installation is unsupported on this platform");
1982
+ try {
1983
+ await copyFile(source, staged);
1984
+ if (process.platform !== "win32") await chmod(staged, 448);
1985
+ if (existsSync(script)) await copyFile(script, previous);
1986
+ await rename3(staged, script);
1987
+ try {
1988
+ if (process.platform === "linux") return await installSystemd(command, args);
1989
+ if (process.platform === "darwin") return await installLaunchd(command, args);
1990
+ if (process.platform === "win32") return await installWindowsTask(command, args);
1991
+ throw new TypeError("service installation is unsupported on this platform");
1992
+ } catch (error) {
1993
+ if (existsSync(previous)) await copyFile(previous, script);
1994
+ throw error;
1995
+ }
1996
+ } finally {
1997
+ await rm3(staged, { force: true }).catch(() => void 0);
1998
+ }
1999
+ }
2000
+ async function runnerV2Installed(platform = process.platform, run = execute4, exists2 = existsSync) {
2001
+ if (platform === "linux") {
2002
+ if (exists2("/opt/uap-local-node-runner-v2/current")) return true;
2003
+ for (const args of [
2004
+ ["list-unit-files", "uap-local-node-runner-v2.service", "--no-legend"],
2005
+ ["--user", "list-unit-files", "uap-local-node-runner-v2.service", "--no-legend"]
2006
+ ]) {
2007
+ try {
2008
+ const result = await run("systemctl", args);
2009
+ if (/^uap-local-node-runner-v2\.service\s/m.test(result.stdout)) return true;
2010
+ } catch {
2011
+ }
2012
+ }
2013
+ }
2014
+ if (platform === "win32") {
2015
+ for (const [command, args] of [
2016
+ ["sc.exe", ["query", "UAPLocalNodeRunnerV2"]],
2017
+ ["schtasks.exe", ["/Query", "/TN", "UAPLocalNodeRunnerV2"]]
2018
+ ]) {
2019
+ try {
2020
+ await run(command, [...args]);
2021
+ return true;
2022
+ } catch {
2023
+ }
2024
+ }
2025
+ }
2026
+ return false;
1964
2027
  }
1965
2028
  async function installSystemd(command, args) {
1966
2029
  const directory = path5.join(os4.homedir(), ".config", "systemd", "user");
@@ -2138,7 +2201,7 @@ function formatCliEvent(event, json2 = false) {
2138
2201
  if (status === "unpaired") return "\u{1F50C} UAP Browser Extension unpaired";
2139
2202
  }
2140
2203
  if (event.event === "remote.session") {
2141
- if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId);
2204
+ if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId) + (event.agentVersion ? " \xB7 v" + String(event.agentVersion) : "");
2142
2205
  if (status === "disconnected") return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId);
2143
2206
  if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted" + httpDetail(event) + " \xB7 retrying in " + String(event.retryMs) + " ms";
2144
2207
  if (status === "reauthorizing") return "\u{1F510} Refreshing Device Control authorization" + httpDetail(event);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codingfrees/uap-device-control",
3
- "version": "0.1.9",
3
+ "version": "0.1.12",
4
4
  "description": "Cross-platform outbound UAP Device Control client",
5
5
  "type": "module",
6
6
  "bin": {