conbridge-agent 0.5.0 → 0.6.0

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.
@@ -29,76 +29,16 @@ __export(cli_exports, {
29
29
  module.exports = __toCommonJS(cli_exports);
30
30
 
31
31
  // <define:__CONBRIDGE_BUILD__>
32
- var define_CONBRIDGE_BUILD_default = { version: "0.5.0", commit: "198044ecd375", built_at: "2026-11-06T04:45:37.003Z", keychain_helper_sha256: "8f0004be35342bf004727258856fc17ed9ca6ea0014cd768b94b6060ae752b1f", distribution: "npm" };
32
+ var define_CONBRIDGE_BUILD_default = { version: "0.6.0", commit: "69f9aa0c007a", built_at: "2026-11-09T10:50:53.899Z", keychain_helper_sha256: "0a2d65388c0acc75305386ce0d6b7ee2e522ed939f291eb5a50055197674c023", distribution: "npm" };
33
33
 
34
34
  // dist/cli.js
35
- var import_node_child_process10 = require("node:child_process");
36
- var import_node_crypto11 = require("node:crypto");
37
- var import_node_fs4 = require("node:fs");
38
- var import_promises15 = require("node:fs/promises");
39
- var import_node_os8 = require("node:os");
40
- var import_node_path17 = require("node:path");
41
- var import_node_url3 = require("node:url");
42
- var import_node_util2 = require("node:util");
43
-
44
- // dist/confirm.js
45
- var import_node_child_process = require("node:child_process");
46
- var import_node_path = require("node:path");
47
- var CONFIRM_TIMEOUT_MS = 13e4;
48
- function confirmText(request) {
49
- const verb = request.created ? "create" : "overwrite";
50
- return `ConBridge wants to ${verb} "${request.path}" in root "${request.rootLabel}" (${request.bytes} bytes). This write was approved in the Console.`.replace(/[\r\n]+/g, " ");
51
- }
52
- function appleScriptString(value) {
53
- return '"' + value.replace(/[\\"]/g, "\\$&").replace(/[\r\n]+/g, " ") + '"';
54
- }
55
- function buildConfirmScript(request) {
56
- return `display dialog ${appleScriptString(confirmText(request))} with title "ConBridge" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" with icon caution giving up after 120`;
57
- }
58
- var macDialogConfirm = (request) => {
59
- if (process.platform !== "darwin")
60
- return Promise.resolve(false);
61
- return new Promise((resolve8) => {
62
- (0, import_node_child_process.execFile)("/usr/bin/osascript", ["-e", buildConfirmScript(request)], { timeout: CONFIRM_TIMEOUT_MS }, (error63, stdout) => {
63
- if (error63)
64
- return resolve8(false);
65
- resolve8(/button returned:Allow/.test(stdout) && !/gave up:true/.test(stdout));
66
- });
67
- });
68
- };
69
- var WINDOWS_CONFIRM_SCRIPT = [
70
- "Add-Type -AssemblyName PresentationFramework",
71
- '$r = [System.Windows.MessageBox]::Show($env:CONBRIDGE_CONFIRM_TEXT, "ConBridge", "YesNo", "Warning", "No")',
72
- 'if ($r -eq "Yes") { exit 0 } else { exit 1 }'
73
- ].join("; ");
74
- var windowsConfirm = (request) => new Promise((resolve8) => {
75
- const powershell = import_node_path.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
76
- (0, import_node_child_process.execFile)(powershell, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WINDOWS_CONFIRM_SCRIPT], { timeout: CONFIRM_TIMEOUT_MS, windowsHide: false, env: { ...process.env, CONBRIDGE_CONFIRM_TEXT: confirmText(request) } }, (error63) => resolve8(!error63));
77
- });
78
- var linuxConfirm = (request) => new Promise((resolve8) => {
79
- if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
80
- return resolve8(false);
81
- const text6 = confirmText(request);
82
- (0, import_node_child_process.execFile)("zenity", ["--question", "--title=ConBridge", `--text=${text6}`, "--ok-label=Allow", "--cancel-label=Deny", "--default-cancel", "--timeout=120"], { timeout: CONFIRM_TIMEOUT_MS }, (error63) => {
83
- if (!error63)
84
- return resolve8(true);
85
- if (error63.code !== "ENOENT")
86
- return resolve8(false);
87
- (0, import_node_child_process.execFile)("kdialog", ["--title", "ConBridge", "--warningyesno", text6, "--yes-label", "Allow", "--no-label", "Deny"], { timeout: CONFIRM_TIMEOUT_MS }, (fallback) => resolve8(!fallback));
88
- });
89
- });
90
- var localConfirm = (request) => {
91
- if (process.platform === "darwin")
92
- return macDialogConfirm(request);
93
- if (process.platform === "win32")
94
- return windowsConfirm(request);
95
- if (process.platform === "linux")
96
- return linuxConfirm(request);
97
- return Promise.resolve(false);
98
- };
35
+ var import_promises16 = require("node:readline/promises");
99
36
 
100
- // dist/connect.js
37
+ // dist/purge.js
101
38
  var import_node_child_process3 = require("node:child_process");
39
+ var import_node_crypto5 = require("node:crypto");
40
+ var import_promises6 = require("node:fs/promises");
41
+ var import_node_os3 = require("node:os");
102
42
  var import_node_path7 = require("node:path");
103
43
 
104
44
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/external.js
@@ -5168,7 +5108,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5168
5108
  var NONE = 0;
5169
5109
  var ASSUMED = 1;
5170
5110
  var PROVEN = 2;
5171
- function isRecursive(inst, stack, resolve8) {
5111
+ function isRecursive(inst, stack, resolve9) {
5172
5112
  const cached2 = recursive.get(inst);
5173
5113
  if (cached2 !== void 0)
5174
5114
  return cached2 ? PROVEN : NONE;
@@ -5178,7 +5118,7 @@ function isRecursive(inst, stack, resolve8) {
5178
5118
  let result2 = NONE;
5179
5119
  const check2 = (child) => {
5180
5120
  if (result2 !== PROVEN && child?._zod) {
5181
- const answer = isRecursive(child, stack, resolve8);
5121
+ const answer = isRecursive(child, stack, resolve9);
5182
5122
  if (answer > result2)
5183
5123
  result2 = answer;
5184
5124
  }
@@ -5189,7 +5129,7 @@ function isRecursive(inst, stack, resolve8) {
5189
5129
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5190
5130
  if (spread && !desc.enumerable)
5191
5131
  continue;
5192
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE;
5132
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve9) : NONE;
5193
5133
  if (child > answer)
5194
5134
  answer = child;
5195
5135
  }
@@ -5253,7 +5193,7 @@ function isRecursive(inst, stack, resolve8) {
5253
5193
  break;
5254
5194
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5255
5195
  case "lazy": {
5256
- const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
5196
+ const inner = def._cachedInner ?? (resolve9 ? inst._zod.innerType : void 0);
5257
5197
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5258
5198
  break;
5259
5199
  }
@@ -19850,7 +19790,9 @@ var INVENTORY_LIMITS = Object.freeze({
19850
19790
  ports: 32,
19851
19791
  imagePackages: 6e3,
19852
19792
  tlsEndpoints: 16,
19853
- health: 200
19793
+ health: 200,
19794
+ aptHeld: 200,
19795
+ listeners: 256
19854
19796
  });
19855
19797
  var inventoryIntervalSchema = external_exports.literal([...INVENTORY_INTERVALS_S]);
19856
19798
  var inventorySettingsSchema = external_exports.strictObject({ enabled: external_exports.boolean(), interval_s: inventoryIntervalSchema });
@@ -19867,6 +19809,8 @@ var inventoryPackageSchema = external_exports.strictObject({
19867
19809
  manager: external_exports.enum(PACKAGE_MANAGERS),
19868
19810
  /** dpkg only, from `apt-cache policy`; absent from agents before 0.5.0. */
19869
19811
  origin: external_exports.enum(PACKAGE_ORIGINS).optional(),
19812
+ /** dpkg only: the version apt would install (`Candidate` in `apt-cache policy`); null when no source offers the package. */
19813
+ candidate: version2.nullable().optional(),
19870
19814
  arch: external_exports.string().max(32).optional(),
19871
19815
  /** Installed size when the manager reports it. */
19872
19816
  size_bytes: bytes.optional(),
@@ -19952,6 +19896,18 @@ var inventoryTlsEndpointSchema = external_exports.strictObject({
19952
19896
  /** The `Strict-Transport-Security` header was present on `HEAD /` (HTTPS web ports only; absent when not checked). */
19953
19897
  hsts: external_exports.boolean().optional()
19954
19898
  });
19899
+ var LISTENER_BINDS = ["public", "private", "loopback"];
19900
+ var inventoryListenerOwnerSchema = external_exports.discriminatedUnion("kind", [
19901
+ external_exports.strictObject({ kind: external_exports.literal("package"), name }),
19902
+ external_exports.strictObject({ kind: external_exports.literal("container"), container_id: external_exports.string().regex(/^[0-9a-f]{12}$/) }),
19903
+ external_exports.strictObject({ kind: external_exports.literal("process"), name: external_exports.string().min(1).max(64) })
19904
+ ]);
19905
+ var inventoryListenerSchema = external_exports.strictObject({
19906
+ proto: external_exports.enum(["tcp", "udp"]),
19907
+ port: external_exports.number().int().min(1).max(65535),
19908
+ bind: external_exports.enum(LISTENER_BINDS),
19909
+ owner: inventoryListenerOwnerSchema.nullable()
19910
+ });
19955
19911
  var inventoryPodSchema = external_exports.strictObject({
19956
19912
  name,
19957
19913
  namespace: name.optional(),
@@ -19964,7 +19920,7 @@ var inventoryPodSchema = external_exports.strictObject({
19964
19920
  node: name.optional(),
19965
19921
  created_at: time3.optional()
19966
19922
  });
19967
- var COVERAGE_STATUSES = ["ok", "unavailable", "denied", "failed", "timeout", "truncated"];
19923
+ var COVERAGE_STATUSES = ["ok", "unavailable", "denied", "failed", "timeout", "truncated", "not_root"];
19968
19924
  var inventoryCoverageSchema = external_exports.strictObject({
19969
19925
  collector: external_exports.string().min(1).max(40).regex(/^[a-z0-9][a-z0-9_-]*$/),
19970
19926
  status: external_exports.enum(COVERAGE_STATUSES),
@@ -20003,6 +19959,19 @@ var inventoryHealthEventSchema = external_exports.strictObject({
20003
19959
  first_seen: time3.optional(),
20004
19960
  last_seen: time3.optional()
20005
19961
  });
19962
+ var aptPackageName = external_exports.string().min(1).max(200).regex(/^[a-z0-9][a-z0-9+.:~-]*$/);
19963
+ var inventoryAptSchema = external_exports.strictObject({
19964
+ /** Newest mtime of `/var/lib/apt/lists/*_InRelease`, milliseconds since epoch; null when there are no such files. */
19965
+ lists_newest_ms: external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable().optional(),
19966
+ /** `APT::Periodic::Update-Package-Lists` (`"1"` or `"always"` → true, `"0"`/`""`/missing → false). */
19967
+ update_lists: external_exports.boolean().nullable().optional(),
19968
+ /** `APT::Periodic::Unattended-Upgrade` (`"1"` or `"always"` → true, `"0"`/`""`/missing → false). */
19969
+ unattended: external_exports.boolean().nullable().optional(),
19970
+ /** At least one enabled apt source entry has a suite ending in `-security`. */
19971
+ security_pocket: external_exports.boolean().nullable().optional(),
19972
+ /** Package names `apt-mark showhold` lists. */
19973
+ held: external_exports.array(aptPackageName).max(INVENTORY_LIMITS.aptHeld).nullable().optional()
19974
+ });
20006
19975
  var inventorySnapshotSchema = external_exports.strictObject({
20007
19976
  schema: external_exports.literal(1),
20008
19977
  collected_at: time3,
@@ -20017,9 +19986,13 @@ var inventorySnapshotSchema = external_exports.strictObject({
20017
19986
  image_packages: external_exports.array(inventoryImagePackageSchema).max(INVENTORY_LIMITS.imagePackages).optional(),
20018
19987
  /** TLS endpoints on well-known local ports (agent 0.5.0 and newer). */
20019
19988
  tls_endpoints: external_exports.array(inventoryTlsEndpointSchema).max(INVENTORY_LIMITS.tlsEndpoints).optional(),
19989
+ /** Listening sockets and their owners (agent 0.7.0 and newer; CB-194). */
19990
+ listeners: external_exports.array(inventoryListenerSchema).max(INVENTORY_LIMITS.listeners).optional(),
20020
19991
  pods: external_exports.array(inventoryPodSchema).max(INVENTORY_LIMITS.pods),
20021
19992
  /** Grouped errors of the last 24 hours (agent 0.5.0 and newer). */
20022
19993
  health: external_exports.array(inventoryHealthEventSchema).max(INVENTORY_LIMITS.health).optional(),
19994
+ /** Apt candidate versions and package-index evidence (CB-190); omitted when apt is absent. */
19995
+ apt: inventoryAptSchema.optional(),
20023
19996
  coverage: external_exports.array(inventoryCoverageSchema).max(INVENTORY_LIMITS.coverage)
20024
19997
  });
20025
19998
 
@@ -20027,6 +20000,14 @@ var inventorySnapshotSchema = external_exports.strictObject({
20027
20000
  var WIRE_VERSION = 1;
20028
20001
  var MAX_ENVELOPE_BYTES = 65536;
20029
20002
  var MAX_CHUNK_BYTES = 8192;
20003
+ var CONNECTION_MODES = Object.freeze(["persistent", "passive", "timed", "ephemeral"]);
20004
+ var LIFECYCLE_CAPABILITY = "lifecycle.v1";
20005
+ var AGENT_REMOVAL_REASONS = Object.freeze({
20006
+ revoked: "removed:revoked",
20007
+ expired: "removed:expired",
20008
+ destroyed: "removed:destroyed",
20009
+ left: "removed:left"
20010
+ });
20030
20011
  var uuid3 = external_exports.uuid();
20031
20012
  var opaque = external_exports.string().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/);
20032
20013
  var capability = external_exports.string().min(3).max(120).regex(/^[a-z][a-z0-9_.-]+$/);
@@ -20085,7 +20066,14 @@ var hello = base.extend({
20085
20066
  kind: external_exports.literal("HELLO"),
20086
20067
  agent_id: uuid3,
20087
20068
  supported_versions: external_exports.array(external_exports.number().int().min(1).max(65535)).min(1).max(16),
20088
- capabilities: external_exports.array(capability).max(128)
20069
+ capabilities: external_exports.array(capability).max(128),
20070
+ session: external_exports.enum(["foreground", "service"]).optional()
20071
+ });
20072
+ var lifecycle = base.extend({
20073
+ kind: external_exports.literal("LIFECYCLE"),
20074
+ connection_mode: external_exports.enum(CONNECTION_MODES),
20075
+ expires_at_ms: external_exports.number().int().nonnegative().nullable(),
20076
+ destroy_deadline_ms: external_exports.number().int().nonnegative().nullable()
20089
20077
  });
20090
20078
  var enroll = base.extend({
20091
20079
  kind: external_exports.literal("ENROLL"),
@@ -20202,6 +20190,7 @@ var softwareInventoryPart = base.extend({
20202
20190
  });
20203
20191
  var envelopeSchema = external_exports.discriminatedUnion("kind", [
20204
20192
  hello,
20193
+ lifecycle,
20205
20194
  enroll,
20206
20195
  inventory,
20207
20196
  heartbeat,
@@ -20242,7 +20231,7 @@ function sizedJson(value) {
20242
20231
  return text6;
20243
20232
  }
20244
20233
  function requireSemanticConstraints(message) {
20245
- if (message.kind === "HELLO" || message.kind === "ENROLL" || message.kind === "HEARTBEAT" || message.kind === "NEGOTIATE" || message.kind === "INVENTORY" || message.kind === "MONITOR_CONFIG" || message.kind === "METRICS" || message.kind === "SOFTWARE_INVENTORY_CONFIG" || message.kind === "SOFTWARE_INVENTORY_REQUEST" || message.kind === "SOFTWARE_INVENTORY_PART") {
20234
+ if (message.kind === "HELLO" || message.kind === "LIFECYCLE" || message.kind === "ENROLL" || message.kind === "HEARTBEAT" || message.kind === "NEGOTIATE" || message.kind === "INVENTORY" || message.kind === "MONITOR_CONFIG" || message.kind === "METRICS" || message.kind === "SOFTWARE_INVENTORY_CONFIG" || message.kind === "SOFTWARE_INVENTORY_REQUEST" || message.kind === "SOFTWARE_INVENTORY_PART") {
20246
20235
  if (message.task_id !== null)
20247
20236
  throw new ProtocolDecodeError("INVALID_MESSAGE", "Control message must not include a task");
20248
20237
  } else if (message.kind !== "ERROR" && message.task_id === null) {
@@ -20423,7 +20412,6 @@ var SEVERITY_ORDER = Object.freeze({
20423
20412
  info: 4
20424
20413
  });
20425
20414
  var CATEGORY_ORDER = Object.freeze({
20426
- access: 0,
20427
20415
  vulnerability: 1,
20428
20416
  exposure: 2,
20429
20417
  lifecycle: 3,
@@ -20662,13 +20650,28 @@ function redactLogMessage(message, options = {}) {
20662
20650
  }
20663
20651
 
20664
20652
  // ../../packages/protocol/dist/security/risk.js
20665
- var RISK_RULES_VERSION = "2026-11-02.1";
20653
+ var RISK_RULES_VERSION = "2026-11-09.1";
20666
20654
  var RATING_BASE = Object.freeze({ critical: 95, high: 80, medium: 55, low: 25, negligible: 10 });
20667
20655
  var CRITICALITY_FACTOR = Object.freeze({ low: 0.8, normal: 1, high: 1.1, critical: 1.2 });
20668
20656
  var CLASS_FACTOR = Object.freeze({ confirmed: 1, potential: 0.7, unknown: 0.5, not_affected: 0, fixed: 0 });
20669
20657
 
20670
20658
  // ../../packages/protocol/dist/security/components.js
20671
- var COMPONENT_RULES_VERSION = "2026-11-05.1";
20659
+ var COMPONENT_RULES_VERSION = "2026-11-09.2";
20660
+ var DAEMON_PACKAGES = Object.freeze([
20661
+ "openssh-server",
20662
+ "postfix",
20663
+ "dovecot-core",
20664
+ "nginx",
20665
+ "apache2",
20666
+ "mysql-server",
20667
+ "mariadb-server",
20668
+ "bind9",
20669
+ "exim4",
20670
+ "haproxy",
20671
+ "docker-ce",
20672
+ "containerd"
20673
+ ]);
20674
+ var DAEMON_PACKAGE_PATTERNS = Object.freeze([/^postgresql-/]);
20672
20675
  var THIRD_PARTY_VERSION_PATTERNS = Object.freeze([
20673
20676
  /nodesource/i,
20674
20677
  /deb\.sury\.org/i,
@@ -20704,10 +20707,10 @@ var PLATFORM_NAMES = Object.freeze({
20704
20707
  });
20705
20708
 
20706
20709
  // ../../packages/protocol/dist/security/buckets.js
20707
- var BUCKET_RULES_VERSION = "2026-11-02.1";
20710
+ var BUCKET_RULES_VERSION = "2026-11-09.1";
20708
20711
 
20709
20712
  // ../../packages/protocol/dist/security/matching.js
20710
- var MATCHING_RULES_VERSION = "2026-11-02.1";
20713
+ var MATCHING_RULES_VERSION = "2026-11-09.3";
20711
20714
  var EVALUATION_RULES_VERSION = [COMPONENT_RULES_VERSION, MATCHING_RULES_VERSION, RISK_RULES_VERSION, BUCKET_RULES_VERSION].join("+");
20712
20715
 
20713
20716
  // ../../packages/protocol/dist/security/jev.js
@@ -20767,6 +20770,122 @@ var JEV_EVAL_CASES = Object.freeze([
20767
20770
  evalCase("13", { top_band: "critical", cvss: 9.8, rating: "critical", ecosystem: "cpe", groups: [group("potential", "device", "critical")] }),
20768
20771
  evalCase("14", { top_band: "low", cvss: 3.7, rating: "low", groups: [group("unknown", "device", "low")] })
20769
20772
  ]);
20773
+ var JEV_ACTION_ROUTES = ["apply_now", "schedule_window", "refresh_sources_first", "mitigate_first", "verify_first", "defer"];
20774
+ var JEV_ACTION_URGENCY_LEVELS = Object.freeze([
20775
+ "Routine: handle in normal maintenance",
20776
+ "Soon: within a few weeks",
20777
+ "Urgent: within days",
20778
+ "Immediate: act today"
20779
+ ]);
20780
+ var JEV_DISRUPTION_LEVELS = Object.freeze([
20781
+ "No disruption: no restart, no downtime",
20782
+ "Restarts a service",
20783
+ "Restarts the host",
20784
+ "Restarts the data path"
20785
+ ]);
20786
+ var ACTION_ROUTE_TEXT = Object.freeze({
20787
+ apply_now: "Apply the fix as soon as possible",
20788
+ schedule_window: "Apply the fix in the next planned maintenance window",
20789
+ refresh_sources_first: "Refresh the package sources first, then apply the fix",
20790
+ mitigate_first: "Reduce exposure first: no safe fix is available yet",
20791
+ verify_first: "Confirm that the software is really affected before acting",
20792
+ defer: "No action now"
20793
+ });
20794
+ var ACTION_ANSWER = external_exports.object({
20795
+ model: external_exports.string().min(1).max(100),
20796
+ answers: external_exports.object({
20797
+ urgency: external_exports.object({ type: external_exports.literal("score"), score: external_exports.number().min(0).max(3), confidence: unit }),
20798
+ route: external_exports.object({ type: external_exports.literal("choice"), choice: external_exports.string(), confidence: unit, probabilities: external_exports.record(external_exports.string(), unit) }),
20799
+ exploitation: external_exports.object({ type: external_exports.literal("noul"), noul: unit }),
20800
+ disruption: external_exports.object({ type: external_exports.literal("score"), score: external_exports.number().min(0).max(3), confidence: unit })
20801
+ })
20802
+ });
20803
+ var JEV_VERIFY_ROUTES = ["check_version_now", "likely_not_affected", "treat_as_confirmed"];
20804
+ var VERIFY_ROUTE_TEXT = Object.freeze({
20805
+ check_version_now: "Check the installed version now (a fresh inventory)",
20806
+ likely_not_affected: "Likely not affected: the fix is probably already backported",
20807
+ treat_as_confirmed: "Treat as confirmed affected"
20808
+ });
20809
+ var VERIFY_ANSWER = external_exports.object({
20810
+ model: external_exports.string().min(1).max(100),
20811
+ answers: external_exports.object({
20812
+ real_exposure: external_exports.object({ type: external_exports.literal("noul"), noul: unit }),
20813
+ verify_route: external_exports.object({ type: external_exports.literal("choice"), choice: external_exports.enum(JEV_VERIFY_ROUTES), confidence: unit })
20814
+ })
20815
+ });
20816
+ var actionCase = (id, partial2, floor = false) => ({
20817
+ id,
20818
+ floor,
20819
+ input: {
20820
+ kind: "package_upgrade",
20821
+ counts: { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 },
20822
+ max_cvss: null,
20823
+ kev_count: 0,
20824
+ max_epss_percentile: null,
20825
+ cwes: [],
20826
+ reachability: "unknown",
20827
+ restart: "none",
20828
+ exposure: "unknown",
20829
+ package_category: "other",
20830
+ asset_kind: "device",
20831
+ criticality: "normal",
20832
+ environment: null,
20833
+ days_open: 0,
20834
+ host_updates_off: null,
20835
+ coverage_complete: true,
20836
+ feasible_routes: [...JEV_ACTION_ROUTES],
20837
+ ...partial2
20838
+ }
20839
+ });
20840
+ var JEV_ACTION_EVAL_CASES = Object.freeze([
20841
+ actionCase("a1", { kind: "package_upgrade", counts: { critical: 3, high: 1, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.8, kev_count: 1, max_epss_percentile: 0.99, cwes: ["CWE-787"], reachability: "index_stale", restart: "service", exposure: "public", package_category: "tls", environment: "production", days_open: 52, host_updates_off: true }, true),
20842
+ actionCase("a2", { kind: "kernel_reboot", counts: { critical: 2, high: 0, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.1, reachability: "reachable", restart: "host", package_category: "kernel", days_open: 3 }, true),
20843
+ actionCase("a3", { kind: "mitigate", counts: { critical: 0, high: 0, medium: 0, low: 5, unknown: 2 }, restart: "none", package_category: "kernel", environment: "production" }),
20844
+ actionCase("a4", { kind: "kernel_reboot", counts: { critical: 40, high: 60, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.8, kev_count: 12, max_epss_percentile: 0.98, reachability: "reachable", restart: "host", package_category: "kernel", days_open: 730 }, true),
20845
+ actionCase("a5", { kind: "package_upgrade", counts: { critical: 1, high: 0, medium: 0, low: 0, unknown: 0 }, max_cvss: 9, reachability: "reachable", exposure: "local", package_category: "ssh" }, true),
20846
+ actionCase("a6", { kind: "package_upgrade", counts: { critical: 0, high: 2, medium: 0, low: 0, unknown: 0 }, max_cvss: 7.8, exposure: "public", package_category: "web_server" }, true),
20847
+ actionCase("a7", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 3, low: 0, unknown: 0 }, max_cvss: 5.5, exposure: "local", package_category: "interpreter", environment: "staging" }),
20848
+ actionCase("a8", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 0, low: 2, unknown: 0 }, max_cvss: 3.1, package_category: "other" }),
20849
+ actionCase("a9", { kind: "site_update", counts: { critical: 1, high: 0, medium: 0, low: 0, unknown: 0 }, max_cvss: 9, exposure: "public", package_category: "cms", asset_kind: "site" }),
20850
+ actionCase("a10", { kind: "composer_update", counts: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0 }, max_cvss: 7.2, exposure: "public", package_category: "cms", asset_kind: "site", environment: "production" }, true),
20851
+ actionCase("a11", { kind: "runtime_upgrade", counts: { critical: 2, high: 0, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.9, kev_count: 3, max_epss_percentile: 0.99, reachability: "reachable", package_category: "interpreter" }, true),
20852
+ actionCase("a12", { kind: "package_upgrade", counts: { critical: 0, high: 3, medium: 0, low: 0, unknown: 0 }, max_cvss: 7.4, reachability: "index_stale", package_category: "database", host_updates_off: true, days_open: 30 }),
20853
+ actionCase("a13", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 2, low: 0, unknown: 0 }, max_cvss: 6, reachability: "held", package_category: "libc", days_open: 90 }),
20854
+ actionCase("a14", { kind: "package_upgrade", counts: { critical: 1, high: 0, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.3, reachability: "not_in_sources", package_category: "tls" }),
20855
+ actionCase("a15", { kind: "mitigate", counts: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0 }, max_cvss: 7, exposure: "local", package_category: "container_runtime" }),
20856
+ actionCase("a16", { kind: "kernel_upgrade_reboot", counts: { critical: 5, high: 0, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.6, kev_count: 1, reachability: "reachable", restart: "host", package_category: "kernel", days_open: 100 }, true),
20857
+ actionCase("a17", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 4, low: 0, unknown: 0 }, max_cvss: 6.5, max_epss_percentile: 0.96, package_category: "mail_server" }),
20858
+ actionCase("a18", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 0, low: 1, unknown: 0 }, max_cvss: 3.5, kev_count: 1, package_category: "other" }, true),
20859
+ actionCase("a19", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 0, low: 0, unknown: 3 }, max_cvss: null, package_category: "other" }),
20860
+ actionCase("a20", { kind: "package_upgrade", counts: { critical: 1, high: 2, medium: 0, low: 0, unknown: 0 }, max_cvss: 9.4, reachability: "reachable", exposure: "public", package_category: "ssh", criticality: "critical", environment: "production" }, true),
20861
+ actionCase("a21", { kind: "package_upgrade", counts: { critical: 0, high: 0, medium: 1, low: 0, unknown: 0 }, max_cvss: 5, feasible_routes: ["verify_first", "defer"] }),
20862
+ actionCase("a22", { kind: "mitigate", counts: { critical: 0, high: 0, medium: 0, low: 1, unknown: 0 }, feasible_routes: ["defer"] }),
20863
+ actionCase("a23", { kind: "kernel_reboot", counts: { critical: 0, high: 0, medium: 0, low: 1, unknown: 0 }, reachability: "reachable", restart: "host", package_category: "kernel", days_open: 1 }),
20864
+ actionCase("a24", { kind: "package_upgrade", counts: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0 }, max_cvss: 7.6, max_epss_percentile: 0.85, exposure: "public", package_category: "tls" }, true)
20865
+ ]);
20866
+ var verifyCase = (id, partial2) => ({
20867
+ id,
20868
+ input: {
20869
+ match_basis: "cpe_banner",
20870
+ source_kind: "upstream_binary",
20871
+ backport_likely: false,
20872
+ cwes: [],
20873
+ attack_vector: null,
20874
+ cvss: null,
20875
+ kev: false,
20876
+ epss_percentile: null,
20877
+ advisory_age_days: null,
20878
+ ...partial2
20879
+ }
20880
+ });
20881
+ var JEV_VERIFY_EVAL_CASES = Object.freeze([
20882
+ verifyCase("v1", { kev: true, cvss: 9.8, attack_vector: "network", cwes: ["CWE-79"] }),
20883
+ verifyCase("v2", { match_basis: "cpe_banner", cvss: 7.5, attack_vector: "network" }),
20884
+ verifyCase("v3", { match_basis: "osv_no_entry", source_kind: "distro_package", backport_likely: true, cvss: 6.1 }),
20885
+ verifyCase("v4", { match_basis: "nvd_range_undetermined", cvss: 5 }),
20886
+ verifyCase("v5", { match_basis: "stale_inventory", cvss: 4, advisory_age_days: 200 }),
20887
+ verifyCase("v6", { match_basis: "derived_identity", source_kind: "language_package", cvss: 6.5 })
20888
+ ]);
20770
20889
 
20771
20890
  // ../../packages/protocol/dist/http.js
20772
20891
  var HTTP_API_VERSION = 1;
@@ -20854,7 +20973,7 @@ var SITE_PLATFORMS = Object.freeze(["joomla", "drupal", "prestashop", "opencart"
20854
20973
  var CONNECTOR_KINDS = Object.freeze(["desktop", "browser", "vscode", "wordpress", ...SITE_PLATFORMS, "github"]);
20855
20974
  var CAPABILITY_RISKS = Object.freeze(["read", "write", "privileged"]);
20856
20975
  var CONNECTOR_NAMESPACES = Object.freeze({
20857
- desktop: Object.freeze(["files.", "ssh.", "shell.", "process.", "system."]),
20976
+ desktop: Object.freeze(["files.", "ssh.", "shell.", "process.", "system.", "agent."]),
20858
20977
  browser: Object.freeze(["browser."]),
20859
20978
  vscode: Object.freeze(["vscode."]),
20860
20979
  wordpress: Object.freeze(["wp.", "elementor.", "wordpress."]),
@@ -21081,6 +21200,25 @@ var SHELL_CAPABILITY_DEFINITIONS = Object.freeze([
21081
21200
  { connector: "desktop", capability: "system.info", risk: "read", description: "Read system information (OS, CPU, memory, disks)", payload: shellPayloadSchemas["system.info"] }
21082
21201
  ]);
21083
21202
 
21203
+ // ../../packages/protocol/dist/connectors/agent.js
21204
+ var AGENT_CAPABILITIES = Object.freeze(["agent.remove"]);
21205
+ function isAgentCapability(value) {
21206
+ return typeof value === "string" && AGENT_CAPABILITIES.includes(value);
21207
+ }
21208
+ var agentPayloadSchemas = {
21209
+ "agent.remove": external_exports.strictObject({ run_at_ms: external_exports.number().int().nonnegative() })
21210
+ };
21211
+ var AGENT_CAPABILITY_DEFINITIONS = Object.freeze([
21212
+ {
21213
+ connector: "desktop",
21214
+ capability: "agent.remove",
21215
+ risk: "privileged",
21216
+ defaultEffect: "ask",
21217
+ description: "Schedule removal of ConBridge from this computer",
21218
+ payload: agentPayloadSchemas["agent.remove"]
21219
+ }
21220
+ ]);
21221
+
21084
21222
  // ../../packages/protocol/dist/connectors/browser.js
21085
21223
  var BROWSER_CAPABILITIES = Object.freeze([
21086
21224
  "browser.tabs.list",
@@ -21515,6 +21653,7 @@ var siteWriteKeys = { idempotency_key: external_exports.uuid(), approval_id: ext
21515
21653
  registerCapabilities(DESKTOP_CAPABILITY_DEFINITIONS);
21516
21654
  registerCapabilities(SSH_CAPABILITY_DEFINITIONS);
21517
21655
  registerCapabilities(SHELL_CAPABILITY_DEFINITIONS);
21656
+ registerCapabilities(AGENT_CAPABILITY_DEFINITIONS);
21518
21657
  registerCapabilities(BROWSER_CAPABILITY_DEFINITIONS);
21519
21658
  registerCapabilities(VSCODE_CAPABILITY_DEFINITIONS);
21520
21659
  registerCapabilities(WORDPRESS_CAPABILITY_DEFINITIONS);
@@ -21636,6 +21775,12 @@ var DEFAULT_DENY_GLOBS = Object.freeze([
21636
21775
  // ../../packages/protocol/dist/index.js
21637
21776
  var moduleInfo = Object.freeze({ name: "@conbridge/protocol", runtime: "shared", status: "scaffold-only" });
21638
21777
 
21778
+ // dist/keychain.js
21779
+ var import_node_child_process2 = require("node:child_process");
21780
+ var import_node_crypto4 = require("node:crypto");
21781
+ var import_promises5 = require("node:fs/promises");
21782
+ var import_node_path6 = require("node:path");
21783
+
21639
21784
  // dist/keystore.js
21640
21785
  var import_node_crypto3 = require("node:crypto");
21641
21786
  var import_promises4 = require("node:fs/promises");
@@ -21643,26 +21788,26 @@ var import_promises4 = require("node:fs/promises");
21643
21788
  // dist/state.js
21644
21789
  var import_promises3 = require("node:fs/promises");
21645
21790
  var import_node_os2 = require("node:os");
21646
- var import_node_path5 = require("node:path");
21791
+ var import_node_path4 = require("node:path");
21647
21792
  var import_node_crypto2 = require("node:crypto");
21648
21793
 
21649
21794
  // dist/service.js
21650
- var import_node_child_process2 = require("node:child_process");
21795
+ var import_node_child_process = require("node:child_process");
21651
21796
  var import_promises2 = require("node:fs/promises");
21652
21797
  var import_node_os = require("node:os");
21653
- var import_node_path4 = require("node:path");
21798
+ var import_node_path3 = require("node:path");
21654
21799
 
21655
21800
  // dist/util.js
21656
21801
  var import_promises = require("node:fs/promises");
21657
21802
  var import_node_crypto = require("node:crypto");
21658
- var import_node_path3 = require("node:path");
21803
+ var import_node_path2 = require("node:path");
21659
21804
 
21660
21805
  // dist/runtime.js
21661
21806
  var import_node_fs = require("node:fs");
21662
- var import_node_path2 = require("node:path");
21807
+ var import_node_path = require("node:path");
21663
21808
  var import_node_sea = require("node:sea");
21664
21809
  var import_node_url = require("node:url");
21665
- var SOURCE_VERSION = "0.5.0";
21810
+ var SOURCE_VERSION = "0.6.0";
21666
21811
  var BUILD_INFO = typeof define_CONBRIDGE_BUILD_default === "object" && define_CONBRIDGE_BUILD_default !== null ? define_CONBRIDGE_BUILD_default : null;
21667
21812
  var AGENT_VERSION = BUILD_INFO?.version ?? SOURCE_VERSION;
21668
21813
  function runningAsSea() {
@@ -21675,12 +21820,12 @@ function runningAsSea() {
21675
21820
  function codeDirectory() {
21676
21821
  if (runningAsSea()) {
21677
21822
  try {
21678
- return (0, import_node_path2.dirname)((0, import_node_fs.realpathSync)(process.execPath));
21823
+ return (0, import_node_path.dirname)((0, import_node_fs.realpathSync)(process.execPath));
21679
21824
  } catch {
21680
- return (0, import_node_path2.dirname)(process.execPath);
21825
+ return (0, import_node_path.dirname)(process.execPath);
21681
21826
  }
21682
21827
  }
21683
- return (0, import_node_path2.dirname)((0, import_node_url.fileURLToPath)(__conbridge_import_meta_url));
21828
+ return (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(__conbridge_import_meta_url));
21684
21829
  }
21685
21830
  function runningFromNpm() {
21686
21831
  return BUILD_INFO?.distribution === "npm" && !runningAsSea();
@@ -21719,7 +21864,7 @@ async function fsyncDirectory(path) {
21719
21864
  }
21720
21865
  }
21721
21866
  async function writeFileAtomic(path, content, mode) {
21722
- const temp = (0, import_node_path3.join)((0, import_node_path3.dirname)(path), `.${(0, import_node_path3.basename)(path)}.${randomToken(6)}.tmp`);
21867
+ const temp = (0, import_node_path2.join)((0, import_node_path2.dirname)(path), `.${(0, import_node_path2.basename)(path)}.${randomToken(6)}.tmp`);
21723
21868
  const handle = await (0, import_promises.open)(temp, "wx", mode);
21724
21869
  try {
21725
21870
  await handle.writeFile(content, "utf8");
@@ -21737,7 +21882,7 @@ async function writeFileAtomic(path, content, mode) {
21737
21882
  await (0, import_promises.unlink)(temp).catch(() => void 0);
21738
21883
  throw error63;
21739
21884
  }
21740
- await fsyncDirectory((0, import_node_path3.dirname)(path));
21885
+ await fsyncDirectory((0, import_node_path2.dirname)(path));
21741
21886
  }
21742
21887
  function errorMessage(error63) {
21743
21888
  return error63 instanceof Error ? error63.message : String(error63);
@@ -21748,22 +21893,22 @@ function errorCode2(error63) {
21748
21893
  return void 0;
21749
21894
  }
21750
21895
  async function realpathLenient(path) {
21751
- const absolute = (0, import_node_path3.resolve)(path);
21896
+ const absolute = (0, import_node_path2.resolve)(path);
21752
21897
  const missing = [];
21753
21898
  let current = absolute;
21754
21899
  for (; ; ) {
21755
21900
  try {
21756
- return (0, import_node_path3.join)(await (0, import_promises.realpath)(current), ...missing);
21901
+ return (0, import_node_path2.join)(await (0, import_promises.realpath)(current), ...missing);
21757
21902
  } catch (error63) {
21758
- const parent = (0, import_node_path3.dirname)(current);
21903
+ const parent = (0, import_node_path2.dirname)(current);
21759
21904
  if (parent === current || errorCode2(error63) !== "ENOENT" && errorCode2(error63) !== "ENOTDIR")
21760
21905
  return absolute;
21761
- missing.unshift((0, import_node_path3.basename)(current));
21906
+ missing.unshift((0, import_node_path2.basename)(current));
21762
21907
  current = parent;
21763
21908
  }
21764
21909
  }
21765
21910
  }
21766
- function isSameOrInside(dir, path, separator = import_node_path3.sep) {
21911
+ function isSameOrInside(dir, path, separator = import_node_path2.sep) {
21767
21912
  const normalize = (value) => (separator === "\\" ? value.replace(/\\/g, "/") : value).toLowerCase();
21768
21913
  const a = normalize(dir);
21769
21914
  const b = normalize(path);
@@ -21822,13 +21967,13 @@ function buildLaunchAgentPlist(options) {
21822
21967
  ].filter((line) => line !== "").join("\n") + "\n";
21823
21968
  }
21824
21969
  function launchAgentPath(home = (0, import_node_os.homedir)()) {
21825
- return (0, import_node_path4.join)(home, "Library", "LaunchAgents", `${LAUNCH_AGENT_LABEL}.plist`);
21970
+ return (0, import_node_path3.join)(home, "Library", "LaunchAgents", `${LAUNCH_AGENT_LABEL}.plist`);
21826
21971
  }
21827
21972
  function defaultLogPath(home = (0, import_node_os.homedir)()) {
21828
- return (0, import_node_path4.join)(home, "Library", "Logs", "conbridge-agent.log");
21973
+ return (0, import_node_path3.join)(home, "Library", "Logs", "conbridge-agent.log");
21829
21974
  }
21830
- var systemCommand = (file2, args) => new Promise((resolve8) => {
21831
- (0, import_node_child_process2.execFile)(file2, args, { windowsHide: true }, (error63, stdout, stderr) => resolve8({ ok: !error63, output: `${stdout}${stderr}`.trim() }));
21975
+ var systemCommand = (file2, args) => new Promise((resolve9) => {
21976
+ (0, import_node_child_process.execFile)(file2, args, { windowsHide: true }, (error63, stdout, stderr) => resolve9({ ok: !error63, output: `${stdout}${stderr}`.trim() }));
21832
21977
  });
21833
21978
  var systemLaunchctl = (args) => systemCommand("/bin/launchctl", args);
21834
21979
  async function stableNodePath(execPath = process.execPath, candidates = ["/opt/homebrew/bin/node", "/usr/local/bin/node"]) {
@@ -21856,14 +22001,15 @@ async function installLaunchAgent(options, deps = {}) {
21856
22001
  throw new Error("LaunchAgent install is only supported on macOS");
21857
22002
  const run2 = deps.launchctl ?? systemLaunchctl;
21858
22003
  const path = launchAgentPath(deps.home);
21859
- await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(path), { recursive: true });
21860
- await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(options.logPath), { recursive: true });
22004
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(path), { recursive: true });
22005
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(options.logPath), { recursive: true });
21861
22006
  await writeFileAtomic(path, buildLaunchAgentPlist(options), 420);
21862
22007
  const domain2 = `gui/${deps.uid ?? (0, import_node_os.userInfo)().uid}`;
21863
22008
  await run2(["bootout", `${domain2}/${LAUNCH_AGENT_LABEL}`]);
22009
+ await run2(["enable", `${domain2}/${LAUNCH_AGENT_LABEL}`]);
21864
22010
  let result2 = await run2(["bootstrap", domain2, path]);
21865
22011
  for (let attempt = 1; !result2.ok && attempt <= 4 && /\b5: Input\/output error/.test(result2.output); attempt += 1) {
21866
- await new Promise((resolve8) => setTimeout(resolve8, 750 * attempt));
22012
+ await new Promise((resolve9) => setTimeout(resolve9, 750 * attempt));
21867
22013
  result2 = await run2(["bootstrap", domain2, path]);
21868
22014
  }
21869
22015
  if (!result2.ok)
@@ -21875,7 +22021,7 @@ async function uninstallLaunchAgent(deps = {}) {
21875
22021
  throw new Error("LaunchAgent uninstall is only supported on macOS");
21876
22022
  const run2 = deps.launchctl ?? systemLaunchctl;
21877
22023
  const path = launchAgentPath(deps.home);
21878
- await run2(["bootout", `gui/${deps.uid ?? (0, import_node_os.userInfo)().uid}/${LAUNCH_AGENT_LABEL}`]);
22024
+ await run2([deps.stopRunning === false ? "disable" : "bootout", `gui/${deps.uid ?? (0, import_node_os.userInfo)().uid}/${LAUNCH_AGENT_LABEL}`]);
21879
22025
  await (0, import_promises2.unlink)(path).catch((error63) => {
21880
22026
  if (errorCode2(error63) !== "ENOENT")
21881
22027
  throw error63;
@@ -21885,7 +22031,7 @@ async function uninstallLaunchAgent(deps = {}) {
21885
22031
  var SYSTEMD_UNIT = "conbridge-agent.service";
21886
22032
  var SYSTEMD_SYSTEM_UNIT_PATH = "/etc/systemd/system/conbridge-agent.service";
21887
22033
  function systemdUnitPath(home = (0, import_node_os.homedir)()) {
21888
- return (0, import_node_path4.join)(home, ".config", "systemd", "user", SYSTEMD_UNIT);
22034
+ return (0, import_node_path3.join)(home, ".config", "systemd", "user", SYSTEMD_UNIT);
21889
22035
  }
21890
22036
  function systemdWord(value) {
21891
22037
  if (/[\r\n]/.test(value))
@@ -21924,7 +22070,7 @@ async function installSystemdService(options, deps = {}) {
21924
22070
  const run2 = deps.run ?? systemCommand;
21925
22071
  if (isRoot(deps)) {
21926
22072
  const path2 = deps.systemUnitPath ?? SYSTEMD_SYSTEM_UNIT_PATH;
21927
- await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(path2), { recursive: true });
22073
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(path2), { recursive: true });
21928
22074
  await writeFileAtomic(path2, buildSystemdUnit({ ...options, system: { home: deps.home ?? (0, import_node_os.homedir)() } }), 420);
21929
22075
  for (const args of [["daemon-reload"], ["enable", SYSTEMD_UNIT], ["restart", SYSTEMD_UNIT]]) {
21930
22076
  const result2 = await run2("systemctl", args);
@@ -21934,7 +22080,7 @@ async function installSystemdService(options, deps = {}) {
21934
22080
  return { location: path2, notes: ["The agent starts when this computer boots (system service, runs as root).", `Logs: journalctl -u ${SYSTEMD_UNIT} -f`] };
21935
22081
  }
21936
22082
  const path = systemdUnitPath(deps.home);
21937
- await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(path), { recursive: true });
22083
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(path), { recursive: true });
21938
22084
  await writeFileAtomic(path, buildSystemdUnit(options), 420);
21939
22085
  const reload = await run2("systemctl", ["--user", "daemon-reload"]);
21940
22086
  if (!reload.ok)
@@ -21958,7 +22104,7 @@ async function uninstallSystemdService(deps = {}) {
21958
22104
  const system = isRoot(deps);
21959
22105
  const path = system ? deps.systemUnitPath ?? SYSTEMD_SYSTEM_UNIT_PATH : systemdUnitPath(deps.home);
21960
22106
  const scope = system ? [] : ["--user"];
21961
- await run2("systemctl", [...scope, "disable", "--now", SYSTEMD_UNIT]);
22107
+ await run2("systemctl", [...scope, "disable", ...deps.stopRunning === false ? [] : ["--now"], SYSTEMD_UNIT]);
21962
22108
  await (0, import_promises2.unlink)(path).catch((error63) => {
21963
22109
  if (errorCode2(error63) !== "ENOENT")
21964
22110
  throw error63;
@@ -21981,8 +22127,8 @@ function withCronLine(current, line) {
21981
22127
  const kept = current.split("\n").filter((entry) => entry.trim() !== "" && !entry.includes(CRON_MARKER));
21982
22128
  return [...kept, ...line ? [line] : []].join("\n") + "\n";
21983
22129
  }
21984
- var systemCrontabWriter = (text6) => new Promise((resolve8) => {
21985
- const child = (0, import_node_child_process2.execFile)("crontab", ["-"], (error63, stdout, stderr) => resolve8({ ok: !error63, output: `${stdout}${stderr}`.trim() }));
22130
+ var systemCrontabWriter = (text6) => new Promise((resolve9) => {
22131
+ const child = (0, import_node_child_process.execFile)("crontab", ["-"], (error63, stdout, stderr) => resolve9({ ok: !error63, output: `${stdout}${stderr}`.trim() }));
21986
22132
  child.stdin?.end(text6);
21987
22133
  });
21988
22134
  async function installCronService(options, deps = {}) {
@@ -22001,15 +22147,15 @@ async function uninstallCronService(deps = {}) {
22001
22147
  return "crontab (@reboot)";
22002
22148
  }
22003
22149
  function linuxDefaultLogPath(home = (0, import_node_os.homedir)()) {
22004
- return (0, import_node_path4.join)(home, ".conbridge", "agent.log");
22150
+ return (0, import_node_path3.join)(home, ".conbridge", "agent.log");
22005
22151
  }
22006
22152
  var WINDOWS_TASK_NAME = "ConBridge Agent";
22007
22153
  var WINDOWS_RESTART_DELAY_S = 10;
22008
22154
  function windowsLauncherPath(stateDir) {
22009
- return (0, import_node_path4.join)(stateDir, "conbridge-agent-service.vbs");
22155
+ return (0, import_node_path3.join)(stateDir, "conbridge-agent-service.vbs");
22010
22156
  }
22011
22157
  function windowsDefaultLogPath(env = process.env, home = (0, import_node_os.homedir)()) {
22012
- return (0, import_node_path4.join)(env.LOCALAPPDATA ?? (0, import_node_path4.join)(home, "AppData", "Local"), "ConBridge", "conbridge-agent.log");
22158
+ return (0, import_node_path3.join)(env.LOCALAPPDATA ?? (0, import_node_path3.join)(home, "AppData", "Local"), "ConBridge", "conbridge-agent.log");
22013
22159
  }
22014
22160
  function windowsPath(value) {
22015
22161
  if (/["%\r\n]/.test(value))
@@ -22067,7 +22213,7 @@ function buildWindowsTaskXml(input2) {
22067
22213
  ].join("\r\n");
22068
22214
  }
22069
22215
  function windowsSystemTool(env, name3) {
22070
- return import_node_path4.win32.join(env.SystemRoot ?? env.windir ?? "C:\\Windows", "System32", name3);
22216
+ return import_node_path3.win32.join(env.SystemRoot ?? env.windir ?? "C:\\Windows", "System32", name3);
22071
22217
  }
22072
22218
  async function installWindowsTask(options, deps = {}) {
22073
22219
  if ((deps.platform ?? process.platform) !== "win32")
@@ -22075,11 +22221,11 @@ async function installWindowsTask(options, deps = {}) {
22075
22221
  const run2 = deps.run ?? systemCommand;
22076
22222
  const env = deps.env ?? process.env;
22077
22223
  const launcherPath = windowsLauncherPath(options.stateDir);
22078
- await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(options.logPath), { recursive: true });
22224
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(options.logPath), { recursive: true });
22079
22225
  await writeFileAtomic(launcherPath, buildWindowsLauncher(options), 384);
22080
22226
  const user = env.USERNAME ?? (0, import_node_os.userInfo)().username;
22081
22227
  const userId = env.USERDOMAIN ? `${env.USERDOMAIN}\\${user}` : user;
22082
- const xmlPath = (0, import_node_path4.join)(options.stateDir, "conbridge-agent-task.xml");
22228
+ const xmlPath = (0, import_node_path3.join)(options.stateDir, "conbridge-agent-task.xml");
22083
22229
  const xml = buildWindowsTaskXml({ userId, launcherPath, wscriptPath: windowsSystemTool(env, "wscript.exe") });
22084
22230
  await (0, import_promises2.writeFile)(xmlPath, Buffer.concat([Buffer.from([255, 254]), Buffer.from(xml, "utf16le")]), { mode: 384 });
22085
22231
  try {
@@ -22102,7 +22248,8 @@ async function uninstallWindowsTask(stateDir, deps = {}) {
22102
22248
  const run2 = deps.run ?? systemCommand;
22103
22249
  const env = deps.env ?? process.env;
22104
22250
  const schtasks = windowsSystemTool(env, "schtasks.exe");
22105
- await run2(schtasks, ["/End", "/TN", WINDOWS_TASK_NAME]);
22251
+ if (deps.stopRunning !== false)
22252
+ await run2(schtasks, ["/End", "/TN", WINDOWS_TASK_NAME]);
22106
22253
  await run2(schtasks, ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"]);
22107
22254
  await (0, import_promises2.unlink)(windowsLauncherPath(stateDir)).catch((error63) => {
22108
22255
  if (errorCode2(error63) !== "ENOENT")
@@ -22136,11 +22283,11 @@ async function serviceLocation(stateDir, deps = {}) {
22136
22283
 
22137
22284
  // dist/state.js
22138
22285
  function protectedAgentPaths(stateDir, home = (0, import_node_os2.homedir)()) {
22139
- return [(0, import_node_path5.resolve)(stateDir), launchAgentPath(home), systemdUnitPath(home), SYSTEMD_SYSTEM_UNIT_PATH];
22286
+ return [(0, import_node_path4.resolve)(stateDir), launchAgentPath(home), systemdUnitPath(home), SYSTEMD_SYSTEM_UNIT_PATH];
22140
22287
  }
22141
22288
  var BROAD_SYSTEM_DIRS = Object.freeze(["/", "/System", "/Library", "/usr", "/bin", "/sbin", "/etc", "/private", "/var", "/tmp", "/Volumes"]);
22142
22289
  function windowsSystemDirs(env) {
22143
- const dirs = [env.SystemRoot, env.windir, env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramData, env.PUBLIC ? import_node_path5.win32.dirname(env.PUBLIC) : void 0];
22290
+ const dirs = [env.SystemRoot, env.windir, env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramData, env.PUBLIC ? import_node_path4.win32.dirname(env.PUBLIC) : void 0];
22144
22291
  return [...new Set(dirs.filter((dir) => typeof dir === "string" && dir.length > 2))];
22145
22292
  }
22146
22293
  async function broadRootReason(rootReal, context) {
@@ -22165,16 +22312,16 @@ var MAX_ROOTS = 64;
22165
22312
  function resolveStateDir(env = process.env) {
22166
22313
  const configured = env.CONBRIDGE_AGENT_HOME;
22167
22314
  if (configured && configured.trim() !== "")
22168
- return (0, import_node_path5.resolve)(configured);
22169
- return (0, import_node_path5.join)((0, import_node_os2.homedir)(), ".conbridge", "agent");
22315
+ return (0, import_node_path4.resolve)(configured);
22316
+ return (0, import_node_path4.join)((0, import_node_os2.homedir)(), ".conbridge", "agent");
22170
22317
  }
22171
22318
  function statePaths(dir) {
22172
22319
  return {
22173
22320
  dir,
22174
- identity: (0, import_node_path5.join)(dir, "identity.json"),
22175
- key: (0, import_node_path5.join)(dir, "device-key.pem"),
22176
- config: (0, import_node_path5.join)(dir, "config.json"),
22177
- journal: (0, import_node_path5.join)(dir, "journal.jsonl")
22321
+ identity: (0, import_node_path4.join)(dir, "identity.json"),
22322
+ key: (0, import_node_path4.join)(dir, "device-key.pem"),
22323
+ config: (0, import_node_path4.join)(dir, "config.json"),
22324
+ journal: (0, import_node_path4.join)(dir, "journal.jsonl")
22178
22325
  };
22179
22326
  }
22180
22327
  async function ensureStateDir(dir) {
@@ -22189,7 +22336,7 @@ var keyStoreDescriptorSchema = external_exports.discriminatedUnion("type", [
22189
22336
  type: external_exports.literal("keychain"),
22190
22337
  key_id: external_exports.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),
22191
22338
  /** A specific keychain file (tests, advanced setups); the user's default Keychain when absent. */
22192
- keychain: external_exports.string().min(1).max(1024).refine((value) => (0, import_node_path5.isAbsolute)(value), "Keychain path must be absolute").optional()
22339
+ keychain: external_exports.string().min(1).max(1024).refine((value) => (0, import_node_path4.isAbsolute)(value), "Keychain path must be absolute").optional()
22193
22340
  })
22194
22341
  ]);
22195
22342
  var identitySchema = external_exports.strictObject({
@@ -22203,11 +22350,15 @@ var identitySchema = external_exports.strictObject({
22203
22350
  platform: external_exports.enum(["macos", "linux", "windows"]),
22204
22351
  fingerprint: external_exports.string().regex(/^[0-9a-f]{4}(-[0-9a-f]{4}){3}$/),
22205
22352
  paired_at: external_exports.iso.datetime({ offset: true }),
22353
+ connection_mode: external_exports.enum(["persistent", "passive", "timed", "ephemeral"]).optional(),
22354
+ expires_at_ms: external_exports.number().int().nonnegative().nullable().optional(),
22355
+ destroy_task_id: external_exports.string().uuid().nullable().optional(),
22356
+ destroy_deadline_ms: external_exports.number().int().nonnegative().nullable().optional(),
22206
22357
  key_store: keyStoreDescriptorSchema.optional()
22207
22358
  });
22208
22359
  var rootSchema = external_exports.strictObject({
22209
22360
  root_id: external_exports.uuid(),
22210
- path: external_exports.string().min(1).refine((value) => (0, import_node_path5.isAbsolute)(value), "Root path must be absolute"),
22361
+ path: external_exports.string().min(1).refine((value) => (0, import_node_path4.isAbsolute)(value), "Root path must be absolute"),
22211
22362
  label: external_exports.string().min(1).max(128),
22212
22363
  writable: external_exports.boolean()
22213
22364
  });
@@ -22269,7 +22420,7 @@ async function saveConfig(paths, config2) {
22269
22420
  }
22270
22421
  async function addRoot(paths, input2) {
22271
22422
  const config2 = await loadConfig(paths);
22272
- const absolute = (0, import_node_path5.resolve)(input2.path);
22423
+ const absolute = (0, import_node_path4.resolve)(input2.path);
22273
22424
  const real = await (0, import_promises3.realpath)(absolute);
22274
22425
  const info = await (0, import_promises3.stat)(real);
22275
22426
  if (!info.isDirectory())
@@ -22301,7 +22452,7 @@ async function removeRoot(paths, rootId) {
22301
22452
  }
22302
22453
 
22303
22454
  // dist/keystore.js
22304
- var import_node_path6 = require("node:path");
22455
+ var import_node_path5 = require("node:path");
22305
22456
  var NodeEd25519Key = class {
22306
22457
  #privateKey;
22307
22458
  #publicRaw;
@@ -22343,7 +22494,7 @@ var FileKeyStore = class {
22343
22494
  async create() {
22344
22495
  const { privateKey } = (0, import_node_crypto3.generateKeyPairSync)("ed25519");
22345
22496
  const pem = privateKey.export({ format: "pem", type: "pkcs8" });
22346
- await ensureStateDir((0, import_node_path6.dirname)(this.#path));
22497
+ await ensureStateDir((0, import_node_path5.dirname)(this.#path));
22347
22498
  await writeFileAtomic(this.#path, typeof pem === "string" ? pem : pem.toString("utf8"), 384);
22348
22499
  return new NodeEd25519Key(privateKey);
22349
22500
  }
@@ -22362,121 +22513,674 @@ function keyFingerprint(rawPublicKey) {
22362
22513
  return hex3.match(/.{4}/g).join("-");
22363
22514
  }
22364
22515
 
22365
- // dist/pairing.js
22366
- var PAIRING_CODE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}-?[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/;
22367
- var DEFAULT_GATEWAY_URL = "https://mcp.conbridge.app";
22368
- function currentPlatform() {
22369
- if (process.platform === "darwin")
22370
- return "macos";
22371
- if (process.platform === "win32")
22372
- return "windows";
22373
- return "linux";
22374
- }
22375
- var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
22376
- function normalizeGatewayUrl(input2) {
22377
- let url2;
22378
- try {
22379
- url2 = new URL(input2);
22380
- } catch {
22381
- throw new Error("Gateway URL is invalid");
22382
- }
22383
- if (url2.protocol !== "https:" && !(url2.protocol === "http:" && LOOPBACK.has(url2.hostname))) {
22384
- throw new Error("Gateway URL must use https (http is allowed only for 127.0.0.1/localhost)");
22385
- }
22386
- if (url2.username || url2.password)
22387
- throw new Error("Gateway URL must not contain credentials");
22388
- return url2.origin;
22389
- }
22390
- function normalizePairingCode(input2) {
22391
- const code = input2.trim().toUpperCase();
22392
- if (!PAIRING_CODE.test(code))
22393
- throw new Error("Pairing code must look like XXXX-XXXX");
22394
- return code.includes("-") ? code : `${code.slice(0, 4)}-${code.slice(4)}`;
22395
- }
22396
- var POLL_TOKEN_HEADER = "X-ConBridge-Poll-Token";
22397
- var offerResponseSchema = external_exports.object({ pairing_id: external_exports.string().min(1).max(128), poll_token: external_exports.string().min(16).max(512) });
22398
- var statusResponseSchema = external_exports.discriminatedUnion("state", [
22399
- external_exports.object({
22400
- state: external_exports.literal("approved"),
22401
- tenant_id: external_exports.string().min(1).max(128),
22402
- device_uuid: external_exports.uuid(),
22403
- user_id: external_exports.string().min(1).max(128),
22404
- gateway_public_key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/),
22405
- display_name: external_exports.string().min(1).max(128).optional()
22406
- }),
22407
- external_exports.object({ state: external_exports.enum(["open", "offered", "pending"]) }),
22408
- external_exports.object({ state: external_exports.enum(["denied", "expired"]) })
22409
- ]);
22410
- var PairingError = class extends Error {
22411
- state;
22412
- constructor(state2, message) {
22516
+ // dist/keychain.js
22517
+ var KEYCHAIN_HELPER_NAME = "conbridge-agent-keychain";
22518
+ var HELPER_TIMEOUT_MS = 15e3;
22519
+ var MAX_HELPER_BYTES = 64 * 1024 * 1024;
22520
+ var KeychainError = class extends Error {
22521
+ code;
22522
+ constructor(code, message) {
22413
22523
  super(message);
22414
- this.name = "PairingError";
22415
- this.state = state2;
22524
+ this.name = "KeychainError";
22525
+ this.code = code;
22416
22526
  }
22417
22527
  };
22418
- async function jsonOrThrow(response, what) {
22419
- let body;
22528
+ function keychainHelperCandidates(env = process.env, codeDir = codeDirectory()) {
22529
+ const candidates = [];
22530
+ const override = env.CONBRIDGE_KEYCHAIN_HELPER;
22531
+ if (override && override.trim() !== "")
22532
+ candidates.push((0, import_node_path6.resolve)(override));
22533
+ candidates.push((0, import_node_path6.join)(codeDir, KEYCHAIN_HELPER_NAME));
22534
+ candidates.push((0, import_node_path6.join)(codeDir, "..", "native", "macos-keychain", ".build", "release", KEYCHAIN_HELPER_NAME));
22535
+ return candidates;
22536
+ }
22537
+ async function verifyKeychainHelper(path, expectedSha256 = BUILD_INFO?.keychain_helper_sha256 ?? null) {
22538
+ if (!(0, import_node_path6.isAbsolute)(path))
22539
+ throw new KeychainError("HELPER_INVALID", "Keychain helper path must be absolute");
22540
+ let real;
22420
22541
  try {
22421
- body = await response.json();
22542
+ real = await (0, import_promises5.realpath)(path);
22422
22543
  } catch {
22423
- body = void 0;
22544
+ throw new KeychainError("HELPER_INVALID", "Keychain helper not found");
22424
22545
  }
22425
- if (!response.ok) {
22426
- const message = body && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : `HTTP ${response.status}`;
22427
- throw new PairingError("http_error", `${what} failed: ${message}`);
22546
+ const info = await (0, import_promises5.stat)(real);
22547
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
22548
+ if (!info.isFile() || info.size < 1024 || info.size > MAX_HELPER_BYTES)
22549
+ throw new KeychainError("HELPER_INVALID", "Keychain helper is not a regular executable");
22550
+ if ((info.mode & 18) !== 0 || (info.mode & 64) === 0)
22551
+ throw new KeychainError("HELPER_INVALID", "Keychain helper has unsafe permissions");
22552
+ if (info.uid !== uid && info.uid !== 0)
22553
+ throw new KeychainError("HELPER_INVALID", "Keychain helper is owned by another user");
22554
+ if (expectedSha256 !== null) {
22555
+ const digest = (0, import_node_crypto4.createHash)("sha256").update(await (0, import_promises5.readFile)(real)).digest("hex");
22556
+ if (digest !== expectedSha256)
22557
+ throw new KeychainError("HELPER_INVALID", "Keychain helper does not match this build");
22428
22558
  }
22429
- return body;
22559
+ return real;
22430
22560
  }
22431
- async function pairDevice(options) {
22432
- const gateway = normalizeGatewayUrl(options.gatewayUrl);
22433
- const code = normalizePairingCode(options.code);
22434
- const name3 = options.name.trim();
22435
- if (name3.length < 1 || name3.length > 128)
22436
- throw new Error("Device name must be 1 to 128 characters");
22437
- const platform2 = options.platform ?? currentPlatform();
22438
- const doFetch = options.fetch ?? ((input2, init) => fetch(input2, init));
22439
- const sleep = options.sleep ?? ((ms) => new Promise((resolve8) => setTimeout(resolve8, ms)));
22440
- const key = await options.keyStore.create();
22441
- const fingerprint = keyFingerprint(key.publicKeyRaw());
22442
- let succeeded = false;
22443
- try {
22444
- const offer = offerResponseSchema.parse(await jsonOrThrow(await doFetch(`${gateway}/v1/agent/pair/offer`, {
22445
- method: "POST",
22446
- headers: { "content-type": "application/json" },
22447
- body: JSON.stringify({ code, public_key: publicKeyB64u(key), display_name: name3, platform: platform2 })
22448
- }), "Pairing offer"));
22449
- options.onOffered?.({ fingerprint, pairing_id: offer.pairing_id });
22450
- const deadline = Date.now() + (options.timeoutMs ?? 11 * 6e4);
22451
- const query = new URLSearchParams({ pairing_id: offer.pairing_id }).toString();
22452
- const pollInit = { method: "GET", headers: { [POLL_TOKEN_HEADER]: offer.poll_token } };
22453
- while (Date.now() < deadline) {
22454
- const status = statusResponseSchema.parse(await jsonOrThrow(await doFetch(`${gateway}/v1/agent/pair/status?${query}`, pollInit), "Pairing status"));
22455
- if (status.state === "approved") {
22456
- if (fromBase64Url(status.gateway_public_key).byteLength !== 32)
22457
- throw new PairingError("invalid", "Gateway key is invalid");
22458
- const identity = {
22459
- version: 1,
22460
- device_uuid: status.device_uuid,
22461
- tenant_id: status.tenant_id,
22462
- user_id: status.user_id,
22463
- gateway_url: gateway,
22464
- gateway_public_key: status.gateway_public_key,
22465
- display_name: status.display_name ?? name3,
22466
- platform: platform2,
22467
- fingerprint,
22468
- paired_at: (/* @__PURE__ */ new Date()).toISOString(),
22469
- key_store: options.keyStore.descriptor
22470
- };
22471
- await options.onApproved?.();
22472
- await saveIdentity(options.paths, identity);
22473
- succeeded = true;
22474
- return identity;
22475
- }
22476
- if (status.state === "denied" || status.state === "expired") {
22477
- throw new PairingError(status.state, status.state === "denied" ? "Pairing was denied in the Console" : "Pairing code expired");
22478
- }
22479
- await sleep(options.pollIntervalMs ?? 2e3);
22561
+ var helperCache = /* @__PURE__ */ new Map();
22562
+ async function findKeychainHelper(options = {}) {
22563
+ if ((options.platform ?? process.platform) !== "darwin")
22564
+ return null;
22565
+ const candidates = keychainHelperCandidates(options.env ?? process.env, options.codeDir ?? codeDirectory());
22566
+ const cacheKey = candidates.join("\0");
22567
+ if (helperCache.has(cacheKey))
22568
+ return helperCache.get(cacheKey) ?? null;
22569
+ let found = null;
22570
+ for (const candidate of candidates) {
22571
+ try {
22572
+ found = await verifyKeychainHelper(candidate);
22573
+ break;
22574
+ } catch {
22575
+ }
22576
+ }
22577
+ helperCache.set(cacheKey, found);
22578
+ return found;
22579
+ }
22580
+ function runHelper(options, command2, keyId, input2) {
22581
+ const args = [...options.keychainPath ? ["--keychain", options.keychainPath] : [], command2, keyId];
22582
+ return new Promise((resolvePromise, reject) => {
22583
+ const child = (0, import_node_child_process2.execFile)(options.helperPath, args, {
22584
+ encoding: "utf8",
22585
+ timeout: options.timeoutMs ?? HELPER_TIMEOUT_MS,
22586
+ maxBuffer: 4096,
22587
+ windowsHide: true,
22588
+ env: { PATH: "/usr/bin:/bin", HOME: process.env.HOME ?? "", TMPDIR: process.env.TMPDIR ?? "/tmp" }
22589
+ }, (error63, stdout) => {
22590
+ if (error63) {
22591
+ const exitCode = typeof error63.code === "number" ? error63.code : null;
22592
+ if (exitCode === 3)
22593
+ return reject(new KeychainError("NOT_FOUND", "Device key is not in the Keychain"));
22594
+ if (exitCode === 1)
22595
+ return reject(new KeychainError("DENIED", "Keychain refused the request (locked, access denied or invalid request)"));
22596
+ return reject(new KeychainError("HELPER_FAILED", "Keychain helper failed to run"));
22597
+ }
22598
+ const lines4 = stdout.split("\n");
22599
+ if (lines4.length !== 2 || lines4[1] !== "" || lines4[0].length > 1024) {
22600
+ return reject(new KeychainError("HELPER_FAILED", "Keychain helper returned unexpected output"));
22601
+ }
22602
+ try {
22603
+ resolvePromise(JSON.parse(lines4[0]));
22604
+ } catch {
22605
+ reject(new KeychainError("HELPER_FAILED", "Keychain helper returned unexpected output"));
22606
+ }
22607
+ });
22608
+ child.stdin?.on("error", () => void 0);
22609
+ child.stdin?.end(input2 ? Buffer.from(input2) : void 0);
22610
+ });
22611
+ }
22612
+ var b64u32 = external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/);
22613
+ var publicIdentitySchema = external_exports.strictObject({
22614
+ deviceUuid: external_exports.string(),
22615
+ publicKeyB64: b64u32,
22616
+ fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9_-]{43}$/)
22617
+ });
22618
+ var signatureSchema = external_exports.strictObject({ signature: external_exports.string().regex(/^[A-Za-z0-9_-]{86}$/) });
22619
+ var deletedSchema = external_exports.strictObject({ deleted: external_exports.literal(true) });
22620
+ function parsePublic(value, keyId) {
22621
+ const parsed = publicIdentitySchema.safeParse(value);
22622
+ if (!parsed.success || parsed.data.deviceUuid !== keyId)
22623
+ throw new KeychainError("HELPER_FAILED", "Keychain helper returned an invalid identity");
22624
+ const raw = Buffer.from(parsed.data.publicKeyB64, "base64url");
22625
+ const digest = (0, import_node_crypto4.createHash)("sha256").update(raw).digest("base64url");
22626
+ if (raw.length !== 32 || parsed.data.fingerprint !== `SHA256:${digest}`) {
22627
+ throw new KeychainError("HELPER_FAILED", "Keychain helper returned an inconsistent identity");
22628
+ }
22629
+ return new Uint8Array(raw);
22630
+ }
22631
+ var KEY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
22632
+ var KeychainDeviceKey = class {
22633
+ #run;
22634
+ #keyId;
22635
+ #publicRaw;
22636
+ constructor(run2, keyId, publicRaw) {
22637
+ this.#run = run2;
22638
+ this.#keyId = keyId;
22639
+ this.#publicRaw = publicRaw;
22640
+ }
22641
+ publicKeyRaw() {
22642
+ return new Uint8Array(this.#publicRaw);
22643
+ }
22644
+ async sign(message) {
22645
+ const parsed = signatureSchema.safeParse(await runHelper(this.#run, "sign", this.#keyId, message));
22646
+ if (!parsed.success)
22647
+ throw new KeychainError("HELPER_FAILED", "Keychain helper returned an invalid signature");
22648
+ const signature = new Uint8Array(Buffer.from(parsed.data.signature, "base64url"));
22649
+ const publicKey = (0, import_node_crypto4.createPublicKey)({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(this.#publicRaw).toString("base64url") }, format: "jwk" });
22650
+ if (!(0, import_node_crypto4.verify)(null, message, publicKey, signature))
22651
+ throw new KeychainError("HELPER_FAILED", "Keychain signature does not verify");
22652
+ return signature;
22653
+ }
22654
+ };
22655
+ var KeychainKeyStore = class {
22656
+ #run;
22657
+ #keyId;
22658
+ #keychainPath;
22659
+ constructor(options) {
22660
+ if (!KEY_ID.test(options.keyId))
22661
+ throw new KeychainError("HELPER_INVALID", "Keychain key id must be a lowercase UUID");
22662
+ if (options.keychainPath !== void 0 && !(0, import_node_path6.isAbsolute)(options.keychainPath)) {
22663
+ throw new KeychainError("HELPER_INVALID", "Keychain path must be absolute");
22664
+ }
22665
+ this.#keyId = options.keyId;
22666
+ this.#keychainPath = options.keychainPath;
22667
+ this.#run = {
22668
+ helperPath: options.helperPath,
22669
+ ...options.keychainPath !== void 0 ? { keychainPath: options.keychainPath } : {},
22670
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
22671
+ };
22672
+ }
22673
+ get descriptor() {
22674
+ return { type: "keychain", key_id: this.#keyId, ...this.#keychainPath !== void 0 ? { keychain: this.#keychainPath } : {} };
22675
+ }
22676
+ async load() {
22677
+ let output2;
22678
+ try {
22679
+ output2 = await runHelper(this.#run, "inspect", this.#keyId);
22680
+ } catch (error63) {
22681
+ if (error63 instanceof KeychainError && error63.code === "NOT_FOUND")
22682
+ return null;
22683
+ throw error63;
22684
+ }
22685
+ return new KeychainDeviceKey(this.#run, this.#keyId, parsePublic(output2, this.#keyId));
22686
+ }
22687
+ async create() {
22688
+ await this.remove();
22689
+ const output2 = await runHelper(this.#run, "create", this.#keyId);
22690
+ return new KeychainDeviceKey(this.#run, this.#keyId, parsePublic(output2, this.#keyId));
22691
+ }
22692
+ async remove() {
22693
+ if (!deletedSchema.safeParse(await runHelper(this.#run, "delete", this.#keyId)).success) {
22694
+ throw new KeychainError("HELPER_FAILED", "Keychain helper returned unexpected output");
22695
+ }
22696
+ }
22697
+ };
22698
+ function chooseKeyStoreType(requested, helperPath, platform2 = process.platform) {
22699
+ if (requested !== void 0 && requested !== "keychain" && requested !== "file") {
22700
+ throw new Error("--key-store must be keychain or file");
22701
+ }
22702
+ if (requested === "file")
22703
+ return "file";
22704
+ if (requested === "keychain") {
22705
+ if (platform2 !== "darwin")
22706
+ throw new Error("The Keychain key store is only available on macOS");
22707
+ if (helperPath === null)
22708
+ throw new Error("The Keychain helper (conbridge-agent-keychain) was not found or failed verification; build it or use --key-store file");
22709
+ return "keychain";
22710
+ }
22711
+ return platform2 === "darwin" && helperPath !== null ? "keychain" : "file";
22712
+ }
22713
+ async function openKeyStore(paths, descriptor, options = {}) {
22714
+ if (!descriptor || descriptor.type === "file")
22715
+ return new FileKeyStore(paths.key);
22716
+ const helperPath = options.helperPath !== void 0 ? options.helperPath : await findKeychainHelper({ ...options.env ? { env: options.env } : {}, ...options.platform ? { platform: options.platform } : {} });
22717
+ if (helperPath === null) {
22718
+ throw new KeychainError("HELPER_INVALID", "This identity keeps its key in the Keychain, but no valid Keychain helper (conbridge-agent-keychain) was found (it must exist next to the agent, not be writable by others and match this build)");
22719
+ }
22720
+ return new KeychainKeyStore({
22721
+ helperPath,
22722
+ keyId: descriptor.key_id,
22723
+ ...descriptor.keychain !== void 0 ? { keychainPath: descriptor.keychain } : {}
22724
+ });
22725
+ }
22726
+
22727
+ // dist/purge.js
22728
+ var ownRemove = async (path) => {
22729
+ await (0, import_promises6.rm)(path, { recursive: true, force: true });
22730
+ };
22731
+ var exists = async (path) => (0, import_promises6.access)(path).then(() => true, () => false);
22732
+ function safeStateDir(stateDir, home, platform2 = process.platform) {
22733
+ const pathApi = platform2 === "win32" ? import_node_path7.win32 : { resolve: import_node_path7.resolve, dirname: import_node_path7.dirname, join: import_node_path7.join, sep: "/" };
22734
+ const dir = pathApi.resolve(stateDir);
22735
+ const homeDir = pathApi.resolve(home);
22736
+ if (dir === pathApi.dirname(dir) || dir === homeDir || homeDir.startsWith(dir + pathApi.sep) || dir === pathApi.join(homeDir, ".conbridge")) {
22737
+ throw new Error("Refusing to purge a directory that is not an agent state directory");
22738
+ }
22739
+ return dir;
22740
+ }
22741
+ var STATE_ENTRY = /^(?:identity\.json|device-key\.pem|config\.json|journal\.jsonl|hosts\.json|known_hosts|agent\.lock|supervisor\.pid|conbridge-agent-service\.vbs|runtime|ssh|\.(?:identity\.json|device-key\.pem|config\.json|journal\.jsonl|hosts\.json)\.[A-Za-z0-9_-]+\.tmp)$/;
22742
+ async function stateEntries(stateDir, dedicated, keepRuntime, pathApi) {
22743
+ const names = await (0, import_promises6.readdir)(stateDir).catch((error63) => {
22744
+ if (error63.code === "ENOENT")
22745
+ return [];
22746
+ throw error63;
22747
+ });
22748
+ return names.filter((name3) => (dedicated || STATE_ENTRY.test(name3)) && !(keepRuntime && name3 === "runtime")).map((name3) => pathApi.join(stateDir, name3));
22749
+ }
22750
+ function boundedCommand(signal) {
22751
+ return (file2, args) => new Promise((done) => {
22752
+ if (signal?.aborted)
22753
+ return done({ ok: false, output: "purge time limit reached" });
22754
+ (0, import_node_child_process3.execFile)(file2, args, { timeout: 1e4, windowsHide: true, ...signal ? { signal } : {} }, (error63, stdout, stderr) => {
22755
+ done({ ok: !error63, output: `${stdout}${stderr}`.trim() });
22756
+ });
22757
+ });
22758
+ }
22759
+ function boundedCronWriter(signal) {
22760
+ return (text6) => new Promise((done) => {
22761
+ if (signal?.aborted)
22762
+ return done({ ok: false, output: "purge time limit reached" });
22763
+ const child = (0, import_node_child_process3.execFile)("crontab", ["-"], { timeout: 1e4, ...signal ? { signal } : {} }, (error63, stdout, stderr) => {
22764
+ done({ ok: !error63, output: `${stdout}${stderr}`.trim() });
22765
+ });
22766
+ child.stdin?.on("error", () => void 0);
22767
+ child.stdin?.end(text6);
22768
+ });
22769
+ }
22770
+ async function removeAgentAutostart(stateDir = resolveStateDir(), deps = {}, signal) {
22771
+ const platform2 = deps.platform ?? process.platform;
22772
+ const run2 = deps.run ?? boundedCommand(signal);
22773
+ const serviceDeps = { stopRunning: false, ...deps, platform: platform2, run: run2, launchctl: deps.launchctl ?? ((args) => run2("/bin/launchctl", args)) };
22774
+ const failures = [];
22775
+ const attempt = async (operation) => {
22776
+ if (signal?.aborted)
22777
+ return;
22778
+ try {
22779
+ await operation();
22780
+ } catch (error63) {
22781
+ failures.push(error63);
22782
+ }
22783
+ };
22784
+ if (platform2 === "darwin")
22785
+ await attempt(() => uninstallLaunchAgent(serviceDeps));
22786
+ if (platform2 === "linux") {
22787
+ await attempt(() => uninstallSystemdService({ ...serviceDeps, uid: 1 }));
22788
+ await attempt(() => uninstallSystemdService({ ...serviceDeps, uid: 0 }));
22789
+ await attempt(() => uninstallCronService({ ...serviceDeps, writeCrontab: deps.writeCrontab ?? boundedCronWriter(signal) }));
22790
+ }
22791
+ if (platform2 === "win32")
22792
+ await attempt(() => uninstallWindowsTask(stateDir, serviceDeps));
22793
+ if (failures.length)
22794
+ throw new AggregateError(failures, "Some autostart files could not be removed");
22795
+ }
22796
+ async function removeAgentIdentity(options = {}, deps = {}) {
22797
+ const stateDir = safeStateDir(options.stateDir ?? deps.env?.CONBRIDGE_AGENT_HOME ?? (0, import_node_path7.join)(deps.home ?? (0, import_node_os3.homedir)(), ".conbridge", "agent"), deps.home ?? (0, import_node_os3.homedir)(), deps.platform);
22798
+ const paths = statePaths(stateDir);
22799
+ const identity = await (deps.loadIdentity ?? loadIdentity)(paths);
22800
+ const failures = [];
22801
+ if (identity) {
22802
+ try {
22803
+ await (await storeFor(paths, identity, deps)).remove();
22804
+ } catch (error63) {
22805
+ failures.push(error63);
22806
+ }
22807
+ }
22808
+ for (const path of [paths.key, paths.identity]) {
22809
+ try {
22810
+ await (deps.remove ?? ownRemove)(path);
22811
+ } catch (error63) {
22812
+ failures.push(error63);
22813
+ }
22814
+ }
22815
+ if (failures.length)
22816
+ throw new AggregateError(failures, "Some identity files could not be removed");
22817
+ }
22818
+ function storeFor(paths, identity, deps) {
22819
+ return deps.openStore ? deps.openStore(paths, identity) : openKeyStore(paths, identity.key_store, {
22820
+ ...deps.env ? { env: deps.env } : {},
22821
+ ...deps.platform ? { platform: deps.platform } : {}
22822
+ });
22823
+ }
22824
+ function agentLeaveMessage(body) {
22825
+ return JSON.stringify({ device_uuid: body.device_uuid, nonce: body.nonce, ts: body.ts });
22826
+ }
22827
+ async function purgeAgent(options, deps = {}) {
22828
+ const platform2 = deps.platform ?? process.platform;
22829
+ const home = deps.home ?? (0, import_node_os3.homedir)();
22830
+ const stateDir = safeStateDir(options.stateDir ?? deps.env?.CONBRIDGE_AGENT_HOME ?? (0, import_node_path7.join)(deps.home ?? (0, import_node_os3.homedir)(), ".conbridge", "agent"), home, platform2);
22831
+ const paths = statePaths(stateDir);
22832
+ const report = deps.report ?? ((line) => console.log(line));
22833
+ const remove = deps.remove ?? ownRemove;
22834
+ const has = deps.exists ?? exists;
22835
+ const steps = [];
22836
+ const leftovers = [];
22837
+ let identity = null;
22838
+ let deferred = false;
22839
+ const start = Date.now();
22840
+ const totalLimit = Math.min(deps.totalTimeoutMs ?? 3e4, 3e4);
22841
+ const stepLimit = Math.min(deps.stepTimeoutMs ?? 1e4, 1e4);
22842
+ const step = async (name3, operation) => {
22843
+ const budget = Math.max(1, Math.min(stepLimit, Math.floor((totalLimit - (Date.now() - start)) / (6 - steps.length))));
22844
+ const controller = new AbortController();
22845
+ let timer;
22846
+ try {
22847
+ await Promise.race([
22848
+ operation(controller.signal),
22849
+ new Promise((_, reject) => {
22850
+ timer = setTimeout(() => {
22851
+ controller.abort();
22852
+ reject(new Error("time limit reached"));
22853
+ }, budget);
22854
+ })
22855
+ ]);
22856
+ steps.push({ step: name3, ok: true });
22857
+ } catch (error63) {
22858
+ const message = error63 instanceof Error ? error63.message : String(error63);
22859
+ steps.push({ step: name3, ok: false, error: message });
22860
+ report(`ConBridge purge: ${name3}: ${message}`);
22861
+ } finally {
22862
+ if (timer)
22863
+ clearTimeout(timer);
22864
+ }
22865
+ };
22866
+ await step("leave", async (signal) => {
22867
+ identity = await (deps.loadIdentity ?? loadIdentity)(paths);
22868
+ if (!identity || signal.aborted)
22869
+ return;
22870
+ const key = await (await storeFor(paths, identity, deps)).load();
22871
+ if (!key || signal.aborted)
22872
+ return;
22873
+ const body = { device_uuid: identity.device_uuid, nonce: (0, import_node_crypto5.randomBytes)(32).toString("base64url"), ts: Date.now() };
22874
+ const signature = toBase64Url(await key.sign(new TextEncoder().encode(agentLeaveMessage(body))));
22875
+ if (signal.aborted)
22876
+ return;
22877
+ const response = await (deps.fetch ?? globalThis.fetch)(new URL("/v1/agent/leave", identity.gateway_url), {
22878
+ method: "POST",
22879
+ headers: { "Content-Type": "application/json", "X-ConBridge-Signature": signature },
22880
+ body: agentLeaveMessage(body),
22881
+ signal
22882
+ });
22883
+ if (!response.ok)
22884
+ throw new Error(`Gateway leave returned HTTP ${response.status}`);
22885
+ await response.body?.cancel();
22886
+ });
22887
+ await step("keep-awake", async () => {
22888
+ await options.stopKeepAwake?.();
22889
+ });
22890
+ await step("autostart", async (signal) => {
22891
+ await removeAgentAutostart(stateDir, deps, signal);
22892
+ });
22893
+ await step("keychain", async (signal) => {
22894
+ if (!identity)
22895
+ identity = await (deps.loadIdentity ?? loadIdentity)(paths);
22896
+ if (platform2 === "darwin" && identity?.key_store?.type === "keychain" && !signal.aborted) {
22897
+ await (await storeFor(paths, identity, deps)).remove();
22898
+ }
22899
+ });
22900
+ const pathApi = platform2 === "win32" ? import_node_path7.win32 : import_node_path7.posix;
22901
+ const dedicated = pathApi.resolve(stateDir) === pathApi.resolve(pathApi.join(home, ".conbridge", "agent"));
22902
+ await step("files", async (signal) => {
22903
+ const parentInfo = await (0, import_promises6.lstat)(pathApi.join(home, ".conbridge")).catch((error63) => {
22904
+ if (error63.code === "ENOENT")
22905
+ return null;
22906
+ throw error63;
22907
+ });
22908
+ if (parentInfo?.isSymbolicLink())
22909
+ throw new Error("Refusing to traverse a symlink at ~/.conbridge");
22910
+ if (options.keepRuntime && (await (0, import_promises6.lstat)(stateDir).catch(() => null))?.isSymbolicLink()) {
22911
+ throw new Error("Refusing to traverse a symlink at the agent state directory");
22912
+ }
22913
+ if (!dedicated && (await (0, import_promises6.lstat)(stateDir).catch(() => null))?.isSymbolicLink()) {
22914
+ throw new Error("Refusing to traverse a symlink at the agent state directory");
22915
+ }
22916
+ const targets = options.keepRuntime ? [] : [pathApi.join(home, ".conbridge", "node"), pathApi.join(home, ".conbridge", "bin")];
22917
+ if (options.keepRuntime || !dedicated)
22918
+ targets.unshift(...await stateEntries(stateDir, dedicated, options.keepRuntime ?? false, pathApi));
22919
+ else
22920
+ targets.unshift(stateDir);
22921
+ const removeEmptyDir = !dedicated && !options.keepRuntime;
22922
+ if (platform2 === "win32" && targets.length > 0) {
22923
+ if (targets.some((path) => /["%\r\n!&|<>^]/.test(path)))
22924
+ throw new Error("Unsupported character in deferred deletion path");
22925
+ if (/["%\r\n!&|<>^]/.test(stateDir))
22926
+ throw new Error("Unsupported character in deferred deletion path");
22927
+ const command2 = `powershell.exe -NoProfile -NonInteractive -Command "Wait-Process -Id ${process.pid} -ErrorAction SilentlyContinue" >nul 2>nul & ${targets.map((path) => `if exist "${path}" (rmdir /s /q "${path}" 2>nul & del /f /q "${path}" 2>nul)`).join(" & ")}${removeEmptyDir ? ` & rmdir "${stateDir}" 2>nul` : ""}`;
22928
+ if (signal.aborted)
22929
+ return;
22930
+ const launch = deps.spawnDetached ?? ((file2, args) => new Promise((resolve9, reject) => {
22931
+ const child = (0, import_node_child_process3.spawn)(file2, args, { detached: true, stdio: "ignore", windowsHide: true });
22932
+ child.once("error", reject);
22933
+ child.once("spawn", () => {
22934
+ child.unref();
22935
+ resolve9();
22936
+ });
22937
+ }));
22938
+ await launch("cmd.exe", ["/d", "/s", "/c", command2]);
22939
+ deferred = true;
22940
+ report("ConBridge files will be deleted after the agent exits.");
22941
+ return;
22942
+ }
22943
+ const failures = [];
22944
+ for (const path of targets) {
22945
+ if (signal.aborted)
22946
+ break;
22947
+ try {
22948
+ await remove(path);
22949
+ } catch (error63) {
22950
+ failures.push(error63);
22951
+ }
22952
+ }
22953
+ if (removeEmptyDir && !signal.aborted) {
22954
+ await (0, import_promises6.rmdir)(stateDir).catch((error63) => {
22955
+ if (error63.code !== "ENOENT" && error63.code !== "ENOTEMPTY" && error63.code !== "EEXIST")
22956
+ failures.push(error63);
22957
+ });
22958
+ }
22959
+ if (failures.length)
22960
+ throw new AggregateError(failures, "Some ConBridge files could not be removed");
22961
+ });
22962
+ await step("leftovers", async (signal) => {
22963
+ if (platform2 === "darwin" && await has("/usr/local/lib/conbridge-agent/uninstall.sh")) {
22964
+ leftovers.push("sudo /usr/local/lib/conbridge-agent/uninstall.sh");
22965
+ }
22966
+ const quote = (path) => `'${path.replace(/'/g, "'\\''")}'`;
22967
+ if (platform2 === "linux") {
22968
+ if (await has(systemdUnitPath(home)))
22969
+ leftovers.push(`systemctl --user disable --now conbridge-agent.service; rm -f -- ${quote(systemdUnitPath(home))}; systemctl --user daemon-reload`);
22970
+ const systemUnit = deps.systemUnitPath ?? SYSTEMD_SYSTEM_UNIT_PATH;
22971
+ if (await has(systemUnit))
22972
+ leftovers.push(`sudo systemctl disable --now conbridge-agent.service; sudo rm -f -- ${quote(systemUnit)}; sudo systemctl daemon-reload`);
22973
+ }
22974
+ if (platform2 === "darwin" && await has(launchAgentPath(home)))
22975
+ leftovers.push(`rm -f -- ${quote(launchAgentPath(home))}`);
22976
+ if (!deferred) {
22977
+ const owned = dedicated ? [stateDir] : await stateEntries(stateDir, false, options.keepRuntime ?? false, pathApi).catch(() => []);
22978
+ for (const path of [...owned, pathApi.join(home, ".conbridge", "node"), pathApi.join(home, ".conbridge", "bin")]) {
22979
+ if (signal.aborted)
22980
+ break;
22981
+ if (options.keepRuntime && (!owned.includes(path) || dedicated && await has(pathApi.join(stateDir, "runtime"))))
22982
+ continue;
22983
+ if (await has(path))
22984
+ leftovers.push(platform2 === "win32" ? `rmdir /s /q "${path}"` : `rm -rf -- ${quote(path)}`);
22985
+ }
22986
+ }
22987
+ for (const command2 of leftovers)
22988
+ report(`ConBridge files remain. To remove them, run: ${command2}`);
22989
+ });
22990
+ report(`ConBridge cleanup completed (${options.reason})${options.keepRuntime ? "; runtime kept" : ""}.`);
22991
+ return { steps, leftovers, deferred };
22992
+ }
22993
+
22994
+ // dist/cli.js
22995
+ var import_node_child_process11 = require("node:child_process");
22996
+ var import_node_crypto12 = require("node:crypto");
22997
+ var import_node_fs4 = require("node:fs");
22998
+ var import_promises17 = require("node:fs/promises");
22999
+ var import_node_os9 = require("node:os");
23000
+ var import_node_path18 = require("node:path");
23001
+ var import_node_url3 = require("node:url");
23002
+ var import_node_util2 = require("node:util");
23003
+
23004
+ // dist/confirm.js
23005
+ var import_node_child_process4 = require("node:child_process");
23006
+ var import_node_path8 = require("node:path");
23007
+ var CONFIRM_TIMEOUT_MS = 13e4;
23008
+ function confirmText(request) {
23009
+ const verb = request.created ? "create" : "overwrite";
23010
+ return `ConBridge wants to ${verb} "${request.path}" in root "${request.rootLabel}" (${request.bytes} bytes). This write was approved in the Console.`.replace(/[\r\n]+/g, " ");
23011
+ }
23012
+ function appleScriptString(value) {
23013
+ return '"' + value.replace(/[\\"]/g, "\\$&").replace(/[\r\n]+/g, " ") + '"';
23014
+ }
23015
+ function buildConfirmScript(request) {
23016
+ return `display dialog ${appleScriptString(confirmText(request))} with title "ConBridge" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" with icon caution giving up after 120`;
23017
+ }
23018
+ var macDialogConfirm = (request) => {
23019
+ if (process.platform !== "darwin")
23020
+ return Promise.resolve(false);
23021
+ return new Promise((resolve9) => {
23022
+ (0, import_node_child_process4.execFile)("/usr/bin/osascript", ["-e", buildConfirmScript(request)], { timeout: CONFIRM_TIMEOUT_MS }, (error63, stdout) => {
23023
+ if (error63)
23024
+ return resolve9(false);
23025
+ resolve9(/button returned:Allow/.test(stdout) && !/gave up:true/.test(stdout));
23026
+ });
23027
+ });
23028
+ };
23029
+ var WINDOWS_CONFIRM_SCRIPT = [
23030
+ "Add-Type -AssemblyName PresentationFramework",
23031
+ '$r = [System.Windows.MessageBox]::Show($env:CONBRIDGE_CONFIRM_TEXT, "ConBridge", "YesNo", "Warning", "No")',
23032
+ 'if ($r -eq "Yes") { exit 0 } else { exit 1 }'
23033
+ ].join("; ");
23034
+ var windowsConfirm = (request) => new Promise((resolve9) => {
23035
+ const powershell = import_node_path8.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
23036
+ (0, import_node_child_process4.execFile)(powershell, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WINDOWS_CONFIRM_SCRIPT], { timeout: CONFIRM_TIMEOUT_MS, windowsHide: false, env: { ...process.env, CONBRIDGE_CONFIRM_TEXT: confirmText(request) } }, (error63) => resolve9(!error63));
23037
+ });
23038
+ var linuxConfirm = (request) => new Promise((resolve9) => {
23039
+ if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
23040
+ return resolve9(false);
23041
+ const text6 = confirmText(request);
23042
+ (0, import_node_child_process4.execFile)("zenity", ["--question", "--title=ConBridge", `--text=${text6}`, "--ok-label=Allow", "--cancel-label=Deny", "--default-cancel", "--timeout=120"], { timeout: CONFIRM_TIMEOUT_MS }, (error63) => {
23043
+ if (!error63)
23044
+ return resolve9(true);
23045
+ if (error63.code !== "ENOENT")
23046
+ return resolve9(false);
23047
+ (0, import_node_child_process4.execFile)("kdialog", ["--title", "ConBridge", "--warningyesno", text6, "--yes-label", "Allow", "--no-label", "Deny"], { timeout: CONFIRM_TIMEOUT_MS }, (fallback) => resolve9(!fallback));
23048
+ });
23049
+ });
23050
+ var localConfirm = (request) => {
23051
+ if (process.platform === "darwin")
23052
+ return macDialogConfirm(request);
23053
+ if (process.platform === "win32")
23054
+ return windowsConfirm(request);
23055
+ if (process.platform === "linux")
23056
+ return linuxConfirm(request);
23057
+ return Promise.resolve(false);
23058
+ };
23059
+
23060
+ // dist/connect.js
23061
+ var import_node_child_process5 = require("node:child_process");
23062
+ var import_node_path9 = require("node:path");
23063
+
23064
+ // dist/pairing.js
23065
+ var PAIRING_CODE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}-?[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/;
23066
+ var DEFAULT_GATEWAY_URL = "https://mcp.conbridge.app";
23067
+ function currentPlatform() {
23068
+ if (process.platform === "darwin")
23069
+ return "macos";
23070
+ if (process.platform === "win32")
23071
+ return "windows";
23072
+ return "linux";
23073
+ }
23074
+ var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
23075
+ function normalizeGatewayUrl(input2) {
23076
+ let url2;
23077
+ try {
23078
+ url2 = new URL(input2);
23079
+ } catch {
23080
+ throw new Error("Gateway URL is invalid");
23081
+ }
23082
+ if (url2.protocol !== "https:" && !(url2.protocol === "http:" && LOOPBACK.has(url2.hostname))) {
23083
+ throw new Error("Gateway URL must use https (http is allowed only for 127.0.0.1/localhost)");
23084
+ }
23085
+ if (url2.username || url2.password)
23086
+ throw new Error("Gateway URL must not contain credentials");
23087
+ return url2.origin;
23088
+ }
23089
+ function normalizePairingCode(input2) {
23090
+ const code = input2.trim().toUpperCase();
23091
+ if (!PAIRING_CODE.test(code))
23092
+ throw new Error("Pairing code must look like XXXX-XXXX");
23093
+ return code.includes("-") ? code : `${code.slice(0, 4)}-${code.slice(4)}`;
23094
+ }
23095
+ var POLL_TOKEN_HEADER = "X-ConBridge-Poll-Token";
23096
+ var offerResponseSchema = external_exports.object({ pairing_id: external_exports.string().min(1).max(128), poll_token: external_exports.string().min(16).max(512) });
23097
+ var statusResponseSchema = external_exports.discriminatedUnion("state", [
23098
+ external_exports.object({
23099
+ state: external_exports.literal("approved"),
23100
+ tenant_id: external_exports.string().min(1).max(128),
23101
+ device_uuid: external_exports.uuid(),
23102
+ user_id: external_exports.string().min(1).max(128),
23103
+ gateway_public_key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/),
23104
+ connection_mode: external_exports.enum(["persistent", "passive", "timed", "ephemeral"]).optional(),
23105
+ expires_at_ms: external_exports.number().int().nonnegative().nullable().optional(),
23106
+ display_name: external_exports.string().min(1).max(128).optional()
23107
+ }),
23108
+ external_exports.object({ state: external_exports.enum(["open", "offered", "pending"]) }),
23109
+ external_exports.object({ state: external_exports.enum(["denied", "expired"]) })
23110
+ ]);
23111
+ var PairingError = class extends Error {
23112
+ state;
23113
+ constructor(state2, message) {
23114
+ super(message);
23115
+ this.name = "PairingError";
23116
+ this.state = state2;
23117
+ }
23118
+ };
23119
+ async function jsonOrThrow(response, what) {
23120
+ let body;
23121
+ try {
23122
+ body = await response.json();
23123
+ } catch {
23124
+ body = void 0;
23125
+ }
23126
+ if (!response.ok) {
23127
+ const message = body && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : `HTTP ${response.status}`;
23128
+ throw new PairingError("http_error", `${what} failed: ${message}`);
23129
+ }
23130
+ return body;
23131
+ }
23132
+ async function pairDevice(options) {
23133
+ const gateway = normalizeGatewayUrl(options.gatewayUrl);
23134
+ const code = normalizePairingCode(options.code);
23135
+ const name3 = options.name.trim();
23136
+ if (name3.length < 1 || name3.length > 128)
23137
+ throw new Error("Device name must be 1 to 128 characters");
23138
+ const platform2 = options.platform ?? currentPlatform();
23139
+ const doFetch = options.fetch ?? ((input2, init) => fetch(input2, init));
23140
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve9) => setTimeout(resolve9, ms)));
23141
+ const key = await options.keyStore.create();
23142
+ const fingerprint = keyFingerprint(key.publicKeyRaw());
23143
+ let succeeded = false;
23144
+ try {
23145
+ const offer = offerResponseSchema.parse(await jsonOrThrow(await doFetch(`${gateway}/v1/agent/pair/offer`, {
23146
+ method: "POST",
23147
+ headers: { "content-type": "application/json" },
23148
+ body: JSON.stringify({ code, public_key: publicKeyB64u(key), display_name: name3, platform: platform2, capabilities: [LIFECYCLE_CAPABILITY] })
23149
+ }), "Pairing offer"));
23150
+ options.onOffered?.({ fingerprint, pairing_id: offer.pairing_id });
23151
+ const deadline = Date.now() + (options.timeoutMs ?? 11 * 6e4);
23152
+ const query = new URLSearchParams({ pairing_id: offer.pairing_id }).toString();
23153
+ const pollInit = { method: "GET", headers: { [POLL_TOKEN_HEADER]: offer.poll_token } };
23154
+ while (Date.now() < deadline) {
23155
+ const status = statusResponseSchema.parse(await jsonOrThrow(await doFetch(`${gateway}/v1/agent/pair/status?${query}`, pollInit), "Pairing status"));
23156
+ if (status.state === "approved") {
23157
+ if (fromBase64Url(status.gateway_public_key).byteLength !== 32)
23158
+ throw new PairingError("invalid", "Gateway key is invalid");
23159
+ const identity = {
23160
+ version: 1,
23161
+ connection_mode: status.connection_mode ?? "persistent",
23162
+ expires_at_ms: status.expires_at_ms ?? null,
23163
+ destroy_deadline_ms: null,
23164
+ device_uuid: status.device_uuid,
23165
+ tenant_id: status.tenant_id,
23166
+ user_id: status.user_id,
23167
+ gateway_url: gateway,
23168
+ gateway_public_key: status.gateway_public_key,
23169
+ display_name: status.display_name ?? name3,
23170
+ platform: platform2,
23171
+ fingerprint,
23172
+ paired_at: (/* @__PURE__ */ new Date()).toISOString(),
23173
+ key_store: options.keyStore.descriptor
23174
+ };
23175
+ await options.onApproved?.();
23176
+ await saveIdentity(options.paths, identity);
23177
+ succeeded = true;
23178
+ return identity;
23179
+ }
23180
+ if (status.state === "denied" || status.state === "expired") {
23181
+ throw new PairingError(status.state, status.state === "denied" ? "Pairing was denied in the Console" : "Pairing code expired");
23182
+ }
23183
+ await sleep(options.pollIntervalMs ?? 2e3);
22480
23184
  }
22481
23185
  throw new PairingError("timeout", "Timed out waiting for approval");
22482
23186
  } finally {
@@ -22486,7 +23190,7 @@ async function pairDevice(options) {
22486
23190
  }
22487
23191
 
22488
23192
  // dist/connect.js
22489
- var CONNECT_GATEWAY_HOSTS = ["mcp.conbridge.app", "staging.mcp.conbridge.app"];
23193
+ var CONNECT_GATEWAY_HOSTS = ["mcp.conbridge.app"];
22490
23194
  function cleanName(value) {
22491
23195
  const text6 = (value ?? "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 64);
22492
23196
  return text6 || "My Mac";
@@ -22540,9 +23244,9 @@ async function runConnect(link, deps, extraHosts = []) {
22540
23244
  const skipped = [];
22541
23245
  for (const folder of folders) {
22542
23246
  try {
22543
- await deps.addFolder(folder, (0, import_node_path7.basename)(folder) || folder, writable);
23247
+ await deps.addFolder(folder, (0, import_node_path9.basename)(folder) || folder, writable);
22544
23248
  } catch (error63) {
22545
- skipped.push(`${(0, import_node_path7.basename)(folder) || folder}: ${friendly(error63)}`);
23249
+ skipped.push(`${(0, import_node_path9.basename)(folder) || folder}: ${friendly(error63)}`);
22546
23250
  }
22547
23251
  }
22548
23252
  if (skipped.length > 0)
@@ -22562,9 +23266,9 @@ function appleScriptString2(value) {
22562
23266
  return '"' + value.replace(/[\\"]/g, "\\$&").replace(/\r?\n/g, '" & linefeed & "') + '"';
22563
23267
  }
22564
23268
  function osascript(script, timeoutMs) {
22565
- return new Promise((resolve8) => {
22566
- (0, import_node_child_process3.execFile)("/usr/bin/osascript", ["-e", "tell current application to activate", "-e", script], { timeout: timeoutMs }, (error63, stdout) => {
22567
- resolve8({ ok: !error63, stdout: stdout ?? "" });
23269
+ return new Promise((resolve9) => {
23270
+ (0, import_node_child_process5.execFile)("/usr/bin/osascript", ["-e", "tell current application to activate", "-e", script], { timeout: timeoutMs }, (error63, stdout) => {
23271
+ resolve9({ ok: !error63, stdout: stdout ?? "" });
22568
23272
  });
22569
23273
  });
22570
23274
  }
@@ -22600,8 +23304,8 @@ Name: ${name3}`;
22600
23304
  };
22601
23305
 
22602
23306
  // dist/journal.js
22603
- var import_promises5 = require("node:fs/promises");
22604
- var import_node_path8 = require("node:path");
23307
+ var import_promises7 = require("node:fs/promises");
23308
+ var import_node_path10 = require("node:path");
22605
23309
  var storedResultSchema = external_exports.strictObject({
22606
23310
  state: external_exports.enum(["SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED"]),
22607
23311
  executed: external_exports.boolean(),
@@ -22676,7 +23380,7 @@ var Journal = class _Journal {
22676
23380
  const journal = new _Journal(path);
22677
23381
  let text6 = "";
22678
23382
  try {
22679
- text6 = await (0, import_promises5.readFile)(path, "utf8");
23383
+ text6 = await (0, import_promises7.readFile)(path, "utf8");
22680
23384
  } catch (error63) {
22681
23385
  if (errorCode2(error63) !== "ENOENT")
22682
23386
  throw error63;
@@ -22734,7 +23438,7 @@ var Journal = class _Journal {
22734
23438
  async #append(entry) {
22735
23439
  const line = JSON.stringify(entrySchema.parse(entry)) + "\n";
22736
23440
  await this.#serialize(async () => {
22737
- const handle = await (0, import_promises5.open)(this.#path, "a", 384);
23441
+ const handle = await (0, import_promises7.open)(this.#path, "a", 384);
22738
23442
  try {
22739
23443
  await handle.appendFile(line, "utf8");
22740
23444
  await handle.sync();
@@ -22784,7 +23488,7 @@ var Journal = class _Journal {
22784
23488
  return this.#serialize(async () => {
22785
23489
  let text6 = "";
22786
23490
  try {
22787
- text6 = await (0, import_promises5.readFile)(this.#path, "utf8");
23491
+ text6 = await (0, import_promises7.readFile)(this.#path, "utf8");
22788
23492
  } catch (error63) {
22789
23493
  if (errorCode2(error63) === "ENOENT")
22790
23494
  return;
@@ -22819,24 +23523,24 @@ var Journal = class _Journal {
22819
23523
  const lines4 = kept.map((entry) => JSON.stringify(entry) + "\n");
22820
23524
  if (watermark !== null)
22821
23525
  lines4.unshift(JSON.stringify(watermarkSchema.parse({ type: "WATERMARK", at_ms: now, watermark_ms: watermark })) + "\n");
22822
- const temp = (0, import_node_path8.join)((0, import_node_path8.dirname)(this.#path), `.${(0, import_node_path8.basename)(this.#path)}.${randomToken(6)}.tmp`);
22823
- const handle = await (0, import_promises5.open)(temp, "wx", 384);
23526
+ const temp = (0, import_node_path10.join)((0, import_node_path10.dirname)(this.#path), `.${(0, import_node_path10.basename)(this.#path)}.${randomToken(6)}.tmp`);
23527
+ const handle = await (0, import_promises7.open)(temp, "wx", 384);
22824
23528
  try {
22825
23529
  await handle.writeFile(lines4.join(""), "utf8");
22826
23530
  await handle.sync();
22827
23531
  } catch (error63) {
22828
23532
  await handle.close().catch(() => void 0);
22829
- await (0, import_promises5.unlink)(temp).catch(() => void 0);
23533
+ await (0, import_promises7.unlink)(temp).catch(() => void 0);
22830
23534
  throw error63;
22831
23535
  }
22832
23536
  await handle.close();
22833
23537
  try {
22834
- await (0, import_promises5.rename)(temp, this.#path);
23538
+ await (0, import_promises7.rename)(temp, this.#path);
22835
23539
  } catch (error63) {
22836
- await (0, import_promises5.unlink)(temp).catch(() => void 0);
23540
+ await (0, import_promises7.unlink)(temp).catch(() => void 0);
22837
23541
  throw error63;
22838
23542
  }
22839
- await fsyncDirectory((0, import_node_path8.dirname)(this.#path));
23543
+ await fsyncDirectory((0, import_node_path10.dirname)(this.#path));
22840
23544
  this.#records.clear();
22841
23545
  this.#nonces.clear();
22842
23546
  for (const entry of kept)
@@ -22847,238 +23551,23 @@ var Journal = class _Journal {
22847
23551
  }
22848
23552
  };
22849
23553
 
22850
- // dist/keychain.js
22851
- var import_node_child_process4 = require("node:child_process");
22852
- var import_node_crypto4 = require("node:crypto");
22853
- var import_promises6 = require("node:fs/promises");
22854
- var import_node_path9 = require("node:path");
22855
- var KEYCHAIN_HELPER_NAME = "conbridge-agent-keychain";
22856
- var HELPER_TIMEOUT_MS = 15e3;
22857
- var MAX_HELPER_BYTES = 64 * 1024 * 1024;
22858
- var KeychainError = class extends Error {
22859
- code;
22860
- constructor(code, message) {
22861
- super(message);
22862
- this.name = "KeychainError";
22863
- this.code = code;
22864
- }
22865
- };
22866
- function keychainHelperCandidates(env = process.env, codeDir = codeDirectory()) {
22867
- const candidates = [];
22868
- const override = env.CONBRIDGE_KEYCHAIN_HELPER;
22869
- if (override && override.trim() !== "")
22870
- candidates.push((0, import_node_path9.resolve)(override));
22871
- candidates.push((0, import_node_path9.join)(codeDir, KEYCHAIN_HELPER_NAME));
22872
- candidates.push((0, import_node_path9.join)(codeDir, "..", "native", "macos-keychain", ".build", "release", KEYCHAIN_HELPER_NAME));
22873
- return candidates;
22874
- }
22875
- async function verifyKeychainHelper(path, expectedSha256 = BUILD_INFO?.keychain_helper_sha256 ?? null) {
22876
- if (!(0, import_node_path9.isAbsolute)(path))
22877
- throw new KeychainError("HELPER_INVALID", "Keychain helper path must be absolute");
22878
- let real;
22879
- try {
22880
- real = await (0, import_promises6.realpath)(path);
22881
- } catch {
22882
- throw new KeychainError("HELPER_INVALID", "Keychain helper not found");
22883
- }
22884
- const info = await (0, import_promises6.stat)(real);
22885
- const uid = typeof process.getuid === "function" ? process.getuid() : -1;
22886
- if (!info.isFile() || info.size < 1024 || info.size > MAX_HELPER_BYTES)
22887
- throw new KeychainError("HELPER_INVALID", "Keychain helper is not a regular executable");
22888
- if ((info.mode & 18) !== 0 || (info.mode & 64) === 0)
22889
- throw new KeychainError("HELPER_INVALID", "Keychain helper has unsafe permissions");
22890
- if (info.uid !== uid && info.uid !== 0)
22891
- throw new KeychainError("HELPER_INVALID", "Keychain helper is owned by another user");
22892
- if (expectedSha256 !== null) {
22893
- const digest = (0, import_node_crypto4.createHash)("sha256").update(await (0, import_promises6.readFile)(real)).digest("hex");
22894
- if (digest !== expectedSha256)
22895
- throw new KeychainError("HELPER_INVALID", "Keychain helper does not match this build");
22896
- }
22897
- return real;
22898
- }
22899
- var helperCache = /* @__PURE__ */ new Map();
22900
- async function findKeychainHelper(options = {}) {
22901
- if ((options.platform ?? process.platform) !== "darwin")
22902
- return null;
22903
- const candidates = keychainHelperCandidates(options.env ?? process.env, options.codeDir ?? codeDirectory());
22904
- const cacheKey = candidates.join("\0");
22905
- if (helperCache.has(cacheKey))
22906
- return helperCache.get(cacheKey) ?? null;
22907
- let found = null;
22908
- for (const candidate of candidates) {
22909
- try {
22910
- found = await verifyKeychainHelper(candidate);
22911
- break;
22912
- } catch {
22913
- }
22914
- }
22915
- helperCache.set(cacheKey, found);
22916
- return found;
22917
- }
22918
- function runHelper(options, command2, keyId, input2) {
22919
- const args = [...options.keychainPath ? ["--keychain", options.keychainPath] : [], command2, keyId];
22920
- return new Promise((resolvePromise, reject) => {
22921
- const child = (0, import_node_child_process4.execFile)(options.helperPath, args, {
22922
- encoding: "utf8",
22923
- timeout: options.timeoutMs ?? HELPER_TIMEOUT_MS,
22924
- maxBuffer: 4096,
22925
- windowsHide: true,
22926
- env: { PATH: "/usr/bin:/bin", HOME: process.env.HOME ?? "", TMPDIR: process.env.TMPDIR ?? "/tmp" }
22927
- }, (error63, stdout) => {
22928
- if (error63) {
22929
- const exitCode = typeof error63.code === "number" ? error63.code : null;
22930
- if (exitCode === 3)
22931
- return reject(new KeychainError("NOT_FOUND", "Device key is not in the Keychain"));
22932
- if (exitCode === 1)
22933
- return reject(new KeychainError("DENIED", "Keychain refused the request (locked, access denied or invalid request)"));
22934
- return reject(new KeychainError("HELPER_FAILED", "Keychain helper failed to run"));
22935
- }
22936
- const lines4 = stdout.split("\n");
22937
- if (lines4.length !== 2 || lines4[1] !== "" || lines4[0].length > 1024) {
22938
- return reject(new KeychainError("HELPER_FAILED", "Keychain helper returned unexpected output"));
22939
- }
22940
- try {
22941
- resolvePromise(JSON.parse(lines4[0]));
22942
- } catch {
22943
- reject(new KeychainError("HELPER_FAILED", "Keychain helper returned unexpected output"));
22944
- }
22945
- });
22946
- child.stdin?.on("error", () => void 0);
22947
- child.stdin?.end(input2 ? Buffer.from(input2) : void 0);
22948
- });
22949
- }
22950
- var b64u32 = external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/);
22951
- var publicIdentitySchema = external_exports.strictObject({
22952
- deviceUuid: external_exports.string(),
22953
- publicKeyB64: b64u32,
22954
- fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9_-]{43}$/)
22955
- });
22956
- var signatureSchema = external_exports.strictObject({ signature: external_exports.string().regex(/^[A-Za-z0-9_-]{86}$/) });
22957
- var deletedSchema = external_exports.strictObject({ deleted: external_exports.literal(true) });
22958
- function parsePublic(value, keyId) {
22959
- const parsed = publicIdentitySchema.safeParse(value);
22960
- if (!parsed.success || parsed.data.deviceUuid !== keyId)
22961
- throw new KeychainError("HELPER_FAILED", "Keychain helper returned an invalid identity");
22962
- const raw = Buffer.from(parsed.data.publicKeyB64, "base64url");
22963
- const digest = (0, import_node_crypto4.createHash)("sha256").update(raw).digest("base64url");
22964
- if (raw.length !== 32 || parsed.data.fingerprint !== `SHA256:${digest}`) {
22965
- throw new KeychainError("HELPER_FAILED", "Keychain helper returned an inconsistent identity");
22966
- }
22967
- return new Uint8Array(raw);
22968
- }
22969
- var KEY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
22970
- var KeychainDeviceKey = class {
22971
- #run;
22972
- #keyId;
22973
- #publicRaw;
22974
- constructor(run2, keyId, publicRaw) {
22975
- this.#run = run2;
22976
- this.#keyId = keyId;
22977
- this.#publicRaw = publicRaw;
22978
- }
22979
- publicKeyRaw() {
22980
- return new Uint8Array(this.#publicRaw);
22981
- }
22982
- async sign(message) {
22983
- const parsed = signatureSchema.safeParse(await runHelper(this.#run, "sign", this.#keyId, message));
22984
- if (!parsed.success)
22985
- throw new KeychainError("HELPER_FAILED", "Keychain helper returned an invalid signature");
22986
- const signature = new Uint8Array(Buffer.from(parsed.data.signature, "base64url"));
22987
- const publicKey = (0, import_node_crypto4.createPublicKey)({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(this.#publicRaw).toString("base64url") }, format: "jwk" });
22988
- if (!(0, import_node_crypto4.verify)(null, message, publicKey, signature))
22989
- throw new KeychainError("HELPER_FAILED", "Keychain signature does not verify");
22990
- return signature;
22991
- }
22992
- };
22993
- var KeychainKeyStore = class {
22994
- #run;
22995
- #keyId;
22996
- #keychainPath;
22997
- constructor(options) {
22998
- if (!KEY_ID.test(options.keyId))
22999
- throw new KeychainError("HELPER_INVALID", "Keychain key id must be a lowercase UUID");
23000
- if (options.keychainPath !== void 0 && !(0, import_node_path9.isAbsolute)(options.keychainPath)) {
23001
- throw new KeychainError("HELPER_INVALID", "Keychain path must be absolute");
23002
- }
23003
- this.#keyId = options.keyId;
23004
- this.#keychainPath = options.keychainPath;
23005
- this.#run = {
23006
- helperPath: options.helperPath,
23007
- ...options.keychainPath !== void 0 ? { keychainPath: options.keychainPath } : {},
23008
- ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
23009
- };
23010
- }
23011
- get descriptor() {
23012
- return { type: "keychain", key_id: this.#keyId, ...this.#keychainPath !== void 0 ? { keychain: this.#keychainPath } : {} };
23013
- }
23014
- async load() {
23015
- let output2;
23016
- try {
23017
- output2 = await runHelper(this.#run, "inspect", this.#keyId);
23018
- } catch (error63) {
23019
- if (error63 instanceof KeychainError && error63.code === "NOT_FOUND")
23020
- return null;
23021
- throw error63;
23022
- }
23023
- return new KeychainDeviceKey(this.#run, this.#keyId, parsePublic(output2, this.#keyId));
23024
- }
23025
- async create() {
23026
- await this.remove();
23027
- const output2 = await runHelper(this.#run, "create", this.#keyId);
23028
- return new KeychainDeviceKey(this.#run, this.#keyId, parsePublic(output2, this.#keyId));
23029
- }
23030
- async remove() {
23031
- if (!deletedSchema.safeParse(await runHelper(this.#run, "delete", this.#keyId)).success) {
23032
- throw new KeychainError("HELPER_FAILED", "Keychain helper returned unexpected output");
23033
- }
23034
- }
23035
- };
23036
- function chooseKeyStoreType(requested, helperPath, platform2 = process.platform) {
23037
- if (requested !== void 0 && requested !== "keychain" && requested !== "file") {
23038
- throw new Error("--key-store must be keychain or file");
23039
- }
23040
- if (requested === "file")
23041
- return "file";
23042
- if (requested === "keychain") {
23043
- if (platform2 !== "darwin")
23044
- throw new Error("The Keychain key store is only available on macOS");
23045
- if (helperPath === null)
23046
- throw new Error("The Keychain helper (conbridge-agent-keychain) was not found or failed verification; build it or use --key-store file");
23047
- return "keychain";
23048
- }
23049
- return platform2 === "darwin" && helperPath !== null ? "keychain" : "file";
23050
- }
23051
- async function openKeyStore(paths, descriptor, options = {}) {
23052
- if (!descriptor || descriptor.type === "file")
23053
- return new FileKeyStore(paths.key);
23054
- const helperPath = options.helperPath !== void 0 ? options.helperPath : await findKeychainHelper({ ...options.env ? { env: options.env } : {}, ...options.platform ? { platform: options.platform } : {} });
23055
- if (helperPath === null) {
23056
- throw new KeychainError("HELPER_INVALID", "This identity keeps its key in the Keychain, but no valid Keychain helper (conbridge-agent-keychain) was found (it must exist next to the agent, not be writable by others and match this build)");
23057
- }
23058
- return new KeychainKeyStore({
23059
- helperPath,
23060
- keyId: descriptor.key_id,
23061
- ...descriptor.keychain !== void 0 ? { keychainPath: descriptor.keychain } : {}
23062
- });
23063
- }
23064
-
23065
23554
  // dist/install.js
23066
- var import_promises7 = require("node:fs/promises");
23067
- var import_node_path10 = require("node:path");
23555
+ var import_promises8 = require("node:fs/promises");
23556
+ var import_node_path11 = require("node:path");
23068
23557
  var import_node_url2 = require("node:url");
23069
23558
  var RUNTIME_ENTRY = "conbridge-agent.cjs";
23070
23559
  function runtimeDir(stateDir) {
23071
- return (0, import_node_path10.join)(stateDir, "runtime");
23560
+ return (0, import_node_path11.join)(stateDir, "runtime");
23072
23561
  }
23073
23562
  function runtimeEntry(stateDir) {
23074
- return (0, import_node_path10.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
23563
+ return (0, import_node_path11.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
23075
23564
  }
23076
23565
  function currentEntry() {
23077
23566
  return (0, import_node_url2.fileURLToPath)(__conbridge_import_meta_url);
23078
23567
  }
23079
23568
  async function sameBytes(a, b) {
23080
23569
  try {
23081
- const [left, right] = await Promise.all([(0, import_promises7.readFile)(a), (0, import_promises7.readFile)(b)]);
23570
+ const [left, right] = await Promise.all([(0, import_promises8.readFile)(a), (0, import_promises8.readFile)(b)]);
23082
23571
  return left.equals(right);
23083
23572
  } catch {
23084
23573
  return false;
@@ -23087,11 +23576,11 @@ async function sameBytes(a, b) {
23087
23576
  async function copyAtomic(from, to, mode) {
23088
23577
  const temp = `${to}.${randomToken(6)}.tmp`;
23089
23578
  try {
23090
- await (0, import_promises7.copyFile)(from, temp);
23091
- await (0, import_promises7.chmod)(temp, mode);
23092
- await (0, import_promises7.rename)(temp, to);
23579
+ await (0, import_promises8.copyFile)(from, temp);
23580
+ await (0, import_promises8.chmod)(temp, mode);
23581
+ await (0, import_promises8.rename)(temp, to);
23093
23582
  } catch (error63) {
23094
- await (0, import_promises7.unlink)(temp).catch(() => void 0);
23583
+ await (0, import_promises8.unlink)(temp).catch(() => void 0);
23095
23584
  throw error63;
23096
23585
  }
23097
23586
  }
@@ -23100,21 +23589,21 @@ async function installRuntime(stateDir, from = {}) {
23100
23589
  const sourceDir = from.codeDir ?? codeDirectory();
23101
23590
  const dir = runtimeDir(stateDir);
23102
23591
  const entry = runtimeEntry(stateDir);
23103
- await (0, import_promises7.mkdir)(dir, { recursive: true, mode: 448 });
23104
- await (0, import_promises7.chmod)(dir, 448);
23592
+ await (0, import_promises8.mkdir)(dir, { recursive: true, mode: 448 });
23593
+ await (0, import_promises8.chmod)(dir, 448);
23105
23594
  let changed = false;
23106
23595
  if (!await sameBytes(source, entry)) {
23107
23596
  await copyAtomic(source, entry, 384);
23108
23597
  changed = true;
23109
23598
  }
23110
- const helper = (0, import_node_path10.join)(sourceDir, KEYCHAIN_HELPER_NAME);
23111
- const helperTarget = (0, import_node_path10.join)(dir, KEYCHAIN_HELPER_NAME);
23112
- const hasHelper = await (0, import_promises7.stat)(helper).then((info) => info.isFile(), () => false);
23599
+ const helper = (0, import_node_path11.join)(sourceDir, KEYCHAIN_HELPER_NAME);
23600
+ const helperTarget = (0, import_node_path11.join)(dir, KEYCHAIN_HELPER_NAME);
23601
+ const hasHelper = await (0, import_promises8.stat)(helper).then((info) => info.isFile(), () => false);
23113
23602
  if (hasHelper && !await sameBytes(helper, helperTarget)) {
23114
23603
  await copyAtomic(helper, helperTarget, 493);
23115
23604
  changed = true;
23116
23605
  } else if (!hasHelper) {
23117
- await (0, import_promises7.unlink)(helperTarget).catch((error63) => {
23606
+ await (0, import_promises8.unlink)(helperTarget).catch((error63) => {
23118
23607
  if (errorCode2(error63) !== "ENOENT")
23119
23608
  throw error63;
23120
23609
  });
@@ -23124,26 +23613,26 @@ async function installRuntime(stateDir, from = {}) {
23124
23613
  async function snapshotRuntime(stateDir) {
23125
23614
  const dir = runtimeDir(stateDir);
23126
23615
  const backup = `${dir}.previous`;
23127
- await (0, import_promises7.rm)(backup, { recursive: true, force: true });
23128
- await (0, import_promises7.mkdir)(backup, { recursive: true, mode: 448 });
23616
+ await (0, import_promises8.rm)(backup, { recursive: true, force: true });
23617
+ await (0, import_promises8.mkdir)(backup, { recursive: true, mode: 448 });
23129
23618
  const saved = /* @__PURE__ */ new Map();
23130
23619
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
23131
- const info = await (0, import_promises7.stat)((0, import_node_path10.join)(dir, name3)).catch(() => null);
23620
+ const info = await (0, import_promises8.stat)((0, import_node_path11.join)(dir, name3)).catch(() => null);
23132
23621
  if (!info?.isFile())
23133
23622
  continue;
23134
- await (0, import_promises7.copyFile)((0, import_node_path10.join)(dir, name3), (0, import_node_path10.join)(backup, name3));
23623
+ await (0, import_promises8.copyFile)((0, import_node_path11.join)(dir, name3), (0, import_node_path11.join)(backup, name3));
23135
23624
  saved.set(name3, info.mode & 511);
23136
23625
  }
23137
- const discard = () => (0, import_promises7.rm)(backup, { recursive: true, force: true });
23626
+ const discard = () => (0, import_promises8.rm)(backup, { recursive: true, force: true });
23138
23627
  return {
23139
23628
  async restore() {
23140
- await (0, import_promises7.mkdir)(dir, { recursive: true, mode: 448 });
23629
+ await (0, import_promises8.mkdir)(dir, { recursive: true, mode: 448 });
23141
23630
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
23142
23631
  const mode = saved.get(name3);
23143
23632
  if (mode !== void 0)
23144
- await copyAtomic((0, import_node_path10.join)(backup, name3), (0, import_node_path10.join)(dir, name3), mode);
23633
+ await copyAtomic((0, import_node_path11.join)(backup, name3), (0, import_node_path11.join)(dir, name3), mode);
23145
23634
  else
23146
- await (0, import_promises7.unlink)((0, import_node_path10.join)(dir, name3)).catch((error63) => {
23635
+ await (0, import_promises8.unlink)((0, import_node_path11.join)(dir, name3)).catch((error63) => {
23147
23636
  if (errorCode2(error63) !== "ENOENT")
23148
23637
  throw error63;
23149
23638
  });
@@ -23159,7 +23648,7 @@ async function runningFromRuntime(stateDir, entry = currentEntry()) {
23159
23648
  }
23160
23649
 
23161
23650
  // dist/keepawake.js
23162
- var import_node_child_process5 = require("node:child_process");
23651
+ var import_node_child_process6 = require("node:child_process");
23163
23652
  var WINDOWS_SCRIPT = (pid) => [
23164
23653
  "$ErrorActionPreference = 'Stop'",
23165
23654
  `Add-Type -Namespace ConBridge -Name Power -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint flags);'`,
@@ -23186,7 +23675,7 @@ function keepAwakeCommand(platform2 = process.platform, pid = process.pid, env =
23186
23675
  }
23187
23676
  return null;
23188
23677
  }
23189
- var defaultSpawner = (file2, args) => (0, import_node_child_process5.spawn)(file2, [...args], { stdio: "ignore", windowsHide: true });
23678
+ var defaultSpawner = (file2, args) => (0, import_node_child_process6.spawn)(file2, [...args], { stdio: "ignore", windowsHide: true });
23190
23679
  function startKeepAwake(options = {}) {
23191
23680
  const logger = options.logger ?? silentLogger;
23192
23681
  const command2 = keepAwakeCommand(options.platform);
@@ -23219,7 +23708,7 @@ function startKeepAwake(options = {}) {
23219
23708
  }
23220
23709
 
23221
23710
  // dist/lock.js
23222
- var import_promises8 = require("node:fs/promises");
23711
+ var import_promises9 = require("node:fs/promises");
23223
23712
  function alive(pid) {
23224
23713
  try {
23225
23714
  process.kill(pid, 0);
@@ -23230,7 +23719,7 @@ function alive(pid) {
23230
23719
  }
23231
23720
  async function readLockPid(path) {
23232
23721
  try {
23233
- const pid = Number.parseInt((await (0, import_promises8.readFile)(path, "utf8")).trim(), 10);
23722
+ const pid = Number.parseInt((await (0, import_promises9.readFile)(path, "utf8")).trim(), 10);
23234
23723
  return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
23235
23724
  } catch {
23236
23725
  return null;
@@ -23239,12 +23728,12 @@ async function readLockPid(path) {
23239
23728
  async function acquireLock(path) {
23240
23729
  for (let attempt = 0; attempt < 2; attempt += 1) {
23241
23730
  try {
23242
- const handle = await (0, import_promises8.open)(path, "wx", 384);
23731
+ const handle = await (0, import_promises9.open)(path, "wx", 384);
23243
23732
  await handle.writeFile(`${process.pid}
23244
23733
  `);
23245
23734
  await handle.close();
23246
23735
  return async () => {
23247
- await (0, import_promises8.unlink)(path).catch(() => void 0);
23736
+ await (0, import_promises9.unlink)(path).catch(() => void 0);
23248
23737
  };
23249
23738
  } catch (error63) {
23250
23739
  if (errorCode2(error63) !== "EEXIST")
@@ -23252,25 +23741,19 @@ async function acquireLock(path) {
23252
23741
  const pid = await readLockPid(path);
23253
23742
  if (pid !== null)
23254
23743
  throw new Error(`Another agent is already running (pid ${pid})`);
23255
- await (0, import_promises8.unlink)(path).catch(() => void 0);
23744
+ await (0, import_promises9.unlink)(path).catch(() => void 0);
23256
23745
  }
23257
23746
  }
23258
23747
  throw new Error("Could not acquire the agent lock");
23259
23748
  }
23260
23749
 
23261
- // dist/runner.js
23262
- var import_node_os7 = require("node:os");
23263
-
23264
- // dist/dispatcher.js
23265
- var import_node_crypto7 = require("node:crypto");
23266
-
23267
23750
  // dist/envelope.js
23268
- var import_node_crypto5 = require("node:crypto");
23269
- function buildEnvelope(identity, kind, taskId2, body, correlationId = (0, import_node_crypto5.randomUUID)()) {
23751
+ var import_node_crypto6 = require("node:crypto");
23752
+ function buildEnvelope(identity, kind, taskId2, body, correlationId = (0, import_node_crypto6.randomUUID)()) {
23270
23753
  return {
23271
23754
  version: 1,
23272
23755
  kind,
23273
- message_id: (0, import_node_crypto5.randomUUID)(),
23756
+ message_id: (0, import_node_crypto6.randomUUID)(),
23274
23757
  correlation_id: correlationId,
23275
23758
  tenant_id: identity.tenant_id,
23276
23759
  user_id: identity.user_id,
@@ -23310,11 +23793,17 @@ function excerpt(value) {
23310
23793
  return fallback.length <= 4096 ? fallback : JSON.stringify({ excerpt_truncated: true });
23311
23794
  }
23312
23795
 
23796
+ // dist/runner.js
23797
+ var import_node_os8 = require("node:os");
23798
+
23799
+ // dist/dispatcher.js
23800
+ var import_node_crypto8 = require("node:crypto");
23801
+
23313
23802
  // dist/fileops.js
23314
23803
  var import_node_fs2 = require("node:fs");
23315
- var import_promises9 = require("node:fs/promises");
23316
- var import_node_crypto6 = require("node:crypto");
23317
- var import_node_path11 = require("node:path");
23804
+ var import_promises10 = require("node:fs/promises");
23805
+ var import_node_crypto7 = require("node:crypto");
23806
+ var import_node_path12 = require("node:path");
23318
23807
 
23319
23808
  // dist/glob.js
23320
23809
  function globToRegExp(glob) {
@@ -23458,7 +23947,7 @@ function decodeText(bytes3) {
23458
23947
  }
23459
23948
  }
23460
23949
  async function hashHandle(handle) {
23461
- const hash2 = (0, import_node_crypto6.createHash)("sha256");
23950
+ const hash2 = (0, import_node_crypto7.createHash)("sha256");
23462
23951
  const buffer = Buffer.allocUnsafe(READ_BLOCK);
23463
23952
  let position2 = 0;
23464
23953
  for (; ; ) {
@@ -23471,7 +23960,7 @@ async function hashHandle(handle) {
23471
23960
  return hash2.digest("hex");
23472
23961
  }
23473
23962
  function sha256OfBytes(bytes3) {
23474
- return (0, import_node_crypto6.createHash)("sha256").update(bytes3).digest("hex");
23963
+ return (0, import_node_crypto7.createHash)("sha256").update(bytes3).digest("hex");
23475
23964
  }
23476
23965
  var RootedFs = class {
23477
23966
  #root;
@@ -23491,7 +23980,7 @@ var RootedFs = class {
23491
23980
  return;
23492
23981
  const forms = /* @__PURE__ */ new Set();
23493
23982
  for (const path of this.#protectedInput) {
23494
- forms.add((0, import_node_path11.resolve)(path));
23983
+ forms.add((0, import_node_path12.resolve)(path));
23495
23984
  forms.add(await realpathLenient(path));
23496
23985
  }
23497
23986
  this.#protected = [...forms];
@@ -23501,7 +23990,7 @@ var RootedFs = class {
23501
23990
  #blockedReal(real) {
23502
23991
  if (this.#protected.some((dir) => isSameOrInside(dir, real)))
23503
23992
  return true;
23504
- return this.#hardDeny.denies(real.split(import_node_path11.sep).filter((segment) => segment !== "").join("/"));
23993
+ return this.#hardDeny.denies(real.split(import_node_path12.sep).filter((segment) => segment !== "").join("/"));
23505
23994
  }
23506
23995
  #checkReal(real) {
23507
23996
  if (this.#blockedReal(real))
@@ -23510,8 +23999,8 @@ var RootedFs = class {
23510
23999
  async #rootReal() {
23511
24000
  await this.#loadProtected();
23512
24001
  try {
23513
- const real = await (0, import_promises9.realpath)(this.#root.path);
23514
- if (!(await (0, import_promises9.stat)(real)).isDirectory())
24002
+ const real = await (0, import_promises10.realpath)(this.#root.path);
24003
+ if (!(await (0, import_promises10.stat)(real)).isDirectory())
23515
24004
  throw new FileOpError("NOT_FOUND", "Root is unavailable");
23516
24005
  return real;
23517
24006
  } catch (error63) {
@@ -23521,11 +24010,11 @@ var RootedFs = class {
23521
24010
  }
23522
24011
  }
23523
24012
  #inside(rootReal, real) {
23524
- const prefix = rootReal.endsWith(import_node_path11.sep) ? rootReal : rootReal + import_node_path11.sep;
24013
+ const prefix = rootReal.endsWith(import_node_path12.sep) ? rootReal : rootReal + import_node_path12.sep;
23525
24014
  return real === rootReal || real.startsWith(prefix);
23526
24015
  }
23527
24016
  #relativeOf(rootReal, real) {
23528
- return (0, import_node_path11.relative)(rootReal, real).split(import_node_path11.sep).join("/");
24017
+ return (0, import_node_path12.relative)(rootReal, real).split(import_node_path12.sep).join("/");
23529
24018
  }
23530
24019
  #checkDeny(rel) {
23531
24020
  if (this.#deny.denies(rel))
@@ -23538,7 +24027,7 @@ var RootedFs = class {
23538
24027
  const rootReal = await this.#rootReal();
23539
24028
  let real;
23540
24029
  try {
23541
- real = await (0, import_promises9.realpath)((0, import_node_path11.join)(rootReal, rel));
24030
+ real = await (0, import_promises10.realpath)((0, import_node_path12.join)(rootReal, rel));
23542
24031
  } catch (error63) {
23543
24032
  throw mapFsError(error63, rel);
23544
24033
  }
@@ -23557,10 +24046,10 @@ var RootedFs = class {
23557
24046
  async #openVerified(rootReal, real) {
23558
24047
  let handle;
23559
24048
  try {
23560
- const before = await (0, import_promises9.lstat)(real);
24049
+ const before = await (0, import_promises10.lstat)(real);
23561
24050
  if (!before.isFile())
23562
24051
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
23563
- handle = await (0, import_promises9.open)(real, OPEN_READ_FLAGS);
24052
+ handle = await (0, import_promises10.open)(real, OPEN_READ_FLAGS);
23564
24053
  } catch (error63) {
23565
24054
  throw mapFsError(error63, "");
23566
24055
  }
@@ -23568,8 +24057,8 @@ var RootedFs = class {
23568
24057
  const info = await handle.stat();
23569
24058
  if (!info.isFile())
23570
24059
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
23571
- const again = await (0, import_promises9.realpath)(real);
23572
- const pathInfo = await (0, import_promises9.stat)(again);
24060
+ const again = await (0, import_promises10.realpath)(real);
24061
+ const pathInfo = await (0, import_promises10.stat)(again);
23573
24062
  if (again !== real || !this.#inside(rootReal, again) || pathInfo.ino !== info.ino || pathInfo.dev !== info.dev) {
23574
24063
  throw new FileOpError("PATH_ESCAPE", "Path changed while it was being opened");
23575
24064
  }
@@ -23588,7 +24077,7 @@ var RootedFs = class {
23588
24077
  try {
23589
24078
  if (!info.isFile())
23590
24079
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file", { path: rel });
23591
- const hash2 = (0, import_node_crypto6.createHash)("sha256");
24080
+ const hash2 = (0, import_node_crypto7.createHash)("sha256");
23592
24081
  const kept = [];
23593
24082
  let keptBytes = 0;
23594
24083
  let size = 0;
@@ -23621,18 +24110,18 @@ var RootedFs = class {
23621
24110
  async list(input2) {
23622
24111
  const { rel, real } = await this.resolveExisting(input2);
23623
24112
  try {
23624
- if (!(await (0, import_promises9.stat)(real)).isDirectory())
24113
+ if (!(await (0, import_promises10.stat)(real)).isDirectory())
23625
24114
  throw new FileOpError("NOT_A_DIRECTORY", "Path is not a directory", { path: rel });
23626
- const dir = await (0, import_promises9.opendir)(real);
24115
+ const dir = await (0, import_promises10.opendir)(real);
23627
24116
  const names = [];
23628
24117
  for await (const entry of dir) {
23629
24118
  const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
23630
24119
  if (this.#deny.denies(childRel))
23631
24120
  continue;
23632
- const childReal = (0, import_node_path11.join)(real, entry.name);
24121
+ const childReal = (0, import_node_path12.join)(real, entry.name);
23633
24122
  if (this.#blockedReal(childReal))
23634
24123
  continue;
23635
- if (entry.isSymbolicLink() && this.#blockedReal(await (0, import_promises9.realpath)(childReal).catch(() => childReal)))
24124
+ if (entry.isSymbolicLink() && this.#blockedReal(await (0, import_promises10.realpath)(childReal).catch(() => childReal)))
23636
24125
  continue;
23637
24126
  const type = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "other";
23638
24127
  names.push({ name: entry.name, type });
@@ -23641,7 +24130,7 @@ var RootedFs = class {
23641
24130
  const entries = [];
23642
24131
  for (const item of names.slice(0, MAX_LIST_ENTRIES)) {
23643
24132
  if (item.type === "file") {
23644
- const size = await (0, import_promises9.lstat)((0, import_node_path11.join)(real, item.name)).then((s) => s.size, () => void 0);
24133
+ const size = await (0, import_promises10.lstat)((0, import_node_path12.join)(real, item.name)).then((s) => s.size, () => void 0);
23645
24134
  entries.push(size === void 0 ? item : { ...item, size });
23646
24135
  } else
23647
24136
  entries.push(item);
@@ -23664,7 +24153,7 @@ var RootedFs = class {
23664
24153
  return;
23665
24154
  let resolved;
23666
24155
  try {
23667
- resolved = await (0, import_promises9.realpath)(fileReal);
24156
+ resolved = await (0, import_promises10.realpath)(fileReal);
23668
24157
  } catch {
23669
24158
  return;
23670
24159
  }
@@ -23672,9 +24161,9 @@ var RootedFs = class {
23672
24161
  return;
23673
24162
  let handle;
23674
24163
  try {
23675
- if (!(await (0, import_promises9.lstat)(resolved)).isFile())
24164
+ if (!(await (0, import_promises10.lstat)(resolved)).isFile())
23676
24165
  return;
23677
- handle = await (0, import_promises9.open)(resolved, OPEN_READ_FLAGS);
24166
+ handle = await (0, import_promises10.open)(resolved, OPEN_READ_FLAGS);
23678
24167
  } catch {
23679
24168
  return;
23680
24169
  }
@@ -23716,7 +24205,7 @@ var RootedFs = class {
23716
24205
  await handle.close().catch(() => void 0);
23717
24206
  }
23718
24207
  };
23719
- const start = await (0, import_promises9.stat)(real).catch((error63) => {
24208
+ const start = await (0, import_promises10.stat)(real).catch((error63) => {
23720
24209
  throw mapFsError(error63, rel);
23721
24210
  });
23722
24211
  if (start.isFile()) {
@@ -23727,7 +24216,7 @@ var RootedFs = class {
23727
24216
  const current = queue.shift();
23728
24217
  let entries;
23729
24218
  try {
23730
- const dir = await (0, import_promises9.opendir)(current.real);
24219
+ const dir = await (0, import_promises10.opendir)(current.real);
23731
24220
  entries = [];
23732
24221
  for await (const entry of dir) {
23733
24222
  entries.push({ name: entry.name, file: entry.isFile(), dir: entry.isDirectory() });
@@ -23742,7 +24231,7 @@ var RootedFs = class {
23742
24231
  const childRel = current.rel === "" ? entry.name : `${current.rel}/${entry.name}`;
23743
24232
  if (this.#deny.denies(childRel))
23744
24233
  continue;
23745
- const childReal = (0, import_node_path11.join)(current.real, entry.name);
24234
+ const childReal = (0, import_node_path12.join)(current.real, entry.name);
23746
24235
  if (this.#blockedReal(childReal))
23747
24236
  continue;
23748
24237
  if (entry.dir)
@@ -23764,7 +24253,7 @@ var RootedFs = class {
23764
24253
  async #currentHash(rootReal, target) {
23765
24254
  let info;
23766
24255
  try {
23767
- info = await (0, import_promises9.lstat)(target);
24256
+ info = await (0, import_promises10.lstat)(target);
23768
24257
  } catch (error63) {
23769
24258
  if (errorCode2(error63) === "ENOENT")
23770
24259
  return { sha256: null, mode: null };
@@ -23796,8 +24285,8 @@ var RootedFs = class {
23796
24285
  const name3 = slash < 0 ? rel : rel.slice(slash + 1);
23797
24286
  let parentReal;
23798
24287
  try {
23799
- parentReal = await (0, import_promises9.realpath)((0, import_node_path11.join)(rootReal, parentRel));
23800
- if (!(await (0, import_promises9.stat)(parentReal)).isDirectory())
24288
+ parentReal = await (0, import_promises10.realpath)((0, import_node_path12.join)(rootReal, parentRel));
24289
+ if (!(await (0, import_promises10.stat)(parentReal)).isDirectory())
23801
24290
  throw new FileOpError("NOT_A_DIRECTORY", "Parent is not a directory");
23802
24291
  } catch (error63) {
23803
24292
  if (errorCode2(error63) === "ENOENT")
@@ -23808,16 +24297,16 @@ var RootedFs = class {
23808
24297
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
23809
24298
  const parentRealRel = this.#relativeOf(rootReal, parentReal);
23810
24299
  this.#checkDeny(parentRealRel === "" ? name3 : `${parentRealRel}/${name3}`);
23811
- const target = (0, import_node_path11.join)(parentReal, name3);
24300
+ const target = (0, import_node_path12.join)(parentReal, name3);
23812
24301
  this.#checkReal(target);
23813
24302
  return { rel, rootReal, parentReal, name: name3, target };
23814
24303
  }
23815
24304
  /** Temp file in the same directory, fsync, re-check the version, rename over the target. */
23816
24305
  async #replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3) {
23817
- const temp = (0, import_node_path11.join)(parentReal, `.${name3}.conbridge-${randomToken(8)}.tmp`);
24306
+ const temp = (0, import_node_path12.join)(parentReal, `.${name3}.conbridge-${randomToken(8)}.tmp`);
23818
24307
  let handle;
23819
24308
  try {
23820
- handle = await (0, import_promises9.open)(temp, import_node_fs2.constants.O_WRONLY | import_node_fs2.constants.O_CREAT | import_node_fs2.constants.O_EXCL | import_node_fs2.constants.O_NOFOLLOW, before.mode ?? 438);
24309
+ handle = await (0, import_promises10.open)(temp, import_node_fs2.constants.O_WRONLY | import_node_fs2.constants.O_CREAT | import_node_fs2.constants.O_EXCL | import_node_fs2.constants.O_NOFOLLOW, before.mode ?? 438);
23821
24310
  } catch (error63) {
23822
24311
  throw mapFsError(error63, rel);
23823
24312
  }
@@ -23831,20 +24320,20 @@ var RootedFs = class {
23831
24320
  } finally {
23832
24321
  await handle.close();
23833
24322
  }
23834
- if (await (0, import_promises9.realpath)(parentReal) !== parentReal)
24323
+ if (await (0, import_promises10.realpath)(parentReal) !== parentReal)
23835
24324
  throw new FileOpError("PATH_ESCAPE", "Directory changed during write");
23836
24325
  const again = await this.#currentHash(rootReal, target);
23837
24326
  if (again.sha256 !== before.sha256) {
23838
24327
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed during write", { path: rel, current_sha256: again.sha256 });
23839
24328
  }
23840
- await (0, import_promises9.rename)(temp, target);
24329
+ await (0, import_promises10.rename)(temp, target);
23841
24330
  renamed = true;
23842
24331
  await fsyncDirectory(parentReal);
23843
24332
  } catch (error63) {
23844
24333
  throw mapFsError(error63, rel);
23845
24334
  } finally {
23846
24335
  if (!renamed)
23847
- await (0, import_promises9.unlink)(temp).catch(() => void 0);
24336
+ await (0, import_promises10.unlink)(temp).catch(() => void 0);
23848
24337
  }
23849
24338
  }
23850
24339
  #requireWritable() {
@@ -23872,7 +24361,7 @@ var RootedFs = class {
23872
24361
  const { rel, real, rootReal } = await this.resolveExisting(input2);
23873
24362
  let info;
23874
24363
  try {
23875
- info = await (0, import_promises9.lstat)(real);
24364
+ info = await (0, import_promises10.lstat)(real);
23876
24365
  } catch (error63) {
23877
24366
  throw mapFsError(error63, rel);
23878
24367
  }
@@ -23894,7 +24383,7 @@ var RootedFs = class {
23894
24383
  }
23895
24384
  }
23896
24385
  if (type === "directory") {
23897
- const entries = await (0, import_promises9.readdir)(real).then((names) => names.length, () => void 0);
24386
+ const entries = await (0, import_promises10.readdir)(real).then((names) => names.length, () => void 0);
23898
24387
  return entries === void 0 ? base2 : { ...base2, entries };
23899
24388
  }
23900
24389
  return base2;
@@ -23944,14 +24433,14 @@ var RootedFs = class {
23944
24433
  let created = false;
23945
24434
  for (let index = 1; index <= segments.length; index += 1) {
23946
24435
  const { rootReal, target } = await this.#resolveNew(segments.slice(0, index).join("/"));
23947
- const existing = await (0, import_promises9.lstat)(target).catch(() => null);
24436
+ const existing = await (0, import_promises10.lstat)(target).catch(() => null);
23948
24437
  if (existing) {
23949
24438
  const segment = segments.slice(0, index).join("/");
23950
24439
  if (existing.isSymbolicLink()) {
23951
- const real = await (0, import_promises9.realpath)(target).catch(() => null);
24440
+ const real = await (0, import_promises10.realpath)(target).catch(() => null);
23952
24441
  if (real === null || !this.#inside(rootReal, real))
23953
24442
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root", { path: segment });
23954
- if (!(await (0, import_promises9.stat)(real)).isDirectory())
24443
+ if (!(await (0, import_promises10.stat)(real)).isDirectory())
23955
24444
  throw new FileOpError("ALREADY_EXISTS", "A file with that name exists", { path: segment });
23956
24445
  continue;
23957
24446
  }
@@ -23960,12 +24449,12 @@ var RootedFs = class {
23960
24449
  continue;
23961
24450
  }
23962
24451
  try {
23963
- await (0, import_promises9.mkdir)(target, { mode: 511 });
24452
+ await (0, import_promises10.mkdir)(target, { mode: 511 });
23964
24453
  } catch (error63) {
23965
24454
  if (errorCode2(error63) !== "EEXIST")
23966
24455
  throw mapFsError(error63, rel);
23967
24456
  }
23968
- if (!this.#inside(rootReal, await (0, import_promises9.realpath)(target)))
24457
+ if (!this.#inside(rootReal, await (0, import_promises10.realpath)(target)))
23969
24458
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
23970
24459
  created = true;
23971
24460
  }
@@ -23975,20 +24464,20 @@ var RootedFs = class {
23975
24464
  async move(input2, to) {
23976
24465
  this.#requireWritable();
23977
24466
  const from = await this.#resolveNew(input2);
23978
- const source = await (0, import_promises9.lstat)(from.target).catch(() => null);
24467
+ const source = await (0, import_promises10.lstat)(from.target).catch(() => null);
23979
24468
  if (!source)
23980
24469
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: from.rel });
23981
- const sourceReal = await (0, import_promises9.realpath)(from.target).catch(() => from.target);
24470
+ const sourceReal = await (0, import_promises10.realpath)(from.target).catch(() => from.target);
23982
24471
  if (this.#protected.some((path) => isSameOrInside(from.target, path) || isSameOrInside(sourceReal, path))) {
23983
24472
  throw new FileOpError("PATH_DENIED", "Path contains files the agent protects", { path: from.rel });
23984
24473
  }
23985
24474
  const dest = await this.#resolveNew(to);
23986
24475
  if (isSameOrInside(from.target, dest.target))
23987
24476
  throw new FileOpError("PATH_INVALID", "Cannot move a folder into itself");
23988
- if (await (0, import_promises9.lstat)(dest.target).then(() => true, () => false))
24477
+ if (await (0, import_promises10.lstat)(dest.target).then(() => true, () => false))
23989
24478
  throw new FileOpError("ALREADY_EXISTS", "The destination already exists", { path: dest.rel });
23990
24479
  try {
23991
- await (0, import_promises9.rename)(from.target, dest.target);
24480
+ await (0, import_promises10.rename)(from.target, dest.target);
23992
24481
  } catch (error63) {
23993
24482
  throw mapFsError(error63, from.rel);
23994
24483
  }
@@ -23999,14 +24488,14 @@ var RootedFs = class {
23999
24488
  async delete(input2, expectedSha256) {
24000
24489
  this.#requireWritable();
24001
24490
  const { rel, rootReal, target, parentReal } = await this.#resolveNew(input2);
24002
- const info = await (0, import_promises9.lstat)(target).catch(() => null);
24491
+ const info = await (0, import_promises10.lstat)(target).catch(() => null);
24003
24492
  if (!info)
24004
24493
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: rel });
24005
24494
  if (info.isDirectory()) {
24006
24495
  if (expectedSha256 !== null)
24007
24496
  throw new FileOpError("NOT_A_FILE", "Path is a directory; pass expected_sha256 null", { path: rel });
24008
24497
  try {
24009
- await (0, import_promises9.rmdir)(target);
24498
+ await (0, import_promises10.rmdir)(target);
24010
24499
  } catch (error63) {
24011
24500
  if (errorCode2(error63) === "ENOTEMPTY" || errorCode2(error63) === "EEXIST")
24012
24501
  throw new FileOpError("NOT_EMPTY", "Directory is not empty", { path: rel });
@@ -24020,7 +24509,7 @@ var RootedFs = class {
24020
24509
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: current.sha256 });
24021
24510
  }
24022
24511
  try {
24023
- await (0, import_promises9.unlink)(target);
24512
+ await (0, import_promises10.unlink)(target);
24024
24513
  } catch (error63) {
24025
24514
  throw mapFsError(error63, rel);
24026
24515
  }
@@ -24064,7 +24553,7 @@ function isExpired(dispatch2, nowMs) {
24064
24553
  return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= nowMs || deadline <= nowMs;
24065
24554
  }
24066
24555
  function isSupportedCapability(capability2) {
24067
- return capabilityDefinition(capability2)?.connector === "desktop" && (isDesktopCapability(capability2) || isSshCapability(capability2) || isShellCapability(capability2));
24556
+ return capabilityDefinition(capability2)?.connector === "desktop" && (isAgentCapability(capability2) || isDesktopCapability(capability2) || isSshCapability(capability2) || isShellCapability(capability2));
24068
24557
  }
24069
24558
  function checkLocalPolicy(dispatch2, config2, sshHosts = []) {
24070
24559
  if (dispatch2.resource.connector !== "desktop") {
@@ -24077,6 +24566,16 @@ function checkLocalPolicy(dispatch2, config2, sshHosts = []) {
24077
24566
  if (dispatch2.risk !== capabilityDefinition(capability2)?.risk) {
24078
24567
  return { code: "POLICY_DENIED", reason: "RISK", message: "Task risk does not match its capability" };
24079
24568
  }
24569
+ if (isAgentCapability(capability2)) {
24570
+ const resourceId = dispatch2.resource.resource_id;
24571
+ const knownResource = config2.roots.some((root2) => root2.root_id === resourceId) || config2.full_access === true && resourceId === SHELL_RESOURCE_ID || sshHosts.some((host) => host.resource_id === resourceId);
24572
+ if (!knownResource)
24573
+ return { code: "TARGET_MISMATCH", reason: "UNKNOWN_RESOURCE", message: "Lifecycle task resource is not configured on this device" };
24574
+ const parsed2 = safeParseCapabilityPayload(capability2, dispatch2.payload);
24575
+ if (!parsed2.success)
24576
+ return { code: "INVALID_MESSAGE", reason: "PAYLOAD", message: "Task payload is invalid" };
24577
+ return { capability: capability2, agent: true, payload: parsed2.data };
24578
+ }
24080
24579
  if (isShellCapability(capability2)) {
24081
24580
  if (config2.full_access !== true) {
24082
24581
  return { code: "POLICY_DENIED", reason: "FULL_ACCESS_OFF", message: "Full access is off on this device (conbridge-agent access full turns it on)" };
@@ -24126,6 +24625,9 @@ function isSshTask(value) {
24126
24625
  function isShellTask(value) {
24127
24626
  return "shell" in value;
24128
24627
  }
24628
+ function isAgentTask(value) {
24629
+ return "agent" in value;
24630
+ }
24129
24631
 
24130
24632
  // dist/dispatcher.js
24131
24633
  var CANCELLED_BEFORE_START = Object.freeze({
@@ -24171,6 +24673,7 @@ var Dispatcher = class {
24171
24673
  /** Cancels whose DONE CANCELLED write is in progress (or failed): never execute these ids. */
24172
24674
  #cancelling = /* @__PURE__ */ new Set();
24173
24675
  #pending = /* @__PURE__ */ new Set();
24676
+ #scheduledRemovals = /* @__PURE__ */ new Map();
24174
24677
  #logger;
24175
24678
  #protectedPaths;
24176
24679
  constructor(options) {
@@ -24290,6 +24793,10 @@ var Dispatcher = class {
24290
24793
  this.#sendResult(dispatch2, denialResult(authorized));
24291
24794
  return;
24292
24795
  }
24796
+ if (isAgentTask(authorized) && !this.#options.scheduleRemoval) {
24797
+ this.#sendResult(dispatch2, denialResult({ code: "POLICY_DENIED", reason: "CAPABILITY", message: "Lifecycle removal is not available on this agent" }));
24798
+ return;
24799
+ }
24293
24800
  const sshExecutor = this.#options.ssh;
24294
24801
  if (isSshTask(authorized) && !sshExecutor) {
24295
24802
  this.#sendResult(dispatch2, denialResult({ code: "POLICY_DENIED", reason: "CAPABILITY", message: "SSH is not available on this agent" }));
@@ -24305,9 +24812,9 @@ var Dispatcher = class {
24305
24812
  const state2 = { phase: "pending", cancelled: false, meta: meta3 };
24306
24813
  this.#inFlight.set(taskId2, state2);
24307
24814
  try {
24308
- const executionNonce = (0, import_node_crypto7.randomUUID)();
24815
+ const executionNonce = (0, import_node_crypto8.randomUUID)();
24309
24816
  this.#sendAck(dispatch2, "RECEIVED", executionNonce);
24310
- let fileTask = isSshTask(authorized) || isShellTask(authorized) ? null : authorized;
24817
+ let fileTask = isSshTask(authorized) || isShellTask(authorized) || isAgentTask(authorized) ? null : authorized;
24311
24818
  let fs = fileTask ? new RootedFs(fileTask.root, effectiveDenyGlobs(config2), { protectedPaths: this.#protectedPaths }) : null;
24312
24819
  if (fileTask && fileTask.capability === "files.write" && config2.confirm_writes) {
24313
24820
  const payload = fileTask.payload;
@@ -24359,6 +24866,34 @@ var Dispatcher = class {
24359
24866
  }
24360
24867
  this.#sendAck(dispatch2, "STARTED", executionNonce);
24361
24868
  const taskContext = { taskId: taskId2, contextId: dispatch2.context_id, actingUserId: actingUser };
24869
+ if (isAgentTask(authorized)) {
24870
+ let deadline = authorized.payload.run_at_ms;
24871
+ this.#scheduledRemovals.set(taskId2, meta3);
24872
+ try {
24873
+ deadline = await this.#options.scheduleRemoval(dispatch2, deadline) ?? deadline;
24874
+ if (state2.cancelled) {
24875
+ await this.#options.cancelRemoval?.(taskId2);
24876
+ return;
24877
+ }
24878
+ const scheduled = {
24879
+ state: "SUCCEEDED",
24880
+ executed: true,
24881
+ safe_message: "Agent removal scheduled",
24882
+ output_excerpt: excerpt({ state: "scheduled", deadline })
24883
+ };
24884
+ await journal.done(taskId2, meta3, scheduled).catch(() => {
24885
+ this.#logger.error("failed to journal removal schedule", { task_id: taskId2 });
24886
+ });
24887
+ if (!state2.cancelled)
24888
+ this.#sendResult(dispatch2, scheduled);
24889
+ } catch {
24890
+ this.#scheduledRemovals.delete(taskId2);
24891
+ const failed = { state: "FAILED", executed: false, safe_message: "Agent removal could not be scheduled" };
24892
+ await journal.done(taskId2, meta3, failed).catch(() => void 0);
24893
+ this.#sendResult(dispatch2, failed);
24894
+ }
24895
+ return;
24896
+ }
24362
24897
  const outcome = isSshTask(authorized) ? await sshExecutor.run(authorized, taskContext).catch(() => ({
24363
24898
  // Unexpected failure after STARTED: whether ssh ran is not known here, so never claim it did not.
24364
24899
  result: {
@@ -24412,7 +24947,7 @@ var Dispatcher = class {
24412
24947
  const authorized = checkLocalPolicy(dispatch2, config2, this.#options.sshHosts?.() ?? []);
24413
24948
  if (isDenial(authorized))
24414
24949
  return { refused: denialResult(authorized), reason: authorized.reason };
24415
- if (isSshTask(authorized) || isShellTask(authorized)) {
24950
+ if (isSshTask(authorized) || isShellTask(authorized) || isAgentTask(authorized)) {
24416
24951
  return { refused: denialResult({ code: "POLICY_DENIED", reason: "CAPABILITY", message: "Task is not a file task" }), reason: "CAPABILITY" };
24417
24952
  }
24418
24953
  return { task: authorized, config: config2 };
@@ -24430,6 +24965,20 @@ var Dispatcher = class {
24430
24965
  }
24431
24966
  const journal = this.#options.journal;
24432
24967
  const state2 = this.#inFlight.get(taskId2);
24968
+ const scheduledMeta = this.#scheduledRemovals.get(taskId2);
24969
+ if (this.#options.cancelRemoval) {
24970
+ const cancelled = await this.#options.cancelRemoval(taskId2);
24971
+ if (cancelled === false)
24972
+ return;
24973
+ if (cancelled === true || scheduledMeta) {
24974
+ this.#scheduledRemovals.delete(taskId2);
24975
+ if (state2)
24976
+ state2.cancelled = true;
24977
+ const record3 = journal.get(taskId2);
24978
+ await this.#tombstone(taskId2, scheduledMeta ?? { capability: "agent.remove", nonce: record3?.nonce ?? void 0 }, cancel2);
24979
+ return;
24980
+ }
24981
+ }
24433
24982
  if (state2) {
24434
24983
  if (state2.phase === "starting") {
24435
24984
  this.#logger.warn("cancel ignored: task already started and cannot be undone", { task_id: taskId2, reason: cancel2.reason });
@@ -24544,16 +25093,16 @@ var Dispatcher = class {
24544
25093
  };
24545
25094
 
24546
25095
  // dist/monitor.js
24547
- var import_promises10 = require("node:fs/promises");
24548
- var import_node_os3 = require("node:os");
25096
+ var import_promises11 = require("node:fs/promises");
25097
+ var import_node_os4 = require("node:os");
24549
25098
  var defaultMonitorSystem = {
24550
25099
  platform: process.platform,
24551
- cpus: import_node_os3.cpus,
24552
- loadavg: import_node_os3.loadavg,
24553
- totalmem: import_node_os3.totalmem,
24554
- freemem: import_node_os3.freemem,
24555
- uptime: import_node_os3.uptime,
24556
- statfs: (path) => (0, import_promises10.statfs)(path),
25100
+ cpus: import_node_os4.cpus,
25101
+ loadavg: import_node_os4.loadavg,
25102
+ totalmem: import_node_os4.totalmem,
25103
+ freemem: import_node_os4.freemem,
25104
+ uptime: import_node_os4.uptime,
25105
+ statfs: (path) => (0, import_promises11.statfs)(path),
24557
25106
  env: process.env
24558
25107
  };
24559
25108
  var MONITOR_FIRST_SAMPLE_MS = 1e3;
@@ -24682,17 +25231,17 @@ var MonitorLoop = class {
24682
25231
  };
24683
25232
 
24684
25233
  // dist/inventory/loop.js
24685
- var import_node_crypto9 = require("node:crypto");
25234
+ var import_node_crypto10 = require("node:crypto");
24686
25235
  var import_node_zlib = require("node:zlib");
24687
25236
 
24688
25237
  // dist/ssh/exec.js
24689
- var import_node_child_process6 = require("node:child_process");
24690
- var import_node_path13 = require("node:path");
25238
+ var import_node_child_process7 = require("node:child_process");
25239
+ var import_node_path14 = require("node:path");
24691
25240
 
24692
25241
  // dist/ssh/hosts.js
24693
- var import_node_crypto8 = require("node:crypto");
24694
- var import_promises11 = require("node:fs/promises");
24695
- var import_node_path12 = require("node:path");
25242
+ var import_node_crypto9 = require("node:crypto");
25243
+ var import_promises12 = require("node:fs/promises");
25244
+ var import_node_path13 = require("node:path");
24696
25245
  var MAX_SSH_HOSTS = 64;
24697
25246
  var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
24698
25247
  var DNS_HOST = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
@@ -24702,7 +25251,7 @@ function isValidSshHost(value) {
24702
25251
  return DNS_HOST.test(value) || IPV6_HOST.test(value);
24703
25252
  }
24704
25253
  function isValidIdentityPath(value) {
24705
- return (0, import_node_path12.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
25254
+ return (0, import_node_path13.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
24706
25255
  }
24707
25256
  var PINNABLE_KEY_TYPES = Object.freeze([
24708
25257
  "ssh-ed25519",
@@ -24727,17 +25276,17 @@ var sshHostSchema = external_exports.strictObject({
24727
25276
  });
24728
25277
  var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS) });
24729
25278
  function sshPaths(stateDir) {
24730
- const dir = (0, import_node_path12.join)(stateDir, "ssh");
24731
- return { dir, hosts: (0, import_node_path12.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path12.join)(dir, "known_hosts") };
25279
+ const dir = (0, import_node_path13.join)(stateDir, "ssh");
25280
+ return { dir, hosts: (0, import_node_path13.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path13.join)(dir, "known_hosts") };
24732
25281
  }
24733
25282
  function knownHostsPath(paths, resourceId) {
24734
- return (0, import_node_path12.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
25283
+ return (0, import_node_path13.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
24735
25284
  }
24736
25285
  function hostKeyAlias(host) {
24737
25286
  return "conbridge-" + host.resource_id;
24738
25287
  }
24739
25288
  function fingerprintOf(publicKey) {
24740
- return "SHA256:" + (0, import_node_crypto8.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
25289
+ return "SHA256:" + (0, import_node_crypto9.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
24741
25290
  }
24742
25291
  function normalizeFingerprint(value) {
24743
25292
  const trimmed = value.trim();
@@ -24767,7 +25316,7 @@ function preferredKey(keys) {
24767
25316
  async function loadSshHosts(paths) {
24768
25317
  let text6;
24769
25318
  try {
24770
- text6 = await (0, import_promises11.readFile)(paths.hosts, "utf8");
25319
+ text6 = await (0, import_promises12.readFile)(paths.hosts, "utf8");
24771
25320
  } catch (error63) {
24772
25321
  if (errorCode2(error63) === "ENOENT")
24773
25322
  return [];
@@ -24777,8 +25326,8 @@ async function loadSshHosts(paths) {
24777
25326
  }
24778
25327
  async function ensureSshDirs(paths) {
24779
25328
  for (const dir of [paths.dir, paths.knownHostsDir]) {
24780
- await (0, import_promises11.mkdir)(dir, { recursive: true, mode: 448 });
24781
- await (0, import_promises11.chmod)(dir, 448);
25329
+ await (0, import_promises12.mkdir)(dir, { recursive: true, mode: 448 });
25330
+ await (0, import_promises12.chmod)(dir, 448);
24782
25331
  }
24783
25332
  }
24784
25333
  async function saveSshHosts(paths, hosts) {
@@ -24802,7 +25351,7 @@ async function validateNewHost(input2) {
24802
25351
  if (input2.identity !== void 0) {
24803
25352
  if (!isValidIdentityPath(input2.identity))
24804
25353
  throw new Error("Identity must be an absolute path without quotes, % or control characters");
24805
- const info = await (0, import_promises11.stat)(input2.identity).catch(() => null);
25354
+ const info = await (0, import_promises12.stat)(input2.identity).catch(() => null);
24806
25355
  if (!info?.isFile())
24807
25356
  throw new Error("Identity file not found");
24808
25357
  }
@@ -24815,7 +25364,7 @@ async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date())
24815
25364
  if (hosts.length >= MAX_SSH_HOSTS)
24816
25365
  throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
24817
25366
  const host = sshHostSchema.parse({
24818
- resource_id: (0, import_node_crypto8.randomUUID)(),
25367
+ resource_id: (0, import_node_crypto9.randomUUID)(),
24819
25368
  alias: input2.alias,
24820
25369
  host: input2.host,
24821
25370
  port: input2.port ?? 22,
@@ -24859,7 +25408,7 @@ async function removeSshHost(paths, alias) {
24859
25408
  if (!host)
24860
25409
  return false;
24861
25410
  await saveSshHosts(paths, hosts.filter((entry) => entry !== host));
24862
- await (0, import_promises11.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
25411
+ await (0, import_promises12.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
24863
25412
  return true;
24864
25413
  }
24865
25414
  function hostAddress(host) {
@@ -24874,7 +25423,7 @@ function inventoryResource2(host) {
24874
25423
  // dist/ssh/exec.js
24875
25424
  var DEFAULT_SSH_BINARIES = Object.freeze({ ssh: "/usr/bin/ssh", keyscan: "/usr/bin/ssh-keyscan" });
24876
25425
  function sshBinariesFromEnv(env = process.env) {
24877
- const pick2 = (value, fallback) => value && (0, import_node_path13.isAbsolute)(value) ? value : fallback;
25426
+ const pick2 = (value, fallback) => value && (0, import_node_path14.isAbsolute)(value) ? value : fallback;
24878
25427
  return { ssh: pick2(env.CONBRIDGE_SSH_BIN, DEFAULT_SSH_BINARIES.ssh), keyscan: pick2(env.CONBRIDGE_SSH_KEYSCAN_BIN, DEFAULT_SSH_BINARIES.keyscan) };
24879
25428
  }
24880
25429
  function sshChildEnv(env = process.env) {
@@ -24887,14 +25436,14 @@ function sshChildEnv(env = process.env) {
24887
25436
  }
24888
25437
  function runProcess(file2, args, options) {
24889
25438
  const started = Date.now();
24890
- return new Promise((resolve8) => {
25439
+ return new Promise((resolve9) => {
24891
25440
  const kept = { stdout: [], stderr: [] };
24892
25441
  const totals = { stdout: 0, stderr: 0 };
24893
25442
  let keptBytes = 0;
24894
25443
  let truncated = false;
24895
25444
  let timedOut = false;
24896
25445
  let settled = false;
24897
- const child = (0, import_node_child_process6.spawn)(file2, [...args], { stdio: ["ignore", "pipe", "pipe"], env: options.env, shell: false });
25446
+ const child = (0, import_node_child_process7.spawn)(file2, [...args], { stdio: ["ignore", "pipe", "pipe"], env: options.env, shell: false });
24898
25447
  const collect = (stream) => (chunk2) => {
24899
25448
  totals[stream] += chunk2.length;
24900
25449
  const room = options.maxBytes - keptBytes;
@@ -24923,7 +25472,7 @@ function runProcess(file2, args, options) {
24923
25472
  clearTimeout(timer);
24924
25473
  if (killTimer)
24925
25474
  clearTimeout(killTimer);
24926
- resolve8({
25475
+ resolve9({
24927
25476
  exitCode,
24928
25477
  timedOut,
24929
25478
  truncated,
@@ -25640,11 +26189,11 @@ async function collectSshHostInventory(host, exec, now = () => /* @__PURE__ */ n
25640
26189
  // dist/inventory/loop.js
25641
26190
  var SEND_SPACING_MS = 2e3;
25642
26191
  var HOST_MIN_INTERVAL_MS = 6e4;
25643
- function encodeSnapshot(snapshot, requestId, runId = (0, import_node_crypto9.randomUUID)(), resourceId) {
26192
+ function encodeSnapshot(snapshot, requestId, runId = (0, import_node_crypto10.randomUUID)(), resourceId) {
25644
26193
  const gz = (0, import_node_zlib.gzipSync)(Buffer.from(JSON.stringify(snapshot), "utf8"), { level: 9 });
25645
26194
  if (gz.byteLength > INVENTORY_MAX_COMPRESSED_BYTES)
25646
26195
  return null;
25647
- const sha2563 = (0, import_node_crypto9.createHash)("sha256").update(gz).digest("hex");
26196
+ const sha2563 = (0, import_node_crypto10.createHash)("sha256").update(gz).digest("hex");
25648
26197
  const data = gz.toString("base64");
25649
26198
  const total = Math.max(1, Math.ceil(data.length / INVENTORY_PART_CHARS));
25650
26199
  return Array.from({ length: total }, (_, sequence) => ({
@@ -25754,8 +26303,8 @@ var InventoryLoop = class {
25754
26303
  const spacing = this.#options.sendSpacingMs ?? SEND_SPACING_MS;
25755
26304
  const wait = this.#lastSendEndMs === null ? 0 : this.#lastSendEndMs + spacing - this.#now();
25756
26305
  if (wait > 0)
25757
- await new Promise((resolve8) => {
25758
- setTimeout(resolve8, wait).unref?.();
26306
+ await new Promise((resolve9) => {
26307
+ setTimeout(resolve9, wait).unref?.();
25759
26308
  });
25760
26309
  return this.#active;
25761
26310
  }
@@ -25813,7 +26362,7 @@ var InventoryLoop = class {
25813
26362
  this.#logger.warn("ssh host inventory skipped", { host: host.alias, reason: outcome.reason });
25814
26363
  continue;
25815
26364
  }
25816
- const parts = encodeSnapshot(outcome.snapshot, requestId, (0, import_node_crypto9.randomUUID)(), host.resource_id);
26365
+ const parts = encodeSnapshot(outcome.snapshot, requestId, (0, import_node_crypto10.randomUUID)(), host.resource_id);
25817
26366
  if (!parts) {
25818
26367
  this.#logger.warn("ssh host inventory skipped", { host: host.alias, reason: "snapshot too large to send" });
25819
26368
  continue;
@@ -25833,10 +26382,10 @@ var InventoryLoop = class {
25833
26382
  };
25834
26383
 
25835
26384
  // dist/inventory/collector.js
25836
- var import_node_child_process7 = require("node:child_process");
26385
+ var import_node_child_process8 = require("node:child_process");
25837
26386
  var import_node_fs3 = require("node:fs");
25838
- var import_promises12 = require("node:fs/promises");
25839
- var import_node_os4 = require("node:os");
26387
+ var import_promises13 = require("node:fs/promises");
26388
+ var import_node_os5 = require("node:os");
25840
26389
 
25841
26390
  // dist/inventory/parsers/services.js
25842
26391
  var NAME_MAX2 = 200;
@@ -26667,14 +27216,16 @@ function parseAptPolicy(stdout) {
26667
27216
  return result2;
26668
27217
  let name3 = null;
26669
27218
  let installed = null;
27219
+ let candidate = null;
26670
27220
  let inInstalledVersion = false;
26671
27221
  let sources = [];
26672
27222
  let full = false;
26673
27223
  const finish = () => {
26674
27224
  if (name3 !== null && installed !== null)
26675
- result2.set(name3, originOf(sources));
27225
+ result2.set(name3, { ...originOf(sources), candidate });
26676
27226
  name3 = null;
26677
27227
  installed = null;
27228
+ candidate = null;
26678
27229
  inInstalledVersion = false;
26679
27230
  sources = [];
26680
27231
  if (result2.size >= MAX_PACKAGES3)
@@ -26714,6 +27265,11 @@ function parseAptPolicy(stdout) {
26714
27265
  installed = value === "" || value === NOT_INSTALLED ? null : value;
26715
27266
  continue;
26716
27267
  }
27268
+ if (indent === 2 && body.startsWith("Candidate:")) {
27269
+ const value = body.slice("Candidate:".length).trim();
27270
+ candidate = value === "" || value === NOT_INSTALLED ? null : value;
27271
+ continue;
27272
+ }
26717
27273
  if (inInstalledVersion && indent >= 4)
26718
27274
  inInstalledVersion = false;
26719
27275
  }
@@ -26767,6 +27323,123 @@ function classifyAptSource(location, suite) {
26767
27323
  return "third_party";
26768
27324
  }
26769
27325
 
27326
+ // dist/inventory/parsers/apt-config.js
27327
+ var UPDATE_LISTS_KEY = "APT::Periodic::Update-Package-Lists";
27328
+ var UNATTENDED_KEY = "APT::Periodic::Unattended-Upgrade";
27329
+ function truthy(raw) {
27330
+ if (raw === null)
27331
+ return false;
27332
+ let value = raw.trim();
27333
+ if (value.endsWith(";"))
27334
+ value = value.slice(0, -1).trim();
27335
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"'))
27336
+ value = value.slice(1, -1);
27337
+ if (value === "")
27338
+ return false;
27339
+ if (value.toLowerCase() === "always")
27340
+ return true;
27341
+ const number4 = Number(value);
27342
+ return Number.isFinite(number4) && number4 > 0;
27343
+ }
27344
+ function parseAptConfig(stdout) {
27345
+ let updateListsValue = null;
27346
+ let unattendedValue = null;
27347
+ if (typeof stdout === "string") {
27348
+ for (const raw of stdout.split(/\r?\n/)) {
27349
+ const line = raw.trim();
27350
+ if (line === "")
27351
+ continue;
27352
+ const space = line.search(/\s/);
27353
+ const key = space < 0 ? line : line.slice(0, space);
27354
+ const value = space < 0 ? "" : line.slice(space + 1).trim();
27355
+ if (key === UPDATE_LISTS_KEY)
27356
+ updateListsValue = value;
27357
+ else if (key === UNATTENDED_KEY)
27358
+ unattendedValue = value;
27359
+ }
27360
+ }
27361
+ return { update_lists: truthy(updateListsValue), unattended: truthy(unattendedValue) };
27362
+ }
27363
+ function parseAptHold(stdout) {
27364
+ if (typeof stdout !== "string")
27365
+ return [];
27366
+ const held = [];
27367
+ for (const raw of stdout.split(/\r?\n/)) {
27368
+ const name3 = raw.trim();
27369
+ if (!/^[a-z0-9][a-z0-9+.:~-]*$/.test(name3) || name3.length > 200)
27370
+ continue;
27371
+ held.push(name3);
27372
+ }
27373
+ return held;
27374
+ }
27375
+
27376
+ // dist/inventory/parsers/apt-sources.js
27377
+ function oneLineHasSecurity(text6) {
27378
+ if (typeof text6 !== "string")
27379
+ return false;
27380
+ for (const raw of text6.split(/\r?\n/)) {
27381
+ const line = raw.trim();
27382
+ if (line === "" || line.startsWith("#"))
27383
+ continue;
27384
+ const suite = oneLineSuite(line);
27385
+ if (suite !== null && suite.endsWith("-security"))
27386
+ return true;
27387
+ }
27388
+ return false;
27389
+ }
27390
+ function oneLineSuite(line) {
27391
+ const tokens = line.split(/\s+/).filter((token) => token !== "");
27392
+ const type = tokens[0];
27393
+ if (type !== "deb" && type !== "deb-src")
27394
+ return null;
27395
+ let index = 1;
27396
+ if (tokens[index]?.startsWith("[")) {
27397
+ while (index < tokens.length && !tokens[index].endsWith("]"))
27398
+ index += 1;
27399
+ index += 1;
27400
+ }
27401
+ const uri = tokens[index];
27402
+ if (!uri)
27403
+ return null;
27404
+ return tokens[index + 1] ?? null;
27405
+ }
27406
+ function deb822HasSecurity(text6) {
27407
+ if (typeof text6 !== "string")
27408
+ return false;
27409
+ for (const stanza of text6.split(/\n[ \t]*\n/)) {
27410
+ let enabled = true;
27411
+ const suites = [];
27412
+ let current = null;
27413
+ for (const raw of stanza.split(/\r?\n/)) {
27414
+ const line = raw.replace(/\s+$/, "");
27415
+ if (line === "" || line.startsWith("#"))
27416
+ continue;
27417
+ if (/^[ \t]/.test(line)) {
27418
+ if (current === "Suites")
27419
+ suites.push(...line.trim().split(/\s+/).filter((item) => item !== ""));
27420
+ continue;
27421
+ }
27422
+ const colon = line.indexOf(":");
27423
+ if (colon <= 0)
27424
+ continue;
27425
+ const field = line.slice(0, colon);
27426
+ const value = line.slice(colon + 1).trim();
27427
+ if (field === "Enabled") {
27428
+ enabled = value.toLowerCase() !== "no";
27429
+ current = null;
27430
+ } else if (field === "Suites") {
27431
+ suites.push(...value.split(/\s+/).filter((item) => item !== ""));
27432
+ current = "Suites";
27433
+ } else {
27434
+ current = null;
27435
+ }
27436
+ }
27437
+ if (enabled && suites.some((suite) => suite.endsWith("-security")))
27438
+ return true;
27439
+ }
27440
+ return false;
27441
+ }
27442
+
26770
27443
  // dist/inventory/parsers/health.js
26771
27444
  var SOURCE_MAX = 120;
26772
27445
  var TEMPLATE_MAX = 300;
@@ -27336,12 +28009,12 @@ function endpointOf(port, protocol, cert, hsts) {
27336
28009
  };
27337
28010
  }
27338
28011
  function hstsOf(port) {
27339
- return new Promise((resolve8) => {
28012
+ return new Promise((resolve9) => {
27340
28013
  let settled = false;
27341
28014
  const finish = (value) => {
27342
28015
  if (!settled) {
27343
28016
  settled = true;
27344
- resolve8(value);
28017
+ resolve9(value);
27345
28018
  }
27346
28019
  };
27347
28020
  const req = (0, import_node_https.request)({ host: "127.0.0.1", port, method: "HEAD", path: "/", rejectUnauthorized: false, timeout: TIMEOUT_MS, headers: { host: "localhost", "user-agent": "conbridge-agent/tls-check" } }, (res) => {
@@ -27358,7 +28031,7 @@ function hstsOf(port) {
27358
28031
  });
27359
28032
  }
27360
28033
  function createTlsProbe(webPorts = WEB_PORTS) {
27361
- return (port) => new Promise((resolve8) => {
28034
+ return (port) => new Promise((resolve9) => {
27362
28035
  let settled = false;
27363
28036
  const socket = (0, import_node_tls.connect)({
27364
28037
  host: "127.0.0.1",
@@ -27373,7 +28046,7 @@ function createTlsProbe(webPorts = WEB_PORTS) {
27373
28046
  if (!settled) {
27374
28047
  settled = true;
27375
28048
  socket.destroy();
27376
- resolve8(value);
28049
+ resolve9(value);
27377
28050
  }
27378
28051
  };
27379
28052
  socket.once("secureConnect", () => {
@@ -27405,6 +28078,216 @@ async function collectTlsEndpoints(probe, ports = TLS_PORTS, width = 4) {
27405
28078
  return found.filter((entry) => entry !== null);
27406
28079
  }
27407
28080
 
28081
+ // dist/inventory/parsers/listeners.js
28082
+ var CONTAINER_PLUMBING = /* @__PURE__ */ new Set(["docker-proxy", "containerd-shim", "rootlesskit"]);
28083
+ function classifyIpv4(address) {
28084
+ if (address === "0.0.0.0")
28085
+ return "public";
28086
+ if (address.startsWith("127."))
28087
+ return "loopback";
28088
+ if (address.startsWith("10."))
28089
+ return "private";
28090
+ if (address.startsWith("192.168."))
28091
+ return "private";
28092
+ if (address.startsWith("169.254."))
28093
+ return "private";
28094
+ if (address.startsWith("172.")) {
28095
+ const second = Number(address.split(".")[1]);
28096
+ if (Number.isInteger(second) && second >= 16 && second <= 31)
28097
+ return "private";
28098
+ return "public";
28099
+ }
28100
+ if (address.startsWith("100.")) {
28101
+ const second = Number(address.split(".")[1]);
28102
+ if (Number.isInteger(second) && second >= 64 && second <= 127)
28103
+ return "private";
28104
+ return "public";
28105
+ }
28106
+ return "public";
28107
+ }
28108
+ function classifyBind(address) {
28109
+ if (typeof address !== "string")
28110
+ return "public";
28111
+ const raw = address.trim();
28112
+ if (raw === "" || raw === "*")
28113
+ return "public";
28114
+ const percent = raw.indexOf("%");
28115
+ const addr = percent < 0 ? raw : raw.slice(0, percent);
28116
+ if (addr.includes(":")) {
28117
+ const lower = addr.toLowerCase();
28118
+ if (lower === "::")
28119
+ return "public";
28120
+ if (lower === "::1")
28121
+ return "loopback";
28122
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
28123
+ if (mapped)
28124
+ return classifyIpv4(mapped[1] ?? "");
28125
+ if (/^fe[89ab]/.test(lower))
28126
+ return "private";
28127
+ if (/^f[cd]/.test(lower))
28128
+ return "private";
28129
+ return "public";
28130
+ }
28131
+ return classifyIpv4(addr);
28132
+ }
28133
+ function splitAddrPort(field) {
28134
+ let address;
28135
+ let portText2;
28136
+ if (field.startsWith("[")) {
28137
+ const close = field.indexOf("]");
28138
+ if (close < 0)
28139
+ return void 0;
28140
+ address = field.slice(1, close);
28141
+ const rest = field.slice(close + 1);
28142
+ if (!rest.startsWith(":"))
28143
+ return void 0;
28144
+ portText2 = rest.slice(1);
28145
+ } else {
28146
+ const colon = field.lastIndexOf(":");
28147
+ if (colon < 0)
28148
+ return void 0;
28149
+ address = field.slice(0, colon);
28150
+ portText2 = field.slice(colon + 1);
28151
+ }
28152
+ const port = Number(portText2);
28153
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
28154
+ return void 0;
28155
+ return { address, port };
28156
+ }
28157
+ function parseUsers(users) {
28158
+ if (typeof users !== "string" || users === "")
28159
+ return { pids: [], process: null };
28160
+ const pids = [];
28161
+ const pidRe = /pid=(\d+)/g;
28162
+ let match;
28163
+ while ((match = pidRe.exec(users)) !== null) {
28164
+ const pid = Number(match[1]);
28165
+ if (Number.isInteger(pid) && pid > 0 && !pids.includes(pid))
28166
+ pids.push(pid);
28167
+ }
28168
+ const name3 = /"([^"]*)"/.exec(users);
28169
+ return { pids, process: name3 && name3[1] ? name3[1] : null };
28170
+ }
28171
+ function parseSsLine(line) {
28172
+ const parts = line.split(/\s+/);
28173
+ if (parts.length < 5)
28174
+ return void 0;
28175
+ const proto = parts[0] === "tcp" ? "tcp" : parts[0] === "udp" ? "udp" : void 0;
28176
+ if (!proto)
28177
+ return void 0;
28178
+ const local = splitAddrPort(parts[4] ?? "");
28179
+ if (!local)
28180
+ return void 0;
28181
+ const { pids, process: process2 } = parseUsers(parts.slice(6).join(" "));
28182
+ return { proto, port: local.port, bind: classifyBind(local.address), pids, process: process2 };
28183
+ }
28184
+ function parseSsListeners(stdout) {
28185
+ if (typeof stdout !== "string")
28186
+ return [];
28187
+ const out = [];
28188
+ for (const raw of stdout.split(/\r?\n/)) {
28189
+ const line = raw.trim();
28190
+ if (line === "")
28191
+ continue;
28192
+ const record2 = parseSsLine(line);
28193
+ if (record2)
28194
+ out.push(record2);
28195
+ }
28196
+ return out;
28197
+ }
28198
+ function parseDpkgSearch(stdout) {
28199
+ const map2 = /* @__PURE__ */ new Map();
28200
+ if (typeof stdout !== "string")
28201
+ return map2;
28202
+ for (const raw of stdout.split(/\r?\n/)) {
28203
+ const line = raw.trim();
28204
+ if (line === "")
28205
+ continue;
28206
+ const sep3 = line.indexOf(": ");
28207
+ if (sep3 < 0)
28208
+ continue;
28209
+ const pkg = line.slice(0, sep3);
28210
+ const path = line.slice(sep3 + 2).trim();
28211
+ if (!/^[a-z0-9][a-z0-9+.:~-]*$/.test(pkg) || !path.startsWith("/"))
28212
+ continue;
28213
+ const name3 = pkg.split(":")[0] ?? "";
28214
+ if (name3 === "")
28215
+ continue;
28216
+ if (!map2.has(path))
28217
+ map2.set(path, name3);
28218
+ }
28219
+ return map2;
28220
+ }
28221
+ function publishedHostPorts(ports) {
28222
+ const set2 = /* @__PURE__ */ new Set();
28223
+ if (!Array.isArray(ports))
28224
+ return set2;
28225
+ for (const entry of ports) {
28226
+ const arrow = entry.indexOf("->");
28227
+ const host = arrow < 0 ? entry : entry.slice(0, arrow);
28228
+ const colon = host.lastIndexOf(":");
28229
+ const portText2 = colon < 0 ? "" : host.slice(colon + 1);
28230
+ const port = Number(portText2);
28231
+ if (Number.isInteger(port) && port >= 1 && port <= 65535)
28232
+ set2.add(port);
28233
+ }
28234
+ return set2;
28235
+ }
28236
+ function processNameOf(name3) {
28237
+ if (typeof name3 !== "string")
28238
+ return null;
28239
+ const base2 = name3.split("/").at(-1) ?? name3;
28240
+ const trimmed = base2.trim();
28241
+ if (trimmed === "")
28242
+ return null;
28243
+ return trimmed.length <= 64 ? trimmed : trimmed.slice(0, 64).trimEnd();
28244
+ }
28245
+ function ownerOf(listener, exeByPid, packageByPath, containerByPort) {
28246
+ const name3 = processNameOf(listener.process);
28247
+ if (name3 !== null && CONTAINER_PLUMBING.has(name3)) {
28248
+ const containerId = containerByPort.get(listener.port);
28249
+ if (containerId)
28250
+ return { kind: "container", container_id: containerId };
28251
+ return { kind: "process", name: name3 };
28252
+ }
28253
+ for (const pid of listener.pids) {
28254
+ const exe = exeByPid.get(pid);
28255
+ if (exe === void 0)
28256
+ continue;
28257
+ const pkg = packageByPath.get(exe);
28258
+ if (pkg !== void 0)
28259
+ return { kind: "package", name: pkg };
28260
+ }
28261
+ if (name3 !== null)
28262
+ return { kind: "process", name: name3 };
28263
+ return null;
28264
+ }
28265
+ function resolveListenerOwners(listeners, exeByPid, packageByPath, containers) {
28266
+ if (!Array.isArray(listeners))
28267
+ return [];
28268
+ const containerByPort = /* @__PURE__ */ new Map();
28269
+ if (Array.isArray(containers)) {
28270
+ for (const container of containers) {
28271
+ for (const port of publishedHostPorts(container.ports)) {
28272
+ if (!containerByPort.has(port))
28273
+ containerByPort.set(port, container.id);
28274
+ }
28275
+ }
28276
+ }
28277
+ const out = [];
28278
+ const seen = /* @__PURE__ */ new Set();
28279
+ for (const listener of listeners) {
28280
+ const owner = ownerOf(listener, exeByPid, packageByPath, containerByPort);
28281
+ const item = { proto: listener.proto, port: listener.port, bind: listener.bind, owner };
28282
+ const key = `${item.proto}\0${item.port}\0${item.bind}\0${JSON.stringify(item.owner)}`;
28283
+ if (seen.has(key))
28284
+ continue;
28285
+ seen.add(key);
28286
+ out.push(item);
28287
+ }
28288
+ return out;
28289
+ }
28290
+
27408
28291
  // dist/inventory/collector.js
27409
28292
  var POSIX_PATH = ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/opt/homebrew/bin", "/opt/homebrew/sbin", "/snap/bin"];
27410
28293
  var DENIED = /permission denied|EACCES|access is denied|got permission denied while trying to connect/i;
@@ -27415,8 +28298,8 @@ function collectorEnv(env = process.env, platform2 = process.platform) {
27415
28298
  const path = [.../* @__PURE__ */ new Set([...(env.PATH ?? "").split(":").filter(Boolean), ...POSIX_PATH])].join(":");
27416
28299
  return platform2 === "linux" ? { ...base2, PATH: path, LC_ALL: "C.UTF-8", LANGUAGE: "" } : { ...base2, PATH: path };
27417
28300
  }
27418
- var defaultRunner = (file2, args, { timeoutMs, maxBytes }) => new Promise((resolve8) => {
27419
- (0, import_node_child_process7.execFile)(file2, [...args], {
28301
+ var defaultRunner = (file2, args, { timeoutMs, maxBytes }) => new Promise((resolve9) => {
28302
+ (0, import_node_child_process8.execFile)(file2, [...args], {
27420
28303
  timeout: timeoutMs,
27421
28304
  maxBuffer: maxBytes,
27422
28305
  killSignal: "SIGKILL",
@@ -27427,7 +28310,7 @@ var defaultRunner = (file2, args, { timeoutMs, maxBytes }) => new Promise((resol
27427
28310
  const code = error63?.code;
27428
28311
  const killed = error63?.killed === true;
27429
28312
  const out = String(stdout ?? ""), err = String(stderr ?? "");
27430
- resolve8({
28313
+ resolve9({
27431
28314
  stdout: out,
27432
28315
  stderr: err,
27433
28316
  ok: !error63,
@@ -27437,13 +28320,13 @@ var defaultRunner = (file2, args, { timeoutMs, maxBytes }) => new Promise((resol
27437
28320
  });
27438
28321
  });
27439
28322
  });
27440
- var defaultReader = async (path) => (0, import_promises12.readFile)(path, "utf8").catch(() => null);
28323
+ var defaultReader = async (path) => (0, import_promises13.readFile)(path, "utf8").catch(() => null);
27441
28324
  async function findExecutablesOnPath(name3, path = collectorEnv().PATH ?? "") {
27442
28325
  const found = [];
27443
28326
  for (const dir of path.split(":").filter((entry) => entry.startsWith("/"))) {
27444
28327
  try {
27445
- const real = await (0, import_promises12.realpath)(`${dir}/${name3}`);
27446
- await (0, import_promises12.access)(real, import_node_fs3.constants.X_OK);
28328
+ const real = await (0, import_promises13.realpath)(`${dir}/${name3}`);
28329
+ await (0, import_promises13.access)(real, import_node_fs3.constants.X_OK);
27447
28330
  if (!found.includes(real))
27448
28331
  found.push(real);
27449
28332
  } catch {
@@ -27451,7 +28334,7 @@ async function findExecutablesOnPath(name3, path = collectorEnv().PATH ?? "") {
27451
28334
  }
27452
28335
  return found;
27453
28336
  }
27454
- function installOf(real, home = (0, import_node_os4.homedir)()) {
28337
+ function installOf(real, home = (0, import_node_os5.homedir)()) {
27455
28338
  if (/^\/(opt\/homebrew|usr\/local\/Cellar|home\/linuxbrew\/\.linuxbrew)\//.test(real))
27456
28339
  return "homebrew";
27457
28340
  if (/^\/(usr\/(bin|sbin|lib|libexec|share)|bin|sbin|snap)\//.test(real))
@@ -27465,7 +28348,7 @@ function installOf(real, home = (0, import_node_os4.homedir)()) {
27465
28348
  async function readFileTail(path, bytes3) {
27466
28349
  let handle = null;
27467
28350
  try {
27468
- handle = await (0, import_promises12.open)(path, "r");
28351
+ handle = await (0, import_promises13.open)(path, "r");
27469
28352
  const { size } = await handle.stat();
27470
28353
  const length = Math.min(size, bytes3);
27471
28354
  const buffer = Buffer.alloc(length);
@@ -27480,11 +28363,11 @@ async function readFileTail(path, bytes3) {
27480
28363
  }
27481
28364
  async function listDirFiles(path, dirs = false) {
27482
28365
  try {
27483
- const entries = await (0, import_promises12.readdir)(path, { withFileTypes: true });
28366
+ const entries = await (0, import_promises13.readdir)(path, { withFileTypes: true });
27484
28367
  const files = [];
27485
28368
  for (const entry of entries.filter((item) => dirs ? item.isDirectory() : item.isFile()).slice(0, 2e3)) {
27486
28369
  try {
27487
- files.push({ name: entry.name, mtimeMs: (await (0, import_promises12.stat)(`${path}/${entry.name}`)).mtimeMs });
28370
+ files.push({ name: entry.name, mtimeMs: (await (0, import_promises13.stat)(`${path}/${entry.name}`)).mtimeMs });
27488
28371
  } catch {
27489
28372
  }
27490
28373
  }
@@ -27494,16 +28377,24 @@ async function listDirFiles(path, dirs = false) {
27494
28377
  }
27495
28378
  }
27496
28379
  var defaultCollectorSystem = {
27497
- platform: (0, import_node_os4.platform)(),
27498
- arch: (0, import_node_os4.arch)(),
27499
- kernel: (0, import_node_os4.release)(),
28380
+ platform: (0, import_node_os5.platform)(),
28381
+ arch: (0, import_node_os5.arch)(),
28382
+ kernel: (0, import_node_os5.release)(),
27500
28383
  run: defaultRunner,
27501
28384
  readText: defaultReader,
27502
28385
  now: () => /* @__PURE__ */ new Date(),
27503
28386
  probeTls: createTlsProbe(),
27504
28387
  readTail: readFileTail,
27505
28388
  listDir: listDirFiles,
27506
- ...(0, import_node_os4.platform)() === "win32" ? {} : { findExecutables: (name3) => findExecutablesOnPath(name3) }
28389
+ isRoot: typeof process.getuid === "function" ? process.getuid() === 0 : false,
28390
+ resolveExe: async (pid) => {
28391
+ try {
28392
+ return await (0, import_promises13.realpath)(`/proc/${pid}/exe`);
28393
+ } catch {
28394
+ return null;
28395
+ }
28396
+ },
28397
+ ...(0, import_node_os5.platform)() === "win32" ? {} : { findExecutables: (name3) => findExecutablesOnPath(name3) }
27507
28398
  };
27508
28399
  var SHORT = { timeoutMs: 1e4, maxBytes: 2 * 1024 * 1024 };
27509
28400
  var LIST = { timeoutMs: 45e3, maxBytes: 48 * 1024 * 1024 };
@@ -27576,9 +28467,11 @@ var Collection = class {
27576
28467
  images = [];
27577
28468
  imagePackages = [];
27578
28469
  tlsEndpoints = [];
28470
+ listeners = [];
27579
28471
  pods = [];
27580
28472
  health = [];
27581
28473
  coverage = [];
28474
+ apt = null;
27582
28475
  constructor(system) {
27583
28476
  this.system = system;
27584
28477
  }
@@ -27649,19 +28542,65 @@ async function collectOs(c) {
27649
28542
  var APT_POLICY_BATCH = 300;
27650
28543
  async function addAptOrigins(c, items) {
27651
28544
  const names = [...new Set(items.map((item) => item.name))].filter((name3) => /^[a-z0-9][a-z0-9+.-]*$/.test(name3));
27652
- const origins = /* @__PURE__ */ new Map();
28545
+ const apt = /* @__PURE__ */ new Map();
27653
28546
  for (let offset = 0; offset < names.length; offset += APT_POLICY_BATCH) {
27654
28547
  const stdout = await c.command("apt-policy", "apt-cache", ["policy", ...names.slice(offset, offset + APT_POLICY_BATCH)], LIST);
27655
28548
  if (stdout === null)
27656
28549
  return;
27657
28550
  for (const [name3, entry] of parseAptPolicy(stdout))
27658
- origins.set(name3.split(":")[0], entry.origin);
28551
+ apt.set(name3.split(":")[0], { origin: entry.origin, candidate: entry.candidate });
27659
28552
  }
27660
28553
  for (const item of items) {
27661
- const origin = origins.get(item.name);
27662
- if (origin)
27663
- item.origin = origin;
28554
+ const entry = apt.get(item.name);
28555
+ if (!entry)
28556
+ continue;
28557
+ if (entry.origin)
28558
+ item.origin = entry.origin;
28559
+ item.candidate = entry.candidate;
28560
+ }
28561
+ }
28562
+ async function newestAptListMs(c) {
28563
+ const files = c.system.listDir ? await c.system.listDir("/var/lib/apt/lists") : null;
28564
+ if (files === null)
28565
+ return null;
28566
+ let newest = null;
28567
+ for (const file2 of files) {
28568
+ if (!file2.name.endsWith("_InRelease"))
28569
+ continue;
28570
+ const ms = Math.round(file2.mtimeMs);
28571
+ if (newest === null || ms > newest)
28572
+ newest = ms;
28573
+ }
28574
+ return newest;
28575
+ }
28576
+ async function securityPocketOf(c) {
28577
+ const sourcesList = await c.system.readText("/etc/apt/sources.list");
28578
+ if (sourcesList !== null && oneLineHasSecurity(sourcesList))
28579
+ return true;
28580
+ const dir = c.system.listDir ? await c.system.listDir("/etc/apt/sources.list.d") : null;
28581
+ if (dir === null)
28582
+ return false;
28583
+ for (const file2 of dir) {
28584
+ const text6 = await c.system.readText(`/etc/apt/sources.list.d/${file2.name}`);
28585
+ if (text6 === null)
28586
+ continue;
28587
+ if (file2.name.endsWith(".list") && oneLineHasSecurity(text6))
28588
+ return true;
28589
+ if (file2.name.endsWith(".sources") && deb822HasSecurity(text6))
28590
+ return true;
27664
28591
  }
28592
+ return false;
28593
+ }
28594
+ async function collectAptEvidence(c) {
28595
+ const config2 = await c.command("apt-config", "apt-config", ["dump"], LIST);
28596
+ if (config2 === null)
28597
+ return;
28598
+ const { update_lists, unattended } = parseAptConfig(config2);
28599
+ const heldRaw = await c.command("apt-hold", "apt-mark", ["showhold"], LIST);
28600
+ const held = (heldRaw === null ? [] : parseAptHold(heldRaw)).slice(0, INVENTORY_LIMITS.aptHeld);
28601
+ const lists_newest_ms = await newestAptListMs(c);
28602
+ const security_pocket = await securityPocketOf(c);
28603
+ c.apt = { lists_newest_ms, update_lists, unattended, security_pocket, held };
27665
28604
  }
27666
28605
  async function collectPackages(c) {
27667
28606
  const { platform: platform2 } = c.system;
@@ -27674,6 +28613,7 @@ async function collectPackages(c) {
27674
28613
  if (dpkg !== null) {
27675
28614
  const items = parseDpkg(dpkg);
27676
28615
  await addAptOrigins(c, items);
28616
+ await collectAptEvidence(c);
27677
28617
  add("dpkg", items);
27678
28618
  } else {
27679
28619
  const rpm = await c.command("rpm", "rpm", ["-qa", "--qf", "%{NAME}\\t%{EPOCH}\\t%{VERSION}\\t%{RELEASE}\\t%{ARCH}\\t%{SIZE}\\n"], LIST);
@@ -27848,6 +28788,48 @@ async function collectContainers(c) {
27848
28788
  image.containers = count3;
27849
28789
  }
27850
28790
  }
28791
+ var DPKG_SEARCH_BATCH = 64;
28792
+ function searchablePath(path) {
28793
+ return path.startsWith("/") && path.length >= 2 && path.length <= 4096 && !/[\u0000\r\n]/.test(path);
28794
+ }
28795
+ async function collectListeners(c) {
28796
+ if (c.system.platform !== "linux")
28797
+ return;
28798
+ const started = Date.now();
28799
+ const root = c.system.isRoot === true;
28800
+ const stdout = await c.command("listeners", "ss", root ? ["-tulnpH"] : ["-tulnH"], SHORT);
28801
+ if (stdout === null)
28802
+ return;
28803
+ const records = parseSsListeners(stdout);
28804
+ if (!root) {
28805
+ const items2 = resolveListenerOwners(records, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), c.containers);
28806
+ c.listeners.push(...items2);
28807
+ c.cover("listeners", "not_root", items2.length, Date.now() - started);
28808
+ return;
28809
+ }
28810
+ const pids = [...new Set(records.flatMap((record2) => record2.pids))];
28811
+ const exeByPid = /* @__PURE__ */ new Map();
28812
+ if (c.system.resolveExe && pids.length > 0) {
28813
+ await pool(pids, 8, async (pid) => {
28814
+ const exe = await c.system.resolveExe(pid);
28815
+ if (exe !== null && searchablePath(exe))
28816
+ exeByPid.set(pid, exe);
28817
+ });
28818
+ }
28819
+ const paths = [...new Set(exeByPid.values())];
28820
+ const packageByPath = /* @__PURE__ */ new Map();
28821
+ for (let offset = 0; offset < paths.length; offset += DPKG_SEARCH_BATCH) {
28822
+ const batch = paths.slice(offset, offset + DPKG_SEARCH_BATCH);
28823
+ const result2 = await c.system.run("dpkg", ["-S", ...batch], SHORT);
28824
+ if (!result2.ok)
28825
+ break;
28826
+ for (const [path, pkg] of parseDpkgSearch(result2.stdout))
28827
+ packageByPath.set(path, pkg);
28828
+ }
28829
+ const items = resolveListenerOwners(records, exeByPid, packageByPath, c.containers);
28830
+ c.listeners.push(...items);
28831
+ c.counted("listeners", items.length, INVENTORY_LIMITS.listeners);
28832
+ }
27851
28833
  var SBOM_IMAGES = 4;
27852
28834
  var SBOM_LIMITS = { timeoutMs: 9e4, maxBytes: 40 * 1024 * 1024 };
27853
28835
  async function collectImageSboms(c) {
@@ -27926,7 +28908,7 @@ async function collectHealth(c) {
27926
28908
  if (jobs !== null)
27927
28909
  c.health.push(...parseLaunchctlList(jobs));
27928
28910
  if (c.system.listDir) {
27929
- const files = [...await c.system.listDir("/Library/Logs/DiagnosticReports") ?? [], ...await c.system.listDir(`${(0, import_node_os4.homedir)()}/Library/Logs/DiagnosticReports`) ?? []];
28911
+ const files = [...await c.system.listDir("/Library/Logs/DiagnosticReports") ?? [], ...await c.system.listDir(`${(0, import_node_os5.homedir)()}/Library/Logs/DiagnosticReports`) ?? []];
27930
28912
  c.health.push(...crashReportEvents(files, now));
27931
28913
  c.cover("health-crash-reports", "ok", files.length, Date.now() - started);
27932
28914
  }
@@ -27943,10 +28925,12 @@ async function collectInventory(system = defaultCollectorSystem) {
27943
28925
  await collectSoftware(c);
27944
28926
  await collectServices(c);
27945
28927
  await collectContainers(c);
28928
+ await collectListeners(c);
27946
28929
  await collectImageSboms(c);
27947
28930
  await collectTls(c);
27948
28931
  await collectHealth(c);
27949
28932
  const tlsEndpoints = valid(inventoryTlsEndpointSchema, c.tlsEndpoints, INVENTORY_LIMITS.tlsEndpoints);
28933
+ const listeners = valid(inventoryListenerSchema, c.listeners, INVENTORY_LIMITS.listeners);
27950
28934
  const health = capHealthEvents(valid(inventoryHealthEventSchema, c.health, Number.MAX_SAFE_INTEGER));
27951
28935
  const snapshot = {
27952
28936
  schema: 1,
@@ -27960,8 +28944,10 @@ async function collectInventory(system = defaultCollectorSystem) {
27960
28944
  images: valid(inventoryImageSchema, c.images, INVENTORY_LIMITS.images),
27961
28945
  ...c.imagePackages.length > 0 ? { image_packages: valid(inventoryImagePackageSchema, c.imagePackages, INVENTORY_LIMITS.imagePackages) } : {},
27962
28946
  ...tlsEndpoints.length > 0 ? { tls_endpoints: tlsEndpoints } : {},
28947
+ ...listeners.length > 0 ? { listeners } : {},
27963
28948
  pods: valid(inventoryPodSchema, c.pods, INVENTORY_LIMITS.pods),
27964
28949
  ...health.length > 0 ? { health } : {},
28950
+ ...c.apt !== null && inventoryAptSchema.safeParse(c.apt).success ? { apt: c.apt } : {},
27965
28951
  coverage: valid(inventoryCoverageSchema, c.coverage, INVENTORY_LIMITS.coverage)
27966
28952
  };
27967
28953
  return inventorySnapshotSchema.parse(snapshot);
@@ -28051,6 +29037,9 @@ var RelaySession = class {
28051
29037
  case "ERROR":
28052
29038
  this.#logger.warn("relay error", { code: envelope.code, message: envelope.safe_message });
28053
29039
  return;
29040
+ case "LIFECYCLE":
29041
+ await this.#options.onLifecycle?.({ connection_mode: envelope.connection_mode, expires_at_ms: envelope.expires_at_ms, destroy_deadline_ms: envelope.destroy_deadline_ms });
29042
+ return;
28054
29043
  case "MONITOR_CONFIG":
28055
29044
  this.#options.onMonitorConfig?.({ enabled: envelope.enabled, interval_s: envelope.interval_s });
28056
29045
  return;
@@ -28092,8 +29081,9 @@ var RelaySession = class {
28092
29081
  this.#state = "ready";
28093
29082
  this.#sendEnvelope(buildEnvelope(this.identity, "HELLO", null, {
28094
29083
  agent_id: identity.device_uuid,
29084
+ session: this.#options.session ?? "service",
28095
29085
  supported_versions: [...SUPPORTED_VERSIONS],
28096
- capabilities: [...DESKTOP_CAPABILITIES, ...SSH_CAPABILITIES, ...SHELL_CAPABILITIES]
29086
+ capabilities: [...DESKTOP_CAPABILITIES, ...SSH_CAPABILITIES, ...SHELL_CAPABILITIES, ...AGENT_CAPABILITIES, LIFECYCLE_CAPABILITY]
28097
29087
  }));
28098
29088
  this.sendInventory();
28099
29089
  this.#options.onReady?.();
@@ -28137,7 +29127,7 @@ function backoffDelay(attempt, options) {
28137
29127
  }
28138
29128
 
28139
29129
  // dist/ssh/handler.js
28140
- var import_node_crypto10 = require("node:crypto");
29130
+ var import_node_crypto11 = require("node:crypto");
28141
29131
  var SSH_STATUS_COMMANDS = Object.freeze({
28142
29132
  uptime: "uptime",
28143
29133
  disk: "df -h",
@@ -28247,7 +29237,7 @@ var SshExecutor = class {
28247
29237
  stdout_bytes: result2.stdoutBytes,
28248
29238
  stderr_bytes: result2.stderrBytes,
28249
29239
  output_truncated: result2.truncated,
28250
- output_sha256: (0, import_node_crypto10.createHash)("sha256").update(result2.stdout).update("\0").update(result2.stderr).digest("hex"),
29240
+ output_sha256: (0, import_node_crypto11.createHash)("sha256").update(result2.stdout).update("\0").update(result2.stderr).digest("hex"),
28251
29241
  duration_ms: result2.durationMs
28252
29242
  };
28253
29243
  }
@@ -28277,10 +29267,10 @@ var SshExecutor = class {
28277
29267
  };
28278
29268
 
28279
29269
  // dist/shell/executor.js
28280
- var import_node_child_process9 = require("node:child_process");
28281
- var import_promises14 = require("node:fs/promises");
28282
- var import_node_os6 = require("node:os");
28283
- var import_node_path15 = require("node:path");
29270
+ var import_node_child_process10 = require("node:child_process");
29271
+ var import_promises15 = require("node:fs/promises");
29272
+ var import_node_os7 = require("node:os");
29273
+ var import_node_path16 = require("node:path");
28284
29274
 
28285
29275
  // dist/shell/output.js
28286
29276
  var OutputBuffer = class {
@@ -28360,18 +29350,18 @@ function trimIncompleteUtf8(bytes3) {
28360
29350
  }
28361
29351
 
28362
29352
  // dist/shell/system.js
28363
- var import_node_child_process8 = require("node:child_process");
28364
- var import_promises13 = require("node:fs/promises");
28365
- var import_node_os5 = require("node:os");
28366
- var import_node_path14 = require("node:path");
29353
+ var import_node_child_process9 = require("node:child_process");
29354
+ var import_promises14 = require("node:fs/promises");
29355
+ var import_node_os6 = require("node:os");
29356
+ var import_node_path15 = require("node:path");
28367
29357
  function windowsTool(env, ...parts) {
28368
- return import_node_path14.win32.join(env.SystemRoot ?? env.windir ?? "C:\\Windows", "System32", ...parts);
29358
+ return import_node_path15.win32.join(env.SystemRoot ?? env.windir ?? "C:\\Windows", "System32", ...parts);
28369
29359
  }
28370
29360
  var POWERSHELL_PREFIX = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $ProgressPreference = 'SilentlyContinue'; ";
28371
29361
  function userShell(env = process.env) {
28372
29362
  let shell = null;
28373
29363
  try {
28374
- shell = (0, import_node_os5.userInfo)().shell;
29364
+ shell = (0, import_node_os6.userInfo)().shell;
28375
29365
  } catch {
28376
29366
  shell = null;
28377
29367
  }
@@ -28407,8 +29397,8 @@ function commandEnv(env = process.env, taskId2) {
28407
29397
  ...taskId2 ? { CONBRIDGE_TASK_ID: taskId2 } : {}
28408
29398
  };
28409
29399
  }
28410
- var run = (file2, args) => new Promise((resolve8) => {
28411
- (0, import_node_child_process8.execFile)(file2, [...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024, timeout: 2e4 }, (error63, stdout) => resolve8({ ok: !error63, stdout: String(stdout) }));
29400
+ var run = (file2, args) => new Promise((resolve9) => {
29401
+ (0, import_node_child_process9.execFile)(file2, [...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024, timeout: 2e4 }, (error63, stdout) => resolve9({ ok: !error63, stdout: String(stdout) }));
28412
29402
  });
28413
29403
  function parsePs(text6) {
28414
29404
  const entries = [];
@@ -28483,39 +29473,39 @@ async function listProcesses(options) {
28483
29473
  return { processes: matching.slice(0, options.limit), total: matching.length, truncated: matching.length > options.limit };
28484
29474
  }
28485
29475
  async function systemInfo() {
28486
- const cores = (0, import_node_os5.cpus)();
29476
+ const cores = (0, import_node_os6.cpus)();
28487
29477
  const disk = async (path) => {
28488
29478
  try {
28489
- const info = await (0, import_promises13.statfs)(path);
29479
+ const info = await (0, import_promises14.statfs)(path);
28490
29480
  return { path, total_bytes: info.blocks * info.bsize, free_bytes: info.bavail * info.bsize };
28491
29481
  } catch {
28492
29482
  return null;
28493
29483
  }
28494
29484
  };
28495
- const home = (0, import_node_os5.homedir)();
28496
- const disks = (await Promise.all([disk((0, import_node_os5.platform)() === "win32" ? home.slice(0, 3) || "C:\\" : "/"), disk(home)])).filter((entry) => entry !== null);
29485
+ const home = (0, import_node_os6.homedir)();
29486
+ const disks = (await Promise.all([disk((0, import_node_os6.platform)() === "win32" ? home.slice(0, 3) || "C:\\" : "/"), disk(home)])).filter((entry) => entry !== null);
28497
29487
  let user = null;
28498
29488
  try {
28499
- user = (0, import_node_os5.userInfo)().username;
29489
+ user = (0, import_node_os6.userInfo)().username;
28500
29490
  } catch {
28501
29491
  user = null;
28502
29492
  }
28503
29493
  return {
28504
- hostname: (0, import_node_os5.hostname)(),
28505
- platform: (0, import_node_os5.platform)(),
28506
- os_version: (0, import_node_os5.version)(),
28507
- release: (0, import_node_os5.release)(),
28508
- arch: (0, import_node_os5.arch)(),
28509
- uptime_s: Math.round((0, import_node_os5.uptime)()),
29494
+ hostname: (0, import_node_os6.hostname)(),
29495
+ platform: (0, import_node_os6.platform)(),
29496
+ os_version: (0, import_node_os6.version)(),
29497
+ release: (0, import_node_os6.release)(),
29498
+ arch: (0, import_node_os6.arch)(),
29499
+ uptime_s: Math.round((0, import_node_os6.uptime)()),
28510
29500
  cpu_model: cores[0]?.model ?? null,
28511
29501
  cpu_count: cores.length,
28512
- load_average: (0, import_node_os5.platform)() === "win32" ? null : (0, import_node_os5.loadavg)().map((value) => Math.round(value * 100) / 100),
28513
- memory_total_bytes: (0, import_node_os5.totalmem)(),
28514
- memory_free_bytes: (0, import_node_os5.freemem)(),
29502
+ load_average: (0, import_node_os6.platform)() === "win32" ? null : (0, import_node_os6.loadavg)().map((value) => Math.round(value * 100) / 100),
29503
+ memory_total_bytes: (0, import_node_os6.totalmem)(),
29504
+ memory_free_bytes: (0, import_node_os6.freemem)(),
28515
29505
  disks,
28516
29506
  user,
28517
29507
  home,
28518
- shell: (0, import_node_os5.platform)() === "win32" ? "powershell" : userShell(),
29508
+ shell: (0, import_node_os6.platform)() === "win32" ? "powershell" : userShell(),
28519
29509
  node_version: process.versions.node,
28520
29510
  agent_version: AGENT_VERSION
28521
29511
  };
@@ -28531,12 +29521,12 @@ var KILL_GRACE_MS = 3e3;
28531
29521
  function failure3(code, reason, message, executed = false, extra = {}) {
28532
29522
  return { result: { state: "FAILED", executed, safe_message: message.slice(0, 256), output_excerpt: excerpt({ error: code, reason, message, ...extra }) } };
28533
29523
  }
28534
- function resolveCwd(input2, home = (0, import_node_os6.homedir)()) {
29524
+ function resolveCwd(input2, home = (0, import_node_os7.homedir)()) {
28535
29525
  if (input2 === void 0 || input2 === "~")
28536
29526
  return home;
28537
29527
  if (input2.startsWith("~/") || input2.startsWith("~\\"))
28538
- return (0, import_node_path15.join)(home, input2.slice(2));
28539
- return (0, import_node_path15.isAbsolute)(input2) ? (0, import_node_path15.resolve)(input2) : null;
29528
+ return (0, import_node_path16.join)(home, input2.slice(2));
29529
+ return (0, import_node_path16.isAbsolute)(input2) ? (0, import_node_path16.resolve)(input2) : null;
28540
29530
  }
28541
29531
  var ShellExecutor = class {
28542
29532
  #options;
@@ -28649,7 +29639,7 @@ var ShellExecutor = class {
28649
29639
  const cwd = resolveCwd(payload.cwd);
28650
29640
  if (cwd === null)
28651
29641
  return failure3("INVALID_MESSAGE", "CWD_INVALID", "cwd must be an absolute directory or start with ~");
28652
- const isDirectory = await (0, import_promises14.stat)(cwd).then((info) => info.isDirectory(), () => false);
29642
+ const isDirectory = await (0, import_promises15.stat)(cwd).then((info) => info.isDirectory(), () => false);
28653
29643
  if (!isDirectory)
28654
29644
  return failure3("NOT_FOUND", "CWD_NOT_FOUND", `Directory not found: ${cwd}`);
28655
29645
  if (this.runningCount >= MAX_RUNNING_COMMANDS) {
@@ -28664,7 +29654,7 @@ var ShellExecutor = class {
28664
29654
  const windows = (this.#options.platform ?? process.platform) === "win32";
28665
29655
  let child;
28666
29656
  try {
28667
- child = (0, import_node_child_process9.spawn)(launch.file, [...launch.args], {
29657
+ child = (0, import_node_child_process10.spawn)(launch.file, [...launch.args], {
28668
29658
  cwd,
28669
29659
  env: commandEnv(this.#options.env ?? process.env, context.taskId),
28670
29660
  windowsHide: true,
@@ -28775,7 +29765,7 @@ var ShellExecutor = class {
28775
29765
  const signal = (name3) => {
28776
29766
  try {
28777
29767
  if (windows) {
28778
- (0, import_node_child_process9.spawn)("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).on("error", () => child.kill());
29768
+ (0, import_node_child_process10.spawn)("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).on("error", () => child.kill());
28779
29769
  } else if (child.pid !== void 0) {
28780
29770
  process.kill(-child.pid, name3);
28781
29771
  }
@@ -28820,13 +29810,13 @@ var ShellExecutor = class {
28820
29810
  function shellResource(config2, platform2 = process.platform) {
28821
29811
  if (config2.full_access !== true)
28822
29812
  return null;
28823
- return { resource_id: SHELL_RESOURCE_ID, kind: SHELL_RESOURCE_KIND, label: `Terminal on ${(0, import_node_os7.hostname)().slice(0, 100)}`, attrs: { platform: platform2, arch: (0, import_node_os7.arch)() } };
29813
+ return { resource_id: SHELL_RESOURCE_ID, kind: SHELL_RESOURCE_KIND, label: `Terminal on ${(0, import_node_os8.hostname)().slice(0, 100)}`, attrs: { platform: platform2, arch: (0, import_node_os8.arch)() } };
28824
29814
  }
28825
29815
  var WATCH_INTERVAL_MS = 5e3;
28826
29816
  var RESUME_GAP_MS = 3e4;
28827
29817
  function networkFingerprint() {
28828
29818
  const parts = [];
28829
- for (const [name3, addresses] of Object.entries((0, import_node_os7.networkInterfaces)())) {
29819
+ for (const [name3, addresses] of Object.entries((0, import_node_os8.networkInterfaces)())) {
28830
29820
  for (const address of addresses ?? [])
28831
29821
  if (!address.internal)
28832
29822
  parts.push(`${name3}/${address.address}`);
@@ -28853,6 +29843,9 @@ function sameRoots(a, b) {
28853
29843
  return key(a) === key(b);
28854
29844
  }
28855
29845
  var AgentRunner = class {
29846
+ #lifecycleTimer;
29847
+ #removal = null;
29848
+ #destroyDispatch = null;
28856
29849
  /** Last software inventory send of this process, across connections (InventoryLoop.lastSentAtMs). */
28857
29850
  #inventorySentAtMs = null;
28858
29851
  #options;
@@ -28879,6 +29872,27 @@ var AgentRunner = class {
28879
29872
  const binaries = options.sshBinaries ?? sshBinariesFromEnv();
28880
29873
  this.#sshInventoryExec = options.inventory?.sshExec ?? defaultSshInventoryExec(sshPaths(options.paths.dir), binaries);
28881
29874
  const dispatcherOptions = {
29875
+ scheduleRemoval: async (dispatch2, runAtMs) => {
29876
+ if (this.#stopped)
29877
+ throw new Error("Agent is stopping");
29878
+ const deadline = this.#options.identity.destroy_deadline_ms ?? runAtMs;
29879
+ if (this.#options.identity.destroy_task_id && this.#options.identity.destroy_task_id !== dispatch2.task_id)
29880
+ return deadline;
29881
+ this.#destroyDispatch = dispatch2;
29882
+ this.#options.identity.destroy_task_id = dispatch2.task_id;
29883
+ await this.#applyLifecycle({ connection_mode: this.#options.identity.connection_mode ?? "persistent", expires_at_ms: this.#options.identity.expires_at_ms ?? null, destroy_deadline_ms: deadline });
29884
+ return deadline;
29885
+ },
29886
+ cancelRemoval: async (taskId2) => {
29887
+ if (this.#options.identity.destroy_task_id !== taskId2)
29888
+ return void 0;
29889
+ if ((this.#options.identity.destroy_deadline_ms ?? 0) <= (this.#options.now ?? Date.now)())
29890
+ return false;
29891
+ this.#destroyDispatch = null;
29892
+ this.#options.identity.destroy_task_id = null;
29893
+ await this.#applyLifecycle({ connection_mode: this.#options.identity.connection_mode ?? "persistent", expires_at_ms: this.#options.identity.expires_at_ms ?? null, destroy_deadline_ms: null });
29894
+ return true;
29895
+ },
28882
29896
  shell: this.#shell,
28883
29897
  identity: options.identity,
28884
29898
  config: () => this.#currentConfig(),
@@ -28930,6 +29944,11 @@ var AgentRunner = class {
28930
29944
  }
28931
29945
  }
28932
29946
  async run() {
29947
+ this.#armLifecycle();
29948
+ if (this.#removal) {
29949
+ await this.#removal;
29950
+ return;
29951
+ }
28933
29952
  await this.#reloadConfig();
28934
29953
  await this.#compactJournal();
28935
29954
  const compaction = setInterval(() => {
@@ -28942,7 +29961,11 @@ var AgentRunner = class {
28942
29961
  } finally {
28943
29962
  clearInterval(compaction);
28944
29963
  stopWatch();
29964
+ if (this.#lifecycleTimer)
29965
+ clearTimeout(this.#lifecycleTimer);
28945
29966
  }
29967
+ if (this.#removal)
29968
+ await this.#removal;
28946
29969
  await this.#dispatcher.drain();
28947
29970
  await this.#shell.shutdown();
28948
29971
  }
@@ -29020,6 +30043,8 @@ var AgentRunner = class {
29020
30043
  }
29021
30044
  stop() {
29022
30045
  this.#stopped = true;
30046
+ if (this.#lifecycleTimer)
30047
+ clearTimeout(this.#lifecycleTimer);
29023
30048
  this.#sleep?.abort();
29024
30049
  try {
29025
30050
  this.#socket?.close(1e3, "agent shutdown");
@@ -29030,14 +30055,85 @@ var AgentRunner = class {
29030
30055
  #wait(ms) {
29031
30056
  const controller = new AbortController();
29032
30057
  this.#sleep = controller;
29033
- return new Promise((resolve8) => {
29034
- const timer = setTimeout(resolve8, ms);
30058
+ return new Promise((resolve9) => {
30059
+ const timer = setTimeout(resolve9, ms);
29035
30060
  controller.signal.addEventListener("abort", () => {
29036
30061
  clearTimeout(timer);
29037
- resolve8();
30062
+ resolve9();
29038
30063
  }, { once: true });
29039
30064
  });
29040
30065
  }
30066
+ async #applyLifecycle(body) {
30067
+ if (this.#stopped)
30068
+ return;
30069
+ if (this.#lifecycleTimer)
30070
+ clearTimeout(this.#lifecycleTimer);
30071
+ Object.assign(this.#options.identity, body);
30072
+ if (body.destroy_deadline_ms === null) {
30073
+ this.#destroyDispatch = null;
30074
+ this.#options.identity.destroy_task_id = null;
30075
+ }
30076
+ await saveIdentity(this.#options.paths, this.#options.identity);
30077
+ this.#armLifecycle();
30078
+ if (body.connection_mode === "passive" && (this.#options.session ?? "service") === "service")
30079
+ this.#handleClose(4409, "mode_passive");
30080
+ }
30081
+ #armLifecycle() {
30082
+ if (this.#lifecycleTimer)
30083
+ clearTimeout(this.#lifecycleTimer);
30084
+ const identity = this.#options.identity;
30085
+ const expiry = identity.connection_mode === "timed" || identity.connection_mode === "ephemeral" ? identity.expires_at_ms : null;
30086
+ const deadline = identity.destroy_deadline_ms;
30087
+ const ends = [expiry, deadline].filter((value) => typeof value === "number");
30088
+ if (!ends.length || this.#stopped)
30089
+ return;
30090
+ const at = Math.min(...ends);
30091
+ const now = (this.#options.now ?? Date.now)();
30092
+ const end = () => {
30093
+ if (at > (this.#options.now ?? Date.now)()) {
30094
+ this.#armLifecycle();
30095
+ return;
30096
+ }
30097
+ this.#handleClose(4403, deadline != null && deadline <= at || identity.connection_mode === "ephemeral" ? "removed:destroyed" : "removed:expired");
30098
+ };
30099
+ if (at <= now)
30100
+ end();
30101
+ else
30102
+ this.#lifecycleTimer = setTimeout(end, Math.min(at - now, 2147483647));
30103
+ }
30104
+ #handleClose(code, reason) {
30105
+ const removed = code === 4403 && ["removed:revoked", "removed:left", "removed:expired", "removed:destroyed"].includes(reason);
30106
+ const passive = code === 4409 && reason === "mode_passive" && (this.#options.session ?? "service") === "service";
30107
+ if (!removed && !passive || this.#removal)
30108
+ return;
30109
+ this.#stopped = true;
30110
+ this.#sleep?.abort();
30111
+ if (this.#lifecycleTimer)
30112
+ clearTimeout(this.#lifecycleTimer);
30113
+ this.#removal = (async () => {
30114
+ const actions = this.#options.lifecycleActions;
30115
+ try {
30116
+ if (reason === "removed:destroyed") {
30117
+ await (actions?.purge() ?? purgeAgent({ reason: "destroyed", stateDir: this.#options.paths.dir, ...this.#options.stopKeepAwake ? { stopKeepAwake: this.#options.stopKeepAwake } : {} }));
30118
+ const dispatch2 = this.#destroyDispatch;
30119
+ if (dispatch2 && this.#session)
30120
+ this.#session.sendFrame(encode3(buildEnvelope(this.#options.identity, "RESULT", dispatch2.task_id, {
30121
+ state: "SUCCEEDED",
30122
+ executed: true,
30123
+ output_excerpt: JSON.stringify({ state: "removed" })
30124
+ }, dispatch2.correlation_id)));
30125
+ } else {
30126
+ await (actions?.removeAutostart() ?? removeAgentAutostart(this.#options.paths.dir)).catch((error63) => this.#logger.warn("autostart removal failed", { error: errorMessage(error63) }));
30127
+ if (!passive)
30128
+ await (actions?.removeIdentity() ?? removeAgentIdentity({ stateDir: this.#options.paths.dir }));
30129
+ }
30130
+ } catch (error63) {
30131
+ this.#logger.warn("lifecycle cleanup failed", { error: errorMessage(error63) });
30132
+ } finally {
30133
+ this.stop();
30134
+ }
30135
+ })();
30136
+ }
29041
30137
  #connectOnce() {
29042
30138
  const { identity, key } = this.#options;
29043
30139
  const url2 = relayUrl(identity.gateway_url, identity.device_uuid);
@@ -29063,6 +30159,8 @@ var AgentRunner = class {
29063
30159
  const session = new RelaySession({
29064
30160
  identity,
29065
30161
  key,
30162
+ session: this.#options.session ?? "service",
30163
+ onLifecycle: (body) => this.#applyLifecycle(body),
29066
30164
  dispatcher: this.#dispatcher,
29067
30165
  config: () => this.#currentConfig(),
29068
30166
  resources: () => {
@@ -29092,7 +30190,7 @@ var AgentRunner = class {
29092
30190
  onInventoryRequest: (requestId) => inventory2.request(requestId)
29093
30191
  });
29094
30192
  this.#session = session;
29095
- return new Promise((resolve8) => {
30193
+ return new Promise((resolve9) => {
29096
30194
  let settled = false;
29097
30195
  const end = (code) => {
29098
30196
  if (settled)
@@ -29111,7 +30209,7 @@ var AgentRunner = class {
29111
30209
  if (this.#endConnection === end)
29112
30210
  this.#endConnection = null;
29113
30211
  this.#logger.info("relay closed", { code });
29114
- resolve8(ready);
30212
+ resolve9(ready);
29115
30213
  };
29116
30214
  this.#endConnection = end;
29117
30215
  const authTimer = setTimeout(() => {
@@ -29125,7 +30223,7 @@ var AgentRunner = class {
29125
30223
  end(4001);
29126
30224
  }, this.#options.authTimeoutMs ?? AUTH_TIMEOUT_MS);
29127
30225
  socket.addEventListener("message", (event) => {
29128
- if (settled)
30226
+ if (settled || this.#stopped)
29129
30227
  return;
29130
30228
  const text6 = frameText(event.data);
29131
30229
  if (text6 === null)
@@ -29142,14 +30240,18 @@ var AgentRunner = class {
29142
30240
  } catch {
29143
30241
  }
29144
30242
  });
29145
- socket.addEventListener("close", (event) => end(event.code));
30243
+ socket.addEventListener("close", (event) => {
30244
+ if (!settled)
30245
+ this.#handleClose(event.code, event.reason);
30246
+ end(event.code);
30247
+ });
29146
30248
  });
29147
30249
  }
29148
30250
  };
29149
30251
 
29150
30252
  // dist/ssh/cli.js
29151
30253
  var import_node_util = require("node:util");
29152
- var import_node_path16 = require("node:path");
30254
+ var import_node_path17 = require("node:path");
29153
30255
  var SshUsageError = class extends Error {
29154
30256
  };
29155
30257
  var SSH_USAGE = ` conbridge-agent ssh add <alias> --host <host> [--port <n>] [--user <name>] [--identity <path>] [--production] [--confirm-fingerprint <SHA256:...>]
@@ -29206,7 +30308,7 @@ async function cmdSsh(stateDir, args, io) {
29206
30308
  host: values.host,
29207
30309
  port: parsePort(values.port),
29208
30310
  user: values.user,
29209
- identity: values.identity === void 0 ? void 0 : (0, import_node_path16.resolve)(values.identity),
30311
+ identity: values.identity === void 0 ? void 0 : (0, import_node_path17.resolve)(values.identity),
29210
30312
  production: values.production === true
29211
30313
  };
29212
30314
  await validateNewHost(input2);
@@ -29293,6 +30395,8 @@ ${SSH_USAGE}
29293
30395
  conbridge-agent access full [--no-home] AI apps you approve may run commands here (terminal, processes)
29294
30396
  conbridge-agent access files files only: shared folders, no terminal
29295
30397
  conbridge-agent access status
30398
+ conbridge-agent start foreground session; Ctrl+C stops it
30399
+ conbridge-agent kill [--yes] [--keep-runtime] remove this agent (alias: remove)
29296
30400
  conbridge-agent run [--confirm-writes]
29297
30401
  conbridge-agent supervise run, restarted after a crash (for systems without a service manager)
29298
30402
  conbridge-agent status [--json]
@@ -29310,6 +30414,9 @@ While it runs, the agent keeps the computer from idle-sleeping (the display may
29310
30414
  with config keep-awake off. Full access (pair --full-access or access full) lets AI apps you approve run commands
29311
30415
  like a terminal; in the Console you choose per computer whether each command asks you first.
29312
30416
 
30417
+ Modes: persistent starts automatically; passive runs only with start; timed expires and removes identity;
30418
+ ephemeral expires or self-destructs and purges ConBridge files.
30419
+
29313
30420
  Key store: macOS Keychain by default when the Keychain helper is available, else a 0600 key file.
29314
30421
  State dir: $CONBRIDGE_AGENT_HOME or ~/.conbridge/agent`;
29315
30422
  var UsageError = class extends Error {
@@ -29318,10 +30425,10 @@ function cliPath() {
29318
30425
  return (0, import_node_url3.fileURLToPath)(__conbridge_import_meta_url);
29319
30426
  }
29320
30427
  function lockPath(paths) {
29321
- return (0, import_node_path17.join)(paths.dir, "agent.lock");
30428
+ return (0, import_node_path18.join)(paths.dir, "agent.lock");
29322
30429
  }
29323
- async function exists(path) {
29324
- return (0, import_promises15.access)(path).then(() => true, () => false);
30430
+ async function exists2(path) {
30431
+ return (0, import_promises17.access)(path).then(() => true, () => false);
29325
30432
  }
29326
30433
  async function runInstalledCopy(paths, argv, io, keepsIdentity = true) {
29327
30434
  if (!runningFromNpm() || await runningFromRuntime(paths.dir))
@@ -29337,7 +30444,7 @@ async function runInstalledCopy(paths, argv, io, keepsIdentity = true) {
29337
30444
  let status;
29338
30445
  try {
29339
30446
  const { entry } = await installRuntime(paths.dir);
29340
- const child = (0, import_node_child_process10.spawnSync)(process.execPath, [entry, ...argv], { stdio: "inherit", env: io.env });
30447
+ const child = (0, import_node_child_process11.spawnSync)(process.execPath, [entry, ...argv], { stdio: "inherit", env: io.env });
29341
30448
  if (child.error)
29342
30449
  throw child.error;
29343
30450
  status = child.status ?? 1;
@@ -29381,12 +30488,12 @@ async function newKeyStore(paths, values, env) {
29381
30488
  throw new UsageError("--keychain only applies to the keychain key store");
29382
30489
  return new FileKeyStore(pendingKeyPath(paths));
29383
30490
  }
29384
- if (values.keychain !== void 0 && !(0, import_node_path17.isAbsolute)(values.keychain))
30491
+ if (values.keychain !== void 0 && !(0, import_node_path18.isAbsolute)(values.keychain))
29385
30492
  throw new UsageError("--keychain needs an absolute path");
29386
30493
  return new KeychainKeyStore({
29387
30494
  helperPath: helper,
29388
- keyId: (0, import_node_crypto11.randomUUID)(),
29389
- ...values.keychain !== void 0 ? { keychainPath: (0, import_node_path17.resolve)(values.keychain) } : {}
30495
+ keyId: (0, import_node_crypto12.randomUUID)(),
30496
+ ...values.keychain !== void 0 ? { keychainPath: (0, import_node_path18.resolve)(values.keychain) } : {}
29390
30497
  });
29391
30498
  }
29392
30499
  async function discardOldKey(paths, identity, env) {
@@ -29416,7 +30523,7 @@ async function cmdPair(paths, args, io) {
29416
30523
  if (installed !== null)
29417
30524
  return installed;
29418
30525
  const gateway = values.gateway ?? DEFAULT_GATEWAY_URL;
29419
- const name3 = (values.name ?? (0, import_node_os8.hostname)()).trim().slice(0, 64) || "My computer";
30526
+ const name3 = (values.name ?? (0, import_node_os9.hostname)()).trim().slice(0, 64) || "My computer";
29420
30527
  const keyStore = await newKeyStore(paths, values, io.env);
29421
30528
  const previous = await loadIdentity(paths);
29422
30529
  if (previous && !values.force)
@@ -29435,7 +30542,7 @@ async function cmdPair(paths, args, io) {
29435
30542
  },
29436
30543
  onApproved: async () => {
29437
30544
  if (keyStore.descriptor.type === "file")
29438
- await (0, import_promises15.rename)(pendingKeyPath(paths), paths.key);
30545
+ await (0, import_promises17.rename)(pendingKeyPath(paths), paths.key);
29439
30546
  }
29440
30547
  });
29441
30548
  if (previous && !(keyStore.descriptor.type === "file" && previous.key_store?.type !== "keychain"))
@@ -29443,6 +30550,12 @@ async function cmdPair(paths, args, io) {
29443
30550
  io.out(`Paired as "${identity.display_name}" (device ${identity.device_uuid}).`);
29444
30551
  if (values["full-access"])
29445
30552
  await cmdAccess(paths, ["full"], io);
30553
+ if (identity.connection_mode === "passive") {
30554
+ await removeAgentAutostart(paths.dir, lifecycleDeps(io));
30555
+ await stopSupervisor(paths);
30556
+ await stopAgentProcess(paths);
30557
+ return cmdRun(paths, [], io, "foreground");
30558
+ }
29446
30559
  if (values["no-service"]) {
29447
30560
  io.out("Next: conbridge-agent roots add <path> --label <label> [--writable], then conbridge-agent run (or service install)");
29448
30561
  return 0;
@@ -29463,7 +30576,7 @@ async function cmdConnect(paths, args, io) {
29463
30576
  const extraHosts = (io.env.CONBRIDGE_CONNECT_HOSTS ?? "").split(",").map((host) => host.trim()).filter(Boolean);
29464
30577
  return await runConnect(link, {
29465
30578
  dialogs: macConnectDialogs,
29466
- isPaired: () => exists(paths.identity),
30579
+ isPaired: () => exists2(paths.identity),
29467
30580
  addFolder: async (path, label, writable) => {
29468
30581
  await addRoot(paths, { path, label, writable, allowBroadRoot: false, ...io.env.HOME ? { home: io.env.HOME } : {} });
29469
30582
  },
@@ -29552,11 +30665,14 @@ async function warnBroadRoots(config2, stateDir, logger, home) {
29552
30665
  }
29553
30666
  return count3;
29554
30667
  }
29555
- async function cmdRun(paths, args, io) {
30668
+ async function cmdRun(paths, args, io, session = "service") {
29556
30669
  const { values } = (0, import_node_util2.parseArgs)({ args, allowPositionals: false, options: { "confirm-writes": { type: "boolean" } } });
29557
30670
  const identity = await loadIdentity(paths);
29558
30671
  if (!identity)
29559
30672
  throw new UsageError("Not paired yet; run conbridge-agent pair first");
30673
+ if (session === "foreground" && (identity.connection_mode === "timed" || identity.connection_mode === "ephemeral") && (await serviceLocation(paths.dir, lifecycleDeps(io)))?.installed) {
30674
+ throw new UsageError("This time-limited device already has autostart installed. Run conbridge-agent service uninstall before start.");
30675
+ }
29560
30676
  const key = await (await openKeyStore(paths, identity.key_store, { env: io.env })).load();
29561
30677
  if (!key)
29562
30678
  throw new Error("Device key is missing; pair again with --force");
@@ -29570,12 +30686,14 @@ async function cmdRun(paths, args, io) {
29570
30686
  if (keepAwakeEnabled(config2))
29571
30687
  stopKeepAwake = startKeepAwake({ logger });
29572
30688
  const journal = await Journal.open(paths.journal);
29573
- const runner = new AgentRunner({
30689
+ const runner = (io.lifecycle?.createRunner ?? ((options) => new AgentRunner(options)))({
29574
30690
  paths,
29575
30691
  identity,
29576
30692
  key,
29577
30693
  journal,
29578
30694
  logger,
30695
+ session,
30696
+ stopKeepAwake: () => stopKeepAwake(),
29579
30697
  confirmWrite: localConfirm,
29580
30698
  ...values["confirm-writes"] ? { confirmWritesOverride: true } : {}
29581
30699
  });
@@ -29587,11 +30705,20 @@ async function cmdRun(paths, args, io) {
29587
30705
  if (signals > 1)
29588
30706
  process.exit(130);
29589
30707
  };
29590
- process.on("SIGINT", () => onSignal("SIGINT"));
29591
- process.on("SIGTERM", () => onSignal("SIGTERM"));
30708
+ const signalsToHandle = ["SIGINT", "SIGTERM", "SIGHUP"];
30709
+ const handlers = signalsToHandle.map((signal) => {
30710
+ const handler = () => onSignal(signal);
30711
+ process.on(signal, handler);
30712
+ return { signal, handler };
30713
+ });
29592
30714
  logger.info("agent starting", { device_uuid: identity.device_uuid, gateway: identity.gateway_url, version: AGENT_VERSION });
29593
30715
  io.out(`ConBridge agent running for device ${identity.device_uuid}. Press Ctrl+C to stop.`);
29594
- await runner.run();
30716
+ try {
30717
+ await runner.run();
30718
+ } finally {
30719
+ for (const { signal, handler } of handlers)
30720
+ process.off(signal, handler);
30721
+ }
29595
30722
  logger.info("agent stopped");
29596
30723
  return 0;
29597
30724
  } finally {
@@ -29648,7 +30775,7 @@ async function cmdStatus(paths, args, io) {
29648
30775
  io.out(`Confirm writes locally: ${config2.confirm_writes ? "on" : "off"}`);
29649
30776
  io.out(`Keep-awake: ${keepAwakeEnabled(config2) ? "on" : "off"}`);
29650
30777
  io.out(`Full access (terminal): ${config2.full_access === true ? "on" : "off"}`);
29651
- if (await exists(paths.journal))
30778
+ if (await exists2(paths.journal))
29652
30779
  io.out(`Journaled tasks: ${(await Journal.open(paths.journal)).size}`);
29653
30780
  const pid = await readLockPid(lockPath(paths));
29654
30781
  io.out(`Agent process: ${pid ? `running (pid ${pid})` : "not running"}`);
@@ -29667,7 +30794,7 @@ async function stopAgentProcess(paths) {
29667
30794
  }
29668
30795
  }
29669
30796
  async function cmdUpdate(paths, io) {
29670
- if (!await exists(paths.identity)) {
30797
+ if (!await exists2(paths.identity)) {
29671
30798
  io.err("Pair this computer first: conbridge-agent pair --code XXXX-XXXX");
29672
30799
  return 2;
29673
30800
  }
@@ -29695,7 +30822,7 @@ async function cmdService(paths, args, io) {
29695
30822
  io.out(buildLaunchAgentPlist({ ...command2, ...custom2, logPath }).trimEnd());
29696
30823
  return 0;
29697
30824
  case "install": {
29698
- if (!await exists(paths.identity)) {
30825
+ if (!await exists2(paths.identity)) {
29699
30826
  io.err("Pair this computer first: conbridge-agent pair --code XXXX-XXXX");
29700
30827
  return 2;
29701
30828
  }
@@ -29750,18 +30877,18 @@ function serviceLogPath(env) {
29750
30877
  return defaultLogPath();
29751
30878
  }
29752
30879
  function supervisorPidPath(paths) {
29753
- return (0, import_node_path17.join)(paths.dir, "supervisor.pid");
30880
+ return (0, import_node_path18.join)(paths.dir, "supervisor.pid");
29754
30881
  }
29755
30882
  function startSupervisorNow(command2, logPath, env) {
29756
30883
  const [file2, ...args] = programArguments(command2);
29757
- void (0, import_promises15.open)(logPath, "a", 384).then((log) => {
29758
- const child = (0, import_node_child_process10.spawn)(file2, [...args.slice(0, -1), "supervise"], { detached: true, stdio: ["ignore", log.fd, log.fd], env });
30884
+ void (0, import_promises17.open)(logPath, "a", 384).then((log) => {
30885
+ const child = (0, import_node_child_process11.spawn)(file2, [...args.slice(0, -1), "supervise"], { detached: true, stdio: ["ignore", log.fd, log.fd], env });
29759
30886
  child.unref();
29760
30887
  void log.close();
29761
30888
  });
29762
30889
  }
29763
30890
  async function stopSupervisor(paths) {
29764
- const pid = Number.parseInt(await (0, import_promises15.readFile)(supervisorPidPath(paths), "utf8").catch(() => ""), 10);
30891
+ const pid = Number.parseInt(await (0, import_promises17.readFile)(supervisorPidPath(paths), "utf8").catch(() => ""), 10);
29765
30892
  if (Number.isInteger(pid) && pid > 1 && pid !== process.pid) {
29766
30893
  try {
29767
30894
  process.kill(pid, "SIGTERM");
@@ -29771,7 +30898,7 @@ async function stopSupervisor(paths) {
29771
30898
  }
29772
30899
  async function cmdSupervise(paths, io) {
29773
30900
  await ensureStateDir(paths.dir);
29774
- await (0, import_promises15.writeFile)(supervisorPidPath(paths), `${process.pid}
30901
+ await (0, import_promises17.writeFile)(supervisorPidPath(paths), `${process.pid}
29775
30902
  `, { mode: 384 });
29776
30903
  const command2 = await agentLaunchCommand({ sea: runningAsSea(), cliPath: cliPath() });
29777
30904
  const [file2, ...args] = programArguments(command2);
@@ -29785,18 +30912,18 @@ async function cmdSupervise(paths, io) {
29785
30912
  process.on("SIGINT", stop);
29786
30913
  try {
29787
30914
  while (!stopping) {
29788
- child = (0, import_node_child_process10.spawn)(file2, args, { stdio: "inherit", env: io.env });
29789
- const code = await new Promise((resolve8) => {
29790
- child.on("exit", (exitCode) => resolve8(exitCode));
29791
- child.on("error", () => resolve8(1));
30915
+ child = (0, import_node_child_process11.spawn)(file2, args, { stdio: "inherit", env: io.env });
30916
+ const code = await new Promise((resolve9) => {
30917
+ child.on("exit", (exitCode) => resolve9(exitCode));
30918
+ child.on("error", () => resolve9(1));
29792
30919
  });
29793
30920
  if (stopping || code === 0)
29794
30921
  break;
29795
30922
  io.err(`${(/* @__PURE__ */ new Date()).toISOString()} supervisor: agent exited with ${String(code)}; restarting in 10 s`);
29796
- await new Promise((resolve8) => setTimeout(resolve8, 1e4));
30923
+ await new Promise((resolve9) => setTimeout(resolve9, 1e4));
29797
30924
  }
29798
30925
  } finally {
29799
- await (0, import_promises15.unlink)(supervisorPidPath(paths)).catch(() => void 0);
30926
+ await (0, import_promises17.unlink)(supervisorPidPath(paths)).catch(() => void 0);
29800
30927
  }
29801
30928
  return 0;
29802
30929
  }
@@ -29818,8 +30945,8 @@ async function cmdAccess(paths, args, io) {
29818
30945
  const { values } = (0, import_node_util2.parseArgs)({ args: rest, allowPositionals: false, options: { "no-home": { type: "boolean" } } });
29819
30946
  await saveConfig(paths, { ...config2, full_access: true });
29820
30947
  if (!values["no-home"]) {
29821
- const home = io.env.HOME ?? (0, import_node_os8.homedir)();
29822
- const real = await (0, import_promises15.realpath)(home).catch(() => null);
30948
+ const home = io.env.HOME ?? (0, import_node_os9.homedir)();
30949
+ const real = await (0, import_promises17.realpath)(home).catch(() => null);
29823
30950
  const covered = config2.roots.some((root) => root.path === real);
29824
30951
  if (real && !covered) {
29825
30952
  const root = await addRoot(paths, { path: real, label: "Home", writable: true, allowBroadRoot: true, home });
@@ -29852,7 +30979,7 @@ async function cmdDoctor(paths, io) {
29852
30979
  const pid = await readLockPid(lockPath(paths));
29853
30980
  checks.push({ ok: pid !== null, label: "Agent running", detail: pid !== null ? `pid ${pid}` : "not running" });
29854
30981
  const config2 = await loadConfig(paths);
29855
- const roots = await Promise.all(config2.roots.map(async (root) => ({ root, ok: await (0, import_promises15.stat)(root.path).then((info) => info.isDirectory(), () => false) })));
30982
+ const roots = await Promise.all(config2.roots.map(async (root) => ({ root, ok: await (0, import_promises17.stat)(root.path).then((info) => info.isDirectory(), () => false) })));
29856
30983
  checks.push({
29857
30984
  ok: roots.every((entry) => entry.ok) ? roots.length > 0 ? true : null : false,
29858
30985
  label: "Shared folders",
@@ -29870,11 +30997,11 @@ async function cmdLogs(paths, args, io) {
29870
30997
  const service = await serviceLocation(paths.dir);
29871
30998
  if (process.platform === "linux" && service?.installed && service.location.endsWith(".service")) {
29872
30999
  const system = service.location.startsWith("/etc/");
29873
- const child = (0, import_node_child_process10.spawnSync)("journalctl", [...system ? [] : ["--user"], "-u", SYSTEMD_UNIT, "-n", String(lines4), ...values.follow ? ["-f"] : [], "--no-pager"], { stdio: "inherit" });
31000
+ const child = (0, import_node_child_process11.spawnSync)("journalctl", [...system ? [] : ["--user"], "-u", SYSTEMD_UNIT, "-n", String(lines4), ...values.follow ? ["-f"] : [], "--no-pager"], { stdio: "inherit" });
29874
31001
  return child.status ?? 1;
29875
31002
  }
29876
31003
  const logPath = serviceLogPath(io.env);
29877
- const text6 = await (0, import_promises15.readFile)(logPath, "utf8").catch(() => null);
31004
+ const text6 = await (0, import_promises17.readFile)(logPath, "utf8").catch(() => null);
29878
31005
  if (text6 === null) {
29879
31006
  io.err(`No log at ${logPath} yet.`);
29880
31007
  return 1;
@@ -29884,14 +31011,14 @@ async function cmdLogs(paths, args, io) {
29884
31011
  io.out(line);
29885
31012
  if (!values.follow)
29886
31013
  return 0;
29887
- let size = (await (0, import_promises15.stat)(logPath)).size;
31014
+ let size = (await (0, import_promises17.stat)(logPath)).size;
29888
31015
  for (; ; ) {
29889
- await new Promise((resolve8) => setTimeout(resolve8, 1e3));
29890
- const now = (await (0, import_promises15.stat)(logPath).catch(() => null))?.size ?? 0;
31016
+ await new Promise((resolve9) => setTimeout(resolve9, 1e3));
31017
+ const now = (await (0, import_promises17.stat)(logPath).catch(() => null))?.size ?? 0;
29891
31018
  if (now < size)
29892
31019
  size = 0;
29893
31020
  if (now > size) {
29894
- const handle = await (0, import_promises15.open)(logPath, "r");
31021
+ const handle = await (0, import_promises17.open)(logPath, "r");
29895
31022
  const buffer = Buffer.alloc(now - size);
29896
31023
  await handle.read(buffer, 0, buffer.length, size);
29897
31024
  await handle.close();
@@ -29907,10 +31034,34 @@ async function cmdUnpair(paths, io) {
29907
31034
  await stopAgentProcess(paths);
29908
31035
  if (identity)
29909
31036
  await discardOldKey(paths, identity, io.env);
29910
- await (0, import_promises15.unlink)(paths.identity).catch(() => void 0);
31037
+ await (0, import_promises17.unlink)(paths.identity).catch(() => void 0);
29911
31038
  io.out(identity ? `Removed the identity of "${identity.display_name}". Remove it in the ConBridge Console (Devices) as well; its key no longer exists here.` : "This computer was not paired.");
29912
31039
  return 0;
29913
31040
  }
31041
+ function lifecycleDeps(io) {
31042
+ return { env: io.env, home: io.env.HOME ?? io.env.USERPROFILE ?? (0, import_node_os9.homedir)(), ...io.lifecycle?.purgeDeps };
31043
+ }
31044
+ async function cmdKill(paths, args, io) {
31045
+ const { values } = (0, import_node_util2.parseArgs)({ args, allowPositionals: false, options: { yes: { type: "boolean" }, "keep-runtime": { type: "boolean" } } });
31046
+ if (!values.yes) {
31047
+ if (!process.stdin.isTTY)
31048
+ throw new UsageError("Removal needs confirmation; use --yes to remove this agent without a prompt.");
31049
+ const prompt = (0, import_promises16.createInterface)({ input: process.stdin, output: process.stdout });
31050
+ try {
31051
+ if ((await prompt.question("Remove ConBridge and its identity from this computer? [y/N] ")).trim().toLowerCase() !== "y")
31052
+ return 0;
31053
+ } finally {
31054
+ prompt.close();
31055
+ }
31056
+ }
31057
+ await stopSupervisor(paths);
31058
+ await stopAgentProcess(paths);
31059
+ const report = await purgeAgent({ reason: "left", keepRuntime: values["keep-runtime"] ?? false, stateDir: paths.dir }, {
31060
+ ...lifecycleDeps(io),
31061
+ report: io.out
31062
+ });
31063
+ return report.steps.every((step) => step.ok || step.step === "leave") ? 0 : 1;
31064
+ }
29914
31065
  async function main(argv, io) {
29915
31066
  const [command2, ...args] = argv;
29916
31067
  const paths = statePaths(resolveStateDir(io.env));
@@ -29926,6 +31077,11 @@ async function main(argv, io) {
29926
31077
  return await cmdConfig(paths, args, io);
29927
31078
  case "ssh":
29928
31079
  return await cmdSsh(paths.dir, args, io);
31080
+ case "start":
31081
+ return await cmdRun(paths, args, io, "foreground");
31082
+ case "kill":
31083
+ case "remove":
31084
+ return await cmdKill(paths, args, io);
29929
31085
  case "run":
29930
31086
  return await cmdRun(paths, args, io);
29931
31087
  case "status":