peerband 0.1.5 → 0.2.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.
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(list2, totalLength) {
69
- if (list2.length === 0) return EMPTY_BUFFER;
70
- if (list2.length === 1) return list2[0];
68
+ function concat(list3, totalLength) {
69
+ if (list3.length === 0) return EMPTY_BUFFER;
70
+ if (list3.length === 1) return list3[0];
71
71
  const target = Buffer.allocUnsafe(totalLength);
72
72
  let offset = 0;
73
- for (let i = 0; i < list2.length; i++) {
74
- const buf = list2[i];
73
+ for (let i = 0; i < list3.length; i++) {
74
+ const buf = list3[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(list2, cb) {
1861
- if (list2.length === 2) {
1860
+ sendFrame(list3, cb) {
1861
+ if (list3.length === 2) {
1862
1862
  this._socket.cork();
1863
- this._socket.write(list2[0]);
1864
- this._socket.write(list2[1], cb);
1863
+ this._socket.write(list3[0]);
1864
+ this._socket.write(list3[1], cb);
1865
1865
  this._socket.uncork();
1866
1866
  } else {
1867
- this._socket.write(list2[0], cb);
1867
+ this._socket.write(list3[0], cb);
1868
1868
  }
1869
1869
  }
1870
1870
  };
@@ -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 list2 = opts.formats || formats_1.formatNames;
10863
- addFormats2(ajv, list2, formats, exportName);
10862
+ const list3 = opts.formats || formats_1.formatNames;
10863
+ addFormats2(ajv, list3, 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, list2, fs, exportName) {
10875
+ function addFormats2(ajv, list3, 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 list2)
10879
+ for (const f of list3)
10880
10880
  ajv.addFormat(f, fs[f]);
10881
10881
  }
10882
10882
  module.exports = exports = formatsPlugin;
@@ -12969,6 +12969,7 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
12969
12969
  import { randomUUID as randomUUID2 } from "node:crypto";
12970
12970
  var AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
12971
12971
  var NOTE_MAX_CHARS = 1024;
12972
+ var CHANNEL_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
12972
12973
  var PANE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
12973
12974
  function eventFrame(name, data, now = /* @__PURE__ */ new Date()) {
12974
12975
  return { type: "event", eventId: randomUUID2(), name, timestamp: now.toISOString(), data };
@@ -12976,6 +12977,13 @@ function eventFrame(name, data, now = /* @__PURE__ */ new Date()) {
12976
12977
  function codePoints(text2) {
12977
12978
  return Array.from(text2).length;
12978
12979
  }
12980
+ function noteChannel(channel) {
12981
+ if (channel === void 0 || channel === null) return void 0;
12982
+ if (typeof channel !== "string" || !CHANNEL_NAME.test(channel)) {
12983
+ throw new ConnectError("invalid_argument", "Invalid channel name.", "Channel names are 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit; see `peerband channels`.");
12984
+ }
12985
+ return channel;
12986
+ }
12979
12987
  function cleanNote(text2) {
12980
12988
  if (typeof text2 !== "string" || text2.trim().length === 0) throw new ConnectError("invalid_argument", "The note is empty.", 'Pass a short note, for example `peerband notify "Tests pass"`.');
12981
12989
  if (codePoints(text2) > NOTE_MAX_CHARS) throw new ConnectError("invalid_argument", `The note is longer than ${NOTE_MAX_CHARS} characters.`, "Shorten the note; put details where the owner can read them, such as a file or the agent output.");
@@ -13068,14 +13076,16 @@ var ConnectorEvents = class {
13068
13076
  async notify(input) {
13069
13077
  if (!this.adapter.getCapabilities().readOutput) throw new ConnectError("unsupported_capability", "This connector does not share agent output, so notes are turned off.", "Use a runtime with output support.");
13070
13078
  const text2 = cleanNote(input.text);
13079
+ const channel = noteChannel(input.channel);
13071
13080
  const agentId = await this.resolveAgent(input.paneId);
13072
- if (!this.send) return { sent: false, agentId };
13081
+ const echo = channel ? { channel } : {};
13082
+ if (!this.send) return { sent: false, agentId, ...echo };
13073
13083
  this.refillNotes();
13074
13084
  if (this.noteTokens < 1) throw new ConnectError("rate_limited", `Too many notes: at most ${this.notesPerMinute} per minute.`, "Wait a minute, and send one note per important result.");
13075
13085
  this.noteTokens -= 1;
13076
- const frame = eventFrame("agent.notified", { agentId, text: text2, audience: "owner" });
13086
+ const frame = eventFrame("agent.notified", { agentId, text: text2, audience: "owner", ...echo });
13077
13087
  const sent = this.send(frame);
13078
- return { sent, agentId, ...sent ? { eventId: frame.eventId } : {} };
13088
+ return { sent, agentId, ...sent ? { eventId: frame.eventId } : {}, ...echo };
13079
13089
  }
13080
13090
  async resolveAgent(paneId) {
13081
13091
  if (typeof paneId !== "string" || !PANE_ID.test(paneId) || !this.adapter.agentIdForPane) return null;
@@ -13193,11 +13203,11 @@ function suggest(input, candidates) {
13193
13203
  return best?.name;
13194
13204
  }
13195
13205
  var HELP_OPTION = { name: "help", short: "h", type: "boolean", description: "Show help for this command." };
13196
- function parseArgs(spec11, argv) {
13197
- const options = [...spec11.options, HELP_OPTION];
13206
+ function parseArgs(spec12, argv) {
13207
+ const options = [...spec12.options, HELP_OPTION];
13198
13208
  const values = {};
13199
13209
  const positionals = [];
13200
- const helpHint = `Run \`peerband ${spec11.name} --help\` for usage.`;
13210
+ const helpHint = `Run \`peerband ${spec12.name} --help\` for usage.`;
13201
13211
  for (let i = 0; i < argv.length; i++) {
13202
13212
  const arg = argv[i];
13203
13213
  if (arg === "--") {
@@ -13217,11 +13227,11 @@ function parseArgs(spec11, argv) {
13217
13227
  option = options.find((candidate) => candidate.name === name);
13218
13228
  if (!option) {
13219
13229
  const near = suggest(name, options.filter((o) => !o.hidden).map((o) => o.name));
13220
- throw new UsageError(`Unknown option --${name} for \`peerband ${spec11.name}\`.`, near ? `Did you mean --${near}? ${helpHint}` : helpHint);
13230
+ throw new UsageError(`Unknown option --${name} for \`peerband ${spec12.name}\`.`, near ? `Did you mean --${near}? ${helpHint}` : helpHint);
13221
13231
  }
13222
13232
  } else {
13223
13233
  option = options.find((candidate) => candidate.short === arg.slice(1));
13224
- if (!option) throw new UsageError(`Unknown option ${arg} for \`peerband ${spec11.name}\`.`, helpHint);
13234
+ if (!option) throw new UsageError(`Unknown option ${arg} for \`peerband ${spec12.name}\`.`, helpHint);
13225
13235
  }
13226
13236
  if (option.type === "boolean") {
13227
13237
  if (inline !== void 0) throw new UsageError(`Option --${option.name} does not take a value.`, helpHint);
@@ -13239,9 +13249,9 @@ function parseArgs(spec11, argv) {
13239
13249
  }
13240
13250
  values[option.name] = value;
13241
13251
  }
13242
- const max = spec11.positionals?.max ?? 0;
13252
+ const max = spec12.positionals?.max ?? 0;
13243
13253
  if (positionals.length > max) {
13244
- throw new UsageError(`Unexpected argument "${positionals[max]}" for \`peerband ${spec11.name}\`.`, helpHint);
13254
+ throw new UsageError(`Unexpected argument "${positionals[max]}" for \`peerband ${spec12.name}\`.`, helpHint);
13245
13255
  }
13246
13256
  return { values, positionals };
13247
13257
  }
@@ -13285,31 +13295,378 @@ function failureDetail(result) {
13285
13295
  return detail.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, 400);
13286
13296
  }
13287
13297
 
13298
+ // src/cli/output.ts
13299
+ function colorEnabled(stream, env) {
13300
+ const force = env.FORCE_COLOR;
13301
+ if (force !== void 0 && force !== "") return force !== "0" && force.toLowerCase() !== "false";
13302
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
13303
+ return Boolean(stream.isTTY) && env.TERM !== "dumb";
13304
+ }
13305
+ function makeStyle(enabled) {
13306
+ const wrap = (open, close) => (text2) => enabled ? `\x1B[${open}m${text2}\x1B[${close}m` : text2;
13307
+ return {
13308
+ enabled,
13309
+ bold: wrap(1, 22),
13310
+ dim: wrap(2, 22),
13311
+ red: wrap(31, 39),
13312
+ green: wrap(32, 39),
13313
+ yellow: wrap(33, 39),
13314
+ cyan: wrap(36, 39)
13315
+ };
13316
+ }
13317
+ var sanitize = (text2) => text2.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
13318
+ var Output = class {
13319
+ constructor(outStream, errStream, env) {
13320
+ this.outStream = outStream;
13321
+ this.errStream = errStream;
13322
+ this.stdout = makeStyle(colorEnabled(outStream, env));
13323
+ this.stderr = makeStyle(colorEnabled(errStream, env));
13324
+ }
13325
+ outStream;
13326
+ errStream;
13327
+ stdout;
13328
+ stderr;
13329
+ print(line = "") {
13330
+ this.outStream.write(`${line}
13331
+ `);
13332
+ }
13333
+ warn(line = "") {
13334
+ this.errStream.write(`${line}
13335
+ `);
13336
+ }
13337
+ /** `peerband: <message>` plus a `Next:` line, on stderr. */
13338
+ fail(message, hint) {
13339
+ const s = this.stderr;
13340
+ this.warn(`${s.bold(s.red("peerband:"))} ${message}`);
13341
+ if (hint) this.warn(`${s.dim("Next:")} ${hint}`);
13342
+ }
13343
+ };
13344
+ var symbols = { ok: "\u2713", dot: "\u25CF", ring: "\u25CB", warn: "!", fail: "\u2717" };
13345
+
13346
+ // src/cli/commands/shared.ts
13347
+ import { resolve } from "node:path";
13348
+
13349
+ // src/cli/skill.ts
13350
+ import { createHash as createHash2 } from "node:crypto";
13351
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
13352
+ import { cp, mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
13353
+ import { dirname as dirname3, join as join3 } from "node:path";
13354
+
13355
+ // src/cli/exec.ts
13356
+ import { spawn } from "node:child_process";
13357
+ var SAFE_ARG = /^[\w@./:\\=+~-]+$/;
13358
+ function cmdQuote(arg) {
13359
+ if (SAFE_ARG.test(arg)) return arg;
13360
+ if (/["%^&|<>!\r\n]/.test(arg)) throw new Error(`Refusing to pass an unsafe argument to the shell: ${arg}`);
13361
+ return `"${arg}"`;
13362
+ }
13363
+ var execProgram = (file, args, options = {}) => new Promise((resolve5) => {
13364
+ const viaShell = process.platform === "win32" && !/[\\/]/.test(file) && !/\.exe$/i.test(file);
13365
+ let child;
13366
+ try {
13367
+ child = viaShell ? spawn([file, ...args].map(cmdQuote).join(" "), { shell: true, env: options.env ?? process.env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) : spawn(file, args, { env: options.env ?? process.env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], shell: false });
13368
+ } catch (error) {
13369
+ resolve5({ code: 1, stdout: "", stderr: error.message });
13370
+ return;
13371
+ }
13372
+ let stdout = "";
13373
+ let stderr = "";
13374
+ let settled = false;
13375
+ const finish = (result) => {
13376
+ if (settled) return;
13377
+ settled = true;
13378
+ clearTimeout(timer);
13379
+ resolve5(result);
13380
+ };
13381
+ const timer = setTimeout(() => {
13382
+ child.kill();
13383
+ finish({ code: 1, stdout, stderr: `${stderr}
13384
+ timed out` });
13385
+ }, options.timeoutMs ?? 3e5);
13386
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
13387
+ stdout += chunk;
13388
+ options.onStdout?.(chunk);
13389
+ });
13390
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
13391
+ stderr += chunk;
13392
+ options.onStderr?.(chunk);
13393
+ });
13394
+ child.once("error", (error) => finish({ code: 127, stdout, stderr: error.message, notFound: error.code === "ENOENT" }));
13395
+ child.once("close", (code) => {
13396
+ if (viaShell && code === 9009) return finish({ code: 127, stdout, stderr: stderr || `${file} was not found`, notFound: true });
13397
+ finish({ code: code ?? 1, stdout, stderr });
13398
+ });
13399
+ });
13400
+
13401
+ // src/cli/skill.ts
13402
+ var SKILLS_CLI = "skills@1.7.4";
13403
+ var SKILL_NAME = "peerband";
13404
+ var SKILLS_TIMEOUT_MS = 12e4;
13405
+ function bundledSkillDir(selfPath = process.argv[1]) {
13406
+ if (!selfPath) return void 0;
13407
+ let dir;
13408
+ try {
13409
+ dir = dirname3(realpathSync(selfPath));
13410
+ } catch {
13411
+ return void 0;
13412
+ }
13413
+ for (let i = 0; i < 4; i++) {
13414
+ const candidate = join3(dir, "skills", SKILL_NAME);
13415
+ if (existsSync(join3(candidate, "SKILL.md"))) return candidate;
13416
+ const parent = dirname3(dir);
13417
+ if (parent === dir) break;
13418
+ dir = parent;
13419
+ }
13420
+ return void 0;
13421
+ }
13422
+ function skillsHome(ctx) {
13423
+ return ctx.env.PEERBAND_SKILLS_HOME || (process.platform === "win32" ? ctx.env.USERPROFILE : ctx.env.HOME) || void 0;
13424
+ }
13425
+ function copyTargets(home) {
13426
+ const targets = [join3(home, ".agents", "skills", SKILL_NAME)];
13427
+ if (existsSync(join3(home, ".claude"))) targets.push(join3(home, ".claude", "skills", SKILL_NAME));
13428
+ return targets;
13429
+ }
13430
+ function installedSkillFile(ctx) {
13431
+ const home = skillsHome(ctx);
13432
+ if (!home) return void 0;
13433
+ return [join3(home, ".agents", "skills", SKILL_NAME), join3(home, ".claude", "skills", SKILL_NAME)].map((dir) => join3(dir, "SKILL.md")).find((file) => existsSync(file));
13434
+ }
13435
+ var skillInstalled = (ctx) => installedSkillFile(ctx) !== void 0;
13436
+ var sha256 = (file) => createHash2("sha256").update(readFileSync(file)).digest("hex");
13437
+ var recordFile = (ctx) => join3(configHome({ env: ctx.env }), "skill.json");
13438
+ function skillEdited(ctx) {
13439
+ const file = installedSkillFile(ctx);
13440
+ if (!file) return false;
13441
+ let recorded;
13442
+ try {
13443
+ recorded = JSON.parse(readFileSync(recordFile(ctx), "utf8")).sha256;
13444
+ } catch {
13445
+ return false;
13446
+ }
13447
+ try {
13448
+ return typeof recorded === "string" && sha256(file) !== recorded;
13449
+ } catch {
13450
+ return false;
13451
+ }
13452
+ }
13453
+ var SkillEditedError = class extends Error {
13454
+ constructor(file) {
13455
+ super(`The PeerBand skill at ${file} has your own changes, so it was not replaced.`);
13456
+ this.file = file;
13457
+ this.name = "SkillEditedError";
13458
+ }
13459
+ file;
13460
+ };
13461
+ function parseSkillsJson(stdout) {
13462
+ const start = stdout.indexOf("[");
13463
+ const end = stdout.lastIndexOf("]");
13464
+ if (start === -1 || end <= start) return void 0;
13465
+ let items;
13466
+ try {
13467
+ items = JSON.parse(stdout.slice(start, end + 1));
13468
+ } catch {
13469
+ return void 0;
13470
+ }
13471
+ if (!Array.isArray(items)) return void 0;
13472
+ const item = items.find((entry) => entry && typeof entry === "object" && entry.name === SKILL_NAME);
13473
+ if (!item || item.status !== "installed" || typeof item.path !== "string") return void 0;
13474
+ const agents = Array.isArray(item.agents) ? item.agents.filter((agent) => typeof agent === "string") : [];
13475
+ return { method: "skills", path: item.path, agents };
13476
+ }
13477
+ function failureReason(stdout, stderr, code) {
13478
+ const json = /"error"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(stdout)?.[1];
13479
+ if (json) return json.replace(/\\(.)/g, "$1");
13480
+ const line = `${stderr}
13481
+ ${stdout}`.split(/\r?\n/).map((text2) => text2.trim()).filter(Boolean).pop();
13482
+ return line ? `${line} (exit code ${code})` : `exit code ${code}`;
13483
+ }
13484
+ async function installSkill(ctx, options = {}) {
13485
+ const source = bundledSkillDir(ctx.selfPath);
13486
+ if (!source) throw new Error("The PeerBand skill is missing from this installation.");
13487
+ if (!options.force && skillEdited(ctx)) throw new SkillEditedError(installedSkillFile(ctx));
13488
+ const remember = async (installed) => {
13489
+ try {
13490
+ const file = recordFile(ctx);
13491
+ await mkdir3(dirname3(file), { recursive: true });
13492
+ await writeFile3(file, `${JSON.stringify({ sha256: sha256(join3(source, "SKILL.md")), path: installed.path }, null, 2)}
13493
+ `);
13494
+ } catch {
13495
+ }
13496
+ return installed;
13497
+ };
13498
+ let reason;
13499
+ if (!options.copy) {
13500
+ const exec2 = ctx.exec ?? execProgram;
13501
+ const result = await exec2("npx", ["-y", SKILLS_CLI, "add", source, "--global", "--yes", "--json"], { timeoutMs: SKILLS_TIMEOUT_MS, env: ctx.env });
13502
+ const installed = parseSkillsJson(result.stdout);
13503
+ if (installed) return remember(installed);
13504
+ reason = result.notFound ? "npx was not found" : failureReason(result.stdout, result.stderr, result.code);
13505
+ options.log?.(`The skills installer did not finish (${reason}); copying the skill instead.`);
13506
+ }
13507
+ const home = skillsHome(ctx);
13508
+ if (!home) throw new Error(`Could not find your home folder to copy the skill into${reason ? ` (skills installer: ${reason})` : ""}.`);
13509
+ const targets = copyTargets(home);
13510
+ for (const target of targets) {
13511
+ await mkdir3(dirname3(target), { recursive: true });
13512
+ await cp(source, target, { recursive: true, force: true });
13513
+ }
13514
+ return remember({ method: "copy", path: targets[0], agents: targets.map((target) => dirname3(dirname3(target))) });
13515
+ }
13516
+
13517
+ // src/cli/commands/shared.ts
13518
+ var credentialsFile = (ctx) => credentialsPath({ env: ctx.env });
13519
+ async function requireCredentials(ctx) {
13520
+ try {
13521
+ return await loadCredentials(credentialsFile(ctx));
13522
+ } catch (error) {
13523
+ if (error instanceof ConfigError) {
13524
+ throw new CliError(error.message, error.hint, error.message === "Not logged in." ? EXIT_NOT_LOGGED_IN : 1);
13525
+ }
13526
+ throw error;
13527
+ }
13528
+ }
13529
+ async function installationCall(ctx, credentials, method, path, body, notFound) {
13530
+ const url = new URL(path, enrollmentBase(credentials.serverUrl));
13531
+ let response;
13532
+ try {
13533
+ response = await ctx.fetch(url, {
13534
+ method,
13535
+ headers: { authorization: `Bearer ${credentials.credential}`, ...body ? { "content-type": "application/json" } : {} },
13536
+ ...body ? { body: JSON.stringify(body) } : {},
13537
+ signal: AbortSignal.timeout(15e3)
13538
+ });
13539
+ } catch (error) {
13540
+ throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
13541
+ }
13542
+ if (response.status === 204) return null;
13543
+ const parsed = await response.json().catch(() => ({}));
13544
+ if (response.ok) return parsed;
13545
+ const detail = typeof parsed.detail === "string" ? parsed.detail : `HTTP ${response.status}`;
13546
+ 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.");
13547
+ if (response.status === 404 && notFound) throw new CliError(notFound);
13548
+ throw new CliError(sanitize(detail));
13549
+ }
13550
+ async function loadMachineConnectorConfig(ctx, explicitPath) {
13551
+ const explicit = explicitPath ?? ctx.env.PEERBAND_CONNECTOR_CONFIG;
13552
+ return explicit ? loadConnectorConfig(resolve(explicit)) : loadConnectorConfig(connectorConfigPath({ env: ctx.env }), { optional: true });
13553
+ }
13554
+ function writesEnabled(config, flags = {}) {
13555
+ if (flags.readOnly) return false;
13556
+ if (flags.enableWrites) return true;
13557
+ return config.enableWrites !== false;
13558
+ }
13559
+ var SKILL_COMMAND = "peerband skill";
13560
+ function printSkillTip(ctx) {
13561
+ if (skillInstalled(ctx)) return;
13562
+ ctx.out.print(ctx.out.stdout.dim(`Give your coding agents the PeerBand skill: ${SKILL_COMMAND}`));
13563
+ }
13564
+ var describeMachine = (credentials) => credentials.machineName ?? credentials.installationId;
13565
+ function printMcpHint(ctx, serverUrl) {
13566
+ const s = ctx.out.stdout;
13567
+ let url;
13568
+ try {
13569
+ url = mcpUrlFor(serverUrl, ctx.env);
13570
+ } catch {
13571
+ return;
13572
+ }
13573
+ ctx.out.print("");
13574
+ ctx.out.print(`${s.bold("MCP server")} ${s.cyan(url)}`);
13575
+ ctx.out.print(
13576
+ s.dim("Add it as a custom connector in ChatGPT or Claude (or any MCP client with remote servers), then sign in and approve access.")
13577
+ );
13578
+ ctx.out.print(s.dim(`Claude Code: claude mcp add --transport http peerband ${url}`));
13579
+ }
13580
+
13581
+ // src/cli/commands/channels.ts
13582
+ var NO_CHANNEL_SUPPORT = "This PeerBand server doesn't support channels yet.";
13583
+ var dashboardUrl = (credentials) => new URL("/dashboard", enrollmentBase(credentials.serverUrl)).href;
13584
+ async function fetchChannels(ctx, credentials) {
13585
+ const body = await installationCall(ctx, credentials, "GET", "/api/installation/channels", void 0, NO_CHANNEL_SUPPORT);
13586
+ if (!body || !Array.isArray(body.channels)) throw new CliError("PeerBand sent an unexpected channel list.", "Try again; run `peerband update` if it keeps happening.");
13587
+ return body.channels.flatMap((raw) => {
13588
+ if (!raw || typeof raw !== "object") return [];
13589
+ const item = raw;
13590
+ if (typeof item.name !== "string" || !CHANNEL_NAME.test(item.name)) return [];
13591
+ const text2 = (value) => typeof value === "string" ? sanitize(value).slice(0, 64) : "unknown";
13592
+ const events = Array.isArray(item.events) ? item.events.filter((event) => typeof event === "string").map((event) => sanitize(event).slice(0, 64)) : [];
13593
+ return [{ name: item.name, format: text2(item.format), state: text2(item.state), events }];
13594
+ });
13595
+ }
13596
+ var STATE_NOTES = {
13597
+ active: "active",
13598
+ pending_verification: "waiting for verification",
13599
+ paused: "paused",
13600
+ disabled: "disabled"
13601
+ };
13602
+ var stateLabel = (state) => STATE_NOTES[state] ?? state;
13603
+ async function list(ctx, json) {
13604
+ const credentials = await requireCredentials(ctx);
13605
+ const channels = await fetchChannels(ctx, credentials);
13606
+ if (json) {
13607
+ ctx.out.print(JSON.stringify({ channels }, null, 2));
13608
+ return 0;
13609
+ }
13610
+ const s = ctx.out.stdout;
13611
+ if (!channels.length) {
13612
+ ctx.out.print("No channels yet for this machine.");
13613
+ ctx.out.print(s.dim(`Add one in the dashboard (${dashboardUrl(credentials)} \u2192 Webhooks): its name is the channel name. Agents then send to it with \`peerband notify --channel NAME "<text>"\`.`));
13614
+ return 0;
13615
+ }
13616
+ ctx.out.print(s.bold("Channels"));
13617
+ const width = Math.max(...channels.map((channel) => channel.name.length));
13618
+ for (const channel of channels) {
13619
+ const state = channel.state === "active" ? s.green(stateLabel(channel.state)) : s.yellow(stateLabel(channel.state));
13620
+ ctx.out.print(` ${channel.name.padEnd(width)} ${channel.format.padEnd(8)} ${state}`);
13621
+ }
13622
+ ctx.out.print("");
13623
+ ctx.out.print(s.dim('Send a note to one with `peerband notify --channel NAME "<text>"`. Manage channels in the dashboard (Webhooks).'));
13624
+ return 0;
13625
+ }
13626
+ var spec = {
13627
+ name: "channels",
13628
+ summary: "List the channels agents can send notes to",
13629
+ usage: "peerband channels [list] [--json]",
13630
+ description: "Lists the channels this machine can send notes to with `peerband notify --channel NAME`. A channel is one of the machine owner's webhooks (for example a Slack or Discord incoming webhook, or your own endpoint), addressed by its name. The owner adds them in the PeerBand dashboard under Webhooks; only webhooks that include this machine are listed. Shows each channel's name, format and state; only active channels accept notes. Webhook URLs and secrets are never shown.",
13631
+ options: [{ name: "json", type: "boolean", description: "Print machine-readable JSON: {channels: [{name, format, state, events}]}." }],
13632
+ positionals: { name: "list", max: 1 },
13633
+ examples: [
13634
+ ["peerband channels", "Channels this machine can send notes to"],
13635
+ ["peerband channels --json", "The same, for scripts"]
13636
+ ],
13637
+ notes: ["Needs `peerband login`; the relay does not have to be running."],
13638
+ async run(parsed, ctx) {
13639
+ const [action] = parsed.positionals;
13640
+ if (action !== void 0 && action !== "list") throw new UsageError(`Unknown channels action "${sanitize(action)}".`, "Use `peerband channels` or `peerband channels list`.");
13641
+ return list(ctx, flag(parsed, "json"));
13642
+ }
13643
+ };
13644
+
13288
13645
  // herdr/relay-tab.mjs
13289
13646
  import { execFile as execFile2 } from "node:child_process";
13290
- import { mkdir as mkdir3, readFile as readFile4, rename as rename3, rm as rm3, rmdir as rmdir2, stat, writeFile as writeFile3 } from "node:fs/promises";
13647
+ import { mkdir as mkdir4, readFile as readFile4, rename as rename3, rm as rm3, rmdir as rmdir2, stat, writeFile as writeFile4 } from "node:fs/promises";
13291
13648
  import { randomUUID as randomUUID3 } from "node:crypto";
13292
- import { dirname as dirname3 } from "node:path";
13649
+ import { dirname as dirname4 } from "node:path";
13293
13650
 
13294
13651
  // herdr/paths.mjs
13295
- import { createHash as createHash2 } from "node:crypto";
13652
+ import { createHash as createHash3 } from "node:crypto";
13296
13653
  import { homedir as homedir2, tmpdir } from "node:os";
13297
- import { join as join3, posix, resolve, win32 } from "node:path";
13654
+ import { join as join4, posix, resolve as resolve2, win32 } from "node:path";
13298
13655
  function configHome2(env = process.env, platform = process.platform, home = homedir2()) {
13299
13656
  if (env.PEERBAND_CONFIG_HOME) return env.PEERBAND_CONFIG_HOME;
13300
- if (platform === "win32") return join3(env.APPDATA || join3(home, "AppData", "Roaming"), "peerband");
13301
- return join3(env.XDG_CONFIG_HOME || join3(home, ".config"), "peerband");
13657
+ if (platform === "win32") return join4(env.APPDATA || join4(home, "AppData", "Roaming"), "peerband");
13658
+ return join4(env.XDG_CONFIG_HOME || join4(home, ".config"), "peerband");
13302
13659
  }
13303
- var lockPath2 = (config = configHome2()) => join3(config, "relay-helper.lock");
13304
- var ownerRecordPath = (config = configHome2()) => join3(lockPath2(config), "owner.json");
13305
- var relayTabPath2 = (config = configHome2()) => join3(config, "relay-tab.json");
13660
+ var lockPath2 = (config = configHome2()) => join4(config, "relay-helper.lock");
13661
+ var ownerRecordPath = (config = configHome2()) => join4(lockPath2(config), "owner.json");
13662
+ var relayTabPath2 = (config = configHome2()) => join4(config, "relay-tab.json");
13306
13663
  function canonicalConfig(config, platform = process.platform) {
13307
13664
  const resolved = (platform === "win32" ? win32 : posix).resolve(config);
13308
13665
  return platform === "win32" ? resolved.toLowerCase() : resolved;
13309
13666
  }
13310
13667
  function controlChannel(config = configHome2(), platform = process.platform) {
13311
- const digest = createHash2("sha256").update(canonicalConfig(config, platform)).digest("hex").slice(0, 24);
13312
- return platform === "win32" ? `\\\\.\\pipe\\peerband-relay-${digest}` : join3(tmpdir(), `pbr-${process.getuid?.() ?? "local"}-${digest}.sock`);
13668
+ const digest = createHash3("sha256").update(canonicalConfig(config, platform)).digest("hex").slice(0, 24);
13669
+ return platform === "win32" ? `\\\\.\\pipe\\peerband-relay-${digest}` : join4(tmpdir(), `pbr-${process.getuid?.() ?? "local"}-${digest}.sock`);
13313
13670
  }
13314
13671
 
13315
13672
  // herdr/relay-tab.mjs
@@ -13385,10 +13742,10 @@ async function readRecord(statePath) {
13385
13742
  return void 0;
13386
13743
  }
13387
13744
  async function writeRecord(statePath, record) {
13388
- await mkdir3(dirname3(statePath), { recursive: true });
13745
+ await mkdir4(dirname4(statePath), { recursive: true });
13389
13746
  const temporary = `${statePath}.${randomUUID3()}.tmp`;
13390
13747
  try {
13391
- await writeFile3(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
13748
+ await writeFile4(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
13392
13749
  await rename3(temporary, statePath);
13393
13750
  } finally {
13394
13751
  await rm3(temporary, { force: true }).catch(() => {
@@ -13397,11 +13754,11 @@ async function writeRecord(statePath, record) {
13397
13754
  }
13398
13755
  async function withLaunchLock(statePath, action) {
13399
13756
  const lockPath3 = `${statePath}.launch-lock`;
13400
- await mkdir3(dirname3(statePath), { recursive: true });
13757
+ await mkdir4(dirname4(statePath), { recursive: true });
13401
13758
  const deadline = Date.now() + 5e3;
13402
13759
  while (true) {
13403
13760
  try {
13404
- await mkdir3(lockPath3);
13761
+ await mkdir4(lockPath3);
13405
13762
  break;
13406
13763
  } catch (error) {
13407
13764
  if (error?.code !== "EEXIST") throw error;
@@ -13597,10 +13954,10 @@ function paneLabel(snapshot) {
13597
13954
  // herdr/stale-lock.mjs
13598
13955
  import { execFile as execFile3 } from "node:child_process";
13599
13956
  import { randomUUID as randomUUID4 } from "node:crypto";
13600
- import { readdir, readFile as readFile5, rename as rename4, rm as rm4, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
13957
+ import { readdir, readFile as readFile5, rename as rename4, rm as rm4, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
13601
13958
  import { createConnection } from "node:net";
13602
13959
  import { hostname as hostname2 } from "node:os";
13603
- import { join as join4, relative } from "node:path";
13960
+ import { join as join5, relative } from "node:path";
13604
13961
  var CREATION_GRACE_MS = 1e4;
13605
13962
  var SUPERVISOR_PATTERN = /lifecycle\.mjs["']?\s+supervise\b/i;
13606
13963
  var CONNECTOR_PATTERN = /peerband(?:\.mjs|\.cmd|\.ps1)?["']?\s+connect\b/i;
@@ -13687,7 +14044,7 @@ async function readOwner(ownerFile) {
13687
14044
  }
13688
14045
  return { text: text2, owner: {} };
13689
14046
  }
13690
- async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list2 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now = Date.now() }) {
14047
+ async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list3 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now = Date.now() }) {
13691
14048
  let info;
13692
14049
  try {
13693
14050
  info = await stat2(lockDir);
@@ -13699,7 +14056,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
13699
14056
  const ignore = /* @__PURE__ */ new Set([process.pid, ...excludePids]);
13700
14057
  const matching = async (keep) => {
13701
14058
  if (!processPattern) return null;
13702
- const processes = await list2();
14059
+ const processes = await list3();
13703
14060
  if (!processes) return null;
13704
14061
  return processes.filter((item) => (item.pid === keep || !ignore.has(item.pid)) && processPattern.test(item.command));
13705
14062
  };
@@ -13737,7 +14094,7 @@ async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
13737
14094
  } catch (error) {
13738
14095
  return Boolean(error && error.code === "ENOENT");
13739
14096
  }
13740
- const moved = await readOwner(join4(quarantine, relative(lockDir, ownerFile)));
14097
+ const moved = await readOwner(join5(quarantine, relative(lockDir, ownerFile)));
13741
14098
  if (expectedOwnerText !== void 0 && moved.text !== expectedOwnerText) {
13742
14099
  await rename4(quarantine, lockDir).catch(() => {
13743
14100
  });
@@ -13763,7 +14120,7 @@ async function resetRelayState(path) {
13763
14120
  }
13764
14121
  const activity = Array.isArray(previous.activity) ? previous.activity : [];
13765
14122
  if (previous.state === "stopping" && previous.connectionState === "disabled") return false;
13766
- await writeFile4(path, `${JSON.stringify({ state: "stopping", connectionState: "disabled", activity })}
14123
+ await writeFile5(path, `${JSON.stringify({ state: "stopping", connectionState: "disabled", activity })}
13767
14124
  `, { mode: 384 });
13768
14125
  return true;
13769
14126
  }
@@ -13787,10 +14144,10 @@ var CONNECTOR_PATTERN2 = CONNECTOR_PATTERN;
13787
14144
  import { resolve as resolve3 } from "node:path";
13788
14145
 
13789
14146
  // src/runtime-herdr/adapter.ts
13790
- import { createHash as createHash3, randomUUID as randomUUID7 } from "node:crypto";
14147
+ import { createHash as createHash4, randomUUID as randomUUID7 } from "node:crypto";
13791
14148
  import { readFile as readFile7, stat as stat3 } from "node:fs/promises";
13792
14149
  import { homedir as homedir3 } from "node:os";
13793
- import { join as join5 } from "node:path";
14150
+ import { join as join6 } from "node:path";
13794
14151
 
13795
14152
  // src/runtime-herdr/subscription.ts
13796
14153
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -14347,7 +14704,7 @@ async function loadHerdrSchema(options = {}) {
14347
14704
  const promptRef = prompt?.properties?.params?.$ref;
14348
14705
  const promptName = promptRef?.split("/").at(-1);
14349
14706
  const params = promptName ? schema.schemas.request.$defs?.[promptName] : void 0;
14350
- const writesHaveAtomicOccupantGuard = Boolean(params?.properties && Object.entries(params.properties).some(([name, spec11]) => /^(expected_generation|expected_terminal_id|expected_agent_session)$/i.test(name) && JSON.stringify(spec11).toLowerCase().includes("occupant")));
14707
+ const writesHaveAtomicOccupantGuard = Boolean(params?.properties && Object.entries(params.properties).some(([name, spec12]) => /^(expected_generation|expected_terminal_id|expected_agent_session)$/i.test(name) && JSON.stringify(spec12).toLowerCase().includes("occupant")));
14351
14708
  return {
14352
14709
  schema,
14353
14710
  validateRequest,
@@ -14380,7 +14737,7 @@ var HerdrAdapter = class {
14380
14737
  bridge;
14381
14738
  constructor(options = {}) {
14382
14739
  this.options = options;
14383
- this.machineId = options.machineId ?? createHash3("sha256").update(`${process.platform}:${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "local"}`).digest("hex").slice(0, 24);
14740
+ this.machineId = options.machineId ?? createHash4("sha256").update(`${process.platform}:${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "local"}`).digest("hex").slice(0, 24);
14384
14741
  }
14385
14742
  getCapabilities() {
14386
14743
  return { readOutput: true, sendMessage: true, reason: "Messages are addressed by a unique live agent name. Herdr does not atomically bind that name to an occupant, so names can be reassigned between validation and delivery." };
@@ -14493,377 +14850,115 @@ var HerdrAdapter = class {
14493
14850
  const result = asObject(await client.request("agent.prompt", { target, text: message }));
14494
14851
  if (result.type !== "agent_prompted") throw this.schemaMismatch("agent.prompt returned an unexpected result type");
14495
14852
  }
14496
- async close() {
14497
- await this.bridge?.stop();
14498
- const pending = await this.ready?.catch(() => void 0);
14499
- await pending?.client.close();
14500
- }
14501
- initialize() {
14502
- if (!this.ready) {
14503
- const pending = (async () => {
14504
- const binary = this.options.binary ?? process.env.HERDR_BIN_PATH ?? "herdr";
14505
- const schema = await loadHerdrSchema({ schemaPath: this.options.schemaPath, binary });
14506
- const socketPath = this.options.socketPath ?? process.env.HERDR_SOCKET_PATH ?? defaultSocketPath();
14507
- this.socketPath = socketPath;
14508
- const client = new HerdrSocketClient({
14509
- socketPath: platformSocketAddress(socketPath),
14510
- timeoutMs: this.options.timeoutMs,
14511
- validateSuccessResponse: schema.validateSuccessResponse,
14512
- validateErrorResponse: schema.validateErrorResponse,
14513
- validateRequest: schema.validateRequest,
14514
- schemaDiagnostics: schema.diagnostics
14515
- });
14516
- const pong = asObject(await client.request("ping", {}));
14517
- if (pong.type !== "pong" || pong.protocol !== schema.schema.protocol) {
14518
- await client.close();
14519
- throw new ConnectError("schema_mismatch", "The connected Herdr server protocol does not match the selected API schema.", "Connect to the Herdr server that belongs to the configured binary or provide its API schema.");
14520
- }
14521
- return { schema, client };
14522
- })();
14523
- this.ready = pending;
14524
- void pending.catch(() => {
14525
- if (this.ready === pending) this.ready = void 0;
14526
- });
14527
- }
14528
- return this.ready;
14529
- }
14530
- schemaMismatch(message) {
14531
- return new ConnectError("schema_mismatch", `Herdr response did not match the selected API schema: ${message}`, "Use the API schema shipped with the connected Herdr version.");
14532
- }
14533
- };
14534
- function toRecord(live, machineId, canSend) {
14535
- const agent = live.agent;
14536
- const label = agent.display_agent ?? agent.name ?? agent.agent ?? agent.terminal_title_stripped ?? agent.title ?? "Herdr agent";
14537
- const status = ["idle", "working", "blocked", "done", "unknown"].includes(agent.agent_status) ? agent.agent_status : "unknown";
14538
- return {
14539
- id: live.id,
14540
- machineId,
14541
- runtime: "herdr",
14542
- agentType: agent.agent ?? agent.display_agent ?? "unknown",
14543
- label,
14544
- workspace: agent.cwd ?? agent.foreground_cwd ?? agent.workspace_id,
14545
- status,
14546
- rawStatus: agent.agent_status,
14547
- observedAt: (/* @__PURE__ */ new Date()).toISOString(),
14548
- stale: false,
14549
- capabilities: { readOutput: true, sendMessage: canSend, ...canSend ? {} : { reason: "A unique valid live name or pane target is required for prompt targeting." } }
14550
- };
14551
- }
14552
- function isValidAlias(value) {
14553
- return typeof value === "string" && /^[a-z][a-z0-9_-]{0,31}$/.test(value);
14554
- }
14555
- function isUniqueLiveAlias(agent, agents) {
14556
- return isValidAlias(agent.name) && agents.filter((candidate) => candidate.name === agent.name).length === 1;
14557
- }
14558
- function promptTarget(agent, agents) {
14559
- if (isUniqueLiveAlias(agent, agents)) return agent.name;
14560
- if (agent.pane_id.length > 0 && agents.filter((candidate) => candidate.pane_id === agent.pane_id).length === 1) return agent.pane_id;
14561
- return void 0;
14562
- }
14563
- function identityFingerprint(agent) {
14564
- const reference = agent.agent_session ? `${agent.agent_session.source}:${agent.agent_session.agent}:${agent.agent_session.kind}:${agent.agent_session.value}` : "";
14565
- return createHash3("sha256").update([agent.terminal_id, agent.agent ?? "", reference].join("\0")).digest("hex");
14566
- }
14567
- function defaultSocketPath() {
14568
- const session = process.env.HERDR_SESSION;
14569
- if (session !== void 0 && (session.length > 64 || !/^[A-Za-z0-9._-]+$/.test(session) || session === "." || session === "..")) {
14570
- throw new ConnectError("invalid_config", "HERDR_SESSION contains unsupported characters.", "Use a Herdr session name with only letters, numbers, dots, underscores, and hyphens.");
14571
- }
14572
- const root = process.platform === "win32" ? join5(process.env.APPDATA ?? join5(homedir3(), "AppData", "Roaming"), "herdr") : join5(process.env.XDG_CONFIG_HOME ?? join5(homedir3(), ".config"), "herdr");
14573
- return session ? join5(root, "sessions", session, "herdr.sock") : join5(root, "herdr.sock");
14574
- }
14575
- function platformSocketAddress(path) {
14576
- if (process.platform !== "win32" || path.startsWith("\\\\.\\pipe\\")) return path;
14577
- return `\\\\.\\pipe\\${path}`;
14578
- }
14579
- function asObject(value) {
14580
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new ConnectError("schema_mismatch", "Herdr returned a non-object result.", "Use the API schema shipped with the connected Herdr version.");
14581
- return value;
14582
- }
14583
- function isAgent(value) {
14584
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
14585
- const v = value;
14586
- return typeof v.pane_id === "string" && typeof v.terminal_id === "string" && typeof v.workspace_id === "string" && typeof v.tab_id === "string" && typeof v.agent_status === "string" && typeof v.revision === "number";
14587
- }
14588
- function clampInteger(value, fallback, min, max) {
14589
- if (value === void 0) return fallback;
14590
- if (!Number.isSafeInteger(value) || value < min || value > max) throw new ConnectError("invalid_argument", `Expected an integer from ${min} through ${max}.`, "Choose a value within the documented output limit.");
14591
- return value;
14592
- }
14593
- async function readEndpointMarker(socketPath) {
14594
- try {
14595
- if (process.platform === "win32") {
14596
- if (socketPath.startsWith("\\\\.\\pipe\\")) return void 0;
14597
- const marker = (await readFile7(socketPath, "utf8")).trim();
14598
- return marker || void 0;
14599
- }
14600
- const file = await stat3(socketPath);
14601
- return `${file.dev}:${file.ino}`;
14602
- } catch {
14603
- return void 0;
14604
- }
14605
- }
14606
-
14607
- // src/cli/output.ts
14608
- function colorEnabled(stream, env) {
14609
- const force = env.FORCE_COLOR;
14610
- if (force !== void 0 && force !== "") return force !== "0" && force.toLowerCase() !== "false";
14611
- if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
14612
- return Boolean(stream.isTTY) && env.TERM !== "dumb";
14613
- }
14614
- function makeStyle(enabled) {
14615
- const wrap = (open, close) => (text2) => enabled ? `\x1B[${open}m${text2}\x1B[${close}m` : text2;
14616
- return {
14617
- enabled,
14618
- bold: wrap(1, 22),
14619
- dim: wrap(2, 22),
14620
- red: wrap(31, 39),
14621
- green: wrap(32, 39),
14622
- yellow: wrap(33, 39),
14623
- cyan: wrap(36, 39)
14624
- };
14625
- }
14626
- var sanitize = (text2) => text2.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
14627
- var Output = class {
14628
- constructor(outStream, errStream, env) {
14629
- this.outStream = outStream;
14630
- this.errStream = errStream;
14631
- this.stdout = makeStyle(colorEnabled(outStream, env));
14632
- this.stderr = makeStyle(colorEnabled(errStream, env));
14633
- }
14634
- outStream;
14635
- errStream;
14636
- stdout;
14637
- stderr;
14638
- print(line = "") {
14639
- this.outStream.write(`${line}
14640
- `);
14641
- }
14642
- warn(line = "") {
14643
- this.errStream.write(`${line}
14644
- `);
14645
- }
14646
- /** `peerband: <message>` plus a `Next:` line, on stderr. */
14647
- fail(message, hint) {
14648
- const s = this.stderr;
14649
- this.warn(`${s.bold(s.red("peerband:"))} ${message}`);
14650
- if (hint) this.warn(`${s.dim("Next:")} ${hint}`);
14651
- }
14652
- };
14653
- var symbols = { ok: "\u2713", dot: "\u25CF", ring: "\u25CB", warn: "!", fail: "\u2717" };
14654
-
14655
- // src/cli/commands/shared.ts
14656
- import { resolve as resolve2 } from "node:path";
14657
-
14658
- // src/cli/skill.ts
14659
- import { createHash as createHash4 } from "node:crypto";
14660
- import { existsSync, readFileSync, realpathSync } from "node:fs";
14661
- import { cp, mkdir as mkdir4, writeFile as writeFile5 } from "node:fs/promises";
14662
- import { dirname as dirname4, join as join6 } from "node:path";
14663
-
14664
- // src/cli/exec.ts
14665
- import { spawn } from "node:child_process";
14666
- var SAFE_ARG = /^[\w@./:\\=+~-]+$/;
14667
- function cmdQuote(arg) {
14668
- if (SAFE_ARG.test(arg)) return arg;
14669
- if (/["%^&|<>!\r\n]/.test(arg)) throw new Error(`Refusing to pass an unsafe argument to the shell: ${arg}`);
14670
- return `"${arg}"`;
14671
- }
14672
- var execProgram = (file, args, options = {}) => new Promise((resolve5) => {
14673
- const viaShell = process.platform === "win32" && !/[\\/]/.test(file) && !/\.exe$/i.test(file);
14674
- let child;
14675
- try {
14676
- child = viaShell ? spawn([file, ...args].map(cmdQuote).join(" "), { shell: true, env: options.env ?? process.env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) : spawn(file, args, { env: options.env ?? process.env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], shell: false });
14677
- } catch (error) {
14678
- resolve5({ code: 1, stdout: "", stderr: error.message });
14679
- return;
14680
- }
14681
- let stdout = "";
14682
- let stderr = "";
14683
- let settled = false;
14684
- const finish = (result) => {
14685
- if (settled) return;
14686
- settled = true;
14687
- clearTimeout(timer);
14688
- resolve5(result);
14689
- };
14690
- const timer = setTimeout(() => {
14691
- child.kill();
14692
- finish({ code: 1, stdout, stderr: `${stderr}
14693
- timed out` });
14694
- }, options.timeoutMs ?? 3e5);
14695
- child.stdout.setEncoding("utf8").on("data", (chunk) => {
14696
- stdout += chunk;
14697
- options.onStdout?.(chunk);
14698
- });
14699
- child.stderr.setEncoding("utf8").on("data", (chunk) => {
14700
- stderr += chunk;
14701
- options.onStderr?.(chunk);
14702
- });
14703
- child.once("error", (error) => finish({ code: 127, stdout, stderr: error.message, notFound: error.code === "ENOENT" }));
14704
- child.once("close", (code) => {
14705
- if (viaShell && code === 9009) return finish({ code: 127, stdout, stderr: stderr || `${file} was not found`, notFound: true });
14706
- finish({ code: code ?? 1, stdout, stderr });
14707
- });
14708
- });
14709
-
14710
- // src/cli/skill.ts
14711
- var SKILLS_CLI = "skills@1.7.4";
14712
- var SKILL_NAME = "peerband";
14713
- var SKILLS_TIMEOUT_MS = 12e4;
14714
- function bundledSkillDir(selfPath = process.argv[1]) {
14715
- if (!selfPath) return void 0;
14716
- let dir;
14717
- try {
14718
- dir = dirname4(realpathSync(selfPath));
14719
- } catch {
14720
- return void 0;
14721
- }
14722
- for (let i = 0; i < 4; i++) {
14723
- const candidate = join6(dir, "skills", SKILL_NAME);
14724
- if (existsSync(join6(candidate, "SKILL.md"))) return candidate;
14725
- const parent = dirname4(dir);
14726
- if (parent === dir) break;
14727
- dir = parent;
14728
- }
14729
- return void 0;
14730
- }
14731
- function skillsHome(ctx) {
14732
- return ctx.env.PEERBAND_SKILLS_HOME || (process.platform === "win32" ? ctx.env.USERPROFILE : ctx.env.HOME) || void 0;
14733
- }
14734
- function copyTargets(home) {
14735
- const targets = [join6(home, ".agents", "skills", SKILL_NAME)];
14736
- if (existsSync(join6(home, ".claude"))) targets.push(join6(home, ".claude", "skills", SKILL_NAME));
14737
- return targets;
14738
- }
14739
- function installedSkillFile(ctx) {
14740
- const home = skillsHome(ctx);
14741
- if (!home) return void 0;
14742
- return [join6(home, ".agents", "skills", SKILL_NAME), join6(home, ".claude", "skills", SKILL_NAME)].map((dir) => join6(dir, "SKILL.md")).find((file) => existsSync(file));
14743
- }
14744
- var skillInstalled = (ctx) => installedSkillFile(ctx) !== void 0;
14745
- var sha256 = (file) => createHash4("sha256").update(readFileSync(file)).digest("hex");
14746
- var recordFile = (ctx) => join6(configHome({ env: ctx.env }), "skill.json");
14747
- function skillEdited(ctx) {
14748
- const file = installedSkillFile(ctx);
14749
- if (!file) return false;
14750
- let recorded;
14751
- try {
14752
- recorded = JSON.parse(readFileSync(recordFile(ctx), "utf8")).sha256;
14753
- } catch {
14754
- return false;
14853
+ async close() {
14854
+ await this.bridge?.stop();
14855
+ const pending = await this.ready?.catch(() => void 0);
14856
+ await pending?.client.close();
14755
14857
  }
14756
- try {
14757
- return typeof recorded === "string" && sha256(file) !== recorded;
14758
- } catch {
14759
- return false;
14858
+ initialize() {
14859
+ if (!this.ready) {
14860
+ const pending = (async () => {
14861
+ const binary = this.options.binary ?? process.env.HERDR_BIN_PATH ?? "herdr";
14862
+ const schema = await loadHerdrSchema({ schemaPath: this.options.schemaPath, binary });
14863
+ const socketPath = this.options.socketPath ?? process.env.HERDR_SOCKET_PATH ?? defaultSocketPath();
14864
+ this.socketPath = socketPath;
14865
+ const client = new HerdrSocketClient({
14866
+ socketPath: platformSocketAddress(socketPath),
14867
+ timeoutMs: this.options.timeoutMs,
14868
+ validateSuccessResponse: schema.validateSuccessResponse,
14869
+ validateErrorResponse: schema.validateErrorResponse,
14870
+ validateRequest: schema.validateRequest,
14871
+ schemaDiagnostics: schema.diagnostics
14872
+ });
14873
+ const pong = asObject(await client.request("ping", {}));
14874
+ if (pong.type !== "pong" || pong.protocol !== schema.schema.protocol) {
14875
+ await client.close();
14876
+ throw new ConnectError("schema_mismatch", "The connected Herdr server protocol does not match the selected API schema.", "Connect to the Herdr server that belongs to the configured binary or provide its API schema.");
14877
+ }
14878
+ return { schema, client };
14879
+ })();
14880
+ this.ready = pending;
14881
+ void pending.catch(() => {
14882
+ if (this.ready === pending) this.ready = void 0;
14883
+ });
14884
+ }
14885
+ return this.ready;
14760
14886
  }
14761
- }
14762
- var SkillEditedError = class extends Error {
14763
- constructor(file) {
14764
- super(`The PeerBand skill at ${file} has your own changes, so it was not replaced.`);
14765
- this.file = file;
14766
- this.name = "SkillEditedError";
14887
+ schemaMismatch(message) {
14888
+ return new ConnectError("schema_mismatch", `Herdr response did not match the selected API schema: ${message}`, "Use the API schema shipped with the connected Herdr version.");
14767
14889
  }
14768
- file;
14769
14890
  };
14770
- function parseSkillsJson(stdout) {
14771
- const start = stdout.indexOf("[");
14772
- const end = stdout.lastIndexOf("]");
14773
- if (start === -1 || end <= start) return void 0;
14774
- let items;
14775
- try {
14776
- items = JSON.parse(stdout.slice(start, end + 1));
14777
- } catch {
14778
- return void 0;
14779
- }
14780
- if (!Array.isArray(items)) return void 0;
14781
- const item = items.find((entry) => entry && typeof entry === "object" && entry.name === SKILL_NAME);
14782
- if (!item || item.status !== "installed" || typeof item.path !== "string") return void 0;
14783
- const agents = Array.isArray(item.agents) ? item.agents.filter((agent) => typeof agent === "string") : [];
14784
- return { method: "skills", path: item.path, agents };
14891
+ function toRecord(live, machineId, canSend) {
14892
+ const agent = live.agent;
14893
+ const label = agent.display_agent ?? agent.name ?? agent.agent ?? agent.terminal_title_stripped ?? agent.title ?? "Herdr agent";
14894
+ const status = ["idle", "working", "blocked", "done", "unknown"].includes(agent.agent_status) ? agent.agent_status : "unknown";
14895
+ return {
14896
+ id: live.id,
14897
+ machineId,
14898
+ runtime: "herdr",
14899
+ agentType: agent.agent ?? agent.display_agent ?? "unknown",
14900
+ label,
14901
+ workspace: agent.cwd ?? agent.foreground_cwd ?? agent.workspace_id,
14902
+ status,
14903
+ rawStatus: agent.agent_status,
14904
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
14905
+ stale: false,
14906
+ capabilities: { readOutput: true, sendMessage: canSend, ...canSend ? {} : { reason: "A unique valid live name or pane target is required for prompt targeting." } }
14907
+ };
14785
14908
  }
14786
- function failureReason(stdout, stderr, code) {
14787
- const json = /"error"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(stdout)?.[1];
14788
- if (json) return json.replace(/\\(.)/g, "$1");
14789
- const line = `${stderr}
14790
- ${stdout}`.split(/\r?\n/).map((text2) => text2.trim()).filter(Boolean).pop();
14791
- return line ? `${line} (exit code ${code})` : `exit code ${code}`;
14909
+ function isValidAlias(value) {
14910
+ return typeof value === "string" && /^[a-z][a-z0-9_-]{0,31}$/.test(value);
14792
14911
  }
14793
- async function installSkill(ctx, options = {}) {
14794
- const source = bundledSkillDir(ctx.selfPath);
14795
- if (!source) throw new Error("The PeerBand skill is missing from this installation.");
14796
- if (!options.force && skillEdited(ctx)) throw new SkillEditedError(installedSkillFile(ctx));
14797
- const remember = async (installed) => {
14798
- try {
14799
- const file = recordFile(ctx);
14800
- await mkdir4(dirname4(file), { recursive: true });
14801
- await writeFile5(file, `${JSON.stringify({ sha256: sha256(join6(source, "SKILL.md")), path: installed.path }, null, 2)}
14802
- `);
14803
- } catch {
14804
- }
14805
- return installed;
14806
- };
14807
- let reason;
14808
- if (!options.copy) {
14809
- const exec2 = ctx.exec ?? execProgram;
14810
- const result = await exec2("npx", ["-y", SKILLS_CLI, "add", source, "--global", "--yes", "--json"], { timeoutMs: SKILLS_TIMEOUT_MS, env: ctx.env });
14811
- const installed = parseSkillsJson(result.stdout);
14812
- if (installed) return remember(installed);
14813
- reason = result.notFound ? "npx was not found" : failureReason(result.stdout, result.stderr, result.code);
14814
- options.log?.(`The skills installer did not finish (${reason}); copying the skill instead.`);
14815
- }
14816
- const home = skillsHome(ctx);
14817
- if (!home) throw new Error(`Could not find your home folder to copy the skill into${reason ? ` (skills installer: ${reason})` : ""}.`);
14818
- const targets = copyTargets(home);
14819
- for (const target of targets) {
14820
- await mkdir4(dirname4(target), { recursive: true });
14821
- await cp(source, target, { recursive: true, force: true });
14822
- }
14823
- return remember({ method: "copy", path: targets[0], agents: targets.map((target) => dirname4(dirname4(target))) });
14912
+ function isUniqueLiveAlias(agent, agents) {
14913
+ return isValidAlias(agent.name) && agents.filter((candidate) => candidate.name === agent.name).length === 1;
14824
14914
  }
14825
-
14826
- // src/cli/commands/shared.ts
14827
- var credentialsFile = (ctx) => credentialsPath({ env: ctx.env });
14828
- async function requireCredentials(ctx) {
14829
- try {
14830
- return await loadCredentials(credentialsFile(ctx));
14831
- } catch (error) {
14832
- if (error instanceof ConfigError) {
14833
- throw new CliError(error.message, error.hint, error.message === "Not logged in." ? EXIT_NOT_LOGGED_IN : 1);
14834
- }
14835
- throw error;
14915
+ function promptTarget(agent, agents) {
14916
+ if (isUniqueLiveAlias(agent, agents)) return agent.name;
14917
+ if (agent.pane_id.length > 0 && agents.filter((candidate) => candidate.pane_id === agent.pane_id).length === 1) return agent.pane_id;
14918
+ return void 0;
14919
+ }
14920
+ function identityFingerprint(agent) {
14921
+ const reference = agent.agent_session ? `${agent.agent_session.source}:${agent.agent_session.agent}:${agent.agent_session.kind}:${agent.agent_session.value}` : "";
14922
+ return createHash4("sha256").update([agent.terminal_id, agent.agent ?? "", reference].join("\0")).digest("hex");
14923
+ }
14924
+ function defaultSocketPath() {
14925
+ const session = process.env.HERDR_SESSION;
14926
+ if (session !== void 0 && (session.length > 64 || !/^[A-Za-z0-9._-]+$/.test(session) || session === "." || session === "..")) {
14927
+ throw new ConnectError("invalid_config", "HERDR_SESSION contains unsupported characters.", "Use a Herdr session name with only letters, numbers, dots, underscores, and hyphens.");
14836
14928
  }
14929
+ const root = process.platform === "win32" ? join6(process.env.APPDATA ?? join6(homedir3(), "AppData", "Roaming"), "herdr") : join6(process.env.XDG_CONFIG_HOME ?? join6(homedir3(), ".config"), "herdr");
14930
+ return session ? join6(root, "sessions", session, "herdr.sock") : join6(root, "herdr.sock");
14837
14931
  }
14838
- async function loadMachineConnectorConfig(ctx, explicitPath) {
14839
- const explicit = explicitPath ?? ctx.env.PEERBAND_CONNECTOR_CONFIG;
14840
- return explicit ? loadConnectorConfig(resolve2(explicit)) : loadConnectorConfig(connectorConfigPath({ env: ctx.env }), { optional: true });
14932
+ function platformSocketAddress(path) {
14933
+ if (process.platform !== "win32" || path.startsWith("\\\\.\\pipe\\")) return path;
14934
+ return `\\\\.\\pipe\\${path}`;
14841
14935
  }
14842
- function writesEnabled(config, flags = {}) {
14843
- if (flags.readOnly) return false;
14844
- if (flags.enableWrites) return true;
14845
- return config.enableWrites !== false;
14936
+ function asObject(value) {
14937
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ConnectError("schema_mismatch", "Herdr returned a non-object result.", "Use the API schema shipped with the connected Herdr version.");
14938
+ return value;
14846
14939
  }
14847
- var SKILL_COMMAND = "peerband skill";
14848
- function printSkillTip(ctx) {
14849
- if (skillInstalled(ctx)) return;
14850
- ctx.out.print(ctx.out.stdout.dim(`Give your coding agents the PeerBand skill: ${SKILL_COMMAND}`));
14940
+ function isAgent(value) {
14941
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
14942
+ const v = value;
14943
+ return typeof v.pane_id === "string" && typeof v.terminal_id === "string" && typeof v.workspace_id === "string" && typeof v.tab_id === "string" && typeof v.agent_status === "string" && typeof v.revision === "number";
14851
14944
  }
14852
- var describeMachine = (credentials) => credentials.machineName ?? credentials.installationId;
14853
- function printMcpHint(ctx, serverUrl) {
14854
- const s = ctx.out.stdout;
14855
- let url;
14945
+ function clampInteger(value, fallback, min, max) {
14946
+ if (value === void 0) return fallback;
14947
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new ConnectError("invalid_argument", `Expected an integer from ${min} through ${max}.`, "Choose a value within the documented output limit.");
14948
+ return value;
14949
+ }
14950
+ async function readEndpointMarker(socketPath) {
14856
14951
  try {
14857
- url = mcpUrlFor(serverUrl, ctx.env);
14952
+ if (process.platform === "win32") {
14953
+ if (socketPath.startsWith("\\\\.\\pipe\\")) return void 0;
14954
+ const marker = (await readFile7(socketPath, "utf8")).trim();
14955
+ return marker || void 0;
14956
+ }
14957
+ const file = await stat3(socketPath);
14958
+ return `${file.dev}:${file.ino}`;
14858
14959
  } catch {
14859
- return;
14960
+ return void 0;
14860
14961
  }
14861
- ctx.out.print("");
14862
- ctx.out.print(`${s.bold("MCP server")} ${s.cyan(url)}`);
14863
- ctx.out.print(
14864
- s.dim("Add it as a custom connector in ChatGPT or Claude (or any MCP client with remote servers), then sign in and approve access.")
14865
- );
14866
- ctx.out.print(s.dim(`Claude Code: claude mcp add --transport http peerband ${url}`));
14867
14962
  }
14868
14963
 
14869
14964
  // src/cli/commands/connect.ts
@@ -14897,7 +14992,7 @@ function activityLine(s, activity, at = /* @__PURE__ */ new Date()) {
14897
14992
  const target = activity.target ? shortTarget(sanitize(activity.target)) : "-";
14898
14993
  return `${s.dim(clock(at))} ${sanitize(activity.tool).padEnd(18)} ${target.padEnd(18)} ${outcome}${" ".repeat(Math.max(0, 20 - activity.outcome.length))} ${s.dim(`${Math.round(activity.latencyMs)} ms`)}`;
14899
14994
  }
14900
- var spec = {
14995
+ var spec2 = {
14901
14996
  name: "connect",
14902
14997
  summary: "Run the connector in the foreground",
14903
14998
  usage: "peerband connect [--runtime herdr|mock] [--read-only] [--config PATH] [--server URL]",
@@ -14933,7 +15028,7 @@ function notifyRequest(message) {
14933
15028
  if (!message || typeof message !== "object" || Array.isArray(message)) return void 0;
14934
15029
  const value = message;
14935
15030
  if (value.type !== "peerband:notify" || typeof value.id !== "string" || value.id.length > 128) return void 0;
14936
- return { id: value.id, text: value.text, paneId: value.paneId };
15031
+ return { id: value.id, text: value.text, paneId: value.paneId, channel: value.channel };
14937
15032
  }
14938
15033
  function startMockStatusCycle(adapter, env) {
14939
15034
  const interval = Number(env.PEERBAND_MOCK_STATUS_INTERVAL_MS);
@@ -15269,7 +15364,7 @@ var ControlUnavailable = class extends Error {
15269
15364
  reason;
15270
15365
  };
15271
15366
  async function requestNotify(note, env, timeoutMs = 8e3) {
15272
- return exchange({ command: "notify", text: note.text, ...note.paneId ? { paneId: note.paneId } : {} }, env, timeoutMs, true);
15367
+ return exchange({ command: "notify", text: note.text, ...note.paneId ? { paneId: note.paneId } : {}, ...note.channel ? { channel: note.channel } : {} }, env, timeoutMs, true);
15273
15368
  }
15274
15369
  async function exchange(payload, env, timeoutMs, typed = false) {
15275
15370
  const config = configHome({ env });
@@ -15860,7 +15955,7 @@ function mapFailure(error, serverUrl) {
15860
15955
  return new CliError(error.message, "Run `peerband login` again, or use `peerband login --grant GRANT`.");
15861
15956
  }
15862
15957
  }
15863
- var spec2 = {
15958
+ var spec3 = {
15864
15959
  name: "login",
15865
15960
  summary: "Connect this machine to your PeerBand account",
15866
15961
  usage: "peerband login [--name NAME] [--no-browser] [--server URL] [--herdr-plugin ask|install|skip]\n peerband login --grant GRANT [--name NAME] [--server URL]",
@@ -15913,7 +16008,7 @@ async function signIn(parsed, ctx) {
15913
16008
  }
15914
16009
 
15915
16010
  // src/cli/commands/logout.ts
15916
- var spec3 = {
16011
+ var spec4 = {
15917
16012
  name: "logout",
15918
16013
  summary: "Forget this machine's PeerBand credential",
15919
16014
  usage: "peerband logout",
@@ -15951,13 +16046,33 @@ function callingPane(env) {
15951
16046
  const pane = env.HERDR_PANE_ID;
15952
16047
  return typeof pane === "string" && PANE_ID2.test(pane) ? pane : void 0;
15953
16048
  }
15954
- async function notify(text2, json, ctx) {
16049
+ async function checkChannel(name, ctx) {
16050
+ const credentials = await requireCredentials(ctx);
16051
+ const channels = await fetchChannels(ctx, credentials);
16052
+ const channel = channels.find((candidate) => candidate.name === name);
16053
+ if (!channel) {
16054
+ const names = channels.map((candidate) => candidate.name);
16055
+ throw new CliError(
16056
+ `There is no channel named "${name}" for this machine. The note was not sent.`,
16057
+ names.length ? `Available channels: ${names.join(", ")}. See \`peerband channels\`.` : `This machine has no channels yet. The owner can add one in the dashboard (${dashboardUrl(credentials)} \u2192 Webhooks).`
16058
+ );
16059
+ }
16060
+ if (channel.state !== "active") {
16061
+ throw new CliError(
16062
+ `The channel "${name}" is ${stateLabel(channel.state)}, so it does not accept notes. The note was not sent.`,
16063
+ `The owner can fix it in the dashboard (${dashboardUrl(credentials)} \u2192 Webhooks), or send the note without --channel.`
16064
+ );
16065
+ }
16066
+ }
16067
+ async function notify(text2, json, ctx, channel) {
16068
+ if (channel !== void 0 && !CHANNEL_NAME.test(channel)) throw new UsageError(`"${sanitize(channel)}" is not a channel name.`, "Channel names are 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit. See `peerband channels`.");
15955
16069
  if (text2.trim().length === 0) throw new UsageError("The note is empty.", 'Pass a short note, for example `peerband notify "Migration finished, 3 tests failing"`.');
15956
16070
  if (codePoints(text2) > NOTE_MAX_CHARS) throw new UsageError(`The note is ${codePoints(text2)} characters; the limit is ${NOTE_MAX_CHARS}.`, "Shorten it to the result or the decision you need; leave details in a file or the agent output.");
16071
+ if (channel !== void 0) await checkChannel(channel, ctx);
15957
16072
  const paneId = callingPane(ctx.env);
15958
16073
  let reply;
15959
16074
  try {
15960
- reply = await requestNotify({ text: text2, ...paneId ? { paneId } : {} }, ctx.env);
16075
+ reply = await requestNotify({ text: text2, ...paneId ? { paneId } : {}, ...channel !== void 0 ? { channel } : {} }, ctx.env);
15961
16076
  } catch (error) {
15962
16077
  if (error instanceof ControlUnavailable && error.reason === "closed") {
15963
16078
  throw new CliError("The running relay does not support notes yet.", "Run `peerband update` to update the CLI and the Herdr plugin, which restarts the relay.");
@@ -15972,40 +16087,52 @@ async function notify(text2, json, ctx) {
15972
16087
  if (reply.error === "invalid" || reply.error === "invalid_argument") throw new UsageError(message, next);
15973
16088
  throw new CliError(message, next ?? "Check `peerband status` and try again.");
15974
16089
  }
16090
+ if (channel !== void 0 && reply.channel !== channel) {
16091
+ throw new CliError(
16092
+ reply.sent === true ? `The relay running on this machine is too old for channels, so the note was sent without one: to the dashboard and any webhooks that take all notes, not only to "${channel}".` : "The relay running on this machine is too old for channels. The note was not sent.",
16093
+ "Run `peerband update` to update the CLI and the Herdr plugin, which restarts the relay."
16094
+ );
16095
+ }
15975
16096
  if (reply.sent !== true) throw new CliError("The relay is not connected to PeerBand right now, so the note was not delivered.", "Check `peerband status`; send the note again once the relay shows Connected.");
15976
16097
  const agentId = typeof reply.agentId === "string" ? reply.agentId : null;
15977
16098
  if (json) {
15978
- ctx.out.print(JSON.stringify({ sent: true, agentId, eventId: typeof reply.eventId === "string" ? reply.eventId : null }, null, 2));
16099
+ ctx.out.print(JSON.stringify({ sent: true, agentId, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
15979
16100
  return 0;
15980
16101
  }
15981
16102
  const s = ctx.out.stdout;
15982
- ctx.out.print(`${s.green(symbols.ok)} Note sent to the machine owner${agentId ? s.dim(` (from agent ${sanitize(agentId)})`) : ""}.`);
16103
+ const target = channel !== void 0 ? `channel ${s.bold(channel)}` : "the machine owner";
16104
+ ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${agentId ? s.dim(` (from agent ${sanitize(agentId)})`) : ""}.`);
15983
16105
  return 0;
15984
16106
  }
15985
- var spec4 = {
16107
+ var spec5 = {
15986
16108
  name: "notify",
15987
16109
  summary: "Send a short note from an agent to the machine owner",
15988
- usage: 'peerband notify "<text>" [--json]',
15989
- description: "Sends a short note (1 to 1024 characters) through the running relay to the owner of this machine, for example when a long task finished or an agent is blocked on a decision. Run it from inside a Herdr pane and the note names the agent in that pane. The note goes to the owner only, never to people this machine is shared with. Control characters are removed and likely secrets are redacted (best effort), but do not put credentials or personal data in notes.",
15990
- options: [{ name: "json", type: "boolean", description: "Print a machine-readable result: {sent, agentId, eventId}." }],
16110
+ usage: 'peerband notify "<text>" [--channel NAME] [--json]',
16111
+ description: "Sends a short note (1 to 1024 characters) through the running relay to the owner of this machine, for example when a long task finished or an agent is blocked on a decision. Run it from inside a Herdr pane and the note names the agent in that pane. The note goes to the owner only, never to people this machine is shared with. Control characters are removed and likely secrets are redacted (best effort), but do not put credentials or personal data in notes.\n\nWithout --channel the note goes to the PeerBand dashboard and to every owner webhook that takes notes. With --channel NAME it still appears in the dashboard (marked with the channel name), but of the owner's webhooks only that one channel receives it (a webhook such as a Slack channel; see `peerband channels`). The channel is checked first: an unknown or inactive channel is an error and nothing is sent.",
16112
+ options: [
16113
+ { name: "channel", type: "string", valueName: "NAME", description: "Deliver the note to this channel instead of every webhook that takes notes; it still shows in the dashboard (see `peerband channels`)." },
16114
+ { name: "json", type: "boolean", description: "Print a machine-readable result: {sent, agentId, eventId}, plus channel with --channel." }
16115
+ ],
15991
16116
  positionals: { name: "text", max: 64 },
15992
16117
  examples: [
15993
16118
  ['peerband notify "Migration finished, 3 tests failing"', "Report a result when a long task ends"],
15994
16119
  ['peerband notify "Blocked: should I drop the legacy table?"', "Ask the owner for a decision"],
16120
+ ['peerband notify --channel deploys "Release 2.3 is live"', "Send to one channel (an owner webhook)"],
15995
16121
  ['peerband notify --json "Build green"', "For scripts: prints the event id"]
15996
16122
  ],
15997
16123
  notes: [
15998
16124
  "Needs the relay (`peerband relay`) to be running and connected; nothing is queued while it is offline.",
16125
+ "--channel also needs `peerband login`: the channel is checked with PeerBand before the note is sent.",
15999
16126
  "Several words without quotes are joined with spaces."
16000
16127
  ],
16001
16128
  async run(parsed, ctx) {
16002
16129
  if (parsed.positionals.length === 0) throw new UsageError("Missing the note text.", 'Usage: peerband notify "<text>"');
16003
- return notify(parsed.positionals.join(" "), flag(parsed, "json"), ctx);
16130
+ return notify(parsed.positionals.join(" "), flag(parsed, "json"), ctx, str(parsed, "channel"));
16004
16131
  }
16005
16132
  };
16006
16133
 
16007
16134
  // src/cli/commands/relay.ts
16008
- var spec5 = {
16135
+ var spec6 = {
16009
16136
  name: "relay",
16010
16137
  summary: "Open or focus the PeerBand Relay tab in Herdr",
16011
16138
  usage: "peerband relay",
@@ -16089,7 +16216,7 @@ async function skillSetup(ctx, mode) {
16089
16216
  ctx.out.print(s.dim(`Add it later with \`${SKILL_COMMAND}\`.`));
16090
16217
  }
16091
16218
  }
16092
- var spec6 = {
16219
+ var spec7 = {
16093
16220
  name: "skill",
16094
16221
  summary: "Install or update the PeerBand skill for your coding agents",
16095
16222
  usage: "peerband skill [--copy] [--force]",
@@ -16136,8 +16263,8 @@ async function existingLogin(parsed, ctx) {
16136
16263
  return void 0;
16137
16264
  }
16138
16265
  }
16139
- var loginOptions = spec2.options.filter((option) => option.name !== "herdr-plugin");
16140
- var spec7 = {
16266
+ var loginOptions = spec3.options.filter((option) => option.name !== "herdr-plugin");
16267
+ var spec8 = {
16141
16268
  name: "setup",
16142
16269
  summary: "Set up this machine: log in, add the Herdr plugin and the agent skill, open the relay",
16143
16270
  usage: "peerband setup [--name NAME] [--no-browser] [--server URL] [--herdr-plugin ask|install|skip] [--skill ask|install|skip] [--no-relay]\n peerband setup --grant GRANT [...]",
@@ -16199,27 +16326,7 @@ var spec7 = {
16199
16326
  // src/cli/commands/share.ts
16200
16327
  var roleLabel = (role) => role === "message" ? "read + message" : "read only";
16201
16328
  var MAX_EXPIRY_DAYS = 30;
16202
- async function call(ctx, credentials, method, path, body) {
16203
- const url = new URL(path, enrollmentBase(credentials.serverUrl));
16204
- let response;
16205
- try {
16206
- response = await ctx.fetch(url, {
16207
- method,
16208
- headers: { authorization: `Bearer ${credentials.credential}`, ...body ? { "content-type": "application/json" } : {} },
16209
- ...body ? { body: JSON.stringify(body) } : {},
16210
- signal: AbortSignal.timeout(15e3)
16211
- });
16212
- } catch (error) {
16213
- throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
16214
- }
16215
- if (response.status === 204) return null;
16216
- const parsed = await response.json().catch(() => ({}));
16217
- if (response.ok) return parsed;
16218
- const detail = typeof parsed.detail === "string" ? parsed.detail : `HTTP ${response.status}`;
16219
- 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.");
16220
- if (response.status === 404 && path.endsWith("/sharing") && method === "GET") throw new CliError("This PeerBand server doesn't support sharing yet.");
16221
- throw new CliError(sanitize(detail));
16222
- }
16329
+ var call = (ctx, credentials, method, path, body) => installationCall(ctx, credentials, method, path, body, path.endsWith("/sharing") && method === "GET" ? "This PeerBand server doesn't support sharing yet." : void 0);
16223
16330
  function expiryDays(raw) {
16224
16331
  if (raw === void 0) return void 0;
16225
16332
  const days = Number(raw);
@@ -16241,7 +16348,7 @@ async function create(ctx, credentials, role, days, json) {
16241
16348
  ctx.out.print(s.dim("They sign in to PeerBand (or create an account) and accept. See who has access with `peerband share list`."));
16242
16349
  return 0;
16243
16350
  }
16244
- async function list(ctx, credentials, json) {
16351
+ async function list2(ctx, credentials, json) {
16245
16352
  const sharing = await call(ctx, credentials, "GET", "/api/installation/sharing");
16246
16353
  if (json) {
16247
16354
  ctx.out.print(JSON.stringify(sharing, null, 2));
@@ -16270,7 +16377,7 @@ async function revoke(ctx, credentials, id) {
16270
16377
  ctx.out.print(`${ctx.out.stdout.green(symbols.ok)} ${id.startsWith("acc_") ? "Access removed." : "Link cancelled."}`);
16271
16378
  return 0;
16272
16379
  }
16273
- var spec8 = {
16380
+ var spec9 = {
16274
16381
  name: "share",
16275
16382
  summary: "Share this machine with another PeerBand user",
16276
16383
  usage: "peerband share [--message] [--expires DAYS] [--json]\n peerband share list [--json]\n peerband share revoke ID",
@@ -16298,7 +16405,7 @@ var spec8 = {
16298
16405
  throw new UsageError("--message and --expires only apply when creating a link.", "Run `peerband share --message` to create one.");
16299
16406
  const days = expiryDays(str(parsed, "expires"));
16300
16407
  const credentials = await requireCredentials(ctx);
16301
- if (action === "list") return list(ctx, credentials, json);
16408
+ if (action === "list") return list2(ctx, credentials, json);
16302
16409
  if (action === "revoke") return revoke(ctx, credentials, id);
16303
16410
  return create(ctx, credentials, flag(parsed, "message") ? "message" : "read", days, json);
16304
16411
  }
@@ -16397,7 +16504,7 @@ function renderHuman(report2, ctx) {
16397
16504
  const width = Math.max(...rows.map(([key]) => key.length));
16398
16505
  for (const [key, value] of rows) ctx.out.print(`${s.bold(key.padEnd(width))} ${value}`);
16399
16506
  }
16400
- var spec9 = {
16507
+ var spec10 = {
16401
16508
  name: "status",
16402
16509
  summary: "Show login, relay and Herdr status",
16403
16510
  usage: "peerband status [--json]",
@@ -16513,7 +16620,7 @@ function toStderr(ctx) {
16513
16620
  function pluginSummary(check) {
16514
16621
  return { herdrFound: check.found, installed: check.installed, source: check.source, problems: check.problems.map((problem) => problem.message) };
16515
16622
  }
16516
- var spec10 = {
16623
+ var spec11 = {
16517
16624
  name: "update",
16518
16625
  summary: "Update the CLI and the Herdr plugin to the latest release",
16519
16626
  usage: "peerband update [--check] [--yes] [--json]",
@@ -16593,19 +16700,19 @@ var spec10 = {
16593
16700
  }
16594
16701
  }
16595
16702
  const exec2 = ctx.exec ?? execProgram;
16596
- const spec11 = `peerband@${latest}`;
16597
- log(`Installing ${spec11} with npm\u2026`);
16703
+ const spec12 = `peerband@${latest}`;
16704
+ log(`Installing ${spec12} with npm\u2026`);
16598
16705
  const forward = (text2) => ctx.stderr.write(text2);
16599
- const npm = await exec2("npm", ["install", "-g", spec11], { timeoutMs: 6e5, env: ctx.env, onStdout: forward, onStderr: forward });
16706
+ const npm = await exec2("npm", ["install", "-g", spec12], { timeoutMs: 6e5, env: ctx.env, onStdout: forward, onStderr: forward });
16600
16707
  if (npm.code !== 0) {
16601
16708
  const permission = /EACCES|EPERM|permission denied/i.test(`${npm.stderr}${npm.stdout}`);
16602
16709
  throw new CliError(
16603
- npm.notFound ? "npm was not found on PATH." : `npm install -g ${spec11} failed (exit code ${npm.code}).`,
16604
- permission ? `npm could not write to its global folder. Fix its permissions (https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally) or run \`npm install -g ${spec11}\` as an administrator, then \`peerband update\`.` : `Check the npm output above, run \`npm install -g ${spec11}\` yourself, then \`peerband update\`.`
16710
+ npm.notFound ? "npm was not found on PATH." : `npm install -g ${spec12} failed (exit code ${npm.code}).`,
16711
+ permission ? `npm could not write to its global folder. Fix its permissions (https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally) or run \`npm install -g ${spec12}\` as an administrator, then \`peerband update\`.` : `Check the npm output above, run \`npm install -g ${spec12}\` yourself, then \`peerband update\`.`
16605
16712
  );
16606
16713
  }
16607
16714
  const entry = join10(install.npmRoot, PACKAGE, "dist", "peerband.mjs");
16608
- if (!existsSync2(entry)) throw new CliError(`npm finished, but the new CLI is not at ${entry}.`, `Run \`npm install -g ${spec11}\` yourself, then \`peerband update\`.`);
16715
+ if (!existsSync2(entry)) throw new CliError(`npm finished, but the new CLI is not at ${entry}.`, `Run \`npm install -g ${spec12}\` yourself, then \`peerband update\`.`);
16609
16716
  log(`${s.green(symbols.ok)} Installed peerband ${latest}.`);
16610
16717
  report2.action = "updated";
16611
16718
  if (skillInstalled(ctx)) {
@@ -16642,7 +16749,7 @@ var spec10 = {
16642
16749
  };
16643
16750
 
16644
16751
  // src/cli/registry.ts
16645
- var commands = [spec7, spec2, spec3, spec9, spec10, spec5, spec6, spec8, spec4, spec];
16752
+ var commands = [spec8, spec3, spec4, spec10, spec11, spec6, spec7, spec9, spec5, spec, spec2];
16646
16753
  var herdrCommands = [installSpec, uninstallSpec];
16647
16754
  function lookup(words) {
16648
16755
  const [first, second] = words;
@@ -16695,7 +16802,10 @@ function rootHelp(s, version) {
16695
16802
  "3. peerband relay Open the relay tab and connect"
16696
16803
  ]),
16697
16804
  ...section(s, "Updating", ["peerband update Update the CLI and the Herdr plugin together (--check to only look)"]),
16698
- ...section(s, "From an agent", ['peerband notify "<text>" Send the machine owner a short note (task done, blocked, result)']),
16805
+ ...section(s, "From an agent", [
16806
+ 'peerband notify "<text>" Send the machine owner a short note (task done, blocked, result)',
16807
+ " --channel NAME Send it to one of the owner's channels instead (see peerband channels)"
16808
+ ]),
16699
16809
  ...section(s, "Exit codes", ["0 ok 1 failure 2 usage error 3 not logged in 130 interrupted"]),
16700
16810
  "",
16701
16811
  `Run ${s.cyan("peerband <command> --help")} for details. Docs: https://peerband.com`
@@ -16703,20 +16813,20 @@ function rootHelp(s, version) {
16703
16813
  return `${lines.join("\n")}
16704
16814
  `;
16705
16815
  }
16706
- function commandHelp(s, spec11) {
16816
+ function commandHelp(s, spec12) {
16707
16817
  const lines = [
16708
- `${s.bold(`peerband ${spec11.name}`)} ${spec11.summary}`,
16709
- ...section(s, "Usage", [spec11.usage]),
16818
+ `${s.bold(`peerband ${spec12.name}`)} ${spec12.summary}`,
16819
+ ...section(s, "Usage", [spec12.usage]),
16710
16820
  "",
16711
- ...spec11.description.split("\n").map((line) => ` ${line}`),
16712
- ...section(s, "Options", table(optionRows(spec11.options), s)),
16821
+ ...spec12.description.split("\n").map((line) => ` ${line}`),
16822
+ ...section(s, "Options", table(optionRows(spec12.options), s)),
16713
16823
  ...section(
16714
16824
  s,
16715
16825
  "Examples",
16716
- spec11.examples.flatMap(([command, comment]) => [`${s.cyan(command)}`, ` ${s.dim(comment)}`])
16826
+ spec12.examples.flatMap(([command, comment]) => [`${s.cyan(command)}`, ` ${s.dim(comment)}`])
16717
16827
  )
16718
16828
  ];
16719
- if (spec11.notes?.length) lines.push(...section(s, "Notes", spec11.notes));
16829
+ if (spec12.notes?.length) lines.push(...section(s, "Notes", spec12.notes));
16720
16830
  return `${lines.join("\n")}
16721
16831
  `;
16722
16832
  }
@@ -16734,7 +16844,7 @@ function herdrGroupHelp(s) {
16734
16844
  }
16735
16845
 
16736
16846
  // src/cli/cli.ts
16737
- var VERSION = true ? "0.1.5" : "0.0.0-dev";
16847
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
16738
16848
  function createContext(overrides = {}) {
16739
16849
  const env = overrides.env ?? process.env;
16740
16850
  const stdout = overrides.stdout ?? process.stdout;
@@ -16755,9 +16865,9 @@ function resolveHelpTarget(words, ctx) {
16755
16865
  const s = ctx.out.stdout;
16756
16866
  if (words.length === 0) return rootHelp(s, ctx.version);
16757
16867
  if (words[0] === "herdr" && words.length === 1) return herdrGroupHelp(s);
16758
- const spec11 = lookup(words);
16759
- if (!spec11) throw unknownCommand(words.join(" "));
16760
- return commandHelp(s, spec11);
16868
+ const spec12 = lookup(words);
16869
+ if (!spec12) throw unknownCommand(words.join(" "));
16870
+ return commandHelp(s, spec12);
16761
16871
  }
16762
16872
  function unknownCommand(name) {
16763
16873
  const near = suggest(name, topLevelNames());
@@ -16800,14 +16910,14 @@ async function run2(argv, ctx = createContext()) {
16800
16910
  words = [first, second];
16801
16911
  args = others;
16802
16912
  }
16803
- const spec11 = lookup(words);
16804
- if (!spec11) throw unknownCommand(first);
16805
- const parsed = parseArgs(spec11, args);
16913
+ const spec12 = lookup(words);
16914
+ if (!spec12) throw unknownCommand(first);
16915
+ const parsed = parseArgs(spec12, args);
16806
16916
  if (parsed.values.help) {
16807
- ctx.out.print(commandHelp(ctx.out.stdout, spec11).trimEnd());
16917
+ ctx.out.print(commandHelp(ctx.out.stdout, spec12).trimEnd());
16808
16918
  return 0;
16809
16919
  }
16810
- return await spec11.run(parsed, ctx);
16920
+ return await spec12.run(parsed, ctx);
16811
16921
  } catch (error) {
16812
16922
  if (error instanceof UsageError) {
16813
16923
  ctx.out.fail(error.message, error.hint);