@agentconnect.md/computer 2.8.0-rc.2 → 2.8.0-rc.4

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.
@@ -517,21 +517,21 @@ var require_cross_spawn = __commonJS({
517
517
  var cp = __require("child_process");
518
518
  var parse3 = require_parse();
519
519
  var enoent = require_enoent();
520
- function spawn6(command, args, options) {
520
+ function spawn8(command, args, options) {
521
521
  const parsed = parse3(command, args, options);
522
522
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
523
523
  enoent.hookChildProcess(spawned, parsed);
524
524
  return spawned;
525
525
  }
526
- function spawnSync9(command, args, options) {
526
+ function spawnSync10(command, args, options) {
527
527
  const parsed = parse3(command, args, options);
528
528
  const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
529
529
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
530
530
  return result;
531
531
  }
532
- module.exports = spawn6;
533
- module.exports.spawn = spawn6;
534
- module.exports.sync = spawnSync9;
532
+ module.exports = spawn8;
533
+ module.exports.spawn = spawn8;
534
+ module.exports.sync = spawnSync10;
535
535
  module.exports._parse = parse3;
536
536
  module.exports._enoent = enoent;
537
537
  }
@@ -31457,10 +31457,10 @@ var require_websocket_server = __commonJS({
31457
31457
  });
31458
31458
 
31459
31459
  // src/cli.ts
31460
- import { existsSync as existsSync6, rmSync as rmSync7, writeFileSync as writeFileSync10 } from "node:fs";
31460
+ import { existsSync as existsSync8, rmSync as rmSync8, writeFileSync as writeFileSync11 } from "node:fs";
31461
31461
  import { hostname as hostname5, networkInterfaces as networkInterfaces2 } from "node:os";
31462
- import { basename as basename2, join as join12 } from "node:path";
31463
- import { createInterface as createInterface2 } from "node:readline";
31462
+ import { basename as basename2, join as join13 } from "node:path";
31463
+ import { createInterface as createInterface3 } from "node:readline";
31464
31464
  import { parseArgs } from "node:util";
31465
31465
 
31466
31466
  // ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.1/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -83841,6 +83841,9 @@ var NodeStreamableHTTPServerTransport = class {
83841
83841
  }
83842
83842
  };
83843
83843
 
83844
+ // src/local-controls.ts
83845
+ import { existsSync as existsSync2 } from "node:fs";
83846
+
83844
83847
  // src/linux/dbus.ts
83845
83848
  import { createConnection as createConnection2 } from "node:net";
83846
83849
  var Variant = class {
@@ -84659,6 +84662,202 @@ var Tray = class _Tray {
84659
84662
  }
84660
84663
  };
84661
84664
 
84665
+ // src/tray-helper.ts
84666
+ import { spawn as spawn3 } from "node:child_process";
84667
+ import { createInterface } from "node:readline";
84668
+ var HelperTray = class _HelperTray {
84669
+ constructor(child2, options) {
84670
+ this.child = child2;
84671
+ this.options = options;
84672
+ }
84673
+ child;
84674
+ options;
84675
+ // Undefined while the helper shows the icon; otherwise why it cannot.
84676
+ problem;
84677
+ last = "";
84678
+ closed = false;
84679
+ static start(path, options) {
84680
+ const child2 = (options.spawnHelper ?? ((file2) => spawn3(file2, [], { stdio: ["pipe", "pipe", "inherit"] })))(path);
84681
+ const tray = new _HelperTray(child2, options);
84682
+ child2.stdin?.on("error", () => void 0);
84683
+ child2.on("error", (error62) => tray.gone(`cannot start the menu bar helper: ${error62.message}`));
84684
+ child2.on("exit", (code, signal) => tray.gone(`the menu bar helper exited (${signal ?? `code ${code}`})`));
84685
+ if (child2.stdout) createInterface({ input: child2.stdout }).on("line", (line) => tray.received(line));
84686
+ return tray;
84687
+ }
84688
+ update(menu) {
84689
+ const line = `${JSON.stringify({ menu })}
84690
+ `;
84691
+ if (line === this.last || this.problem) return;
84692
+ this.last = line;
84693
+ this.child.stdin?.write(line);
84694
+ }
84695
+ close() {
84696
+ this.closed = true;
84697
+ this.child.stdin?.end();
84698
+ }
84699
+ received(line) {
84700
+ let message;
84701
+ try {
84702
+ message = JSON.parse(line);
84703
+ } catch {
84704
+ return;
84705
+ }
84706
+ if (message.action === "click" && typeof message.id === "string") this.options.onClick(message.id);
84707
+ if (message.action === "menu-open") this.options.onMenuOpen();
84708
+ if (message.action === "restart") this.options.onRestart();
84709
+ }
84710
+ gone(problem) {
84711
+ if (this.closed || this.problem) return;
84712
+ this.problem = problem;
84713
+ this.options.log(`tray: ${problem}`);
84714
+ }
84715
+ };
84716
+
84717
+ // src/menu-bar.ts
84718
+ var CONTROL_PLANE = {
84719
+ connected: ["ok", "connected"],
84720
+ connecting: ["progress", "connecting\u2026"],
84721
+ disconnected: ["fail", "disconnected, click to retry"],
84722
+ revoked: ["fail", "revoked, add this Mac again in the console"],
84723
+ unregistered: ["fail", "not registered"]
84724
+ };
84725
+ var grant = (label, state, id) => state === void 0 ? { id, title: `${label}: unknown, click to open Settings`, mark: "warn" } : state === "allowed" ? { id, title: `${label}: allowed`, mark: "ok" } : state === "stale" ? { id: `reset-${id}`, title: `${label}: not in effect, click to reset and allow again`, mark: "fail" } : { id, title: `${label}: not allowed, click to open Settings`, mark: "fail" };
84726
+ function menuBarMenu(tray, facts, busy = /* @__PURE__ */ new Set()) {
84727
+ const [cpMark, cpText] = busy.has("control-plane") ? CONTROL_PLANE.connecting : CONTROL_PLANE[facts.controlPlane.state];
84728
+ const driver = busy.has("driver") ? { title: `Cua Driver ${facts.driver.version}: installing\u2026`, mark: "progress", enabled: false } : facts.driver.running ? { id: "cua-driver", title: `Cua Driver ${facts.driver.version}: running`, mark: "ok", enabled: false } : { id: "cua-driver", title: `Cua Driver ${facts.driver.version}: not running, click to reinstall`, mark: "fail" };
84729
+ const ffmpeg = busy.has("ffmpeg") || facts.ffmpeg.installing ? { title: `ffmpeg ${facts.ffmpeg.version}: downloading\u2026`, mark: "progress", enabled: false } : facts.ffmpeg.installed ? { id: "ffmpeg", title: `ffmpeg ${facts.ffmpeg.version}: installed`, mark: "ok", enabled: false } : facts.ffmpeg.installable ? { id: "ffmpeg", title: `ffmpeg ${facts.ffmpeg.version}: not installed, click to install`, mark: "fail" } : { title: "ffmpeg: not found, the viewer falls back to screenshots", mark: "warn", enabled: false };
84730
+ const version2 = facts.appVersion ? `Version ${facts.version} (app ${facts.appVersion})` : `Version ${facts.version}`;
84731
+ return {
84732
+ tone: tray.tone,
84733
+ tooltip: `AgentConnect Computer: ${tray.status}`,
84734
+ items: [
84735
+ { title: facts.name ? `AgentConnect Computer \xB7 ${facts.name}` : "AgentConnect Computer", enabled: false },
84736
+ { title: `Agents: ${tray.status}`, enabled: false },
84737
+ tray.canResume ? { id: "resume", title: "Resume Agent Input" } : { id: "stop", title: "Stop All Agent Input", enabled: tray.canStop },
84738
+ { title: "", separator: true },
84739
+ {
84740
+ id: "control-plane",
84741
+ title: `Control Plane${facts.controlPlane.host ? ` (${facts.controlPlane.host})` : ""}: ${cpText}`,
84742
+ mark: cpMark,
84743
+ enabled: cpMark === "fail" && facts.controlPlane.state !== "revoked"
84744
+ },
84745
+ grant("Screen Recording", facts.screenRecording, "screen-recording"),
84746
+ grant("Device Control (Accessibility)", facts.accessibility, "accessibility"),
84747
+ driver,
84748
+ ffmpeg,
84749
+ { title: "", separator: true },
84750
+ { id: "start-at-login", title: "Start at Login", checked: facts.startAtLogin },
84751
+ { id: "logs", title: "Open Logs" },
84752
+ { title: version2, enabled: false },
84753
+ { title: "", separator: true },
84754
+ {
84755
+ id: "uninstall",
84756
+ title: "Uninstall\u2026",
84757
+ confirm: {
84758
+ title: "Uninstall AgentConnect Computer?",
84759
+ message: "Terminal opens and runs the uninstaller: it stops the service and removes the app. Your Computer key and settings stay unless you run it with --purge.",
84760
+ button: "Uninstall"
84761
+ }
84762
+ },
84763
+ {
84764
+ id: "quit",
84765
+ title: "Quit AgentConnect Computer",
84766
+ confirm: {
84767
+ title: "Quit AgentConnect Computer?",
84768
+ message: "Agents cannot use this Mac until it starts again at your next login.",
84769
+ button: "Quit"
84770
+ }
84771
+ }
84772
+ ]
84773
+ };
84774
+ }
84775
+ function startMenuBar(helper, host, initial, start = HelperTray.start) {
84776
+ let tray = initial;
84777
+ let facts;
84778
+ const busy = /* @__PURE__ */ new Set();
84779
+ const render = () => {
84780
+ if (facts) helperTray.update(menuBarMenu(tray, facts, busy));
84781
+ };
84782
+ const refresh = () => host.facts().then(
84783
+ (fresh) => {
84784
+ facts = fresh;
84785
+ render();
84786
+ },
84787
+ (error62) => host.log(`menu bar: cannot read the status: ${error62.message}`)
84788
+ );
84789
+ const task = (kind, run3) => {
84790
+ if (busy.has(kind)) return;
84791
+ busy.add(kind);
84792
+ render();
84793
+ void run3().catch((error62) => host.log(`menu bar: ${kind}: ${error62.message}`)).finally(() => {
84794
+ busy.delete(kind);
84795
+ void refresh();
84796
+ });
84797
+ };
84798
+ const click = (id) => {
84799
+ switch (id) {
84800
+ case "stop":
84801
+ return host.stop();
84802
+ case "resume":
84803
+ return host.resume();
84804
+ case "control-plane":
84805
+ return task("control-plane", async () => {
84806
+ if (!await host.reconnect()) host.openLogs();
84807
+ });
84808
+ case "screen-recording":
84809
+ return host.openSettings("screenRecording");
84810
+ case "accessibility":
84811
+ return host.openSettings("accessibility");
84812
+ case "reset-screen-recording":
84813
+ return host.resetGrant("screenRecording");
84814
+ case "reset-accessibility":
84815
+ return host.resetGrant("accessibility");
84816
+ case "cua-driver":
84817
+ return task("driver", () => host.installDriver());
84818
+ case "ffmpeg":
84819
+ return task("ffmpeg", () => host.installFfmpeg());
84820
+ case "start-at-login":
84821
+ host.setStartAtLogin(!(facts?.startAtLogin ?? true));
84822
+ return void refresh();
84823
+ case "logs":
84824
+ return host.openLogs();
84825
+ case "uninstall":
84826
+ return host.uninstall();
84827
+ case "quit":
84828
+ return host.quit();
84829
+ }
84830
+ };
84831
+ const helperTray = start(helper, {
84832
+ onClick: click,
84833
+ onMenuOpen: () => void refresh(),
84834
+ onRestart: () => {
84835
+ host.log("macOS asked AgentConnect Computer to quit; restarting the service");
84836
+ host.restart();
84837
+ },
84838
+ log: host.log
84839
+ });
84840
+ void refresh();
84841
+ return {
84842
+ update(state) {
84843
+ tray = state;
84844
+ render();
84845
+ },
84846
+ checks() {
84847
+ const problem = helperTray.problem;
84848
+ return [
84849
+ problem ? {
84850
+ name: "tray",
84851
+ status: "warn",
84852
+ detail: `${problem}: no local indicator; stop agents with agentconnect-computer pause`,
84853
+ fix: "restart the service: agentconnect-computer service restart"
84854
+ } : { name: "tray", status: "ok", detail: "the menu bar icon shows agent control and can stop it" }
84855
+ ];
84856
+ },
84857
+ close: () => helperTray.close()
84858
+ };
84859
+ }
84860
+
84662
84861
  // src/local-controls.ts
84663
84862
  var TRAY_STOP_REASON = "stopped from the tray";
84664
84863
  var HOTKEY_STOP_REASON = "stopped with the stop hotkey";
@@ -84684,17 +84883,77 @@ function trayState(computer, refusal) {
84684
84883
  return { tone: "online", status: "ready, no agent in control", ...flags };
84685
84884
  }
84686
84885
  var TRAY_REFRESH_MS = 2e3;
84886
+ function ownerActions({ computer, log: log40 }) {
84887
+ return {
84888
+ stop(reason) {
84889
+ if (computer.liveStatus() === "paused") return;
84890
+ computer.pause(reason);
84891
+ log40(`PAUSED (${reason}): all agent input is blocked until the owner resumes`);
84892
+ },
84893
+ resume() {
84894
+ if (!trayState(computer, void 0).canResume) return;
84895
+ computer.resume();
84896
+ log40("resumed from the tray");
84897
+ }
84898
+ };
84899
+ }
84900
+ function refreshing(controls, log40) {
84901
+ controls.update();
84902
+ const refresh = setInterval(() => controls.update(), TRAY_REFRESH_MS);
84903
+ refresh.unref();
84904
+ for (const check2 of controls.checks().filter((check3) => check3.status === "warn")) {
84905
+ log40(`local controls: ${check2.name}: ${check2.detail}`);
84906
+ }
84907
+ const close = controls.close;
84908
+ return {
84909
+ ...controls,
84910
+ close() {
84911
+ clearInterval(refresh);
84912
+ close();
84913
+ }
84914
+ };
84915
+ }
84916
+ function startMacLocalControls(options) {
84917
+ const { computer, log: log40 } = options;
84918
+ const actions = ownerActions(options);
84919
+ const helper = options.menuBar?.helper;
84920
+ const problem = !options.menuBar ? "no menu bar host" : !helper ? "the daemon runs outside AgentConnect Computer.app" : !existsSync2(helper) ? "this AgentConnect Computer.app has no menu bar helper" : void 0;
84921
+ const menuBar = problem || !helper || !options.menuBar ? void 0 : startMenuBar(
84922
+ helper,
84923
+ { ...options.menuBar.host, stop: () => actions.stop(TRAY_STOP_REASON), resume: actions.resume, log: log40 },
84924
+ trayState(computer, options.refusal()),
84925
+ options.startHelperTray
84926
+ );
84927
+ return refreshing(
84928
+ {
84929
+ keyboard: () => false,
84930
+ checks: () => menuBar?.checks() ?? [
84931
+ {
84932
+ name: "tray",
84933
+ status: "warn",
84934
+ detail: `${problem}: no local indicator; stop agents with agentconnect-computer pause`,
84935
+ fix: "update the app with agentconnect computer upgrade, then restart the service"
84936
+ }
84937
+ ],
84938
+ update() {
84939
+ menuBar?.update(trayState(computer, options.refusal()));
84940
+ },
84941
+ close() {
84942
+ menuBar?.close();
84943
+ }
84944
+ },
84945
+ log40
84946
+ );
84947
+ }
84687
84948
  async function startLocalControls(options) {
84688
84949
  const env = options.env ?? process.env;
84689
- if ((options.platform ?? process.platform) !== "linux" || !env.DISPLAY || env.WAYLAND_DISPLAY) return void 0;
84950
+ const platform = options.platform ?? process.platform;
84951
+ if (platform === "darwin") return startMacLocalControls(options);
84952
+ if (platform !== "linux" || !env.DISPLAY || env.WAYLAND_DISPLAY) return void 0;
84690
84953
  const { computer, log: log40 } = options;
84691
84954
  const hotkey = options.stopHotkey ? parseHotkey(options.stopHotkey) : void 0;
84692
84955
  const hotkeyInvalid = options.stopHotkey && !hotkey ? `"${options.stopHotkey}" is not a valid hotkey` : void 0;
84693
- const stop = (reason) => {
84694
- if (computer.liveStatus() === "paused") return;
84695
- computer.pause(reason);
84696
- log40(`PAUSED (${reason}): all agent input is blocked until the owner resumes`);
84697
- };
84956
+ const { stop, resume } = ownerActions(options);
84698
84957
  let x11;
84699
84958
  let x11Problem;
84700
84959
  try {
@@ -84713,11 +84972,7 @@ async function startLocalControls(options) {
84713
84972
  try {
84714
84973
  tray = await (options.startTray ?? Tray.start)({
84715
84974
  onStop: () => stop(TRAY_STOP_REASON),
84716
- onResume: () => {
84717
- if (!trayState(computer, void 0).canResume) return;
84718
- computer.resume();
84719
- log40("resumed from the tray");
84720
- },
84975
+ onResume: resume,
84721
84976
  ...hotkey ? { hotkeyLabel: hotkey.label } : {},
84722
84977
  log: log40
84723
84978
  });
@@ -84757,22 +85012,16 @@ async function startLocalControls(options) {
84757
85012
  tray?.update(trayState(computer, options.refusal()));
84758
85013
  },
84759
85014
  close() {
84760
- clearInterval(refresh);
84761
85015
  x11?.close();
84762
85016
  tray?.close();
84763
85017
  }
84764
85018
  };
84765
- controls.update();
84766
- const refresh = setInterval(() => controls.update(), TRAY_REFRESH_MS);
84767
- refresh.unref();
84768
- const problems = controls.checks().filter((check2) => check2.status === "warn");
84769
- for (const check2 of problems) log40(`local controls: ${check2.name}: ${check2.detail}`);
84770
- return controls;
85019
+ return refreshing(controls, log40);
84771
85020
  }
84772
85021
 
84773
85022
  // src/self.ts
84774
85023
  import { execFile } from "node:child_process";
84775
- import { resolve } from "node:path";
85024
+ import { dirname as dirname2, resolve } from "node:path";
84776
85025
  function runSelf(args, timeoutMs) {
84777
85026
  const argv = [process.argv[1], ...args];
84778
85027
  return new Promise((resolve2, reject) => {
@@ -84788,13 +85037,14 @@ function runSelf(args, timeoutMs) {
84788
85037
  });
84789
85038
  }
84790
85039
  var appBundlePath = () => /^(.*\.app)\/Contents\/MacOS\/[^/]+$/.exec(process.execPath)?.[1];
85040
+ var menuBarHelperPath = () => appBundlePath() ? resolve(dirname2(process.execPath), "agentconnect-computer-menubar") : void 0;
84791
85041
  var selfCommand = () => process.env.AGENTCONNECT_COMPUTER_COMMAND?.trim() || "agentconnect-computer";
84792
85042
  var SERVICE_ENTRY_ENV = "AGENTCONNECT_COMPUTER_SERVICE_ENTRY";
84793
85043
  var managedEntry = () => process.env[SERVICE_ENTRY_ENV]?.trim() || void 0;
84794
85044
  var serviceEntry = () => managedEntry() ?? resolve(process.argv[1]);
84795
85045
 
84796
85046
  // src/version.ts
84797
- var COMPUTER_DAEMON_VERSION = true ? "2.8.0-rc.2" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
85047
+ var COMPUTER_DAEMON_VERSION = true ? "2.8.0-rc.4" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
84798
85048
 
84799
85049
  // src/http-server.ts
84800
85050
  var CONTROL_HEADER = "x-agentconnect-computer";
@@ -84925,7 +85175,7 @@ async function control(req, res, path, options) {
84925
85175
  // src/stream/ffmpeg.ts
84926
85176
  import { spawnSync as spawnSync3 } from "node:child_process";
84927
85177
  import { createHash as createHash4 } from "node:crypto";
84928
- import { existsSync as existsSync2, mkdirSync as mkdirSync5, mkdtempSync as mkdtempSync2, renameSync as renameSync3, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "node:fs";
85178
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, mkdtempSync as mkdtempSync2, renameSync as renameSync3, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "node:fs";
84929
85179
  import { join as join6 } from "node:path";
84930
85180
  import { gunzipSync } from "node:zlib";
84931
85181
 
@@ -85055,16 +85305,25 @@ var installedFfmpegPath = (dataDir2) => join6(dataDir2, "ffmpeg", FFMPEG_VERSION
85055
85305
  function resolveFfmpegPath(dataDir2, explicit) {
85056
85306
  if (explicit) return explicit;
85057
85307
  const installed = installedFfmpegPath(dataDir2);
85058
- return existsSync2(installed) ? installed : binaryName2();
85308
+ return existsSync3(installed) ? installed : binaryName2();
85059
85309
  }
85060
85310
  function ffmpegAvailable(command) {
85061
85311
  const probe = spawnSync3(command, ["-hide_banner", "-version"], { stdio: "ignore", windowsHide: true });
85062
85312
  return probe.status === 0;
85063
85313
  }
85064
85314
  var canInstallFfmpeg = () => pinnedBuild() !== void 0;
85065
- async function installFfmpeg(dataDir2, log40 = console.log) {
85315
+ var downloads = /* @__PURE__ */ new Map();
85316
+ var ffmpegInstalling = (dataDir2) => downloads.has(installedFfmpegPath(dataDir2));
85317
+ function installFfmpeg(dataDir2, log40 = console.log) {
85066
85318
  const target = installedFfmpegPath(dataDir2);
85067
- if (existsSync2(target)) return target;
85319
+ const running = downloads.get(target);
85320
+ if (running) return running;
85321
+ const download = downloadFfmpeg(dataDir2, target, log40).finally(() => downloads.delete(target));
85322
+ downloads.set(target, download);
85323
+ return download;
85324
+ }
85325
+ async function downloadFfmpeg(dataDir2, target, log40) {
85326
+ if (existsSync3(target)) return target;
85068
85327
  const build3 = pinnedBuild();
85069
85328
  if (!build3) throw new Error("no pinned ffmpeg for this platform; install it with your package manager");
85070
85329
  log40(`Downloading ${build3.url} (for the WebRTC viewer)`);
@@ -107708,7 +107967,7 @@ function selectedPairType(pc) {
107708
107967
  var onlyCandidatesFor = (sdp, address) => sdp.split("\r\n").filter((line) => !line.startsWith("a=candidate:") || line.split(" ")[4] === address).join("\r\n");
107709
107968
 
107710
107969
  // src/stream/screen-stream.ts
107711
- import { spawn as spawn3 } from "node:child_process";
107970
+ import { spawn as spawn4 } from "node:child_process";
107712
107971
  import { createSocket as createSocket3 } from "node:dgram";
107713
107972
  import { once as once2 } from "node:events";
107714
107973
  var EARLY_EXIT_MS = 4e3;
@@ -107773,7 +108032,7 @@ var ScreenStream = class {
107773
108032
  ...encodeArgs(this.options, input2.filters, this.socket.address().port)
107774
108033
  ];
107775
108034
  const startedAt = Date.now();
107776
- const child2 = spawn3(this.options.ffmpeg(), args, {
108035
+ const child2 = spawn4(this.options.ffmpeg(), args, {
107777
108036
  stdio: [input2.producer ? "pipe" : "ignore", "ignore", "pipe"],
107778
108037
  windowsHide: true
107779
108038
  });
@@ -107786,7 +108045,7 @@ var ScreenStream = class {
107786
108045
  child2.stderr.on("data", collect);
107787
108046
  let producer;
107788
108047
  if (input2.producer) {
107789
- const feeder = spawn3(input2.producer.command, input2.producer.args, { stdio: ["ignore", "pipe", "pipe"] });
108048
+ const feeder = spawn4(input2.producer.command, input2.producer.args, { stdio: ["ignore", "pipe", "pipe"] });
107790
108049
  producer = feeder;
107791
108050
  this.children.add(feeder);
107792
108051
  feeder.stdout.pipe(child2.stdin);
@@ -108573,22 +108832,22 @@ function createViewer(options) {
108573
108832
  }
108574
108833
 
108575
108834
  // src/keep-awake.ts
108576
- import { spawn as spawn4, spawnSync as spawnSync4 } from "node:child_process";
108835
+ import { spawn as spawn5, spawnSync as spawnSync4 } from "node:child_process";
108577
108836
  function keepDisplayAwake(log40) {
108578
108837
  let child2;
108579
108838
  if (process.platform === "darwin") {
108580
108839
  wakeDisplay();
108581
- child2 = spawn4("caffeinate", ["-d", "-i", "-w", String(process.pid)], { stdio: "ignore" });
108840
+ child2 = spawn5("caffeinate", ["-d", "-i", "-w", String(process.pid)], { stdio: "ignore" });
108582
108841
  } else if (process.platform === "win32") {
108583
108842
  const script = `$t = Add-Type -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);' -Name Power -Namespace AgentConnect -PassThru
108584
108843
  [void]$t::SetThreadExecutionState([uint32]2147483651)
108585
108844
  Wait-Process -Id ${process.pid}`;
108586
- child2 = spawn4("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
108845
+ child2 = spawn5("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
108587
108846
  stdio: "ignore",
108588
108847
  windowsHide: true
108589
108848
  });
108590
108849
  } else if (process.platform === "linux" && gnomeSession() && hasCommand("gnome-session-inhibit")) {
108591
- child2 = spawn4(
108850
+ child2 = spawn5(
108592
108851
  "gnome-session-inhibit",
108593
108852
  [
108594
108853
  "--inhibit",
@@ -108644,9 +108903,9 @@ function readGrantRecord(dir) {
108644
108903
  function recordGrants(dir, state, asked, now = /* @__PURE__ */ new Date()) {
108645
108904
  const record2 = readGrantRecord(dir);
108646
108905
  const at = now.toISOString();
108647
- for (const grant of ["accessibility", "screenRecording"]) {
108648
- if (state[grant]) record2.held[grant] ??= at;
108649
- else if (asked) record2.asked[grant] ??= at;
108906
+ for (const grant2 of ["accessibility", "screenRecording"]) {
108907
+ if (state[grant2]) record2.held[grant2] ??= at;
108908
+ else if (asked) record2.asked[grant2] ??= at;
108650
108909
  }
108651
108910
  try {
108652
108911
  writeFileSync6(grantRecordPath(dir), `${JSON.stringify(record2, null, 2)}
@@ -108655,9 +108914,19 @@ function recordGrants(dir, state, asked, now = /* @__PURE__ */ new Date()) {
108655
108914
  }
108656
108915
  return record2;
108657
108916
  }
108658
- function grantLoss(record2, grant) {
108659
- if (record2.held[grant]) return "lost";
108660
- return record2.asked[grant] ? "listed-off" : "never-asked";
108917
+ function forgetGrant(dir, grant2) {
108918
+ const record2 = readGrantRecord(dir);
108919
+ delete record2.asked[grant2];
108920
+ delete record2.held[grant2];
108921
+ try {
108922
+ writeFileSync6(grantRecordPath(dir), `${JSON.stringify(record2, null, 2)}
108923
+ `, { mode: 384 });
108924
+ } catch {
108925
+ }
108926
+ }
108927
+ function grantLoss(record2, grant2) {
108928
+ if (record2.held[grant2]) return "lost";
108929
+ return record2.asked[grant2] ? "listed-off" : "never-asked";
108661
108930
  }
108662
108931
 
108663
108932
  // src/cp/authority.ts
@@ -109074,6 +109343,14 @@ var ComputerCpClient = class {
109074
109343
  this.transport?.close(1e3, "shutdown");
109075
109344
  this.transport = void 0;
109076
109345
  }
109346
+ /** Skips the backoff wait and dials now, as the owner's menu bar asks; a live or ended channel is left alone. */
109347
+ reconnectNow() {
109348
+ if (this.state !== "DEGRADED" || this.reconnectTimer === void 0) return;
109349
+ this.clock.clearTimeout(this.reconnectTimer);
109350
+ this.reconnectTimer = void 0;
109351
+ this.backoff.reset();
109352
+ void this.attempt();
109353
+ }
109077
109354
  /** Send a heartbeat now, e.g. when the status or the facts changed. */
109078
109355
  beat() {
109079
109356
  if (this.state !== "READY" || !this.transport) return;
@@ -109302,264 +109579,105 @@ function consoleStopHandler(computer, changed) {
109302
109579
  };
109303
109580
  }
109304
109581
 
109305
- // src/cp/relay-links.ts
109306
- var HELLO_TIMEOUT_MS = 15e3;
109307
- var RelayLink = class {
109308
- constructor(entry, deps, clock) {
109309
- this.entry = entry;
109310
- this.deps = deps;
109311
- this.clock = clock;
109312
- this.backoff = new Backoff(deps.jitter ? { jitter: deps.jitter } : {});
109313
- }
109314
- entry;
109315
- deps;
109316
- clock;
109317
- state = "CONNECTING";
109318
- transport;
109319
- timer;
109320
- backoff;
109321
- start() {
109322
- void this.attempt();
109323
- }
109324
- stop() {
109325
- this.state = "STOPPED";
109326
- this.clearTimer();
109327
- this.transport?.close(1e3, "shutdown");
109328
- this.transport = void 0;
109329
- }
109330
- dial(url2) {
109331
- if (this.deps.connect) return this.deps.connect(url2);
109332
- return ClientTransport.dial(url2, {
109333
- subprotocol: RELAY_COMPUTER_SUBPROTOCOL,
109334
- path: new URL(url2).pathname,
109335
- maxPayload: RELAY_COMPUTER_MAX_FRAME_BYTES
109336
- });
109337
- }
109338
- async attempt() {
109339
- if (this.state === "STOPPED") return;
109340
- this.state = "CONNECTING";
109341
- const token = this.deps.token();
109342
- if (!token) return this.wait();
109343
- let transport;
109344
- try {
109345
- transport = await this.dial(relayComputerWsUrl(this.entry.url));
109346
- } catch (error62) {
109347
- this.deps.log(`relay ${this.entry.relayId}: cannot connect: ${error62.message}`);
109348
- return this.wait();
109349
- }
109350
- if (this.state !== "CONNECTING") return void transport.close(1e3, "shutdown");
109351
- this.transport = transport;
109352
- this.state = "HELLO";
109353
- const hello = buildRelayComputerFrame("cr/hello", {
109354
- computerId: this.deps.computerId,
109355
- token,
109356
- desktopDaemonVersion: this.deps.desktopDaemonVersion
109357
- });
109358
- transport.onMessage((text) => this.onText(transport, hello.id, text));
109359
- transport.onClose((code, reason) => this.onClose(transport, code, reason));
109360
- this.timer = this.clock.setTimeout(() => {
109361
- this.timer = void 0;
109362
- if (this.state === "HELLO" && this.transport === transport) transport.close(1e3, "hello timeout");
109363
- }, HELLO_TIMEOUT_MS);
109364
- transport.send(JSON.stringify(hello));
109365
- }
109366
- onText(transport, helloId, text) {
109367
- if (this.transport !== transport) return;
109368
- const decoded = decodeRelayComputerFrame(text);
109369
- if (!decoded.ok) return this.deps.log(`relay ${this.entry.relayId}: unreadable frame (${decoded.msg})`);
109370
- const frame = decoded.frame;
109371
- if (this.state === "HELLO") return this.onHelloReply(transport, helloId, frame);
109372
- if (this.state === "READY" && frame.type === "cr/http") return void this.serve(transport, frame);
109373
- }
109374
- onHelloReply(transport, helloId, frame) {
109375
- if (frame.corr !== helloId) return;
109376
- this.clearTimer();
109377
- if (frame.type === "cr/hello/ok" && frame.payload.relayId === this.entry.relayId) {
109378
- this.state = "READY";
109379
- this.backoff.reset();
109380
- this.deps.log(`relay ${this.entry.relayId}: attached`);
109381
- return;
109382
- }
109383
- const why = frame.type === "error" ? frame.payload.message : `reached relay ${String(frame.payload.relayId)}`;
109384
- this.deps.log(`relay ${this.entry.relayId}: not attached (${why})`);
109385
- transport.close(1e3, "hello refused");
109386
- }
109387
- async serve(transport, frame) {
109388
- let response;
109389
- try {
109390
- response = await this.deps.handle(frame.payload);
109391
- } catch (error62) {
109392
- this.deps.log(`relay ${this.entry.relayId}: request failed: ${error62.message}`);
109393
- response = { status: 500, headers: {} };
109394
- }
109395
- if (this.transport !== transport || this.state !== "READY") return;
109396
- try {
109397
- transport.send(JSON.stringify(buildRelayComputerFrame("cr/http/result", response, { corr: frame.id })));
109398
- } catch (error62) {
109399
- this.deps.log(`relay ${this.entry.relayId}: reply failed: ${error62.message}`);
109400
- }
109401
- }
109402
- onClose(transport, code, reason) {
109403
- if (this.transport !== transport) return;
109404
- this.transport = void 0;
109405
- this.clearTimer();
109406
- if (this.state === "STOPPED") return;
109407
- this.deps.log(`relay ${this.entry.relayId}: closed (${code}${reason ? ` ${reason}` : ""})`);
109408
- this.wait();
109409
- }
109410
- wait() {
109411
- if (this.state === "STOPPED") return;
109412
- this.state = "WAITING";
109413
- this.clearTimer();
109414
- this.timer = this.clock.setTimeout(() => {
109415
- this.timer = void 0;
109416
- void this.attempt();
109417
- }, this.backoff.next());
109418
- }
109419
- clearTimer() {
109420
- if (this.timer !== void 0) this.clock.clearTimeout(this.timer);
109421
- this.timer = void 0;
109422
- }
109423
- };
109424
- var RelayLinks = class {
109425
- constructor(deps) {
109426
- this.deps = deps;
109427
- this.clock = deps.clock ?? systemClock;
109428
- }
109429
- deps;
109430
- links = /* @__PURE__ */ new Map();
109431
- clock;
109432
- converge(relays) {
109433
- const wanted = new Map(relays.map((entry) => [entry.relayId, entry]));
109434
- for (const [id, link] of this.links) {
109435
- const entry = wanted.get(id);
109436
- if (entry && entry.url === link.entry.url) continue;
109437
- link.stop();
109438
- this.links.delete(id);
109439
- }
109440
- for (const [id, entry] of wanted) {
109441
- const current = this.links.get(id);
109442
- if (current && current.state !== "WAITING") continue;
109443
- current?.stop();
109444
- const link = new RelayLink(entry, this.deps, this.clock);
109445
- this.links.set(id, link);
109446
- link.start();
109447
- }
109448
- }
109449
- /** Close every link: on revoke, a lapsed key or shutdown. */
109450
- stop() {
109451
- for (const link of this.links.values()) link.stop();
109452
- this.links.clear();
109453
- }
109454
- /** Relay ids with an attached link. */
109455
- attached() {
109456
- return [...this.links.values()].filter((link) => link.state === "READY").map((link) => link.entry.relayId);
109457
- }
109458
- };
109582
+ // src/menu-bar-host.ts
109583
+ import { spawn as spawn7, spawnSync as spawnSync7 } from "node:child_process";
109584
+ import { chmodSync as chmodSync2, existsSync as existsSync6, readFileSync as readFileSync5, rmSync as rmSync6, writeFileSync as writeFileSync9 } from "node:fs";
109585
+ import { tmpdir } from "node:os";
109586
+ import { join as join11 } from "node:path";
109459
109587
 
109460
- // src/mcp-access.ts
109461
- var bearer = (authorization) => /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1];
109462
- function channelPrincipal(authorization, authority, computerId) {
109463
- const token = bearer(authorization);
109464
- const id = computerId();
109465
- if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
109466
- const claims = authority.verify(token, "mcp", id);
109467
- if (!claims?.ses || !claims.agt) return void 0;
109468
- return {
109469
- client: computerLeaseHolderName({ agentId: claims.agt, sessionId: claims.ses }),
109470
- viewOnly: claims.mode === "view",
109471
- agent: { agentId: claims.agt, sessionId: claims.ses }
109472
- };
109588
+ // src/service-macos.ts
109589
+ import { spawnSync as spawnSync5 } from "node:child_process";
109590
+ import { existsSync as existsSync4, mkdirSync as mkdirSync6, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "node:fs";
109591
+ import { homedir as homedir3 } from "node:os";
109592
+ import { join as join8 } from "node:path";
109593
+ var SERVICE_LABEL = "md.agentconnect.computer";
109594
+ var plistPath = () => join8(homedir3(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
109595
+ var domain2 = () => `gui/${process.getuid()}`;
109596
+ var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
109597
+ function launchctl(...args) {
109598
+ const result = spawnSync5("launchctl", args, { encoding: "utf8" });
109599
+ return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };
109473
109600
  }
109474
- var RESPONSE_HEADERS = ["allow", "content-type", "mcp-protocol-version", "mcp-session-id", "www-authenticate"];
109475
- function reply(status, body, headers = {}) {
109476
- return {
109477
- status,
109478
- headers: { "content-type": "application/json", ...headers },
109479
- body: Buffer.from(JSON.stringify(body)).toString("base64")
109480
- };
109601
+ var guiSession = () => launchctl("print", domain2()).ok;
109602
+ function servicePlist(program, logPath) {
109603
+ return `<?xml version="1.0" encoding="UTF-8"?>
109604
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
109605
+ <plist version="1.0">
109606
+ <dict>
109607
+ <key>Label</key><string>${SERVICE_LABEL}</string>
109608
+ <key>ProgramArguments</key><array>${[...program, "run"].map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
109609
+ <key>AssociatedBundleIdentifiers</key><array><string>${SERVICE_LABEL}</string></array>
109610
+ <key>LimitLoadToSessionType</key><string>Aqua</string>
109611
+ <key>ProcessType</key><string>Interactive</string>
109612
+ <key>RunAtLoad</key><true/>
109613
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
109614
+ <key>StandardOutPath</key><string>${xml(logPath)}</string>
109615
+ <key>StandardErrorPath</key><string>${xml(logPath)}</string>
109616
+ <key>EnvironmentVariables</key><dict><key>NODE_OPTIONS</key><string></string></dict>
109617
+ </dict>
109618
+ </plist>
109619
+ `;
109481
109620
  }
109482
- function viewerPrincipal(authorization, authority, computerId) {
109483
- const token = bearer(authorization);
109484
- const id = computerId();
109485
- if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
109486
- const claims = authority.verify(token, "view", id);
109487
- if (!claims?.usr) return void 0;
109488
- return {
109489
- client: `console:${claims.usr}`,
109490
- control: claims.mode === "control",
109491
- iceServers: claims.ice ?? [],
109492
- stunUrls: claims.stun ?? [],
109493
- valid: () => authority.verify(token, "view", id) !== void 0
109494
- };
109621
+ function installService(program, logPath) {
109622
+ mkdirSync6(join8(homedir3(), "Library", "LaunchAgents"), { recursive: true });
109623
+ stopService();
109624
+ writeFileSync7(plistPath(), servicePlist(program, logPath));
109625
+ if (!guiSession()) return false;
109626
+ startService();
109627
+ return true;
109495
109628
  }
109496
- function viewerAuthenticator(member, localClient) {
109497
- return (authorization, via) => {
109498
- const principal = member(authorization);
109499
- if (principal) return principal;
109500
- if (via !== "local") return void 0;
109501
- const client = localClient(authorization);
109502
- return client ? { client, control: true } : void 0;
109503
- };
109629
+ function startArgs(status, uid) {
109630
+ if (status.loaded && status.pid !== void 0) return void 0;
109631
+ return status.loaded ? ["kickstart", `gui/${uid}/${SERVICE_LABEL}`] : ["bootstrap", `gui/${uid}`, plistPath()];
109504
109632
  }
109505
- function createRelayedMcpHandler(deps) {
109506
- return async (request2) => {
109507
- const pathname = new URL(request2.path, "http://desktop.invalid").pathname;
109508
- if (deps.viewer && pathname.startsWith(COMPUTER_VIEWER_API_PREFIX)) {
109509
- const out = await deps.viewer({
109510
- method: request2.method,
109511
- path: pathname,
109512
- authorization: request2.headers.authorization,
109513
- via: "relay",
109514
- ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
109515
- });
109516
- if (out.body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
109517
- return {
109518
- status: out.status,
109519
- headers: out.headers,
109520
- ...out.body.length > 0 ? { body: out.body.toString("base64") } : {}
109521
- };
109522
- }
109523
- if (pathname !== "/mcp") return reply(404, { error: "not found" });
109524
- const principal = deps.authenticate(request2.headers.authorization);
109525
- if (!principal) return reply(401, { error: "unauthorized" }, { "www-authenticate": "Bearer" });
109526
- if (request2.method !== "POST" && request2.method !== "DELETE") {
109527
- return reply(405, { error: "method not allowed" }, { allow: "POST, DELETE" });
109528
- }
109529
- const mcp = deps.createMcpServer(principal);
109530
- const transport = new WebStandardStreamableHTTPServerTransport({
109531
- sessionIdGenerator: void 0,
109532
- enableJsonResponse: true
109533
- });
109534
- try {
109535
- await mcp.connect(transport);
109536
- const response = await transport.handleRequest(
109537
- new Request("http://desktop.invalid/mcp", {
109538
- method: request2.method,
109539
- headers: request2.headers,
109540
- ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
109541
- })
109542
- );
109543
- const body = Buffer.from(await response.arrayBuffer());
109544
- if (body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
109545
- const headers = {};
109546
- for (const name of RESPONSE_HEADERS) {
109547
- const value = response.headers.get(name);
109548
- if (value !== null) headers[name] = value;
109549
- }
109550
- return { status: response.status, headers, ...body.length > 0 ? { body: body.toString("base64") } : {} };
109551
- } catch (error62) {
109552
- deps.log(`relayed request failed: ${error62.message}`);
109553
- return reply(500, { error: "failed" });
109554
- } finally {
109555
- void mcp.close().catch(() => void 0);
109556
- }
109557
- };
109633
+ function startService() {
109634
+ const args = startArgs(serviceStatus(), process.getuid());
109635
+ if (!args) return;
109636
+ if (!guiSession()) throw new Error("nobody is logged in to this Mac's desktop: the service starts at the next login");
109637
+ setStartAtLogin(true);
109638
+ const result = launchctl(...args);
109639
+ if (!result.ok) throw new Error(`launchctl ${args[0]} failed: ${result.output}`);
109640
+ }
109641
+ function stopService() {
109642
+ if (!serviceStatus().loaded) return;
109643
+ launchctl("bootout", `${domain2()}/${SERVICE_LABEL}`);
109644
+ const deadline = Date.now() + 1e4;
109645
+ while (serviceStatus().loaded && Date.now() < deadline) spawnSync5("sleep", ["0.2"]);
109646
+ }
109647
+ function restartService() {
109648
+ const result = launchctl("kickstart", "-k", `${domain2()}/${SERVICE_LABEL}`);
109649
+ if (!result.ok) throw new Error(`launchctl kickstart failed: ${result.output}`);
109650
+ }
109651
+ function uninstallService() {
109652
+ stopService();
109653
+ rmSync4(plistPath(), { force: true });
109654
+ }
109655
+ function serviceStatus() {
109656
+ const installed = existsSync4(plistPath());
109657
+ const result = launchctl("print", `${domain2()}/${SERVICE_LABEL}`);
109658
+ if (!result.ok) return { installed, loaded: false };
109659
+ const pid = /^\s*pid = (\d+)/m.exec(result.output)?.[1];
109660
+ const state = /^\s*state = (\S+)/m.exec(result.output)?.[1];
109661
+ return { installed, loaded: true, ...pid ? { pid: Number(pid) } : {}, ...state ? { state } : {} };
109662
+ }
109663
+ function startsAtLogin() {
109664
+ if (!existsSync4(plistPath())) return false;
109665
+ const disabled = launchctl("print-disabled", domain2()).output;
109666
+ return ![`"${SERVICE_LABEL}" => disabled`, `"${SERVICE_LABEL}" => true`].some((line) => disabled.includes(line));
109667
+ }
109668
+ function setStartAtLogin(on) {
109669
+ launchctl(on ? "enable" : "disable", `${domain2()}/${SERVICE_LABEL}`);
109558
109670
  }
109559
109671
 
109672
+ // src/setup.ts
109673
+ import { spawn as spawn6, spawnSync as spawnSync6 } from "node:child_process";
109674
+ import { existsSync as existsSync5 } from "node:fs";
109675
+ import { basename, dirname as dirname3, isAbsolute, join as join10 } from "node:path";
109676
+ import { createInterface as createInterface2 } from "node:readline";
109677
+
109560
109678
  // src/cp/registration.ts
109561
- import { chmodSync, closeSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync4, renameSync as renameSync4, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "node:fs";
109562
- import { join as join8 } from "node:path";
109679
+ import { chmodSync, closeSync, mkdirSync as mkdirSync7, openSync, readFileSync as readFileSync4, renameSync as renameSync4, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "node:fs";
109680
+ import { join as join9 } from "node:path";
109563
109681
  var Registration = external_exports.object({
109564
109682
  cpUrl: external_exports.string().url(),
109565
109683
  channelUrl: external_exports.string().url(),
@@ -109575,7 +109693,7 @@ var Registration = external_exports.object({
109575
109693
  revokedAt: external_exports.string().datetime().optional(),
109576
109694
  revokedReason: external_exports.string().optional()
109577
109695
  });
109578
- var registrationPath = (dir = dataDir()) => join8(dir, "computer-key.json");
109696
+ var registrationPath = (dir = dataDir()) => join9(dir, "computer-key.json");
109579
109697
  function loadRegistration(dir = dataDir()) {
109580
109698
  let raw;
109581
109699
  try {
@@ -109587,16 +109705,16 @@ function loadRegistration(dir = dataDir()) {
109587
109705
  return Registration.parse(JSON.parse(raw));
109588
109706
  }
109589
109707
  function saveRegistration(registration, dir = dataDir()) {
109590
- mkdirSync6(dir, { recursive: true, mode: 448 });
109708
+ mkdirSync7(dir, { recursive: true, mode: 448 });
109591
109709
  if (process.platform !== "win32") chmodSync(dir, 448);
109592
109710
  const path = registrationPath(dir);
109593
109711
  const tmp = `${path}.tmp`;
109594
109712
  const body = `${JSON.stringify(Registration.parse(registration), null, 2)}
109595
109713
  `;
109596
- rmSync4(tmp, { force: true });
109714
+ rmSync5(tmp, { force: true });
109597
109715
  const fd = openSync(tmp, "wx", 384);
109598
109716
  try {
109599
- writeFileSync7(fd, body);
109717
+ writeFileSync8(fd, body);
109600
109718
  } finally {
109601
109719
  closeSync(fd);
109602
109720
  }
@@ -109659,1277 +109777,1620 @@ async function registerOrKeep(dir, cpUrl, register3) {
109659
109777
  }
109660
109778
  }
109661
109779
 
109662
- // src/cp/report.ts
109663
- import { spawnSync as spawnSync5 } from "node:child_process";
109664
- import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync5 } from "node:fs";
109665
- import { release as release2 } from "node:os";
109666
- var MAX_CHECKS = 64;
109667
- var MAX_TEXT = 1e3;
109668
- var computerOs = (platform = process.platform) => platform === "darwin" ? "macos" : platform === "win32" ? "windows" : "linux";
109669
- function osVersion(platform = process.platform) {
109670
- if (platform === "linux") {
109671
- try {
109672
- const pretty = /^PRETTY_NAME="?([^"\n]+)"?$/m.exec(readFileSync5("/etc/os-release", "utf8"))?.[1];
109673
- if (pretty) return pretty.slice(0, 120);
109674
- } catch {
109675
- }
109676
- }
109677
- if (platform === "darwin") {
109678
- const result = spawnSync5("sw_vers", ["-productVersion"], { encoding: "utf8" });
109679
- if (result.status === 0 && result.stdout.trim()) return `macOS ${result.stdout.trim()}`;
109680
- }
109681
- return `${platform} ${release2()}`.slice(0, 120);
109682
- }
109683
- function xvfbServes(display) {
109684
- const number4 = /^:(\d+)/.exec(display)?.[1];
109685
- if (number4 === void 0) return false;
109686
- try {
109687
- for (const pid of readdirSync("/proc")) {
109688
- if (!/^\d+$/.test(pid)) continue;
109689
- const argv = readFileSync5(`/proc/${pid}/cmdline`, "utf8").split("\0");
109690
- if (/(^|\/)Xvfb$/.test(argv[0] ?? "") && argv.includes(`:${number4}`)) return true;
109691
- }
109692
- } catch {
109780
+ // src/setup.ts
109781
+ var localizeChecks = (checks, command = selfCommand()) => {
109782
+ const rename = (text) => text.replace(/(?<![\w/.-])agentconnect-computer(?= |$)/g, command);
109783
+ return checks.map((check2) => ({
109784
+ ...check2,
109785
+ detail: rename(check2.detail),
109786
+ ...check2.fix === void 0 ? {} : { fix: rename(check2.fix) }
109787
+ }));
109788
+ };
109789
+ var ICON = { ok: "\u2705", info: "\u2139\uFE0F ", warn: "\u26A0\uFE0F ", fail: "\u274C" };
109790
+ var FIREWALL_RULE = "AgentConnect Computer (Node.js)";
109791
+ var MAC_PANES = {
109792
+ accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
109793
+ screenRecording: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
109794
+ };
109795
+ function printChecks(checks) {
109796
+ const width = Math.max(...checks.map((check2) => check2.name.length));
109797
+ for (const check2 of checks) {
109798
+ console.log(`${ICON[check2.status]} ${check2.name.padEnd(width)} ${check2.detail}`);
109799
+ if (check2.fix && check2.status !== "ok") console.log(` ${" ".repeat(width)} \u2192 ${check2.fix}`);
109693
109800
  }
109694
- return false;
109695
- }
109696
- function sessionKind(platform = process.platform, env = process.env) {
109697
- if (platform === "darwin") return "aqua";
109698
- if (platform === "win32") return env.SESSIONNAME?.startsWith("RDP") ? "rdp" : "console";
109699
- if (env.WAYLAND_DISPLAY) return "wayland-gnome";
109700
- return env.DISPLAY && xvfbServes(env.DISPLAY) ? "xvfb" : "x11";
109701
- }
109702
- function isolationKind(env = process.env) {
109703
- const declared = env.AGENTCONNECT_COMPUTER_ISOLATION;
109704
- if (declared === "none" || declared === "container" || declared === "vm") return declared;
109705
- return existsSync3("/.dockerenv") || existsSync3("/run/.containerenv") ? "container" : "none";
109801
+ const failed = checks.filter((check2) => check2.status === "fail").length;
109802
+ const warned = checks.filter((check2) => check2.status === "warn").length;
109803
+ console.log(
109804
+ failed ? `
109805
+ ${failed} check(s) failed.` : warned ? `
109806
+ All required checks passed (${warned} warning(s)).` : "\nAll checks passed."
109807
+ );
109808
+ return failed === 0;
109706
109809
  }
109707
- var truncate = (text) => text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT - 1)}\u2026` : text;
109708
- function doctorReport(checks, at = /* @__PURE__ */ new Date()) {
109810
+ var hostApp = () => {
109811
+ const app = appBundlePath();
109812
+ return app ? basename(app) : process.env.TERM_PROGRAM ?? process.env.__CFBundleIdentifier ?? "the launching app";
109813
+ };
109814
+ var overSsh = () => Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY) && !process.env.__CFBundleIdentifier && !process.env.TERM_PROGRAM;
109815
+ async function macPermissions(driver, prompt = false) {
109816
+ const result = await driver.call("check_permissions", prompt ? { prompt: true } : { prompt: false });
109817
+ const meta3 = result.structuredContent ?? {};
109709
109818
  return {
109710
- checkedAt: at.toISOString(),
109711
- checks: checks.slice(0, MAX_CHECKS).map((check2) => ({
109712
- name: check2.name.slice(0, 64) || "check",
109713
- status: check2.status,
109714
- detail: truncate(check2.detail),
109715
- ...check2.fix ? { fix: truncate(check2.fix) } : {}
109716
- }))
109819
+ accessibility: meta3.accessibility === true,
109820
+ screenRecording: meta3.screen_recording === true,
109821
+ directCapture: typeof meta3.direct_capture_status === "string" ? meta3.direct_capture_status : "not_checked"
109717
109822
  };
109718
109823
  }
109719
- function capabilitiesFrom(checks, display, options = {}) {
109720
- const platform = options.platform ?? process.platform;
109721
- const status = (name) => checks?.find((check2) => check2.name === name)?.status;
109722
- const ok = (name) => status(name) === "ok";
109723
- const known = (name) => status(name) === void 0 ? void 0 : ok(name);
109724
- const driver = ok("cua-driver");
109725
- const accessibility = known("accessibility");
109726
- const screenshot = driver && ok("screenshot");
109727
- const permissions = {};
109728
- if (accessibility !== void 0) permissions.accessibility = accessibility;
109729
- const screenRecording = known("screen recording");
109730
- if (screenRecording !== void 0) permissions.screenRecording = screenRecording;
109731
- const portal = known("portal");
109732
- if (portal !== void 0) permissions.portal = portal;
109733
- const firewall = status("firewall");
109734
- if (firewall !== void 0) permissions.firewall = firewall === "ok" || firewall === "info";
109735
- return {
109736
- screenshot,
109737
- // On macOS clicks are dropped silently without Accessibility, so input needs that grant too.
109738
- input: driver && (platform !== "darwin" || accessibility === true),
109739
- // libei on GNOME Wayland sends keycodes only, so IME text is dropped (§3.2.3).
109740
- textInput: options.session === "wayland-gnome" ? "keymap-only" : "full",
109741
- humanActivity: options.keyboardActivity ? "pointer+keyboard" : "pointer",
109742
- backgroundInput: false,
109743
- accessibilityTree: false,
109744
- viewer: options.webrtc !== false && ok("ffmpeg") && ok("screen capture"),
109745
- viewerStun: true,
109746
- ...options.egress ? { egress: true } : {},
109747
- displays: display && display.screenWidth > 0 && display.screenHeight > 0 ? [
109748
- {
109749
- id: "primary",
109750
- width: Math.round(display.screenWidth),
109751
- height: Math.round(display.screenHeight),
109752
- scale: display.scale > 0 ? display.scale : 1
109753
- }
109754
- ] : [],
109755
- permissions
109756
- };
109824
+ function powershell(script, timeoutMs = 3e4) {
109825
+ const result = spawnSync6("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
109826
+ encoding: "utf8",
109827
+ windowsHide: true,
109828
+ timeout: timeoutMs
109829
+ });
109830
+ return { ok: result.status === 0, stdout: result.stdout ?? "" };
109757
109831
  }
109758
-
109759
- // src/cp/env-registration.ts
109760
- import { createHash as createHash6 } from "node:crypto";
109761
- import { readFileSync as readFileSync6 } from "node:fs";
109762
- var REGISTER_TOKEN_ENV = "AGENTCONNECT_REGISTER_TOKEN";
109763
- var REGISTER_TOKEN_FILE_ENV = "AGENTCONNECT_REGISTER_TOKEN_FILE";
109764
- var CP_URL_ENV = "AGENTCONNECT_CP_URL";
109765
- var COMPUTER_NAME_ENV = "AGENTCONNECT_COMPUTER_NAME";
109766
- function registrationFromEnv(env = process.env, read = (path) => readFileSync6(path, "utf8")) {
109767
- let token = env[REGISTER_TOKEN_ENV]?.trim() ?? "";
109768
- const file2 = env[REGISTER_TOKEN_FILE_ENV]?.trim();
109769
- if (!token && file2) {
109832
+ var psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
109833
+ function firewallState(program) {
109834
+ const script = `$ErrorActionPreference = 'SilentlyContinue'
109835
+ $p = ${psQuote(program)}
109836
+ $rules = @(Get-NetFirewallApplicationFilter | Where-Object { [Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p } | Get-NetFirewallRule | Where-Object { "$($_.Enabled)" -eq 'True' -and "$($_.Direction)" -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; action = "$($_.Action)"; profile = "$($_.Profile)" } })
109837
+ $profiles = @(Get-NetConnectionProfile | ForEach-Object { "$($_.NetworkCategory)" })
109838
+ ConvertTo-Json -Compress -InputObject @{ rules = $rules; profiles = $profiles }`;
109839
+ const result = powershell(script);
109840
+ if (!result.ok) return void 0;
109841
+ try {
109842
+ const parsed = JSON.parse(result.stdout.trim());
109843
+ const rules = parsed.rules ?? [];
109844
+ return {
109845
+ allow: rules.filter((rule) => rule.action === "Allow"),
109846
+ block: rules.filter((rule) => rule.action === "Block"),
109847
+ activeProfiles: [...new Set(parsed.profiles ?? [])]
109848
+ };
109849
+ } catch {
109850
+ return void 0;
109851
+ }
109852
+ }
109853
+ var profileCovered = (profile, category) => profile === "Any" || profile.split(/,\s*/).includes(category === "DomainAuthenticated" ? "Domain" : category);
109854
+ async function doctor(ctx, captureTimeoutMs = 15e3) {
109855
+ const checks = [];
109856
+ const { config: config2 } = ctx;
109857
+ const registration = registrationCheck(ctx.dir);
109858
+ checks.push({ name: "version", status: "ok", detail: `desktop daemon ${COMPUTER_DAEMON_VERSION}` });
109859
+ checks.push(
109860
+ config2.clients.length > 0 ? {
109861
+ name: "config",
109862
+ status: "ok",
109863
+ detail: `${configPath(ctx.dir)} (clients: ${config2.clients.map((client) => client.name).join(", ")})`
109864
+ } : registration.status === "ok" ? { name: "config", status: "ok", detail: `${configPath(ctx.dir)} (no local client tokens)` } : { name: "config", status: "fail", detail: "no client token yet", fix: `run: ${selfCommand()} setup` }
109865
+ );
109866
+ checks.push(registration);
109867
+ checks.push(sessionCheck());
109868
+ wakeDisplay();
109869
+ if (isAbsolute(ctx.driverCommand) && !existsSync5(ctx.driverCommand)) {
109870
+ checks.push({
109871
+ name: "cua-driver",
109872
+ status: "fail",
109873
+ detail: `missing ${ctx.driverCommand}`,
109874
+ fix: `run: ${selfCommand()} setup`
109875
+ });
109876
+ } else {
109877
+ const driver = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: config2.driverCallTimeoutMs });
109770
109878
  try {
109771
- token = read(file2).trim();
109772
- } catch (error62) {
109773
- throw new Error(
109774
- `cannot read ${REGISTER_TOKEN_FILE_ENV} (${file2}): ${error62.code ?? "error"}`
109879
+ const size = await driver.call("get_screen_size", {});
109880
+ checks.push({
109881
+ name: "cua-driver",
109882
+ status: "ok",
109883
+ detail: `${driver.version ?? CUA_DRIVER_VERSION}: ${size.content.find((block) => block.text)?.text ?? "started"}`
109884
+ });
109885
+ if (process.platform === "darwin")
109886
+ checks.push(
109887
+ ...macPermissionChecks(await macPermissions(driver), appBundlePath() ? readGrantRecord(ctx.dir) : void 0)
109888
+ );
109889
+ const shot = await driver.call("get_desktop_state", { max_image_dimension: 320 }).then(() => void 0).catch((error62) => error62.message);
109890
+ checks.push(
109891
+ shot ? { name: "screenshot", status: "fail", detail: shot.slice(0, 160), fix: permissionFix() } : { name: "screenshot", status: "ok", detail: "desktop capture works" }
109775
109892
  );
109893
+ } catch (error62) {
109894
+ checks.push({
109895
+ name: "cua-driver",
109896
+ status: "fail",
109897
+ detail: error62.message.slice(0, 160),
109898
+ fix: `run: ${selfCommand()} setup`
109899
+ });
109900
+ } finally {
109901
+ await driver.close();
109776
109902
  }
109777
109903
  }
109778
- if (!token) return void 0;
109779
- const cpUrl = env[CP_URL_ENV]?.trim();
109780
- if (!cpUrl) throw new Error(`${CP_URL_ENV} is required with a registration token (the console prints it)`);
109781
- const name = env[COMPUTER_NAME_ENV]?.trim();
109782
- return { token, cpUrl, ...name ? { name } : {} };
109904
+ checks.push(displayCheck(config2));
109905
+ checks.push(...ffmpegChecks(ctx, captureTimeoutMs));
109906
+ if (process.platform === "win32") checks.push(firewallCheck(config2));
109907
+ if (process.platform === "linux") checks.push(...linuxChecks(ctx));
109908
+ checks.push(await daemonCheck(config2));
109909
+ return checks;
109783
109910
  }
109784
- var tokenSha256 = (token) => createHash6("sha256").update(token).digest("hex");
109785
- var keepsRegistration = (current, wanted) => Boolean(
109786
- current && !current.revokedAt && current.cpUrl === cpBaseUrl(wanted.cpUrl) && current.tokenSha256 === tokenSha256(wanted.token)
109787
- );
109788
- var staysRevoked = (current, cpUrl) => Boolean(current?.revokedAt && current.cpUrl === cpBaseUrl(cpUrl));
109789
- async function registerFromEnv(options) {
109790
- const { wanted } = options;
109791
- if (!wanted) return { kind: "none" };
109792
- const current = options.load();
109793
- if (current && keepsRegistration(current, wanted)) return { kind: "kept", registration: current };
109911
+ function registrationCheck(dir) {
109912
+ let registration;
109794
109913
  try {
109795
- const registration = { ...await options.exchange(wanted), tokenSha256: tokenSha256(wanted.token) };
109796
- options.save(registration);
109797
- return { kind: "registered", registration };
109914
+ registration = loadRegistration(dir);
109798
109915
  } catch (error62) {
109799
- if (error62 instanceof RegistrationTokenRefused && current && staysRevoked(current, wanted.cpUrl)) {
109800
- return { kind: "stays-revoked", registration: current, reason: error62.message };
109801
- }
109802
- throw error62;
109916
+ return {
109917
+ name: "control plane",
109918
+ status: "fail",
109919
+ detail: `unreadable ${registrationPath(dir)}: ${error62.message}`.slice(0, 300),
109920
+ fix: `register again: ${selfCommand()} setup --register <token> --cp-url <url>`
109921
+ };
109803
109922
  }
109804
- }
109805
-
109806
- // src/cp/pool-bootstrap.ts
109807
- import { once as once3 } from "node:events";
109808
- import { createServer as createServer3 } from "node:http";
109809
- var POOL_BOOTSTRAP_PORT_ENV = "AGENTCONNECT_POOL_BOOTSTRAP_PORT";
109810
- function poolBootstrapPort(env = process.env) {
109811
- const raw = env[POOL_BOOTSTRAP_PORT_ENV]?.trim();
109812
- if (!raw) return void 0;
109813
- const port = Number(raw);
109814
- if (!Number.isInteger(port) || port < 1 || port > 65535)
109815
- throw new Error(`${POOL_BOOTSTRAP_PORT_ENV} is not a valid port: ${raw}`);
109816
- return port;
109817
- }
109818
- var MAX_BODY = 4096;
109819
- var live = (registration) => registration && !registration.revokedAt ? registration : void 0;
109820
- function send2(res, status, body) {
109821
- res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
109822
- res.end(JSON.stringify(body));
109823
- }
109824
- async function readBody2(req) {
109825
- let body = "";
109826
- for await (const chunk of req) {
109827
- body += String(chunk);
109828
- if (body.length > MAX_BODY) throw new Error("body too large");
109923
+ if (!registration) {
109924
+ return { name: "control plane", status: "info", detail: "not registered: local client tokens only" };
109925
+ }
109926
+ if (registration.revokedAt) {
109927
+ return {
109928
+ name: "control plane",
109929
+ status: "fail",
109930
+ detail: `computer ${registration.computerId} was revoked (${registration.revokedReason ?? "by the Control Plane"}): all input is refused`,
109931
+ fix: `create a new registration in the console, then: ${selfCommand()} setup --register <token> --cp-url ${registration.cpUrl}`
109932
+ };
109829
109933
  }
109830
- return body;
109831
- }
109832
- async function startPoolBootstrap(options) {
109833
- let resolveRegistered;
109834
- const registered = new Promise((resolve2) => resolveRegistered = resolve2);
109835
- const existing = live(options.load());
109836
- if (existing) resolveRegistered(existing);
109837
- let registering;
109838
- const status = () => {
109839
- const current = live(options.load());
109840
- return current ? { registered: true, computerId: current.computerId } : { registered: false };
109841
- };
109842
- const server = createServer3((req, res) => {
109843
- void (async () => {
109844
- const path = new URL(req.url ?? "/", "http://localhost").pathname;
109845
- if (path === "/pool/status" && req.method === "GET") return send2(res, 200, status());
109846
- if (path !== "/pool/register" || req.method !== "POST") return send2(res, 404, { error: "not found" });
109847
- if (status().registered) return send2(res, 409, status());
109848
- let token;
109849
- let name;
109850
- try {
109851
- ;
109852
- ({ token, name } = JSON.parse(await readBody2(req)));
109853
- } catch {
109854
- return send2(res, 400, { error: "invalid body" });
109855
- }
109856
- if (typeof token !== "string" || !token || typeof name !== "string" || !name.trim())
109857
- return send2(res, 400, { error: "token and name are required" });
109858
- registering ??= options.register(token, name.trim().slice(0, 120)).finally(() => registering = void 0);
109859
- try {
109860
- const registration = await registering;
109861
- options.log(`registered as managed computer ${registration.computerId}`);
109862
- resolveRegistered(registration);
109863
- return send2(res, 200, { registered: true, computerId: registration.computerId });
109864
- } catch (error62) {
109865
- options.log(`managed registration failed: ${error62.message}`);
109866
- return send2(res, 502, { error: "registration failed" });
109867
- }
109868
- })().catch(() => {
109869
- if (!res.headersSent) send2(res, 500, { error: "failed" });
109870
- });
109871
- });
109872
- server.listen(options.port, options.host ?? "0.0.0.0");
109873
- await once3(server, "listening");
109874
- const address = server.address();
109875
- if (!existing) options.log(`waiting for the pool to register this desktop (port ${address.port})`);
109876
109934
  return {
109877
- registered,
109878
- address,
109879
- close: () => new Promise((resolve2) => {
109880
- server.closeAllConnections();
109881
- server.close(() => resolve2());
109882
- })
109935
+ name: "control plane",
109936
+ status: "ok",
109937
+ detail: `registered as computer ${registration.computerId} with ${registration.cpUrl}`
109883
109938
  };
109884
109939
  }
109885
-
109886
- // src/egress.ts
109887
- import { request as httpRequest, createServer as createServer4 } from "node:http";
109888
- import { request as httpsRequest } from "node:https";
109889
- import { connect as netConnect, isIP as isIP4 } from "node:net";
109890
- import { connect as tlsConnect } from "node:tls";
109891
- var EGRESS_PORT_ENV = "AGENTCONNECT_EGRESS_PORT";
109892
- var CONNECT_TIMEOUT_MS = 15e3;
109893
- var MAX_PROXY_HEADER_BYTES = 16 * 1024;
109894
- var HOP_BY_HOP = /* @__PURE__ */ new Set([
109895
- "connection",
109896
- "keep-alive",
109897
- "proxy-authenticate",
109898
- "proxy-authorization",
109899
- "proxy-connection",
109900
- "te",
109901
- "trailer",
109902
- "transfer-encoding",
109903
- "upgrade"
109904
- ]);
109905
- function egressPort(env = process.env) {
109906
- const raw = env[EGRESS_PORT_ENV]?.trim();
109907
- if (!raw) return void 0;
109908
- const port = Number(raw);
109909
- if (!Number.isInteger(port) || port < 1 || port > 65535)
109910
- throw new Error(`${EGRESS_PORT_ENV} is not a valid port: ${raw}`);
109911
- return port;
109912
- }
109913
- function connectTarget(authority) {
109914
- const match = /^\[?([^\]]+?)\]?:(\d{1,5})$/.exec(authority ?? "");
109915
- if (!match) return void 0;
109916
- const port = Number(match[2]);
109917
- return port > 0 && port <= 65535 ? { host: match[1], port } : void 0;
109918
- }
109919
- var basic = (egress) => egress.username !== void 0 || egress.password !== void 0 ? `Basic ${Buffer.from(`${egress.username ?? ""}:${egress.password ?? ""}`).toString("base64")}` : void 0;
109920
- function forwardHeaders(headers) {
109921
- const out = {};
109922
- for (const [name, value] of Object.entries(headers)) {
109923
- if (value !== void 0 && !HOP_BY_HOP.has(name.toLowerCase())) out[name] = value;
109940
+ function sessionCheck() {
109941
+ if (process.platform === "darwin") {
109942
+ return overSsh() ? {
109943
+ name: "session",
109944
+ status: "warn",
109945
+ detail: "running over SSH: macOS ties permissions to the app that starts the daemon",
109946
+ fix: "run setup / run from Terminal on the desktop itself"
109947
+ } : { name: "session", status: "ok", detail: `desktop session, host app ${hostApp()}` };
109924
109948
  }
109925
- return out;
109926
- }
109927
- var EgressForwarder = class {
109928
- constructor(opts) {
109929
- this.opts = opts;
109949
+ if (process.platform === "win32") {
109950
+ const session = process.env.SESSIONNAME;
109951
+ if (!session) {
109952
+ return {
109953
+ name: "session",
109954
+ status: "fail",
109955
+ detail: "not an interactive desktop session (service or scheduled task?)",
109956
+ fix: "start it from a terminal on the logged-in desktop"
109957
+ };
109958
+ }
109959
+ return session.startsWith("RDP") ? {
109960
+ name: "session",
109961
+ status: "warn",
109962
+ detail: `${session}: disconnecting RDP locks this session and stops capture`,
109963
+ fix: "prefer the console session"
109964
+ } : { name: "session", status: "ok", detail: `interactive session (${session})` };
109930
109965
  }
109931
- opts;
109932
- policy = { mode: "pending" };
109933
- server;
109934
- sockets = /* @__PURE__ */ new Set();
109935
- get mode() {
109936
- return this.policy.mode;
109966
+ if (waylandSession()) {
109967
+ return {
109968
+ name: "session",
109969
+ status: "ok",
109970
+ detail: `Wayland (${process.env.XDG_CURRENT_DESKTOP ?? "unknown desktop"}, ${process.env.WAYLAND_DISPLAY})`
109971
+ };
109937
109972
  }
109938
- /** Apply the organization's egress; open connections keep the route they started on. */
109939
- apply(policy) {
109940
- const before = this.describe();
109941
- this.policy = policy;
109942
- const after = this.describe();
109943
- if (after !== before) this.opts.log(`egress: ${after}`);
109973
+ return process.env.DISPLAY ? { name: "session", status: "ok", detail: `X11 display ${process.env.DISPLAY}` } : {
109974
+ name: "session",
109975
+ status: "fail",
109976
+ detail: "no DISPLAY or WAYLAND_DISPLAY",
109977
+ fix: "run inside the graphical session (or export its WAYLAND_DISPLAY, XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS)"
109978
+ };
109979
+ }
109980
+ var permissionFix = () => process.platform === "darwin" ? `grant ${hostApp()} the macOS permissions: ${selfCommand()} setup` : void 0;
109981
+ var PANE = {
109982
+ accessibility: "Privacy & Security > Accessibility (macOS 27: Device Control and Data Access)",
109983
+ screenRecording: "Privacy & Security > Screen & System Audio Recording"
109984
+ };
109985
+ function macPermissionChecks(state, record2, app = hostApp()) {
109986
+ const inApp = Boolean(record2);
109987
+ const reopen = inApp ? `then: ${selfCommand()} service restart` : "then Cmd+Q and reopen";
109988
+ const check2 = (grant2, name, effect) => {
109989
+ if (state[grant2]) return { name, status: "ok", detail: `granted to ${app}` };
109990
+ const loss = record2 ? grantLoss(record2, grant2) : "never-asked";
109991
+ if (loss === "lost")
109992
+ return {
109993
+ name,
109994
+ status: "fail",
109995
+ detail: `was granted to ${app} but is not in effect: switched off, or held by an earlier build of the app${effect}`,
109996
+ fix: `run: tccutil reset ${TCC_SERVICE[grant2]} ${APP_ID}, then: ${selfCommand()} setup`
109997
+ };
109998
+ if (loss === "listed-off")
109999
+ return {
110000
+ name,
110001
+ status: "fail",
110002
+ detail: `${app} is listed in ${PANE[grant2]} but switched off${effect}`,
110003
+ fix: `switch ${app} on there (listed is not enough), ${reopen}`
110004
+ };
110005
+ return {
110006
+ name,
110007
+ status: "fail",
110008
+ detail: `not granted to ${app}${effect}`,
110009
+ fix: inApp ? `run: ${selfCommand()} setup` : `${PANE[grant2]}: switch it on, ${reopen}`
110010
+ };
110011
+ };
110012
+ return [
110013
+ check2("accessibility", "accessibility", ": clicks and keys are silently dropped while pointer moves still work"),
110014
+ check2("screenRecording", "screen recording", "")
110015
+ ];
110016
+ }
110017
+ function displayCheck(config2) {
110018
+ const minutes = displaySleepMinutes();
110019
+ const setting = minutes === void 0 ? "" : minutes === 0 ? " (display sleep: never)" : ` (display sleep: ${minutes} min)`;
110020
+ if (config2.keepAwake && !canKeepAwake()) {
110021
+ return {
110022
+ name: "display",
110023
+ status: "warn",
110024
+ detail: "cannot hold this desktop awake: a blanked or locked screen cannot be captured or controlled",
110025
+ fix: "disable screen blanking and automatic lock in the desktop settings"
110026
+ };
109944
110027
  }
109945
- // Never the credentials: the proxy's origin is enough to tell which one is in use.
109946
- describe() {
109947
- if (this.policy.mode !== "proxy") return this.policy.mode;
109948
- return `proxy ${new URL(this.policy.url).origin}`;
110028
+ return config2.keepAwake ? { name: "display", status: "ok", detail: `the daemon keeps the display awake while it runs${setting}` } : {
110029
+ name: "display",
110030
+ status: minutes === 0 ? "ok" : "warn",
110031
+ detail: `keepAwake is off${setting}: a sleeping or locked display cannot be captured or controlled`,
110032
+ fix: 'set "keepAwake": true in config.json'
110033
+ };
110034
+ }
110035
+ var GNOME_HELPER = "winrects@cua";
110036
+ var gnomeWayland = () => waylandSession() && /GNOME/i.test(process.env.XDG_CURRENT_DESKTOP ?? "");
110037
+ function gnomeHelperState() {
110038
+ const info = spawnSync6("gnome-extensions", ["info", GNOME_HELPER], { encoding: "utf8" });
110039
+ if (info.status !== 0) return "missing";
110040
+ return /State:\s*(ACTIVE|ENABLED)/i.test(info.stdout ?? "") ? "active" : "installed";
110041
+ }
110042
+ function linuxChecks(ctx) {
110043
+ if (!waylandSession()) return [];
110044
+ const checks = [];
110045
+ if (gnomeWayland()) {
110046
+ const helper = gnomeHelperState();
110047
+ checks.push(
110048
+ helper === "active" ? {
110049
+ name: "gnome helper",
110050
+ status: "ok",
110051
+ detail: `${GNOME_HELPER} extension active (pixel geometry, capture, cursor)`
110052
+ } : {
110053
+ name: "gnome helper",
110054
+ status: "fail",
110055
+ detail: helper === "installed" ? `${GNOME_HELPER} is installed but not loaded yet` : `${GNOME_HELPER} extension missing: no pixel coordinates or safe input on GNOME Wayland`,
110056
+ fix: helper === "installed" ? "log out and back in once" : `run: ${selfCommand()} setup`
110057
+ }
110058
+ );
109949
110059
  }
109950
- async start() {
109951
- const server = createServer4((req, res) => this.onRequest(req, res));
109952
- server.on("connect", (req, socket, head) => this.onConnect(req, socket, head));
109953
- server.on("connection", (socket) => {
109954
- this.sockets.add(socket);
109955
- socket.once("close", () => this.sockets.delete(socket));
109956
- });
109957
- server.on("clientError", (_err, socket) => socket.destroy());
109958
- await new Promise((resolve2, reject) => {
109959
- server.once("error", reject);
109960
- server.listen(this.opts.port, this.opts.host ?? "127.0.0.1", () => resolve2());
109961
- });
109962
- this.server = server;
109963
- const address = server.address();
109964
- return typeof address === "object" && address ? address.port : this.opts.port;
109965
- }
109966
- async stop() {
109967
- for (const socket of this.sockets) socket.destroy();
109968
- await new Promise((resolve2) => this.server ? this.server.close(() => resolve2()) : resolve2());
109969
- this.server = void 0;
109970
- }
109971
- // A tunnel (HTTPS and WebSocket traffic): straight to the target, or a CONNECT through the organization's proxy.
109972
- onConnect(req, client, head) {
109973
- const policy = this.policy;
109974
- const target = connectTarget(req.url);
109975
- const refuse = (status) => {
109976
- client.end(`HTTP/1.1 ${status}\r
109977
- Connection: close\r
109978
- Content-Length: 0\r
109979
- \r
109980
- `);
109981
- };
109982
- if (!target) return refuse("400 Bad Request");
109983
- if (policy.mode === "pending") return refuse("503 Service Unavailable");
109984
- client.on("error", () => {
109985
- });
109986
- const upstream = policy.mode === "direct" ? netConnect(target.port, target.host) : this.dialProxy(new URL(policy.url));
109987
- let opened = false;
109988
- upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error("timeout")));
109989
- upstream.on("error", () => {
109990
- if (opened) client.destroy();
109991
- else if (!client.destroyed) refuse("502 Bad Gateway");
109992
- });
109993
- client.once("close", () => upstream.destroy());
109994
- const open3 = (rest) => {
109995
- opened = true;
109996
- upstream.setTimeout(0);
109997
- client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
109998
- if (rest.length > 0) client.write(rest);
109999
- if (head.length > 0) upstream.write(head);
110000
- upstream.pipe(client);
110001
- client.pipe(upstream);
110002
- };
110003
- if (policy.mode === "direct") {
110004
- upstream.once("connect", () => open3(Buffer.alloc(0)));
110005
- return;
110060
+ const portal = spawnSync6("systemctl", ["--user", "is-active", "xdg-desktop-portal"], { encoding: "utf8" });
110061
+ checks.push(
110062
+ portal.stdout?.trim() === "active" ? { name: "portal", status: "ok", detail: "xdg-desktop-portal running (screen sharing, remote input)" } : {
110063
+ name: "portal",
110064
+ status: "fail",
110065
+ detail: "xdg-desktop-portal is not running on this session",
110066
+ fix: "install xdg-desktop-portal plus the desktop backend (xdg-desktop-portal-gnome / -kde)"
110006
110067
  }
110007
- const auth = basic(policy);
110008
- const authority = target.host.includes(":") ? `[${target.host}]:${target.port}` : `${target.host}:${target.port}`;
110009
- upstream.once(policy.url.startsWith("https:") ? "secureConnect" : "connect", () => {
110010
- upstream.write(
110011
- `CONNECT ${authority} HTTP/1.1\r
110012
- Host: ${authority}\r
110013
- ${auth ? `Proxy-Authorization: ${auth}\r
110014
- ` : ""}\r
110015
- `
110016
- );
110017
- });
110018
- let buffered = Buffer.alloc(0);
110019
- const onData = (chunk) => {
110020
- buffered = Buffer.concat([buffered, chunk]);
110021
- const end = buffered.indexOf("\r\n\r\n");
110022
- if (end < 0) {
110023
- if (buffered.length > MAX_PROXY_HEADER_BYTES) upstream.destroy(new Error("oversized proxy reply"));
110024
- return;
110068
+ );
110069
+ if (ctx.config.webrtc) {
110070
+ const gi = spawnSync6("python3", ["-c", "import gi"], { stdio: "ignore" }).status === 0;
110071
+ const missing = [
110072
+ !gi && "python3-gi",
110073
+ ...["pipewiresrc", "y4menc", "videorate"].filter(
110074
+ (element) => spawnSync6("gst-inspect-1.0", [element], { stdio: "ignore" }).status !== 0
110075
+ )
110076
+ ].filter(Boolean);
110077
+ checks.push(
110078
+ missing.length === 0 ? { name: "pipewire", status: "ok", detail: "python3-gi and GStreamer PipeWire capture available" } : {
110079
+ name: "pipewire",
110080
+ status: "warn",
110081
+ detail: `missing ${missing.join(", ")}: the /view page falls back to screenshots`,
110082
+ fix: "install python3-gi gstreamer1.0-pipewire gstreamer1.0-plugins-good gstreamer1.0-plugins-base"
110025
110083
  }
110026
- upstream.off("data", onData);
110027
- const status = /^HTTP\/1\.[01] (\d{3})/.exec(buffered.subarray(0, end).toString("latin1"))?.[1];
110028
- if (status !== "200") {
110029
- upstream.destroy();
110030
- return refuse(status === "407" ? "502 Bad Gateway (egress proxy refused the credentials)" : "502 Bad Gateway");
110084
+ );
110085
+ }
110086
+ return checks;
110087
+ }
110088
+ function ffmpegChecks(ctx, timeoutMs) {
110089
+ if (!ctx.config.webrtc)
110090
+ return [{ name: "webrtc viewer", status: "warn", detail: 'disabled in config ("webrtc": false)' }];
110091
+ if (!ffmpegAvailable(ctx.ffmpeg)) {
110092
+ return [
110093
+ {
110094
+ name: "ffmpeg",
110095
+ status: "warn",
110096
+ detail: "not found: the /view page falls back to screenshots",
110097
+ fix: `run: ${selfCommand()} install-ffmpeg`
110031
110098
  }
110032
- open3(buffered.subarray(end + 4));
110033
- };
110034
- upstream.on("data", onData);
110099
+ ];
110035
110100
  }
110036
- // A plain HTTP request in absolute form: fetched directly, or handed to the organization's proxy as is.
110037
- onRequest(req, res) {
110038
- const policy = this.policy;
110039
- let target;
110040
- try {
110041
- target = new URL(req.url ?? "");
110042
- } catch {
110043
- res.writeHead(400).end();
110044
- return;
110045
- }
110046
- if (target.protocol !== "http:") return void res.writeHead(400).end();
110047
- if (policy.mode === "pending") return void res.writeHead(503).end("egress is not configured yet");
110048
- const headers = forwardHeaders(req.headers);
110049
- let upstream;
110050
- if (policy.mode === "direct") {
110051
- upstream = httpRequest({
110052
- host: target.hostname,
110053
- port: target.port || 80,
110054
- method: req.method,
110055
- path: `${target.pathname}${target.search}`,
110056
- headers
110057
- });
110058
- } else {
110059
- const proxy = new URL(policy.url);
110060
- const auth = basic(policy);
110061
- upstream = (proxy.protocol === "https:" ? httpsRequest : httpRequest)({
110062
- host: proxy.hostname,
110063
- port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
110064
- method: req.method,
110065
- path: target.href,
110066
- headers: { ...headers, ...auth ? { "proxy-authorization": auth } : {} }
110067
- });
110101
+ if (waylandSession() && !existsSync5(screencastTokenPath(ctx.dir))) {
110102
+ return [
110103
+ { name: "ffmpeg", status: "ok", detail: ctx.ffmpeg },
110104
+ {
110105
+ name: "screen capture",
110106
+ status: "warn",
110107
+ detail: "screen sharing not approved yet (Wayland portal): /view falls back to screenshots",
110108
+ fix: `run: ${selfCommand()} setup, then pick the screen and click Share`
110109
+ }
110110
+ ];
110111
+ }
110112
+ const probe = probeCapture(ctx.ffmpeg, ctx.config.streamFps, timeoutMs, ctx.dir);
110113
+ return [
110114
+ { name: "ffmpeg", status: "ok", detail: ctx.ffmpeg },
110115
+ probe.ok ? { name: "screen capture", status: "ok", detail: `ffmpeg ${probe.input} captures the display` } : {
110116
+ name: "screen capture",
110117
+ status: "fail",
110118
+ detail: probe.error ?? "ffmpeg could not capture the display",
110119
+ fix: process.platform === "darwin" ? "answer the macOS screen-capture prompt (setup triggers it), then Cmd+Q and reopen the terminal" : "check that a desktop is attached and unlocked"
110068
110120
  }
110069
- upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error("timeout")));
110070
- upstream.on("response", (answer) => {
110071
- upstream.setTimeout(0);
110072
- res.writeHead(answer.statusCode ?? 502, forwardHeaders(answer.headers));
110073
- answer.pipe(res);
110074
- });
110075
- upstream.on("error", () => {
110076
- if (!res.headersSent) res.writeHead(502).end();
110077
- else res.destroy();
110078
- });
110079
- req.pipe(upstream);
110121
+ ];
110122
+ }
110123
+ function firewallCheck(config2) {
110124
+ if (isLoopbackHost(config2.host)) {
110125
+ return { name: "firewall", status: "info", detail: `listening on ${config2.host} only; no inbound rule needed` };
110080
110126
  }
110081
- dialProxy(proxy) {
110082
- const port = Number(proxy.port || (proxy.protocol === "https:" ? 443 : 80));
110083
- return proxy.protocol === "https:" ? tlsConnect({ host: proxy.hostname, port, ...isIP4(proxy.hostname) ? {} : { servername: proxy.hostname } }) : netConnect(port, proxy.hostname);
110127
+ const state = firewallState(process.execPath);
110128
+ if (!state) return { name: "firewall", status: "warn", detail: "could not read Windows Firewall rules" };
110129
+ const fix = `run: ${selfCommand()} setup (asks for administrator approval once)`;
110130
+ if (state.block.length > 0) {
110131
+ return {
110132
+ name: "firewall",
110133
+ status: "fail",
110134
+ detail: `inbound block rule(s) for ${process.execPath}: ${state.block.map((rule) => rule.name).join(", ")}`,
110135
+ fix
110136
+ };
110084
110137
  }
110085
- };
110086
-
110087
- // src/public-address.ts
110088
- import { lookup } from "node:dns/promises";
110089
- import { isIP as isIP5 } from "node:net";
110090
- function publicBaseUrl(config2) {
110091
- if (config2.publicUrl) return config2.publicUrl.replace(/\/+$/, "");
110092
- if (config2.rtcAddress) return `http://${urlHost(config2.rtcAddress)}:${config2.port}`;
110093
- return void 0;
110094
- }
110095
- async function rtcAdvertiseAddress(config2, resolve2 = async (host) => (await lookup(host, { family: 4 })).address, log40 = () => void 0) {
110096
- if (config2.rtcAddress) return config2.rtcAddress;
110097
- if (!config2.publicUrl) return void 0;
110098
- const host = new URL(config2.publicUrl).hostname.replace(/^\[(.*)\]$/, "$1");
110099
- if (isIP5(host)) return host;
110100
- try {
110101
- return await resolve2(host);
110102
- } catch (error62) {
110103
- log40(`cannot resolve ${host} for WebRTC (${error62.message}); set RTC_ADDRESS to the public IP`);
110104
- return void 0;
110138
+ const uncovered = state.activeProfiles.filter(
110139
+ (category) => !state.allow.some((rule) => profileCovered(rule.profile, category))
110140
+ );
110141
+ if (state.allow.length === 0 || uncovered.length > 0) {
110142
+ return {
110143
+ name: "firewall",
110144
+ status: "warn",
110145
+ detail: state.allow.length === 0 ? "no inbound allow rule for Node.js: remote MCP and WebRTC will be blocked or prompt" : `Node.js is not allowed on active ${uncovered.join("/")} network(s)`,
110146
+ fix
110147
+ };
110105
110148
  }
110106
- }
110107
-
110108
- // src/doctor-schedule.ts
110109
- function scheduleDoctor(options) {
110110
- let timer;
110111
- let stopped = false;
110112
- const runOnce = async () => {
110113
- if (stopped) return;
110114
- try {
110115
- await options.run();
110116
- } catch (error62) {
110117
- options.onError(error62);
110118
- }
110119
- if (timer) clearTimeout(timer);
110120
- if (stopped) return;
110121
- timer = setTimeout(() => enqueue(), options.intervalMs);
110122
- timer.unref();
110123
- };
110124
- let runs = runOnce();
110125
- const enqueue = () => {
110126
- runs = runs.then(runOnce);
110127
- };
110128
110149
  return {
110129
- refresh: enqueue,
110130
- stop() {
110131
- stopped = true;
110132
- if (timer) clearTimeout(timer);
110133
- }
110150
+ name: "firewall",
110151
+ status: "ok",
110152
+ detail: `Node.js allowed inbound (${state.allow.map((rule) => rule.profile).join(", ")})`
110134
110153
  };
110135
110154
  }
110136
-
110137
- // src/service-linux.ts
110138
- import { execFile as execFile2, spawnSync as spawnSync6 } from "node:child_process";
110139
- import { copyFileSync, mkdirSync as mkdirSync7, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "node:fs";
110140
- import { homedir as homedir3 } from "node:os";
110141
- import { join as join9 } from "node:path";
110142
- var UNIT = "agentconnect-computer.service";
110143
- var unitPath = () => join9(process.env.XDG_CONFIG_HOME ?? join9(homedir3(), ".config"), "systemd", "user", UNIT);
110144
- var SESSION_VARS = [
110145
- "DISPLAY",
110146
- "XAUTHORITY",
110147
- "WAYLAND_DISPLAY",
110148
- "XDG_SESSION_TYPE",
110149
- "XDG_CURRENT_DESKTOP",
110150
- "XDG_RUNTIME_DIR",
110151
- "DBUS_SESSION_BUS_ADDRESS"
110152
- ];
110153
- var SESSION_ENV = "AGENTCONNECT_COMPUTER_SESSION";
110154
- var SESSION_DISPLAY_VARS = ["DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY", SESSION_ENV];
110155
- var EXIT_NEW_SESSION = 75;
110156
- var autostartPath = () => join9(process.env.XDG_CONFIG_HOME ?? join9(homedir3(), ".config"), "autostart", "agentconnect-computer.desktop");
110157
- function systemctl(...args) {
110158
- const result = spawnSync6("systemctl", ["--user", ...args], { encoding: "utf8" });
110159
- return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };
110155
+ async function daemonCheck(config2) {
110156
+ const running = await fetch(`${controlBaseUrl(config2)}/healthz`, { signal: AbortSignal.timeout(2e3) }).then((response) => response.ok).catch(() => false);
110157
+ return {
110158
+ name: "daemon",
110159
+ status: running ? "ok" : "info",
110160
+ detail: running ? `running on port ${config2.port}` : `not running (start it with: ${selfCommand()} run; listens on ${config2.host}:${config2.port})`
110161
+ };
110160
110162
  }
110161
- var quote = (value) => `"${value.replace(/(["\\])/g, "\\$1")}"`;
110162
- function unitFile(node2, script) {
110163
- return `[Unit]
110164
- Description=AgentConnect Computer (computer-use daemon)
110165
- PartOf=graphical-session.target
110166
- After=graphical-session.target
110167
- StartLimitIntervalSec=120
110168
- StartLimitBurst=5
110169
-
110170
- [Service]
110171
- ExecCondition=/bin/sh -c 'test -n "$DISPLAY$WAYLAND_DISPLAY"'
110172
- ExecStart=${quote(node2)} ${quote(script)} run
110173
- Restart=on-failure
110174
- RestartSec=3
110175
-
110176
- [Install]
110177
- WantedBy=graphical-session.target
110178
- `;
110163
+ async function setupPermissions(ctx) {
110164
+ if (process.platform === "darwin") return setupMac(ctx);
110165
+ if (process.platform === "win32") return setupWindowsFirewall(ctx);
110166
+ if (process.platform === "linux") return setupLinux(ctx);
110179
110167
  }
110180
- function autostartEntry() {
110181
- const steps = [
110182
- `systemctl --user import-environment ${SESSION_VARS.join(" ")}`,
110183
- `systemctl --user set-environment ${SESSION_ENV}=$XDG_SESSION_ID`,
110184
- `systemctl --user reset-failed ${UNIT}`,
110185
- `systemctl --user start ${UNIT}`
110186
- ];
110187
- return `[Desktop Entry]
110188
- Type=Application
110189
- Name=AgentConnect Computer
110190
- Comment=Starts the AgentConnect Computer service in this desktop session
110191
- Exec=sh -c '${steps.join("; ")}'
110192
- NoDisplay=true
110193
- X-GNOME-Autostart-enabled=true
110194
- `;
110168
+ async function setupLinux(ctx) {
110169
+ if (!waylandSession()) {
110170
+ ctx.log(
110171
+ process.env.DISPLAY ? "X11 session: no approvals needed." : "No graphical session here: nothing to approve."
110172
+ );
110173
+ return;
110174
+ }
110175
+ if (gnomeWayland()) {
110176
+ const state = gnomeHelperState();
110177
+ if (state === "missing") {
110178
+ const installer = join10(dirname3(ctx.driverCommand), "wayland-helper", "install.sh");
110179
+ const result = spawnSync6(installer, [], { encoding: "utf8" });
110180
+ ctx.log(
110181
+ result.status === 0 ? `Installed the ${GNOME_HELPER} GNOME extension.` : `Extension install failed: ${result.stderr}`
110182
+ );
110183
+ }
110184
+ if (state !== "active") ctx.log("GNOME loads extensions at login: log out and back in once, then run setup again.");
110185
+ }
110186
+ if (ctx.config.webrtc && ffmpegAvailable(ctx.ffmpeg)) {
110187
+ ctx.log("Approve screen sharing on this screen: pick the monitor, then click Share (asked once).");
110188
+ const probe = probeCapture(ctx.ffmpeg, ctx.config.streamFps, 18e4, ctx.dir);
110189
+ ctx.log(
110190
+ probe.ok ? "Screen sharing approved; the WebRTC viewer can stream." : `Screen sharing failed: ${probe.error}`
110191
+ );
110192
+ }
110193
+ ctx.log('Approve remote input on this screen: allow "remote interaction" when GNOME asks (asked once).');
110194
+ const driver = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: 18e4 });
110195
+ try {
110196
+ await driver.call("press_key", { scope: "desktop", key: "shift" });
110197
+ ctx.log("Remote input works.");
110198
+ } catch (error62) {
110199
+ ctx.log(`Remote input not available yet: ${error62.message.slice(0, 200)}`);
110200
+ } finally {
110201
+ await driver.close();
110202
+ }
110195
110203
  }
110196
- function installService(dataDir2, script, managed = false) {
110197
- let target = script;
110198
- if (!managed) {
110199
- const app = join9(dataDir2, "app");
110200
- mkdirSync7(app, { recursive: true });
110201
- target = join9(app, "agentconnect-computer.mjs");
110202
- if (script !== target) copyFileSync(script, target);
110204
+ async function setupMac(ctx) {
110205
+ if (overSsh()) {
110206
+ ctx.log(`macOS permissions cannot be granted over SSH: run \`${selfCommand()} setup\` in Terminal on the Mac.`);
110207
+ return;
110203
110208
  }
110204
- mkdirSync7(join9(unitPath(), ".."), { recursive: true });
110205
- writeFileSync8(unitPath(), unitFile(process.execPath, target));
110206
- mkdirSync7(join9(autostartPath(), ".."), { recursive: true });
110207
- writeFileSync8(autostartPath(), autostartEntry());
110208
- systemctl("daemon-reload");
110209
- const enabled = systemctl("enable", UNIT);
110210
- if (!enabled.ok) throw new Error(`systemctl --user enable failed: ${enabled.output}`);
110211
- if (inGraphicalSession()) {
110212
- systemctl("import-environment", ...SESSION_VARS.filter((name) => process.env[name]));
110213
- const session = process.env.XDG_SESSION_ID;
110214
- if (session && graphicalSessionSync(session)) systemctl("set-environment", `${SESSION_ENV}=${session}`);
110215
- else systemctl("unset-environment", SESSION_ENV);
110216
- systemctl("reset-failed", UNIT);
110217
- systemctl("restart", UNIT);
110209
+ const app = hostApp();
110210
+ ctx.log(
110211
+ `macOS grants these permissions to ${app}, which runs this command; \`agentconnect computer install\` installs the AgentConnect Computer app to hold them instead.`
110212
+ );
110213
+ const driver = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: 18e4 });
110214
+ try {
110215
+ let state = await macPermissions(driver);
110216
+ if (state.accessibility && state.screenRecording) {
110217
+ ctx.log(`macOS permissions already granted to ${app}.`);
110218
+ } else {
110219
+ ctx.log(`Requesting Accessibility and Screen Recording for ${app}: answer the macOS dialogs.`);
110220
+ state = await macPermissions(driver, true).catch(() => state);
110221
+ if (!state.accessibility) open2(MAC_PANES.accessibility);
110222
+ else if (!state.screenRecording) open2(MAC_PANES.screenRecording);
110223
+ state = await waitForGrants(ctx, app, state);
110224
+ }
110225
+ if (ctx.config.webrtc && ffmpegAvailable(ctx.ffmpeg) && state.screenRecording) {
110226
+ ctx.log("Testing ffmpeg screen capture: if macOS asks to let the app bypass the window picker, click Allow.");
110227
+ const probe = probeCapture(ctx.ffmpeg, ctx.config.streamFps, 12e4, ctx.dir);
110228
+ ctx.log(probe.ok ? "ffmpeg screen capture works." : `ffmpeg screen capture failed: ${probe.error}`);
110229
+ }
110230
+ if (!state.screenRecording || !state.accessibility) {
110231
+ ctx.log(`After switching the permissions on, quit ${app} (Cmd+Q), reopen it and run: ${selfCommand()} doctor`);
110232
+ }
110233
+ } finally {
110234
+ await driver.close();
110218
110235
  }
110219
110236
  }
110220
- var GRAPHICAL_TYPES = /* @__PURE__ */ new Set(["x11", "wayland", "mir"]);
110221
- function graphicalSessionSync(id) {
110222
- const type = spawnSync6("loginctl", ["show-session", id, "-p", "Type", "--value"], { encoding: "utf8" });
110223
- return type.status === 0 && GRAPHICAL_TYPES.has(type.stdout.trim());
110237
+ async function waitForGrants(ctx, app, initial) {
110238
+ let state = initial;
110239
+ const interactive = process.stdin.isTTY;
110240
+ ctx.log(
110241
+ `Waiting for: ${[!state.accessibility && "Accessibility", !state.screenRecording && "Screen Recording"].filter(Boolean).join(", ")}` + (interactive ? " (press Enter to stop waiting)" : "")
110242
+ );
110243
+ let skipped = false;
110244
+ const rl = interactive ? createInterface2({ input: process.stdin }) : void 0;
110245
+ rl?.once("line", () => skipped = true);
110246
+ const deadline = Date.now() + 10 * 6e4;
110247
+ let openedScreenPane = state.accessibility;
110248
+ try {
110249
+ while (!skipped && Date.now() < deadline && !(state.accessibility && state.screenRecording)) {
110250
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
110251
+ const probe = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: 2e4 });
110252
+ const next = await macPermissions(probe).catch(() => state).finally(() => probe.close());
110253
+ if (next.accessibility && !state.accessibility) ctx.log(`Accessibility granted to ${app}.`);
110254
+ if (next.screenRecording && !state.screenRecording) ctx.log(`Screen Recording granted to ${app}.`);
110255
+ state = next;
110256
+ if (state.accessibility && !state.screenRecording && !openedScreenPane) {
110257
+ openedScreenPane = true;
110258
+ open2(MAC_PANES.screenRecording);
110259
+ ctx.log(`Now switch on Screen & System Audio Recording for ${app}; it takes effect after reopening ${app}.`);
110260
+ }
110261
+ }
110262
+ } finally {
110263
+ rl?.close();
110264
+ }
110265
+ return state;
110224
110266
  }
110225
- var inGraphicalSession = (env = process.env) => Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
110226
- function startService() {
110227
- const result = systemctl("start", UNIT);
110228
- if (!result.ok) throw new Error(`systemctl --user start failed: ${result.output}`);
110267
+ function open2(url2) {
110268
+ spawn6("open", [url2], { stdio: "ignore", detached: true }).unref();
110229
110269
  }
110230
- function stopService() {
110231
- systemctl("stop", UNIT);
110270
+ function setupWindowsFirewall(ctx) {
110271
+ if (isLoopbackHost(ctx.config.host)) {
110272
+ ctx.log(`Listening on ${ctx.config.host} only, so no Windows Firewall rule is needed.`);
110273
+ return;
110274
+ }
110275
+ const program = process.execPath;
110276
+ const state = firewallState(program);
110277
+ const uncovered = state?.activeProfiles.filter(
110278
+ (category) => !state.allow.some((rule) => profileCovered(rule.profile, category))
110279
+ );
110280
+ if (state && state.block.length === 0 && state.allow.length > 0 && uncovered?.length === 0) {
110281
+ ctx.log("Windows Firewall already allows Node.js inbound.");
110282
+ return;
110283
+ }
110284
+ ctx.log(`Adding a Windows Firewall rule "${FIREWALL_RULE}" for ${program} (approve the administrator prompt).`);
110285
+ const elevated = `$p = ${psQuote(program)}
110286
+ Get-NetFirewallRule -DisplayName ${psQuote(FIREWALL_RULE)} -ErrorAction SilentlyContinue | Remove-NetFirewallRule
110287
+ Get-NetFirewallApplicationFilter | Where-Object { [Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p } | Get-NetFirewallRule | Where-Object { "$($_.Action)" -eq 'Block' -and "$($_.Direction)" -eq 'Inbound' } | Disable-NetFirewallRule
110288
+ New-NetFirewallRule -DisplayName ${psQuote(FIREWALL_RULE)} -Direction Inbound -Program $p -Action Allow -Profile Any | Out-Null`;
110289
+ const encoded = Buffer.from(elevated, "utf16le").toString("base64");
110290
+ const result = powershell(
110291
+ `Start-Process powershell.exe -Verb RunAs -Wait -WindowStyle Hidden -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand','${encoded}'`,
110292
+ 18e4
110293
+ );
110294
+ ctx.log(
110295
+ result.ok ? "Firewall rule added; any Node.js block rules were disabled." : "Firewall rule not added (administrator prompt declined?); Windows will ask on first connection instead."
110296
+ );
110232
110297
  }
110233
- function restartService() {
110234
- const result = systemctl("restart", UNIT);
110235
- if (!result.ok) throw new Error(`systemctl --user restart failed: ${result.output}`);
110298
+
110299
+ // src/menu-bar-host.ts
110300
+ var RECONNECT_WAIT_MS = 1e4;
110301
+ var PERMISSIONS_TIMEOUT_MS = 5e3;
110302
+ var within = (promise2, ms) => Promise.race([promise2, new Promise((_, reject) => setTimeout(() => reject(new Error("timed out")), ms).unref())]);
110303
+ function grantState(granted, record2, grant2) {
110304
+ if (granted) return "allowed";
110305
+ return grantLoss(record2, grant2) === "lost" ? "stale" : "off";
110306
+ }
110307
+ function controlPlaneState(registration, client) {
110308
+ if (!registration) return "unregistered";
110309
+ if (registration.revokedAt) return "revoked";
110310
+ switch (client?.state) {
110311
+ case "READY":
110312
+ return "connected";
110313
+ case "REVOKED":
110314
+ return "revoked";
110315
+ case "DEGRADED":
110316
+ case "STOPPED":
110317
+ case void 0:
110318
+ return "disconnected";
110319
+ default:
110320
+ return "connecting";
110321
+ }
110236
110322
  }
110237
- function uninstallService() {
110238
- systemctl("disable", "--now", UNIT);
110239
- rmSync5(unitPath(), { force: true });
110240
- rmSync5(autostartPath(), { force: true });
110241
- systemctl("daemon-reload");
110323
+ var appVersion = (appPath) => {
110324
+ if (!appPath) return void 0;
110325
+ try {
110326
+ const plist = readFileSync5(join11(appPath, "Contents", "Info.plist"), "utf8");
110327
+ return /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)?.[1];
110328
+ } catch {
110329
+ return void 0;
110330
+ }
110331
+ };
110332
+ function uninstallScript(channel) {
110333
+ const cli = `@agentconnect.md/cli${channel === "rc" ? "@rc" : ""}`;
110334
+ return `#!/bin/zsh -l
110335
+ echo "Uninstalling AgentConnect Computer\u2026"
110336
+ if command -v agentconnect >/dev/null 2>&1; then
110337
+ agentconnect computer uninstall
110338
+ else
110339
+ npx -y ${cli} computer uninstall
110340
+ fi
110341
+ echo
110342
+ echo "Done. You can close this window."
110343
+ `;
110242
110344
  }
110243
- function serviceStatus() {
110244
- const show = systemctl("show", UNIT, "-p", "LoadState", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID");
110245
- const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(show.output)?.[1];
110246
- const pid = Number(field("MainPID"));
110345
+ function macMenuBarHost(deps) {
110346
+ const { dir, driver, log: log40 } = deps;
110347
+ const host = deps.registration ? new URL(deps.registration.channelUrl).host : void 0;
110247
110348
  return {
110248
- installed: field("LoadState") === "loaded",
110249
- loaded: field("ActiveState") === "active",
110250
- ...pid ? { pid } : {},
110251
- state: `${field("ActiveState")}/${field("SubState")}`
110349
+ async facts() {
110350
+ let permissions = await within(macPermissions(driver), PERMISSIONS_TIMEOUT_MS).catch(() => void 0);
110351
+ if (permissions && !permissions.accessibility && await deps.accessibilityGranted()) {
110352
+ permissions = await within(macPermissions(driver), PERMISSIONS_TIMEOUT_MS).catch(() => void 0);
110353
+ }
110354
+ const name = deps.name();
110355
+ const app = appVersion(deps.appPath);
110356
+ const record2 = readGrantRecord(dir);
110357
+ return {
110358
+ ...name ? { name } : {},
110359
+ version: COMPUTER_DAEMON_VERSION,
110360
+ ...app ? { appVersion: app } : {},
110361
+ controlPlane: { state: controlPlaneState(deps.registration, deps.client()), ...host ? { host } : {} },
110362
+ ...permissions ? {
110363
+ screenRecording: grantState(permissions.screenRecording, record2, "screenRecording"),
110364
+ accessibility: grantState(permissions.accessibility, record2, "accessibility")
110365
+ } : {},
110366
+ driver: { version: driver.version ?? CUA_DRIVER_VERSION, running: permissions !== void 0 },
110367
+ ffmpeg: {
110368
+ version: FFMPEG_VERSION,
110369
+ installed: ffmpegAvailable(resolveFfmpegPath(dir, deps.ffmpegPath)),
110370
+ installable: canInstallFfmpeg() && !deps.ffmpegPath,
110371
+ installing: ffmpegInstalling(dir)
110372
+ },
110373
+ startAtLogin: startsAtLogin()
110374
+ };
110375
+ },
110376
+ async reconnect() {
110377
+ const client = deps.client();
110378
+ if (!client) return false;
110379
+ client.reconnectNow();
110380
+ const deadline = Date.now() + RECONNECT_WAIT_MS;
110381
+ while (client.state !== "READY" && Date.now() < deadline) await new Promise((resolve2) => setTimeout(resolve2, 250));
110382
+ return client.state === "READY";
110383
+ },
110384
+ async installDriver() {
110385
+ rmSync6(installedDriverDir(dir), { recursive: true, force: true });
110386
+ await installDriver(dir, log40);
110387
+ deps.shutdown(1);
110388
+ },
110389
+ async installFfmpeg() {
110390
+ await installFfmpeg(dir, log40);
110391
+ deps.onFfmpegInstalled();
110392
+ },
110393
+ openSettings: (pane) => open2(MAC_PANES[pane]),
110394
+ resetGrant(grant2) {
110395
+ open2(MAC_PANES[grant2]);
110396
+ forgetGrant(dir, grant2);
110397
+ log40(`resetting the ${grant2} grant held for an earlier build of the app, from the menu bar`);
110398
+ const reset = spawnSync7("tccutil", ["reset", TCC_SERVICE[grant2], APP_ID], { encoding: "utf8" });
110399
+ if (reset.status !== 0) log40(`tccutil reset failed: ${`${reset.stdout}${reset.stderr}`.trim()}`);
110400
+ void runSelf(["permissions", "--json", "--prompt"], 2e5).catch(() => void 0);
110401
+ },
110402
+ setStartAtLogin(on) {
110403
+ setStartAtLogin(on);
110404
+ log40(`start at login turned ${on ? "on" : "off"} from the menu bar`);
110405
+ },
110406
+ openLogs() {
110407
+ const file2 = join11(dir, "daemon.log");
110408
+ spawn7("open", existsSync6(file2) ? ["-a", "Console", file2] : [dir], { stdio: "ignore", detached: true }).unref();
110409
+ },
110410
+ uninstall() {
110411
+ let channel;
110412
+ try {
110413
+ channel = JSON.parse(readFileSync5(join11(dir, "versions.json"), "utf8")).channel;
110414
+ } catch {
110415
+ channel = void 0;
110416
+ }
110417
+ const script = join11(tmpdir(), "agentconnect-computer-uninstall.command");
110418
+ writeFileSync9(script, uninstallScript(channel));
110419
+ chmodSync2(script, 493);
110420
+ log40("uninstall requested from the menu bar; running it in Terminal");
110421
+ spawn7("open", ["-a", "Terminal", script], { stdio: "ignore", detached: true }).unref();
110422
+ },
110423
+ quit() {
110424
+ log40("quit from the menu bar; the service starts again at the next login");
110425
+ deps.shutdown(0);
110426
+ },
110427
+ restart: () => deps.shutdown(1)
110252
110428
  };
110253
110429
  }
110254
- var run = (command, args) => new Promise((resolve2) => {
110255
- execFile2(
110256
- command,
110257
- args,
110258
- { encoding: "utf8", timeout: 1e4 },
110259
- (error62, stdout, stderr) => resolve2({
110260
- ok: !error62,
110261
- exited: Boolean(error62) && typeof error62?.code === "number" && !error62.killed,
110262
- stdout: stdout ?? "",
110263
- stderr: stderr ?? ""
110264
- })
110265
- );
110266
- });
110267
- var environmentValue = (output2, name) => new RegExp(`^${name}=(.*)$`, "m").exec(output2)?.[1]?.trim() || void 0;
110268
- var GONE = /no session|not known|does not exist/i;
110269
- async function sessionProperty(id, property, exec = run) {
110270
- const result = await exec("loginctl", ["show-session", id, "-p", property, "--value"]);
110271
- if (result.ok) return result.stdout.trim() || void 0;
110272
- return result.exited && GONE.test(result.stderr) ? null : void 0;
110430
+
110431
+ // src/accessibility-watch.ts
110432
+ var INTERVAL_MS = 5e3;
110433
+ function watchAccessibility(options) {
110434
+ let done = false;
110435
+ let running;
110436
+ const now = () => {
110437
+ if (done) return Promise.resolve(true);
110438
+ running ??= (async () => {
110439
+ if (!await options.check().catch(() => false)) return false;
110440
+ done = true;
110441
+ clearInterval(timer);
110442
+ options.log("Accessibility granted; restarting Cua Driver so input takes effect");
110443
+ await options.restartDriver();
110444
+ return true;
110445
+ })().finally(() => {
110446
+ running = void 0;
110447
+ });
110448
+ return running;
110449
+ };
110450
+ const timer = setInterval(() => void now(), options.intervalMs ?? INTERVAL_MS);
110451
+ timer.unref();
110452
+ return {
110453
+ now,
110454
+ stop() {
110455
+ done = true;
110456
+ clearInterval(timer);
110457
+ }
110458
+ };
110273
110459
  }
110274
- var logindProbe = {
110275
- async graphical(id) {
110276
- const type = await sessionProperty(id, "Type");
110277
- return type == null ? type : GRAPHICAL_TYPES.has(type);
110278
- },
110279
- async live(id) {
110280
- const state = await sessionProperty(id, "State");
110281
- return state === void 0 ? void 0 : state !== null && state !== "closing";
110282
- },
110283
- async managerSession() {
110284
- const env = await run("systemctl", ["--user", "show-environment"]);
110285
- return env.ok ? environmentValue(env.stdout, SESSION_ENV) : void 0;
110286
- },
110287
- async forget(id) {
110288
- if (await this.managerSession() !== id) return;
110289
- await run("systemctl", ["--user", "unset-environment", ...SESSION_DISPLAY_VARS]);
110460
+
110461
+ // src/cp/relay-links.ts
110462
+ var HELLO_TIMEOUT_MS = 15e3;
110463
+ var RelayLink = class {
110464
+ constructor(entry, deps, clock) {
110465
+ this.entry = entry;
110466
+ this.deps = deps;
110467
+ this.clock = clock;
110468
+ this.backoff = new Backoff(deps.jitter ? { jitter: deps.jitter } : {});
110290
110469
  }
110291
- };
110292
- var UNKNOWN_LIMIT = 3;
110293
- function watchSession(options) {
110294
- const probe = options.probe ?? logindProbe;
110295
- let stopped = false;
110296
- let busy = false;
110297
- let checked = false;
110298
- let unknown2 = 0;
110299
- const tick = async () => {
110300
- if (stopped || busy) return;
110301
- busy = true;
110470
+ entry;
110471
+ deps;
110472
+ clock;
110473
+ state = "CONNECTING";
110474
+ transport;
110475
+ timer;
110476
+ backoff;
110477
+ start() {
110478
+ void this.attempt();
110479
+ }
110480
+ stop() {
110481
+ this.state = "STOPPED";
110482
+ this.clearTimer();
110483
+ this.transport?.close(1e3, "shutdown");
110484
+ this.transport = void 0;
110485
+ }
110486
+ dial(url2) {
110487
+ if (this.deps.connect) return this.deps.connect(url2);
110488
+ return ClientTransport.dial(url2, {
110489
+ subprotocol: RELAY_COMPUTER_SUBPROTOCOL,
110490
+ path: new URL(url2).pathname,
110491
+ maxPayload: RELAY_COMPUTER_MAX_FRAME_BYTES
110492
+ });
110493
+ }
110494
+ async attempt() {
110495
+ if (this.state === "STOPPED") return;
110496
+ this.state = "CONNECTING";
110497
+ const token = this.deps.token();
110498
+ if (!token) return this.wait();
110499
+ let transport;
110302
110500
  try {
110303
- if (!checked) {
110304
- const graphical = await probe.graphical(options.session);
110305
- if (graphical === void 0) return;
110306
- checked = true;
110307
- if (graphical === null) return await end();
110308
- if (!graphical) {
110309
- stop();
110310
- options.onIgnored?.(`session ${options.session} is not a graphical session; not following it`);
110311
- return;
110312
- }
110313
- }
110314
- const live2 = await probe.live(options.session);
110315
- if (live2 === true) unknown2 = 0;
110316
- if (live2 === true || live2 === void 0 && ++unknown2 < UNKNOWN_LIMIT) return;
110317
- await end();
110318
- } finally {
110319
- busy = false;
110501
+ transport = await this.dial(relayComputerWsUrl(this.entry.url));
110502
+ } catch (error62) {
110503
+ this.deps.log(`relay ${this.entry.relayId}: cannot connect: ${error62.message}`);
110504
+ return this.wait();
110320
110505
  }
110321
- };
110322
- const end = async () => {
110323
- const next = await probe.managerSession();
110324
- if (next && next !== options.session && await probe.live(next) === true) {
110325
- stop();
110326
- options.onEnded(EXIT_NEW_SESSION, `desktop session ${options.session} ended; restarting in session ${next}`);
110506
+ if (this.state !== "CONNECTING") return void transport.close(1e3, "shutdown");
110507
+ this.transport = transport;
110508
+ this.state = "HELLO";
110509
+ const hello = buildRelayComputerFrame("cr/hello", {
110510
+ computerId: this.deps.computerId,
110511
+ token,
110512
+ desktopDaemonVersion: this.deps.desktopDaemonVersion
110513
+ });
110514
+ transport.onMessage((text) => this.onText(transport, hello.id, text));
110515
+ transport.onClose((code, reason) => this.onClose(transport, code, reason));
110516
+ this.timer = this.clock.setTimeout(() => {
110517
+ this.timer = void 0;
110518
+ if (this.state === "HELLO" && this.transport === transport) transport.close(1e3, "hello timeout");
110519
+ }, HELLO_TIMEOUT_MS);
110520
+ transport.send(JSON.stringify(hello));
110521
+ }
110522
+ onText(transport, helloId, text) {
110523
+ if (this.transport !== transport) return;
110524
+ const decoded = decodeRelayComputerFrame(text);
110525
+ if (!decoded.ok) return this.deps.log(`relay ${this.entry.relayId}: unreadable frame (${decoded.msg})`);
110526
+ const frame = decoded.frame;
110527
+ if (this.state === "HELLO") return this.onHelloReply(transport, helloId, frame);
110528
+ if (this.state === "READY" && frame.type === "cr/http") return void this.serve(transport, frame);
110529
+ }
110530
+ onHelloReply(transport, helloId, frame) {
110531
+ if (frame.corr !== helloId) return;
110532
+ this.clearTimer();
110533
+ if (frame.type === "cr/hello/ok" && frame.payload.relayId === this.entry.relayId) {
110534
+ this.state = "READY";
110535
+ this.backoff.reset();
110536
+ this.deps.log(`relay ${this.entry.relayId}: attached`);
110327
110537
  return;
110328
110538
  }
110329
- await probe.forget(options.session);
110330
- stop();
110331
- options.onEnded(0, `desktop session ${options.session} ended`);
110332
- };
110333
- const timer = setInterval(() => void tick(), options.intervalMs ?? 5e3);
110334
- timer.unref();
110335
- const stop = () => {
110336
- stopped = true;
110337
- clearInterval(timer);
110338
- };
110339
- return stop;
110340
- }
110341
-
110342
- // src/service-macos.ts
110343
- import { spawnSync as spawnSync7 } from "node:child_process";
110344
- import { existsSync as existsSync4, mkdirSync as mkdirSync8, rmSync as rmSync6, writeFileSync as writeFileSync9 } from "node:fs";
110345
- import { homedir as homedir4 } from "node:os";
110346
- import { join as join10 } from "node:path";
110347
- var SERVICE_LABEL = "md.agentconnect.computer";
110348
- var plistPath = () => join10(homedir4(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
110349
- var domain2 = () => `gui/${process.getuid()}`;
110350
- var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
110351
- function launchctl(...args) {
110352
- const result = spawnSync7("launchctl", args, { encoding: "utf8" });
110353
- return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };
110354
- }
110355
- var guiSession = () => launchctl("print", domain2()).ok;
110356
- function servicePlist(program, logPath) {
110357
- return `<?xml version="1.0" encoding="UTF-8"?>
110358
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
110359
- <plist version="1.0">
110360
- <dict>
110361
- <key>Label</key><string>${SERVICE_LABEL}</string>
110362
- <key>ProgramArguments</key><array>${[...program, "run"].map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
110363
- <key>AssociatedBundleIdentifiers</key><array><string>${SERVICE_LABEL}</string></array>
110364
- <key>LimitLoadToSessionType</key><string>Aqua</string>
110365
- <key>ProcessType</key><string>Interactive</string>
110366
- <key>RunAtLoad</key><true/>
110367
- <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
110368
- <key>StandardOutPath</key><string>${xml(logPath)}</string>
110369
- <key>StandardErrorPath</key><string>${xml(logPath)}</string>
110370
- <key>EnvironmentVariables</key><dict><key>NODE_OPTIONS</key><string></string></dict>
110371
- </dict>
110372
- </plist>
110373
- `;
110374
- }
110375
- function installService2(program, logPath) {
110376
- mkdirSync8(join10(homedir4(), "Library", "LaunchAgents"), { recursive: true });
110377
- stopService2();
110378
- writeFileSync9(plistPath(), servicePlist(program, logPath));
110379
- if (!guiSession()) return false;
110380
- startService2();
110381
- return true;
110382
- }
110383
- function startService2() {
110384
- if (serviceStatus2().loaded) return;
110385
- if (!guiSession()) throw new Error("nobody is logged in to this Mac's desktop: the service starts at the next login");
110386
- const result = launchctl("bootstrap", domain2(), plistPath());
110387
- if (!result.ok) throw new Error(`launchctl bootstrap failed: ${result.output}`);
110388
- }
110389
- function stopService2() {
110390
- if (!serviceStatus2().loaded) return;
110391
- launchctl("bootout", `${domain2()}/${SERVICE_LABEL}`);
110392
- const deadline = Date.now() + 1e4;
110393
- while (serviceStatus2().loaded && Date.now() < deadline) spawnSync7("sleep", ["0.2"]);
110394
- }
110395
- function restartService2() {
110396
- const result = launchctl("kickstart", "-k", `${domain2()}/${SERVICE_LABEL}`);
110397
- if (!result.ok) throw new Error(`launchctl kickstart failed: ${result.output}`);
110398
- }
110399
- function uninstallService2() {
110400
- stopService2();
110401
- rmSync6(plistPath(), { force: true });
110402
- }
110403
- function serviceStatus2() {
110404
- const installed = existsSync4(plistPath());
110405
- const result = launchctl("print", `${domain2()}/${SERVICE_LABEL}`);
110406
- if (!result.ok) return { installed, loaded: false };
110407
- const pid = /^\s*pid = (\d+)/m.exec(result.output)?.[1];
110408
- const state = /^\s*state = (\S+)/m.exec(result.output)?.[1];
110409
- return { installed, loaded: true, ...pid ? { pid: Number(pid) } : {}, ...state ? { state } : {} };
110410
- }
110411
-
110412
- // src/setup.ts
110413
- import { spawn as spawn5, spawnSync as spawnSync8 } from "node:child_process";
110414
- import { existsSync as existsSync5 } from "node:fs";
110415
- import { basename, dirname as dirname2, isAbsolute, join as join11 } from "node:path";
110416
- import { createInterface } from "node:readline";
110417
- var localizeChecks = (checks, command = selfCommand()) => {
110418
- const rename = (text) => text.replace(/(?<![\w/.-])agentconnect-computer(?= |$)/g, command);
110419
- return checks.map((check2) => ({
110420
- ...check2,
110421
- detail: rename(check2.detail),
110422
- ...check2.fix === void 0 ? {} : { fix: rename(check2.fix) }
110423
- }));
110424
- };
110425
- var ICON = { ok: "\u2705", info: "\u2139\uFE0F ", warn: "\u26A0\uFE0F ", fail: "\u274C" };
110426
- var FIREWALL_RULE = "AgentConnect Computer (Node.js)";
110427
- var MAC_PANES = {
110428
- accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
110429
- screenRecording: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
110539
+ const why = frame.type === "error" ? frame.payload.message : `reached relay ${String(frame.payload.relayId)}`;
110540
+ this.deps.log(`relay ${this.entry.relayId}: not attached (${why})`);
110541
+ transport.close(1e3, "hello refused");
110542
+ }
110543
+ async serve(transport, frame) {
110544
+ let response;
110545
+ try {
110546
+ response = await this.deps.handle(frame.payload);
110547
+ } catch (error62) {
110548
+ this.deps.log(`relay ${this.entry.relayId}: request failed: ${error62.message}`);
110549
+ response = { status: 500, headers: {} };
110550
+ }
110551
+ if (this.transport !== transport || this.state !== "READY") return;
110552
+ try {
110553
+ transport.send(JSON.stringify(buildRelayComputerFrame("cr/http/result", response, { corr: frame.id })));
110554
+ } catch (error62) {
110555
+ this.deps.log(`relay ${this.entry.relayId}: reply failed: ${error62.message}`);
110556
+ }
110557
+ }
110558
+ onClose(transport, code, reason) {
110559
+ if (this.transport !== transport) return;
110560
+ this.transport = void 0;
110561
+ this.clearTimer();
110562
+ if (this.state === "STOPPED") return;
110563
+ this.deps.log(`relay ${this.entry.relayId}: closed (${code}${reason ? ` ${reason}` : ""})`);
110564
+ this.wait();
110565
+ }
110566
+ wait() {
110567
+ if (this.state === "STOPPED") return;
110568
+ this.state = "WAITING";
110569
+ this.clearTimer();
110570
+ this.timer = this.clock.setTimeout(() => {
110571
+ this.timer = void 0;
110572
+ void this.attempt();
110573
+ }, this.backoff.next());
110574
+ }
110575
+ clearTimer() {
110576
+ if (this.timer !== void 0) this.clock.clearTimeout(this.timer);
110577
+ this.timer = void 0;
110578
+ }
110430
110579
  };
110431
- function printChecks(checks) {
110432
- const width = Math.max(...checks.map((check2) => check2.name.length));
110433
- for (const check2 of checks) {
110434
- console.log(`${ICON[check2.status]} ${check2.name.padEnd(width)} ${check2.detail}`);
110435
- if (check2.fix && check2.status !== "ok") console.log(` ${" ".repeat(width)} \u2192 ${check2.fix}`);
110580
+ var RelayLinks = class {
110581
+ constructor(deps) {
110582
+ this.deps = deps;
110583
+ this.clock = deps.clock ?? systemClock;
110584
+ }
110585
+ deps;
110586
+ links = /* @__PURE__ */ new Map();
110587
+ clock;
110588
+ converge(relays) {
110589
+ const wanted = new Map(relays.map((entry) => [entry.relayId, entry]));
110590
+ for (const [id, link] of this.links) {
110591
+ const entry = wanted.get(id);
110592
+ if (entry && entry.url === link.entry.url) continue;
110593
+ link.stop();
110594
+ this.links.delete(id);
110595
+ }
110596
+ for (const [id, entry] of wanted) {
110597
+ const current = this.links.get(id);
110598
+ if (current && current.state !== "WAITING") continue;
110599
+ current?.stop();
110600
+ const link = new RelayLink(entry, this.deps, this.clock);
110601
+ this.links.set(id, link);
110602
+ link.start();
110603
+ }
110604
+ }
110605
+ /** Close every link: on revoke, a lapsed key or shutdown. */
110606
+ stop() {
110607
+ for (const link of this.links.values()) link.stop();
110608
+ this.links.clear();
110609
+ }
110610
+ /** Relay ids with an attached link. */
110611
+ attached() {
110612
+ return [...this.links.values()].filter((link) => link.state === "READY").map((link) => link.entry.relayId);
110436
110613
  }
110437
- const failed = checks.filter((check2) => check2.status === "fail").length;
110438
- const warned = checks.filter((check2) => check2.status === "warn").length;
110439
- console.log(
110440
- failed ? `
110441
- ${failed} check(s) failed.` : warned ? `
110442
- All required checks passed (${warned} warning(s)).` : "\nAll checks passed."
110443
- );
110444
- return failed === 0;
110445
- }
110446
- var hostApp = () => {
110447
- const app = appBundlePath();
110448
- return app ? basename(app) : process.env.TERM_PROGRAM ?? process.env.__CFBundleIdentifier ?? "the launching app";
110449
110614
  };
110450
- var overSsh = () => Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY) && !process.env.__CFBundleIdentifier && !process.env.TERM_PROGRAM;
110451
- async function macPermissions(driver, prompt = false) {
110452
- const result = await driver.call("check_permissions", prompt ? { prompt: true } : { prompt: false });
110453
- const meta3 = result.structuredContent ?? {};
110615
+
110616
+ // src/mcp-access.ts
110617
+ var bearer = (authorization) => /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1];
110618
+ function channelPrincipal(authorization, authority, computerId) {
110619
+ const token = bearer(authorization);
110620
+ const id = computerId();
110621
+ if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
110622
+ const claims = authority.verify(token, "mcp", id);
110623
+ if (!claims?.ses || !claims.agt) return void 0;
110454
110624
  return {
110455
- accessibility: meta3.accessibility === true,
110456
- screenRecording: meta3.screen_recording === true,
110457
- directCapture: typeof meta3.direct_capture_status === "string" ? meta3.direct_capture_status : "not_checked"
110625
+ client: computerLeaseHolderName({ agentId: claims.agt, sessionId: claims.ses }),
110626
+ viewOnly: claims.mode === "view",
110627
+ agent: { agentId: claims.agt, sessionId: claims.ses }
110458
110628
  };
110459
110629
  }
110460
- function powershell(script, timeoutMs = 3e4) {
110461
- const result = spawnSync8("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
110462
- encoding: "utf8",
110463
- windowsHide: true,
110464
- timeout: timeoutMs
110465
- });
110466
- return { ok: result.status === 0, stdout: result.stdout ?? "" };
110630
+ var RESPONSE_HEADERS = ["allow", "content-type", "mcp-protocol-version", "mcp-session-id", "www-authenticate"];
110631
+ function reply(status, body, headers = {}) {
110632
+ return {
110633
+ status,
110634
+ headers: { "content-type": "application/json", ...headers },
110635
+ body: Buffer.from(JSON.stringify(body)).toString("base64")
110636
+ };
110467
110637
  }
110468
- var psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
110469
- function firewallState(program) {
110470
- const script = `$ErrorActionPreference = 'SilentlyContinue'
110471
- $p = ${psQuote(program)}
110472
- $rules = @(Get-NetFirewallApplicationFilter | Where-Object { [Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p } | Get-NetFirewallRule | Where-Object { "$($_.Enabled)" -eq 'True' -and "$($_.Direction)" -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; action = "$($_.Action)"; profile = "$($_.Profile)" } })
110473
- $profiles = @(Get-NetConnectionProfile | ForEach-Object { "$($_.NetworkCategory)" })
110474
- ConvertTo-Json -Compress -InputObject @{ rules = $rules; profiles = $profiles }`;
110475
- const result = powershell(script);
110476
- if (!result.ok) return void 0;
110477
- try {
110478
- const parsed = JSON.parse(result.stdout.trim());
110479
- const rules = parsed.rules ?? [];
110480
- return {
110481
- allow: rules.filter((rule) => rule.action === "Allow"),
110482
- block: rules.filter((rule) => rule.action === "Block"),
110483
- activeProfiles: [...new Set(parsed.profiles ?? [])]
110484
- };
110485
- } catch {
110486
- return void 0;
110487
- }
110638
+ function viewerPrincipal(authorization, authority, computerId) {
110639
+ const token = bearer(authorization);
110640
+ const id = computerId();
110641
+ if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
110642
+ const claims = authority.verify(token, "view", id);
110643
+ if (!claims?.usr) return void 0;
110644
+ return {
110645
+ client: `console:${claims.usr}`,
110646
+ control: claims.mode === "control",
110647
+ iceServers: claims.ice ?? [],
110648
+ stunUrls: claims.stun ?? [],
110649
+ valid: () => authority.verify(token, "view", id) !== void 0
110650
+ };
110488
110651
  }
110489
- var profileCovered = (profile, category) => profile === "Any" || profile.split(/,\s*/).includes(category === "DomainAuthenticated" ? "Domain" : category);
110490
- async function doctor(ctx, captureTimeoutMs = 15e3) {
110491
- const checks = [];
110492
- const { config: config2 } = ctx;
110493
- const registration = registrationCheck(ctx.dir);
110494
- checks.push({ name: "version", status: "ok", detail: `desktop daemon ${COMPUTER_DAEMON_VERSION}` });
110495
- checks.push(
110496
- config2.clients.length > 0 ? {
110497
- name: "config",
110498
- status: "ok",
110499
- detail: `${configPath(ctx.dir)} (clients: ${config2.clients.map((client) => client.name).join(", ")})`
110500
- } : registration.status === "ok" ? { name: "config", status: "ok", detail: `${configPath(ctx.dir)} (no local client tokens)` } : { name: "config", status: "fail", detail: "no client token yet", fix: `run: ${selfCommand()} setup` }
110501
- );
110502
- checks.push(registration);
110503
- checks.push(sessionCheck());
110504
- wakeDisplay();
110505
- if (isAbsolute(ctx.driverCommand) && !existsSync5(ctx.driverCommand)) {
110506
- checks.push({
110507
- name: "cua-driver",
110508
- status: "fail",
110509
- detail: `missing ${ctx.driverCommand}`,
110510
- fix: `run: ${selfCommand()} setup`
110652
+ function viewerAuthenticator(member, localClient) {
110653
+ return (authorization, via) => {
110654
+ const principal = member(authorization);
110655
+ if (principal) return principal;
110656
+ if (via !== "local") return void 0;
110657
+ const client = localClient(authorization);
110658
+ return client ? { client, control: true } : void 0;
110659
+ };
110660
+ }
110661
+ function createRelayedMcpHandler(deps) {
110662
+ return async (request2) => {
110663
+ const pathname = new URL(request2.path, "http://desktop.invalid").pathname;
110664
+ if (deps.viewer && pathname.startsWith(COMPUTER_VIEWER_API_PREFIX)) {
110665
+ const out = await deps.viewer({
110666
+ method: request2.method,
110667
+ path: pathname,
110668
+ authorization: request2.headers.authorization,
110669
+ via: "relay",
110670
+ ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
110671
+ });
110672
+ if (out.body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
110673
+ return {
110674
+ status: out.status,
110675
+ headers: out.headers,
110676
+ ...out.body.length > 0 ? { body: out.body.toString("base64") } : {}
110677
+ };
110678
+ }
110679
+ if (pathname !== "/mcp") return reply(404, { error: "not found" });
110680
+ const principal = deps.authenticate(request2.headers.authorization);
110681
+ if (!principal) return reply(401, { error: "unauthorized" }, { "www-authenticate": "Bearer" });
110682
+ if (request2.method !== "POST" && request2.method !== "DELETE") {
110683
+ return reply(405, { error: "method not allowed" }, { allow: "POST, DELETE" });
110684
+ }
110685
+ const mcp = deps.createMcpServer(principal);
110686
+ const transport = new WebStandardStreamableHTTPServerTransport({
110687
+ sessionIdGenerator: void 0,
110688
+ enableJsonResponse: true
110511
110689
  });
110512
- } else {
110513
- const driver = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: config2.driverCallTimeoutMs });
110514
110690
  try {
110515
- const size = await driver.call("get_screen_size", {});
110516
- checks.push({
110517
- name: "cua-driver",
110518
- status: "ok",
110519
- detail: `${driver.version ?? CUA_DRIVER_VERSION}: ${size.content.find((block) => block.text)?.text ?? "started"}`
110520
- });
110521
- if (process.platform === "darwin")
110522
- checks.push(
110523
- ...macPermissionChecks(await macPermissions(driver), appBundlePath() ? readGrantRecord(ctx.dir) : void 0)
110524
- );
110525
- const shot = await driver.call("get_desktop_state", { max_image_dimension: 320 }).then(() => void 0).catch((error62) => error62.message);
110526
- checks.push(
110527
- shot ? { name: "screenshot", status: "fail", detail: shot.slice(0, 160), fix: permissionFix() } : { name: "screenshot", status: "ok", detail: "desktop capture works" }
110691
+ await mcp.connect(transport);
110692
+ const response = await transport.handleRequest(
110693
+ new Request("http://desktop.invalid/mcp", {
110694
+ method: request2.method,
110695
+ headers: request2.headers,
110696
+ ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
110697
+ })
110528
110698
  );
110699
+ const body = Buffer.from(await response.arrayBuffer());
110700
+ if (body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
110701
+ const headers = {};
110702
+ for (const name of RESPONSE_HEADERS) {
110703
+ const value = response.headers.get(name);
110704
+ if (value !== null) headers[name] = value;
110705
+ }
110706
+ return { status: response.status, headers, ...body.length > 0 ? { body: body.toString("base64") } : {} };
110529
110707
  } catch (error62) {
110530
- checks.push({
110531
- name: "cua-driver",
110532
- status: "fail",
110533
- detail: error62.message.slice(0, 160),
110534
- fix: `run: ${selfCommand()} setup`
110535
- });
110708
+ deps.log(`relayed request failed: ${error62.message}`);
110709
+ return reply(500, { error: "failed" });
110536
110710
  } finally {
110537
- await driver.close();
110711
+ void mcp.close().catch(() => void 0);
110538
110712
  }
110539
- }
110540
- checks.push(displayCheck(config2));
110541
- checks.push(...ffmpegChecks(ctx, captureTimeoutMs));
110542
- if (process.platform === "win32") checks.push(firewallCheck(config2));
110543
- if (process.platform === "linux") checks.push(...linuxChecks(ctx));
110544
- checks.push(await daemonCheck(config2));
110545
- return checks;
110713
+ };
110546
110714
  }
110547
- function registrationCheck(dir) {
110548
- let registration;
110549
- try {
110550
- registration = loadRegistration(dir);
110551
- } catch (error62) {
110552
- return {
110553
- name: "control plane",
110554
- status: "fail",
110555
- detail: `unreadable ${registrationPath(dir)}: ${error62.message}`.slice(0, 300),
110556
- fix: `register again: ${selfCommand()} setup --register <token> --cp-url <url>`
110557
- };
110715
+
110716
+ // src/cp/report.ts
110717
+ import { spawnSync as spawnSync8 } from "node:child_process";
110718
+ import { existsSync as existsSync7, readdirSync, readFileSync as readFileSync6 } from "node:fs";
110719
+ import { release as release2 } from "node:os";
110720
+ var MAX_CHECKS = 64;
110721
+ var MAX_TEXT = 1e3;
110722
+ var computerOs = (platform = process.platform) => platform === "darwin" ? "macos" : platform === "win32" ? "windows" : "linux";
110723
+ function osVersion(platform = process.platform) {
110724
+ if (platform === "linux") {
110725
+ try {
110726
+ const pretty = /^PRETTY_NAME="?([^"\n]+)"?$/m.exec(readFileSync6("/etc/os-release", "utf8"))?.[1];
110727
+ if (pretty) return pretty.slice(0, 120);
110728
+ } catch {
110729
+ }
110558
110730
  }
110559
- if (!registration) {
110560
- return { name: "control plane", status: "info", detail: "not registered: local client tokens only" };
110731
+ if (platform === "darwin") {
110732
+ const result = spawnSync8("sw_vers", ["-productVersion"], { encoding: "utf8" });
110733
+ if (result.status === 0 && result.stdout.trim()) return `macOS ${result.stdout.trim()}`;
110561
110734
  }
110562
- if (registration.revokedAt) {
110563
- return {
110564
- name: "control plane",
110565
- status: "fail",
110566
- detail: `computer ${registration.computerId} was revoked (${registration.revokedReason ?? "by the Control Plane"}): all input is refused`,
110567
- fix: `create a new registration in the console, then: ${selfCommand()} setup --register <token> --cp-url ${registration.cpUrl}`
110568
- };
110735
+ return `${platform} ${release2()}`.slice(0, 120);
110736
+ }
110737
+ function xvfbServes(display) {
110738
+ const number4 = /^:(\d+)/.exec(display)?.[1];
110739
+ if (number4 === void 0) return false;
110740
+ try {
110741
+ for (const pid of readdirSync("/proc")) {
110742
+ if (!/^\d+$/.test(pid)) continue;
110743
+ const argv = readFileSync6(`/proc/${pid}/cmdline`, "utf8").split("\0");
110744
+ if (/(^|\/)Xvfb$/.test(argv[0] ?? "") && argv.includes(`:${number4}`)) return true;
110745
+ }
110746
+ } catch {
110569
110747
  }
110748
+ return false;
110749
+ }
110750
+ function sessionKind(platform = process.platform, env = process.env) {
110751
+ if (platform === "darwin") return "aqua";
110752
+ if (platform === "win32") return env.SESSIONNAME?.startsWith("RDP") ? "rdp" : "console";
110753
+ if (env.WAYLAND_DISPLAY) return "wayland-gnome";
110754
+ return env.DISPLAY && xvfbServes(env.DISPLAY) ? "xvfb" : "x11";
110755
+ }
110756
+ function isolationKind(env = process.env) {
110757
+ const declared = env.AGENTCONNECT_COMPUTER_ISOLATION;
110758
+ if (declared === "none" || declared === "container" || declared === "vm") return declared;
110759
+ return existsSync7("/.dockerenv") || existsSync7("/run/.containerenv") ? "container" : "none";
110760
+ }
110761
+ var truncate = (text) => text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT - 1)}\u2026` : text;
110762
+ function doctorReport(checks, at = /* @__PURE__ */ new Date()) {
110570
110763
  return {
110571
- name: "control plane",
110572
- status: "ok",
110573
- detail: `registered as computer ${registration.computerId} with ${registration.cpUrl}`
110764
+ checkedAt: at.toISOString(),
110765
+ checks: checks.slice(0, MAX_CHECKS).map((check2) => ({
110766
+ name: check2.name.slice(0, 64) || "check",
110767
+ status: check2.status,
110768
+ detail: truncate(check2.detail),
110769
+ ...check2.fix ? { fix: truncate(check2.fix) } : {}
110770
+ }))
110574
110771
  };
110575
110772
  }
110576
- function sessionCheck() {
110577
- if (process.platform === "darwin") {
110578
- return overSsh() ? {
110579
- name: "session",
110580
- status: "warn",
110581
- detail: "running over SSH: macOS ties permissions to the app that starts the daemon",
110582
- fix: "run setup / run from Terminal on the desktop itself"
110583
- } : { name: "session", status: "ok", detail: `desktop session, host app ${hostApp()}` };
110584
- }
110585
- if (process.platform === "win32") {
110586
- const session = process.env.SESSIONNAME;
110587
- if (!session) {
110588
- return {
110589
- name: "session",
110590
- status: "fail",
110591
- detail: "not an interactive desktop session (service or scheduled task?)",
110592
- fix: "start it from a terminal on the logged-in desktop"
110593
- };
110773
+ function capabilitiesFrom(checks, display, options = {}) {
110774
+ const platform = options.platform ?? process.platform;
110775
+ const status = (name) => checks?.find((check2) => check2.name === name)?.status;
110776
+ const ok = (name) => status(name) === "ok";
110777
+ const known = (name) => status(name) === void 0 ? void 0 : ok(name);
110778
+ const driver = ok("cua-driver");
110779
+ const accessibility = known("accessibility");
110780
+ const screenshot = driver && ok("screenshot");
110781
+ const permissions = {};
110782
+ if (accessibility !== void 0) permissions.accessibility = accessibility;
110783
+ const screenRecording = known("screen recording");
110784
+ if (screenRecording !== void 0) permissions.screenRecording = screenRecording;
110785
+ const portal = known("portal");
110786
+ if (portal !== void 0) permissions.portal = portal;
110787
+ const firewall = status("firewall");
110788
+ if (firewall !== void 0) permissions.firewall = firewall === "ok" || firewall === "info";
110789
+ return {
110790
+ screenshot,
110791
+ // On macOS clicks are dropped silently without Accessibility, so input needs that grant too.
110792
+ input: driver && (platform !== "darwin" || accessibility === true),
110793
+ // libei on GNOME Wayland sends keycodes only, so IME text is dropped (§3.2.3).
110794
+ textInput: options.session === "wayland-gnome" ? "keymap-only" : "full",
110795
+ humanActivity: options.keyboardActivity ? "pointer+keyboard" : "pointer",
110796
+ backgroundInput: false,
110797
+ accessibilityTree: false,
110798
+ viewer: options.webrtc !== false && ok("ffmpeg") && ok("screen capture"),
110799
+ viewerStun: true,
110800
+ ...options.egress ? { egress: true } : {},
110801
+ displays: display && display.screenWidth > 0 && display.screenHeight > 0 ? [
110802
+ {
110803
+ id: "primary",
110804
+ width: Math.round(display.screenWidth),
110805
+ height: Math.round(display.screenHeight),
110806
+ scale: display.scale > 0 ? display.scale : 1
110807
+ }
110808
+ ] : [],
110809
+ permissions
110810
+ };
110811
+ }
110812
+
110813
+ // src/cp/env-registration.ts
110814
+ import { createHash as createHash6 } from "node:crypto";
110815
+ import { readFileSync as readFileSync7 } from "node:fs";
110816
+ var REGISTER_TOKEN_ENV = "AGENTCONNECT_REGISTER_TOKEN";
110817
+ var REGISTER_TOKEN_FILE_ENV = "AGENTCONNECT_REGISTER_TOKEN_FILE";
110818
+ var CP_URL_ENV = "AGENTCONNECT_CP_URL";
110819
+ var COMPUTER_NAME_ENV = "AGENTCONNECT_COMPUTER_NAME";
110820
+ function registrationFromEnv(env = process.env, read = (path) => readFileSync7(path, "utf8")) {
110821
+ let token = env[REGISTER_TOKEN_ENV]?.trim() ?? "";
110822
+ const file2 = env[REGISTER_TOKEN_FILE_ENV]?.trim();
110823
+ if (!token && file2) {
110824
+ try {
110825
+ token = read(file2).trim();
110826
+ } catch (error62) {
110827
+ throw new Error(
110828
+ `cannot read ${REGISTER_TOKEN_FILE_ENV} (${file2}): ${error62.code ?? "error"}`
110829
+ );
110594
110830
  }
110595
- return session.startsWith("RDP") ? {
110596
- name: "session",
110597
- status: "warn",
110598
- detail: `${session}: disconnecting RDP locks this session and stops capture`,
110599
- fix: "prefer the console session"
110600
- } : { name: "session", status: "ok", detail: `interactive session (${session})` };
110601
110831
  }
110602
- if (waylandSession()) {
110603
- return {
110604
- name: "session",
110605
- status: "ok",
110606
- detail: `Wayland (${process.env.XDG_CURRENT_DESKTOP ?? "unknown desktop"}, ${process.env.WAYLAND_DISPLAY})`
110607
- };
110832
+ if (!token) return void 0;
110833
+ const cpUrl = env[CP_URL_ENV]?.trim();
110834
+ if (!cpUrl) throw new Error(`${CP_URL_ENV} is required with a registration token (the console prints it)`);
110835
+ const name = env[COMPUTER_NAME_ENV]?.trim();
110836
+ return { token, cpUrl, ...name ? { name } : {} };
110837
+ }
110838
+ var tokenSha256 = (token) => createHash6("sha256").update(token).digest("hex");
110839
+ var keepsRegistration = (current, wanted) => Boolean(
110840
+ current && !current.revokedAt && current.cpUrl === cpBaseUrl(wanted.cpUrl) && current.tokenSha256 === tokenSha256(wanted.token)
110841
+ );
110842
+ var staysRevoked = (current, cpUrl) => Boolean(current?.revokedAt && current.cpUrl === cpBaseUrl(cpUrl));
110843
+ async function registerFromEnv(options) {
110844
+ const { wanted } = options;
110845
+ if (!wanted) return { kind: "none" };
110846
+ const current = options.load();
110847
+ if (current && keepsRegistration(current, wanted)) return { kind: "kept", registration: current };
110848
+ try {
110849
+ const registration = { ...await options.exchange(wanted), tokenSha256: tokenSha256(wanted.token) };
110850
+ options.save(registration);
110851
+ return { kind: "registered", registration };
110852
+ } catch (error62) {
110853
+ if (error62 instanceof RegistrationTokenRefused && current && staysRevoked(current, wanted.cpUrl)) {
110854
+ return { kind: "stays-revoked", registration: current, reason: error62.message };
110855
+ }
110856
+ throw error62;
110608
110857
  }
110609
- return process.env.DISPLAY ? { name: "session", status: "ok", detail: `X11 display ${process.env.DISPLAY}` } : {
110610
- name: "session",
110611
- status: "fail",
110612
- detail: "no DISPLAY or WAYLAND_DISPLAY",
110613
- fix: "run inside the graphical session (or export its WAYLAND_DISPLAY, XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS)"
110614
- };
110615
110858
  }
110616
- var permissionFix = () => process.platform === "darwin" ? `grant ${hostApp()} the macOS permissions: ${selfCommand()} setup` : void 0;
110617
- var PANE = {
110618
- accessibility: "Privacy & Security > Accessibility (macOS 27: Device Control and Data Access)",
110619
- screenRecording: "Privacy & Security > Screen & System Audio Recording"
110620
- };
110621
- function macPermissionChecks(state, record2, app = hostApp()) {
110622
- const inApp = Boolean(record2);
110623
- const reopen = inApp ? `then: ${selfCommand()} service restart` : "then Cmd+Q and reopen";
110624
- const check2 = (grant, name, effect) => {
110625
- if (state[grant]) return { name, status: "ok", detail: `granted to ${app}` };
110626
- const loss = record2 ? grantLoss(record2, grant) : "never-asked";
110627
- if (loss === "lost")
110628
- return {
110629
- name,
110630
- status: "fail",
110631
- detail: `was granted to ${app} but is not in effect: switched off, or held by an earlier build of the app${effect}`,
110632
- fix: `run: tccutil reset ${TCC_SERVICE[grant]} ${APP_ID}, then: ${selfCommand()} setup`
110633
- };
110634
- if (loss === "listed-off")
110635
- return {
110636
- name,
110637
- status: "fail",
110638
- detail: `${app} is listed in ${PANE[grant]} but switched off${effect}`,
110639
- fix: `switch ${app} on there (listed is not enough), ${reopen}`
110640
- };
110641
- return {
110642
- name,
110643
- status: "fail",
110644
- detail: `not granted to ${app}${effect}`,
110645
- fix: inApp ? `run: ${selfCommand()} setup` : `${PANE[grant]}: switch it on, ${reopen}`
110646
- };
110647
- };
110648
- return [
110649
- check2("accessibility", "accessibility", ": clicks and keys are silently dropped while pointer moves still work"),
110650
- check2("screenRecording", "screen recording", "")
110651
- ];
110859
+
110860
+ // src/cp/pool-bootstrap.ts
110861
+ import { once as once3 } from "node:events";
110862
+ import { createServer as createServer3 } from "node:http";
110863
+ var POOL_BOOTSTRAP_PORT_ENV = "AGENTCONNECT_POOL_BOOTSTRAP_PORT";
110864
+ function poolBootstrapPort(env = process.env) {
110865
+ const raw = env[POOL_BOOTSTRAP_PORT_ENV]?.trim();
110866
+ if (!raw) return void 0;
110867
+ const port = Number(raw);
110868
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
110869
+ throw new Error(`${POOL_BOOTSTRAP_PORT_ENV} is not a valid port: ${raw}`);
110870
+ return port;
110652
110871
  }
110653
- function displayCheck(config2) {
110654
- const minutes = displaySleepMinutes();
110655
- const setting = minutes === void 0 ? "" : minutes === 0 ? " (display sleep: never)" : ` (display sleep: ${minutes} min)`;
110656
- if (config2.keepAwake && !canKeepAwake()) {
110657
- return {
110658
- name: "display",
110659
- status: "warn",
110660
- detail: "cannot hold this desktop awake: a blanked or locked screen cannot be captured or controlled",
110661
- fix: "disable screen blanking and automatic lock in the desktop settings"
110662
- };
110663
- }
110664
- return config2.keepAwake ? { name: "display", status: "ok", detail: `the daemon keeps the display awake while it runs${setting}` } : {
110665
- name: "display",
110666
- status: minutes === 0 ? "ok" : "warn",
110667
- detail: `keepAwake is off${setting}: a sleeping or locked display cannot be captured or controlled`,
110668
- fix: 'set "keepAwake": true in config.json'
110669
- };
110872
+ var MAX_BODY = 4096;
110873
+ var live = (registration) => registration && !registration.revokedAt ? registration : void 0;
110874
+ function send2(res, status, body) {
110875
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
110876
+ res.end(JSON.stringify(body));
110670
110877
  }
110671
- var GNOME_HELPER = "winrects@cua";
110672
- var gnomeWayland = () => waylandSession() && /GNOME/i.test(process.env.XDG_CURRENT_DESKTOP ?? "");
110673
- function gnomeHelperState() {
110674
- const info = spawnSync8("gnome-extensions", ["info", GNOME_HELPER], { encoding: "utf8" });
110675
- if (info.status !== 0) return "missing";
110676
- return /State:\s*(ACTIVE|ENABLED)/i.test(info.stdout ?? "") ? "active" : "installed";
110878
+ async function readBody2(req) {
110879
+ let body = "";
110880
+ for await (const chunk of req) {
110881
+ body += String(chunk);
110882
+ if (body.length > MAX_BODY) throw new Error("body too large");
110883
+ }
110884
+ return body;
110677
110885
  }
110678
- function linuxChecks(ctx) {
110679
- if (!waylandSession()) return [];
110680
- const checks = [];
110681
- if (gnomeWayland()) {
110682
- const helper = gnomeHelperState();
110683
- checks.push(
110684
- helper === "active" ? {
110685
- name: "gnome helper",
110686
- status: "ok",
110687
- detail: `${GNOME_HELPER} extension active (pixel geometry, capture, cursor)`
110688
- } : {
110689
- name: "gnome helper",
110690
- status: "fail",
110691
- detail: helper === "installed" ? `${GNOME_HELPER} is installed but not loaded yet` : `${GNOME_HELPER} extension missing: no pixel coordinates or safe input on GNOME Wayland`,
110692
- fix: helper === "installed" ? "log out and back in once" : `run: ${selfCommand()} setup`
110886
+ async function startPoolBootstrap(options) {
110887
+ let resolveRegistered;
110888
+ const registered = new Promise((resolve2) => resolveRegistered = resolve2);
110889
+ const existing = live(options.load());
110890
+ if (existing) resolveRegistered(existing);
110891
+ let registering;
110892
+ const status = () => {
110893
+ const current = live(options.load());
110894
+ return current ? { registered: true, computerId: current.computerId } : { registered: false };
110895
+ };
110896
+ const server = createServer3((req, res) => {
110897
+ void (async () => {
110898
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
110899
+ if (path === "/pool/status" && req.method === "GET") return send2(res, 200, status());
110900
+ if (path !== "/pool/register" || req.method !== "POST") return send2(res, 404, { error: "not found" });
110901
+ if (status().registered) return send2(res, 409, status());
110902
+ let token;
110903
+ let name;
110904
+ try {
110905
+ ;
110906
+ ({ token, name } = JSON.parse(await readBody2(req)));
110907
+ } catch {
110908
+ return send2(res, 400, { error: "invalid body" });
110693
110909
  }
110694
- );
110695
- }
110696
- const portal = spawnSync8("systemctl", ["--user", "is-active", "xdg-desktop-portal"], { encoding: "utf8" });
110697
- checks.push(
110698
- portal.stdout?.trim() === "active" ? { name: "portal", status: "ok", detail: "xdg-desktop-portal running (screen sharing, remote input)" } : {
110699
- name: "portal",
110700
- status: "fail",
110701
- detail: "xdg-desktop-portal is not running on this session",
110702
- fix: "install xdg-desktop-portal plus the desktop backend (xdg-desktop-portal-gnome / -kde)"
110703
- }
110704
- );
110705
- if (ctx.config.webrtc) {
110706
- const gi = spawnSync8("python3", ["-c", "import gi"], { stdio: "ignore" }).status === 0;
110707
- const missing = [
110708
- !gi && "python3-gi",
110709
- ...["pipewiresrc", "y4menc", "videorate"].filter(
110710
- (element) => spawnSync8("gst-inspect-1.0", [element], { stdio: "ignore" }).status !== 0
110711
- )
110712
- ].filter(Boolean);
110713
- checks.push(
110714
- missing.length === 0 ? { name: "pipewire", status: "ok", detail: "python3-gi and GStreamer PipeWire capture available" } : {
110715
- name: "pipewire",
110716
- status: "warn",
110717
- detail: `missing ${missing.join(", ")}: the /view page falls back to screenshots`,
110718
- fix: "install python3-gi gstreamer1.0-pipewire gstreamer1.0-plugins-good gstreamer1.0-plugins-base"
110910
+ if (typeof token !== "string" || !token || typeof name !== "string" || !name.trim())
110911
+ return send2(res, 400, { error: "token and name are required" });
110912
+ registering ??= options.register(token, name.trim().slice(0, 120)).finally(() => registering = void 0);
110913
+ try {
110914
+ const registration = await registering;
110915
+ options.log(`registered as managed computer ${registration.computerId}`);
110916
+ resolveRegistered(registration);
110917
+ return send2(res, 200, { registered: true, computerId: registration.computerId });
110918
+ } catch (error62) {
110919
+ options.log(`managed registration failed: ${error62.message}`);
110920
+ return send2(res, 502, { error: "registration failed" });
110719
110921
  }
110720
- );
110922
+ })().catch(() => {
110923
+ if (!res.headersSent) send2(res, 500, { error: "failed" });
110924
+ });
110925
+ });
110926
+ server.listen(options.port, options.host ?? "0.0.0.0");
110927
+ await once3(server, "listening");
110928
+ const address = server.address();
110929
+ if (!existing) options.log(`waiting for the pool to register this desktop (port ${address.port})`);
110930
+ return {
110931
+ registered,
110932
+ address,
110933
+ close: () => new Promise((resolve2) => {
110934
+ server.closeAllConnections();
110935
+ server.close(() => resolve2());
110936
+ })
110937
+ };
110938
+ }
110939
+
110940
+ // src/egress.ts
110941
+ import { request as httpRequest, createServer as createServer4 } from "node:http";
110942
+ import { request as httpsRequest } from "node:https";
110943
+ import { connect as netConnect, isIP as isIP4 } from "node:net";
110944
+ import { connect as tlsConnect } from "node:tls";
110945
+ var EGRESS_PORT_ENV = "AGENTCONNECT_EGRESS_PORT";
110946
+ var CONNECT_TIMEOUT_MS = 15e3;
110947
+ var MAX_PROXY_HEADER_BYTES = 16 * 1024;
110948
+ var HOP_BY_HOP = /* @__PURE__ */ new Set([
110949
+ "connection",
110950
+ "keep-alive",
110951
+ "proxy-authenticate",
110952
+ "proxy-authorization",
110953
+ "proxy-connection",
110954
+ "te",
110955
+ "trailer",
110956
+ "transfer-encoding",
110957
+ "upgrade"
110958
+ ]);
110959
+ function egressPort(env = process.env) {
110960
+ const raw = env[EGRESS_PORT_ENV]?.trim();
110961
+ if (!raw) return void 0;
110962
+ const port = Number(raw);
110963
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
110964
+ throw new Error(`${EGRESS_PORT_ENV} is not a valid port: ${raw}`);
110965
+ return port;
110966
+ }
110967
+ function connectTarget(authority) {
110968
+ const match = /^\[?([^\]]+?)\]?:(\d{1,5})$/.exec(authority ?? "");
110969
+ if (!match) return void 0;
110970
+ const port = Number(match[2]);
110971
+ return port > 0 && port <= 65535 ? { host: match[1], port } : void 0;
110972
+ }
110973
+ var basic = (egress) => egress.username !== void 0 || egress.password !== void 0 ? `Basic ${Buffer.from(`${egress.username ?? ""}:${egress.password ?? ""}`).toString("base64")}` : void 0;
110974
+ function forwardHeaders(headers) {
110975
+ const out = {};
110976
+ for (const [name, value] of Object.entries(headers)) {
110977
+ if (value !== void 0 && !HOP_BY_HOP.has(name.toLowerCase())) out[name] = value;
110721
110978
  }
110722
- return checks;
110979
+ return out;
110723
110980
  }
110724
- function ffmpegChecks(ctx, timeoutMs) {
110725
- if (!ctx.config.webrtc)
110726
- return [{ name: "webrtc viewer", status: "warn", detail: 'disabled in config ("webrtc": false)' }];
110727
- if (!ffmpegAvailable(ctx.ffmpeg)) {
110728
- return [
110729
- {
110730
- name: "ffmpeg",
110731
- status: "warn",
110732
- detail: "not found: the /view page falls back to screenshots",
110733
- fix: `run: ${selfCommand()} install-ffmpeg`
110981
+ var EgressForwarder = class {
110982
+ constructor(opts) {
110983
+ this.opts = opts;
110984
+ }
110985
+ opts;
110986
+ policy = { mode: "pending" };
110987
+ server;
110988
+ sockets = /* @__PURE__ */ new Set();
110989
+ get mode() {
110990
+ return this.policy.mode;
110991
+ }
110992
+ /** Apply the organization's egress; open connections keep the route they started on. */
110993
+ apply(policy) {
110994
+ const before = this.describe();
110995
+ this.policy = policy;
110996
+ const after = this.describe();
110997
+ if (after !== before) this.opts.log(`egress: ${after}`);
110998
+ }
110999
+ // Never the credentials: the proxy's origin is enough to tell which one is in use.
111000
+ describe() {
111001
+ if (this.policy.mode !== "proxy") return this.policy.mode;
111002
+ return `proxy ${new URL(this.policy.url).origin}`;
111003
+ }
111004
+ async start() {
111005
+ const server = createServer4((req, res) => this.onRequest(req, res));
111006
+ server.on("connect", (req, socket, head) => this.onConnect(req, socket, head));
111007
+ server.on("connection", (socket) => {
111008
+ this.sockets.add(socket);
111009
+ socket.once("close", () => this.sockets.delete(socket));
111010
+ });
111011
+ server.on("clientError", (_err, socket) => socket.destroy());
111012
+ await new Promise((resolve2, reject) => {
111013
+ server.once("error", reject);
111014
+ server.listen(this.opts.port, this.opts.host ?? "127.0.0.1", () => resolve2());
111015
+ });
111016
+ this.server = server;
111017
+ const address = server.address();
111018
+ return typeof address === "object" && address ? address.port : this.opts.port;
111019
+ }
111020
+ async stop() {
111021
+ for (const socket of this.sockets) socket.destroy();
111022
+ await new Promise((resolve2) => this.server ? this.server.close(() => resolve2()) : resolve2());
111023
+ this.server = void 0;
111024
+ }
111025
+ // A tunnel (HTTPS and WebSocket traffic): straight to the target, or a CONNECT through the organization's proxy.
111026
+ onConnect(req, client, head) {
111027
+ const policy = this.policy;
111028
+ const target = connectTarget(req.url);
111029
+ const refuse = (status) => {
111030
+ client.end(`HTTP/1.1 ${status}\r
111031
+ Connection: close\r
111032
+ Content-Length: 0\r
111033
+ \r
111034
+ `);
111035
+ };
111036
+ if (!target) return refuse("400 Bad Request");
111037
+ if (policy.mode === "pending") return refuse("503 Service Unavailable");
111038
+ client.on("error", () => {
111039
+ });
111040
+ const upstream = policy.mode === "direct" ? netConnect(target.port, target.host) : this.dialProxy(new URL(policy.url));
111041
+ let opened = false;
111042
+ upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error("timeout")));
111043
+ upstream.on("error", () => {
111044
+ if (opened) client.destroy();
111045
+ else if (!client.destroyed) refuse("502 Bad Gateway");
111046
+ });
111047
+ client.once("close", () => upstream.destroy());
111048
+ const open3 = (rest) => {
111049
+ opened = true;
111050
+ upstream.setTimeout(0);
111051
+ client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
111052
+ if (rest.length > 0) client.write(rest);
111053
+ if (head.length > 0) upstream.write(head);
111054
+ upstream.pipe(client);
111055
+ client.pipe(upstream);
111056
+ };
111057
+ if (policy.mode === "direct") {
111058
+ upstream.once("connect", () => open3(Buffer.alloc(0)));
111059
+ return;
111060
+ }
111061
+ const auth = basic(policy);
111062
+ const authority = target.host.includes(":") ? `[${target.host}]:${target.port}` : `${target.host}:${target.port}`;
111063
+ upstream.once(policy.url.startsWith("https:") ? "secureConnect" : "connect", () => {
111064
+ upstream.write(
111065
+ `CONNECT ${authority} HTTP/1.1\r
111066
+ Host: ${authority}\r
111067
+ ${auth ? `Proxy-Authorization: ${auth}\r
111068
+ ` : ""}\r
111069
+ `
111070
+ );
111071
+ });
111072
+ let buffered = Buffer.alloc(0);
111073
+ const onData = (chunk) => {
111074
+ buffered = Buffer.concat([buffered, chunk]);
111075
+ const end = buffered.indexOf("\r\n\r\n");
111076
+ if (end < 0) {
111077
+ if (buffered.length > MAX_PROXY_HEADER_BYTES) upstream.destroy(new Error("oversized proxy reply"));
111078
+ return;
110734
111079
  }
110735
- ];
110736
- }
110737
- if (waylandSession() && !existsSync5(screencastTokenPath(ctx.dir))) {
110738
- return [
110739
- { name: "ffmpeg", status: "ok", detail: ctx.ffmpeg },
110740
- {
110741
- name: "screen capture",
110742
- status: "warn",
110743
- detail: "screen sharing not approved yet (Wayland portal): /view falls back to screenshots",
110744
- fix: `run: ${selfCommand()} setup, then pick the screen and click Share`
111080
+ upstream.off("data", onData);
111081
+ const status = /^HTTP\/1\.[01] (\d{3})/.exec(buffered.subarray(0, end).toString("latin1"))?.[1];
111082
+ if (status !== "200") {
111083
+ upstream.destroy();
111084
+ return refuse(status === "407" ? "502 Bad Gateway (egress proxy refused the credentials)" : "502 Bad Gateway");
110745
111085
  }
110746
- ];
111086
+ open3(buffered.subarray(end + 4));
111087
+ };
111088
+ upstream.on("data", onData);
110747
111089
  }
110748
- const probe = probeCapture(ctx.ffmpeg, ctx.config.streamFps, timeoutMs, ctx.dir);
110749
- return [
110750
- { name: "ffmpeg", status: "ok", detail: ctx.ffmpeg },
110751
- probe.ok ? { name: "screen capture", status: "ok", detail: `ffmpeg ${probe.input} captures the display` } : {
110752
- name: "screen capture",
110753
- status: "fail",
110754
- detail: probe.error ?? "ffmpeg could not capture the display",
110755
- fix: process.platform === "darwin" ? "answer the macOS screen-capture prompt (setup triggers it), then Cmd+Q and reopen the terminal" : "check that a desktop is attached and unlocked"
111090
+ // A plain HTTP request in absolute form: fetched directly, or handed to the organization's proxy as is.
111091
+ onRequest(req, res) {
111092
+ const policy = this.policy;
111093
+ let target;
111094
+ try {
111095
+ target = new URL(req.url ?? "");
111096
+ } catch {
111097
+ res.writeHead(400).end();
111098
+ return;
110756
111099
  }
110757
- ];
110758
- }
110759
- function firewallCheck(config2) {
110760
- if (isLoopbackHost(config2.host)) {
110761
- return { name: "firewall", status: "info", detail: `listening on ${config2.host} only; no inbound rule needed` };
111100
+ if (target.protocol !== "http:") return void res.writeHead(400).end();
111101
+ if (policy.mode === "pending") return void res.writeHead(503).end("egress is not configured yet");
111102
+ const headers = forwardHeaders(req.headers);
111103
+ let upstream;
111104
+ if (policy.mode === "direct") {
111105
+ upstream = httpRequest({
111106
+ host: target.hostname,
111107
+ port: target.port || 80,
111108
+ method: req.method,
111109
+ path: `${target.pathname}${target.search}`,
111110
+ headers
111111
+ });
111112
+ } else {
111113
+ const proxy = new URL(policy.url);
111114
+ const auth = basic(policy);
111115
+ upstream = (proxy.protocol === "https:" ? httpsRequest : httpRequest)({
111116
+ host: proxy.hostname,
111117
+ port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
111118
+ method: req.method,
111119
+ path: target.href,
111120
+ headers: { ...headers, ...auth ? { "proxy-authorization": auth } : {} }
111121
+ });
111122
+ }
111123
+ upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error("timeout")));
111124
+ upstream.on("response", (answer) => {
111125
+ upstream.setTimeout(0);
111126
+ res.writeHead(answer.statusCode ?? 502, forwardHeaders(answer.headers));
111127
+ answer.pipe(res);
111128
+ });
111129
+ upstream.on("error", () => {
111130
+ if (!res.headersSent) res.writeHead(502).end();
111131
+ else res.destroy();
111132
+ });
111133
+ req.pipe(upstream);
110762
111134
  }
110763
- const state = firewallState(process.execPath);
110764
- if (!state) return { name: "firewall", status: "warn", detail: "could not read Windows Firewall rules" };
110765
- const fix = `run: ${selfCommand()} setup (asks for administrator approval once)`;
110766
- if (state.block.length > 0) {
110767
- return {
110768
- name: "firewall",
110769
- status: "fail",
110770
- detail: `inbound block rule(s) for ${process.execPath}: ${state.block.map((rule) => rule.name).join(", ")}`,
110771
- fix
110772
- };
111135
+ dialProxy(proxy) {
111136
+ const port = Number(proxy.port || (proxy.protocol === "https:" ? 443 : 80));
111137
+ return proxy.protocol === "https:" ? tlsConnect({ host: proxy.hostname, port, ...isIP4(proxy.hostname) ? {} : { servername: proxy.hostname } }) : netConnect(port, proxy.hostname);
110773
111138
  }
110774
- const uncovered = state.activeProfiles.filter(
110775
- (category) => !state.allow.some((rule) => profileCovered(rule.profile, category))
110776
- );
110777
- if (state.allow.length === 0 || uncovered.length > 0) {
110778
- return {
110779
- name: "firewall",
110780
- status: "warn",
110781
- detail: state.allow.length === 0 ? "no inbound allow rule for Node.js: remote MCP and WebRTC will be blocked or prompt" : `Node.js is not allowed on active ${uncovered.join("/")} network(s)`,
110782
- fix
110783
- };
111139
+ };
111140
+
111141
+ // src/public-address.ts
111142
+ import { lookup } from "node:dns/promises";
111143
+ import { isIP as isIP5 } from "node:net";
111144
+ function publicBaseUrl(config2) {
111145
+ if (config2.publicUrl) return config2.publicUrl.replace(/\/+$/, "");
111146
+ if (config2.rtcAddress) return `http://${urlHost(config2.rtcAddress)}:${config2.port}`;
111147
+ return void 0;
111148
+ }
111149
+ async function rtcAdvertiseAddress(config2, resolve2 = async (host) => (await lookup(host, { family: 4 })).address, log40 = () => void 0) {
111150
+ if (config2.rtcAddress) return config2.rtcAddress;
111151
+ if (!config2.publicUrl) return void 0;
111152
+ const host = new URL(config2.publicUrl).hostname.replace(/^\[(.*)\]$/, "$1");
111153
+ if (isIP5(host)) return host;
111154
+ try {
111155
+ return await resolve2(host);
111156
+ } catch (error62) {
111157
+ log40(`cannot resolve ${host} for WebRTC (${error62.message}); set RTC_ADDRESS to the public IP`);
111158
+ return void 0;
110784
111159
  }
110785
- return {
110786
- name: "firewall",
110787
- status: "ok",
110788
- detail: `Node.js allowed inbound (${state.allow.map((rule) => rule.profile).join(", ")})`
110789
- };
110790
111160
  }
110791
- async function daemonCheck(config2) {
110792
- const running = await fetch(`${controlBaseUrl(config2)}/healthz`, { signal: AbortSignal.timeout(2e3) }).then((response) => response.ok).catch(() => false);
111161
+
111162
+ // src/doctor-schedule.ts
111163
+ function scheduleDoctor(options) {
111164
+ let timer;
111165
+ let stopped = false;
111166
+ const runOnce = async () => {
111167
+ if (stopped) return;
111168
+ try {
111169
+ await options.run();
111170
+ } catch (error62) {
111171
+ options.onError(error62);
111172
+ }
111173
+ if (timer) clearTimeout(timer);
111174
+ if (stopped) return;
111175
+ timer = setTimeout(() => enqueue(), options.intervalMs);
111176
+ timer.unref();
111177
+ };
111178
+ let runs = runOnce();
111179
+ const enqueue = () => {
111180
+ runs = runs.then(runOnce);
111181
+ };
110793
111182
  return {
110794
- name: "daemon",
110795
- status: running ? "ok" : "info",
110796
- detail: running ? `running on port ${config2.port}` : `not running (start it with: ${selfCommand()} run; listens on ${config2.host}:${config2.port})`
111183
+ refresh: enqueue,
111184
+ stop() {
111185
+ stopped = true;
111186
+ if (timer) clearTimeout(timer);
111187
+ }
110797
111188
  };
110798
111189
  }
110799
- async function setupPermissions(ctx) {
110800
- if (process.platform === "darwin") return setupMac(ctx);
110801
- if (process.platform === "win32") return setupWindowsFirewall(ctx);
110802
- if (process.platform === "linux") return setupLinux(ctx);
111190
+
111191
+ // src/service-linux.ts
111192
+ import { execFile as execFile2, spawnSync as spawnSync9 } from "node:child_process";
111193
+ import { copyFileSync, mkdirSync as mkdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync10 } from "node:fs";
111194
+ import { homedir as homedir4 } from "node:os";
111195
+ import { join as join12 } from "node:path";
111196
+ var UNIT = "agentconnect-computer.service";
111197
+ var unitPath = () => join12(process.env.XDG_CONFIG_HOME ?? join12(homedir4(), ".config"), "systemd", "user", UNIT);
111198
+ var SESSION_VARS = [
111199
+ "DISPLAY",
111200
+ "XAUTHORITY",
111201
+ "WAYLAND_DISPLAY",
111202
+ "XDG_SESSION_TYPE",
111203
+ "XDG_CURRENT_DESKTOP",
111204
+ "XDG_RUNTIME_DIR",
111205
+ "DBUS_SESSION_BUS_ADDRESS"
111206
+ ];
111207
+ var SESSION_ENV = "AGENTCONNECT_COMPUTER_SESSION";
111208
+ var SESSION_DISPLAY_VARS = ["DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY", SESSION_ENV];
111209
+ var EXIT_NEW_SESSION = 75;
111210
+ var autostartPath = () => join12(process.env.XDG_CONFIG_HOME ?? join12(homedir4(), ".config"), "autostart", "agentconnect-computer.desktop");
111211
+ function systemctl(...args) {
111212
+ const result = spawnSync9("systemctl", ["--user", ...args], { encoding: "utf8" });
111213
+ return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };
110803
111214
  }
110804
- async function setupLinux(ctx) {
110805
- if (!waylandSession()) {
110806
- ctx.log(
110807
- process.env.DISPLAY ? "X11 session: no approvals needed." : "No graphical session here: nothing to approve."
110808
- );
110809
- return;
110810
- }
110811
- if (gnomeWayland()) {
110812
- const state = gnomeHelperState();
110813
- if (state === "missing") {
110814
- const installer = join11(dirname2(ctx.driverCommand), "wayland-helper", "install.sh");
110815
- const result = spawnSync8(installer, [], { encoding: "utf8" });
110816
- ctx.log(
110817
- result.status === 0 ? `Installed the ${GNOME_HELPER} GNOME extension.` : `Extension install failed: ${result.stderr}`
110818
- );
110819
- }
110820
- if (state !== "active") ctx.log("GNOME loads extensions at login: log out and back in once, then run setup again.");
110821
- }
110822
- if (ctx.config.webrtc && ffmpegAvailable(ctx.ffmpeg)) {
110823
- ctx.log("Approve screen sharing on this screen: pick the monitor, then click Share (asked once).");
110824
- const probe = probeCapture(ctx.ffmpeg, ctx.config.streamFps, 18e4, ctx.dir);
110825
- ctx.log(
110826
- probe.ok ? "Screen sharing approved; the WebRTC viewer can stream." : `Screen sharing failed: ${probe.error}`
110827
- );
110828
- }
110829
- ctx.log('Approve remote input on this screen: allow "remote interaction" when GNOME asks (asked once).');
110830
- const driver = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: 18e4 });
110831
- try {
110832
- await driver.call("press_key", { scope: "desktop", key: "shift" });
110833
- ctx.log("Remote input works.");
110834
- } catch (error62) {
110835
- ctx.log(`Remote input not available yet: ${error62.message.slice(0, 200)}`);
110836
- } finally {
110837
- await driver.close();
110838
- }
111215
+ var quote = (value) => `"${value.replace(/(["\\])/g, "\\$1")}"`;
111216
+ function unitFile(node2, script) {
111217
+ return `[Unit]
111218
+ Description=AgentConnect Computer (computer-use daemon)
111219
+ PartOf=graphical-session.target
111220
+ After=graphical-session.target
111221
+ StartLimitIntervalSec=120
111222
+ StartLimitBurst=5
111223
+
111224
+ [Service]
111225
+ ExecCondition=/bin/sh -c 'test -n "$DISPLAY$WAYLAND_DISPLAY"'
111226
+ ExecStart=${quote(node2)} ${quote(script)} run
111227
+ Restart=on-failure
111228
+ RestartSec=3
111229
+
111230
+ [Install]
111231
+ WantedBy=graphical-session.target
111232
+ `;
110839
111233
  }
110840
- async function setupMac(ctx) {
110841
- if (overSsh()) {
110842
- ctx.log(`macOS permissions cannot be granted over SSH: run \`${selfCommand()} setup\` in Terminal on the Mac.`);
110843
- return;
111234
+ function autostartEntry() {
111235
+ const steps = [
111236
+ `systemctl --user import-environment ${SESSION_VARS.join(" ")}`,
111237
+ `systemctl --user set-environment ${SESSION_ENV}=$XDG_SESSION_ID`,
111238
+ `systemctl --user reset-failed ${UNIT}`,
111239
+ `systemctl --user start ${UNIT}`
111240
+ ];
111241
+ return `[Desktop Entry]
111242
+ Type=Application
111243
+ Name=AgentConnect Computer
111244
+ Comment=Starts the AgentConnect Computer service in this desktop session
111245
+ Exec=sh -c '${steps.join("; ")}'
111246
+ NoDisplay=true
111247
+ X-GNOME-Autostart-enabled=true
111248
+ `;
111249
+ }
111250
+ function installService2(dataDir2, script, managed = false) {
111251
+ let target = script;
111252
+ if (!managed) {
111253
+ const app = join12(dataDir2, "app");
111254
+ mkdirSync8(app, { recursive: true });
111255
+ target = join12(app, "agentconnect-computer.mjs");
111256
+ if (script !== target) copyFileSync(script, target);
110844
111257
  }
110845
- const app = hostApp();
110846
- ctx.log(
110847
- `macOS grants these permissions to ${app}, which runs this command; \`agentconnect computer install\` installs the AgentConnect Computer app to hold them instead.`
110848
- );
110849
- const driver = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: 18e4 });
110850
- try {
110851
- let state = await macPermissions(driver);
110852
- if (state.accessibility && state.screenRecording) {
110853
- ctx.log(`macOS permissions already granted to ${app}.`);
110854
- } else {
110855
- ctx.log(`Requesting Accessibility and Screen Recording for ${app}: answer the macOS dialogs.`);
110856
- state = await macPermissions(driver, true).catch(() => state);
110857
- if (!state.accessibility) open2(MAC_PANES.accessibility);
110858
- else if (!state.screenRecording) open2(MAC_PANES.screenRecording);
110859
- state = await waitForGrants(ctx, app, state);
110860
- }
110861
- if (ctx.config.webrtc && ffmpegAvailable(ctx.ffmpeg) && state.screenRecording) {
110862
- ctx.log("Testing ffmpeg screen capture: if macOS asks to let the app bypass the window picker, click Allow.");
110863
- const probe = probeCapture(ctx.ffmpeg, ctx.config.streamFps, 12e4, ctx.dir);
110864
- ctx.log(probe.ok ? "ffmpeg screen capture works." : `ffmpeg screen capture failed: ${probe.error}`);
110865
- }
110866
- if (!state.screenRecording || !state.accessibility) {
110867
- ctx.log(`After switching the permissions on, quit ${app} (Cmd+Q), reopen it and run: ${selfCommand()} doctor`);
110868
- }
110869
- } finally {
110870
- await driver.close();
111258
+ mkdirSync8(join12(unitPath(), ".."), { recursive: true });
111259
+ writeFileSync10(unitPath(), unitFile(process.execPath, target));
111260
+ mkdirSync8(join12(autostartPath(), ".."), { recursive: true });
111261
+ writeFileSync10(autostartPath(), autostartEntry());
111262
+ systemctl("daemon-reload");
111263
+ const enabled = systemctl("enable", UNIT);
111264
+ if (!enabled.ok) throw new Error(`systemctl --user enable failed: ${enabled.output}`);
111265
+ if (inGraphicalSession()) {
111266
+ systemctl("import-environment", ...SESSION_VARS.filter((name) => process.env[name]));
111267
+ const session = process.env.XDG_SESSION_ID;
111268
+ if (session && graphicalSessionSync(session)) systemctl("set-environment", `${SESSION_ENV}=${session}`);
111269
+ else systemctl("unset-environment", SESSION_ENV);
111270
+ systemctl("reset-failed", UNIT);
111271
+ systemctl("restart", UNIT);
110871
111272
  }
110872
111273
  }
110873
- async function waitForGrants(ctx, app, initial) {
110874
- let state = initial;
110875
- const interactive = process.stdin.isTTY;
110876
- ctx.log(
110877
- `Waiting for: ${[!state.accessibility && "Accessibility", !state.screenRecording && "Screen Recording"].filter(Boolean).join(", ")}` + (interactive ? " (press Enter to stop waiting)" : "")
110878
- );
110879
- let skipped = false;
110880
- const rl = interactive ? createInterface({ input: process.stdin }) : void 0;
110881
- rl?.once("line", () => skipped = true);
110882
- const deadline = Date.now() + 10 * 6e4;
110883
- let openedScreenPane = state.accessibility;
110884
- try {
110885
- while (!skipped && Date.now() < deadline && !(state.accessibility && state.screenRecording)) {
110886
- await new Promise((resolve2) => setTimeout(resolve2, 2e3));
110887
- const probe = new CuaDriver({ command: ctx.driverCommand, callTimeoutMs: 2e4 });
110888
- const next = await macPermissions(probe).catch(() => state).finally(() => probe.close());
110889
- if (next.accessibility && !state.accessibility) ctx.log(`Accessibility granted to ${app}.`);
110890
- if (next.screenRecording && !state.screenRecording) ctx.log(`Screen Recording granted to ${app}.`);
110891
- state = next;
110892
- if (state.accessibility && !state.screenRecording && !openedScreenPane) {
110893
- openedScreenPane = true;
110894
- open2(MAC_PANES.screenRecording);
110895
- ctx.log(`Now switch on Screen & System Audio Recording for ${app}; it takes effect after reopening ${app}.`);
110896
- }
110897
- }
110898
- } finally {
110899
- rl?.close();
110900
- }
110901
- return state;
111274
+ var GRAPHICAL_TYPES = /* @__PURE__ */ new Set(["x11", "wayland", "mir"]);
111275
+ function graphicalSessionSync(id) {
111276
+ const type = spawnSync9("loginctl", ["show-session", id, "-p", "Type", "--value"], { encoding: "utf8" });
111277
+ return type.status === 0 && GRAPHICAL_TYPES.has(type.stdout.trim());
110902
111278
  }
110903
- function open2(url2) {
110904
- spawn5("open", [url2], { stdio: "ignore", detached: true }).unref();
111279
+ var inGraphicalSession = (env = process.env) => Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
111280
+ function startService2() {
111281
+ const result = systemctl("start", UNIT);
111282
+ if (!result.ok) throw new Error(`systemctl --user start failed: ${result.output}`);
110905
111283
  }
110906
- function setupWindowsFirewall(ctx) {
110907
- if (isLoopbackHost(ctx.config.host)) {
110908
- ctx.log(`Listening on ${ctx.config.host} only, so no Windows Firewall rule is needed.`);
110909
- return;
110910
- }
110911
- const program = process.execPath;
110912
- const state = firewallState(program);
110913
- const uncovered = state?.activeProfiles.filter(
110914
- (category) => !state.allow.some((rule) => profileCovered(rule.profile, category))
111284
+ function stopService2() {
111285
+ systemctl("stop", UNIT);
111286
+ }
111287
+ function restartService2() {
111288
+ const result = systemctl("restart", UNIT);
111289
+ if (!result.ok) throw new Error(`systemctl --user restart failed: ${result.output}`);
111290
+ }
111291
+ function uninstallService2() {
111292
+ systemctl("disable", "--now", UNIT);
111293
+ rmSync7(unitPath(), { force: true });
111294
+ rmSync7(autostartPath(), { force: true });
111295
+ systemctl("daemon-reload");
111296
+ }
111297
+ function serviceStatus2() {
111298
+ const show = systemctl("show", UNIT, "-p", "LoadState", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID");
111299
+ const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(show.output)?.[1];
111300
+ const pid = Number(field("MainPID"));
111301
+ return {
111302
+ installed: field("LoadState") === "loaded",
111303
+ loaded: field("ActiveState") === "active",
111304
+ ...pid ? { pid } : {},
111305
+ state: `${field("ActiveState")}/${field("SubState")}`
111306
+ };
111307
+ }
111308
+ var run = (command, args) => new Promise((resolve2) => {
111309
+ execFile2(
111310
+ command,
111311
+ args,
111312
+ { encoding: "utf8", timeout: 1e4 },
111313
+ (error62, stdout, stderr) => resolve2({
111314
+ ok: !error62,
111315
+ exited: Boolean(error62) && typeof error62?.code === "number" && !error62.killed,
111316
+ stdout: stdout ?? "",
111317
+ stderr: stderr ?? ""
111318
+ })
110915
111319
  );
110916
- if (state && state.block.length === 0 && state.allow.length > 0 && uncovered?.length === 0) {
110917
- ctx.log("Windows Firewall already allows Node.js inbound.");
110918
- return;
111320
+ });
111321
+ var environmentValue = (output2, name) => new RegExp(`^${name}=(.*)$`, "m").exec(output2)?.[1]?.trim() || void 0;
111322
+ var GONE = /no session|not known|does not exist/i;
111323
+ async function sessionProperty(id, property, exec = run) {
111324
+ const result = await exec("loginctl", ["show-session", id, "-p", property, "--value"]);
111325
+ if (result.ok) return result.stdout.trim() || void 0;
111326
+ return result.exited && GONE.test(result.stderr) ? null : void 0;
111327
+ }
111328
+ var logindProbe = {
111329
+ async graphical(id) {
111330
+ const type = await sessionProperty(id, "Type");
111331
+ return type == null ? type : GRAPHICAL_TYPES.has(type);
111332
+ },
111333
+ async live(id) {
111334
+ const state = await sessionProperty(id, "State");
111335
+ return state === void 0 ? void 0 : state !== null && state !== "closing";
111336
+ },
111337
+ async managerSession() {
111338
+ const env = await run("systemctl", ["--user", "show-environment"]);
111339
+ return env.ok ? environmentValue(env.stdout, SESSION_ENV) : void 0;
111340
+ },
111341
+ async forget(id) {
111342
+ if (await this.managerSession() !== id) return;
111343
+ await run("systemctl", ["--user", "unset-environment", ...SESSION_DISPLAY_VARS]);
110919
111344
  }
110920
- ctx.log(`Adding a Windows Firewall rule "${FIREWALL_RULE}" for ${program} (approve the administrator prompt).`);
110921
- const elevated = `$p = ${psQuote(program)}
110922
- Get-NetFirewallRule -DisplayName ${psQuote(FIREWALL_RULE)} -ErrorAction SilentlyContinue | Remove-NetFirewallRule
110923
- Get-NetFirewallApplicationFilter | Where-Object { [Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p } | Get-NetFirewallRule | Where-Object { "$($_.Action)" -eq 'Block' -and "$($_.Direction)" -eq 'Inbound' } | Disable-NetFirewallRule
110924
- New-NetFirewallRule -DisplayName ${psQuote(FIREWALL_RULE)} -Direction Inbound -Program $p -Action Allow -Profile Any | Out-Null`;
110925
- const encoded = Buffer.from(elevated, "utf16le").toString("base64");
110926
- const result = powershell(
110927
- `Start-Process powershell.exe -Verb RunAs -Wait -WindowStyle Hidden -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand','${encoded}'`,
110928
- 18e4
110929
- );
110930
- ctx.log(
110931
- result.ok ? "Firewall rule added; any Node.js block rules were disabled." : "Firewall rule not added (administrator prompt declined?); Windows will ask on first connection instead."
110932
- );
111345
+ };
111346
+ var UNKNOWN_LIMIT = 3;
111347
+ function watchSession(options) {
111348
+ const probe = options.probe ?? logindProbe;
111349
+ let stopped = false;
111350
+ let busy = false;
111351
+ let checked = false;
111352
+ let unknown2 = 0;
111353
+ const tick = async () => {
111354
+ if (stopped || busy) return;
111355
+ busy = true;
111356
+ try {
111357
+ if (!checked) {
111358
+ const graphical = await probe.graphical(options.session);
111359
+ if (graphical === void 0) return;
111360
+ checked = true;
111361
+ if (graphical === null) return await end();
111362
+ if (!graphical) {
111363
+ stop();
111364
+ options.onIgnored?.(`session ${options.session} is not a graphical session; not following it`);
111365
+ return;
111366
+ }
111367
+ }
111368
+ const live2 = await probe.live(options.session);
111369
+ if (live2 === true) unknown2 = 0;
111370
+ if (live2 === true || live2 === void 0 && ++unknown2 < UNKNOWN_LIMIT) return;
111371
+ await end();
111372
+ } finally {
111373
+ busy = false;
111374
+ }
111375
+ };
111376
+ const end = async () => {
111377
+ const next = await probe.managerSession();
111378
+ if (next && next !== options.session && await probe.live(next) === true) {
111379
+ stop();
111380
+ options.onEnded(EXIT_NEW_SESSION, `desktop session ${options.session} ended; restarting in session ${next}`);
111381
+ return;
111382
+ }
111383
+ await probe.forget(options.session);
111384
+ stop();
111385
+ options.onEnded(0, `desktop session ${options.session} ended`);
111386
+ };
111387
+ const timer = setInterval(() => void tick(), options.intervalMs ?? 5e3);
111388
+ timer.unref();
111389
+ const stop = () => {
111390
+ stopped = true;
111391
+ clearInterval(timer);
111392
+ };
111393
+ return stop;
110933
111394
  }
110934
111395
 
110935
111396
  // src/cli.ts
@@ -111117,8 +111578,8 @@ function printClientSetup(config2, client, token, tokenFile) {
111117
111578
  const base = publicBaseUrl(config2) ?? `http://${host}:${config2.port}`;
111118
111579
  let shown = token;
111119
111580
  if (tokenFile) {
111120
- rmSync7(tokenFile, { force: true });
111121
- writeFileSync10(tokenFile, `${token}
111581
+ rmSync8(tokenFile, { force: true });
111582
+ writeFileSync11(tokenFile, `${token}
111122
111583
  `, { mode: 384, flag: "wx" });
111123
111584
  shown = "<token>";
111124
111585
  console.log(`
@@ -111176,7 +111637,7 @@ function buildComputer(dir, config2, onStatus, refusal, report, screenshots, nam
111176
111637
  const computer = new Computer({
111177
111638
  driver,
111178
111639
  config: config2,
111179
- audit: auditSinks(fileAuditSink(join12(dir, "audit.log")), ...report ? [report] : []),
111640
+ audit: auditSinks(fileAuditSink(join13(dir, "audit.log")), ...report ? [report] : []),
111180
111641
  log: log39,
111181
111642
  ...onStatus ? { onStatus } : {},
111182
111643
  ...refusal ? { refusal } : {},
@@ -111400,9 +111861,9 @@ async function run2(dir, initial, clientName) {
111400
111861
  const issued = issueClientToken(config2, clientName);
111401
111862
  config2 = issued.config;
111402
111863
  saveConfig(config2, dir);
111403
- printClientSetup(config2, clientName, issued.token, process.stdout.isTTY ? void 0 : join12(dir, "client-token"));
111864
+ printClientSetup(config2, clientName, issued.token, process.stdout.isTTY ? void 0 : join13(dir, "client-token"));
111404
111865
  }
111405
- if (!config2.driverPath && !existsSync6(installedDriverPath(dir))) await installDriver(dir);
111866
+ if (!config2.driverPath && !existsSync8(installedDriverPath(dir))) await installDriver(dir);
111406
111867
  const setTitle = (status) => {
111407
111868
  process.title = `AgentConnect Computer \u2014 ${status}`;
111408
111869
  };
@@ -111460,6 +111921,13 @@ async function run2(dir, initial, clientName) {
111460
111921
  if (state && (!state.accessibility || !state.screenRecording)) {
111461
111922
  void runSelf(["permissions", "--json", "--prompt"], 2e5).catch(() => void 0);
111462
111923
  }
111924
+ if (state && !state.accessibility) {
111925
+ live2.accessibility = watchAccessibility({
111926
+ check: async () => JSON.parse(await runSelf(["permissions", "--json"], 6e4)).accessibility === true,
111927
+ restartDriver: () => driver.close(),
111928
+ log: log39
111929
+ });
111930
+ }
111463
111931
  }
111464
111932
  const releaseDisplay = config2.keepAwake ? keepDisplayAwake(log39) : () => void 0;
111465
111933
  const driverTools = await loadDriverTools(driver, config2);
@@ -111479,6 +111947,25 @@ async function run2(dir, initial, clientName) {
111479
111947
  refusal: () => authority.refusal(),
111480
111948
  stopHotkey: config2.stopHotkey,
111481
111949
  headless: sessionKind() === "xvfb",
111950
+ ...process.platform === "darwin" ? {
111951
+ menuBar: {
111952
+ helper: menuBarHelperPath(),
111953
+ host: macMenuBarHost({
111954
+ dir,
111955
+ ffmpegPath: config2.ffmpegPath,
111956
+ appPath: appBundlePath(),
111957
+ driver,
111958
+ name: () => computer.info().name,
111959
+ registration,
111960
+ client: () => live2.channel?.client,
111961
+ // A non-zero exit makes launchd's KeepAlive start the daemon again; zero leaves it stopped.
111962
+ shutdown: (code) => void shutdown(code),
111963
+ onFfmpegInstalled: () => live2.channel?.refreshDoctor(),
111964
+ accessibilityGranted: () => live2.accessibility?.now() ?? Promise.resolve(false),
111965
+ log: log39
111966
+ })
111967
+ }
111968
+ } : {},
111482
111969
  log: log39
111483
111970
  });
111484
111971
  const createMcpServer = ({ client, viewOnly, agent }) => createComputerMcpServer({ computer, client, driverTools, viewOnly, ...agent ? { agent } : {} });
@@ -111536,6 +112023,7 @@ async function run2(dir, initial, clientName) {
111536
112023
  await auditReport?.flush();
111537
112024
  live2.channel?.stop();
111538
112025
  live2.local?.close();
112026
+ live2.accessibility?.stop();
111539
112027
  authority.close();
111540
112028
  releaseDisplay();
111541
112029
  await Promise.allSettled([server.close(), driver.close(), egress?.stop()]);
@@ -111597,7 +112085,7 @@ async function waitForDaemon(config2, timeoutMs) {
111597
112085
  var macServiceProgram = () => [process.execPath, serviceEntry()];
111598
112086
  async function setupMacApp(dir, config2) {
111599
112087
  const app = basename2(appBundlePath());
111600
- if (!installService2(macServiceProgram(), join12(dir, "daemon.log"))) {
112088
+ if (!installService(macServiceProgram(), join13(dir, "daemon.log"))) {
111601
112089
  throw new Error(
111602
112090
  `installed LaunchAgent ${plistPath()}, but nobody is logged in to this Mac's desktop: log in (in person or through Screen Sharing) to answer the permission prompts, then run: ${selfCommand()} setup`
111603
112091
  );
@@ -111605,7 +112093,7 @@ async function setupMacApp(dir, config2) {
111605
112093
  console.log(`Installed LaunchAgent ${plistPath()} and started ${app}.`);
111606
112094
  if (overSsh()) console.log(`The permission prompts appear on the Mac's own screen; answer them there.`);
111607
112095
  if (!await waitForDaemon(config2, 6e4))
111608
- throw new Error(`the service did not come up; see ${join12(dir, "daemon.log")}`);
112096
+ throw new Error(`the service did not come up; see ${join13(dir, "daemon.log")}`);
111609
112097
  const grants = async (prompt) => await (await controlFetch(config2, `/control/permissions${prompt ? "?prompt=1" : ""}`, 21e4)).json();
111610
112098
  let state = await grants(false);
111611
112099
  const initiallyMissingScreen = !state.screenRecording;
@@ -111619,7 +112107,7 @@ async function setupMacApp(dir, config2) {
111619
112107
  const interactive = process.stdin.isTTY;
111620
112108
  if (interactive) console.log("Waiting for the grants (press Enter to stop waiting)...");
111621
112109
  let skipped = false;
111622
- const rl = interactive ? createInterface2({ input: process.stdin }) : void 0;
112110
+ const rl = interactive ? createInterface3({ input: process.stdin }) : void 0;
111623
112111
  rl?.once("line", () => skipped = true);
111624
112112
  const deadline = Date.now() + 10 * 6e4;
111625
112113
  let screenPaneOpened = state.accessibility;
@@ -111629,7 +112117,7 @@ async function setupMacApp(dir, config2) {
111629
112117
  await new Promise((resolve2) => setTimeout(resolve2, 2e3));
111630
112118
  if (state.accessibility && Date.now() - lastRestart > 2e4) {
111631
112119
  lastRestart = Date.now();
111632
- restartService2();
112120
+ restartService();
111633
112121
  await waitForDaemon(config2, 6e4);
111634
112122
  }
111635
112123
  const next = await grants(false).catch(() => state);
@@ -111648,7 +112136,7 @@ async function setupMacApp(dir, config2) {
111648
112136
  }
111649
112137
  if (initiallyMissingScreen && state.screenRecording) {
111650
112138
  console.log(`Restarting ${app} so the Screen Recording grant takes effect...`);
111651
- restartService2();
112139
+ restartService();
111652
112140
  await waitForDaemon(config2, 6e4);
111653
112141
  }
111654
112142
  console.log(`Checking from inside ${app} (if macOS asks to let it bypass the window picker, click Allow):`);
@@ -111661,32 +112149,32 @@ function serviceCommand(dir, config2, action) {
111661
112149
  if (!appBundlePath())
111662
112150
  throw new Error("run this from the AgentConnect Computer.app binary (\u2026/Contents/MacOS/agentconnect-computer)");
111663
112151
  }
111664
- if (action === "install") installService2(macServiceProgram(), join12(dir, "daemon.log"));
111665
- else if (action === "uninstall") uninstallService2();
111666
- else if (action === "start") startService2();
111667
- else if (action === "stop") stopService2();
111668
- else if (action === "restart") restartService2();
112152
+ if (action === "install") installService(macServiceProgram(), join13(dir, "daemon.log"));
112153
+ else if (action === "uninstall") uninstallService();
112154
+ else if (action === "start") startService();
112155
+ else if (action === "stop") stopService();
112156
+ else if (action === "restart") restartService();
111669
112157
  else if (action !== "status") throw new Error("usage: service install | uninstall | start | stop | restart | status");
111670
- const status = serviceStatus2();
112158
+ const status = serviceStatus();
111671
112159
  console.log(
111672
112160
  JSON.stringify(
111673
- { ...status, plist: plistPath(), log: join12(dir, "daemon.log"), port: config2.port, app: hostApp() },
112161
+ { ...status, plist: plistPath(), log: join13(dir, "daemon.log"), port: config2.port, app: hostApp() },
111674
112162
  null,
111675
112163
  2
111676
112164
  )
111677
112165
  );
111678
112166
  }
111679
112167
  function linuxServiceCommand(dir, config2, action) {
111680
- if (action === "install") installService(dir, serviceEntry(), Boolean(managedEntry()));
111681
- else if (action === "uninstall") uninstallService();
111682
- else if (action === "start") startService();
111683
- else if (action === "stop") stopService();
111684
- else if (action === "restart") restartService();
112168
+ if (action === "install") installService2(dir, serviceEntry(), Boolean(managedEntry()));
112169
+ else if (action === "uninstall") uninstallService2();
112170
+ else if (action === "start") startService2();
112171
+ else if (action === "stop") stopService2();
112172
+ else if (action === "restart") restartService2();
111685
112173
  else if (action !== "status") throw new Error("usage: service install | uninstall | start | stop | restart | status");
111686
112174
  console.log(
111687
112175
  JSON.stringify(
111688
112176
  {
111689
- ...serviceStatus(),
112177
+ ...serviceStatus2(),
111690
112178
  unit: unitPath(),
111691
112179
  log: `journalctl --user -u ${UNIT}`,
111692
112180
  port: config2.port
@@ -111698,11 +112186,11 @@ function linuxServiceCommand(dir, config2, action) {
111698
112186
  }
111699
112187
  async function setupLinuxService(dir, config2) {
111700
112188
  const running = await waitForDaemon(config2, 1e3);
111701
- if (running && !serviceStatus().loaded) {
112189
+ if (running && !serviceStatus2().loaded) {
111702
112190
  console.log(`A daemon started by hand is already on port ${config2.port}; stop it so the service can take over.`);
111703
112191
  return void 0;
111704
112192
  }
111705
- installService(dir, serviceEntry(), Boolean(managedEntry()));
112193
+ installService2(dir, serviceEntry(), Boolean(managedEntry()));
111706
112194
  console.log(`Installed and started the systemd user service ${unitPath()}.`);
111707
112195
  if (!await waitForDaemon(config2, 6e4)) {
111708
112196
  console.log(`The service did not come up; see: journalctl --user -u ${UNIT}`);
@@ -111737,7 +112225,7 @@ async function setup(dir, initial, clientName, withService) {
111737
112225
  if (process.platform === "darwin" && appBundlePath()) {
111738
112226
  checks = await setupMacApp(dir, config2);
111739
112227
  } else if (process.platform === "linux" && withService && !inGraphicalSession()) {
111740
- installService(dir, serviceEntry(), Boolean(managedEntry()));
112228
+ installService2(dir, serviceEntry(), Boolean(managedEntry()));
111741
112229
  console.log(`Installed the systemd user service ${unitPath()}.`);
111742
112230
  console.log("No graphical session in this shell: the service starts when you next log in to the desktop.");
111743
112231
  console.log(`Then check it there with: ${selfCommand()} doctor`);
@@ -111751,7 +112239,7 @@ async function setup(dir, initial, clientName, withService) {
111751
112239
  }
111752
112240
  const ok = printChecks(checks);
111753
112241
  if (token && clientName) printClientSetup(config2, clientName, token);
111754
- const serviceRunning = process.platform === "darwin" ? serviceStatus2().loaded : process.platform === "linux" && serviceStatus().loaded;
112242
+ const serviceRunning = process.platform === "darwin" ? serviceStatus().loaded : process.platform === "linux" && serviceStatus2().loaded;
111755
112243
  console.log(
111756
112244
  !ok ? `Fix the failed checks, then run: ${selfCommand()} doctor` : withService && serviceRunning ? `The daemon runs as a background service: ${selfCommand()}${managedEntry() ? "" : " service"} status | restart | stop` : `Start the daemon with: ${selfCommand()} run`
111757
112245
  );