peerband 0.3.0 → 0.3.2

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/README.md CHANGED
@@ -174,24 +174,28 @@ The plugin adds a persistent tab titled `PeerBand Relay [On]` or `[Off]` that sh
174
174
 
175
175
  ## herdr-core and the Herdr desktop app
176
176
 
177
- [herdr-core](https://github.com/herdrdev/herdr-core) (`hc`) runs terminals and agents that keep running after you close the window; the Herdr desktop app draws spaces, tabs and panes on top of it. herdr-core has no plugin tab, so for it the relay runs in the background:
177
+ [herdr-core](https://github.com/herdrdev/herdr-core) (`hc`) runs terminals and agents that keep running after you close the window; the Herdr desktop app draws spaces, tabs and panes on top of it.
178
+
179
+ One relay serves both. The Relay tab in the Herdr terminal app also lists the agents in herdr-core whenever a core is running, so if you use the terminal app you need nothing else. Without the terminal app, run the relay in the background, since herdr-core has no plugin tab:
178
180
 
179
181
  ```sh
180
182
  peerband relay --core # connect this machine's herdr-core agents
181
- peerband status # Relay: Connected (herdr-core, in the background)
183
+ peerband status # Relay: Connected (in the background, for herdr-core)
182
184
  peerband relay --stop # disconnect
183
185
  ```
184
186
 
185
- `peerband setup` starts it for you when herdr-core is installed and the Herdr terminal app is not. It keeps running when you close the desktop app or a terminal, and it reconnects when the core restarts. It does not start again by itself after you log out or restart the computer: run `peerband relay --core` again. One relay serves one runtime per machine, so stop a Herdr Relay tab before starting the herdr-core relay.
187
+ `peerband setup` starts it for you when herdr-core is installed and the Herdr terminal app is not. It keeps running when you close the desktop app or a terminal, and it reconnects when the core restarts. It does not start again by itself after you log out or restart the computer: run `peerband relay --core` again. The background relay serves the Herdr terminal app too whenever that runs, so one relay covers both whichever way you start it; `peerband relay --core` while a Relay tab is open just says herdr-core is already served.
186
188
 
187
189
  How it works:
188
190
 
191
+ - The relay connects to a core that is already running (the desktop app starts one, and so do commands such as `hc run`) and never starts one itself. When the core stops, its agents leave the list; they come back within about 30 seconds of it starting again.
189
192
  - The connector talks to the core through `hc connect` (JSON-RPC over stdin and stdout), so it uses the same core, socket and named pipe as `hc` itself, including `HC_SOCKET`. It needs `hc` on `PATH`, `HC_BIN`, or `herdrCore.binary` in `connector.json`.
190
193
  - An agent is a live terminal on this machine whose program reports its status through OSC 7501, the way herdr-core and the desktop app see it. Plain shells are not agents. Terminals on machines your core added (`box/t3`) are not shown: run a relay on that machine.
191
194
  - Status changes arrive from the core's event stream (`events.subscribe`), never from reading the screen.
192
195
  - Spaces and tabs come from the desktop app's layout. Agents that no tab shows, such as ones started with `hc run --bg`, are grouped under **Background**.
193
196
  - Messages are typed into the agent's terminal with `terminal.send`, which waits for you to finish an unsent draft (up to a minute). Core refuses to type into a blocked agent. Terminal addresses (`t7`) are never reused, and the connector checks that the same program still runs there right before it sends.
194
- - `peerband notify` inside a core terminal names its agent through `HC_TERMINAL_ID`.
197
+ - `peerband notify` inside a core terminal names its agent through `HC_TERMINAL_ID`, even when the core was started from a Herdr pane and its terminals inherited that pane's `HERDR_PANE_ID`.
198
+ - In `list_environment`, each workspace carries `runtime` (`herdr` or `herdr-core`) and `readOnly`.
195
199
  - The dashboard shows the layout but cannot change it yet: creating, renaming and closing spaces, tabs and panes is a Herdr terminal app feature for now. Reading a plain shell's output works.
196
200
 
197
201
  ## Commands
@@ -203,8 +207,8 @@ How it works:
203
207
  | `peerband logout` | Stop a running relay, close its tab, delete the local relay state and the local credential. Does not revoke it on the server |
204
208
  | `peerband status` | Show login, relay, messaging and Herdr state, including whether the Herdr plugin is the right one. `--json` for machine-readable output |
205
209
  | `peerband update` | Update the CLI from npm and then the Herdr plugin to match, restarting the relay if it was running. Already up to date: checks the plugin and repairs it. Flags: `--check` (only report), `--yes`, `--json` |
206
- | `peerband connect` | Run the connector in the foreground. Flags: `--runtime herdr\|herdr-core\|mock`, `--read-only`, `--config PATH`, `--server URL` (`--enable-writes` is still accepted but redundant) |
207
- | `peerband relay` | Open or focus the Relay tab in Herdr. If the plugin is missing the wrong version, a local checkout, or points at another config directory, it offers to repair it first. `--core` runs the relay in the background for herdr-core instead; `--stop` stops whichever relay is running |
210
+ | `peerband connect` | Run the connector in the foreground. Flags: `--runtime auto\|herdr\|herdr-core\|mock`, `--read-only`, `--config PATH`, `--server URL` (`--enable-writes` is still accepted but redundant) |
211
+ | `peerband relay` | Open or focus the Relay tab in Herdr. If the plugin is missing the wrong version, a local checkout, or points at another config directory, it offers to repair it first. `--core` runs the relay in the background instead, for herdr-core without the Herdr terminal app; `--stop` stops whichever relay is running |
208
212
  | `peerband skill` | Install or update the PeerBand agent skill for every coding agent on this machine (through `npx skills add`, falling back to a copy). Keeps a skill you edited unless `--force`; `--copy` skips npx |
209
213
  | `peerband share` | Create a single-use invite link that shares this machine with another PeerBand user (read only; `--message` also allows messages; `--expires DAYS`, default 7). `share list` shows who has access and unused links; `share revoke ID` removes access or cancels a link |
210
214
  | `peerband notify "<text>"` | From inside a Herdr pane or a herdr-core terminal: send the machine owner a short note (1 to 1024 characters) through the running relay, for example when a long task finished or an agent is blocked on a decision. The note names the agent in that pane. `--channel NAME` sends it to one of your channels instead, such as `telegram` (see below). `--json` for machine-readable output |
@@ -226,7 +230,7 @@ Optional `connector.json`:
226
230
 
227
231
  ```json
228
232
  {
229
- "runtime": "herdr",
233
+ "runtime": "auto",
230
234
  "allowedAgents": ["claude"],
231
235
  "allowedWorkspaces": ["my-project"],
232
236
  "enableWrites": false,
@@ -245,7 +249,7 @@ Optional `connector.json`:
245
249
  }
246
250
  ```
247
251
 
248
- All fields are optional. `enableWrites` defaults to `true`; set it to `false` to make this machine read-only (the same as `peerband connect --read-only`; it also applies to the Relay tab). `allowedAgents` and `allowedWorkspaces` restrict what MCP clients can see; `stateDirectory` moves the receipt store (default `state/` in the config home). The `herdr` block is only needed when Herdr is not on `PATH` or you target a specific session. `runtime` (`herdr` or `herdr-core`) chooses what the connector serves when neither `--runtime` nor `PEERBAND_RUNTIME` is set; `peerband relay --core` always serves herdr-core. The `herdrCore` block is only needed when `hc` is not on `PATH` (the connector also looks in the installer's default folder).
252
+ All fields are optional. `enableWrites` defaults to `true`; set it to `false` to make this machine read-only (the same as `peerband connect --read-only`; it also applies to the Relay tab). `allowedAgents` and `allowedWorkspaces` restrict what MCP clients can see; `stateDirectory` moves the receipt store (default `state/` in the config home). The `herdr` block is only needed when Herdr is not on `PATH` or you target a specific session. `runtime` chooses what the connector serves when neither `--runtime` nor `PEERBAND_RUNTIME` is set: `auto` (the default: the Herdr terminal app, plus herdr-core whenever a core runs), `herdr` (the terminal app only) or `herdr-core` (herdr-core only, starting a core if none runs). `peerband relay --core` always runs `auto`. The `herdrCore` block is only needed when `hc` is not on `PATH` (the connector also looks in the installer's default folder).
249
253
 
250
254
  ## Agent events and notes
251
255
 
package/dist/peerband.mjs CHANGED
@@ -12587,7 +12587,7 @@ async function deleteCredentials(path = credentialsPath()) {
12587
12587
 
12588
12588
  // src/core/connector-config.ts
12589
12589
  import { readFile as readFile3 } from "node:fs/promises";
12590
- var RUNTIMES = ["herdr", "herdr-core"];
12590
+ var RUNTIMES = ["auto", "herdr", "herdr-core"];
12591
12591
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12592
12592
  function rejectUnknown(record, allowed, where2) {
12593
12593
  const unknown = Object.keys(record).find((key2) => !allowed.includes(key2));
@@ -13290,7 +13290,7 @@ var ConnectorEvents = class {
13290
13290
  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.");
13291
13291
  const text2 = cleanNote(input.text);
13292
13292
  const channel = noteChannel(input.channel);
13293
- const agentId2 = input.agentId !== void 0 ? await this.explicitAgent(input.agentId) : await this.resolveAgent(input.paneId) ?? await this.resolveAgent(input.terminalId);
13293
+ const agentId2 = input.agentId !== void 0 ? await this.explicitAgent(input.agentId) : await this.resolveAgent(input.terminalId) ?? await this.resolveAgent(input.paneId);
13294
13294
  const echo = channel ? { channel } : {};
13295
13295
  if (!this.send) return { sent: false, agentId: agentId2, ...echo };
13296
13296
  this.refillNotes();
@@ -13514,6 +13514,8 @@ function failureDetail(result) {
13514
13514
  const parsed = JSON.parse(text2);
13515
13515
  detail = parsed.error?.message || parsed.message || text2;
13516
13516
  } catch {
13517
+ const errorLine = text2.split(/\r?\n/).reverse().find((line) => /^\s*error\b/i.test(line));
13518
+ if (errorLine) detail = errorLine.trim();
13517
13519
  }
13518
13520
  return detail.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, 400);
13519
13521
  }
@@ -15986,11 +15988,12 @@ function parseLayout(value) {
15986
15988
  }
15987
15989
 
15988
15990
  // src/runtime-herdr-core/rpc.ts
15989
- import { spawn as spawn2 } from "node:child_process";
15991
+ import { execFile as execFile5, spawn as spawn2 } from "node:child_process";
15990
15992
  import { existsSync as existsSync2 } from "node:fs";
15991
15993
  import { homedir as homedir4 } from "node:os";
15992
15994
  import { join as join7 } from "node:path";
15993
15995
  import { createInterface } from "node:readline";
15996
+ import { PassThrough } from "node:stream";
15994
15997
  var CoreRpcError = class extends Error {
15995
15998
  constructor(kind, message, hint) {
15996
15999
  super(message);
@@ -16031,12 +16034,13 @@ var CoreConnection = class {
16031
16034
  this.done = stream.closed.then((error) => {
16032
16035
  this.open = false;
16033
16036
  lines.close();
16034
- const reason = error && error.code === "ENOENT" ? new ConnectError("runtime_unavailable", "herdr-core (hc) was not found.", "Install herdr-core (https://github.com/herdrdev/herdr-core) or set herdrCore.binary in connector.json.") : new ConnectError("runtime_unavailable", "The herdr-core connection closed.", "Check that herdr-core is running (`hc server status`), then retry.");
16037
+ const never = error instanceof ConnectError;
16038
+ const reason = never ? error : error && error.code === "ENOENT" ? new ConnectError("runtime_unavailable", "herdr-core (hc) was not found.", "Install herdr-core (https://github.com/herdrdev/herdr-core) or set herdrCore.binary in connector.json.") : new ConnectError("runtime_unavailable", "The herdr-core connection closed.", "Check that herdr-core is running (`hc server status`), then retry.");
16035
16039
  this.closeReason = reason;
16036
16040
  for (const [id, request] of this.pending) {
16037
16041
  clearTimeout(request.timer);
16038
16042
  this.pending.delete(id);
16039
- request.reject(request.method === "terminal.send" ? new ConnectError("delivery_unknown", "herdr-core closed before confirming the message.", "Read the agent output before deciding whether to send it again.") : reason);
16043
+ request.reject(request.method === "terminal.send" && !never ? new ConnectError("delivery_unknown", "herdr-core closed before confirming the message.", "Read the agent output before deciding whether to send it again.") : reason);
16040
16044
  }
16041
16045
  });
16042
16046
  }
@@ -16126,6 +16130,56 @@ var CoreRpcClient = class {
16126
16130
  }
16127
16131
  }
16128
16132
  };
16133
+ function findCoreBinary(explicit, env = process.env) {
16134
+ if (explicit) return explicit;
16135
+ if (env.HC_BIN) return env.HC_BIN;
16136
+ const binary = resolveCoreBinary(void 0, env);
16137
+ if (binary !== "hc") return binary;
16138
+ const onPath = (env.PATH ?? env.Path ?? "").split(process.platform === "win32" ? ";" : ":").some((dir) => dir && (existsSync2(join7(dir, "hc")) || existsSync2(join7(dir, "hc.exe"))));
16139
+ return onPath ? "hc" : void 0;
16140
+ }
16141
+ function coreRunning(binary, timeoutMs = 5e3) {
16142
+ return new Promise((resolve6) => {
16143
+ execFile5(binary, ["server", "status", "--json"], { timeout: timeoutMs, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout) => {
16144
+ if (error) return resolve6(false);
16145
+ try {
16146
+ const status = JSON.parse(String(stdout));
16147
+ resolve6(!status.error && typeof status.core === "object" && status.core !== null);
16148
+ } catch {
16149
+ resolve6(false);
16150
+ }
16151
+ });
16152
+ });
16153
+ }
16154
+ function attachOnlyStream(binary, running = coreRunning, spawnStream = spawnCoreStream(binary)) {
16155
+ return () => {
16156
+ const input = new PassThrough();
16157
+ const output = new PassThrough();
16158
+ let inner;
16159
+ let done = false;
16160
+ let finish2;
16161
+ const closed = new Promise((resolve6) => {
16162
+ finish2 = (error) => {
16163
+ if (done) return;
16164
+ done = true;
16165
+ output.end();
16166
+ resolve6(error);
16167
+ };
16168
+ });
16169
+ void running(binary).then((up) => {
16170
+ if (done) return;
16171
+ if (!up) return finish2(new ConnectError("runtime_unavailable", "herdr-core is not running.", "Open the Herdr desktop app or run `hc server start`."));
16172
+ inner = spawnStream();
16173
+ input.pipe(inner.input);
16174
+ inner.output.on("data", (chunk) => output.write(chunk));
16175
+ void inner.closed.then(finish2);
16176
+ }, () => finish2(new ConnectError("runtime_unavailable", "herdr-core is not running.", "Open the Herdr desktop app or run `hc server start`.")));
16177
+ return { input, output, closed, close: () => {
16178
+ if (inner) inner.close();
16179
+ else finish2(void 0);
16180
+ } };
16181
+ };
16182
+ }
16129
16183
 
16130
16184
  // src/runtime-herdr-core/adapter.ts
16131
16185
  var LOCAL_ADDRESS2 = /^t[0-9]{1,12}$/;
@@ -16133,11 +16187,16 @@ var PROTOCOL_GENERATION = 1;
16133
16187
  var REQUIRED_METHODS = ["terminal.list", "terminal.get", "terminal.read", "terminal.send", "events.subscribe", "doc.get"];
16134
16188
  var LIST_EVENTS = /* @__PURE__ */ new Set(["created", "lost", "restarted", "finished", "removed"]);
16135
16189
  var SEND_TIMEOUT_MS = 9e4;
16190
+ var READ_SLACK_LINES = 120;
16191
+ function foldBlankRows(text2) {
16192
+ return text2.replace(/[ \t]+(?=\r?\n|$)/g, "").replace(/(?:\r?\n){3,}/g, "\n\n").replace(/(?:\r?\n)+$/, "");
16193
+ }
16136
16194
  var APP_KINDS = { "claude-code": "claude", "cursor-agent": "cursor", "github-copilot": "copilot", "grok-build": "grok" };
16137
16195
  var HerdrCoreAdapter = class {
16138
16196
  constructor(options = {}) {
16139
16197
  this.options = options;
16140
- this.factory = options.streamFactory ?? spawnCoreStream(resolveCoreBinary(options.binary));
16198
+ const binary = resolveCoreBinary(options.binary);
16199
+ this.factory = options.streamFactory ?? (options.attachOnly ? attachOnlyStream(binary) : spawnCoreStream(binary));
16141
16200
  this.timeoutMs = options.timeoutMs ?? 1e4;
16142
16201
  this.client = new CoreRpcClient(this.factory, this.timeoutMs);
16143
16202
  this.machineId = options.machineId ?? createHash5("sha256").update(`${process.platform}:${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "local"}`).digest("hex").slice(0, 24);
@@ -16150,6 +16209,7 @@ var HerdrCoreAdapter = class {
16150
16209
  };
16151
16210
  }));
16152
16211
  this.settleMs = options.settleMs ?? 150;
16212
+ this.nudgeMs = options.nudgeMs ?? 400;
16153
16213
  }
16154
16214
  options;
16155
16215
  client;
@@ -16173,6 +16233,8 @@ var HerdrCoreAdapter = class {
16173
16233
  wake;
16174
16234
  sleep;
16175
16235
  settleMs;
16236
+ nudgeMs;
16237
+ methods = /* @__PURE__ */ new Set();
16176
16238
  getCapabilities() {
16177
16239
  return { readOutput: true, sendMessage: true, reason: "Messages go to the agent's terminal address, which herdr-core never reuses. PeerBand checks that the same program still runs there right before sending." };
16178
16240
  }
@@ -16255,9 +16317,9 @@ var HerdrCoreAdapter = class {
16255
16317
  }
16256
16318
  async read(address, options) {
16257
16319
  const lines = clampInteger2(options.lines, 80, 1, 500);
16258
- const result = await this.call("terminal.read", { terminal: address, lines });
16320
+ const result = await this.call("terminal.read", { terminal: address, lines: Math.min(500, lines + READ_SLACK_LINES) });
16259
16321
  if (!result || typeof result.text !== "string") throw schemaMismatch2("terminal.read returned no text");
16260
- const text2 = result.text.replace(/(?:[ \t]*\r?\n)+[ \t]*$/, "");
16322
+ const text2 = foldBlankRows(result.text);
16261
16323
  const output = sanitizeOutput(text2, { ...options, lines, bytes: clampInteger2(options.bytes, 16384, 1, 32768) });
16262
16324
  const visibleOnly = result.how === "screen" && typeof result.why === "string";
16263
16325
  return { ...output, ...visibleOnly ? { source: "visible" } : {}, truncated: visibleOnly || output.truncated || result.complete === false, observedAt: (/* @__PURE__ */ new Date()).toISOString(), untrusted: true };
@@ -16278,6 +16340,24 @@ var HerdrCoreAdapter = class {
16278
16340
  }
16279
16341
  const result = await this.call("terminal.send", { terminal: live.terminal.address, text: message }, SEND_TIMEOUT_MS);
16280
16342
  if (!result || typeof result !== "object" || typeof result.turn !== "number") throw new ConnectError("delivery_unknown", "herdr-core answered the message with an unexpected result.", "Read the agent output before deciding whether to send it again.");
16343
+ await this.nudgeUnsubmitted(live, result);
16344
+ }
16345
+ /**
16346
+ * Codex reads a long paste followed at once by Enter as part of the paste, so the message stays in its input box
16347
+ * (core reports `started: false`). Every relayed message is long because of its sender line. Press Enter once more
16348
+ * when the agent was not busy and still has not started. An extra Enter on an empty prompt does nothing.
16349
+ */
16350
+ async nudgeUnsubmitted(live, result) {
16351
+ if (result.started !== false || result.status === "working" || !this.methods.has("terminal.keys")) return;
16352
+ await new Promise((resolve6) => setTimeout(resolve6, this.nudgeMs));
16353
+ try {
16354
+ const now2 = await this.call("terminal.get", { terminal: live.terminal.address });
16355
+ if (!isTerminal(now2) || now2.state !== "live" || identityFingerprint2(this.coreId, now2) !== live.fingerprint) return;
16356
+ const state = now2.status?.state;
16357
+ if (state === "working" || state === "blocked" || state === "error") return;
16358
+ await this.call("terminal.keys", { terminal: live.terminal.address, keys: ["enter"] });
16359
+ } catch {
16360
+ }
16281
16361
  }
16282
16362
  /** The layout as the dashboard shows it. Read only: herdr-core spaces and tabs belong to the desktop app. */
16283
16363
  async listEnvironment() {
@@ -16341,6 +16421,7 @@ var HerdrCoreAdapter = class {
16341
16421
  async watch(log) {
16342
16422
  let delay = 1e3;
16343
16423
  let announced = false;
16424
+ let connected = false;
16344
16425
  while (!this.stopped) {
16345
16426
  const connection = new CoreConnection(this.factory(), (message) => this.onNotification(message));
16346
16427
  this.stream = connection;
@@ -16351,6 +16432,7 @@ var HerdrCoreAdapter = class {
16351
16432
  log("Watching herdr-core for agent status changes.");
16352
16433
  announced = true;
16353
16434
  }
16435
+ connected = true;
16354
16436
  this.scheduleRefresh(0);
16355
16437
  await connection.done;
16356
16438
  } catch {
@@ -16359,7 +16441,11 @@ var HerdrCoreAdapter = class {
16359
16441
  }
16360
16442
  if (this.stopped) break;
16361
16443
  if (Date.now() - startedAt > 6e4) delay = 1e3;
16362
- log("herdr-core event stream closed; reconnecting.");
16444
+ if (connected) {
16445
+ log("herdr-core event stream closed; reconnecting.");
16446
+ this.emit({ kind: "agents_changed" });
16447
+ }
16448
+ connected = false;
16363
16449
  await this.sleep(delay);
16364
16450
  delay = Math.min(delay * 2, 3e4);
16365
16451
  }
@@ -16420,6 +16506,7 @@ var HerdrCoreAdapter = class {
16420
16506
  if (!hello || hello.generation !== PROTOCOL_GENERATION) throw new ConnectError("schema_mismatch", "This herdr-core speaks a protocol generation PeerBand does not support.", "Update PeerBand (`peerband update`) and herdr-core (`hc update`).");
16421
16507
  const methods = Array.isArray(hello.methods) ? hello.methods : [];
16422
16508
  const missing = REQUIRED_METHODS.filter((method) => !methods.includes(method));
16509
+ this.methods = new Set(methods.filter((method) => typeof method === "string"));
16423
16510
  if (missing.length) throw new ConnectError("schema_mismatch", `This herdr-core lacks ${missing.join(", ")}.`, "Update herdr-core with `hc update`.");
16424
16511
  return typeof hello.core?.id === "string" ? hello.core.id : "core";
16425
16512
  })();
@@ -16511,6 +16598,127 @@ function clampInteger2(value, fallback, min, max) {
16511
16598
  return value;
16512
16599
  }
16513
16600
 
16601
+ // src/runtime-combined/index.ts
16602
+ var ENVIRONMENT_KEYS = ["workspaces", "tabs", "panes"];
16603
+ var MAX_ROWS = 50;
16604
+ var MAX_ENVIRONMENT_BYTES = 48 * 1024;
16605
+ var CombinedAdapter = class {
16606
+ constructor(parts) {
16607
+ this.parts = parts;
16608
+ if (parts.length === 0) throw new Error("CombinedAdapter needs at least one runtime.");
16609
+ }
16610
+ parts;
16611
+ /** Which runtime listed each workspace, tab and pane id in the last list_environment. */
16612
+ environmentOwners = /* @__PURE__ */ new Map();
16613
+ get runtimeNames() {
16614
+ return this.parts.map((part) => part.name);
16615
+ }
16616
+ getCapabilities() {
16617
+ const capabilities = this.parts.map((part) => part.adapter.getCapabilities());
16618
+ const reasons = capabilities.map((capability) => capability.reason).filter((reason) => Boolean(reason));
16619
+ return {
16620
+ readOutput: capabilities.some((capability) => capability.readOutput),
16621
+ sendMessage: capabilities.some((capability) => capability.sendMessage),
16622
+ ...reasons.length ? { reason: reasons.join(" ") } : {}
16623
+ };
16624
+ }
16625
+ async listAgents() {
16626
+ const results = await Promise.allSettled(this.parts.map((part) => part.adapter.listAgents()));
16627
+ const agents = results.flatMap((result) => result.status === "fulfilled" ? result.value : []);
16628
+ if (results.every((result) => result.status === "rejected")) throw results[0].reason;
16629
+ return agents;
16630
+ }
16631
+ getAgent(id) {
16632
+ return this.agentPart(id).adapter.getAgent(id);
16633
+ }
16634
+ readOutput(id, options) {
16635
+ return this.agentPart(id).adapter.readOutput(id, options);
16636
+ }
16637
+ sendMessage(id, message) {
16638
+ return this.agentPart(id).adapter.sendMessage(id, message);
16639
+ }
16640
+ async agentIdForPane(paneId) {
16641
+ for (const part of this.parts) {
16642
+ const id = await part.adapter.agentIdForPane?.(paneId).catch(() => void 0);
16643
+ if (id) return id;
16644
+ }
16645
+ return void 0;
16646
+ }
16647
+ onEvent(listener, log) {
16648
+ const stops = this.parts.map((part) => part.adapter.onEvent?.(listener, log));
16649
+ return () => {
16650
+ for (const stop of stops) stop?.();
16651
+ };
16652
+ }
16653
+ async listEnvironment() {
16654
+ const listing = this.parts.filter((part) => part.adapter.listEnvironment);
16655
+ if (listing.length === 0) throw new ConnectError("unsupported_capability", "This runtime does not support environment control.", "Use a compatible Herdr runtime.");
16656
+ const results = await Promise.allSettled(listing.map((part) => part.adapter.listEnvironment()));
16657
+ if (results.every((result) => result.status === "rejected")) throw results[0].reason;
16658
+ const owners = /* @__PURE__ */ new Map();
16659
+ const merged = { actions: [] };
16660
+ const rows = { workspaces: [], tabs: [], panes: [] };
16661
+ const truncated = { workspaces: false, tabs: false, panes: false };
16662
+ let actionsSet = false;
16663
+ results.forEach((result, index) => {
16664
+ if (result.status !== "fulfilled") return;
16665
+ const part = listing[index];
16666
+ const environment = result.value;
16667
+ if (!actionsSet && Array.isArray(environment.actions)) {
16668
+ merged.actions = environment.actions;
16669
+ actionsSet = true;
16670
+ }
16671
+ const offset = rows.workspaces.length;
16672
+ for (const key2 of ENVIRONMENT_KEYS) {
16673
+ const list3 = Array.isArray(environment[key2]) ? environment[key2] : [];
16674
+ if (environment[`${key2}Truncated`] === true) truncated[key2] = true;
16675
+ for (const row of list3) {
16676
+ const id = row[key2 === "workspaces" ? "workspaceId" : key2 === "tabs" ? "tabId" : "paneId"];
16677
+ if (typeof id === "string" && !owners.has(id)) owners.set(id, part);
16678
+ if (key2 === "workspaces") {
16679
+ rows.workspaces.push({ ...row, ...typeof row.number === "number" ? { number: row.number + offset } : {}, runtime: part.name, readOnly: !(Array.isArray(environment.actions) && environment.actions.length > 0) });
16680
+ } else {
16681
+ rows[key2].push(row);
16682
+ }
16683
+ }
16684
+ }
16685
+ });
16686
+ for (const key2 of ENVIRONMENT_KEYS) {
16687
+ merged[key2] = rows[key2].slice(0, MAX_ROWS);
16688
+ merged[`${key2}Truncated`] = truncated[key2] || rows[key2].length > MAX_ROWS;
16689
+ }
16690
+ if (Buffer.byteLength(JSON.stringify(merged), "utf8") > MAX_ENVIRONMENT_BYTES) throw new ConnectError("response_too_large", "The environment metadata exceeds the frame budget.", "Close some panes before listing the layout remotely.");
16691
+ this.environmentOwners = owners;
16692
+ return merged;
16693
+ }
16694
+ async controlEnvironment(command) {
16695
+ const part = await this.environmentPart([command.paneId, command.tabId, command.workspaceId]);
16696
+ if (!part.adapter.controlEnvironment) throw new ConnectError("unsupported_capability", `The ${part.name} runtime cannot change its layout from PeerBand.`, "Arrange it in its own app.");
16697
+ return part.adapter.controlEnvironment(command);
16698
+ }
16699
+ async readPane(paneId, options) {
16700
+ const part = await this.environmentPart([paneId]);
16701
+ if (!part.adapter.readPane) throw new ConnectError("unsupported_capability", "This runtime cannot read panes.", "Use a compatible Herdr runtime.");
16702
+ return part.adapter.readPane(paneId, options);
16703
+ }
16704
+ async close() {
16705
+ await Promise.allSettled(this.parts.map((part) => part.adapter.close?.()));
16706
+ }
16707
+ agentPart(id) {
16708
+ return this.parts.find((part) => part.ownsAgent(id)) ?? this.parts[0];
16709
+ }
16710
+ /**
16711
+ * The runtime that listed the first given id, else the primary one. Ids come from list_environment; one this
16712
+ * relay has not listed yet (a new pane, or a relay that just started) refreshes the listing once.
16713
+ */
16714
+ async environmentPart(ids) {
16715
+ const known = ids.filter((id) => id !== void 0);
16716
+ const find = () => known.map((id) => this.environmentOwners.get(id)).find((owner) => owner !== void 0);
16717
+ if (known.length && !find() && this.parts.length > 1) await this.listEnvironment().catch(() => void 0);
16718
+ return find() ?? this.parts[0];
16719
+ }
16720
+ };
16721
+
16514
16722
  // src/cli/commands/connect.ts
16515
16723
  function clock(date = /* @__PURE__ */ new Date()) {
16516
16724
  return date.toTimeString().slice(0, 8);
@@ -16547,10 +16755,10 @@ function activityLine(s, activity, at = /* @__PURE__ */ new Date()) {
16547
16755
  var spec2 = {
16548
16756
  name: "connect",
16549
16757
  summary: "Run the connector in the foreground",
16550
- usage: "peerband connect [--runtime herdr|herdr-core|mock] [--read-only] [--config PATH] [--server URL]",
16758
+ usage: "peerband connect [--runtime auto|herdr|herdr-core|mock] [--read-only] [--config PATH] [--server URL]",
16551
16759
  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, or `peerband relay --core` for herdr-core and the Herdr desktop app.',
16552
16760
  options: [
16553
- { name: "runtime", type: "string", valueName: "herdr|herdr-core|mock", description: 'Agent runtime: "herdr" (the Herdr terminal app), "herdr-core" (hc, also behind the Herdr desktop app) or "mock" (fake agents for testing). Default: $PEERBAND_RUNTIME, then "runtime" in connector.json, then herdr.' },
16761
+ { name: "runtime", type: "string", valueName: "auto|herdr|herdr-core|mock", description: 'Agent runtime: "auto" (the Herdr terminal app, plus herdr-core whenever a core is running), "herdr" (the Herdr terminal app only), "herdr-core" (hc, also behind the Herdr desktop app, only) or "mock" (fake agents for testing). Default: $PEERBAND_RUNTIME, then "runtime" in connector.json, then auto.' },
16554
16762
  { name: "disable-environment-control", type: "boolean", description: 'Turn off the owner-only Herdr environment tools (open tabs and panes, start agents) on this machine (also: "enableEnvironmentControl": false in connector.json). They are on by default and still need the environment:control consent.' },
16555
16763
  { name: "enable-environment-control", type: "boolean", description: "Redundant: environment controls are on by default. Kept so old scripts keep working." },
16556
16764
  { 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).' },
@@ -16610,18 +16818,23 @@ function isShutdownMessage(message) {
16610
16818
  }
16611
16819
  async function connect(options, ctx) {
16612
16820
  const requested = options.runtime ?? ctx.env.PEERBAND_RUNTIME;
16613
- if (requested !== void 0 && requested !== "herdr" && requested !== "herdr-core" && requested !== "mock") throw new UsageError(`Unknown runtime "${requested}".`, "Use --runtime herdr, --runtime herdr-core or --runtime mock.");
16821
+ if (requested !== void 0 && requested !== "auto" && requested !== "herdr" && requested !== "herdr-core" && requested !== "mock") throw new UsageError(`Unknown runtime "${requested}".`, "Use --runtime auto, herdr, herdr-core or mock.");
16614
16822
  const credentials = await requireCredentials(ctx);
16615
16823
  if (options.server) credentials.serverUrl = validateServerUrl(options.server);
16616
16824
  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.");
16617
16825
  if (options.disableEnvironmentControl && options.enableEnvironmentControl) throw new UsageError("--disable-environment-control and --enable-environment-control contradict each other.", "Use --disable-environment-control to turn environment controls off; they are on by default.");
16618
16826
  const config = await loadMachineConnectorConfig(ctx, options.config);
16619
- const runtime = requested ?? config.runtime ?? "herdr";
16827
+ const runtime = requested ?? config.runtime ?? "auto";
16620
16828
  const enableWrites = writesEnabled(config, { readOnly: options.readOnly, enableWrites: options.enableWrites });
16621
16829
  const managed = Boolean(options.managed);
16622
16830
  const s = ctx.out.stderr;
16623
16831
  const machine = describeMachine(credentials);
16624
- const adapter = runtime === "mock" ? new MockRuntime() : runtime === "herdr-core" ? new HerdrCoreAdapter(config.herdrCore ?? {}) : new HerdrAdapter(config.herdr ?? {});
16832
+ const coreBinary = runtime === "auto" ? findCoreBinary(config.herdrCore?.binary, ctx.env) : void 0;
16833
+ const adapter = runtime === "mock" ? new MockRuntime() : runtime === "herdr-core" ? new HerdrCoreAdapter(config.herdrCore ?? {}) : coreBinary ? new CombinedAdapter([
16834
+ { name: "herdr", adapter: new HerdrAdapter(config.herdr ?? {}), ownsAgent: (id) => id.startsWith("herdr_") },
16835
+ { name: "herdr-core", adapter: new HerdrCoreAdapter({ ...config.herdrCore, binary: coreBinary, attachOnly: true }), ownsAgent: (id) => id.startsWith("hc_") }
16836
+ ]) : new HerdrAdapter(config.herdr ?? {});
16837
+ const runtimeLabel = runtime === "auto" ? coreBinary ? "Herdr and herdr-core" : "herdr" : runtime;
16625
16838
  const core = new ConnectorCore(adapter, {
16626
16839
  writesEnabled: enableWrites,
16627
16840
  environmentControlEnabled: environmentControlEnabled(config, { disable: options.disableEnvironmentControl, enable: options.enableEnvironmentControl }),
@@ -16689,7 +16902,7 @@ async function connect(options, ctx) {
16689
16902
  events.start();
16690
16903
  if (!managed) {
16691
16904
  ctx.out.warn(
16692
- `${s.bold("peerband")} ${s.dim(`${runtime} runtime, ${enableWrites ? "messages allowed" : "read-only"}. Press Ctrl+C to stop.`)}`
16905
+ `${s.bold("peerband")} ${s.dim(`${runtimeLabel} runtime, ${enableWrites ? "messages allowed" : "read-only"}. Press Ctrl+C to stop.`)}`
16693
16906
  );
16694
16907
  }
16695
16908
  await runRemoteClient(core, credentials, {
@@ -17733,13 +17946,17 @@ function lifecycleScript(ctx) {
17733
17946
  const self = ctx.selfPath ?? process.argv[1] ?? "";
17734
17947
  return join11(resolve5(dirname5(self), ".."), "herdr", "lifecycle.mjs");
17735
17948
  }
17736
- async function startBackgroundRelay(ctx, runtime, options = {}) {
17949
+ async function startBackgroundRelay(ctx, runtime = "auto", options = {}) {
17737
17950
  const current = await runningRelayRuntime(ctx.env);
17738
- if (current === runtime) return "running";
17951
+ if (current === runtime || current === "herdr-core") return "running";
17952
+ if (current === "herdr") {
17953
+ const configured = (await loadMachineConnectorConfig(ctx).catch(() => void 0))?.runtime;
17954
+ if (configured === void 0 || configured === "auto") return "running";
17955
+ }
17739
17956
  if (current !== void 0) {
17740
17957
  throw new CliError(
17741
- `A PeerBand relay for ${current === "herdr" ? "the Herdr terminal app" : current} is already running on this machine. One relay serves one runtime.`,
17742
- "Stop it with `peerband relay --stop` (or close the Relay tab in Herdr), then run `peerband relay --core` again."
17958
+ current === "herdr" ? 'The PeerBand relay running in Herdr serves only the Herdr terminal app: connector.json sets "runtime": "herdr".' : `A PeerBand relay for ${current} is already running on this machine, and a machine has one relay.`,
17959
+ current === "herdr" ? "Remove that setting (the default serves Herdr and herdr-core together), then restart the relay with `peerband relay --stop` and `peerband relay`." : "Stop it with `peerband relay --stop`, then run `peerband relay --core` again."
17743
17960
  );
17744
17961
  }
17745
17962
  const exec2 = ctx.exec ?? execProgram;
@@ -17763,7 +17980,7 @@ var spec6 = {
17763
17980
  name: "relay",
17764
17981
  summary: "Open the PeerBand Relay in Herdr, or run it in the background for herdr-core",
17765
17982
  usage: "peerband relay [--core] [--stop]",
17766
- 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.\n\nWith --core the relay serves herdr-core (`hc`) instead, the terminal server behind the Herdr desktop app. herdr-core has no plugin tab, so the relay runs in the background: closing the desktop app or a terminal leaves it connected. Check it with `peerband status` and stop it with `peerband relay --stop`. It does not start again by itself after you log out or restart the computer; run `peerband relay --core` again. One relay serves one runtime per machine.",
17983
+ 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.\n\nWith --core the relay serves herdr-core (`hc`) instead, the terminal server behind the Herdr desktop app. herdr-core has no plugin tab, so the relay runs in the background: closing the desktop app or a terminal leaves it connected. Check it with `peerband status` and stop it with `peerband relay --stop`. It does not start again by itself after you log out or restart the computer; run `peerband relay --core` again. The relay also serves the Herdr terminal app when it runs, and the Relay tab in Herdr serves herdr-core in the same way, so one relay covers both; `--core` is only needed without the Herdr terminal app. The relay connects to a herdr-core that is running (the desktop app starts one, and so do commands such as `hc run`) and never starts one itself.",
17767
17984
  options: [
17768
17985
  { name: "core", type: "boolean", description: "Run the relay in the background for herdr-core and the Herdr desktop app." },
17769
17986
  { name: "stop", type: "boolean", description: "Stop the relay running on this machine (either kind)." }
@@ -17783,8 +18000,8 @@ var spec6 = {
17783
18000
  }
17784
18001
  const credentials = await requireCredentials(ctx);
17785
18002
  if (flag(parsed, "core")) {
17786
- const state = await startBackgroundRelay(ctx, "herdr-core");
17787
- ctx.out.print(state === "running" ? `${s.green(symbols.ok)} The PeerBand Relay for herdr-core is already running.` : `${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core.`);
18003
+ const state = await startBackgroundRelay(ctx);
18004
+ ctx.out.print(state === "running" ? `${s.green(symbols.ok)} A PeerBand Relay that serves herdr-core is already running.` : `${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core.`);
17788
18005
  ctx.out.print(s.dim("Check it with `peerband status`; stop it with `peerband relay --stop`."));
17789
18006
  printMcpHint(ctx, credentials.serverUrl);
17790
18007
  printSkillTip(ctx);
@@ -17958,7 +18175,7 @@ var spec8 = {
17958
18175
  ctx.out.print(s.dim("Skipped. Open it later with `peerband relay`."));
17959
18176
  } else if (herdr2 === "no-herdr" && await coreInstalled(ctx)) {
17960
18177
  try {
17961
- await startBackgroundRelay(ctx, "herdr-core", { checked: true });
18178
+ await startBackgroundRelay(ctx, "auto", { checked: true });
17962
18179
  relayOpen = true;
17963
18180
  ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core ${s.dim("(stop it with `peerband relay --stop`)")}.`);
17964
18181
  } catch (error) {
@@ -18143,7 +18360,7 @@ function renderHuman(report2, ctx) {
18143
18360
  rows.push(["Installation", report2.installationId ?? ""]);
18144
18361
  if (report2.enrolledAt) rows.push(["Enrolled", report2.enrolledAt]);
18145
18362
  }
18146
- const relayLine = report2.relay.running ? `${colorConnection(s, report2.relay.connection)}${report2.relay.runtime === "herdr-core" ? s.dim(" (herdr-core, in the background; stop with `peerband relay --stop`)") : ""}` : report2.relay.source === "file" && report2.relay.connection && report2.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report2.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`, or `peerband relay --core` for herdr-core)")}`);
18363
+ const relayLine = report2.relay.running ? `${colorConnection(s, report2.relay.connection)}${report2.relay.runtime === "herdr-core" || report2.relay.runtime === "auto" ? s.dim(" (in the background, for herdr-core; stop with `peerband relay --stop`)") : ""}` : report2.relay.source === "file" && report2.relay.connection && report2.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report2.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`, or `peerband relay --core` for herdr-core)")}`);
18147
18364
  rows.push(["Relay", relayLine]);
18148
18365
  if (report2.messages) {
18149
18366
  rows.push([
@@ -18585,7 +18802,7 @@ function herdrGroupHelp(s) {
18585
18802
  }
18586
18803
 
18587
18804
  // src/cli/cli.ts
18588
- var VERSION = true ? "0.3.0" : "0.0.0-dev";
18805
+ var VERSION = true ? "0.3.2" : "0.0.0-dev";
18589
18806
  function createContext(overrides = {}) {
18590
18807
  const env = overrides.env ?? process.env;
18591
18808
  const stdout = overrides.stdout ?? process.stdout;
@@ -16,7 +16,7 @@ const pluginRoot = resolve(dirname(script), "..");
16
16
  const connectorEntry = process.env.PEERBAND_CONNECTOR_ENTRY || join(pluginRoot, "dist", "peerband.mjs");
17
17
  const paneStatePath = relayStatePath(config);
18
18
  // Runtimes the supervisor passes on to the connector child.
19
- const RUNTIMES = ["mock", "herdr-core"];
19
+ const RUNTIMES = ["mock", "auto", "herdr-core"];
20
20
 
21
21
  // Starting Node can take several seconds on a loaded machine (5-8 s has been seen on Windows), so waits are
22
22
  // deadlines measured in time, not a fixed number of quick retries.
package/herdr-plugin.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  id = "peerband"
2
2
  name = "PeerBand"
3
- version = "0.3.0"
3
+ version = "0.3.2"
4
4
  min_herdr_version = "0.9.3"
5
5
  description = "Reach your Herdr agents from any MCP client through your PeerBand account"
6
6
  platforms = ["linux", "macos", "windows"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peerband",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "PeerBand CLI and Herdr plugin: reach your local coding agents from any MCP client through your PeerBand account",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",