peerband 0.2.9 → 0.3.1
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 +71 -7
- package/dist/peerband.mjs +1677 -360
- package/herdr/lifecycle.mjs +10 -4
- package/herdr-plugin.toml +1 -1
- package/package.json +1 -1
- package/skills/peerband/SKILL.md +31 -3
package/dist/peerband.mjs
CHANGED
|
@@ -21,9 +21,9 @@ var __commonJS = (cb, mod) => function __require2() {
|
|
|
21
21
|
};
|
|
22
22
|
var __copyProps = (to, from, except, desc) => {
|
|
23
23
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
24
|
-
for (let
|
|
25
|
-
if (!__hasOwnProp.call(to,
|
|
26
|
-
__defProp(to,
|
|
24
|
+
for (let key2 of __getOwnPropNames(from))
|
|
25
|
+
if (!__hasOwnProp.call(to, key2) && key2 !== except)
|
|
26
|
+
__defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
|
|
27
27
|
}
|
|
28
28
|
return to;
|
|
29
29
|
};
|
|
@@ -369,44 +369,44 @@ var require_permessage_deflate = __commonJS({
|
|
|
369
369
|
*/
|
|
370
370
|
normalizeParams(configurations) {
|
|
371
371
|
configurations.forEach((params) => {
|
|
372
|
-
Object.keys(params).forEach((
|
|
373
|
-
let value = params[
|
|
372
|
+
Object.keys(params).forEach((key2) => {
|
|
373
|
+
let value = params[key2];
|
|
374
374
|
if (value.length > 1) {
|
|
375
|
-
throw new Error(`Parameter "${
|
|
375
|
+
throw new Error(`Parameter "${key2}" must have only a single value`);
|
|
376
376
|
}
|
|
377
377
|
value = value[0];
|
|
378
|
-
if (
|
|
378
|
+
if (key2 === "client_max_window_bits") {
|
|
379
379
|
if (value !== true) {
|
|
380
380
|
const num = +value;
|
|
381
381
|
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
382
382
|
throw new TypeError(
|
|
383
|
-
`Invalid value for parameter "${
|
|
383
|
+
`Invalid value for parameter "${key2}": ${value}`
|
|
384
384
|
);
|
|
385
385
|
}
|
|
386
386
|
value = num;
|
|
387
387
|
} else if (!this._isServer) {
|
|
388
388
|
throw new TypeError(
|
|
389
|
-
`Invalid value for parameter "${
|
|
389
|
+
`Invalid value for parameter "${key2}": ${value}`
|
|
390
390
|
);
|
|
391
391
|
}
|
|
392
|
-
} else if (
|
|
392
|
+
} else if (key2 === "server_max_window_bits") {
|
|
393
393
|
const num = +value;
|
|
394
394
|
if (!Number.isInteger(num) || num < 8 || num > 15) {
|
|
395
395
|
throw new TypeError(
|
|
396
|
-
`Invalid value for parameter "${
|
|
396
|
+
`Invalid value for parameter "${key2}": ${value}`
|
|
397
397
|
);
|
|
398
398
|
}
|
|
399
399
|
value = num;
|
|
400
|
-
} else if (
|
|
400
|
+
} else if (key2 === "client_no_context_takeover" || key2 === "server_no_context_takeover") {
|
|
401
401
|
if (value !== true) {
|
|
402
402
|
throw new TypeError(
|
|
403
|
-
`Invalid value for parameter "${
|
|
403
|
+
`Invalid value for parameter "${key2}": ${value}`
|
|
404
404
|
);
|
|
405
405
|
}
|
|
406
406
|
} else {
|
|
407
|
-
throw new Error(`Unknown parameter "${
|
|
407
|
+
throw new Error(`Unknown parameter "${key2}"`);
|
|
408
408
|
}
|
|
409
|
-
params[
|
|
409
|
+
params[key2] = value;
|
|
410
410
|
});
|
|
411
411
|
});
|
|
412
412
|
return configurations;
|
|
@@ -454,8 +454,8 @@ var require_permessage_deflate = __commonJS({
|
|
|
454
454
|
_decompress(data, fin, callback) {
|
|
455
455
|
const endpoint = this._isServer ? "client" : "server";
|
|
456
456
|
if (!this._inflate) {
|
|
457
|
-
const
|
|
458
|
-
const windowBits = typeof this.params[
|
|
457
|
+
const key2 = `${endpoint}_max_window_bits`;
|
|
458
|
+
const windowBits = typeof this.params[key2] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key2];
|
|
459
459
|
this._inflate = zlib.createInflateRaw({
|
|
460
460
|
...this._options.zlibInflateOptions,
|
|
461
461
|
windowBits
|
|
@@ -505,8 +505,8 @@ var require_permessage_deflate = __commonJS({
|
|
|
505
505
|
_compress(data, fin, callback) {
|
|
506
506
|
const endpoint = this._isServer ? "server" : "client";
|
|
507
507
|
if (!this._deflate) {
|
|
508
|
-
const
|
|
509
|
-
const windowBits = typeof this.params[
|
|
508
|
+
const key2 = `${endpoint}_max_window_bits`;
|
|
509
|
+
const windowBits = typeof this.params[key2] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key2];
|
|
510
510
|
this._deflate = zlib.createDeflateRaw({
|
|
511
511
|
...this._options.zlibDeflateOptions,
|
|
512
512
|
windowBits
|
|
@@ -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: createHash6 } = __require("crypto");
|
|
2279
2279
|
var { Duplex, Readable } = __require("stream");
|
|
2280
2280
|
var { URL: URL2 } = __require("url");
|
|
2281
2281
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -2826,7 +2826,7 @@ var require_websocket = __commonJS({
|
|
|
2826
2826
|
}
|
|
2827
2827
|
}
|
|
2828
2828
|
const defaultPort = isSecure ? 443 : 80;
|
|
2829
|
-
const
|
|
2829
|
+
const key2 = randomBytes(16).toString("base64");
|
|
2830
2830
|
const request = isSecure ? https.request : http.request;
|
|
2831
2831
|
const protocolSet = /* @__PURE__ */ new Set();
|
|
2832
2832
|
let perMessageDeflate;
|
|
@@ -2837,7 +2837,7 @@ var require_websocket = __commonJS({
|
|
|
2837
2837
|
opts.headers = {
|
|
2838
2838
|
...opts.headers,
|
|
2839
2839
|
"Sec-WebSocket-Version": opts.protocolVersion,
|
|
2840
|
-
"Sec-WebSocket-Key":
|
|
2840
|
+
"Sec-WebSocket-Key": key2,
|
|
2841
2841
|
Connection: "Upgrade",
|
|
2842
2842
|
Upgrade: "websocket"
|
|
2843
2843
|
};
|
|
@@ -2888,8 +2888,8 @@ var require_websocket = __commonJS({
|
|
|
2888
2888
|
const headers = options && options.headers;
|
|
2889
2889
|
options = { ...options, headers: {} };
|
|
2890
2890
|
if (headers) {
|
|
2891
|
-
for (const [
|
|
2892
|
-
options.headers[
|
|
2891
|
+
for (const [key3, value] of Object.entries(headers)) {
|
|
2892
|
+
options.headers[key3.toLowerCase()] = value;
|
|
2893
2893
|
}
|
|
2894
2894
|
}
|
|
2895
2895
|
} else if (websocket.listenerCount("redirect") === 0) {
|
|
@@ -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 = createHash6("sha1").update(key2 + 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;
|
|
@@ -3247,7 +3247,7 @@ var require_stream = __commonJS({
|
|
|
3247
3247
|
callback();
|
|
3248
3248
|
if (duplex._readableState.endEmitted) duplex.destroy();
|
|
3249
3249
|
} else {
|
|
3250
|
-
ws._socket.once("finish", function
|
|
3250
|
+
ws._socket.once("finish", function finish2() {
|
|
3251
3251
|
callback();
|
|
3252
3252
|
});
|
|
3253
3253
|
ws.close();
|
|
@@ -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: createHash6 } = __require("crypto");
|
|
3329
3329
|
var extension2 = require_extension();
|
|
3330
3330
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
3331
3331
|
var subprotocol2 = require_subprotocol();
|
|
@@ -3524,7 +3524,7 @@ var require_websocket_server = __commonJS({
|
|
|
3524
3524
|
*/
|
|
3525
3525
|
handleUpgrade(req, socket, head, cb) {
|
|
3526
3526
|
socket.on("error", socketOnError);
|
|
3527
|
-
const
|
|
3527
|
+
const key2 = req.headers["sec-websocket-key"];
|
|
3528
3528
|
const upgrade = req.headers.upgrade;
|
|
3529
3529
|
const version = +req.headers["sec-websocket-version"];
|
|
3530
3530
|
if (req.method !== "GET") {
|
|
@@ -3537,7 +3537,7 @@ var require_websocket_server = __commonJS({
|
|
|
3537
3537
|
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3538
3538
|
return;
|
|
3539
3539
|
}
|
|
3540
|
-
if (
|
|
3540
|
+
if (key2 === void 0 || !keyRegex.test(key2)) {
|
|
3541
3541
|
const message = "Missing or invalid Sec-WebSocket-Key header";
|
|
3542
3542
|
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
|
|
3543
3543
|
return;
|
|
@@ -3597,7 +3597,7 @@ var require_websocket_server = __commonJS({
|
|
|
3597
3597
|
}
|
|
3598
3598
|
this.completeUpgrade(
|
|
3599
3599
|
extensions,
|
|
3600
|
-
|
|
3600
|
+
key2,
|
|
3601
3601
|
protocols,
|
|
3602
3602
|
req,
|
|
3603
3603
|
socket,
|
|
@@ -3609,7 +3609,7 @@ var require_websocket_server = __commonJS({
|
|
|
3609
3609
|
}
|
|
3610
3610
|
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
|
|
3611
3611
|
}
|
|
3612
|
-
this.completeUpgrade(extensions,
|
|
3612
|
+
this.completeUpgrade(extensions, key2, protocols, req, socket, head, cb);
|
|
3613
3613
|
}
|
|
3614
3614
|
/**
|
|
3615
3615
|
* Upgrade the connection to WebSocket.
|
|
@@ -3624,7 +3624,7 @@ var require_websocket_server = __commonJS({
|
|
|
3624
3624
|
* @throws {Error} If called more than once with the same socket
|
|
3625
3625
|
* @private
|
|
3626
3626
|
*/
|
|
3627
|
-
completeUpgrade(extensions,
|
|
3627
|
+
completeUpgrade(extensions, key2, protocols, req, socket, head, cb) {
|
|
3628
3628
|
if (!socket.readable || !socket.writable) return socket.destroy();
|
|
3629
3629
|
if (socket[kWebSocket]) {
|
|
3630
3630
|
throw new Error(
|
|
@@ -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 = createHash6("sha1").update(key2 + GUID).digest("base64");
|
|
3636
3636
|
const headers = [
|
|
3637
3637
|
"HTTP/1.1 101 Switching Protocols",
|
|
3638
3638
|
"Upgrade: websocket",
|
|
@@ -4058,15 +4058,15 @@ var require_code = __commonJS({
|
|
|
4058
4058
|
return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
4059
4059
|
}
|
|
4060
4060
|
exports.safeStringify = safeStringify;
|
|
4061
|
-
function getProperty(
|
|
4062
|
-
return typeof
|
|
4061
|
+
function getProperty(key2) {
|
|
4062
|
+
return typeof key2 == "string" && exports.IDENTIFIER.test(key2) ? new _Code(`.${key2}`) : _`[${key2}]`;
|
|
4063
4063
|
}
|
|
4064
4064
|
exports.getProperty = getProperty;
|
|
4065
|
-
function getEsmExportName(
|
|
4066
|
-
if (typeof
|
|
4067
|
-
return new _Code(`${
|
|
4065
|
+
function getEsmExportName(key2) {
|
|
4066
|
+
if (typeof key2 == "string" && exports.IDENTIFIER.test(key2)) {
|
|
4067
|
+
return new _Code(`${key2}`);
|
|
4068
4068
|
}
|
|
4069
|
-
throw new Error(`CodeGen: invalid export name: ${
|
|
4069
|
+
throw new Error(`CodeGen: invalid export name: ${key2}, use explicit $id name mapping`);
|
|
4070
4070
|
}
|
|
4071
4071
|
exports.getEsmExportName = getEsmExportName;
|
|
4072
4072
|
function regexpCode(rx) {
|
|
@@ -4693,11 +4693,11 @@ var require_codegen = __commonJS({
|
|
|
4693
4693
|
// returns code for object literal for the passed argument list of key-value pairs
|
|
4694
4694
|
object(...keyValues) {
|
|
4695
4695
|
const code = ["{"];
|
|
4696
|
-
for (const [
|
|
4696
|
+
for (const [key2, value] of keyValues) {
|
|
4697
4697
|
if (code.length > 1)
|
|
4698
4698
|
code.push(",");
|
|
4699
|
-
code.push(
|
|
4700
|
-
if (
|
|
4699
|
+
code.push(key2);
|
|
4700
|
+
if (key2 !== value || this.opts.es5) {
|
|
4701
4701
|
code.push(":");
|
|
4702
4702
|
(0, code_1.addCodeArg)(code, value);
|
|
4703
4703
|
}
|
|
@@ -4972,17 +4972,17 @@ var require_util = __commonJS({
|
|
|
4972
4972
|
if (typeof schema === "boolean")
|
|
4973
4973
|
return;
|
|
4974
4974
|
const rules = self.RULES.keywords;
|
|
4975
|
-
for (const
|
|
4976
|
-
if (!rules[
|
|
4977
|
-
checkStrictMode(it, `unknown keyword: "${
|
|
4975
|
+
for (const key2 in schema) {
|
|
4976
|
+
if (!rules[key2])
|
|
4977
|
+
checkStrictMode(it, `unknown keyword: "${key2}"`);
|
|
4978
4978
|
}
|
|
4979
4979
|
}
|
|
4980
4980
|
exports.checkUnknownRules = checkUnknownRules;
|
|
4981
4981
|
function schemaHasRules(schema, rules) {
|
|
4982
4982
|
if (typeof schema == "boolean")
|
|
4983
4983
|
return !schema;
|
|
4984
|
-
for (const
|
|
4985
|
-
if (rules[
|
|
4984
|
+
for (const key2 in schema)
|
|
4985
|
+
if (rules[key2])
|
|
4986
4986
|
return true;
|
|
4987
4987
|
return false;
|
|
4988
4988
|
}
|
|
@@ -4990,8 +4990,8 @@ var require_util = __commonJS({
|
|
|
4990
4990
|
function schemaHasRulesButRef(schema, RULES) {
|
|
4991
4991
|
if (typeof schema == "boolean")
|
|
4992
4992
|
return !schema;
|
|
4993
|
-
for (const
|
|
4994
|
-
if (
|
|
4993
|
+
for (const key2 in schema)
|
|
4994
|
+
if (key2 !== "$ref" && RULES.all[key2])
|
|
4995
4995
|
return true;
|
|
4996
4996
|
return false;
|
|
4997
4997
|
}
|
|
@@ -5569,8 +5569,8 @@ var require_defaults = __commonJS({
|
|
|
5569
5569
|
function assignDefaults(it, ty) {
|
|
5570
5570
|
const { properties, items } = it.schema;
|
|
5571
5571
|
if (ty === "object" && properties) {
|
|
5572
|
-
for (const
|
|
5573
|
-
assignDefault(it,
|
|
5572
|
+
for (const key2 in properties) {
|
|
5573
|
+
assignDefault(it, key2, properties[key2].default);
|
|
5574
5574
|
}
|
|
5575
5575
|
} else if (ty === "array" && Array.isArray(items)) {
|
|
5576
5576
|
items.forEach((sch, i) => assignDefault(it, i, sch.default));
|
|
@@ -5954,8 +5954,8 @@ var require_fast_deep_equal = __commonJS({
|
|
|
5954
5954
|
for (i = length; i-- !== 0; )
|
|
5955
5955
|
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
|
|
5956
5956
|
for (i = length; i-- !== 0; ) {
|
|
5957
|
-
var
|
|
5958
|
-
if (!equal(a[
|
|
5957
|
+
var key2 = keys[i];
|
|
5958
|
+
if (!equal(a[key2], b[key2])) return false;
|
|
5959
5959
|
}
|
|
5960
5960
|
return true;
|
|
5961
5961
|
}
|
|
@@ -6027,20 +6027,20 @@ var require_json_schema_traverse = __commonJS({
|
|
|
6027
6027
|
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
|
|
6028
6028
|
if (schema && typeof schema == "object" && !Array.isArray(schema)) {
|
|
6029
6029
|
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
6030
|
-
for (var
|
|
6031
|
-
var sch = schema[
|
|
6030
|
+
for (var key2 in schema) {
|
|
6031
|
+
var sch = schema[key2];
|
|
6032
6032
|
if (Array.isArray(sch)) {
|
|
6033
|
-
if (
|
|
6033
|
+
if (key2 in traverse.arrayKeywords) {
|
|
6034
6034
|
for (var i = 0; i < sch.length; i++)
|
|
6035
|
-
_traverse(opts, pre, post, sch[i], jsonPtr + "/" +
|
|
6035
|
+
_traverse(opts, pre, post, sch[i], jsonPtr + "/" + key2 + "/" + i, rootSchema, jsonPtr, key2, schema, i);
|
|
6036
6036
|
}
|
|
6037
|
-
} else if (
|
|
6037
|
+
} else if (key2 in traverse.propsKeywords) {
|
|
6038
6038
|
if (sch && typeof sch == "object") {
|
|
6039
6039
|
for (var prop in sch)
|
|
6040
|
-
_traverse(opts, pre, post, sch[prop], jsonPtr + "/" +
|
|
6040
|
+
_traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key2 + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key2, schema, prop);
|
|
6041
6041
|
}
|
|
6042
|
-
} else if (
|
|
6043
|
-
_traverse(opts, pre, post, sch, jsonPtr + "/" +
|
|
6042
|
+
} else if (key2 in traverse.keywords || opts.allKeys && !(key2 in traverse.skipKeywords)) {
|
|
6043
|
+
_traverse(opts, pre, post, sch, jsonPtr + "/" + key2, rootSchema, jsonPtr, key2, schema);
|
|
6044
6044
|
}
|
|
6045
6045
|
}
|
|
6046
6046
|
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
@@ -6097,10 +6097,10 @@ var require_resolve = __commonJS({
|
|
|
6097
6097
|
"$dynamicAnchor"
|
|
6098
6098
|
]);
|
|
6099
6099
|
function hasRef(schema) {
|
|
6100
|
-
for (const
|
|
6101
|
-
if (REF_KEYWORDS.has(
|
|
6100
|
+
for (const key2 in schema) {
|
|
6101
|
+
if (REF_KEYWORDS.has(key2))
|
|
6102
6102
|
return true;
|
|
6103
|
-
const sch = schema[
|
|
6103
|
+
const sch = schema[key2];
|
|
6104
6104
|
if (Array.isArray(sch) && sch.some(hasRef))
|
|
6105
6105
|
return true;
|
|
6106
6106
|
if (typeof sch == "object" && hasRef(sch))
|
|
@@ -6110,14 +6110,14 @@ var require_resolve = __commonJS({
|
|
|
6110
6110
|
}
|
|
6111
6111
|
function countKeys(schema) {
|
|
6112
6112
|
let count = 0;
|
|
6113
|
-
for (const
|
|
6114
|
-
if (
|
|
6113
|
+
for (const key2 in schema) {
|
|
6114
|
+
if (key2 === "$ref")
|
|
6115
6115
|
return Infinity;
|
|
6116
6116
|
count++;
|
|
6117
|
-
if (SIMPLE_INLINED.has(
|
|
6117
|
+
if (SIMPLE_INLINED.has(key2))
|
|
6118
6118
|
continue;
|
|
6119
|
-
if (typeof schema[
|
|
6120
|
-
(0, util_1.eachItem)(schema[
|
|
6119
|
+
if (typeof schema[key2] == "object") {
|
|
6120
|
+
(0, util_1.eachItem)(schema[key2], (sch) => count += countKeys(sch));
|
|
6121
6121
|
}
|
|
6122
6122
|
if (count === Infinity)
|
|
6123
6123
|
return Infinity;
|
|
@@ -6306,8 +6306,8 @@ var require_validate = __commonJS({
|
|
|
6306
6306
|
function schemaCxtHasRules({ schema, self }) {
|
|
6307
6307
|
if (typeof schema == "boolean")
|
|
6308
6308
|
return !schema;
|
|
6309
|
-
for (const
|
|
6310
|
-
if (self.RULES.all[
|
|
6309
|
+
for (const key2 in schema)
|
|
6310
|
+
if (self.RULES.all[key2])
|
|
6311
6311
|
return true;
|
|
6312
6312
|
return false;
|
|
6313
6313
|
}
|
|
@@ -6873,7 +6873,7 @@ var require_compile = __commonJS({
|
|
|
6873
6873
|
const schOrFunc = root.refs[ref];
|
|
6874
6874
|
if (schOrFunc)
|
|
6875
6875
|
return schOrFunc;
|
|
6876
|
-
let _sch =
|
|
6876
|
+
let _sch = resolve6.call(this, root, ref);
|
|
6877
6877
|
if (_sch === void 0) {
|
|
6878
6878
|
const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
|
|
6879
6879
|
const { schemaId } = this.opts;
|
|
@@ -6900,7 +6900,7 @@ var require_compile = __commonJS({
|
|
|
6900
6900
|
function sameSchemaEnv(s1, s2) {
|
|
6901
6901
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
6902
6902
|
}
|
|
6903
|
-
function
|
|
6903
|
+
function resolve6(root, ref) {
|
|
6904
6904
|
let sch;
|
|
6905
6905
|
while (typeof (sch = this.refs[ref]) == "string")
|
|
6906
6906
|
ref = sch;
|
|
@@ -7730,7 +7730,7 @@ var require_fast_uri = __commonJS({
|
|
|
7730
7730
|
}
|
|
7731
7731
|
return uri;
|
|
7732
7732
|
}
|
|
7733
|
-
function
|
|
7733
|
+
function resolve6(baseURI, relativeURI, options) {
|
|
7734
7734
|
const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
|
|
7735
7735
|
const {
|
|
7736
7736
|
parsed: baseParsed,
|
|
@@ -8099,7 +8099,7 @@ var require_fast_uri = __commonJS({
|
|
|
8099
8099
|
var fastUri = {
|
|
8100
8100
|
SCHEMES,
|
|
8101
8101
|
normalize,
|
|
8102
|
-
resolve:
|
|
8102
|
+
resolve: resolve6,
|
|
8103
8103
|
resolveComponent,
|
|
8104
8104
|
equal,
|
|
8105
8105
|
serialize,
|
|
@@ -8346,7 +8346,7 @@ var require_core = __commonJS({
|
|
|
8346
8346
|
}
|
|
8347
8347
|
}
|
|
8348
8348
|
// Adds schema to the instance
|
|
8349
|
-
addSchema(schema,
|
|
8349
|
+
addSchema(schema, key2, _meta, _validateSchema = this.opts.validateSchema) {
|
|
8350
8350
|
if (Array.isArray(schema)) {
|
|
8351
8351
|
for (const sch of schema)
|
|
8352
8352
|
this.addSchema(sch, void 0, _meta, _validateSchema);
|
|
@@ -8360,15 +8360,15 @@ var require_core = __commonJS({
|
|
|
8360
8360
|
throw new Error(`schema ${schemaId} must be string`);
|
|
8361
8361
|
}
|
|
8362
8362
|
}
|
|
8363
|
-
|
|
8364
|
-
this._checkUnique(
|
|
8365
|
-
this.schemas[
|
|
8363
|
+
key2 = (0, resolve_1.normalizeId)(key2 || id);
|
|
8364
|
+
this._checkUnique(key2);
|
|
8365
|
+
this.schemas[key2] = this._addSchema(schema, _meta, key2, _validateSchema, true);
|
|
8366
8366
|
return this;
|
|
8367
8367
|
}
|
|
8368
8368
|
// Add schema that will be used to validate other schemas
|
|
8369
8369
|
// options in META_IGNORE_OPTIONS are alway set to false
|
|
8370
|
-
addMetaSchema(schema,
|
|
8371
|
-
this.addSchema(schema,
|
|
8370
|
+
addMetaSchema(schema, key2, _validateSchema = this.opts.validateSchema) {
|
|
8371
|
+
this.addSchema(schema, key2, true, _validateSchema);
|
|
8372
8372
|
return this;
|
|
8373
8373
|
}
|
|
8374
8374
|
// Validate schema against its meta-schema
|
|
@@ -8524,14 +8524,14 @@ var require_core = __commonJS({
|
|
|
8524
8524
|
let keywords = metaSchema;
|
|
8525
8525
|
for (const seg of segments)
|
|
8526
8526
|
keywords = keywords[seg];
|
|
8527
|
-
for (const
|
|
8528
|
-
const rule = rules[
|
|
8527
|
+
for (const key2 in rules) {
|
|
8528
|
+
const rule = rules[key2];
|
|
8529
8529
|
if (typeof rule != "object")
|
|
8530
8530
|
continue;
|
|
8531
8531
|
const { $data } = rule.definition;
|
|
8532
|
-
const schema = keywords[
|
|
8532
|
+
const schema = keywords[key2];
|
|
8533
8533
|
if ($data && schema)
|
|
8534
|
-
keywords[
|
|
8534
|
+
keywords[key2] = schemaOrData(schema);
|
|
8535
8535
|
}
|
|
8536
8536
|
}
|
|
8537
8537
|
return metaSchema;
|
|
@@ -8604,10 +8604,10 @@ var require_core = __commonJS({
|
|
|
8604
8604
|
Ajv.MissingRefError = ref_error_1.default;
|
|
8605
8605
|
exports.default = Ajv;
|
|
8606
8606
|
function checkOptions(checkOpts, options, msg, log = "error") {
|
|
8607
|
-
for (const
|
|
8608
|
-
const opt =
|
|
8607
|
+
for (const key2 in checkOpts) {
|
|
8608
|
+
const opt = key2;
|
|
8609
8609
|
if (opt in options)
|
|
8610
|
-
this.logger[log](`${msg}: option ${
|
|
8610
|
+
this.logger[log](`${msg}: option ${key2}. ${checkOpts[opt]}`);
|
|
8611
8611
|
}
|
|
8612
8612
|
}
|
|
8613
8613
|
function getSchEnv(keyRef) {
|
|
@@ -8621,8 +8621,8 @@ var require_core = __commonJS({
|
|
|
8621
8621
|
if (Array.isArray(optsSchemas))
|
|
8622
8622
|
this.addSchema(optsSchemas);
|
|
8623
8623
|
else
|
|
8624
|
-
for (const
|
|
8625
|
-
this.addSchema(optsSchemas[
|
|
8624
|
+
for (const key2 in optsSchemas)
|
|
8625
|
+
this.addSchema(optsSchemas[key2], key2);
|
|
8626
8626
|
}
|
|
8627
8627
|
function addInitialFormats() {
|
|
8628
8628
|
for (const name in this.opts.formats) {
|
|
@@ -9670,11 +9670,11 @@ var require_dependencies = __commonJS({
|
|
|
9670
9670
|
function splitDependencies({ schema }) {
|
|
9671
9671
|
const propertyDeps = {};
|
|
9672
9672
|
const schemaDeps = {};
|
|
9673
|
-
for (const
|
|
9674
|
-
if (
|
|
9673
|
+
for (const key2 in schema) {
|
|
9674
|
+
if (key2 === "__proto__")
|
|
9675
9675
|
continue;
|
|
9676
|
-
const deps = Array.isArray(schema[
|
|
9677
|
-
deps[
|
|
9676
|
+
const deps = Array.isArray(schema[key2]) ? propertyDeps : schemaDeps;
|
|
9677
|
+
deps[key2] = schema[key2];
|
|
9678
9678
|
}
|
|
9679
9679
|
return [propertyDeps, schemaDeps];
|
|
9680
9680
|
}
|
|
@@ -9751,13 +9751,13 @@ var require_propertyNames = __commonJS({
|
|
|
9751
9751
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
9752
9752
|
return;
|
|
9753
9753
|
const valid = gen.name("valid");
|
|
9754
|
-
gen.forIn("key", data, (
|
|
9755
|
-
cxt.setParams({ propertyName:
|
|
9754
|
+
gen.forIn("key", data, (key2) => {
|
|
9755
|
+
cxt.setParams({ propertyName: key2 });
|
|
9756
9756
|
cxt.subschema({
|
|
9757
9757
|
keyword: "propertyNames",
|
|
9758
|
-
data:
|
|
9758
|
+
data: key2,
|
|
9759
9759
|
dataTypes: ["string"],
|
|
9760
|
-
propertyName:
|
|
9760
|
+
propertyName: key2,
|
|
9761
9761
|
compositeRule: true
|
|
9762
9762
|
}, valid);
|
|
9763
9763
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
@@ -9806,38 +9806,38 @@ var require_additionalProperties = __commonJS({
|
|
|
9806
9806
|
checkAdditionalProperties();
|
|
9807
9807
|
cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
|
|
9808
9808
|
function checkAdditionalProperties() {
|
|
9809
|
-
gen.forIn("key", data, (
|
|
9809
|
+
gen.forIn("key", data, (key2) => {
|
|
9810
9810
|
if (!props.length && !patProps.length)
|
|
9811
|
-
additionalPropertyCode(
|
|
9811
|
+
additionalPropertyCode(key2);
|
|
9812
9812
|
else
|
|
9813
|
-
gen.if(isAdditional(
|
|
9813
|
+
gen.if(isAdditional(key2), () => additionalPropertyCode(key2));
|
|
9814
9814
|
});
|
|
9815
9815
|
}
|
|
9816
|
-
function isAdditional(
|
|
9816
|
+
function isAdditional(key2) {
|
|
9817
9817
|
let definedProp;
|
|
9818
9818
|
if (props.length > 8) {
|
|
9819
9819
|
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
|
|
9820
|
-
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema,
|
|
9820
|
+
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key2);
|
|
9821
9821
|
} else if (props.length) {
|
|
9822
|
-
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${
|
|
9822
|
+
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key2} === ${p}`));
|
|
9823
9823
|
} else {
|
|
9824
9824
|
definedProp = codegen_1.nil;
|
|
9825
9825
|
}
|
|
9826
9826
|
if (patProps.length) {
|
|
9827
|
-
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${
|
|
9827
|
+
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key2})`));
|
|
9828
9828
|
}
|
|
9829
9829
|
return (0, codegen_1.not)(definedProp);
|
|
9830
9830
|
}
|
|
9831
|
-
function deleteAdditional(
|
|
9832
|
-
gen.code((0, codegen_1._)`delete ${data}[${
|
|
9831
|
+
function deleteAdditional(key2) {
|
|
9832
|
+
gen.code((0, codegen_1._)`delete ${data}[${key2}]`);
|
|
9833
9833
|
}
|
|
9834
|
-
function additionalPropertyCode(
|
|
9834
|
+
function additionalPropertyCode(key2) {
|
|
9835
9835
|
if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
|
|
9836
|
-
deleteAdditional(
|
|
9836
|
+
deleteAdditional(key2);
|
|
9837
9837
|
return;
|
|
9838
9838
|
}
|
|
9839
9839
|
if (schema === false) {
|
|
9840
|
-
cxt.setParams({ additionalProperty:
|
|
9840
|
+
cxt.setParams({ additionalProperty: key2 });
|
|
9841
9841
|
cxt.error();
|
|
9842
9842
|
if (!allErrors)
|
|
9843
9843
|
gen.break();
|
|
@@ -9846,22 +9846,22 @@ var require_additionalProperties = __commonJS({
|
|
|
9846
9846
|
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
9847
9847
|
const valid = gen.name("valid");
|
|
9848
9848
|
if (opts.removeAdditional === "failing") {
|
|
9849
|
-
applyAdditionalSchema(
|
|
9849
|
+
applyAdditionalSchema(key2, valid, false);
|
|
9850
9850
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
9851
9851
|
cxt.reset();
|
|
9852
|
-
deleteAdditional(
|
|
9852
|
+
deleteAdditional(key2);
|
|
9853
9853
|
});
|
|
9854
9854
|
} else {
|
|
9855
|
-
applyAdditionalSchema(
|
|
9855
|
+
applyAdditionalSchema(key2, valid);
|
|
9856
9856
|
if (!allErrors)
|
|
9857
9857
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
9858
9858
|
}
|
|
9859
9859
|
}
|
|
9860
9860
|
}
|
|
9861
|
-
function applyAdditionalSchema(
|
|
9861
|
+
function applyAdditionalSchema(key2, valid, errors) {
|
|
9862
9862
|
const subschema = {
|
|
9863
9863
|
keyword: "additionalProperties",
|
|
9864
|
-
dataProp:
|
|
9864
|
+
dataProp: key2,
|
|
9865
9865
|
dataPropType: util_1.Type.Str
|
|
9866
9866
|
};
|
|
9867
9867
|
if (errors === false) {
|
|
@@ -9986,19 +9986,19 @@ var require_patternProperties = __commonJS({
|
|
|
9986
9986
|
}
|
|
9987
9987
|
}
|
|
9988
9988
|
function validateProperties(pat) {
|
|
9989
|
-
gen.forIn("key", data, (
|
|
9990
|
-
gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${
|
|
9989
|
+
gen.forIn("key", data, (key2) => {
|
|
9990
|
+
gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key2})`, () => {
|
|
9991
9991
|
const alwaysValid = alwaysValidPatterns.includes(pat);
|
|
9992
9992
|
if (!alwaysValid) {
|
|
9993
9993
|
cxt.subschema({
|
|
9994
9994
|
keyword: "patternProperties",
|
|
9995
9995
|
schemaProp: pat,
|
|
9996
|
-
dataProp:
|
|
9996
|
+
dataProp: key2,
|
|
9997
9997
|
dataPropType: util_2.Type.Str
|
|
9998
9998
|
}, valid);
|
|
9999
9999
|
}
|
|
10000
10000
|
if (it.opts.unevaluated && props !== true) {
|
|
10001
|
-
gen.assign((0, codegen_1._)`${props}[${
|
|
10001
|
+
gen.assign((0, codegen_1._)`${props}[${key2}]`, true);
|
|
10002
10002
|
} else if (!alwaysValid && !it.allErrors) {
|
|
10003
10003
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
10004
10004
|
}
|
|
@@ -11106,15 +11106,15 @@ var require_unevaluatedProperties = __commonJS({
|
|
|
11106
11106
|
throw new Error("ajv implementation error");
|
|
11107
11107
|
const { allErrors, props } = it;
|
|
11108
11108
|
if (props instanceof codegen_1.Name) {
|
|
11109
|
-
gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (
|
|
11109
|
+
gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key2) => gen.if(unevaluatedDynamic(props, key2), () => unevaluatedPropCode(key2))));
|
|
11110
11110
|
} else if (props !== true) {
|
|
11111
|
-
gen.forIn("key", data, (
|
|
11111
|
+
gen.forIn("key", data, (key2) => props === void 0 ? unevaluatedPropCode(key2) : gen.if(unevaluatedStatic(props, key2), () => unevaluatedPropCode(key2)));
|
|
11112
11112
|
}
|
|
11113
11113
|
it.props = true;
|
|
11114
11114
|
cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
|
|
11115
|
-
function unevaluatedPropCode(
|
|
11115
|
+
function unevaluatedPropCode(key2) {
|
|
11116
11116
|
if (schema === false) {
|
|
11117
|
-
cxt.setParams({ unevaluatedProperty:
|
|
11117
|
+
cxt.setParams({ unevaluatedProperty: key2 });
|
|
11118
11118
|
cxt.error();
|
|
11119
11119
|
if (!allErrors)
|
|
11120
11120
|
gen.break();
|
|
@@ -11124,21 +11124,21 @@ var require_unevaluatedProperties = __commonJS({
|
|
|
11124
11124
|
const valid = gen.name("valid");
|
|
11125
11125
|
cxt.subschema({
|
|
11126
11126
|
keyword: "unevaluatedProperties",
|
|
11127
|
-
dataProp:
|
|
11127
|
+
dataProp: key2,
|
|
11128
11128
|
dataPropType: util_1.Type.Str
|
|
11129
11129
|
}, valid);
|
|
11130
11130
|
if (!allErrors)
|
|
11131
11131
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
11132
11132
|
}
|
|
11133
11133
|
}
|
|
11134
|
-
function unevaluatedDynamic(evaluatedProps,
|
|
11135
|
-
return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${
|
|
11134
|
+
function unevaluatedDynamic(evaluatedProps, key2) {
|
|
11135
|
+
return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key2}]`;
|
|
11136
11136
|
}
|
|
11137
|
-
function unevaluatedStatic(evaluatedProps,
|
|
11137
|
+
function unevaluatedStatic(evaluatedProps, key2) {
|
|
11138
11138
|
const ps = [];
|
|
11139
11139
|
for (const p in evaluatedProps) {
|
|
11140
11140
|
if (evaluatedProps[p] === true)
|
|
11141
|
-
ps.push((0, codegen_1._)`${
|
|
11141
|
+
ps.push((0, codegen_1._)`${key2} !== ${p}`);
|
|
11142
11142
|
}
|
|
11143
11143
|
return (0, codegen_1.and)(...ps);
|
|
11144
11144
|
}
|
|
@@ -11768,19 +11768,19 @@ function invalid(message) {
|
|
|
11768
11768
|
function environmentCommand(args) {
|
|
11769
11769
|
const action = args.action;
|
|
11770
11770
|
if (!ENVIRONMENT_ACTIONS.includes(action)) invalid("Unsupported environment action.");
|
|
11771
|
-
for (const
|
|
11772
|
-
if (
|
|
11773
|
-
const value = args[
|
|
11774
|
-
const max =
|
|
11775
|
-
if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f-\u009f]/.test(value)) invalid(`Invalid ${
|
|
11776
|
-
if (
|
|
11777
|
-
}
|
|
11778
|
-
for (const
|
|
11771
|
+
for (const key2 of Object.keys(args)) {
|
|
11772
|
+
if (key2 !== "action" && !FIELDS[action].includes(key2)) invalid(`Unexpected argument: ${key2}.`);
|
|
11773
|
+
const value = args[key2];
|
|
11774
|
+
const max = key2 === "cwd" ? 2048 : key2 === "text" ? 4096 : key2 === "label" ? 128 : 256;
|
|
11775
|
+
if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f-\u009f]/.test(value)) invalid(`Invalid ${key2}.`);
|
|
11776
|
+
if (key2.endsWith("Id") && !/^[A-Za-z0-9][A-Za-z0-9:_-]{0,255}$/.test(value)) invalid(`Invalid ${key2}.`);
|
|
11777
|
+
}
|
|
11778
|
+
for (const key2 of REQUIRED[action]) if (args[key2] === void 0) invalid(`${key2} is required.`);
|
|
11779
11779
|
if (args.cwd !== void 0 && !/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(args.cwd)) invalid("cwd must be an absolute path on the remote machine.");
|
|
11780
11780
|
if (args.direction !== void 0 && !["right", "down", "left", "up"].includes(args.direction)) invalid("Invalid split direction.");
|
|
11781
11781
|
if (args.name !== void 0 && !/^[a-z][a-z0-9_-]{0,31}$/.test(args.name)) invalid("Invalid agent name.");
|
|
11782
11782
|
if (args.kind !== void 0 && !KINDS.has(args.kind)) invalid("Unsupported agent kind.");
|
|
11783
|
-
return Object.fromEntries(["action", ...FIELDS[action]].filter((
|
|
11783
|
+
return Object.fromEntries(["action", ...FIELDS[action]].filter((key2) => args[key2] !== void 0).map((key2) => [key2, args[key2]]));
|
|
11784
11784
|
}
|
|
11785
11785
|
|
|
11786
11786
|
// src/core/core.ts
|
|
@@ -11847,7 +11847,7 @@ var MockRuntime = class {
|
|
|
11847
11847
|
machineId;
|
|
11848
11848
|
constructor(machineId = "mock-machine") {
|
|
11849
11849
|
this.machineId = machineId;
|
|
11850
|
-
const
|
|
11850
|
+
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
11851
11851
|
const seed = [
|
|
11852
11852
|
{ runtime: "mock", agentType: "codex", label: "Codex \xB7 api", workspace: "demo/api", status: "working", rawStatus: "working" },
|
|
11853
11853
|
{ runtime: "mock", agentType: "claude", label: "Claude \xB7 docs", workspace: "demo/docs", status: "idle", rawStatus: "idle" },
|
|
@@ -11855,7 +11855,7 @@ var MockRuntime = class {
|
|
|
11855
11855
|
];
|
|
11856
11856
|
for (const [index, base] of seed.entries()) {
|
|
11857
11857
|
const id = `mock-${hash(`${machineId}:${index}`).slice(0, 24)}`;
|
|
11858
|
-
this.agents.set(id, { ...base, id, machineId, observedAt:
|
|
11858
|
+
this.agents.set(id, { ...base, id, machineId, observedAt: now2, stale: false, capabilities: { readOutput: true, sendMessage: true } });
|
|
11859
11859
|
this.output.set(id, [`${base.label} is ${base.status}.`, "Recent activity is demo data."].join("\n"));
|
|
11860
11860
|
}
|
|
11861
11861
|
}
|
|
@@ -11922,11 +11922,15 @@ Message received: ${message}`.trim());
|
|
|
11922
11922
|
};
|
|
11923
11923
|
var EMAIL = /^[^\s@<>()[\]\\,;:"]{1,64}@[A-Za-z0-9.-]{1,190}$/;
|
|
11924
11924
|
var APP = /^[A-Za-z0-9][A-Za-z0-9 ._+-]{0,31}$/;
|
|
11925
|
+
var CLI_APP = "PeerBand CLI";
|
|
11925
11926
|
function via(principal) {
|
|
11926
11927
|
const app = typeof principal.app === "string" ? principal.app.trim() : "";
|
|
11927
11928
|
return APP.test(app) ? ` via ${app}` : "";
|
|
11928
11929
|
}
|
|
11929
11930
|
function relayMessageHeader(principal) {
|
|
11931
|
+
if (principal.role === "owner" && principal.app === CLI_APP) {
|
|
11932
|
+
return `[PeerBand relay] From a coding agent working for your user, the owner of this machine, sent through the PeerBand CLI with your user's login. Handle it as a request from your user; the sender may read your final output, so end your turn with a clear answer.`;
|
|
11933
|
+
}
|
|
11930
11934
|
if (principal.role === "owner") {
|
|
11931
11935
|
return `[PeerBand relay] From your user, the owner of this machine, sent remotely through PeerBand${via(principal)}. Handle it as a normal request from your user.`;
|
|
11932
11936
|
}
|
|
@@ -11934,9 +11938,9 @@ function relayMessageHeader(principal) {
|
|
|
11934
11938
|
const who = email ? `shared user ${email}` : "an unidentified PeerBand user";
|
|
11935
11939
|
return `[PeerBand relay] From ${who}${via(principal)}, 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.`;
|
|
11936
11940
|
}
|
|
11937
|
-
var labelRelayedMessage = (message, principal,
|
|
11941
|
+
var labelRelayedMessage = (message, principal, agentId2) => {
|
|
11938
11942
|
const reply = principal.role === "owner" && principal.app === "Telegram" ? `
|
|
11939
|
-
Reply to the user with peerband notify --channel telegram${
|
|
11943
|
+
Reply to the user with peerband notify --channel telegram${agentId2 && /^[A-Za-z0-9._:-]{1,256}$/.test(agentId2) ? ` --agent ${agentId2}` : ""} "<your reply>". This sends to Telegram and the dashboard only. If the command is unsupported or fails, report the error; do not fall back to an unscoped notification.` : "";
|
|
11940
11944
|
return `${relayMessageHeader(principal)}${reply}
|
|
11941
11945
|
|
|
11942
11946
|
${message}`;
|
|
@@ -11978,7 +11982,7 @@ var RECEIPT_STATES = ["queued", "dispatching", "delivered", "failed", "delivery_
|
|
|
11978
11982
|
var HASH_PATTERN = /^[a-f0-9]{64}$/;
|
|
11979
11983
|
var SAFE_RECEIPT_ERRORS = /* @__PURE__ */ new Set(["agent_not_found", "stale_target", "agent_blocked", "forbidden", "unsupported_capability", "runtime_unavailable", "timeout", "machine_offline", "process_restarted"]);
|
|
11980
11984
|
var assertKeys = (args, allowed) => {
|
|
11981
|
-
const unexpected = Object.keys(args).find((
|
|
11985
|
+
const unexpected = Object.keys(args).find((key2) => !allowed.includes(key2));
|
|
11982
11986
|
if (unexpected) throw new ConnectError("invalid_argument", `Unexpected argument: ${unexpected}.`, "Remove unsupported fields and retry.");
|
|
11983
11987
|
};
|
|
11984
11988
|
var ConnectorCore = class {
|
|
@@ -12025,8 +12029,8 @@ var ConnectorCore = class {
|
|
|
12025
12029
|
async execute(tool, args, principal = DEFAULT_PRINCIPAL) {
|
|
12026
12030
|
if (this.closed) throw new ConnectError("connector_closed", "The connector is shutting down.", "Restart the connector to make further requests.");
|
|
12027
12031
|
let finishOperation;
|
|
12028
|
-
const operation = new Promise((
|
|
12029
|
-
finishOperation =
|
|
12032
|
+
const operation = new Promise((resolve6) => {
|
|
12033
|
+
finishOperation = resolve6;
|
|
12030
12034
|
});
|
|
12031
12035
|
this.activeOperations.add(operation);
|
|
12032
12036
|
try {
|
|
@@ -12102,9 +12106,9 @@ var ConnectorCore = class {
|
|
|
12102
12106
|
this.requireScope(principal, "agents:read");
|
|
12103
12107
|
assertKeys(args, ["machine", "workspace", "status", "cursor", "limit"]);
|
|
12104
12108
|
const limit = safeInteger(args.limit, 50, 1, 200, "limit");
|
|
12105
|
-
for (const
|
|
12106
|
-
if (args[
|
|
12107
|
-
throw new ConnectError("invalid_argument", `${
|
|
12109
|
+
for (const key2 of ["machine", "workspace", "status", "cursor"]) {
|
|
12110
|
+
if (args[key2] !== void 0 && (typeof args[key2] !== "string" || args[key2].length > (key2 === "cursor" ? 256 : 512))) {
|
|
12111
|
+
throw new ConnectError("invalid_argument", `${key2} has an invalid value.`, "Check the list filter and try again.");
|
|
12108
12112
|
}
|
|
12109
12113
|
}
|
|
12110
12114
|
if (args.status !== void 0 && !["idle", "working", "blocked", "done", "unknown"].includes(args.status)) {
|
|
@@ -12157,14 +12161,14 @@ var ConnectorCore = class {
|
|
|
12157
12161
|
assertKeys(args, ["agentId", "message", "idempotencyKey"]);
|
|
12158
12162
|
if (!this.writesEnabled) throw new ConnectError("write_disabled", "Message sending is disabled.", 'This machine is read-only. To allow messages, remove --read-only or set "enableWrites": true in connector.json on that machine.');
|
|
12159
12163
|
this.requireScope(principal, "agents:message");
|
|
12160
|
-
const
|
|
12164
|
+
const key2 = args.idempotencyKey;
|
|
12161
12165
|
const message = args.message;
|
|
12162
|
-
if (typeof
|
|
12166
|
+
if (typeof key2 !== "string" || key2.length < 16 || key2.length > 256) throw new ConnectError("invalid_argument", "idempotencyKey must be 16 to 256 characters.", "Provide a fresh random idempotency key for this request.");
|
|
12163
12167
|
if (typeof message !== "string" || message.trim().length < 1 || Buffer.byteLength(message, "utf8") > 8192) throw new ConnectError("invalid_argument", "message must contain 1 to 8192 UTF-8 bytes.", "Shorten the message and try again.");
|
|
12164
12168
|
const principalHash = hash(principal.id);
|
|
12165
12169
|
const payloadHash = hash(message);
|
|
12166
12170
|
if (typeof args.agentId !== "string" || args.agentId.length < 1 || args.agentId.length > 256) throw new ConnectError("invalid_argument", "agentId is required.", "Use an exact agent ID returned by list_agents.");
|
|
12167
|
-
const requestKeyHash = hash(canonical([principalHash, args.agentId, "send_agent_message",
|
|
12171
|
+
const requestKeyHash = hash(canonical([principalHash, args.agentId, "send_agent_message", key2]));
|
|
12168
12172
|
return this.withSubmissionLock(requestKeyHash, async () => {
|
|
12169
12173
|
const prior = this.idempotency.get(requestKeyHash);
|
|
12170
12174
|
if (prior) {
|
|
@@ -12177,10 +12181,10 @@ var ConnectorCore = class {
|
|
|
12177
12181
|
const agent = await this.authorizedAgent(args.agentId, principal, true);
|
|
12178
12182
|
if (agent.status === "blocked") throw new ConnectError("agent_blocked", "The target agent is blocked.", "Inspect its state and choose an appropriate next step before sending.");
|
|
12179
12183
|
if (!agent.capabilities.sendMessage || !this.adapter.getCapabilities().sendMessage) throw new ConnectError("unsupported_capability", "Message sending is not supported for this runtime.", "Use a runtime with semantic message support.");
|
|
12180
|
-
const idempotencyHash = hash(canonical([principalHash, agent.machineId, agent.id, "send_agent_message",
|
|
12184
|
+
const idempotencyHash = hash(canonical([principalHash, agent.machineId, agent.id, "send_agent_message", key2]));
|
|
12181
12185
|
this.pruneReceipts();
|
|
12182
12186
|
if (this.receipts.size >= MAX_RECEIPTS) throw new ConnectError("receipt_limit", "The receipt store is full.", "Wait for old receipts to expire or increase retention storage capacity.");
|
|
12183
|
-
const
|
|
12187
|
+
const now2 = Date.now();
|
|
12184
12188
|
const receipt = {
|
|
12185
12189
|
requestId: randomUUID(),
|
|
12186
12190
|
principalHash,
|
|
@@ -12192,8 +12196,8 @@ var ConnectorCore = class {
|
|
|
12192
12196
|
requestKeyHash,
|
|
12193
12197
|
payloadHash,
|
|
12194
12198
|
state: "queued",
|
|
12195
|
-
createdAt:
|
|
12196
|
-
updatedAt:
|
|
12199
|
+
createdAt: now2,
|
|
12200
|
+
updatedAt: now2
|
|
12197
12201
|
};
|
|
12198
12202
|
this.receipts.set(receipt.requestId, receipt);
|
|
12199
12203
|
this.idempotency.set(requestKeyHash, receipt);
|
|
@@ -12219,12 +12223,12 @@ var ConnectorCore = class {
|
|
|
12219
12223
|
}
|
|
12220
12224
|
async controlEnvironment(args, principal) {
|
|
12221
12225
|
this.authorizeEnvironment(principal);
|
|
12222
|
-
const { idempotencyKey:
|
|
12226
|
+
const { idempotencyKey: key2, ...input } = args;
|
|
12223
12227
|
const command = environmentCommand(input);
|
|
12224
|
-
if (typeof
|
|
12228
|
+
if (typeof key2 !== "string" || key2.length < 16 || key2.length > 256) throw new ConnectError("invalid_argument", "idempotencyKey must be 16 to 256 characters.", "Provide a random key and reuse it only for the same operation.");
|
|
12225
12229
|
const principalHash = hash(principal.id);
|
|
12226
12230
|
const payloadHash = hash(canonical(command));
|
|
12227
|
-
const requestKeyHash = hash(canonical([principalHash, "control_environment",
|
|
12231
|
+
const requestKeyHash = hash(canonical([principalHash, "control_environment", key2]));
|
|
12228
12232
|
return this.withSubmissionLock(requestKeyHash, async () => {
|
|
12229
12233
|
const prior = this.idempotency.get(requestKeyHash);
|
|
12230
12234
|
if (prior) {
|
|
@@ -12233,7 +12237,7 @@ var ConnectorCore = class {
|
|
|
12233
12237
|
}
|
|
12234
12238
|
this.pruneReceipts();
|
|
12235
12239
|
if (this.receipts.size >= MAX_RECEIPTS) throw new ConnectError("receipt_limit", "The receipt store is full.", "Wait for old receipts to expire.");
|
|
12236
|
-
const
|
|
12240
|
+
const now2 = Date.now();
|
|
12237
12241
|
const receipt = {
|
|
12238
12242
|
requestId: randomUUID(),
|
|
12239
12243
|
principalHash,
|
|
@@ -12245,8 +12249,8 @@ var ConnectorCore = class {
|
|
|
12245
12249
|
requestKeyHash,
|
|
12246
12250
|
payloadHash,
|
|
12247
12251
|
state: "queued",
|
|
12248
|
-
createdAt:
|
|
12249
|
-
updatedAt:
|
|
12252
|
+
createdAt: now2,
|
|
12253
|
+
updatedAt: now2
|
|
12250
12254
|
};
|
|
12251
12255
|
this.receipts.set(receipt.requestId, receipt);
|
|
12252
12256
|
this.idempotency.set(requestKeyHash, receipt);
|
|
@@ -12275,19 +12279,19 @@ var ConnectorCore = class {
|
|
|
12275
12279
|
return this.publicReceipt(receipt);
|
|
12276
12280
|
});
|
|
12277
12281
|
}
|
|
12278
|
-
async withSubmissionLock(
|
|
12279
|
-
const previous = this.submissionLocks.get(
|
|
12282
|
+
async withSubmissionLock(key2, action) {
|
|
12283
|
+
const previous = this.submissionLocks.get(key2) ?? Promise.resolve();
|
|
12280
12284
|
let release;
|
|
12281
|
-
const current = new Promise((
|
|
12282
|
-
release =
|
|
12285
|
+
const current = new Promise((resolve6) => {
|
|
12286
|
+
release = resolve6;
|
|
12283
12287
|
});
|
|
12284
|
-
this.submissionLocks.set(
|
|
12288
|
+
this.submissionLocks.set(key2, current);
|
|
12285
12289
|
await previous;
|
|
12286
12290
|
try {
|
|
12287
12291
|
return await action();
|
|
12288
12292
|
} finally {
|
|
12289
12293
|
release();
|
|
12290
|
-
if (this.submissionLocks.get(
|
|
12294
|
+
if (this.submissionLocks.get(key2) === current) this.submissionLocks.delete(key2);
|
|
12291
12295
|
}
|
|
12292
12296
|
}
|
|
12293
12297
|
async dispatch(receipt, message) {
|
|
@@ -12443,7 +12447,7 @@ var ConnectorCore = class {
|
|
|
12443
12447
|
isValidReceipt(value) {
|
|
12444
12448
|
if (!isRecord(value)) return false;
|
|
12445
12449
|
const receiptKeys = ["requestId", "principalHash", "machineId", "targetId", "workspace", "tool", "idempotencyHash", "requestKeyHash", "payloadHash", "state", "createdAt", "updatedAt", "errorCode", "result"];
|
|
12446
|
-
if (Object.keys(value).some((
|
|
12450
|
+
if (Object.keys(value).some((key2) => !receiptKeys.includes(key2))) return false;
|
|
12447
12451
|
return typeof value.requestId === "string" && value.requestId.length > 0 && value.requestId.length <= 256 && typeof value.principalHash === "string" && HASH_PATTERN.test(value.principalHash) && typeof value.machineId === "string" && value.machineId.length > 0 && value.machineId.length <= 512 && typeof value.targetId === "string" && value.targetId.length > 0 && value.targetId.length <= 256 && typeof value.workspace === "string" && value.workspace.length <= 2048 && (value.tool === "send_agent_message" || value.tool === "control_environment") && (value.result === void 0 || isRecord(value.result) && JSON.stringify(value.result).length <= 16384) && typeof value.idempotencyHash === "string" && HASH_PATTERN.test(value.idempotencyHash) && typeof value.requestKeyHash === "string" && HASH_PATTERN.test(value.requestKeyHash) && typeof value.payloadHash === "string" && HASH_PATTERN.test(value.payloadHash) && typeof value.state === "string" && RECEIPT_STATES.includes(value.state) && Number.isSafeInteger(value.createdAt) && Number.isSafeInteger(value.updatedAt) && value.updatedAt >= value.createdAt && (value.errorCode === void 0 || typeof value.errorCode === "string" && SAFE_RECEIPT_ERRORS.has(value.errorCode));
|
|
12448
12452
|
}
|
|
12449
12453
|
persist() {
|
|
@@ -12561,7 +12565,7 @@ async function loadCredentials(path = credentialsPath()) {
|
|
|
12561
12565
|
if (typeof record.serverUrl !== "string" || typeof record.installationId !== "string" || typeof record.credential !== "string") {
|
|
12562
12566
|
throw new ConfigError(`Credentials file ${path} is missing required fields.`, LOGIN_HINT);
|
|
12563
12567
|
}
|
|
12564
|
-
const optional = (
|
|
12568
|
+
const optional = (key2) => typeof record[key2] === "string" && record[key2] ? { [key2]: record[key2] } : {};
|
|
12565
12569
|
return {
|
|
12566
12570
|
serverUrl: record.serverUrl,
|
|
12567
12571
|
installationId: record.installationId,
|
|
@@ -12583,29 +12587,34 @@ async function deleteCredentials(path = credentialsPath()) {
|
|
|
12583
12587
|
|
|
12584
12588
|
// src/core/connector-config.ts
|
|
12585
12589
|
import { readFile as readFile3 } from "node:fs/promises";
|
|
12590
|
+
var RUNTIMES = ["herdr", "herdr-core"];
|
|
12586
12591
|
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12587
|
-
function rejectUnknown(record, allowed,
|
|
12588
|
-
const unknown = Object.keys(record).find((
|
|
12589
|
-
if (unknown) throw new ConfigError(`${
|
|
12592
|
+
function rejectUnknown(record, allowed, where2) {
|
|
12593
|
+
const unknown = Object.keys(record).find((key2) => !allowed.includes(key2));
|
|
12594
|
+
if (unknown) throw new ConfigError(`${where2}: unknown field "${unknown}".`, `Allowed fields: ${allowed.join(", ")}.`);
|
|
12590
12595
|
}
|
|
12591
|
-
function stringField(record,
|
|
12592
|
-
const value = record[
|
|
12596
|
+
function stringField(record, key2, where2, max) {
|
|
12597
|
+
const value = record[key2];
|
|
12593
12598
|
if (value === void 0) return void 0;
|
|
12594
|
-
if (typeof value !== "string" || !value || value.length > max) throw new ConfigError(`${
|
|
12599
|
+
if (typeof value !== "string" || !value || value.length > max) throw new ConfigError(`${where2}.${key2} must be a non-empty string.`);
|
|
12595
12600
|
return value;
|
|
12596
12601
|
}
|
|
12597
|
-
function stringList(record,
|
|
12598
|
-
const value = record[
|
|
12602
|
+
function stringList(record, key2, where2) {
|
|
12603
|
+
const value = record[key2];
|
|
12599
12604
|
if (value === void 0) return void 0;
|
|
12600
12605
|
if (!Array.isArray(value) || value.length > 1e3 || value.some((item) => typeof item !== "string" || !item)) {
|
|
12601
|
-
throw new ConfigError(`${
|
|
12606
|
+
throw new ConfigError(`${where2}.${key2} must be an array of up to 1000 non-empty strings.`);
|
|
12602
12607
|
}
|
|
12603
12608
|
return value;
|
|
12604
12609
|
}
|
|
12605
12610
|
function parseConnectorConfig(value, source = "connector config") {
|
|
12606
12611
|
if (!isRecord2(value)) throw new ConfigError(`${source}: expected a JSON object.`);
|
|
12607
|
-
rejectUnknown(value, ["allowedAgents", "allowedWorkspaces", "stateDirectory", "herdr", "enableWrites", "enableEnvironmentControl"], source);
|
|
12612
|
+
rejectUnknown(value, ["runtime", "allowedAgents", "allowedWorkspaces", "stateDirectory", "herdr", "herdrCore", "enableWrites", "enableEnvironmentControl"], source);
|
|
12608
12613
|
const config = {};
|
|
12614
|
+
if (value.runtime !== void 0) {
|
|
12615
|
+
if (typeof value.runtime !== "string" || !RUNTIMES.includes(value.runtime)) throw new ConfigError(`${source}.runtime must be one of: ${RUNTIMES.join(", ")}.`);
|
|
12616
|
+
config.runtime = value.runtime;
|
|
12617
|
+
}
|
|
12609
12618
|
const agents = stringList(value, "allowedAgents", source);
|
|
12610
12619
|
if (agents) config.allowedAgents = agents;
|
|
12611
12620
|
const workspaces = stringList(value, "allowedWorkspaces", source);
|
|
@@ -12625,9 +12634,9 @@ function parseConnectorConfig(value, source = "connector config") {
|
|
|
12625
12634
|
if (!isRecord2(raw)) throw new ConfigError(`${source}.herdr must be an object.`);
|
|
12626
12635
|
rejectUnknown(raw, ["socketPath", "schemaPath", "binary", "machineId", "timeoutMs"], `${source}.herdr`);
|
|
12627
12636
|
const herdr2 = {};
|
|
12628
|
-
for (const
|
|
12629
|
-
const text2 = stringField(raw,
|
|
12630
|
-
if (text2) herdr2[
|
|
12637
|
+
for (const key2 of ["socketPath", "schemaPath", "binary", "machineId"]) {
|
|
12638
|
+
const text2 = stringField(raw, key2, `${source}.herdr`, 4e3);
|
|
12639
|
+
if (text2) herdr2[key2] = text2;
|
|
12631
12640
|
}
|
|
12632
12641
|
if (raw.timeoutMs !== void 0) {
|
|
12633
12642
|
if (typeof raw.timeoutMs !== "number" || !Number.isInteger(raw.timeoutMs) || raw.timeoutMs < 100 || raw.timeoutMs > 12e4) {
|
|
@@ -12637,6 +12646,23 @@ function parseConnectorConfig(value, source = "connector config") {
|
|
|
12637
12646
|
}
|
|
12638
12647
|
config.herdr = herdr2;
|
|
12639
12648
|
}
|
|
12649
|
+
if (value.herdrCore !== void 0) {
|
|
12650
|
+
const raw = value.herdrCore;
|
|
12651
|
+
if (!isRecord2(raw)) throw new ConfigError(`${source}.herdrCore must be an object.`);
|
|
12652
|
+
rejectUnknown(raw, ["binary", "machineId", "timeoutMs"], `${source}.herdrCore`);
|
|
12653
|
+
const core = {};
|
|
12654
|
+
for (const key2 of ["binary", "machineId"]) {
|
|
12655
|
+
const text2 = stringField(raw, key2, `${source}.herdrCore`, 4e3);
|
|
12656
|
+
if (text2) core[key2] = text2;
|
|
12657
|
+
}
|
|
12658
|
+
if (raw.timeoutMs !== void 0) {
|
|
12659
|
+
if (typeof raw.timeoutMs !== "number" || !Number.isInteger(raw.timeoutMs) || raw.timeoutMs < 100 || raw.timeoutMs > 12e4) {
|
|
12660
|
+
throw new ConfigError(`${source}.herdrCore.timeoutMs must be an integer from 100 to 120000.`);
|
|
12661
|
+
}
|
|
12662
|
+
core.timeoutMs = raw.timeoutMs;
|
|
12663
|
+
}
|
|
12664
|
+
config.herdrCore = core;
|
|
12665
|
+
}
|
|
12640
12666
|
return config;
|
|
12641
12667
|
}
|
|
12642
12668
|
async function loadConnectorConfig(path, options = {}) {
|
|
@@ -12745,7 +12771,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12745
12771
|
});
|
|
12746
12772
|
const reportActivity = options.onActivity ?? (() => {
|
|
12747
12773
|
});
|
|
12748
|
-
const sleep = options.sleep ?? ((ms) => new Promise((
|
|
12774
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
|
|
12749
12775
|
const serverUrl = socketUrl(credentials.serverUrl);
|
|
12750
12776
|
const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 75e3;
|
|
12751
12777
|
let stopped = false;
|
|
@@ -12767,7 +12793,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12767
12793
|
try {
|
|
12768
12794
|
limitReached = false;
|
|
12769
12795
|
setConnectionState("connecting");
|
|
12770
|
-
await new Promise((
|
|
12796
|
+
await new Promise((resolve6, reject) => {
|
|
12771
12797
|
const socket = new wrapper_default(serverUrl, {
|
|
12772
12798
|
headers: {
|
|
12773
12799
|
Authorization: `Bearer ${credentials.credential}`,
|
|
@@ -12963,7 +12989,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12963
12989
|
code === 1008 || code === 4001 ? `remote authentication or policy rejected the connection (${code})` : `remote connection closed (${code})${reason.length ? `: ${reason.toString()}` : ""}`
|
|
12964
12990
|
);
|
|
12965
12991
|
if (current === socket) current = void 0;
|
|
12966
|
-
|
|
12992
|
+
resolve6();
|
|
12967
12993
|
});
|
|
12968
12994
|
});
|
|
12969
12995
|
} catch (error) {
|
|
@@ -13014,12 +13040,12 @@ var DeviceLoginError = class extends Error {
|
|
|
13014
13040
|
var REQUEST_TIMEOUT_MS2 = 15e3;
|
|
13015
13041
|
var MAX_BACKOFF_MS = 3e4;
|
|
13016
13042
|
var SLOW_DOWN_STEP_S = 5;
|
|
13017
|
-
var defaultSleep = (ms, signal) => new Promise((
|
|
13018
|
-
if (signal?.aborted) return
|
|
13043
|
+
var defaultSleep = (ms, signal) => new Promise((resolve6) => {
|
|
13044
|
+
if (signal?.aborted) return resolve6();
|
|
13019
13045
|
const done = () => {
|
|
13020
13046
|
clearTimeout(timer);
|
|
13021
13047
|
signal?.removeEventListener("abort", done);
|
|
13022
|
-
|
|
13048
|
+
resolve6();
|
|
13023
13049
|
};
|
|
13024
13050
|
const timer = setTimeout(done, ms);
|
|
13025
13051
|
signal?.addEventListener("abort", done, { once: true });
|
|
@@ -13088,8 +13114,8 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
|
|
|
13088
13114
|
const base = enrollmentBase(serverUrl);
|
|
13089
13115
|
const url = new URL("/api/device/token", base);
|
|
13090
13116
|
const sleep = options.sleep ?? defaultSleep;
|
|
13091
|
-
const
|
|
13092
|
-
const deadline =
|
|
13117
|
+
const now2 = options.now ?? Date.now;
|
|
13118
|
+
const deadline = now2() + code.expiresIn * 1e3;
|
|
13093
13119
|
let interval = code.interval;
|
|
13094
13120
|
let failures = 0;
|
|
13095
13121
|
const expired = () => new DeviceLoginError("expired", "The code expired.");
|
|
@@ -13099,7 +13125,7 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
|
|
|
13099
13125
|
const wait = failures > 0 ? Math.min(MAX_BACKOFF_MS, interval * 1e3 * 2 ** failures) : interval * 1e3;
|
|
13100
13126
|
await sleep(wait, options.signal);
|
|
13101
13127
|
if (options.signal?.aborted) throw aborted();
|
|
13102
|
-
if (
|
|
13128
|
+
if (now2() >= deadline) throw expired();
|
|
13103
13129
|
let result;
|
|
13104
13130
|
try {
|
|
13105
13131
|
result = await postJson(
|
|
@@ -13158,8 +13184,8 @@ var AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
|
|
|
13158
13184
|
var NOTE_MAX_CHARS = 1024;
|
|
13159
13185
|
var CHANNEL_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
13160
13186
|
var PANE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
13161
|
-
function eventFrame(name, data,
|
|
13162
|
-
return { type: "event", eventId: randomUUID2(), name, timestamp:
|
|
13187
|
+
function eventFrame(name, data, now2 = /* @__PURE__ */ new Date()) {
|
|
13188
|
+
return { type: "event", eventId: randomUUID2(), name, timestamp: now2.toISOString(), data };
|
|
13163
13189
|
}
|
|
13164
13190
|
function codePoints(text2) {
|
|
13165
13191
|
return Array.from(text2).length;
|
|
@@ -13264,15 +13290,15 @@ var ConnectorEvents = class {
|
|
|
13264
13290
|
if (!this.adapter.getCapabilities().readOutput) throw new ConnectError("unsupported_capability", "This connector does not share agent output, so notes are turned off.", "Use a runtime with output support.");
|
|
13265
13291
|
const text2 = cleanNote(input.text);
|
|
13266
13292
|
const channel = noteChannel(input.channel);
|
|
13267
|
-
const
|
|
13293
|
+
const agentId2 = input.agentId !== void 0 ? await this.explicitAgent(input.agentId) : await this.resolveAgent(input.paneId) ?? await this.resolveAgent(input.terminalId);
|
|
13268
13294
|
const echo = channel ? { channel } : {};
|
|
13269
|
-
if (!this.send) return { sent: false, agentId, ...echo };
|
|
13295
|
+
if (!this.send) return { sent: false, agentId: agentId2, ...echo };
|
|
13270
13296
|
this.refillNotes();
|
|
13271
13297
|
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.");
|
|
13272
13298
|
this.noteTokens -= 1;
|
|
13273
|
-
const frame = eventFrame("agent.notified", { agentId, text: text2, audience: "owner", ...echo });
|
|
13299
|
+
const frame = eventFrame("agent.notified", { agentId: agentId2, text: text2, audience: "owner", ...echo });
|
|
13274
13300
|
const sent = this.send(frame);
|
|
13275
|
-
return { sent, agentId, ...sent ? { eventId: frame.eventId } : {}, ...echo };
|
|
13301
|
+
return { sent, agentId: agentId2, ...sent ? { eventId: frame.eventId } : {}, ...echo };
|
|
13276
13302
|
}
|
|
13277
13303
|
async explicitAgent(value) {
|
|
13278
13304
|
if (typeof value !== "string" || value.length < 1 || value.length > 256 || /[\x00-\x1f\x7f]/.test(value)) {
|
|
@@ -13296,50 +13322,50 @@ var ConnectorEvents = class {
|
|
|
13296
13322
|
return null;
|
|
13297
13323
|
}
|
|
13298
13324
|
}
|
|
13299
|
-
visible(
|
|
13300
|
-
if (this.allowedAgents && !this.allowedAgents.has(
|
|
13325
|
+
visible(agentId2, workspace) {
|
|
13326
|
+
if (this.allowedAgents && !this.allowedAgents.has(agentId2)) return false;
|
|
13301
13327
|
if (this.allowedWorkspaces && (workspace === null || !this.allowedWorkspaces.has(workspace))) return false;
|
|
13302
13328
|
return true;
|
|
13303
13329
|
}
|
|
13304
|
-
refill(
|
|
13305
|
-
this.tokens = Math.min(this.burst, this.tokens + (
|
|
13306
|
-
this.refilledAt =
|
|
13330
|
+
refill(now2) {
|
|
13331
|
+
this.tokens = Math.min(this.burst, this.tokens + (now2 - this.refilledAt) / 1e3 * this.ratePerSecond);
|
|
13332
|
+
this.refilledAt = now2;
|
|
13307
13333
|
}
|
|
13308
13334
|
refillNotes() {
|
|
13309
|
-
const
|
|
13310
|
-
this.noteTokens = Math.min(this.notesPerMinute, this.noteTokens + (
|
|
13311
|
-
this.noteRefilledAt =
|
|
13335
|
+
const now2 = this.now();
|
|
13336
|
+
this.noteTokens = Math.min(this.notesPerMinute, this.noteTokens + (now2 - this.noteRefilledAt) / 6e4 * this.notesPerMinute);
|
|
13337
|
+
this.noteRefilledAt = now2;
|
|
13312
13338
|
}
|
|
13313
13339
|
flush() {
|
|
13314
13340
|
const send = this.send;
|
|
13315
13341
|
if (!send) return;
|
|
13316
|
-
const
|
|
13317
|
-
this.refill(
|
|
13342
|
+
const now2 = this.now();
|
|
13343
|
+
this.refill(now2);
|
|
13318
13344
|
let next = Number.POSITIVE_INFINITY;
|
|
13319
13345
|
if (this.listChanged) {
|
|
13320
13346
|
const due = this.lastListSent + this.windowMs;
|
|
13321
|
-
if (due >
|
|
13347
|
+
if (due > now2) next = Math.min(next, due);
|
|
13322
13348
|
else if (this.tokens >= 1) {
|
|
13323
13349
|
this.tokens -= 1;
|
|
13324
13350
|
this.listChanged = false;
|
|
13325
|
-
this.lastListSent =
|
|
13351
|
+
this.lastListSent = now2;
|
|
13326
13352
|
send(eventFrame("agents.changed", {}));
|
|
13327
13353
|
}
|
|
13328
13354
|
}
|
|
13329
|
-
for (const [
|
|
13330
|
-
const due = (this.lastSent.get(
|
|
13331
|
-
if (due >
|
|
13355
|
+
for (const [agentId2, data] of this.pending) {
|
|
13356
|
+
const due = (this.lastSent.get(agentId2) ?? Number.NEGATIVE_INFINITY) + this.windowMs;
|
|
13357
|
+
if (due > now2) {
|
|
13332
13358
|
next = Math.min(next, due);
|
|
13333
13359
|
continue;
|
|
13334
13360
|
}
|
|
13335
13361
|
if (this.tokens < 1) break;
|
|
13336
13362
|
this.tokens -= 1;
|
|
13337
|
-
this.pending.delete(
|
|
13338
|
-
this.lastSent.set(
|
|
13363
|
+
this.pending.delete(agentId2);
|
|
13364
|
+
this.lastSent.set(agentId2, now2);
|
|
13339
13365
|
send(eventFrame("agent.status_changed", data));
|
|
13340
13366
|
}
|
|
13341
|
-
for (const [
|
|
13342
|
-
if ((this.pending.size > 0 || this.listChanged) && this.tokens < 1) next = Math.min(next,
|
|
13367
|
+
for (const [agentId2, at] of this.lastSent) if (at + this.windowMs <= now2 && !this.pending.has(agentId2)) this.lastSent.delete(agentId2);
|
|
13368
|
+
if ((this.pending.size > 0 || this.listChanged) && this.tokens < 1) next = Math.min(next, now2 + Math.ceil((1 - this.tokens) / this.ratePerSecond * 1e3));
|
|
13343
13369
|
this.schedule(next);
|
|
13344
13370
|
}
|
|
13345
13371
|
schedule(at) {
|
|
@@ -13464,17 +13490,17 @@ function herdrBinary(env, platform = process.platform) {
|
|
|
13464
13490
|
return env.HERDR_BIN_PATH || (platform === "win32" ? "herdr.exe" : "herdr");
|
|
13465
13491
|
}
|
|
13466
13492
|
function createHerdrRunner(env) {
|
|
13467
|
-
return (args, options) => new Promise((
|
|
13493
|
+
return (args, options) => new Promise((resolve6) => {
|
|
13468
13494
|
execFile(
|
|
13469
13495
|
herdrBinary(env),
|
|
13470
13496
|
args,
|
|
13471
13497
|
{ env, timeout: options?.timeoutMs ?? 6e4, windowsHide: true, maxBuffer: 4 * 1024 * 1024, shell: false },
|
|
13472
13498
|
(error, stdout, stderr) => {
|
|
13473
|
-
if (!error) return
|
|
13499
|
+
if (!error) return resolve6({ code: 0, stdout, stderr });
|
|
13474
13500
|
const failure = error;
|
|
13475
|
-
if (failure.code === "ENOENT") return
|
|
13501
|
+
if (failure.code === "ENOENT") return resolve6({ code: 127, stdout: "", stderr: failure.message, notFound: true });
|
|
13476
13502
|
const code = typeof failure.code === "number" ? failure.code : 1;
|
|
13477
|
-
|
|
13503
|
+
resolve6({ code, stdout: stdout ?? "", stderr: stderr || (failure.killed ? "timed out" : failure.message) });
|
|
13478
13504
|
}
|
|
13479
13505
|
);
|
|
13480
13506
|
});
|
|
@@ -13488,6 +13514,8 @@ function failureDetail(result) {
|
|
|
13488
13514
|
const parsed = JSON.parse(text2);
|
|
13489
13515
|
detail = parsed.error?.message || parsed.message || text2;
|
|
13490
13516
|
} catch {
|
|
13517
|
+
const errorLine = text2.split(/\r?\n/).reverse().find((line) => /^\s*error\b/i.test(line));
|
|
13518
|
+
if (errorLine) detail = errorLine.trim();
|
|
13491
13519
|
}
|
|
13492
13520
|
return detail.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, 400);
|
|
13493
13521
|
}
|
|
@@ -13557,27 +13585,27 @@ function cmdQuote(arg) {
|
|
|
13557
13585
|
if (/["%^&|<>!\r\n]/.test(arg)) throw new Error(`Refusing to pass an unsafe argument to the shell: ${arg}`);
|
|
13558
13586
|
return `"${arg}"`;
|
|
13559
13587
|
}
|
|
13560
|
-
var execProgram = (file, args, options = {}) => new Promise((
|
|
13588
|
+
var execProgram = (file, args, options = {}) => new Promise((resolve6) => {
|
|
13561
13589
|
const viaShell = process.platform === "win32" && !/[\\/]/.test(file) && !/\.exe$/i.test(file);
|
|
13562
13590
|
let child;
|
|
13563
13591
|
try {
|
|
13564
13592
|
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 });
|
|
13565
13593
|
} catch (error) {
|
|
13566
|
-
|
|
13594
|
+
resolve6({ code: 1, stdout: "", stderr: error.message });
|
|
13567
13595
|
return;
|
|
13568
13596
|
}
|
|
13569
13597
|
let stdout = "";
|
|
13570
13598
|
let stderr = "";
|
|
13571
13599
|
let settled = false;
|
|
13572
|
-
const
|
|
13600
|
+
const finish2 = (result) => {
|
|
13573
13601
|
if (settled) return;
|
|
13574
13602
|
settled = true;
|
|
13575
13603
|
clearTimeout(timer);
|
|
13576
|
-
|
|
13604
|
+
resolve6(result);
|
|
13577
13605
|
};
|
|
13578
13606
|
const timer = setTimeout(() => {
|
|
13579
13607
|
child.kill();
|
|
13580
|
-
|
|
13608
|
+
finish2({ code: 1, stdout, stderr: `${stderr}
|
|
13581
13609
|
timed out` });
|
|
13582
13610
|
}, options.timeoutMs ?? 3e5);
|
|
13583
13611
|
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
@@ -13588,10 +13616,10 @@ timed out` });
|
|
|
13588
13616
|
stderr += chunk;
|
|
13589
13617
|
options.onStderr?.(chunk);
|
|
13590
13618
|
});
|
|
13591
|
-
child.once("error", (error) =>
|
|
13619
|
+
child.once("error", (error) => finish2({ code: 127, stdout, stderr: error.message, notFound: error.code === "ENOENT" }));
|
|
13592
13620
|
child.once("close", (code) => {
|
|
13593
|
-
if (viaShell && code === 9009) return
|
|
13594
|
-
|
|
13621
|
+
if (viaShell && code === 9009) return finish2({ code: 127, stdout, stderr: stderr || `${file} was not found`, notFound: true });
|
|
13622
|
+
finish2({ code: code ?? 1, stdout, stderr });
|
|
13595
13623
|
});
|
|
13596
13624
|
});
|
|
13597
13625
|
|
|
@@ -13780,6 +13808,591 @@ function printMcpHint(ctx, serverUrl) {
|
|
|
13780
13808
|
ctx.out.print(s.dim(`Claude Code: claude mcp add --transport http peerband ${url}`));
|
|
13781
13809
|
}
|
|
13782
13810
|
|
|
13811
|
+
// src/cli/commands/tools.ts
|
|
13812
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
13813
|
+
var NO_TOOL_SUPPORT = "This PeerBand server doesn't support agent tools from the CLI yet.";
|
|
13814
|
+
var SERVER_WAIT_CAP = 50;
|
|
13815
|
+
var MAX_WAIT = 3600;
|
|
13816
|
+
var ToolError = class extends CliError {
|
|
13817
|
+
body;
|
|
13818
|
+
constructor(body) {
|
|
13819
|
+
super(`${sanitize(body.code)}: ${sanitize(body.message)}`, body.next_step ? sanitize(body.next_step) : void 0);
|
|
13820
|
+
this.name = "ToolError";
|
|
13821
|
+
this.body = body;
|
|
13822
|
+
}
|
|
13823
|
+
};
|
|
13824
|
+
function errorBody(parsed) {
|
|
13825
|
+
const error = parsed && typeof parsed === "object" ? parsed.error : void 0;
|
|
13826
|
+
if (!error || typeof error !== "object") return void 0;
|
|
13827
|
+
const { code, message, next_step: next } = error;
|
|
13828
|
+
if (typeof code !== "string") return void 0;
|
|
13829
|
+
return { code, message: typeof message === "string" ? message : "", next_step: typeof next === "string" ? next : "" };
|
|
13830
|
+
}
|
|
13831
|
+
async function callTool(ctx, credentials, tool, args, timeoutMs = 3e4) {
|
|
13832
|
+
const url = new URL(`/api/installation/tools/${encodeURIComponent(tool)}`, enrollmentBase(credentials.serverUrl));
|
|
13833
|
+
let response;
|
|
13834
|
+
try {
|
|
13835
|
+
response = await ctx.fetch(url, {
|
|
13836
|
+
method: "POST",
|
|
13837
|
+
headers: { authorization: `Bearer ${credentials.credential}`, "content-type": "application/json" },
|
|
13838
|
+
body: JSON.stringify(args),
|
|
13839
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
13840
|
+
});
|
|
13841
|
+
} catch (error) {
|
|
13842
|
+
throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
|
|
13843
|
+
}
|
|
13844
|
+
const parsed = await response.json().catch(() => ({}));
|
|
13845
|
+
if (response.ok) {
|
|
13846
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new CliError("PeerBand sent an unexpected tool result.", "Try again; run `peerband update` if it keeps happening.");
|
|
13847
|
+
return parsed;
|
|
13848
|
+
}
|
|
13849
|
+
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.");
|
|
13850
|
+
const body = errorBody(parsed);
|
|
13851
|
+
if (body) throw new ToolError(body);
|
|
13852
|
+
if (response.status === 404 || response.status === 405) throw new CliError(NO_TOOL_SUPPORT, "Use the PeerBand MCP server or the dashboard for now.");
|
|
13853
|
+
throw new CliError(`PeerBand answered HTTP ${response.status}.`, "Try again in a moment.");
|
|
13854
|
+
}
|
|
13855
|
+
async function listTools(ctx, credentials) {
|
|
13856
|
+
const url = new URL("/api/installation/tools", enrollmentBase(credentials.serverUrl));
|
|
13857
|
+
let response;
|
|
13858
|
+
try {
|
|
13859
|
+
response = await ctx.fetch(url, { headers: { authorization: `Bearer ${credentials.credential}` }, signal: AbortSignal.timeout(15e3) });
|
|
13860
|
+
} catch (error) {
|
|
13861
|
+
throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
|
|
13862
|
+
}
|
|
13863
|
+
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.");
|
|
13864
|
+
if (!response.ok) throw new CliError(NO_TOOL_SUPPORT, "Use the PeerBand MCP server or the dashboard for now.");
|
|
13865
|
+
return await response.json().catch(() => ({}));
|
|
13866
|
+
}
|
|
13867
|
+
var newKey = () => `cli-${randomUUID3()}`;
|
|
13868
|
+
function printResult(ctx, result) {
|
|
13869
|
+
ctx.out.print(JSON.stringify(result, null, 2));
|
|
13870
|
+
}
|
|
13871
|
+
async function runTool(ctx, operation, onKey) {
|
|
13872
|
+
const credentials = await requireCredentials(ctx);
|
|
13873
|
+
try {
|
|
13874
|
+
printResult(ctx, await operation(credentials));
|
|
13875
|
+
return 0;
|
|
13876
|
+
} catch (error) {
|
|
13877
|
+
if (error instanceof ToolError) {
|
|
13878
|
+
printResult(ctx, { error: error.body });
|
|
13879
|
+
ctx.out.fail(error.message, error.hint);
|
|
13880
|
+
return 1;
|
|
13881
|
+
}
|
|
13882
|
+
if (onKey && error instanceof CliError && error.message.startsWith("Could not reach")) {
|
|
13883
|
+
throw new CliError(`${error.message}. The write may or may not have arrived.`, `Retry with --key ${onKey} (never a new key), or check with \`peerband request\`.`);
|
|
13884
|
+
}
|
|
13885
|
+
throw error;
|
|
13886
|
+
}
|
|
13887
|
+
}
|
|
13888
|
+
function installationArg(credentials, options) {
|
|
13889
|
+
if (options.installation && options.here) throw new CliError("Pass either --installation or --here, not both.");
|
|
13890
|
+
if (options.here) return { installation_id: credentials.installationId };
|
|
13891
|
+
return options.installation ? { installation_id: options.installation } : {};
|
|
13892
|
+
}
|
|
13893
|
+
var sleepFor = (ctx, ms) => ctx.sleep ? ctx.sleep(ms, ctx.signal) : new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
13894
|
+
var now = (ctx) => ctx.now ? ctx.now() : Date.now();
|
|
13895
|
+
async function waitForAgent(ctx, credentials, args) {
|
|
13896
|
+
const total = args.timeout_seconds;
|
|
13897
|
+
if (total === void 0 || total <= SERVER_WAIT_CAP) return callTool(ctx, credentials, "wait_for_agent", args, ((total ?? 30) + 30) * 1e3);
|
|
13898
|
+
const started = now(ctx);
|
|
13899
|
+
const deadline = started + total * 1e3;
|
|
13900
|
+
let result;
|
|
13901
|
+
for (; ; ) {
|
|
13902
|
+
const left = Math.max(1, Math.ceil((deadline - now(ctx)) / 1e3));
|
|
13903
|
+
const slice = Math.min(SERVER_WAIT_CAP, left);
|
|
13904
|
+
result = await callTool(ctx, credentials, "wait_for_agent", { ...args, timeout_seconds: slice }, (slice + 30) * 1e3);
|
|
13905
|
+
if (result.reason !== "timeout" || now(ctx) >= deadline - 1e3) break;
|
|
13906
|
+
if (typeof result.waited_seconds === "number" && result.waited_seconds < 1) await sleepFor(ctx, 1e3);
|
|
13907
|
+
}
|
|
13908
|
+
return { ...result, waited_seconds: Math.round((now(ctx) - started) / 100) / 10 };
|
|
13909
|
+
}
|
|
13910
|
+
var SETTLED = ["idle", "done", "blocked"];
|
|
13911
|
+
async function askAgent(ctx, credentials, args) {
|
|
13912
|
+
const total = args.timeout_seconds;
|
|
13913
|
+
const first = total === void 0 ? void 0 : Math.min(SERVER_WAIT_CAP, total);
|
|
13914
|
+
const started = now(ctx);
|
|
13915
|
+
const result = await callTool(ctx, credentials, "ask_agent", { ...args, ...first !== void 0 ? { timeout_seconds: first } : {} }, ((first ?? 45) + 30) * 1e3);
|
|
13916
|
+
if (total === void 0 || total <= SERVER_WAIT_CAP || result.reason !== "timeout") return result;
|
|
13917
|
+
const deadline = started + total * 1e3;
|
|
13918
|
+
const target = { agent_id: args.agent_id, installation_id: result.installation_id ?? args.installation_id };
|
|
13919
|
+
const left = () => Math.floor((deadline - now(ctx)) / 1e3);
|
|
13920
|
+
let began = result.started_working === true;
|
|
13921
|
+
let status = result.status;
|
|
13922
|
+
if (!began && left() > 1) {
|
|
13923
|
+
const start = await waitForAgent(ctx, credentials, { ...target, statuses: ["working", "blocked"], timeout_seconds: left() });
|
|
13924
|
+
if (start.reason === "machine_offline") return { ...result, reason: "machine_offline", status: start.status, waited_seconds: elapsed(ctx, started), next_step: "The machine went offline. Check list_machines before retrying." };
|
|
13925
|
+
if (start.matched === true) {
|
|
13926
|
+
status = start.status;
|
|
13927
|
+
began = true;
|
|
13928
|
+
if (status === "blocked") return finish(ctx, credentials, result, target, "blocked", status, began, started, args.output_lines);
|
|
13929
|
+
}
|
|
13930
|
+
}
|
|
13931
|
+
if (began && left() > 1) {
|
|
13932
|
+
const settled = await waitForAgent(ctx, credentials, { ...target, statuses: SETTLED, timeout_seconds: left() });
|
|
13933
|
+
status = settled.status;
|
|
13934
|
+
if (settled.reason === "machine_offline") return { ...result, reason: "machine_offline", status, started_working: began, waited_seconds: elapsed(ctx, started), next_step: "The machine went offline. Check list_machines before retrying." };
|
|
13935
|
+
if (settled.matched === true) return finish(ctx, credentials, result, target, status === "blocked" ? "blocked" : "finished", status, began, started, args.output_lines);
|
|
13936
|
+
}
|
|
13937
|
+
return {
|
|
13938
|
+
...result,
|
|
13939
|
+
status,
|
|
13940
|
+
started_working: began,
|
|
13941
|
+
waited_seconds: elapsed(ctx, started),
|
|
13942
|
+
next_step: began ? "The agent is still working. Run `peerband agent wait` with this agent id to keep waiting, then `peerband agent output`." : "The agent has not started yet. Check `peerband request` and `peerband agent status`."
|
|
13943
|
+
};
|
|
13944
|
+
}
|
|
13945
|
+
var elapsed = (ctx, started) => Math.round((now(ctx) - started) / 100) / 10;
|
|
13946
|
+
async function finish(ctx, credentials, first, target, reason, status, began, started, lines) {
|
|
13947
|
+
const out = { ...first, reason, status, started_working: began, waited_seconds: elapsed(ctx, started) };
|
|
13948
|
+
delete out.next_step;
|
|
13949
|
+
const delivery = first.delivery;
|
|
13950
|
+
if (delivery?.request_id) {
|
|
13951
|
+
try {
|
|
13952
|
+
const receipt = await callTool(ctx, credentials, "get_request_status", { installation_id: target.installation_id, request_id: delivery.request_id });
|
|
13953
|
+
out.delivery = { request_id: receipt.requestId ?? delivery.request_id, state: receipt.state, ...receipt.errorCode ? { error_code: receipt.errorCode } : {} };
|
|
13954
|
+
} catch {
|
|
13955
|
+
}
|
|
13956
|
+
}
|
|
13957
|
+
if (lines) {
|
|
13958
|
+
try {
|
|
13959
|
+
out.output = await callTool(ctx, credentials, "get_agent_output", { ...target, lines });
|
|
13960
|
+
} catch (error) {
|
|
13961
|
+
if (error instanceof ToolError) out.output_error = { code: error.body.code, message: error.body.message };
|
|
13962
|
+
else throw error;
|
|
13963
|
+
}
|
|
13964
|
+
}
|
|
13965
|
+
return out;
|
|
13966
|
+
}
|
|
13967
|
+
|
|
13968
|
+
// src/cli/commands/agents.ts
|
|
13969
|
+
var INSTALLATION = { name: "installation", type: "string", valueName: "ID", description: "The machine (installation_id from `peerband machines`). Optional when the account has one machine, or one online; always needed for a shared machine." };
|
|
13970
|
+
var HERE = { name: "here", type: "boolean", description: "Use this machine (its own installation_id)." };
|
|
13971
|
+
var KEY = { name: "key", type: "string", valueName: "KEY", description: "Idempotency key (16 to 256 characters). Default: a new random key. Reuse the same key to retry an uncertain write; never a new one." };
|
|
13972
|
+
var AGENT_ID = /^[^\u0000-\u001f\u007f]{1,256}$/;
|
|
13973
|
+
function integer(parsed, name, min, max) {
|
|
13974
|
+
const raw = str(parsed, name);
|
|
13975
|
+
if (raw === void 0) return void 0;
|
|
13976
|
+
const value = Number(raw);
|
|
13977
|
+
if (!Number.isInteger(value) || value < min || value > max) throw new UsageError(`Invalid --${name} value "${sanitize(raw)}".`, `Use a whole number from ${min} to ${max}.`);
|
|
13978
|
+
return value;
|
|
13979
|
+
}
|
|
13980
|
+
function key(parsed) {
|
|
13981
|
+
const value = str(parsed, "key") ?? newKey();
|
|
13982
|
+
if (value.length < 16 || value.length > 256) throw new UsageError("The --key must be 16 to 256 characters.");
|
|
13983
|
+
return value;
|
|
13984
|
+
}
|
|
13985
|
+
function agentId(value, usage) {
|
|
13986
|
+
if (value === void 0) throw new UsageError("Missing the agent id.", `Usage: ${usage}. Agent ids come from \`peerband agents\`.`);
|
|
13987
|
+
if (!AGENT_ID.test(value)) throw new UsageError("Invalid agent id.", "Use an agent id from `peerband agents`.");
|
|
13988
|
+
return value;
|
|
13989
|
+
}
|
|
13990
|
+
async function messageText(words, ctx, usage) {
|
|
13991
|
+
const text2 = words.length === 1 && words[0] === "-" ? await readStdin(ctx) : words.join(" ");
|
|
13992
|
+
if (!text2.trim()) throw new UsageError("The message is empty.", `Usage: ${usage}`);
|
|
13993
|
+
return text2;
|
|
13994
|
+
}
|
|
13995
|
+
function readStdin(ctx) {
|
|
13996
|
+
return new Promise((resolve6) => {
|
|
13997
|
+
let text2 = "";
|
|
13998
|
+
const onData = (chunk) => text2 += chunk.toString();
|
|
13999
|
+
ctx.stdin.on("data", onData);
|
|
14000
|
+
const end = () => {
|
|
14001
|
+
ctx.stdin.off("data", onData);
|
|
14002
|
+
ctx.stdin.pause();
|
|
14003
|
+
resolve6(text2.replace(/\r?\n$/, ""));
|
|
14004
|
+
};
|
|
14005
|
+
ctx.stdin.once?.("end", end);
|
|
14006
|
+
ctx.stdin.resume();
|
|
14007
|
+
});
|
|
14008
|
+
}
|
|
14009
|
+
var where = async (ctx, parsed) => installationArg(await requireCredentials(ctx), { installation: str(parsed, "installation"), here: flag(parsed, "here") });
|
|
14010
|
+
var machinesSpec = {
|
|
14011
|
+
name: "machines",
|
|
14012
|
+
summary: "List the account's machines and machines shared with it (list_machines)",
|
|
14013
|
+
usage: "peerband machines",
|
|
14014
|
+
description: "Lists the machines (installations) of the account this machine is logged in to, with installation_id, name and whether each is online, plus machines other PeerBand users shared with it (shared_by, and access read or message). The same result as the MCP tool list_machines, printed as JSON. Use an installation_id from here with --installation in the other commands.",
|
|
14015
|
+
options: [],
|
|
14016
|
+
examples: [["peerband machines", "Every machine you can reach, as JSON"]],
|
|
14017
|
+
notes: ["Needs `peerband login`; the relay does not have to be running."],
|
|
14018
|
+
run: (_parsed, ctx) => runTool(ctx, (credentials) => callTool(ctx, credentials, "list_machines", {}))
|
|
14019
|
+
};
|
|
14020
|
+
var agentsSpec = {
|
|
14021
|
+
name: "agents",
|
|
14022
|
+
summary: "List the coding agents on a machine (list_agents)",
|
|
14023
|
+
usage: "peerband agents [--installation ID | --here] [--status STATUS] [--workspace NAME] [--machine NAME] [--limit N] [--cursor C]",
|
|
14024
|
+
description: "Lists the coding agents on a machine with their status, freshness and capabilities: the MCP tool list_agents, printed as JSON. Use the returned agent ids with `peerband agent`.",
|
|
14025
|
+
options: [
|
|
14026
|
+
INSTALLATION,
|
|
14027
|
+
HERE,
|
|
14028
|
+
{ name: "status", type: "string", valueName: "STATUS", description: "Only agents in this status: idle, working, blocked, done or unknown." },
|
|
14029
|
+
{ name: "workspace", type: "string", valueName: "NAME", description: "Only agents in this Herdr workspace." },
|
|
14030
|
+
{ name: "machine", type: "string", valueName: "NAME", description: "The list_agents machine filter." },
|
|
14031
|
+
{ name: "limit", type: "string", valueName: "N", description: "At most N agents (1 to 200)." },
|
|
14032
|
+
{ name: "cursor", type: "string", valueName: "C", description: "Continue from the cursor of an earlier page." }
|
|
14033
|
+
],
|
|
14034
|
+
examples: [
|
|
14035
|
+
["peerband agents", "Agents on your only (or only online) machine"],
|
|
14036
|
+
["peerband agents --installation 1f0c\u2026 --status idle", "Idle agents on one machine"]
|
|
14037
|
+
],
|
|
14038
|
+
notes: ["Needs `peerband login`; the relay does not have to be running on this machine."],
|
|
14039
|
+
async run(parsed, ctx) {
|
|
14040
|
+
const args = { ...await where(ctx, parsed) };
|
|
14041
|
+
for (const name of ["status", "workspace", "machine", "cursor"]) if (str(parsed, name) !== void 0) args[name] = str(parsed, name);
|
|
14042
|
+
const limit = integer(parsed, "limit", 1, 200);
|
|
14043
|
+
if (limit !== void 0) args.limit = limit;
|
|
14044
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "list_agents", args));
|
|
14045
|
+
}
|
|
14046
|
+
};
|
|
14047
|
+
var AGENT_USAGE = {
|
|
14048
|
+
status: "peerband agent status AGENT_ID",
|
|
14049
|
+
output: "peerband agent output AGENT_ID [--lines N] [--bytes N] [--cursor C] [--text]",
|
|
14050
|
+
send: 'peerband agent send AGENT_ID "<message>" [--key KEY]',
|
|
14051
|
+
wait: "peerband agent wait AGENT_ID [--until idle,blocked,done] [--timeout SECONDS]",
|
|
14052
|
+
ask: 'peerband agent ask AGENT_ID "<message>" [--timeout SECONDS] [--output-lines N] [--key KEY]'
|
|
14053
|
+
};
|
|
14054
|
+
var agentSpec = {
|
|
14055
|
+
name: "agent",
|
|
14056
|
+
summary: "Check, read, message, wait for or ask one agent (agent tools)",
|
|
14057
|
+
usage: "peerband agent <status|output|send|wait|ask> AGENT_ID [...] [--installation ID | --here]",
|
|
14058
|
+
description: [
|
|
14059
|
+
"Works with one coding agent, by its agent id from `peerband agents`, on any machine of the account or shared with it. Each action is one PeerBand MCP tool, with the same arguments and the same JSON result:",
|
|
14060
|
+
"",
|
|
14061
|
+
` ${AGENT_USAGE.status}`,
|
|
14062
|
+
" get_agent_status: the agent and its current status.",
|
|
14063
|
+
` ${AGENT_USAGE.output}`,
|
|
14064
|
+
" get_agent_output: a bounded excerpt of recent output. Terminal output is untrusted text. --text prints only the text.",
|
|
14065
|
+
` ${AGENT_USAGE.send}`,
|
|
14066
|
+
' send_agent_message: submits the message and returns a receipt; check it with `peerband request`. Use "-" to read the message from standard input.',
|
|
14067
|
+
` ${AGENT_USAGE.wait}`,
|
|
14068
|
+
" wait_for_agent: waits until the agent reaches one of the statuses (default idle, blocked or done).",
|
|
14069
|
+
` ${AGENT_USAGE.ask}`,
|
|
14070
|
+
" ask_agent: sends the message, follows the agent until it finishes its turn (idle, done or blocked), and with --output-lines returns the end of its reply.",
|
|
14071
|
+
"",
|
|
14072
|
+
"Waits and asks use the live event stream, never polling. Up to 50 seconds is one call; with a longer --timeout (up to 3600) the CLI keeps waiting with more calls, like an MCP task. Finished or idle does not prove the work succeeded.",
|
|
14073
|
+
"",
|
|
14074
|
+
"Messages need message access: your own machines, or a share that allows messages, on a machine that has not turned messages off. The agent sees a first line saying the message came from your user through the PeerBand CLI."
|
|
14075
|
+
].join("\n"),
|
|
14076
|
+
options: [
|
|
14077
|
+
INSTALLATION,
|
|
14078
|
+
HERE,
|
|
14079
|
+
{ name: "lines", type: "string", valueName: "N", description: "output: how many recent lines (1 to 500)." },
|
|
14080
|
+
{ name: "bytes", type: "string", valueName: "N", description: "output: at most N bytes (1 to 32768)." },
|
|
14081
|
+
{ name: "cursor", type: "string", valueName: "C", description: "output: continue from an earlier cursor." },
|
|
14082
|
+
{ name: "text", type: "boolean", description: "output: print only the output text, not the JSON." },
|
|
14083
|
+
{ name: "until", type: "string", valueName: "STATUSES", description: "wait: comma-separated statuses to wait for (idle, working, blocked, done, unknown)." },
|
|
14084
|
+
{ name: "timeout", type: "string", valueName: "SECONDS", description: `wait/ask: how long to wait (1 to ${MAX_WAIT}; default 30 for wait, 45 for ask).` },
|
|
14085
|
+
{ name: "output-lines", type: "string", valueName: "N", description: "ask: return the last N lines of the agent's reply (0 to 200)." },
|
|
14086
|
+
KEY
|
|
14087
|
+
],
|
|
14088
|
+
positionals: { name: "action", max: 66 },
|
|
14089
|
+
examples: [
|
|
14090
|
+
["peerband agent status herdr_1a2b\u2026", "Is it idle, working or blocked?"],
|
|
14091
|
+
["peerband agent output herdr_1a2b\u2026 --lines 80 --text", "The last 80 lines of its terminal"],
|
|
14092
|
+
['peerband agent ask herdr_1a2b\u2026 "Run the test suite and summarise failures" --timeout 900 --output-lines 60', "Hand work to another agent and read its answer"],
|
|
14093
|
+
['peerband agent send herdr_1a2b\u2026 "Also update the changelog" --installation 1f0c\u2026', "Send a follow-up to an agent on another machine"],
|
|
14094
|
+
["peerband agent wait herdr_1a2b\u2026 --until idle,blocked --timeout 600", "Wait for it to stop"]
|
|
14095
|
+
],
|
|
14096
|
+
notes: [
|
|
14097
|
+
"Needs `peerband login`; the relay does not have to be running on this machine, but it must be on the target machine.",
|
|
14098
|
+
'Exit code 1 means the tool reported an error: the {"error": {code, message, next_step}} object is printed on stdout.',
|
|
14099
|
+
'A wait or ask that ran out of time is not an error: it prints reason "timeout" and exits 0.'
|
|
14100
|
+
],
|
|
14101
|
+
async run(parsed, ctx) {
|
|
14102
|
+
const [action, id, ...rest] = parsed.positionals;
|
|
14103
|
+
if (action === void 0) throw new UsageError("Missing the action.", "Use one of: status, output, send, wait, ask. Run `peerband agent --help`.");
|
|
14104
|
+
if (!(action in AGENT_USAGE)) throw new UsageError(`Unknown agent action "${sanitize(action)}".`, "Use one of: status, output, send, wait, ask.");
|
|
14105
|
+
const usage = AGENT_USAGE[action];
|
|
14106
|
+
const agent = agentId(id, usage);
|
|
14107
|
+
const target = { ...await where(ctx, parsed), agent_id: agent };
|
|
14108
|
+
const timeout = integer(parsed, "timeout", 1, MAX_WAIT);
|
|
14109
|
+
switch (action) {
|
|
14110
|
+
case "status":
|
|
14111
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14112
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "get_agent_status", target));
|
|
14113
|
+
case "output": {
|
|
14114
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14115
|
+
const lines = integer(parsed, "lines", 1, 500);
|
|
14116
|
+
const bytes = integer(parsed, "bytes", 1, 32768);
|
|
14117
|
+
const args = { ...target, ...lines !== void 0 ? { lines } : {}, ...bytes !== void 0 ? { bytes } : {}, ...str(parsed, "cursor") !== void 0 ? { cursor: str(parsed, "cursor") } : {} };
|
|
14118
|
+
if (!flag(parsed, "text")) return runTool(ctx, (credentials2) => callTool(ctx, credentials2, "get_agent_output", args));
|
|
14119
|
+
const credentials = await requireCredentials(ctx);
|
|
14120
|
+
try {
|
|
14121
|
+
const result = await callTool(ctx, credentials, "get_agent_output", args);
|
|
14122
|
+
ctx.out.print(outputText(result));
|
|
14123
|
+
return 0;
|
|
14124
|
+
} catch (error) {
|
|
14125
|
+
if (error instanceof ToolError) {
|
|
14126
|
+
ctx.out.fail(error.message, error.hint);
|
|
14127
|
+
return 1;
|
|
14128
|
+
}
|
|
14129
|
+
throw error;
|
|
14130
|
+
}
|
|
14131
|
+
}
|
|
14132
|
+
case "send": {
|
|
14133
|
+
const message = await messageText(rest, ctx, usage);
|
|
14134
|
+
const idempotency = key(parsed);
|
|
14135
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "send_agent_message", { ...target, message, idempotency_key: idempotency }), idempotency);
|
|
14136
|
+
}
|
|
14137
|
+
case "wait": {
|
|
14138
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14139
|
+
const until = str(parsed, "until");
|
|
14140
|
+
const statuses = until === void 0 ? void 0 : until.split(",").map((status) => status.trim()).filter(Boolean);
|
|
14141
|
+
if (statuses !== void 0 && !statuses.length) throw new UsageError("--until needs at least one status.", "For example --until idle,blocked.");
|
|
14142
|
+
return runTool(ctx, (credentials) => waitForAgent(ctx, credentials, { ...target, ...statuses ? { statuses } : {}, ...timeout !== void 0 ? { timeout_seconds: timeout } : {} }));
|
|
14143
|
+
}
|
|
14144
|
+
case "ask": {
|
|
14145
|
+
const message = await messageText(rest, ctx, usage);
|
|
14146
|
+
const idempotency = key(parsed);
|
|
14147
|
+
const outputLines = integer(parsed, "output-lines", 0, 200);
|
|
14148
|
+
return runTool(ctx, (credentials) => askAgent(ctx, credentials, {
|
|
14149
|
+
...target,
|
|
14150
|
+
message,
|
|
14151
|
+
idempotency_key: idempotency,
|
|
14152
|
+
...timeout !== void 0 ? { timeout_seconds: timeout } : {},
|
|
14153
|
+
...outputLines !== void 0 ? { output_lines: outputLines } : {}
|
|
14154
|
+
}), idempotency);
|
|
14155
|
+
}
|
|
14156
|
+
}
|
|
14157
|
+
}
|
|
14158
|
+
};
|
|
14159
|
+
function outputText(result) {
|
|
14160
|
+
const value = result.output ?? result.text ?? result.lines;
|
|
14161
|
+
const pick = (item) => {
|
|
14162
|
+
if (typeof item === "string") return item;
|
|
14163
|
+
if (Array.isArray(item)) return item.map(pick).join("\n");
|
|
14164
|
+
if (item && typeof item === "object") {
|
|
14165
|
+
const object = item;
|
|
14166
|
+
return pick(object.text ?? object.value ?? object.lines ?? "");
|
|
14167
|
+
}
|
|
14168
|
+
return "";
|
|
14169
|
+
};
|
|
14170
|
+
return pick(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, " ");
|
|
14171
|
+
}
|
|
14172
|
+
var requestSpec = {
|
|
14173
|
+
name: "request",
|
|
14174
|
+
summary: "Check the delivery state of a message or environment change (get_request_status)",
|
|
14175
|
+
usage: "peerband request REQUEST_ID [--installation ID | --here]",
|
|
14176
|
+
description: 'Checks a write submitted with `peerband agent send`, `peerband agent ask` or `peerband env`, by the requestId in its receipt: the MCP tool get_request_status, printed as JSON. "Delivered" means the prompt reached Herdr, not that the task finished; environment receipts include result ids when completed. Ask the same machine the write went to.',
|
|
14177
|
+
options: [INSTALLATION, HERE],
|
|
14178
|
+
positionals: { name: "request_id", max: 1 },
|
|
14179
|
+
examples: [["peerband request 6c1d\u2026 --installation 1f0c\u2026", "Did the message arrive?"]],
|
|
14180
|
+
async run(parsed, ctx) {
|
|
14181
|
+
const [id] = parsed.positionals;
|
|
14182
|
+
if (!id) throw new UsageError("Missing the request id.", "Usage: peerband request REQUEST_ID. It is the requestId in a send receipt.");
|
|
14183
|
+
const args = { ...await where(ctx, parsed), request_id: id };
|
|
14184
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "get_request_status", args));
|
|
14185
|
+
}
|
|
14186
|
+
};
|
|
14187
|
+
var ENV_ACTIONS = {
|
|
14188
|
+
"workspace.create": ["cwd"],
|
|
14189
|
+
"tab.create": ["workspace-id", "cwd"],
|
|
14190
|
+
"pane.split": ["pane-id", "cwd", "direction"],
|
|
14191
|
+
"agent.start": ["pane-id", "name", "kind"],
|
|
14192
|
+
"agent.rename": ["pane-id", "name"],
|
|
14193
|
+
"workspace.rename": ["workspace-id", "label"],
|
|
14194
|
+
"tab.rename": ["tab-id", "label"],
|
|
14195
|
+
"pane.rename": ["pane-id", "label"],
|
|
14196
|
+
"workspace.focus": ["workspace-id"],
|
|
14197
|
+
"tab.focus": ["tab-id"],
|
|
14198
|
+
"pane.focus": ["pane-id"],
|
|
14199
|
+
"workspace.close": ["workspace-id"],
|
|
14200
|
+
"tab.close": ["tab-id"],
|
|
14201
|
+
"pane.close": ["pane-id"]
|
|
14202
|
+
};
|
|
14203
|
+
var ENV_FIELDS = ["workspace-id", "tab-id", "pane-id", "cwd", "label", "direction", "name", "kind"];
|
|
14204
|
+
var envSpec = {
|
|
14205
|
+
name: "env",
|
|
14206
|
+
summary: "List or change this machine's Herdr workspaces, tabs and panes (list_environment, control_environment)",
|
|
14207
|
+
usage: "peerband env list --here | peerband env ACTION --here [--workspace-id ID] [--tab-id ID] [--pane-id ID] [--cwd PATH] [--label TEXT] [--direction D] [--name NAME] [--kind KIND] [--key KEY]",
|
|
14208
|
+
description: [
|
|
14209
|
+
"`peerband env list` is the MCP tool list_environment: the workspaces, tabs and panes, including panes without an agent. Metadata only; labels are untrusted.",
|
|
14210
|
+
"",
|
|
14211
|
+
"`peerband env ACTION` is control_environment, with the same actions and fields:",
|
|
14212
|
+
" workspace.create --cwd [--label] tab.create --workspace-id --cwd [--label]",
|
|
14213
|
+
" pane.split --pane-id --cwd --direction right|down|left|up",
|
|
14214
|
+
" agent.start --pane-id --name --kind (an idle shell pane; then `peerband agents` for its id)",
|
|
14215
|
+
" agent.rename --pane-id --name",
|
|
14216
|
+
" workspace/tab/pane.rename --<target>-id --label workspace/tab/pane.focus --<target>-id",
|
|
14217
|
+
" workspace/tab/pane.close --<target>-id ends everything running there; only when the owner asked for it",
|
|
14218
|
+
"It returns a durable receipt: check it with `peerband request --here`. Reuse the same --key to retry; never a new one for an uncertain write.",
|
|
14219
|
+
"",
|
|
14220
|
+
`From the CLI, environment control reaches this machine only (pass --here). Other machines need the dashboard or an MCP client with environment:control consent. The connector's own switch ("enableEnvironmentControl": false) still turns it off. There is no shell typing, agent stop or permission approval.`
|
|
14221
|
+
].join("\n"),
|
|
14222
|
+
options: [
|
|
14223
|
+
INSTALLATION,
|
|
14224
|
+
HERE,
|
|
14225
|
+
{ name: "workspace-id", type: "string", valueName: "ID", description: "Workspace id from `peerband env list`." },
|
|
14226
|
+
{ name: "tab-id", type: "string", valueName: "ID", description: "Tab id." },
|
|
14227
|
+
{ name: "pane-id", type: "string", valueName: "ID", description: "Pane id." },
|
|
14228
|
+
{ name: "cwd", type: "string", valueName: "PATH", description: "Absolute working directory on this machine." },
|
|
14229
|
+
{ name: "label", type: "string", valueName: "TEXT", description: "Name for a new or renamed workspace, tab or pane." },
|
|
14230
|
+
{ name: "direction", type: "string", valueName: "D", description: "pane.split: right, down, left or up." },
|
|
14231
|
+
{ name: "name", type: "string", valueName: "NAME", description: "agent.start / agent.rename: the agent name." },
|
|
14232
|
+
{ name: "kind", type: "string", valueName: "KIND", description: "agent.start: the agent to start, e.g. claude or codex." },
|
|
14233
|
+
KEY
|
|
14234
|
+
],
|
|
14235
|
+
positionals: { name: "action", max: 1 },
|
|
14236
|
+
examples: [
|
|
14237
|
+
["peerband env list --here", "This machine's workspaces, tabs and panes"],
|
|
14238
|
+
["peerband env pane.split --here --pane-id p_3 --cwd /home/me/app --direction right", "Open a new pane"],
|
|
14239
|
+
["peerband env agent.start --here --pane-id p_4 --name reviewer --kind claude", "Start an agent in an idle pane"]
|
|
14240
|
+
],
|
|
14241
|
+
notes: ["Needs `peerband login`, and the relay running on this machine."],
|
|
14242
|
+
async run(parsed, ctx) {
|
|
14243
|
+
const [action] = parsed.positionals;
|
|
14244
|
+
if (!action) throw new UsageError("Missing the action.", "Use `peerband env list --here`, or an action such as pane.split. Run `peerband env --help`.");
|
|
14245
|
+
const base = await where(ctx, parsed);
|
|
14246
|
+
if (!base.installation_id) throw new UsageError("Environment commands need an explicit machine.", "Pass --here for this machine.");
|
|
14247
|
+
if (action === "list") return runTool(ctx, (credentials) => callTool(ctx, credentials, "list_environment", base));
|
|
14248
|
+
const needs = ENV_ACTIONS[action];
|
|
14249
|
+
if (!needs) throw new UsageError(`Unknown environment action "${sanitize(action)}".`, `Use list or one of: ${Object.keys(ENV_ACTIONS).join(", ")}.`);
|
|
14250
|
+
const allowed = /* @__PURE__ */ new Set([...needs, ...action.endsWith(".create") && action !== "agent.start" ? ["label"] : []]);
|
|
14251
|
+
const missing = needs.filter((name) => str(parsed, name) === void 0);
|
|
14252
|
+
if (missing.length) throw new UsageError(`${action} needs ${missing.map((name) => `--${name}`).join(", ")}.`, "Run `peerband env --help`.");
|
|
14253
|
+
const extra = ENV_FIELDS.filter((name) => str(parsed, name) !== void 0 && !allowed.has(name));
|
|
14254
|
+
if (extra.length) throw new UsageError(`${action} does not take ${extra.map((name) => `--${name}`).join(", ")}.`, "Run `peerband env --help`.");
|
|
14255
|
+
const idempotency = key(parsed);
|
|
14256
|
+
const args = { ...base, action, idempotency_key: idempotency };
|
|
14257
|
+
for (const name of allowed) if (str(parsed, name) !== void 0) args[name.replace("-", "_")] = str(parsed, name);
|
|
14258
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "control_environment", args), idempotency);
|
|
14259
|
+
}
|
|
14260
|
+
};
|
|
14261
|
+
var CONCIERGE_USAGE = {
|
|
14262
|
+
ask: 'peerband concierge ask "<task>" [--thread ID] [--key KEY] [--wait SECONDS]',
|
|
14263
|
+
run: "peerband concierge run RUN_ID",
|
|
14264
|
+
cancel: "peerband concierge cancel RUN_ID",
|
|
14265
|
+
inbox: "peerband concierge inbox [--unread] [--limit N]",
|
|
14266
|
+
reply: 'peerband concierge reply NOTE_ID "<message>" [--key KEY]'
|
|
14267
|
+
};
|
|
14268
|
+
var RUN_DONE = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "needs_input"]);
|
|
14269
|
+
var conciergeSpec = {
|
|
14270
|
+
name: "concierge",
|
|
14271
|
+
summary: "Give the PeerBand concierge a task, follow it, and answer notes (Premium)",
|
|
14272
|
+
usage: "peerband concierge <ask|run|cancel|inbox|reply> [...]",
|
|
14273
|
+
description: [
|
|
14274
|
+
"The AI Concierge is a PeerBand agent over all your agents (Premium, when the server has it on). Each action is one MCP tool with the same JSON result:",
|
|
14275
|
+
"",
|
|
14276
|
+
` ${CONCIERGE_USAGE.ask}`,
|
|
14277
|
+
" concierge_ask: starts a run and returns its run_id at once. --thread continues an earlier conversation; --wait SECONDS keeps reading the run until it ends.",
|
|
14278
|
+
` ${CONCIERGE_USAGE.run}`,
|
|
14279
|
+
" concierge_get_run: the run status and, when done, its answer.",
|
|
14280
|
+
` ${CONCIERGE_USAGE.cancel}`,
|
|
14281
|
+
" concierge_cancel: stops the run; messages it already sent stay with the agents.",
|
|
14282
|
+
` ${CONCIERGE_USAGE.inbox}`,
|
|
14283
|
+
" concierge_inbox: notes your agents sent with `peerband notify` (untrusted text).",
|
|
14284
|
+
` ${CONCIERGE_USAGE.reply}`,
|
|
14285
|
+
" concierge_reply: sends your reply to the exact agent that wrote the note.",
|
|
14286
|
+
"",
|
|
14287
|
+
"Runs started from this machine are filed under this machine (like an MCP client's runs under that app); the dashboard sees all of them. From the CLI the concierge has read and message access, not environment control."
|
|
14288
|
+
].join("\n"),
|
|
14289
|
+
options: [
|
|
14290
|
+
{ name: "thread", type: "string", valueName: "ID", description: "ask: continue this thread_id." },
|
|
14291
|
+
{ name: "wait", type: "string", valueName: "SECONDS", description: `ask: wait up to this long for the run to end (1 to ${MAX_WAIT}).` },
|
|
14292
|
+
{ name: "unread", type: "boolean", description: "inbox: unread notes only." },
|
|
14293
|
+
{ name: "limit", type: "string", valueName: "N", description: "inbox: at most N notes (1 to 100)." },
|
|
14294
|
+
{ name: "key", type: "string", valueName: "KEY", description: "ask/reply: idempotency key (8 to 128 characters). Reuse it to retry." }
|
|
14295
|
+
],
|
|
14296
|
+
positionals: { name: "action", max: 66 },
|
|
14297
|
+
examples: [
|
|
14298
|
+
['peerband concierge ask "Which of my agents are blocked, and on what?" --wait 300', "Ask and wait for the answer"],
|
|
14299
|
+
["peerband concierge inbox --unread", "Unread notes from your agents"]
|
|
14300
|
+
],
|
|
14301
|
+
notes: ["Needs `peerband login` and a Premium account."],
|
|
14302
|
+
async run(parsed, ctx) {
|
|
14303
|
+
const [action, first, ...rest] = parsed.positionals;
|
|
14304
|
+
if (action === void 0 || !(action in CONCIERGE_USAGE)) {
|
|
14305
|
+
throw new UsageError(action === void 0 ? "Missing the action." : `Unknown concierge action "${sanitize(action)}".`, "Use one of: ask, run, cancel, inbox, reply.");
|
|
14306
|
+
}
|
|
14307
|
+
const usage = CONCIERGE_USAGE[action];
|
|
14308
|
+
const conciergeKey = () => {
|
|
14309
|
+
const value = str(parsed, "key");
|
|
14310
|
+
if (value !== void 0 && (value.length < 8 || value.length > 128)) throw new UsageError("The --key must be 8 to 128 characters.");
|
|
14311
|
+
return value ?? newKey();
|
|
14312
|
+
};
|
|
14313
|
+
const id = (value, what) => {
|
|
14314
|
+
if (!value) throw new UsageError(`Missing the ${what}.`, `Usage: ${usage}`);
|
|
14315
|
+
return value;
|
|
14316
|
+
};
|
|
14317
|
+
switch (action) {
|
|
14318
|
+
case "ask": {
|
|
14319
|
+
const request = await messageText(first === void 0 ? [] : [first, ...rest], ctx, usage);
|
|
14320
|
+
const wait = integer(parsed, "wait", 1, MAX_WAIT);
|
|
14321
|
+
const idempotency = conciergeKey();
|
|
14322
|
+
const args = { request, idempotency_key: idempotency, ...str(parsed, "thread") ? { thread_id: str(parsed, "thread") } : {} };
|
|
14323
|
+
return runTool(ctx, async (credentials) => {
|
|
14324
|
+
const run3 = await callTool(ctx, credentials, "concierge_ask", args);
|
|
14325
|
+
if (wait === void 0 || typeof run3.run_id !== "string") return run3;
|
|
14326
|
+
return followRun(ctx, credentials, run3.run_id, wait, run3);
|
|
14327
|
+
}, idempotency);
|
|
14328
|
+
}
|
|
14329
|
+
case "run":
|
|
14330
|
+
case "cancel": {
|
|
14331
|
+
const runId = id(first, "run id");
|
|
14332
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14333
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, action === "run" ? "concierge_get_run" : "concierge_cancel", { run_id: runId }));
|
|
14334
|
+
}
|
|
14335
|
+
case "inbox": {
|
|
14336
|
+
if (first !== void 0) throw new UsageError(`Unexpected argument "${sanitize(first)}".`, `Usage: ${usage}`);
|
|
14337
|
+
const limit = integer(parsed, "limit", 1, 100);
|
|
14338
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "concierge_inbox", { unread_only: flag(parsed, "unread"), ...limit !== void 0 ? { limit } : {} }));
|
|
14339
|
+
}
|
|
14340
|
+
default: {
|
|
14341
|
+
const noteId = id(first, "note id");
|
|
14342
|
+
const message = await messageText(rest, ctx, usage);
|
|
14343
|
+
const idempotency = conciergeKey();
|
|
14344
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "concierge_reply", { note_id: noteId, message, idempotency_key: idempotency }), idempotency);
|
|
14345
|
+
}
|
|
14346
|
+
}
|
|
14347
|
+
}
|
|
14348
|
+
};
|
|
14349
|
+
async function followRun(ctx, credentials, runId, seconds, last) {
|
|
14350
|
+
const now2 = () => ctx.now ? ctx.now() : Date.now();
|
|
14351
|
+
const sleep = (ms) => ctx.sleep ? ctx.sleep(ms, ctx.signal) : new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
14352
|
+
const deadline = now2() + seconds * 1e3;
|
|
14353
|
+
let view = last;
|
|
14354
|
+
while (!RUN_DONE.has(String(view.status)) && now2() < deadline) {
|
|
14355
|
+
await sleep(Math.min(3e3, Math.max(0, deadline - now2())));
|
|
14356
|
+
view = await callTool(ctx, credentials, "concierge_get_run", { run_id: runId });
|
|
14357
|
+
}
|
|
14358
|
+
return view;
|
|
14359
|
+
}
|
|
14360
|
+
var toolsSpec = {
|
|
14361
|
+
name: "tools",
|
|
14362
|
+
summary: "List the PeerBand tools this machine can call",
|
|
14363
|
+
usage: "peerband tools",
|
|
14364
|
+
description: `Lists the PeerBand MCP tools this server offers the CLI (the concierge tools only when it is on), with the access this machine's login carries. Call any of them with \`peerband tool NAME '{"arg": "value"}'\`.`,
|
|
14365
|
+
options: [],
|
|
14366
|
+
examples: [["peerband tools", "What this machine can do through PeerBand"]],
|
|
14367
|
+
run: (_parsed, ctx) => runTool(ctx, (credentials) => listTools(ctx, credentials))
|
|
14368
|
+
};
|
|
14369
|
+
var toolSpec = {
|
|
14370
|
+
name: "tool",
|
|
14371
|
+
summary: "Call a PeerBand MCP tool by name with JSON arguments",
|
|
14372
|
+
usage: `peerband tool NAME ['{"arg": "value"}' | -]`,
|
|
14373
|
+
description: 'Calls one PeerBand MCP tool with exactly the arguments an MCP client would send (a JSON object, or "-" to read it from standard input) and prints its structured result as JSON. The named commands (`peerband agents`, `peerband agent ask`, ...) are friendlier; this one is for scripts and for tools without a command of their own. wait_for_agent and ask_agent are single calls here (at most 50 seconds).',
|
|
14374
|
+
options: [],
|
|
14375
|
+
positionals: { name: "name", max: 2 },
|
|
14376
|
+
examples: [
|
|
14377
|
+
["peerband tool list_machines", "Same as peerband machines"],
|
|
14378
|
+
[`peerband tool get_agent_status '{"agent_id": "herdr_1a2b\u2026", "installation_id": "1f0c\u2026"}'`, "Any tool, any arguments"]
|
|
14379
|
+
],
|
|
14380
|
+
async run(parsed, ctx) {
|
|
14381
|
+
const [name, json] = parsed.positionals;
|
|
14382
|
+
if (!name || !/^[a-z_]{1,64}$/.test(name)) throw new UsageError("Missing or invalid tool name.", "Run `peerband tools` to list them.");
|
|
14383
|
+
const raw = json === "-" ? await readStdin(ctx) : json ?? "{}";
|
|
14384
|
+
let args;
|
|
14385
|
+
try {
|
|
14386
|
+
args = JSON.parse(raw);
|
|
14387
|
+
} catch {
|
|
14388
|
+
throw new UsageError("The arguments are not valid JSON.", `Pass a JSON object, for example '{"agent_id": "\u2026"}'.`);
|
|
14389
|
+
}
|
|
14390
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) throw new UsageError("The arguments must be a JSON object.");
|
|
14391
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, name, args, 12e4));
|
|
14392
|
+
}
|
|
14393
|
+
};
|
|
14394
|
+
var toolCommands = [machinesSpec, agentsSpec, agentSpec, requestSpec, envSpec, conciergeSpec, toolsSpec, toolSpec];
|
|
14395
|
+
|
|
13783
14396
|
// src/cli/commands/channels.ts
|
|
13784
14397
|
var NO_CHANNEL_SUPPORT = "This PeerBand server doesn't support channels yet.";
|
|
13785
14398
|
var TELEGRAM_CHANNEL = "telegram";
|
|
@@ -13848,7 +14461,7 @@ var spec = {
|
|
|
13848
14461
|
// herdr/relay-tab.mjs
|
|
13849
14462
|
import { execFile as execFile2 } from "node:child_process";
|
|
13850
14463
|
import { mkdir as mkdir4, readFile as readFile4, rename as rename3, rm as rm3, rmdir as rmdir2, stat, writeFile as writeFile4 } from "node:fs/promises";
|
|
13851
|
-
import { randomUUID as
|
|
14464
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
13852
14465
|
import { dirname as dirname4 } from "node:path";
|
|
13853
14466
|
|
|
13854
14467
|
// herdr/paths.mjs
|
|
@@ -13946,7 +14559,7 @@ async function readRecord(statePath) {
|
|
|
13946
14559
|
}
|
|
13947
14560
|
async function writeRecord(statePath, record) {
|
|
13948
14561
|
await mkdir4(dirname4(statePath), { recursive: true });
|
|
13949
|
-
const temporary = `${statePath}.${
|
|
14562
|
+
const temporary = `${statePath}.${randomUUID4()}.tmp`;
|
|
13950
14563
|
try {
|
|
13951
14564
|
await writeFile4(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
13952
14565
|
await rename3(temporary, statePath);
|
|
@@ -13969,7 +14582,7 @@ async function withLaunchLock(statePath, action) {
|
|
|
13969
14582
|
try {
|
|
13970
14583
|
const info = await stat(lockPath3);
|
|
13971
14584
|
if (Date.now() - info.mtimeMs > 12e4) {
|
|
13972
|
-
const quarantine = `${lockPath3}.stale-${
|
|
14585
|
+
const quarantine = `${lockPath3}.stale-${randomUUID4()}`;
|
|
13973
14586
|
await rename3(lockPath3, quarantine).then(() => rmdir2(quarantine)).catch(() => {
|
|
13974
14587
|
});
|
|
13975
14588
|
stale = true;
|
|
@@ -13979,7 +14592,7 @@ async function withLaunchLock(statePath, action) {
|
|
|
13979
14592
|
}
|
|
13980
14593
|
if (stale) continue;
|
|
13981
14594
|
if (Date.now() >= deadline) throw new Error("Another PeerBand Relay tab launch is already in progress");
|
|
13982
|
-
await new Promise((
|
|
14595
|
+
await new Promise((resolve6) => setTimeout(resolve6, 100));
|
|
13983
14596
|
}
|
|
13984
14597
|
}
|
|
13985
14598
|
try {
|
|
@@ -14024,7 +14637,7 @@ async function renameOwnedSinglePaneTab(run3, pane, label) {
|
|
|
14024
14637
|
await run3(["tab", "rename", pane.tab_id, label]);
|
|
14025
14638
|
return true;
|
|
14026
14639
|
}
|
|
14027
|
-
function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker =
|
|
14640
|
+
function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker = randomUUID4, warn = () => {
|
|
14028
14641
|
} }) {
|
|
14029
14642
|
if (typeof run3 !== "function" || typeof statePath !== "string") throw new TypeError("run and statePath are required");
|
|
14030
14643
|
const lastVerifiedTitle = /* @__PURE__ */ new Map();
|
|
@@ -14036,10 +14649,10 @@ function createRelayTabController({ run: run3, statePath, pluginPaneId = "", new
|
|
|
14036
14649
|
if (!pane) return false;
|
|
14037
14650
|
try {
|
|
14038
14651
|
const label = tabTitle(enabled);
|
|
14039
|
-
const
|
|
14040
|
-
if (lastVerifiedTitle.get(
|
|
14652
|
+
const key2 = `${pane.pane_id}\0${pane.tab_id}`;
|
|
14653
|
+
if (lastVerifiedTitle.get(key2) === label) return true;
|
|
14041
14654
|
const renamed = await renameOwnedSinglePaneTab(run3, pane, label);
|
|
14042
|
-
if (renamed) lastVerifiedTitle.set(
|
|
14655
|
+
if (renamed) lastVerifiedTitle.set(key2, label);
|
|
14043
14656
|
return renamed;
|
|
14044
14657
|
} catch {
|
|
14045
14658
|
return false;
|
|
@@ -14158,7 +14771,7 @@ function paneLabel(snapshot) {
|
|
|
14158
14771
|
|
|
14159
14772
|
// herdr/stale-lock.mjs
|
|
14160
14773
|
import { execFile as execFile3 } from "node:child_process";
|
|
14161
|
-
import { randomUUID as
|
|
14774
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
14162
14775
|
import { readdir, readFile as readFile5, rename as rename4, rm as rm4, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
|
|
14163
14776
|
import { createConnection } from "node:net";
|
|
14164
14777
|
import { hostname as hostname2 } from "node:os";
|
|
@@ -14176,24 +14789,24 @@ function pidAlive2(pid) {
|
|
|
14176
14789
|
}
|
|
14177
14790
|
}
|
|
14178
14791
|
function probeChannel(channel, timeout = 1500) {
|
|
14179
|
-
return new Promise((
|
|
14792
|
+
return new Promise((resolve6) => {
|
|
14180
14793
|
let settled = false;
|
|
14181
14794
|
const socket = createConnection(channel);
|
|
14182
|
-
const
|
|
14795
|
+
const finish2 = (value) => {
|
|
14183
14796
|
if (settled) return;
|
|
14184
14797
|
settled = true;
|
|
14185
14798
|
clearTimeout(timer);
|
|
14186
14799
|
socket.destroy();
|
|
14187
|
-
|
|
14800
|
+
resolve6(value);
|
|
14188
14801
|
};
|
|
14189
|
-
const timer = setTimeout(() =>
|
|
14190
|
-
socket.once("connect", () =>
|
|
14191
|
-
socket.once("error", (error) =>
|
|
14802
|
+
const timer = setTimeout(() => finish2("unknown"), timeout);
|
|
14803
|
+
socket.once("connect", () => finish2("listening"));
|
|
14804
|
+
socket.once("error", (error) => finish2(error && (error.code === "ENOENT" || error.code === "ECONNREFUSED") ? "absent" : "unknown"));
|
|
14192
14805
|
});
|
|
14193
14806
|
}
|
|
14194
14807
|
function run(file, args, timeout) {
|
|
14195
|
-
return new Promise((
|
|
14196
|
-
execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) =>
|
|
14808
|
+
return new Promise((resolve6) => {
|
|
14809
|
+
execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve6(error ? null : String(stdout)));
|
|
14197
14810
|
});
|
|
14198
14811
|
}
|
|
14199
14812
|
async function listProcesses(platform = process.platform) {
|
|
@@ -14249,7 +14862,7 @@ async function readOwner(ownerFile) {
|
|
|
14249
14862
|
}
|
|
14250
14863
|
return { text: text2, owner: {} };
|
|
14251
14864
|
}
|
|
14252
|
-
async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list3 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now = Date.now() }) {
|
|
14865
|
+
async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list3 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now: now2 = Date.now() }) {
|
|
14253
14866
|
let info;
|
|
14254
14867
|
try {
|
|
14255
14868
|
info = await stat2(lockDir);
|
|
@@ -14278,7 +14891,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
|
|
|
14278
14891
|
}
|
|
14279
14892
|
return { state: "live", reason: `owner process ${pid} is running`, ownerText: text2, pid };
|
|
14280
14893
|
}
|
|
14281
|
-
if (text2 === null &&
|
|
14894
|
+
if (text2 === null && now2 - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
|
|
14282
14895
|
if (channel) {
|
|
14283
14896
|
const probed = await probe(channel);
|
|
14284
14897
|
if (probed === "listening") return { state: "live", reason: "a helper answers on the control channel", ownerText: text2 };
|
|
@@ -14293,7 +14906,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
|
|
|
14293
14906
|
return { state: "stale", reason: "no matching process is running", ownerText: text2 };
|
|
14294
14907
|
}
|
|
14295
14908
|
async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
|
|
14296
|
-
const quarantine = `${lockDir}.stale-${
|
|
14909
|
+
const quarantine = `${lockDir}.stale-${randomUUID5()}`;
|
|
14297
14910
|
try {
|
|
14298
14911
|
await rename4(lockDir, quarantine);
|
|
14299
14912
|
} catch (error) {
|
|
@@ -14353,31 +14966,31 @@ var FIELDS2 = ["workspace_id", "tab_id", "pane_id", "name", "label", "cwd", "age
|
|
|
14353
14966
|
function metadata(value) {
|
|
14354
14967
|
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
14355
14968
|
const row = value;
|
|
14356
|
-
const result = Object.fromEntries(FIELDS2.filter((
|
|
14357
|
-
for (const
|
|
14969
|
+
const result = Object.fromEntries(FIELDS2.filter((key2) => typeof row[key2] === "string").map((key2) => [key2.replace(/_([a-z])/g, (_, c) => c.toUpperCase()), sanitizeOutput(row[key2], { bytes: key2 === "cwd" ? 2048 : 256, lines: 1 }).text]));
|
|
14970
|
+
for (const key2 of ["number", "pane_count", "tab_count"]) if (Number.isSafeInteger(row[key2]) && row[key2] >= 0) result[key2.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = row[key2];
|
|
14358
14971
|
if (typeof row.focused === "boolean") result.focused = row.focused;
|
|
14359
14972
|
return result;
|
|
14360
14973
|
}
|
|
14361
14974
|
function environmentMetadata(value) {
|
|
14362
14975
|
const row = value && typeof value === "object" ? value : {};
|
|
14363
14976
|
const result = metadata(row);
|
|
14364
|
-
for (const
|
|
14365
|
-
if (row[
|
|
14977
|
+
for (const key2 of ["workspace", "tab", "pane", "root_pane", "agent"]) {
|
|
14978
|
+
if (row[key2] && typeof row[key2] === "object") result[key2.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = metadata(row[key2]);
|
|
14366
14979
|
}
|
|
14367
14980
|
return result;
|
|
14368
14981
|
}
|
|
14369
14982
|
async function listEnvironment(client) {
|
|
14370
14983
|
const result = { actions: [...ENVIRONMENT_ACTIONS] };
|
|
14371
|
-
for (const [method,
|
|
14984
|
+
for (const [method, key2] of [["workspace.list", "workspaces"], ["tab.list", "tabs"], ["pane.list", "panes"]]) {
|
|
14372
14985
|
const response = await client.request(method, {});
|
|
14373
|
-
if (!Array.isArray(response[
|
|
14374
|
-
let rows = response[
|
|
14375
|
-
if (
|
|
14986
|
+
if (!Array.isArray(response[key2])) throw new ConnectError("schema_mismatch", `Unexpected ${method} response.`, "Check the installed Herdr schema.");
|
|
14987
|
+
let rows = response[key2];
|
|
14988
|
+
if (key2 === "panes") {
|
|
14376
14989
|
const listed = await client.request("agent.list", {});
|
|
14377
14990
|
rows = rows.map((pane) => ({ ...pane, name: listed.agents?.find((agent) => agent.pane_id === pane.pane_id)?.name }));
|
|
14378
14991
|
}
|
|
14379
|
-
result[
|
|
14380
|
-
result[`${
|
|
14992
|
+
result[key2] = rows.slice(0, 50).map(metadata);
|
|
14993
|
+
result[`${key2}Truncated`] = response[key2].length > 50;
|
|
14381
14994
|
}
|
|
14382
14995
|
if (Buffer.byteLength(JSON.stringify(result), "utf8") > 48 * 1024) throw new ConnectError("response_too_large", "The environment metadata exceeds the frame budget.", "Reduce the session layout before listing it remotely.");
|
|
14383
14996
|
return result;
|
|
@@ -14385,9 +14998,9 @@ async function listEnvironment(client) {
|
|
|
14385
14998
|
function environmentParams(input) {
|
|
14386
14999
|
const command = environmentCommand(input);
|
|
14387
15000
|
const params = {};
|
|
14388
|
-
for (const [
|
|
14389
|
-
if (
|
|
14390
|
-
params[
|
|
15001
|
+
for (const [key2, value] of Object.entries(command)) {
|
|
15002
|
+
if (key2 === "action") continue;
|
|
15003
|
+
params[key2.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = value;
|
|
14391
15004
|
}
|
|
14392
15005
|
if (["workspace.create", "tab.create", "pane.split"].includes(command.action)) params.focus = false;
|
|
14393
15006
|
if (command.action === "pane.split") {
|
|
@@ -14404,28 +15017,28 @@ function environmentParams(input) {
|
|
|
14404
15017
|
}
|
|
14405
15018
|
|
|
14406
15019
|
// src/runtime-herdr/adapter.ts
|
|
14407
|
-
import { createHash as createHash4, randomUUID as
|
|
15020
|
+
import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
|
|
14408
15021
|
import { readFile as readFile7, stat as stat3 } from "node:fs/promises";
|
|
14409
15022
|
import { homedir as homedir3 } from "node:os";
|
|
14410
15023
|
import { join as join6 } from "node:path";
|
|
14411
15024
|
|
|
14412
15025
|
// src/runtime-herdr/subscription.ts
|
|
14413
|
-
import { randomUUID as
|
|
15026
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
14414
15027
|
import { createConnection as createConnection2 } from "node:net";
|
|
14415
15028
|
function openSubscription(options) {
|
|
14416
|
-
const id = `sub_${
|
|
15029
|
+
const id = `sub_${randomUUID6()}`;
|
|
14417
15030
|
const request = { id, method: "events.subscribe", params: { subscriptions: options.subscriptions } };
|
|
14418
15031
|
const maxLineBytes = options.maxLineBytes ?? 1024 * 1024;
|
|
14419
15032
|
let acknowledged = false;
|
|
14420
15033
|
let resolveStarted;
|
|
14421
15034
|
let rejectStarted;
|
|
14422
15035
|
let resolveClosed;
|
|
14423
|
-
const started = new Promise((
|
|
14424
|
-
resolveStarted =
|
|
15036
|
+
const started = new Promise((resolve6, reject) => {
|
|
15037
|
+
resolveStarted = resolve6;
|
|
14425
15038
|
rejectStarted = reject;
|
|
14426
15039
|
});
|
|
14427
|
-
const closed = new Promise((
|
|
14428
|
-
resolveClosed =
|
|
15040
|
+
const closed = new Promise((resolve6) => {
|
|
15041
|
+
resolveClosed = resolve6;
|
|
14429
15042
|
});
|
|
14430
15043
|
void started.catch(() => void 0);
|
|
14431
15044
|
if (options.validateRequest && !options.validateRequest(request)) {
|
|
@@ -14518,8 +15131,8 @@ var HerdrEventBridge = class {
|
|
|
14518
15131
|
constructor(host, options = {}) {
|
|
14519
15132
|
this.host = host;
|
|
14520
15133
|
this.log = options.log ?? (() => void 0);
|
|
14521
|
-
this.sleep = options.sleep ?? ((ms) => new Promise((
|
|
14522
|
-
const timer = setTimeout(
|
|
15134
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve6) => {
|
|
15135
|
+
const timer = setTimeout(resolve6, ms);
|
|
14523
15136
|
timer.unref?.();
|
|
14524
15137
|
}));
|
|
14525
15138
|
this.random = options.random ?? Math.random;
|
|
@@ -14638,8 +15251,8 @@ var HerdrEventBridge = class {
|
|
|
14638
15251
|
}
|
|
14639
15252
|
}
|
|
14640
15253
|
async pause(ms) {
|
|
14641
|
-
await Promise.race([this.sleep(ms), new Promise((
|
|
14642
|
-
this.wake =
|
|
15254
|
+
await Promise.race([this.sleep(ms), new Promise((resolve6) => {
|
|
15255
|
+
this.wake = resolve6;
|
|
14643
15256
|
})]);
|
|
14644
15257
|
this.wake = void 0;
|
|
14645
15258
|
}
|
|
@@ -14715,7 +15328,7 @@ function sameSet(a, b) {
|
|
|
14715
15328
|
}
|
|
14716
15329
|
|
|
14717
15330
|
// src/runtime-herdr/socket-client.ts
|
|
14718
|
-
import { randomUUID as
|
|
15331
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
14719
15332
|
import { createConnection as createConnection3 } from "node:net";
|
|
14720
15333
|
var HerdrSocketClient = class {
|
|
14721
15334
|
socketPath;
|
|
@@ -14748,7 +15361,7 @@ var HerdrSocketClient = class {
|
|
|
14748
15361
|
async request(method, params = {}) {
|
|
14749
15362
|
if (this.closed) throw this.unavailable("Herdr socket client is closed");
|
|
14750
15363
|
if (this.inflight >= this.maxPending) throw this.unavailable("Too many Herdr requests are in flight");
|
|
14751
|
-
const id =
|
|
15364
|
+
const id = randomUUID7();
|
|
14752
15365
|
const request = { id, method, params };
|
|
14753
15366
|
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.");
|
|
14754
15367
|
const line = Buffer.from(`${JSON.stringify(request)}
|
|
@@ -14762,7 +15375,7 @@ var HerdrSocketClient = class {
|
|
|
14762
15375
|
this.inflight -= 1;
|
|
14763
15376
|
throw error;
|
|
14764
15377
|
}
|
|
14765
|
-
return new Promise((
|
|
15378
|
+
return new Promise((resolve6, reject) => {
|
|
14766
15379
|
const timer = setTimeout(() => {
|
|
14767
15380
|
this.pending.delete(id);
|
|
14768
15381
|
this.inflight -= 1;
|
|
@@ -14770,7 +15383,7 @@ var HerdrSocketClient = class {
|
|
|
14770
15383
|
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."));
|
|
14771
15384
|
}, this.timeoutMs);
|
|
14772
15385
|
timer.unref?.();
|
|
14773
|
-
this.pending.set(id, { resolve:
|
|
15386
|
+
this.pending.set(id, { resolve: resolve6, reject, timer, method, socket });
|
|
14774
15387
|
socket.write(line, (error) => {
|
|
14775
15388
|
if (!error) return;
|
|
14776
15389
|
const pending = this.pending.get(id);
|
|
@@ -14786,13 +15399,13 @@ var HerdrSocketClient = class {
|
|
|
14786
15399
|
async close() {
|
|
14787
15400
|
this.closed = true;
|
|
14788
15401
|
this.failAll(this.unavailable("Herdr socket client closed"));
|
|
14789
|
-
await Promise.all([...this.sockets].map((socket) => new Promise((
|
|
14790
|
-
if (socket.destroyed)
|
|
14791
|
-
else socket.end(
|
|
15402
|
+
await Promise.all([...this.sockets].map((socket) => new Promise((resolve6) => {
|
|
15403
|
+
if (socket.destroyed) resolve6();
|
|
15404
|
+
else socket.end(resolve6);
|
|
14792
15405
|
})));
|
|
14793
15406
|
}
|
|
14794
15407
|
connect() {
|
|
14795
|
-
return new Promise((
|
|
15408
|
+
return new Promise((resolve6, reject) => {
|
|
14796
15409
|
const socket = createConnection3(this.socketPath);
|
|
14797
15410
|
const onError = () => {
|
|
14798
15411
|
socket.destroy();
|
|
@@ -14813,7 +15426,7 @@ var HerdrSocketClient = class {
|
|
|
14813
15426
|
this.buffers.delete(socket);
|
|
14814
15427
|
this.failSocket(socket, this.unavailable("Herdr closed the socket before replying"));
|
|
14815
15428
|
});
|
|
14816
|
-
|
|
15429
|
+
resolve6(socket);
|
|
14817
15430
|
});
|
|
14818
15431
|
});
|
|
14819
15432
|
}
|
|
@@ -15036,7 +15649,7 @@ var HerdrAdapter = class {
|
|
|
15036
15649
|
if (!isAgent(raw)) throw this.schemaMismatch("agent.list contained an invalid agent record");
|
|
15037
15650
|
const fingerprint = identityFingerprint(raw);
|
|
15038
15651
|
const previous = !reconnected ? previousTargets.find((item) => item.fingerprint === fingerprint) : void 0;
|
|
15039
|
-
const id = previous?.id ?? `herdr_${
|
|
15652
|
+
const id = previous?.id ?? `herdr_${randomUUID8()}`;
|
|
15040
15653
|
const live = { id, fingerprint, agent: raw };
|
|
15041
15654
|
next.set(raw.pane_id, live);
|
|
15042
15655
|
nextIds.add(id);
|
|
@@ -15149,7 +15762,7 @@ var HerdrAdapter = class {
|
|
|
15149
15762
|
async controlEnvironment(command) {
|
|
15150
15763
|
const params = environmentParams(command);
|
|
15151
15764
|
const { schema, client } = await this.initialize();
|
|
15152
|
-
const request = { id:
|
|
15765
|
+
const request = { id: randomUUID8(), method: command.action, params };
|
|
15153
15766
|
if (!schema.validateRequest(request)) throw new ConnectError("unsupported_capability", "The installed Herdr API does not support this environment action.", "Update Herdr and use its matching schema.");
|
|
15154
15767
|
const result = asObject(await client.request(command.action, params));
|
|
15155
15768
|
const expected = command.action === "workspace.create" ? "workspace_created" : command.action === "tab.create" ? "tab_created" : command.action === "agent.start" ? "agent_started" : command.action === "agent.rename" ? "agent_info" : void 0;
|
|
@@ -15206,12 +15819,12 @@ async function readLayout(client) {
|
|
|
15206
15819
|
]);
|
|
15207
15820
|
return { spaces, tabs };
|
|
15208
15821
|
}
|
|
15209
|
-
function layoutEntries(result, type,
|
|
15822
|
+
function layoutEntries(result, type, key2, idKey) {
|
|
15210
15823
|
const entries = /* @__PURE__ */ new Map();
|
|
15211
15824
|
if (!result || typeof result !== "object") return entries;
|
|
15212
15825
|
const value = result;
|
|
15213
|
-
if (value.type !== type || !Array.isArray(value[
|
|
15214
|
-
for (const item of value[
|
|
15826
|
+
if (value.type !== type || !Array.isArray(value[key2])) return entries;
|
|
15827
|
+
for (const item of value[key2]) {
|
|
15215
15828
|
if (!item || typeof item !== "object") continue;
|
|
15216
15829
|
const row = item;
|
|
15217
15830
|
if (typeof row[idKey] !== "string") continue;
|
|
@@ -15309,6 +15922,619 @@ async function readEndpointMarker(socketPath) {
|
|
|
15309
15922
|
}
|
|
15310
15923
|
}
|
|
15311
15924
|
|
|
15925
|
+
// src/runtime-herdr-core/adapter.ts
|
|
15926
|
+
import { createHash as createHash5, randomUUID as randomUUID9 } from "node:crypto";
|
|
15927
|
+
|
|
15928
|
+
// src/runtime-herdr-core/layout.ts
|
|
15929
|
+
var LAYOUT_DOC = "herdr-app";
|
|
15930
|
+
var BACKGROUND_SPACE_ID = "hc-background";
|
|
15931
|
+
var BACKGROUND_TAB_ID = "hc-background-tab";
|
|
15932
|
+
var BACKGROUND_SPACE_LABEL = "Background";
|
|
15933
|
+
var BACKGROUND_TAB_LABEL = "Not in a tab";
|
|
15934
|
+
var LOCAL_ADDRESS = /^t[0-9]{1,12}$/;
|
|
15935
|
+
var ID = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,255}$/;
|
|
15936
|
+
var MAX_NODES = 1e4;
|
|
15937
|
+
var emptyLayout = () => ({ spaces: [], byTerminal: /* @__PURE__ */ new Map() });
|
|
15938
|
+
function cleanLabel(value) {
|
|
15939
|
+
if (typeof value !== "string") return null;
|
|
15940
|
+
const label = value.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, 128);
|
|
15941
|
+
return label || null;
|
|
15942
|
+
}
|
|
15943
|
+
function folderName(folder) {
|
|
15944
|
+
if (typeof folder !== "string") return null;
|
|
15945
|
+
const parts = folder.split(/[\\/]/).filter(Boolean);
|
|
15946
|
+
return cleanLabel(parts[parts.length - 1]);
|
|
15947
|
+
}
|
|
15948
|
+
function addTerminal(content, found) {
|
|
15949
|
+
const terminal = content && typeof content === "object" ? content.terminal : void 0;
|
|
15950
|
+
if (typeof terminal === "string" && LOCAL_ADDRESS.test(terminal) && !found.includes(terminal)) found.push(terminal);
|
|
15951
|
+
}
|
|
15952
|
+
function terminalsIn(node, found, budget) {
|
|
15953
|
+
if (budget.left-- <= 0 || !node || typeof node !== "object" || Array.isArray(node)) return;
|
|
15954
|
+
const value = node;
|
|
15955
|
+
if (value.type === "block") addTerminal(value.content, found);
|
|
15956
|
+
if (Array.isArray(value.children)) for (const child of value.children) terminalsIn(child, found, budget);
|
|
15957
|
+
if (Array.isArray(value.floating)) {
|
|
15958
|
+
for (const float of value.floating) {
|
|
15959
|
+
if (!float || typeof float !== "object") continue;
|
|
15960
|
+
addTerminal(float.content, found);
|
|
15961
|
+
terminalsIn(float.pane, found, budget);
|
|
15962
|
+
}
|
|
15963
|
+
}
|
|
15964
|
+
}
|
|
15965
|
+
function parseLayout(value) {
|
|
15966
|
+
const layout = emptyLayout();
|
|
15967
|
+
if (!value || typeof value !== "object" || !Array.isArray(value.spaces)) return layout;
|
|
15968
|
+
const budget = { left: MAX_NODES };
|
|
15969
|
+
for (const raw of value.spaces) {
|
|
15970
|
+
if (!raw || typeof raw !== "object") continue;
|
|
15971
|
+
const row = raw;
|
|
15972
|
+
if (typeof row.id !== "string" || !ID.test(row.id) || row.id === BACKGROUND_SPACE_ID) continue;
|
|
15973
|
+
const space = { id: row.id, label: cleanLabel(row.name) ?? folderName(row.folder), number: layout.spaces.length + 1, tabs: [] };
|
|
15974
|
+
for (const rawTab of Array.isArray(row.tabs) ? row.tabs : []) {
|
|
15975
|
+
if (!rawTab || typeof rawTab !== "object") continue;
|
|
15976
|
+
const tabRow = rawTab;
|
|
15977
|
+
if (typeof tabRow.id !== "string" || !ID.test(tabRow.id)) continue;
|
|
15978
|
+
const terminals = [];
|
|
15979
|
+
terminalsIn(tabRow.root, terminals, budget);
|
|
15980
|
+
terminalsIn({ floating: tabRow.floating }, terminals, budget);
|
|
15981
|
+
const tab = { id: tabRow.id, spaceId: space.id, label: cleanLabel(tabRow.name), number: space.tabs.length + 1, terminals };
|
|
15982
|
+
space.tabs.push(tab);
|
|
15983
|
+
for (const address of terminals) if (!layout.byTerminal.has(address)) layout.byTerminal.set(address, { space, tab });
|
|
15984
|
+
}
|
|
15985
|
+
layout.spaces.push(space);
|
|
15986
|
+
}
|
|
15987
|
+
return layout;
|
|
15988
|
+
}
|
|
15989
|
+
|
|
15990
|
+
// src/runtime-herdr-core/rpc.ts
|
|
15991
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
15992
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
15993
|
+
import { homedir as homedir4 } from "node:os";
|
|
15994
|
+
import { join as join7 } from "node:path";
|
|
15995
|
+
import { createInterface } from "node:readline";
|
|
15996
|
+
var CoreRpcError = class extends Error {
|
|
15997
|
+
constructor(kind, message, hint) {
|
|
15998
|
+
super(message);
|
|
15999
|
+
this.kind = kind;
|
|
16000
|
+
this.hint = hint;
|
|
16001
|
+
this.name = "CoreRpcError";
|
|
16002
|
+
}
|
|
16003
|
+
kind;
|
|
16004
|
+
hint;
|
|
16005
|
+
};
|
|
16006
|
+
var MAX_LINE_BYTES = 8 * 1024 * 1024;
|
|
16007
|
+
function resolveCoreBinary(explicit, env = process.env) {
|
|
16008
|
+
if (explicit) return explicit;
|
|
16009
|
+
if (env.HC_BIN) return env.HC_BIN;
|
|
16010
|
+
const fallback = process.platform === "win32" ? join7(env.LOCALAPPDATA ?? join7(homedir4(), "AppData", "Local"), "Programs", "herdr-core", "hc.exe") : join7(homedir4(), ".local", "bin", "hc");
|
|
16011
|
+
const onPath = (env.PATH ?? env.Path ?? "").split(process.platform === "win32" ? ";" : ":").some((dir) => dir && (existsSync2(join7(dir, "hc")) || existsSync2(join7(dir, "hc.exe"))));
|
|
16012
|
+
return !onPath && existsSync2(fallback) ? fallback : "hc";
|
|
16013
|
+
}
|
|
16014
|
+
function spawnCoreStream(binary) {
|
|
16015
|
+
return () => {
|
|
16016
|
+
const child = spawn2(binary, ["connect"], { stdio: ["pipe", "pipe", "ignore"], windowsHide: true, shell: false });
|
|
16017
|
+
const closed = new Promise((resolve6) => {
|
|
16018
|
+
child.once("error", (error) => resolve6(error));
|
|
16019
|
+
child.once("exit", () => resolve6(void 0));
|
|
16020
|
+
});
|
|
16021
|
+
child.stdin.on("error", () => void 0);
|
|
16022
|
+
return { input: child.stdin, output: child.stdout, closed, close: () => {
|
|
16023
|
+
child.kill();
|
|
16024
|
+
} };
|
|
16025
|
+
};
|
|
16026
|
+
}
|
|
16027
|
+
var CoreConnection = class {
|
|
16028
|
+
constructor(stream, onNotification) {
|
|
16029
|
+
this.stream = stream;
|
|
16030
|
+
this.onNotification = onNotification;
|
|
16031
|
+
const lines = createInterface({ input: stream.output, crlfDelay: Infinity });
|
|
16032
|
+
lines.on("line", (line) => this.receive(line));
|
|
16033
|
+
this.done = stream.closed.then((error) => {
|
|
16034
|
+
this.open = false;
|
|
16035
|
+
lines.close();
|
|
16036
|
+
const reason = error && error.code === "ENOENT" ? new ConnectError("runtime_unavailable", "herdr-core (hc) was not found.", "Install herdr-core (https://github.com/herdrdev/herdr-core) or set herdrCore.binary in connector.json.") : new ConnectError("runtime_unavailable", "The herdr-core connection closed.", "Check that herdr-core is running (`hc server status`), then retry.");
|
|
16037
|
+
this.closeReason = reason;
|
|
16038
|
+
for (const [id, request] of this.pending) {
|
|
16039
|
+
clearTimeout(request.timer);
|
|
16040
|
+
this.pending.delete(id);
|
|
16041
|
+
request.reject(request.method === "terminal.send" ? new ConnectError("delivery_unknown", "herdr-core closed before confirming the message.", "Read the agent output before deciding whether to send it again.") : reason);
|
|
16042
|
+
}
|
|
16043
|
+
});
|
|
16044
|
+
}
|
|
16045
|
+
stream;
|
|
16046
|
+
onNotification;
|
|
16047
|
+
pending = /* @__PURE__ */ new Map();
|
|
16048
|
+
nextId = 1;
|
|
16049
|
+
open = true;
|
|
16050
|
+
done;
|
|
16051
|
+
closeReason;
|
|
16052
|
+
get isOpen() {
|
|
16053
|
+
return this.open;
|
|
16054
|
+
}
|
|
16055
|
+
request(method, params, timeoutMs) {
|
|
16056
|
+
if (!this.open) return Promise.reject(this.closeReason ?? new ConnectError("runtime_unavailable", "The herdr-core connection is closed.", "Retry once herdr-core is running."));
|
|
16057
|
+
const id = this.nextId++;
|
|
16058
|
+
return new Promise((resolve6, reject) => {
|
|
16059
|
+
const timer = setTimeout(() => {
|
|
16060
|
+
if (!this.pending.delete(id)) return;
|
|
16061
|
+
reject(method === "terminal.send" ? new ConnectError("delivery_unknown", "herdr-core did not confirm the message in time.", "Read the agent output before deciding whether to send it again.") : new ConnectError("timeout", `herdr-core ${method} timed out.`, "Check that herdr-core is responsive and retry."));
|
|
16062
|
+
}, timeoutMs);
|
|
16063
|
+
timer.unref?.();
|
|
16064
|
+
this.pending.set(id, { resolve: resolve6, reject, timer, method });
|
|
16065
|
+
this.stream.input.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
|
|
16066
|
+
`);
|
|
16067
|
+
});
|
|
16068
|
+
}
|
|
16069
|
+
close() {
|
|
16070
|
+
this.stream.close();
|
|
16071
|
+
}
|
|
16072
|
+
receive(line) {
|
|
16073
|
+
if (!line.trim()) return;
|
|
16074
|
+
if (Buffer.byteLength(line, "utf8") > MAX_LINE_BYTES) {
|
|
16075
|
+
this.close();
|
|
16076
|
+
return;
|
|
16077
|
+
}
|
|
16078
|
+
let message;
|
|
16079
|
+
try {
|
|
16080
|
+
const parsed = JSON.parse(line);
|
|
16081
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
|
|
16082
|
+
message = parsed;
|
|
16083
|
+
} catch {
|
|
16084
|
+
return;
|
|
16085
|
+
}
|
|
16086
|
+
if (typeof message.id === "number") {
|
|
16087
|
+
const request = this.pending.get(message.id);
|
|
16088
|
+
if (!request) return;
|
|
16089
|
+
this.pending.delete(message.id);
|
|
16090
|
+
clearTimeout(request.timer);
|
|
16091
|
+
if (message.error && typeof message.error === "object") {
|
|
16092
|
+
const error = message.error;
|
|
16093
|
+
request.reject(new CoreRpcError(
|
|
16094
|
+
typeof error.data?.kind === "string" ? error.data.kind : "error",
|
|
16095
|
+
typeof error.message === "string" ? error.message : "herdr-core error",
|
|
16096
|
+
typeof error.data?.hint === "string" ? error.data.hint : void 0
|
|
16097
|
+
));
|
|
16098
|
+
} else request.resolve(message.result);
|
|
16099
|
+
return;
|
|
16100
|
+
}
|
|
16101
|
+
if (typeof message.method === "string" && this.onNotification) {
|
|
16102
|
+
const params = message.params && typeof message.params === "object" && !Array.isArray(message.params) ? message.params : {};
|
|
16103
|
+
this.onNotification({ method: message.method, params });
|
|
16104
|
+
}
|
|
16105
|
+
}
|
|
16106
|
+
};
|
|
16107
|
+
var CoreRpcClient = class {
|
|
16108
|
+
constructor(factory, timeoutMs = 1e4) {
|
|
16109
|
+
this.factory = factory;
|
|
16110
|
+
this.timeoutMs = timeoutMs;
|
|
16111
|
+
}
|
|
16112
|
+
factory;
|
|
16113
|
+
timeoutMs;
|
|
16114
|
+
connection;
|
|
16115
|
+
closed = false;
|
|
16116
|
+
async request(method, params = {}, timeoutMs = this.timeoutMs) {
|
|
16117
|
+
if (this.closed) throw new ConnectError("runtime_unavailable", "The herdr-core client is closed.", "Restart the relay.");
|
|
16118
|
+
if (!this.connection?.isOpen) this.connection = new CoreConnection(this.factory());
|
|
16119
|
+
return this.connection.request(method, params, timeoutMs);
|
|
16120
|
+
}
|
|
16121
|
+
async close() {
|
|
16122
|
+
this.closed = true;
|
|
16123
|
+
const connection = this.connection;
|
|
16124
|
+
this.connection = void 0;
|
|
16125
|
+
if (connection?.isOpen) {
|
|
16126
|
+
connection.close();
|
|
16127
|
+
await connection.done;
|
|
16128
|
+
}
|
|
16129
|
+
}
|
|
16130
|
+
};
|
|
16131
|
+
|
|
16132
|
+
// src/runtime-herdr-core/adapter.ts
|
|
16133
|
+
var LOCAL_ADDRESS2 = /^t[0-9]{1,12}$/;
|
|
16134
|
+
var PROTOCOL_GENERATION = 1;
|
|
16135
|
+
var REQUIRED_METHODS = ["terminal.list", "terminal.get", "terminal.read", "terminal.send", "events.subscribe", "doc.get"];
|
|
16136
|
+
var LIST_EVENTS = /* @__PURE__ */ new Set(["created", "lost", "restarted", "finished", "removed"]);
|
|
16137
|
+
var SEND_TIMEOUT_MS = 9e4;
|
|
16138
|
+
var APP_KINDS = { "claude-code": "claude", "cursor-agent": "cursor", "github-copilot": "copilot", "grok-build": "grok" };
|
|
16139
|
+
var HerdrCoreAdapter = class {
|
|
16140
|
+
constructor(options = {}) {
|
|
16141
|
+
this.options = options;
|
|
16142
|
+
this.factory = options.streamFactory ?? spawnCoreStream(resolveCoreBinary(options.binary));
|
|
16143
|
+
this.timeoutMs = options.timeoutMs ?? 1e4;
|
|
16144
|
+
this.client = new CoreRpcClient(this.factory, this.timeoutMs);
|
|
16145
|
+
this.machineId = options.machineId ?? createHash5("sha256").update(`${process.platform}:${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "local"}`).digest("hex").slice(0, 24);
|
|
16146
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve6) => {
|
|
16147
|
+
const timer = setTimeout(resolve6, ms);
|
|
16148
|
+
timer.unref?.();
|
|
16149
|
+
this.wake = () => {
|
|
16150
|
+
clearTimeout(timer);
|
|
16151
|
+
resolve6();
|
|
16152
|
+
};
|
|
16153
|
+
}));
|
|
16154
|
+
this.settleMs = options.settleMs ?? 150;
|
|
16155
|
+
this.nudgeMs = options.nudgeMs ?? 400;
|
|
16156
|
+
}
|
|
16157
|
+
options;
|
|
16158
|
+
client;
|
|
16159
|
+
factory;
|
|
16160
|
+
machineId;
|
|
16161
|
+
timeoutMs;
|
|
16162
|
+
ready;
|
|
16163
|
+
coreId;
|
|
16164
|
+
current = /* @__PURE__ */ new Map();
|
|
16165
|
+
records = /* @__PURE__ */ new Map();
|
|
16166
|
+
retired = /* @__PURE__ */ new Set();
|
|
16167
|
+
layout = emptyLayout();
|
|
16168
|
+
terminals = [];
|
|
16169
|
+
refreshing;
|
|
16170
|
+
listed = false;
|
|
16171
|
+
listeners = /* @__PURE__ */ new Set();
|
|
16172
|
+
watching;
|
|
16173
|
+
stopped = false;
|
|
16174
|
+
stream;
|
|
16175
|
+
refreshTimer;
|
|
16176
|
+
wake;
|
|
16177
|
+
sleep;
|
|
16178
|
+
settleMs;
|
|
16179
|
+
nudgeMs;
|
|
16180
|
+
methods = /* @__PURE__ */ new Set();
|
|
16181
|
+
getCapabilities() {
|
|
16182
|
+
return { readOutput: true, sendMessage: true, reason: "Messages go to the agent's terminal address, which herdr-core never reuses. PeerBand checks that the same program still runs there right before sending." };
|
|
16183
|
+
}
|
|
16184
|
+
async listAgents() {
|
|
16185
|
+
if (!this.refreshing) this.refreshing = this.refreshAgents().finally(() => {
|
|
16186
|
+
this.refreshing = void 0;
|
|
16187
|
+
});
|
|
16188
|
+
return this.refreshing;
|
|
16189
|
+
}
|
|
16190
|
+
async refreshAgents() {
|
|
16191
|
+
const coreId = await this.initialize();
|
|
16192
|
+
const [listed, layout] = await Promise.all([
|
|
16193
|
+
this.call("terminal.list", {}),
|
|
16194
|
+
this.call("doc.get", { name: LAYOUT_DOC }).then((result) => parseLayout(result?.value), () => emptyLayout())
|
|
16195
|
+
]);
|
|
16196
|
+
const terminals = listed?.terminals;
|
|
16197
|
+
if (!Array.isArray(terminals)) throw schemaMismatch2("terminal.list returned no terminal list");
|
|
16198
|
+
const reconnected = this.coreId !== void 0 && this.coreId !== coreId;
|
|
16199
|
+
this.coreId = coreId;
|
|
16200
|
+
const previous = new Map([...this.current.values()].map((live) => [live.fingerprint, live]));
|
|
16201
|
+
const previousRecords = this.records;
|
|
16202
|
+
const next = /* @__PURE__ */ new Map();
|
|
16203
|
+
const records = [];
|
|
16204
|
+
this.terminals = terminals.filter(isTerminal).filter((terminal) => LOCAL_ADDRESS2.test(terminal.address) && terminal.state === "live");
|
|
16205
|
+
for (const terminal of this.terminals) {
|
|
16206
|
+
if (!isAgent2(terminal)) continue;
|
|
16207
|
+
const fingerprint = identityFingerprint2(coreId, terminal);
|
|
16208
|
+
const id = (!reconnected ? previous.get(fingerprint)?.id : void 0) ?? `hc_${randomUUID9()}`;
|
|
16209
|
+
const live = { id, fingerprint, terminal };
|
|
16210
|
+
next.set(terminal.address, live);
|
|
16211
|
+
records.push(toRecord2(live, this.machineId, layout));
|
|
16212
|
+
}
|
|
16213
|
+
const ids = new Set(records.map((record) => record.id));
|
|
16214
|
+
for (const live of this.current.values()) if (!ids.has(live.id)) this.retired.add(live.id);
|
|
16215
|
+
const idsChanged = this.listed && (ids.size !== previousRecords.size || [...previousRecords.keys()].some((id) => !ids.has(id)));
|
|
16216
|
+
const layoutChanged = this.listed && records.some((record) => {
|
|
16217
|
+
const before = previousRecords.get(record.id);
|
|
16218
|
+
return before !== void 0 && (JSON.stringify(before.location) !== JSON.stringify(record.location) || before.label !== record.label);
|
|
16219
|
+
});
|
|
16220
|
+
this.current = next;
|
|
16221
|
+
this.layout = layout;
|
|
16222
|
+
this.records = new Map(records.map((record) => [record.id, record]));
|
|
16223
|
+
const firstList = !this.listed;
|
|
16224
|
+
this.listed = true;
|
|
16225
|
+
if (!firstList) {
|
|
16226
|
+
for (const record of records) {
|
|
16227
|
+
const before = previousRecords.get(record.id);
|
|
16228
|
+
if (before && before.status !== record.status) this.emit({ kind: "status", agentId: record.id, status: record.status, previousStatus: before.status, label: record.label, workspace: record.workspace, revision: null });
|
|
16229
|
+
}
|
|
16230
|
+
if (idsChanged || layoutChanged) this.emit({ kind: "agents_changed" });
|
|
16231
|
+
}
|
|
16232
|
+
return records;
|
|
16233
|
+
}
|
|
16234
|
+
async getAgent(id) {
|
|
16235
|
+
const agents = await this.listAgents();
|
|
16236
|
+
const record = agents.find((agent) => agent.id === id);
|
|
16237
|
+
if (record) return record;
|
|
16238
|
+
if (this.retired.has(id)) throw new ConnectError("stale_target", "This agent handle refers to a program that has exited or changed.", "Refresh the agent list and select its current occupant.");
|
|
16239
|
+
throw new ConnectError("agent_not_found", "No herdr-core agent has that identifier.", "List agents and use a current agent identifier.");
|
|
16240
|
+
}
|
|
16241
|
+
/** The agent id for a core terminal address such as $HC_TERMINAL_ID, after a fresh list. */
|
|
16242
|
+
async agentIdForPane(paneId) {
|
|
16243
|
+
await this.listAgents();
|
|
16244
|
+
return this.current.get(paneId)?.id;
|
|
16245
|
+
}
|
|
16246
|
+
async readOutput(id, options = {}) {
|
|
16247
|
+
if (options.cursor !== void 0) throw new ConnectError("unsupported_capability", "herdr-core output cursors are not supported.", "Request output again with a bounded line or byte limit and no cursor.");
|
|
16248
|
+
await this.getAgent(id);
|
|
16249
|
+
const live = this.liveById(id);
|
|
16250
|
+
const result = await this.read(live.terminal.address, options);
|
|
16251
|
+
await this.getAgent(id);
|
|
16252
|
+
return result;
|
|
16253
|
+
}
|
|
16254
|
+
async readPane(paneId, options = {}) {
|
|
16255
|
+
await this.listAgents();
|
|
16256
|
+
if (!LOCAL_ADDRESS2.test(paneId) || !this.terminals.some((terminal) => terminal.address === paneId)) {
|
|
16257
|
+
throw new ConnectError("agent_not_found", "No live herdr-core terminal has that id.", "Refresh the environment and pick a current pane.");
|
|
16258
|
+
}
|
|
16259
|
+
return this.read(paneId, options);
|
|
16260
|
+
}
|
|
16261
|
+
async read(address, options) {
|
|
16262
|
+
const lines = clampInteger2(options.lines, 80, 1, 500);
|
|
16263
|
+
const result = await this.call("terminal.read", { terminal: address, lines });
|
|
16264
|
+
if (!result || typeof result.text !== "string") throw schemaMismatch2("terminal.read returned no text");
|
|
16265
|
+
const text2 = result.text.replace(/(?:[ \t]*\r?\n)+[ \t]*$/, "");
|
|
16266
|
+
const output = sanitizeOutput(text2, { ...options, lines, bytes: clampInteger2(options.bytes, 16384, 1, 32768) });
|
|
16267
|
+
const visibleOnly = result.how === "screen" && typeof result.why === "string";
|
|
16268
|
+
return { ...output, ...visibleOnly ? { source: "visible" } : {}, truncated: visibleOnly || output.truncated || result.complete === false, observedAt: (/* @__PURE__ */ new Date()).toISOString(), untrusted: true };
|
|
16269
|
+
}
|
|
16270
|
+
async sendMessage(id, message) {
|
|
16271
|
+
if (typeof message !== "string" || message.length === 0 || Buffer.byteLength(message, "utf8") > 16384) {
|
|
16272
|
+
throw new ConnectError("invalid_argument", "Message must contain 1 to 16384 UTF-8 bytes.", "Shorten the message and try again.");
|
|
16273
|
+
}
|
|
16274
|
+
await this.getAgent(id);
|
|
16275
|
+
const live = this.liveById(id);
|
|
16276
|
+
if (live.terminal.status?.state === "blocked" || live.terminal.status?.state === "error") {
|
|
16277
|
+
throw new ConnectError("agent_blocked", "The agent is blocked and cannot accept a message.", "Inspect the agent and resolve what it is waiting for before sending a message.");
|
|
16278
|
+
}
|
|
16279
|
+
const now2 = await this.call("terminal.get", { terminal: live.terminal.address });
|
|
16280
|
+
if (!isTerminal(now2) || now2.state !== "live" || identityFingerprint2(this.coreId, now2) !== live.fingerprint) {
|
|
16281
|
+
this.retired.add(id);
|
|
16282
|
+
throw new ConnectError("stale_target", "The program in this terminal changed before the message was sent.", "Refresh the agent list and select its current occupant.");
|
|
16283
|
+
}
|
|
16284
|
+
const result = await this.call("terminal.send", { terminal: live.terminal.address, text: message }, SEND_TIMEOUT_MS);
|
|
16285
|
+
if (!result || typeof result !== "object" || typeof result.turn !== "number") throw new ConnectError("delivery_unknown", "herdr-core answered the message with an unexpected result.", "Read the agent output before deciding whether to send it again.");
|
|
16286
|
+
await this.nudgeUnsubmitted(live, result);
|
|
16287
|
+
}
|
|
16288
|
+
/**
|
|
16289
|
+
* Codex reads a long paste followed at once by Enter as part of the paste, so the message stays in its input box
|
|
16290
|
+
* (core reports `started: false`). Every relayed message is long because of its sender line. Press Enter once more
|
|
16291
|
+
* when the agent was not busy and still has not started. An extra Enter on an empty prompt does nothing.
|
|
16292
|
+
*/
|
|
16293
|
+
async nudgeUnsubmitted(live, result) {
|
|
16294
|
+
if (result.started !== false || result.status === "working" || !this.methods.has("terminal.keys")) return;
|
|
16295
|
+
await new Promise((resolve6) => setTimeout(resolve6, this.nudgeMs));
|
|
16296
|
+
try {
|
|
16297
|
+
const now2 = await this.call("terminal.get", { terminal: live.terminal.address });
|
|
16298
|
+
if (!isTerminal(now2) || now2.state !== "live" || identityFingerprint2(this.coreId, now2) !== live.fingerprint) return;
|
|
16299
|
+
const state = now2.status?.state;
|
|
16300
|
+
if (state === "working" || state === "blocked" || state === "error") return;
|
|
16301
|
+
await this.call("terminal.keys", { terminal: live.terminal.address, keys: ["enter"] });
|
|
16302
|
+
} catch {
|
|
16303
|
+
}
|
|
16304
|
+
}
|
|
16305
|
+
/** The layout as the dashboard shows it. Read only: herdr-core spaces and tabs belong to the desktop app. */
|
|
16306
|
+
async listEnvironment() {
|
|
16307
|
+
const agents = await this.listAgents();
|
|
16308
|
+
const byAddress = new Map([...this.current.values()].map((live) => [live.terminal.address, this.records.get(live.id)]));
|
|
16309
|
+
const terminals = new Map(this.terminals.map((terminal) => [terminal.address, terminal]));
|
|
16310
|
+
const workspaces = [];
|
|
16311
|
+
const tabs = [];
|
|
16312
|
+
const panes = [];
|
|
16313
|
+
const pane = (address, tabId, workspaceId) => {
|
|
16314
|
+
const terminal = terminals.get(address);
|
|
16315
|
+
if (!terminal) return;
|
|
16316
|
+
const agent = byAddress.get(address);
|
|
16317
|
+
const cwd = cleanText(terminal.foreground?.cwd ?? terminal.cwd, 2048);
|
|
16318
|
+
panes.push({ paneId: address, tabId, workspaceId, ...cwd ? { cwd } : {}, ...agent ? { agent: agent.agentType, agentStatus: agent.rawStatus, name: agent.label } : { label: cleanText(terminal.name ?? terminal.foreground?.name, 256) ?? address } });
|
|
16319
|
+
};
|
|
16320
|
+
for (const space of this.layout.spaces) {
|
|
16321
|
+
workspaces.push({ workspaceId: space.id, ...space.label ? { label: space.label } : {}, number: space.number, tabCount: space.tabs.length });
|
|
16322
|
+
for (const tab of space.tabs) {
|
|
16323
|
+
const shown = tab.terminals.filter((address) => terminals.has(address));
|
|
16324
|
+
tabs.push({ tabId: tab.id, workspaceId: space.id, ...tab.label ? { label: tab.label } : {}, number: tab.number, paneCount: shown.length });
|
|
16325
|
+
for (const address of shown) pane(address, tab.id, space.id);
|
|
16326
|
+
}
|
|
16327
|
+
}
|
|
16328
|
+
const background = agents.filter((agent) => agent.location?.space.id === BACKGROUND_SPACE_ID);
|
|
16329
|
+
if (background.length) {
|
|
16330
|
+
workspaces.push({ workspaceId: BACKGROUND_SPACE_ID, label: BACKGROUND_SPACE_LABEL, number: this.layout.spaces.length + 1, tabCount: 1 });
|
|
16331
|
+
tabs.push({ tabId: BACKGROUND_TAB_ID, workspaceId: BACKGROUND_SPACE_ID, label: BACKGROUND_TAB_LABEL, number: 1, paneCount: background.length });
|
|
16332
|
+
for (const live of this.current.values()) if (this.records.get(live.id)?.location?.space.id === BACKGROUND_SPACE_ID) pane(live.terminal.address, BACKGROUND_TAB_ID, BACKGROUND_SPACE_ID);
|
|
16333
|
+
}
|
|
16334
|
+
const result = { actions: [], runtime: "herdr-core" };
|
|
16335
|
+
for (const [key2, rows] of [["workspaces", workspaces], ["tabs", tabs], ["panes", panes]]) {
|
|
16336
|
+
result[key2] = rows.slice(0, 50);
|
|
16337
|
+
result[`${key2}Truncated`] = rows.length > 50;
|
|
16338
|
+
}
|
|
16339
|
+
if (Buffer.byteLength(JSON.stringify(result), "utf8") > 48 * 1024) throw new ConnectError("response_too_large", "The environment metadata exceeds the frame budget.", "Close some terminals before listing the layout remotely.");
|
|
16340
|
+
return result;
|
|
16341
|
+
}
|
|
16342
|
+
async controlEnvironment() {
|
|
16343
|
+
throw new ConnectError("unsupported_capability", "Changing spaces, tabs and panes is not available for herdr-core yet.", "Arrange them in the Herdr desktop app.");
|
|
16344
|
+
}
|
|
16345
|
+
/** Status and list-change events from core's events.subscribe (metadata only, never terminal text). */
|
|
16346
|
+
onEvent(listener, log) {
|
|
16347
|
+
this.listeners.add(listener);
|
|
16348
|
+
if (!this.watching) {
|
|
16349
|
+
this.stopped = false;
|
|
16350
|
+
this.watching = this.watch(log ?? (() => void 0));
|
|
16351
|
+
}
|
|
16352
|
+
return () => {
|
|
16353
|
+
this.listeners.delete(listener);
|
|
16354
|
+
};
|
|
16355
|
+
}
|
|
16356
|
+
async close() {
|
|
16357
|
+
this.stopped = true;
|
|
16358
|
+
clearTimeout(this.refreshTimer);
|
|
16359
|
+
this.stream?.close();
|
|
16360
|
+
this.wake?.();
|
|
16361
|
+
await this.watching?.catch(() => void 0);
|
|
16362
|
+
await this.client.close();
|
|
16363
|
+
}
|
|
16364
|
+
async watch(log) {
|
|
16365
|
+
let delay = 1e3;
|
|
16366
|
+
let announced = false;
|
|
16367
|
+
while (!this.stopped) {
|
|
16368
|
+
const connection = new CoreConnection(this.factory(), (message) => this.onNotification(message));
|
|
16369
|
+
this.stream = connection;
|
|
16370
|
+
const startedAt = Date.now();
|
|
16371
|
+
try {
|
|
16372
|
+
await connection.request("events.subscribe", {}, this.timeoutMs);
|
|
16373
|
+
if (!announced) {
|
|
16374
|
+
log("Watching herdr-core for agent status changes.");
|
|
16375
|
+
announced = true;
|
|
16376
|
+
}
|
|
16377
|
+
this.scheduleRefresh(0);
|
|
16378
|
+
await connection.done;
|
|
16379
|
+
} catch {
|
|
16380
|
+
connection.close();
|
|
16381
|
+
await connection.done;
|
|
16382
|
+
}
|
|
16383
|
+
if (this.stopped) break;
|
|
16384
|
+
if (Date.now() - startedAt > 6e4) delay = 1e3;
|
|
16385
|
+
log("herdr-core event stream closed; reconnecting.");
|
|
16386
|
+
await this.sleep(delay);
|
|
16387
|
+
delay = Math.min(delay * 2, 3e4);
|
|
16388
|
+
}
|
|
16389
|
+
}
|
|
16390
|
+
onNotification(message) {
|
|
16391
|
+
if (message.method === "missed") {
|
|
16392
|
+
this.scheduleRefresh();
|
|
16393
|
+
return;
|
|
16394
|
+
}
|
|
16395
|
+
if (message.method !== "event") return;
|
|
16396
|
+
const { type, terminal, data, seq } = message.params;
|
|
16397
|
+
if (type === "doc") {
|
|
16398
|
+
const doc = data;
|
|
16399
|
+
if (doc?.name === LAYOUT_DOC && message.params.machine === void 0) this.scheduleRefresh();
|
|
16400
|
+
return;
|
|
16401
|
+
}
|
|
16402
|
+
if (typeof terminal !== "string" || !LOCAL_ADDRESS2.test(terminal)) return;
|
|
16403
|
+
if (typeof type === "string" && LIST_EVENTS.has(type)) {
|
|
16404
|
+
this.scheduleRefresh();
|
|
16405
|
+
return;
|
|
16406
|
+
}
|
|
16407
|
+
if (type !== "status") return;
|
|
16408
|
+
const reported = data?.status ?? null;
|
|
16409
|
+
const live = this.current.get(terminal);
|
|
16410
|
+
if (!live || !reported || typeof reported.state !== "string") {
|
|
16411
|
+
this.scheduleRefresh();
|
|
16412
|
+
return;
|
|
16413
|
+
}
|
|
16414
|
+
const record = this.records.get(live.id);
|
|
16415
|
+
if (!record) return;
|
|
16416
|
+
const status = toStatus(reported.state);
|
|
16417
|
+
live.terminal = { ...live.terminal, status: reported };
|
|
16418
|
+
if (record.status === status && record.rawStatus === reported.state) return;
|
|
16419
|
+
const previousStatus = record.status;
|
|
16420
|
+
this.records.set(record.id, { ...record, status, rawStatus: reported.state, observedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
16421
|
+
if (previousStatus !== status) this.emit({ kind: "status", agentId: record.id, status, previousStatus, label: record.label, workspace: record.workspace, revision: typeof seq === "number" && Number.isSafeInteger(seq) ? seq : null });
|
|
16422
|
+
}
|
|
16423
|
+
scheduleRefresh(delay = this.settleMs) {
|
|
16424
|
+
if (this.stopped || this.refreshTimer) return;
|
|
16425
|
+
this.refreshTimer = setTimeout(() => {
|
|
16426
|
+
this.refreshTimer = void 0;
|
|
16427
|
+
void this.listAgents().catch(() => void 0);
|
|
16428
|
+
}, delay);
|
|
16429
|
+
this.refreshTimer.unref?.();
|
|
16430
|
+
}
|
|
16431
|
+
emit(event) {
|
|
16432
|
+
for (const listener of [...this.listeners]) listener(event);
|
|
16433
|
+
}
|
|
16434
|
+
liveById(id) {
|
|
16435
|
+
const live = [...this.current.values()].find((item) => item.id === id);
|
|
16436
|
+
if (!live) throw new ConnectError("stale_target", "This agent handle is no longer current.", "Refresh the agent list and select its current occupant.");
|
|
16437
|
+
return live;
|
|
16438
|
+
}
|
|
16439
|
+
initialize() {
|
|
16440
|
+
if (!this.ready) {
|
|
16441
|
+
const pending = (async () => {
|
|
16442
|
+
const hello = await this.call("hello", {});
|
|
16443
|
+
if (!hello || hello.generation !== PROTOCOL_GENERATION) throw new ConnectError("schema_mismatch", "This herdr-core speaks a protocol generation PeerBand does not support.", "Update PeerBand (`peerband update`) and herdr-core (`hc update`).");
|
|
16444
|
+
const methods = Array.isArray(hello.methods) ? hello.methods : [];
|
|
16445
|
+
const missing = REQUIRED_METHODS.filter((method) => !methods.includes(method));
|
|
16446
|
+
this.methods = new Set(methods.filter((method) => typeof method === "string"));
|
|
16447
|
+
if (missing.length) throw new ConnectError("schema_mismatch", `This herdr-core lacks ${missing.join(", ")}.`, "Update herdr-core with `hc update`.");
|
|
16448
|
+
return typeof hello.core?.id === "string" ? hello.core.id : "core";
|
|
16449
|
+
})();
|
|
16450
|
+
this.ready = pending;
|
|
16451
|
+
void pending.catch(() => {
|
|
16452
|
+
if (this.ready === pending) this.ready = void 0;
|
|
16453
|
+
});
|
|
16454
|
+
}
|
|
16455
|
+
return this.ready.then(async (id) => {
|
|
16456
|
+
if (this.coreId === void 0) return id;
|
|
16457
|
+
const status = await this.call("server.status", {}).catch(() => void 0);
|
|
16458
|
+
return typeof status?.core?.id === "string" ? status.core.id : id;
|
|
16459
|
+
});
|
|
16460
|
+
}
|
|
16461
|
+
async call(method, params, timeoutMs) {
|
|
16462
|
+
try {
|
|
16463
|
+
return await this.client.request(method, params, timeoutMs);
|
|
16464
|
+
} catch (error) {
|
|
16465
|
+
throw mapError(error, method);
|
|
16466
|
+
}
|
|
16467
|
+
}
|
|
16468
|
+
};
|
|
16469
|
+
function mapError(error, method) {
|
|
16470
|
+
if (!(error instanceof CoreRpcError)) return error;
|
|
16471
|
+
switch (error.kind) {
|
|
16472
|
+
case "not_found":
|
|
16473
|
+
case "finished":
|
|
16474
|
+
return new ConnectError("stale_target", "That terminal is no longer running in herdr-core.", "Refresh the agent list and select its current occupant.");
|
|
16475
|
+
case "blocked":
|
|
16476
|
+
return new ConnectError("agent_blocked", "The agent is blocked and cannot accept a message.", "Inspect the agent and resolve what it is waiting for before sending a message.");
|
|
16477
|
+
case "invalid_params":
|
|
16478
|
+
return new ConnectError("schema_mismatch", `herdr-core rejected ${method}.`, "Update PeerBand and herdr-core.");
|
|
16479
|
+
case "unavailable":
|
|
16480
|
+
return method === "terminal.send" ? new ConnectError("delivery_unknown", "herdr-core could not confirm the message.", "Read the agent output before deciding whether to send it again.") : new ConnectError("runtime_unavailable", "herdr-core cannot reach that terminal right now.", "Wait for it to restart, then retry.");
|
|
16481
|
+
default:
|
|
16482
|
+
return method === "terminal.send" ? new ConnectError("delivery_unknown", "herdr-core reported an error while sending.", "Read the agent output before deciding whether to send it again.") : new ConnectError("runtime_unavailable", `herdr-core ${method} failed.`, "Check `hc server status`, then retry.");
|
|
16483
|
+
}
|
|
16484
|
+
}
|
|
16485
|
+
function schemaMismatch2(message) {
|
|
16486
|
+
return new ConnectError("schema_mismatch", `herdr-core response did not match the expected API: ${message}`, "Update PeerBand and herdr-core.");
|
|
16487
|
+
}
|
|
16488
|
+
function isTerminal(value) {
|
|
16489
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && typeof value.address === "string";
|
|
16490
|
+
}
|
|
16491
|
+
function isAgent2(terminal) {
|
|
16492
|
+
return typeof terminal.pid === "number" && Boolean(terminal.status) && typeof terminal.status?.state === "string";
|
|
16493
|
+
}
|
|
16494
|
+
function toStatus(word) {
|
|
16495
|
+
if (word === "idle" || word === "working" || word === "blocked" || word === "done") return word;
|
|
16496
|
+
return word === "error" ? "blocked" : "unknown";
|
|
16497
|
+
}
|
|
16498
|
+
function identityFingerprint2(coreId, terminal) {
|
|
16499
|
+
return createHash5("sha256").update([coreId, terminal.address, String(terminal.created_ms ?? ""), String(terminal.pid ?? "")].join("\0")).digest("hex");
|
|
16500
|
+
}
|
|
16501
|
+
function cleanText(value, max) {
|
|
16502
|
+
if (typeof value !== "string") return void 0;
|
|
16503
|
+
return sanitizeOutput(value, { bytes: max, lines: 1 }).text || void 0;
|
|
16504
|
+
}
|
|
16505
|
+
function programName(value) {
|
|
16506
|
+
if (!value) return void 0;
|
|
16507
|
+
const base = value.split(/[\\/]/).pop() ?? value;
|
|
16508
|
+
return base.replace(/\.(exe|cmd|bat)$/i, "") || void 0;
|
|
16509
|
+
}
|
|
16510
|
+
function toRecord2(live, machineId, layout) {
|
|
16511
|
+
const { terminal } = live;
|
|
16512
|
+
const app = cleanLabel(terminal.status?.app) ?? void 0;
|
|
16513
|
+
const agentType = (app ? APP_KINDS[app] ?? app : void 0) ?? programName(terminal.argv?.[0]) ?? "unknown";
|
|
16514
|
+
const label = cleanLabel(terminal.name) ?? app ?? cleanLabel(programName(terminal.foreground?.name)) ?? terminal.address;
|
|
16515
|
+
const rawStatus = terminal.status?.state ?? "unknown";
|
|
16516
|
+
const place = layout.byTerminal.get(terminal.address);
|
|
16517
|
+
return {
|
|
16518
|
+
id: live.id,
|
|
16519
|
+
machineId,
|
|
16520
|
+
runtime: "herdr-core",
|
|
16521
|
+
agentType,
|
|
16522
|
+
label,
|
|
16523
|
+
workspace: cleanText(terminal.foreground?.cwd ?? terminal.cwd, 2048) ?? terminal.address,
|
|
16524
|
+
status: toStatus(rawStatus),
|
|
16525
|
+
rawStatus,
|
|
16526
|
+
observedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
16527
|
+
stale: false,
|
|
16528
|
+
capabilities: { readOutput: true, sendMessage: true },
|
|
16529
|
+
location: place ? { space: { id: place.space.id, label: place.space.label, number: place.space.number }, tab: { id: place.tab.id, label: place.tab.label, number: place.tab.number } } : { space: { id: BACKGROUND_SPACE_ID, label: BACKGROUND_SPACE_LABEL, number: layout.spaces.length + 1 }, tab: { id: BACKGROUND_TAB_ID, label: BACKGROUND_TAB_LABEL, number: 1 } }
|
|
16530
|
+
};
|
|
16531
|
+
}
|
|
16532
|
+
function clampInteger2(value, fallback, min, max) {
|
|
16533
|
+
if (value === void 0) return fallback;
|
|
16534
|
+
if (!Number.isSafeInteger(value) || value < min || value > max) throw new ConnectError("invalid_argument", `Expected an integer from ${min} through ${max}.`, "Choose a value within the documented output limit.");
|
|
16535
|
+
return value;
|
|
16536
|
+
}
|
|
16537
|
+
|
|
15312
16538
|
// src/cli/commands/connect.ts
|
|
15313
16539
|
function clock(date = /* @__PURE__ */ new Date()) {
|
|
15314
16540
|
return date.toTimeString().slice(0, 8);
|
|
@@ -15345,10 +16571,10 @@ function activityLine(s, activity, at = /* @__PURE__ */ new Date()) {
|
|
|
15345
16571
|
var spec2 = {
|
|
15346
16572
|
name: "connect",
|
|
15347
16573
|
summary: "Run the connector in the foreground",
|
|
15348
|
-
usage: "peerband connect [--runtime herdr|mock] [--read-only] [--config PATH] [--server URL]",
|
|
15349
|
-
description: 'Connects this machine to PeerBand and serves agent requests from your MCP clients until you press Ctrl+C. MCP clients may send messages to agents by default, but only after you approve the agents:message consent when you connect them; pass --read-only (or set "enableWrites": false in connector.json) to make this machine read-only. Activity lines show metadata only (tool, target, outcome, latency), never message or output content. Most people use `peerband relay` instead, which runs the connector inside Herdr.',
|
|
16574
|
+
usage: "peerband connect [--runtime herdr|herdr-core|mock] [--read-only] [--config PATH] [--server URL]",
|
|
16575
|
+
description: 'Connects this machine to PeerBand and serves agent requests from your MCP clients until you press Ctrl+C. MCP clients may send messages to agents by default, but only after you approve the agents:message consent when you connect them; pass --read-only (or set "enableWrites": false in connector.json) to make this machine read-only. Activity lines show metadata only (tool, target, outcome, latency), never message or output content. Most people use `peerband relay` instead, which runs the connector inside Herdr, or `peerband relay --core` for herdr-core and the Herdr desktop app.',
|
|
15350
16576
|
options: [
|
|
15351
|
-
{ name: "runtime", type: "string", valueName: "herdr|mock", description: 'Agent runtime
|
|
16577
|
+
{ name: "runtime", type: "string", valueName: "herdr|herdr-core|mock", description: 'Agent runtime: "herdr" (the Herdr terminal app), "herdr-core" (hc, also behind the Herdr desktop app) or "mock" (fake agents for testing). Default: $PEERBAND_RUNTIME, then "runtime" in connector.json, then herdr.' },
|
|
15352
16578
|
{ name: "disable-environment-control", type: "boolean", description: 'Turn off the owner-only Herdr environment tools (open tabs and panes, start agents) on this machine (also: "enableEnvironmentControl": false in connector.json). They are on by default and still need the environment:control consent.' },
|
|
15353
16579
|
{ name: "enable-environment-control", type: "boolean", description: "Redundant: environment controls are on by default. Kept so old scripts keep working." },
|
|
15354
16580
|
{ name: "read-only", type: "boolean", description: 'Do not allow MCP clients to send messages to agents on this machine (also: "enableWrites": false in connector.json).' },
|
|
@@ -15360,6 +16586,7 @@ var spec2 = {
|
|
|
15360
16586
|
examples: [
|
|
15361
16587
|
["peerband connect", "Serve until Ctrl+C; messages to agents are allowed (with OAuth consent)"],
|
|
15362
16588
|
["peerband connect --read-only", "Never let MCP clients send messages to agents from this machine"],
|
|
16589
|
+
["peerband connect --runtime herdr-core", "Serve the agents in herdr-core (hc) and the Herdr desktop app"],
|
|
15363
16590
|
["peerband connect --runtime mock", "Try the connection with fake agents"]
|
|
15364
16591
|
],
|
|
15365
16592
|
async run(parsed, ctx) {
|
|
@@ -15382,7 +16609,7 @@ function notifyRequest(message) {
|
|
|
15382
16609
|
if (!message || typeof message !== "object" || Array.isArray(message)) return void 0;
|
|
15383
16610
|
const value = message;
|
|
15384
16611
|
if (value.type !== "peerband:notify" && value.type !== "peerband:notify-agent" || typeof value.id !== "string" || value.id.length > 128) return void 0;
|
|
15385
|
-
return { id: value.id, text: value.text, paneId: value.paneId, ...value.type === "peerband:notify-agent" ? { agentId: value.agentId ?? null } : {}, channel: value.channel };
|
|
16612
|
+
return { id: value.id, text: value.text, paneId: value.paneId, terminalId: value.terminalId, ...value.type === "peerband:notify-agent" ? { agentId: value.agentId ?? null } : {}, channel: value.channel };
|
|
15386
16613
|
}
|
|
15387
16614
|
function startMockStatusCycle(adapter, env) {
|
|
15388
16615
|
const interval = Number(env.PEERBAND_MOCK_STATUS_INTERVAL_MS);
|
|
@@ -15406,18 +16633,19 @@ function isShutdownMessage(message) {
|
|
|
15406
16633
|
return Boolean(message) && typeof message === "object" && !Array.isArray(message) && Object.keys(message).length === 1 && message.type === "peerband:shutdown";
|
|
15407
16634
|
}
|
|
15408
16635
|
async function connect(options, ctx) {
|
|
15409
|
-
const
|
|
15410
|
-
if (
|
|
16636
|
+
const requested = options.runtime ?? ctx.env.PEERBAND_RUNTIME;
|
|
16637
|
+
if (requested !== void 0 && requested !== "herdr" && requested !== "herdr-core" && requested !== "mock") throw new UsageError(`Unknown runtime "${requested}".`, "Use --runtime herdr, --runtime herdr-core or --runtime mock.");
|
|
15411
16638
|
const credentials = await requireCredentials(ctx);
|
|
15412
16639
|
if (options.server) credentials.serverUrl = validateServerUrl(options.server);
|
|
15413
16640
|
if (options.readOnly && options.enableWrites) throw new UsageError("--read-only and --enable-writes contradict each other.", "Use --read-only to turn messaging off; messaging is on by default.");
|
|
15414
16641
|
if (options.disableEnvironmentControl && options.enableEnvironmentControl) throw new UsageError("--disable-environment-control and --enable-environment-control contradict each other.", "Use --disable-environment-control to turn environment controls off; they are on by default.");
|
|
15415
16642
|
const config = await loadMachineConnectorConfig(ctx, options.config);
|
|
16643
|
+
const runtime = requested ?? config.runtime ?? "herdr";
|
|
15416
16644
|
const enableWrites = writesEnabled(config, { readOnly: options.readOnly, enableWrites: options.enableWrites });
|
|
15417
16645
|
const managed = Boolean(options.managed);
|
|
15418
16646
|
const s = ctx.out.stderr;
|
|
15419
16647
|
const machine = describeMachine(credentials);
|
|
15420
|
-
const adapter = runtime === "mock" ? new MockRuntime() : new HerdrAdapter(config.herdr ?? {});
|
|
16648
|
+
const adapter = runtime === "mock" ? new MockRuntime() : runtime === "herdr-core" ? new HerdrCoreAdapter(config.herdrCore ?? {}) : new HerdrAdapter(config.herdr ?? {});
|
|
15421
16649
|
const core = new ConnectorCore(adapter, {
|
|
15422
16650
|
writesEnabled: enableWrites,
|
|
15423
16651
|
environmentControlEnabled: environmentControlEnabled(config, { disable: options.disableEnvironmentControl, enable: options.enableEnvironmentControl }),
|
|
@@ -15534,11 +16762,11 @@ async function connect(options, ctx) {
|
|
|
15534
16762
|
// src/cli/commands/herdr.ts
|
|
15535
16763
|
import { mkdir as mkdir5, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
|
|
15536
16764
|
import { statSync } from "node:fs";
|
|
15537
|
-
import { join as
|
|
16765
|
+
import { join as join10, resolve as resolve4 } from "node:path";
|
|
15538
16766
|
|
|
15539
16767
|
// src/cli/commands/herdr-check.ts
|
|
15540
16768
|
import { readFile as readFile8, stat as stat4 } from "node:fs/promises";
|
|
15541
|
-
import { join as
|
|
16769
|
+
import { join as join8 } from "node:path";
|
|
15542
16770
|
var PLUGIN_ID = "peerband";
|
|
15543
16771
|
var REPAIR_COMMAND = "peerband herdr install";
|
|
15544
16772
|
var UPDATE_COMMAND = "peerband update";
|
|
@@ -15560,7 +16788,7 @@ async function readSettings(ctx) {
|
|
|
15560
16788
|
const configDir = dir.code === 0 ? dir.stdout.trim() : "";
|
|
15561
16789
|
if (!configDir) return null;
|
|
15562
16790
|
try {
|
|
15563
|
-
const value = JSON.parse(await readFile8(
|
|
16791
|
+
const value = JSON.parse(await readFile8(join8(configDir, "settings.json"), "utf8"));
|
|
15564
16792
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
15565
16793
|
} catch {
|
|
15566
16794
|
return null;
|
|
@@ -15636,7 +16864,7 @@ function installCommand(target) {
|
|
|
15636
16864
|
return target.kind === "local" ? `herdr plugin link ${target.dir}` : `herdr plugin install ${target.source} --ref ${target.ref} --yes`;
|
|
15637
16865
|
}
|
|
15638
16866
|
async function herdrRetrying(ctx, args, timeoutMs) {
|
|
15639
|
-
const sleep = ctx.sleep ?? ((ms) => new Promise((
|
|
16867
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
|
|
15640
16868
|
let result = await ctx.runHerdr(args, { timeoutMs });
|
|
15641
16869
|
for (const delay of RETRY_DELAYS_MS) {
|
|
15642
16870
|
if (result.code === 0 || result.notFound || !RETRYABLE.test(failureDetail(result))) return result;
|
|
@@ -15710,7 +16938,7 @@ async function replacePlugin(ctx, previousSource, installed, target) {
|
|
|
15710
16938
|
|
|
15711
16939
|
// src/cli/relay-maint.ts
|
|
15712
16940
|
import { rm as rm5 } from "node:fs/promises";
|
|
15713
|
-
import { join as
|
|
16941
|
+
import { join as join9 } from "node:path";
|
|
15714
16942
|
|
|
15715
16943
|
// src/cli/control.ts
|
|
15716
16944
|
import { readFile as readFile9 } from "node:fs/promises";
|
|
@@ -15727,7 +16955,7 @@ var ControlUnavailable = class extends Error {
|
|
|
15727
16955
|
reason;
|
|
15728
16956
|
};
|
|
15729
16957
|
async function requestNotify(note, env, timeoutMs = 8e3) {
|
|
15730
|
-
return exchange({ command: note.agentId !== void 0 ? "notify-agent" : "notify", text: note.text, ...note.agentId !== void 0 ? { agentId: note.agentId } : {}, ...note.paneId ? { paneId: note.paneId } : {}, ...note.channel ? { channel: note.channel } : {} }, env, timeoutMs, true);
|
|
16958
|
+
return exchange({ command: note.agentId !== void 0 ? "notify-agent" : "notify", text: note.text, ...note.agentId !== void 0 ? { agentId: note.agentId } : {}, ...note.paneId ? { paneId: note.paneId } : {}, ...note.terminalId ? { terminalId: note.terminalId } : {}, ...note.channel ? { channel: note.channel } : {} }, env, timeoutMs, true);
|
|
15731
16959
|
}
|
|
15732
16960
|
async function exchange(payload, env, timeoutMs, typed = false) {
|
|
15733
16961
|
const config = configHome({ env });
|
|
@@ -15740,20 +16968,20 @@ async function exchange(payload, env, timeoutMs, typed = false) {
|
|
|
15740
16968
|
}
|
|
15741
16969
|
if (typeof record.token !== "string") throw typed ? new ControlUnavailable("not-running", "Invalid helper record") : new Error("Invalid helper record");
|
|
15742
16970
|
const socket = createConnection4(controlChannel2(config));
|
|
15743
|
-
return new Promise((
|
|
16971
|
+
return new Promise((resolve6, reject) => {
|
|
15744
16972
|
let text2 = "";
|
|
15745
16973
|
let settled = false;
|
|
15746
|
-
const
|
|
16974
|
+
const finish2 = (error, value) => {
|
|
15747
16975
|
if (settled) return;
|
|
15748
16976
|
settled = true;
|
|
15749
16977
|
clearTimeout(timer);
|
|
15750
16978
|
socket.destroy();
|
|
15751
16979
|
if (error) reject(error);
|
|
15752
|
-
else
|
|
16980
|
+
else resolve6(value ?? {});
|
|
15753
16981
|
};
|
|
15754
16982
|
let connected = false;
|
|
15755
|
-
const timer = setTimeout(() =>
|
|
15756
|
-
socket.once("error", (error) =>
|
|
16983
|
+
const timer = setTimeout(() => finish2(typed ? new ControlUnavailable("timeout", "Helper control timeout") : new Error("Helper control timeout")), timeoutMs);
|
|
16984
|
+
socket.once("error", (error) => finish2(typed ? new ControlUnavailable(connected ? "closed" : "not-running", error.message) : error));
|
|
15757
16985
|
socket.once("connect", () => {
|
|
15758
16986
|
connected = true;
|
|
15759
16987
|
socket.write(`${JSON.stringify({ token: record.token, ...payload })}
|
|
@@ -15761,16 +16989,16 @@ async function exchange(payload, env, timeoutMs, typed = false) {
|
|
|
15761
16989
|
});
|
|
15762
16990
|
socket.on("data", (chunk) => {
|
|
15763
16991
|
text2 += chunk.toString();
|
|
15764
|
-
if (text2.length > 65536) return
|
|
16992
|
+
if (text2.length > 65536) return finish2(new Error("Invalid control response"));
|
|
15765
16993
|
const newline = text2.indexOf("\n");
|
|
15766
16994
|
if (newline < 0) return;
|
|
15767
16995
|
try {
|
|
15768
|
-
|
|
16996
|
+
finish2(void 0, JSON.parse(text2.slice(0, newline)));
|
|
15769
16997
|
} catch (error) {
|
|
15770
|
-
|
|
16998
|
+
finish2(error);
|
|
15771
16999
|
}
|
|
15772
17000
|
});
|
|
15773
|
-
socket.once("end", () =>
|
|
17001
|
+
socket.once("end", () => finish2(typed ? new ControlUnavailable("closed", "Helper control closed") : new Error("Helper control closed")));
|
|
15774
17002
|
});
|
|
15775
17003
|
}
|
|
15776
17004
|
async function relaySnapshot(env) {
|
|
@@ -15798,7 +17026,7 @@ async function stopRelay(env) {
|
|
|
15798
17026
|
// src/cli/relay-maint.ts
|
|
15799
17027
|
var RELAY_MARKER = "peerband_relay";
|
|
15800
17028
|
var RELAY_LABEL = /^PeerBand Relay\b/;
|
|
15801
|
-
var defaultSleep2 = (ms) => new Promise((
|
|
17029
|
+
var defaultSleep2 = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
15802
17030
|
var sleeper = (ctx) => ctx.sleep ?? defaultSleep2;
|
|
15803
17031
|
async function relayRunning(ctx) {
|
|
15804
17032
|
const snapshot = await relaySnapshot(ctx.env);
|
|
@@ -15863,7 +17091,7 @@ async function cleanRelayState(ctx, options = {}) {
|
|
|
15863
17091
|
if (helper.reclaimed) report2.reclaimed.push(lockPath({ env: ctx.env }));
|
|
15864
17092
|
else if (helper.verdict.state === "live") report2.held.push({ lock: lockPath({ env: ctx.env }), reason: helper.verdict.reason });
|
|
15865
17093
|
const receiptsLock = `${receiptsPath({ env: ctx.env })}.lock`;
|
|
15866
|
-
const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile:
|
|
17094
|
+
const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile: join9(receiptsLock, "owner"), processPattern: CONNECTOR_PATTERN2 });
|
|
15867
17095
|
if (receipts.reclaimed) report2.reclaimed.push(receiptsLock);
|
|
15868
17096
|
else if (receipts.verdict.state === "live") report2.held.push({ lock: receiptsLock, reason: receipts.verdict.reason });
|
|
15869
17097
|
const helperGone = helper.verdict.state !== "live";
|
|
@@ -15920,7 +17148,7 @@ async function releasePlugin(ctx) {
|
|
|
15920
17148
|
return { wasRunning, hadPanes: panes.length > 0 };
|
|
15921
17149
|
}
|
|
15922
17150
|
async function waitForRelay(ctx, timeoutMs) {
|
|
15923
|
-
const sleep = ctx.sleep ?? ((ms) => new Promise((
|
|
17151
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
|
|
15924
17152
|
for (let waited = 0; waited < timeoutMs; waited += 1e3) {
|
|
15925
17153
|
if (await relayRunning(ctx)) return true;
|
|
15926
17154
|
await sleep(1e3);
|
|
@@ -15981,7 +17209,7 @@ async function installPlugin(ctx, options = {}) {
|
|
|
15981
17209
|
const configDir = dirResult.stdout.trim();
|
|
15982
17210
|
if (!configDir) throw new CliError("Herdr did not report a plugin config directory.", "Run `herdr plugin config-dir peerband` to investigate.");
|
|
15983
17211
|
await mkdir5(configDir, { recursive: true });
|
|
15984
|
-
await writeFile6(
|
|
17212
|
+
await writeFile6(join10(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
|
|
15985
17213
|
`, { mode: 384 });
|
|
15986
17214
|
ctx.out.print(`${s.green(symbols.ok)} Saved plugin settings ${s.dim(`(node ${process.execPath})`)}`);
|
|
15987
17215
|
const after = await pluginInstalled(ctx);
|
|
@@ -16031,7 +17259,7 @@ var uninstallSpec = {
|
|
|
16031
17259
|
const configDir = dirResult.code === 0 ? dirResult.stdout.trim() : "";
|
|
16032
17260
|
const removed = await removePlugin(ctx);
|
|
16033
17261
|
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.");
|
|
16034
|
-
if (configDir) await rm6(
|
|
17262
|
+
if (configDir) await rm6(join10(configDir, "settings.json"), { force: true }).catch(() => void 0);
|
|
16035
17263
|
ctx.out.print(`${s.green(symbols.ok)} Removed the PeerBand plugin from Herdr.`);
|
|
16036
17264
|
} else {
|
|
16037
17265
|
ctx.out.print("The PeerBand plugin is not installed in Herdr; nothing to remove.");
|
|
@@ -16054,7 +17282,7 @@ var groupSpec = {
|
|
|
16054
17282
|
import { hostname as hostname3 } from "node:os";
|
|
16055
17283
|
|
|
16056
17284
|
// src/cli/browser.ts
|
|
16057
|
-
import { spawn as
|
|
17285
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
16058
17286
|
function browserDecision(url, context) {
|
|
16059
17287
|
if (context.noBrowser) return { open: false, reason: "flag" };
|
|
16060
17288
|
if (context.env.SSH_CONNECTION || context.env.SSH_TTY || context.env.SSH_CLIENT) return { open: false, reason: "ssh" };
|
|
@@ -16074,16 +17302,16 @@ function openerCommand(platform, url) {
|
|
|
16074
17302
|
}
|
|
16075
17303
|
function openBrowser(url, platform = process.platform) {
|
|
16076
17304
|
const { command, args } = openerCommand(platform, url);
|
|
16077
|
-
return new Promise((
|
|
17305
|
+
return new Promise((resolve6) => {
|
|
16078
17306
|
try {
|
|
16079
|
-
const child =
|
|
16080
|
-
child.once("error", () =>
|
|
17307
|
+
const child = spawn3(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
|
|
17308
|
+
child.once("error", () => resolve6(false));
|
|
16081
17309
|
child.once("spawn", () => {
|
|
16082
17310
|
child.unref();
|
|
16083
|
-
|
|
17311
|
+
resolve6(true);
|
|
16084
17312
|
});
|
|
16085
17313
|
} catch {
|
|
16086
|
-
|
|
17314
|
+
resolve6(false);
|
|
16087
17315
|
}
|
|
16088
17316
|
});
|
|
16089
17317
|
}
|
|
@@ -16096,7 +17324,7 @@ var PromptAborted = class extends Error {
|
|
|
16096
17324
|
}
|
|
16097
17325
|
};
|
|
16098
17326
|
function askYesNo(stdin, stderr, prompt, defaultYes = true) {
|
|
16099
|
-
return new Promise((
|
|
17327
|
+
return new Promise((resolve6, reject) => {
|
|
16100
17328
|
let value = "";
|
|
16101
17329
|
const cleanup = () => {
|
|
16102
17330
|
stdin.off("data", onData);
|
|
@@ -16113,7 +17341,7 @@ function askYesNo(stdin, stderr, prompt, defaultYes = true) {
|
|
|
16113
17341
|
if (end === -1) return;
|
|
16114
17342
|
cleanup();
|
|
16115
17343
|
const answer = value.trim().toLowerCase();
|
|
16116
|
-
|
|
17344
|
+
resolve6(answer === "" ? defaultYes : answer === "y" || answer === "yes");
|
|
16117
17345
|
};
|
|
16118
17346
|
stderr.write(prompt);
|
|
16119
17347
|
stdin.resume();
|
|
@@ -16406,8 +17634,12 @@ var spec4 = {
|
|
|
16406
17634
|
var PANE_ID2 = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
16407
17635
|
var START_RELAY = "Start the relay with `peerband relay`.";
|
|
16408
17636
|
function callingPane(env) {
|
|
16409
|
-
const pane
|
|
16410
|
-
return
|
|
17637
|
+
for (const pane of [env.HERDR_PANE_ID, env.HC_TERMINAL_ID]) if (typeof pane === "string" && PANE_ID2.test(pane)) return pane;
|
|
17638
|
+
return void 0;
|
|
17639
|
+
}
|
|
17640
|
+
function callingTerminal(env) {
|
|
17641
|
+
const terminal = env.HC_TERMINAL_ID;
|
|
17642
|
+
return typeof terminal === "string" && PANE_ID2.test(terminal) ? terminal : void 0;
|
|
16411
17643
|
}
|
|
16412
17644
|
async function checkChannel(name, ctx) {
|
|
16413
17645
|
const credentials = await requireCredentials(ctx);
|
|
@@ -16440,9 +17672,10 @@ async function notify(text2, json, ctx, channel, agent) {
|
|
|
16440
17672
|
if (agent !== void 0 && (agent.length < 1 || agent.length > 256 || /[\x00-\x1f\x7f]/.test(agent))) throw new UsageError("Invalid agent id.", "Use the exact agent id in the relayed reply instructions.");
|
|
16441
17673
|
if (channel !== void 0) await checkChannel(channel, ctx);
|
|
16442
17674
|
const paneId = callingPane(ctx.env);
|
|
17675
|
+
const terminalId = callingTerminal(ctx.env);
|
|
16443
17676
|
let reply;
|
|
16444
17677
|
try {
|
|
16445
|
-
reply = await requestNotify({ text: text2, ...agent !== void 0 ? { agentId: agent } : {}, ...paneId ? { paneId } : {}, ...channel !== void 0 ? { channel } : {} }, ctx.env);
|
|
17678
|
+
reply = await requestNotify({ text: text2, ...agent !== void 0 ? { agentId: agent } : {}, ...paneId ? { paneId } : {}, ...terminalId && terminalId !== paneId ? { terminalId } : {}, ...channel !== void 0 ? { channel } : {} }, ctx.env);
|
|
16446
17679
|
} catch (error) {
|
|
16447
17680
|
if (error instanceof ControlUnavailable && error.reason === "closed") {
|
|
16448
17681
|
throw new CliError(agent !== void 0 ? "The relay closed before confirming the explicit-agent notification. It may need an update; delivery is unconfirmed." : "The running relay does not support notes yet.", "Run `peerband update` to update the CLI and the Herdr plugin, which restarts the relay.");
|
|
@@ -16465,14 +17698,14 @@ async function notify(text2, json, ctx, channel, agent) {
|
|
|
16465
17698
|
}
|
|
16466
17699
|
if (agent !== void 0 && reply.agentId !== agent) throw new CliError("The relay did not confirm the requested agent identity.", "Run `peerband update`; do not resend without --agent.");
|
|
16467
17700
|
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.");
|
|
16468
|
-
const
|
|
17701
|
+
const agentId2 = typeof reply.agentId === "string" ? reply.agentId : null;
|
|
16469
17702
|
if (json) {
|
|
16470
|
-
ctx.out.print(JSON.stringify({ sent: true, agentId, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
|
|
17703
|
+
ctx.out.print(JSON.stringify({ sent: true, agentId: agentId2, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
|
|
16471
17704
|
return 0;
|
|
16472
17705
|
}
|
|
16473
17706
|
const s = ctx.out.stdout;
|
|
16474
17707
|
const target = channel !== void 0 ? `channel ${s.bold(channel)}` : "the machine owner";
|
|
16475
|
-
ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${
|
|
17708
|
+
ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${agentId2 ? s.dim(` (from agent ${sanitize(agentId2)})`) : ""}.`);
|
|
16476
17709
|
return 0;
|
|
16477
17710
|
}
|
|
16478
17711
|
var spec5 = {
|
|
@@ -16504,19 +17737,85 @@ var spec5 = {
|
|
|
16504
17737
|
}
|
|
16505
17738
|
};
|
|
16506
17739
|
|
|
17740
|
+
// src/cli/background.ts
|
|
17741
|
+
import { readFile as readFile10 } from "node:fs/promises";
|
|
17742
|
+
import { dirname as dirname5, join as join11, resolve as resolve5 } from "node:path";
|
|
17743
|
+
async function recordedRelayRuntime(env) {
|
|
17744
|
+
try {
|
|
17745
|
+
const record = JSON.parse(await readFile10(ownerRecordPath2(configHome({ env })), "utf8"));
|
|
17746
|
+
return typeof record.runtime === "string" ? record.runtime : "herdr";
|
|
17747
|
+
} catch {
|
|
17748
|
+
return "herdr";
|
|
17749
|
+
}
|
|
17750
|
+
}
|
|
17751
|
+
async function runningRelayRuntime(env) {
|
|
17752
|
+
const snapshot = await relaySnapshot(env);
|
|
17753
|
+
if (snapshot?.source !== "control" || snapshot.state !== "running") return void 0;
|
|
17754
|
+
return recordedRelayRuntime(env);
|
|
17755
|
+
}
|
|
17756
|
+
function lifecycleScript(ctx) {
|
|
17757
|
+
const self = ctx.selfPath ?? process.argv[1] ?? "";
|
|
17758
|
+
return join11(resolve5(dirname5(self), ".."), "herdr", "lifecycle.mjs");
|
|
17759
|
+
}
|
|
17760
|
+
async function startBackgroundRelay(ctx, runtime, options = {}) {
|
|
17761
|
+
const current = await runningRelayRuntime(ctx.env);
|
|
17762
|
+
if (current === runtime) return "running";
|
|
17763
|
+
if (current !== void 0) {
|
|
17764
|
+
throw new CliError(
|
|
17765
|
+
`A PeerBand relay for ${current === "herdr" ? "the Herdr terminal app" : current} is already running on this machine. One relay serves one runtime.`,
|
|
17766
|
+
"Stop it with `peerband relay --stop` (or close the Relay tab in Herdr), then run `peerband relay --core` again."
|
|
17767
|
+
);
|
|
17768
|
+
}
|
|
17769
|
+
const exec2 = ctx.exec ?? execProgram;
|
|
17770
|
+
const probe = options.checked ? void 0 : await exec2(resolveCoreBinary(void 0, ctx.env), ["--version"], { env: ctx.env, timeoutMs: 15e3 });
|
|
17771
|
+
if (probe?.notFound) {
|
|
17772
|
+
throw new CliError("herdr-core (hc) was not found on this machine.", "Install it (https://github.com/herdrdev/herdr-core) or the Herdr desktop app, open a new terminal, then run `peerband relay --core` again.");
|
|
17773
|
+
}
|
|
17774
|
+
const result = await exec2(process.execPath, [lifecycleScript(ctx), "start"], { env: { ...ctx.env, PEERBAND_RUNTIME: runtime }, timeoutMs: 6e4 });
|
|
17775
|
+
if (result.code !== 0) {
|
|
17776
|
+
const detail = sanitize(result.stderr.trim().split("\n").pop() ?? "").replace(/^peerband:\s*/, "");
|
|
17777
|
+
throw new CliError(detail || "The PeerBand relay did not start.", "Run `peerband status`, then `peerband login` if you are not logged in.");
|
|
17778
|
+
}
|
|
17779
|
+
return "started";
|
|
17780
|
+
}
|
|
17781
|
+
async function stopBackgroundRelay(ctx) {
|
|
17782
|
+
return stopRelay(ctx.env);
|
|
17783
|
+
}
|
|
17784
|
+
|
|
16507
17785
|
// src/cli/commands/relay.ts
|
|
16508
17786
|
var spec6 = {
|
|
16509
17787
|
name: "relay",
|
|
16510
|
-
summary: "Open
|
|
16511
|
-
usage: "peerband relay",
|
|
16512
|
-
description: "Opens the PeerBand Relay in a persistent Herdr tab, or focuses it if it is already open. The tab shows your account, connection state and metadata-only activity; closing it disconnects. Requires Herdr and the PeerBand plugin (`peerband herdr install`). If the plugin is wrong (another version, a local checkout, or a stale config directory), relay offers to repair it first.",
|
|
16513
|
-
options: [
|
|
16514
|
-
|
|
16515
|
-
|
|
17788
|
+
summary: "Open the PeerBand Relay in Herdr, or run it in the background for herdr-core",
|
|
17789
|
+
usage: "peerband relay [--core] [--stop]",
|
|
17790
|
+
description: "Opens the PeerBand Relay in a persistent Herdr tab, or focuses it if it is already open. The tab shows your account, connection state and metadata-only activity; closing it disconnects. Requires Herdr and the PeerBand plugin (`peerband herdr install`). If the plugin is wrong (another version, a local checkout, or a stale config directory), relay offers to repair it first.\n\nWith --core the relay serves herdr-core (`hc`) instead, the terminal server behind the Herdr desktop app. herdr-core has no plugin tab, so the relay runs in the background: closing the desktop app or a terminal leaves it connected. Check it with `peerband status` and stop it with `peerband relay --stop`. It does not start again by itself after you log out or restart the computer; run `peerband relay --core` again. One relay serves one runtime per machine.",
|
|
17791
|
+
options: [
|
|
17792
|
+
{ name: "core", type: "boolean", description: "Run the relay in the background for herdr-core and the Herdr desktop app." },
|
|
17793
|
+
{ name: "stop", type: "boolean", description: "Stop the relay running on this machine (either kind)." }
|
|
17794
|
+
],
|
|
17795
|
+
examples: [
|
|
17796
|
+
["peerband relay", "Open the relay tab in Herdr"],
|
|
17797
|
+
["peerband relay --core", "Connect herdr-core (and the Herdr desktop app) in the background"],
|
|
17798
|
+
["peerband relay --stop", "Disconnect this machine"]
|
|
17799
|
+
],
|
|
17800
|
+
async run(parsed, ctx) {
|
|
17801
|
+
const s = ctx.out.stdout;
|
|
17802
|
+
if (flag(parsed, "stop")) {
|
|
17803
|
+
if (flag(parsed, "core")) throw new UsageError("--core and --stop cannot be combined.", "`peerband relay --stop` stops whichever relay is running.");
|
|
17804
|
+
if (await stopBackgroundRelay(ctx)) ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay stopped.`);
|
|
17805
|
+
else ctx.out.print(s.dim("No PeerBand relay is running on this machine."));
|
|
17806
|
+
return 0;
|
|
17807
|
+
}
|
|
16516
17808
|
const credentials = await requireCredentials(ctx);
|
|
17809
|
+
if (flag(parsed, "core")) {
|
|
17810
|
+
const state = await startBackgroundRelay(ctx, "herdr-core");
|
|
17811
|
+
ctx.out.print(state === "running" ? `${s.green(symbols.ok)} The PeerBand Relay for herdr-core is already running.` : `${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core.`);
|
|
17812
|
+
ctx.out.print(s.dim("Check it with `peerband status`; stop it with `peerband relay --stop`."));
|
|
17813
|
+
printMcpHint(ctx, credentials.serverUrl);
|
|
17814
|
+
printSkillTip(ctx);
|
|
17815
|
+
return 0;
|
|
17816
|
+
}
|
|
16517
17817
|
await ensureHerdrPlugin(ctx);
|
|
16518
17818
|
await openRelay(ctx);
|
|
16519
|
-
const s = ctx.out.stdout;
|
|
16520
17819
|
ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is open in Herdr.`);
|
|
16521
17820
|
printMcpHint(ctx, credentials.serverUrl);
|
|
16522
17821
|
printSkillTip(ctx);
|
|
@@ -16540,8 +17839,8 @@ async function openRelay(ctx) {
|
|
|
16540
17839
|
var SKILL_MODES = ["ask", "install", "skip"];
|
|
16541
17840
|
function report(ctx, installed) {
|
|
16542
17841
|
const s = ctx.out.stdout;
|
|
16543
|
-
const
|
|
16544
|
-
ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand skill ${
|
|
17842
|
+
const where2 = 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(", ")}`;
|
|
17843
|
+
ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand skill ${where2}.`);
|
|
16545
17844
|
ctx.out.print(s.dim(` ${installed.path}`));
|
|
16546
17845
|
}
|
|
16547
17846
|
function keptEdits(ctx, file) {
|
|
@@ -16636,6 +17935,10 @@ async function existingLogin(parsed, ctx) {
|
|
|
16636
17935
|
return void 0;
|
|
16637
17936
|
}
|
|
16638
17937
|
}
|
|
17938
|
+
async function coreInstalled(ctx) {
|
|
17939
|
+
const result = await (ctx.exec ?? execProgram)(resolveCoreBinary(void 0, ctx.env), ["--version"], { env: ctx.env, timeoutMs: 15e3 });
|
|
17940
|
+
return result.code === 0 && /^hc\s/.test(result.stdout.trim());
|
|
17941
|
+
}
|
|
16639
17942
|
var loginOptions = spec3.options.filter((option) => option.name !== "herdr-plugin");
|
|
16640
17943
|
var spec8 = {
|
|
16641
17944
|
name: "setup",
|
|
@@ -16677,6 +17980,15 @@ var spec8 = {
|
|
|
16677
17980
|
let relayOpen = false;
|
|
16678
17981
|
if (flag(parsed, "no-relay")) {
|
|
16679
17982
|
ctx.out.print(s.dim("Skipped. Open it later with `peerband relay`."));
|
|
17983
|
+
} else if (herdr2 === "no-herdr" && await coreInstalled(ctx)) {
|
|
17984
|
+
try {
|
|
17985
|
+
await startBackgroundRelay(ctx, "herdr-core", { checked: true });
|
|
17986
|
+
relayOpen = true;
|
|
17987
|
+
ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core ${s.dim("(stop it with `peerband relay --stop`)")}.`);
|
|
17988
|
+
} catch (error) {
|
|
17989
|
+
ctx.out.warn(`${s.yellow(symbols.warn)} Could not start the PeerBand Relay for herdr-core: ${error.message}`);
|
|
17990
|
+
if (error instanceof CliError && error.hint) ctx.out.print(s.dim(` ${error.hint}`));
|
|
17991
|
+
}
|
|
16680
17992
|
} else if (herdr2 !== "ready") {
|
|
16681
17993
|
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\`.`));
|
|
16682
17994
|
} else {
|
|
@@ -16800,6 +18112,7 @@ async function buildStatus(ctx) {
|
|
|
16800
18112
|
credentials = void 0;
|
|
16801
18113
|
}
|
|
16802
18114
|
const snapshot = await relaySnapshot(ctx.env);
|
|
18115
|
+
const running = snapshot?.source === "control" && snapshot.state === "running";
|
|
16803
18116
|
const plugin = await checkHerdrPlugin(ctx);
|
|
16804
18117
|
const messages = await loadMachineConnectorConfig(ctx).then(
|
|
16805
18118
|
(config) => writesEnabled(config) ? "allowed" : "read-only",
|
|
@@ -16817,9 +18130,10 @@ async function buildStatus(ctx) {
|
|
|
16817
18130
|
installationId: credentials?.installationId ?? null,
|
|
16818
18131
|
enrolledAt: credentials?.enrolledAt ?? null,
|
|
16819
18132
|
relay: {
|
|
16820
|
-
running
|
|
18133
|
+
running,
|
|
16821
18134
|
connection: snapshot?.connectionState ?? null,
|
|
16822
|
-
source: snapshot?.source ?? "none"
|
|
18135
|
+
source: snapshot?.source ?? "none",
|
|
18136
|
+
runtime: running ? await recordedRelayRuntime(ctx.env) : null
|
|
16823
18137
|
},
|
|
16824
18138
|
messages,
|
|
16825
18139
|
herdr: {
|
|
@@ -16853,7 +18167,7 @@ function renderHuman(report2, ctx) {
|
|
|
16853
18167
|
rows.push(["Installation", report2.installationId ?? ""]);
|
|
16854
18168
|
if (report2.enrolledAt) rows.push(["Enrolled", report2.enrolledAt]);
|
|
16855
18169
|
}
|
|
16856
|
-
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`)")}`);
|
|
18170
|
+
const relayLine = report2.relay.running ? `${colorConnection(s, report2.relay.connection)}${report2.relay.runtime === "herdr-core" ? s.dim(" (herdr-core, in the background; stop with `peerband relay --stop`)") : ""}` : report2.relay.source === "file" && report2.relay.connection && report2.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report2.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`, or `peerband relay --core` for herdr-core)")}`);
|
|
16857
18171
|
rows.push(["Relay", relayLine]);
|
|
16858
18172
|
if (report2.messages) {
|
|
16859
18173
|
rows.push([
|
|
@@ -16874,8 +18188,8 @@ function renderHuman(report2, ctx) {
|
|
|
16874
18188
|
}
|
|
16875
18189
|
rows.push(["peerband", `${report2.version} ${s.dim(`(node ${report2.node})`)}`]);
|
|
16876
18190
|
rows.push(["Config", s.dim(report2.configHome)]);
|
|
16877
|
-
const width = Math.max(...rows.map(([
|
|
16878
|
-
for (const [
|
|
18191
|
+
const width = Math.max(...rows.map(([key2]) => key2.length));
|
|
18192
|
+
for (const [key2, value] of rows) ctx.out.print(`${s.bold(key2.padEnd(width))} ${value}`);
|
|
16879
18193
|
}
|
|
16880
18194
|
var spec10 = {
|
|
16881
18195
|
name: "status",
|
|
@@ -16970,8 +18284,8 @@ var spec11 = {
|
|
|
16970
18284
|
};
|
|
16971
18285
|
|
|
16972
18286
|
// src/cli/commands/update.ts
|
|
16973
|
-
import { existsSync as
|
|
16974
|
-
import { dirname as
|
|
18287
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
18288
|
+
import { dirname as dirname6, isAbsolute, join as join12, relative as relative2 } from "node:path";
|
|
16975
18289
|
var DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
16976
18290
|
var PACKAGE = "peerband";
|
|
16977
18291
|
var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
@@ -17024,14 +18338,14 @@ function isInside(child, parent) {
|
|
|
17024
18338
|
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
17025
18339
|
}
|
|
17026
18340
|
function checkoutRoot(self) {
|
|
17027
|
-
let dir =
|
|
18341
|
+
let dir = dirname6(self);
|
|
17028
18342
|
for (let i = 0; i < 4; i++) {
|
|
17029
18343
|
try {
|
|
17030
|
-
const pkg = JSON.parse(readFileSync2(
|
|
17031
|
-
if (pkg.name === PACKAGE &&
|
|
18344
|
+
const pkg = JSON.parse(readFileSync2(join12(dir, "package.json"), "utf8"));
|
|
18345
|
+
if (pkg.name === PACKAGE && existsSync3(join12(dir, ".git"))) return dir;
|
|
17032
18346
|
} catch {
|
|
17033
18347
|
}
|
|
17034
|
-
const parent =
|
|
18348
|
+
const parent = dirname6(dir);
|
|
17035
18349
|
if (parent === dir) break;
|
|
17036
18350
|
dir = parent;
|
|
17037
18351
|
}
|
|
@@ -17042,7 +18356,7 @@ async function detectInstall(ctx) {
|
|
|
17042
18356
|
if (/[\\/]_npx[\\/]/.test(self)) return { kind: "npx", self };
|
|
17043
18357
|
const npm = await (ctx.exec ?? execProgram)("npm", ["root", "-g"], { timeoutMs: 6e4, env: ctx.env });
|
|
17044
18358
|
const npmRoot = npm.code === 0 ? npm.stdout.trim().split(/\r?\n/).pop()?.trim() : void 0;
|
|
17045
|
-
if (npmRoot && isInside(self, real(
|
|
18359
|
+
if (npmRoot && isInside(self, real(join12(npmRoot, PACKAGE)))) return { kind: "npm-global", self, npmRoot };
|
|
17046
18360
|
const checkout = checkoutRoot(self);
|
|
17047
18361
|
if (checkout) return { kind: "source", self, npmRoot, detail: checkout };
|
|
17048
18362
|
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" };
|
|
@@ -17096,7 +18410,7 @@ var spec12 = {
|
|
|
17096
18410
|
const plugin = await checkHerdrPlugin(ctx);
|
|
17097
18411
|
const report2 = { current: ctx.version, latest, updateAvailable: newer, action: "none", plugin: pluginSummary(plugin) };
|
|
17098
18412
|
const pluginNeedsRepair = plugin.found && plugin.installed && plugin.problems.length > 0;
|
|
17099
|
-
const
|
|
18413
|
+
const finish2 = (code = 0) => {
|
|
17100
18414
|
if (json) ctx.out.print(JSON.stringify(report2, null, 2));
|
|
17101
18415
|
return code;
|
|
17102
18416
|
};
|
|
@@ -17104,7 +18418,7 @@ var spec12 = {
|
|
|
17104
18418
|
if (newer) log(`${s.yellow(symbols.warn)} PeerBand ${latest} is available (you have ${ctx.version}). Run ${s.bold("peerband update")}.`);
|
|
17105
18419
|
else log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
|
|
17106
18420
|
if (pluginNeedsRepair) log(`${s.yellow(symbols.warn)} The Herdr plugin needs repair: ${plugin.problems[0].message} ${s.dim("(run `peerband update`)")}`);
|
|
17107
|
-
return
|
|
18421
|
+
return finish2();
|
|
17108
18422
|
}
|
|
17109
18423
|
if (!newer) {
|
|
17110
18424
|
log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
|
|
@@ -17118,7 +18432,7 @@ var spec12 = {
|
|
|
17118
18432
|
} else if (plugin.installed) {
|
|
17119
18433
|
log(`${s.green(symbols.ok)} The Herdr plugin matches ${s.dim(`(${plugin.source ?? "installed"})`)}.`);
|
|
17120
18434
|
}
|
|
17121
|
-
return
|
|
18435
|
+
return finish2();
|
|
17122
18436
|
}
|
|
17123
18437
|
const install = await detectInstall(ctx);
|
|
17124
18438
|
report2.install = install.kind;
|
|
@@ -17128,7 +18442,7 @@ var spec12 = {
|
|
|
17128
18442
|
report2.manual = manual;
|
|
17129
18443
|
if (json) {
|
|
17130
18444
|
io.out.fail(manual.message, manual.hint);
|
|
17131
|
-
return
|
|
18445
|
+
return finish2(1);
|
|
17132
18446
|
}
|
|
17133
18447
|
throw new CliError(`PeerBand ${latest} is available (you have ${ctx.version}). ${manual.message}`, manual.hint);
|
|
17134
18448
|
}
|
|
@@ -17143,7 +18457,7 @@ var spec12 = {
|
|
|
17143
18457
|
if (!proceed) {
|
|
17144
18458
|
report2.action = "cancelled";
|
|
17145
18459
|
log(s.dim("Not updated."));
|
|
17146
|
-
return
|
|
18460
|
+
return finish2();
|
|
17147
18461
|
}
|
|
17148
18462
|
}
|
|
17149
18463
|
const exec2 = ctx.exec ?? execProgram;
|
|
@@ -17158,8 +18472,8 @@ var spec12 = {
|
|
|
17158
18472
|
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 ${spec13}\` as an administrator, then \`peerband update\`.` : `Check the npm output above, run \`npm install -g ${spec13}\` yourself, then \`peerband update\`.`
|
|
17159
18473
|
);
|
|
17160
18474
|
}
|
|
17161
|
-
const entry =
|
|
17162
|
-
if (!
|
|
18475
|
+
const entry = join12(install.npmRoot, PACKAGE, "dist", "peerband.mjs");
|
|
18476
|
+
if (!existsSync3(entry)) throw new CliError(`npm finished, but the new CLI is not at ${entry}.`, `Run \`npm install -g ${spec13}\` yourself, then \`peerband update\`.`);
|
|
17163
18477
|
log(`${s.green(symbols.ok)} Installed peerband ${latest}.`);
|
|
17164
18478
|
report2.action = "updated";
|
|
17165
18479
|
if (skillInstalled(ctx)) {
|
|
@@ -17173,11 +18487,11 @@ var spec12 = {
|
|
|
17173
18487
|
}
|
|
17174
18488
|
if (!plugin.found) {
|
|
17175
18489
|
log(s.dim("Herdr was not found, so there is no plugin to update."));
|
|
17176
|
-
return
|
|
18490
|
+
return finish2();
|
|
17177
18491
|
}
|
|
17178
18492
|
if (!plugin.installed) {
|
|
17179
18493
|
log(`${s.dim("Next:")} peerband herdr install ${s.dim("(adds the PeerBand plugin to Herdr)")}`);
|
|
17180
|
-
return
|
|
18494
|
+
return finish2();
|
|
17181
18495
|
}
|
|
17182
18496
|
log("Updating the Herdr plugin with the new CLI\u2026");
|
|
17183
18497
|
const env = { ...ctx.env, ...io.out.stdout.enabled && ctx.env.FORCE_COLOR === void 0 ? { FORCE_COLOR: "1" } : {} };
|
|
@@ -17191,12 +18505,12 @@ var spec12 = {
|
|
|
17191
18505
|
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`.");
|
|
17192
18506
|
}
|
|
17193
18507
|
report2.plugin = pluginSummary(await checkHerdrPlugin({ ...ctx, version: latest }));
|
|
17194
|
-
return
|
|
18508
|
+
return finish2();
|
|
17195
18509
|
}
|
|
17196
18510
|
};
|
|
17197
18511
|
|
|
17198
18512
|
// src/cli/registry.ts
|
|
17199
|
-
var commands = [spec8, spec3, spec4, spec10, spec12, spec6, spec7, spec9, spec5, spec, spec11, spec2];
|
|
18513
|
+
var commands = [spec8, spec3, spec4, spec10, spec12, spec6, spec7, spec9, spec5, spec, spec11, spec2, ...toolCommands];
|
|
17200
18514
|
var herdrCommands = [installSpec, uninstallSpec];
|
|
17201
18515
|
function lookup(words) {
|
|
17202
18516
|
const [first, second] = words;
|
|
@@ -17252,7 +18566,10 @@ function rootHelp(s, version) {
|
|
|
17252
18566
|
...section(s, "From an agent", [
|
|
17253
18567
|
'peerband notify "<text>" Send the machine owner a short note (task done, blocked, result)',
|
|
17254
18568
|
" --channel NAME Send it to one of the owner's channels instead (see peerband channels)",
|
|
17255
|
-
" --agent ID Attribute a reply to this exact current agent"
|
|
18569
|
+
" --agent ID Attribute a reply to this exact current agent",
|
|
18570
|
+
"peerband agents List agents on your machines (peerband machines for the machines)",
|
|
18571
|
+
'peerband agent ask ID "\u2026" Hand work to another agent and wait for its answer',
|
|
18572
|
+
"peerband tools Every PeerBand MCP tool, as a command (results are JSON)"
|
|
17256
18573
|
]),
|
|
17257
18574
|
...section(s, "Exit codes", ["0 ok 1 failure 2 usage error 3 not logged in 130 interrupted"]),
|
|
17258
18575
|
"",
|
|
@@ -17292,7 +18609,7 @@ function herdrGroupHelp(s) {
|
|
|
17292
18609
|
}
|
|
17293
18610
|
|
|
17294
18611
|
// src/cli/cli.ts
|
|
17295
|
-
var VERSION = true ? "0.
|
|
18612
|
+
var VERSION = true ? "0.3.1" : "0.0.0-dev";
|
|
17296
18613
|
function createContext(overrides = {}) {
|
|
17297
18614
|
const env = overrides.env ?? process.env;
|
|
17298
18615
|
const stdout = overrides.stdout ?? process.stdout;
|