peerband 0.1.3 → 0.1.6
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 +53 -14
- package/dist/peerband.mjs +2686 -919
- package/herdr/README.md +18 -18
- package/herdr/control.mjs +2 -1
- package/herdr/launch.mjs +87 -87
- package/herdr/lifecycle.mjs +141 -55
- package/herdr/pane.mjs +124 -46
- 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/herdr/README.md
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
# Herdr plugin sources (contributors)
|
|
2
|
-
|
|
3
|
-
Plain `.mjs` files run directly by Herdr; they are not bundled. Every command in `../herdr-plugin.toml` goes through `launch.mjs`, which picks the right Node (from `settings.json` written by `peerband herdr install`: `nodePath`, optional `configHome`), checks Node >= 22.13, applies `configHome` (`PEERBAND_CONFIG_HOME`, unless already set), and imports one allowlisted entry (`pane`, `open-pane`, `lifecycle`).
|
|
4
|
-
|
|
5
|
-
- `pane*.mjs` - the persistent "PeerBand Relay" TUI tab. `pane-state.mjs` validates connector events; `pane-ui.mjs` renders.
|
|
6
|
-
- `lifecycle.mjs` - supervisor that owns the connector child (`node dist/peerband.mjs connect --managed`, plus `--runtime mock` if `PEERBAND_RUNTIME=mock`, `--config` if `PEERBAND_CONNECTOR_CONFIG` is set). Closing the owning pane stops the child. Never kills a stored PID.
|
|
7
|
-
- `control.mjs`, `paths.mjs` - control channel and config paths (`paths.mjs` mirrors `configHome()` in `src/core/config.ts`).
|
|
8
|
-
- `relay-tab.mjs` - marker-validated tab open/reuse/rename/close. `openRelayTab()` is also imported by the bundled CLI (`peerband relay`), so it must not depend on files next to it.
|
|
9
|
-
|
|
10
|
-
## Connector child contract
|
|
11
|
-
|
|
12
|
-
Spawned with an IPC channel. It sends `{ type: "peerband:pane-event", kind: "connection", state }` and `{ type: "peerband:pane-event", kind: "activity", requestId, tool, target?, outcome, latencyMs }`, and exits on `{ type: "peerband:shutdown" }`.
|
|
13
|
-
|
|
14
|
-
## Environment
|
|
15
|
-
|
|
16
|
-
- `PEERBAND_CONFIG_HOME`, `HERDR_BIN_PATH` (Herdr always sets it for plugin processes; `settings.json` no longer records it, and a leftover `herdrBinary` key is ignored), `HERDR_PLUGIN_CONFIG_DIR` (Herdr-provided), `HERDR_PANE_ID`.
|
|
17
|
-
- `PEERBAND_RUNTIME=mock`, `PEERBAND_CONNECTOR_CONFIG=<path>` - forwarded to the connector child.
|
|
18
|
-
- Test-only: `PEERBAND_CONNECTOR_ENTRY` replaces `dist/peerband.mjs` as the connector child (tests use `test/fixtures/fake-connector.mjs`); `PEERBAND_NODE_MIN` overrides the Node version floor in `launch.mjs`; `PEERBAND_LAUNCH_DEBUG=1` makes `launch.mjs` print the Node it runs under.
|
|
1
|
+
# Herdr plugin sources (contributors)
|
|
2
|
+
|
|
3
|
+
Plain `.mjs` files run directly by Herdr; they are not bundled. Every command in `../herdr-plugin.toml` goes through `launch.mjs`, which picks the right Node (from `settings.json` written by `peerband herdr install`: `nodePath`, optional `configHome`), checks Node >= 22.13, applies `configHome` (`PEERBAND_CONFIG_HOME`, unless already set), and imports one allowlisted entry (`pane`, `open-pane`, `lifecycle`).
|
|
4
|
+
|
|
5
|
+
- `pane*.mjs` - the persistent "PeerBand Relay" TUI tab. `pane-state.mjs` validates connector events; `pane-ui.mjs` renders.
|
|
6
|
+
- `lifecycle.mjs` - supervisor that owns the connector child (`node dist/peerband.mjs connect --managed`, plus `--runtime mock` if `PEERBAND_RUNTIME=mock`, `--config` if `PEERBAND_CONNECTOR_CONFIG` is set). Closing the owning pane stops the child. Never kills a stored PID.
|
|
7
|
+
- `control.mjs`, `paths.mjs` - control channel and config paths (`paths.mjs` mirrors `configHome()` in `src/core/config.ts`).
|
|
8
|
+
- `relay-tab.mjs` - marker-validated tab open/reuse/rename/close. `openRelayTab()` is also imported by the bundled CLI (`peerband relay`), so it must not depend on files next to it.
|
|
9
|
+
|
|
10
|
+
## Connector child contract
|
|
11
|
+
|
|
12
|
+
Spawned with an IPC channel. It sends `{ type: "peerband:pane-event", kind: "connection", state }` and `{ type: "peerband:pane-event", kind: "activity", requestId, tool, target?, outcome, latencyMs }`, and exits on `{ type: "peerband:shutdown" }`.
|
|
13
|
+
|
|
14
|
+
## Environment
|
|
15
|
+
|
|
16
|
+
- `PEERBAND_CONFIG_HOME`, `HERDR_BIN_PATH` (Herdr always sets it for plugin processes; `settings.json` no longer records it, and a leftover `herdrBinary` key is ignored), `HERDR_PLUGIN_CONFIG_DIR` (Herdr-provided), `HERDR_PANE_ID`.
|
|
17
|
+
- `PEERBAND_RUNTIME=mock`, `PEERBAND_CONNECTOR_CONFIG=<path>` - forwarded to the connector child.
|
|
18
|
+
- Test-only: `PEERBAND_CONNECTOR_ENTRY` replaces `dist/peerband.mjs` as the connector child (tests use `test/fixtures/fake-connector.mjs`); `PEERBAND_NODE_MIN` overrides the Node version floor in `launch.mjs`; `PEERBAND_LAUNCH_DEBUG=1` makes `launch.mjs` print the Node it runs under.
|
package/herdr/control.mjs
CHANGED
|
@@ -13,7 +13,8 @@ const matches = (a, b) => typeof a === "string" && timingSafeEqual(
|
|
|
13
13
|
createHash("sha256").update(b).digest(),
|
|
14
14
|
);
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
// Generous: on a loaded Windows machine the helper can take seconds to answer even a local pipe.
|
|
17
|
+
export async function connectControl({ timeout = 10_000, initialCommand } = {}) {
|
|
17
18
|
const record = JSON.parse(await readFile(recordPath, "utf8"));
|
|
18
19
|
const socket = createConnection(channel);
|
|
19
20
|
await new Promise((resolve, reject) => {
|
package/herdr/launch.mjs
CHANGED
|
@@ -1,87 +1,87 @@
|
|
|
1
|
-
// PeerBand Herdr launcher. Every manifest command runs through this file:
|
|
2
|
-
// node herdr/launch.mjs <entry> [args...]
|
|
3
|
-
// Written in conservative syntax (no top-level await, no optional chaining) so that it still parses on old
|
|
4
|
-
// Node versions and can print a friendly "Node too old" message instead of a SyntaxError.
|
|
5
|
-
import { spawnSync } from "child_process";
|
|
6
|
-
import { existsSync, readFileSync } from "fs";
|
|
7
|
-
import { dirname, join } from "path";
|
|
8
|
-
import { pathToFileURL } from "url";
|
|
9
|
-
|
|
10
|
-
var ENTRIES = ["pane", "open-pane", "lifecycle"];
|
|
11
|
-
// PEERBAND_NODE_MIN is for tests only.
|
|
12
|
-
var MIN_NODE = (process.env.PEERBAND_NODE_MIN || "22.13.0").split(".").map(Number);
|
|
13
|
-
|
|
14
|
-
function fail(message) {
|
|
15
|
-
process.stderr.write(message + "\n");
|
|
16
|
-
process.exit(1);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function nodeIsRecentEnough() {
|
|
20
|
-
var have = process.versions.node.split(".").map(Number);
|
|
21
|
-
for (var i = 0; i < 3; i++) {
|
|
22
|
-
if (have[i] > MIN_NODE[i]) return true;
|
|
23
|
-
if (have[i] < MIN_NODE[i]) return false;
|
|
24
|
-
}
|
|
25
|
-
return true;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function readSettings() {
|
|
29
|
-
var dir = process.env.HERDR_PLUGIN_CONFIG_DIR;
|
|
30
|
-
if (!dir) return {};
|
|
31
|
-
try {
|
|
32
|
-
var value = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"));
|
|
33
|
-
return value && typeof value === "object" ? value : {};
|
|
34
|
-
} catch {
|
|
35
|
-
return {};
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function main() {
|
|
40
|
-
var entry = process.argv[2];
|
|
41
|
-
if (ENTRIES.indexOf(entry) < 0) {
|
|
42
|
-
fail("peerband: unknown plugin entry " + JSON.stringify(entry || "") + ". Expected one of: " + ENTRIES.join(", ") + ".");
|
|
43
|
-
}
|
|
44
|
-
var settings = readSettings();
|
|
45
|
-
var args = process.argv.slice(2);
|
|
46
|
-
|
|
47
|
-
if (
|
|
48
|
-
typeof settings.nodePath === "string" && settings.nodePath &&
|
|
49
|
-
settings.nodePath !== process.execPath &&
|
|
50
|
-
!process.env.PEERBAND_LAUNCHED &&
|
|
51
|
-
existsSync(settings.nodePath)
|
|
52
|
-
) {
|
|
53
|
-
var env = {};
|
|
54
|
-
for (var key in process.env) env[key] = process.env[key];
|
|
55
|
-
env.PEERBAND_LAUNCHED = "1";
|
|
56
|
-
// The pane entry is an interactive TUI: on Windows, hiding the console would detach it.
|
|
57
|
-
var result = spawnSync(settings.nodePath, [process.argv[1]].concat(args), {
|
|
58
|
-
stdio: "inherit",
|
|
59
|
-
env: env,
|
|
60
|
-
windowsHide: entry !== "pane",
|
|
61
|
-
});
|
|
62
|
-
if (result.error) fail("peerband: could not start Node.js at " + settings.nodePath + " (" + result.error.message + "). Run `peerband herdr install` to refresh the plugin settings.");
|
|
63
|
-
process.exit(result.status === null ? 1 : result.status);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
if (!nodeIsRecentEnough()) {
|
|
67
|
-
fail(
|
|
68
|
-
"PeerBand needs Node.js " + MIN_NODE.join(".") + " or newer (Herdr found " + process.versions.node + " at " + process.execPath + "). " +
|
|
69
|
-
"Run `peerband herdr install` from a shell with Node.js " + MIN_NODE.join(".") + "+ so the plugin remembers it."
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
if (typeof settings.configHome === "string" && settings.configHome && !process.env.PEERBAND_CONFIG_HOME) {
|
|
74
|
-
process.env.PEERBAND_CONFIG_HOME = settings.configHome;
|
|
75
|
-
}
|
|
76
|
-
if (process.env.PEERBAND_LAUNCH_DEBUG) process.stderr.write("peerband-launch: node=" + process.execPath + " entry=" + entry + "\n");
|
|
77
|
-
|
|
78
|
-
// Entry modules read their own arguments from argv[2..] (lifecycle's argv[2] is its command), so
|
|
79
|
-
// present them with the argv they would have had if run directly.
|
|
80
|
-
var entryPath = join(dirname(process.argv[1]), entry + ".mjs");
|
|
81
|
-
process.argv.splice(1, 2, entryPath);
|
|
82
|
-
import(pathToFileURL(entryPath).href).catch(function (error) {
|
|
83
|
-
fail("peerband: could not start " + entry + ": " + (error && error.message ? error.message : error));
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
main();
|
|
1
|
+
// PeerBand Herdr launcher. Every manifest command runs through this file:
|
|
2
|
+
// node herdr/launch.mjs <entry> [args...]
|
|
3
|
+
// Written in conservative syntax (no top-level await, no optional chaining) so that it still parses on old
|
|
4
|
+
// Node versions and can print a friendly "Node too old" message instead of a SyntaxError.
|
|
5
|
+
import { spawnSync } from "child_process";
|
|
6
|
+
import { existsSync, readFileSync } from "fs";
|
|
7
|
+
import { dirname, join } from "path";
|
|
8
|
+
import { pathToFileURL } from "url";
|
|
9
|
+
|
|
10
|
+
var ENTRIES = ["pane", "open-pane", "lifecycle"];
|
|
11
|
+
// PEERBAND_NODE_MIN is for tests only.
|
|
12
|
+
var MIN_NODE = (process.env.PEERBAND_NODE_MIN || "22.13.0").split(".").map(Number);
|
|
13
|
+
|
|
14
|
+
function fail(message) {
|
|
15
|
+
process.stderr.write(message + "\n");
|
|
16
|
+
process.exit(1);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function nodeIsRecentEnough() {
|
|
20
|
+
var have = process.versions.node.split(".").map(Number);
|
|
21
|
+
for (var i = 0; i < 3; i++) {
|
|
22
|
+
if (have[i] > MIN_NODE[i]) return true;
|
|
23
|
+
if (have[i] < MIN_NODE[i]) return false;
|
|
24
|
+
}
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function readSettings() {
|
|
29
|
+
var dir = process.env.HERDR_PLUGIN_CONFIG_DIR;
|
|
30
|
+
if (!dir) return {};
|
|
31
|
+
try {
|
|
32
|
+
var value = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"));
|
|
33
|
+
return value && typeof value === "object" ? value : {};
|
|
34
|
+
} catch {
|
|
35
|
+
return {};
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function main() {
|
|
40
|
+
var entry = process.argv[2];
|
|
41
|
+
if (ENTRIES.indexOf(entry) < 0) {
|
|
42
|
+
fail("peerband: unknown plugin entry " + JSON.stringify(entry || "") + ". Expected one of: " + ENTRIES.join(", ") + ".");
|
|
43
|
+
}
|
|
44
|
+
var settings = readSettings();
|
|
45
|
+
var args = process.argv.slice(2);
|
|
46
|
+
|
|
47
|
+
if (
|
|
48
|
+
typeof settings.nodePath === "string" && settings.nodePath &&
|
|
49
|
+
settings.nodePath !== process.execPath &&
|
|
50
|
+
!process.env.PEERBAND_LAUNCHED &&
|
|
51
|
+
existsSync(settings.nodePath)
|
|
52
|
+
) {
|
|
53
|
+
var env = {};
|
|
54
|
+
for (var key in process.env) env[key] = process.env[key];
|
|
55
|
+
env.PEERBAND_LAUNCHED = "1";
|
|
56
|
+
// The pane entry is an interactive TUI: on Windows, hiding the console would detach it.
|
|
57
|
+
var result = spawnSync(settings.nodePath, [process.argv[1]].concat(args), {
|
|
58
|
+
stdio: "inherit",
|
|
59
|
+
env: env,
|
|
60
|
+
windowsHide: entry !== "pane",
|
|
61
|
+
});
|
|
62
|
+
if (result.error) fail("peerband: could not start Node.js at " + settings.nodePath + " (" + result.error.message + "). Run `peerband herdr install` to refresh the plugin settings.");
|
|
63
|
+
process.exit(result.status === null ? 1 : result.status);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (!nodeIsRecentEnough()) {
|
|
67
|
+
fail(
|
|
68
|
+
"PeerBand needs Node.js " + MIN_NODE.join(".") + " or newer (Herdr found " + process.versions.node + " at " + process.execPath + "). " +
|
|
69
|
+
"Run `peerband herdr install` from a shell with Node.js " + MIN_NODE.join(".") + "+ so the plugin remembers it."
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (typeof settings.configHome === "string" && settings.configHome && !process.env.PEERBAND_CONFIG_HOME) {
|
|
74
|
+
process.env.PEERBAND_CONFIG_HOME = settings.configHome;
|
|
75
|
+
}
|
|
76
|
+
if (process.env.PEERBAND_LAUNCH_DEBUG) process.stderr.write("peerband-launch: node=" + process.execPath + " entry=" + entry + "\n");
|
|
77
|
+
|
|
78
|
+
// Entry modules read their own arguments from argv[2..] (lifecycle's argv[2] is its command), so
|
|
79
|
+
// present them with the argv they would have had if run directly.
|
|
80
|
+
var entryPath = join(dirname(process.argv[1]), entry + ".mjs");
|
|
81
|
+
process.argv.splice(1, 2, entryPath);
|
|
82
|
+
import(pathToFileURL(entryPath).href).catch(function (error) {
|
|
83
|
+
fail("peerband: could not start " + entry + ": " + (error && error.message ? error.message : error));
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
main();
|
package/herdr/lifecycle.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
|
|
|
8
8
|
import { normalizePaneEvent, createPaneSnapshot, fallbackPaneSnapshot } from "./pane-state.mjs";
|
|
9
9
|
import { config, lock, recordPath, channel, connectControl, matches } from "./control.mjs";
|
|
10
10
|
import { relayStatePath } from "./paths.mjs";
|
|
11
|
+
import { ownerIdentity, reclaimIfStale, resetRelayState, SUPERVISOR_PATTERN } from "./stale-lock.mjs";
|
|
11
12
|
|
|
12
13
|
const script = fileURLToPath(import.meta.url);
|
|
13
14
|
const pluginRoot = resolve(dirname(script), "..");
|
|
@@ -15,15 +16,33 @@ const pluginRoot = resolve(dirname(script), "..");
|
|
|
15
16
|
const connectorEntry = process.env.PEERBAND_CONNECTOR_ENTRY || join(pluginRoot, "dist", "peerband.mjs");
|
|
16
17
|
const paneStatePath = relayStatePath(config);
|
|
17
18
|
|
|
19
|
+
// Starting Node can take several seconds on a loaded machine (5-8 s has been seen on Windows), so waits are
|
|
20
|
+
// deadlines measured in time, not a fixed number of quick retries.
|
|
21
|
+
const CONTROL_TIMEOUT_MS = 10_000;
|
|
22
|
+
const HELPER_START_MS = 30_000;
|
|
23
|
+
// A helper started for the Relay pane stops if no pane attaches within this time.
|
|
24
|
+
const AWAIT_UI_MS = 60_000;
|
|
25
|
+
|
|
26
|
+
async function waitForHelper() {
|
|
27
|
+
const deadline = Date.now() + HELPER_START_MS;
|
|
28
|
+
for (;;) {
|
|
29
|
+
try { return await request("status"); }
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (Date.now() >= deadline) throw error;
|
|
32
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
18
37
|
async function request(command) {
|
|
19
|
-
const socket = await connectControl({ initialCommand: command, timeout:
|
|
38
|
+
const socket = await connectControl({ initialCommand: command, timeout: CONTROL_TIMEOUT_MS });
|
|
20
39
|
return new Promise((resolve, reject) => {
|
|
21
40
|
let text = "";
|
|
22
41
|
let settled = false;
|
|
23
42
|
const timer = setTimeout(() => {
|
|
24
43
|
socket.destroy();
|
|
25
44
|
finish(new Error("Helper control timeout"));
|
|
26
|
-
},
|
|
45
|
+
}, CONTROL_TIMEOUT_MS);
|
|
27
46
|
const finish = (error, value) => {
|
|
28
47
|
if (settled) return;
|
|
29
48
|
settled = true;
|
|
@@ -78,6 +97,8 @@ async function supervise() {
|
|
|
78
97
|
let owner = null;
|
|
79
98
|
let connectionState = "disabled";
|
|
80
99
|
let activity = [];
|
|
100
|
+
// `peerband notify` requests waiting for the connector child's answer, by id.
|
|
101
|
+
const pendingNotes = new Map();
|
|
81
102
|
try {
|
|
82
103
|
const previous = JSON.parse(await readFile(paneStatePath, "utf8"));
|
|
83
104
|
activity = createPaneSnapshot(previous).activity;
|
|
@@ -116,7 +137,8 @@ async function supervise() {
|
|
|
116
137
|
uiOwned = true;
|
|
117
138
|
if (!child) startChild();
|
|
118
139
|
reply(currentSnapshot());
|
|
119
|
-
} else if (input.command === "
|
|
140
|
+
} else if (input.command === "notify") forwardNote(input, reply);
|
|
141
|
+
else if (input.command === "status") reply(currentSnapshot(), true);
|
|
120
142
|
else if (input.command === "stop") {
|
|
121
143
|
reply({ state: "stopping" }, true);
|
|
122
144
|
stopSupervisor();
|
|
@@ -135,7 +157,8 @@ async function supervise() {
|
|
|
135
157
|
};
|
|
136
158
|
socket.on("data", (chunk) => {
|
|
137
159
|
buffer += chunk.toString();
|
|
138
|
-
|
|
160
|
+
// Room for a `notify` line (a note of up to 1024 characters, JSON-escaped); other commands are tiny.
|
|
161
|
+
if (buffer.length > 16384) { socket.destroy(); return; }
|
|
139
162
|
let newline;
|
|
140
163
|
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
141
164
|
const line = buffer.slice(0, newline);
|
|
@@ -145,6 +168,49 @@ async function supervise() {
|
|
|
145
168
|
}
|
|
146
169
|
});
|
|
147
170
|
});
|
|
171
|
+
// Hands a note to the connector child, which sends it to PeerBand as an `agent.notified` event.
|
|
172
|
+
function forwardNote(input, reply) {
|
|
173
|
+
const text = input.text;
|
|
174
|
+
const paneId = input.paneId;
|
|
175
|
+
if (typeof text !== "string" || text.length > 4096 || (paneId !== undefined && (typeof paneId !== "string" || paneId.length > 128))) {
|
|
176
|
+
reply({ error: "invalid", message: "The note must be text of at most 1024 characters." }, true);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const current = child;
|
|
180
|
+
if (!current || stopping || finalStop || !current.connected) {
|
|
181
|
+
reply({ error: "not-running", message: "The relay is turned off." }, true);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const id = randomBytes(12).toString("hex");
|
|
185
|
+
const timer = setTimeout(() => {
|
|
186
|
+
if (!pendingNotes.delete(id)) return;
|
|
187
|
+
reply({ error: "timeout", message: "The connector did not answer in time." }, true);
|
|
188
|
+
}, 5000);
|
|
189
|
+
timer.unref();
|
|
190
|
+
pendingNotes.set(id, { reply, timer });
|
|
191
|
+
current.send({ type: "peerband:notify", id, text, ...(paneId ? { paneId } : {}) }, (error) => {
|
|
192
|
+
if (!error || !pendingNotes.delete(id)) return;
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
reply({ error: "not-running", message: "The connector is not reachable." }, true);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function settleNote(message) {
|
|
198
|
+
const pending = pendingNotes.get(message.id);
|
|
199
|
+
if (!pending) return;
|
|
200
|
+
pendingNotes.delete(message.id);
|
|
201
|
+
clearTimeout(pending.timer);
|
|
202
|
+
const text = (value, max) => (typeof value === "string" ? value.slice(0, max) : undefined);
|
|
203
|
+
pending.reply(message.ok === true
|
|
204
|
+
? { ok: true, sent: message.sent === true, agentId: text(message.agentId, 256) ?? null, ...(text(message.eventId, 64) ? { eventId: text(message.eventId, 64) } : {}) }
|
|
205
|
+
: { error: text(message.code, 64) ?? "error", message: text(message.message, 512) ?? "The note could not be sent.", ...(text(message.nextStep, 512) ? { nextStep: text(message.nextStep, 512) } : {}) }, true);
|
|
206
|
+
}
|
|
207
|
+
const failNotes = () => {
|
|
208
|
+
for (const [id, pending] of pendingNotes) {
|
|
209
|
+
pendingNotes.delete(id);
|
|
210
|
+
clearTimeout(pending.timer);
|
|
211
|
+
pending.reply({ error: "not-running", message: "The connector stopped before sending the note." }, true);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
148
214
|
const cleanup = async () => {
|
|
149
215
|
if (owner) { const previous = owner; owner = null; previous.destroy(); }
|
|
150
216
|
server.close();
|
|
@@ -186,6 +252,7 @@ async function supervise() {
|
|
|
186
252
|
save();
|
|
187
253
|
current.on("message", (message) => {
|
|
188
254
|
if (child !== current) return;
|
|
255
|
+
if (message && typeof message === "object" && message.type === "peerband:notify-result" && typeof message.id === "string") { settleNote(message); return; }
|
|
189
256
|
const event = normalizePaneEvent(message);
|
|
190
257
|
if (!event) return;
|
|
191
258
|
if (event.kind === "connection") connectionState = stopping && event.state !== "revoked" ? "disabled" : event.state;
|
|
@@ -201,6 +268,7 @@ async function supervise() {
|
|
|
201
268
|
current.once("exit", () => {
|
|
202
269
|
if (child !== current) return;
|
|
203
270
|
child = null;
|
|
271
|
+
failNotes();
|
|
204
272
|
if (stopping) connectionState = "disabled";
|
|
205
273
|
else if (connectionState !== "revoked") connectionState = "unavailable";
|
|
206
274
|
save();
|
|
@@ -218,13 +286,13 @@ async function supervise() {
|
|
|
218
286
|
server.once("error", reject);
|
|
219
287
|
server.listen(channel, resolve);
|
|
220
288
|
});
|
|
221
|
-
await writeFile(recordPath, JSON.stringify({ token }), {
|
|
289
|
+
await writeFile(recordPath, JSON.stringify({ token, ...ownerIdentity() }), {
|
|
222
290
|
mode: 0o600,
|
|
223
291
|
flag: "wx",
|
|
224
292
|
});
|
|
225
293
|
if (process.argv[3] !== "--await-ui") startChild();
|
|
226
294
|
else if (!owner) {
|
|
227
|
-
const idleTimer = setTimeout(() => { if (!owner) stopSupervisor(); },
|
|
295
|
+
const idleTimer = setTimeout(() => { if (!owner) stopSupervisor(); }, AWAIT_UI_MS);
|
|
228
296
|
idleTimer.unref();
|
|
229
297
|
}
|
|
230
298
|
}
|
|
@@ -234,6 +302,61 @@ async function assertConnectorEntry() {
|
|
|
234
302
|
catch { throw new Error(`PeerBand connector not found at ${connectorEntry}. Reinstall the plugin with \`peerband herdr install\` (a source checkout needs \`npm run build\` first).`); }
|
|
235
303
|
}
|
|
236
304
|
|
|
305
|
+
function lockError(verdict) {
|
|
306
|
+
return new Error(
|
|
307
|
+
`Another PeerBand helper still holds the relay lock (${verdict.reason}). ` +
|
|
308
|
+
"Stop it with `peerband herdr install` (restarts the relay cleanly) or end that process, then try again.",
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Removes the helper lock when its owner is provably gone (dead pid, or a legacy lock nobody answers for).
|
|
313
|
+
async function reclaimStaleHelperLock() {
|
|
314
|
+
const result = await reclaimIfStale({
|
|
315
|
+
lockDir: lock,
|
|
316
|
+
ownerFile: recordPath,
|
|
317
|
+
channel,
|
|
318
|
+
processPattern: SUPERVISOR_PATTERN,
|
|
319
|
+
log: (message) => console.error(`peerband: ${message}`),
|
|
320
|
+
});
|
|
321
|
+
if (result.reclaimed) await resetRelayState(paneStatePath).catch(() => {});
|
|
322
|
+
return result;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Takes the helper lock for `start`. Returns false when a running helper already answered (its status is printed).
|
|
326
|
+
async function acquireForStart() {
|
|
327
|
+
for (let round = 0; round < 3; round++) {
|
|
328
|
+
try {
|
|
329
|
+
await mkdir(lock, { mode: 0o700 });
|
|
330
|
+
return true;
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (error.code !== "EEXIST") throw error;
|
|
333
|
+
}
|
|
334
|
+
let existing = null;
|
|
335
|
+
try { existing = await request("status"); } catch { /* not answering */ }
|
|
336
|
+
if (existing && existing.state === "running") {
|
|
337
|
+
console.log(JSON.stringify(existing));
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
if (existing && existing.state === "stopping") {
|
|
341
|
+
for (let attempt = 0; attempt < 50; attempt++) {
|
|
342
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
343
|
+
try {
|
|
344
|
+
const current = await request("status");
|
|
345
|
+
if (current.state === "running") {
|
|
346
|
+
console.log(JSON.stringify(current));
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
} catch { break; }
|
|
350
|
+
}
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (existing) throw new Error("Existing helper is still changing state.");
|
|
354
|
+
const { reclaimed, verdict } = await reclaimStaleHelperLock();
|
|
355
|
+
if (!reclaimed && verdict.state !== "absent") throw lockError(verdict);
|
|
356
|
+
}
|
|
357
|
+
throw new Error("Existing helper could not be safely restarted.");
|
|
358
|
+
}
|
|
359
|
+
|
|
237
360
|
async function main() {
|
|
238
361
|
const command = process.argv[2];
|
|
239
362
|
if (command === "supervise") {
|
|
@@ -248,55 +371,21 @@ async function main() {
|
|
|
248
371
|
console.log(JSON.stringify(existing));
|
|
249
372
|
return;
|
|
250
373
|
} catch {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
throw new Error("Existing helper lock could not be verified. Inspect the helper before manually clearing a stale lock.");
|
|
254
|
-
} catch (error) {
|
|
255
|
-
if (error.code !== "ENOENT") throw error;
|
|
256
|
-
}
|
|
374
|
+
const { reclaimed, verdict } = await reclaimStaleHelperLock();
|
|
375
|
+
if (!reclaimed && verdict.state !== "absent") throw lockError(verdict);
|
|
257
376
|
}
|
|
258
377
|
await mkdir(lock, { mode: 0o700 });
|
|
259
378
|
const supervisor = spawn(process.execPath, [script, "supervise", "--await-ui"], {
|
|
260
379
|
cwd: config, detached: true, stdio: "ignore", windowsHide: true, shell: false,
|
|
261
380
|
});
|
|
262
381
|
supervisor.unref();
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
catch { await new Promise((resolve) => setTimeout(resolve, 100)); }
|
|
266
|
-
}
|
|
267
|
-
throw new Error("The PeerBand helper did not start. Run `peerband status`, then `peerband login` if you are not logged in.");
|
|
382
|
+
try { console.log(JSON.stringify(await waitForHelper())); return; }
|
|
383
|
+
catch { throw new Error("The PeerBand helper did not start. Run `peerband status`, then `peerband login` if you are not logged in."); }
|
|
268
384
|
}
|
|
269
385
|
if (command === "start" || command === "enable") {
|
|
270
386
|
await assertConnectorEntry();
|
|
271
387
|
await mkdir(config, { recursive: true, mode: 0o700 });
|
|
272
|
-
|
|
273
|
-
await mkdir(lock, { mode: 0o700 });
|
|
274
|
-
} catch (error) {
|
|
275
|
-
if (error.code !== "EEXIST") throw error;
|
|
276
|
-
try {
|
|
277
|
-
const existing = await request("status");
|
|
278
|
-
if (existing.state === "running") {
|
|
279
|
-
console.log(JSON.stringify(existing));
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
if (existing.state === "stopping") {
|
|
283
|
-
for (let attempt = 0; attempt < 50; attempt++) {
|
|
284
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
285
|
-
try {
|
|
286
|
-
const current = await request("status");
|
|
287
|
-
if (current.state === "running") {
|
|
288
|
-
console.log(JSON.stringify(current));
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
} catch { break; }
|
|
292
|
-
}
|
|
293
|
-
await mkdir(lock, { mode: 0o700 });
|
|
294
|
-
} else throw new Error("Existing helper is still changing state.");
|
|
295
|
-
} catch {
|
|
296
|
-
try { await access(lock); } catch { throw new Error("Existing helper could not be safely restarted."); }
|
|
297
|
-
throw new Error("Existing helper lock could not be verified. Inspect the helper before manually clearing a stale lock.");
|
|
298
|
-
}
|
|
299
|
-
}
|
|
388
|
+
if (!(await acquireForStart())) return;
|
|
300
389
|
const supervisor = spawn(process.execPath, [script, "supervise"], {
|
|
301
390
|
cwd: config,
|
|
302
391
|
detached: true,
|
|
@@ -305,17 +394,14 @@ async function main() {
|
|
|
305
394
|
shell: false,
|
|
306
395
|
});
|
|
307
396
|
supervisor.unref();
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
397
|
+
try {
|
|
398
|
+
console.log(JSON.stringify(await waitForHelper()));
|
|
399
|
+
return;
|
|
400
|
+
} catch {
|
|
401
|
+
throw new Error(
|
|
402
|
+
"The PeerBand helper did not start. Run `peerband status`, then `peerband login` if you are not logged in.",
|
|
403
|
+
);
|
|
315
404
|
}
|
|
316
|
-
throw new Error(
|
|
317
|
-
"The PeerBand helper did not start. Run `peerband status`, then `peerband login` if you are not logged in.",
|
|
318
|
-
);
|
|
319
405
|
}
|
|
320
406
|
if (command === "status" || command === "stop" || command === "disable") {
|
|
321
407
|
try {
|