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.
- package/README.md +54 -14
- package/dist/peerband.mjs +2586 -695
- package/herdr/README.md +18 -18
- package/herdr/launch.mjs +87 -87
- package/herdr/lifecycle.mjs +111 -37
- package/herdr/pane.mjs +105 -42
- package/herdr/relay-tab.mjs +17 -0
- package/herdr/stale-lock.mjs +200 -0
- package/herdr-plugin.toml +1 -1
- package/install/install.ps1 +119 -118
- package/install/install.sh +12 -11
- package/package.json +2 -2
- package/protocol/README.md +8 -3
- package/protocol/relay-messages.schema.json +134 -78
- package/skills/peerband/SKILL.md +94 -0
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(
|
|
69
|
-
if (
|
|
70
|
-
if (
|
|
68
|
+
function concat(list2, totalLength) {
|
|
69
|
+
if (list2.length === 0) return EMPTY_BUFFER;
|
|
70
|
+
if (list2.length === 1) return list2[0];
|
|
71
71
|
const target = Buffer.allocUnsafe(totalLength);
|
|
72
72
|
let offset = 0;
|
|
73
|
-
for (let i = 0; i <
|
|
74
|
-
const buf =
|
|
73
|
+
for (let i = 0; i < list2.length; i++) {
|
|
74
|
+
const buf = list2[i];
|
|
75
75
|
target.set(buf, offset);
|
|
76
76
|
offset += buf.length;
|
|
77
77
|
}
|
|
@@ -1857,14 +1857,14 @@ var require_sender = __commonJS({
|
|
|
1857
1857
|
* @param {Function} [cb] Callback
|
|
1858
1858
|
* @private
|
|
1859
1859
|
*/
|
|
1860
|
-
sendFrame(
|
|
1861
|
-
if (
|
|
1860
|
+
sendFrame(list2, cb) {
|
|
1861
|
+
if (list2.length === 2) {
|
|
1862
1862
|
this._socket.cork();
|
|
1863
|
-
this._socket.write(
|
|
1864
|
-
this._socket.write(
|
|
1863
|
+
this._socket.write(list2[0]);
|
|
1864
|
+
this._socket.write(list2[1], cb);
|
|
1865
1865
|
this._socket.uncork();
|
|
1866
1866
|
} else {
|
|
1867
|
-
this._socket.write(
|
|
1867
|
+
this._socket.write(list2[0], cb);
|
|
1868
1868
|
}
|
|
1869
1869
|
}
|
|
1870
1870
|
};
|
|
@@ -2275,7 +2275,7 @@ var require_websocket = __commonJS({
|
|
|
2275
2275
|
var http = __require("http");
|
|
2276
2276
|
var net = __require("net");
|
|
2277
2277
|
var tls = __require("tls");
|
|
2278
|
-
var { randomBytes, createHash:
|
|
2278
|
+
var { randomBytes, createHash: createHash5 } = __require("crypto");
|
|
2279
2279
|
var { Duplex, Readable } = __require("stream");
|
|
2280
2280
|
var { URL: URL2 } = __require("url");
|
|
2281
2281
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -2956,7 +2956,7 @@ var require_websocket = __commonJS({
|
|
|
2956
2956
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2957
2957
|
return;
|
|
2958
2958
|
}
|
|
2959
|
-
const digest =
|
|
2959
|
+
const digest = createHash5("sha1").update(key + GUID).digest("base64");
|
|
2960
2960
|
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2961
2961
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2962
2962
|
return;
|
|
@@ -3325,7 +3325,7 @@ var require_websocket_server = __commonJS({
|
|
|
3325
3325
|
var EventEmitter = __require("events");
|
|
3326
3326
|
var http = __require("http");
|
|
3327
3327
|
var { Duplex } = __require("stream");
|
|
3328
|
-
var { createHash:
|
|
3328
|
+
var { createHash: createHash5 } = __require("crypto");
|
|
3329
3329
|
var extension2 = require_extension();
|
|
3330
3330
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
3331
3331
|
var subprotocol2 = require_subprotocol();
|
|
@@ -3632,7 +3632,7 @@ var require_websocket_server = __commonJS({
|
|
|
3632
3632
|
);
|
|
3633
3633
|
}
|
|
3634
3634
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3635
|
-
const digest =
|
|
3635
|
+
const digest = createHash5("sha1").update(key + GUID).digest("base64");
|
|
3636
3636
|
const headers = [
|
|
3637
3637
|
"HTTP/1.1 101 Switching Protocols",
|
|
3638
3638
|
"Upgrade: websocket",
|
|
@@ -7011,14 +7011,14 @@ var require_utils = __commonJS({
|
|
|
7011
7011
|
BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15];
|
|
7012
7012
|
}
|
|
7013
7013
|
}
|
|
7014
|
-
function percentEncodeNonAscii(
|
|
7015
|
-
if (
|
|
7016
|
-
return BYTE_HEX[192 |
|
|
7014
|
+
function percentEncodeNonAscii(cp2) {
|
|
7015
|
+
if (cp2 < 2048) {
|
|
7016
|
+
return BYTE_HEX[192 | cp2 >> 6] + BYTE_HEX[128 | cp2 & 63];
|
|
7017
7017
|
}
|
|
7018
|
-
if (
|
|
7019
|
-
return BYTE_HEX[224 |
|
|
7018
|
+
if (cp2 < 65536) {
|
|
7019
|
+
return BYTE_HEX[224 | cp2 >> 12] + BYTE_HEX[128 | cp2 >> 6 & 63] + BYTE_HEX[128 | cp2 & 63];
|
|
7020
7020
|
}
|
|
7021
|
-
return BYTE_HEX[240 |
|
|
7021
|
+
return BYTE_HEX[240 | cp2 >> 18] + BYTE_HEX[128 | cp2 >> 12 & 63] + BYTE_HEX[128 | cp2 >> 6 & 63] + BYTE_HEX[128 | cp2 & 63];
|
|
7022
7022
|
}
|
|
7023
7023
|
function stringArrayToHexStripped(input) {
|
|
7024
7024
|
let acc = "";
|
|
@@ -7382,8 +7382,8 @@ var require_utils = __commonJS({
|
|
|
7382
7382
|
function encodeFragment(input) {
|
|
7383
7383
|
return encodeComponent(input, isQueryFragmentCharacter);
|
|
7384
7384
|
}
|
|
7385
|
-
function isEscapeSafe(
|
|
7386
|
-
return
|
|
7385
|
+
function isEscapeSafe(cp2) {
|
|
7386
|
+
return cp2 >= 48 && cp2 <= 57 || cp2 >= 65 && cp2 <= 90 || cp2 >= 97 && cp2 <= 122 || cp2 === 42 || cp2 === 43 || cp2 === 45 || cp2 === 46 || cp2 === 47 || cp2 === 64 || cp2 === 95;
|
|
7387
7387
|
}
|
|
7388
7388
|
function normalizeQueryFragmentEncoding(input) {
|
|
7389
7389
|
let output = "";
|
|
@@ -7763,49 +7763,49 @@ var require_fast_uri = __commonJS({
|
|
|
7763
7763
|
schemelessOptions.skipEscape = true;
|
|
7764
7764
|
return serialize(resolved, schemelessOptions);
|
|
7765
7765
|
}
|
|
7766
|
-
function resolveComponent(base,
|
|
7766
|
+
function resolveComponent(base, relative3, options, skipNormalization) {
|
|
7767
7767
|
const target = {};
|
|
7768
7768
|
if (!skipNormalization) {
|
|
7769
7769
|
base = parse(serialize(base, options), options);
|
|
7770
|
-
|
|
7770
|
+
relative3 = parse(serialize(relative3, options), options);
|
|
7771
7771
|
}
|
|
7772
7772
|
options = options || {};
|
|
7773
|
-
if (!options.tolerant &&
|
|
7774
|
-
target.scheme =
|
|
7775
|
-
target.userinfo =
|
|
7776
|
-
target.host =
|
|
7777
|
-
target.port =
|
|
7778
|
-
target.path = removeDotSegments(
|
|
7779
|
-
target.query =
|
|
7773
|
+
if (!options.tolerant && relative3.scheme) {
|
|
7774
|
+
target.scheme = relative3.scheme;
|
|
7775
|
+
target.userinfo = relative3.userinfo;
|
|
7776
|
+
target.host = relative3.host;
|
|
7777
|
+
target.port = relative3.port;
|
|
7778
|
+
target.path = removeDotSegments(relative3.path || "");
|
|
7779
|
+
target.query = relative3.query;
|
|
7780
7780
|
} else {
|
|
7781
|
-
if (
|
|
7782
|
-
target.userinfo =
|
|
7783
|
-
target.host =
|
|
7784
|
-
target.port =
|
|
7785
|
-
target.path = removeDotSegments(
|
|
7786
|
-
target.query =
|
|
7781
|
+
if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
|
|
7782
|
+
target.userinfo = relative3.userinfo;
|
|
7783
|
+
target.host = relative3.host;
|
|
7784
|
+
target.port = relative3.port;
|
|
7785
|
+
target.path = removeDotSegments(relative3.path || "");
|
|
7786
|
+
target.query = relative3.query;
|
|
7787
7787
|
} else {
|
|
7788
|
-
if (!
|
|
7788
|
+
if (!relative3.path) {
|
|
7789
7789
|
target.path = base.path;
|
|
7790
|
-
if (
|
|
7791
|
-
target.query =
|
|
7790
|
+
if (relative3.query !== void 0) {
|
|
7791
|
+
target.query = relative3.query;
|
|
7792
7792
|
} else {
|
|
7793
7793
|
target.query = base.query;
|
|
7794
7794
|
}
|
|
7795
7795
|
} else {
|
|
7796
|
-
if (
|
|
7797
|
-
target.path = removeDotSegments(
|
|
7796
|
+
if (relative3.path[0] === "/") {
|
|
7797
|
+
target.path = removeDotSegments(relative3.path);
|
|
7798
7798
|
} else {
|
|
7799
7799
|
if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
|
|
7800
|
-
target.path = "/" +
|
|
7800
|
+
target.path = "/" + relative3.path;
|
|
7801
7801
|
} else if (!base.path) {
|
|
7802
|
-
target.path =
|
|
7802
|
+
target.path = relative3.path;
|
|
7803
7803
|
} else {
|
|
7804
|
-
target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) +
|
|
7804
|
+
target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
|
|
7805
7805
|
}
|
|
7806
7806
|
target.path = removeDotSegments(target.path);
|
|
7807
7807
|
}
|
|
7808
|
-
target.query =
|
|
7808
|
+
target.query = relative3.query;
|
|
7809
7809
|
}
|
|
7810
7810
|
target.userinfo = base.userinfo;
|
|
7811
7811
|
target.host = base.host;
|
|
@@ -7813,7 +7813,7 @@ var require_fast_uri = __commonJS({
|
|
|
7813
7813
|
}
|
|
7814
7814
|
target.scheme = base.scheme;
|
|
7815
7815
|
}
|
|
7816
|
-
target.fragment =
|
|
7816
|
+
target.fragment = relative3.fragment;
|
|
7817
7817
|
return target;
|
|
7818
7818
|
}
|
|
7819
7819
|
function equal(uriA, uriB, options) {
|
|
@@ -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
|
|
10863
|
-
addFormats2(ajv,
|
|
10862
|
+
const list2 = opts.formats || formats_1.formatNames;
|
|
10863
|
+
addFormats2(ajv, list2, formats, exportName);
|
|
10864
10864
|
if (opts.keywords)
|
|
10865
10865
|
(0, limit_1.default)(ajv);
|
|
10866
10866
|
return ajv;
|
|
@@ -10872,11 +10872,11 @@ var require_dist = __commonJS({
|
|
|
10872
10872
|
throw new Error(`Unknown format "${name}"`);
|
|
10873
10873
|
return f;
|
|
10874
10874
|
};
|
|
10875
|
-
function addFormats2(ajv,
|
|
10875
|
+
function addFormats2(ajv, list2, fs, exportName) {
|
|
10876
10876
|
var _a;
|
|
10877
10877
|
var _b;
|
|
10878
10878
|
(_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
|
|
10879
|
-
for (const f of
|
|
10879
|
+
for (const f of list2)
|
|
10880
10880
|
ajv.addFormat(f, fs[f]);
|
|
10881
10881
|
}
|
|
10882
10882
|
module.exports = exports = formatsPlugin;
|
|
@@ -11711,8 +11711,9 @@ var require__ = __commonJS({
|
|
|
11711
11711
|
|
|
11712
11712
|
// src/core/core.ts
|
|
11713
11713
|
import { createHash, randomUUID } from "node:crypto";
|
|
11714
|
-
import { mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
11715
|
-
import {
|
|
11714
|
+
import { mkdir, readFile, rename, rm, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
11715
|
+
import { hostname } from "node:os";
|
|
11716
|
+
import { dirname, join } from "node:path";
|
|
11716
11717
|
var ConnectError = class extends Error {
|
|
11717
11718
|
constructor(code, message, nextStep) {
|
|
11718
11719
|
super(message);
|
|
@@ -11768,6 +11769,7 @@ var MockRuntime = class {
|
|
|
11768
11769
|
agents = /* @__PURE__ */ new Map();
|
|
11769
11770
|
retired = /* @__PURE__ */ new Set();
|
|
11770
11771
|
output = /* @__PURE__ */ new Map();
|
|
11772
|
+
listeners = /* @__PURE__ */ new Set();
|
|
11771
11773
|
machineId;
|
|
11772
11774
|
constructor(machineId = "mock-machine") {
|
|
11773
11775
|
this.machineId = machineId;
|
|
@@ -11805,6 +11807,31 @@ Message received: ${message}`.trim());
|
|
|
11805
11807
|
getCapabilities() {
|
|
11806
11808
|
return { readOutput: true, sendMessage: true };
|
|
11807
11809
|
}
|
|
11810
|
+
onEvent(listener) {
|
|
11811
|
+
this.listeners.add(listener);
|
|
11812
|
+
return () => {
|
|
11813
|
+
this.listeners.delete(listener);
|
|
11814
|
+
};
|
|
11815
|
+
}
|
|
11816
|
+
/** Mock panes are named `mock:<index>` in seed order. */
|
|
11817
|
+
async agentIdForPane(paneId) {
|
|
11818
|
+
const match = /^mock:(\d+)$/.exec(paneId);
|
|
11819
|
+
return match ? [...this.agents.keys()][Number(match[1])] : void 0;
|
|
11820
|
+
}
|
|
11821
|
+
/** Changes an agent's status and emits a status event, as a real runtime would. */
|
|
11822
|
+
setStatus(id, status) {
|
|
11823
|
+
const agent = this.agents.get(id);
|
|
11824
|
+
if (!agent) throw new ConnectError("agent_not_found", "No agent has this identity.", "List agents and use an exact agent ID.");
|
|
11825
|
+
const previousStatus = agent.status;
|
|
11826
|
+
if (previousStatus === status) return;
|
|
11827
|
+
agent.status = status;
|
|
11828
|
+
agent.rawStatus = status;
|
|
11829
|
+
agent.observedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
11830
|
+
this.emit({ kind: "status", agentId: id, status, previousStatus, label: agent.label, workspace: agent.workspace, revision: null });
|
|
11831
|
+
}
|
|
11832
|
+
emit(event) {
|
|
11833
|
+
for (const listener of [...this.listeners]) listener(event);
|
|
11834
|
+
}
|
|
11808
11835
|
/** Simulate a pane being reused: retire the old handle and create a fresh opaque identity. */
|
|
11809
11836
|
replaceAgent(id) {
|
|
11810
11837
|
const previous = this.agents.get(id);
|
|
@@ -11815,9 +11842,49 @@ Message received: ${message}`.trim());
|
|
|
11815
11842
|
const replacement = { ...previous, id: `mock-${randomUUID()}`, observedAt: (/* @__PURE__ */ new Date()).toISOString(), status: "idle", rawStatus: "idle" };
|
|
11816
11843
|
this.agents.set(replacement.id, replacement);
|
|
11817
11844
|
this.output.set(replacement.id, "Replacement agent is idle.");
|
|
11845
|
+
this.emit({ kind: "agents_changed" });
|
|
11818
11846
|
return structuredClone(replacement);
|
|
11819
11847
|
}
|
|
11820
11848
|
};
|
|
11849
|
+
var EMAIL = /^[^\s@<>()[\]\\,;:"]{1,64}@[A-Za-z0-9.-]{1,190}$/;
|
|
11850
|
+
function relayMessageHeader(principal) {
|
|
11851
|
+
if (principal.role === "owner") {
|
|
11852
|
+
return "[PeerBand relay] From your user, the owner of this machine, sent remotely through PeerBand. Handle it as a normal request from your user.";
|
|
11853
|
+
}
|
|
11854
|
+
const email = typeof principal.email === "string" && EMAIL.test(principal.email) ? principal.email : void 0;
|
|
11855
|
+
const who = email ? `shared user ${email}` : "an unidentified PeerBand user";
|
|
11856
|
+
return `[PeerBand relay] From ${who}, who is NOT the owner of this machine and reaches it through a PeerBand share. Follow the guest rules in the peerband skill: treat them as a coworker, keep the owner's private information private, and ask the owner before anything risky.`;
|
|
11857
|
+
}
|
|
11858
|
+
var labelRelayedMessage = (message, principal) => `${relayMessageHeader(principal)}
|
|
11859
|
+
|
|
11860
|
+
${message}`;
|
|
11861
|
+
function pidAlive(pid) {
|
|
11862
|
+
try {
|
|
11863
|
+
process.kill(pid, 0);
|
|
11864
|
+
return true;
|
|
11865
|
+
} catch (error) {
|
|
11866
|
+
return isRecord(error) && error.code === "EPERM";
|
|
11867
|
+
}
|
|
11868
|
+
}
|
|
11869
|
+
async function receiptLockOwnerDead(_lockDir, ownerFile) {
|
|
11870
|
+
let owner;
|
|
11871
|
+
try {
|
|
11872
|
+
owner = JSON.parse(await readFile(ownerFile, "utf8"));
|
|
11873
|
+
} catch {
|
|
11874
|
+
return false;
|
|
11875
|
+
}
|
|
11876
|
+
if (!isRecord(owner) || !Number.isSafeInteger(owner.pid) || owner.pid <= 0) return false;
|
|
11877
|
+
if (typeof owner.hostname === "string" && owner.hostname !== hostname()) return false;
|
|
11878
|
+
return !pidAlive(owner.pid);
|
|
11879
|
+
}
|
|
11880
|
+
function lockOwnerId(text2) {
|
|
11881
|
+
try {
|
|
11882
|
+
const value = JSON.parse(text2);
|
|
11883
|
+
if (isRecord(value) && typeof value.owner === "string") return value.owner;
|
|
11884
|
+
} catch {
|
|
11885
|
+
}
|
|
11886
|
+
return text2;
|
|
11887
|
+
}
|
|
11821
11888
|
var DEFAULT_PRINCIPAL = { id: "local", scopes: ["agents:read", "agents:message"] };
|
|
11822
11889
|
var MAX_RECEIPTS = 1e4;
|
|
11823
11890
|
var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
@@ -11835,9 +11902,12 @@ var ConnectorCore = class {
|
|
|
11835
11902
|
constructor(adapter, options = {}) {
|
|
11836
11903
|
this.adapter = adapter;
|
|
11837
11904
|
this.writesEnabled = options.writesEnabled ?? false;
|
|
11905
|
+
this.labelMessages = options.labelMessages ?? false;
|
|
11838
11906
|
this.allowedAgents = options.allowedAgents ? new Set(options.allowedAgents) : void 0;
|
|
11839
11907
|
this.allowedWorkspaces = options.allowedWorkspaces ? new Set(options.allowedWorkspaces) : void 0;
|
|
11840
11908
|
this.receiptPath = options.receiptPath;
|
|
11909
|
+
this.lockIsStale = options.lockIsStale ?? receiptLockOwnerDead;
|
|
11910
|
+
this.onLockReclaimed = options.onLockReclaimed;
|
|
11841
11911
|
this.retentionMs = options.retentionMs ?? DEFAULT_RETENTION_MS;
|
|
11842
11912
|
if (!Number.isSafeInteger(this.retentionMs) || this.retentionMs < 6e4 || this.retentionMs > 365 * 24 * 60 * 60 * 1e3) {
|
|
11843
11913
|
throw new ConnectError("invalid_argument", "retentionMs is outside the supported range.", "Choose retention from one minute to one year.");
|
|
@@ -11849,10 +11919,13 @@ var ConnectorCore = class {
|
|
|
11849
11919
|
receipts = /* @__PURE__ */ new Map();
|
|
11850
11920
|
idempotency = /* @__PURE__ */ new Map();
|
|
11851
11921
|
writesEnabled;
|
|
11922
|
+
labelMessages;
|
|
11852
11923
|
allowedAgents;
|
|
11853
11924
|
allowedWorkspaces;
|
|
11854
11925
|
retentionMs;
|
|
11855
11926
|
receiptPath;
|
|
11927
|
+
lockIsStale;
|
|
11928
|
+
onLockReclaimed;
|
|
11856
11929
|
lockOwner;
|
|
11857
11930
|
get lockPath() {
|
|
11858
11931
|
return this.receiptPath ? `${this.receiptPath}.lock` : void 0;
|
|
@@ -12024,7 +12097,7 @@ var ConnectorCore = class {
|
|
|
12024
12097
|
this.idempotency.delete(requestKeyHash);
|
|
12025
12098
|
throw new ConnectError("receipt_store_unavailable", "The request receipt could not be saved; nothing was sent.", "Check local storage access and retry with the same key.");
|
|
12026
12099
|
}
|
|
12027
|
-
const job = this.dispatch(receipt, message).catch(() => void 0);
|
|
12100
|
+
const job = this.dispatch(receipt, this.labelMessages ? labelRelayedMessage(message, principal) : message).catch(() => void 0);
|
|
12028
12101
|
this.inFlight.add(job);
|
|
12029
12102
|
void job.finally(() => this.inFlight.delete(job));
|
|
12030
12103
|
return this.publicReceipt(receipt);
|
|
@@ -12131,37 +12204,61 @@ var ConnectorCore = class {
|
|
|
12131
12204
|
await this.persist();
|
|
12132
12205
|
}
|
|
12133
12206
|
async acquireLock() {
|
|
12134
|
-
const
|
|
12135
|
-
if (!
|
|
12207
|
+
const lockPath3 = this.lockPath;
|
|
12208
|
+
if (!lockPath3 || !this.receiptPath) return;
|
|
12136
12209
|
await mkdir(dirname(this.receiptPath), { recursive: true });
|
|
12137
|
-
|
|
12138
|
-
|
|
12139
|
-
|
|
12140
|
-
|
|
12141
|
-
|
|
12210
|
+
const ownerFile = join(lockPath3, "owner");
|
|
12211
|
+
for (let attempt = 0; ; attempt++) {
|
|
12212
|
+
try {
|
|
12213
|
+
await mkdir(lockPath3, { mode: 448 });
|
|
12214
|
+
break;
|
|
12215
|
+
} catch (error) {
|
|
12216
|
+
if (!(isRecord(error) && error.code === "EEXIST")) throw error;
|
|
12217
|
+
}
|
|
12218
|
+
if (attempt === 0 && await this.lockIsStale(lockPath3, ownerFile).catch(() => false) && await this.reclaimStaleLock(lockPath3, ownerFile)) continue;
|
|
12219
|
+
throw new ConnectError("receipt_store_locked", "Another connector process owns this receipt store.", "Stop the other process or configure a separate state directory.");
|
|
12142
12220
|
}
|
|
12143
12221
|
const owner = randomUUID();
|
|
12144
12222
|
this.lockOwner = owner;
|
|
12223
|
+
const record = { owner, pid: process.pid, hostname: hostname(), startedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
12145
12224
|
try {
|
|
12146
|
-
await writeFile(
|
|
12225
|
+
await writeFile(ownerFile, JSON.stringify(record), { encoding: "utf8", flag: "wx", mode: 384 });
|
|
12147
12226
|
} catch (error) {
|
|
12148
12227
|
this.lockOwner = void 0;
|
|
12149
12228
|
try {
|
|
12150
|
-
await rmdir(
|
|
12229
|
+
await rmdir(lockPath3);
|
|
12151
12230
|
} catch {
|
|
12152
12231
|
}
|
|
12153
12232
|
throw error;
|
|
12154
12233
|
}
|
|
12155
12234
|
}
|
|
12235
|
+
/** Moves the stale lock aside (atomic, one winner), checks it is the one inspected, then deletes it. */
|
|
12236
|
+
async reclaimStaleLock(lockPath3, ownerFile) {
|
|
12237
|
+
const before = await readFile(ownerFile, "utf8").catch(() => null);
|
|
12238
|
+
const quarantine = `${lockPath3}.stale-${randomUUID()}`;
|
|
12239
|
+
try {
|
|
12240
|
+
await rename(lockPath3, quarantine);
|
|
12241
|
+
} catch {
|
|
12242
|
+
return false;
|
|
12243
|
+
}
|
|
12244
|
+
const moved = await readFile(join(quarantine, "owner"), "utf8").catch(() => null);
|
|
12245
|
+
if (moved !== before) {
|
|
12246
|
+
await rename(quarantine, lockPath3).catch(() => void 0);
|
|
12247
|
+
return false;
|
|
12248
|
+
}
|
|
12249
|
+
await rm(quarantine, { recursive: true, force: true }).catch(() => void 0);
|
|
12250
|
+
this.onLockReclaimed?.(`Reclaimed a stale receipt-store lock ${lockPath3}${before ? ` (previous owner: ${before.slice(0, 200)})` : ""}.`);
|
|
12251
|
+
return true;
|
|
12252
|
+
}
|
|
12156
12253
|
async releaseLock() {
|
|
12157
|
-
const
|
|
12254
|
+
const lockPath3 = this.lockPath;
|
|
12158
12255
|
const owner = this.lockOwner;
|
|
12159
|
-
if (!
|
|
12256
|
+
if (!lockPath3 || !owner) return;
|
|
12160
12257
|
try {
|
|
12161
|
-
const currentOwner = await readFile(`${
|
|
12162
|
-
if (currentOwner !== owner) return;
|
|
12163
|
-
await unlink(`${
|
|
12164
|
-
await rmdir(
|
|
12258
|
+
const currentOwner = await readFile(`${lockPath3}/owner`, "utf8");
|
|
12259
|
+
if (lockOwnerId(currentOwner) !== owner) return;
|
|
12260
|
+
await unlink(`${lockPath3}/owner`);
|
|
12261
|
+
await rmdir(lockPath3);
|
|
12165
12262
|
} catch (error) {
|
|
12166
12263
|
if (isRecord(error) && error.code === "ENOENT") return;
|
|
12167
12264
|
throw error;
|
|
@@ -12190,9 +12287,9 @@ var ConnectorCore = class {
|
|
|
12190
12287
|
};
|
|
12191
12288
|
|
|
12192
12289
|
// src/core/config.ts
|
|
12193
|
-
import { chmod, mkdir as mkdir2, readFile as readFile2, rename as rename2, rm, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
12290
|
+
import { chmod, mkdir as mkdir2, readFile as readFile2, rename as rename2, rm as rm2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
12194
12291
|
import { homedir } from "node:os";
|
|
12195
|
-
import { dirname as dirname2, join } from "node:path";
|
|
12292
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
12196
12293
|
var DEFAULT_SERVER_URL = "https://peerband.com";
|
|
12197
12294
|
var ConfigError = class extends Error {
|
|
12198
12295
|
hint;
|
|
@@ -12207,16 +12304,18 @@ function configHome(options = {}) {
|
|
|
12207
12304
|
const platform = options.platform ?? process.platform;
|
|
12208
12305
|
const home = options.home ?? homedir();
|
|
12209
12306
|
if (env.PEERBAND_CONFIG_HOME) return env.PEERBAND_CONFIG_HOME;
|
|
12210
|
-
if (platform === "win32") return
|
|
12211
|
-
return
|
|
12212
|
-
}
|
|
12213
|
-
var credentialsPath = (options) =>
|
|
12214
|
-
var
|
|
12215
|
-
var
|
|
12216
|
-
var
|
|
12217
|
-
var
|
|
12218
|
-
|
|
12219
|
-
|
|
12307
|
+
if (platform === "win32") return join2(env.APPDATA || join2(home, "AppData", "Roaming"), "peerband");
|
|
12308
|
+
return join2(env.XDG_CONFIG_HOME || join2(home, ".config"), "peerband");
|
|
12309
|
+
}
|
|
12310
|
+
var credentialsPath = (options) => join2(configHome(options), "credentials.json");
|
|
12311
|
+
var lockPath = (options) => join2(configHome(options), "relay-helper.lock");
|
|
12312
|
+
var relayStatePath = (options) => join2(configHome(options), "relay-state.json");
|
|
12313
|
+
var relayTabPath = (options) => join2(configHome(options), "relay-tab.json");
|
|
12314
|
+
var stateDirectory = (options) => join2(configHome(options), "state");
|
|
12315
|
+
var receiptsPath = (options) => join2(stateDirectory(options), "receipts.json");
|
|
12316
|
+
var connectorConfigPath = (options) => join2(configHome(options), "connector.json");
|
|
12317
|
+
function isLoopback(hostname4) {
|
|
12318
|
+
const host = hostname4.replace(/^\[|\]$/g, "").toLowerCase();
|
|
12220
12319
|
return host === "localhost" || host === "127.0.0.1" || host === "::1";
|
|
12221
12320
|
}
|
|
12222
12321
|
function validateServerUrl(value) {
|
|
@@ -12300,7 +12399,7 @@ async function loadCredentials(path = credentialsPath()) {
|
|
|
12300
12399
|
}
|
|
12301
12400
|
async function deleteCredentials(path = credentialsPath()) {
|
|
12302
12401
|
try {
|
|
12303
|
-
await
|
|
12402
|
+
await rm2(path);
|
|
12304
12403
|
return true;
|
|
12305
12404
|
} catch (error) {
|
|
12306
12405
|
if (error.code === "ENOENT") return false;
|
|
@@ -12403,8 +12502,8 @@ function socketUrl(serverUrl) {
|
|
|
12403
12502
|
throw new Error("Remote server URL must use https or wss.");
|
|
12404
12503
|
if (url.username || url.password)
|
|
12405
12504
|
throw new Error("Remote server URL cannot contain credentials.");
|
|
12406
|
-
const
|
|
12407
|
-
const loopback =
|
|
12505
|
+
const hostname4 = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
12506
|
+
const loopback = hostname4 === "localhost" || hostname4.endsWith(".localhost") || hostname4 === "::1" || isIP(hostname4) === 4 && hostname4.startsWith("127.");
|
|
12408
12507
|
if ((url.protocol === "http:" || url.protocol === "ws:") && !loopback)
|
|
12409
12508
|
throw new Error(
|
|
12410
12509
|
"Remote connections must use HTTPS/WSS except on localhost."
|
|
@@ -12430,18 +12529,19 @@ function enrollmentBase(serverUrl) {
|
|
|
12430
12529
|
);
|
|
12431
12530
|
if (base.username || base.password)
|
|
12432
12531
|
throw new Error("Enrollment server URL cannot contain credentials.");
|
|
12433
|
-
const
|
|
12434
|
-
const loopback =
|
|
12532
|
+
const hostname4 = base.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
12533
|
+
const loopback = hostname4 === "localhost" || hostname4.endsWith(".localhost") || hostname4 === "::1" || isIP(hostname4) === 4 && hostname4.startsWith("127.");
|
|
12435
12534
|
if (base.protocol === "http:" && !loopback)
|
|
12436
12535
|
throw new Error("Enrollment requires HTTPS except on localhost.");
|
|
12437
12536
|
return base;
|
|
12438
12537
|
}
|
|
12439
|
-
async function redeemEnrollment(serverUrl, grant, name, fetcher = fetch) {
|
|
12538
|
+
async function redeemEnrollment(serverUrl, grant, name, fetcher = fetch, previousCredential) {
|
|
12440
12539
|
const base = enrollmentBase(serverUrl);
|
|
12441
12540
|
const response = await fetcher(new URL("/api/enrollments/redeem", base), {
|
|
12442
12541
|
method: "POST",
|
|
12443
12542
|
headers: { "content-type": "application/json" },
|
|
12444
|
-
|
|
12543
|
+
// previous_credential lets the server keep this machine's record (see DeviceLoginOptions).
|
|
12544
|
+
body: JSON.stringify({ grant, name, ...previousCredential ? { previous_credential: previousCredential } : {} }),
|
|
12445
12545
|
signal: AbortSignal.timeout(15e3)
|
|
12446
12546
|
});
|
|
12447
12547
|
const body = await response.json().catch(() => ({}));
|
|
@@ -12487,7 +12587,10 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12487
12587
|
setConnectionState("connecting");
|
|
12488
12588
|
await new Promise((resolve5, reject) => {
|
|
12489
12589
|
const socket = new wrapper_default(serverUrl, {
|
|
12490
|
-
headers: {
|
|
12590
|
+
headers: {
|
|
12591
|
+
Authorization: `Bearer ${credentials.credential}`,
|
|
12592
|
+
...options.events ? { "x-peerband-features": "events" } : {}
|
|
12593
|
+
},
|
|
12491
12594
|
maxPayload: MAX_FRAME,
|
|
12492
12595
|
handshakeTimeout: 1e4,
|
|
12493
12596
|
perMessageDeflate: false
|
|
@@ -12522,6 +12625,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12522
12625
|
Math.min(1e4, Math.max(10, heartbeatTimeoutMs / 4))
|
|
12523
12626
|
);
|
|
12524
12627
|
heartbeatTimer.unref();
|
|
12628
|
+
options.events?.attach((frame) => sendEvent(socket, frame));
|
|
12525
12629
|
});
|
|
12526
12630
|
socket.on("message", async (data, isBinary) => {
|
|
12527
12631
|
if (stopped) {
|
|
@@ -12663,6 +12767,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12663
12767
|
});
|
|
12664
12768
|
socket.once("close", (code, reason) => {
|
|
12665
12769
|
if (heartbeatTimer) clearInterval(heartbeatTimer);
|
|
12770
|
+
options.events?.detach();
|
|
12666
12771
|
if (Date.now() - openedAt >= 3e4) attempt = 0;
|
|
12667
12772
|
if (code === 4001 || code === 4003 || code === 4401) stopped = true;
|
|
12668
12773
|
if (stopped) setConnectionState("revoked");
|
|
@@ -12698,6 +12803,17 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12698
12803
|
active.clear();
|
|
12699
12804
|
}
|
|
12700
12805
|
}
|
|
12806
|
+
function sendEvent(socket, frame) {
|
|
12807
|
+
if (socket.readyState !== wrapper_default.OPEN) return false;
|
|
12808
|
+
let text2;
|
|
12809
|
+
try {
|
|
12810
|
+
text2 = encode(frame);
|
|
12811
|
+
} catch {
|
|
12812
|
+
return false;
|
|
12813
|
+
}
|
|
12814
|
+
socket.send(text2);
|
|
12815
|
+
return true;
|
|
12816
|
+
}
|
|
12701
12817
|
|
|
12702
12818
|
// src/core/device-login.ts
|
|
12703
12819
|
var DeviceLoginError = class extends Error {
|
|
@@ -12799,7 +12915,11 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
|
|
|
12799
12915
|
if (now() >= deadline) throw expired();
|
|
12800
12916
|
let result;
|
|
12801
12917
|
try {
|
|
12802
|
-
result = await postJson(
|
|
12918
|
+
result = await postJson(
|
|
12919
|
+
url,
|
|
12920
|
+
{ device_code: code.deviceCode, ...options.previousCredential ? { previous_credential: options.previousCredential } : {} },
|
|
12921
|
+
options
|
|
12922
|
+
);
|
|
12803
12923
|
} catch {
|
|
12804
12924
|
if (options.signal?.aborted) throw aborted();
|
|
12805
12925
|
failures = Math.min(failures + 1, 10);
|
|
@@ -12845,6 +12965,190 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
|
|
|
12845
12965
|
}
|
|
12846
12966
|
}
|
|
12847
12967
|
|
|
12968
|
+
// src/core/events.ts
|
|
12969
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
12970
|
+
var AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
|
|
12971
|
+
var NOTE_MAX_CHARS = 1024;
|
|
12972
|
+
var PANE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
12973
|
+
function eventFrame(name, data, now = /* @__PURE__ */ new Date()) {
|
|
12974
|
+
return { type: "event", eventId: randomUUID2(), name, timestamp: now.toISOString(), data };
|
|
12975
|
+
}
|
|
12976
|
+
function codePoints(text2) {
|
|
12977
|
+
return Array.from(text2).length;
|
|
12978
|
+
}
|
|
12979
|
+
function cleanNote(text2) {
|
|
12980
|
+
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
|
+
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.");
|
|
12982
|
+
let clean = sanitizeOutput(text2, { lines: 500, bytes: 32 * 1024 }).text.trim();
|
|
12983
|
+
if (codePoints(clean) > NOTE_MAX_CHARS) clean = [...clean].slice(0, NOTE_MAX_CHARS).join("");
|
|
12984
|
+
if (clean.length === 0) throw new ConnectError("invalid_argument", "The note has no printable text.", "Pass a short plain-text note.");
|
|
12985
|
+
return clean;
|
|
12986
|
+
}
|
|
12987
|
+
var ConnectorEvents = class {
|
|
12988
|
+
constructor(adapter, options = {}) {
|
|
12989
|
+
this.adapter = adapter;
|
|
12990
|
+
this.allowedAgents = options.allowedAgents ? new Set(options.allowedAgents) : void 0;
|
|
12991
|
+
this.allowedWorkspaces = options.allowedWorkspaces ? new Set(options.allowedWorkspaces) : void 0;
|
|
12992
|
+
this.windowMs = options.windowMs ?? 250;
|
|
12993
|
+
this.ratePerSecond = options.ratePerSecond ?? 10;
|
|
12994
|
+
this.burst = options.burst ?? 20;
|
|
12995
|
+
this.notesPerMinute = options.notesPerMinute ?? 10;
|
|
12996
|
+
this.now = options.now ?? Date.now;
|
|
12997
|
+
this.log = options.log;
|
|
12998
|
+
this.tokens = this.burst;
|
|
12999
|
+
this.noteTokens = this.notesPerMinute;
|
|
13000
|
+
this.refilledAt = this.noteRefilledAt = this.now();
|
|
13001
|
+
}
|
|
13002
|
+
adapter;
|
|
13003
|
+
allowedAgents;
|
|
13004
|
+
allowedWorkspaces;
|
|
13005
|
+
windowMs;
|
|
13006
|
+
ratePerSecond;
|
|
13007
|
+
burst;
|
|
13008
|
+
notesPerMinute;
|
|
13009
|
+
now;
|
|
13010
|
+
log;
|
|
13011
|
+
send;
|
|
13012
|
+
unsubscribe;
|
|
13013
|
+
pending = /* @__PURE__ */ new Map();
|
|
13014
|
+
lastSent = /* @__PURE__ */ new Map();
|
|
13015
|
+
listChanged = false;
|
|
13016
|
+
lastListSent = Number.NEGATIVE_INFINITY;
|
|
13017
|
+
tokens;
|
|
13018
|
+
refilledAt;
|
|
13019
|
+
noteTokens;
|
|
13020
|
+
noteRefilledAt;
|
|
13021
|
+
timer;
|
|
13022
|
+
timerAt = Number.POSITIVE_INFINITY;
|
|
13023
|
+
/** Starts listening to the runtime. Runtimes without events are fine: only notes are sent then. */
|
|
13024
|
+
start() {
|
|
13025
|
+
if (this.unsubscribe || !this.adapter.onEvent) return;
|
|
13026
|
+
this.unsubscribe = this.adapter.onEvent((event) => this.push(event), this.log);
|
|
13027
|
+
}
|
|
13028
|
+
close() {
|
|
13029
|
+
this.unsubscribe?.();
|
|
13030
|
+
this.unsubscribe = void 0;
|
|
13031
|
+
this.detach();
|
|
13032
|
+
}
|
|
13033
|
+
attach(send) {
|
|
13034
|
+
this.send = send;
|
|
13035
|
+
this.pending.clear();
|
|
13036
|
+
this.listChanged = false;
|
|
13037
|
+
this.lastListSent = this.now();
|
|
13038
|
+
send(eventFrame("agents.changed", {}));
|
|
13039
|
+
}
|
|
13040
|
+
detach() {
|
|
13041
|
+
this.send = void 0;
|
|
13042
|
+
this.pending.clear();
|
|
13043
|
+
this.listChanged = false;
|
|
13044
|
+
if (this.timer) clearTimeout(this.timer);
|
|
13045
|
+
this.timer = void 0;
|
|
13046
|
+
this.timerAt = Number.POSITIVE_INFINITY;
|
|
13047
|
+
}
|
|
13048
|
+
get connected() {
|
|
13049
|
+
return this.send !== void 0;
|
|
13050
|
+
}
|
|
13051
|
+
push(event) {
|
|
13052
|
+
if (!this.send) return;
|
|
13053
|
+
if (event.kind === "agents_changed") this.listChanged = true;
|
|
13054
|
+
else {
|
|
13055
|
+
if (!this.visible(event.agentId, event.workspace)) return;
|
|
13056
|
+
this.pending.set(event.agentId, {
|
|
13057
|
+
agentId: event.agentId,
|
|
13058
|
+
status: event.status,
|
|
13059
|
+
previousStatus: event.previousStatus,
|
|
13060
|
+
label: event.label,
|
|
13061
|
+
workspace: event.workspace,
|
|
13062
|
+
revision: event.revision
|
|
13063
|
+
});
|
|
13064
|
+
}
|
|
13065
|
+
this.flush();
|
|
13066
|
+
}
|
|
13067
|
+
/** Sends an owner-directed note. Resolves the calling pane to an agent id when the runtime can. */
|
|
13068
|
+
async notify(input) {
|
|
13069
|
+
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
|
+
const text2 = cleanNote(input.text);
|
|
13071
|
+
const agentId = await this.resolveAgent(input.paneId);
|
|
13072
|
+
if (!this.send) return { sent: false, agentId };
|
|
13073
|
+
this.refillNotes();
|
|
13074
|
+
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
|
+
this.noteTokens -= 1;
|
|
13076
|
+
const frame = eventFrame("agent.notified", { agentId, text: text2, audience: "owner" });
|
|
13077
|
+
const sent = this.send(frame);
|
|
13078
|
+
return { sent, agentId, ...sent ? { eventId: frame.eventId } : {} };
|
|
13079
|
+
}
|
|
13080
|
+
async resolveAgent(paneId) {
|
|
13081
|
+
if (typeof paneId !== "string" || !PANE_ID.test(paneId) || !this.adapter.agentIdForPane) return null;
|
|
13082
|
+
try {
|
|
13083
|
+
const id = await this.adapter.agentIdForPane(paneId);
|
|
13084
|
+
if (!id) return null;
|
|
13085
|
+
if (!this.allowedAgents && !this.allowedWorkspaces) return id;
|
|
13086
|
+
const agent = await this.adapter.getAgent(id);
|
|
13087
|
+
return this.visible(agent.id, agent.workspace) ? agent.id : null;
|
|
13088
|
+
} catch {
|
|
13089
|
+
return null;
|
|
13090
|
+
}
|
|
13091
|
+
}
|
|
13092
|
+
visible(agentId, workspace) {
|
|
13093
|
+
if (this.allowedAgents && !this.allowedAgents.has(agentId)) return false;
|
|
13094
|
+
if (this.allowedWorkspaces && (workspace === null || !this.allowedWorkspaces.has(workspace))) return false;
|
|
13095
|
+
return true;
|
|
13096
|
+
}
|
|
13097
|
+
refill(now) {
|
|
13098
|
+
this.tokens = Math.min(this.burst, this.tokens + (now - this.refilledAt) / 1e3 * this.ratePerSecond);
|
|
13099
|
+
this.refilledAt = now;
|
|
13100
|
+
}
|
|
13101
|
+
refillNotes() {
|
|
13102
|
+
const now = this.now();
|
|
13103
|
+
this.noteTokens = Math.min(this.notesPerMinute, this.noteTokens + (now - this.noteRefilledAt) / 6e4 * this.notesPerMinute);
|
|
13104
|
+
this.noteRefilledAt = now;
|
|
13105
|
+
}
|
|
13106
|
+
flush() {
|
|
13107
|
+
const send = this.send;
|
|
13108
|
+
if (!send) return;
|
|
13109
|
+
const now = this.now();
|
|
13110
|
+
this.refill(now);
|
|
13111
|
+
let next = Number.POSITIVE_INFINITY;
|
|
13112
|
+
if (this.listChanged) {
|
|
13113
|
+
const due = this.lastListSent + this.windowMs;
|
|
13114
|
+
if (due > now) next = Math.min(next, due);
|
|
13115
|
+
else if (this.tokens >= 1) {
|
|
13116
|
+
this.tokens -= 1;
|
|
13117
|
+
this.listChanged = false;
|
|
13118
|
+
this.lastListSent = now;
|
|
13119
|
+
send(eventFrame("agents.changed", {}));
|
|
13120
|
+
}
|
|
13121
|
+
}
|
|
13122
|
+
for (const [agentId, data] of this.pending) {
|
|
13123
|
+
const due = (this.lastSent.get(agentId) ?? Number.NEGATIVE_INFINITY) + this.windowMs;
|
|
13124
|
+
if (due > now) {
|
|
13125
|
+
next = Math.min(next, due);
|
|
13126
|
+
continue;
|
|
13127
|
+
}
|
|
13128
|
+
if (this.tokens < 1) break;
|
|
13129
|
+
this.tokens -= 1;
|
|
13130
|
+
this.pending.delete(agentId);
|
|
13131
|
+
this.lastSent.set(agentId, now);
|
|
13132
|
+
send(eventFrame("agent.status_changed", data));
|
|
13133
|
+
}
|
|
13134
|
+
for (const [agentId, at] of this.lastSent) if (at + this.windowMs <= now && !this.pending.has(agentId)) this.lastSent.delete(agentId);
|
|
13135
|
+
if ((this.pending.size > 0 || this.listChanged) && this.tokens < 1) next = Math.min(next, now + Math.ceil((1 - this.tokens) / this.ratePerSecond * 1e3));
|
|
13136
|
+
this.schedule(next);
|
|
13137
|
+
}
|
|
13138
|
+
schedule(at) {
|
|
13139
|
+
if (!Number.isFinite(at)) return;
|
|
13140
|
+
if (this.timer && this.timerAt <= at) return;
|
|
13141
|
+
if (this.timer) clearTimeout(this.timer);
|
|
13142
|
+
this.timerAt = at;
|
|
13143
|
+
this.timer = setTimeout(() => {
|
|
13144
|
+
this.timer = void 0;
|
|
13145
|
+
this.timerAt = Number.POSITIVE_INFINITY;
|
|
13146
|
+
this.flush();
|
|
13147
|
+
}, Math.max(0, at - this.now()));
|
|
13148
|
+
this.timer.unref?.();
|
|
13149
|
+
}
|
|
13150
|
+
};
|
|
13151
|
+
|
|
12848
13152
|
// src/cli/types.ts
|
|
12849
13153
|
var UsageError = class extends Error {
|
|
12850
13154
|
hint;
|
|
@@ -12889,11 +13193,11 @@ function suggest(input, candidates) {
|
|
|
12889
13193
|
return best?.name;
|
|
12890
13194
|
}
|
|
12891
13195
|
var HELP_OPTION = { name: "help", short: "h", type: "boolean", description: "Show help for this command." };
|
|
12892
|
-
function parseArgs(
|
|
12893
|
-
const options = [...
|
|
13196
|
+
function parseArgs(spec11, argv) {
|
|
13197
|
+
const options = [...spec11.options, HELP_OPTION];
|
|
12894
13198
|
const values = {};
|
|
12895
13199
|
const positionals = [];
|
|
12896
|
-
const helpHint = `Run \`peerband ${
|
|
13200
|
+
const helpHint = `Run \`peerband ${spec11.name} --help\` for usage.`;
|
|
12897
13201
|
for (let i = 0; i < argv.length; i++) {
|
|
12898
13202
|
const arg = argv[i];
|
|
12899
13203
|
if (arg === "--") {
|
|
@@ -12913,11 +13217,11 @@ function parseArgs(spec6, argv) {
|
|
|
12913
13217
|
option = options.find((candidate) => candidate.name === name);
|
|
12914
13218
|
if (!option) {
|
|
12915
13219
|
const near = suggest(name, options.filter((o) => !o.hidden).map((o) => o.name));
|
|
12916
|
-
throw new UsageError(`Unknown option --${name} for \`peerband ${
|
|
13220
|
+
throw new UsageError(`Unknown option --${name} for \`peerband ${spec11.name}\`.`, near ? `Did you mean --${near}? ${helpHint}` : helpHint);
|
|
12917
13221
|
}
|
|
12918
13222
|
} else {
|
|
12919
13223
|
option = options.find((candidate) => candidate.short === arg.slice(1));
|
|
12920
|
-
if (!option) throw new UsageError(`Unknown option ${arg} for \`peerband ${
|
|
13224
|
+
if (!option) throw new UsageError(`Unknown option ${arg} for \`peerband ${spec11.name}\`.`, helpHint);
|
|
12921
13225
|
}
|
|
12922
13226
|
if (option.type === "boolean") {
|
|
12923
13227
|
if (inline !== void 0) throw new UsageError(`Option --${option.name} does not take a value.`, helpHint);
|
|
@@ -12935,9 +13239,9 @@ function parseArgs(spec6, argv) {
|
|
|
12935
13239
|
}
|
|
12936
13240
|
values[option.name] = value;
|
|
12937
13241
|
}
|
|
12938
|
-
const max =
|
|
13242
|
+
const max = spec11.positionals?.max ?? 0;
|
|
12939
13243
|
if (positionals.length > max) {
|
|
12940
|
-
throw new UsageError(`Unexpected argument "${positionals[max]}" for \`peerband ${
|
|
13244
|
+
throw new UsageError(`Unexpected argument "${positionals[max]}" for \`peerband ${spec11.name}\`.`, helpHint);
|
|
12941
13245
|
}
|
|
12942
13246
|
return { values, positionals };
|
|
12943
13247
|
}
|
|
@@ -12981,87 +13285,880 @@ function failureDetail(result) {
|
|
|
12981
13285
|
return detail.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, 400);
|
|
12982
13286
|
}
|
|
12983
13287
|
|
|
12984
|
-
//
|
|
12985
|
-
import {
|
|
13288
|
+
// herdr/relay-tab.mjs
|
|
13289
|
+
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";
|
|
13291
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
13292
|
+
import { dirname as dirname3 } from "node:path";
|
|
12986
13293
|
|
|
12987
|
-
//
|
|
12988
|
-
import { createHash as createHash2
|
|
12989
|
-
import {
|
|
12990
|
-
import {
|
|
12991
|
-
|
|
13294
|
+
// herdr/paths.mjs
|
|
13295
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
13296
|
+
import { homedir as homedir2, tmpdir } from "node:os";
|
|
13297
|
+
import { join as join3, posix, resolve, win32 } from "node:path";
|
|
13298
|
+
function configHome2(env = process.env, platform = process.platform, home = homedir2()) {
|
|
13299
|
+
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");
|
|
13302
|
+
}
|
|
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");
|
|
13306
|
+
function canonicalConfig(config, platform = process.platform) {
|
|
13307
|
+
const resolved = (platform === "win32" ? win32 : posix).resolve(config);
|
|
13308
|
+
return platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
13309
|
+
}
|
|
13310
|
+
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`);
|
|
13313
|
+
}
|
|
12992
13314
|
|
|
12993
|
-
//
|
|
12994
|
-
import {
|
|
12995
|
-
|
|
12996
|
-
var
|
|
12997
|
-
|
|
12998
|
-
|
|
12999
|
-
|
|
13000
|
-
|
|
13001
|
-
|
|
13002
|
-
|
|
13003
|
-
|
|
13004
|
-
|
|
13005
|
-
sockets = /* @__PURE__ */ new Set();
|
|
13006
|
-
buffers = /* @__PURE__ */ new WeakMap();
|
|
13007
|
-
pending = /* @__PURE__ */ new Map();
|
|
13008
|
-
closed = false;
|
|
13009
|
-
epoch = 0;
|
|
13010
|
-
inflight = 0;
|
|
13011
|
-
constructor(options) {
|
|
13012
|
-
this.socketPath = options.socketPath;
|
|
13013
|
-
this.timeoutMs = options.timeoutMs ?? 5e3;
|
|
13014
|
-
this.maxLineBytes = options.maxLineBytes ?? 2 * 1024 * 1024;
|
|
13015
|
-
this.maxPending = options.maxPending ?? 32;
|
|
13016
|
-
this.validateSuccessResponse = options.validateSuccessResponse;
|
|
13017
|
-
this.validateErrorResponse = options.validateErrorResponse;
|
|
13018
|
-
this.validateRequest = options.validateRequest;
|
|
13019
|
-
this.schemaDiagnostics = options.schemaDiagnostics;
|
|
13315
|
+
// herdr/relay-tab.mjs
|
|
13316
|
+
import { promisify } from "node:util";
|
|
13317
|
+
var exec = promisify(execFile2);
|
|
13318
|
+
var pluginId = "peerband";
|
|
13319
|
+
var entrypoint = "relay";
|
|
13320
|
+
var markerName = "peerband_relay";
|
|
13321
|
+
var markerSource = "peerband-relay";
|
|
13322
|
+
var tabTitle = (enabled) => `PeerBand Relay [${enabled ? "On" : "Off"}]`;
|
|
13323
|
+
var productionController;
|
|
13324
|
+
function describeHerdrFailure(error, binary = "herdr") {
|
|
13325
|
+
if (error?.code === "ENOENT") {
|
|
13326
|
+
return `Herdr was not found (${binary}). Install Herdr, put it on PATH, or set HERDR_BIN_PATH to its executable.`;
|
|
13020
13327
|
}
|
|
13021
|
-
|
|
13022
|
-
|
|
13328
|
+
const detail = safeFailure(error);
|
|
13329
|
+
if (/plugin/i.test(detail) && /not found|not installed|unknown|no such|does not exist|not registered/i.test(detail)) {
|
|
13330
|
+
return `The PeerBand plugin is not installed in Herdr (${detail}). Run \`peerband herdr install\`.`;
|
|
13023
13331
|
}
|
|
13024
|
-
|
|
13025
|
-
|
|
13026
|
-
|
|
13027
|
-
|
|
13028
|
-
|
|
13029
|
-
|
|
13030
|
-
|
|
13031
|
-
|
|
13032
|
-
|
|
13033
|
-
|
|
13034
|
-
|
|
13332
|
+
return detail;
|
|
13333
|
+
}
|
|
13334
|
+
function productionOptions() {
|
|
13335
|
+
return {
|
|
13336
|
+
run: async (args) => {
|
|
13337
|
+
const binary = process.env.HERDR_BIN_PATH || "herdr";
|
|
13338
|
+
try {
|
|
13339
|
+
const result = await exec(binary, args, { timeout: 1e4, windowsHide: true, maxBuffer: 65536 });
|
|
13340
|
+
return parseHerdrCommandOutput(result.stdout, args);
|
|
13341
|
+
} catch (error) {
|
|
13342
|
+
throw new Error(`${args.slice(0, args[0] === "plugin" ? 3 : 2).join(" ")}: ${describeHerdrFailure(error, binary)}`);
|
|
13343
|
+
}
|
|
13344
|
+
},
|
|
13345
|
+
statePath: relayTabPath2(),
|
|
13346
|
+
pluginPaneId: process.env.HERDR_PANE_ID,
|
|
13347
|
+
warn: (message) => process.stderr.write(`${message}
|
|
13348
|
+
`)
|
|
13349
|
+
};
|
|
13350
|
+
}
|
|
13351
|
+
function safeFailure(error) {
|
|
13352
|
+
const raw = typeof error?.stderr === "string" && error.stderr.trim() ? error.stderr : error?.message;
|
|
13353
|
+
let detail = raw;
|
|
13354
|
+
try {
|
|
13355
|
+
const response = JSON.parse(raw);
|
|
13356
|
+
detail = response.error?.message || response.message || "Herdr rejected the command";
|
|
13357
|
+
} catch {
|
|
13358
|
+
}
|
|
13359
|
+
return String(detail || "Herdr command failed").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 400);
|
|
13360
|
+
}
|
|
13361
|
+
function parseHerdrCommandOutput(raw, args) {
|
|
13362
|
+
const needsData = args[0] === "pane" && ["get", "list"].includes(args[1]) || args[0] === "plugin" && args[1] === "pane" && args[2] === "open";
|
|
13363
|
+
const text2 = raw.trim();
|
|
13364
|
+
if (!text2 && !needsData) return {};
|
|
13365
|
+
let value;
|
|
13366
|
+
try {
|
|
13367
|
+
value = JSON.parse(text2);
|
|
13368
|
+
} catch {
|
|
13369
|
+
if (!needsData) return {};
|
|
13370
|
+
throw new Error("Herdr returned an invalid JSON data response");
|
|
13371
|
+
}
|
|
13372
|
+
if (value?.ok === false || value?.error) throw new Error(value.error?.message || "Herdr command failed");
|
|
13373
|
+
if (!value || typeof value !== "object") {
|
|
13374
|
+
if (!needsData) return {};
|
|
13375
|
+
throw new Error("Herdr returned no pane data");
|
|
13376
|
+
}
|
|
13377
|
+
return value.result ?? value;
|
|
13378
|
+
}
|
|
13379
|
+
async function readRecord(statePath) {
|
|
13380
|
+
try {
|
|
13381
|
+
const value = JSON.parse(await readFile4(statePath, "utf8"));
|
|
13382
|
+
if (value?.version === 1 && typeof value.paneId === "string" && typeof value.marker === "string") return value;
|
|
13383
|
+
} catch {
|
|
13384
|
+
}
|
|
13385
|
+
return void 0;
|
|
13386
|
+
}
|
|
13387
|
+
async function writeRecord(statePath, record) {
|
|
13388
|
+
await mkdir3(dirname3(statePath), { recursive: true });
|
|
13389
|
+
const temporary = `${statePath}.${randomUUID3()}.tmp`;
|
|
13390
|
+
try {
|
|
13391
|
+
await writeFile3(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
13392
|
+
await rename3(temporary, statePath);
|
|
13393
|
+
} finally {
|
|
13394
|
+
await rm3(temporary, { force: true }).catch(() => {
|
|
13395
|
+
});
|
|
13396
|
+
}
|
|
13397
|
+
}
|
|
13398
|
+
async function withLaunchLock(statePath, action) {
|
|
13399
|
+
const lockPath3 = `${statePath}.launch-lock`;
|
|
13400
|
+
await mkdir3(dirname3(statePath), { recursive: true });
|
|
13401
|
+
const deadline = Date.now() + 5e3;
|
|
13402
|
+
while (true) {
|
|
13035
13403
|
try {
|
|
13036
|
-
|
|
13404
|
+
await mkdir3(lockPath3);
|
|
13405
|
+
break;
|
|
13037
13406
|
} catch (error) {
|
|
13038
|
-
|
|
13039
|
-
|
|
13040
|
-
|
|
13041
|
-
|
|
13042
|
-
|
|
13043
|
-
|
|
13044
|
-
|
|
13045
|
-
|
|
13046
|
-
|
|
13047
|
-
}, this.timeoutMs);
|
|
13048
|
-
timer.unref?.();
|
|
13049
|
-
this.pending.set(id, { resolve: resolve5, reject, timer, method, socket });
|
|
13050
|
-
socket.write(line, (error) => {
|
|
13051
|
-
if (!error) return;
|
|
13052
|
-
const pending = this.pending.get(id);
|
|
13053
|
-
if (pending) {
|
|
13054
|
-
this.pending.delete(id);
|
|
13055
|
-
clearTimeout(timer);
|
|
13056
|
-
this.inflight -= 1;
|
|
13057
|
-
reject(this.mapTransportError(method));
|
|
13407
|
+
if (error?.code !== "EEXIST") throw error;
|
|
13408
|
+
let stale = false;
|
|
13409
|
+
try {
|
|
13410
|
+
const info = await stat(lockPath3);
|
|
13411
|
+
if (Date.now() - info.mtimeMs > 12e4) {
|
|
13412
|
+
const quarantine = `${lockPath3}.stale-${randomUUID3()}`;
|
|
13413
|
+
await rename3(lockPath3, quarantine).then(() => rmdir2(quarantine)).catch(() => {
|
|
13414
|
+
});
|
|
13415
|
+
stale = true;
|
|
13058
13416
|
}
|
|
13059
|
-
}
|
|
13417
|
+
} catch {
|
|
13418
|
+
stale = true;
|
|
13419
|
+
}
|
|
13420
|
+
if (stale) continue;
|
|
13421
|
+
if (Date.now() >= deadline) throw new Error("Another PeerBand Relay tab launch is already in progress");
|
|
13422
|
+
await new Promise((resolve5) => setTimeout(resolve5, 100));
|
|
13423
|
+
}
|
|
13424
|
+
}
|
|
13425
|
+
try {
|
|
13426
|
+
return await action();
|
|
13427
|
+
} finally {
|
|
13428
|
+
await rmdir2(lockPath3).catch(() => {
|
|
13060
13429
|
});
|
|
13061
13430
|
}
|
|
13062
|
-
|
|
13063
|
-
|
|
13064
|
-
|
|
13431
|
+
}
|
|
13432
|
+
async function inspectOwned(run3, record) {
|
|
13433
|
+
if (!record) return void 0;
|
|
13434
|
+
let pane;
|
|
13435
|
+
try {
|
|
13436
|
+
pane = (await run3(["pane", "get", record.paneId])).pane;
|
|
13437
|
+
} catch {
|
|
13438
|
+
return void 0;
|
|
13439
|
+
}
|
|
13440
|
+
if (!pane || pane.pane_id !== record.paneId || pane.tokens?.[markerName] !== record.marker) return void 0;
|
|
13441
|
+
return pane;
|
|
13442
|
+
}
|
|
13443
|
+
async function findMarkedPane(run3) {
|
|
13444
|
+
let listed;
|
|
13445
|
+
try {
|
|
13446
|
+
listed = (await run3(["pane", "list"])).panes;
|
|
13447
|
+
} catch {
|
|
13448
|
+
return void 0;
|
|
13449
|
+
}
|
|
13450
|
+
if (!Array.isArray(listed)) return void 0;
|
|
13451
|
+
return listed.find((item) => typeof item?.pane_id === "string" && typeof item.tokens?.[markerName] === "string" && item.tokens[markerName]);
|
|
13452
|
+
}
|
|
13453
|
+
async function renameOwnedSinglePaneTab(run3, pane, label) {
|
|
13454
|
+
if (!pane?.workspace_id || !pane?.tab_id || !pane?.pane_id) return false;
|
|
13455
|
+
let listed;
|
|
13456
|
+
try {
|
|
13457
|
+
listed = (await run3(["pane", "list", "--workspace", pane.workspace_id])).panes;
|
|
13458
|
+
} catch {
|
|
13459
|
+
return false;
|
|
13460
|
+
}
|
|
13461
|
+
if (!Array.isArray(listed)) return false;
|
|
13462
|
+
const inTab = listed.filter((item) => item.tab_id === pane.tab_id);
|
|
13463
|
+
if (inTab.length !== 1 || inTab[0]?.pane_id !== pane.pane_id) return false;
|
|
13464
|
+
await run3(["tab", "rename", pane.tab_id, label]);
|
|
13465
|
+
return true;
|
|
13466
|
+
}
|
|
13467
|
+
function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker = randomUUID3, warn = () => {
|
|
13468
|
+
} }) {
|
|
13469
|
+
if (typeof run3 !== "function" || typeof statePath !== "string") throw new TypeError("run and statePath are required");
|
|
13470
|
+
const lastVerifiedTitle = /* @__PURE__ */ new Map();
|
|
13471
|
+
async function sync(enabled) {
|
|
13472
|
+
if (typeof pluginPaneId !== "string" || !pluginPaneId) return false;
|
|
13473
|
+
const record = await readRecord(statePath);
|
|
13474
|
+
if (!record || record.paneId !== pluginPaneId) return false;
|
|
13475
|
+
const pane = await inspectOwned(run3, record);
|
|
13476
|
+
if (!pane) return false;
|
|
13477
|
+
try {
|
|
13478
|
+
const label = tabTitle(enabled);
|
|
13479
|
+
const key = `${pane.pane_id}\0${pane.tab_id}`;
|
|
13480
|
+
if (lastVerifiedTitle.get(key) === label) return true;
|
|
13481
|
+
const renamed = await renameOwnedSinglePaneTab(run3, pane, label);
|
|
13482
|
+
if (renamed) lastVerifiedTitle.set(key, label);
|
|
13483
|
+
return renamed;
|
|
13484
|
+
} catch {
|
|
13485
|
+
return false;
|
|
13486
|
+
}
|
|
13487
|
+
}
|
|
13488
|
+
async function close() {
|
|
13489
|
+
const record = await readRecord(statePath);
|
|
13490
|
+
if (!record || pluginPaneId !== record.paneId) return false;
|
|
13491
|
+
if (!await inspectOwned(run3, record)) return false;
|
|
13492
|
+
try {
|
|
13493
|
+
await run3(["plugin", "pane", "close", record.paneId]);
|
|
13494
|
+
await rm3(statePath, { force: true });
|
|
13495
|
+
return true;
|
|
13496
|
+
} catch {
|
|
13497
|
+
return false;
|
|
13498
|
+
}
|
|
13499
|
+
}
|
|
13500
|
+
async function open() {
|
|
13501
|
+
return withLaunchLock(statePath, async () => {
|
|
13502
|
+
const previous = await readRecord(statePath);
|
|
13503
|
+
const pane = await inspectOwned(run3, previous);
|
|
13504
|
+
if (pane) {
|
|
13505
|
+
await run3(["plugin", "pane", "focus", pane.pane_id]);
|
|
13506
|
+
return pane.pane_id;
|
|
13507
|
+
}
|
|
13508
|
+
const existing = await findMarkedPane(run3);
|
|
13509
|
+
if (existing) {
|
|
13510
|
+
await writeRecord(statePath, { version: 1, paneId: existing.pane_id, marker: existing.tokens[markerName] });
|
|
13511
|
+
await run3(["plugin", "pane", "focus", existing.pane_id]);
|
|
13512
|
+
return existing.pane_id;
|
|
13513
|
+
}
|
|
13514
|
+
const result = await run3(["plugin", "pane", "open", "--plugin", pluginId, "--entrypoint", entrypoint, "--placement", "tab", "--focus"]);
|
|
13515
|
+
const opened = result.plugin_pane;
|
|
13516
|
+
if (opened?.plugin_id !== pluginId || opened?.entrypoint !== entrypoint || typeof opened.pane?.pane_id !== "string") {
|
|
13517
|
+
throw new Error("Herdr did not return the expected plugin pane");
|
|
13518
|
+
}
|
|
13519
|
+
const record = { version: 1, paneId: opened.pane.pane_id, marker: newMarker() };
|
|
13520
|
+
try {
|
|
13521
|
+
await renameOwnedSinglePaneTab(run3, opened.pane, tabTitle(false)).catch((error) => {
|
|
13522
|
+
warn(`Relay tab opened; its initial title could not be set: ${safeFailure(error)}`);
|
|
13523
|
+
});
|
|
13524
|
+
await writeRecord(statePath, record);
|
|
13525
|
+
await run3(["pane", "report-metadata", record.paneId, "--source", markerSource, "--token", `${markerName}=${record.marker}`]);
|
|
13526
|
+
const marked = await inspectOwned(run3, record);
|
|
13527
|
+
if (!marked) throw new Error("Herdr did not retain the plugin pane ownership marker");
|
|
13528
|
+
return record.paneId;
|
|
13529
|
+
} catch (error) {
|
|
13530
|
+
await run3(["plugin", "pane", "close", record.paneId]).catch(() => {
|
|
13531
|
+
});
|
|
13532
|
+
const current = await readRecord(statePath);
|
|
13533
|
+
if (current?.paneId === record.paneId && current.marker === record.marker) await rm3(statePath, { force: true }).catch(() => {
|
|
13534
|
+
});
|
|
13535
|
+
throw error;
|
|
13536
|
+
}
|
|
13537
|
+
});
|
|
13538
|
+
}
|
|
13539
|
+
return { open, sync, close };
|
|
13540
|
+
}
|
|
13541
|
+
function getProductionController() {
|
|
13542
|
+
productionController ??= createRelayTabController(productionOptions());
|
|
13543
|
+
return productionController;
|
|
13544
|
+
}
|
|
13545
|
+
async function openRelayTab(options) {
|
|
13546
|
+
const controller = options ? createRelayTabController({ ...productionOptions(), ...options }) : getProductionController();
|
|
13547
|
+
return controller.open();
|
|
13548
|
+
}
|
|
13549
|
+
|
|
13550
|
+
// herdr/pane-state.mjs
|
|
13551
|
+
var CONNECTION_STATES = /* @__PURE__ */ new Set(["connecting", "connected", "reconnecting", "revoked", "unavailable", "remote-unavailable", "helper-unavailable", "disabled"]);
|
|
13552
|
+
var OUTCOMES = /* @__PURE__ */ new Set(["success", "runtime-unavailable", "error", "uncertain", "timeout"]);
|
|
13553
|
+
var TOOLS = /* @__PURE__ */ new Set(["list_agents", "get_agent_status", "get_agent_output", "get_request_status", "send_agent_message"]);
|
|
13554
|
+
function normalizeStoredActivity(value) {
|
|
13555
|
+
if (!value || typeof value !== "object" || typeof value.requestId !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(value.requestId) || !TOOLS.has(value.tool) || !OUTCOMES.has(value.outcome) || !Number.isFinite(value.latencyMs) || typeof value.at !== "string" || Number.isNaN(Date.parse(value.at))) return null;
|
|
13556
|
+
return { kind: "activity", requestId: value.requestId, tool: value.tool, ...typeof value.target === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value.target) ? { target: value.target } : {}, outcome: value.outcome, latencyMs: Math.max(0, Math.min(864e5, Math.round(value.latencyMs))), at: new Date(value.at).toISOString() };
|
|
13557
|
+
}
|
|
13558
|
+
function createPaneSnapshot({ state, connectionState, activity }) {
|
|
13559
|
+
return {
|
|
13560
|
+
state: state === "running" ? "running" : "stopping",
|
|
13561
|
+
connectionState: CONNECTION_STATES.has(connectionState) ? connectionState : "unavailable",
|
|
13562
|
+
activity: Array.isArray(activity) ? activity.map(normalizeStoredActivity).filter(Boolean).slice(-100) : []
|
|
13563
|
+
};
|
|
13564
|
+
}
|
|
13565
|
+
function fallbackPaneSnapshot(value) {
|
|
13566
|
+
const snapshot = createPaneSnapshot(value);
|
|
13567
|
+
return {
|
|
13568
|
+
...snapshot,
|
|
13569
|
+
state: "stopping",
|
|
13570
|
+
connectionState: snapshot.connectionState === "revoked" || snapshot.connectionState === "disabled" ? snapshot.connectionState : "helper-unavailable"
|
|
13571
|
+
};
|
|
13572
|
+
}
|
|
13573
|
+
function paneLabel(snapshot) {
|
|
13574
|
+
if (!snapshot) return "Disconnected";
|
|
13575
|
+
switch (snapshot.connectionState) {
|
|
13576
|
+
case "connected":
|
|
13577
|
+
return "Connected";
|
|
13578
|
+
case "connecting":
|
|
13579
|
+
return "Connecting";
|
|
13580
|
+
case "reconnecting":
|
|
13581
|
+
return "Reconnecting";
|
|
13582
|
+
case "revoked":
|
|
13583
|
+
return "Access revoked";
|
|
13584
|
+
case "remote-unavailable":
|
|
13585
|
+
return "PeerBand unavailable";
|
|
13586
|
+
case "helper-unavailable":
|
|
13587
|
+
return "Helper unavailable";
|
|
13588
|
+
case "unavailable":
|
|
13589
|
+
return "Herdr unavailable";
|
|
13590
|
+
case "disabled":
|
|
13591
|
+
return "Disconnected";
|
|
13592
|
+
default:
|
|
13593
|
+
return "Herdr unavailable";
|
|
13594
|
+
}
|
|
13595
|
+
}
|
|
13596
|
+
|
|
13597
|
+
// herdr/stale-lock.mjs
|
|
13598
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
13599
|
+
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";
|
|
13601
|
+
import { createConnection } from "node:net";
|
|
13602
|
+
import { hostname as hostname2 } from "node:os";
|
|
13603
|
+
import { join as join4, relative } from "node:path";
|
|
13604
|
+
var CREATION_GRACE_MS = 1e4;
|
|
13605
|
+
var SUPERVISOR_PATTERN = /lifecycle\.mjs["']?\s+supervise\b/i;
|
|
13606
|
+
var CONNECTOR_PATTERN = /peerband(?:\.mjs|\.cmd|\.ps1)?["']?\s+connect\b/i;
|
|
13607
|
+
function pidAlive2(pid) {
|
|
13608
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
13609
|
+
try {
|
|
13610
|
+
process.kill(pid, 0);
|
|
13611
|
+
return true;
|
|
13612
|
+
} catch (error) {
|
|
13613
|
+
return Boolean(error && error.code === "EPERM");
|
|
13614
|
+
}
|
|
13615
|
+
}
|
|
13616
|
+
function probeChannel(channel, timeout = 1500) {
|
|
13617
|
+
return new Promise((resolve5) => {
|
|
13618
|
+
let settled = false;
|
|
13619
|
+
const socket = createConnection(channel);
|
|
13620
|
+
const finish = (value) => {
|
|
13621
|
+
if (settled) return;
|
|
13622
|
+
settled = true;
|
|
13623
|
+
clearTimeout(timer);
|
|
13624
|
+
socket.destroy();
|
|
13625
|
+
resolve5(value);
|
|
13626
|
+
};
|
|
13627
|
+
const timer = setTimeout(() => finish("unknown"), timeout);
|
|
13628
|
+
socket.once("connect", () => finish("listening"));
|
|
13629
|
+
socket.once("error", (error) => finish(error && (error.code === "ENOENT" || error.code === "ECONNREFUSED") ? "absent" : "unknown"));
|
|
13630
|
+
});
|
|
13631
|
+
}
|
|
13632
|
+
function run(file, args, timeout) {
|
|
13633
|
+
return new Promise((resolve5) => {
|
|
13634
|
+
execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve5(error ? null : String(stdout)));
|
|
13635
|
+
});
|
|
13636
|
+
}
|
|
13637
|
+
async function listProcesses(platform = process.platform) {
|
|
13638
|
+
if (platform === "linux") {
|
|
13639
|
+
let entries;
|
|
13640
|
+
try {
|
|
13641
|
+
entries = await readdir("/proc");
|
|
13642
|
+
} catch {
|
|
13643
|
+
return null;
|
|
13644
|
+
}
|
|
13645
|
+
const result = [];
|
|
13646
|
+
for (const entry of entries) {
|
|
13647
|
+
if (!/^\d+$/.test(entry)) continue;
|
|
13648
|
+
try {
|
|
13649
|
+
const command = (await readFile5(`/proc/${entry}/cmdline`, "utf8")).split("\0").join(" ").trim();
|
|
13650
|
+
if (command) result.push({ pid: Number(entry), command });
|
|
13651
|
+
} catch {
|
|
13652
|
+
}
|
|
13653
|
+
}
|
|
13654
|
+
return result;
|
|
13655
|
+
}
|
|
13656
|
+
if (platform === "win32") {
|
|
13657
|
+
const script = `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`;
|
|
13658
|
+
const text3 = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 15e3);
|
|
13659
|
+
if (text3 === null) return null;
|
|
13660
|
+
return parseProcessLines(text3, " ");
|
|
13661
|
+
}
|
|
13662
|
+
const text2 = await run("ps", ["-axo", "pid=,command="], 1e4);
|
|
13663
|
+
return text2 === null ? null : parseProcessLines(text2, " ");
|
|
13664
|
+
}
|
|
13665
|
+
function parseProcessLines(text2, separator) {
|
|
13666
|
+
const result = [];
|
|
13667
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
13668
|
+
const line = raw.trim();
|
|
13669
|
+
if (!line) continue;
|
|
13670
|
+
const at = line.indexOf(separator);
|
|
13671
|
+
const pid = Number(at < 0 ? line : line.slice(0, at));
|
|
13672
|
+
if (Number.isSafeInteger(pid) && pid > 0) result.push({ pid, command: at < 0 ? "" : line.slice(at + 1).trim() });
|
|
13673
|
+
}
|
|
13674
|
+
return result;
|
|
13675
|
+
}
|
|
13676
|
+
async function readOwner(ownerFile) {
|
|
13677
|
+
let text2;
|
|
13678
|
+
try {
|
|
13679
|
+
text2 = await readFile5(ownerFile, "utf8");
|
|
13680
|
+
} catch {
|
|
13681
|
+
return { text: null, owner: null };
|
|
13682
|
+
}
|
|
13683
|
+
try {
|
|
13684
|
+
const value = JSON.parse(text2);
|
|
13685
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return { text: text2, owner: value };
|
|
13686
|
+
} catch {
|
|
13687
|
+
}
|
|
13688
|
+
return { text: text2, owner: {} };
|
|
13689
|
+
}
|
|
13690
|
+
async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list2 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now = Date.now() }) {
|
|
13691
|
+
let info;
|
|
13692
|
+
try {
|
|
13693
|
+
info = await stat2(lockDir);
|
|
13694
|
+
} catch (error) {
|
|
13695
|
+
if (error && error.code === "ENOENT") return { state: "absent", reason: "no lock", ownerText: null };
|
|
13696
|
+
return { state: "live", reason: `the lock could not be read (${error && error.code})`, ownerText: null };
|
|
13697
|
+
}
|
|
13698
|
+
const { text: text2, owner } = await readOwner(ownerFile);
|
|
13699
|
+
const ignore = /* @__PURE__ */ new Set([process.pid, ...excludePids]);
|
|
13700
|
+
const matching = async (keep) => {
|
|
13701
|
+
if (!processPattern) return null;
|
|
13702
|
+
const processes = await list2();
|
|
13703
|
+
if (!processes) return null;
|
|
13704
|
+
return processes.filter((item) => (item.pid === keep || !ignore.has(item.pid)) && processPattern.test(item.command));
|
|
13705
|
+
};
|
|
13706
|
+
if (owner && Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
13707
|
+
const pid = owner.pid;
|
|
13708
|
+
if (typeof owner.hostname === "string" && owner.hostname && owner.hostname !== host) {
|
|
13709
|
+
return { state: "live", reason: `the owner runs on another host (${owner.hostname})`, ownerText: text2, pid };
|
|
13710
|
+
}
|
|
13711
|
+
if (!alive(pid)) return { state: "stale", reason: `owner process ${pid} is not running`, ownerText: text2, pid };
|
|
13712
|
+
if (channel && await probe(channel) !== "absent") return { state: "live", reason: `owner process ${pid} is running`, ownerText: text2, pid };
|
|
13713
|
+
const candidates2 = await matching(pid);
|
|
13714
|
+
if (candidates2 && !candidates2.some((item) => item.pid === pid)) {
|
|
13715
|
+
return { state: "stale", reason: `process ${pid} is running but is not a PeerBand ${channel ? "helper" : "connector"}`, ownerText: text2, pid };
|
|
13716
|
+
}
|
|
13717
|
+
return { state: "live", reason: `owner process ${pid} is running`, ownerText: text2, pid };
|
|
13718
|
+
}
|
|
13719
|
+
if (text2 === null && now - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
|
|
13720
|
+
if (channel) {
|
|
13721
|
+
const probed = await probe(channel);
|
|
13722
|
+
if (probed === "listening") return { state: "live", reason: "a helper answers on the control channel", ownerText: text2 };
|
|
13723
|
+
if (probed === "unknown") return { state: "live", reason: "the control channel could not be checked", ownerText: text2 };
|
|
13724
|
+
return { state: "stale", reason: "no helper answers on the control channel", ownerText: text2 };
|
|
13725
|
+
}
|
|
13726
|
+
const candidates = await matching();
|
|
13727
|
+
if (candidates && candidates.length > 0) {
|
|
13728
|
+
return { state: "live", reason: `a matching process is running (pid ${candidates.map((item) => item.pid).join(", ")})`, ownerText: text2 };
|
|
13729
|
+
}
|
|
13730
|
+
if (!candidates) return { state: "live", reason: "running processes could not be listed", ownerText: text2 };
|
|
13731
|
+
return { state: "stale", reason: "no matching process is running", ownerText: text2 };
|
|
13732
|
+
}
|
|
13733
|
+
async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
|
|
13734
|
+
const quarantine = `${lockDir}.stale-${randomUUID4()}`;
|
|
13735
|
+
try {
|
|
13736
|
+
await rename4(lockDir, quarantine);
|
|
13737
|
+
} catch (error) {
|
|
13738
|
+
return Boolean(error && error.code === "ENOENT");
|
|
13739
|
+
}
|
|
13740
|
+
const moved = await readOwner(join4(quarantine, relative(lockDir, ownerFile)));
|
|
13741
|
+
if (expectedOwnerText !== void 0 && moved.text !== expectedOwnerText) {
|
|
13742
|
+
await rename4(quarantine, lockDir).catch(() => {
|
|
13743
|
+
});
|
|
13744
|
+
return false;
|
|
13745
|
+
}
|
|
13746
|
+
await rm4(quarantine, { recursive: true, force: true }).catch(() => {
|
|
13747
|
+
});
|
|
13748
|
+
return true;
|
|
13749
|
+
}
|
|
13750
|
+
async function reclaimIfStale(options) {
|
|
13751
|
+
const verdict = await inspectLock(options);
|
|
13752
|
+
if (verdict.state !== "stale") return { reclaimed: false, verdict };
|
|
13753
|
+
const reclaimed = await reclaimLock({ lockDir: options.lockDir, ownerFile: options.ownerFile, expectedOwnerText: verdict.ownerText ?? void 0 });
|
|
13754
|
+
if (reclaimed && options.log) options.log(`Reclaimed a stale lock ${options.lockDir} (${verdict.reason}).`);
|
|
13755
|
+
return { reclaimed, verdict };
|
|
13756
|
+
}
|
|
13757
|
+
async function resetRelayState(path) {
|
|
13758
|
+
let previous = {};
|
|
13759
|
+
try {
|
|
13760
|
+
previous = JSON.parse(await readFile5(path, "utf8")) || {};
|
|
13761
|
+
} catch (error) {
|
|
13762
|
+
if (error && error.code === "ENOENT") return false;
|
|
13763
|
+
}
|
|
13764
|
+
const activity = Array.isArray(previous.activity) ? previous.activity : [];
|
|
13765
|
+
if (previous.state === "stopping" && previous.connectionState === "disabled") return false;
|
|
13766
|
+
await writeFile4(path, `${JSON.stringify({ state: "stopping", connectionState: "disabled", activity })}
|
|
13767
|
+
`, { mode: 384 });
|
|
13768
|
+
return true;
|
|
13769
|
+
}
|
|
13770
|
+
|
|
13771
|
+
// src/cli/herdr-js.ts
|
|
13772
|
+
var openRelayTab2 = openRelayTab;
|
|
13773
|
+
var canonicalConfig2 = canonicalConfig;
|
|
13774
|
+
var controlChannel2 = controlChannel;
|
|
13775
|
+
var ownerRecordPath2 = ownerRecordPath;
|
|
13776
|
+
var fallbackPaneSnapshot2 = fallbackPaneSnapshot;
|
|
13777
|
+
var createPaneSnapshot2 = createPaneSnapshot;
|
|
13778
|
+
var paneLabel2 = paneLabel;
|
|
13779
|
+
var inspectLock2 = inspectLock;
|
|
13780
|
+
var reclaimIfStale2 = reclaimIfStale;
|
|
13781
|
+
var resetRelayState2 = resetRelayState;
|
|
13782
|
+
var probeChannel2 = probeChannel;
|
|
13783
|
+
var SUPERVISOR_PATTERN2 = SUPERVISOR_PATTERN;
|
|
13784
|
+
var CONNECTOR_PATTERN2 = CONNECTOR_PATTERN;
|
|
13785
|
+
|
|
13786
|
+
// src/cli/commands/connect.ts
|
|
13787
|
+
import { resolve as resolve3 } from "node:path";
|
|
13788
|
+
|
|
13789
|
+
// src/runtime-herdr/adapter.ts
|
|
13790
|
+
import { createHash as createHash3, randomUUID as randomUUID7 } from "node:crypto";
|
|
13791
|
+
import { readFile as readFile7, stat as stat3 } from "node:fs/promises";
|
|
13792
|
+
import { homedir as homedir3 } from "node:os";
|
|
13793
|
+
import { join as join5 } from "node:path";
|
|
13794
|
+
|
|
13795
|
+
// src/runtime-herdr/subscription.ts
|
|
13796
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
13797
|
+
import { createConnection as createConnection2 } from "node:net";
|
|
13798
|
+
function openSubscription(options) {
|
|
13799
|
+
const id = `sub_${randomUUID5()}`;
|
|
13800
|
+
const request = { id, method: "events.subscribe", params: { subscriptions: options.subscriptions } };
|
|
13801
|
+
const maxLineBytes = options.maxLineBytes ?? 1024 * 1024;
|
|
13802
|
+
let acknowledged = false;
|
|
13803
|
+
let resolveStarted;
|
|
13804
|
+
let rejectStarted;
|
|
13805
|
+
let resolveClosed;
|
|
13806
|
+
const started = new Promise((resolve5, reject) => {
|
|
13807
|
+
resolveStarted = resolve5;
|
|
13808
|
+
rejectStarted = reject;
|
|
13809
|
+
});
|
|
13810
|
+
const closed = new Promise((resolve5) => {
|
|
13811
|
+
resolveClosed = resolve5;
|
|
13812
|
+
});
|
|
13813
|
+
void started.catch(() => void 0);
|
|
13814
|
+
if (options.validateRequest && !options.validateRequest(request)) {
|
|
13815
|
+
rejectStarted(new ConnectError("unsupported_capability", "This Herdr API schema does not accept the event subscription.", "Update Herdr to a version with events.subscribe."));
|
|
13816
|
+
resolveClosed();
|
|
13817
|
+
return { started, closed, close: () => void 0 };
|
|
13818
|
+
}
|
|
13819
|
+
const socket = createConnection2(options.socketPath);
|
|
13820
|
+
const fail = (error) => {
|
|
13821
|
+
if (!acknowledged) rejectStarted(error);
|
|
13822
|
+
socket.destroy();
|
|
13823
|
+
};
|
|
13824
|
+
socket.setNoDelay(true);
|
|
13825
|
+
const timer = setTimeout(() => fail(new ConnectError("timeout", "Herdr did not acknowledge the event subscription.", "Check that Herdr is responsive.")), options.timeoutMs ?? 5e3);
|
|
13826
|
+
timer.unref?.();
|
|
13827
|
+
let buffer = Buffer.alloc(0);
|
|
13828
|
+
socket.once("connect", () => socket.write(`${JSON.stringify(request)}
|
|
13829
|
+
`));
|
|
13830
|
+
socket.on("error", () => fail(new ConnectError("runtime_unavailable", "Cannot connect to the Herdr socket for events.", "Start Herdr and verify its local socket path.")));
|
|
13831
|
+
socket.on("close", () => {
|
|
13832
|
+
clearTimeout(timer);
|
|
13833
|
+
if (!acknowledged) rejectStarted(new ConnectError("runtime_unavailable", "Herdr closed the event socket before subscribing.", "Start Herdr and verify its local socket path."));
|
|
13834
|
+
resolveClosed();
|
|
13835
|
+
});
|
|
13836
|
+
socket.on("data", (chunk) => {
|
|
13837
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
13838
|
+
let newline;
|
|
13839
|
+
while ((newline = buffer.indexOf(10)) >= 0) {
|
|
13840
|
+
const line = buffer.subarray(0, newline);
|
|
13841
|
+
buffer = buffer.subarray(newline + 1);
|
|
13842
|
+
if (line.length === 0) continue;
|
|
13843
|
+
if (line.length > maxLineBytes) {
|
|
13844
|
+
fail(protocolError("Herdr event line exceeded the size limit"));
|
|
13845
|
+
return;
|
|
13846
|
+
}
|
|
13847
|
+
let value;
|
|
13848
|
+
try {
|
|
13849
|
+
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line));
|
|
13850
|
+
} catch {
|
|
13851
|
+
fail(protocolError("Herdr sent malformed JSON on the event socket"));
|
|
13852
|
+
return;
|
|
13853
|
+
}
|
|
13854
|
+
if (!isRecord3(value)) continue;
|
|
13855
|
+
if (value.id === id) {
|
|
13856
|
+
if (isRecord3(value.error)) {
|
|
13857
|
+
const code = typeof value.error.code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(value.error.code) ? value.error.code : "runtime_error";
|
|
13858
|
+
fail(new ConnectError(code, `Herdr rejected events.subscribe (${code}).`, "Update Herdr to a version with event subscriptions."));
|
|
13859
|
+
return;
|
|
13860
|
+
}
|
|
13861
|
+
if (isRecord3(value.result) && value.result.type === "subscription_started") {
|
|
13862
|
+
acknowledged = true;
|
|
13863
|
+
clearTimeout(timer);
|
|
13864
|
+
resolveStarted();
|
|
13865
|
+
} else {
|
|
13866
|
+
fail(protocolError("Herdr answered events.subscribe with an unexpected result"));
|
|
13867
|
+
return;
|
|
13868
|
+
}
|
|
13869
|
+
continue;
|
|
13870
|
+
}
|
|
13871
|
+
if (acknowledged && typeof value.event === "string" && isRecord3(value.data)) options.onEvent({ event: value.event, data: value.data });
|
|
13872
|
+
}
|
|
13873
|
+
if (buffer.length > maxLineBytes) fail(protocolError("Herdr event line exceeded the size limit"));
|
|
13874
|
+
});
|
|
13875
|
+
return { started, closed, close: () => {
|
|
13876
|
+
socket.destroy();
|
|
13877
|
+
} };
|
|
13878
|
+
}
|
|
13879
|
+
function protocolError(message) {
|
|
13880
|
+
return new ConnectError("protocol_error", message, "Check that the installed Herdr version matches its API schema.");
|
|
13881
|
+
}
|
|
13882
|
+
function isRecord3(value) {
|
|
13883
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13884
|
+
}
|
|
13885
|
+
|
|
13886
|
+
// src/runtime-herdr/events.ts
|
|
13887
|
+
var LIST_SUBSCRIPTIONS = ["pane.created", "pane.closed", "pane.exited", "pane.agent_detected"];
|
|
13888
|
+
var UNSUPPORTED = /* @__PURE__ */ new Set(["invalid_request", "unknown_method", "method_not_found", "unsupported_capability", "schema_mismatch"]);
|
|
13889
|
+
var normalizeName = (name) => name.replaceAll(".", "_");
|
|
13890
|
+
var HerdrEventBridge = class {
|
|
13891
|
+
constructor(host, options = {}) {
|
|
13892
|
+
this.host = host;
|
|
13893
|
+
this.log = options.log ?? (() => void 0);
|
|
13894
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve5) => {
|
|
13895
|
+
const timer = setTimeout(resolve5, ms);
|
|
13896
|
+
timer.unref?.();
|
|
13897
|
+
}));
|
|
13898
|
+
this.random = options.random ?? Math.random;
|
|
13899
|
+
this.settleMs = options.settleMs ?? 100;
|
|
13900
|
+
this.listSettleMs = options.listSettleMs ?? 250;
|
|
13901
|
+
this.open = options.openSubscription ?? openSubscription;
|
|
13902
|
+
}
|
|
13903
|
+
host;
|
|
13904
|
+
listeners = /* @__PURE__ */ new Set();
|
|
13905
|
+
log;
|
|
13906
|
+
sleep;
|
|
13907
|
+
random;
|
|
13908
|
+
settleMs;
|
|
13909
|
+
listSettleMs;
|
|
13910
|
+
open;
|
|
13911
|
+
running;
|
|
13912
|
+
stopped = true;
|
|
13913
|
+
handle;
|
|
13914
|
+
subscribedPanes = /* @__PURE__ */ new Set();
|
|
13915
|
+
lastStatus = /* @__PURE__ */ new Map();
|
|
13916
|
+
dirty = /* @__PURE__ */ new Map();
|
|
13917
|
+
statusTimer;
|
|
13918
|
+
listTimer;
|
|
13919
|
+
wake;
|
|
13920
|
+
unsupportedLogged = false;
|
|
13921
|
+
resubscribeRequested = false;
|
|
13922
|
+
subscribe(listener) {
|
|
13923
|
+
this.listeners.add(listener);
|
|
13924
|
+
if (this.stopped) {
|
|
13925
|
+
this.stopped = false;
|
|
13926
|
+
this.running = this.run().catch(() => void 0);
|
|
13927
|
+
}
|
|
13928
|
+
return () => {
|
|
13929
|
+
this.listeners.delete(listener);
|
|
13930
|
+
if (this.listeners.size === 0) void this.stop();
|
|
13931
|
+
};
|
|
13932
|
+
}
|
|
13933
|
+
async stop() {
|
|
13934
|
+
this.stopped = true;
|
|
13935
|
+
this.handle?.close();
|
|
13936
|
+
this.wake?.();
|
|
13937
|
+
if (this.statusTimer) clearTimeout(this.statusTimer);
|
|
13938
|
+
if (this.listTimer) clearTimeout(this.listTimer);
|
|
13939
|
+
this.statusTimer = this.listTimer = void 0;
|
|
13940
|
+
this.dirty.clear();
|
|
13941
|
+
await this.running;
|
|
13942
|
+
}
|
|
13943
|
+
/** Called by the adapter after every agent.list refresh. */
|
|
13944
|
+
agentsRefreshed(idsChanged) {
|
|
13945
|
+
if (this.stopped) return;
|
|
13946
|
+
if (idsChanged) this.emit({ kind: "agents_changed" });
|
|
13947
|
+
const panes = new Set(this.host.agents().map((agent) => agent.paneId));
|
|
13948
|
+
if (this.handle && !sameSet(panes, this.subscribedPanes)) this.requestResubscribe(this.handle);
|
|
13949
|
+
}
|
|
13950
|
+
requestResubscribe(handle) {
|
|
13951
|
+
this.resubscribeRequested = true;
|
|
13952
|
+
handle.close();
|
|
13953
|
+
}
|
|
13954
|
+
emit(event) {
|
|
13955
|
+
for (const listener of [...this.listeners]) {
|
|
13956
|
+
try {
|
|
13957
|
+
listener(event);
|
|
13958
|
+
} catch {
|
|
13959
|
+
}
|
|
13960
|
+
}
|
|
13961
|
+
}
|
|
13962
|
+
async run() {
|
|
13963
|
+
let attempt = 0;
|
|
13964
|
+
let dropped = false;
|
|
13965
|
+
while (!this.stopped) {
|
|
13966
|
+
let resubscribe = false;
|
|
13967
|
+
this.resubscribeRequested = false;
|
|
13968
|
+
try {
|
|
13969
|
+
const { socketPath, validateRequest, supportsEvents } = await this.host.prepare();
|
|
13970
|
+
if (!supportsEvents) {
|
|
13971
|
+
this.unsupported("this Herdr version has no events.subscribe");
|
|
13972
|
+
return;
|
|
13973
|
+
}
|
|
13974
|
+
await this.host.refresh();
|
|
13975
|
+
if (this.stopped) return;
|
|
13976
|
+
const agents = this.host.agents();
|
|
13977
|
+
const panes = new Set(agents.map((agent) => agent.paneId));
|
|
13978
|
+
for (const agent of agents) this.lastStatus.set(agent.agentId, agent.status);
|
|
13979
|
+
const subscriptions = [
|
|
13980
|
+
...[...panes].map((paneId) => ({ type: "pane.agent_status_changed", pane_id: paneId })),
|
|
13981
|
+
...LIST_SUBSCRIPTIONS.map((type) => ({ type }))
|
|
13982
|
+
];
|
|
13983
|
+
const handle = this.open({ socketPath, subscriptions, validateRequest, onEvent: (event) => this.onPushed(event) });
|
|
13984
|
+
this.handle = handle;
|
|
13985
|
+
this.subscribedPanes = panes;
|
|
13986
|
+
await handle.started;
|
|
13987
|
+
if (attempt > 0) this.log("Herdr agent events resumed.");
|
|
13988
|
+
attempt = 0;
|
|
13989
|
+
if (dropped) this.emit({ kind: "agents_changed" });
|
|
13990
|
+
dropped = false;
|
|
13991
|
+
if (!sameSet(new Set(this.host.agents().map((agent) => agent.paneId)), panes)) this.requestResubscribe(handle);
|
|
13992
|
+
await handle.closed;
|
|
13993
|
+
resubscribe = this.resubscribeRequested;
|
|
13994
|
+
if (!resubscribe && !this.stopped) {
|
|
13995
|
+
dropped = true;
|
|
13996
|
+
this.log("Herdr closed the agent event stream; retrying.");
|
|
13997
|
+
}
|
|
13998
|
+
} catch (error) {
|
|
13999
|
+
if (error instanceof ConnectError && UNSUPPORTED.has(error.code)) {
|
|
14000
|
+
this.unsupported(`Herdr rejected events.subscribe (${error.code})`);
|
|
14001
|
+
return;
|
|
14002
|
+
}
|
|
14003
|
+
if (attempt === 0 && !this.stopped) this.log(`Herdr agent events unavailable (${error instanceof ConnectError ? error.code : "error"}); retrying.`);
|
|
14004
|
+
} finally {
|
|
14005
|
+
this.handle = void 0;
|
|
14006
|
+
}
|
|
14007
|
+
if (this.stopped) return;
|
|
14008
|
+
if (resubscribe) continue;
|
|
14009
|
+
const ceiling = Math.min(3e4, 500 * 2 ** Math.min(attempt++, 6));
|
|
14010
|
+
await this.pause(Math.round(ceiling * (0.5 + this.random() * 0.5)));
|
|
14011
|
+
}
|
|
14012
|
+
}
|
|
14013
|
+
async pause(ms) {
|
|
14014
|
+
await Promise.race([this.sleep(ms), new Promise((resolve5) => {
|
|
14015
|
+
this.wake = resolve5;
|
|
14016
|
+
})]);
|
|
14017
|
+
this.wake = void 0;
|
|
14018
|
+
}
|
|
14019
|
+
unsupported(reason) {
|
|
14020
|
+
this.stopped = true;
|
|
14021
|
+
if (this.unsupportedLogged) return;
|
|
14022
|
+
this.unsupportedLogged = true;
|
|
14023
|
+
this.log(`Agent events are off: ${reason}. Clients can still poll.`);
|
|
14024
|
+
}
|
|
14025
|
+
onPushed(event) {
|
|
14026
|
+
if (this.stopped) return;
|
|
14027
|
+
const name = normalizeName(event.event);
|
|
14028
|
+
if (name === "pane_agent_status_changed") this.onStatus(event.data);
|
|
14029
|
+
else if (LIST_SUBSCRIPTIONS.map(normalizeName).includes(name)) this.scheduleListRefresh();
|
|
14030
|
+
}
|
|
14031
|
+
onStatus(data) {
|
|
14032
|
+
const paneId = data.pane_id;
|
|
14033
|
+
const raw = data.agent_status;
|
|
14034
|
+
if (typeof paneId !== "string") return;
|
|
14035
|
+
const status = typeof raw === "string" && AGENT_STATUSES.includes(raw) ? raw : "unknown";
|
|
14036
|
+
const agent = this.host.agents().find((candidate) => candidate.paneId === paneId);
|
|
14037
|
+
if (!agent) {
|
|
14038
|
+
this.scheduleListRefresh();
|
|
14039
|
+
return;
|
|
14040
|
+
}
|
|
14041
|
+
const previousStatus = this.lastStatus.get(agent.agentId) ?? null;
|
|
14042
|
+
if (previousStatus === status) return;
|
|
14043
|
+
this.lastStatus.set(agent.agentId, status);
|
|
14044
|
+
this.dirty.set(paneId, { agentId: agent.agentId, status, previousStatus, label: agent.label, workspace: agent.workspace });
|
|
14045
|
+
this.statusTimer ??= setTimeout(() => {
|
|
14046
|
+
this.statusTimer = void 0;
|
|
14047
|
+
void this.flushStatus();
|
|
14048
|
+
}, this.settleMs);
|
|
14049
|
+
this.statusTimer.unref?.();
|
|
14050
|
+
}
|
|
14051
|
+
async flushStatus() {
|
|
14052
|
+
const batch = [...this.dirty.values()];
|
|
14053
|
+
this.dirty.clear();
|
|
14054
|
+
let fresh = true;
|
|
14055
|
+
try {
|
|
14056
|
+
await this.host.refresh();
|
|
14057
|
+
} catch {
|
|
14058
|
+
fresh = false;
|
|
14059
|
+
}
|
|
14060
|
+
if (this.stopped) return;
|
|
14061
|
+
const current = new Map(this.host.agents().map((agent) => [agent.agentId, agent]));
|
|
14062
|
+
for (const item of batch) {
|
|
14063
|
+
const record = fresh ? current.get(item.agentId) : void 0;
|
|
14064
|
+
if (fresh && !record) continue;
|
|
14065
|
+
this.emit({
|
|
14066
|
+
kind: "status",
|
|
14067
|
+
agentId: item.agentId,
|
|
14068
|
+
status: item.status,
|
|
14069
|
+
previousStatus: item.previousStatus,
|
|
14070
|
+
label: record?.label ?? item.label,
|
|
14071
|
+
workspace: record?.workspace ?? item.workspace,
|
|
14072
|
+
revision: record ? record.revision : null
|
|
14073
|
+
});
|
|
14074
|
+
}
|
|
14075
|
+
}
|
|
14076
|
+
scheduleListRefresh() {
|
|
14077
|
+
this.listTimer ??= setTimeout(() => {
|
|
14078
|
+
this.listTimer = void 0;
|
|
14079
|
+
void this.host.refresh().catch(() => void 0);
|
|
14080
|
+
}, this.listSettleMs);
|
|
14081
|
+
this.listTimer.unref?.();
|
|
14082
|
+
}
|
|
14083
|
+
};
|
|
14084
|
+
function sameSet(a, b) {
|
|
14085
|
+
if (a.size !== b.size) return false;
|
|
14086
|
+
for (const value of a) if (!b.has(value)) return false;
|
|
14087
|
+
return true;
|
|
14088
|
+
}
|
|
14089
|
+
|
|
14090
|
+
// src/runtime-herdr/socket-client.ts
|
|
14091
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
14092
|
+
import { createConnection as createConnection3 } from "node:net";
|
|
14093
|
+
var HerdrSocketClient = class {
|
|
14094
|
+
socketPath;
|
|
14095
|
+
timeoutMs;
|
|
14096
|
+
maxLineBytes;
|
|
14097
|
+
maxPending;
|
|
14098
|
+
validateSuccessResponse;
|
|
14099
|
+
validateErrorResponse;
|
|
14100
|
+
validateRequest;
|
|
14101
|
+
schemaDiagnostics;
|
|
14102
|
+
sockets = /* @__PURE__ */ new Set();
|
|
14103
|
+
buffers = /* @__PURE__ */ new WeakMap();
|
|
14104
|
+
pending = /* @__PURE__ */ new Map();
|
|
14105
|
+
closed = false;
|
|
14106
|
+
epoch = 0;
|
|
14107
|
+
inflight = 0;
|
|
14108
|
+
constructor(options) {
|
|
14109
|
+
this.socketPath = options.socketPath;
|
|
14110
|
+
this.timeoutMs = options.timeoutMs ?? 5e3;
|
|
14111
|
+
this.maxLineBytes = options.maxLineBytes ?? 2 * 1024 * 1024;
|
|
14112
|
+
this.maxPending = options.maxPending ?? 32;
|
|
14113
|
+
this.validateSuccessResponse = options.validateSuccessResponse;
|
|
14114
|
+
this.validateErrorResponse = options.validateErrorResponse;
|
|
14115
|
+
this.validateRequest = options.validateRequest;
|
|
14116
|
+
this.schemaDiagnostics = options.schemaDiagnostics;
|
|
14117
|
+
}
|
|
14118
|
+
get connectionEpoch() {
|
|
14119
|
+
return this.epoch;
|
|
14120
|
+
}
|
|
14121
|
+
async request(method, params = {}) {
|
|
14122
|
+
if (this.closed) throw this.unavailable("Herdr socket client is closed");
|
|
14123
|
+
if (this.inflight >= this.maxPending) throw this.unavailable("Too many Herdr requests are in flight");
|
|
14124
|
+
const id = randomUUID6();
|
|
14125
|
+
const request = { id, method, params };
|
|
14126
|
+
if (this.validateRequest && !this.validateRequest(request)) throw new ConnectError("schema_mismatch", `Herdr request does not match the selected API schema (${this.schemaDiagnostics?.() ?? "schema validation failed"})`, "Use an adapter and schema version compatible with the installed Herdr binary.");
|
|
14127
|
+
const line = Buffer.from(`${JSON.stringify(request)}
|
|
14128
|
+
`, "utf8");
|
|
14129
|
+
if (line.length > this.maxLineBytes) throw this.unavailable("Herdr request exceeds the configured size limit");
|
|
14130
|
+
this.inflight += 1;
|
|
14131
|
+
let socket;
|
|
14132
|
+
try {
|
|
14133
|
+
socket = await this.connect();
|
|
14134
|
+
} catch (error) {
|
|
14135
|
+
this.inflight -= 1;
|
|
14136
|
+
throw error;
|
|
14137
|
+
}
|
|
14138
|
+
return new Promise((resolve5, reject) => {
|
|
14139
|
+
const timer = setTimeout(() => {
|
|
14140
|
+
this.pending.delete(id);
|
|
14141
|
+
this.inflight -= 1;
|
|
14142
|
+
socket.end();
|
|
14143
|
+
reject(method === "agent.prompt" ? new ConnectError("delivery_unknown", "Herdr did not acknowledge the prompt before the request timed out.", "Check the agent status before deciding whether to send the prompt again.") : new ConnectError("timeout", `Herdr ${method} request timed out`, "Check that Herdr is responsive and retry the read."));
|
|
14144
|
+
}, this.timeoutMs);
|
|
14145
|
+
timer.unref?.();
|
|
14146
|
+
this.pending.set(id, { resolve: resolve5, reject, timer, method, socket });
|
|
14147
|
+
socket.write(line, (error) => {
|
|
14148
|
+
if (!error) return;
|
|
14149
|
+
const pending = this.pending.get(id);
|
|
14150
|
+
if (pending) {
|
|
14151
|
+
this.pending.delete(id);
|
|
14152
|
+
clearTimeout(timer);
|
|
14153
|
+
this.inflight -= 1;
|
|
14154
|
+
reject(this.mapTransportError(method));
|
|
14155
|
+
}
|
|
14156
|
+
});
|
|
14157
|
+
});
|
|
14158
|
+
}
|
|
14159
|
+
async close() {
|
|
14160
|
+
this.closed = true;
|
|
14161
|
+
this.failAll(this.unavailable("Herdr socket client closed"));
|
|
13065
14162
|
await Promise.all([...this.sockets].map((socket) => new Promise((resolve5) => {
|
|
13066
14163
|
if (socket.destroyed) resolve5();
|
|
13067
14164
|
else socket.end(resolve5);
|
|
@@ -13069,7 +14166,7 @@ var HerdrSocketClient = class {
|
|
|
13069
14166
|
}
|
|
13070
14167
|
connect() {
|
|
13071
14168
|
return new Promise((resolve5, reject) => {
|
|
13072
|
-
const socket =
|
|
14169
|
+
const socket = createConnection3(this.socketPath);
|
|
13073
14170
|
const onError = () => {
|
|
13074
14171
|
socket.destroy();
|
|
13075
14172
|
this.sockets.delete(socket);
|
|
@@ -13185,15 +14282,15 @@ var HerdrSocketClient = class {
|
|
|
13185
14282
|
// src/runtime-herdr/schema.ts
|
|
13186
14283
|
var import_ajv_formats = __toESM(require_dist(), 1);
|
|
13187
14284
|
var import__ = __toESM(require__(), 1);
|
|
13188
|
-
import { execFile as
|
|
13189
|
-
import { readFile as
|
|
13190
|
-
import { promisify } from "node:util";
|
|
13191
|
-
var execFileAsync =
|
|
14285
|
+
import { execFile as execFile4 } from "node:child_process";
|
|
14286
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
14287
|
+
import { promisify as promisify2 } from "node:util";
|
|
14288
|
+
var execFileAsync = promisify2(execFile4);
|
|
13192
14289
|
var addFormats = import_ajv_formats.default.default ?? import_ajv_formats.default;
|
|
13193
14290
|
async function loadHerdrSchema(options = {}) {
|
|
13194
14291
|
let raw;
|
|
13195
14292
|
try {
|
|
13196
|
-
if (options.schemaPath) raw = await
|
|
14293
|
+
if (options.schemaPath) raw = await readFile6(options.schemaPath, "utf8");
|
|
13197
14294
|
else {
|
|
13198
14295
|
if (!options.binary) throw new Error("No schemaPath or Herdr binary was configured");
|
|
13199
14296
|
const result = await execFileAsync(options.binary, ["api", "schema", "--json"], {
|
|
@@ -13250,7 +14347,7 @@ async function loadHerdrSchema(options = {}) {
|
|
|
13250
14347
|
const promptRef = prompt?.properties?.params?.$ref;
|
|
13251
14348
|
const promptName = promptRef?.split("/").at(-1);
|
|
13252
14349
|
const params = promptName ? schema.schemas.request.$defs?.[promptName] : void 0;
|
|
13253
|
-
const writesHaveAtomicOccupantGuard = Boolean(params?.properties && Object.entries(params.properties).some(([name,
|
|
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")));
|
|
13254
14351
|
return {
|
|
13255
14352
|
schema,
|
|
13256
14353
|
validateRequest,
|
|
@@ -13278,9 +14375,12 @@ var HerdrAdapter = class {
|
|
|
13278
14375
|
endpointMarker;
|
|
13279
14376
|
socketPath;
|
|
13280
14377
|
refreshing;
|
|
14378
|
+
listed = false;
|
|
14379
|
+
records = /* @__PURE__ */ new Map();
|
|
14380
|
+
bridge;
|
|
13281
14381
|
constructor(options = {}) {
|
|
13282
14382
|
this.options = options;
|
|
13283
|
-
this.machineId = options.machineId ??
|
|
14383
|
+
this.machineId = options.machineId ?? createHash3("sha256").update(`${process.platform}:${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "local"}`).digest("hex").slice(0, 24);
|
|
13284
14384
|
}
|
|
13285
14385
|
getCapabilities() {
|
|
13286
14386
|
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." };
|
|
@@ -13308,16 +14408,47 @@ var HerdrAdapter = class {
|
|
|
13308
14408
|
if (!isAgent(raw)) throw this.schemaMismatch("agent.list contained an invalid agent record");
|
|
13309
14409
|
const fingerprint = identityFingerprint(raw);
|
|
13310
14410
|
const previous = !reconnected ? previousTargets.find((item) => item.fingerprint === fingerprint) : void 0;
|
|
13311
|
-
const id = previous?.id ?? `herdr_${
|
|
14411
|
+
const id = previous?.id ?? `herdr_${randomUUID7()}`;
|
|
13312
14412
|
const live = { id, fingerprint, agent: raw };
|
|
13313
14413
|
next.set(raw.pane_id, live);
|
|
13314
14414
|
nextIds.add(id);
|
|
13315
14415
|
records.push(toRecord(live, this.machineId, promptTarget(raw, rawAgents) !== void 0));
|
|
13316
14416
|
}
|
|
13317
14417
|
for (const previous of previousTargets) if (!nextIds.has(previous.id)) this.retired.add(previous.id);
|
|
14418
|
+
const idsChanged = this.listed && (nextIds.size !== previousTargets.length || previousTargets.some((item) => !nextIds.has(item.id)));
|
|
13318
14419
|
this.current = next;
|
|
14420
|
+
this.records = new Map(records.map((record) => [record.id, record]));
|
|
14421
|
+
this.listed = true;
|
|
14422
|
+
this.bridge?.agentsRefreshed(idsChanged);
|
|
13319
14423
|
return records;
|
|
13320
14424
|
}
|
|
14425
|
+
/** Status and list-change events from Herdr's events.subscribe (metadata only, never pane text). */
|
|
14426
|
+
onEvent(listener, log) {
|
|
14427
|
+
this.bridge ??= new HerdrEventBridge({
|
|
14428
|
+
prepare: async () => {
|
|
14429
|
+
const { schema } = await this.initialize();
|
|
14430
|
+
const request = schema.schema.schemas.request;
|
|
14431
|
+
return {
|
|
14432
|
+
socketPath: platformSocketAddress(this.socketPath),
|
|
14433
|
+
validateRequest: schema.validateRequest,
|
|
14434
|
+
supportsEvents: Boolean(request.oneOf?.some((branch) => branch.properties?.method?.const === "events.subscribe"))
|
|
14435
|
+
};
|
|
14436
|
+
},
|
|
14437
|
+
refresh: async () => {
|
|
14438
|
+
await this.listAgents();
|
|
14439
|
+
},
|
|
14440
|
+
agents: () => [...this.current.values()].map((live) => {
|
|
14441
|
+
const record = this.records.get(live.id);
|
|
14442
|
+
return { paneId: live.agent.pane_id, agentId: live.id, status: record?.status ?? "unknown", label: record?.label ?? "Herdr agent", workspace: record?.workspace ?? live.agent.workspace_id, revision: live.agent.revision };
|
|
14443
|
+
})
|
|
14444
|
+
}, { ...this.options.events, log });
|
|
14445
|
+
return this.bridge.subscribe(listener);
|
|
14446
|
+
}
|
|
14447
|
+
/** The agent id for a Herdr pane id such as HERDR_PANE_ID, after a fresh agent.list. */
|
|
14448
|
+
async agentIdForPane(paneId) {
|
|
14449
|
+
await this.listAgents();
|
|
14450
|
+
return this.current.get(paneId)?.id;
|
|
14451
|
+
}
|
|
13321
14452
|
async getAgent(id) {
|
|
13322
14453
|
const agents = await this.listAgents();
|
|
13323
14454
|
const record = agents.find((agent) => agent.id === id);
|
|
@@ -13363,6 +14494,7 @@ var HerdrAdapter = class {
|
|
|
13363
14494
|
if (result.type !== "agent_prompted") throw this.schemaMismatch("agent.prompt returned an unexpected result type");
|
|
13364
14495
|
}
|
|
13365
14496
|
async close() {
|
|
14497
|
+
await this.bridge?.stop();
|
|
13366
14498
|
const pending = await this.ready?.catch(() => void 0);
|
|
13367
14499
|
await pending?.client.close();
|
|
13368
14500
|
}
|
|
@@ -13430,15 +14562,15 @@ function promptTarget(agent, agents) {
|
|
|
13430
14562
|
}
|
|
13431
14563
|
function identityFingerprint(agent) {
|
|
13432
14564
|
const reference = agent.agent_session ? `${agent.agent_session.source}:${agent.agent_session.agent}:${agent.agent_session.kind}:${agent.agent_session.value}` : "";
|
|
13433
|
-
return
|
|
14565
|
+
return createHash3("sha256").update([agent.terminal_id, agent.agent ?? "", reference].join("\0")).digest("hex");
|
|
13434
14566
|
}
|
|
13435
14567
|
function defaultSocketPath() {
|
|
13436
14568
|
const session = process.env.HERDR_SESSION;
|
|
13437
14569
|
if (session !== void 0 && (session.length > 64 || !/^[A-Za-z0-9._-]+$/.test(session) || session === "." || session === "..")) {
|
|
13438
14570
|
throw new ConnectError("invalid_config", "HERDR_SESSION contains unsupported characters.", "Use a Herdr session name with only letters, numbers, dots, underscores, and hyphens.");
|
|
13439
14571
|
}
|
|
13440
|
-
const root = process.platform === "win32" ?
|
|
13441
|
-
return session ?
|
|
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");
|
|
13442
14574
|
}
|
|
13443
14575
|
function platformSocketAddress(path) {
|
|
13444
14576
|
if (process.platform !== "win32" || path.startsWith("\\\\.\\pipe\\")) return path;
|
|
@@ -13462,10 +14594,10 @@ async function readEndpointMarker(socketPath) {
|
|
|
13462
14594
|
try {
|
|
13463
14595
|
if (process.platform === "win32") {
|
|
13464
14596
|
if (socketPath.startsWith("\\\\.\\pipe\\")) return void 0;
|
|
13465
|
-
const marker = (await
|
|
14597
|
+
const marker = (await readFile7(socketPath, "utf8")).trim();
|
|
13466
14598
|
return marker || void 0;
|
|
13467
14599
|
}
|
|
13468
|
-
const file = await
|
|
14600
|
+
const file = await stat3(socketPath);
|
|
13469
14601
|
return `${file.dev}:${file.ino}`;
|
|
13470
14602
|
} catch {
|
|
13471
14603
|
return void 0;
|
|
@@ -13521,7 +14653,177 @@ var Output = class {
|
|
|
13521
14653
|
var symbols = { ok: "\u2713", dot: "\u25CF", ring: "\u25CB", warn: "!", fail: "\u2717" };
|
|
13522
14654
|
|
|
13523
14655
|
// src/cli/commands/shared.ts
|
|
13524
|
-
import { resolve } from "node:path";
|
|
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;
|
|
14755
|
+
}
|
|
14756
|
+
try {
|
|
14757
|
+
return typeof recorded === "string" && sha256(file) !== recorded;
|
|
14758
|
+
} catch {
|
|
14759
|
+
return false;
|
|
14760
|
+
}
|
|
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";
|
|
14767
|
+
}
|
|
14768
|
+
file;
|
|
14769
|
+
};
|
|
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 };
|
|
14785
|
+
}
|
|
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}`;
|
|
14792
|
+
}
|
|
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))) });
|
|
14824
|
+
}
|
|
14825
|
+
|
|
14826
|
+
// src/cli/commands/shared.ts
|
|
13525
14827
|
var credentialsFile = (ctx) => credentialsPath({ env: ctx.env });
|
|
13526
14828
|
async function requireCredentials(ctx) {
|
|
13527
14829
|
try {
|
|
@@ -13535,15 +14837,16 @@ async function requireCredentials(ctx) {
|
|
|
13535
14837
|
}
|
|
13536
14838
|
async function loadMachineConnectorConfig(ctx, explicitPath) {
|
|
13537
14839
|
const explicit = explicitPath ?? ctx.env.PEERBAND_CONNECTOR_CONFIG;
|
|
13538
|
-
return explicit ? loadConnectorConfig(
|
|
14840
|
+
return explicit ? loadConnectorConfig(resolve2(explicit)) : loadConnectorConfig(connectorConfigPath({ env: ctx.env }), { optional: true });
|
|
13539
14841
|
}
|
|
13540
14842
|
function writesEnabled(config, flags = {}) {
|
|
13541
14843
|
if (flags.readOnly) return false;
|
|
13542
14844
|
if (flags.enableWrites) return true;
|
|
13543
14845
|
return config.enableWrites !== false;
|
|
13544
14846
|
}
|
|
13545
|
-
var SKILL_COMMAND = "
|
|
14847
|
+
var SKILL_COMMAND = "peerband skill";
|
|
13546
14848
|
function printSkillTip(ctx) {
|
|
14849
|
+
if (skillInstalled(ctx)) return;
|
|
13547
14850
|
ctx.out.print(ctx.out.stdout.dim(`Give your coding agents the PeerBand skill: ${SKILL_COMMAND}`));
|
|
13548
14851
|
}
|
|
13549
14852
|
var describeMachine = (credentials) => credentials.machineName ?? credentials.installationId;
|
|
@@ -13626,6 +14929,23 @@ var spec = {
|
|
|
13626
14929
|
);
|
|
13627
14930
|
}
|
|
13628
14931
|
};
|
|
14932
|
+
function notifyRequest(message) {
|
|
14933
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) return void 0;
|
|
14934
|
+
const value = message;
|
|
14935
|
+
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 };
|
|
14937
|
+
}
|
|
14938
|
+
function startMockStatusCycle(adapter, env) {
|
|
14939
|
+
const interval = Number(env.PEERBAND_MOCK_STATUS_INTERVAL_MS);
|
|
14940
|
+
if (!Number.isSafeInteger(interval) || interval < 50) return () => void 0;
|
|
14941
|
+
const timer = setInterval(() => {
|
|
14942
|
+
void adapter.listAgents().then(([first]) => {
|
|
14943
|
+
if (first) adapter.setStatus(first.id, first.status === "working" ? "idle" : "working");
|
|
14944
|
+
});
|
|
14945
|
+
}, interval);
|
|
14946
|
+
timer.unref();
|
|
14947
|
+
return () => clearInterval(timer);
|
|
14948
|
+
}
|
|
13629
14949
|
function isShutdownMessage(message) {
|
|
13630
14950
|
return Boolean(message) && typeof message === "object" && !Array.isArray(message) && Object.keys(message).length === 1 && message.type === "peerband:shutdown";
|
|
13631
14951
|
}
|
|
@@ -13643,10 +14963,22 @@ async function connect(options, ctx) {
|
|
|
13643
14963
|
const adapter = runtime === "mock" ? new MockRuntime() : new HerdrAdapter(config.herdr ?? {});
|
|
13644
14964
|
const core = new ConnectorCore(adapter, {
|
|
13645
14965
|
writesEnabled: enableWrites,
|
|
14966
|
+
labelMessages: true,
|
|
14967
|
+
allowedAgents: config.allowedAgents,
|
|
14968
|
+
allowedWorkspaces: config.allowedWorkspaces,
|
|
14969
|
+
receiptPath: config.stateDirectory ? resolve3(config.stateDirectory, "receipts.json") : receiptsPath({ env: ctx.env }),
|
|
14970
|
+
// A lock left by a connector that died (or by an older version without a pid) is reclaimed instead of refusing forever.
|
|
14971
|
+
lockIsStale: async (lockDir, ownerFile) => (await inspectLock2({ lockDir, ownerFile, processPattern: CONNECTOR_PATTERN2 })).state === "stale",
|
|
14972
|
+
onLockReclaimed: (message) => ctx.out.warn(ctx.out.stderr.dim(`peerband: ${message}`))
|
|
14973
|
+
});
|
|
14974
|
+
const events = new ConnectorEvents(adapter, {
|
|
13646
14975
|
allowedAgents: config.allowedAgents,
|
|
13647
14976
|
allowedWorkspaces: config.allowedWorkspaces,
|
|
13648
|
-
|
|
14977
|
+
log: (message) => {
|
|
14978
|
+
if (!managed) ctx.out.warn(s.dim(` ${sanitize(message)}`));
|
|
14979
|
+
}
|
|
13649
14980
|
});
|
|
14981
|
+
const stopMockCycle = adapter instanceof MockRuntime ? startMockStatusCycle(adapter, ctx.env) : () => void 0;
|
|
13650
14982
|
const abort = new AbortController();
|
|
13651
14983
|
let signalled;
|
|
13652
14984
|
const onSignal = (signal) => {
|
|
@@ -13658,6 +14990,20 @@ async function connect(options, ctx) {
|
|
|
13658
14990
|
const onDisconnect = () => abort.abort();
|
|
13659
14991
|
const onMessage = (message) => {
|
|
13660
14992
|
if (isShutdownMessage(message)) abort.abort();
|
|
14993
|
+
const notify2 = notifyRequest(message);
|
|
14994
|
+
if (notify2) {
|
|
14995
|
+
void events.notify(notify2).then(
|
|
14996
|
+
(result) => process.send?.({ type: "peerband:notify-result", id: notify2.id, ok: true, ...result }),
|
|
14997
|
+
(error) => process.send?.({
|
|
14998
|
+
type: "peerband:notify-result",
|
|
14999
|
+
id: notify2.id,
|
|
15000
|
+
ok: false,
|
|
15001
|
+
code: error instanceof ConnectError ? error.code : "runtime_error",
|
|
15002
|
+
message: error instanceof ConnectError ? error.message : "The note could not be sent.",
|
|
15003
|
+
nextStep: error instanceof ConnectError ? error.nextStep : void 0
|
|
15004
|
+
})
|
|
15005
|
+
);
|
|
15006
|
+
}
|
|
13661
15007
|
};
|
|
13662
15008
|
process.once("SIGINT", onSigint);
|
|
13663
15009
|
process.once("SIGTERM", onSigterm);
|
|
@@ -13678,6 +15024,7 @@ async function connect(options, ctx) {
|
|
|
13678
15024
|
};
|
|
13679
15025
|
try {
|
|
13680
15026
|
await core.initialize();
|
|
15027
|
+
events.start();
|
|
13681
15028
|
if (!managed) {
|
|
13682
15029
|
ctx.out.warn(
|
|
13683
15030
|
`${s.bold("peerband")} ${s.dim(`${runtime} runtime, ${enableWrites ? "messages allowed" : "read-only"}. Press Ctrl+C to stop.`)}`
|
|
@@ -13685,6 +15032,7 @@ async function connect(options, ctx) {
|
|
|
13685
15032
|
}
|
|
13686
15033
|
await runRemoteClient(core, credentials, {
|
|
13687
15034
|
signal: abort.signal,
|
|
15035
|
+
events,
|
|
13688
15036
|
onStatus: (message) => {
|
|
13689
15037
|
if (!managed) ctx.out.warn(s.dim(` ${sanitize(message)}`));
|
|
13690
15038
|
},
|
|
@@ -13712,6 +15060,8 @@ async function connect(options, ctx) {
|
|
|
13712
15060
|
process.off("SIGTERM", onSigterm);
|
|
13713
15061
|
process.off("message", onMessage);
|
|
13714
15062
|
process.off("disconnect", onDisconnect);
|
|
15063
|
+
stopMockCycle();
|
|
15064
|
+
events.close();
|
|
13715
15065
|
await core.close();
|
|
13716
15066
|
await adapter.close?.();
|
|
13717
15067
|
if (ipc && process.connected) process.disconnect();
|
|
@@ -13724,322 +15074,214 @@ async function connect(options, ctx) {
|
|
|
13724
15074
|
}
|
|
13725
15075
|
|
|
13726
15076
|
// src/cli/commands/herdr.ts
|
|
13727
|
-
import { mkdir as
|
|
15077
|
+
import { mkdir as mkdir5, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
|
|
13728
15078
|
import { statSync } from "node:fs";
|
|
13729
|
-
import { join as
|
|
13730
|
-
|
|
13731
|
-
// src/cli/
|
|
13732
|
-
import { readFile as
|
|
13733
|
-
import {
|
|
13734
|
-
|
|
13735
|
-
|
|
13736
|
-
|
|
13737
|
-
|
|
13738
|
-
|
|
13739
|
-
|
|
13740
|
-
|
|
13741
|
-
|
|
13742
|
-
|
|
13743
|
-
|
|
13744
|
-
|
|
13745
|
-
|
|
13746
|
-
if (env.PEERBAND_CONFIG_HOME) return env.PEERBAND_CONFIG_HOME;
|
|
13747
|
-
if (platform === "win32") return join3(env.APPDATA || join3(home, "AppData", "Roaming"), "peerband");
|
|
13748
|
-
return join3(env.XDG_CONFIG_HOME || join3(home, ".config"), "peerband");
|
|
13749
|
-
}
|
|
13750
|
-
var lockPath = (config = configHome2()) => join3(config, "relay-helper.lock");
|
|
13751
|
-
var ownerRecordPath = (config = configHome2()) => join3(lockPath(config), "owner.json");
|
|
13752
|
-
var relayTabPath = (config = configHome2()) => join3(config, "relay-tab.json");
|
|
13753
|
-
function canonicalConfig(config, platform = process.platform) {
|
|
13754
|
-
const resolved = (platform === "win32" ? win32 : posix).resolve(config);
|
|
13755
|
-
return platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
13756
|
-
}
|
|
13757
|
-
function controlChannel(config = configHome2(), platform = process.platform) {
|
|
13758
|
-
const digest = createHash3("sha256").update(canonicalConfig(config, platform)).digest("hex").slice(0, 24);
|
|
13759
|
-
return platform === "win32" ? `\\\\.\\pipe\\peerband-relay-${digest}` : join3(tmpdir(), `pbr-${process.getuid?.() ?? "local"}-${digest}.sock`);
|
|
13760
|
-
}
|
|
13761
|
-
|
|
13762
|
-
// herdr/relay-tab.mjs
|
|
13763
|
-
import { promisify as promisify2 } from "node:util";
|
|
13764
|
-
var exec = promisify2(execFile3);
|
|
13765
|
-
var pluginId = "peerband";
|
|
13766
|
-
var entrypoint = "relay";
|
|
13767
|
-
var markerName = "peerband_relay";
|
|
13768
|
-
var markerSource = "peerband-relay";
|
|
13769
|
-
var tabTitle = (enabled) => `PeerBand Relay [${enabled ? "On" : "Off"}]`;
|
|
13770
|
-
var productionController;
|
|
13771
|
-
function describeHerdrFailure(error, binary = "herdr") {
|
|
13772
|
-
if (error?.code === "ENOENT") {
|
|
13773
|
-
return `Herdr was not found (${binary}). Install Herdr, put it on PATH, or set HERDR_BIN_PATH to its executable.`;
|
|
13774
|
-
}
|
|
13775
|
-
const detail = safeFailure(error);
|
|
13776
|
-
if (/plugin/i.test(detail) && /not found|not installed|unknown|no such|does not exist|not registered/i.test(detail)) {
|
|
13777
|
-
return `The PeerBand plugin is not installed in Herdr (${detail}). Run \`peerband herdr install\`.`;
|
|
13778
|
-
}
|
|
13779
|
-
return detail;
|
|
13780
|
-
}
|
|
13781
|
-
function productionOptions() {
|
|
13782
|
-
return {
|
|
13783
|
-
run: async (args) => {
|
|
13784
|
-
const binary = process.env.HERDR_BIN_PATH || "herdr";
|
|
13785
|
-
try {
|
|
13786
|
-
const result = await exec(binary, args, { timeout: 1e4, windowsHide: true, maxBuffer: 65536 });
|
|
13787
|
-
return parseHerdrCommandOutput(result.stdout, args);
|
|
13788
|
-
} catch (error) {
|
|
13789
|
-
throw new Error(`${args.slice(0, args[0] === "plugin" ? 3 : 2).join(" ")}: ${describeHerdrFailure(error, binary)}`);
|
|
13790
|
-
}
|
|
13791
|
-
},
|
|
13792
|
-
statePath: relayTabPath(),
|
|
13793
|
-
pluginPaneId: process.env.HERDR_PANE_ID,
|
|
13794
|
-
warn: (message) => process.stderr.write(`${message}
|
|
13795
|
-
`)
|
|
13796
|
-
};
|
|
13797
|
-
}
|
|
13798
|
-
function safeFailure(error) {
|
|
13799
|
-
const raw = typeof error?.stderr === "string" && error.stderr.trim() ? error.stderr : error?.message;
|
|
13800
|
-
let detail = raw;
|
|
13801
|
-
try {
|
|
13802
|
-
const response = JSON.parse(raw);
|
|
13803
|
-
detail = response.error?.message || response.message || "Herdr rejected the command";
|
|
13804
|
-
} catch {
|
|
13805
|
-
}
|
|
13806
|
-
return String(detail || "Herdr command failed").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 400);
|
|
13807
|
-
}
|
|
13808
|
-
function parseHerdrCommandOutput(raw, args) {
|
|
13809
|
-
const needsData = args[0] === "pane" && ["get", "list"].includes(args[1]) || args[0] === "plugin" && args[1] === "pane" && args[2] === "open";
|
|
13810
|
-
const text2 = raw.trim();
|
|
13811
|
-
if (!text2 && !needsData) return {};
|
|
13812
|
-
let value;
|
|
13813
|
-
try {
|
|
13814
|
-
value = JSON.parse(text2);
|
|
13815
|
-
} catch {
|
|
13816
|
-
if (!needsData) return {};
|
|
13817
|
-
throw new Error("Herdr returned an invalid JSON data response");
|
|
13818
|
-
}
|
|
13819
|
-
if (value?.ok === false || value?.error) throw new Error(value.error?.message || "Herdr command failed");
|
|
13820
|
-
if (!value || typeof value !== "object") {
|
|
13821
|
-
if (!needsData) return {};
|
|
13822
|
-
throw new Error("Herdr returned no pane data");
|
|
13823
|
-
}
|
|
13824
|
-
return value.result ?? value;
|
|
13825
|
-
}
|
|
13826
|
-
async function readRecord(statePath) {
|
|
13827
|
-
try {
|
|
13828
|
-
const value = JSON.parse(await readFile6(statePath, "utf8"));
|
|
13829
|
-
if (value?.version === 1 && typeof value.paneId === "string" && typeof value.marker === "string") return value;
|
|
13830
|
-
} catch {
|
|
13831
|
-
}
|
|
13832
|
-
return void 0;
|
|
13833
|
-
}
|
|
13834
|
-
async function writeRecord(statePath, record) {
|
|
13835
|
-
await mkdir3(dirname3(statePath), { recursive: true });
|
|
13836
|
-
const temporary = `${statePath}.${randomUUID4()}.tmp`;
|
|
13837
|
-
try {
|
|
13838
|
-
await writeFile3(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
13839
|
-
await rename3(temporary, statePath);
|
|
13840
|
-
} finally {
|
|
13841
|
-
await rm2(temporary, { force: true }).catch(() => {
|
|
13842
|
-
});
|
|
13843
|
-
}
|
|
13844
|
-
}
|
|
13845
|
-
async function withLaunchLock(statePath, action) {
|
|
13846
|
-
const lockPath2 = `${statePath}.launch-lock`;
|
|
13847
|
-
await mkdir3(dirname3(statePath), { recursive: true });
|
|
13848
|
-
const deadline = Date.now() + 5e3;
|
|
13849
|
-
while (true) {
|
|
13850
|
-
try {
|
|
13851
|
-
await mkdir3(lockPath2);
|
|
13852
|
-
break;
|
|
13853
|
-
} catch (error) {
|
|
13854
|
-
if (error?.code !== "EEXIST") throw error;
|
|
13855
|
-
let stale = false;
|
|
13856
|
-
try {
|
|
13857
|
-
const info = await stat2(lockPath2);
|
|
13858
|
-
if (Date.now() - info.mtimeMs > 12e4) {
|
|
13859
|
-
const quarantine = `${lockPath2}.stale-${randomUUID4()}`;
|
|
13860
|
-
await rename3(lockPath2, quarantine).then(() => rmdir2(quarantine)).catch(() => {
|
|
13861
|
-
});
|
|
13862
|
-
stale = true;
|
|
13863
|
-
}
|
|
13864
|
-
} catch {
|
|
13865
|
-
stale = true;
|
|
13866
|
-
}
|
|
13867
|
-
if (stale) continue;
|
|
13868
|
-
if (Date.now() >= deadline) throw new Error("Another PeerBand Relay tab launch is already in progress");
|
|
13869
|
-
await new Promise((resolve5) => setTimeout(resolve5, 100));
|
|
13870
|
-
}
|
|
13871
|
-
}
|
|
13872
|
-
try {
|
|
13873
|
-
return await action();
|
|
13874
|
-
} finally {
|
|
13875
|
-
await rmdir2(lockPath2).catch(() => {
|
|
13876
|
-
});
|
|
13877
|
-
}
|
|
15079
|
+
import { join as join9, resolve as resolve4 } from "node:path";
|
|
15080
|
+
|
|
15081
|
+
// src/cli/commands/herdr-check.ts
|
|
15082
|
+
import { readFile as readFile8, stat as stat4 } from "node:fs/promises";
|
|
15083
|
+
import { join as join7 } from "node:path";
|
|
15084
|
+
var PLUGIN_ID = "peerband";
|
|
15085
|
+
var REPAIR_COMMAND = "peerband herdr install";
|
|
15086
|
+
var UPDATE_COMMAND = "peerband update";
|
|
15087
|
+
var fixCommand = (problem) => problem?.code === "version-mismatch" ? UPDATE_COMMAND : REPAIR_COMMAND;
|
|
15088
|
+
async function pluginInstalled(ctx) {
|
|
15089
|
+
const result = await ctx.runHerdr(["plugin", "list"], { timeoutMs: 1e4 });
|
|
15090
|
+
if (result.notFound) return { found: false, installed: false, source: null };
|
|
15091
|
+
if (result.code !== 0) return { found: true, installed: false, source: null, detail: failureDetail(result) };
|
|
15092
|
+
const line = /^\s*-\s+peerband\s.*$/m.exec(result.stdout)?.[0];
|
|
15093
|
+
if (line === void 0) return { found: true, installed: false, source: null };
|
|
15094
|
+
const source = /\[([^\]]*)\]\s*$/.exec(line)?.[1]?.trim() || null;
|
|
15095
|
+
return { found: true, installed: true, source };
|
|
13878
15096
|
}
|
|
13879
|
-
|
|
13880
|
-
|
|
13881
|
-
|
|
15097
|
+
function herdrVersion(output) {
|
|
15098
|
+
return /\d+\.\d+\.\d+(?:[-+.\w]*)?/.exec(output)?.[0] ?? null;
|
|
15099
|
+
}
|
|
15100
|
+
async function readSettings(ctx) {
|
|
15101
|
+
const dir = await ctx.runHerdr(["plugin", "config-dir", PLUGIN_ID], { timeoutMs: 1e4 });
|
|
15102
|
+
const configDir = dir.code === 0 ? dir.stdout.trim() : "";
|
|
15103
|
+
if (!configDir) return null;
|
|
13882
15104
|
try {
|
|
13883
|
-
|
|
15105
|
+
const value = JSON.parse(await readFile8(join7(configDir, "settings.json"), "utf8"));
|
|
15106
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
13884
15107
|
} catch {
|
|
13885
|
-
return
|
|
15108
|
+
return null;
|
|
13886
15109
|
}
|
|
13887
|
-
if (!pane || pane.pane_id !== record.paneId || pane.tokens?.[markerName] !== record.marker) return void 0;
|
|
13888
|
-
return pane;
|
|
13889
15110
|
}
|
|
13890
|
-
async function
|
|
13891
|
-
if (!pane?.workspace_id || !pane?.tab_id || !pane?.pane_id) return false;
|
|
13892
|
-
let listed;
|
|
15111
|
+
async function isFile(path) {
|
|
13893
15112
|
try {
|
|
13894
|
-
|
|
15113
|
+
return (await stat4(path)).isFile();
|
|
13895
15114
|
} catch {
|
|
13896
15115
|
return false;
|
|
13897
15116
|
}
|
|
13898
|
-
if (!Array.isArray(listed)) return false;
|
|
13899
|
-
const inTab = listed.filter((item) => item.tab_id === pane.tab_id);
|
|
13900
|
-
if (inTab.length !== 1 || inTab[0]?.pane_id !== pane.pane_id) return false;
|
|
13901
|
-
await run2(["tab", "rename", pane.tab_id, label]);
|
|
13902
|
-
return true;
|
|
13903
15117
|
}
|
|
13904
|
-
function
|
|
13905
|
-
|
|
13906
|
-
|
|
13907
|
-
|
|
13908
|
-
|
|
13909
|
-
|
|
13910
|
-
|
|
13911
|
-
|
|
13912
|
-
|
|
13913
|
-
|
|
13914
|
-
|
|
13915
|
-
|
|
13916
|
-
const key = `${pane.pane_id}\0${pane.tab_id}`;
|
|
13917
|
-
if (lastVerifiedTitle.get(key) === label) return true;
|
|
13918
|
-
const renamed = await renameOwnedSinglePaneTab(run2, pane, label);
|
|
13919
|
-
if (renamed) lastVerifiedTitle.set(key, label);
|
|
13920
|
-
return renamed;
|
|
13921
|
-
} catch {
|
|
13922
|
-
return false;
|
|
13923
|
-
}
|
|
15118
|
+
function sourceRef(source) {
|
|
15119
|
+
const at = source.lastIndexOf("@");
|
|
15120
|
+
return at > 0 ? source.slice(at + 1) || null : null;
|
|
15121
|
+
}
|
|
15122
|
+
async function checkHerdrPlugin(ctx) {
|
|
15123
|
+
const version = await ctx.runHerdr(["--version"], { timeoutMs: 1e4 });
|
|
15124
|
+
if (version.notFound) return { found: false, herdrVersion: null, installed: false, source: null, problems: [] };
|
|
15125
|
+
const herdrV = version.code === 0 ? herdrVersion(`${version.stdout} ${version.stderr}`) : null;
|
|
15126
|
+
const listed = await pluginInstalled(ctx);
|
|
15127
|
+
if (listed.detail) return { found: true, herdrVersion: herdrV, installed: false, source: null, detail: listed.detail, problems: [] };
|
|
15128
|
+
if (!listed.installed) {
|
|
15129
|
+
return { found: true, herdrVersion: herdrV, installed: false, source: null, problems: [{ code: "not-installed", message: "The PeerBand plugin is not installed in Herdr." }] };
|
|
13924
15130
|
}
|
|
13925
|
-
|
|
13926
|
-
|
|
13927
|
-
|
|
13928
|
-
|
|
13929
|
-
|
|
13930
|
-
|
|
13931
|
-
|
|
13932
|
-
|
|
13933
|
-
|
|
13934
|
-
|
|
15131
|
+
const problems = [];
|
|
15132
|
+
const source = listed.source;
|
|
15133
|
+
const override = Boolean(ctx.env.PEERBAND_HERDR_SOURCE);
|
|
15134
|
+
if (source?.startsWith("local:")) {
|
|
15135
|
+
if (!override) problems.push({ code: "local-source", message: `The plugin is linked to a local checkout (${source.slice("local:".length)}), not the v${ctx.version} release.` });
|
|
15136
|
+
} else if (source !== null && !override) {
|
|
15137
|
+
const expected = ctx.env.PEERBAND_HERDR_REF || `v${ctx.version}`;
|
|
15138
|
+
const ref = sourceRef(source);
|
|
15139
|
+
if (ref !== expected) {
|
|
15140
|
+
problems.push({ code: "version-mismatch", message: `The plugin is ${ref ? `at ${ref}` : "not pinned to a version"}, but this CLI is ${expected}.` });
|
|
13935
15141
|
}
|
|
15142
|
+
} else if (source !== null && ctx.env.PEERBAND_HERDR_REF) {
|
|
15143
|
+
const ref = sourceRef(source);
|
|
15144
|
+
if (ref !== ctx.env.PEERBAND_HERDR_REF) problems.push({ code: "version-mismatch", message: `The plugin is at ${ref ?? "no ref"}, but PEERBAND_HERDR_REF is ${ctx.env.PEERBAND_HERDR_REF}.` });
|
|
13936
15145
|
}
|
|
13937
|
-
|
|
13938
|
-
|
|
13939
|
-
|
|
13940
|
-
|
|
13941
|
-
|
|
13942
|
-
|
|
13943
|
-
|
|
13944
|
-
}
|
|
13945
|
-
const result = await run2(["plugin", "pane", "open", "--plugin", pluginId, "--entrypoint", entrypoint, "--placement", "tab", "--focus"]);
|
|
13946
|
-
const opened = result.plugin_pane;
|
|
13947
|
-
if (opened?.plugin_id !== pluginId || opened?.entrypoint !== entrypoint || typeof opened.pane?.pane_id !== "string") {
|
|
13948
|
-
throw new Error("Herdr did not return the expected plugin pane");
|
|
13949
|
-
}
|
|
13950
|
-
const record = { version: 1, paneId: opened.pane.pane_id, marker: newMarker() };
|
|
13951
|
-
try {
|
|
13952
|
-
await renameOwnedSinglePaneTab(run2, opened.pane, tabTitle(false)).catch((error) => {
|
|
13953
|
-
warn(`Relay tab opened; its initial title could not be set: ${safeFailure(error)}`);
|
|
13954
|
-
});
|
|
13955
|
-
await writeRecord(statePath, record);
|
|
13956
|
-
await run2(["pane", "report-metadata", record.paneId, "--source", markerSource, "--token", `${markerName}=${record.marker}`]);
|
|
13957
|
-
const marked = await inspectOwned(run2, record);
|
|
13958
|
-
if (!marked) throw new Error("Herdr did not retain the plugin pane ownership marker");
|
|
13959
|
-
return record.paneId;
|
|
13960
|
-
} catch (error) {
|
|
13961
|
-
await run2(["plugin", "pane", "close", record.paneId]).catch(() => {
|
|
13962
|
-
});
|
|
13963
|
-
const current = await readRecord(statePath);
|
|
13964
|
-
if (current?.paneId === record.paneId && current.marker === record.marker) await rm2(statePath, { force: true }).catch(() => {
|
|
13965
|
-
});
|
|
13966
|
-
throw error;
|
|
13967
|
-
}
|
|
13968
|
-
});
|
|
15146
|
+
const settings = await readSettings(ctx);
|
|
15147
|
+
const current = configHome({ env: ctx.env });
|
|
15148
|
+
const fallback = configHome({ env: { ...ctx.env, PEERBAND_CONFIG_HOME: void 0 } });
|
|
15149
|
+
const recorded = settings && typeof settings.configHome === "string" && settings.configHome ? settings.configHome : fallback;
|
|
15150
|
+
if (settings && canonicalConfig2(recorded) !== canonicalConfig2(current)) {
|
|
15151
|
+
const shown = typeof settings.configHome === "string" && settings.configHome ? settings.configHome : `${fallback} (default)`;
|
|
15152
|
+
problems.push({ code: "config-home", message: `The plugin uses the config directory ${shown}, but this CLI uses ${current}.` });
|
|
13969
15153
|
}
|
|
13970
|
-
|
|
15154
|
+
const nodePath = settings?.nodePath;
|
|
15155
|
+
if (typeof nodePath !== "string" || !nodePath) {
|
|
15156
|
+
problems.push({ code: "node-path", message: "The plugin settings do not record a Node.js path." });
|
|
15157
|
+
} else if (!await isFile(nodePath)) {
|
|
15158
|
+
problems.push({ code: "node-path", message: `The Node.js recorded in the plugin settings no longer exists (${nodePath}).` });
|
|
15159
|
+
}
|
|
15160
|
+
return { found: true, herdrVersion: herdrV, installed: true, source, problems };
|
|
13971
15161
|
}
|
|
13972
|
-
|
|
13973
|
-
|
|
13974
|
-
|
|
15162
|
+
|
|
15163
|
+
// src/cli/plugin-replace.ts
|
|
15164
|
+
var PLUGIN_ID2 = "peerband";
|
|
15165
|
+
var RETRYABLE = /os error (?:5|32|33)\b|code: (?:5|32|33)\b|being used by another process|\bEBUSY\b|\bEPERM\b|\bEACCES\b|access is denied|resource busy|text file busy|directory not empty/i;
|
|
15166
|
+
var ALREADY_INSTALLED = /already (?:installed|exists|registered)|exists already/i;
|
|
15167
|
+
var RETRY_DELAYS_MS = [1e3, 2e3, 4e3, 8e3];
|
|
15168
|
+
function parseSource(source) {
|
|
15169
|
+
if (!source) return null;
|
|
15170
|
+
if (source.startsWith("local:")) return { kind: "local", dir: source.slice("local:".length) };
|
|
15171
|
+
const match = /^(?:github:)?([^@\s]+\/[^@\s]+)@([^@\s]+)$/.exec(source);
|
|
15172
|
+
return match ? { kind: "github", source: match[1], ref: match[2] } : null;
|
|
13975
15173
|
}
|
|
13976
|
-
|
|
13977
|
-
|
|
13978
|
-
return controller.open();
|
|
15174
|
+
function describeTarget(target) {
|
|
15175
|
+
return target.kind === "local" ? `local checkout ${target.dir}` : `${target.source} @ ${target.ref}`;
|
|
13979
15176
|
}
|
|
13980
|
-
|
|
13981
|
-
|
|
13982
|
-
var CONNECTION_STATES = /* @__PURE__ */ new Set(["connecting", "connected", "reconnecting", "revoked", "unavailable", "remote-unavailable", "helper-unavailable", "disabled"]);
|
|
13983
|
-
var OUTCOMES = /* @__PURE__ */ new Set(["success", "runtime-unavailable", "error", "uncertain", "timeout"]);
|
|
13984
|
-
var TOOLS = /* @__PURE__ */ new Set(["list_agents", "get_agent_status", "get_agent_output", "get_request_status", "send_agent_message"]);
|
|
13985
|
-
function normalizeStoredActivity(value) {
|
|
13986
|
-
if (!value || typeof value !== "object" || typeof value.requestId !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(value.requestId) || !TOOLS.has(value.tool) || !OUTCOMES.has(value.outcome) || !Number.isFinite(value.latencyMs) || typeof value.at !== "string" || Number.isNaN(Date.parse(value.at))) return null;
|
|
13987
|
-
return { kind: "activity", requestId: value.requestId, tool: value.tool, ...typeof value.target === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value.target) ? { target: value.target } : {}, outcome: value.outcome, latencyMs: Math.max(0, Math.min(864e5, Math.round(value.latencyMs))), at: new Date(value.at).toISOString() };
|
|
15177
|
+
function installCommand(target) {
|
|
15178
|
+
return target.kind === "local" ? `herdr plugin link ${target.dir}` : `herdr plugin install ${target.source} --ref ${target.ref} --yes`;
|
|
13988
15179
|
}
|
|
13989
|
-
function
|
|
13990
|
-
|
|
13991
|
-
|
|
13992
|
-
|
|
13993
|
-
|
|
13994
|
-
|
|
15180
|
+
async function herdrRetrying(ctx, args, timeoutMs) {
|
|
15181
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
|
|
15182
|
+
let result = await ctx.runHerdr(args, { timeoutMs });
|
|
15183
|
+
for (const delay of RETRY_DELAYS_MS) {
|
|
15184
|
+
if (result.code === 0 || result.notFound || !RETRYABLE.test(failureDetail(result))) return result;
|
|
15185
|
+
ctx.out.print(ctx.out.stdout.dim(`Herdr reports the plugin files are still in use; retrying in ${delay / 1e3}s\u2026`));
|
|
15186
|
+
await sleep(delay);
|
|
15187
|
+
result = await ctx.runHerdr(args, { timeoutMs });
|
|
15188
|
+
}
|
|
15189
|
+
return result;
|
|
13995
15190
|
}
|
|
13996
|
-
function
|
|
13997
|
-
|
|
13998
|
-
return {
|
|
13999
|
-
...snapshot,
|
|
14000
|
-
state: "stopping",
|
|
14001
|
-
connectionState: snapshot.connectionState === "revoked" || snapshot.connectionState === "disabled" ? snapshot.connectionState : "helper-unavailable"
|
|
14002
|
-
};
|
|
15191
|
+
function putPlugin(ctx, target) {
|
|
15192
|
+
return target.kind === "local" ? herdrRetrying(ctx, ["plugin", "link", target.dir], 6e4) : herdrRetrying(ctx, ["plugin", "install", target.source, "--ref", target.ref, "--yes"], 18e4);
|
|
14003
15193
|
}
|
|
14004
|
-
function
|
|
14005
|
-
|
|
14006
|
-
|
|
14007
|
-
|
|
14008
|
-
|
|
14009
|
-
|
|
14010
|
-
|
|
14011
|
-
|
|
14012
|
-
|
|
14013
|
-
|
|
14014
|
-
|
|
14015
|
-
|
|
14016
|
-
|
|
14017
|
-
|
|
14018
|
-
|
|
14019
|
-
|
|
14020
|
-
|
|
14021
|
-
|
|
14022
|
-
|
|
14023
|
-
|
|
14024
|
-
|
|
15194
|
+
async function removePlugin(ctx) {
|
|
15195
|
+
const uninstall = await herdrRetrying(ctx, ["plugin", "uninstall", PLUGIN_ID2], 6e4);
|
|
15196
|
+
if (uninstall.code === 0) return { removed: true, detail: "" };
|
|
15197
|
+
const unlink3 = await herdrRetrying(ctx, ["plugin", "unlink", PLUGIN_ID2], 6e4);
|
|
15198
|
+
if (unlink3.code === 0) return { removed: true, detail: "" };
|
|
15199
|
+
return { removed: false, detail: failureDetail(uninstall) };
|
|
15200
|
+
}
|
|
15201
|
+
var ReplaceError = class extends CliError {
|
|
15202
|
+
restored;
|
|
15203
|
+
constructor(message, hint, restored) {
|
|
15204
|
+
super(message, hint);
|
|
15205
|
+
this.restored = restored;
|
|
15206
|
+
}
|
|
15207
|
+
};
|
|
15208
|
+
async function rollback(ctx, previous, target, detail) {
|
|
15209
|
+
const check = target.kind === "github" ? `Check that ${target.source} at ref ${target.ref} exists and that you are online (override with PEERBAND_HERDR_SOURCE or PEERBAND_HERDR_REF). ` : "Check that the directory is a peerband-cli checkout containing herdr-plugin.toml. ";
|
|
15210
|
+
const retry = `${check}Close every PeerBand Relay tab and retry \`peerband herdr install\`; if it keeps failing, run \`${installCommand(target)}\` yourself.`;
|
|
15211
|
+
if (!previous) throw new ReplaceError(`Installing the PeerBand plugin (${describeTarget(target)}) failed: ${detail}`, retry, false);
|
|
15212
|
+
ctx.out.print(ctx.out.stdout.dim(`Installing ${describeTarget(target)} failed; restoring the previous plugin (${describeTarget(previous)}).`));
|
|
15213
|
+
const restored = await putPlugin(ctx, previous);
|
|
15214
|
+
if (restored.code === 0 && (await pluginInstalled(ctx)).installed) {
|
|
15215
|
+
throw new ReplaceError(`Installing the PeerBand plugin (${describeTarget(target)}) failed: ${detail}. The previous plugin (${describeTarget(previous)}) was restored.`, retry, true);
|
|
15216
|
+
}
|
|
15217
|
+
throw new ReplaceError(
|
|
15218
|
+
`Installing the PeerBand plugin (${describeTarget(target)}) failed: ${detail}. Restoring the previous plugin failed too: ${failureDetail(restored)}. Herdr has no PeerBand plugin right now.`,
|
|
15219
|
+
`Close every PeerBand Relay tab, then run \`${installCommand(target)}\` (or \`${installCommand(previous)}\` for the previous version), then \`peerband herdr install\`.`,
|
|
15220
|
+
false
|
|
15221
|
+
);
|
|
15222
|
+
}
|
|
15223
|
+
async function replacePlugin(ctx, previousSource, installed, target) {
|
|
15224
|
+
const previous = installed ? parseSource(previousSource) : null;
|
|
15225
|
+
if (!installed) {
|
|
15226
|
+
const result2 = await putPlugin(ctx, target);
|
|
15227
|
+
if (result2.code !== 0) await rollback(ctx, null, target, failureDetail(result2));
|
|
15228
|
+
return;
|
|
15229
|
+
}
|
|
15230
|
+
if (target.kind === "github" && previous?.kind !== "local") {
|
|
15231
|
+
const result2 = await putPlugin(ctx, target);
|
|
15232
|
+
if (result2.code === 0) return;
|
|
15233
|
+
const detail = failureDetail(result2);
|
|
15234
|
+
if (!ALREADY_INSTALLED.test(detail)) {
|
|
15235
|
+
if ((await pluginInstalled(ctx)).installed) {
|
|
15236
|
+
throw new ReplaceError(
|
|
15237
|
+
`Installing the PeerBand plugin (${describeTarget(target)}) failed: ${detail}. The previous plugin${previousSource ? ` (${previousSource})` : ""} is still installed.`,
|
|
15238
|
+
`Check that ${target.source} at ref ${target.ref} exists and that you are online. Override with PEERBAND_HERDR_SOURCE or PEERBAND_HERDR_REF.`,
|
|
15239
|
+
true
|
|
15240
|
+
);
|
|
15241
|
+
}
|
|
15242
|
+
await rollback(ctx, previous, target, detail);
|
|
15243
|
+
}
|
|
14025
15244
|
}
|
|
15245
|
+
const removed = await removePlugin(ctx);
|
|
15246
|
+
if (!removed.removed) {
|
|
15247
|
+
throw new ReplaceError(`Could not replace the existing PeerBand plugin: ${removed.detail}`, `Close every PeerBand Relay tab, run \`herdr plugin uninstall ${PLUGIN_ID2}\` yourself, then retry.`, true);
|
|
15248
|
+
}
|
|
15249
|
+
const result = await putPlugin(ctx, target);
|
|
15250
|
+
if (result.code !== 0) await rollback(ctx, previous, target, failureDetail(result));
|
|
14026
15251
|
}
|
|
14027
15252
|
|
|
14028
|
-
// src/cli/
|
|
14029
|
-
|
|
14030
|
-
|
|
14031
|
-
var controlChannel2 = controlChannel;
|
|
14032
|
-
var ownerRecordPath2 = ownerRecordPath;
|
|
14033
|
-
var fallbackPaneSnapshot2 = fallbackPaneSnapshot;
|
|
14034
|
-
var createPaneSnapshot2 = createPaneSnapshot;
|
|
14035
|
-
var paneLabel2 = paneLabel;
|
|
15253
|
+
// src/cli/relay-maint.ts
|
|
15254
|
+
import { rm as rm5 } from "node:fs/promises";
|
|
15255
|
+
import { join as join8 } from "node:path";
|
|
14036
15256
|
|
|
14037
15257
|
// src/cli/control.ts
|
|
15258
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
15259
|
+
import { createConnection as createConnection4 } from "node:net";
|
|
14038
15260
|
async function requestControl(command, env, timeoutMs = 3e3) {
|
|
15261
|
+
return exchange({ command }, env, timeoutMs);
|
|
15262
|
+
}
|
|
15263
|
+
var ControlUnavailable = class extends Error {
|
|
15264
|
+
constructor(reason, message) {
|
|
15265
|
+
super(message);
|
|
15266
|
+
this.reason = reason;
|
|
15267
|
+
this.name = "ControlUnavailable";
|
|
15268
|
+
}
|
|
15269
|
+
reason;
|
|
15270
|
+
};
|
|
15271
|
+
async function requestNotify(note, env, timeoutMs = 8e3) {
|
|
15272
|
+
return exchange({ command: "notify", text: note.text, ...note.paneId ? { paneId: note.paneId } : {} }, env, timeoutMs, true);
|
|
15273
|
+
}
|
|
15274
|
+
async function exchange(payload, env, timeoutMs, typed = false) {
|
|
14039
15275
|
const config = configHome({ env });
|
|
14040
|
-
|
|
14041
|
-
|
|
14042
|
-
|
|
15276
|
+
let record;
|
|
15277
|
+
try {
|
|
15278
|
+
record = JSON.parse(await readFile9(ownerRecordPath2(config), "utf8"));
|
|
15279
|
+
} catch (error) {
|
|
15280
|
+
if (typed) throw new ControlUnavailable("not-running", "No relay helper is running");
|
|
15281
|
+
throw error;
|
|
15282
|
+
}
|
|
15283
|
+
if (typeof record.token !== "string") throw typed ? new ControlUnavailable("not-running", "Invalid helper record") : new Error("Invalid helper record");
|
|
15284
|
+
const socket = createConnection4(controlChannel2(config));
|
|
14043
15285
|
return new Promise((resolve5, reject) => {
|
|
14044
15286
|
let text2 = "";
|
|
14045
15287
|
let settled = false;
|
|
@@ -14051,10 +15293,14 @@ async function requestControl(command, env, timeoutMs = 3e3) {
|
|
|
14051
15293
|
if (error) reject(error);
|
|
14052
15294
|
else resolve5(value ?? {});
|
|
14053
15295
|
};
|
|
14054
|
-
|
|
14055
|
-
|
|
14056
|
-
socket.once("
|
|
14057
|
-
|
|
15296
|
+
let connected = false;
|
|
15297
|
+
const timer = setTimeout(() => finish(typed ? new ControlUnavailable("timeout", "Helper control timeout") : new Error("Helper control timeout")), timeoutMs);
|
|
15298
|
+
socket.once("error", (error) => finish(typed ? new ControlUnavailable(connected ? "closed" : "not-running", error.message) : error));
|
|
15299
|
+
socket.once("connect", () => {
|
|
15300
|
+
connected = true;
|
|
15301
|
+
socket.write(`${JSON.stringify({ token: record.token, ...payload })}
|
|
15302
|
+
`);
|
|
15303
|
+
});
|
|
14058
15304
|
socket.on("data", (chunk) => {
|
|
14059
15305
|
text2 += chunk.toString();
|
|
14060
15306
|
if (text2.length > 65536) return finish(new Error("Invalid control response"));
|
|
@@ -14066,7 +15312,7 @@ async function requestControl(command, env, timeoutMs = 3e3) {
|
|
|
14066
15312
|
finish(error);
|
|
14067
15313
|
}
|
|
14068
15314
|
});
|
|
14069
|
-
socket.once("end", () => finish(new Error("Helper control closed")));
|
|
15315
|
+
socket.once("end", () => finish(typed ? new ControlUnavailable("closed", "Helper control closed") : new Error("Helper control closed")));
|
|
14070
15316
|
});
|
|
14071
15317
|
}
|
|
14072
15318
|
async function relaySnapshot(env) {
|
|
@@ -14076,7 +15322,7 @@ async function relaySnapshot(env) {
|
|
|
14076
15322
|
} catch {
|
|
14077
15323
|
}
|
|
14078
15324
|
try {
|
|
14079
|
-
const saved = JSON.parse(await
|
|
15325
|
+
const saved = JSON.parse(await readFile9(relayStatePath({ env }), "utf8"));
|
|
14080
15326
|
return { ...fallbackPaneSnapshot2(saved), source: "file" };
|
|
14081
15327
|
} catch {
|
|
14082
15328
|
return void 0;
|
|
@@ -14091,89 +15337,92 @@ async function stopRelay(env) {
|
|
|
14091
15337
|
}
|
|
14092
15338
|
}
|
|
14093
15339
|
|
|
14094
|
-
// src/cli/
|
|
14095
|
-
|
|
14096
|
-
|
|
14097
|
-
var
|
|
14098
|
-
var
|
|
14099
|
-
async function
|
|
14100
|
-
const
|
|
14101
|
-
|
|
14102
|
-
if (result.code !== 0) return { found: true, installed: false, source: null, detail: failureDetail(result) };
|
|
14103
|
-
const line = /^\s*-\s+peerband\s.*$/m.exec(result.stdout)?.[0];
|
|
14104
|
-
if (line === void 0) return { found: true, installed: false, source: null };
|
|
14105
|
-
const source = /\[([^\]]*)\]\s*$/.exec(line)?.[1]?.trim() || null;
|
|
14106
|
-
return { found: true, installed: true, source };
|
|
14107
|
-
}
|
|
14108
|
-
function herdrVersion(output) {
|
|
14109
|
-
return /\d+\.\d+\.\d+(?:[-+.\w]*)?/.exec(output)?.[0] ?? null;
|
|
15340
|
+
// src/cli/relay-maint.ts
|
|
15341
|
+
var RELAY_MARKER = "peerband_relay";
|
|
15342
|
+
var RELAY_LABEL = /^PeerBand Relay\b/;
|
|
15343
|
+
var defaultSleep2 = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
15344
|
+
var sleeper = (ctx) => ctx.sleep ?? defaultSleep2;
|
|
15345
|
+
async function relayRunning(ctx) {
|
|
15346
|
+
const snapshot = await relaySnapshot(ctx.env);
|
|
15347
|
+
return snapshot?.source === "control" && snapshot.state === "running";
|
|
14110
15348
|
}
|
|
14111
|
-
async function
|
|
14112
|
-
const
|
|
14113
|
-
|
|
14114
|
-
|
|
15349
|
+
async function findRelayPanes(ctx) {
|
|
15350
|
+
const result = await ctx.runHerdr(["pane", "list"], { timeoutMs: 1e4 });
|
|
15351
|
+
if (result.code !== 0) return [];
|
|
15352
|
+
let panes;
|
|
14115
15353
|
try {
|
|
14116
|
-
const
|
|
14117
|
-
|
|
15354
|
+
const parsed = JSON.parse(result.stdout);
|
|
15355
|
+
panes = parsed.result?.panes ?? parsed.panes;
|
|
14118
15356
|
} catch {
|
|
14119
|
-
return
|
|
15357
|
+
return [];
|
|
14120
15358
|
}
|
|
14121
|
-
|
|
14122
|
-
|
|
14123
|
-
|
|
14124
|
-
|
|
14125
|
-
|
|
14126
|
-
|
|
15359
|
+
if (!Array.isArray(panes)) return [];
|
|
15360
|
+
const found = [];
|
|
15361
|
+
for (const pane of panes) {
|
|
15362
|
+
if (!pane || typeof pane.pane_id !== "string") continue;
|
|
15363
|
+
const tokens = pane.tokens && typeof pane.tokens === "object" ? pane.tokens : {};
|
|
15364
|
+
const label = typeof pane.label === "string" ? pane.label : void 0;
|
|
15365
|
+
if (typeof tokens[RELAY_MARKER] === "string" || label && RELAY_LABEL.test(label)) found.push({ paneId: pane.pane_id, label });
|
|
14127
15366
|
}
|
|
15367
|
+
return found;
|
|
14128
15368
|
}
|
|
14129
|
-
function
|
|
14130
|
-
|
|
14131
|
-
|
|
14132
|
-
}
|
|
14133
|
-
|
|
14134
|
-
|
|
14135
|
-
|
|
14136
|
-
const herdrV = version.code === 0 ? herdrVersion(`${version.stdout} ${version.stderr}`) : null;
|
|
14137
|
-
const listed = await pluginInstalled(ctx);
|
|
14138
|
-
if (listed.detail) return { found: true, herdrVersion: herdrV, installed: false, source: null, detail: listed.detail, problems: [] };
|
|
14139
|
-
if (!listed.installed) {
|
|
14140
|
-
return { found: true, herdrVersion: herdrV, installed: false, source: null, problems: [{ code: "not-installed", message: "The PeerBand plugin is not installed in Herdr." }] };
|
|
14141
|
-
}
|
|
14142
|
-
const problems = [];
|
|
14143
|
-
const source = listed.source;
|
|
14144
|
-
const override = Boolean(ctx.env.PEERBAND_HERDR_SOURCE);
|
|
14145
|
-
if (source?.startsWith("local:")) {
|
|
14146
|
-
if (!override) problems.push({ code: "local-source", message: `The plugin is linked to a local checkout (${source.slice("local:".length)}), not the v${ctx.version} release.` });
|
|
14147
|
-
} else if (source !== null && !override) {
|
|
14148
|
-
const expected = ctx.env.PEERBAND_HERDR_REF || `v${ctx.version}`;
|
|
14149
|
-
const ref = sourceRef(source);
|
|
14150
|
-
if (ref !== expected) {
|
|
14151
|
-
problems.push({ code: "version-mismatch", message: `The plugin is ${ref ? `at ${ref}` : "not pinned to a version"}, but this CLI is ${expected}.` });
|
|
15369
|
+
async function closeRelayPanes(ctx, panes, waitMs = 8e3) {
|
|
15370
|
+
let closed = 0;
|
|
15371
|
+
for (const pane of panes) {
|
|
15372
|
+
const viaPlugin = await ctx.runHerdr(["plugin", "pane", "close", pane.paneId], { timeoutMs: 1e4 });
|
|
15373
|
+
if (viaPlugin.code === 0) {
|
|
15374
|
+
closed++;
|
|
15375
|
+
continue;
|
|
14152
15376
|
}
|
|
14153
|
-
|
|
14154
|
-
|
|
14155
|
-
if (ref !== ctx.env.PEERBAND_HERDR_REF) problems.push({ code: "version-mismatch", message: `The plugin is at ${ref ?? "no ref"}, but PEERBAND_HERDR_REF is ${ctx.env.PEERBAND_HERDR_REF}.` });
|
|
15377
|
+
const plain = await ctx.runHerdr(["pane", "close", pane.paneId], { timeoutMs: 1e4 });
|
|
15378
|
+
if (plain.code === 0) closed++;
|
|
14156
15379
|
}
|
|
14157
|
-
const
|
|
14158
|
-
const
|
|
14159
|
-
|
|
14160
|
-
|
|
14161
|
-
|
|
14162
|
-
|
|
14163
|
-
problems.push({ code: "config-home", message: `The plugin uses the config directory ${shown}, but this CLI uses ${current}.` });
|
|
15380
|
+
const ids = new Set(panes.map((pane) => pane.paneId));
|
|
15381
|
+
const sleep = sleeper(ctx);
|
|
15382
|
+
for (let waited = 0; ids.size > 0 && waited < waitMs; waited += 250) {
|
|
15383
|
+
const remaining = await findRelayPanes(ctx);
|
|
15384
|
+
if (!remaining.some((pane) => ids.has(pane.paneId))) break;
|
|
15385
|
+
await sleep(250);
|
|
14164
15386
|
}
|
|
14165
|
-
|
|
14166
|
-
|
|
14167
|
-
|
|
14168
|
-
|
|
14169
|
-
|
|
15387
|
+
await rm5(relayTabPath({ env: ctx.env }), { force: true }).catch(() => void 0);
|
|
15388
|
+
return closed;
|
|
15389
|
+
}
|
|
15390
|
+
async function stopRelayAndWait(ctx, waitMs = 1e4) {
|
|
15391
|
+
const stopped = await stopRelay(ctx.env);
|
|
15392
|
+
if (!stopped) return false;
|
|
15393
|
+
const channel = controlChannel2(configHome({ env: ctx.env }));
|
|
15394
|
+
const sleep = sleeper(ctx);
|
|
15395
|
+
for (let waited = 0; waited < waitMs; waited += 200) {
|
|
15396
|
+
if (await probeChannel2(channel, 1e3) === "absent") break;
|
|
15397
|
+
await sleep(200);
|
|
14170
15398
|
}
|
|
14171
|
-
return
|
|
15399
|
+
return true;
|
|
15400
|
+
}
|
|
15401
|
+
async function cleanRelayState(ctx, options = {}) {
|
|
15402
|
+
const config = configHome({ env: ctx.env });
|
|
15403
|
+
const report2 = { reclaimed: [], held: [], removedState: false };
|
|
15404
|
+
const helper = await reclaimIfStale2({ lockDir: lockPath({ env: ctx.env }), ownerFile: ownerRecordPath2(config), channel: controlChannel2(config), processPattern: SUPERVISOR_PATTERN2 });
|
|
15405
|
+
if (helper.reclaimed) report2.reclaimed.push(lockPath({ env: ctx.env }));
|
|
15406
|
+
else if (helper.verdict.state === "live") report2.held.push({ lock: lockPath({ env: ctx.env }), reason: helper.verdict.reason });
|
|
15407
|
+
const receiptsLock = `${receiptsPath({ env: ctx.env })}.lock`;
|
|
15408
|
+
const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile: join8(receiptsLock, "owner"), processPattern: CONNECTOR_PATTERN2 });
|
|
15409
|
+
if (receipts.reclaimed) report2.reclaimed.push(receiptsLock);
|
|
15410
|
+
else if (receipts.verdict.state === "live") report2.held.push({ lock: receiptsLock, reason: receipts.verdict.reason });
|
|
15411
|
+
const helperGone = helper.verdict.state !== "live";
|
|
15412
|
+
if (helperGone) {
|
|
15413
|
+
if (options.remove) {
|
|
15414
|
+
await rm5(relayStatePath({ env: ctx.env }), { force: true }).catch(() => void 0);
|
|
15415
|
+
await rm5(relayTabPath({ env: ctx.env }), { force: true }).catch(() => void 0);
|
|
15416
|
+
report2.removedState = true;
|
|
15417
|
+
} else {
|
|
15418
|
+
report2.removedState = await resetRelayState2(relayStatePath({ env: ctx.env })).catch(() => false);
|
|
15419
|
+
}
|
|
15420
|
+
}
|
|
15421
|
+
return report2;
|
|
14172
15422
|
}
|
|
14173
15423
|
|
|
14174
15424
|
// src/cli/commands/herdr.ts
|
|
14175
15425
|
var DEFAULT_SOURCE = "kshvidler/peerband-cli";
|
|
14176
|
-
var PLUGIN_ID2 = "peerband";
|
|
14177
15426
|
function isDirectory(path) {
|
|
14178
15427
|
try {
|
|
14179
15428
|
return statSync(path).isDirectory();
|
|
@@ -14190,94 +15439,148 @@ function must(result, what, hint) {
|
|
|
14190
15439
|
if (result.code !== 0) throw new CliError(`${what} failed: ${failureDetail(result)}`, hint);
|
|
14191
15440
|
return result;
|
|
14192
15441
|
}
|
|
14193
|
-
async function removePlugin(ctx) {
|
|
14194
|
-
const uninstall = await herdr(ctx, ["plugin", "uninstall", PLUGIN_ID2]);
|
|
14195
|
-
if (uninstall.code === 0) return { removed: true, detail: "" };
|
|
14196
|
-
const unlink3 = await herdr(ctx, ["plugin", "unlink", PLUGIN_ID2]);
|
|
14197
|
-
if (unlink3.code === 0) return { removed: true, detail: "" };
|
|
14198
|
-
return { removed: false, detail: failureDetail(uninstall) };
|
|
14199
|
-
}
|
|
14200
15442
|
function pluginSettings(env) {
|
|
14201
15443
|
return {
|
|
14202
15444
|
nodePath: process.execPath,
|
|
14203
15445
|
...env.PEERBAND_CONFIG_HOME ? { configHome: env.PEERBAND_CONFIG_HOME } : {}
|
|
14204
15446
|
};
|
|
14205
15447
|
}
|
|
15448
|
+
function reportCleanup(ctx, report2) {
|
|
15449
|
+
const s = ctx.out.stdout;
|
|
15450
|
+
if (report2.reclaimed.length) ctx.out.print(`${s.green(symbols.ok)} Cleared ${report2.reclaimed.length === 1 ? "a stale relay lock" : `${report2.reclaimed.length} stale relay locks`} left by a process that is no longer running.`);
|
|
15451
|
+
for (const held of report2.held) ctx.out.warn(`${ctx.out.stderr.yellow(symbols.warn)} ${held.lock} is still held: ${held.reason}.`);
|
|
15452
|
+
}
|
|
15453
|
+
async function releasePlugin(ctx) {
|
|
15454
|
+
const s = ctx.out.stdout;
|
|
15455
|
+
const wasRunning = await relayRunning(ctx);
|
|
15456
|
+
const panes = await findRelayPanes(ctx);
|
|
15457
|
+
if (await stopRelayAndWait(ctx)) ctx.out.print(`${s.green(symbols.ok)} Stopped the PeerBand Relay.`);
|
|
15458
|
+
if (panes.length) {
|
|
15459
|
+
const closed = await closeRelayPanes(ctx, panes);
|
|
15460
|
+
ctx.out.print(`${s.green(symbols.ok)} Closed ${closed === 1 ? "the PeerBand Relay tab" : `${closed} PeerBand Relay tabs`}.`);
|
|
15461
|
+
}
|
|
15462
|
+
return { wasRunning, hadPanes: panes.length > 0 };
|
|
15463
|
+
}
|
|
15464
|
+
async function waitForRelay(ctx, timeoutMs) {
|
|
15465
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
|
|
15466
|
+
for (let waited = 0; waited < timeoutMs; waited += 1e3) {
|
|
15467
|
+
if (await relayRunning(ctx)) return true;
|
|
15468
|
+
await sleep(1e3);
|
|
15469
|
+
}
|
|
15470
|
+
return relayRunning(ctx);
|
|
15471
|
+
}
|
|
15472
|
+
async function reopenRelay(ctx) {
|
|
15473
|
+
const s = ctx.out.stdout;
|
|
15474
|
+
const open = ctx.openRelayTab ?? openRelayTab2;
|
|
15475
|
+
const attempt = async () => {
|
|
15476
|
+
try {
|
|
15477
|
+
await open();
|
|
15478
|
+
return true;
|
|
15479
|
+
} catch (error) {
|
|
15480
|
+
ctx.out.warn(`${ctx.out.stderr.yellow(symbols.warn)} Could not reopen the PeerBand Relay tab: ${error.message}`);
|
|
15481
|
+
return false;
|
|
15482
|
+
}
|
|
15483
|
+
};
|
|
15484
|
+
if (!await attempt()) {
|
|
15485
|
+
ctx.out.print(`${s.dim("Next:")} peerband relay`);
|
|
15486
|
+
return false;
|
|
15487
|
+
}
|
|
15488
|
+
if (ctx.openRelayTab || await waitForRelay(ctx, 3e4)) {
|
|
15489
|
+
ctx.out.print(`${s.green(symbols.ok)} Reopened the PeerBand Relay tab.`);
|
|
15490
|
+
return true;
|
|
15491
|
+
}
|
|
15492
|
+
ctx.out.print(s.dim("The relay did not start yet; reopening the Relay tab once more."));
|
|
15493
|
+
await stopRelayAndWait(ctx);
|
|
15494
|
+
await closeRelayPanes(ctx, await findRelayPanes(ctx));
|
|
15495
|
+
if (await attempt() && await waitForRelay(ctx, 45e3)) {
|
|
15496
|
+
ctx.out.print(`${s.green(symbols.ok)} Reopened the PeerBand Relay tab.`);
|
|
15497
|
+
return true;
|
|
15498
|
+
}
|
|
15499
|
+
ctx.out.warn(`${ctx.out.stderr.yellow(symbols.warn)} The PeerBand Relay tab is open, but the relay has not started. Check the tab, or run \`peerband status\`.`);
|
|
15500
|
+
return false;
|
|
15501
|
+
}
|
|
15502
|
+
async function installPlugin(ctx, options = {}) {
|
|
15503
|
+
const s = ctx.out.stdout;
|
|
15504
|
+
const source = ctx.env.PEERBAND_HERDR_SOURCE || DEFAULT_SOURCE;
|
|
15505
|
+
const ref = ctx.env.PEERBAND_HERDR_REF || `v${ctx.version}`;
|
|
15506
|
+
const target = isDirectory(source) ? { kind: "local", dir: resolve4(source) } : { kind: "github", source, ref };
|
|
15507
|
+
const before = await pluginInstalled(ctx);
|
|
15508
|
+
if (!before.found) throw new CliError(NOT_FOUND_MESSAGE, NOT_FOUND_HINT);
|
|
15509
|
+
if (before.detail) throw new CliError(`Herdr could not list plugins: ${before.detail}`, "Check that your Herdr is 0.9.3 or newer (`herdr --version`).");
|
|
15510
|
+
const loggedIn = await loadCredentials(credentialsFile(ctx)).then(() => true, () => false);
|
|
15511
|
+
const held = await releasePlugin(ctx);
|
|
15512
|
+
reportCleanup(ctx, await cleanRelayState(ctx));
|
|
15513
|
+
const restore = loggedIn && (held.wasRunning || held.hadPanes);
|
|
15514
|
+
if (before.installed) ctx.out.print(s.dim(`Replacing the PeerBand plugin${before.source ? ` (${before.source})` : ""} with ${describeTarget(target)}.`));
|
|
15515
|
+
try {
|
|
15516
|
+
await replacePlugin(ctx, before.source, before.installed, target);
|
|
15517
|
+
} catch (error) {
|
|
15518
|
+
if (error instanceof ReplaceError && error.restored && restore) await reopenRelay(ctx);
|
|
15519
|
+
throw error;
|
|
15520
|
+
}
|
|
15521
|
+
ctx.out.print(`${s.green(symbols.ok)} ${target.kind === "local" ? `Linked the PeerBand plugin from ${target.dir}` : `Installed the PeerBand plugin (${target.source} @ ${target.ref})`}`);
|
|
15522
|
+
const dirResult = must(await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID2]), "herdr plugin config-dir", "The plugin may not have registered; run `herdr plugin list`.");
|
|
15523
|
+
const configDir = dirResult.stdout.trim();
|
|
15524
|
+
if (!configDir) throw new CliError("Herdr did not report a plugin config directory.", "Run `herdr plugin config-dir peerband` to investigate.");
|
|
15525
|
+
await mkdir5(configDir, { recursive: true });
|
|
15526
|
+
await writeFile6(join9(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
|
|
15527
|
+
`, { mode: 384 });
|
|
15528
|
+
ctx.out.print(`${s.green(symbols.ok)} Saved plugin settings ${s.dim(`(node ${process.execPath})`)}`);
|
|
15529
|
+
const after = await pluginInstalled(ctx);
|
|
15530
|
+
if (!after.installed) throw new CliError("Herdr does not list the PeerBand plugin after installing it.", "Run `herdr plugin list` and check the output above for errors.");
|
|
15531
|
+
if (restore) {
|
|
15532
|
+
await reopenRelay(ctx);
|
|
15533
|
+
} else if (options.relayNext !== false) {
|
|
15534
|
+
ctx.out.print(`${s.dim("Next:")} ${loggedIn ? "peerband relay" : "peerband login, then peerband relay"}`);
|
|
15535
|
+
}
|
|
15536
|
+
if (options.afterUpdate) ctx.out.print(`${s.green(symbols.ok)} PeerBand ${ctx.version} is ready.`);
|
|
15537
|
+
return 0;
|
|
15538
|
+
}
|
|
14206
15539
|
var installSpec = {
|
|
14207
15540
|
name: "herdr install",
|
|
14208
15541
|
summary: "Install the PeerBand plugin into Herdr",
|
|
14209
15542
|
usage: "peerband herdr install",
|
|
14210
|
-
description: "Installs (or updates) the PeerBand plugin in Herdr and records which Node.js to run it with, so the plugin works even if Herdr finds a different `node` on its PATH. Run it from a shell with Node.js 22.13 or newer.",
|
|
14211
|
-
options: [],
|
|
15543
|
+
description: "Installs (or updates) the PeerBand plugin in Herdr and records which Node.js to run it with, so the plugin works even if Herdr finds a different `node` on its PATH. Run it from a shell with Node.js 22.13 or newer.\nBefore replacing a plugin it stops the PeerBand Relay and closes its tabs (they keep the plugin files open), clears stale relay locks, and afterwards reopens the Relay tab if it was open. If the new plugin cannot be installed, the previous one is put back.",
|
|
15544
|
+
options: [{ name: "after-update", type: "boolean", description: "Internal: final step of `peerband update`.", hidden: true }],
|
|
14212
15545
|
examples: [
|
|
14213
15546
|
["peerband herdr install", "Install the release matching this CLI version"],
|
|
14214
15547
|
["PEERBAND_HERDR_REF=main peerband herdr install", "Install another branch, tag or commit"],
|
|
14215
15548
|
["PEERBAND_HERDR_SOURCE=./peerband-cli peerband herdr install", "Link a local checkout (build it first with npm run build)"]
|
|
14216
15549
|
],
|
|
14217
15550
|
notes: [
|
|
14218
|
-
`Environment: PEERBAND_HERDR_SOURCE (default ${DEFAULT_SOURCE}; an existing directory is linked instead of installed), PEERBAND_HERDR_REF (default v<version>), HERDR_BIN_PATH (used to find Herdr)
|
|
15551
|
+
`Environment: PEERBAND_HERDR_SOURCE (default ${DEFAULT_SOURCE}; an existing directory is linked instead of installed), PEERBAND_HERDR_REF (default v<version>), HERDR_BIN_PATH (used to find Herdr).`,
|
|
15552
|
+
"To update the CLI and the plugin together, use `peerband update`."
|
|
14219
15553
|
],
|
|
14220
|
-
|
|
14221
|
-
const s = ctx.out.stdout;
|
|
14222
|
-
const source = ctx.env.PEERBAND_HERDR_SOURCE || DEFAULT_SOURCE;
|
|
14223
|
-
const ref = ctx.env.PEERBAND_HERDR_REF || `v${ctx.version}`;
|
|
14224
|
-
const local = isDirectory(source);
|
|
14225
|
-
const before = await pluginInstalled(ctx);
|
|
14226
|
-
if (!before.found) throw new CliError(NOT_FOUND_MESSAGE, NOT_FOUND_HINT);
|
|
14227
|
-
if (before.detail) throw new CliError(`Herdr could not list plugins: ${before.detail}`, "Check that your Herdr is 0.9.3 or newer (`herdr --version`).");
|
|
14228
|
-
if (before.installed) {
|
|
14229
|
-
const removed = await removePlugin(ctx);
|
|
14230
|
-
if (!removed.removed) throw new CliError(`Could not replace the existing PeerBand plugin: ${removed.detail}`, `Run \`herdr plugin uninstall ${PLUGIN_ID2}\` yourself, then retry.`);
|
|
14231
|
-
ctx.out.print(s.dim(`Replacing the existing PeerBand plugin.`));
|
|
14232
|
-
}
|
|
14233
|
-
if (local) {
|
|
14234
|
-
const dir = resolve4(source);
|
|
14235
|
-
must(await herdr(ctx, ["plugin", "link", dir]), "herdr plugin link", "Check that the directory is a peerband-cli checkout containing herdr-plugin.toml.");
|
|
14236
|
-
ctx.out.print(`${s.green(symbols.ok)} Linked the PeerBand plugin from ${dir}`);
|
|
14237
|
-
} else {
|
|
14238
|
-
must(
|
|
14239
|
-
await herdr(ctx, ["plugin", "install", source, "--ref", ref, "--yes"], 18e4),
|
|
14240
|
-
"herdr plugin install",
|
|
14241
|
-
`Check that ${source} at ref ${ref} exists and that you are online. Override with PEERBAND_HERDR_SOURCE or PEERBAND_HERDR_REF.`
|
|
14242
|
-
);
|
|
14243
|
-
ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand plugin (${source} @ ${ref})`);
|
|
14244
|
-
}
|
|
14245
|
-
const dirResult = must(await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID2]), "herdr plugin config-dir", "The plugin may not have registered; run `herdr plugin list`.");
|
|
14246
|
-
const configDir = dirResult.stdout.trim();
|
|
14247
|
-
if (!configDir) throw new CliError("Herdr did not report a plugin config directory.", "Run `herdr plugin config-dir peerband` to investigate.");
|
|
14248
|
-
await mkdir4(configDir, { recursive: true });
|
|
14249
|
-
await writeFile4(join5(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
|
|
14250
|
-
`, { mode: 384 });
|
|
14251
|
-
ctx.out.print(`${s.green(symbols.ok)} Saved plugin settings ${s.dim(`(node ${process.execPath})`)}`);
|
|
14252
|
-
const after = await pluginInstalled(ctx);
|
|
14253
|
-
if (!after.installed) throw new CliError("Herdr does not list the PeerBand plugin after installing it.", "Run `herdr plugin list` and check the output above for errors.");
|
|
14254
|
-
const loggedIn = await loadCredentials(credentialsFile(ctx)).then(() => true, () => false);
|
|
14255
|
-
ctx.out.print(`${s.dim("Next:")} ${loggedIn ? "peerband relay" : "peerband login, then peerband relay"}`);
|
|
14256
|
-
return 0;
|
|
14257
|
-
}
|
|
15554
|
+
run: (parsed, ctx) => installPlugin(ctx, { afterUpdate: flag(parsed, "after-update") })
|
|
14258
15555
|
};
|
|
14259
15556
|
var uninstallSpec = {
|
|
14260
15557
|
name: "herdr uninstall",
|
|
14261
15558
|
summary: "Remove the PeerBand plugin from Herdr",
|
|
14262
15559
|
usage: "peerband herdr uninstall",
|
|
14263
|
-
description: "Stops the PeerBand Relay
|
|
15560
|
+
description: "Stops the PeerBand Relay, closes its tabs, removes the plugin (uninstalls it, or unlinks a local checkout) and the plugin settings file written by install, and deletes the relay's local state (relay-state.json, relay-tab.json and locks left by processes that are no longer running). Your login is kept. Safe to run more than once.",
|
|
14264
15561
|
options: [],
|
|
14265
15562
|
examples: [["peerband herdr uninstall", "Remove the plugin"]],
|
|
14266
15563
|
async run(_parsed, ctx) {
|
|
14267
15564
|
const s = ctx.out.stdout;
|
|
14268
15565
|
const state = await pluginInstalled(ctx);
|
|
14269
|
-
|
|
14270
|
-
if (!state.
|
|
14271
|
-
ctx
|
|
14272
|
-
|
|
15566
|
+
await releasePlugin(ctx);
|
|
15567
|
+
if (!state.found) {
|
|
15568
|
+
reportCleanup(ctx, await cleanRelayState(ctx, { remove: true }));
|
|
15569
|
+
throw new CliError(NOT_FOUND_MESSAGE, NOT_FOUND_HINT);
|
|
15570
|
+
}
|
|
15571
|
+
if (state.installed) {
|
|
15572
|
+
const dirResult = await herdr(ctx, ["plugin", "config-dir", PLUGIN_ID2]);
|
|
15573
|
+
const configDir = dirResult.code === 0 ? dirResult.stdout.trim() : "";
|
|
15574
|
+
const removed = await removePlugin(ctx);
|
|
15575
|
+
if (!removed.removed) throw new CliError(`Could not remove the PeerBand plugin: ${removed.detail}`, "Close every PeerBand Relay tab, then run `herdr plugin list` to see its state.");
|
|
15576
|
+
if (configDir) await rm6(join9(configDir, "settings.json"), { force: true }).catch(() => void 0);
|
|
15577
|
+
ctx.out.print(`${s.green(symbols.ok)} Removed the PeerBand plugin from Herdr.`);
|
|
15578
|
+
} else {
|
|
15579
|
+
ctx.out.print("The PeerBand plugin is not installed in Herdr; nothing to remove.");
|
|
14273
15580
|
}
|
|
14274
|
-
|
|
14275
|
-
|
|
14276
|
-
|
|
14277
|
-
const removed = await removePlugin(ctx);
|
|
14278
|
-
if (!removed.removed) throw new CliError(`Could not remove the PeerBand plugin: ${removed.detail}`, "Run `herdr plugin list` to see its state.");
|
|
14279
|
-
if (configDir) await rm3(join5(configDir, "settings.json"), { force: true }).catch(() => void 0);
|
|
14280
|
-
ctx.out.print(`${s.green(symbols.ok)} Removed the PeerBand plugin from Herdr.`);
|
|
15581
|
+
const report2 = await cleanRelayState(ctx, { remove: true });
|
|
15582
|
+
reportCleanup(ctx, report2);
|
|
15583
|
+
if (report2.removedState && state.installed) ctx.out.print(s.dim("Deleted the local relay state. Your login is kept (`peerband logout` removes it)."));
|
|
14281
15584
|
return 0;
|
|
14282
15585
|
}
|
|
14283
15586
|
};
|
|
@@ -14290,10 +15593,10 @@ var groupSpec = {
|
|
|
14290
15593
|
};
|
|
14291
15594
|
|
|
14292
15595
|
// src/cli/commands/login.ts
|
|
14293
|
-
import { hostname } from "node:os";
|
|
15596
|
+
import { hostname as hostname3 } from "node:os";
|
|
14294
15597
|
|
|
14295
15598
|
// src/cli/browser.ts
|
|
14296
|
-
import { spawn } from "node:child_process";
|
|
15599
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
14297
15600
|
function browserDecision(url, context) {
|
|
14298
15601
|
if (context.noBrowser) return { open: false, reason: "flag" };
|
|
14299
15602
|
if (context.env.SSH_CONNECTION || context.env.SSH_TTY || context.env.SSH_CLIENT) return { open: false, reason: "ssh" };
|
|
@@ -14315,7 +15618,7 @@ function openBrowser(url, platform = process.platform) {
|
|
|
14315
15618
|
const { command, args } = openerCommand(platform, url);
|
|
14316
15619
|
return new Promise((resolve5) => {
|
|
14317
15620
|
try {
|
|
14318
|
-
const child =
|
|
15621
|
+
const child = spawn2(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
|
|
14319
15622
|
child.once("error", () => resolve5(false));
|
|
14320
15623
|
child.once("spawn", () => {
|
|
14321
15624
|
child.unref();
|
|
@@ -14362,20 +15665,22 @@ function askYesNo(stdin, stderr, prompt, defaultYes = true) {
|
|
|
14362
15665
|
|
|
14363
15666
|
// src/cli/commands/herdr-setup.ts
|
|
14364
15667
|
var HERDR_PLUGIN_MODES = ["ask", "install", "skip"];
|
|
14365
|
-
async function herdrSetup(ctx, mode) {
|
|
15668
|
+
async function herdrSetup(ctx, mode, options = {}) {
|
|
14366
15669
|
const s = ctx.out.stdout;
|
|
14367
|
-
const
|
|
15670
|
+
const relayNext = options.relayNext ?? true;
|
|
15671
|
+
const then = relayNext ? ` ${s.dim("then")} peerband relay` : "";
|
|
15672
|
+
const manual = `${s.dim("Next:")} peerband herdr install${then}`;
|
|
14368
15673
|
const state = await checkHerdrPlugin(ctx);
|
|
14369
15674
|
if (!state.found) {
|
|
14370
15675
|
ctx.out.print("");
|
|
14371
15676
|
ctx.out.print(`${s.yellow(symbols.warn)} Herdr was not found. The PeerBand Relay tab needs Herdr 0.9.3 or newer.`);
|
|
14372
15677
|
ctx.out.print(" 1. Install Herdr: https://herdr.dev");
|
|
14373
|
-
ctx.out.print(` 2. ${s.bold("peerband herdr install")} ${s.dim("then")} ${s.bold("peerband relay")}`);
|
|
14374
|
-
return;
|
|
15678
|
+
ctx.out.print(` 2. ${s.bold("peerband herdr install")} ${s.dim("then")} ${s.bold(relayNext ? "peerband relay" : "peerband setup")}`);
|
|
15679
|
+
return "no-herdr";
|
|
14375
15680
|
}
|
|
14376
15681
|
if (state.installed && state.problems.length === 0) {
|
|
14377
|
-
ctx.out.print(`${s.dim("Next:")} peerband relay ${s.dim("(opens the PeerBand Relay tab in Herdr)")}`);
|
|
14378
|
-
return;
|
|
15682
|
+
if (relayNext) ctx.out.print(`${s.dim("Next:")} peerband relay ${s.dim("(opens the PeerBand Relay tab in Herdr)")}`);
|
|
15683
|
+
return "ready";
|
|
14379
15684
|
}
|
|
14380
15685
|
const repair = state.installed;
|
|
14381
15686
|
if (repair) {
|
|
@@ -14390,31 +15695,33 @@ async function herdrSetup(ctx, mode) {
|
|
|
14390
15695
|
} catch (error) {
|
|
14391
15696
|
if (!(error instanceof PromptAborted)) throw error;
|
|
14392
15697
|
ctx.out.print(manual);
|
|
14393
|
-
return;
|
|
15698
|
+
return "not-ready";
|
|
14394
15699
|
}
|
|
14395
15700
|
if (!install) {
|
|
14396
15701
|
ctx.out.print(s.dim(`Skipped. ${repair ? "Repair" : "Add"} it later with \`${REPAIR_COMMAND}\`, then open the relay with \`peerband relay\`.`));
|
|
14397
|
-
return;
|
|
15702
|
+
return "not-ready";
|
|
14398
15703
|
}
|
|
14399
15704
|
}
|
|
14400
15705
|
if (!install) {
|
|
14401
15706
|
ctx.out.print(manual);
|
|
14402
|
-
return;
|
|
15707
|
+
return "not-ready";
|
|
14403
15708
|
}
|
|
14404
15709
|
try {
|
|
14405
|
-
await
|
|
15710
|
+
await installPlugin(ctx, { relayNext });
|
|
14406
15711
|
} catch (error) {
|
|
14407
15712
|
const message = error.message;
|
|
14408
15713
|
ctx.out.warn(`${s.yellow(symbols.warn)} Could not ${repair ? "repair" : "add"} the PeerBand plugin${repair ? "" : " to Herdr"}: ${message}`);
|
|
14409
15714
|
if (error instanceof CliError && error.hint) ctx.out.warn(` ${error.hint}`);
|
|
14410
15715
|
ctx.out.print(s.dim(`You are logged in. ${repair ? "Repair" : "Add"} the plugin later with \`peerband herdr install\`, then run \`peerband relay\`.`));
|
|
15716
|
+
return "not-ready";
|
|
14411
15717
|
}
|
|
15718
|
+
return "ready";
|
|
14412
15719
|
}
|
|
14413
15720
|
async function ensureHerdrPlugin(ctx) {
|
|
14414
15721
|
const check = await checkHerdrPlugin(ctx);
|
|
14415
15722
|
if (!check.found || check.problems.length === 0) return;
|
|
14416
15723
|
const s = ctx.out.stderr;
|
|
14417
|
-
const fix =
|
|
15724
|
+
const fix = `Run \`${fixCommand(check.problems[0])}\`, then \`peerband relay\`.`;
|
|
14418
15725
|
const reasons = check.problems.map((problem) => problem.message);
|
|
14419
15726
|
if (!(ctx.stdin.isTTY && ctx.stderr.isTTY)) throw new CliError(`The PeerBand Herdr plugin needs repair. ${reasons.join(" ")}`, fix);
|
|
14420
15727
|
ctx.out.warn(`${s.yellow(symbols.warn)} The PeerBand plugin in Herdr needs repair: ${reasons[0]}`);
|
|
@@ -14431,6 +15738,14 @@ async function ensureHerdrPlugin(ctx) {
|
|
|
14431
15738
|
}
|
|
14432
15739
|
|
|
14433
15740
|
// src/cli/commands/login.ts
|
|
15741
|
+
function reusableCredential(previous, serverUrl) {
|
|
15742
|
+
if (!previous) return void 0;
|
|
15743
|
+
try {
|
|
15744
|
+
return new URL(previous.serverUrl).origin === new URL(serverUrl).origin ? previous.credential : void 0;
|
|
15745
|
+
} catch {
|
|
15746
|
+
return void 0;
|
|
15747
|
+
}
|
|
15748
|
+
}
|
|
14434
15749
|
async function persist(ctx, redeemed) {
|
|
14435
15750
|
const credentials = { ...redeemed, enrolledAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
14436
15751
|
await saveCredentials(credentials, credentialsFile(ctx));
|
|
@@ -14439,7 +15754,7 @@ async function persist(ctx, redeemed) {
|
|
|
14439
15754
|
async function loginWithGrant(ctx, options) {
|
|
14440
15755
|
let redeemed;
|
|
14441
15756
|
try {
|
|
14442
|
-
redeemed = await redeemEnrollment(options.serverUrl, options.grant, options.name, ctx.fetch);
|
|
15757
|
+
redeemed = await redeemEnrollment(options.serverUrl, options.grant, options.name, ctx.fetch, options.previousCredential);
|
|
14443
15758
|
} catch (error) {
|
|
14444
15759
|
const message = error.message;
|
|
14445
15760
|
const rejected = /could not be redeemed/i.test(message);
|
|
@@ -14511,7 +15826,7 @@ async function loginWithBrowser(ctx, options) {
|
|
|
14511
15826
|
}
|
|
14512
15827
|
let redeemed;
|
|
14513
15828
|
try {
|
|
14514
|
-
redeemed = await pollDeviceToken(options.serverUrl, code, shared);
|
|
15829
|
+
redeemed = await pollDeviceToken(options.serverUrl, code, { ...shared, ...options.previousCredential ? { previousCredential: options.previousCredential } : {} });
|
|
14515
15830
|
} catch (error) {
|
|
14516
15831
|
throw mapFailure(error, options.serverUrl);
|
|
14517
15832
|
} finally {
|
|
@@ -14549,7 +15864,7 @@ var spec2 = {
|
|
|
14549
15864
|
name: "login",
|
|
14550
15865
|
summary: "Connect this machine to your PeerBand account",
|
|
14551
15866
|
usage: "peerband login [--name NAME] [--no-browser] [--server URL] [--herdr-plugin ask|install|skip]\n peerband login --grant GRANT [--name NAME] [--server URL]",
|
|
14552
|
-
description: "Signs this machine in through your browser. login prints a link and a short code, opens the page (unless you are on SSH, a headless machine or pass --no-browser), and waits while you confirm the code in your PeerBand account. The credential is stored in your PeerBand config directory (readable only by you). Running login again replaces the
|
|
15867
|
+
description: "Signs this machine in through your browser. login prints a link and a short code, opens the page (unless you are on SSH, a headless machine or pass --no-browser), and waits while you confirm the code in your PeerBand account. The credential is stored in your PeerBand config directory (readable only by you). Running login again replaces the stored credential; when you sign in to the same account and server, this machine keeps its record in your account (installation ID and shares).\n\nOn a headless machine or in CI, use a one-time grant instead: create it in the PeerBand dashboard and pass --grant GRANT (or set PEERBAND_GRANT).\n\nWhen login succeeds it checks for Herdr. If the PeerBand plugin is missing, or installed but wrong (another version, a local checkout, a stale config directory), it offers to add or repair it (--herdr-plugin ask, the default; it only asks on a terminal), adds it without asking (install), or just prints the command (skip).",
|
|
14553
15868
|
options: [
|
|
14554
15869
|
{ name: "no-browser", type: "boolean", description: "Do not open a browser; print the link and code only (SSH, containers)." },
|
|
14555
15870
|
{ name: "name", type: "string", valueName: "NAME", description: "Name shown for this machine in the dashboard. Default: this computer's hostname." },
|
|
@@ -14566,40 +15881,57 @@ var spec2 = {
|
|
|
14566
15881
|
],
|
|
14567
15882
|
notes: ["The code you confirm in the browser must match the one shown here. The secret device code and any grant are never printed or stored. Plain HTTP is only accepted for localhost."],
|
|
14568
15883
|
async run(parsed, ctx) {
|
|
14569
|
-
const
|
|
14570
|
-
|
|
14571
|
-
const herdrMode = rawMode;
|
|
14572
|
-
const serverUrl = resolveServerUrl(str(parsed, "server"), ctx.env);
|
|
14573
|
-
const name = str(parsed, "name")?.trim() || hostname();
|
|
14574
|
-
const grant = (str(parsed, "grant") ?? ctx.env.PEERBAND_GRANT)?.trim();
|
|
14575
|
-
delete ctx.env.PEERBAND_GRANT;
|
|
14576
|
-
if (parsed.values.grant !== void 0 && !grant) throw new UsageError("The grant is empty.", "Pass the grant from your PeerBand dashboard: --grant GRANT.");
|
|
14577
|
-
const previous = await loadCredentials(credentialsFile(ctx)).catch(() => void 0);
|
|
14578
|
-
const credentials = grant ? await loginWithGrant(ctx, { serverUrl, grant, name }) : await loginWithBrowser(ctx, { serverUrl, name, noBrowser: parsed.values["no-browser"] === true });
|
|
14579
|
-
const s = ctx.out.stdout;
|
|
14580
|
-
if (previous) ctx.out.print(s.dim(`Replaced the previous login (${previous.machineName ?? previous.installationId} on ${previous.serverUrl}).`));
|
|
14581
|
-
const who = credentials.accountEmail ? ` (${credentials.accountEmail})` : "";
|
|
14582
|
-
ctx.out.print(`${s.green(symbols.ok)} Logged in as ${s.bold(credentials.machineName ?? name)}${who}`);
|
|
15884
|
+
const herdrMode = herdrPluginMode(parsed);
|
|
15885
|
+
await signIn(parsed, ctx);
|
|
14583
15886
|
await herdrSetup(ctx, herdrMode);
|
|
14584
15887
|
ctx.out.print("");
|
|
14585
15888
|
printSkillTip(ctx);
|
|
14586
15889
|
return 0;
|
|
14587
15890
|
}
|
|
14588
15891
|
};
|
|
15892
|
+
function herdrPluginMode(parsed) {
|
|
15893
|
+
const rawMode = str(parsed, "herdr-plugin")?.trim().toLowerCase() ?? "ask";
|
|
15894
|
+
if (!HERDR_PLUGIN_MODES.includes(rawMode)) throw new UsageError(`Invalid --herdr-plugin value "${rawMode}".`, "Use --herdr-plugin ask, install or skip.");
|
|
15895
|
+
return rawMode;
|
|
15896
|
+
}
|
|
15897
|
+
async function signIn(parsed, ctx) {
|
|
15898
|
+
const serverUrl = resolveServerUrl(str(parsed, "server"), ctx.env);
|
|
15899
|
+
const name = str(parsed, "name")?.trim() || hostname3();
|
|
15900
|
+
const grant = (str(parsed, "grant") ?? ctx.env.PEERBAND_GRANT)?.trim();
|
|
15901
|
+
delete ctx.env.PEERBAND_GRANT;
|
|
15902
|
+
if (parsed.values.grant !== void 0 && !grant) throw new UsageError("The grant is empty.", "Pass the grant from your PeerBand dashboard: --grant GRANT.");
|
|
15903
|
+
const previous = await loadCredentials(credentialsFile(ctx)).catch(() => void 0);
|
|
15904
|
+
const previousCredential = reusableCredential(previous, serverUrl);
|
|
15905
|
+
const credentials = grant ? await loginWithGrant(ctx, { serverUrl, grant, name, ...previousCredential ? { previousCredential } : {} }) : await loginWithBrowser(ctx, { serverUrl, name, noBrowser: parsed.values["no-browser"] === true, ...previousCredential ? { previousCredential } : {} });
|
|
15906
|
+
const s = ctx.out.stdout;
|
|
15907
|
+
if (previous && previous.installationId === credentials.installationId && previous.serverUrl === credentials.serverUrl)
|
|
15908
|
+
ctx.out.print(s.dim("Kept this machine in your account with a new credential; its shares stay in place."));
|
|
15909
|
+
else if (previous) ctx.out.print(s.dim(`Replaced the previous login (${previous.machineName ?? previous.installationId} on ${previous.serverUrl}).`));
|
|
15910
|
+
const who = credentials.accountEmail ? ` (${credentials.accountEmail})` : "";
|
|
15911
|
+
ctx.out.print(`${s.green(symbols.ok)} Logged in as ${s.bold(credentials.machineName ?? name)}${who}`);
|
|
15912
|
+
return credentials;
|
|
15913
|
+
}
|
|
14589
15914
|
|
|
14590
15915
|
// src/cli/commands/logout.ts
|
|
14591
15916
|
var spec3 = {
|
|
14592
15917
|
name: "logout",
|
|
14593
15918
|
summary: "Forget this machine's PeerBand credential",
|
|
14594
15919
|
usage: "peerband logout",
|
|
14595
|
-
description: "Deletes the stored credential from this machine
|
|
15920
|
+
description: "Deletes the stored credential from this machine, stops a running PeerBand Relay, closes its Herdr tabs and deletes the local relay state (relay-state.json, relay-tab.json and locks left by processes that are no longer running). Safe to run more than once. It does not revoke the machine on the server: remove it from your PeerBand dashboard to revoke access for good.",
|
|
14596
15921
|
options: [],
|
|
14597
15922
|
examples: [["peerband logout", "Remove the local credential"]],
|
|
14598
15923
|
async run(_parsed, ctx) {
|
|
14599
15924
|
const s = ctx.out.stdout;
|
|
14600
15925
|
const previous = await loadCredentials(credentialsFile(ctx)).catch(() => void 0);
|
|
14601
|
-
const
|
|
15926
|
+
const panes = await findRelayPanes(ctx);
|
|
15927
|
+
const stopped = await stopRelayAndWait(ctx);
|
|
14602
15928
|
if (stopped) ctx.out.print(`${s.green(symbols.ok)} Stopped the running PeerBand Relay.`);
|
|
15929
|
+
if (panes.length) {
|
|
15930
|
+
const closed = await closeRelayPanes(ctx, panes);
|
|
15931
|
+
if (closed) ctx.out.print(`${s.green(symbols.ok)} Closed ${closed === 1 ? "the PeerBand Relay tab" : `${closed} PeerBand Relay tabs`}.`);
|
|
15932
|
+
}
|
|
15933
|
+
const cleanup = await cleanRelayState(ctx, { remove: true });
|
|
15934
|
+
for (const held of cleanup.held) ctx.out.warn(`${ctx.out.stderr.yellow(symbols.warn)} ${held.lock} is still held: ${held.reason}.`);
|
|
14603
15935
|
const removed = await deleteCredentials(credentialsFile(ctx));
|
|
14604
15936
|
if (!removed) {
|
|
14605
15937
|
ctx.out.print("Already logged out; there is no credential on this machine.");
|
|
@@ -14612,8 +15944,68 @@ var spec3 = {
|
|
|
14612
15944
|
}
|
|
14613
15945
|
};
|
|
14614
15946
|
|
|
14615
|
-
// src/cli/commands/
|
|
15947
|
+
// src/cli/commands/notify.ts
|
|
15948
|
+
var PANE_ID2 = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
15949
|
+
var START_RELAY = "Start the relay with `peerband relay`.";
|
|
15950
|
+
function callingPane(env) {
|
|
15951
|
+
const pane = env.HERDR_PANE_ID;
|
|
15952
|
+
return typeof pane === "string" && PANE_ID2.test(pane) ? pane : void 0;
|
|
15953
|
+
}
|
|
15954
|
+
async function notify(text2, json, ctx) {
|
|
15955
|
+
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
|
+
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.");
|
|
15957
|
+
const paneId = callingPane(ctx.env);
|
|
15958
|
+
let reply;
|
|
15959
|
+
try {
|
|
15960
|
+
reply = await requestNotify({ text: text2, ...paneId ? { paneId } : {} }, ctx.env);
|
|
15961
|
+
} catch (error) {
|
|
15962
|
+
if (error instanceof ControlUnavailable && error.reason === "closed") {
|
|
15963
|
+
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.");
|
|
15964
|
+
}
|
|
15965
|
+
if (error instanceof ControlUnavailable && error.reason === "timeout") throw new CliError("The relay did not answer in time; the note may not have been sent.", "Check `peerband status`.");
|
|
15966
|
+
throw new CliError("No PeerBand relay is running on this machine.", START_RELAY);
|
|
15967
|
+
}
|
|
15968
|
+
if (typeof reply.error === "string") {
|
|
15969
|
+
const message = typeof reply.message === "string" ? sanitize(reply.message) : "The note could not be sent.";
|
|
15970
|
+
const next = typeof reply.nextStep === "string" ? sanitize(reply.nextStep) : void 0;
|
|
15971
|
+
if (reply.error === "not-running") throw new CliError(`${message} The note was not sent.`, START_RELAY);
|
|
15972
|
+
if (reply.error === "invalid" || reply.error === "invalid_argument") throw new UsageError(message, next);
|
|
15973
|
+
throw new CliError(message, next ?? "Check `peerband status` and try again.");
|
|
15974
|
+
}
|
|
15975
|
+
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
|
+
const agentId = typeof reply.agentId === "string" ? reply.agentId : null;
|
|
15977
|
+
if (json) {
|
|
15978
|
+
ctx.out.print(JSON.stringify({ sent: true, agentId, eventId: typeof reply.eventId === "string" ? reply.eventId : null }, null, 2));
|
|
15979
|
+
return 0;
|
|
15980
|
+
}
|
|
15981
|
+
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)})`) : ""}.`);
|
|
15983
|
+
return 0;
|
|
15984
|
+
}
|
|
14616
15985
|
var spec4 = {
|
|
15986
|
+
name: "notify",
|
|
15987
|
+
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}." }],
|
|
15991
|
+
positionals: { name: "text", max: 64 },
|
|
15992
|
+
examples: [
|
|
15993
|
+
['peerband notify "Migration finished, 3 tests failing"', "Report a result when a long task ends"],
|
|
15994
|
+
['peerband notify "Blocked: should I drop the legacy table?"', "Ask the owner for a decision"],
|
|
15995
|
+
['peerband notify --json "Build green"', "For scripts: prints the event id"]
|
|
15996
|
+
],
|
|
15997
|
+
notes: [
|
|
15998
|
+
"Needs the relay (`peerband relay`) to be running and connected; nothing is queued while it is offline.",
|
|
15999
|
+
"Several words without quotes are joined with spaces."
|
|
16000
|
+
],
|
|
16001
|
+
async run(parsed, ctx) {
|
|
16002
|
+
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);
|
|
16004
|
+
}
|
|
16005
|
+
};
|
|
16006
|
+
|
|
16007
|
+
// src/cli/commands/relay.ts
|
|
16008
|
+
var spec5 = {
|
|
14617
16009
|
name: "relay",
|
|
14618
16010
|
summary: "Open or focus the PeerBand Relay tab in Herdr",
|
|
14619
16011
|
usage: "peerband relay",
|
|
@@ -14623,22 +16015,293 @@ var spec4 = {
|
|
|
14623
16015
|
async run(_parsed, ctx) {
|
|
14624
16016
|
const credentials = await requireCredentials(ctx);
|
|
14625
16017
|
await ensureHerdrPlugin(ctx);
|
|
16018
|
+
await openRelay(ctx);
|
|
16019
|
+
const s = ctx.out.stdout;
|
|
16020
|
+
ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is open in Herdr.`);
|
|
16021
|
+
printMcpHint(ctx, credentials.serverUrl);
|
|
16022
|
+
printSkillTip(ctx);
|
|
16023
|
+
return 0;
|
|
16024
|
+
}
|
|
16025
|
+
};
|
|
16026
|
+
async function openRelay(ctx) {
|
|
16027
|
+
try {
|
|
16028
|
+
await (ctx.openRelayTab ?? openRelayTab2)();
|
|
16029
|
+
} catch (error) {
|
|
16030
|
+
const message = sanitize(error.message || "Could not open the PeerBand Relay tab.");
|
|
16031
|
+
let hint = "Make sure Herdr is running, then try `peerband relay` again.";
|
|
16032
|
+
if (/was not found/i.test(message)) hint = NOT_FOUND_HINT;
|
|
16033
|
+
else if (/not installed/i.test(message)) hint = "Run `peerband herdr install`, then `peerband relay`.";
|
|
16034
|
+
else if (/already in progress/i.test(message)) hint = "Wait a moment and run `peerband relay` again.";
|
|
16035
|
+
throw new CliError(message, hint);
|
|
16036
|
+
}
|
|
16037
|
+
}
|
|
16038
|
+
|
|
16039
|
+
// src/cli/commands/skill.ts
|
|
16040
|
+
var SKILL_MODES = ["ask", "install", "skip"];
|
|
16041
|
+
function report(ctx, installed) {
|
|
16042
|
+
const s = ctx.out.stdout;
|
|
16043
|
+
const where = installed.method === "skills" && installed.agents.length > 0 ? `for ${installed.agents.slice(0, 6).join(", ")}${installed.agents.length > 6 ? ` and ${installed.agents.length - 6} more` : ""}` : `in ${installed.agents.join(", ")}`;
|
|
16044
|
+
ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand skill ${where}.`);
|
|
16045
|
+
ctx.out.print(s.dim(` ${installed.path}`));
|
|
16046
|
+
}
|
|
16047
|
+
function keptEdits(ctx, file) {
|
|
16048
|
+
const s = ctx.out.stdout;
|
|
16049
|
+
ctx.out.print(`${s.green(symbols.ok)} Kept your own version of the PeerBand skill ${s.dim(`(${file})`)}.`);
|
|
16050
|
+
ctx.out.print(s.dim(" To replace it with the version shipped with this CLI: peerband skill --force"));
|
|
16051
|
+
}
|
|
16052
|
+
async function skillSetup(ctx, mode) {
|
|
16053
|
+
const s = ctx.out.stdout;
|
|
16054
|
+
if (mode === "skip") {
|
|
16055
|
+
ctx.out.print(s.dim(`Skipped the agent skill. Add it later with \`${SKILL_COMMAND}\`.`));
|
|
16056
|
+
return;
|
|
16057
|
+
}
|
|
16058
|
+
if (skillEdited(ctx)) {
|
|
16059
|
+
keptEdits(ctx, installedSkillFile(ctx));
|
|
16060
|
+
return;
|
|
16061
|
+
}
|
|
16062
|
+
let install = mode === "install";
|
|
16063
|
+
if (mode === "ask") {
|
|
16064
|
+
if (!(ctx.stdin.isTTY && ctx.stderr.isTTY)) {
|
|
16065
|
+
ctx.out.print(`${s.dim("Next:")} ${SKILL_COMMAND} ${s.dim("(teaches your coding agents how to handle PeerBand messages)")}`);
|
|
16066
|
+
return;
|
|
16067
|
+
}
|
|
16068
|
+
ctx.out.print("");
|
|
16069
|
+
ctx.out.print("The PeerBand skill tells your coding agents (Claude Code, Codex, Cursor, ...) how to handle messages that");
|
|
16070
|
+
ctx.out.print("arrive through PeerBand, including strict privacy rules for people you share this machine with.");
|
|
16071
|
+
const question = skillInstalled(ctx) ? "Update the PeerBand skill for your agents? [Y/n] " : "Install the PeerBand skill for your agents? [Y/n] ";
|
|
16072
|
+
try {
|
|
16073
|
+
install = await askYesNo(ctx.stdin, ctx.stderr, question);
|
|
16074
|
+
} catch (error) {
|
|
16075
|
+
if (!(error instanceof PromptAborted)) throw error;
|
|
16076
|
+
install = false;
|
|
16077
|
+
}
|
|
16078
|
+
if (!install) {
|
|
16079
|
+
ctx.out.print(`${s.yellow(symbols.warn)} Skipped. Without the skill, your agents get no guidance for messages from people you share with. Add it later with \`${SKILL_COMMAND}\`.`);
|
|
16080
|
+
return;
|
|
16081
|
+
}
|
|
16082
|
+
}
|
|
16083
|
+
ctx.out.print(s.dim("Installing the PeerBand skill\u2026"));
|
|
16084
|
+
try {
|
|
16085
|
+
report(ctx, await installSkill(ctx, { log: (line) => ctx.out.print(s.dim(line)) }));
|
|
16086
|
+
} catch (error) {
|
|
16087
|
+
if (error instanceof SkillEditedError) return keptEdits(ctx, error.file);
|
|
16088
|
+
ctx.out.warn(`${s.yellow(symbols.warn)} Could not install the PeerBand skill: ${error.message}`);
|
|
16089
|
+
ctx.out.print(s.dim(`Add it later with \`${SKILL_COMMAND}\`.`));
|
|
16090
|
+
}
|
|
16091
|
+
}
|
|
16092
|
+
var spec6 = {
|
|
16093
|
+
name: "skill",
|
|
16094
|
+
summary: "Install or update the PeerBand skill for your coding agents",
|
|
16095
|
+
usage: "peerband skill [--copy] [--force]",
|
|
16096
|
+
description: "Installs the PeerBand agent skill that ships with this CLI for every coding agent on this machine. It uses the skills CLI (npx skills add), which keeps one copy in ~/.agents/skills/peerband and links it into each agent it finds (Claude Code, Codex, Cursor, Gemini CLI, OpenCode and others). If that fails, or with --copy, it copies the skill into ~/.agents/skills and ~/.claude/skills instead.\n\nThe skill tells agents how to use the PeerBand MCP tools and how to handle messages relayed through PeerBand: requests from you are handled normally; requests from people you shared this machine with follow strict privacy rules.\n\nTo change those rules, edit SKILL.md in ~/.agents/skills/peerband. Once you have edited it, `peerband skill` and `peerband update` keep your version; --force replaces it with the shipped one. Running it again otherwise updates the skill to the version of this CLI.",
|
|
16097
|
+
options: [
|
|
16098
|
+
{ name: "copy", type: "boolean", description: "Copy the files instead of running the skills CLI (offline, or when npx is blocked)." },
|
|
16099
|
+
{ name: "force", type: "boolean", description: "Replace the skill even if you edited it." },
|
|
16100
|
+
{ name: "if-installed", type: "boolean", description: "Only update an existing, unedited installation (used by peerband update).", hidden: true }
|
|
16101
|
+
],
|
|
16102
|
+
examples: [
|
|
16103
|
+
["peerband skill", "Install the skill for every coding agent found"],
|
|
16104
|
+
["peerband skill --copy", "Copy it into ~/.agents and ~/.claude without npx"],
|
|
16105
|
+
["peerband skill --force", "Go back to the shipped skill, dropping your edits"]
|
|
16106
|
+
],
|
|
16107
|
+
async run(parsed, ctx) {
|
|
16108
|
+
const onlyUpdate = flag(parsed, "if-installed");
|
|
16109
|
+
if (onlyUpdate && !skillInstalled(ctx)) return 0;
|
|
14626
16110
|
try {
|
|
14627
|
-
await (ctx
|
|
16111
|
+
report(ctx, await installSkill(ctx, { copy: flag(parsed, "copy"), force: flag(parsed, "force"), log: (line) => ctx.out.print(ctx.out.stdout.dim(line)) }));
|
|
14628
16112
|
} catch (error) {
|
|
14629
|
-
|
|
14630
|
-
|
|
14631
|
-
|
|
14632
|
-
|
|
14633
|
-
|
|
14634
|
-
throw new CliError(message, hint);
|
|
16113
|
+
if (error instanceof SkillEditedError) {
|
|
16114
|
+
keptEdits(ctx, error.file);
|
|
16115
|
+
return 0;
|
|
16116
|
+
}
|
|
16117
|
+
throw new CliError(`Could not install the PeerBand skill: ${error.message}`, "Try `peerband skill --copy`, or install it from GitHub: `npx skills add kshvidler/peerband-cli`.");
|
|
14635
16118
|
}
|
|
16119
|
+
return 0;
|
|
16120
|
+
}
|
|
16121
|
+
};
|
|
16122
|
+
|
|
16123
|
+
// src/cli/commands/setup.ts
|
|
16124
|
+
function skillMode(parsed) {
|
|
16125
|
+
const raw = str(parsed, "skill")?.trim().toLowerCase() ?? "ask";
|
|
16126
|
+
if (!SKILL_MODES.includes(raw)) throw new UsageError(`Invalid --skill value "${raw}".`, "Use --skill ask, install or skip.");
|
|
16127
|
+
return raw;
|
|
16128
|
+
}
|
|
16129
|
+
async function existingLogin(parsed, ctx) {
|
|
16130
|
+
if (str(parsed, "grant") !== void 0 || ctx.env.PEERBAND_GRANT) return void 0;
|
|
16131
|
+
const previous = await loadCredentials(credentialsFile(ctx)).catch(() => void 0);
|
|
16132
|
+
if (!previous) return void 0;
|
|
16133
|
+
try {
|
|
16134
|
+
return new URL(previous.serverUrl).origin === new URL(resolveServerUrl(str(parsed, "server"), ctx.env)).origin ? previous : void 0;
|
|
16135
|
+
} catch {
|
|
16136
|
+
return void 0;
|
|
16137
|
+
}
|
|
16138
|
+
}
|
|
16139
|
+
var loginOptions = spec2.options.filter((option) => option.name !== "herdr-plugin");
|
|
16140
|
+
var spec7 = {
|
|
16141
|
+
name: "setup",
|
|
16142
|
+
summary: "Set up this machine: log in, add the Herdr plugin and the agent skill, open the relay",
|
|
16143
|
+
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 [...]",
|
|
16144
|
+
description: "Does everything a new machine needs, in one go, and is safe to run again:\n 1. Logs in through your browser (skipped when this machine is already logged in to the same server).\n 2. Adds or repairs the PeerBand plugin in Herdr.\n 3. Installs the PeerBand skill for your coding agents (see `peerband skill`). It tells them how to handle messages that arrive through PeerBand, with strict privacy rules for people you share this machine with.\n 4. Opens the PeerBand Relay tab in Herdr, which connects the machine.\n\nOn a terminal each optional step asks first, with Yes as the default. Without a terminal, ask means skip and setup prints the command for that step.",
|
|
16145
|
+
options: [
|
|
16146
|
+
...loginOptions,
|
|
16147
|
+
{ name: "herdr-plugin", type: "string", valueName: "ask|install|skip", description: "Add the PeerBand plugin to Herdr: ask (default; prompts on a terminal), install, or skip." },
|
|
16148
|
+
{ name: "skill", type: "string", valueName: "ask|install|skip", description: "Install the PeerBand skill for your coding agents: ask (default; prompts on a terminal), install, or skip." },
|
|
16149
|
+
{ name: "no-relay", type: "boolean", description: "Do not open the Relay tab at the end." }
|
|
16150
|
+
],
|
|
16151
|
+
examples: [
|
|
16152
|
+
["peerband setup", "Log in, add the plugin and the skill, open the relay"],
|
|
16153
|
+
["peerband setup --herdr-plugin install --skill install", "The same without questions (used by the install scripts)"],
|
|
16154
|
+
["PEERBAND_GRANT=... peerband setup --name work-laptop --no-relay", "Headless: log in with a dashboard grant"]
|
|
16155
|
+
],
|
|
16156
|
+
async run(parsed, ctx) {
|
|
16157
|
+
const herdrMode = herdrPluginMode(parsed);
|
|
16158
|
+
const skill = skillMode(parsed);
|
|
14636
16159
|
const s = ctx.out.stdout;
|
|
14637
|
-
|
|
16160
|
+
const step = (n, title) => {
|
|
16161
|
+
ctx.out.print("");
|
|
16162
|
+
ctx.out.print(s.bold(`${n}/4 ${title}`));
|
|
16163
|
+
};
|
|
16164
|
+
step(1, "Log in");
|
|
16165
|
+
let credentials = await existingLogin(parsed, ctx);
|
|
16166
|
+
if (credentials) {
|
|
16167
|
+
const who = credentials.accountEmail ? ` (${credentials.accountEmail})` : "";
|
|
16168
|
+
ctx.out.print(`${s.green(symbols.ok)} Already logged in as ${s.bold(credentials.machineName ?? credentials.installationId)}${who} ${s.dim("(`peerband login` signs in again)")}`);
|
|
16169
|
+
} else {
|
|
16170
|
+
credentials = await signIn(parsed, ctx);
|
|
16171
|
+
}
|
|
16172
|
+
step(2, "Herdr plugin");
|
|
16173
|
+
const herdr2 = await herdrSetup(ctx, herdrMode, { relayNext: false });
|
|
16174
|
+
step(3, "Agent skill");
|
|
16175
|
+
await skillSetup(ctx, skill);
|
|
16176
|
+
step(4, "Relay");
|
|
16177
|
+
let relayOpen = false;
|
|
16178
|
+
if (flag(parsed, "no-relay")) {
|
|
16179
|
+
ctx.out.print(s.dim("Skipped. Open it later with `peerband relay`."));
|
|
16180
|
+
} else if (herdr2 !== "ready") {
|
|
16181
|
+
ctx.out.print(s.dim(`Not opened: ${herdr2 === "no-herdr" ? "Herdr is not installed" : "the Herdr plugin is not ready"}. When it is, run \`peerband relay\`.`));
|
|
16182
|
+
} else {
|
|
16183
|
+
try {
|
|
16184
|
+
await openRelay(ctx);
|
|
16185
|
+
relayOpen = true;
|
|
16186
|
+
ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is open in Herdr.`);
|
|
16187
|
+
} catch (error) {
|
|
16188
|
+
ctx.out.warn(`${s.yellow(symbols.warn)} Could not open the PeerBand Relay tab: ${error.message}`);
|
|
16189
|
+
if (error instanceof CliError && error.hint) ctx.out.print(s.dim(` ${error.hint}`));
|
|
16190
|
+
}
|
|
16191
|
+
}
|
|
14638
16192
|
printMcpHint(ctx, credentials.serverUrl);
|
|
14639
|
-
|
|
16193
|
+
ctx.out.print("");
|
|
16194
|
+
ctx.out.print(relayOpen ? `${s.green(symbols.ok)} PeerBand is set up.` : `${s.dim("Setup finished. Check it any time with")} peerband status`);
|
|
16195
|
+
return 0;
|
|
16196
|
+
}
|
|
16197
|
+
};
|
|
16198
|
+
|
|
16199
|
+
// src/cli/commands/share.ts
|
|
16200
|
+
var roleLabel = (role) => role === "message" ? "read + message" : "read only";
|
|
16201
|
+
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
|
+
}
|
|
16223
|
+
function expiryDays(raw) {
|
|
16224
|
+
if (raw === void 0) return void 0;
|
|
16225
|
+
const days = Number(raw);
|
|
16226
|
+
if (!Number.isInteger(days) || days < 1 || days > MAX_EXPIRY_DAYS) throw new UsageError(`Invalid --expires value "${raw}".`, `Use a whole number of days from 1 to ${MAX_EXPIRY_DAYS}.`);
|
|
16227
|
+
return days;
|
|
16228
|
+
}
|
|
16229
|
+
async function create(ctx, credentials, role, days, json) {
|
|
16230
|
+
const link = await call(ctx, credentials, "POST", "/api/installation/invites", { role, ...days ? { expires_in_days: days } : {} });
|
|
16231
|
+
if (json) {
|
|
16232
|
+
ctx.out.print(JSON.stringify(link, null, 2));
|
|
16233
|
+
return 0;
|
|
16234
|
+
}
|
|
16235
|
+
const s = ctx.out.stdout;
|
|
16236
|
+
ctx.out.print(`${s.green(symbols.ok)} Invite link for ${s.bold(credentials.machineName ?? "this machine")} (${roleLabel(link.role)}):`);
|
|
16237
|
+
ctx.out.print("");
|
|
16238
|
+
ctx.out.print(` ${s.cyan(sanitize(link.url))}`);
|
|
16239
|
+
ctx.out.print("");
|
|
16240
|
+
ctx.out.print(`Send it to one person. It works once and expires ${sanitize(link.expires_at)}.`);
|
|
16241
|
+
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
|
+
return 0;
|
|
16243
|
+
}
|
|
16244
|
+
async function list(ctx, credentials, json) {
|
|
16245
|
+
const sharing = await call(ctx, credentials, "GET", "/api/installation/sharing");
|
|
16246
|
+
if (json) {
|
|
16247
|
+
ctx.out.print(JSON.stringify(sharing, null, 2));
|
|
14640
16248
|
return 0;
|
|
14641
16249
|
}
|
|
16250
|
+
const s = ctx.out.stdout;
|
|
16251
|
+
ctx.out.print(s.bold("People with access"));
|
|
16252
|
+
if (!sharing.guests.length) ctx.out.print(s.dim(" Nobody else has access yet. Create a link with `peerband share`."));
|
|
16253
|
+
for (const guest of sharing.guests) {
|
|
16254
|
+
const used = guest.last_used_at ? `last used ${sanitize(guest.last_used_at)}` : "not used yet";
|
|
16255
|
+
ctx.out.print(` ${sanitize(guest.email ?? "PeerBand user")} ${roleLabel(guest.role)} ${s.dim(`${used} \xB7 ${guest.id}`)}`);
|
|
16256
|
+
}
|
|
16257
|
+
if (sharing.invites.length) {
|
|
16258
|
+
ctx.out.print("");
|
|
16259
|
+
ctx.out.print(s.bold("Unused links"));
|
|
16260
|
+
for (const invite of sharing.invites) ctx.out.print(` ${roleLabel(invite.role)} ${s.dim(`expires ${sanitize(invite.expires_at)} \xB7 ${invite.id}`)}`);
|
|
16261
|
+
}
|
|
16262
|
+
ctx.out.print("");
|
|
16263
|
+
ctx.out.print(s.dim("Remove access or cancel a link with `peerband share revoke ID`. Change roles in the dashboard."));
|
|
16264
|
+
return 0;
|
|
16265
|
+
}
|
|
16266
|
+
async function revoke(ctx, credentials, id) {
|
|
16267
|
+
if (!id) throw new UsageError("Missing the ID to revoke.", "Run `peerband share list` to see IDs (acc_\u2026 for people, inv_\u2026 for links).");
|
|
16268
|
+
if (!/^(acc|inv)_[\w-]{1,64}$/.test(id)) throw new UsageError(`"${sanitize(id)}" is not a share ID.`, "IDs start with acc_ (a person) or inv_ (a link); see `peerband share list`.");
|
|
16269
|
+
await call(ctx, credentials, "DELETE", `/api/installation/sharing/${encodeURIComponent(id)}`);
|
|
16270
|
+
ctx.out.print(`${ctx.out.stdout.green(symbols.ok)} ${id.startsWith("acc_") ? "Access removed." : "Link cancelled."}`);
|
|
16271
|
+
return 0;
|
|
16272
|
+
}
|
|
16273
|
+
var spec8 = {
|
|
16274
|
+
name: "share",
|
|
16275
|
+
summary: "Share this machine with another PeerBand user",
|
|
16276
|
+
usage: "peerband share [--message] [--expires DAYS] [--json]\n peerband share list [--json]\n peerband share revoke ID",
|
|
16277
|
+
description: "Creates an invitation link for this machine. The person who opens it signs in to PeerBand (or creates an account) and accepts; this machine then appears in their dashboard and in list_machines in their MCP client. Guests can list and read this machine's agents. With --message they can also send messages, if their MCP client has the agents:message consent and this machine allows messages (a machine started with --read-only never does).\n\nEach link works for one person and expires after 7 days unless you pass --expires. You see each guest's email and a log of what they read or send (metadata only) in the dashboard.\n\n`share list` shows who has access and the unused links; `share revoke ID` removes a person's access (acc_\u2026) or cancels a link (inv_\u2026).",
|
|
16278
|
+
options: [
|
|
16279
|
+
{ name: "message", type: "boolean", description: "Also let the guest send messages to agents. Default: read only." },
|
|
16280
|
+
{ name: "expires", type: "string", valueName: "DAYS", description: `Days until the link expires, 1 to ${MAX_EXPIRY_DAYS}. Default: 7.` },
|
|
16281
|
+
{ name: "json", type: "boolean", description: "Print machine-readable JSON." }
|
|
16282
|
+
],
|
|
16283
|
+
positionals: { name: "list | revoke ID", max: 2 },
|
|
16284
|
+
examples: [
|
|
16285
|
+
["peerband share", "Create a read-only invite link for this machine"],
|
|
16286
|
+
["peerband share --message --expires 1", "A link that also allows messages, valid for one day"],
|
|
16287
|
+
["peerband share list", "People with access and unused links"],
|
|
16288
|
+
["peerband share revoke acc_AbC123", "Remove someone's access"]
|
|
16289
|
+
],
|
|
16290
|
+
notes: ["The link is shown once. Anyone who has it can accept it until it is used, so send it only to the person you mean."],
|
|
16291
|
+
async run(parsed, ctx) {
|
|
16292
|
+
const [action, id] = parsed.positionals;
|
|
16293
|
+
const json = flag(parsed, "json");
|
|
16294
|
+
if (action !== void 0 && action !== "list" && action !== "revoke")
|
|
16295
|
+
throw new UsageError(`Unknown share action "${sanitize(action)}".`, "Use `peerband share`, `peerband share list` or `peerband share revoke ID`.");
|
|
16296
|
+
if (action !== "revoke" && id !== void 0) throw new UsageError(`Unexpected argument "${sanitize(id)}".`, "Run `peerband share --help` for usage.");
|
|
16297
|
+
if (action && (parsed.values.message !== void 0 || parsed.values.expires !== void 0))
|
|
16298
|
+
throw new UsageError("--message and --expires only apply when creating a link.", "Run `peerband share --message` to create one.");
|
|
16299
|
+
const days = expiryDays(str(parsed, "expires"));
|
|
16300
|
+
const credentials = await requireCredentials(ctx);
|
|
16301
|
+
if (action === "list") return list(ctx, credentials, json);
|
|
16302
|
+
if (action === "revoke") return revoke(ctx, credentials, id);
|
|
16303
|
+
return create(ctx, credentials, flag(parsed, "message") ? "message" : "read", days, json);
|
|
16304
|
+
}
|
|
14642
16305
|
};
|
|
14643
16306
|
|
|
14644
16307
|
// src/cli/commands/status.ts
|
|
@@ -14696,45 +16359,45 @@ function colorConnection(s, state) {
|
|
|
14696
16359
|
if (state === "disabled") return s.dim(`${symbols.ring} ${label}`);
|
|
14697
16360
|
return s.red(`${symbols.dot} ${label}`);
|
|
14698
16361
|
}
|
|
14699
|
-
function renderHuman(
|
|
16362
|
+
function renderHuman(report2, ctx) {
|
|
14700
16363
|
const s = ctx.out.stdout;
|
|
14701
16364
|
const rows = [];
|
|
14702
16365
|
rows.push([
|
|
14703
16366
|
"Account",
|
|
14704
|
-
|
|
16367
|
+
report2.loggedIn ? `${s.green(symbols.ok)} logged in${report2.email ? ` as ${report2.email}` : ""}` : `${s.red(symbols.fail)} not logged in ${s.dim("(run `peerband login`)")}`
|
|
14705
16368
|
]);
|
|
14706
|
-
if (
|
|
14707
|
-
rows.push(["Machine",
|
|
14708
|
-
rows.push(["Server",
|
|
14709
|
-
if (
|
|
14710
|
-
rows.push(["Installation",
|
|
14711
|
-
if (
|
|
14712
|
-
}
|
|
14713
|
-
const relayLine =
|
|
16369
|
+
if (report2.loggedIn) {
|
|
16370
|
+
rows.push(["Machine", report2.machine ?? s.dim("(unnamed)")]);
|
|
16371
|
+
rows.push(["Server", report2.server ?? ""]);
|
|
16372
|
+
if (report2.mcpUrl) rows.push(["MCP server", report2.mcpUrl]);
|
|
16373
|
+
rows.push(["Installation", report2.installationId ?? ""]);
|
|
16374
|
+
if (report2.enrolledAt) rows.push(["Enrolled", report2.enrolledAt]);
|
|
16375
|
+
}
|
|
16376
|
+
const relayLine = report2.relay.running ? colorConnection(s, report2.relay.connection) : 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`)")}`);
|
|
14714
16377
|
rows.push(["Relay", relayLine]);
|
|
14715
|
-
if (
|
|
16378
|
+
if (report2.messages) {
|
|
14716
16379
|
rows.push([
|
|
14717
16380
|
"Messages",
|
|
14718
|
-
|
|
16381
|
+
report2.messages === "allowed" ? `allowed ${s.dim('(needs the agents:message consent; turn off with --read-only or "enableWrites": false in connector.json)')}` : "read-only"
|
|
14719
16382
|
]);
|
|
14720
16383
|
}
|
|
14721
16384
|
rows.push([
|
|
14722
16385
|
"Herdr",
|
|
14723
|
-
!
|
|
16386
|
+
!report2.herdr.found ? `${s.yellow(symbols.warn)} not found ${s.dim("(set HERDR_BIN_PATH or add herdr to PATH)")}` : `${report2.herdr.version ?? "unknown version"}`
|
|
14724
16387
|
]);
|
|
14725
|
-
if (
|
|
14726
|
-
const first =
|
|
16388
|
+
if (report2.herdr.found) {
|
|
16389
|
+
const first = report2.herdr.pluginProblems[0];
|
|
14727
16390
|
rows.push([
|
|
14728
16391
|
"Plugin",
|
|
14729
|
-
!
|
|
16392
|
+
!report2.herdr.pluginInstalled ? `${s.yellow(symbols.warn)} not installed ${s.dim(`(run \`${REPAIR_COMMAND}\`)`)}` : first ? `${s.yellow(symbols.warn)} ${first.message} ${s.dim(`(run \`${fixCommand(first)}\`)`)}` : `${s.green(symbols.ok)} ${report2.herdr.pluginSource ?? "installed"}`
|
|
14730
16393
|
]);
|
|
14731
16394
|
}
|
|
14732
|
-
rows.push(["peerband", `${
|
|
14733
|
-
rows.push(["Config", s.dim(
|
|
16395
|
+
rows.push(["peerband", `${report2.version} ${s.dim(`(node ${report2.node})`)}`]);
|
|
16396
|
+
rows.push(["Config", s.dim(report2.configHome)]);
|
|
14734
16397
|
const width = Math.max(...rows.map(([key]) => key.length));
|
|
14735
16398
|
for (const [key, value] of rows) ctx.out.print(`${s.bold(key.padEnd(width))} ${value}`);
|
|
14736
16399
|
}
|
|
14737
|
-
var
|
|
16400
|
+
var spec9 = {
|
|
14738
16401
|
name: "status",
|
|
14739
16402
|
summary: "Show login, relay and Herdr status",
|
|
14740
16403
|
usage: "peerband status [--json]",
|
|
@@ -14745,15 +16408,241 @@ var spec5 = {
|
|
|
14745
16408
|
["peerband status --json", "For scripts; check .loggedIn and .relay.connection"]
|
|
14746
16409
|
],
|
|
14747
16410
|
async run(parsed, ctx) {
|
|
14748
|
-
const
|
|
14749
|
-
if (flag(parsed, "json")) ctx.out.print(JSON.stringify(
|
|
14750
|
-
else renderHuman(
|
|
14751
|
-
return
|
|
16411
|
+
const report2 = await buildStatus(ctx);
|
|
16412
|
+
if (flag(parsed, "json")) ctx.out.print(JSON.stringify(report2, null, 2));
|
|
16413
|
+
else renderHuman(report2, ctx);
|
|
16414
|
+
return report2.loggedIn ? 0 : EXIT_NOT_LOGGED_IN;
|
|
16415
|
+
}
|
|
16416
|
+
};
|
|
16417
|
+
|
|
16418
|
+
// src/cli/commands/update.ts
|
|
16419
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
16420
|
+
import { dirname as dirname5, isAbsolute, join as join10, relative as relative2 } from "node:path";
|
|
16421
|
+
var DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
16422
|
+
var PACKAGE = "peerband";
|
|
16423
|
+
var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
16424
|
+
function compareVersions(a, b) {
|
|
16425
|
+
const left = VERSION_PATTERN.exec(a);
|
|
16426
|
+
const right = VERSION_PATTERN.exec(b);
|
|
16427
|
+
if (!left || !right) return a === b ? 0 : a < b ? -1 : 1;
|
|
16428
|
+
for (let i = 1; i <= 3; i++) {
|
|
16429
|
+
const diff = Number(left[i]) - Number(right[i]);
|
|
16430
|
+
if (diff !== 0) return Math.sign(diff);
|
|
16431
|
+
}
|
|
16432
|
+
const [preA, preB] = [left[4], right[4]];
|
|
16433
|
+
if (preA === preB) return 0;
|
|
16434
|
+
if (!preA) return 1;
|
|
16435
|
+
if (!preB) return -1;
|
|
16436
|
+
return preA < preB ? -1 : 1;
|
|
16437
|
+
}
|
|
16438
|
+
var OFFLINE_HINT = "Check your internet connection and try again. To update by hand: `npm install -g peerband@latest`, then `peerband update`.";
|
|
16439
|
+
async function fetchLatestVersion(ctx, timeoutMs = 1e4) {
|
|
16440
|
+
const base = (ctx.env.PEERBAND_NPM_REGISTRY || DEFAULT_REGISTRY).replace(/\/+$/, "");
|
|
16441
|
+
const url = `${base}/${PACKAGE}/latest`;
|
|
16442
|
+
let response;
|
|
16443
|
+
try {
|
|
16444
|
+
response = await ctx.fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
|
|
16445
|
+
} catch (error) {
|
|
16446
|
+
const reason = error?.name === "TimeoutError" ? `no answer within ${timeoutMs / 1e3}s` : error?.message || String(error);
|
|
16447
|
+
throw new CliError(`Could not reach the npm registry to check for updates (${reason}).`, OFFLINE_HINT);
|
|
16448
|
+
}
|
|
16449
|
+
if (!response.ok) throw new CliError(`The npm registry answered HTTP ${response.status} for ${url}.`, OFFLINE_HINT);
|
|
16450
|
+
let body;
|
|
16451
|
+
try {
|
|
16452
|
+
body = await response.json();
|
|
16453
|
+
} catch {
|
|
16454
|
+
throw new CliError(`The npm registry returned an unreadable answer for ${url}.`, OFFLINE_HINT);
|
|
16455
|
+
}
|
|
16456
|
+
const version = body && typeof body === "object" ? body.version : void 0;
|
|
16457
|
+
if (typeof version !== "string" || !VERSION_PATTERN.test(version)) throw new CliError(`The npm registry did not report a valid version for ${PACKAGE}.`, OFFLINE_HINT);
|
|
16458
|
+
return version;
|
|
16459
|
+
}
|
|
16460
|
+
function real(path) {
|
|
16461
|
+
try {
|
|
16462
|
+
return realpathSync2(path);
|
|
16463
|
+
} catch {
|
|
16464
|
+
return path;
|
|
16465
|
+
}
|
|
16466
|
+
}
|
|
16467
|
+
function isInside(child, parent) {
|
|
16468
|
+
const fold = (path) => process.platform === "win32" ? path.toLowerCase() : path;
|
|
16469
|
+
const rel = relative2(fold(parent), fold(child));
|
|
16470
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
16471
|
+
}
|
|
16472
|
+
function checkoutRoot(self) {
|
|
16473
|
+
let dir = dirname5(self);
|
|
16474
|
+
for (let i = 0; i < 4; i++) {
|
|
16475
|
+
try {
|
|
16476
|
+
const pkg = JSON.parse(readFileSync2(join10(dir, "package.json"), "utf8"));
|
|
16477
|
+
if (pkg.name === PACKAGE && existsSync2(join10(dir, ".git"))) return dir;
|
|
16478
|
+
} catch {
|
|
16479
|
+
}
|
|
16480
|
+
const parent = dirname5(dir);
|
|
16481
|
+
if (parent === dir) break;
|
|
16482
|
+
dir = parent;
|
|
16483
|
+
}
|
|
16484
|
+
return void 0;
|
|
16485
|
+
}
|
|
16486
|
+
async function detectInstall(ctx) {
|
|
16487
|
+
const self = real(ctx.selfPath ?? ctx.env.PEERBAND_SELF_PATH ?? process.argv[1] ?? "");
|
|
16488
|
+
if (/[\\/]_npx[\\/]/.test(self)) return { kind: "npx", self };
|
|
16489
|
+
const npm = await (ctx.exec ?? execProgram)("npm", ["root", "-g"], { timeoutMs: 6e4, env: ctx.env });
|
|
16490
|
+
const npmRoot = npm.code === 0 ? npm.stdout.trim().split(/\r?\n/).pop()?.trim() : void 0;
|
|
16491
|
+
if (npmRoot && isInside(self, real(join10(npmRoot, PACKAGE)))) return { kind: "npm-global", self, npmRoot };
|
|
16492
|
+
const checkout = checkoutRoot(self);
|
|
16493
|
+
if (checkout) return { kind: "source", self, npmRoot, detail: checkout };
|
|
16494
|
+
return { kind: "unknown", self, npmRoot, detail: npm.notFound ? "npm was not found on PATH" : npmRoot ? `it is not under npm's global folder ${npmRoot}` : "npm did not report its global folder" };
|
|
16495
|
+
}
|
|
16496
|
+
function manualUpdate(info, latest) {
|
|
16497
|
+
const global = `npm install -g peerband@${latest}`;
|
|
16498
|
+
switch (info.kind) {
|
|
16499
|
+
case "npx":
|
|
16500
|
+
return { message: "This peerband was started through npx, so there is no installed copy to update.", hint: `Install it once with \`${global}\`, then run \`peerband update\` to update the Herdr plugin too.` };
|
|
16501
|
+
case "source":
|
|
16502
|
+
return {
|
|
16503
|
+
message: `This peerband runs from a source checkout (${info.detail}).`,
|
|
16504
|
+
hint: "Update the checkout (`git pull`, `npm ci`, `npm run build`), then run `peerband herdr install`. To use the release instead: `" + global + "`, then `peerband update`."
|
|
16505
|
+
};
|
|
16506
|
+
default:
|
|
16507
|
+
return { message: `Could not tell how this peerband was installed (${info.detail ?? info.self}).`, hint: `Run \`${global}\`, then \`peerband update\` to update the Herdr plugin.` };
|
|
16508
|
+
}
|
|
16509
|
+
}
|
|
16510
|
+
function toStderr(ctx) {
|
|
16511
|
+
return { ...ctx, stdout: ctx.stderr, out: new Output(ctx.stderr, ctx.stderr, ctx.env) };
|
|
16512
|
+
}
|
|
16513
|
+
function pluginSummary(check) {
|
|
16514
|
+
return { herdrFound: check.found, installed: check.installed, source: check.source, problems: check.problems.map((problem) => problem.message) };
|
|
16515
|
+
}
|
|
16516
|
+
var spec10 = {
|
|
16517
|
+
name: "update",
|
|
16518
|
+
summary: "Update the CLI and the Herdr plugin to the latest release",
|
|
16519
|
+
usage: "peerband update [--check] [--yes] [--json]",
|
|
16520
|
+
description: "Checks npm for the latest PeerBand release and, if it is newer, installs it with `npm install -g` and then lets the new CLI update the Herdr plugin: it stops the PeerBand Relay and closes its tab, replaces the plugin (the previous one is put back if that fails), clears stale relay locks, and reopens the Relay tab if it was open.\nWhen the CLI is already up to date it still checks that the Herdr plugin matches it and repairs it if not (for example after a plain `npm install -g peerband`).",
|
|
16521
|
+
options: [
|
|
16522
|
+
{ name: "check", type: "boolean", description: "Only report whether an update is available; change nothing." },
|
|
16523
|
+
{ name: "yes", short: "y", type: "boolean", description: "Do not ask for confirmation." },
|
|
16524
|
+
{ name: "json", type: "boolean", description: "Print a machine-readable JSON summary (progress goes to stderr)." }
|
|
16525
|
+
],
|
|
16526
|
+
examples: [
|
|
16527
|
+
["peerband update", "Update everything"],
|
|
16528
|
+
["peerband update --check", "See whether an update is available"],
|
|
16529
|
+
["peerband update --yes --json", "Non-interactive, for scripts"]
|
|
16530
|
+
],
|
|
16531
|
+
notes: [
|
|
16532
|
+
"Only a global npm install can update itself. From npx or a source checkout, update prints the command to run instead.",
|
|
16533
|
+
"Environment: PEERBAND_NPM_REGISTRY (registry to check, default https://registry.npmjs.org)."
|
|
16534
|
+
],
|
|
16535
|
+
async run(parsed, ctx) {
|
|
16536
|
+
const json = flag(parsed, "json");
|
|
16537
|
+
const io = json ? toStderr(ctx) : ctx;
|
|
16538
|
+
const s = io.out.stdout;
|
|
16539
|
+
const log = (line) => io.out.print(line);
|
|
16540
|
+
const latest = await fetchLatestVersion(ctx);
|
|
16541
|
+
const newer = compareVersions(latest, ctx.version) > 0;
|
|
16542
|
+
const plugin = await checkHerdrPlugin(ctx);
|
|
16543
|
+
const report2 = { current: ctx.version, latest, updateAvailable: newer, action: "none", plugin: pluginSummary(plugin) };
|
|
16544
|
+
const pluginNeedsRepair = plugin.found && plugin.installed && plugin.problems.length > 0;
|
|
16545
|
+
const finish = (code = 0) => {
|
|
16546
|
+
if (json) ctx.out.print(JSON.stringify(report2, null, 2));
|
|
16547
|
+
return code;
|
|
16548
|
+
};
|
|
16549
|
+
if (flag(parsed, "check")) {
|
|
16550
|
+
if (newer) log(`${s.yellow(symbols.warn)} PeerBand ${latest} is available (you have ${ctx.version}). Run ${s.bold("peerband update")}.`);
|
|
16551
|
+
else log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
|
|
16552
|
+
if (pluginNeedsRepair) log(`${s.yellow(symbols.warn)} The Herdr plugin needs repair: ${plugin.problems[0].message} ${s.dim("(run `peerband update`)")}`);
|
|
16553
|
+
return finish();
|
|
16554
|
+
}
|
|
16555
|
+
if (!newer) {
|
|
16556
|
+
log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
|
|
16557
|
+
if (pluginNeedsRepair) {
|
|
16558
|
+
log(`${s.yellow(symbols.warn)} The Herdr plugin does not match this CLI: ${plugin.problems[0].message} Repairing it.`);
|
|
16559
|
+
await installPlugin(io);
|
|
16560
|
+
report2.action = "repaired-plugin";
|
|
16561
|
+
report2.plugin = pluginSummary(await checkHerdrPlugin(ctx));
|
|
16562
|
+
} else if (plugin.found && !plugin.installed && !plugin.detail) {
|
|
16563
|
+
log(`${s.dim("The PeerBand plugin is not installed in Herdr. Add it with:")} peerband herdr install`);
|
|
16564
|
+
} else if (plugin.installed) {
|
|
16565
|
+
log(`${s.green(symbols.ok)} The Herdr plugin matches ${s.dim(`(${plugin.source ?? "installed"})`)}.`);
|
|
16566
|
+
}
|
|
16567
|
+
return finish();
|
|
16568
|
+
}
|
|
16569
|
+
const install = await detectInstall(ctx);
|
|
16570
|
+
report2.install = install.kind;
|
|
16571
|
+
if (install.kind !== "npm-global" || !install.npmRoot) {
|
|
16572
|
+
const manual = manualUpdate(install, latest);
|
|
16573
|
+
report2.action = "manual";
|
|
16574
|
+
report2.manual = manual;
|
|
16575
|
+
if (json) {
|
|
16576
|
+
io.out.fail(manual.message, manual.hint);
|
|
16577
|
+
return finish(1);
|
|
16578
|
+
}
|
|
16579
|
+
throw new CliError(`PeerBand ${latest} is available (you have ${ctx.version}). ${manual.message}`, manual.hint);
|
|
16580
|
+
}
|
|
16581
|
+
if (!flag(parsed, "yes") && !json && ctx.stdin.isTTY && ctx.stderr.isTTY) {
|
|
16582
|
+
let proceed;
|
|
16583
|
+
try {
|
|
16584
|
+
proceed = await askYesNo(ctx.stdin, ctx.stderr, `Update PeerBand ${ctx.version} \u2192 ${latest}? [Y/n] `);
|
|
16585
|
+
} catch (error) {
|
|
16586
|
+
if (!(error instanceof PromptAborted)) throw error;
|
|
16587
|
+
proceed = false;
|
|
16588
|
+
}
|
|
16589
|
+
if (!proceed) {
|
|
16590
|
+
report2.action = "cancelled";
|
|
16591
|
+
log(s.dim("Not updated."));
|
|
16592
|
+
return finish();
|
|
16593
|
+
}
|
|
16594
|
+
}
|
|
16595
|
+
const exec2 = ctx.exec ?? execProgram;
|
|
16596
|
+
const spec11 = `peerband@${latest}`;
|
|
16597
|
+
log(`Installing ${spec11} with npm\u2026`);
|
|
16598
|
+
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 });
|
|
16600
|
+
if (npm.code !== 0) {
|
|
16601
|
+
const permission = /EACCES|EPERM|permission denied/i.test(`${npm.stderr}${npm.stdout}`);
|
|
16602
|
+
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\`.`
|
|
16605
|
+
);
|
|
16606
|
+
}
|
|
16607
|
+
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\`.`);
|
|
16609
|
+
log(`${s.green(symbols.ok)} Installed peerband ${latest}.`);
|
|
16610
|
+
report2.action = "updated";
|
|
16611
|
+
if (skillInstalled(ctx)) {
|
|
16612
|
+
const refreshed = await exec2(process.execPath, [entry, "skill", "--if-installed"], {
|
|
16613
|
+
timeoutMs: 5 * 6e4,
|
|
16614
|
+
env: ctx.env,
|
|
16615
|
+
onStdout: (text2) => io.stdout.write(text2),
|
|
16616
|
+
onStderr: (text2) => ctx.stderr.write(text2)
|
|
16617
|
+
});
|
|
16618
|
+
if (refreshed.code !== 0) io.out.warn(`${io.out.stderr.yellow(symbols.warn)} Could not update the PeerBand skill. Run \`peerband skill\` later.`);
|
|
16619
|
+
}
|
|
16620
|
+
if (!plugin.found) {
|
|
16621
|
+
log(s.dim("Herdr was not found, so there is no plugin to update."));
|
|
16622
|
+
return finish();
|
|
16623
|
+
}
|
|
16624
|
+
if (!plugin.installed) {
|
|
16625
|
+
log(`${s.dim("Next:")} peerband herdr install ${s.dim("(adds the PeerBand plugin to Herdr)")}`);
|
|
16626
|
+
return finish();
|
|
16627
|
+
}
|
|
16628
|
+
log("Updating the Herdr plugin with the new CLI\u2026");
|
|
16629
|
+
const env = { ...ctx.env, ...io.out.stdout.enabled && ctx.env.FORCE_COLOR === void 0 ? { FORCE_COLOR: "1" } : {} };
|
|
16630
|
+
const handoff = await exec2(process.execPath, [entry, "herdr", "install", "--after-update"], {
|
|
16631
|
+
timeoutMs: 15 * 6e4,
|
|
16632
|
+
env,
|
|
16633
|
+
onStdout: (text2) => io.stdout.write(text2),
|
|
16634
|
+
onStderr: (text2) => ctx.stderr.write(text2)
|
|
16635
|
+
});
|
|
16636
|
+
if (handoff.code !== 0) {
|
|
16637
|
+
throw new CliError(`peerband ${latest} is installed, but updating the Herdr plugin failed (exit code ${handoff.code}).`, "Fix the problem shown above, then run `peerband herdr install`.");
|
|
16638
|
+
}
|
|
16639
|
+
report2.plugin = pluginSummary(await checkHerdrPlugin({ ...ctx, version: latest }));
|
|
16640
|
+
return finish();
|
|
14752
16641
|
}
|
|
14753
16642
|
};
|
|
14754
16643
|
|
|
14755
16644
|
// src/cli/registry.ts
|
|
14756
|
-
var commands = [spec2, spec3, spec5, spec4, spec];
|
|
16645
|
+
var commands = [spec7, spec2, spec3, spec9, spec10, spec5, spec6, spec8, spec4, spec];
|
|
14757
16646
|
var herdrCommands = [installSpec, uninstallSpec];
|
|
14758
16647
|
function lookup(words) {
|
|
14759
16648
|
const [first, second] = words;
|
|
@@ -14805,6 +16694,8 @@ function rootHelp(s, version) {
|
|
|
14805
16694
|
"2. peerband herdr install Add the plugin to Herdr",
|
|
14806
16695
|
"3. peerband relay Open the relay tab and connect"
|
|
14807
16696
|
]),
|
|
16697
|
+
...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)']),
|
|
14808
16699
|
...section(s, "Exit codes", ["0 ok 1 failure 2 usage error 3 not logged in 130 interrupted"]),
|
|
14809
16700
|
"",
|
|
14810
16701
|
`Run ${s.cyan("peerband <command> --help")} for details. Docs: https://peerband.com`
|
|
@@ -14812,20 +16703,20 @@ function rootHelp(s, version) {
|
|
|
14812
16703
|
return `${lines.join("\n")}
|
|
14813
16704
|
`;
|
|
14814
16705
|
}
|
|
14815
|
-
function commandHelp(s,
|
|
16706
|
+
function commandHelp(s, spec11) {
|
|
14816
16707
|
const lines = [
|
|
14817
|
-
`${s.bold(`peerband ${
|
|
14818
|
-
...section(s, "Usage", [
|
|
16708
|
+
`${s.bold(`peerband ${spec11.name}`)} ${spec11.summary}`,
|
|
16709
|
+
...section(s, "Usage", [spec11.usage]),
|
|
14819
16710
|
"",
|
|
14820
|
-
...
|
|
14821
|
-
...section(s, "Options", table(optionRows(
|
|
16711
|
+
...spec11.description.split("\n").map((line) => ` ${line}`),
|
|
16712
|
+
...section(s, "Options", table(optionRows(spec11.options), s)),
|
|
14822
16713
|
...section(
|
|
14823
16714
|
s,
|
|
14824
16715
|
"Examples",
|
|
14825
|
-
|
|
16716
|
+
spec11.examples.flatMap(([command, comment]) => [`${s.cyan(command)}`, ` ${s.dim(comment)}`])
|
|
14826
16717
|
)
|
|
14827
16718
|
];
|
|
14828
|
-
if (
|
|
16719
|
+
if (spec11.notes?.length) lines.push(...section(s, "Notes", spec11.notes));
|
|
14829
16720
|
return `${lines.join("\n")}
|
|
14830
16721
|
`;
|
|
14831
16722
|
}
|
|
@@ -14843,7 +16734,7 @@ function herdrGroupHelp(s) {
|
|
|
14843
16734
|
}
|
|
14844
16735
|
|
|
14845
16736
|
// src/cli/cli.ts
|
|
14846
|
-
var VERSION = true ? "0.1.
|
|
16737
|
+
var VERSION = true ? "0.1.5" : "0.0.0-dev";
|
|
14847
16738
|
function createContext(overrides = {}) {
|
|
14848
16739
|
const env = overrides.env ?? process.env;
|
|
14849
16740
|
const stdout = overrides.stdout ?? process.stdout;
|
|
@@ -14864,15 +16755,15 @@ function resolveHelpTarget(words, ctx) {
|
|
|
14864
16755
|
const s = ctx.out.stdout;
|
|
14865
16756
|
if (words.length === 0) return rootHelp(s, ctx.version);
|
|
14866
16757
|
if (words[0] === "herdr" && words.length === 1) return herdrGroupHelp(s);
|
|
14867
|
-
const
|
|
14868
|
-
if (!
|
|
14869
|
-
return commandHelp(s,
|
|
16758
|
+
const spec11 = lookup(words);
|
|
16759
|
+
if (!spec11) throw unknownCommand(words.join(" "));
|
|
16760
|
+
return commandHelp(s, spec11);
|
|
14870
16761
|
}
|
|
14871
16762
|
function unknownCommand(name) {
|
|
14872
16763
|
const near = suggest(name, topLevelNames());
|
|
14873
16764
|
return new UsageError(`Unknown command "${name}".`, near ? `Did you mean \`peerband ${near}\`? Run \`peerband --help\` for all commands.` : "Run `peerband --help` for all commands.");
|
|
14874
16765
|
}
|
|
14875
|
-
async function
|
|
16766
|
+
async function run2(argv, ctx = createContext()) {
|
|
14876
16767
|
try {
|
|
14877
16768
|
const [first, ...rest] = argv;
|
|
14878
16769
|
if (first === void 0) {
|
|
@@ -14909,14 +16800,14 @@ async function run(argv, ctx = createContext()) {
|
|
|
14909
16800
|
words = [first, second];
|
|
14910
16801
|
args = others;
|
|
14911
16802
|
}
|
|
14912
|
-
const
|
|
14913
|
-
if (!
|
|
14914
|
-
const parsed = parseArgs(
|
|
16803
|
+
const spec11 = lookup(words);
|
|
16804
|
+
if (!spec11) throw unknownCommand(first);
|
|
16805
|
+
const parsed = parseArgs(spec11, args);
|
|
14915
16806
|
if (parsed.values.help) {
|
|
14916
|
-
ctx.out.print(commandHelp(ctx.out.stdout,
|
|
16807
|
+
ctx.out.print(commandHelp(ctx.out.stdout, spec11).trimEnd());
|
|
14917
16808
|
return 0;
|
|
14918
16809
|
}
|
|
14919
|
-
return await
|
|
16810
|
+
return await spec11.run(parsed, ctx);
|
|
14920
16811
|
} catch (error) {
|
|
14921
16812
|
if (error instanceof UsageError) {
|
|
14922
16813
|
ctx.out.fail(error.message, error.hint);
|
|
@@ -14937,4 +16828,4 @@ async function run(argv, ctx = createContext()) {
|
|
|
14937
16828
|
}
|
|
14938
16829
|
|
|
14939
16830
|
// src/cli/main.ts
|
|
14940
|
-
process.exitCode = await
|
|
16831
|
+
process.exitCode = await run2(process.argv.slice(2));
|