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

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