peerband 0.1.2 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -122,6 +122,15 @@ async function inspectOwned(run, record) {
122
122
  return pane;
123
123
  }
124
124
 
125
+ // A pane carrying our ownership marker token, i.e. one opened (and verified) by a Relay tab controller.
126
+ async function findMarkedPane(run) {
127
+ let listed;
128
+ try { listed = (await run(["pane", "list"])).panes; }
129
+ catch { return undefined; }
130
+ if (!Array.isArray(listed)) return undefined;
131
+ return listed.find((item) => typeof item?.pane_id === "string" && typeof item.tokens?.[markerName] === "string" && item.tokens[markerName]);
132
+ }
133
+
125
134
  async function renameOwnedSinglePaneTab(run, pane, label) {
126
135
  if (!pane?.workspace_id || !pane?.tab_id || !pane?.pane_id) return false;
127
136
  let listed;
@@ -174,6 +183,14 @@ export function createRelayTabController({ run, statePath, pluginPaneId = "", ne
174
183
  await run(["plugin", "pane", "focus", pane.pane_id]);
175
184
  return pane.pane_id;
176
185
  }
186
+ // The record is missing or stale (another config, a crash, Herdr restarted), but a Relay pane this
187
+ // controller marked earlier may still be open: adopt and focus it instead of opening a duplicate.
188
+ const existing = await findMarkedPane(run);
189
+ if (existing) {
190
+ await writeRecord(statePath, { version: 1, paneId: existing.pane_id, marker: existing.tokens[markerName] });
191
+ await run(["plugin", "pane", "focus", existing.pane_id]);
192
+ return existing.pane_id;
193
+ }
177
194
 
178
195
  // A stale state file never authorizes closing or renaming its old pane. Replace it with a
179
196
  // fresh random ownership marker only after Herdr returns a validated plugin pane.
@@ -0,0 +1,200 @@
1
+ // Stale-lock detection and reclaim, shared by the plugin (lifecycle.mjs) and the CLI (bundled).
2
+ // A lock is a directory created with mkdir (atomic). Its owner file records who holds it:
3
+ // relay-helper.lock/owner.json {"token","pid","hostname","startedAt"} (written by the supervisor)
4
+ // state/receipts.json.lock/owner {"owner","pid","hostname","startedAt"} (written by the connector)
5
+ // Locks written by PeerBand 0.1.3 and older have no pid ("legacy"). A lock is only reclaimed when its owner is
6
+ // provably gone: a recorded pid on this host that is not alive (or alive but clearly another program), or, for a
7
+ // legacy lock, nobody answering on the helper control channel (helper lock) / no matching process running (receipts).
8
+ import { execFile } from "node:child_process";
9
+ import { randomUUID } from "node:crypto";
10
+ import { readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
11
+ import { createConnection } from "node:net";
12
+ import { hostname } from "node:os";
13
+ import { join, relative } from "node:path";
14
+
15
+ // A lock directory without an owner file may be one that is being created right now.
16
+ const CREATION_GRACE_MS = 10_000;
17
+
18
+ export const SUPERVISOR_PATTERN = /lifecycle\.mjs["']?\s+supervise\b/i;
19
+ export const CONNECTOR_PATTERN = /peerband(?:\.mjs|\.cmd|\.ps1)?["']?\s+connect\b/i;
20
+
21
+ /** Fields recorded in every new owner file. */
22
+ export function ownerIdentity() {
23
+ return { pid: process.pid, hostname: hostname(), startedAt: new Date().toISOString() };
24
+ }
25
+
26
+ /** True when a process with this pid exists (EPERM means it exists but belongs to someone else). */
27
+ export function pidAlive(pid) {
28
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
29
+ try {
30
+ process.kill(pid, 0);
31
+ return true;
32
+ } catch (error) {
33
+ return Boolean(error && error.code === "EPERM");
34
+ }
35
+ }
36
+
37
+ /** "listening" when something accepts connections on the channel, "absent" when nothing does, "unknown" otherwise. */
38
+ export function probeChannel(channel, timeout = 1500) {
39
+ return new Promise((resolve) => {
40
+ let settled = false;
41
+ const socket = createConnection(channel);
42
+ const finish = (value) => {
43
+ if (settled) return;
44
+ settled = true;
45
+ clearTimeout(timer);
46
+ socket.destroy();
47
+ resolve(value);
48
+ };
49
+ const timer = setTimeout(() => finish("unknown"), timeout);
50
+ socket.once("connect", () => finish("listening"));
51
+ socket.once("error", (error) => finish(error && (error.code === "ENOENT" || error.code === "ECONNREFUSED") ? "absent" : "unknown"));
52
+ });
53
+ }
54
+
55
+ function run(file, args, timeout) {
56
+ return new Promise((resolve) => {
57
+ execFile(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve(error ? null : String(stdout)));
58
+ });
59
+ }
60
+
61
+ /** Best-effort list of running processes with their command lines, or null when it cannot be read. */
62
+ export async function listProcesses(platform = process.platform) {
63
+ if (platform === "linux") {
64
+ let entries;
65
+ try { entries = await readdir("/proc"); } catch { return null; }
66
+ const result = [];
67
+ for (const entry of entries) {
68
+ if (!/^\d+$/.test(entry)) continue;
69
+ try {
70
+ const command = (await readFile(`/proc/${entry}/cmdline`, "utf8")).split("\0").join(" ").trim();
71
+ if (command) result.push({ pid: Number(entry), command });
72
+ } catch { /* exited meanwhile */ }
73
+ }
74
+ return result;
75
+ }
76
+ if (platform === "win32") {
77
+ const script = "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }";
78
+ const text = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 15_000);
79
+ if (text === null) return null;
80
+ return parseProcessLines(text, "\t");
81
+ }
82
+ const text = await run("ps", ["-axo", "pid=,command="], 10_000);
83
+ return text === null ? null : parseProcessLines(text, " ");
84
+ }
85
+
86
+ function parseProcessLines(text, separator) {
87
+ const result = [];
88
+ for (const raw of text.split(/\r?\n/)) {
89
+ const line = raw.trim();
90
+ if (!line) continue;
91
+ const at = line.indexOf(separator);
92
+ const pid = Number(at < 0 ? line : line.slice(0, at));
93
+ if (Number.isSafeInteger(pid) && pid > 0) result.push({ pid, command: at < 0 ? "" : line.slice(at + 1).trim() });
94
+ }
95
+ return result;
96
+ }
97
+
98
+ async function readOwner(ownerFile) {
99
+ let text;
100
+ try { text = await readFile(ownerFile, "utf8"); } catch { return { text: null, owner: null }; }
101
+ try {
102
+ const value = JSON.parse(text);
103
+ if (value && typeof value === "object" && !Array.isArray(value)) return { text, owner: value };
104
+ } catch { /* a legacy receipt lock holds a bare uuid */ }
105
+ return { text, owner: {} };
106
+ }
107
+
108
+ /**
109
+ * Decides whether a lock is held by a live owner.
110
+ * Returns { state: "absent" | "live" | "stale", reason, ownerText, pid? }.
111
+ * `channel`: the helper control channel that a live owner answers on (optional).
112
+ * `processPattern`: command-line pattern of a process that could own the lock (optional).
113
+ * `listProcesses`, `probe`, `alive`, `host`: test seams.
114
+ */
115
+ export async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list = listProcesses, probe = probeChannel, alive = pidAlive, host = hostname(), now = Date.now() }) {
116
+ let info;
117
+ try { info = await stat(lockDir); } catch (error) {
118
+ if (error && error.code === "ENOENT") return { state: "absent", reason: "no lock", ownerText: null };
119
+ return { state: "live", reason: `the lock could not be read (${error && error.code})`, ownerText: null };
120
+ }
121
+ const { text, owner } = await readOwner(ownerFile);
122
+ const ignore = new Set([process.pid, ...excludePids]);
123
+ // Processes whose command line matches the owner pattern (null when unknown). `keep` is never filtered out.
124
+ const matching = async (keep) => {
125
+ if (!processPattern) return null;
126
+ const processes = await list();
127
+ if (!processes) return null;
128
+ return processes.filter((item) => (item.pid === keep || !ignore.has(item.pid)) && processPattern.test(item.command));
129
+ };
130
+
131
+ if (owner && Number.isSafeInteger(owner.pid) && owner.pid > 0) {
132
+ const pid = owner.pid;
133
+ if (typeof owner.hostname === "string" && owner.hostname && owner.hostname !== host) {
134
+ return { state: "live", reason: `the owner runs on another host (${owner.hostname})`, ownerText: text, pid };
135
+ }
136
+ if (!alive(pid)) return { state: "stale", reason: `owner process ${pid} is not running`, ownerText: text, pid };
137
+ // The pid is alive. It may have been reused by an unrelated program after the owner died.
138
+ if (channel && (await probe(channel)) !== "absent") return { state: "live", reason: `owner process ${pid} is running`, ownerText: text, pid };
139
+ const candidates = await matching(pid);
140
+ if (candidates && !candidates.some((item) => item.pid === pid)) {
141
+ return { state: "stale", reason: `process ${pid} is running but is not a PeerBand ${channel ? "helper" : "connector"}`, ownerText: text, pid };
142
+ }
143
+ return { state: "live", reason: `owner process ${pid} is running`, ownerText: text, pid };
144
+ }
145
+
146
+ // Legacy lock (no pid), or a lock whose owner file is missing.
147
+ if (text === null && now - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
148
+ if (channel) {
149
+ // The channel name is derived from the config folder and a helper listens on it before it writes its owner
150
+ // file, for as long as it lives. Nothing listening therefore means the helper of *this* config is gone, which a
151
+ // process list cannot tell (it cannot see which config folder another helper serves).
152
+ const probed = await probe(channel);
153
+ if (probed === "listening") return { state: "live", reason: "a helper answers on the control channel", ownerText: text };
154
+ if (probed === "unknown") return { state: "live", reason: "the control channel could not be checked", ownerText: text };
155
+ return { state: "stale", reason: "no helper answers on the control channel", ownerText: text };
156
+ }
157
+ const candidates = await matching();
158
+ if (candidates && candidates.length > 0) {
159
+ return { state: "live", reason: `a matching process is running (pid ${candidates.map((item) => item.pid).join(", ")})`, ownerText: text };
160
+ }
161
+ if (!candidates) return { state: "live", reason: "running processes could not be listed", ownerText: text };
162
+ return { state: "stale", reason: "no matching process is running", ownerText: text };
163
+ }
164
+
165
+ /**
166
+ * Atomically removes a stale lock: rename it aside (only one reclaimer can win), check that the moved lock is
167
+ * still the one that was inspected, then delete it. If the owner changed meanwhile, it is put back.
168
+ */
169
+ export async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
170
+ const quarantine = `${lockDir}.stale-${randomUUID()}`;
171
+ try { await rename(lockDir, quarantine); } catch (error) { return Boolean(error && error.code === "ENOENT"); }
172
+ const moved = await readOwner(join(quarantine, relative(lockDir, ownerFile)));
173
+ if (expectedOwnerText !== undefined && moved.text !== expectedOwnerText) {
174
+ await rename(quarantine, lockDir).catch(() => {});
175
+ return false;
176
+ }
177
+ await rm(quarantine, { recursive: true, force: true }).catch(() => {});
178
+ return true;
179
+ }
180
+
181
+ /** inspectLock + reclaimLock. Returns { reclaimed, verdict }. `log` receives one line when a lock is reclaimed. */
182
+ export async function reclaimIfStale(options) {
183
+ const verdict = await inspectLock(options);
184
+ if (verdict.state !== "stale") return { reclaimed: false, verdict };
185
+ const reclaimed = await reclaimLock({ lockDir: options.lockDir, ownerFile: options.ownerFile, expectedOwnerText: verdict.ownerText ?? undefined });
186
+ if (reclaimed && options.log) options.log(`Reclaimed a stale lock ${options.lockDir} (${verdict.reason}).`);
187
+ return { reclaimed, verdict };
188
+ }
189
+
190
+ /** Marks a saved relay snapshot as stopped (keeps the activity list), so nothing reads it as still running. */
191
+ export async function resetRelayState(path) {
192
+ let previous = {};
193
+ try { previous = JSON.parse(await readFile(path, "utf8")) || {}; } catch (error) {
194
+ if (error && error.code === "ENOENT") return false;
195
+ }
196
+ const activity = Array.isArray(previous.activity) ? previous.activity : [];
197
+ if (previous.state === "stopping" && previous.connectionState === "disabled") return false;
198
+ await writeFile(path, `${JSON.stringify({ state: "stopping", connectionState: "disabled", activity })}\n`, { mode: 0o600 });
199
+ return true;
200
+ }
package/herdr-plugin.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  id = "peerband"
2
2
  name = "PeerBand"
3
- version = "0.1.2"
3
+ version = "0.1.5"
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"]
@@ -1,118 +1,119 @@
1
- # PeerBand installer for Windows PowerShell 5.1 and PowerShell 7+.
2
- #
3
- # irm https://peerband.com/install.ps1 | iex
4
- # Installs the CLI, then runs the interactive `peerband login` (opens your browser).
5
- # Headless/CI only: use a dashboard grant instead of the browser, e.g.
6
- # $env:PEERBAND_GRANT = 'GRANT'; $env:PEERBAND_NAME = 'my-pc'; irm https://peerband.com/install.ps1 | iex
7
- #
8
- # & ([scriptblock]::Create((irm https://peerband.com/install.ps1))) -Grant GRANT -Name my-pc
9
- #
10
- # Env: PEERBAND_GRANT, PEERBAND_NAME, PEERBAND_VERSION (default latest),
11
- # PEERBAND_PACKAGE (tarball path or git URL; overrides the npm package).
12
- # There is deliberately no param() block so that `irm | iex` works.
13
-
14
- $ErrorActionPreference = 'Stop'
15
- $pbGrant = $env:PEERBAND_GRANT
16
- $pbName = $env:PEERBAND_NAME
17
- $pbShowHelp = $false
18
- $pbUsageError = $null
19
- $pbColor = -not $env:NO_COLOR
20
- $pbIsFile = [bool]$PSCommandPath
21
-
22
- for ($i = 0; $i -lt $args.Count; $i++) {
23
- switch -Regex ([string]$args[$i]) {
24
- '^-{1,2}(Grant)$' { if ($i + 1 -lt $args.Count) { $pbGrant = [string]$args[++$i] } else { $pbUsageError = '-Grant needs a value' } }
25
- '^-{1,2}(Name)$' { if ($i + 1 -lt $args.Count) { $pbName = [string]$args[++$i] } else { $pbUsageError = '-Name needs a value' } }
26
- '^(-{1,2}(Help|h)|/\?)$' { $pbShowHelp = $true }
27
- default { $pbUsageError = "unknown argument: $($args[$i])" }
28
- }
29
- }
30
-
31
- function Say($Text, $Color = $null) {
32
- if ($pbColor -and $Color) { Write-Host $Text -ForegroundColor $Color } else { Write-Host $Text }
33
- }
34
- function Fail($Message, [int]$Code = 1) {
35
- [Console]::Error.WriteLine("error: $Message")
36
- if ($script:pbIsFile) { exit $Code }
37
- # `exit` would close the user's shell under `irm | iex`; stop the script instead.
38
- throw "PeerBand installer stopped (see the error above)."
39
- }
40
-
41
- if ($pbShowHelp) {
42
- Say @'
43
- PeerBand installer
44
-
45
- Usage: install.ps1 [-Name NAME] [-Grant GRANT]
46
-
47
- By default the installer runs "peerband login", which opens your browser to sign in.
48
-
49
- -Name NAME machine name shown in the dashboard (default: hostname)
50
- -Grant GRANT headless/CI only: short-lived enrollment grant from the PeerBand dashboard,
51
- used instead of the browser sign-in
52
- -Help show this help
53
-
54
- Environment: PEERBAND_GRANT, PEERBAND_NAME, PEERBAND_VERSION, PEERBAND_PACKAGE
55
- '@
56
- if ($pbIsFile) { exit 0 } else { return }
57
- }
58
- if ($pbUsageError) { Fail "install.ps1: $pbUsageError (try -Help)" 2 }
59
- $env:PEERBAND_GRANT = $null
60
-
61
- Say '==> Checking Node.js' Cyan
62
- $nodeUrl = 'https://nodejs.org/en/download'
63
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) { Fail "Node.js 22.13 or newer is required but was not found. Install it from $nodeUrl and re-run." }
64
- $nodeRaw = ((& node --version) | Select-Object -First 1)
65
- $nodeVer = $null
66
- $nodeText = ([string]$nodeRaw).Trim().TrimStart('v')
67
- if (-not [version]::TryParse($nodeText, [ref]$nodeVer)) { Fail "Could not read the Node.js version (got '$nodeRaw'). Install Node.js 22.13+ from $nodeUrl" }
68
- if ($nodeVer -lt [version]'22.13') { Fail "Node.js $nodeVer is too old; PeerBand needs 22.13 or newer. Install it from $nodeUrl and re-run." }
69
- Say " ok Node.js $nodeVer" Green
70
- if (-not (Get-Command npm.cmd -ErrorAction SilentlyContinue)) { Fail "npm was not found next to Node.js. Reinstall Node.js from $nodeUrl" }
71
-
72
- Say '==> Installing the peerband CLI' Cyan
73
- $pbVersion = if ($env:PEERBAND_VERSION) { $env:PEERBAND_VERSION } else { 'latest' }
74
- $pkg = if ($env:PEERBAND_PACKAGE) { $env:PEERBAND_PACKAGE } else { "peerband@$pbVersion" }
75
- & npm.cmd install -g $pkg
76
- if ($LASTEXITCODE -ne 0) { Fail "npm install -g $pkg failed (exit $LASTEXITCODE)." }
77
- # Run the CLI this installer just put in npm's global prefix by full path, so
78
- # another `peerband` earlier on PATH is never run in its place.
79
- $prefix = ((& npm.cmd prefix -g) | Select-Object -First 1)
80
- $pbExe = if ($prefix) { Join-Path $prefix 'peerband.cmd' } else { $null }
81
- if (-not $pbExe -or -not (Test-Path $pbExe)) { Fail "peerband was installed but is missing from the npm prefix ('npm prefix -g'). Re-run the installer." }
82
- $pbOnPath = Get-Command peerband -ErrorAction SilentlyContinue | Select-Object -First 1
83
- if (-not $pbOnPath) {
84
- $env:PATH = "$prefix;$env:PATH"
85
- Say " !! $prefix is not on your PATH. Add it under Settings > System > About > Advanced system settings > Environment Variables." Yellow
86
- } elseif ([IO.Path]::GetFullPath($pbOnPath.Source) -ne [IO.Path]::GetFullPath($pbExe)) {
87
- Say " !! Another peerband command comes first on your PATH: $($pbOnPath.Source)" Yellow
88
- Say " Remove it, or move $prefix ahead of it in PATH, so 'peerband' runs this CLI." Yellow
89
- }
90
- Say ' ok peerband installed' Green
91
-
92
- Say '==> Logging in' Cyan
93
- $loginArgs = @('login', '--herdr-plugin', 'install')
94
- if ($pbName) { $loginArgs += @('--name', $pbName) }
95
- try {
96
- if ($pbGrant) { $env:PEERBAND_GRANT = $pbGrant }
97
- & $pbExe @loginArgs
98
- $loginCode = $LASTEXITCODE
99
- } finally {
100
- $env:PEERBAND_GRANT = $null
101
- $pbGrant = $null
102
- }
103
- if ($loginCode -ne 0) { Fail "peerband login failed. Run 'peerband login' again, or on a headless machine use 'peerband login --grant GRANT' with a grant from your PeerBand dashboard." }
104
-
105
- # `peerband login --herdr-plugin install` has already added the plugin to Herdr when Herdr is present.
106
- $pbHasHerdr = [bool](Get-Command herdr -ErrorAction SilentlyContinue)
107
-
108
- Say ''
109
- if ($pbHasHerdr) {
110
- Say 'PeerBand is ready. Next:' Green
111
- Say ' peerband relay open the PeerBand Relay tab in Herdr'
112
- Say ' peerband status check your connection (and the Herdr plugin)'
113
- } else {
114
- Say 'PeerBand is installed and logged in. Next:' Green
115
- Say ' 1. Install Herdr 0.9.3 or newer: https://herdr.dev'
116
- Say ' 2. peerband herdr install then peerband relay'
117
- Say ' peerband status check your connection'
118
- }
1
+ # PeerBand installer for Windows PowerShell 5.1 and PowerShell 7+.
2
+ #
3
+ # irm https://peerband.com/install.ps1 | iex
4
+ # Installs the CLI, then runs the interactive `peerband setup` (browser login, Herdr plugin, agent skill, relay).
5
+ # Headless/CI only: use a dashboard grant instead of the browser, e.g.
6
+ # $env:PEERBAND_GRANT = 'GRANT'; $env:PEERBAND_NAME = 'my-pc'; irm https://peerband.com/install.ps1 | iex
7
+ #
8
+ # & ([scriptblock]::Create((irm https://peerband.com/install.ps1))) -Grant GRANT -Name my-pc
9
+ #
10
+ # Env: PEERBAND_GRANT, PEERBAND_NAME, PEERBAND_VERSION (default latest),
11
+ # PEERBAND_PACKAGE (tarball path or git URL; overrides the npm package).
12
+ # There is deliberately no param() block so that `irm | iex` works.
13
+
14
+ $ErrorActionPreference = 'Stop'
15
+ $pbGrant = $env:PEERBAND_GRANT
16
+ $pbName = $env:PEERBAND_NAME
17
+ $pbShowHelp = $false
18
+ $pbUsageError = $null
19
+ $pbColor = -not $env:NO_COLOR
20
+ $pbIsFile = [bool]$PSCommandPath
21
+
22
+ for ($i = 0; $i -lt $args.Count; $i++) {
23
+ switch -Regex ([string]$args[$i]) {
24
+ '^-{1,2}(Grant)$' { if ($i + 1 -lt $args.Count) { $pbGrant = [string]$args[++$i] } else { $pbUsageError = '-Grant needs a value' } }
25
+ '^-{1,2}(Name)$' { if ($i + 1 -lt $args.Count) { $pbName = [string]$args[++$i] } else { $pbUsageError = '-Name needs a value' } }
26
+ '^(-{1,2}(Help|h)|/\?)$' { $pbShowHelp = $true }
27
+ default { $pbUsageError = "unknown argument: $($args[$i])" }
28
+ }
29
+ }
30
+
31
+ function Say($Text, $Color = $null) {
32
+ if ($pbColor -and $Color) { Write-Host $Text -ForegroundColor $Color } else { Write-Host $Text }
33
+ }
34
+ function Fail($Message, [int]$Code = 1) {
35
+ [Console]::Error.WriteLine("error: $Message")
36
+ if ($script:pbIsFile) { exit $Code }
37
+ # `exit` would close the user's shell under `irm | iex`; stop the script instead.
38
+ throw "PeerBand installer stopped (see the error above)."
39
+ }
40
+
41
+ if ($pbShowHelp) {
42
+ Say @'
43
+ PeerBand installer
44
+
45
+ Usage: install.ps1 [-Name NAME] [-Grant GRANT]
46
+
47
+ By default the installer runs "peerband setup": it opens your browser to sign in, adds the
48
+ PeerBand plugin to Herdr, offers the PeerBand skill for your coding agents and opens the relay.
49
+
50
+ -Name NAME machine name shown in the dashboard (default: hostname)
51
+ -Grant GRANT headless/CI only: short-lived enrollment grant from the PeerBand dashboard,
52
+ used instead of the browser sign-in
53
+ -Help show this help
54
+
55
+ Environment: PEERBAND_GRANT, PEERBAND_NAME, PEERBAND_VERSION, PEERBAND_PACKAGE
56
+ '@
57
+ if ($pbIsFile) { exit 0 } else { return }
58
+ }
59
+ if ($pbUsageError) { Fail "install.ps1: $pbUsageError (try -Help)" 2 }
60
+ $env:PEERBAND_GRANT = $null
61
+
62
+ Say '==> Checking Node.js' Cyan
63
+ $nodeUrl = 'https://nodejs.org/en/download'
64
+ if (-not (Get-Command node -ErrorAction SilentlyContinue)) { Fail "Node.js 22.13 or newer is required but was not found. Install it from $nodeUrl and re-run." }
65
+ $nodeRaw = ((& node --version) | Select-Object -First 1)
66
+ $nodeVer = $null
67
+ $nodeText = ([string]$nodeRaw).Trim().TrimStart('v')
68
+ if (-not [version]::TryParse($nodeText, [ref]$nodeVer)) { Fail "Could not read the Node.js version (got '$nodeRaw'). Install Node.js 22.13+ from $nodeUrl" }
69
+ if ($nodeVer -lt [version]'22.13') { Fail "Node.js $nodeVer is too old; PeerBand needs 22.13 or newer. Install it from $nodeUrl and re-run." }
70
+ Say " ok Node.js $nodeVer" Green
71
+ if (-not (Get-Command npm.cmd -ErrorAction SilentlyContinue)) { Fail "npm was not found next to Node.js. Reinstall Node.js from $nodeUrl" }
72
+
73
+ Say '==> Installing the peerband CLI' Cyan
74
+ $pbVersion = if ($env:PEERBAND_VERSION) { $env:PEERBAND_VERSION } else { 'latest' }
75
+ $pkg = if ($env:PEERBAND_PACKAGE) { $env:PEERBAND_PACKAGE } else { "peerband@$pbVersion" }
76
+ & npm.cmd install -g $pkg
77
+ if ($LASTEXITCODE -ne 0) { Fail "npm install -g $pkg failed (exit $LASTEXITCODE)." }
78
+ # Run the CLI this installer just put in npm's global prefix by full path, so
79
+ # another `peerband` earlier on PATH is never run in its place.
80
+ $prefix = ((& npm.cmd prefix -g) | Select-Object -First 1)
81
+ $pbExe = if ($prefix) { Join-Path $prefix 'peerband.cmd' } else { $null }
82
+ if (-not $pbExe -or -not (Test-Path $pbExe)) { Fail "peerband was installed but is missing from the npm prefix ('npm prefix -g'). Re-run the installer." }
83
+ $pbOnPath = Get-Command peerband -ErrorAction SilentlyContinue | Select-Object -First 1
84
+ if (-not $pbOnPath) {
85
+ $env:PATH = "$prefix;$env:PATH"
86
+ Say " !! $prefix is not on your PATH. Add it under Settings > System > About > Advanced system settings > Environment Variables." Yellow
87
+ } elseif ([IO.Path]::GetFullPath($pbOnPath.Source) -ne [IO.Path]::GetFullPath($pbExe)) {
88
+ Say " !! Another peerband command comes first on your PATH: $($pbOnPath.Source)" Yellow
89
+ Say " Remove it, or move $prefix ahead of it in PATH, so 'peerband' runs this CLI." Yellow
90
+ }
91
+ Say ' ok peerband installed' Green
92
+
93
+ Say '==> Setting up' Cyan
94
+ $loginArgs = @('setup', '--herdr-plugin', 'install')
95
+ # Headless (grant) setup cannot ask, so it installs the agent skill; a browser setup asks first (Yes by default).
96
+ if ($pbGrant) { $loginArgs += @('--skill', 'install') }
97
+ if ($pbName) { $loginArgs += @('--name', $pbName) }
98
+ try {
99
+ if ($pbGrant) { $env:PEERBAND_GRANT = $pbGrant }
100
+ & $pbExe @loginArgs
101
+ $loginCode = $LASTEXITCODE
102
+ } finally {
103
+ $env:PEERBAND_GRANT = $null
104
+ $pbGrant = $null
105
+ }
106
+ if ($loginCode -ne 0) { Fail "peerband setup failed. Run 'peerband setup' again, or on a headless machine use 'peerband setup --grant GRANT' with a grant from your PeerBand dashboard." }
107
+
108
+ # `peerband setup` has already added the plugin, offered the skill and opened the relay when Herdr is present.
109
+ $pbHasHerdr = [bool](Get-Command herdr -ErrorAction SilentlyContinue)
110
+
111
+ Say ''
112
+ if ($pbHasHerdr) {
113
+ Say 'PeerBand is installed. Check it any time with: peerband status' Green
114
+ } else {
115
+ Say 'PeerBand is installed and logged in. Next:' Green
116
+ Say ' 1. Install Herdr 0.9.3 or newer: https://herdr.dev'
117
+ Say ' 2. peerband setup adds the Herdr plugin and opens the relay'
118
+ Say ' peerband status check your connection'
119
+ }
@@ -1,7 +1,7 @@
1
1
  #!/bin/sh
2
2
  # PeerBand installer.
3
3
  # curl -fsSL https://peerband.com/install.sh | sh
4
- # Installs the CLI, then runs the interactive `peerband login` (opens your browser).
4
+ # Installs the CLI, then runs the interactive `peerband setup` (browser login, Herdr plugin, agent skill, relay).
5
5
  # curl -fsSL https://peerband.com/install.sh | sh -s -- --grant GRANT --name NAME
6
6
  # Headless/CI only: enroll with a dashboard grant instead of the browser.
7
7
  # Env: PEERBAND_GRANT, PEERBAND_NAME, PEERBAND_VERSION (default latest),
@@ -24,7 +24,8 @@ PeerBand installer
24
24
 
25
25
  Usage: install.sh [--name NAME] [--grant GRANT]
26
26
 
27
- By default the installer runs "peerband login", which opens your browser to sign in.
27
+ By default the installer runs "peerband setup": it opens your browser to sign in, adds the
28
+ PeerBand plugin to Herdr, offers the PeerBand skill for your coding agents and opens the relay.
28
29
 
29
30
  --name NAME machine name shown in the dashboard (default: hostname)
30
31
  --grant GRANT headless/CI only: short-lived enrollment grant from the PeerBand dashboard,
@@ -76,29 +77,29 @@ elif [ "$onpath" != "$pb" ]; then
76
77
  fi
77
78
  ok "peerband installed"
78
79
 
79
- step "Logging in"
80
+ step "Setting up"
80
81
  if [ -n "$grant" ]; then
81
82
  if [ -n "$name" ]; then
82
- PEERBAND_GRANT=$grant "$pb" login --herdr-plugin install --name "$name" || die "peerband login failed. Get a fresh grant from your PeerBand dashboard."
83
+ PEERBAND_GRANT=$grant "$pb" setup --herdr-plugin install --skill install --name "$name" || die "peerband setup failed. Get a fresh grant from your PeerBand dashboard."
83
84
  else
84
- PEERBAND_GRANT=$grant "$pb" login --herdr-plugin install || die "peerband login failed. Get a fresh grant from your PeerBand dashboard."
85
+ PEERBAND_GRANT=$grant "$pb" setup --herdr-plugin install --skill install || die "peerband setup failed. Get a fresh grant from your PeerBand dashboard."
85
86
  fi
86
87
  else
87
88
  # Browser sign-in. Under `curl | sh` stdin is the script itself; use the terminal instead.
88
89
  set -- --herdr-plugin install
89
90
  [ -z "$name" ] || set -- "$@" --name "$name"
90
91
  if (exec </dev/tty) 2>/dev/null; then
91
- "$pb" login "$@" </dev/tty
92
+ "$pb" setup "$@" </dev/tty
92
93
  else
93
- "$pb" login "$@"
94
- fi || die "peerband login failed. Run 'peerband login' again, or on a headless machine use 'peerband login --grant GRANT' with a grant from your PeerBand dashboard."
94
+ "$pb" setup "$@"
95
+ fi || die "peerband setup failed. Run 'peerband setup' again, or on a headless machine use 'peerband setup --grant GRANT' with a grant from your PeerBand dashboard."
95
96
  fi
96
97
  grant=''
97
98
 
98
- # `peerband login --herdr-plugin install` has already added the plugin to Herdr when Herdr is present.
99
+ # `peerband setup` has already added the plugin, offered the skill and opened the relay when Herdr is present.
99
100
  if command -v herdr >/dev/null 2>&1; then
100
- printf '\n%sPeerBand is ready.%s Next:\n peerband relay open the PeerBand Relay tab in Herdr\n peerband status check your connection (and the Herdr plugin)\n' "$G" "$N"
101
+ printf '\n%sPeerBand is installed.%s Check it any time with: peerband status\n' "$G" "$N"
101
102
  else
102
103
  warn "Herdr was not found. PeerBand reaches the agents you run in Herdr."
103
- printf '\n%sPeerBand is installed and logged in.%s Next:\n 1. Install Herdr 0.9.3 or newer: https://herdr.dev\n 2. peerband herdr install then peerband relay\n peerband status check your connection\n' "$G" "$N"
104
+ printf '\n%sPeerBand is installed and logged in.%s Next:\n 1. Install Herdr 0.9.3 or newer: https://herdr.dev\n 2. peerband setup adds the Herdr plugin and opens the relay\n peerband status check your connection\n' "$G" "$N"
104
105
  fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peerband",
3
- "version": "0.1.2",
3
+ "version": "0.1.5",
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",
@@ -10,7 +10,7 @@
10
10
  "keywords": ["peerband", "herdr", "mcp", "coding-agents", "cli"],
11
11
  "bin": { "peerband": "dist/peerband.mjs" },
12
12
  "engines": { "node": ">=22.13.0" },
13
- "files": ["dist/", "herdr/", "herdr-plugin.toml", "protocol/", "install/", "README.md", "LICENSE", "NOTICE", "SECURITY.md"],
13
+ "files": ["dist/", "herdr/", "herdr-plugin.toml", "protocol/", "install/", "skills/", "README.md", "LICENSE", "NOTICE", "SECURITY.md"],
14
14
  "scripts": {
15
15
  "build": "node scripts/build.mjs",
16
16
  "typecheck": "tsc --noEmit",
@@ -6,7 +6,7 @@ The `peerband` client talks to the PeerBand service over two interfaces. The ser
6
6
  | --- | --- |
7
7
  | `enrollment-redeem.schema.json` | `POST /api/enrollments/redeem`: exchange a short-lived grant (from the PeerBand dashboard) for an installation credential. `$defs`: `request`, `response`, `errorResponse`. |
8
8
  | `device-authorization.schema.json` | Browser sign-in: `POST /api/device/code` and `POST /api/device/token` (what `peerband login` sends and receives), plus the dashboard approval endpoints. `$defs`: `codeRequest`, `codeResponse`, `tokenRequest`, `tokenResponse`, `tokenError`, `rateLimited`, `requestStatus`, `decisionResponse`. |
9
- | `relay-messages.schema.json` | Every WebSocket text frame on `wss://<server>/connections`, both directions, as a `oneOf` discriminated by `type`: `request`, `ping` (server to client), `pong`, `response` (client to server). |
9
+ | `relay-messages.schema.json` | Every WebSocket text frame on `wss://<server>/connections`, both directions, as a `oneOf` discriminated by `type`: `request`, `ping` (server to client), `pong`, `response`, `event` (client to server). |
10
10
 
11
11
  ## Device login summary
12
12
 
@@ -22,15 +22,20 @@ The grant flow (`enrollment-redeem.schema.json`) remains available for headless
22
22
  ## Relay summary
23
23
 
24
24
  1. The client opens `wss://<server>/connections` with `Authorization: Bearer <installation credential>` (never in the URL). Plain `ws://` is only accepted for loopback hosts.
25
- 2. The server sends `request` frames (`id`, `tool`, `args`, `principal`). The client runs them through its local policy layer (allow-lists, write opt-in, output sanitization, idempotent receipts) and answers with a `response` carrying exactly one of `result` or `error {code, message, next_step}`.
25
+ 2. The server sends `request` frames (`id`, `tool`, `args`, `principal`). The client runs them through its local policy layer (allow-lists, write opt-in, output sanitization, idempotent receipts) and answers with a `response` carrying exactly one of `result` or `error {code, message, next_step}`. `principal` is `{id, scopes, role, email}`: `role` is `owner` or `guest` (a shared user) and `email` is the caller's account email when known. The client starts every message it delivers to an agent with a `[PeerBand relay]` line naming the sender from these fields; a missing role counts as a guest.
26
26
  3. The server sends `ping` after 20 s of silence; the client replies `pong`. The client closes the socket with code 4000 and reconnects if it hears nothing from the server for 75 s.
27
27
  4. Limits: 64 KiB per frame, 32 outstanding requests, 15 s per request. Requests are never replayed; a write whose response is lost is reported as `delivery_unknown`.
28
28
  5. Close codes 4001 (replaced), 4003, 4401 (auth) and HTTP 401/403 on upgrade mean the credential is revoked or superseded: the client stops reconnecting.
29
+ 6. Agent events: the client sends `x-peerband-features: events` on the upgrade and then pushes `event` frames (`eventId`, `name`, `timestamp`, `data`) without being asked:
30
+ - `agent.status_changed` `{agentId, status, previousStatus, label, workspace, revision}` when an agent's status changes (at most one per agent per 250 ms, latest wins, with an overall rate cap);
31
+ - `agents.changed` `{}` when agents appear, exit or change occupant, and once after every (re)connect, so consumers re-list;
32
+ - `agent.notified` `{agentId, text, audience: "owner"}` for a note sent with `peerband notify` (1 to 1024 characters, sanitized and redacted like agent output).
33
+ Events are metadata only and never carry terminal output. They are sent only while the socket is open; nothing is queued while disconnected.
29
34
 
30
35
  The client only reports metadata (tool, target id, outcome, latency) to its local activity log; message bodies and agent output are never logged.
31
36
 
32
37
  ## Versioning
33
38
 
34
- The protocol has no explicit version field today. Changes are additive: new optional fields and new `tool` values may appear, so implementations must ignore unknown fields on received messages. A breaking change would use a new endpoint path or a `hello` negotiation message and be documented here with a bump of the schema `$id`. Schemas are published with each client release in `protocol/`.
39
+ The protocol has no explicit version field today. Changes are additive: new optional fields, new `tool` values and new frame types may appear, so implementations must ignore unknown fields and unknown frame types on received messages. The `event` frame is such an addition: servers that do not know it ignore it, and the `x-peerband-features` upgrade header tells servers that do which clients emit events. A breaking change would use a new endpoint path or a `hello` negotiation message and be documented here with a bump of the schema `$id`. Schemas are published with each client release in `protocol/`.
35
40
 
36
41
  The tests in `test/protocol.test.ts` validate messages produced by the real relay client against these schemas.