peerband 0.2.8 → 0.3.0
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 +73 -7
- package/dist/peerband.mjs +1676 -365
- package/herdr/lifecycle.mjs +17 -5
- package/herdr-plugin.toml +1 -1
- package/package.json +1 -1
- package/skills/peerband/SKILL.md +33 -5
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,13 @@ 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) => {
|
|
11942
|
+
const reply = principal.role === "owner" && principal.app === "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.` : "";
|
|
11944
|
+
return `${relayMessageHeader(principal)}${reply}
|
|
11938
11945
|
|
|
11939
11946
|
${message}`;
|
|
11947
|
+
};
|
|
11940
11948
|
function pidAlive(pid) {
|
|
11941
11949
|
try {
|
|
11942
11950
|
process.kill(pid, 0);
|
|
@@ -11974,7 +11982,7 @@ var RECEIPT_STATES = ["queued", "dispatching", "delivered", "failed", "delivery_
|
|
|
11974
11982
|
var HASH_PATTERN = /^[a-f0-9]{64}$/;
|
|
11975
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"]);
|
|
11976
11984
|
var assertKeys = (args, allowed) => {
|
|
11977
|
-
const unexpected = Object.keys(args).find((
|
|
11985
|
+
const unexpected = Object.keys(args).find((key2) => !allowed.includes(key2));
|
|
11978
11986
|
if (unexpected) throw new ConnectError("invalid_argument", `Unexpected argument: ${unexpected}.`, "Remove unsupported fields and retry.");
|
|
11979
11987
|
};
|
|
11980
11988
|
var ConnectorCore = class {
|
|
@@ -12021,8 +12029,8 @@ var ConnectorCore = class {
|
|
|
12021
12029
|
async execute(tool, args, principal = DEFAULT_PRINCIPAL) {
|
|
12022
12030
|
if (this.closed) throw new ConnectError("connector_closed", "The connector is shutting down.", "Restart the connector to make further requests.");
|
|
12023
12031
|
let finishOperation;
|
|
12024
|
-
const operation = new Promise((
|
|
12025
|
-
finishOperation =
|
|
12032
|
+
const operation = new Promise((resolve6) => {
|
|
12033
|
+
finishOperation = resolve6;
|
|
12026
12034
|
});
|
|
12027
12035
|
this.activeOperations.add(operation);
|
|
12028
12036
|
try {
|
|
@@ -12098,9 +12106,9 @@ var ConnectorCore = class {
|
|
|
12098
12106
|
this.requireScope(principal, "agents:read");
|
|
12099
12107
|
assertKeys(args, ["machine", "workspace", "status", "cursor", "limit"]);
|
|
12100
12108
|
const limit = safeInteger(args.limit, 50, 1, 200, "limit");
|
|
12101
|
-
for (const
|
|
12102
|
-
if (args[
|
|
12103
|
-
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.");
|
|
12104
12112
|
}
|
|
12105
12113
|
}
|
|
12106
12114
|
if (args.status !== void 0 && !["idle", "working", "blocked", "done", "unknown"].includes(args.status)) {
|
|
@@ -12153,14 +12161,14 @@ var ConnectorCore = class {
|
|
|
12153
12161
|
assertKeys(args, ["agentId", "message", "idempotencyKey"]);
|
|
12154
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.');
|
|
12155
12163
|
this.requireScope(principal, "agents:message");
|
|
12156
|
-
const
|
|
12164
|
+
const key2 = args.idempotencyKey;
|
|
12157
12165
|
const message = args.message;
|
|
12158
|
-
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.");
|
|
12159
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.");
|
|
12160
12168
|
const principalHash = hash(principal.id);
|
|
12161
12169
|
const payloadHash = hash(message);
|
|
12162
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.");
|
|
12163
|
-
const requestKeyHash = hash(canonical([principalHash, args.agentId, "send_agent_message",
|
|
12171
|
+
const requestKeyHash = hash(canonical([principalHash, args.agentId, "send_agent_message", key2]));
|
|
12164
12172
|
return this.withSubmissionLock(requestKeyHash, async () => {
|
|
12165
12173
|
const prior = this.idempotency.get(requestKeyHash);
|
|
12166
12174
|
if (prior) {
|
|
@@ -12173,10 +12181,10 @@ var ConnectorCore = class {
|
|
|
12173
12181
|
const agent = await this.authorizedAgent(args.agentId, principal, true);
|
|
12174
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.");
|
|
12175
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.");
|
|
12176
|
-
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]));
|
|
12177
12185
|
this.pruneReceipts();
|
|
12178
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.");
|
|
12179
|
-
const
|
|
12187
|
+
const now2 = Date.now();
|
|
12180
12188
|
const receipt = {
|
|
12181
12189
|
requestId: randomUUID(),
|
|
12182
12190
|
principalHash,
|
|
@@ -12188,8 +12196,8 @@ var ConnectorCore = class {
|
|
|
12188
12196
|
requestKeyHash,
|
|
12189
12197
|
payloadHash,
|
|
12190
12198
|
state: "queued",
|
|
12191
|
-
createdAt:
|
|
12192
|
-
updatedAt:
|
|
12199
|
+
createdAt: now2,
|
|
12200
|
+
updatedAt: now2
|
|
12193
12201
|
};
|
|
12194
12202
|
this.receipts.set(receipt.requestId, receipt);
|
|
12195
12203
|
this.idempotency.set(requestKeyHash, receipt);
|
|
@@ -12200,7 +12208,7 @@ var ConnectorCore = class {
|
|
|
12200
12208
|
this.idempotency.delete(requestKeyHash);
|
|
12201
12209
|
throw new ConnectError("receipt_store_unavailable", "The request receipt could not be saved; nothing was sent.", "Check local storage access and retry with the same key.");
|
|
12202
12210
|
}
|
|
12203
|
-
const job = this.dispatch(receipt, this.labelMessages ? labelRelayedMessage(message, principal) : message).catch(() => void 0);
|
|
12211
|
+
const job = this.dispatch(receipt, this.labelMessages ? labelRelayedMessage(message, principal, agent.id) : message).catch(() => void 0);
|
|
12204
12212
|
this.inFlight.add(job);
|
|
12205
12213
|
void job.finally(() => this.inFlight.delete(job));
|
|
12206
12214
|
return this.publicReceipt(receipt);
|
|
@@ -12215,12 +12223,12 @@ var ConnectorCore = class {
|
|
|
12215
12223
|
}
|
|
12216
12224
|
async controlEnvironment(args, principal) {
|
|
12217
12225
|
this.authorizeEnvironment(principal);
|
|
12218
|
-
const { idempotencyKey:
|
|
12226
|
+
const { idempotencyKey: key2, ...input } = args;
|
|
12219
12227
|
const command = environmentCommand(input);
|
|
12220
|
-
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.");
|
|
12221
12229
|
const principalHash = hash(principal.id);
|
|
12222
12230
|
const payloadHash = hash(canonical(command));
|
|
12223
|
-
const requestKeyHash = hash(canonical([principalHash, "control_environment",
|
|
12231
|
+
const requestKeyHash = hash(canonical([principalHash, "control_environment", key2]));
|
|
12224
12232
|
return this.withSubmissionLock(requestKeyHash, async () => {
|
|
12225
12233
|
const prior = this.idempotency.get(requestKeyHash);
|
|
12226
12234
|
if (prior) {
|
|
@@ -12229,7 +12237,7 @@ var ConnectorCore = class {
|
|
|
12229
12237
|
}
|
|
12230
12238
|
this.pruneReceipts();
|
|
12231
12239
|
if (this.receipts.size >= MAX_RECEIPTS) throw new ConnectError("receipt_limit", "The receipt store is full.", "Wait for old receipts to expire.");
|
|
12232
|
-
const
|
|
12240
|
+
const now2 = Date.now();
|
|
12233
12241
|
const receipt = {
|
|
12234
12242
|
requestId: randomUUID(),
|
|
12235
12243
|
principalHash,
|
|
@@ -12241,8 +12249,8 @@ var ConnectorCore = class {
|
|
|
12241
12249
|
requestKeyHash,
|
|
12242
12250
|
payloadHash,
|
|
12243
12251
|
state: "queued",
|
|
12244
|
-
createdAt:
|
|
12245
|
-
updatedAt:
|
|
12252
|
+
createdAt: now2,
|
|
12253
|
+
updatedAt: now2
|
|
12246
12254
|
};
|
|
12247
12255
|
this.receipts.set(receipt.requestId, receipt);
|
|
12248
12256
|
this.idempotency.set(requestKeyHash, receipt);
|
|
@@ -12271,19 +12279,19 @@ var ConnectorCore = class {
|
|
|
12271
12279
|
return this.publicReceipt(receipt);
|
|
12272
12280
|
});
|
|
12273
12281
|
}
|
|
12274
|
-
async withSubmissionLock(
|
|
12275
|
-
const previous = this.submissionLocks.get(
|
|
12282
|
+
async withSubmissionLock(key2, action) {
|
|
12283
|
+
const previous = this.submissionLocks.get(key2) ?? Promise.resolve();
|
|
12276
12284
|
let release;
|
|
12277
|
-
const current = new Promise((
|
|
12278
|
-
release =
|
|
12285
|
+
const current = new Promise((resolve6) => {
|
|
12286
|
+
release = resolve6;
|
|
12279
12287
|
});
|
|
12280
|
-
this.submissionLocks.set(
|
|
12288
|
+
this.submissionLocks.set(key2, current);
|
|
12281
12289
|
await previous;
|
|
12282
12290
|
try {
|
|
12283
12291
|
return await action();
|
|
12284
12292
|
} finally {
|
|
12285
12293
|
release();
|
|
12286
|
-
if (this.submissionLocks.get(
|
|
12294
|
+
if (this.submissionLocks.get(key2) === current) this.submissionLocks.delete(key2);
|
|
12287
12295
|
}
|
|
12288
12296
|
}
|
|
12289
12297
|
async dispatch(receipt, message) {
|
|
@@ -12439,7 +12447,7 @@ var ConnectorCore = class {
|
|
|
12439
12447
|
isValidReceipt(value) {
|
|
12440
12448
|
if (!isRecord(value)) return false;
|
|
12441
12449
|
const receiptKeys = ["requestId", "principalHash", "machineId", "targetId", "workspace", "tool", "idempotencyHash", "requestKeyHash", "payloadHash", "state", "createdAt", "updatedAt", "errorCode", "result"];
|
|
12442
|
-
if (Object.keys(value).some((
|
|
12450
|
+
if (Object.keys(value).some((key2) => !receiptKeys.includes(key2))) return false;
|
|
12443
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));
|
|
12444
12452
|
}
|
|
12445
12453
|
persist() {
|
|
@@ -12557,7 +12565,7 @@ async function loadCredentials(path = credentialsPath()) {
|
|
|
12557
12565
|
if (typeof record.serverUrl !== "string" || typeof record.installationId !== "string" || typeof record.credential !== "string") {
|
|
12558
12566
|
throw new ConfigError(`Credentials file ${path} is missing required fields.`, LOGIN_HINT);
|
|
12559
12567
|
}
|
|
12560
|
-
const optional = (
|
|
12568
|
+
const optional = (key2) => typeof record[key2] === "string" && record[key2] ? { [key2]: record[key2] } : {};
|
|
12561
12569
|
return {
|
|
12562
12570
|
serverUrl: record.serverUrl,
|
|
12563
12571
|
installationId: record.installationId,
|
|
@@ -12579,29 +12587,34 @@ async function deleteCredentials(path = credentialsPath()) {
|
|
|
12579
12587
|
|
|
12580
12588
|
// src/core/connector-config.ts
|
|
12581
12589
|
import { readFile as readFile3 } from "node:fs/promises";
|
|
12590
|
+
var RUNTIMES = ["herdr", "herdr-core"];
|
|
12582
12591
|
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12583
|
-
function rejectUnknown(record, allowed,
|
|
12584
|
-
const unknown = Object.keys(record).find((
|
|
12585
|
-
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(", ")}.`);
|
|
12586
12595
|
}
|
|
12587
|
-
function stringField(record,
|
|
12588
|
-
const value = record[
|
|
12596
|
+
function stringField(record, key2, where2, max) {
|
|
12597
|
+
const value = record[key2];
|
|
12589
12598
|
if (value === void 0) return void 0;
|
|
12590
|
-
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.`);
|
|
12591
12600
|
return value;
|
|
12592
12601
|
}
|
|
12593
|
-
function stringList(record,
|
|
12594
|
-
const value = record[
|
|
12602
|
+
function stringList(record, key2, where2) {
|
|
12603
|
+
const value = record[key2];
|
|
12595
12604
|
if (value === void 0) return void 0;
|
|
12596
12605
|
if (!Array.isArray(value) || value.length > 1e3 || value.some((item) => typeof item !== "string" || !item)) {
|
|
12597
|
-
throw new ConfigError(`${
|
|
12606
|
+
throw new ConfigError(`${where2}.${key2} must be an array of up to 1000 non-empty strings.`);
|
|
12598
12607
|
}
|
|
12599
12608
|
return value;
|
|
12600
12609
|
}
|
|
12601
12610
|
function parseConnectorConfig(value, source = "connector config") {
|
|
12602
12611
|
if (!isRecord2(value)) throw new ConfigError(`${source}: expected a JSON object.`);
|
|
12603
|
-
rejectUnknown(value, ["allowedAgents", "allowedWorkspaces", "stateDirectory", "herdr", "enableWrites", "enableEnvironmentControl"], source);
|
|
12612
|
+
rejectUnknown(value, ["runtime", "allowedAgents", "allowedWorkspaces", "stateDirectory", "herdr", "herdrCore", "enableWrites", "enableEnvironmentControl"], source);
|
|
12604
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
|
+
}
|
|
12605
12618
|
const agents = stringList(value, "allowedAgents", source);
|
|
12606
12619
|
if (agents) config.allowedAgents = agents;
|
|
12607
12620
|
const workspaces = stringList(value, "allowedWorkspaces", source);
|
|
@@ -12621,9 +12634,9 @@ function parseConnectorConfig(value, source = "connector config") {
|
|
|
12621
12634
|
if (!isRecord2(raw)) throw new ConfigError(`${source}.herdr must be an object.`);
|
|
12622
12635
|
rejectUnknown(raw, ["socketPath", "schemaPath", "binary", "machineId", "timeoutMs"], `${source}.herdr`);
|
|
12623
12636
|
const herdr2 = {};
|
|
12624
|
-
for (const
|
|
12625
|
-
const text2 = stringField(raw,
|
|
12626
|
-
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;
|
|
12627
12640
|
}
|
|
12628
12641
|
if (raw.timeoutMs !== void 0) {
|
|
12629
12642
|
if (typeof raw.timeoutMs !== "number" || !Number.isInteger(raw.timeoutMs) || raw.timeoutMs < 100 || raw.timeoutMs > 12e4) {
|
|
@@ -12633,6 +12646,23 @@ function parseConnectorConfig(value, source = "connector config") {
|
|
|
12633
12646
|
}
|
|
12634
12647
|
config.herdr = herdr2;
|
|
12635
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
|
+
}
|
|
12636
12666
|
return config;
|
|
12637
12667
|
}
|
|
12638
12668
|
async function loadConnectorConfig(path, options = {}) {
|
|
@@ -12741,7 +12771,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12741
12771
|
});
|
|
12742
12772
|
const reportActivity = options.onActivity ?? (() => {
|
|
12743
12773
|
});
|
|
12744
|
-
const sleep = options.sleep ?? ((ms) => new Promise((
|
|
12774
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
|
|
12745
12775
|
const serverUrl = socketUrl(credentials.serverUrl);
|
|
12746
12776
|
const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 75e3;
|
|
12747
12777
|
let stopped = false;
|
|
@@ -12763,7 +12793,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12763
12793
|
try {
|
|
12764
12794
|
limitReached = false;
|
|
12765
12795
|
setConnectionState("connecting");
|
|
12766
|
-
await new Promise((
|
|
12796
|
+
await new Promise((resolve6, reject) => {
|
|
12767
12797
|
const socket = new wrapper_default(serverUrl, {
|
|
12768
12798
|
headers: {
|
|
12769
12799
|
Authorization: `Bearer ${credentials.credential}`,
|
|
@@ -12959,7 +12989,7 @@ async function runRemoteClient(core, credentials, options = {}) {
|
|
|
12959
12989
|
code === 1008 || code === 4001 ? `remote authentication or policy rejected the connection (${code})` : `remote connection closed (${code})${reason.length ? `: ${reason.toString()}` : ""}`
|
|
12960
12990
|
);
|
|
12961
12991
|
if (current === socket) current = void 0;
|
|
12962
|
-
|
|
12992
|
+
resolve6();
|
|
12963
12993
|
});
|
|
12964
12994
|
});
|
|
12965
12995
|
} catch (error) {
|
|
@@ -13010,12 +13040,12 @@ var DeviceLoginError = class extends Error {
|
|
|
13010
13040
|
var REQUEST_TIMEOUT_MS2 = 15e3;
|
|
13011
13041
|
var MAX_BACKOFF_MS = 3e4;
|
|
13012
13042
|
var SLOW_DOWN_STEP_S = 5;
|
|
13013
|
-
var defaultSleep = (ms, signal) => new Promise((
|
|
13014
|
-
if (signal?.aborted) return
|
|
13043
|
+
var defaultSleep = (ms, signal) => new Promise((resolve6) => {
|
|
13044
|
+
if (signal?.aborted) return resolve6();
|
|
13015
13045
|
const done = () => {
|
|
13016
13046
|
clearTimeout(timer);
|
|
13017
13047
|
signal?.removeEventListener("abort", done);
|
|
13018
|
-
|
|
13048
|
+
resolve6();
|
|
13019
13049
|
};
|
|
13020
13050
|
const timer = setTimeout(done, ms);
|
|
13021
13051
|
signal?.addEventListener("abort", done, { once: true });
|
|
@@ -13084,8 +13114,8 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
|
|
|
13084
13114
|
const base = enrollmentBase(serverUrl);
|
|
13085
13115
|
const url = new URL("/api/device/token", base);
|
|
13086
13116
|
const sleep = options.sleep ?? defaultSleep;
|
|
13087
|
-
const
|
|
13088
|
-
const deadline =
|
|
13117
|
+
const now2 = options.now ?? Date.now;
|
|
13118
|
+
const deadline = now2() + code.expiresIn * 1e3;
|
|
13089
13119
|
let interval = code.interval;
|
|
13090
13120
|
let failures = 0;
|
|
13091
13121
|
const expired = () => new DeviceLoginError("expired", "The code expired.");
|
|
@@ -13095,7 +13125,7 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
|
|
|
13095
13125
|
const wait = failures > 0 ? Math.min(MAX_BACKOFF_MS, interval * 1e3 * 2 ** failures) : interval * 1e3;
|
|
13096
13126
|
await sleep(wait, options.signal);
|
|
13097
13127
|
if (options.signal?.aborted) throw aborted();
|
|
13098
|
-
if (
|
|
13128
|
+
if (now2() >= deadline) throw expired();
|
|
13099
13129
|
let result;
|
|
13100
13130
|
try {
|
|
13101
13131
|
result = await postJson(
|
|
@@ -13154,8 +13184,8 @@ var AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
|
|
|
13154
13184
|
var NOTE_MAX_CHARS = 1024;
|
|
13155
13185
|
var CHANNEL_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
13156
13186
|
var PANE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
13157
|
-
function eventFrame(name, data,
|
|
13158
|
-
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 };
|
|
13159
13189
|
}
|
|
13160
13190
|
function codePoints(text2) {
|
|
13161
13191
|
return Array.from(text2).length;
|
|
@@ -13260,15 +13290,25 @@ var ConnectorEvents = class {
|
|
|
13260
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.");
|
|
13261
13291
|
const text2 = cleanNote(input.text);
|
|
13262
13292
|
const channel = noteChannel(input.channel);
|
|
13263
|
-
const
|
|
13293
|
+
const agentId2 = input.agentId !== void 0 ? await this.explicitAgent(input.agentId) : await this.resolveAgent(input.paneId) ?? await this.resolveAgent(input.terminalId);
|
|
13264
13294
|
const echo = channel ? { channel } : {};
|
|
13265
|
-
if (!this.send) return { sent: false, agentId, ...echo };
|
|
13295
|
+
if (!this.send) return { sent: false, agentId: agentId2, ...echo };
|
|
13266
13296
|
this.refillNotes();
|
|
13267
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.");
|
|
13268
13298
|
this.noteTokens -= 1;
|
|
13269
|
-
const frame = eventFrame("agent.notified", { agentId, text: text2, audience: "owner", ...echo });
|
|
13299
|
+
const frame = eventFrame("agent.notified", { agentId: agentId2, text: text2, audience: "owner", ...echo });
|
|
13270
13300
|
const sent = this.send(frame);
|
|
13271
|
-
return { sent, agentId, ...sent ? { eventId: frame.eventId } : {}, ...echo };
|
|
13301
|
+
return { sent, agentId: agentId2, ...sent ? { eventId: frame.eventId } : {}, ...echo };
|
|
13302
|
+
}
|
|
13303
|
+
async explicitAgent(value) {
|
|
13304
|
+
if (typeof value !== "string" || value.length < 1 || value.length > 256 || /[\x00-\x1f\x7f]/.test(value)) {
|
|
13305
|
+
throw new ConnectError("invalid_argument", "Invalid agent id.", "Use the exact agent id in the relayed reply instructions.");
|
|
13306
|
+
}
|
|
13307
|
+
const agent = await this.adapter.getAgent(value);
|
|
13308
|
+
if (agent.id !== value || !this.visible(agent.id, agent.workspace)) {
|
|
13309
|
+
throw new ConnectError("forbidden", "This agent is outside the configured allowlist.", "Choose an allowed agent.");
|
|
13310
|
+
}
|
|
13311
|
+
return agent.id;
|
|
13272
13312
|
}
|
|
13273
13313
|
async resolveAgent(paneId) {
|
|
13274
13314
|
if (typeof paneId !== "string" || !PANE_ID.test(paneId) || !this.adapter.agentIdForPane) return null;
|
|
@@ -13282,50 +13322,50 @@ var ConnectorEvents = class {
|
|
|
13282
13322
|
return null;
|
|
13283
13323
|
}
|
|
13284
13324
|
}
|
|
13285
|
-
visible(
|
|
13286
|
-
if (this.allowedAgents && !this.allowedAgents.has(
|
|
13325
|
+
visible(agentId2, workspace) {
|
|
13326
|
+
if (this.allowedAgents && !this.allowedAgents.has(agentId2)) return false;
|
|
13287
13327
|
if (this.allowedWorkspaces && (workspace === null || !this.allowedWorkspaces.has(workspace))) return false;
|
|
13288
13328
|
return true;
|
|
13289
13329
|
}
|
|
13290
|
-
refill(
|
|
13291
|
-
this.tokens = Math.min(this.burst, this.tokens + (
|
|
13292
|
-
this.refilledAt =
|
|
13330
|
+
refill(now2) {
|
|
13331
|
+
this.tokens = Math.min(this.burst, this.tokens + (now2 - this.refilledAt) / 1e3 * this.ratePerSecond);
|
|
13332
|
+
this.refilledAt = now2;
|
|
13293
13333
|
}
|
|
13294
13334
|
refillNotes() {
|
|
13295
|
-
const
|
|
13296
|
-
this.noteTokens = Math.min(this.notesPerMinute, this.noteTokens + (
|
|
13297
|
-
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;
|
|
13298
13338
|
}
|
|
13299
13339
|
flush() {
|
|
13300
13340
|
const send = this.send;
|
|
13301
13341
|
if (!send) return;
|
|
13302
|
-
const
|
|
13303
|
-
this.refill(
|
|
13342
|
+
const now2 = this.now();
|
|
13343
|
+
this.refill(now2);
|
|
13304
13344
|
let next = Number.POSITIVE_INFINITY;
|
|
13305
13345
|
if (this.listChanged) {
|
|
13306
13346
|
const due = this.lastListSent + this.windowMs;
|
|
13307
|
-
if (due >
|
|
13347
|
+
if (due > now2) next = Math.min(next, due);
|
|
13308
13348
|
else if (this.tokens >= 1) {
|
|
13309
13349
|
this.tokens -= 1;
|
|
13310
13350
|
this.listChanged = false;
|
|
13311
|
-
this.lastListSent =
|
|
13351
|
+
this.lastListSent = now2;
|
|
13312
13352
|
send(eventFrame("agents.changed", {}));
|
|
13313
13353
|
}
|
|
13314
13354
|
}
|
|
13315
|
-
for (const [
|
|
13316
|
-
const due = (this.lastSent.get(
|
|
13317
|
-
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) {
|
|
13318
13358
|
next = Math.min(next, due);
|
|
13319
13359
|
continue;
|
|
13320
13360
|
}
|
|
13321
13361
|
if (this.tokens < 1) break;
|
|
13322
13362
|
this.tokens -= 1;
|
|
13323
|
-
this.pending.delete(
|
|
13324
|
-
this.lastSent.set(
|
|
13363
|
+
this.pending.delete(agentId2);
|
|
13364
|
+
this.lastSent.set(agentId2, now2);
|
|
13325
13365
|
send(eventFrame("agent.status_changed", data));
|
|
13326
13366
|
}
|
|
13327
|
-
for (const [
|
|
13328
|
-
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));
|
|
13329
13369
|
this.schedule(next);
|
|
13330
13370
|
}
|
|
13331
13371
|
schedule(at) {
|
|
@@ -13450,17 +13490,17 @@ function herdrBinary(env, platform = process.platform) {
|
|
|
13450
13490
|
return env.HERDR_BIN_PATH || (platform === "win32" ? "herdr.exe" : "herdr");
|
|
13451
13491
|
}
|
|
13452
13492
|
function createHerdrRunner(env) {
|
|
13453
|
-
return (args, options) => new Promise((
|
|
13493
|
+
return (args, options) => new Promise((resolve6) => {
|
|
13454
13494
|
execFile(
|
|
13455
13495
|
herdrBinary(env),
|
|
13456
13496
|
args,
|
|
13457
13497
|
{ env, timeout: options?.timeoutMs ?? 6e4, windowsHide: true, maxBuffer: 4 * 1024 * 1024, shell: false },
|
|
13458
13498
|
(error, stdout, stderr) => {
|
|
13459
|
-
if (!error) return
|
|
13499
|
+
if (!error) return resolve6({ code: 0, stdout, stderr });
|
|
13460
13500
|
const failure = error;
|
|
13461
|
-
if (failure.code === "ENOENT") return
|
|
13501
|
+
if (failure.code === "ENOENT") return resolve6({ code: 127, stdout: "", stderr: failure.message, notFound: true });
|
|
13462
13502
|
const code = typeof failure.code === "number" ? failure.code : 1;
|
|
13463
|
-
|
|
13503
|
+
resolve6({ code, stdout: stdout ?? "", stderr: stderr || (failure.killed ? "timed out" : failure.message) });
|
|
13464
13504
|
}
|
|
13465
13505
|
);
|
|
13466
13506
|
});
|
|
@@ -13543,27 +13583,27 @@ function cmdQuote(arg) {
|
|
|
13543
13583
|
if (/["%^&|<>!\r\n]/.test(arg)) throw new Error(`Refusing to pass an unsafe argument to the shell: ${arg}`);
|
|
13544
13584
|
return `"${arg}"`;
|
|
13545
13585
|
}
|
|
13546
|
-
var execProgram = (file, args, options = {}) => new Promise((
|
|
13586
|
+
var execProgram = (file, args, options = {}) => new Promise((resolve6) => {
|
|
13547
13587
|
const viaShell = process.platform === "win32" && !/[\\/]/.test(file) && !/\.exe$/i.test(file);
|
|
13548
13588
|
let child;
|
|
13549
13589
|
try {
|
|
13550
13590
|
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 });
|
|
13551
13591
|
} catch (error) {
|
|
13552
|
-
|
|
13592
|
+
resolve6({ code: 1, stdout: "", stderr: error.message });
|
|
13553
13593
|
return;
|
|
13554
13594
|
}
|
|
13555
13595
|
let stdout = "";
|
|
13556
13596
|
let stderr = "";
|
|
13557
13597
|
let settled = false;
|
|
13558
|
-
const
|
|
13598
|
+
const finish2 = (result) => {
|
|
13559
13599
|
if (settled) return;
|
|
13560
13600
|
settled = true;
|
|
13561
13601
|
clearTimeout(timer);
|
|
13562
|
-
|
|
13602
|
+
resolve6(result);
|
|
13563
13603
|
};
|
|
13564
13604
|
const timer = setTimeout(() => {
|
|
13565
13605
|
child.kill();
|
|
13566
|
-
|
|
13606
|
+
finish2({ code: 1, stdout, stderr: `${stderr}
|
|
13567
13607
|
timed out` });
|
|
13568
13608
|
}, options.timeoutMs ?? 3e5);
|
|
13569
13609
|
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
@@ -13574,10 +13614,10 @@ timed out` });
|
|
|
13574
13614
|
stderr += chunk;
|
|
13575
13615
|
options.onStderr?.(chunk);
|
|
13576
13616
|
});
|
|
13577
|
-
child.once("error", (error) =>
|
|
13617
|
+
child.once("error", (error) => finish2({ code: 127, stdout, stderr: error.message, notFound: error.code === "ENOENT" }));
|
|
13578
13618
|
child.once("close", (code) => {
|
|
13579
|
-
if (viaShell && code === 9009) return
|
|
13580
|
-
|
|
13619
|
+
if (viaShell && code === 9009) return finish2({ code: 127, stdout, stderr: stderr || `${file} was not found`, notFound: true });
|
|
13620
|
+
finish2({ code: code ?? 1, stdout, stderr });
|
|
13581
13621
|
});
|
|
13582
13622
|
});
|
|
13583
13623
|
|
|
@@ -13766,6 +13806,591 @@ function printMcpHint(ctx, serverUrl) {
|
|
|
13766
13806
|
ctx.out.print(s.dim(`Claude Code: claude mcp add --transport http peerband ${url}`));
|
|
13767
13807
|
}
|
|
13768
13808
|
|
|
13809
|
+
// src/cli/commands/tools.ts
|
|
13810
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
13811
|
+
var NO_TOOL_SUPPORT = "This PeerBand server doesn't support agent tools from the CLI yet.";
|
|
13812
|
+
var SERVER_WAIT_CAP = 50;
|
|
13813
|
+
var MAX_WAIT = 3600;
|
|
13814
|
+
var ToolError = class extends CliError {
|
|
13815
|
+
body;
|
|
13816
|
+
constructor(body) {
|
|
13817
|
+
super(`${sanitize(body.code)}: ${sanitize(body.message)}`, body.next_step ? sanitize(body.next_step) : void 0);
|
|
13818
|
+
this.name = "ToolError";
|
|
13819
|
+
this.body = body;
|
|
13820
|
+
}
|
|
13821
|
+
};
|
|
13822
|
+
function errorBody(parsed) {
|
|
13823
|
+
const error = parsed && typeof parsed === "object" ? parsed.error : void 0;
|
|
13824
|
+
if (!error || typeof error !== "object") return void 0;
|
|
13825
|
+
const { code, message, next_step: next } = error;
|
|
13826
|
+
if (typeof code !== "string") return void 0;
|
|
13827
|
+
return { code, message: typeof message === "string" ? message : "", next_step: typeof next === "string" ? next : "" };
|
|
13828
|
+
}
|
|
13829
|
+
async function callTool(ctx, credentials, tool, args, timeoutMs = 3e4) {
|
|
13830
|
+
const url = new URL(`/api/installation/tools/${encodeURIComponent(tool)}`, enrollmentBase(credentials.serverUrl));
|
|
13831
|
+
let response;
|
|
13832
|
+
try {
|
|
13833
|
+
response = await ctx.fetch(url, {
|
|
13834
|
+
method: "POST",
|
|
13835
|
+
headers: { authorization: `Bearer ${credentials.credential}`, "content-type": "application/json" },
|
|
13836
|
+
body: JSON.stringify(args),
|
|
13837
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
13838
|
+
});
|
|
13839
|
+
} catch (error) {
|
|
13840
|
+
throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
|
|
13841
|
+
}
|
|
13842
|
+
const parsed = await response.json().catch(() => ({}));
|
|
13843
|
+
if (response.ok) {
|
|
13844
|
+
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.");
|
|
13845
|
+
return parsed;
|
|
13846
|
+
}
|
|
13847
|
+
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.");
|
|
13848
|
+
const body = errorBody(parsed);
|
|
13849
|
+
if (body) throw new ToolError(body);
|
|
13850
|
+
if (response.status === 404 || response.status === 405) throw new CliError(NO_TOOL_SUPPORT, "Use the PeerBand MCP server or the dashboard for now.");
|
|
13851
|
+
throw new CliError(`PeerBand answered HTTP ${response.status}.`, "Try again in a moment.");
|
|
13852
|
+
}
|
|
13853
|
+
async function listTools(ctx, credentials) {
|
|
13854
|
+
const url = new URL("/api/installation/tools", enrollmentBase(credentials.serverUrl));
|
|
13855
|
+
let response;
|
|
13856
|
+
try {
|
|
13857
|
+
response = await ctx.fetch(url, { headers: { authorization: `Bearer ${credentials.credential}` }, signal: AbortSignal.timeout(15e3) });
|
|
13858
|
+
} catch (error) {
|
|
13859
|
+
throw new CliError(`Could not reach ${url.origin}: ${error.message}`, "Check your network connection and try again.");
|
|
13860
|
+
}
|
|
13861
|
+
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.");
|
|
13862
|
+
if (!response.ok) throw new CliError(NO_TOOL_SUPPORT, "Use the PeerBand MCP server or the dashboard for now.");
|
|
13863
|
+
return await response.json().catch(() => ({}));
|
|
13864
|
+
}
|
|
13865
|
+
var newKey = () => `cli-${randomUUID3()}`;
|
|
13866
|
+
function printResult(ctx, result) {
|
|
13867
|
+
ctx.out.print(JSON.stringify(result, null, 2));
|
|
13868
|
+
}
|
|
13869
|
+
async function runTool(ctx, operation, onKey) {
|
|
13870
|
+
const credentials = await requireCredentials(ctx);
|
|
13871
|
+
try {
|
|
13872
|
+
printResult(ctx, await operation(credentials));
|
|
13873
|
+
return 0;
|
|
13874
|
+
} catch (error) {
|
|
13875
|
+
if (error instanceof ToolError) {
|
|
13876
|
+
printResult(ctx, { error: error.body });
|
|
13877
|
+
ctx.out.fail(error.message, error.hint);
|
|
13878
|
+
return 1;
|
|
13879
|
+
}
|
|
13880
|
+
if (onKey && error instanceof CliError && error.message.startsWith("Could not reach")) {
|
|
13881
|
+
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\`.`);
|
|
13882
|
+
}
|
|
13883
|
+
throw error;
|
|
13884
|
+
}
|
|
13885
|
+
}
|
|
13886
|
+
function installationArg(credentials, options) {
|
|
13887
|
+
if (options.installation && options.here) throw new CliError("Pass either --installation or --here, not both.");
|
|
13888
|
+
if (options.here) return { installation_id: credentials.installationId };
|
|
13889
|
+
return options.installation ? { installation_id: options.installation } : {};
|
|
13890
|
+
}
|
|
13891
|
+
var sleepFor = (ctx, ms) => ctx.sleep ? ctx.sleep(ms, ctx.signal) : new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
13892
|
+
var now = (ctx) => ctx.now ? ctx.now() : Date.now();
|
|
13893
|
+
async function waitForAgent(ctx, credentials, args) {
|
|
13894
|
+
const total = args.timeout_seconds;
|
|
13895
|
+
if (total === void 0 || total <= SERVER_WAIT_CAP) return callTool(ctx, credentials, "wait_for_agent", args, ((total ?? 30) + 30) * 1e3);
|
|
13896
|
+
const started = now(ctx);
|
|
13897
|
+
const deadline = started + total * 1e3;
|
|
13898
|
+
let result;
|
|
13899
|
+
for (; ; ) {
|
|
13900
|
+
const left = Math.max(1, Math.ceil((deadline - now(ctx)) / 1e3));
|
|
13901
|
+
const slice = Math.min(SERVER_WAIT_CAP, left);
|
|
13902
|
+
result = await callTool(ctx, credentials, "wait_for_agent", { ...args, timeout_seconds: slice }, (slice + 30) * 1e3);
|
|
13903
|
+
if (result.reason !== "timeout" || now(ctx) >= deadline - 1e3) break;
|
|
13904
|
+
if (typeof result.waited_seconds === "number" && result.waited_seconds < 1) await sleepFor(ctx, 1e3);
|
|
13905
|
+
}
|
|
13906
|
+
return { ...result, waited_seconds: Math.round((now(ctx) - started) / 100) / 10 };
|
|
13907
|
+
}
|
|
13908
|
+
var SETTLED = ["idle", "done", "blocked"];
|
|
13909
|
+
async function askAgent(ctx, credentials, args) {
|
|
13910
|
+
const total = args.timeout_seconds;
|
|
13911
|
+
const first = total === void 0 ? void 0 : Math.min(SERVER_WAIT_CAP, total);
|
|
13912
|
+
const started = now(ctx);
|
|
13913
|
+
const result = await callTool(ctx, credentials, "ask_agent", { ...args, ...first !== void 0 ? { timeout_seconds: first } : {} }, ((first ?? 45) + 30) * 1e3);
|
|
13914
|
+
if (total === void 0 || total <= SERVER_WAIT_CAP || result.reason !== "timeout") return result;
|
|
13915
|
+
const deadline = started + total * 1e3;
|
|
13916
|
+
const target = { agent_id: args.agent_id, installation_id: result.installation_id ?? args.installation_id };
|
|
13917
|
+
const left = () => Math.floor((deadline - now(ctx)) / 1e3);
|
|
13918
|
+
let began = result.started_working === true;
|
|
13919
|
+
let status = result.status;
|
|
13920
|
+
if (!began && left() > 1) {
|
|
13921
|
+
const start = await waitForAgent(ctx, credentials, { ...target, statuses: ["working", "blocked"], timeout_seconds: left() });
|
|
13922
|
+
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." };
|
|
13923
|
+
if (start.matched === true) {
|
|
13924
|
+
status = start.status;
|
|
13925
|
+
began = true;
|
|
13926
|
+
if (status === "blocked") return finish(ctx, credentials, result, target, "blocked", status, began, started, args.output_lines);
|
|
13927
|
+
}
|
|
13928
|
+
}
|
|
13929
|
+
if (began && left() > 1) {
|
|
13930
|
+
const settled = await waitForAgent(ctx, credentials, { ...target, statuses: SETTLED, timeout_seconds: left() });
|
|
13931
|
+
status = settled.status;
|
|
13932
|
+
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." };
|
|
13933
|
+
if (settled.matched === true) return finish(ctx, credentials, result, target, status === "blocked" ? "blocked" : "finished", status, began, started, args.output_lines);
|
|
13934
|
+
}
|
|
13935
|
+
return {
|
|
13936
|
+
...result,
|
|
13937
|
+
status,
|
|
13938
|
+
started_working: began,
|
|
13939
|
+
waited_seconds: elapsed(ctx, started),
|
|
13940
|
+
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`."
|
|
13941
|
+
};
|
|
13942
|
+
}
|
|
13943
|
+
var elapsed = (ctx, started) => Math.round((now(ctx) - started) / 100) / 10;
|
|
13944
|
+
async function finish(ctx, credentials, first, target, reason, status, began, started, lines) {
|
|
13945
|
+
const out = { ...first, reason, status, started_working: began, waited_seconds: elapsed(ctx, started) };
|
|
13946
|
+
delete out.next_step;
|
|
13947
|
+
const delivery = first.delivery;
|
|
13948
|
+
if (delivery?.request_id) {
|
|
13949
|
+
try {
|
|
13950
|
+
const receipt = await callTool(ctx, credentials, "get_request_status", { installation_id: target.installation_id, request_id: delivery.request_id });
|
|
13951
|
+
out.delivery = { request_id: receipt.requestId ?? delivery.request_id, state: receipt.state, ...receipt.errorCode ? { error_code: receipt.errorCode } : {} };
|
|
13952
|
+
} catch {
|
|
13953
|
+
}
|
|
13954
|
+
}
|
|
13955
|
+
if (lines) {
|
|
13956
|
+
try {
|
|
13957
|
+
out.output = await callTool(ctx, credentials, "get_agent_output", { ...target, lines });
|
|
13958
|
+
} catch (error) {
|
|
13959
|
+
if (error instanceof ToolError) out.output_error = { code: error.body.code, message: error.body.message };
|
|
13960
|
+
else throw error;
|
|
13961
|
+
}
|
|
13962
|
+
}
|
|
13963
|
+
return out;
|
|
13964
|
+
}
|
|
13965
|
+
|
|
13966
|
+
// src/cli/commands/agents.ts
|
|
13967
|
+
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." };
|
|
13968
|
+
var HERE = { name: "here", type: "boolean", description: "Use this machine (its own installation_id)." };
|
|
13969
|
+
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." };
|
|
13970
|
+
var AGENT_ID = /^[^\u0000-\u001f\u007f]{1,256}$/;
|
|
13971
|
+
function integer(parsed, name, min, max) {
|
|
13972
|
+
const raw = str(parsed, name);
|
|
13973
|
+
if (raw === void 0) return void 0;
|
|
13974
|
+
const value = Number(raw);
|
|
13975
|
+
if (!Number.isInteger(value) || value < min || value > max) throw new UsageError(`Invalid --${name} value "${sanitize(raw)}".`, `Use a whole number from ${min} to ${max}.`);
|
|
13976
|
+
return value;
|
|
13977
|
+
}
|
|
13978
|
+
function key(parsed) {
|
|
13979
|
+
const value = str(parsed, "key") ?? newKey();
|
|
13980
|
+
if (value.length < 16 || value.length > 256) throw new UsageError("The --key must be 16 to 256 characters.");
|
|
13981
|
+
return value;
|
|
13982
|
+
}
|
|
13983
|
+
function agentId(value, usage) {
|
|
13984
|
+
if (value === void 0) throw new UsageError("Missing the agent id.", `Usage: ${usage}. Agent ids come from \`peerband agents\`.`);
|
|
13985
|
+
if (!AGENT_ID.test(value)) throw new UsageError("Invalid agent id.", "Use an agent id from `peerband agents`.");
|
|
13986
|
+
return value;
|
|
13987
|
+
}
|
|
13988
|
+
async function messageText(words, ctx, usage) {
|
|
13989
|
+
const text2 = words.length === 1 && words[0] === "-" ? await readStdin(ctx) : words.join(" ");
|
|
13990
|
+
if (!text2.trim()) throw new UsageError("The message is empty.", `Usage: ${usage}`);
|
|
13991
|
+
return text2;
|
|
13992
|
+
}
|
|
13993
|
+
function readStdin(ctx) {
|
|
13994
|
+
return new Promise((resolve6) => {
|
|
13995
|
+
let text2 = "";
|
|
13996
|
+
const onData = (chunk) => text2 += chunk.toString();
|
|
13997
|
+
ctx.stdin.on("data", onData);
|
|
13998
|
+
const end = () => {
|
|
13999
|
+
ctx.stdin.off("data", onData);
|
|
14000
|
+
ctx.stdin.pause();
|
|
14001
|
+
resolve6(text2.replace(/\r?\n$/, ""));
|
|
14002
|
+
};
|
|
14003
|
+
ctx.stdin.once?.("end", end);
|
|
14004
|
+
ctx.stdin.resume();
|
|
14005
|
+
});
|
|
14006
|
+
}
|
|
14007
|
+
var where = async (ctx, parsed) => installationArg(await requireCredentials(ctx), { installation: str(parsed, "installation"), here: flag(parsed, "here") });
|
|
14008
|
+
var machinesSpec = {
|
|
14009
|
+
name: "machines",
|
|
14010
|
+
summary: "List the account's machines and machines shared with it (list_machines)",
|
|
14011
|
+
usage: "peerband machines",
|
|
14012
|
+
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.",
|
|
14013
|
+
options: [],
|
|
14014
|
+
examples: [["peerband machines", "Every machine you can reach, as JSON"]],
|
|
14015
|
+
notes: ["Needs `peerband login`; the relay does not have to be running."],
|
|
14016
|
+
run: (_parsed, ctx) => runTool(ctx, (credentials) => callTool(ctx, credentials, "list_machines", {}))
|
|
14017
|
+
};
|
|
14018
|
+
var agentsSpec = {
|
|
14019
|
+
name: "agents",
|
|
14020
|
+
summary: "List the coding agents on a machine (list_agents)",
|
|
14021
|
+
usage: "peerband agents [--installation ID | --here] [--status STATUS] [--workspace NAME] [--machine NAME] [--limit N] [--cursor C]",
|
|
14022
|
+
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`.",
|
|
14023
|
+
options: [
|
|
14024
|
+
INSTALLATION,
|
|
14025
|
+
HERE,
|
|
14026
|
+
{ name: "status", type: "string", valueName: "STATUS", description: "Only agents in this status: idle, working, blocked, done or unknown." },
|
|
14027
|
+
{ name: "workspace", type: "string", valueName: "NAME", description: "Only agents in this Herdr workspace." },
|
|
14028
|
+
{ name: "machine", type: "string", valueName: "NAME", description: "The list_agents machine filter." },
|
|
14029
|
+
{ name: "limit", type: "string", valueName: "N", description: "At most N agents (1 to 200)." },
|
|
14030
|
+
{ name: "cursor", type: "string", valueName: "C", description: "Continue from the cursor of an earlier page." }
|
|
14031
|
+
],
|
|
14032
|
+
examples: [
|
|
14033
|
+
["peerband agents", "Agents on your only (or only online) machine"],
|
|
14034
|
+
["peerband agents --installation 1f0c\u2026 --status idle", "Idle agents on one machine"]
|
|
14035
|
+
],
|
|
14036
|
+
notes: ["Needs `peerband login`; the relay does not have to be running on this machine."],
|
|
14037
|
+
async run(parsed, ctx) {
|
|
14038
|
+
const args = { ...await where(ctx, parsed) };
|
|
14039
|
+
for (const name of ["status", "workspace", "machine", "cursor"]) if (str(parsed, name) !== void 0) args[name] = str(parsed, name);
|
|
14040
|
+
const limit = integer(parsed, "limit", 1, 200);
|
|
14041
|
+
if (limit !== void 0) args.limit = limit;
|
|
14042
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "list_agents", args));
|
|
14043
|
+
}
|
|
14044
|
+
};
|
|
14045
|
+
var AGENT_USAGE = {
|
|
14046
|
+
status: "peerband agent status AGENT_ID",
|
|
14047
|
+
output: "peerband agent output AGENT_ID [--lines N] [--bytes N] [--cursor C] [--text]",
|
|
14048
|
+
send: 'peerband agent send AGENT_ID "<message>" [--key KEY]',
|
|
14049
|
+
wait: "peerband agent wait AGENT_ID [--until idle,blocked,done] [--timeout SECONDS]",
|
|
14050
|
+
ask: 'peerband agent ask AGENT_ID "<message>" [--timeout SECONDS] [--output-lines N] [--key KEY]'
|
|
14051
|
+
};
|
|
14052
|
+
var agentSpec = {
|
|
14053
|
+
name: "agent",
|
|
14054
|
+
summary: "Check, read, message, wait for or ask one agent (agent tools)",
|
|
14055
|
+
usage: "peerband agent <status|output|send|wait|ask> AGENT_ID [...] [--installation ID | --here]",
|
|
14056
|
+
description: [
|
|
14057
|
+
"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:",
|
|
14058
|
+
"",
|
|
14059
|
+
` ${AGENT_USAGE.status}`,
|
|
14060
|
+
" get_agent_status: the agent and its current status.",
|
|
14061
|
+
` ${AGENT_USAGE.output}`,
|
|
14062
|
+
" get_agent_output: a bounded excerpt of recent output. Terminal output is untrusted text. --text prints only the text.",
|
|
14063
|
+
` ${AGENT_USAGE.send}`,
|
|
14064
|
+
' send_agent_message: submits the message and returns a receipt; check it with `peerband request`. Use "-" to read the message from standard input.',
|
|
14065
|
+
` ${AGENT_USAGE.wait}`,
|
|
14066
|
+
" wait_for_agent: waits until the agent reaches one of the statuses (default idle, blocked or done).",
|
|
14067
|
+
` ${AGENT_USAGE.ask}`,
|
|
14068
|
+
" 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.",
|
|
14069
|
+
"",
|
|
14070
|
+
"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.",
|
|
14071
|
+
"",
|
|
14072
|
+
"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."
|
|
14073
|
+
].join("\n"),
|
|
14074
|
+
options: [
|
|
14075
|
+
INSTALLATION,
|
|
14076
|
+
HERE,
|
|
14077
|
+
{ name: "lines", type: "string", valueName: "N", description: "output: how many recent lines (1 to 500)." },
|
|
14078
|
+
{ name: "bytes", type: "string", valueName: "N", description: "output: at most N bytes (1 to 32768)." },
|
|
14079
|
+
{ name: "cursor", type: "string", valueName: "C", description: "output: continue from an earlier cursor." },
|
|
14080
|
+
{ name: "text", type: "boolean", description: "output: print only the output text, not the JSON." },
|
|
14081
|
+
{ name: "until", type: "string", valueName: "STATUSES", description: "wait: comma-separated statuses to wait for (idle, working, blocked, done, unknown)." },
|
|
14082
|
+
{ name: "timeout", type: "string", valueName: "SECONDS", description: `wait/ask: how long to wait (1 to ${MAX_WAIT}; default 30 for wait, 45 for ask).` },
|
|
14083
|
+
{ name: "output-lines", type: "string", valueName: "N", description: "ask: return the last N lines of the agent's reply (0 to 200)." },
|
|
14084
|
+
KEY
|
|
14085
|
+
],
|
|
14086
|
+
positionals: { name: "action", max: 66 },
|
|
14087
|
+
examples: [
|
|
14088
|
+
["peerband agent status herdr_1a2b\u2026", "Is it idle, working or blocked?"],
|
|
14089
|
+
["peerband agent output herdr_1a2b\u2026 --lines 80 --text", "The last 80 lines of its terminal"],
|
|
14090
|
+
['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"],
|
|
14091
|
+
['peerband agent send herdr_1a2b\u2026 "Also update the changelog" --installation 1f0c\u2026', "Send a follow-up to an agent on another machine"],
|
|
14092
|
+
["peerband agent wait herdr_1a2b\u2026 --until idle,blocked --timeout 600", "Wait for it to stop"]
|
|
14093
|
+
],
|
|
14094
|
+
notes: [
|
|
14095
|
+
"Needs `peerband login`; the relay does not have to be running on this machine, but it must be on the target machine.",
|
|
14096
|
+
'Exit code 1 means the tool reported an error: the {"error": {code, message, next_step}} object is printed on stdout.',
|
|
14097
|
+
'A wait or ask that ran out of time is not an error: it prints reason "timeout" and exits 0.'
|
|
14098
|
+
],
|
|
14099
|
+
async run(parsed, ctx) {
|
|
14100
|
+
const [action, id, ...rest] = parsed.positionals;
|
|
14101
|
+
if (action === void 0) throw new UsageError("Missing the action.", "Use one of: status, output, send, wait, ask. Run `peerband agent --help`.");
|
|
14102
|
+
if (!(action in AGENT_USAGE)) throw new UsageError(`Unknown agent action "${sanitize(action)}".`, "Use one of: status, output, send, wait, ask.");
|
|
14103
|
+
const usage = AGENT_USAGE[action];
|
|
14104
|
+
const agent = agentId(id, usage);
|
|
14105
|
+
const target = { ...await where(ctx, parsed), agent_id: agent };
|
|
14106
|
+
const timeout = integer(parsed, "timeout", 1, MAX_WAIT);
|
|
14107
|
+
switch (action) {
|
|
14108
|
+
case "status":
|
|
14109
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14110
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "get_agent_status", target));
|
|
14111
|
+
case "output": {
|
|
14112
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14113
|
+
const lines = integer(parsed, "lines", 1, 500);
|
|
14114
|
+
const bytes = integer(parsed, "bytes", 1, 32768);
|
|
14115
|
+
const args = { ...target, ...lines !== void 0 ? { lines } : {}, ...bytes !== void 0 ? { bytes } : {}, ...str(parsed, "cursor") !== void 0 ? { cursor: str(parsed, "cursor") } : {} };
|
|
14116
|
+
if (!flag(parsed, "text")) return runTool(ctx, (credentials2) => callTool(ctx, credentials2, "get_agent_output", args));
|
|
14117
|
+
const credentials = await requireCredentials(ctx);
|
|
14118
|
+
try {
|
|
14119
|
+
const result = await callTool(ctx, credentials, "get_agent_output", args);
|
|
14120
|
+
ctx.out.print(outputText(result));
|
|
14121
|
+
return 0;
|
|
14122
|
+
} catch (error) {
|
|
14123
|
+
if (error instanceof ToolError) {
|
|
14124
|
+
ctx.out.fail(error.message, error.hint);
|
|
14125
|
+
return 1;
|
|
14126
|
+
}
|
|
14127
|
+
throw error;
|
|
14128
|
+
}
|
|
14129
|
+
}
|
|
14130
|
+
case "send": {
|
|
14131
|
+
const message = await messageText(rest, ctx, usage);
|
|
14132
|
+
const idempotency = key(parsed);
|
|
14133
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "send_agent_message", { ...target, message, idempotency_key: idempotency }), idempotency);
|
|
14134
|
+
}
|
|
14135
|
+
case "wait": {
|
|
14136
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14137
|
+
const until = str(parsed, "until");
|
|
14138
|
+
const statuses = until === void 0 ? void 0 : until.split(",").map((status) => status.trim()).filter(Boolean);
|
|
14139
|
+
if (statuses !== void 0 && !statuses.length) throw new UsageError("--until needs at least one status.", "For example --until idle,blocked.");
|
|
14140
|
+
return runTool(ctx, (credentials) => waitForAgent(ctx, credentials, { ...target, ...statuses ? { statuses } : {}, ...timeout !== void 0 ? { timeout_seconds: timeout } : {} }));
|
|
14141
|
+
}
|
|
14142
|
+
case "ask": {
|
|
14143
|
+
const message = await messageText(rest, ctx, usage);
|
|
14144
|
+
const idempotency = key(parsed);
|
|
14145
|
+
const outputLines = integer(parsed, "output-lines", 0, 200);
|
|
14146
|
+
return runTool(ctx, (credentials) => askAgent(ctx, credentials, {
|
|
14147
|
+
...target,
|
|
14148
|
+
message,
|
|
14149
|
+
idempotency_key: idempotency,
|
|
14150
|
+
...timeout !== void 0 ? { timeout_seconds: timeout } : {},
|
|
14151
|
+
...outputLines !== void 0 ? { output_lines: outputLines } : {}
|
|
14152
|
+
}), idempotency);
|
|
14153
|
+
}
|
|
14154
|
+
}
|
|
14155
|
+
}
|
|
14156
|
+
};
|
|
14157
|
+
function outputText(result) {
|
|
14158
|
+
const value = result.output ?? result.text ?? result.lines;
|
|
14159
|
+
const pick = (item) => {
|
|
14160
|
+
if (typeof item === "string") return item;
|
|
14161
|
+
if (Array.isArray(item)) return item.map(pick).join("\n");
|
|
14162
|
+
if (item && typeof item === "object") {
|
|
14163
|
+
const object = item;
|
|
14164
|
+
return pick(object.text ?? object.value ?? object.lines ?? "");
|
|
14165
|
+
}
|
|
14166
|
+
return "";
|
|
14167
|
+
};
|
|
14168
|
+
return pick(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, " ");
|
|
14169
|
+
}
|
|
14170
|
+
var requestSpec = {
|
|
14171
|
+
name: "request",
|
|
14172
|
+
summary: "Check the delivery state of a message or environment change (get_request_status)",
|
|
14173
|
+
usage: "peerband request REQUEST_ID [--installation ID | --here]",
|
|
14174
|
+
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.',
|
|
14175
|
+
options: [INSTALLATION, HERE],
|
|
14176
|
+
positionals: { name: "request_id", max: 1 },
|
|
14177
|
+
examples: [["peerband request 6c1d\u2026 --installation 1f0c\u2026", "Did the message arrive?"]],
|
|
14178
|
+
async run(parsed, ctx) {
|
|
14179
|
+
const [id] = parsed.positionals;
|
|
14180
|
+
if (!id) throw new UsageError("Missing the request id.", "Usage: peerband request REQUEST_ID. It is the requestId in a send receipt.");
|
|
14181
|
+
const args = { ...await where(ctx, parsed), request_id: id };
|
|
14182
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "get_request_status", args));
|
|
14183
|
+
}
|
|
14184
|
+
};
|
|
14185
|
+
var ENV_ACTIONS = {
|
|
14186
|
+
"workspace.create": ["cwd"],
|
|
14187
|
+
"tab.create": ["workspace-id", "cwd"],
|
|
14188
|
+
"pane.split": ["pane-id", "cwd", "direction"],
|
|
14189
|
+
"agent.start": ["pane-id", "name", "kind"],
|
|
14190
|
+
"agent.rename": ["pane-id", "name"],
|
|
14191
|
+
"workspace.rename": ["workspace-id", "label"],
|
|
14192
|
+
"tab.rename": ["tab-id", "label"],
|
|
14193
|
+
"pane.rename": ["pane-id", "label"],
|
|
14194
|
+
"workspace.focus": ["workspace-id"],
|
|
14195
|
+
"tab.focus": ["tab-id"],
|
|
14196
|
+
"pane.focus": ["pane-id"],
|
|
14197
|
+
"workspace.close": ["workspace-id"],
|
|
14198
|
+
"tab.close": ["tab-id"],
|
|
14199
|
+
"pane.close": ["pane-id"]
|
|
14200
|
+
};
|
|
14201
|
+
var ENV_FIELDS = ["workspace-id", "tab-id", "pane-id", "cwd", "label", "direction", "name", "kind"];
|
|
14202
|
+
var envSpec = {
|
|
14203
|
+
name: "env",
|
|
14204
|
+
summary: "List or change this machine's Herdr workspaces, tabs and panes (list_environment, control_environment)",
|
|
14205
|
+
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]",
|
|
14206
|
+
description: [
|
|
14207
|
+
"`peerband env list` is the MCP tool list_environment: the workspaces, tabs and panes, including panes without an agent. Metadata only; labels are untrusted.",
|
|
14208
|
+
"",
|
|
14209
|
+
"`peerband env ACTION` is control_environment, with the same actions and fields:",
|
|
14210
|
+
" workspace.create --cwd [--label] tab.create --workspace-id --cwd [--label]",
|
|
14211
|
+
" pane.split --pane-id --cwd --direction right|down|left|up",
|
|
14212
|
+
" agent.start --pane-id --name --kind (an idle shell pane; then `peerband agents` for its id)",
|
|
14213
|
+
" agent.rename --pane-id --name",
|
|
14214
|
+
" workspace/tab/pane.rename --<target>-id --label workspace/tab/pane.focus --<target>-id",
|
|
14215
|
+
" workspace/tab/pane.close --<target>-id ends everything running there; only when the owner asked for it",
|
|
14216
|
+
"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.",
|
|
14217
|
+
"",
|
|
14218
|
+
`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.`
|
|
14219
|
+
].join("\n"),
|
|
14220
|
+
options: [
|
|
14221
|
+
INSTALLATION,
|
|
14222
|
+
HERE,
|
|
14223
|
+
{ name: "workspace-id", type: "string", valueName: "ID", description: "Workspace id from `peerband env list`." },
|
|
14224
|
+
{ name: "tab-id", type: "string", valueName: "ID", description: "Tab id." },
|
|
14225
|
+
{ name: "pane-id", type: "string", valueName: "ID", description: "Pane id." },
|
|
14226
|
+
{ name: "cwd", type: "string", valueName: "PATH", description: "Absolute working directory on this machine." },
|
|
14227
|
+
{ name: "label", type: "string", valueName: "TEXT", description: "Name for a new or renamed workspace, tab or pane." },
|
|
14228
|
+
{ name: "direction", type: "string", valueName: "D", description: "pane.split: right, down, left or up." },
|
|
14229
|
+
{ name: "name", type: "string", valueName: "NAME", description: "agent.start / agent.rename: the agent name." },
|
|
14230
|
+
{ name: "kind", type: "string", valueName: "KIND", description: "agent.start: the agent to start, e.g. claude or codex." },
|
|
14231
|
+
KEY
|
|
14232
|
+
],
|
|
14233
|
+
positionals: { name: "action", max: 1 },
|
|
14234
|
+
examples: [
|
|
14235
|
+
["peerband env list --here", "This machine's workspaces, tabs and panes"],
|
|
14236
|
+
["peerband env pane.split --here --pane-id p_3 --cwd /home/me/app --direction right", "Open a new pane"],
|
|
14237
|
+
["peerband env agent.start --here --pane-id p_4 --name reviewer --kind claude", "Start an agent in an idle pane"]
|
|
14238
|
+
],
|
|
14239
|
+
notes: ["Needs `peerband login`, and the relay running on this machine."],
|
|
14240
|
+
async run(parsed, ctx) {
|
|
14241
|
+
const [action] = parsed.positionals;
|
|
14242
|
+
if (!action) throw new UsageError("Missing the action.", "Use `peerband env list --here`, or an action such as pane.split. Run `peerband env --help`.");
|
|
14243
|
+
const base = await where(ctx, parsed);
|
|
14244
|
+
if (!base.installation_id) throw new UsageError("Environment commands need an explicit machine.", "Pass --here for this machine.");
|
|
14245
|
+
if (action === "list") return runTool(ctx, (credentials) => callTool(ctx, credentials, "list_environment", base));
|
|
14246
|
+
const needs = ENV_ACTIONS[action];
|
|
14247
|
+
if (!needs) throw new UsageError(`Unknown environment action "${sanitize(action)}".`, `Use list or one of: ${Object.keys(ENV_ACTIONS).join(", ")}.`);
|
|
14248
|
+
const allowed = /* @__PURE__ */ new Set([...needs, ...action.endsWith(".create") && action !== "agent.start" ? ["label"] : []]);
|
|
14249
|
+
const missing = needs.filter((name) => str(parsed, name) === void 0);
|
|
14250
|
+
if (missing.length) throw new UsageError(`${action} needs ${missing.map((name) => `--${name}`).join(", ")}.`, "Run `peerband env --help`.");
|
|
14251
|
+
const extra = ENV_FIELDS.filter((name) => str(parsed, name) !== void 0 && !allowed.has(name));
|
|
14252
|
+
if (extra.length) throw new UsageError(`${action} does not take ${extra.map((name) => `--${name}`).join(", ")}.`, "Run `peerband env --help`.");
|
|
14253
|
+
const idempotency = key(parsed);
|
|
14254
|
+
const args = { ...base, action, idempotency_key: idempotency };
|
|
14255
|
+
for (const name of allowed) if (str(parsed, name) !== void 0) args[name.replace("-", "_")] = str(parsed, name);
|
|
14256
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "control_environment", args), idempotency);
|
|
14257
|
+
}
|
|
14258
|
+
};
|
|
14259
|
+
var CONCIERGE_USAGE = {
|
|
14260
|
+
ask: 'peerband concierge ask "<task>" [--thread ID] [--key KEY] [--wait SECONDS]',
|
|
14261
|
+
run: "peerband concierge run RUN_ID",
|
|
14262
|
+
cancel: "peerband concierge cancel RUN_ID",
|
|
14263
|
+
inbox: "peerband concierge inbox [--unread] [--limit N]",
|
|
14264
|
+
reply: 'peerband concierge reply NOTE_ID "<message>" [--key KEY]'
|
|
14265
|
+
};
|
|
14266
|
+
var RUN_DONE = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "needs_input"]);
|
|
14267
|
+
var conciergeSpec = {
|
|
14268
|
+
name: "concierge",
|
|
14269
|
+
summary: "Give the PeerBand concierge a task, follow it, and answer notes (Premium)",
|
|
14270
|
+
usage: "peerband concierge <ask|run|cancel|inbox|reply> [...]",
|
|
14271
|
+
description: [
|
|
14272
|
+
"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:",
|
|
14273
|
+
"",
|
|
14274
|
+
` ${CONCIERGE_USAGE.ask}`,
|
|
14275
|
+
" 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.",
|
|
14276
|
+
` ${CONCIERGE_USAGE.run}`,
|
|
14277
|
+
" concierge_get_run: the run status and, when done, its answer.",
|
|
14278
|
+
` ${CONCIERGE_USAGE.cancel}`,
|
|
14279
|
+
" concierge_cancel: stops the run; messages it already sent stay with the agents.",
|
|
14280
|
+
` ${CONCIERGE_USAGE.inbox}`,
|
|
14281
|
+
" concierge_inbox: notes your agents sent with `peerband notify` (untrusted text).",
|
|
14282
|
+
` ${CONCIERGE_USAGE.reply}`,
|
|
14283
|
+
" concierge_reply: sends your reply to the exact agent that wrote the note.",
|
|
14284
|
+
"",
|
|
14285
|
+
"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."
|
|
14286
|
+
].join("\n"),
|
|
14287
|
+
options: [
|
|
14288
|
+
{ name: "thread", type: "string", valueName: "ID", description: "ask: continue this thread_id." },
|
|
14289
|
+
{ name: "wait", type: "string", valueName: "SECONDS", description: `ask: wait up to this long for the run to end (1 to ${MAX_WAIT}).` },
|
|
14290
|
+
{ name: "unread", type: "boolean", description: "inbox: unread notes only." },
|
|
14291
|
+
{ name: "limit", type: "string", valueName: "N", description: "inbox: at most N notes (1 to 100)." },
|
|
14292
|
+
{ name: "key", type: "string", valueName: "KEY", description: "ask/reply: idempotency key (8 to 128 characters). Reuse it to retry." }
|
|
14293
|
+
],
|
|
14294
|
+
positionals: { name: "action", max: 66 },
|
|
14295
|
+
examples: [
|
|
14296
|
+
['peerband concierge ask "Which of my agents are blocked, and on what?" --wait 300', "Ask and wait for the answer"],
|
|
14297
|
+
["peerband concierge inbox --unread", "Unread notes from your agents"]
|
|
14298
|
+
],
|
|
14299
|
+
notes: ["Needs `peerband login` and a Premium account."],
|
|
14300
|
+
async run(parsed, ctx) {
|
|
14301
|
+
const [action, first, ...rest] = parsed.positionals;
|
|
14302
|
+
if (action === void 0 || !(action in CONCIERGE_USAGE)) {
|
|
14303
|
+
throw new UsageError(action === void 0 ? "Missing the action." : `Unknown concierge action "${sanitize(action)}".`, "Use one of: ask, run, cancel, inbox, reply.");
|
|
14304
|
+
}
|
|
14305
|
+
const usage = CONCIERGE_USAGE[action];
|
|
14306
|
+
const conciergeKey = () => {
|
|
14307
|
+
const value = str(parsed, "key");
|
|
14308
|
+
if (value !== void 0 && (value.length < 8 || value.length > 128)) throw new UsageError("The --key must be 8 to 128 characters.");
|
|
14309
|
+
return value ?? newKey();
|
|
14310
|
+
};
|
|
14311
|
+
const id = (value, what) => {
|
|
14312
|
+
if (!value) throw new UsageError(`Missing the ${what}.`, `Usage: ${usage}`);
|
|
14313
|
+
return value;
|
|
14314
|
+
};
|
|
14315
|
+
switch (action) {
|
|
14316
|
+
case "ask": {
|
|
14317
|
+
const request = await messageText(first === void 0 ? [] : [first, ...rest], ctx, usage);
|
|
14318
|
+
const wait = integer(parsed, "wait", 1, MAX_WAIT);
|
|
14319
|
+
const idempotency = conciergeKey();
|
|
14320
|
+
const args = { request, idempotency_key: idempotency, ...str(parsed, "thread") ? { thread_id: str(parsed, "thread") } : {} };
|
|
14321
|
+
return runTool(ctx, async (credentials) => {
|
|
14322
|
+
const run3 = await callTool(ctx, credentials, "concierge_ask", args);
|
|
14323
|
+
if (wait === void 0 || typeof run3.run_id !== "string") return run3;
|
|
14324
|
+
return followRun(ctx, credentials, run3.run_id, wait, run3);
|
|
14325
|
+
}, idempotency);
|
|
14326
|
+
}
|
|
14327
|
+
case "run":
|
|
14328
|
+
case "cancel": {
|
|
14329
|
+
const runId = id(first, "run id");
|
|
14330
|
+
if (rest.length) throw new UsageError(`Unexpected argument "${sanitize(rest[0])}".`, `Usage: ${usage}`);
|
|
14331
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, action === "run" ? "concierge_get_run" : "concierge_cancel", { run_id: runId }));
|
|
14332
|
+
}
|
|
14333
|
+
case "inbox": {
|
|
14334
|
+
if (first !== void 0) throw new UsageError(`Unexpected argument "${sanitize(first)}".`, `Usage: ${usage}`);
|
|
14335
|
+
const limit = integer(parsed, "limit", 1, 100);
|
|
14336
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "concierge_inbox", { unread_only: flag(parsed, "unread"), ...limit !== void 0 ? { limit } : {} }));
|
|
14337
|
+
}
|
|
14338
|
+
default: {
|
|
14339
|
+
const noteId = id(first, "note id");
|
|
14340
|
+
const message = await messageText(rest, ctx, usage);
|
|
14341
|
+
const idempotency = conciergeKey();
|
|
14342
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, "concierge_reply", { note_id: noteId, message, idempotency_key: idempotency }), idempotency);
|
|
14343
|
+
}
|
|
14344
|
+
}
|
|
14345
|
+
}
|
|
14346
|
+
};
|
|
14347
|
+
async function followRun(ctx, credentials, runId, seconds, last) {
|
|
14348
|
+
const now2 = () => ctx.now ? ctx.now() : Date.now();
|
|
14349
|
+
const sleep = (ms) => ctx.sleep ? ctx.sleep(ms, ctx.signal) : new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
14350
|
+
const deadline = now2() + seconds * 1e3;
|
|
14351
|
+
let view = last;
|
|
14352
|
+
while (!RUN_DONE.has(String(view.status)) && now2() < deadline) {
|
|
14353
|
+
await sleep(Math.min(3e3, Math.max(0, deadline - now2())));
|
|
14354
|
+
view = await callTool(ctx, credentials, "concierge_get_run", { run_id: runId });
|
|
14355
|
+
}
|
|
14356
|
+
return view;
|
|
14357
|
+
}
|
|
14358
|
+
var toolsSpec = {
|
|
14359
|
+
name: "tools",
|
|
14360
|
+
summary: "List the PeerBand tools this machine can call",
|
|
14361
|
+
usage: "peerband tools",
|
|
14362
|
+
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"}'\`.`,
|
|
14363
|
+
options: [],
|
|
14364
|
+
examples: [["peerband tools", "What this machine can do through PeerBand"]],
|
|
14365
|
+
run: (_parsed, ctx) => runTool(ctx, (credentials) => listTools(ctx, credentials))
|
|
14366
|
+
};
|
|
14367
|
+
var toolSpec = {
|
|
14368
|
+
name: "tool",
|
|
14369
|
+
summary: "Call a PeerBand MCP tool by name with JSON arguments",
|
|
14370
|
+
usage: `peerband tool NAME ['{"arg": "value"}' | -]`,
|
|
14371
|
+
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).',
|
|
14372
|
+
options: [],
|
|
14373
|
+
positionals: { name: "name", max: 2 },
|
|
14374
|
+
examples: [
|
|
14375
|
+
["peerband tool list_machines", "Same as peerband machines"],
|
|
14376
|
+
[`peerband tool get_agent_status '{"agent_id": "herdr_1a2b\u2026", "installation_id": "1f0c\u2026"}'`, "Any tool, any arguments"]
|
|
14377
|
+
],
|
|
14378
|
+
async run(parsed, ctx) {
|
|
14379
|
+
const [name, json] = parsed.positionals;
|
|
14380
|
+
if (!name || !/^[a-z_]{1,64}$/.test(name)) throw new UsageError("Missing or invalid tool name.", "Run `peerband tools` to list them.");
|
|
14381
|
+
const raw = json === "-" ? await readStdin(ctx) : json ?? "{}";
|
|
14382
|
+
let args;
|
|
14383
|
+
try {
|
|
14384
|
+
args = JSON.parse(raw);
|
|
14385
|
+
} catch {
|
|
14386
|
+
throw new UsageError("The arguments are not valid JSON.", `Pass a JSON object, for example '{"agent_id": "\u2026"}'.`);
|
|
14387
|
+
}
|
|
14388
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) throw new UsageError("The arguments must be a JSON object.");
|
|
14389
|
+
return runTool(ctx, (credentials) => callTool(ctx, credentials, name, args, 12e4));
|
|
14390
|
+
}
|
|
14391
|
+
};
|
|
14392
|
+
var toolCommands = [machinesSpec, agentsSpec, agentSpec, requestSpec, envSpec, conciergeSpec, toolsSpec, toolSpec];
|
|
14393
|
+
|
|
13769
14394
|
// src/cli/commands/channels.ts
|
|
13770
14395
|
var NO_CHANNEL_SUPPORT = "This PeerBand server doesn't support channels yet.";
|
|
13771
14396
|
var TELEGRAM_CHANNEL = "telegram";
|
|
@@ -13834,7 +14459,7 @@ var spec = {
|
|
|
13834
14459
|
// herdr/relay-tab.mjs
|
|
13835
14460
|
import { execFile as execFile2 } from "node:child_process";
|
|
13836
14461
|
import { mkdir as mkdir4, readFile as readFile4, rename as rename3, rm as rm3, rmdir as rmdir2, stat, writeFile as writeFile4 } from "node:fs/promises";
|
|
13837
|
-
import { randomUUID as
|
|
14462
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
13838
14463
|
import { dirname as dirname4 } from "node:path";
|
|
13839
14464
|
|
|
13840
14465
|
// herdr/paths.mjs
|
|
@@ -13932,7 +14557,7 @@ async function readRecord(statePath) {
|
|
|
13932
14557
|
}
|
|
13933
14558
|
async function writeRecord(statePath, record) {
|
|
13934
14559
|
await mkdir4(dirname4(statePath), { recursive: true });
|
|
13935
|
-
const temporary = `${statePath}.${
|
|
14560
|
+
const temporary = `${statePath}.${randomUUID4()}.tmp`;
|
|
13936
14561
|
try {
|
|
13937
14562
|
await writeFile4(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
13938
14563
|
await rename3(temporary, statePath);
|
|
@@ -13955,7 +14580,7 @@ async function withLaunchLock(statePath, action) {
|
|
|
13955
14580
|
try {
|
|
13956
14581
|
const info = await stat(lockPath3);
|
|
13957
14582
|
if (Date.now() - info.mtimeMs > 12e4) {
|
|
13958
|
-
const quarantine = `${lockPath3}.stale-${
|
|
14583
|
+
const quarantine = `${lockPath3}.stale-${randomUUID4()}`;
|
|
13959
14584
|
await rename3(lockPath3, quarantine).then(() => rmdir2(quarantine)).catch(() => {
|
|
13960
14585
|
});
|
|
13961
14586
|
stale = true;
|
|
@@ -13965,7 +14590,7 @@ async function withLaunchLock(statePath, action) {
|
|
|
13965
14590
|
}
|
|
13966
14591
|
if (stale) continue;
|
|
13967
14592
|
if (Date.now() >= deadline) throw new Error("Another PeerBand Relay tab launch is already in progress");
|
|
13968
|
-
await new Promise((
|
|
14593
|
+
await new Promise((resolve6) => setTimeout(resolve6, 100));
|
|
13969
14594
|
}
|
|
13970
14595
|
}
|
|
13971
14596
|
try {
|
|
@@ -14010,7 +14635,7 @@ async function renameOwnedSinglePaneTab(run3, pane, label) {
|
|
|
14010
14635
|
await run3(["tab", "rename", pane.tab_id, label]);
|
|
14011
14636
|
return true;
|
|
14012
14637
|
}
|
|
14013
|
-
function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker =
|
|
14638
|
+
function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker = randomUUID4, warn = () => {
|
|
14014
14639
|
} }) {
|
|
14015
14640
|
if (typeof run3 !== "function" || typeof statePath !== "string") throw new TypeError("run and statePath are required");
|
|
14016
14641
|
const lastVerifiedTitle = /* @__PURE__ */ new Map();
|
|
@@ -14022,10 +14647,10 @@ function createRelayTabController({ run: run3, statePath, pluginPaneId = "", new
|
|
|
14022
14647
|
if (!pane) return false;
|
|
14023
14648
|
try {
|
|
14024
14649
|
const label = tabTitle(enabled);
|
|
14025
|
-
const
|
|
14026
|
-
if (lastVerifiedTitle.get(
|
|
14650
|
+
const key2 = `${pane.pane_id}\0${pane.tab_id}`;
|
|
14651
|
+
if (lastVerifiedTitle.get(key2) === label) return true;
|
|
14027
14652
|
const renamed = await renameOwnedSinglePaneTab(run3, pane, label);
|
|
14028
|
-
if (renamed) lastVerifiedTitle.set(
|
|
14653
|
+
if (renamed) lastVerifiedTitle.set(key2, label);
|
|
14029
14654
|
return renamed;
|
|
14030
14655
|
} catch {
|
|
14031
14656
|
return false;
|
|
@@ -14144,7 +14769,7 @@ function paneLabel(snapshot) {
|
|
|
14144
14769
|
|
|
14145
14770
|
// herdr/stale-lock.mjs
|
|
14146
14771
|
import { execFile as execFile3 } from "node:child_process";
|
|
14147
|
-
import { randomUUID as
|
|
14772
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
14148
14773
|
import { readdir, readFile as readFile5, rename as rename4, rm as rm4, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
|
|
14149
14774
|
import { createConnection } from "node:net";
|
|
14150
14775
|
import { hostname as hostname2 } from "node:os";
|
|
@@ -14162,24 +14787,24 @@ function pidAlive2(pid) {
|
|
|
14162
14787
|
}
|
|
14163
14788
|
}
|
|
14164
14789
|
function probeChannel(channel, timeout = 1500) {
|
|
14165
|
-
return new Promise((
|
|
14790
|
+
return new Promise((resolve6) => {
|
|
14166
14791
|
let settled = false;
|
|
14167
14792
|
const socket = createConnection(channel);
|
|
14168
|
-
const
|
|
14793
|
+
const finish2 = (value) => {
|
|
14169
14794
|
if (settled) return;
|
|
14170
14795
|
settled = true;
|
|
14171
14796
|
clearTimeout(timer);
|
|
14172
14797
|
socket.destroy();
|
|
14173
|
-
|
|
14798
|
+
resolve6(value);
|
|
14174
14799
|
};
|
|
14175
|
-
const timer = setTimeout(() =>
|
|
14176
|
-
socket.once("connect", () =>
|
|
14177
|
-
socket.once("error", (error) =>
|
|
14800
|
+
const timer = setTimeout(() => finish2("unknown"), timeout);
|
|
14801
|
+
socket.once("connect", () => finish2("listening"));
|
|
14802
|
+
socket.once("error", (error) => finish2(error && (error.code === "ENOENT" || error.code === "ECONNREFUSED") ? "absent" : "unknown"));
|
|
14178
14803
|
});
|
|
14179
14804
|
}
|
|
14180
14805
|
function run(file, args, timeout) {
|
|
14181
|
-
return new Promise((
|
|
14182
|
-
execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) =>
|
|
14806
|
+
return new Promise((resolve6) => {
|
|
14807
|
+
execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve6(error ? null : String(stdout)));
|
|
14183
14808
|
});
|
|
14184
14809
|
}
|
|
14185
14810
|
async function listProcesses(platform = process.platform) {
|
|
@@ -14235,7 +14860,7 @@ async function readOwner(ownerFile) {
|
|
|
14235
14860
|
}
|
|
14236
14861
|
return { text: text2, owner: {} };
|
|
14237
14862
|
}
|
|
14238
|
-
async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list3 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now = Date.now() }) {
|
|
14863
|
+
async function inspectLock({ lockDir, ownerFile, channel, processPattern, excludePids = [], listProcesses: list3 = listProcesses, probe = probeChannel, alive = pidAlive2, host = hostname2(), now: now2 = Date.now() }) {
|
|
14239
14864
|
let info;
|
|
14240
14865
|
try {
|
|
14241
14866
|
info = await stat2(lockDir);
|
|
@@ -14264,7 +14889,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
|
|
|
14264
14889
|
}
|
|
14265
14890
|
return { state: "live", reason: `owner process ${pid} is running`, ownerText: text2, pid };
|
|
14266
14891
|
}
|
|
14267
|
-
if (text2 === null &&
|
|
14892
|
+
if (text2 === null && now2 - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
|
|
14268
14893
|
if (channel) {
|
|
14269
14894
|
const probed = await probe(channel);
|
|
14270
14895
|
if (probed === "listening") return { state: "live", reason: "a helper answers on the control channel", ownerText: text2 };
|
|
@@ -14279,7 +14904,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
|
|
|
14279
14904
|
return { state: "stale", reason: "no matching process is running", ownerText: text2 };
|
|
14280
14905
|
}
|
|
14281
14906
|
async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
|
|
14282
|
-
const quarantine = `${lockDir}.stale-${
|
|
14907
|
+
const quarantine = `${lockDir}.stale-${randomUUID5()}`;
|
|
14283
14908
|
try {
|
|
14284
14909
|
await rename4(lockDir, quarantine);
|
|
14285
14910
|
} catch (error) {
|
|
@@ -14339,31 +14964,31 @@ var FIELDS2 = ["workspace_id", "tab_id", "pane_id", "name", "label", "cwd", "age
|
|
|
14339
14964
|
function metadata(value) {
|
|
14340
14965
|
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
14341
14966
|
const row = value;
|
|
14342
|
-
const result = Object.fromEntries(FIELDS2.filter((
|
|
14343
|
-
for (const
|
|
14967
|
+
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]));
|
|
14968
|
+
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];
|
|
14344
14969
|
if (typeof row.focused === "boolean") result.focused = row.focused;
|
|
14345
14970
|
return result;
|
|
14346
14971
|
}
|
|
14347
14972
|
function environmentMetadata(value) {
|
|
14348
14973
|
const row = value && typeof value === "object" ? value : {};
|
|
14349
14974
|
const result = metadata(row);
|
|
14350
|
-
for (const
|
|
14351
|
-
if (row[
|
|
14975
|
+
for (const key2 of ["workspace", "tab", "pane", "root_pane", "agent"]) {
|
|
14976
|
+
if (row[key2] && typeof row[key2] === "object") result[key2.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = metadata(row[key2]);
|
|
14352
14977
|
}
|
|
14353
14978
|
return result;
|
|
14354
14979
|
}
|
|
14355
14980
|
async function listEnvironment(client) {
|
|
14356
14981
|
const result = { actions: [...ENVIRONMENT_ACTIONS] };
|
|
14357
|
-
for (const [method,
|
|
14982
|
+
for (const [method, key2] of [["workspace.list", "workspaces"], ["tab.list", "tabs"], ["pane.list", "panes"]]) {
|
|
14358
14983
|
const response = await client.request(method, {});
|
|
14359
|
-
if (!Array.isArray(response[
|
|
14360
|
-
let rows = response[
|
|
14361
|
-
if (
|
|
14984
|
+
if (!Array.isArray(response[key2])) throw new ConnectError("schema_mismatch", `Unexpected ${method} response.`, "Check the installed Herdr schema.");
|
|
14985
|
+
let rows = response[key2];
|
|
14986
|
+
if (key2 === "panes") {
|
|
14362
14987
|
const listed = await client.request("agent.list", {});
|
|
14363
14988
|
rows = rows.map((pane) => ({ ...pane, name: listed.agents?.find((agent) => agent.pane_id === pane.pane_id)?.name }));
|
|
14364
14989
|
}
|
|
14365
|
-
result[
|
|
14366
|
-
result[`${
|
|
14990
|
+
result[key2] = rows.slice(0, 50).map(metadata);
|
|
14991
|
+
result[`${key2}Truncated`] = response[key2].length > 50;
|
|
14367
14992
|
}
|
|
14368
14993
|
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.");
|
|
14369
14994
|
return result;
|
|
@@ -14371,9 +14996,9 @@ async function listEnvironment(client) {
|
|
|
14371
14996
|
function environmentParams(input) {
|
|
14372
14997
|
const command = environmentCommand(input);
|
|
14373
14998
|
const params = {};
|
|
14374
|
-
for (const [
|
|
14375
|
-
if (
|
|
14376
|
-
params[
|
|
14999
|
+
for (const [key2, value] of Object.entries(command)) {
|
|
15000
|
+
if (key2 === "action") continue;
|
|
15001
|
+
params[key2.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = value;
|
|
14377
15002
|
}
|
|
14378
15003
|
if (["workspace.create", "tab.create", "pane.split"].includes(command.action)) params.focus = false;
|
|
14379
15004
|
if (command.action === "pane.split") {
|
|
@@ -14390,28 +15015,28 @@ function environmentParams(input) {
|
|
|
14390
15015
|
}
|
|
14391
15016
|
|
|
14392
15017
|
// src/runtime-herdr/adapter.ts
|
|
14393
|
-
import { createHash as createHash4, randomUUID as
|
|
15018
|
+
import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
|
|
14394
15019
|
import { readFile as readFile7, stat as stat3 } from "node:fs/promises";
|
|
14395
15020
|
import { homedir as homedir3 } from "node:os";
|
|
14396
15021
|
import { join as join6 } from "node:path";
|
|
14397
15022
|
|
|
14398
15023
|
// src/runtime-herdr/subscription.ts
|
|
14399
|
-
import { randomUUID as
|
|
15024
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
14400
15025
|
import { createConnection as createConnection2 } from "node:net";
|
|
14401
15026
|
function openSubscription(options) {
|
|
14402
|
-
const id = `sub_${
|
|
15027
|
+
const id = `sub_${randomUUID6()}`;
|
|
14403
15028
|
const request = { id, method: "events.subscribe", params: { subscriptions: options.subscriptions } };
|
|
14404
15029
|
const maxLineBytes = options.maxLineBytes ?? 1024 * 1024;
|
|
14405
15030
|
let acknowledged = false;
|
|
14406
15031
|
let resolveStarted;
|
|
14407
15032
|
let rejectStarted;
|
|
14408
15033
|
let resolveClosed;
|
|
14409
|
-
const started = new Promise((
|
|
14410
|
-
resolveStarted =
|
|
15034
|
+
const started = new Promise((resolve6, reject) => {
|
|
15035
|
+
resolveStarted = resolve6;
|
|
14411
15036
|
rejectStarted = reject;
|
|
14412
15037
|
});
|
|
14413
|
-
const closed = new Promise((
|
|
14414
|
-
resolveClosed =
|
|
15038
|
+
const closed = new Promise((resolve6) => {
|
|
15039
|
+
resolveClosed = resolve6;
|
|
14415
15040
|
});
|
|
14416
15041
|
void started.catch(() => void 0);
|
|
14417
15042
|
if (options.validateRequest && !options.validateRequest(request)) {
|
|
@@ -14504,8 +15129,8 @@ var HerdrEventBridge = class {
|
|
|
14504
15129
|
constructor(host, options = {}) {
|
|
14505
15130
|
this.host = host;
|
|
14506
15131
|
this.log = options.log ?? (() => void 0);
|
|
14507
|
-
this.sleep = options.sleep ?? ((ms) => new Promise((
|
|
14508
|
-
const timer = setTimeout(
|
|
15132
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve6) => {
|
|
15133
|
+
const timer = setTimeout(resolve6, ms);
|
|
14509
15134
|
timer.unref?.();
|
|
14510
15135
|
}));
|
|
14511
15136
|
this.random = options.random ?? Math.random;
|
|
@@ -14624,8 +15249,8 @@ var HerdrEventBridge = class {
|
|
|
14624
15249
|
}
|
|
14625
15250
|
}
|
|
14626
15251
|
async pause(ms) {
|
|
14627
|
-
await Promise.race([this.sleep(ms), new Promise((
|
|
14628
|
-
this.wake =
|
|
15252
|
+
await Promise.race([this.sleep(ms), new Promise((resolve6) => {
|
|
15253
|
+
this.wake = resolve6;
|
|
14629
15254
|
})]);
|
|
14630
15255
|
this.wake = void 0;
|
|
14631
15256
|
}
|
|
@@ -14701,7 +15326,7 @@ function sameSet(a, b) {
|
|
|
14701
15326
|
}
|
|
14702
15327
|
|
|
14703
15328
|
// src/runtime-herdr/socket-client.ts
|
|
14704
|
-
import { randomUUID as
|
|
15329
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
14705
15330
|
import { createConnection as createConnection3 } from "node:net";
|
|
14706
15331
|
var HerdrSocketClient = class {
|
|
14707
15332
|
socketPath;
|
|
@@ -14734,7 +15359,7 @@ var HerdrSocketClient = class {
|
|
|
14734
15359
|
async request(method, params = {}) {
|
|
14735
15360
|
if (this.closed) throw this.unavailable("Herdr socket client is closed");
|
|
14736
15361
|
if (this.inflight >= this.maxPending) throw this.unavailable("Too many Herdr requests are in flight");
|
|
14737
|
-
const id =
|
|
15362
|
+
const id = randomUUID7();
|
|
14738
15363
|
const request = { id, method, params };
|
|
14739
15364
|
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.");
|
|
14740
15365
|
const line = Buffer.from(`${JSON.stringify(request)}
|
|
@@ -14748,7 +15373,7 @@ var HerdrSocketClient = class {
|
|
|
14748
15373
|
this.inflight -= 1;
|
|
14749
15374
|
throw error;
|
|
14750
15375
|
}
|
|
14751
|
-
return new Promise((
|
|
15376
|
+
return new Promise((resolve6, reject) => {
|
|
14752
15377
|
const timer = setTimeout(() => {
|
|
14753
15378
|
this.pending.delete(id);
|
|
14754
15379
|
this.inflight -= 1;
|
|
@@ -14756,7 +15381,7 @@ var HerdrSocketClient = class {
|
|
|
14756
15381
|
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."));
|
|
14757
15382
|
}, this.timeoutMs);
|
|
14758
15383
|
timer.unref?.();
|
|
14759
|
-
this.pending.set(id, { resolve:
|
|
15384
|
+
this.pending.set(id, { resolve: resolve6, reject, timer, method, socket });
|
|
14760
15385
|
socket.write(line, (error) => {
|
|
14761
15386
|
if (!error) return;
|
|
14762
15387
|
const pending = this.pending.get(id);
|
|
@@ -14772,13 +15397,13 @@ var HerdrSocketClient = class {
|
|
|
14772
15397
|
async close() {
|
|
14773
15398
|
this.closed = true;
|
|
14774
15399
|
this.failAll(this.unavailable("Herdr socket client closed"));
|
|
14775
|
-
await Promise.all([...this.sockets].map((socket) => new Promise((
|
|
14776
|
-
if (socket.destroyed)
|
|
14777
|
-
else socket.end(
|
|
15400
|
+
await Promise.all([...this.sockets].map((socket) => new Promise((resolve6) => {
|
|
15401
|
+
if (socket.destroyed) resolve6();
|
|
15402
|
+
else socket.end(resolve6);
|
|
14778
15403
|
})));
|
|
14779
15404
|
}
|
|
14780
15405
|
connect() {
|
|
14781
|
-
return new Promise((
|
|
15406
|
+
return new Promise((resolve6, reject) => {
|
|
14782
15407
|
const socket = createConnection3(this.socketPath);
|
|
14783
15408
|
const onError = () => {
|
|
14784
15409
|
socket.destroy();
|
|
@@ -14799,7 +15424,7 @@ var HerdrSocketClient = class {
|
|
|
14799
15424
|
this.buffers.delete(socket);
|
|
14800
15425
|
this.failSocket(socket, this.unavailable("Herdr closed the socket before replying"));
|
|
14801
15426
|
});
|
|
14802
|
-
|
|
15427
|
+
resolve6(socket);
|
|
14803
15428
|
});
|
|
14804
15429
|
});
|
|
14805
15430
|
}
|
|
@@ -15022,7 +15647,7 @@ var HerdrAdapter = class {
|
|
|
15022
15647
|
if (!isAgent(raw)) throw this.schemaMismatch("agent.list contained an invalid agent record");
|
|
15023
15648
|
const fingerprint = identityFingerprint(raw);
|
|
15024
15649
|
const previous = !reconnected ? previousTargets.find((item) => item.fingerprint === fingerprint) : void 0;
|
|
15025
|
-
const id = previous?.id ?? `herdr_${
|
|
15650
|
+
const id = previous?.id ?? `herdr_${randomUUID8()}`;
|
|
15026
15651
|
const live = { id, fingerprint, agent: raw };
|
|
15027
15652
|
next.set(raw.pane_id, live);
|
|
15028
15653
|
nextIds.add(id);
|
|
@@ -15135,7 +15760,7 @@ var HerdrAdapter = class {
|
|
|
15135
15760
|
async controlEnvironment(command) {
|
|
15136
15761
|
const params = environmentParams(command);
|
|
15137
15762
|
const { schema, client } = await this.initialize();
|
|
15138
|
-
const request = { id:
|
|
15763
|
+
const request = { id: randomUUID8(), method: command.action, params };
|
|
15139
15764
|
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.");
|
|
15140
15765
|
const result = asObject(await client.request(command.action, params));
|
|
15141
15766
|
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;
|
|
@@ -15192,12 +15817,12 @@ async function readLayout(client) {
|
|
|
15192
15817
|
]);
|
|
15193
15818
|
return { spaces, tabs };
|
|
15194
15819
|
}
|
|
15195
|
-
function layoutEntries(result, type,
|
|
15820
|
+
function layoutEntries(result, type, key2, idKey) {
|
|
15196
15821
|
const entries = /* @__PURE__ */ new Map();
|
|
15197
15822
|
if (!result || typeof result !== "object") return entries;
|
|
15198
15823
|
const value = result;
|
|
15199
|
-
if (value.type !== type || !Array.isArray(value[
|
|
15200
|
-
for (const item of value[
|
|
15824
|
+
if (value.type !== type || !Array.isArray(value[key2])) return entries;
|
|
15825
|
+
for (const item of value[key2]) {
|
|
15201
15826
|
if (!item || typeof item !== "object") continue;
|
|
15202
15827
|
const row = item;
|
|
15203
15828
|
if (typeof row[idKey] !== "string") continue;
|
|
@@ -15295,6 +15920,597 @@ async function readEndpointMarker(socketPath) {
|
|
|
15295
15920
|
}
|
|
15296
15921
|
}
|
|
15297
15922
|
|
|
15923
|
+
// src/runtime-herdr-core/adapter.ts
|
|
15924
|
+
import { createHash as createHash5, randomUUID as randomUUID9 } from "node:crypto";
|
|
15925
|
+
|
|
15926
|
+
// src/runtime-herdr-core/layout.ts
|
|
15927
|
+
var LAYOUT_DOC = "herdr-app";
|
|
15928
|
+
var BACKGROUND_SPACE_ID = "hc-background";
|
|
15929
|
+
var BACKGROUND_TAB_ID = "hc-background-tab";
|
|
15930
|
+
var BACKGROUND_SPACE_LABEL = "Background";
|
|
15931
|
+
var BACKGROUND_TAB_LABEL = "Not in a tab";
|
|
15932
|
+
var LOCAL_ADDRESS = /^t[0-9]{1,12}$/;
|
|
15933
|
+
var ID = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,255}$/;
|
|
15934
|
+
var MAX_NODES = 1e4;
|
|
15935
|
+
var emptyLayout = () => ({ spaces: [], byTerminal: /* @__PURE__ */ new Map() });
|
|
15936
|
+
function cleanLabel(value) {
|
|
15937
|
+
if (typeof value !== "string") return null;
|
|
15938
|
+
const label = value.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, 128);
|
|
15939
|
+
return label || null;
|
|
15940
|
+
}
|
|
15941
|
+
function folderName(folder) {
|
|
15942
|
+
if (typeof folder !== "string") return null;
|
|
15943
|
+
const parts = folder.split(/[\\/]/).filter(Boolean);
|
|
15944
|
+
return cleanLabel(parts[parts.length - 1]);
|
|
15945
|
+
}
|
|
15946
|
+
function addTerminal(content, found) {
|
|
15947
|
+
const terminal = content && typeof content === "object" ? content.terminal : void 0;
|
|
15948
|
+
if (typeof terminal === "string" && LOCAL_ADDRESS.test(terminal) && !found.includes(terminal)) found.push(terminal);
|
|
15949
|
+
}
|
|
15950
|
+
function terminalsIn(node, found, budget) {
|
|
15951
|
+
if (budget.left-- <= 0 || !node || typeof node !== "object" || Array.isArray(node)) return;
|
|
15952
|
+
const value = node;
|
|
15953
|
+
if (value.type === "block") addTerminal(value.content, found);
|
|
15954
|
+
if (Array.isArray(value.children)) for (const child of value.children) terminalsIn(child, found, budget);
|
|
15955
|
+
if (Array.isArray(value.floating)) {
|
|
15956
|
+
for (const float of value.floating) {
|
|
15957
|
+
if (!float || typeof float !== "object") continue;
|
|
15958
|
+
addTerminal(float.content, found);
|
|
15959
|
+
terminalsIn(float.pane, found, budget);
|
|
15960
|
+
}
|
|
15961
|
+
}
|
|
15962
|
+
}
|
|
15963
|
+
function parseLayout(value) {
|
|
15964
|
+
const layout = emptyLayout();
|
|
15965
|
+
if (!value || typeof value !== "object" || !Array.isArray(value.spaces)) return layout;
|
|
15966
|
+
const budget = { left: MAX_NODES };
|
|
15967
|
+
for (const raw of value.spaces) {
|
|
15968
|
+
if (!raw || typeof raw !== "object") continue;
|
|
15969
|
+
const row = raw;
|
|
15970
|
+
if (typeof row.id !== "string" || !ID.test(row.id) || row.id === BACKGROUND_SPACE_ID) continue;
|
|
15971
|
+
const space = { id: row.id, label: cleanLabel(row.name) ?? folderName(row.folder), number: layout.spaces.length + 1, tabs: [] };
|
|
15972
|
+
for (const rawTab of Array.isArray(row.tabs) ? row.tabs : []) {
|
|
15973
|
+
if (!rawTab || typeof rawTab !== "object") continue;
|
|
15974
|
+
const tabRow = rawTab;
|
|
15975
|
+
if (typeof tabRow.id !== "string" || !ID.test(tabRow.id)) continue;
|
|
15976
|
+
const terminals = [];
|
|
15977
|
+
terminalsIn(tabRow.root, terminals, budget);
|
|
15978
|
+
terminalsIn({ floating: tabRow.floating }, terminals, budget);
|
|
15979
|
+
const tab = { id: tabRow.id, spaceId: space.id, label: cleanLabel(tabRow.name), number: space.tabs.length + 1, terminals };
|
|
15980
|
+
space.tabs.push(tab);
|
|
15981
|
+
for (const address of terminals) if (!layout.byTerminal.has(address)) layout.byTerminal.set(address, { space, tab });
|
|
15982
|
+
}
|
|
15983
|
+
layout.spaces.push(space);
|
|
15984
|
+
}
|
|
15985
|
+
return layout;
|
|
15986
|
+
}
|
|
15987
|
+
|
|
15988
|
+
// src/runtime-herdr-core/rpc.ts
|
|
15989
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
15990
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
15991
|
+
import { homedir as homedir4 } from "node:os";
|
|
15992
|
+
import { join as join7 } from "node:path";
|
|
15993
|
+
import { createInterface } from "node:readline";
|
|
15994
|
+
var CoreRpcError = class extends Error {
|
|
15995
|
+
constructor(kind, message, hint) {
|
|
15996
|
+
super(message);
|
|
15997
|
+
this.kind = kind;
|
|
15998
|
+
this.hint = hint;
|
|
15999
|
+
this.name = "CoreRpcError";
|
|
16000
|
+
}
|
|
16001
|
+
kind;
|
|
16002
|
+
hint;
|
|
16003
|
+
};
|
|
16004
|
+
var MAX_LINE_BYTES = 8 * 1024 * 1024;
|
|
16005
|
+
function resolveCoreBinary(explicit, env = process.env) {
|
|
16006
|
+
if (explicit) return explicit;
|
|
16007
|
+
if (env.HC_BIN) return env.HC_BIN;
|
|
16008
|
+
const fallback = process.platform === "win32" ? join7(env.LOCALAPPDATA ?? join7(homedir4(), "AppData", "Local"), "Programs", "herdr-core", "hc.exe") : join7(homedir4(), ".local", "bin", "hc");
|
|
16009
|
+
const onPath = (env.PATH ?? env.Path ?? "").split(process.platform === "win32" ? ";" : ":").some((dir) => dir && (existsSync2(join7(dir, "hc")) || existsSync2(join7(dir, "hc.exe"))));
|
|
16010
|
+
return !onPath && existsSync2(fallback) ? fallback : "hc";
|
|
16011
|
+
}
|
|
16012
|
+
function spawnCoreStream(binary) {
|
|
16013
|
+
return () => {
|
|
16014
|
+
const child = spawn2(binary, ["connect"], { stdio: ["pipe", "pipe", "ignore"], windowsHide: true, shell: false });
|
|
16015
|
+
const closed = new Promise((resolve6) => {
|
|
16016
|
+
child.once("error", (error) => resolve6(error));
|
|
16017
|
+
child.once("exit", () => resolve6(void 0));
|
|
16018
|
+
});
|
|
16019
|
+
child.stdin.on("error", () => void 0);
|
|
16020
|
+
return { input: child.stdin, output: child.stdout, closed, close: () => {
|
|
16021
|
+
child.kill();
|
|
16022
|
+
} };
|
|
16023
|
+
};
|
|
16024
|
+
}
|
|
16025
|
+
var CoreConnection = class {
|
|
16026
|
+
constructor(stream, onNotification) {
|
|
16027
|
+
this.stream = stream;
|
|
16028
|
+
this.onNotification = onNotification;
|
|
16029
|
+
const lines = createInterface({ input: stream.output, crlfDelay: Infinity });
|
|
16030
|
+
lines.on("line", (line) => this.receive(line));
|
|
16031
|
+
this.done = stream.closed.then((error) => {
|
|
16032
|
+
this.open = false;
|
|
16033
|
+
lines.close();
|
|
16034
|
+
const reason = error && error.code === "ENOENT" ? new ConnectError("runtime_unavailable", "herdr-core (hc) was not found.", "Install herdr-core (https://github.com/herdrdev/herdr-core) or set herdrCore.binary in connector.json.") : new ConnectError("runtime_unavailable", "The herdr-core connection closed.", "Check that herdr-core is running (`hc server status`), then retry.");
|
|
16035
|
+
this.closeReason = reason;
|
|
16036
|
+
for (const [id, request] of this.pending) {
|
|
16037
|
+
clearTimeout(request.timer);
|
|
16038
|
+
this.pending.delete(id);
|
|
16039
|
+
request.reject(request.method === "terminal.send" ? new ConnectError("delivery_unknown", "herdr-core closed before confirming the message.", "Read the agent output before deciding whether to send it again.") : reason);
|
|
16040
|
+
}
|
|
16041
|
+
});
|
|
16042
|
+
}
|
|
16043
|
+
stream;
|
|
16044
|
+
onNotification;
|
|
16045
|
+
pending = /* @__PURE__ */ new Map();
|
|
16046
|
+
nextId = 1;
|
|
16047
|
+
open = true;
|
|
16048
|
+
done;
|
|
16049
|
+
closeReason;
|
|
16050
|
+
get isOpen() {
|
|
16051
|
+
return this.open;
|
|
16052
|
+
}
|
|
16053
|
+
request(method, params, timeoutMs) {
|
|
16054
|
+
if (!this.open) return Promise.reject(this.closeReason ?? new ConnectError("runtime_unavailable", "The herdr-core connection is closed.", "Retry once herdr-core is running."));
|
|
16055
|
+
const id = this.nextId++;
|
|
16056
|
+
return new Promise((resolve6, reject) => {
|
|
16057
|
+
const timer = setTimeout(() => {
|
|
16058
|
+
if (!this.pending.delete(id)) return;
|
|
16059
|
+
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."));
|
|
16060
|
+
}, timeoutMs);
|
|
16061
|
+
timer.unref?.();
|
|
16062
|
+
this.pending.set(id, { resolve: resolve6, reject, timer, method });
|
|
16063
|
+
this.stream.input.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
|
|
16064
|
+
`);
|
|
16065
|
+
});
|
|
16066
|
+
}
|
|
16067
|
+
close() {
|
|
16068
|
+
this.stream.close();
|
|
16069
|
+
}
|
|
16070
|
+
receive(line) {
|
|
16071
|
+
if (!line.trim()) return;
|
|
16072
|
+
if (Buffer.byteLength(line, "utf8") > MAX_LINE_BYTES) {
|
|
16073
|
+
this.close();
|
|
16074
|
+
return;
|
|
16075
|
+
}
|
|
16076
|
+
let message;
|
|
16077
|
+
try {
|
|
16078
|
+
const parsed = JSON.parse(line);
|
|
16079
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
|
|
16080
|
+
message = parsed;
|
|
16081
|
+
} catch {
|
|
16082
|
+
return;
|
|
16083
|
+
}
|
|
16084
|
+
if (typeof message.id === "number") {
|
|
16085
|
+
const request = this.pending.get(message.id);
|
|
16086
|
+
if (!request) return;
|
|
16087
|
+
this.pending.delete(message.id);
|
|
16088
|
+
clearTimeout(request.timer);
|
|
16089
|
+
if (message.error && typeof message.error === "object") {
|
|
16090
|
+
const error = message.error;
|
|
16091
|
+
request.reject(new CoreRpcError(
|
|
16092
|
+
typeof error.data?.kind === "string" ? error.data.kind : "error",
|
|
16093
|
+
typeof error.message === "string" ? error.message : "herdr-core error",
|
|
16094
|
+
typeof error.data?.hint === "string" ? error.data.hint : void 0
|
|
16095
|
+
));
|
|
16096
|
+
} else request.resolve(message.result);
|
|
16097
|
+
return;
|
|
16098
|
+
}
|
|
16099
|
+
if (typeof message.method === "string" && this.onNotification) {
|
|
16100
|
+
const params = message.params && typeof message.params === "object" && !Array.isArray(message.params) ? message.params : {};
|
|
16101
|
+
this.onNotification({ method: message.method, params });
|
|
16102
|
+
}
|
|
16103
|
+
}
|
|
16104
|
+
};
|
|
16105
|
+
var CoreRpcClient = class {
|
|
16106
|
+
constructor(factory, timeoutMs = 1e4) {
|
|
16107
|
+
this.factory = factory;
|
|
16108
|
+
this.timeoutMs = timeoutMs;
|
|
16109
|
+
}
|
|
16110
|
+
factory;
|
|
16111
|
+
timeoutMs;
|
|
16112
|
+
connection;
|
|
16113
|
+
closed = false;
|
|
16114
|
+
async request(method, params = {}, timeoutMs = this.timeoutMs) {
|
|
16115
|
+
if (this.closed) throw new ConnectError("runtime_unavailable", "The herdr-core client is closed.", "Restart the relay.");
|
|
16116
|
+
if (!this.connection?.isOpen) this.connection = new CoreConnection(this.factory());
|
|
16117
|
+
return this.connection.request(method, params, timeoutMs);
|
|
16118
|
+
}
|
|
16119
|
+
async close() {
|
|
16120
|
+
this.closed = true;
|
|
16121
|
+
const connection = this.connection;
|
|
16122
|
+
this.connection = void 0;
|
|
16123
|
+
if (connection?.isOpen) {
|
|
16124
|
+
connection.close();
|
|
16125
|
+
await connection.done;
|
|
16126
|
+
}
|
|
16127
|
+
}
|
|
16128
|
+
};
|
|
16129
|
+
|
|
16130
|
+
// src/runtime-herdr-core/adapter.ts
|
|
16131
|
+
var LOCAL_ADDRESS2 = /^t[0-9]{1,12}$/;
|
|
16132
|
+
var PROTOCOL_GENERATION = 1;
|
|
16133
|
+
var REQUIRED_METHODS = ["terminal.list", "terminal.get", "terminal.read", "terminal.send", "events.subscribe", "doc.get"];
|
|
16134
|
+
var LIST_EVENTS = /* @__PURE__ */ new Set(["created", "lost", "restarted", "finished", "removed"]);
|
|
16135
|
+
var SEND_TIMEOUT_MS = 9e4;
|
|
16136
|
+
var APP_KINDS = { "claude-code": "claude", "cursor-agent": "cursor", "github-copilot": "copilot", "grok-build": "grok" };
|
|
16137
|
+
var HerdrCoreAdapter = class {
|
|
16138
|
+
constructor(options = {}) {
|
|
16139
|
+
this.options = options;
|
|
16140
|
+
this.factory = options.streamFactory ?? spawnCoreStream(resolveCoreBinary(options.binary));
|
|
16141
|
+
this.timeoutMs = options.timeoutMs ?? 1e4;
|
|
16142
|
+
this.client = new CoreRpcClient(this.factory, this.timeoutMs);
|
|
16143
|
+
this.machineId = options.machineId ?? createHash5("sha256").update(`${process.platform}:${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "local"}`).digest("hex").slice(0, 24);
|
|
16144
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve6) => {
|
|
16145
|
+
const timer = setTimeout(resolve6, ms);
|
|
16146
|
+
timer.unref?.();
|
|
16147
|
+
this.wake = () => {
|
|
16148
|
+
clearTimeout(timer);
|
|
16149
|
+
resolve6();
|
|
16150
|
+
};
|
|
16151
|
+
}));
|
|
16152
|
+
this.settleMs = options.settleMs ?? 150;
|
|
16153
|
+
}
|
|
16154
|
+
options;
|
|
16155
|
+
client;
|
|
16156
|
+
factory;
|
|
16157
|
+
machineId;
|
|
16158
|
+
timeoutMs;
|
|
16159
|
+
ready;
|
|
16160
|
+
coreId;
|
|
16161
|
+
current = /* @__PURE__ */ new Map();
|
|
16162
|
+
records = /* @__PURE__ */ new Map();
|
|
16163
|
+
retired = /* @__PURE__ */ new Set();
|
|
16164
|
+
layout = emptyLayout();
|
|
16165
|
+
terminals = [];
|
|
16166
|
+
refreshing;
|
|
16167
|
+
listed = false;
|
|
16168
|
+
listeners = /* @__PURE__ */ new Set();
|
|
16169
|
+
watching;
|
|
16170
|
+
stopped = false;
|
|
16171
|
+
stream;
|
|
16172
|
+
refreshTimer;
|
|
16173
|
+
wake;
|
|
16174
|
+
sleep;
|
|
16175
|
+
settleMs;
|
|
16176
|
+
getCapabilities() {
|
|
16177
|
+
return { readOutput: true, sendMessage: true, reason: "Messages go to the agent's terminal address, which herdr-core never reuses. PeerBand checks that the same program still runs there right before sending." };
|
|
16178
|
+
}
|
|
16179
|
+
async listAgents() {
|
|
16180
|
+
if (!this.refreshing) this.refreshing = this.refreshAgents().finally(() => {
|
|
16181
|
+
this.refreshing = void 0;
|
|
16182
|
+
});
|
|
16183
|
+
return this.refreshing;
|
|
16184
|
+
}
|
|
16185
|
+
async refreshAgents() {
|
|
16186
|
+
const coreId = await this.initialize();
|
|
16187
|
+
const [listed, layout] = await Promise.all([
|
|
16188
|
+
this.call("terminal.list", {}),
|
|
16189
|
+
this.call("doc.get", { name: LAYOUT_DOC }).then((result) => parseLayout(result?.value), () => emptyLayout())
|
|
16190
|
+
]);
|
|
16191
|
+
const terminals = listed?.terminals;
|
|
16192
|
+
if (!Array.isArray(terminals)) throw schemaMismatch2("terminal.list returned no terminal list");
|
|
16193
|
+
const reconnected = this.coreId !== void 0 && this.coreId !== coreId;
|
|
16194
|
+
this.coreId = coreId;
|
|
16195
|
+
const previous = new Map([...this.current.values()].map((live) => [live.fingerprint, live]));
|
|
16196
|
+
const previousRecords = this.records;
|
|
16197
|
+
const next = /* @__PURE__ */ new Map();
|
|
16198
|
+
const records = [];
|
|
16199
|
+
this.terminals = terminals.filter(isTerminal).filter((terminal) => LOCAL_ADDRESS2.test(terminal.address) && terminal.state === "live");
|
|
16200
|
+
for (const terminal of this.terminals) {
|
|
16201
|
+
if (!isAgent2(terminal)) continue;
|
|
16202
|
+
const fingerprint = identityFingerprint2(coreId, terminal);
|
|
16203
|
+
const id = (!reconnected ? previous.get(fingerprint)?.id : void 0) ?? `hc_${randomUUID9()}`;
|
|
16204
|
+
const live = { id, fingerprint, terminal };
|
|
16205
|
+
next.set(terminal.address, live);
|
|
16206
|
+
records.push(toRecord2(live, this.machineId, layout));
|
|
16207
|
+
}
|
|
16208
|
+
const ids = new Set(records.map((record) => record.id));
|
|
16209
|
+
for (const live of this.current.values()) if (!ids.has(live.id)) this.retired.add(live.id);
|
|
16210
|
+
const idsChanged = this.listed && (ids.size !== previousRecords.size || [...previousRecords.keys()].some((id) => !ids.has(id)));
|
|
16211
|
+
const layoutChanged = this.listed && records.some((record) => {
|
|
16212
|
+
const before = previousRecords.get(record.id);
|
|
16213
|
+
return before !== void 0 && (JSON.stringify(before.location) !== JSON.stringify(record.location) || before.label !== record.label);
|
|
16214
|
+
});
|
|
16215
|
+
this.current = next;
|
|
16216
|
+
this.layout = layout;
|
|
16217
|
+
this.records = new Map(records.map((record) => [record.id, record]));
|
|
16218
|
+
const firstList = !this.listed;
|
|
16219
|
+
this.listed = true;
|
|
16220
|
+
if (!firstList) {
|
|
16221
|
+
for (const record of records) {
|
|
16222
|
+
const before = previousRecords.get(record.id);
|
|
16223
|
+
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 });
|
|
16224
|
+
}
|
|
16225
|
+
if (idsChanged || layoutChanged) this.emit({ kind: "agents_changed" });
|
|
16226
|
+
}
|
|
16227
|
+
return records;
|
|
16228
|
+
}
|
|
16229
|
+
async getAgent(id) {
|
|
16230
|
+
const agents = await this.listAgents();
|
|
16231
|
+
const record = agents.find((agent) => agent.id === id);
|
|
16232
|
+
if (record) return record;
|
|
16233
|
+
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.");
|
|
16234
|
+
throw new ConnectError("agent_not_found", "No herdr-core agent has that identifier.", "List agents and use a current agent identifier.");
|
|
16235
|
+
}
|
|
16236
|
+
/** The agent id for a core terminal address such as $HC_TERMINAL_ID, after a fresh list. */
|
|
16237
|
+
async agentIdForPane(paneId) {
|
|
16238
|
+
await this.listAgents();
|
|
16239
|
+
return this.current.get(paneId)?.id;
|
|
16240
|
+
}
|
|
16241
|
+
async readOutput(id, options = {}) {
|
|
16242
|
+
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.");
|
|
16243
|
+
await this.getAgent(id);
|
|
16244
|
+
const live = this.liveById(id);
|
|
16245
|
+
const result = await this.read(live.terminal.address, options);
|
|
16246
|
+
await this.getAgent(id);
|
|
16247
|
+
return result;
|
|
16248
|
+
}
|
|
16249
|
+
async readPane(paneId, options = {}) {
|
|
16250
|
+
await this.listAgents();
|
|
16251
|
+
if (!LOCAL_ADDRESS2.test(paneId) || !this.terminals.some((terminal) => terminal.address === paneId)) {
|
|
16252
|
+
throw new ConnectError("agent_not_found", "No live herdr-core terminal has that id.", "Refresh the environment and pick a current pane.");
|
|
16253
|
+
}
|
|
16254
|
+
return this.read(paneId, options);
|
|
16255
|
+
}
|
|
16256
|
+
async read(address, options) {
|
|
16257
|
+
const lines = clampInteger2(options.lines, 80, 1, 500);
|
|
16258
|
+
const result = await this.call("terminal.read", { terminal: address, lines });
|
|
16259
|
+
if (!result || typeof result.text !== "string") throw schemaMismatch2("terminal.read returned no text");
|
|
16260
|
+
const text2 = result.text.replace(/(?:[ \t]*\r?\n)+[ \t]*$/, "");
|
|
16261
|
+
const output = sanitizeOutput(text2, { ...options, lines, bytes: clampInteger2(options.bytes, 16384, 1, 32768) });
|
|
16262
|
+
const visibleOnly = result.how === "screen" && typeof result.why === "string";
|
|
16263
|
+
return { ...output, ...visibleOnly ? { source: "visible" } : {}, truncated: visibleOnly || output.truncated || result.complete === false, observedAt: (/* @__PURE__ */ new Date()).toISOString(), untrusted: true };
|
|
16264
|
+
}
|
|
16265
|
+
async sendMessage(id, message) {
|
|
16266
|
+
if (typeof message !== "string" || message.length === 0 || Buffer.byteLength(message, "utf8") > 16384) {
|
|
16267
|
+
throw new ConnectError("invalid_argument", "Message must contain 1 to 16384 UTF-8 bytes.", "Shorten the message and try again.");
|
|
16268
|
+
}
|
|
16269
|
+
await this.getAgent(id);
|
|
16270
|
+
const live = this.liveById(id);
|
|
16271
|
+
if (live.terminal.status?.state === "blocked" || live.terminal.status?.state === "error") {
|
|
16272
|
+
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.");
|
|
16273
|
+
}
|
|
16274
|
+
const now2 = await this.call("terminal.get", { terminal: live.terminal.address });
|
|
16275
|
+
if (!isTerminal(now2) || now2.state !== "live" || identityFingerprint2(this.coreId, now2) !== live.fingerprint) {
|
|
16276
|
+
this.retired.add(id);
|
|
16277
|
+
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.");
|
|
16278
|
+
}
|
|
16279
|
+
const result = await this.call("terminal.send", { terminal: live.terminal.address, text: message }, SEND_TIMEOUT_MS);
|
|
16280
|
+
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.");
|
|
16281
|
+
}
|
|
16282
|
+
/** The layout as the dashboard shows it. Read only: herdr-core spaces and tabs belong to the desktop app. */
|
|
16283
|
+
async listEnvironment() {
|
|
16284
|
+
const agents = await this.listAgents();
|
|
16285
|
+
const byAddress = new Map([...this.current.values()].map((live) => [live.terminal.address, this.records.get(live.id)]));
|
|
16286
|
+
const terminals = new Map(this.terminals.map((terminal) => [terminal.address, terminal]));
|
|
16287
|
+
const workspaces = [];
|
|
16288
|
+
const tabs = [];
|
|
16289
|
+
const panes = [];
|
|
16290
|
+
const pane = (address, tabId, workspaceId) => {
|
|
16291
|
+
const terminal = terminals.get(address);
|
|
16292
|
+
if (!terminal) return;
|
|
16293
|
+
const agent = byAddress.get(address);
|
|
16294
|
+
const cwd = cleanText(terminal.foreground?.cwd ?? terminal.cwd, 2048);
|
|
16295
|
+
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 } });
|
|
16296
|
+
};
|
|
16297
|
+
for (const space of this.layout.spaces) {
|
|
16298
|
+
workspaces.push({ workspaceId: space.id, ...space.label ? { label: space.label } : {}, number: space.number, tabCount: space.tabs.length });
|
|
16299
|
+
for (const tab of space.tabs) {
|
|
16300
|
+
const shown = tab.terminals.filter((address) => terminals.has(address));
|
|
16301
|
+
tabs.push({ tabId: tab.id, workspaceId: space.id, ...tab.label ? { label: tab.label } : {}, number: tab.number, paneCount: shown.length });
|
|
16302
|
+
for (const address of shown) pane(address, tab.id, space.id);
|
|
16303
|
+
}
|
|
16304
|
+
}
|
|
16305
|
+
const background = agents.filter((agent) => agent.location?.space.id === BACKGROUND_SPACE_ID);
|
|
16306
|
+
if (background.length) {
|
|
16307
|
+
workspaces.push({ workspaceId: BACKGROUND_SPACE_ID, label: BACKGROUND_SPACE_LABEL, number: this.layout.spaces.length + 1, tabCount: 1 });
|
|
16308
|
+
tabs.push({ tabId: BACKGROUND_TAB_ID, workspaceId: BACKGROUND_SPACE_ID, label: BACKGROUND_TAB_LABEL, number: 1, paneCount: background.length });
|
|
16309
|
+
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);
|
|
16310
|
+
}
|
|
16311
|
+
const result = { actions: [], runtime: "herdr-core" };
|
|
16312
|
+
for (const [key2, rows] of [["workspaces", workspaces], ["tabs", tabs], ["panes", panes]]) {
|
|
16313
|
+
result[key2] = rows.slice(0, 50);
|
|
16314
|
+
result[`${key2}Truncated`] = rows.length > 50;
|
|
16315
|
+
}
|
|
16316
|
+
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.");
|
|
16317
|
+
return result;
|
|
16318
|
+
}
|
|
16319
|
+
async controlEnvironment() {
|
|
16320
|
+
throw new ConnectError("unsupported_capability", "Changing spaces, tabs and panes is not available for herdr-core yet.", "Arrange them in the Herdr desktop app.");
|
|
16321
|
+
}
|
|
16322
|
+
/** Status and list-change events from core's events.subscribe (metadata only, never terminal text). */
|
|
16323
|
+
onEvent(listener, log) {
|
|
16324
|
+
this.listeners.add(listener);
|
|
16325
|
+
if (!this.watching) {
|
|
16326
|
+
this.stopped = false;
|
|
16327
|
+
this.watching = this.watch(log ?? (() => void 0));
|
|
16328
|
+
}
|
|
16329
|
+
return () => {
|
|
16330
|
+
this.listeners.delete(listener);
|
|
16331
|
+
};
|
|
16332
|
+
}
|
|
16333
|
+
async close() {
|
|
16334
|
+
this.stopped = true;
|
|
16335
|
+
clearTimeout(this.refreshTimer);
|
|
16336
|
+
this.stream?.close();
|
|
16337
|
+
this.wake?.();
|
|
16338
|
+
await this.watching?.catch(() => void 0);
|
|
16339
|
+
await this.client.close();
|
|
16340
|
+
}
|
|
16341
|
+
async watch(log) {
|
|
16342
|
+
let delay = 1e3;
|
|
16343
|
+
let announced = false;
|
|
16344
|
+
while (!this.stopped) {
|
|
16345
|
+
const connection = new CoreConnection(this.factory(), (message) => this.onNotification(message));
|
|
16346
|
+
this.stream = connection;
|
|
16347
|
+
const startedAt = Date.now();
|
|
16348
|
+
try {
|
|
16349
|
+
await connection.request("events.subscribe", {}, this.timeoutMs);
|
|
16350
|
+
if (!announced) {
|
|
16351
|
+
log("Watching herdr-core for agent status changes.");
|
|
16352
|
+
announced = true;
|
|
16353
|
+
}
|
|
16354
|
+
this.scheduleRefresh(0);
|
|
16355
|
+
await connection.done;
|
|
16356
|
+
} catch {
|
|
16357
|
+
connection.close();
|
|
16358
|
+
await connection.done;
|
|
16359
|
+
}
|
|
16360
|
+
if (this.stopped) break;
|
|
16361
|
+
if (Date.now() - startedAt > 6e4) delay = 1e3;
|
|
16362
|
+
log("herdr-core event stream closed; reconnecting.");
|
|
16363
|
+
await this.sleep(delay);
|
|
16364
|
+
delay = Math.min(delay * 2, 3e4);
|
|
16365
|
+
}
|
|
16366
|
+
}
|
|
16367
|
+
onNotification(message) {
|
|
16368
|
+
if (message.method === "missed") {
|
|
16369
|
+
this.scheduleRefresh();
|
|
16370
|
+
return;
|
|
16371
|
+
}
|
|
16372
|
+
if (message.method !== "event") return;
|
|
16373
|
+
const { type, terminal, data, seq } = message.params;
|
|
16374
|
+
if (type === "doc") {
|
|
16375
|
+
const doc = data;
|
|
16376
|
+
if (doc?.name === LAYOUT_DOC && message.params.machine === void 0) this.scheduleRefresh();
|
|
16377
|
+
return;
|
|
16378
|
+
}
|
|
16379
|
+
if (typeof terminal !== "string" || !LOCAL_ADDRESS2.test(terminal)) return;
|
|
16380
|
+
if (typeof type === "string" && LIST_EVENTS.has(type)) {
|
|
16381
|
+
this.scheduleRefresh();
|
|
16382
|
+
return;
|
|
16383
|
+
}
|
|
16384
|
+
if (type !== "status") return;
|
|
16385
|
+
const reported = data?.status ?? null;
|
|
16386
|
+
const live = this.current.get(terminal);
|
|
16387
|
+
if (!live || !reported || typeof reported.state !== "string") {
|
|
16388
|
+
this.scheduleRefresh();
|
|
16389
|
+
return;
|
|
16390
|
+
}
|
|
16391
|
+
const record = this.records.get(live.id);
|
|
16392
|
+
if (!record) return;
|
|
16393
|
+
const status = toStatus(reported.state);
|
|
16394
|
+
live.terminal = { ...live.terminal, status: reported };
|
|
16395
|
+
if (record.status === status && record.rawStatus === reported.state) return;
|
|
16396
|
+
const previousStatus = record.status;
|
|
16397
|
+
this.records.set(record.id, { ...record, status, rawStatus: reported.state, observedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
16398
|
+
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 });
|
|
16399
|
+
}
|
|
16400
|
+
scheduleRefresh(delay = this.settleMs) {
|
|
16401
|
+
if (this.stopped || this.refreshTimer) return;
|
|
16402
|
+
this.refreshTimer = setTimeout(() => {
|
|
16403
|
+
this.refreshTimer = void 0;
|
|
16404
|
+
void this.listAgents().catch(() => void 0);
|
|
16405
|
+
}, delay);
|
|
16406
|
+
this.refreshTimer.unref?.();
|
|
16407
|
+
}
|
|
16408
|
+
emit(event) {
|
|
16409
|
+
for (const listener of [...this.listeners]) listener(event);
|
|
16410
|
+
}
|
|
16411
|
+
liveById(id) {
|
|
16412
|
+
const live = [...this.current.values()].find((item) => item.id === id);
|
|
16413
|
+
if (!live) throw new ConnectError("stale_target", "This agent handle is no longer current.", "Refresh the agent list and select its current occupant.");
|
|
16414
|
+
return live;
|
|
16415
|
+
}
|
|
16416
|
+
initialize() {
|
|
16417
|
+
if (!this.ready) {
|
|
16418
|
+
const pending = (async () => {
|
|
16419
|
+
const hello = await this.call("hello", {});
|
|
16420
|
+
if (!hello || hello.generation !== PROTOCOL_GENERATION) throw new ConnectError("schema_mismatch", "This herdr-core speaks a protocol generation PeerBand does not support.", "Update PeerBand (`peerband update`) and herdr-core (`hc update`).");
|
|
16421
|
+
const methods = Array.isArray(hello.methods) ? hello.methods : [];
|
|
16422
|
+
const missing = REQUIRED_METHODS.filter((method) => !methods.includes(method));
|
|
16423
|
+
if (missing.length) throw new ConnectError("schema_mismatch", `This herdr-core lacks ${missing.join(", ")}.`, "Update herdr-core with `hc update`.");
|
|
16424
|
+
return typeof hello.core?.id === "string" ? hello.core.id : "core";
|
|
16425
|
+
})();
|
|
16426
|
+
this.ready = pending;
|
|
16427
|
+
void pending.catch(() => {
|
|
16428
|
+
if (this.ready === pending) this.ready = void 0;
|
|
16429
|
+
});
|
|
16430
|
+
}
|
|
16431
|
+
return this.ready.then(async (id) => {
|
|
16432
|
+
if (this.coreId === void 0) return id;
|
|
16433
|
+
const status = await this.call("server.status", {}).catch(() => void 0);
|
|
16434
|
+
return typeof status?.core?.id === "string" ? status.core.id : id;
|
|
16435
|
+
});
|
|
16436
|
+
}
|
|
16437
|
+
async call(method, params, timeoutMs) {
|
|
16438
|
+
try {
|
|
16439
|
+
return await this.client.request(method, params, timeoutMs);
|
|
16440
|
+
} catch (error) {
|
|
16441
|
+
throw mapError(error, method);
|
|
16442
|
+
}
|
|
16443
|
+
}
|
|
16444
|
+
};
|
|
16445
|
+
function mapError(error, method) {
|
|
16446
|
+
if (!(error instanceof CoreRpcError)) return error;
|
|
16447
|
+
switch (error.kind) {
|
|
16448
|
+
case "not_found":
|
|
16449
|
+
case "finished":
|
|
16450
|
+
return new ConnectError("stale_target", "That terminal is no longer running in herdr-core.", "Refresh the agent list and select its current occupant.");
|
|
16451
|
+
case "blocked":
|
|
16452
|
+
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.");
|
|
16453
|
+
case "invalid_params":
|
|
16454
|
+
return new ConnectError("schema_mismatch", `herdr-core rejected ${method}.`, "Update PeerBand and herdr-core.");
|
|
16455
|
+
case "unavailable":
|
|
16456
|
+
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.");
|
|
16457
|
+
default:
|
|
16458
|
+
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.");
|
|
16459
|
+
}
|
|
16460
|
+
}
|
|
16461
|
+
function schemaMismatch2(message) {
|
|
16462
|
+
return new ConnectError("schema_mismatch", `herdr-core response did not match the expected API: ${message}`, "Update PeerBand and herdr-core.");
|
|
16463
|
+
}
|
|
16464
|
+
function isTerminal(value) {
|
|
16465
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && typeof value.address === "string";
|
|
16466
|
+
}
|
|
16467
|
+
function isAgent2(terminal) {
|
|
16468
|
+
return typeof terminal.pid === "number" && Boolean(terminal.status) && typeof terminal.status?.state === "string";
|
|
16469
|
+
}
|
|
16470
|
+
function toStatus(word) {
|
|
16471
|
+
if (word === "idle" || word === "working" || word === "blocked" || word === "done") return word;
|
|
16472
|
+
return word === "error" ? "blocked" : "unknown";
|
|
16473
|
+
}
|
|
16474
|
+
function identityFingerprint2(coreId, terminal) {
|
|
16475
|
+
return createHash5("sha256").update([coreId, terminal.address, String(terminal.created_ms ?? ""), String(terminal.pid ?? "")].join("\0")).digest("hex");
|
|
16476
|
+
}
|
|
16477
|
+
function cleanText(value, max) {
|
|
16478
|
+
if (typeof value !== "string") return void 0;
|
|
16479
|
+
return sanitizeOutput(value, { bytes: max, lines: 1 }).text || void 0;
|
|
16480
|
+
}
|
|
16481
|
+
function programName(value) {
|
|
16482
|
+
if (!value) return void 0;
|
|
16483
|
+
const base = value.split(/[\\/]/).pop() ?? value;
|
|
16484
|
+
return base.replace(/\.(exe|cmd|bat)$/i, "") || void 0;
|
|
16485
|
+
}
|
|
16486
|
+
function toRecord2(live, machineId, layout) {
|
|
16487
|
+
const { terminal } = live;
|
|
16488
|
+
const app = cleanLabel(terminal.status?.app) ?? void 0;
|
|
16489
|
+
const agentType = (app ? APP_KINDS[app] ?? app : void 0) ?? programName(terminal.argv?.[0]) ?? "unknown";
|
|
16490
|
+
const label = cleanLabel(terminal.name) ?? app ?? cleanLabel(programName(terminal.foreground?.name)) ?? terminal.address;
|
|
16491
|
+
const rawStatus = terminal.status?.state ?? "unknown";
|
|
16492
|
+
const place = layout.byTerminal.get(terminal.address);
|
|
16493
|
+
return {
|
|
16494
|
+
id: live.id,
|
|
16495
|
+
machineId,
|
|
16496
|
+
runtime: "herdr-core",
|
|
16497
|
+
agentType,
|
|
16498
|
+
label,
|
|
16499
|
+
workspace: cleanText(terminal.foreground?.cwd ?? terminal.cwd, 2048) ?? terminal.address,
|
|
16500
|
+
status: toStatus(rawStatus),
|
|
16501
|
+
rawStatus,
|
|
16502
|
+
observedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
16503
|
+
stale: false,
|
|
16504
|
+
capabilities: { readOutput: true, sendMessage: true },
|
|
16505
|
+
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 } }
|
|
16506
|
+
};
|
|
16507
|
+
}
|
|
16508
|
+
function clampInteger2(value, fallback, min, max) {
|
|
16509
|
+
if (value === void 0) return fallback;
|
|
16510
|
+
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.");
|
|
16511
|
+
return value;
|
|
16512
|
+
}
|
|
16513
|
+
|
|
15298
16514
|
// src/cli/commands/connect.ts
|
|
15299
16515
|
function clock(date = /* @__PURE__ */ new Date()) {
|
|
15300
16516
|
return date.toTimeString().slice(0, 8);
|
|
@@ -15331,10 +16547,10 @@ function activityLine(s, activity, at = /* @__PURE__ */ new Date()) {
|
|
|
15331
16547
|
var spec2 = {
|
|
15332
16548
|
name: "connect",
|
|
15333
16549
|
summary: "Run the connector in the foreground",
|
|
15334
|
-
usage: "peerband connect [--runtime herdr|mock] [--read-only] [--config PATH] [--server URL]",
|
|
15335
|
-
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.',
|
|
16550
|
+
usage: "peerband connect [--runtime herdr|herdr-core|mock] [--read-only] [--config PATH] [--server URL]",
|
|
16551
|
+
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.',
|
|
15336
16552
|
options: [
|
|
15337
|
-
{ name: "runtime", type: "string", valueName: "herdr|mock", description: 'Agent runtime
|
|
16553
|
+
{ name: "runtime", type: "string", valueName: "herdr|herdr-core|mock", description: 'Agent runtime: "herdr" (the Herdr terminal app), "herdr-core" (hc, also behind the Herdr desktop app) or "mock" (fake agents for testing). Default: $PEERBAND_RUNTIME, then "runtime" in connector.json, then herdr.' },
|
|
15338
16554
|
{ 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.' },
|
|
15339
16555
|
{ name: "enable-environment-control", type: "boolean", description: "Redundant: environment controls are on by default. Kept so old scripts keep working." },
|
|
15340
16556
|
{ 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).' },
|
|
@@ -15346,6 +16562,7 @@ var spec2 = {
|
|
|
15346
16562
|
examples: [
|
|
15347
16563
|
["peerband connect", "Serve until Ctrl+C; messages to agents are allowed (with OAuth consent)"],
|
|
15348
16564
|
["peerband connect --read-only", "Never let MCP clients send messages to agents from this machine"],
|
|
16565
|
+
["peerband connect --runtime herdr-core", "Serve the agents in herdr-core (hc) and the Herdr desktop app"],
|
|
15349
16566
|
["peerband connect --runtime mock", "Try the connection with fake agents"]
|
|
15350
16567
|
],
|
|
15351
16568
|
async run(parsed, ctx) {
|
|
@@ -15367,8 +16584,8 @@ var spec2 = {
|
|
|
15367
16584
|
function notifyRequest(message) {
|
|
15368
16585
|
if (!message || typeof message !== "object" || Array.isArray(message)) return void 0;
|
|
15369
16586
|
const value = message;
|
|
15370
|
-
if (value.type !== "peerband:notify" || typeof value.id !== "string" || value.id.length > 128) return void 0;
|
|
15371
|
-
return { id: value.id, text: value.text, paneId: value.paneId, channel: value.channel };
|
|
16587
|
+
if (value.type !== "peerband:notify" && value.type !== "peerband:notify-agent" || typeof value.id !== "string" || value.id.length > 128) return void 0;
|
|
16588
|
+
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 };
|
|
15372
16589
|
}
|
|
15373
16590
|
function startMockStatusCycle(adapter, env) {
|
|
15374
16591
|
const interval = Number(env.PEERBAND_MOCK_STATUS_INTERVAL_MS);
|
|
@@ -15392,18 +16609,19 @@ function isShutdownMessage(message) {
|
|
|
15392
16609
|
return Boolean(message) && typeof message === "object" && !Array.isArray(message) && Object.keys(message).length === 1 && message.type === "peerband:shutdown";
|
|
15393
16610
|
}
|
|
15394
16611
|
async function connect(options, ctx) {
|
|
15395
|
-
const
|
|
15396
|
-
if (
|
|
16612
|
+
const requested = options.runtime ?? ctx.env.PEERBAND_RUNTIME;
|
|
16613
|
+
if (requested !== void 0 && requested !== "herdr" && requested !== "herdr-core" && requested !== "mock") throw new UsageError(`Unknown runtime "${requested}".`, "Use --runtime herdr, --runtime herdr-core or --runtime mock.");
|
|
15397
16614
|
const credentials = await requireCredentials(ctx);
|
|
15398
16615
|
if (options.server) credentials.serverUrl = validateServerUrl(options.server);
|
|
15399
16616
|
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.");
|
|
15400
16617
|
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.");
|
|
15401
16618
|
const config = await loadMachineConnectorConfig(ctx, options.config);
|
|
16619
|
+
const runtime = requested ?? config.runtime ?? "herdr";
|
|
15402
16620
|
const enableWrites = writesEnabled(config, { readOnly: options.readOnly, enableWrites: options.enableWrites });
|
|
15403
16621
|
const managed = Boolean(options.managed);
|
|
15404
16622
|
const s = ctx.out.stderr;
|
|
15405
16623
|
const machine = describeMachine(credentials);
|
|
15406
|
-
const adapter = runtime === "mock" ? new MockRuntime() : new HerdrAdapter(config.herdr ?? {});
|
|
16624
|
+
const adapter = runtime === "mock" ? new MockRuntime() : runtime === "herdr-core" ? new HerdrCoreAdapter(config.herdrCore ?? {}) : new HerdrAdapter(config.herdr ?? {});
|
|
15407
16625
|
const core = new ConnectorCore(adapter, {
|
|
15408
16626
|
writesEnabled: enableWrites,
|
|
15409
16627
|
environmentControlEnabled: environmentControlEnabled(config, { disable: options.disableEnvironmentControl, enable: options.enableEnvironmentControl }),
|
|
@@ -15520,11 +16738,11 @@ async function connect(options, ctx) {
|
|
|
15520
16738
|
// src/cli/commands/herdr.ts
|
|
15521
16739
|
import { mkdir as mkdir5, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
|
|
15522
16740
|
import { statSync } from "node:fs";
|
|
15523
|
-
import { join as
|
|
16741
|
+
import { join as join10, resolve as resolve4 } from "node:path";
|
|
15524
16742
|
|
|
15525
16743
|
// src/cli/commands/herdr-check.ts
|
|
15526
16744
|
import { readFile as readFile8, stat as stat4 } from "node:fs/promises";
|
|
15527
|
-
import { join as
|
|
16745
|
+
import { join as join8 } from "node:path";
|
|
15528
16746
|
var PLUGIN_ID = "peerband";
|
|
15529
16747
|
var REPAIR_COMMAND = "peerband herdr install";
|
|
15530
16748
|
var UPDATE_COMMAND = "peerband update";
|
|
@@ -15546,7 +16764,7 @@ async function readSettings(ctx) {
|
|
|
15546
16764
|
const configDir = dir.code === 0 ? dir.stdout.trim() : "";
|
|
15547
16765
|
if (!configDir) return null;
|
|
15548
16766
|
try {
|
|
15549
|
-
const value = JSON.parse(await readFile8(
|
|
16767
|
+
const value = JSON.parse(await readFile8(join8(configDir, "settings.json"), "utf8"));
|
|
15550
16768
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
15551
16769
|
} catch {
|
|
15552
16770
|
return null;
|
|
@@ -15622,7 +16840,7 @@ function installCommand(target) {
|
|
|
15622
16840
|
return target.kind === "local" ? `herdr plugin link ${target.dir}` : `herdr plugin install ${target.source} --ref ${target.ref} --yes`;
|
|
15623
16841
|
}
|
|
15624
16842
|
async function herdrRetrying(ctx, args, timeoutMs) {
|
|
15625
|
-
const sleep = ctx.sleep ?? ((ms) => new Promise((
|
|
16843
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
|
|
15626
16844
|
let result = await ctx.runHerdr(args, { timeoutMs });
|
|
15627
16845
|
for (const delay of RETRY_DELAYS_MS) {
|
|
15628
16846
|
if (result.code === 0 || result.notFound || !RETRYABLE.test(failureDetail(result))) return result;
|
|
@@ -15696,7 +16914,7 @@ async function replacePlugin(ctx, previousSource, installed, target) {
|
|
|
15696
16914
|
|
|
15697
16915
|
// src/cli/relay-maint.ts
|
|
15698
16916
|
import { rm as rm5 } from "node:fs/promises";
|
|
15699
|
-
import { join as
|
|
16917
|
+
import { join as join9 } from "node:path";
|
|
15700
16918
|
|
|
15701
16919
|
// src/cli/control.ts
|
|
15702
16920
|
import { readFile as readFile9 } from "node:fs/promises";
|
|
@@ -15713,7 +16931,7 @@ var ControlUnavailable = class extends Error {
|
|
|
15713
16931
|
reason;
|
|
15714
16932
|
};
|
|
15715
16933
|
async function requestNotify(note, env, timeoutMs = 8e3) {
|
|
15716
|
-
return exchange({ command: "notify", text: note.text, ...note.paneId ? { paneId: note.paneId } : {}, ...note.channel ? { channel: note.channel } : {} }, env, timeoutMs, true);
|
|
16934
|
+
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);
|
|
15717
16935
|
}
|
|
15718
16936
|
async function exchange(payload, env, timeoutMs, typed = false) {
|
|
15719
16937
|
const config = configHome({ env });
|
|
@@ -15726,20 +16944,20 @@ async function exchange(payload, env, timeoutMs, typed = false) {
|
|
|
15726
16944
|
}
|
|
15727
16945
|
if (typeof record.token !== "string") throw typed ? new ControlUnavailable("not-running", "Invalid helper record") : new Error("Invalid helper record");
|
|
15728
16946
|
const socket = createConnection4(controlChannel2(config));
|
|
15729
|
-
return new Promise((
|
|
16947
|
+
return new Promise((resolve6, reject) => {
|
|
15730
16948
|
let text2 = "";
|
|
15731
16949
|
let settled = false;
|
|
15732
|
-
const
|
|
16950
|
+
const finish2 = (error, value) => {
|
|
15733
16951
|
if (settled) return;
|
|
15734
16952
|
settled = true;
|
|
15735
16953
|
clearTimeout(timer);
|
|
15736
16954
|
socket.destroy();
|
|
15737
16955
|
if (error) reject(error);
|
|
15738
|
-
else
|
|
16956
|
+
else resolve6(value ?? {});
|
|
15739
16957
|
};
|
|
15740
16958
|
let connected = false;
|
|
15741
|
-
const timer = setTimeout(() =>
|
|
15742
|
-
socket.once("error", (error) =>
|
|
16959
|
+
const timer = setTimeout(() => finish2(typed ? new ControlUnavailable("timeout", "Helper control timeout") : new Error("Helper control timeout")), timeoutMs);
|
|
16960
|
+
socket.once("error", (error) => finish2(typed ? new ControlUnavailable(connected ? "closed" : "not-running", error.message) : error));
|
|
15743
16961
|
socket.once("connect", () => {
|
|
15744
16962
|
connected = true;
|
|
15745
16963
|
socket.write(`${JSON.stringify({ token: record.token, ...payload })}
|
|
@@ -15747,16 +16965,16 @@ async function exchange(payload, env, timeoutMs, typed = false) {
|
|
|
15747
16965
|
});
|
|
15748
16966
|
socket.on("data", (chunk) => {
|
|
15749
16967
|
text2 += chunk.toString();
|
|
15750
|
-
if (text2.length > 65536) return
|
|
16968
|
+
if (text2.length > 65536) return finish2(new Error("Invalid control response"));
|
|
15751
16969
|
const newline = text2.indexOf("\n");
|
|
15752
16970
|
if (newline < 0) return;
|
|
15753
16971
|
try {
|
|
15754
|
-
|
|
16972
|
+
finish2(void 0, JSON.parse(text2.slice(0, newline)));
|
|
15755
16973
|
} catch (error) {
|
|
15756
|
-
|
|
16974
|
+
finish2(error);
|
|
15757
16975
|
}
|
|
15758
16976
|
});
|
|
15759
|
-
socket.once("end", () =>
|
|
16977
|
+
socket.once("end", () => finish2(typed ? new ControlUnavailable("closed", "Helper control closed") : new Error("Helper control closed")));
|
|
15760
16978
|
});
|
|
15761
16979
|
}
|
|
15762
16980
|
async function relaySnapshot(env) {
|
|
@@ -15784,7 +17002,7 @@ async function stopRelay(env) {
|
|
|
15784
17002
|
// src/cli/relay-maint.ts
|
|
15785
17003
|
var RELAY_MARKER = "peerband_relay";
|
|
15786
17004
|
var RELAY_LABEL = /^PeerBand Relay\b/;
|
|
15787
|
-
var defaultSleep2 = (ms) => new Promise((
|
|
17005
|
+
var defaultSleep2 = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
15788
17006
|
var sleeper = (ctx) => ctx.sleep ?? defaultSleep2;
|
|
15789
17007
|
async function relayRunning(ctx) {
|
|
15790
17008
|
const snapshot = await relaySnapshot(ctx.env);
|
|
@@ -15849,7 +17067,7 @@ async function cleanRelayState(ctx, options = {}) {
|
|
|
15849
17067
|
if (helper.reclaimed) report2.reclaimed.push(lockPath({ env: ctx.env }));
|
|
15850
17068
|
else if (helper.verdict.state === "live") report2.held.push({ lock: lockPath({ env: ctx.env }), reason: helper.verdict.reason });
|
|
15851
17069
|
const receiptsLock = `${receiptsPath({ env: ctx.env })}.lock`;
|
|
15852
|
-
const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile:
|
|
17070
|
+
const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile: join9(receiptsLock, "owner"), processPattern: CONNECTOR_PATTERN2 });
|
|
15853
17071
|
if (receipts.reclaimed) report2.reclaimed.push(receiptsLock);
|
|
15854
17072
|
else if (receipts.verdict.state === "live") report2.held.push({ lock: receiptsLock, reason: receipts.verdict.reason });
|
|
15855
17073
|
const helperGone = helper.verdict.state !== "live";
|
|
@@ -15906,7 +17124,7 @@ async function releasePlugin(ctx) {
|
|
|
15906
17124
|
return { wasRunning, hadPanes: panes.length > 0 };
|
|
15907
17125
|
}
|
|
15908
17126
|
async function waitForRelay(ctx, timeoutMs) {
|
|
15909
|
-
const sleep = ctx.sleep ?? ((ms) => new Promise((
|
|
17127
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
|
|
15910
17128
|
for (let waited = 0; waited < timeoutMs; waited += 1e3) {
|
|
15911
17129
|
if (await relayRunning(ctx)) return true;
|
|
15912
17130
|
await sleep(1e3);
|
|
@@ -15967,7 +17185,7 @@ async function installPlugin(ctx, options = {}) {
|
|
|
15967
17185
|
const configDir = dirResult.stdout.trim();
|
|
15968
17186
|
if (!configDir) throw new CliError("Herdr did not report a plugin config directory.", "Run `herdr plugin config-dir peerband` to investigate.");
|
|
15969
17187
|
await mkdir5(configDir, { recursive: true });
|
|
15970
|
-
await writeFile6(
|
|
17188
|
+
await writeFile6(join10(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
|
|
15971
17189
|
`, { mode: 384 });
|
|
15972
17190
|
ctx.out.print(`${s.green(symbols.ok)} Saved plugin settings ${s.dim(`(node ${process.execPath})`)}`);
|
|
15973
17191
|
const after = await pluginInstalled(ctx);
|
|
@@ -16017,7 +17235,7 @@ var uninstallSpec = {
|
|
|
16017
17235
|
const configDir = dirResult.code === 0 ? dirResult.stdout.trim() : "";
|
|
16018
17236
|
const removed = await removePlugin(ctx);
|
|
16019
17237
|
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.");
|
|
16020
|
-
if (configDir) await rm6(
|
|
17238
|
+
if (configDir) await rm6(join10(configDir, "settings.json"), { force: true }).catch(() => void 0);
|
|
16021
17239
|
ctx.out.print(`${s.green(symbols.ok)} Removed the PeerBand plugin from Herdr.`);
|
|
16022
17240
|
} else {
|
|
16023
17241
|
ctx.out.print("The PeerBand plugin is not installed in Herdr; nothing to remove.");
|
|
@@ -16040,7 +17258,7 @@ var groupSpec = {
|
|
|
16040
17258
|
import { hostname as hostname3 } from "node:os";
|
|
16041
17259
|
|
|
16042
17260
|
// src/cli/browser.ts
|
|
16043
|
-
import { spawn as
|
|
17261
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
16044
17262
|
function browserDecision(url, context) {
|
|
16045
17263
|
if (context.noBrowser) return { open: false, reason: "flag" };
|
|
16046
17264
|
if (context.env.SSH_CONNECTION || context.env.SSH_TTY || context.env.SSH_CLIENT) return { open: false, reason: "ssh" };
|
|
@@ -16060,16 +17278,16 @@ function openerCommand(platform, url) {
|
|
|
16060
17278
|
}
|
|
16061
17279
|
function openBrowser(url, platform = process.platform) {
|
|
16062
17280
|
const { command, args } = openerCommand(platform, url);
|
|
16063
|
-
return new Promise((
|
|
17281
|
+
return new Promise((resolve6) => {
|
|
16064
17282
|
try {
|
|
16065
|
-
const child =
|
|
16066
|
-
child.once("error", () =>
|
|
17283
|
+
const child = spawn3(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
|
|
17284
|
+
child.once("error", () => resolve6(false));
|
|
16067
17285
|
child.once("spawn", () => {
|
|
16068
17286
|
child.unref();
|
|
16069
|
-
|
|
17287
|
+
resolve6(true);
|
|
16070
17288
|
});
|
|
16071
17289
|
} catch {
|
|
16072
|
-
|
|
17290
|
+
resolve6(false);
|
|
16073
17291
|
}
|
|
16074
17292
|
});
|
|
16075
17293
|
}
|
|
@@ -16082,7 +17300,7 @@ var PromptAborted = class extends Error {
|
|
|
16082
17300
|
}
|
|
16083
17301
|
};
|
|
16084
17302
|
function askYesNo(stdin, stderr, prompt, defaultYes = true) {
|
|
16085
|
-
return new Promise((
|
|
17303
|
+
return new Promise((resolve6, reject) => {
|
|
16086
17304
|
let value = "";
|
|
16087
17305
|
const cleanup = () => {
|
|
16088
17306
|
stdin.off("data", onData);
|
|
@@ -16099,7 +17317,7 @@ function askYesNo(stdin, stderr, prompt, defaultYes = true) {
|
|
|
16099
17317
|
if (end === -1) return;
|
|
16100
17318
|
cleanup();
|
|
16101
17319
|
const answer = value.trim().toLowerCase();
|
|
16102
|
-
|
|
17320
|
+
resolve6(answer === "" ? defaultYes : answer === "y" || answer === "yes");
|
|
16103
17321
|
};
|
|
16104
17322
|
stderr.write(prompt);
|
|
16105
17323
|
stdin.resume();
|
|
@@ -16392,8 +17610,12 @@ var spec4 = {
|
|
|
16392
17610
|
var PANE_ID2 = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
16393
17611
|
var START_RELAY = "Start the relay with `peerband relay`.";
|
|
16394
17612
|
function callingPane(env) {
|
|
16395
|
-
const pane
|
|
16396
|
-
return
|
|
17613
|
+
for (const pane of [env.HERDR_PANE_ID, env.HC_TERMINAL_ID]) if (typeof pane === "string" && PANE_ID2.test(pane)) return pane;
|
|
17614
|
+
return void 0;
|
|
17615
|
+
}
|
|
17616
|
+
function callingTerminal(env) {
|
|
17617
|
+
const terminal = env.HC_TERMINAL_ID;
|
|
17618
|
+
return typeof terminal === "string" && PANE_ID2.test(terminal) ? terminal : void 0;
|
|
16397
17619
|
}
|
|
16398
17620
|
async function checkChannel(name, ctx) {
|
|
16399
17621
|
const credentials = await requireCredentials(ctx);
|
|
@@ -16419,18 +17641,20 @@ async function checkChannel(name, ctx) {
|
|
|
16419
17641
|
);
|
|
16420
17642
|
}
|
|
16421
17643
|
}
|
|
16422
|
-
async function notify(text2, json, ctx, channel) {
|
|
17644
|
+
async function notify(text2, json, ctx, channel, agent) {
|
|
16423
17645
|
if (channel !== void 0 && !CHANNEL_NAME.test(channel)) throw new UsageError(`"${sanitize(channel)}" is not a channel name.`, "Channel names are 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit. See `peerband channels`.");
|
|
16424
17646
|
if (text2.trim().length === 0) throw new UsageError("The note is empty.", 'Pass a short note, for example `peerband notify "Migration finished, 3 tests failing"`.');
|
|
16425
17647
|
if (codePoints(text2) > NOTE_MAX_CHARS) throw new UsageError(`The note is ${codePoints(text2)} characters; the limit is ${NOTE_MAX_CHARS}.`, "Shorten it to the result or the decision you need; leave details in a file or the agent output.");
|
|
17648
|
+
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.");
|
|
16426
17649
|
if (channel !== void 0) await checkChannel(channel, ctx);
|
|
16427
17650
|
const paneId = callingPane(ctx.env);
|
|
17651
|
+
const terminalId = callingTerminal(ctx.env);
|
|
16428
17652
|
let reply;
|
|
16429
17653
|
try {
|
|
16430
|
-
reply = await requestNotify({ text: text2, ...paneId ? { paneId } : {}, ...channel !== void 0 ? { channel } : {} }, ctx.env);
|
|
17654
|
+
reply = await requestNotify({ text: text2, ...agent !== void 0 ? { agentId: agent } : {}, ...paneId ? { paneId } : {}, ...terminalId && terminalId !== paneId ? { terminalId } : {}, ...channel !== void 0 ? { channel } : {} }, ctx.env);
|
|
16431
17655
|
} catch (error) {
|
|
16432
17656
|
if (error instanceof ControlUnavailable && error.reason === "closed") {
|
|
16433
|
-
throw new CliError("The running relay does not support notes yet.", "Run `peerband update` to update the CLI and the Herdr plugin, which restarts the relay.");
|
|
17657
|
+
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.");
|
|
16434
17658
|
}
|
|
16435
17659
|
if (error instanceof ControlUnavailable && error.reason === "timeout") throw new CliError("The relay did not answer in time; the note may not have been sent.", "Check `peerband status`.");
|
|
16436
17660
|
throw new CliError("No PeerBand relay is running on this machine.", START_RELAY);
|
|
@@ -16448,24 +17672,26 @@ async function notify(text2, json, ctx, channel) {
|
|
|
16448
17672
|
"Run `peerband update` to update the CLI and the Herdr plugin, which restarts the relay."
|
|
16449
17673
|
);
|
|
16450
17674
|
}
|
|
17675
|
+
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.");
|
|
16451
17676
|
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.");
|
|
16452
|
-
const
|
|
17677
|
+
const agentId2 = typeof reply.agentId === "string" ? reply.agentId : null;
|
|
16453
17678
|
if (json) {
|
|
16454
|
-
ctx.out.print(JSON.stringify({ sent: true, agentId, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
|
|
17679
|
+
ctx.out.print(JSON.stringify({ sent: true, agentId: agentId2, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
|
|
16455
17680
|
return 0;
|
|
16456
17681
|
}
|
|
16457
17682
|
const s = ctx.out.stdout;
|
|
16458
17683
|
const target = channel !== void 0 ? `channel ${s.bold(channel)}` : "the machine owner";
|
|
16459
|
-
ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${
|
|
17684
|
+
ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${agentId2 ? s.dim(` (from agent ${sanitize(agentId2)})`) : ""}.`);
|
|
16460
17685
|
return 0;
|
|
16461
17686
|
}
|
|
16462
17687
|
var spec5 = {
|
|
16463
17688
|
name: "notify",
|
|
16464
17689
|
summary: "Send a short note from an agent to the machine owner",
|
|
16465
|
-
usage: 'peerband notify "<text>" [--channel NAME] [--json]',
|
|
17690
|
+
usage: 'peerband notify "<text>" [--channel NAME] [--agent ID] [--json]',
|
|
16466
17691
|
description: "Sends a short note (1 to 1024 characters) through the running relay to the owner of this machine, for example when a long task finished or an agent is blocked on a decision. Run it from inside a Herdr pane and the note names the agent in that pane. The note goes to the owner only, never to people this machine is shared with. Control characters are removed and likely secrets are redacted (best effort), but do not put credentials or personal data in notes.\n\nWithout --channel the note goes to the PeerBand dashboard, to every owner webhook that takes notes and, once the owner has connected Telegram, to their Telegram chat with the PeerBand bot (unless they turned notes off there). With --channel NAME it still appears in the dashboard (marked with the channel name), but only that one channel receives it: `telegram` for the owner's Telegram (even with notes turned off there), or a webhook such as a Slack channel; see `peerband channels`. The channel is checked first: an unknown or inactive channel is an error and nothing is sent.",
|
|
16467
17692
|
options: [
|
|
16468
17693
|
{ name: "channel", type: "string", valueName: "NAME", description: "Deliver the note to this one channel (`telegram`, or a webhook name) instead of everywhere notes go; it still shows in the dashboard (see `peerband channels`)." },
|
|
17694
|
+
{ name: "agent", type: "string", valueName: "ID", description: "Use this exact current agent id instead of inferring it from the calling pane. Fails if the id is stale or disallowed." },
|
|
16469
17695
|
{ name: "json", type: "boolean", description: "Print a machine-readable result: {sent, agentId, eventId}, plus channel with --channel." }
|
|
16470
17696
|
],
|
|
16471
17697
|
positionals: { name: "text", max: 64 },
|
|
@@ -16483,23 +17709,89 @@ var spec5 = {
|
|
|
16483
17709
|
],
|
|
16484
17710
|
async run(parsed, ctx) {
|
|
16485
17711
|
if (parsed.positionals.length === 0) throw new UsageError("Missing the note text.", 'Usage: peerband notify "<text>"');
|
|
16486
|
-
return notify(parsed.positionals.join(" "), flag(parsed, "json"), ctx, str(parsed, "channel"));
|
|
17712
|
+
return notify(parsed.positionals.join(" "), flag(parsed, "json"), ctx, str(parsed, "channel"), str(parsed, "agent"));
|
|
16487
17713
|
}
|
|
16488
17714
|
};
|
|
16489
17715
|
|
|
17716
|
+
// src/cli/background.ts
|
|
17717
|
+
import { readFile as readFile10 } from "node:fs/promises";
|
|
17718
|
+
import { dirname as dirname5, join as join11, resolve as resolve5 } from "node:path";
|
|
17719
|
+
async function recordedRelayRuntime(env) {
|
|
17720
|
+
try {
|
|
17721
|
+
const record = JSON.parse(await readFile10(ownerRecordPath2(configHome({ env })), "utf8"));
|
|
17722
|
+
return typeof record.runtime === "string" ? record.runtime : "herdr";
|
|
17723
|
+
} catch {
|
|
17724
|
+
return "herdr";
|
|
17725
|
+
}
|
|
17726
|
+
}
|
|
17727
|
+
async function runningRelayRuntime(env) {
|
|
17728
|
+
const snapshot = await relaySnapshot(env);
|
|
17729
|
+
if (snapshot?.source !== "control" || snapshot.state !== "running") return void 0;
|
|
17730
|
+
return recordedRelayRuntime(env);
|
|
17731
|
+
}
|
|
17732
|
+
function lifecycleScript(ctx) {
|
|
17733
|
+
const self = ctx.selfPath ?? process.argv[1] ?? "";
|
|
17734
|
+
return join11(resolve5(dirname5(self), ".."), "herdr", "lifecycle.mjs");
|
|
17735
|
+
}
|
|
17736
|
+
async function startBackgroundRelay(ctx, runtime, options = {}) {
|
|
17737
|
+
const current = await runningRelayRuntime(ctx.env);
|
|
17738
|
+
if (current === runtime) return "running";
|
|
17739
|
+
if (current !== void 0) {
|
|
17740
|
+
throw new CliError(
|
|
17741
|
+
`A PeerBand relay for ${current === "herdr" ? "the Herdr terminal app" : current} is already running on this machine. One relay serves one runtime.`,
|
|
17742
|
+
"Stop it with `peerband relay --stop` (or close the Relay tab in Herdr), then run `peerband relay --core` again."
|
|
17743
|
+
);
|
|
17744
|
+
}
|
|
17745
|
+
const exec2 = ctx.exec ?? execProgram;
|
|
17746
|
+
const probe = options.checked ? void 0 : await exec2(resolveCoreBinary(void 0, ctx.env), ["--version"], { env: ctx.env, timeoutMs: 15e3 });
|
|
17747
|
+
if (probe?.notFound) {
|
|
17748
|
+
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.");
|
|
17749
|
+
}
|
|
17750
|
+
const result = await exec2(process.execPath, [lifecycleScript(ctx), "start"], { env: { ...ctx.env, PEERBAND_RUNTIME: runtime }, timeoutMs: 6e4 });
|
|
17751
|
+
if (result.code !== 0) {
|
|
17752
|
+
const detail = sanitize(result.stderr.trim().split("\n").pop() ?? "").replace(/^peerband:\s*/, "");
|
|
17753
|
+
throw new CliError(detail || "The PeerBand relay did not start.", "Run `peerband status`, then `peerband login` if you are not logged in.");
|
|
17754
|
+
}
|
|
17755
|
+
return "started";
|
|
17756
|
+
}
|
|
17757
|
+
async function stopBackgroundRelay(ctx) {
|
|
17758
|
+
return stopRelay(ctx.env);
|
|
17759
|
+
}
|
|
17760
|
+
|
|
16490
17761
|
// src/cli/commands/relay.ts
|
|
16491
17762
|
var spec6 = {
|
|
16492
17763
|
name: "relay",
|
|
16493
|
-
summary: "Open
|
|
16494
|
-
usage: "peerband relay",
|
|
16495
|
-
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.",
|
|
16496
|
-
options: [
|
|
16497
|
-
|
|
16498
|
-
|
|
17764
|
+
summary: "Open the PeerBand Relay in Herdr, or run it in the background for herdr-core",
|
|
17765
|
+
usage: "peerband relay [--core] [--stop]",
|
|
17766
|
+
description: "Opens the PeerBand Relay in a persistent Herdr tab, or focuses it if it is already open. The tab shows your account, connection state and metadata-only activity; closing it disconnects. Requires Herdr and the PeerBand plugin (`peerband herdr install`). If the plugin is wrong (another version, a local checkout, or a stale config directory), relay offers to repair it first.\n\nWith --core the relay serves herdr-core (`hc`) instead, the terminal server behind the Herdr desktop app. herdr-core has no plugin tab, so the relay runs in the background: closing the desktop app or a terminal leaves it connected. Check it with `peerband status` and stop it with `peerband relay --stop`. It does not start again by itself after you log out or restart the computer; run `peerband relay --core` again. One relay serves one runtime per machine.",
|
|
17767
|
+
options: [
|
|
17768
|
+
{ name: "core", type: "boolean", description: "Run the relay in the background for herdr-core and the Herdr desktop app." },
|
|
17769
|
+
{ name: "stop", type: "boolean", description: "Stop the relay running on this machine (either kind)." }
|
|
17770
|
+
],
|
|
17771
|
+
examples: [
|
|
17772
|
+
["peerband relay", "Open the relay tab in Herdr"],
|
|
17773
|
+
["peerband relay --core", "Connect herdr-core (and the Herdr desktop app) in the background"],
|
|
17774
|
+
["peerband relay --stop", "Disconnect this machine"]
|
|
17775
|
+
],
|
|
17776
|
+
async run(parsed, ctx) {
|
|
17777
|
+
const s = ctx.out.stdout;
|
|
17778
|
+
if (flag(parsed, "stop")) {
|
|
17779
|
+
if (flag(parsed, "core")) throw new UsageError("--core and --stop cannot be combined.", "`peerband relay --stop` stops whichever relay is running.");
|
|
17780
|
+
if (await stopBackgroundRelay(ctx)) ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay stopped.`);
|
|
17781
|
+
else ctx.out.print(s.dim("No PeerBand relay is running on this machine."));
|
|
17782
|
+
return 0;
|
|
17783
|
+
}
|
|
16499
17784
|
const credentials = await requireCredentials(ctx);
|
|
17785
|
+
if (flag(parsed, "core")) {
|
|
17786
|
+
const state = await startBackgroundRelay(ctx, "herdr-core");
|
|
17787
|
+
ctx.out.print(state === "running" ? `${s.green(symbols.ok)} The PeerBand Relay for herdr-core is already running.` : `${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core.`);
|
|
17788
|
+
ctx.out.print(s.dim("Check it with `peerband status`; stop it with `peerband relay --stop`."));
|
|
17789
|
+
printMcpHint(ctx, credentials.serverUrl);
|
|
17790
|
+
printSkillTip(ctx);
|
|
17791
|
+
return 0;
|
|
17792
|
+
}
|
|
16500
17793
|
await ensureHerdrPlugin(ctx);
|
|
16501
17794
|
await openRelay(ctx);
|
|
16502
|
-
const s = ctx.out.stdout;
|
|
16503
17795
|
ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is open in Herdr.`);
|
|
16504
17796
|
printMcpHint(ctx, credentials.serverUrl);
|
|
16505
17797
|
printSkillTip(ctx);
|
|
@@ -16523,8 +17815,8 @@ async function openRelay(ctx) {
|
|
|
16523
17815
|
var SKILL_MODES = ["ask", "install", "skip"];
|
|
16524
17816
|
function report(ctx, installed) {
|
|
16525
17817
|
const s = ctx.out.stdout;
|
|
16526
|
-
const
|
|
16527
|
-
ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand skill ${
|
|
17818
|
+
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(", ")}`;
|
|
17819
|
+
ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand skill ${where2}.`);
|
|
16528
17820
|
ctx.out.print(s.dim(` ${installed.path}`));
|
|
16529
17821
|
}
|
|
16530
17822
|
function keptEdits(ctx, file) {
|
|
@@ -16619,6 +17911,10 @@ async function existingLogin(parsed, ctx) {
|
|
|
16619
17911
|
return void 0;
|
|
16620
17912
|
}
|
|
16621
17913
|
}
|
|
17914
|
+
async function coreInstalled(ctx) {
|
|
17915
|
+
const result = await (ctx.exec ?? execProgram)(resolveCoreBinary(void 0, ctx.env), ["--version"], { env: ctx.env, timeoutMs: 15e3 });
|
|
17916
|
+
return result.code === 0 && /^hc\s/.test(result.stdout.trim());
|
|
17917
|
+
}
|
|
16622
17918
|
var loginOptions = spec3.options.filter((option) => option.name !== "herdr-plugin");
|
|
16623
17919
|
var spec8 = {
|
|
16624
17920
|
name: "setup",
|
|
@@ -16660,6 +17956,15 @@ var spec8 = {
|
|
|
16660
17956
|
let relayOpen = false;
|
|
16661
17957
|
if (flag(parsed, "no-relay")) {
|
|
16662
17958
|
ctx.out.print(s.dim("Skipped. Open it later with `peerband relay`."));
|
|
17959
|
+
} else if (herdr2 === "no-herdr" && await coreInstalled(ctx)) {
|
|
17960
|
+
try {
|
|
17961
|
+
await startBackgroundRelay(ctx, "herdr-core", { checked: true });
|
|
17962
|
+
relayOpen = true;
|
|
17963
|
+
ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is running in the background for herdr-core ${s.dim("(stop it with `peerband relay --stop`)")}.`);
|
|
17964
|
+
} catch (error) {
|
|
17965
|
+
ctx.out.warn(`${s.yellow(symbols.warn)} Could not start the PeerBand Relay for herdr-core: ${error.message}`);
|
|
17966
|
+
if (error instanceof CliError && error.hint) ctx.out.print(s.dim(` ${error.hint}`));
|
|
17967
|
+
}
|
|
16663
17968
|
} else if (herdr2 !== "ready") {
|
|
16664
17969
|
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\`.`));
|
|
16665
17970
|
} else {
|
|
@@ -16783,6 +18088,7 @@ async function buildStatus(ctx) {
|
|
|
16783
18088
|
credentials = void 0;
|
|
16784
18089
|
}
|
|
16785
18090
|
const snapshot = await relaySnapshot(ctx.env);
|
|
18091
|
+
const running = snapshot?.source === "control" && snapshot.state === "running";
|
|
16786
18092
|
const plugin = await checkHerdrPlugin(ctx);
|
|
16787
18093
|
const messages = await loadMachineConnectorConfig(ctx).then(
|
|
16788
18094
|
(config) => writesEnabled(config) ? "allowed" : "read-only",
|
|
@@ -16800,9 +18106,10 @@ async function buildStatus(ctx) {
|
|
|
16800
18106
|
installationId: credentials?.installationId ?? null,
|
|
16801
18107
|
enrolledAt: credentials?.enrolledAt ?? null,
|
|
16802
18108
|
relay: {
|
|
16803
|
-
running
|
|
18109
|
+
running,
|
|
16804
18110
|
connection: snapshot?.connectionState ?? null,
|
|
16805
|
-
source: snapshot?.source ?? "none"
|
|
18111
|
+
source: snapshot?.source ?? "none",
|
|
18112
|
+
runtime: running ? await recordedRelayRuntime(ctx.env) : null
|
|
16806
18113
|
},
|
|
16807
18114
|
messages,
|
|
16808
18115
|
herdr: {
|
|
@@ -16836,7 +18143,7 @@ function renderHuman(report2, ctx) {
|
|
|
16836
18143
|
rows.push(["Installation", report2.installationId ?? ""]);
|
|
16837
18144
|
if (report2.enrolledAt) rows.push(["Enrolled", report2.enrolledAt]);
|
|
16838
18145
|
}
|
|
16839
|
-
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`)")}`);
|
|
18146
|
+
const relayLine = report2.relay.running ? `${colorConnection(s, report2.relay.connection)}${report2.relay.runtime === "herdr-core" ? s.dim(" (herdr-core, in the background; stop with `peerband relay --stop`)") : ""}` : report2.relay.source === "file" && report2.relay.connection && report2.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report2.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`, or `peerband relay --core` for herdr-core)")}`);
|
|
16840
18147
|
rows.push(["Relay", relayLine]);
|
|
16841
18148
|
if (report2.messages) {
|
|
16842
18149
|
rows.push([
|
|
@@ -16857,8 +18164,8 @@ function renderHuman(report2, ctx) {
|
|
|
16857
18164
|
}
|
|
16858
18165
|
rows.push(["peerband", `${report2.version} ${s.dim(`(node ${report2.node})`)}`]);
|
|
16859
18166
|
rows.push(["Config", s.dim(report2.configHome)]);
|
|
16860
|
-
const width = Math.max(...rows.map(([
|
|
16861
|
-
for (const [
|
|
18167
|
+
const width = Math.max(...rows.map(([key2]) => key2.length));
|
|
18168
|
+
for (const [key2, value] of rows) ctx.out.print(`${s.bold(key2.padEnd(width))} ${value}`);
|
|
16862
18169
|
}
|
|
16863
18170
|
var spec10 = {
|
|
16864
18171
|
name: "status",
|
|
@@ -16953,8 +18260,8 @@ var spec11 = {
|
|
|
16953
18260
|
};
|
|
16954
18261
|
|
|
16955
18262
|
// src/cli/commands/update.ts
|
|
16956
|
-
import { existsSync as
|
|
16957
|
-
import { dirname as
|
|
18263
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
18264
|
+
import { dirname as dirname6, isAbsolute, join as join12, relative as relative2 } from "node:path";
|
|
16958
18265
|
var DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
16959
18266
|
var PACKAGE = "peerband";
|
|
16960
18267
|
var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
@@ -17007,14 +18314,14 @@ function isInside(child, parent) {
|
|
|
17007
18314
|
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
17008
18315
|
}
|
|
17009
18316
|
function checkoutRoot(self) {
|
|
17010
|
-
let dir =
|
|
18317
|
+
let dir = dirname6(self);
|
|
17011
18318
|
for (let i = 0; i < 4; i++) {
|
|
17012
18319
|
try {
|
|
17013
|
-
const pkg = JSON.parse(readFileSync2(
|
|
17014
|
-
if (pkg.name === PACKAGE &&
|
|
18320
|
+
const pkg = JSON.parse(readFileSync2(join12(dir, "package.json"), "utf8"));
|
|
18321
|
+
if (pkg.name === PACKAGE && existsSync3(join12(dir, ".git"))) return dir;
|
|
17015
18322
|
} catch {
|
|
17016
18323
|
}
|
|
17017
|
-
const parent =
|
|
18324
|
+
const parent = dirname6(dir);
|
|
17018
18325
|
if (parent === dir) break;
|
|
17019
18326
|
dir = parent;
|
|
17020
18327
|
}
|
|
@@ -17025,7 +18332,7 @@ async function detectInstall(ctx) {
|
|
|
17025
18332
|
if (/[\\/]_npx[\\/]/.test(self)) return { kind: "npx", self };
|
|
17026
18333
|
const npm = await (ctx.exec ?? execProgram)("npm", ["root", "-g"], { timeoutMs: 6e4, env: ctx.env });
|
|
17027
18334
|
const npmRoot = npm.code === 0 ? npm.stdout.trim().split(/\r?\n/).pop()?.trim() : void 0;
|
|
17028
|
-
if (npmRoot && isInside(self, real(
|
|
18335
|
+
if (npmRoot && isInside(self, real(join12(npmRoot, PACKAGE)))) return { kind: "npm-global", self, npmRoot };
|
|
17029
18336
|
const checkout = checkoutRoot(self);
|
|
17030
18337
|
if (checkout) return { kind: "source", self, npmRoot, detail: checkout };
|
|
17031
18338
|
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" };
|
|
@@ -17079,7 +18386,7 @@ var spec12 = {
|
|
|
17079
18386
|
const plugin = await checkHerdrPlugin(ctx);
|
|
17080
18387
|
const report2 = { current: ctx.version, latest, updateAvailable: newer, action: "none", plugin: pluginSummary(plugin) };
|
|
17081
18388
|
const pluginNeedsRepair = plugin.found && plugin.installed && plugin.problems.length > 0;
|
|
17082
|
-
const
|
|
18389
|
+
const finish2 = (code = 0) => {
|
|
17083
18390
|
if (json) ctx.out.print(JSON.stringify(report2, null, 2));
|
|
17084
18391
|
return code;
|
|
17085
18392
|
};
|
|
@@ -17087,7 +18394,7 @@ var spec12 = {
|
|
|
17087
18394
|
if (newer) log(`${s.yellow(symbols.warn)} PeerBand ${latest} is available (you have ${ctx.version}). Run ${s.bold("peerband update")}.`);
|
|
17088
18395
|
else log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
|
|
17089
18396
|
if (pluginNeedsRepair) log(`${s.yellow(symbols.warn)} The Herdr plugin needs repair: ${plugin.problems[0].message} ${s.dim("(run `peerband update`)")}`);
|
|
17090
|
-
return
|
|
18397
|
+
return finish2();
|
|
17091
18398
|
}
|
|
17092
18399
|
if (!newer) {
|
|
17093
18400
|
log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
|
|
@@ -17101,7 +18408,7 @@ var spec12 = {
|
|
|
17101
18408
|
} else if (plugin.installed) {
|
|
17102
18409
|
log(`${s.green(symbols.ok)} The Herdr plugin matches ${s.dim(`(${plugin.source ?? "installed"})`)}.`);
|
|
17103
18410
|
}
|
|
17104
|
-
return
|
|
18411
|
+
return finish2();
|
|
17105
18412
|
}
|
|
17106
18413
|
const install = await detectInstall(ctx);
|
|
17107
18414
|
report2.install = install.kind;
|
|
@@ -17111,7 +18418,7 @@ var spec12 = {
|
|
|
17111
18418
|
report2.manual = manual;
|
|
17112
18419
|
if (json) {
|
|
17113
18420
|
io.out.fail(manual.message, manual.hint);
|
|
17114
|
-
return
|
|
18421
|
+
return finish2(1);
|
|
17115
18422
|
}
|
|
17116
18423
|
throw new CliError(`PeerBand ${latest} is available (you have ${ctx.version}). ${manual.message}`, manual.hint);
|
|
17117
18424
|
}
|
|
@@ -17126,7 +18433,7 @@ var spec12 = {
|
|
|
17126
18433
|
if (!proceed) {
|
|
17127
18434
|
report2.action = "cancelled";
|
|
17128
18435
|
log(s.dim("Not updated."));
|
|
17129
|
-
return
|
|
18436
|
+
return finish2();
|
|
17130
18437
|
}
|
|
17131
18438
|
}
|
|
17132
18439
|
const exec2 = ctx.exec ?? execProgram;
|
|
@@ -17141,8 +18448,8 @@ var spec12 = {
|
|
|
17141
18448
|
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\`.`
|
|
17142
18449
|
);
|
|
17143
18450
|
}
|
|
17144
|
-
const entry =
|
|
17145
|
-
if (!
|
|
18451
|
+
const entry = join12(install.npmRoot, PACKAGE, "dist", "peerband.mjs");
|
|
18452
|
+
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\`.`);
|
|
17146
18453
|
log(`${s.green(symbols.ok)} Installed peerband ${latest}.`);
|
|
17147
18454
|
report2.action = "updated";
|
|
17148
18455
|
if (skillInstalled(ctx)) {
|
|
@@ -17156,11 +18463,11 @@ var spec12 = {
|
|
|
17156
18463
|
}
|
|
17157
18464
|
if (!plugin.found) {
|
|
17158
18465
|
log(s.dim("Herdr was not found, so there is no plugin to update."));
|
|
17159
|
-
return
|
|
18466
|
+
return finish2();
|
|
17160
18467
|
}
|
|
17161
18468
|
if (!plugin.installed) {
|
|
17162
18469
|
log(`${s.dim("Next:")} peerband herdr install ${s.dim("(adds the PeerBand plugin to Herdr)")}`);
|
|
17163
|
-
return
|
|
18470
|
+
return finish2();
|
|
17164
18471
|
}
|
|
17165
18472
|
log("Updating the Herdr plugin with the new CLI\u2026");
|
|
17166
18473
|
const env = { ...ctx.env, ...io.out.stdout.enabled && ctx.env.FORCE_COLOR === void 0 ? { FORCE_COLOR: "1" } : {} };
|
|
@@ -17174,12 +18481,12 @@ var spec12 = {
|
|
|
17174
18481
|
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`.");
|
|
17175
18482
|
}
|
|
17176
18483
|
report2.plugin = pluginSummary(await checkHerdrPlugin({ ...ctx, version: latest }));
|
|
17177
|
-
return
|
|
18484
|
+
return finish2();
|
|
17178
18485
|
}
|
|
17179
18486
|
};
|
|
17180
18487
|
|
|
17181
18488
|
// src/cli/registry.ts
|
|
17182
|
-
var commands = [spec8, spec3, spec4, spec10, spec12, spec6, spec7, spec9, spec5, spec, spec11, spec2];
|
|
18489
|
+
var commands = [spec8, spec3, spec4, spec10, spec12, spec6, spec7, spec9, spec5, spec, spec11, spec2, ...toolCommands];
|
|
17183
18490
|
var herdrCommands = [installSpec, uninstallSpec];
|
|
17184
18491
|
function lookup(words) {
|
|
17185
18492
|
const [first, second] = words;
|
|
@@ -17234,7 +18541,11 @@ function rootHelp(s, version) {
|
|
|
17234
18541
|
...section(s, "Updating", ["peerband update Update the CLI and the Herdr plugin together (--check to only look)"]),
|
|
17235
18542
|
...section(s, "From an agent", [
|
|
17236
18543
|
'peerband notify "<text>" Send the machine owner a short note (task done, blocked, result)',
|
|
17237
|
-
" --channel NAME Send it to one of the owner's channels instead (see peerband channels)"
|
|
18544
|
+
" --channel NAME Send it to one of the owner's channels instead (see peerband channels)",
|
|
18545
|
+
" --agent ID Attribute a reply to this exact current agent",
|
|
18546
|
+
"peerband agents List agents on your machines (peerband machines for the machines)",
|
|
18547
|
+
'peerband agent ask ID "\u2026" Hand work to another agent and wait for its answer',
|
|
18548
|
+
"peerband tools Every PeerBand MCP tool, as a command (results are JSON)"
|
|
17238
18549
|
]),
|
|
17239
18550
|
...section(s, "Exit codes", ["0 ok 1 failure 2 usage error 3 not logged in 130 interrupted"]),
|
|
17240
18551
|
"",
|
|
@@ -17274,7 +18585,7 @@ function herdrGroupHelp(s) {
|
|
|
17274
18585
|
}
|
|
17275
18586
|
|
|
17276
18587
|
// src/cli/cli.ts
|
|
17277
|
-
var VERSION = true ? "0.
|
|
18588
|
+
var VERSION = true ? "0.3.0" : "0.0.0-dev";
|
|
17278
18589
|
function createContext(overrides = {}) {
|
|
17279
18590
|
const env = overrides.env ?? process.env;
|
|
17280
18591
|
const stdout = overrides.stdout ?? process.stdout;
|