peerband 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/peerband.mjs CHANGED
@@ -65,13 +65,13 @@ var require_buffer_util = __commonJS({
65
65
  "use strict";
66
66
  var { EMPTY_BUFFER } = require_constants();
67
67
  var FastBuffer = Buffer[Symbol.species];
68
- function concat(list, totalLength) {
69
- if (list.length === 0) return EMPTY_BUFFER;
70
- if (list.length === 1) return list[0];
68
+ function concat(list2, totalLength) {
69
+ if (list2.length === 0) return EMPTY_BUFFER;
70
+ if (list2.length === 1) return list2[0];
71
71
  const target = Buffer.allocUnsafe(totalLength);
72
72
  let offset = 0;
73
- for (let i = 0; i < list.length; i++) {
74
- const buf = list[i];
73
+ for (let i = 0; i < list2.length; i++) {
74
+ const buf = list2[i];
75
75
  target.set(buf, offset);
76
76
  offset += buf.length;
77
77
  }
@@ -1857,14 +1857,14 @@ var require_sender = __commonJS({
1857
1857
  * @param {Function} [cb] Callback
1858
1858
  * @private
1859
1859
  */
1860
- sendFrame(list, cb) {
1861
- if (list.length === 2) {
1860
+ sendFrame(list2, cb) {
1861
+ if (list2.length === 2) {
1862
1862
  this._socket.cork();
1863
- this._socket.write(list[0]);
1864
- this._socket.write(list[1], cb);
1863
+ this._socket.write(list2[0]);
1864
+ this._socket.write(list2[1], cb);
1865
1865
  this._socket.uncork();
1866
1866
  } else {
1867
- this._socket.write(list[0], cb);
1867
+ this._socket.write(list2[0], cb);
1868
1868
  }
1869
1869
  }
1870
1870
  };
@@ -6873,7 +6873,7 @@ var require_compile = __commonJS({
6873
6873
  const schOrFunc = root.refs[ref];
6874
6874
  if (schOrFunc)
6875
6875
  return schOrFunc;
6876
- let _sch = resolve3.call(this, root, ref);
6876
+ let _sch = resolve5.call(this, root, ref);
6877
6877
  if (_sch === void 0) {
6878
6878
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
6879
6879
  const { schemaId } = this.opts;
@@ -6900,7 +6900,7 @@ var require_compile = __commonJS({
6900
6900
  function sameSchemaEnv(s1, s2) {
6901
6901
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
6902
6902
  }
6903
- function resolve3(root, ref) {
6903
+ function resolve5(root, ref) {
6904
6904
  let sch;
6905
6905
  while (typeof (sch = this.refs[ref]) == "string")
6906
6906
  ref = sch;
@@ -7730,7 +7730,7 @@ var require_fast_uri = __commonJS({
7730
7730
  }
7731
7731
  return uri;
7732
7732
  }
7733
- function resolve3(baseURI, relativeURI, options) {
7733
+ function resolve5(baseURI, relativeURI, options) {
7734
7734
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
7735
7735
  const {
7736
7736
  parsed: baseParsed,
@@ -8099,7 +8099,7 @@ var require_fast_uri = __commonJS({
8099
8099
  var fastUri = {
8100
8100
  SCHEMES,
8101
8101
  normalize,
8102
- resolve: resolve3,
8102
+ resolve: resolve5,
8103
8103
  resolveComponent,
8104
8104
  equal,
8105
8105
  serialize,
@@ -10859,8 +10859,8 @@ var require_dist = __commonJS({
10859
10859
  return ajv;
10860
10860
  }
10861
10861
  const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
10862
- const list = opts.formats || formats_1.formatNames;
10863
- addFormats2(ajv, list, formats, exportName);
10862
+ const list2 = opts.formats || formats_1.formatNames;
10863
+ addFormats2(ajv, list2, formats, exportName);
10864
10864
  if (opts.keywords)
10865
10865
  (0, limit_1.default)(ajv);
10866
10866
  return ajv;
@@ -10872,11 +10872,11 @@ var require_dist = __commonJS({
10872
10872
  throw new Error(`Unknown format "${name}"`);
10873
10873
  return f;
10874
10874
  };
10875
- function addFormats2(ajv, list, fs, exportName) {
10875
+ function addFormats2(ajv, list2, fs, exportName) {
10876
10876
  var _a;
10877
10877
  var _b;
10878
10878
  (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
10879
- for (const f of list)
10879
+ for (const f of list2)
10880
10880
  ajv.addFormat(f, fs[f]);
10881
10881
  }
10882
10882
  module.exports = exports = formatsPlugin;
@@ -11867,8 +11867,8 @@ var ConnectorCore = class {
11867
11867
  async execute(tool, args, principal = DEFAULT_PRINCIPAL) {
11868
11868
  if (this.closed) throw new ConnectError("connector_closed", "The connector is shutting down.", "Restart the connector to make further requests.");
11869
11869
  let finishOperation;
11870
- const operation = new Promise((resolve3) => {
11871
- finishOperation = resolve3;
11870
+ const operation = new Promise((resolve5) => {
11871
+ finishOperation = resolve5;
11872
11872
  });
11873
11873
  this.activeOperations.add(operation);
11874
11874
  try {
@@ -11975,7 +11975,7 @@ var ConnectorCore = class {
11975
11975
  }
11976
11976
  async sendMessage(args, principal) {
11977
11977
  assertKeys(args, ["agentId", "message", "idempotencyKey"]);
11978
- if (!this.writesEnabled) throw new ConnectError("write_disabled", "Message sending is disabled.", "Enable writes explicitly in local configuration.");
11978
+ if (!this.writesEnabled) throw new ConnectError("write_disabled", "Message sending is disabled.", 'This machine is read-only. To allow messages, remove --read-only or set "enableWrites": true in connector.json on that machine.');
11979
11979
  this.requireScope(principal, "agents:message");
11980
11980
  const key = args.idempotencyKey;
11981
11981
  const message = args.message;
@@ -12033,8 +12033,8 @@ var ConnectorCore = class {
12033
12033
  async withSubmissionLock(key, action) {
12034
12034
  const previous = this.submissionLocks.get(key) ?? Promise.resolve();
12035
12035
  let release;
12036
- const current = new Promise((resolve3) => {
12037
- release = resolve3;
12036
+ const current = new Promise((resolve5) => {
12037
+ release = resolve5;
12038
12038
  });
12039
12039
  this.submissionLocks.set(key, current);
12040
12040
  await previous;
@@ -12436,12 +12436,13 @@ function enrollmentBase(serverUrl) {
12436
12436
  throw new Error("Enrollment requires HTTPS except on localhost.");
12437
12437
  return base;
12438
12438
  }
12439
- async function redeemEnrollment(serverUrl, grant, name, fetcher = fetch) {
12439
+ async function redeemEnrollment(serverUrl, grant, name, fetcher = fetch, previousCredential) {
12440
12440
  const base = enrollmentBase(serverUrl);
12441
12441
  const response = await fetcher(new URL("/api/enrollments/redeem", base), {
12442
12442
  method: "POST",
12443
12443
  headers: { "content-type": "application/json" },
12444
- body: JSON.stringify({ grant, name }),
12444
+ // previous_credential lets the server keep this machine's record (see DeviceLoginOptions).
12445
+ body: JSON.stringify({ grant, name, ...previousCredential ? { previous_credential: previousCredential } : {} }),
12445
12446
  signal: AbortSignal.timeout(15e3)
12446
12447
  });
12447
12448
  const body = await response.json().catch(() => ({}));
@@ -12465,7 +12466,7 @@ async function runRemoteClient(core, credentials, options = {}) {
12465
12466
  });
12466
12467
  const reportActivity = options.onActivity ?? (() => {
12467
12468
  });
12468
- const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
12469
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
12469
12470
  const serverUrl = socketUrl(credentials.serverUrl);
12470
12471
  const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 75e3;
12471
12472
  let stopped = false;
@@ -12485,7 +12486,7 @@ async function runRemoteClient(core, credentials, options = {}) {
12485
12486
  while (!stopped) {
12486
12487
  try {
12487
12488
  setConnectionState("connecting");
12488
- await new Promise((resolve3, reject) => {
12489
+ await new Promise((resolve5, reject) => {
12489
12490
  const socket = new wrapper_default(serverUrl, {
12490
12491
  headers: { Authorization: `Bearer ${credentials.credential}` },
12491
12492
  maxPayload: MAX_FRAME,
@@ -12671,7 +12672,7 @@ async function runRemoteClient(core, credentials, options = {}) {
12671
12672
  code === 1008 || code === 4001 ? `remote authentication or policy rejected the connection (${code})` : `remote connection closed (${code})${reason.length ? `: ${reason.toString()}` : ""}`
12672
12673
  );
12673
12674
  if (current === socket) current = void 0;
12674
- resolve3();
12675
+ resolve5();
12675
12676
  });
12676
12677
  });
12677
12678
  } catch (error) {
@@ -12711,12 +12712,12 @@ var DeviceLoginError = class extends Error {
12711
12712
  var REQUEST_TIMEOUT_MS2 = 15e3;
12712
12713
  var MAX_BACKOFF_MS = 3e4;
12713
12714
  var SLOW_DOWN_STEP_S = 5;
12714
- var defaultSleep = (ms, signal) => new Promise((resolve3) => {
12715
- if (signal?.aborted) return resolve3();
12715
+ var defaultSleep = (ms, signal) => new Promise((resolve5) => {
12716
+ if (signal?.aborted) return resolve5();
12716
12717
  const done = () => {
12717
12718
  clearTimeout(timer);
12718
12719
  signal?.removeEventListener("abort", done);
12719
- resolve3();
12720
+ resolve5();
12720
12721
  };
12721
12722
  const timer = setTimeout(done, ms);
12722
12723
  signal?.addEventListener("abort", done, { once: true });
@@ -12799,7 +12800,11 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
12799
12800
  if (now() >= deadline) throw expired();
12800
12801
  let result;
12801
12802
  try {
12802
- result = await postJson(url, { device_code: code.deviceCode }, options);
12803
+ result = await postJson(
12804
+ url,
12805
+ { device_code: code.deviceCode, ...options.previousCredential ? { previous_credential: options.previousCredential } : {} },
12806
+ options
12807
+ );
12803
12808
  } catch {
12804
12809
  if (options.signal?.aborted) throw aborted();
12805
12810
  failures = Math.min(failures + 1, 10);
@@ -12889,11 +12894,11 @@ function suggest(input, candidates) {
12889
12894
  return best?.name;
12890
12895
  }
12891
12896
  var HELP_OPTION = { name: "help", short: "h", type: "boolean", description: "Show help for this command." };
12892
- function parseArgs(spec6, argv) {
12893
- const options = [...spec6.options, HELP_OPTION];
12897
+ function parseArgs(spec7, argv) {
12898
+ const options = [...spec7.options, HELP_OPTION];
12894
12899
  const values = {};
12895
12900
  const positionals = [];
12896
- const helpHint = `Run \`peerband ${spec6.name} --help\` for usage.`;
12901
+ const helpHint = `Run \`peerband ${spec7.name} --help\` for usage.`;
12897
12902
  for (let i = 0; i < argv.length; i++) {
12898
12903
  const arg = argv[i];
12899
12904
  if (arg === "--") {
@@ -12913,11 +12918,11 @@ function parseArgs(spec6, argv) {
12913
12918
  option = options.find((candidate) => candidate.name === name);
12914
12919
  if (!option) {
12915
12920
  const near = suggest(name, options.filter((o) => !o.hidden).map((o) => o.name));
12916
- throw new UsageError(`Unknown option --${name} for \`peerband ${spec6.name}\`.`, near ? `Did you mean --${near}? ${helpHint}` : helpHint);
12921
+ throw new UsageError(`Unknown option --${name} for \`peerband ${spec7.name}\`.`, near ? `Did you mean --${near}? ${helpHint}` : helpHint);
12917
12922
  }
12918
12923
  } else {
12919
12924
  option = options.find((candidate) => candidate.short === arg.slice(1));
12920
- if (!option) throw new UsageError(`Unknown option ${arg} for \`peerband ${spec6.name}\`.`, helpHint);
12925
+ if (!option) throw new UsageError(`Unknown option ${arg} for \`peerband ${spec7.name}\`.`, helpHint);
12921
12926
  }
12922
12927
  if (option.type === "boolean") {
12923
12928
  if (inline !== void 0) throw new UsageError(`Option --${option.name} does not take a value.`, helpHint);
@@ -12935,9 +12940,9 @@ function parseArgs(spec6, argv) {
12935
12940
  }
12936
12941
  values[option.name] = value;
12937
12942
  }
12938
- const max = spec6.positionals?.max ?? 0;
12943
+ const max = spec7.positionals?.max ?? 0;
12939
12944
  if (positionals.length > max) {
12940
- throw new UsageError(`Unexpected argument "${positionals[max]}" for \`peerband ${spec6.name}\`.`, helpHint);
12945
+ throw new UsageError(`Unexpected argument "${positionals[max]}" for \`peerband ${spec7.name}\`.`, helpHint);
12941
12946
  }
12942
12947
  return { values, positionals };
12943
12948
  }
@@ -12953,17 +12958,17 @@ function herdrBinary(env, platform = process.platform) {
12953
12958
  return env.HERDR_BIN_PATH || (platform === "win32" ? "herdr.exe" : "herdr");
12954
12959
  }
12955
12960
  function createHerdrRunner(env) {
12956
- return (args, options) => new Promise((resolve3) => {
12961
+ return (args, options) => new Promise((resolve5) => {
12957
12962
  execFile(
12958
12963
  herdrBinary(env),
12959
12964
  args,
12960
12965
  { env, timeout: options?.timeoutMs ?? 6e4, windowsHide: true, maxBuffer: 4 * 1024 * 1024, shell: false },
12961
12966
  (error, stdout, stderr) => {
12962
- if (!error) return resolve3({ code: 0, stdout, stderr });
12967
+ if (!error) return resolve5({ code: 0, stdout, stderr });
12963
12968
  const failure = error;
12964
- if (failure.code === "ENOENT") return resolve3({ code: 127, stdout: "", stderr: failure.message, notFound: true });
12969
+ if (failure.code === "ENOENT") return resolve5({ code: 127, stdout: "", stderr: failure.message, notFound: true });
12965
12970
  const code = typeof failure.code === "number" ? failure.code : 1;
12966
- resolve3({ code, stdout: stdout ?? "", stderr: stderr || (failure.killed ? "timed out" : failure.message) });
12971
+ resolve5({ code, stdout: stdout ?? "", stderr: stderr || (failure.killed ? "timed out" : failure.message) });
12967
12972
  }
12968
12973
  );
12969
12974
  });
@@ -12982,7 +12987,7 @@ function failureDetail(result) {
12982
12987
  }
12983
12988
 
12984
12989
  // src/cli/commands/connect.ts
12985
- import { resolve } from "node:path";
12990
+ import { resolve as resolve2 } from "node:path";
12986
12991
 
12987
12992
  // src/runtime-herdr/adapter.ts
12988
12993
  import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
@@ -13038,7 +13043,7 @@ var HerdrSocketClient = class {
13038
13043
  this.inflight -= 1;
13039
13044
  throw error;
13040
13045
  }
13041
- return new Promise((resolve3, reject) => {
13046
+ return new Promise((resolve5, reject) => {
13042
13047
  const timer = setTimeout(() => {
13043
13048
  this.pending.delete(id);
13044
13049
  this.inflight -= 1;
@@ -13046,7 +13051,7 @@ var HerdrSocketClient = class {
13046
13051
  reject(method === "agent.prompt" ? new ConnectError("delivery_unknown", "Herdr did not acknowledge the prompt before the request timed out.", "Check the agent status before deciding whether to send the prompt again.") : new ConnectError("timeout", `Herdr ${method} request timed out`, "Check that Herdr is responsive and retry the read."));
13047
13052
  }, this.timeoutMs);
13048
13053
  timer.unref?.();
13049
- this.pending.set(id, { resolve: resolve3, reject, timer, method, socket });
13054
+ this.pending.set(id, { resolve: resolve5, reject, timer, method, socket });
13050
13055
  socket.write(line, (error) => {
13051
13056
  if (!error) return;
13052
13057
  const pending = this.pending.get(id);
@@ -13062,13 +13067,13 @@ var HerdrSocketClient = class {
13062
13067
  async close() {
13063
13068
  this.closed = true;
13064
13069
  this.failAll(this.unavailable("Herdr socket client closed"));
13065
- await Promise.all([...this.sockets].map((socket) => new Promise((resolve3) => {
13066
- if (socket.destroyed) resolve3();
13067
- else socket.end(resolve3);
13070
+ await Promise.all([...this.sockets].map((socket) => new Promise((resolve5) => {
13071
+ if (socket.destroyed) resolve5();
13072
+ else socket.end(resolve5);
13068
13073
  })));
13069
13074
  }
13070
13075
  connect() {
13071
- return new Promise((resolve3, reject) => {
13076
+ return new Promise((resolve5, reject) => {
13072
13077
  const socket = createConnection(this.socketPath);
13073
13078
  const onError = () => {
13074
13079
  socket.destroy();
@@ -13089,7 +13094,7 @@ var HerdrSocketClient = class {
13089
13094
  this.buffers.delete(socket);
13090
13095
  this.failSocket(socket, this.unavailable("Herdr closed the socket before replying"));
13091
13096
  });
13092
- resolve3(socket);
13097
+ resolve5(socket);
13093
13098
  });
13094
13099
  });
13095
13100
  }
@@ -13250,7 +13255,7 @@ async function loadHerdrSchema(options = {}) {
13250
13255
  const promptRef = prompt?.properties?.params?.$ref;
13251
13256
  const promptName = promptRef?.split("/").at(-1);
13252
13257
  const params = promptName ? schema.schemas.request.$defs?.[promptName] : void 0;
13253
- const writesHaveAtomicOccupantGuard = Boolean(params?.properties && Object.entries(params.properties).some(([name, spec6]) => /^(expected_generation|expected_terminal_id|expected_agent_session)$/i.test(name) && JSON.stringify(spec6).toLowerCase().includes("occupant")));
13258
+ const writesHaveAtomicOccupantGuard = Boolean(params?.properties && Object.entries(params.properties).some(([name, spec7]) => /^(expected_generation|expected_terminal_id|expected_agent_session)$/i.test(name) && JSON.stringify(spec7).toLowerCase().includes("occupant")));
13254
13259
  return {
13255
13260
  schema,
13256
13261
  validateRequest,
@@ -13521,6 +13526,7 @@ var Output = class {
13521
13526
  var symbols = { ok: "\u2713", dot: "\u25CF", ring: "\u25CB", warn: "!", fail: "\u2717" };
13522
13527
 
13523
13528
  // src/cli/commands/shared.ts
13529
+ import { resolve } from "node:path";
13524
13530
  var credentialsFile = (ctx) => credentialsPath({ env: ctx.env });
13525
13531
  async function requireCredentials(ctx) {
13526
13532
  try {
@@ -13532,6 +13538,19 @@ async function requireCredentials(ctx) {
13532
13538
  throw error;
13533
13539
  }
13534
13540
  }
13541
+ async function loadMachineConnectorConfig(ctx, explicitPath) {
13542
+ const explicit = explicitPath ?? ctx.env.PEERBAND_CONNECTOR_CONFIG;
13543
+ return explicit ? loadConnectorConfig(resolve(explicit)) : loadConnectorConfig(connectorConfigPath({ env: ctx.env }), { optional: true });
13544
+ }
13545
+ function writesEnabled(config, flags = {}) {
13546
+ if (flags.readOnly) return false;
13547
+ if (flags.enableWrites) return true;
13548
+ return config.enableWrites !== false;
13549
+ }
13550
+ var SKILL_COMMAND = "npx skills add kshvidler/peerband-cli";
13551
+ function printSkillTip(ctx) {
13552
+ ctx.out.print(ctx.out.stdout.dim(`Give your coding agents the PeerBand skill: ${SKILL_COMMAND}`));
13553
+ }
13535
13554
  var describeMachine = (credentials) => credentials.machineName ?? credentials.installationId;
13536
13555
  function printMcpHint(ctx, serverUrl) {
13537
13556
  const s = ctx.out.stdout;
@@ -13583,18 +13602,19 @@ function activityLine(s, activity, at = /* @__PURE__ */ new Date()) {
13583
13602
  var spec = {
13584
13603
  name: "connect",
13585
13604
  summary: "Run the connector in the foreground",
13586
- usage: "peerband connect [--runtime herdr|mock] [--enable-writes] [--config PATH] [--server URL]",
13587
- description: "Connects this machine to PeerBand and serves agent requests from your MCP clients until you press Ctrl+C. Without --enable-writes the connector is read-only. Activity lines show metadata only (tool, target, outcome, latency), never message or output content. Most people use `peerband relay` instead, which runs the connector inside Herdr.",
13605
+ usage: "peerband connect [--runtime herdr|mock] [--read-only] [--config PATH] [--server URL]",
13606
+ description: 'Connects this machine to PeerBand and serves agent requests from your MCP clients until you press Ctrl+C. MCP clients may send messages to agents by default, but only after you approve the agents:message consent when you connect them; pass --read-only (or set "enableWrites": false in connector.json) to make this machine read-only. Activity lines show metadata only (tool, target, outcome, latency), never message or output content. Most people use `peerband relay` instead, which runs the connector inside Herdr.',
13588
13607
  options: [
13589
13608
  { name: "runtime", type: "string", valueName: "herdr|mock", description: 'Agent runtime. Default: $PEERBAND_RUNTIME or herdr. "mock" serves fake agents for testing.' },
13590
- { name: "enable-writes", type: "boolean", description: 'Allow MCP clients to send messages to agents (also: "enableWrites": true in connector.json).' },
13609
+ { name: "read-only", type: "boolean", description: 'Do not allow MCP clients to send messages to agents on this machine (also: "enableWrites": false in connector.json).' },
13610
+ { name: "enable-writes", type: "boolean", description: "Redundant: sending messages is allowed by default. Kept so old scripts keep working." },
13591
13611
  { name: "config", type: "string", valueName: "PATH", description: "Connector config file. Default: $PEERBAND_CONNECTOR_CONFIG or connector.json in the config directory (optional)." },
13592
13612
  { name: "server", type: "string", valueName: "URL", description: "Override the server stored at login." },
13593
13613
  { name: "managed", type: "boolean", hidden: true, description: "Internal: run under the Herdr plugin supervisor over IPC." }
13594
13614
  ],
13595
13615
  examples: [
13596
- ["peerband connect", "Serve read-only until Ctrl+C"],
13597
- ["peerband connect --enable-writes", "Also allow sending messages to agents"],
13616
+ ["peerband connect", "Serve until Ctrl+C; messages to agents are allowed (with OAuth consent)"],
13617
+ ["peerband connect --read-only", "Never let MCP clients send messages to agents from this machine"],
13598
13618
  ["peerband connect --runtime mock", "Try the connection with fake agents"]
13599
13619
  ],
13600
13620
  async run(parsed, ctx) {
@@ -13602,6 +13622,7 @@ var spec = {
13602
13622
  {
13603
13623
  runtime: str(parsed, "runtime"),
13604
13624
  enableWrites: flag(parsed, "enable-writes"),
13625
+ readOnly: flag(parsed, "read-only"),
13605
13626
  config: str(parsed, "config"),
13606
13627
  server: str(parsed, "server"),
13607
13628
  managed: flag(parsed, "managed")
@@ -13618,9 +13639,9 @@ async function connect(options, ctx) {
13618
13639
  if (runtime !== "herdr" && runtime !== "mock") throw new UsageError(`Unknown runtime "${runtime}".`, "Use --runtime herdr or --runtime mock.");
13619
13640
  const credentials = await requireCredentials(ctx);
13620
13641
  if (options.server) credentials.serverUrl = validateServerUrl(options.server);
13621
- const explicitConfig = options.config ?? ctx.env.PEERBAND_CONNECTOR_CONFIG;
13622
- const config = explicitConfig ? await loadConnectorConfig(resolve(explicitConfig)) : await loadConnectorConfig(connectorConfigPath({ env: ctx.env }), { optional: true });
13623
- const enableWrites = Boolean(options.enableWrites) || config.enableWrites === true;
13642
+ if (options.readOnly && options.enableWrites) throw new UsageError("--read-only and --enable-writes contradict each other.", "Use --read-only to turn messaging off; messaging is on by default.");
13643
+ const config = await loadMachineConnectorConfig(ctx, options.config);
13644
+ const enableWrites = writesEnabled(config, { readOnly: options.readOnly, enableWrites: options.enableWrites });
13624
13645
  const managed = Boolean(options.managed);
13625
13646
  const s = ctx.out.stderr;
13626
13647
  const machine = describeMachine(credentials);
@@ -13629,7 +13650,7 @@ async function connect(options, ctx) {
13629
13650
  writesEnabled: enableWrites,
13630
13651
  allowedAgents: config.allowedAgents,
13631
13652
  allowedWorkspaces: config.allowedWorkspaces,
13632
- receiptPath: config.stateDirectory ? resolve(config.stateDirectory, "receipts.json") : receiptsPath({ env: ctx.env })
13653
+ receiptPath: config.stateDirectory ? resolve2(config.stateDirectory, "receipts.json") : receiptsPath({ env: ctx.env })
13633
13654
  });
13634
13655
  const abort = new AbortController();
13635
13656
  let signalled;
@@ -13664,7 +13685,7 @@ async function connect(options, ctx) {
13664
13685
  await core.initialize();
13665
13686
  if (!managed) {
13666
13687
  ctx.out.warn(
13667
- `${s.bold("peerband")} ${s.dim(`${runtime} runtime, ${enableWrites ? "writes enabled" : "read-only"}. Press Ctrl+C to stop.`)}`
13688
+ `${s.bold("peerband")} ${s.dim(`${runtime} runtime, ${enableWrites ? "messages allowed" : "read-only"}. Press Ctrl+C to stop.`)}`
13668
13689
  );
13669
13690
  }
13670
13691
  await runRemoteClient(core, credentials, {
@@ -13710,7 +13731,7 @@ async function connect(options, ctx) {
13710
13731
  // src/cli/commands/herdr.ts
13711
13732
  import { mkdir as mkdir4, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
13712
13733
  import { statSync } from "node:fs";
13713
- import { join as join4, resolve as resolve2 } from "node:path";
13734
+ import { join as join5, resolve as resolve4 } from "node:path";
13714
13735
 
13715
13736
  // src/cli/control.ts
13716
13737
  import { readFile as readFile7 } from "node:fs/promises";
@@ -13725,7 +13746,7 @@ import { dirname as dirname3 } from "node:path";
13725
13746
  // herdr/paths.mjs
13726
13747
  import { createHash as createHash3 } from "node:crypto";
13727
13748
  import { homedir as homedir3, tmpdir } from "node:os";
13728
- import { join as join3, posix, win32 } from "node:path";
13749
+ import { join as join3, posix, resolve as resolve3, win32 } from "node:path";
13729
13750
  function configHome2(env = process.env, platform = process.platform, home = homedir3()) {
13730
13751
  if (env.PEERBAND_CONFIG_HOME) return env.PEERBAND_CONFIG_HOME;
13731
13752
  if (platform === "win32") return join3(env.APPDATA || join3(home, "AppData", "Roaming"), "peerband");
@@ -13850,7 +13871,7 @@ async function withLaunchLock(statePath, action) {
13850
13871
  }
13851
13872
  if (stale) continue;
13852
13873
  if (Date.now() >= deadline) throw new Error("Another PeerBand Relay tab launch is already in progress");
13853
- await new Promise((resolve3) => setTimeout(resolve3, 100));
13874
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
13854
13875
  }
13855
13876
  }
13856
13877
  try {
@@ -14011,6 +14032,7 @@ function paneLabel(snapshot) {
14011
14032
 
14012
14033
  // src/cli/herdr-js.ts
14013
14034
  var openRelayTab2 = openRelayTab;
14035
+ var canonicalConfig2 = canonicalConfig;
14014
14036
  var controlChannel2 = controlChannel;
14015
14037
  var ownerRecordPath2 = ownerRecordPath;
14016
14038
  var fallbackPaneSnapshot2 = fallbackPaneSnapshot;
@@ -14023,7 +14045,7 @@ async function requestControl(command, env, timeoutMs = 3e3) {
14023
14045
  const record = JSON.parse(await readFile7(ownerRecordPath2(config), "utf8"));
14024
14046
  if (typeof record.token !== "string") throw new Error("Invalid helper record");
14025
14047
  const socket = createConnection2(controlChannel2(config));
14026
- return new Promise((resolve3, reject) => {
14048
+ return new Promise((resolve5, reject) => {
14027
14049
  let text2 = "";
14028
14050
  let settled = false;
14029
14051
  const finish = (error, value) => {
@@ -14032,7 +14054,7 @@ async function requestControl(command, env, timeoutMs = 3e3) {
14032
14054
  clearTimeout(timer);
14033
14055
  socket.destroy();
14034
14056
  if (error) reject(error);
14035
- else resolve3(value ?? {});
14057
+ else resolve5(value ?? {});
14036
14058
  };
14037
14059
  const timer = setTimeout(() => finish(new Error("Helper control timeout")), timeoutMs);
14038
14060
  socket.once("error", (error) => finish(error));
@@ -14074,117 +14096,89 @@ async function stopRelay(env) {
14074
14096
  }
14075
14097
  }
14076
14098
 
14077
- // src/cli/commands/status.ts
14099
+ // src/cli/commands/herdr-check.ts
14100
+ import { readFile as readFile8, stat as stat3 } from "node:fs/promises";
14101
+ import { join as join4 } from "node:path";
14102
+ var PLUGIN_ID = "peerband";
14103
+ var REPAIR_COMMAND = "peerband herdr install";
14078
14104
  async function pluginInstalled(ctx) {
14079
14105
  const result = await ctx.runHerdr(["plugin", "list"], { timeoutMs: 1e4 });
14080
- if (result.notFound) return { found: false, installed: false };
14081
- if (result.code !== 0) return { found: true, installed: false, detail: failureDetail(result) };
14082
- return { found: true, installed: /^\s*-\s+peerband\s/m.test(result.stdout) };
14106
+ if (result.notFound) return { found: false, installed: false, source: null };
14107
+ if (result.code !== 0) return { found: true, installed: false, source: null, detail: failureDetail(result) };
14108
+ const line = /^\s*-\s+peerband\s.*$/m.exec(result.stdout)?.[0];
14109
+ if (line === void 0) return { found: true, installed: false, source: null };
14110
+ const source = /\[([^\]]*)\]\s*$/.exec(line)?.[1]?.trim() || null;
14111
+ return { found: true, installed: true, source };
14083
14112
  }
14084
14113
  function herdrVersion(output) {
14085
14114
  return /\d+\.\d+\.\d+(?:[-+.\w]*)?/.exec(output)?.[0] ?? null;
14086
14115
  }
14087
- function safeMcpUrl(serverUrl, env) {
14116
+ async function readSettings(ctx) {
14117
+ const dir = await ctx.runHerdr(["plugin", "config-dir", PLUGIN_ID], { timeoutMs: 1e4 });
14118
+ const configDir = dir.code === 0 ? dir.stdout.trim() : "";
14119
+ if (!configDir) return null;
14088
14120
  try {
14089
- return mcpUrlFor(serverUrl, env);
14121
+ const value = JSON.parse(await readFile8(join4(configDir, "settings.json"), "utf8"));
14122
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
14090
14123
  } catch {
14091
14124
  return null;
14092
14125
  }
14093
14126
  }
14094
- async function buildStatus(ctx) {
14095
- let credentials;
14127
+ async function isFile(path) {
14096
14128
  try {
14097
- credentials = await loadCredentials(credentialsFile(ctx));
14129
+ return (await stat3(path)).isFile();
14098
14130
  } catch {
14099
- credentials = void 0;
14131
+ return false;
14100
14132
  }
14101
- const snapshot = await relaySnapshot(ctx.env);
14102
- const version = await ctx.runHerdr(["--version"], { timeoutMs: 1e4 });
14103
- const plugin = version.notFound ? { found: false, installed: false } : await pluginInstalled(ctx);
14104
- const herdrFound = !version.notFound;
14105
- return {
14106
- version: ctx.version,
14107
- node: process.versions.node,
14108
- configHome: configHome({ env: ctx.env }),
14109
- loggedIn: Boolean(credentials),
14110
- machine: credentials?.machineName ?? null,
14111
- email: credentials?.accountEmail ?? null,
14112
- server: credentials?.serverUrl ?? null,
14113
- mcpUrl: credentials ? safeMcpUrl(credentials.serverUrl, ctx.env) : null,
14114
- installationId: credentials?.installationId ?? null,
14115
- enrolledAt: credentials?.enrolledAt ?? null,
14116
- relay: {
14117
- running: snapshot?.source === "control" && snapshot.state === "running",
14118
- connection: snapshot?.connectionState ?? null,
14119
- source: snapshot?.source ?? "none"
14120
- },
14121
- herdr: {
14122
- found: herdrFound,
14123
- version: herdrFound && version.code === 0 ? herdrVersion(`${version.stdout} ${version.stderr}`) : null,
14124
- pluginInstalled: herdrFound ? plugin.installed : null
14125
- }
14126
- };
14127
14133
  }
14128
- function colorConnection(s, state) {
14129
- if (!state) return s.dim("not running");
14130
- const label = paneLabel2({ state: "running", connectionState: state, activity: [] });
14131
- if (state === "connected") return s.green(`${symbols.dot} ${label}`);
14132
- if (state === "connecting" || state === "reconnecting") return s.yellow(`${symbols.dot} ${label}`);
14133
- if (state === "disabled") return s.dim(`${symbols.ring} ${label}`);
14134
- return s.red(`${symbols.dot} ${label}`);
14134
+ function sourceRef(source) {
14135
+ const at = source.lastIndexOf("@");
14136
+ return at > 0 ? source.slice(at + 1) || null : null;
14135
14137
  }
14136
- function renderHuman(report, ctx) {
14137
- const s = ctx.out.stdout;
14138
- const rows = [];
14139
- rows.push([
14140
- "Account",
14141
- report.loggedIn ? `${s.green(symbols.ok)} logged in${report.email ? ` as ${report.email}` : ""}` : `${s.red(symbols.fail)} not logged in ${s.dim("(run `peerband login`)")}`
14142
- ]);
14143
- if (report.loggedIn) {
14144
- rows.push(["Machine", report.machine ?? s.dim("(unnamed)")]);
14145
- rows.push(["Server", report.server ?? ""]);
14146
- if (report.mcpUrl) rows.push(["MCP server", report.mcpUrl]);
14147
- rows.push(["Installation", report.installationId ?? ""]);
14148
- if (report.enrolledAt) rows.push(["Enrolled", report.enrolledAt]);
14149
- }
14150
- const relayLine = report.relay.running ? colorConnection(s, report.relay.connection) : report.relay.source === "file" && report.relay.connection && report.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`)")}`);
14151
- rows.push(["Relay", relayLine]);
14152
- rows.push([
14153
- "Herdr",
14154
- !report.herdr.found ? `${s.yellow(symbols.warn)} not found ${s.dim("(set HERDR_BIN_PATH or add herdr to PATH)")}` : `${report.herdr.version ?? "unknown version"}`
14155
- ]);
14156
- if (report.herdr.found) {
14157
- rows.push([
14158
- "Plugin",
14159
- report.herdr.pluginInstalled ? `${s.green(symbols.ok)} installed` : `${s.yellow(symbols.warn)} not installed ${s.dim("(run `peerband herdr install`)")}`
14160
- ]);
14161
- }
14162
- rows.push(["peerband", `${report.version} ${s.dim(`(node ${report.node})`)}`]);
14163
- rows.push(["Config", s.dim(report.configHome)]);
14164
- const width = Math.max(...rows.map(([key]) => key.length));
14165
- for (const [key, value] of rows) ctx.out.print(`${s.bold(key.padEnd(width))} ${value}`);
14138
+ async function checkHerdrPlugin(ctx) {
14139
+ const version = await ctx.runHerdr(["--version"], { timeoutMs: 1e4 });
14140
+ if (version.notFound) return { found: false, herdrVersion: null, installed: false, source: null, problems: [] };
14141
+ const herdrV = version.code === 0 ? herdrVersion(`${version.stdout} ${version.stderr}`) : null;
14142
+ const listed = await pluginInstalled(ctx);
14143
+ if (listed.detail) return { found: true, herdrVersion: herdrV, installed: false, source: null, detail: listed.detail, problems: [] };
14144
+ if (!listed.installed) {
14145
+ return { found: true, herdrVersion: herdrV, installed: false, source: null, problems: [{ code: "not-installed", message: "The PeerBand plugin is not installed in Herdr." }] };
14146
+ }
14147
+ const problems = [];
14148
+ const source = listed.source;
14149
+ const override = Boolean(ctx.env.PEERBAND_HERDR_SOURCE);
14150
+ if (source?.startsWith("local:")) {
14151
+ if (!override) problems.push({ code: "local-source", message: `The plugin is linked to a local checkout (${source.slice("local:".length)}), not the v${ctx.version} release.` });
14152
+ } else if (source !== null && !override) {
14153
+ const expected = ctx.env.PEERBAND_HERDR_REF || `v${ctx.version}`;
14154
+ const ref = sourceRef(source);
14155
+ if (ref !== expected) {
14156
+ problems.push({ code: "version-mismatch", message: `The plugin is ${ref ? `at ${ref}` : "not pinned to a version"}, but this CLI is ${expected}.` });
14157
+ }
14158
+ } else if (source !== null && ctx.env.PEERBAND_HERDR_REF) {
14159
+ const ref = sourceRef(source);
14160
+ if (ref !== ctx.env.PEERBAND_HERDR_REF) problems.push({ code: "version-mismatch", message: `The plugin is at ${ref ?? "no ref"}, but PEERBAND_HERDR_REF is ${ctx.env.PEERBAND_HERDR_REF}.` });
14161
+ }
14162
+ const settings = await readSettings(ctx);
14163
+ const current = configHome({ env: ctx.env });
14164
+ const fallback = configHome({ env: { ...ctx.env, PEERBAND_CONFIG_HOME: void 0 } });
14165
+ const recorded = settings && typeof settings.configHome === "string" && settings.configHome ? settings.configHome : fallback;
14166
+ if (settings && canonicalConfig2(recorded) !== canonicalConfig2(current)) {
14167
+ const shown = typeof settings.configHome === "string" && settings.configHome ? settings.configHome : `${fallback} (default)`;
14168
+ problems.push({ code: "config-home", message: `The plugin uses the config directory ${shown}, but this CLI uses ${current}.` });
14169
+ }
14170
+ const nodePath = settings?.nodePath;
14171
+ if (typeof nodePath !== "string" || !nodePath) {
14172
+ problems.push({ code: "node-path", message: "The plugin settings do not record a Node.js path." });
14173
+ } else if (!await isFile(nodePath)) {
14174
+ problems.push({ code: "node-path", message: `The Node.js recorded in the plugin settings no longer exists (${nodePath}).` });
14175
+ }
14176
+ return { found: true, herdrVersion: herdrV, installed: true, source, problems };
14166
14177
  }
14167
- var spec2 = {
14168
- name: "status",
14169
- summary: "Show login, relay and Herdr status",
14170
- usage: "peerband status [--json]",
14171
- description: "Shows whether this machine is logged in, whether the PeerBand Relay is running and connected, and whether Herdr and the PeerBand plugin are installed. Exits with code 3 when not logged in.",
14172
- options: [{ name: "json", type: "boolean", description: "Print a stable machine-readable JSON object instead of text." }],
14173
- examples: [
14174
- ["peerband status", "Human-readable summary"],
14175
- ["peerband status --json", "For scripts; check .loggedIn and .relay.connection"]
14176
- ],
14177
- async run(parsed, ctx) {
14178
- const report = await buildStatus(ctx);
14179
- if (flag(parsed, "json")) ctx.out.print(JSON.stringify(report, null, 2));
14180
- else renderHuman(report, ctx);
14181
- return report.loggedIn ? 0 : EXIT_NOT_LOGGED_IN;
14182
- }
14183
- };
14184
14178
 
14185
14179
  // src/cli/commands/herdr.ts
14186
14180
  var DEFAULT_SOURCE = "kshvidler/peerband-cli";
14187
- var PLUGIN_ID = "peerband";
14181
+ var PLUGIN_ID2 = "peerband";
14188
14182
  function isDirectory(path) {
14189
14183
  try {
14190
14184
  return statSync(path).isDirectory();
@@ -14202,9 +14196,9 @@ function must(result, what, hint) {
14202
14196
  return result;
14203
14197
  }
14204
14198
  async function removePlugin(ctx) {
14205
- const uninstall = await herdr(ctx, ["plugin", "uninstall", PLUGIN_ID]);
14199
+ const uninstall = await herdr(ctx, ["plugin", "uninstall", PLUGIN_ID2]);
14206
14200
  if (uninstall.code === 0) return { removed: true, detail: "" };
14207
- const unlink3 = await herdr(ctx, ["plugin", "unlink", PLUGIN_ID]);
14201
+ const unlink3 = await herdr(ctx, ["plugin", "unlink", PLUGIN_ID2]);
14208
14202
  if (unlink3.code === 0) return { removed: true, detail: "" };
14209
14203
  return { removed: false, detail: failureDetail(uninstall) };
14210
14204
  }
@@ -14238,11 +14232,11 @@ var installSpec = {
14238
14232
  if (before.detail) throw new CliError(`Herdr could not list plugins: ${before.detail}`, "Check that your Herdr is 0.9.3 or newer (`herdr --version`).");
14239
14233
  if (before.installed) {
14240
14234
  const removed = await removePlugin(ctx);
14241
- if (!removed.removed) throw new CliError(`Could not replace the existing PeerBand plugin: ${removed.detail}`, `Run \`herdr plugin uninstall ${PLUGIN_ID}\` yourself, then retry.`);
14235
+ if (!removed.removed) throw new CliError(`Could not replace the existing PeerBand plugin: ${removed.detail}`, `Run \`herdr plugin uninstall ${PLUGIN_ID2}\` yourself, then retry.`);
14242
14236
  ctx.out.print(s.dim(`Replacing the existing PeerBand plugin.`));
14243
14237
  }
14244
14238
  if (local) {
14245
- const dir = resolve2(source);
14239
+ const dir = resolve4(source);
14246
14240
  must(await herdr(ctx, ["plugin", "link", dir]), "herdr plugin link", "Check that the directory is a peerband-cli checkout containing herdr-plugin.toml.");
14247
14241
  ctx.out.print(`${s.green(symbols.ok)} Linked the PeerBand plugin from ${dir}`);
14248
14242
  } else {
@@ -14253,11 +14247,11 @@ var installSpec = {
14253
14247
  );
14254
14248
  ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand plugin (${source} @ ${ref})`);
14255
14249
  }
14256
- const dirResult = must(await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID]), "herdr plugin config-dir", "The plugin may not have registered; run `herdr plugin list`.");
14250
+ const dirResult = must(await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID2]), "herdr plugin config-dir", "The plugin may not have registered; run `herdr plugin list`.");
14257
14251
  const configDir = dirResult.stdout.trim();
14258
14252
  if (!configDir) throw new CliError("Herdr did not report a plugin config directory.", "Run `herdr plugin config-dir peerband` to investigate.");
14259
14253
  await mkdir4(configDir, { recursive: true });
14260
- await writeFile4(join4(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
14254
+ await writeFile4(join5(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
14261
14255
  `, { mode: 384 });
14262
14256
  ctx.out.print(`${s.green(symbols.ok)} Saved plugin settings ${s.dim(`(node ${process.execPath})`)}`);
14263
14257
  const after = await pluginInstalled(ctx);
@@ -14283,11 +14277,11 @@ var uninstallSpec = {
14283
14277
  return 0;
14284
14278
  }
14285
14279
  if (await stopRelay(ctx.env)) ctx.out.print(`${s.green(symbols.ok)} Stopped the running PeerBand Relay.`);
14286
- const dirResult = await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID]);
14280
+ const dirResult = await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID2]);
14287
14281
  const configDir = dirResult.code === 0 ? dirResult.stdout.trim() : "";
14288
14282
  const removed = await removePlugin(ctx);
14289
14283
  if (!removed.removed) throw new CliError(`Could not remove the PeerBand plugin: ${removed.detail}`, "Run `herdr plugin list` to see its state.");
14290
- if (configDir) await rm3(join4(configDir, "settings.json"), { force: true }).catch(() => void 0);
14284
+ if (configDir) await rm3(join5(configDir, "settings.json"), { force: true }).catch(() => void 0);
14291
14285
  ctx.out.print(`${s.green(symbols.ok)} Removed the PeerBand plugin from Herdr.`);
14292
14286
  return 0;
14293
14287
  }
@@ -14324,16 +14318,16 @@ function openerCommand(platform, url) {
14324
14318
  }
14325
14319
  function openBrowser(url, platform = process.platform) {
14326
14320
  const { command, args } = openerCommand(platform, url);
14327
- return new Promise((resolve3) => {
14321
+ return new Promise((resolve5) => {
14328
14322
  try {
14329
14323
  const child = spawn(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
14330
- child.once("error", () => resolve3(false));
14324
+ child.once("error", () => resolve5(false));
14331
14325
  child.once("spawn", () => {
14332
14326
  child.unref();
14333
- resolve3(true);
14327
+ resolve5(true);
14334
14328
  });
14335
14329
  } catch {
14336
- resolve3(false);
14330
+ resolve5(false);
14337
14331
  }
14338
14332
  });
14339
14333
  }
@@ -14346,7 +14340,7 @@ var PromptAborted = class extends Error {
14346
14340
  }
14347
14341
  };
14348
14342
  function askYesNo(stdin, stderr, prompt, defaultYes = true) {
14349
- return new Promise((resolve3, reject) => {
14343
+ return new Promise((resolve5, reject) => {
14350
14344
  let value = "";
14351
14345
  const cleanup = () => {
14352
14346
  stdin.off("data", onData);
@@ -14363,7 +14357,7 @@ function askYesNo(stdin, stderr, prompt, defaultYes = true) {
14363
14357
  if (end === -1) return;
14364
14358
  cleanup();
14365
14359
  const answer = value.trim().toLowerCase();
14366
- resolve3(answer === "" ? defaultYes : answer === "y" || answer === "yes");
14360
+ resolve5(answer === "" ? defaultYes : answer === "y" || answer === "yes");
14367
14361
  };
14368
14362
  stderr.write(prompt);
14369
14363
  stdin.resume();
@@ -14376,7 +14370,7 @@ var HERDR_PLUGIN_MODES = ["ask", "install", "skip"];
14376
14370
  async function herdrSetup(ctx, mode) {
14377
14371
  const s = ctx.out.stdout;
14378
14372
  const manual = `${s.dim("Next:")} peerband herdr install ${s.dim("then")} peerband relay`;
14379
- const state = await pluginInstalled(ctx);
14373
+ const state = await checkHerdrPlugin(ctx);
14380
14374
  if (!state.found) {
14381
14375
  ctx.out.print("");
14382
14376
  ctx.out.print(`${s.yellow(symbols.warn)} Herdr was not found. The PeerBand Relay tab needs Herdr 0.9.3 or newer.`);
@@ -14384,21 +14378,27 @@ async function herdrSetup(ctx, mode) {
14384
14378
  ctx.out.print(` 2. ${s.bold("peerband herdr install")} ${s.dim("then")} ${s.bold("peerband relay")}`);
14385
14379
  return;
14386
14380
  }
14387
- if (state.installed) {
14381
+ if (state.installed && state.problems.length === 0) {
14388
14382
  ctx.out.print(`${s.dim("Next:")} peerband relay ${s.dim("(opens the PeerBand Relay tab in Herdr)")}`);
14389
14383
  return;
14390
14384
  }
14385
+ const repair = state.installed;
14386
+ if (repair) {
14387
+ ctx.out.print("");
14388
+ ctx.out.print(`${s.yellow(symbols.warn)} The PeerBand plugin in Herdr needs repair: ${state.problems[0].message}`);
14389
+ if (state.problems.length > 1) ctx.out.print(s.dim(` (${state.problems.length - 1} more problem${state.problems.length > 2 ? "s" : ""}; see \`peerband status\`)`));
14390
+ }
14391
14391
  let install = mode === "install";
14392
14392
  if (mode === "ask" && ctx.stdin.isTTY && ctx.stderr.isTTY) {
14393
14393
  try {
14394
- install = await askYesNo(ctx.stdin, ctx.stderr, "Add the PeerBand plugin to Herdr now? [Y/n] ");
14394
+ install = await askYesNo(ctx.stdin, ctx.stderr, repair ? "Repair the PeerBand plugin now? [Y/n] " : "Add the PeerBand plugin to Herdr now? [Y/n] ");
14395
14395
  } catch (error) {
14396
14396
  if (!(error instanceof PromptAborted)) throw error;
14397
14397
  ctx.out.print(manual);
14398
14398
  return;
14399
14399
  }
14400
14400
  if (!install) {
14401
- ctx.out.print(s.dim("Skipped. Add it later with `peerband herdr install`, then open the relay with `peerband relay`."));
14401
+ ctx.out.print(s.dim(`Skipped. ${repair ? "Repair" : "Add"} it later with \`${REPAIR_COMMAND}\`, then open the relay with \`peerband relay\`.`));
14402
14402
  return;
14403
14403
  }
14404
14404
  }
@@ -14410,13 +14410,40 @@ async function herdrSetup(ctx, mode) {
14410
14410
  await installSpec.run({ values: {}, positionals: [] }, ctx);
14411
14411
  } catch (error) {
14412
14412
  const message = error.message;
14413
- ctx.out.warn(`${s.yellow(symbols.warn)} Could not add the PeerBand plugin to Herdr: ${message}`);
14413
+ ctx.out.warn(`${s.yellow(symbols.warn)} Could not ${repair ? "repair" : "add"} the PeerBand plugin${repair ? "" : " to Herdr"}: ${message}`);
14414
14414
  if (error instanceof CliError && error.hint) ctx.out.warn(` ${error.hint}`);
14415
- ctx.out.print(s.dim("You are logged in. Add the plugin later with `peerband herdr install`, then run `peerband relay`."));
14415
+ ctx.out.print(s.dim(`You are logged in. ${repair ? "Repair" : "Add"} the plugin later with \`peerband herdr install\`, then run \`peerband relay\`.`));
14416
+ }
14417
+ }
14418
+ async function ensureHerdrPlugin(ctx) {
14419
+ const check = await checkHerdrPlugin(ctx);
14420
+ if (!check.found || check.problems.length === 0) return;
14421
+ const s = ctx.out.stderr;
14422
+ const fix = "Run `peerband herdr install`, then `peerband relay`.";
14423
+ const reasons = check.problems.map((problem) => problem.message);
14424
+ if (!(ctx.stdin.isTTY && ctx.stderr.isTTY)) throw new CliError(`The PeerBand Herdr plugin needs repair. ${reasons.join(" ")}`, fix);
14425
+ ctx.out.warn(`${s.yellow(symbols.warn)} The PeerBand plugin in Herdr needs repair: ${reasons[0]}`);
14426
+ if (reasons.length > 1) ctx.out.warn(s.dim(` Also: ${reasons.slice(1).join(" ")}`));
14427
+ let repair;
14428
+ try {
14429
+ repair = await askYesNo(ctx.stdin, ctx.stderr, "Repair the PeerBand plugin now? [Y/n] ");
14430
+ } catch (error) {
14431
+ if (!(error instanceof PromptAborted)) throw error;
14432
+ repair = false;
14416
14433
  }
14434
+ if (!repair) throw new CliError(`The PeerBand Herdr plugin needs repair. ${reasons[0]}`, fix);
14435
+ await installSpec.run({ values: {}, positionals: [] }, ctx);
14417
14436
  }
14418
14437
 
14419
14438
  // src/cli/commands/login.ts
14439
+ function reusableCredential(previous, serverUrl) {
14440
+ if (!previous) return void 0;
14441
+ try {
14442
+ return new URL(previous.serverUrl).origin === new URL(serverUrl).origin ? previous.credential : void 0;
14443
+ } catch {
14444
+ return void 0;
14445
+ }
14446
+ }
14420
14447
  async function persist(ctx, redeemed) {
14421
14448
  const credentials = { ...redeemed, enrolledAt: (/* @__PURE__ */ new Date()).toISOString() };
14422
14449
  await saveCredentials(credentials, credentialsFile(ctx));
@@ -14425,7 +14452,7 @@ async function persist(ctx, redeemed) {
14425
14452
  async function loginWithGrant(ctx, options) {
14426
14453
  let redeemed;
14427
14454
  try {
14428
- redeemed = await redeemEnrollment(options.serverUrl, options.grant, options.name, ctx.fetch);
14455
+ redeemed = await redeemEnrollment(options.serverUrl, options.grant, options.name, ctx.fetch, options.previousCredential);
14429
14456
  } catch (error) {
14430
14457
  const message = error.message;
14431
14458
  const rejected = /could not be redeemed/i.test(message);
@@ -14497,7 +14524,7 @@ async function loginWithBrowser(ctx, options) {
14497
14524
  }
14498
14525
  let redeemed;
14499
14526
  try {
14500
- redeemed = await pollDeviceToken(options.serverUrl, code, shared);
14527
+ redeemed = await pollDeviceToken(options.serverUrl, code, { ...shared, ...options.previousCredential ? { previousCredential: options.previousCredential } : {} });
14501
14528
  } catch (error) {
14502
14529
  throw mapFailure(error, options.serverUrl);
14503
14530
  } finally {
@@ -14531,11 +14558,11 @@ function mapFailure(error, serverUrl) {
14531
14558
  return new CliError(error.message, "Run `peerband login` again, or use `peerband login --grant GRANT`.");
14532
14559
  }
14533
14560
  }
14534
- var spec3 = {
14561
+ var spec2 = {
14535
14562
  name: "login",
14536
14563
  summary: "Connect this machine to your PeerBand account",
14537
14564
  usage: "peerband login [--name NAME] [--no-browser] [--server URL] [--herdr-plugin ask|install|skip]\n peerband login --grant GRANT [--name NAME] [--server URL]",
14538
- description: "Signs this machine in through your browser. login prints a link and a short code, opens the page (unless you are on SSH, a headless machine or pass --no-browser), and waits while you confirm the code in your PeerBand account. The credential is stored in your PeerBand config directory (readable only by you). Running login again replaces the existing enrollment.\n\nOn a headless machine or in CI, use a one-time grant instead: create it in the PeerBand dashboard and pass --grant GRANT (or set PEERBAND_GRANT).\n\nWhen login succeeds it checks for Herdr. If the PeerBand plugin is missing it offers to add it (--herdr-plugin ask, the default; it only asks on a terminal), adds it without asking (install), or just prints the command (skip).",
14565
+ description: "Signs this machine in through your browser. login prints a link and a short code, opens the page (unless you are on SSH, a headless machine or pass --no-browser), and waits while you confirm the code in your PeerBand account. The credential is stored in your PeerBand config directory (readable only by you). Running login again replaces the stored credential; when you sign in to the same account and server, this machine keeps its record in your account (installation ID and shares).\n\nOn a headless machine or in CI, use a one-time grant instead: create it in the PeerBand dashboard and pass --grant GRANT (or set PEERBAND_GRANT).\n\nWhen login succeeds it checks for Herdr. If the PeerBand plugin is missing, or installed but wrong (another version, a local checkout, a stale config directory), it offers to add or repair it (--herdr-plugin ask, the default; it only asks on a terminal), adds it without asking (install), or just prints the command (skip).",
14539
14566
  options: [
14540
14567
  { name: "no-browser", type: "boolean", description: "Do not open a browser; print the link and code only (SSH, containers)." },
14541
14568
  { name: "name", type: "string", valueName: "NAME", description: "Name shown for this machine in the dashboard. Default: this computer's hostname." },
@@ -14561,18 +14588,23 @@ var spec3 = {
14561
14588
  delete ctx.env.PEERBAND_GRANT;
14562
14589
  if (parsed.values.grant !== void 0 && !grant) throw new UsageError("The grant is empty.", "Pass the grant from your PeerBand dashboard: --grant GRANT.");
14563
14590
  const previous = await loadCredentials(credentialsFile(ctx)).catch(() => void 0);
14564
- const credentials = grant ? await loginWithGrant(ctx, { serverUrl, grant, name }) : await loginWithBrowser(ctx, { serverUrl, name, noBrowser: parsed.values["no-browser"] === true });
14591
+ const previousCredential = reusableCredential(previous, serverUrl);
14592
+ const credentials = grant ? await loginWithGrant(ctx, { serverUrl, grant, name, ...previousCredential ? { previousCredential } : {} }) : await loginWithBrowser(ctx, { serverUrl, name, noBrowser: parsed.values["no-browser"] === true, ...previousCredential ? { previousCredential } : {} });
14565
14593
  const s = ctx.out.stdout;
14566
- if (previous) ctx.out.print(s.dim(`Replaced the previous login (${previous.machineName ?? previous.installationId} on ${previous.serverUrl}).`));
14594
+ if (previous && previous.installationId === credentials.installationId && previous.serverUrl === credentials.serverUrl)
14595
+ ctx.out.print(s.dim("Kept this machine in your account with a new credential; its shares stay in place."));
14596
+ else if (previous) ctx.out.print(s.dim(`Replaced the previous login (${previous.machineName ?? previous.installationId} on ${previous.serverUrl}).`));
14567
14597
  const who = credentials.accountEmail ? ` (${credentials.accountEmail})` : "";
14568
14598
  ctx.out.print(`${s.green(symbols.ok)} Logged in as ${s.bold(credentials.machineName ?? name)}${who}`);
14569
14599
  await herdrSetup(ctx, herdrMode);
14600
+ ctx.out.print("");
14601
+ printSkillTip(ctx);
14570
14602
  return 0;
14571
14603
  }
14572
14604
  };
14573
14605
 
14574
14606
  // src/cli/commands/logout.ts
14575
- var spec4 = {
14607
+ var spec3 = {
14576
14608
  name: "logout",
14577
14609
  summary: "Forget this machine's PeerBand credential",
14578
14610
  usage: "peerband logout",
@@ -14597,15 +14629,16 @@ var spec4 = {
14597
14629
  };
14598
14630
 
14599
14631
  // src/cli/commands/relay.ts
14600
- var spec5 = {
14632
+ var spec4 = {
14601
14633
  name: "relay",
14602
14634
  summary: "Open or focus the PeerBand Relay tab in Herdr",
14603
14635
  usage: "peerband relay",
14604
- description: "Opens the PeerBand Relay in a persistent Herdr tab, or focuses it if it is already open. The tab shows your account, connection state and metadata-only activity; closing it disconnects. Requires Herdr and the PeerBand plugin (`peerband herdr install`).",
14636
+ description: "Opens the PeerBand Relay in a persistent Herdr tab, or focuses it if it is already open. The tab shows your account, connection state and metadata-only activity; closing it disconnects. Requires Herdr and the PeerBand plugin (`peerband herdr install`). If the plugin is wrong (another version, a local checkout, or a stale config directory), relay offers to repair it first.",
14605
14637
  options: [],
14606
14638
  examples: [["peerband relay", "Open the relay tab"]],
14607
14639
  async run(_parsed, ctx) {
14608
14640
  const credentials = await requireCredentials(ctx);
14641
+ await ensureHerdrPlugin(ctx);
14609
14642
  try {
14610
14643
  await (ctx.openRelayTab ?? openRelayTab2)();
14611
14644
  } catch (error) {
@@ -14619,12 +14652,232 @@ var spec5 = {
14619
14652
  const s = ctx.out.stdout;
14620
14653
  ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is open in Herdr.`);
14621
14654
  printMcpHint(ctx, credentials.serverUrl);
14655
+ printSkillTip(ctx);
14622
14656
  return 0;
14623
14657
  }
14624
14658
  };
14625
14659
 
14660
+ // src/cli/commands/share.ts
14661
+ var roleLabel = (role) => role === "message" ? "read + message" : "read only";
14662
+ var MAX_EXPIRY_DAYS = 30;
14663
+ async function call(ctx, credentials, method, path, body) {
14664
+ const url = new URL(path, enrollmentBase(credentials.serverUrl));
14665
+ let response;
14666
+ try {
14667
+ response = await ctx.fetch(url, {
14668
+ method,
14669
+ headers: { authorization: `Bearer ${credentials.credential}`, ...body ? { "content-type": "application/json" } : {} },
14670
+ ...body ? { body: JSON.stringify(body) } : {},
14671
+ signal: AbortSignal.timeout(15e3)
14672
+ });
14673
+ } catch (error) {
14674
+ throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
14675
+ }
14676
+ if (response.status === 204) return null;
14677
+ const parsed = await response.json().catch(() => ({}));
14678
+ if (response.ok) return parsed;
14679
+ const detail = typeof parsed.detail === "string" ? parsed.detail : `HTTP ${response.status}`;
14680
+ if (response.status === 401) throw new CliError("PeerBand rejected this machine's credential (it may have been revoked).", "Run `peerband login` again to sign in.");
14681
+ if (response.status === 404 && path.endsWith("/sharing") && method === "GET") throw new CliError("This PeerBand server doesn't support sharing yet.");
14682
+ throw new CliError(sanitize(detail));
14683
+ }
14684
+ function expiryDays(raw) {
14685
+ if (raw === void 0) return void 0;
14686
+ const days = Number(raw);
14687
+ if (!Number.isInteger(days) || days < 1 || days > MAX_EXPIRY_DAYS) throw new UsageError(`Invalid --expires value "${raw}".`, `Use a whole number of days from 1 to ${MAX_EXPIRY_DAYS}.`);
14688
+ return days;
14689
+ }
14690
+ async function create(ctx, credentials, role, days, json) {
14691
+ const link = await call(ctx, credentials, "POST", "/api/installation/invites", { role, ...days ? { expires_in_days: days } : {} });
14692
+ if (json) {
14693
+ ctx.out.print(JSON.stringify(link, null, 2));
14694
+ return 0;
14695
+ }
14696
+ const s = ctx.out.stdout;
14697
+ ctx.out.print(`${s.green(symbols.ok)} Invite link for ${s.bold(credentials.machineName ?? "this machine")} (${roleLabel(link.role)}):`);
14698
+ ctx.out.print("");
14699
+ ctx.out.print(` ${s.cyan(sanitize(link.url))}`);
14700
+ ctx.out.print("");
14701
+ ctx.out.print(`Send it to one person. It works once and expires ${sanitize(link.expires_at)}.`);
14702
+ ctx.out.print(s.dim("They sign in to PeerBand (or create an account) and accept. See who has access with `peerband share list`."));
14703
+ return 0;
14704
+ }
14705
+ async function list(ctx, credentials, json) {
14706
+ const sharing = await call(ctx, credentials, "GET", "/api/installation/sharing");
14707
+ if (json) {
14708
+ ctx.out.print(JSON.stringify(sharing, null, 2));
14709
+ return 0;
14710
+ }
14711
+ const s = ctx.out.stdout;
14712
+ ctx.out.print(s.bold("People with access"));
14713
+ if (!sharing.guests.length) ctx.out.print(s.dim(" Nobody else has access yet. Create a link with `peerband share`."));
14714
+ for (const guest of sharing.guests) {
14715
+ const used = guest.last_used_at ? `last used ${sanitize(guest.last_used_at)}` : "not used yet";
14716
+ ctx.out.print(` ${sanitize(guest.email ?? "PeerBand user")} ${roleLabel(guest.role)} ${s.dim(`${used} \xB7 ${guest.id}`)}`);
14717
+ }
14718
+ if (sharing.invites.length) {
14719
+ ctx.out.print("");
14720
+ ctx.out.print(s.bold("Unused links"));
14721
+ for (const invite of sharing.invites) ctx.out.print(` ${roleLabel(invite.role)} ${s.dim(`expires ${sanitize(invite.expires_at)} \xB7 ${invite.id}`)}`);
14722
+ }
14723
+ ctx.out.print("");
14724
+ ctx.out.print(s.dim("Remove access or cancel a link with `peerband share revoke ID`. Change roles in the dashboard."));
14725
+ return 0;
14726
+ }
14727
+ async function revoke(ctx, credentials, id) {
14728
+ if (!id) throw new UsageError("Missing the ID to revoke.", "Run `peerband share list` to see IDs (acc_\u2026 for people, inv_\u2026 for links).");
14729
+ if (!/^(acc|inv)_[\w-]{1,64}$/.test(id)) throw new UsageError(`"${sanitize(id)}" is not a share ID.`, "IDs start with acc_ (a person) or inv_ (a link); see `peerband share list`.");
14730
+ await call(ctx, credentials, "DELETE", `/api/installation/sharing/${encodeURIComponent(id)}`);
14731
+ ctx.out.print(`${ctx.out.stdout.green(symbols.ok)} ${id.startsWith("acc_") ? "Access removed." : "Link cancelled."}`);
14732
+ return 0;
14733
+ }
14734
+ var spec5 = {
14735
+ name: "share",
14736
+ summary: "Share this machine with another PeerBand user",
14737
+ usage: "peerband share [--message] [--expires DAYS] [--json]\n peerband share list [--json]\n peerband share revoke ID",
14738
+ description: "Creates an invitation link for this machine. The person who opens it signs in to PeerBand (or creates an account) and accepts; this machine then appears in their dashboard and in list_machines in their MCP client. Guests can list and read this machine's agents. With --message they can also send messages, if their MCP client has the agents:message consent and this machine allows messages (a machine started with --read-only never does).\n\nEach link works for one person and expires after 7 days unless you pass --expires. You see each guest's email and a log of what they read or send (metadata only) in the dashboard.\n\n`share list` shows who has access and the unused links; `share revoke ID` removes a person's access (acc_\u2026) or cancels a link (inv_\u2026).",
14739
+ options: [
14740
+ { name: "message", type: "boolean", description: "Also let the guest send messages to agents. Default: read only." },
14741
+ { name: "expires", type: "string", valueName: "DAYS", description: `Days until the link expires, 1 to ${MAX_EXPIRY_DAYS}. Default: 7.` },
14742
+ { name: "json", type: "boolean", description: "Print machine-readable JSON." }
14743
+ ],
14744
+ positionals: { name: "list | revoke ID", max: 2 },
14745
+ examples: [
14746
+ ["peerband share", "Create a read-only invite link for this machine"],
14747
+ ["peerband share --message --expires 1", "A link that also allows messages, valid for one day"],
14748
+ ["peerband share list", "People with access and unused links"],
14749
+ ["peerband share revoke acc_AbC123", "Remove someone's access"]
14750
+ ],
14751
+ notes: ["The link is shown once. Anyone who has it can accept it until it is used, so send it only to the person you mean."],
14752
+ async run(parsed, ctx) {
14753
+ const [action, id] = parsed.positionals;
14754
+ const json = flag(parsed, "json");
14755
+ if (action !== void 0 && action !== "list" && action !== "revoke")
14756
+ throw new UsageError(`Unknown share action "${sanitize(action)}".`, "Use `peerband share`, `peerband share list` or `peerband share revoke ID`.");
14757
+ if (action !== "revoke" && id !== void 0) throw new UsageError(`Unexpected argument "${sanitize(id)}".`, "Run `peerband share --help` for usage.");
14758
+ if (action && (parsed.values.message !== void 0 || parsed.values.expires !== void 0))
14759
+ throw new UsageError("--message and --expires only apply when creating a link.", "Run `peerband share --message` to create one.");
14760
+ const days = expiryDays(str(parsed, "expires"));
14761
+ const credentials = await requireCredentials(ctx);
14762
+ if (action === "list") return list(ctx, credentials, json);
14763
+ if (action === "revoke") return revoke(ctx, credentials, id);
14764
+ return create(ctx, credentials, flag(parsed, "message") ? "message" : "read", days, json);
14765
+ }
14766
+ };
14767
+
14768
+ // src/cli/commands/status.ts
14769
+ function safeMcpUrl(serverUrl, env) {
14770
+ try {
14771
+ return mcpUrlFor(serverUrl, env);
14772
+ } catch {
14773
+ return null;
14774
+ }
14775
+ }
14776
+ async function buildStatus(ctx) {
14777
+ let credentials;
14778
+ try {
14779
+ credentials = await loadCredentials(credentialsFile(ctx));
14780
+ } catch {
14781
+ credentials = void 0;
14782
+ }
14783
+ const snapshot = await relaySnapshot(ctx.env);
14784
+ const plugin = await checkHerdrPlugin(ctx);
14785
+ const messages = await loadMachineConnectorConfig(ctx).then(
14786
+ (config) => writesEnabled(config) ? "allowed" : "read-only",
14787
+ () => null
14788
+ );
14789
+ return {
14790
+ version: ctx.version,
14791
+ node: process.versions.node,
14792
+ configHome: configHome({ env: ctx.env }),
14793
+ loggedIn: Boolean(credentials),
14794
+ machine: credentials?.machineName ?? null,
14795
+ email: credentials?.accountEmail ?? null,
14796
+ server: credentials?.serverUrl ?? null,
14797
+ mcpUrl: credentials ? safeMcpUrl(credentials.serverUrl, ctx.env) : null,
14798
+ installationId: credentials?.installationId ?? null,
14799
+ enrolledAt: credentials?.enrolledAt ?? null,
14800
+ relay: {
14801
+ running: snapshot?.source === "control" && snapshot.state === "running",
14802
+ connection: snapshot?.connectionState ?? null,
14803
+ source: snapshot?.source ?? "none"
14804
+ },
14805
+ messages,
14806
+ herdr: {
14807
+ found: plugin.found,
14808
+ version: plugin.herdrVersion,
14809
+ pluginInstalled: plugin.found ? plugin.installed : null,
14810
+ pluginSource: plugin.source,
14811
+ pluginProblems: plugin.problems
14812
+ }
14813
+ };
14814
+ }
14815
+ function colorConnection(s, state) {
14816
+ if (!state) return s.dim("not running");
14817
+ const label = paneLabel2({ state: "running", connectionState: state, activity: [] });
14818
+ if (state === "connected") return s.green(`${symbols.dot} ${label}`);
14819
+ if (state === "connecting" || state === "reconnecting") return s.yellow(`${symbols.dot} ${label}`);
14820
+ if (state === "disabled") return s.dim(`${symbols.ring} ${label}`);
14821
+ return s.red(`${symbols.dot} ${label}`);
14822
+ }
14823
+ function renderHuman(report, ctx) {
14824
+ const s = ctx.out.stdout;
14825
+ const rows = [];
14826
+ rows.push([
14827
+ "Account",
14828
+ report.loggedIn ? `${s.green(symbols.ok)} logged in${report.email ? ` as ${report.email}` : ""}` : `${s.red(symbols.fail)} not logged in ${s.dim("(run `peerband login`)")}`
14829
+ ]);
14830
+ if (report.loggedIn) {
14831
+ rows.push(["Machine", report.machine ?? s.dim("(unnamed)")]);
14832
+ rows.push(["Server", report.server ?? ""]);
14833
+ if (report.mcpUrl) rows.push(["MCP server", report.mcpUrl]);
14834
+ rows.push(["Installation", report.installationId ?? ""]);
14835
+ if (report.enrolledAt) rows.push(["Enrolled", report.enrolledAt]);
14836
+ }
14837
+ const relayLine = report.relay.running ? colorConnection(s, report.relay.connection) : report.relay.source === "file" && report.relay.connection && report.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`)")}`);
14838
+ rows.push(["Relay", relayLine]);
14839
+ if (report.messages) {
14840
+ rows.push([
14841
+ "Messages",
14842
+ report.messages === "allowed" ? `allowed ${s.dim('(needs the agents:message consent; turn off with --read-only or "enableWrites": false in connector.json)')}` : "read-only"
14843
+ ]);
14844
+ }
14845
+ rows.push([
14846
+ "Herdr",
14847
+ !report.herdr.found ? `${s.yellow(symbols.warn)} not found ${s.dim("(set HERDR_BIN_PATH or add herdr to PATH)")}` : `${report.herdr.version ?? "unknown version"}`
14848
+ ]);
14849
+ if (report.herdr.found) {
14850
+ const first = report.herdr.pluginProblems[0];
14851
+ rows.push([
14852
+ "Plugin",
14853
+ !report.herdr.pluginInstalled ? `${s.yellow(symbols.warn)} not installed ${s.dim(`(run \`${REPAIR_COMMAND}\`)`)}` : first ? `${s.yellow(symbols.warn)} ${first.message} ${s.dim(`(run \`${REPAIR_COMMAND}\`)`)}` : `${s.green(symbols.ok)} ${report.herdr.pluginSource ?? "installed"}`
14854
+ ]);
14855
+ }
14856
+ rows.push(["peerband", `${report.version} ${s.dim(`(node ${report.node})`)}`]);
14857
+ rows.push(["Config", s.dim(report.configHome)]);
14858
+ const width = Math.max(...rows.map(([key]) => key.length));
14859
+ for (const [key, value] of rows) ctx.out.print(`${s.bold(key.padEnd(width))} ${value}`);
14860
+ }
14861
+ var spec6 = {
14862
+ name: "status",
14863
+ summary: "Show login, relay and Herdr status",
14864
+ usage: "peerband status [--json]",
14865
+ description: "Shows whether this machine is logged in, whether the PeerBand Relay is running and connected, and whether Herdr and the PeerBand plugin are installed. Exits with code 3 when not logged in.",
14866
+ options: [{ name: "json", type: "boolean", description: "Print a stable machine-readable JSON object instead of text." }],
14867
+ examples: [
14868
+ ["peerband status", "Human-readable summary"],
14869
+ ["peerband status --json", "For scripts; check .loggedIn and .relay.connection"]
14870
+ ],
14871
+ async run(parsed, ctx) {
14872
+ const report = await buildStatus(ctx);
14873
+ if (flag(parsed, "json")) ctx.out.print(JSON.stringify(report, null, 2));
14874
+ else renderHuman(report, ctx);
14875
+ return report.loggedIn ? 0 : EXIT_NOT_LOGGED_IN;
14876
+ }
14877
+ };
14878
+
14626
14879
  // src/cli/registry.ts
14627
- var commands = [spec3, spec4, spec2, spec5, spec];
14880
+ var commands = [spec2, spec3, spec6, spec4, spec5, spec];
14628
14881
  var herdrCommands = [installSpec, uninstallSpec];
14629
14882
  function lookup(words) {
14630
14883
  const [first, second] = words;
@@ -14683,20 +14936,20 @@ function rootHelp(s, version) {
14683
14936
  return `${lines.join("\n")}
14684
14937
  `;
14685
14938
  }
14686
- function commandHelp(s, spec6) {
14939
+ function commandHelp(s, spec7) {
14687
14940
  const lines = [
14688
- `${s.bold(`peerband ${spec6.name}`)} ${spec6.summary}`,
14689
- ...section(s, "Usage", [spec6.usage]),
14941
+ `${s.bold(`peerband ${spec7.name}`)} ${spec7.summary}`,
14942
+ ...section(s, "Usage", [spec7.usage]),
14690
14943
  "",
14691
- ...spec6.description.split("\n").map((line) => ` ${line}`),
14692
- ...section(s, "Options", table(optionRows(spec6.options), s)),
14944
+ ...spec7.description.split("\n").map((line) => ` ${line}`),
14945
+ ...section(s, "Options", table(optionRows(spec7.options), s)),
14693
14946
  ...section(
14694
14947
  s,
14695
14948
  "Examples",
14696
- spec6.examples.flatMap(([command, comment]) => [`${s.cyan(command)}`, ` ${s.dim(comment)}`])
14949
+ spec7.examples.flatMap(([command, comment]) => [`${s.cyan(command)}`, ` ${s.dim(comment)}`])
14697
14950
  )
14698
14951
  ];
14699
- if (spec6.notes?.length) lines.push(...section(s, "Notes", spec6.notes));
14952
+ if (spec7.notes?.length) lines.push(...section(s, "Notes", spec7.notes));
14700
14953
  return `${lines.join("\n")}
14701
14954
  `;
14702
14955
  }
@@ -14714,7 +14967,7 @@ function herdrGroupHelp(s) {
14714
14967
  }
14715
14968
 
14716
14969
  // src/cli/cli.ts
14717
- var VERSION = true ? "0.1.1" : "0.0.0-dev";
14970
+ var VERSION = true ? "0.1.3" : "0.0.0-dev";
14718
14971
  function createContext(overrides = {}) {
14719
14972
  const env = overrides.env ?? process.env;
14720
14973
  const stdout = overrides.stdout ?? process.stdout;
@@ -14735,9 +14988,9 @@ function resolveHelpTarget(words, ctx) {
14735
14988
  const s = ctx.out.stdout;
14736
14989
  if (words.length === 0) return rootHelp(s, ctx.version);
14737
14990
  if (words[0] === "herdr" && words.length === 1) return herdrGroupHelp(s);
14738
- const spec6 = lookup(words);
14739
- if (!spec6) throw unknownCommand(words.join(" "));
14740
- return commandHelp(s, spec6);
14991
+ const spec7 = lookup(words);
14992
+ if (!spec7) throw unknownCommand(words.join(" "));
14993
+ return commandHelp(s, spec7);
14741
14994
  }
14742
14995
  function unknownCommand(name) {
14743
14996
  const near = suggest(name, topLevelNames());
@@ -14780,14 +15033,14 @@ async function run(argv, ctx = createContext()) {
14780
15033
  words = [first, second];
14781
15034
  args = others;
14782
15035
  }
14783
- const spec6 = lookup(words);
14784
- if (!spec6) throw unknownCommand(first);
14785
- const parsed = parseArgs(spec6, args);
15036
+ const spec7 = lookup(words);
15037
+ if (!spec7) throw unknownCommand(first);
15038
+ const parsed = parseArgs(spec7, args);
14786
15039
  if (parsed.values.help) {
14787
- ctx.out.print(commandHelp(ctx.out.stdout, spec6).trimEnd());
15040
+ ctx.out.print(commandHelp(ctx.out.stdout, spec7).trimEnd());
14788
15041
  return 0;
14789
15042
  }
14790
- return await spec6.run(parsed, ctx);
15043
+ return await spec7.run(parsed, ctx);
14791
15044
  } catch (error) {
14792
15045
  if (error instanceof UsageError) {
14793
15046
  ctx.out.fail(error.message, error.hint);