peerband 0.2.9 → 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/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 key of __getOwnPropNames(from))
25
- if (!__hasOwnProp.call(to, key) && key !== except)
26
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
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((key) => {
373
- let value = params[key];
372
+ Object.keys(params).forEach((key2) => {
373
+ let value = params[key2];
374
374
  if (value.length > 1) {
375
- throw new Error(`Parameter "${key}" must have only a single value`);
375
+ throw new Error(`Parameter "${key2}" must have only a single value`);
376
376
  }
377
377
  value = value[0];
378
- if (key === "client_max_window_bits") {
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 "${key}": ${value}`
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 "${key}": ${value}`
389
+ `Invalid value for parameter "${key2}": ${value}`
390
390
  );
391
391
  }
392
- } else if (key === "server_max_window_bits") {
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 "${key}": ${value}`
396
+ `Invalid value for parameter "${key2}": ${value}`
397
397
  );
398
398
  }
399
399
  value = num;
400
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
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 "${key}": ${value}`
403
+ `Invalid value for parameter "${key2}": ${value}`
404
404
  );
405
405
  }
406
406
  } else {
407
- throw new Error(`Unknown parameter "${key}"`);
407
+ throw new Error(`Unknown parameter "${key2}"`);
408
408
  }
409
- params[key] = value;
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 key = `${endpoint}_max_window_bits`;
458
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
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 key = `${endpoint}_max_window_bits`;
509
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
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: createHash5 } = __require("crypto");
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 key = randomBytes(16).toString("base64");
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": 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 [key2, value] of Object.entries(headers)) {
2892
- options.headers[key2.toLowerCase()] = value;
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 = createHash5("sha1").update(key + GUID).digest("base64");
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 finish() {
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: createHash5 } = __require("crypto");
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 key = req.headers["sec-websocket-key"];
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 (key === void 0 || !keyRegex.test(key)) {
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
- key,
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, key, protocols, req, socket, head, cb);
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, key, protocols, req, socket, head, cb) {
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 = createHash5("sha1").update(key + GUID).digest("base64");
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(key) {
4062
- return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
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(key) {
4066
- if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
4067
- return new _Code(`${key}`);
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: ${key}, use explicit $id name mapping`);
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 [key, value] of keyValues) {
4696
+ for (const [key2, value] of keyValues) {
4697
4697
  if (code.length > 1)
4698
4698
  code.push(",");
4699
- code.push(key);
4700
- if (key !== value || this.opts.es5) {
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 key in schema) {
4976
- if (!rules[key])
4977
- checkStrictMode(it, `unknown keyword: "${key}"`);
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 key in schema)
4985
- if (rules[key])
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 key in schema)
4994
- if (key !== "$ref" && RULES.all[key])
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 key in properties) {
5573
- assignDefault(it, key, properties[key].default);
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 key = keys[i];
5958
- if (!equal(a[key], b[key])) return false;
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 key in schema) {
6031
- var sch = schema[key];
6030
+ for (var key2 in schema) {
6031
+ var sch = schema[key2];
6032
6032
  if (Array.isArray(sch)) {
6033
- if (key in traverse.arrayKeywords) {
6033
+ if (key2 in traverse.arrayKeywords) {
6034
6034
  for (var i = 0; i < sch.length; i++)
6035
- _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
6035
+ _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key2 + "/" + i, rootSchema, jsonPtr, key2, schema, i);
6036
6036
  }
6037
- } else if (key in traverse.propsKeywords) {
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 + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
6040
+ _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key2 + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key2, schema, prop);
6041
6041
  }
6042
- } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
6043
- _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
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 key in schema) {
6101
- if (REF_KEYWORDS.has(key))
6100
+ for (const key2 in schema) {
6101
+ if (REF_KEYWORDS.has(key2))
6102
6102
  return true;
6103
- const sch = schema[key];
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 key in schema) {
6114
- if (key === "$ref")
6113
+ for (const key2 in schema) {
6114
+ if (key2 === "$ref")
6115
6115
  return Infinity;
6116
6116
  count++;
6117
- if (SIMPLE_INLINED.has(key))
6117
+ if (SIMPLE_INLINED.has(key2))
6118
6118
  continue;
6119
- if (typeof schema[key] == "object") {
6120
- (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
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 key in schema)
6310
- if (self.RULES.all[key])
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 = resolve5.call(this, root, ref);
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 resolve5(root, ref) {
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 resolve5(baseURI, relativeURI, options) {
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: resolve5,
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, key, _meta, _validateSchema = this.opts.validateSchema) {
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
- key = (0, resolve_1.normalizeId)(key || id);
8364
- this._checkUnique(key);
8365
- this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
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, key, _validateSchema = this.opts.validateSchema) {
8371
- this.addSchema(schema, key, true, _validateSchema);
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 key in rules) {
8528
- const rule = rules[key];
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[key];
8532
+ const schema = keywords[key2];
8533
8533
  if ($data && schema)
8534
- keywords[key] = schemaOrData(schema);
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 key in checkOpts) {
8608
- const opt = key;
8607
+ for (const key2 in checkOpts) {
8608
+ const opt = key2;
8609
8609
  if (opt in options)
8610
- this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
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 key in optsSchemas)
8625
- this.addSchema(optsSchemas[key], key);
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 key in schema) {
9674
- if (key === "__proto__")
9673
+ for (const key2 in schema) {
9674
+ if (key2 === "__proto__")
9675
9675
  continue;
9676
- const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
9677
- deps[key] = schema[key];
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, (key) => {
9755
- cxt.setParams({ propertyName: key });
9754
+ gen.forIn("key", data, (key2) => {
9755
+ cxt.setParams({ propertyName: key2 });
9756
9756
  cxt.subschema({
9757
9757
  keyword: "propertyNames",
9758
- data: key,
9758
+ data: key2,
9759
9759
  dataTypes: ["string"],
9760
- propertyName: key,
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, (key) => {
9809
+ gen.forIn("key", data, (key2) => {
9810
9810
  if (!props.length && !patProps.length)
9811
- additionalPropertyCode(key);
9811
+ additionalPropertyCode(key2);
9812
9812
  else
9813
- gen.if(isAdditional(key), () => additionalPropertyCode(key));
9813
+ gen.if(isAdditional(key2), () => additionalPropertyCode(key2));
9814
9814
  });
9815
9815
  }
9816
- function isAdditional(key) {
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, key);
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._)`${key} === ${p}`));
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(${key})`));
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(key) {
9832
- gen.code((0, codegen_1._)`delete ${data}[${key}]`);
9831
+ function deleteAdditional(key2) {
9832
+ gen.code((0, codegen_1._)`delete ${data}[${key2}]`);
9833
9833
  }
9834
- function additionalPropertyCode(key) {
9834
+ function additionalPropertyCode(key2) {
9835
9835
  if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
9836
- deleteAdditional(key);
9836
+ deleteAdditional(key2);
9837
9837
  return;
9838
9838
  }
9839
9839
  if (schema === false) {
9840
- cxt.setParams({ additionalProperty: key });
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(key, valid, false);
9849
+ applyAdditionalSchema(key2, valid, false);
9850
9850
  gen.if((0, codegen_1.not)(valid), () => {
9851
9851
  cxt.reset();
9852
- deleteAdditional(key);
9852
+ deleteAdditional(key2);
9853
9853
  });
9854
9854
  } else {
9855
- applyAdditionalSchema(key, valid);
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(key, valid, errors) {
9861
+ function applyAdditionalSchema(key2, valid, errors) {
9862
9862
  const subschema = {
9863
9863
  keyword: "additionalProperties",
9864
- dataProp: key,
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, (key) => {
9990
- gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
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: key,
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}[${key}]`, true);
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, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
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, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
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(key) {
11115
+ function unevaluatedPropCode(key2) {
11116
11116
  if (schema === false) {
11117
- cxt.setParams({ unevaluatedProperty: key });
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: key,
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, key) {
11135
- return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`;
11134
+ function unevaluatedDynamic(evaluatedProps, key2) {
11135
+ return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key2}]`;
11136
11136
  }
11137
- function unevaluatedStatic(evaluatedProps, key) {
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._)`${key} !== ${p}`);
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 key of Object.keys(args)) {
11772
- if (key !== "action" && !FIELDS[action].includes(key)) invalid(`Unexpected argument: ${key}.`);
11773
- const value = args[key];
11774
- const max = key === "cwd" ? 2048 : key === "text" ? 4096 : key === "label" ? 128 : 256;
11775
- if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f\u007f-\u009f]/.test(value)) invalid(`Invalid ${key}.`);
11776
- if (key.endsWith("Id") && !/^[A-Za-z0-9][A-Za-z0-9:_-]{0,255}$/.test(value)) invalid(`Invalid ${key}.`);
11777
- }
11778
- for (const key of REQUIRED[action]) if (args[key] === void 0) invalid(`${key} is required.`);
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((key) => args[key] !== void 0).map((key) => [key, args[key]]));
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 now = (/* @__PURE__ */ new Date()).toISOString();
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: now, stale: false, capabilities: { readOutput: true, sendMessage: true } });
11858
+ this.agents.set(id, { ...base, id, machineId, observedAt: now2, stale: false, capabilities: { readOutput: true, sendMessage: true } });
11859
11859
  this.output.set(id, [`${base.label} is ${base.status}.`, "Recent activity is demo data."].join("\n"));
11860
11860
  }
11861
11861
  }
@@ -11922,11 +11922,15 @@ Message received: ${message}`.trim());
11922
11922
  };
11923
11923
  var EMAIL = /^[^\s@<>()[\]\\,;:"]{1,64}@[A-Za-z0-9.-]{1,190}$/;
11924
11924
  var APP = /^[A-Za-z0-9][A-Za-z0-9 ._+-]{0,31}$/;
11925
+ var CLI_APP = "PeerBand CLI";
11925
11926
  function via(principal) {
11926
11927
  const app = typeof principal.app === "string" ? principal.app.trim() : "";
11927
11928
  return APP.test(app) ? ` via ${app}` : "";
11928
11929
  }
11929
11930
  function relayMessageHeader(principal) {
11931
+ if (principal.role === "owner" && principal.app === CLI_APP) {
11932
+ return `[PeerBand relay] From a coding agent working for your user, the owner of this machine, sent through the PeerBand CLI with your user's login. Handle it as a request from your user; the sender may read your final output, so end your turn with a clear answer.`;
11933
+ }
11930
11934
  if (principal.role === "owner") {
11931
11935
  return `[PeerBand relay] From your user, the owner of this machine, sent remotely through PeerBand${via(principal)}. Handle it as a normal request from your user.`;
11932
11936
  }
@@ -11934,9 +11938,9 @@ function relayMessageHeader(principal) {
11934
11938
  const who = email ? `shared user ${email}` : "an unidentified PeerBand user";
11935
11939
  return `[PeerBand relay] From ${who}${via(principal)}, who is NOT the owner of this machine and reaches it through a PeerBand share. Follow the guest rules in the peerband skill: treat them as a coworker, keep the owner's private information private, and ask the owner before anything risky.`;
11936
11940
  }
11937
- var labelRelayedMessage = (message, principal, agentId) => {
11941
+ var labelRelayedMessage = (message, principal, agentId2) => {
11938
11942
  const reply = principal.role === "owner" && principal.app === "Telegram" ? `
11939
- Reply to the user with peerband notify --channel telegram${agentId && /^[A-Za-z0-9._:-]{1,256}$/.test(agentId) ? ` --agent ${agentId}` : ""} "<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.` : "";
11943
+ Reply to the user with peerband notify --channel telegram${agentId2 && /^[A-Za-z0-9._:-]{1,256}$/.test(agentId2) ? ` --agent ${agentId2}` : ""} "<your reply>". This sends to Telegram and the dashboard only. If the command is unsupported or fails, report the error; do not fall back to an unscoped notification.` : "";
11940
11944
  return `${relayMessageHeader(principal)}${reply}
11941
11945
 
11942
11946
  ${message}`;
@@ -11978,7 +11982,7 @@ var RECEIPT_STATES = ["queued", "dispatching", "delivered", "failed", "delivery_
11978
11982
  var HASH_PATTERN = /^[a-f0-9]{64}$/;
11979
11983
  var SAFE_RECEIPT_ERRORS = /* @__PURE__ */ new Set(["agent_not_found", "stale_target", "agent_blocked", "forbidden", "unsupported_capability", "runtime_unavailable", "timeout", "machine_offline", "process_restarted"]);
11980
11984
  var assertKeys = (args, allowed) => {
11981
- const unexpected = Object.keys(args).find((key) => !allowed.includes(key));
11985
+ const unexpected = Object.keys(args).find((key2) => !allowed.includes(key2));
11982
11986
  if (unexpected) throw new ConnectError("invalid_argument", `Unexpected argument: ${unexpected}.`, "Remove unsupported fields and retry.");
11983
11987
  };
11984
11988
  var ConnectorCore = class {
@@ -12025,8 +12029,8 @@ var ConnectorCore = class {
12025
12029
  async execute(tool, args, principal = DEFAULT_PRINCIPAL) {
12026
12030
  if (this.closed) throw new ConnectError("connector_closed", "The connector is shutting down.", "Restart the connector to make further requests.");
12027
12031
  let finishOperation;
12028
- const operation = new Promise((resolve5) => {
12029
- finishOperation = resolve5;
12032
+ const operation = new Promise((resolve6) => {
12033
+ finishOperation = resolve6;
12030
12034
  });
12031
12035
  this.activeOperations.add(operation);
12032
12036
  try {
@@ -12102,9 +12106,9 @@ var ConnectorCore = class {
12102
12106
  this.requireScope(principal, "agents:read");
12103
12107
  assertKeys(args, ["machine", "workspace", "status", "cursor", "limit"]);
12104
12108
  const limit = safeInteger(args.limit, 50, 1, 200, "limit");
12105
- for (const key of ["machine", "workspace", "status", "cursor"]) {
12106
- if (args[key] !== void 0 && (typeof args[key] !== "string" || args[key].length > (key === "cursor" ? 256 : 512))) {
12107
- throw new ConnectError("invalid_argument", `${key} has an invalid value.`, "Check the list filter and try again.");
12109
+ for (const key2 of ["machine", "workspace", "status", "cursor"]) {
12110
+ if (args[key2] !== void 0 && (typeof args[key2] !== "string" || args[key2].length > (key2 === "cursor" ? 256 : 512))) {
12111
+ throw new ConnectError("invalid_argument", `${key2} has an invalid value.`, "Check the list filter and try again.");
12108
12112
  }
12109
12113
  }
12110
12114
  if (args.status !== void 0 && !["idle", "working", "blocked", "done", "unknown"].includes(args.status)) {
@@ -12157,14 +12161,14 @@ var ConnectorCore = class {
12157
12161
  assertKeys(args, ["agentId", "message", "idempotencyKey"]);
12158
12162
  if (!this.writesEnabled) throw new ConnectError("write_disabled", "Message sending is disabled.", 'This machine is read-only. To allow messages, remove --read-only or set "enableWrites": true in connector.json on that machine.');
12159
12163
  this.requireScope(principal, "agents:message");
12160
- const key = args.idempotencyKey;
12164
+ const key2 = args.idempotencyKey;
12161
12165
  const message = args.message;
12162
- if (typeof key !== "string" || key.length < 16 || key.length > 256) throw new ConnectError("invalid_argument", "idempotencyKey must be 16 to 256 characters.", "Provide a fresh random idempotency key for this request.");
12166
+ if (typeof key2 !== "string" || key2.length < 16 || key2.length > 256) throw new ConnectError("invalid_argument", "idempotencyKey must be 16 to 256 characters.", "Provide a fresh random idempotency key for this request.");
12163
12167
  if (typeof message !== "string" || message.trim().length < 1 || Buffer.byteLength(message, "utf8") > 8192) throw new ConnectError("invalid_argument", "message must contain 1 to 8192 UTF-8 bytes.", "Shorten the message and try again.");
12164
12168
  const principalHash = hash(principal.id);
12165
12169
  const payloadHash = hash(message);
12166
12170
  if (typeof args.agentId !== "string" || args.agentId.length < 1 || args.agentId.length > 256) throw new ConnectError("invalid_argument", "agentId is required.", "Use an exact agent ID returned by list_agents.");
12167
- const requestKeyHash = hash(canonical([principalHash, args.agentId, "send_agent_message", key]));
12171
+ const requestKeyHash = hash(canonical([principalHash, args.agentId, "send_agent_message", key2]));
12168
12172
  return this.withSubmissionLock(requestKeyHash, async () => {
12169
12173
  const prior = this.idempotency.get(requestKeyHash);
12170
12174
  if (prior) {
@@ -12177,10 +12181,10 @@ var ConnectorCore = class {
12177
12181
  const agent = await this.authorizedAgent(args.agentId, principal, true);
12178
12182
  if (agent.status === "blocked") throw new ConnectError("agent_blocked", "The target agent is blocked.", "Inspect its state and choose an appropriate next step before sending.");
12179
12183
  if (!agent.capabilities.sendMessage || !this.adapter.getCapabilities().sendMessage) throw new ConnectError("unsupported_capability", "Message sending is not supported for this runtime.", "Use a runtime with semantic message support.");
12180
- const idempotencyHash = hash(canonical([principalHash, agent.machineId, agent.id, "send_agent_message", key]));
12184
+ const idempotencyHash = hash(canonical([principalHash, agent.machineId, agent.id, "send_agent_message", key2]));
12181
12185
  this.pruneReceipts();
12182
12186
  if (this.receipts.size >= MAX_RECEIPTS) throw new ConnectError("receipt_limit", "The receipt store is full.", "Wait for old receipts to expire or increase retention storage capacity.");
12183
- const now = Date.now();
12187
+ const now2 = Date.now();
12184
12188
  const receipt = {
12185
12189
  requestId: randomUUID(),
12186
12190
  principalHash,
@@ -12192,8 +12196,8 @@ var ConnectorCore = class {
12192
12196
  requestKeyHash,
12193
12197
  payloadHash,
12194
12198
  state: "queued",
12195
- createdAt: now,
12196
- updatedAt: now
12199
+ createdAt: now2,
12200
+ updatedAt: now2
12197
12201
  };
12198
12202
  this.receipts.set(receipt.requestId, receipt);
12199
12203
  this.idempotency.set(requestKeyHash, receipt);
@@ -12219,12 +12223,12 @@ var ConnectorCore = class {
12219
12223
  }
12220
12224
  async controlEnvironment(args, principal) {
12221
12225
  this.authorizeEnvironment(principal);
12222
- const { idempotencyKey: key, ...input } = args;
12226
+ const { idempotencyKey: key2, ...input } = args;
12223
12227
  const command = environmentCommand(input);
12224
- if (typeof key !== "string" || key.length < 16 || key.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.");
12228
+ if (typeof key2 !== "string" || key2.length < 16 || key2.length > 256) throw new ConnectError("invalid_argument", "idempotencyKey must be 16 to 256 characters.", "Provide a random key and reuse it only for the same operation.");
12225
12229
  const principalHash = hash(principal.id);
12226
12230
  const payloadHash = hash(canonical(command));
12227
- const requestKeyHash = hash(canonical([principalHash, "control_environment", key]));
12231
+ const requestKeyHash = hash(canonical([principalHash, "control_environment", key2]));
12228
12232
  return this.withSubmissionLock(requestKeyHash, async () => {
12229
12233
  const prior = this.idempotency.get(requestKeyHash);
12230
12234
  if (prior) {
@@ -12233,7 +12237,7 @@ var ConnectorCore = class {
12233
12237
  }
12234
12238
  this.pruneReceipts();
12235
12239
  if (this.receipts.size >= MAX_RECEIPTS) throw new ConnectError("receipt_limit", "The receipt store is full.", "Wait for old receipts to expire.");
12236
- const now = Date.now();
12240
+ const now2 = Date.now();
12237
12241
  const receipt = {
12238
12242
  requestId: randomUUID(),
12239
12243
  principalHash,
@@ -12245,8 +12249,8 @@ var ConnectorCore = class {
12245
12249
  requestKeyHash,
12246
12250
  payloadHash,
12247
12251
  state: "queued",
12248
- createdAt: now,
12249
- updatedAt: now
12252
+ createdAt: now2,
12253
+ updatedAt: now2
12250
12254
  };
12251
12255
  this.receipts.set(receipt.requestId, receipt);
12252
12256
  this.idempotency.set(requestKeyHash, receipt);
@@ -12275,19 +12279,19 @@ var ConnectorCore = class {
12275
12279
  return this.publicReceipt(receipt);
12276
12280
  });
12277
12281
  }
12278
- async withSubmissionLock(key, action) {
12279
- const previous = this.submissionLocks.get(key) ?? Promise.resolve();
12282
+ async withSubmissionLock(key2, action) {
12283
+ const previous = this.submissionLocks.get(key2) ?? Promise.resolve();
12280
12284
  let release;
12281
- const current = new Promise((resolve5) => {
12282
- release = resolve5;
12285
+ const current = new Promise((resolve6) => {
12286
+ release = resolve6;
12283
12287
  });
12284
- this.submissionLocks.set(key, current);
12288
+ this.submissionLocks.set(key2, current);
12285
12289
  await previous;
12286
12290
  try {
12287
12291
  return await action();
12288
12292
  } finally {
12289
12293
  release();
12290
- if (this.submissionLocks.get(key) === current) this.submissionLocks.delete(key);
12294
+ if (this.submissionLocks.get(key2) === current) this.submissionLocks.delete(key2);
12291
12295
  }
12292
12296
  }
12293
12297
  async dispatch(receipt, message) {
@@ -12443,7 +12447,7 @@ var ConnectorCore = class {
12443
12447
  isValidReceipt(value) {
12444
12448
  if (!isRecord(value)) return false;
12445
12449
  const receiptKeys = ["requestId", "principalHash", "machineId", "targetId", "workspace", "tool", "idempotencyHash", "requestKeyHash", "payloadHash", "state", "createdAt", "updatedAt", "errorCode", "result"];
12446
- if (Object.keys(value).some((key) => !receiptKeys.includes(key))) return false;
12450
+ if (Object.keys(value).some((key2) => !receiptKeys.includes(key2))) return false;
12447
12451
  return typeof value.requestId === "string" && value.requestId.length > 0 && value.requestId.length <= 256 && typeof value.principalHash === "string" && HASH_PATTERN.test(value.principalHash) && typeof value.machineId === "string" && value.machineId.length > 0 && value.machineId.length <= 512 && typeof value.targetId === "string" && value.targetId.length > 0 && value.targetId.length <= 256 && typeof value.workspace === "string" && value.workspace.length <= 2048 && (value.tool === "send_agent_message" || value.tool === "control_environment") && (value.result === void 0 || isRecord(value.result) && JSON.stringify(value.result).length <= 16384) && typeof value.idempotencyHash === "string" && HASH_PATTERN.test(value.idempotencyHash) && typeof value.requestKeyHash === "string" && HASH_PATTERN.test(value.requestKeyHash) && typeof value.payloadHash === "string" && HASH_PATTERN.test(value.payloadHash) && typeof value.state === "string" && RECEIPT_STATES.includes(value.state) && Number.isSafeInteger(value.createdAt) && Number.isSafeInteger(value.updatedAt) && value.updatedAt >= value.createdAt && (value.errorCode === void 0 || typeof value.errorCode === "string" && SAFE_RECEIPT_ERRORS.has(value.errorCode));
12448
12452
  }
12449
12453
  persist() {
@@ -12561,7 +12565,7 @@ async function loadCredentials(path = credentialsPath()) {
12561
12565
  if (typeof record.serverUrl !== "string" || typeof record.installationId !== "string" || typeof record.credential !== "string") {
12562
12566
  throw new ConfigError(`Credentials file ${path} is missing required fields.`, LOGIN_HINT);
12563
12567
  }
12564
- const optional = (key) => typeof record[key] === "string" && record[key] ? { [key]: record[key] } : {};
12568
+ const optional = (key2) => typeof record[key2] === "string" && record[key2] ? { [key2]: record[key2] } : {};
12565
12569
  return {
12566
12570
  serverUrl: record.serverUrl,
12567
12571
  installationId: record.installationId,
@@ -12583,29 +12587,34 @@ async function deleteCredentials(path = credentialsPath()) {
12583
12587
 
12584
12588
  // src/core/connector-config.ts
12585
12589
  import { readFile as readFile3 } from "node:fs/promises";
12590
+ var RUNTIMES = ["herdr", "herdr-core"];
12586
12591
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12587
- function rejectUnknown(record, allowed, where) {
12588
- const unknown = Object.keys(record).find((key) => !allowed.includes(key));
12589
- if (unknown) throw new ConfigError(`${where}: unknown field "${unknown}".`, `Allowed fields: ${allowed.join(", ")}.`);
12592
+ function rejectUnknown(record, allowed, where2) {
12593
+ const unknown = Object.keys(record).find((key2) => !allowed.includes(key2));
12594
+ if (unknown) throw new ConfigError(`${where2}: unknown field "${unknown}".`, `Allowed fields: ${allowed.join(", ")}.`);
12590
12595
  }
12591
- function stringField(record, key, where, max) {
12592
- const value = record[key];
12596
+ function stringField(record, key2, where2, max) {
12597
+ const value = record[key2];
12593
12598
  if (value === void 0) return void 0;
12594
- if (typeof value !== "string" || !value || value.length > max) throw new ConfigError(`${where}.${key} must be a non-empty string.`);
12599
+ if (typeof value !== "string" || !value || value.length > max) throw new ConfigError(`${where2}.${key2} must be a non-empty string.`);
12595
12600
  return value;
12596
12601
  }
12597
- function stringList(record, key, where) {
12598
- const value = record[key];
12602
+ function stringList(record, key2, where2) {
12603
+ const value = record[key2];
12599
12604
  if (value === void 0) return void 0;
12600
12605
  if (!Array.isArray(value) || value.length > 1e3 || value.some((item) => typeof item !== "string" || !item)) {
12601
- throw new ConfigError(`${where}.${key} must be an array of up to 1000 non-empty strings.`);
12606
+ throw new ConfigError(`${where2}.${key2} must be an array of up to 1000 non-empty strings.`);
12602
12607
  }
12603
12608
  return value;
12604
12609
  }
12605
12610
  function parseConnectorConfig(value, source = "connector config") {
12606
12611
  if (!isRecord2(value)) throw new ConfigError(`${source}: expected a JSON object.`);
12607
- rejectUnknown(value, ["allowedAgents", "allowedWorkspaces", "stateDirectory", "herdr", "enableWrites", "enableEnvironmentControl"], source);
12612
+ rejectUnknown(value, ["runtime", "allowedAgents", "allowedWorkspaces", "stateDirectory", "herdr", "herdrCore", "enableWrites", "enableEnvironmentControl"], source);
12608
12613
  const config = {};
12614
+ if (value.runtime !== void 0) {
12615
+ if (typeof value.runtime !== "string" || !RUNTIMES.includes(value.runtime)) throw new ConfigError(`${source}.runtime must be one of: ${RUNTIMES.join(", ")}.`);
12616
+ config.runtime = value.runtime;
12617
+ }
12609
12618
  const agents = stringList(value, "allowedAgents", source);
12610
12619
  if (agents) config.allowedAgents = agents;
12611
12620
  const workspaces = stringList(value, "allowedWorkspaces", source);
@@ -12625,9 +12634,9 @@ function parseConnectorConfig(value, source = "connector config") {
12625
12634
  if (!isRecord2(raw)) throw new ConfigError(`${source}.herdr must be an object.`);
12626
12635
  rejectUnknown(raw, ["socketPath", "schemaPath", "binary", "machineId", "timeoutMs"], `${source}.herdr`);
12627
12636
  const herdr2 = {};
12628
- for (const key of ["socketPath", "schemaPath", "binary", "machineId"]) {
12629
- const text2 = stringField(raw, key, `${source}.herdr`, 4e3);
12630
- if (text2) herdr2[key] = text2;
12637
+ for (const key2 of ["socketPath", "schemaPath", "binary", "machineId"]) {
12638
+ const text2 = stringField(raw, key2, `${source}.herdr`, 4e3);
12639
+ if (text2) herdr2[key2] = text2;
12631
12640
  }
12632
12641
  if (raw.timeoutMs !== void 0) {
12633
12642
  if (typeof raw.timeoutMs !== "number" || !Number.isInteger(raw.timeoutMs) || raw.timeoutMs < 100 || raw.timeoutMs > 12e4) {
@@ -12637,6 +12646,23 @@ function parseConnectorConfig(value, source = "connector config") {
12637
12646
  }
12638
12647
  config.herdr = herdr2;
12639
12648
  }
12649
+ if (value.herdrCore !== void 0) {
12650
+ const raw = value.herdrCore;
12651
+ if (!isRecord2(raw)) throw new ConfigError(`${source}.herdrCore must be an object.`);
12652
+ rejectUnknown(raw, ["binary", "machineId", "timeoutMs"], `${source}.herdrCore`);
12653
+ const core = {};
12654
+ for (const key2 of ["binary", "machineId"]) {
12655
+ const text2 = stringField(raw, key2, `${source}.herdrCore`, 4e3);
12656
+ if (text2) core[key2] = text2;
12657
+ }
12658
+ if (raw.timeoutMs !== void 0) {
12659
+ if (typeof raw.timeoutMs !== "number" || !Number.isInteger(raw.timeoutMs) || raw.timeoutMs < 100 || raw.timeoutMs > 12e4) {
12660
+ throw new ConfigError(`${source}.herdrCore.timeoutMs must be an integer from 100 to 120000.`);
12661
+ }
12662
+ core.timeoutMs = raw.timeoutMs;
12663
+ }
12664
+ config.herdrCore = core;
12665
+ }
12640
12666
  return config;
12641
12667
  }
12642
12668
  async function loadConnectorConfig(path, options = {}) {
@@ -12745,7 +12771,7 @@ async function runRemoteClient(core, credentials, options = {}) {
12745
12771
  });
12746
12772
  const reportActivity = options.onActivity ?? (() => {
12747
12773
  });
12748
- const sleep = options.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
12774
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
12749
12775
  const serverUrl = socketUrl(credentials.serverUrl);
12750
12776
  const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 75e3;
12751
12777
  let stopped = false;
@@ -12767,7 +12793,7 @@ async function runRemoteClient(core, credentials, options = {}) {
12767
12793
  try {
12768
12794
  limitReached = false;
12769
12795
  setConnectionState("connecting");
12770
- await new Promise((resolve5, reject) => {
12796
+ await new Promise((resolve6, reject) => {
12771
12797
  const socket = new wrapper_default(serverUrl, {
12772
12798
  headers: {
12773
12799
  Authorization: `Bearer ${credentials.credential}`,
@@ -12963,7 +12989,7 @@ async function runRemoteClient(core, credentials, options = {}) {
12963
12989
  code === 1008 || code === 4001 ? `remote authentication or policy rejected the connection (${code})` : `remote connection closed (${code})${reason.length ? `: ${reason.toString()}` : ""}`
12964
12990
  );
12965
12991
  if (current === socket) current = void 0;
12966
- resolve5();
12992
+ resolve6();
12967
12993
  });
12968
12994
  });
12969
12995
  } catch (error) {
@@ -13014,12 +13040,12 @@ var DeviceLoginError = class extends Error {
13014
13040
  var REQUEST_TIMEOUT_MS2 = 15e3;
13015
13041
  var MAX_BACKOFF_MS = 3e4;
13016
13042
  var SLOW_DOWN_STEP_S = 5;
13017
- var defaultSleep = (ms, signal) => new Promise((resolve5) => {
13018
- if (signal?.aborted) return resolve5();
13043
+ var defaultSleep = (ms, signal) => new Promise((resolve6) => {
13044
+ if (signal?.aborted) return resolve6();
13019
13045
  const done = () => {
13020
13046
  clearTimeout(timer);
13021
13047
  signal?.removeEventListener("abort", done);
13022
- resolve5();
13048
+ resolve6();
13023
13049
  };
13024
13050
  const timer = setTimeout(done, ms);
13025
13051
  signal?.addEventListener("abort", done, { once: true });
@@ -13088,8 +13114,8 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
13088
13114
  const base = enrollmentBase(serverUrl);
13089
13115
  const url = new URL("/api/device/token", base);
13090
13116
  const sleep = options.sleep ?? defaultSleep;
13091
- const now = options.now ?? Date.now;
13092
- const deadline = now() + code.expiresIn * 1e3;
13117
+ const now2 = options.now ?? Date.now;
13118
+ const deadline = now2() + code.expiresIn * 1e3;
13093
13119
  let interval = code.interval;
13094
13120
  let failures = 0;
13095
13121
  const expired = () => new DeviceLoginError("expired", "The code expired.");
@@ -13099,7 +13125,7 @@ async function pollDeviceToken(serverUrl, code, options = {}) {
13099
13125
  const wait = failures > 0 ? Math.min(MAX_BACKOFF_MS, interval * 1e3 * 2 ** failures) : interval * 1e3;
13100
13126
  await sleep(wait, options.signal);
13101
13127
  if (options.signal?.aborted) throw aborted();
13102
- if (now() >= deadline) throw expired();
13128
+ if (now2() >= deadline) throw expired();
13103
13129
  let result;
13104
13130
  try {
13105
13131
  result = await postJson(
@@ -13158,8 +13184,8 @@ var AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
13158
13184
  var NOTE_MAX_CHARS = 1024;
13159
13185
  var CHANNEL_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
13160
13186
  var PANE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
13161
- function eventFrame(name, data, now = /* @__PURE__ */ new Date()) {
13162
- return { type: "event", eventId: randomUUID2(), name, timestamp: now.toISOString(), data };
13187
+ function eventFrame(name, data, now2 = /* @__PURE__ */ new Date()) {
13188
+ return { type: "event", eventId: randomUUID2(), name, timestamp: now2.toISOString(), data };
13163
13189
  }
13164
13190
  function codePoints(text2) {
13165
13191
  return Array.from(text2).length;
@@ -13264,15 +13290,15 @@ var ConnectorEvents = class {
13264
13290
  if (!this.adapter.getCapabilities().readOutput) throw new ConnectError("unsupported_capability", "This connector does not share agent output, so notes are turned off.", "Use a runtime with output support.");
13265
13291
  const text2 = cleanNote(input.text);
13266
13292
  const channel = noteChannel(input.channel);
13267
- const agentId = input.agentId !== void 0 ? await this.explicitAgent(input.agentId) : await this.resolveAgent(input.paneId);
13293
+ const agentId2 = input.agentId !== void 0 ? await this.explicitAgent(input.agentId) : await this.resolveAgent(input.paneId) ?? await this.resolveAgent(input.terminalId);
13268
13294
  const echo = channel ? { channel } : {};
13269
- if (!this.send) return { sent: false, agentId, ...echo };
13295
+ if (!this.send) return { sent: false, agentId: agentId2, ...echo };
13270
13296
  this.refillNotes();
13271
13297
  if (this.noteTokens < 1) throw new ConnectError("rate_limited", `Too many notes: at most ${this.notesPerMinute} per minute.`, "Wait a minute, and send one note per important result.");
13272
13298
  this.noteTokens -= 1;
13273
- const frame = eventFrame("agent.notified", { agentId, text: text2, audience: "owner", ...echo });
13299
+ const frame = eventFrame("agent.notified", { agentId: agentId2, text: text2, audience: "owner", ...echo });
13274
13300
  const sent = this.send(frame);
13275
- return { sent, agentId, ...sent ? { eventId: frame.eventId } : {}, ...echo };
13301
+ return { sent, agentId: agentId2, ...sent ? { eventId: frame.eventId } : {}, ...echo };
13276
13302
  }
13277
13303
  async explicitAgent(value) {
13278
13304
  if (typeof value !== "string" || value.length < 1 || value.length > 256 || /[\x00-\x1f\x7f]/.test(value)) {
@@ -13296,50 +13322,50 @@ var ConnectorEvents = class {
13296
13322
  return null;
13297
13323
  }
13298
13324
  }
13299
- visible(agentId, workspace) {
13300
- if (this.allowedAgents && !this.allowedAgents.has(agentId)) return false;
13325
+ visible(agentId2, workspace) {
13326
+ if (this.allowedAgents && !this.allowedAgents.has(agentId2)) return false;
13301
13327
  if (this.allowedWorkspaces && (workspace === null || !this.allowedWorkspaces.has(workspace))) return false;
13302
13328
  return true;
13303
13329
  }
13304
- refill(now) {
13305
- this.tokens = Math.min(this.burst, this.tokens + (now - this.refilledAt) / 1e3 * this.ratePerSecond);
13306
- this.refilledAt = now;
13330
+ refill(now2) {
13331
+ this.tokens = Math.min(this.burst, this.tokens + (now2 - this.refilledAt) / 1e3 * this.ratePerSecond);
13332
+ this.refilledAt = now2;
13307
13333
  }
13308
13334
  refillNotes() {
13309
- const now = this.now();
13310
- this.noteTokens = Math.min(this.notesPerMinute, this.noteTokens + (now - this.noteRefilledAt) / 6e4 * this.notesPerMinute);
13311
- this.noteRefilledAt = now;
13335
+ const now2 = this.now();
13336
+ this.noteTokens = Math.min(this.notesPerMinute, this.noteTokens + (now2 - this.noteRefilledAt) / 6e4 * this.notesPerMinute);
13337
+ this.noteRefilledAt = now2;
13312
13338
  }
13313
13339
  flush() {
13314
13340
  const send = this.send;
13315
13341
  if (!send) return;
13316
- const now = this.now();
13317
- this.refill(now);
13342
+ const now2 = this.now();
13343
+ this.refill(now2);
13318
13344
  let next = Number.POSITIVE_INFINITY;
13319
13345
  if (this.listChanged) {
13320
13346
  const due = this.lastListSent + this.windowMs;
13321
- if (due > now) next = Math.min(next, due);
13347
+ if (due > now2) next = Math.min(next, due);
13322
13348
  else if (this.tokens >= 1) {
13323
13349
  this.tokens -= 1;
13324
13350
  this.listChanged = false;
13325
- this.lastListSent = now;
13351
+ this.lastListSent = now2;
13326
13352
  send(eventFrame("agents.changed", {}));
13327
13353
  }
13328
13354
  }
13329
- for (const [agentId, data] of this.pending) {
13330
- const due = (this.lastSent.get(agentId) ?? Number.NEGATIVE_INFINITY) + this.windowMs;
13331
- if (due > now) {
13355
+ for (const [agentId2, data] of this.pending) {
13356
+ const due = (this.lastSent.get(agentId2) ?? Number.NEGATIVE_INFINITY) + this.windowMs;
13357
+ if (due > now2) {
13332
13358
  next = Math.min(next, due);
13333
13359
  continue;
13334
13360
  }
13335
13361
  if (this.tokens < 1) break;
13336
13362
  this.tokens -= 1;
13337
- this.pending.delete(agentId);
13338
- this.lastSent.set(agentId, now);
13363
+ this.pending.delete(agentId2);
13364
+ this.lastSent.set(agentId2, now2);
13339
13365
  send(eventFrame("agent.status_changed", data));
13340
13366
  }
13341
- for (const [agentId, at] of this.lastSent) if (at + this.windowMs <= now && !this.pending.has(agentId)) this.lastSent.delete(agentId);
13342
- if ((this.pending.size > 0 || this.listChanged) && this.tokens < 1) next = Math.min(next, now + Math.ceil((1 - this.tokens) / this.ratePerSecond * 1e3));
13367
+ for (const [agentId2, at] of this.lastSent) if (at + this.windowMs <= now2 && !this.pending.has(agentId2)) this.lastSent.delete(agentId2);
13368
+ if ((this.pending.size > 0 || this.listChanged) && this.tokens < 1) next = Math.min(next, now2 + Math.ceil((1 - this.tokens) / this.ratePerSecond * 1e3));
13343
13369
  this.schedule(next);
13344
13370
  }
13345
13371
  schedule(at) {
@@ -13464,17 +13490,17 @@ function herdrBinary(env, platform = process.platform) {
13464
13490
  return env.HERDR_BIN_PATH || (platform === "win32" ? "herdr.exe" : "herdr");
13465
13491
  }
13466
13492
  function createHerdrRunner(env) {
13467
- return (args, options) => new Promise((resolve5) => {
13493
+ return (args, options) => new Promise((resolve6) => {
13468
13494
  execFile(
13469
13495
  herdrBinary(env),
13470
13496
  args,
13471
13497
  { env, timeout: options?.timeoutMs ?? 6e4, windowsHide: true, maxBuffer: 4 * 1024 * 1024, shell: false },
13472
13498
  (error, stdout, stderr) => {
13473
- if (!error) return resolve5({ code: 0, stdout, stderr });
13499
+ if (!error) return resolve6({ code: 0, stdout, stderr });
13474
13500
  const failure = error;
13475
- if (failure.code === "ENOENT") return resolve5({ code: 127, stdout: "", stderr: failure.message, notFound: true });
13501
+ if (failure.code === "ENOENT") return resolve6({ code: 127, stdout: "", stderr: failure.message, notFound: true });
13476
13502
  const code = typeof failure.code === "number" ? failure.code : 1;
13477
- resolve5({ code, stdout: stdout ?? "", stderr: stderr || (failure.killed ? "timed out" : failure.message) });
13503
+ resolve6({ code, stdout: stdout ?? "", stderr: stderr || (failure.killed ? "timed out" : failure.message) });
13478
13504
  }
13479
13505
  );
13480
13506
  });
@@ -13557,27 +13583,27 @@ function cmdQuote(arg) {
13557
13583
  if (/["%^&|<>!\r\n]/.test(arg)) throw new Error(`Refusing to pass an unsafe argument to the shell: ${arg}`);
13558
13584
  return `"${arg}"`;
13559
13585
  }
13560
- var execProgram = (file, args, options = {}) => new Promise((resolve5) => {
13586
+ var execProgram = (file, args, options = {}) => new Promise((resolve6) => {
13561
13587
  const viaShell = process.platform === "win32" && !/[\\/]/.test(file) && !/\.exe$/i.test(file);
13562
13588
  let child;
13563
13589
  try {
13564
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 });
13565
13591
  } catch (error) {
13566
- resolve5({ code: 1, stdout: "", stderr: error.message });
13592
+ resolve6({ code: 1, stdout: "", stderr: error.message });
13567
13593
  return;
13568
13594
  }
13569
13595
  let stdout = "";
13570
13596
  let stderr = "";
13571
13597
  let settled = false;
13572
- const finish = (result) => {
13598
+ const finish2 = (result) => {
13573
13599
  if (settled) return;
13574
13600
  settled = true;
13575
13601
  clearTimeout(timer);
13576
- resolve5(result);
13602
+ resolve6(result);
13577
13603
  };
13578
13604
  const timer = setTimeout(() => {
13579
13605
  child.kill();
13580
- finish({ code: 1, stdout, stderr: `${stderr}
13606
+ finish2({ code: 1, stdout, stderr: `${stderr}
13581
13607
  timed out` });
13582
13608
  }, options.timeoutMs ?? 3e5);
13583
13609
  child.stdout.setEncoding("utf8").on("data", (chunk) => {
@@ -13588,10 +13614,10 @@ timed out` });
13588
13614
  stderr += chunk;
13589
13615
  options.onStderr?.(chunk);
13590
13616
  });
13591
- child.once("error", (error) => finish({ code: 127, stdout, stderr: error.message, notFound: error.code === "ENOENT" }));
13617
+ child.once("error", (error) => finish2({ code: 127, stdout, stderr: error.message, notFound: error.code === "ENOENT" }));
13592
13618
  child.once("close", (code) => {
13593
- if (viaShell && code === 9009) return finish({ code: 127, stdout, stderr: stderr || `${file} was not found`, notFound: true });
13594
- finish({ code: code ?? 1, stdout, stderr });
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 });
13595
13621
  });
13596
13622
  });
13597
13623
 
@@ -13780,6 +13806,591 @@ function printMcpHint(ctx, serverUrl) {
13780
13806
  ctx.out.print(s.dim(`Claude Code: claude mcp add --transport http peerband ${url}`));
13781
13807
  }
13782
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
+
13783
14394
  // src/cli/commands/channels.ts
13784
14395
  var NO_CHANNEL_SUPPORT = "This PeerBand server doesn't support channels yet.";
13785
14396
  var TELEGRAM_CHANNEL = "telegram";
@@ -13848,7 +14459,7 @@ var spec = {
13848
14459
  // herdr/relay-tab.mjs
13849
14460
  import { execFile as execFile2 } from "node:child_process";
13850
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";
13851
- import { randomUUID as randomUUID3 } from "node:crypto";
14462
+ import { randomUUID as randomUUID4 } from "node:crypto";
13852
14463
  import { dirname as dirname4 } from "node:path";
13853
14464
 
13854
14465
  // herdr/paths.mjs
@@ -13946,7 +14557,7 @@ async function readRecord(statePath) {
13946
14557
  }
13947
14558
  async function writeRecord(statePath, record) {
13948
14559
  await mkdir4(dirname4(statePath), { recursive: true });
13949
- const temporary = `${statePath}.${randomUUID3()}.tmp`;
14560
+ const temporary = `${statePath}.${randomUUID4()}.tmp`;
13950
14561
  try {
13951
14562
  await writeFile4(temporary, JSON.stringify(record), { encoding: "utf8", mode: 384, flag: "wx" });
13952
14563
  await rename3(temporary, statePath);
@@ -13969,7 +14580,7 @@ async function withLaunchLock(statePath, action) {
13969
14580
  try {
13970
14581
  const info = await stat(lockPath3);
13971
14582
  if (Date.now() - info.mtimeMs > 12e4) {
13972
- const quarantine = `${lockPath3}.stale-${randomUUID3()}`;
14583
+ const quarantine = `${lockPath3}.stale-${randomUUID4()}`;
13973
14584
  await rename3(lockPath3, quarantine).then(() => rmdir2(quarantine)).catch(() => {
13974
14585
  });
13975
14586
  stale = true;
@@ -13979,7 +14590,7 @@ async function withLaunchLock(statePath, action) {
13979
14590
  }
13980
14591
  if (stale) continue;
13981
14592
  if (Date.now() >= deadline) throw new Error("Another PeerBand Relay tab launch is already in progress");
13982
- await new Promise((resolve5) => setTimeout(resolve5, 100));
14593
+ await new Promise((resolve6) => setTimeout(resolve6, 100));
13983
14594
  }
13984
14595
  }
13985
14596
  try {
@@ -14024,7 +14635,7 @@ async function renameOwnedSinglePaneTab(run3, pane, label) {
14024
14635
  await run3(["tab", "rename", pane.tab_id, label]);
14025
14636
  return true;
14026
14637
  }
14027
- function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker = randomUUID3, warn = () => {
14638
+ function createRelayTabController({ run: run3, statePath, pluginPaneId = "", newMarker = randomUUID4, warn = () => {
14028
14639
  } }) {
14029
14640
  if (typeof run3 !== "function" || typeof statePath !== "string") throw new TypeError("run and statePath are required");
14030
14641
  const lastVerifiedTitle = /* @__PURE__ */ new Map();
@@ -14036,10 +14647,10 @@ function createRelayTabController({ run: run3, statePath, pluginPaneId = "", new
14036
14647
  if (!pane) return false;
14037
14648
  try {
14038
14649
  const label = tabTitle(enabled);
14039
- const key = `${pane.pane_id}\0${pane.tab_id}`;
14040
- if (lastVerifiedTitle.get(key) === label) return true;
14650
+ const key2 = `${pane.pane_id}\0${pane.tab_id}`;
14651
+ if (lastVerifiedTitle.get(key2) === label) return true;
14041
14652
  const renamed = await renameOwnedSinglePaneTab(run3, pane, label);
14042
- if (renamed) lastVerifiedTitle.set(key, label);
14653
+ if (renamed) lastVerifiedTitle.set(key2, label);
14043
14654
  return renamed;
14044
14655
  } catch {
14045
14656
  return false;
@@ -14158,7 +14769,7 @@ function paneLabel(snapshot) {
14158
14769
 
14159
14770
  // herdr/stale-lock.mjs
14160
14771
  import { execFile as execFile3 } from "node:child_process";
14161
- import { randomUUID as randomUUID4 } from "node:crypto";
14772
+ import { randomUUID as randomUUID5 } from "node:crypto";
14162
14773
  import { readdir, readFile as readFile5, rename as rename4, rm as rm4, stat as stat2, writeFile as writeFile5 } from "node:fs/promises";
14163
14774
  import { createConnection } from "node:net";
14164
14775
  import { hostname as hostname2 } from "node:os";
@@ -14176,24 +14787,24 @@ function pidAlive2(pid) {
14176
14787
  }
14177
14788
  }
14178
14789
  function probeChannel(channel, timeout = 1500) {
14179
- return new Promise((resolve5) => {
14790
+ return new Promise((resolve6) => {
14180
14791
  let settled = false;
14181
14792
  const socket = createConnection(channel);
14182
- const finish = (value) => {
14793
+ const finish2 = (value) => {
14183
14794
  if (settled) return;
14184
14795
  settled = true;
14185
14796
  clearTimeout(timer);
14186
14797
  socket.destroy();
14187
- resolve5(value);
14798
+ resolve6(value);
14188
14799
  };
14189
- const timer = setTimeout(() => finish("unknown"), timeout);
14190
- socket.once("connect", () => finish("listening"));
14191
- socket.once("error", (error) => finish(error && (error.code === "ENOENT" || error.code === "ECONNREFUSED") ? "absent" : "unknown"));
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"));
14192
14803
  });
14193
14804
  }
14194
14805
  function run(file, args, timeout) {
14195
- return new Promise((resolve5) => {
14196
- execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve5(error ? null : String(stdout)));
14806
+ return new Promise((resolve6) => {
14807
+ execFile3(file, args, { timeout, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve6(error ? null : String(stdout)));
14197
14808
  });
14198
14809
  }
14199
14810
  async function listProcesses(platform = process.platform) {
@@ -14249,7 +14860,7 @@ async function readOwner(ownerFile) {
14249
14860
  }
14250
14861
  return { text: text2, owner: {} };
14251
14862
  }
14252
- 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() }) {
14253
14864
  let info;
14254
14865
  try {
14255
14866
  info = await stat2(lockDir);
@@ -14278,7 +14889,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
14278
14889
  }
14279
14890
  return { state: "live", reason: `owner process ${pid} is running`, ownerText: text2, pid };
14280
14891
  }
14281
- if (text2 === null && now - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
14892
+ if (text2 === null && now2 - info.mtimeMs < CREATION_GRACE_MS) return { state: "live", reason: "the lock is being created", ownerText: null };
14282
14893
  if (channel) {
14283
14894
  const probed = await probe(channel);
14284
14895
  if (probed === "listening") return { state: "live", reason: "a helper answers on the control channel", ownerText: text2 };
@@ -14293,7 +14904,7 @@ async function inspectLock({ lockDir, ownerFile, channel, processPattern, exclud
14293
14904
  return { state: "stale", reason: "no matching process is running", ownerText: text2 };
14294
14905
  }
14295
14906
  async function reclaimLock({ lockDir, ownerFile, expectedOwnerText }) {
14296
- const quarantine = `${lockDir}.stale-${randomUUID4()}`;
14907
+ const quarantine = `${lockDir}.stale-${randomUUID5()}`;
14297
14908
  try {
14298
14909
  await rename4(lockDir, quarantine);
14299
14910
  } catch (error) {
@@ -14353,31 +14964,31 @@ var FIELDS2 = ["workspace_id", "tab_id", "pane_id", "name", "label", "cwd", "age
14353
14964
  function metadata(value) {
14354
14965
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
14355
14966
  const row = value;
14356
- const result = Object.fromEntries(FIELDS2.filter((key) => typeof row[key] === "string").map((key) => [key.replace(/_([a-z])/g, (_, c) => c.toUpperCase()), sanitizeOutput(row[key], { bytes: key === "cwd" ? 2048 : 256, lines: 1 }).text]));
14357
- for (const key of ["number", "pane_count", "tab_count"]) if (Number.isSafeInteger(row[key]) && row[key] >= 0) result[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = row[key];
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];
14358
14969
  if (typeof row.focused === "boolean") result.focused = row.focused;
14359
14970
  return result;
14360
14971
  }
14361
14972
  function environmentMetadata(value) {
14362
14973
  const row = value && typeof value === "object" ? value : {};
14363
14974
  const result = metadata(row);
14364
- for (const key of ["workspace", "tab", "pane", "root_pane", "agent"]) {
14365
- if (row[key] && typeof row[key] === "object") result[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = metadata(row[key]);
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]);
14366
14977
  }
14367
14978
  return result;
14368
14979
  }
14369
14980
  async function listEnvironment(client) {
14370
14981
  const result = { actions: [...ENVIRONMENT_ACTIONS] };
14371
- for (const [method, key] of [["workspace.list", "workspaces"], ["tab.list", "tabs"], ["pane.list", "panes"]]) {
14982
+ for (const [method, key2] of [["workspace.list", "workspaces"], ["tab.list", "tabs"], ["pane.list", "panes"]]) {
14372
14983
  const response = await client.request(method, {});
14373
- if (!Array.isArray(response[key])) throw new ConnectError("schema_mismatch", `Unexpected ${method} response.`, "Check the installed Herdr schema.");
14374
- let rows = response[key];
14375
- if (key === "panes") {
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") {
14376
14987
  const listed = await client.request("agent.list", {});
14377
14988
  rows = rows.map((pane) => ({ ...pane, name: listed.agents?.find((agent) => agent.pane_id === pane.pane_id)?.name }));
14378
14989
  }
14379
- result[key] = rows.slice(0, 50).map(metadata);
14380
- result[`${key}Truncated`] = response[key].length > 50;
14990
+ result[key2] = rows.slice(0, 50).map(metadata);
14991
+ result[`${key2}Truncated`] = response[key2].length > 50;
14381
14992
  }
14382
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.");
14383
14994
  return result;
@@ -14385,9 +14996,9 @@ async function listEnvironment(client) {
14385
14996
  function environmentParams(input) {
14386
14997
  const command = environmentCommand(input);
14387
14998
  const params = {};
14388
- for (const [key, value] of Object.entries(command)) {
14389
- if (key === "action") continue;
14390
- params[key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = value;
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;
14391
15002
  }
14392
15003
  if (["workspace.create", "tab.create", "pane.split"].includes(command.action)) params.focus = false;
14393
15004
  if (command.action === "pane.split") {
@@ -14404,28 +15015,28 @@ function environmentParams(input) {
14404
15015
  }
14405
15016
 
14406
15017
  // src/runtime-herdr/adapter.ts
14407
- import { createHash as createHash4, randomUUID as randomUUID7 } from "node:crypto";
15018
+ import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
14408
15019
  import { readFile as readFile7, stat as stat3 } from "node:fs/promises";
14409
15020
  import { homedir as homedir3 } from "node:os";
14410
15021
  import { join as join6 } from "node:path";
14411
15022
 
14412
15023
  // src/runtime-herdr/subscription.ts
14413
- import { randomUUID as randomUUID5 } from "node:crypto";
15024
+ import { randomUUID as randomUUID6 } from "node:crypto";
14414
15025
  import { createConnection as createConnection2 } from "node:net";
14415
15026
  function openSubscription(options) {
14416
- const id = `sub_${randomUUID5()}`;
15027
+ const id = `sub_${randomUUID6()}`;
14417
15028
  const request = { id, method: "events.subscribe", params: { subscriptions: options.subscriptions } };
14418
15029
  const maxLineBytes = options.maxLineBytes ?? 1024 * 1024;
14419
15030
  let acknowledged = false;
14420
15031
  let resolveStarted;
14421
15032
  let rejectStarted;
14422
15033
  let resolveClosed;
14423
- const started = new Promise((resolve5, reject) => {
14424
- resolveStarted = resolve5;
15034
+ const started = new Promise((resolve6, reject) => {
15035
+ resolveStarted = resolve6;
14425
15036
  rejectStarted = reject;
14426
15037
  });
14427
- const closed = new Promise((resolve5) => {
14428
- resolveClosed = resolve5;
15038
+ const closed = new Promise((resolve6) => {
15039
+ resolveClosed = resolve6;
14429
15040
  });
14430
15041
  void started.catch(() => void 0);
14431
15042
  if (options.validateRequest && !options.validateRequest(request)) {
@@ -14518,8 +15129,8 @@ var HerdrEventBridge = class {
14518
15129
  constructor(host, options = {}) {
14519
15130
  this.host = host;
14520
15131
  this.log = options.log ?? (() => void 0);
14521
- this.sleep = options.sleep ?? ((ms) => new Promise((resolve5) => {
14522
- const timer = setTimeout(resolve5, ms);
15132
+ this.sleep = options.sleep ?? ((ms) => new Promise((resolve6) => {
15133
+ const timer = setTimeout(resolve6, ms);
14523
15134
  timer.unref?.();
14524
15135
  }));
14525
15136
  this.random = options.random ?? Math.random;
@@ -14638,8 +15249,8 @@ var HerdrEventBridge = class {
14638
15249
  }
14639
15250
  }
14640
15251
  async pause(ms) {
14641
- await Promise.race([this.sleep(ms), new Promise((resolve5) => {
14642
- this.wake = resolve5;
15252
+ await Promise.race([this.sleep(ms), new Promise((resolve6) => {
15253
+ this.wake = resolve6;
14643
15254
  })]);
14644
15255
  this.wake = void 0;
14645
15256
  }
@@ -14715,7 +15326,7 @@ function sameSet(a, b) {
14715
15326
  }
14716
15327
 
14717
15328
  // src/runtime-herdr/socket-client.ts
14718
- import { randomUUID as randomUUID6 } from "node:crypto";
15329
+ import { randomUUID as randomUUID7 } from "node:crypto";
14719
15330
  import { createConnection as createConnection3 } from "node:net";
14720
15331
  var HerdrSocketClient = class {
14721
15332
  socketPath;
@@ -14748,7 +15359,7 @@ var HerdrSocketClient = class {
14748
15359
  async request(method, params = {}) {
14749
15360
  if (this.closed) throw this.unavailable("Herdr socket client is closed");
14750
15361
  if (this.inflight >= this.maxPending) throw this.unavailable("Too many Herdr requests are in flight");
14751
- const id = randomUUID6();
15362
+ const id = randomUUID7();
14752
15363
  const request = { id, method, params };
14753
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.");
14754
15365
  const line = Buffer.from(`${JSON.stringify(request)}
@@ -14762,7 +15373,7 @@ var HerdrSocketClient = class {
14762
15373
  this.inflight -= 1;
14763
15374
  throw error;
14764
15375
  }
14765
- return new Promise((resolve5, reject) => {
15376
+ return new Promise((resolve6, reject) => {
14766
15377
  const timer = setTimeout(() => {
14767
15378
  this.pending.delete(id);
14768
15379
  this.inflight -= 1;
@@ -14770,7 +15381,7 @@ var HerdrSocketClient = class {
14770
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."));
14771
15382
  }, this.timeoutMs);
14772
15383
  timer.unref?.();
14773
- this.pending.set(id, { resolve: resolve5, reject, timer, method, socket });
15384
+ this.pending.set(id, { resolve: resolve6, reject, timer, method, socket });
14774
15385
  socket.write(line, (error) => {
14775
15386
  if (!error) return;
14776
15387
  const pending = this.pending.get(id);
@@ -14786,13 +15397,13 @@ var HerdrSocketClient = class {
14786
15397
  async close() {
14787
15398
  this.closed = true;
14788
15399
  this.failAll(this.unavailable("Herdr socket client closed"));
14789
- await Promise.all([...this.sockets].map((socket) => new Promise((resolve5) => {
14790
- if (socket.destroyed) resolve5();
14791
- else socket.end(resolve5);
15400
+ await Promise.all([...this.sockets].map((socket) => new Promise((resolve6) => {
15401
+ if (socket.destroyed) resolve6();
15402
+ else socket.end(resolve6);
14792
15403
  })));
14793
15404
  }
14794
15405
  connect() {
14795
- return new Promise((resolve5, reject) => {
15406
+ return new Promise((resolve6, reject) => {
14796
15407
  const socket = createConnection3(this.socketPath);
14797
15408
  const onError = () => {
14798
15409
  socket.destroy();
@@ -14813,7 +15424,7 @@ var HerdrSocketClient = class {
14813
15424
  this.buffers.delete(socket);
14814
15425
  this.failSocket(socket, this.unavailable("Herdr closed the socket before replying"));
14815
15426
  });
14816
- resolve5(socket);
15427
+ resolve6(socket);
14817
15428
  });
14818
15429
  });
14819
15430
  }
@@ -15036,7 +15647,7 @@ var HerdrAdapter = class {
15036
15647
  if (!isAgent(raw)) throw this.schemaMismatch("agent.list contained an invalid agent record");
15037
15648
  const fingerprint = identityFingerprint(raw);
15038
15649
  const previous = !reconnected ? previousTargets.find((item) => item.fingerprint === fingerprint) : void 0;
15039
- const id = previous?.id ?? `herdr_${randomUUID7()}`;
15650
+ const id = previous?.id ?? `herdr_${randomUUID8()}`;
15040
15651
  const live = { id, fingerprint, agent: raw };
15041
15652
  next.set(raw.pane_id, live);
15042
15653
  nextIds.add(id);
@@ -15149,7 +15760,7 @@ var HerdrAdapter = class {
15149
15760
  async controlEnvironment(command) {
15150
15761
  const params = environmentParams(command);
15151
15762
  const { schema, client } = await this.initialize();
15152
- const request = { id: randomUUID7(), method: command.action, params };
15763
+ const request = { id: randomUUID8(), method: command.action, params };
15153
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.");
15154
15765
  const result = asObject(await client.request(command.action, params));
15155
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;
@@ -15206,12 +15817,12 @@ async function readLayout(client) {
15206
15817
  ]);
15207
15818
  return { spaces, tabs };
15208
15819
  }
15209
- function layoutEntries(result, type, key, idKey) {
15820
+ function layoutEntries(result, type, key2, idKey) {
15210
15821
  const entries = /* @__PURE__ */ new Map();
15211
15822
  if (!result || typeof result !== "object") return entries;
15212
15823
  const value = result;
15213
- if (value.type !== type || !Array.isArray(value[key])) return entries;
15214
- for (const item of value[key]) {
15824
+ if (value.type !== type || !Array.isArray(value[key2])) return entries;
15825
+ for (const item of value[key2]) {
15215
15826
  if (!item || typeof item !== "object") continue;
15216
15827
  const row = item;
15217
15828
  if (typeof row[idKey] !== "string") continue;
@@ -15309,6 +15920,597 @@ async function readEndpointMarker(socketPath) {
15309
15920
  }
15310
15921
  }
15311
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
+
15312
16514
  // src/cli/commands/connect.ts
15313
16515
  function clock(date = /* @__PURE__ */ new Date()) {
15314
16516
  return date.toTimeString().slice(0, 8);
@@ -15345,10 +16547,10 @@ function activityLine(s, activity, at = /* @__PURE__ */ new Date()) {
15345
16547
  var spec2 = {
15346
16548
  name: "connect",
15347
16549
  summary: "Run the connector in the foreground",
15348
- usage: "peerband connect [--runtime herdr|mock] [--read-only] [--config PATH] [--server URL]",
15349
- description: 'Connects this machine to PeerBand and serves agent requests from your MCP clients until you press Ctrl+C. MCP clients may send messages to agents by default, but only after you approve the agents:message consent when you connect them; pass --read-only (or set "enableWrites": false in connector.json) to make this machine read-only. Activity lines show metadata only (tool, target, outcome, latency), never message or output content. Most people use `peerband relay` instead, which runs the connector inside Herdr.',
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.',
15350
16552
  options: [
15351
- { name: "runtime", type: "string", valueName: "herdr|mock", description: 'Agent runtime. Default: $PEERBAND_RUNTIME or herdr. "mock" serves fake agents for testing.' },
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.' },
15352
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.' },
15353
16555
  { name: "enable-environment-control", type: "boolean", description: "Redundant: environment controls are on by default. Kept so old scripts keep working." },
15354
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).' },
@@ -15360,6 +16562,7 @@ var spec2 = {
15360
16562
  examples: [
15361
16563
  ["peerband connect", "Serve until Ctrl+C; messages to agents are allowed (with OAuth consent)"],
15362
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"],
15363
16566
  ["peerband connect --runtime mock", "Try the connection with fake agents"]
15364
16567
  ],
15365
16568
  async run(parsed, ctx) {
@@ -15382,7 +16585,7 @@ function notifyRequest(message) {
15382
16585
  if (!message || typeof message !== "object" || Array.isArray(message)) return void 0;
15383
16586
  const value = message;
15384
16587
  if (value.type !== "peerband:notify" && value.type !== "peerband:notify-agent" || typeof value.id !== "string" || value.id.length > 128) return void 0;
15385
- return { id: value.id, text: value.text, paneId: value.paneId, ...value.type === "peerband:notify-agent" ? { agentId: value.agentId ?? null } : {}, channel: value.channel };
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 };
15386
16589
  }
15387
16590
  function startMockStatusCycle(adapter, env) {
15388
16591
  const interval = Number(env.PEERBAND_MOCK_STATUS_INTERVAL_MS);
@@ -15406,18 +16609,19 @@ function isShutdownMessage(message) {
15406
16609
  return Boolean(message) && typeof message === "object" && !Array.isArray(message) && Object.keys(message).length === 1 && message.type === "peerband:shutdown";
15407
16610
  }
15408
16611
  async function connect(options, ctx) {
15409
- const runtime = options.runtime ?? ctx.env.PEERBAND_RUNTIME ?? "herdr";
15410
- if (runtime !== "herdr" && runtime !== "mock") throw new UsageError(`Unknown runtime "${runtime}".`, "Use --runtime herdr or --runtime mock.");
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.");
15411
16614
  const credentials = await requireCredentials(ctx);
15412
16615
  if (options.server) credentials.serverUrl = validateServerUrl(options.server);
15413
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.");
15414
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.");
15415
16618
  const config = await loadMachineConnectorConfig(ctx, options.config);
16619
+ const runtime = requested ?? config.runtime ?? "herdr";
15416
16620
  const enableWrites = writesEnabled(config, { readOnly: options.readOnly, enableWrites: options.enableWrites });
15417
16621
  const managed = Boolean(options.managed);
15418
16622
  const s = ctx.out.stderr;
15419
16623
  const machine = describeMachine(credentials);
15420
- 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 ?? {});
15421
16625
  const core = new ConnectorCore(adapter, {
15422
16626
  writesEnabled: enableWrites,
15423
16627
  environmentControlEnabled: environmentControlEnabled(config, { disable: options.disableEnvironmentControl, enable: options.enableEnvironmentControl }),
@@ -15534,11 +16738,11 @@ async function connect(options, ctx) {
15534
16738
  // src/cli/commands/herdr.ts
15535
16739
  import { mkdir as mkdir5, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
15536
16740
  import { statSync } from "node:fs";
15537
- import { join as join9, resolve as resolve4 } from "node:path";
16741
+ import { join as join10, resolve as resolve4 } from "node:path";
15538
16742
 
15539
16743
  // src/cli/commands/herdr-check.ts
15540
16744
  import { readFile as readFile8, stat as stat4 } from "node:fs/promises";
15541
- import { join as join7 } from "node:path";
16745
+ import { join as join8 } from "node:path";
15542
16746
  var PLUGIN_ID = "peerband";
15543
16747
  var REPAIR_COMMAND = "peerband herdr install";
15544
16748
  var UPDATE_COMMAND = "peerband update";
@@ -15560,7 +16764,7 @@ async function readSettings(ctx) {
15560
16764
  const configDir = dir.code === 0 ? dir.stdout.trim() : "";
15561
16765
  if (!configDir) return null;
15562
16766
  try {
15563
- const value = JSON.parse(await readFile8(join7(configDir, "settings.json"), "utf8"));
16767
+ const value = JSON.parse(await readFile8(join8(configDir, "settings.json"), "utf8"));
15564
16768
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
15565
16769
  } catch {
15566
16770
  return null;
@@ -15636,7 +16840,7 @@ function installCommand(target) {
15636
16840
  return target.kind === "local" ? `herdr plugin link ${target.dir}` : `herdr plugin install ${target.source} --ref ${target.ref} --yes`;
15637
16841
  }
15638
16842
  async function herdrRetrying(ctx, args, timeoutMs) {
15639
- const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
16843
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
15640
16844
  let result = await ctx.runHerdr(args, { timeoutMs });
15641
16845
  for (const delay of RETRY_DELAYS_MS) {
15642
16846
  if (result.code === 0 || result.notFound || !RETRYABLE.test(failureDetail(result))) return result;
@@ -15710,7 +16914,7 @@ async function replacePlugin(ctx, previousSource, installed, target) {
15710
16914
 
15711
16915
  // src/cli/relay-maint.ts
15712
16916
  import { rm as rm5 } from "node:fs/promises";
15713
- import { join as join8 } from "node:path";
16917
+ import { join as join9 } from "node:path";
15714
16918
 
15715
16919
  // src/cli/control.ts
15716
16920
  import { readFile as readFile9 } from "node:fs/promises";
@@ -15727,7 +16931,7 @@ var ControlUnavailable = class extends Error {
15727
16931
  reason;
15728
16932
  };
15729
16933
  async function requestNotify(note, env, timeoutMs = 8e3) {
15730
- return exchange({ command: note.agentId !== void 0 ? "notify-agent" : "notify", text: note.text, ...note.agentId !== void 0 ? { agentId: note.agentId } : {}, ...note.paneId ? { paneId: note.paneId } : {}, ...note.channel ? { channel: note.channel } : {} }, env, timeoutMs, true);
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);
15731
16935
  }
15732
16936
  async function exchange(payload, env, timeoutMs, typed = false) {
15733
16937
  const config = configHome({ env });
@@ -15740,20 +16944,20 @@ async function exchange(payload, env, timeoutMs, typed = false) {
15740
16944
  }
15741
16945
  if (typeof record.token !== "string") throw typed ? new ControlUnavailable("not-running", "Invalid helper record") : new Error("Invalid helper record");
15742
16946
  const socket = createConnection4(controlChannel2(config));
15743
- return new Promise((resolve5, reject) => {
16947
+ return new Promise((resolve6, reject) => {
15744
16948
  let text2 = "";
15745
16949
  let settled = false;
15746
- const finish = (error, value) => {
16950
+ const finish2 = (error, value) => {
15747
16951
  if (settled) return;
15748
16952
  settled = true;
15749
16953
  clearTimeout(timer);
15750
16954
  socket.destroy();
15751
16955
  if (error) reject(error);
15752
- else resolve5(value ?? {});
16956
+ else resolve6(value ?? {});
15753
16957
  };
15754
16958
  let connected = false;
15755
- const timer = setTimeout(() => finish(typed ? new ControlUnavailable("timeout", "Helper control timeout") : new Error("Helper control timeout")), timeoutMs);
15756
- socket.once("error", (error) => finish(typed ? new ControlUnavailable(connected ? "closed" : "not-running", error.message) : 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));
15757
16961
  socket.once("connect", () => {
15758
16962
  connected = true;
15759
16963
  socket.write(`${JSON.stringify({ token: record.token, ...payload })}
@@ -15761,16 +16965,16 @@ async function exchange(payload, env, timeoutMs, typed = false) {
15761
16965
  });
15762
16966
  socket.on("data", (chunk) => {
15763
16967
  text2 += chunk.toString();
15764
- if (text2.length > 65536) return finish(new Error("Invalid control response"));
16968
+ if (text2.length > 65536) return finish2(new Error("Invalid control response"));
15765
16969
  const newline = text2.indexOf("\n");
15766
16970
  if (newline < 0) return;
15767
16971
  try {
15768
- finish(void 0, JSON.parse(text2.slice(0, newline)));
16972
+ finish2(void 0, JSON.parse(text2.slice(0, newline)));
15769
16973
  } catch (error) {
15770
- finish(error);
16974
+ finish2(error);
15771
16975
  }
15772
16976
  });
15773
- socket.once("end", () => finish(typed ? new ControlUnavailable("closed", "Helper control closed") : new Error("Helper control closed")));
16977
+ socket.once("end", () => finish2(typed ? new ControlUnavailable("closed", "Helper control closed") : new Error("Helper control closed")));
15774
16978
  });
15775
16979
  }
15776
16980
  async function relaySnapshot(env) {
@@ -15798,7 +17002,7 @@ async function stopRelay(env) {
15798
17002
  // src/cli/relay-maint.ts
15799
17003
  var RELAY_MARKER = "peerband_relay";
15800
17004
  var RELAY_LABEL = /^PeerBand Relay\b/;
15801
- var defaultSleep2 = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
17005
+ var defaultSleep2 = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
15802
17006
  var sleeper = (ctx) => ctx.sleep ?? defaultSleep2;
15803
17007
  async function relayRunning(ctx) {
15804
17008
  const snapshot = await relaySnapshot(ctx.env);
@@ -15863,7 +17067,7 @@ async function cleanRelayState(ctx, options = {}) {
15863
17067
  if (helper.reclaimed) report2.reclaimed.push(lockPath({ env: ctx.env }));
15864
17068
  else if (helper.verdict.state === "live") report2.held.push({ lock: lockPath({ env: ctx.env }), reason: helper.verdict.reason });
15865
17069
  const receiptsLock = `${receiptsPath({ env: ctx.env })}.lock`;
15866
- const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile: join8(receiptsLock, "owner"), processPattern: CONNECTOR_PATTERN2 });
17070
+ const receipts = await reclaimIfStale2({ lockDir: receiptsLock, ownerFile: join9(receiptsLock, "owner"), processPattern: CONNECTOR_PATTERN2 });
15867
17071
  if (receipts.reclaimed) report2.reclaimed.push(receiptsLock);
15868
17072
  else if (receipts.verdict.state === "live") report2.held.push({ lock: receiptsLock, reason: receipts.verdict.reason });
15869
17073
  const helperGone = helper.verdict.state !== "live";
@@ -15920,7 +17124,7 @@ async function releasePlugin(ctx) {
15920
17124
  return { wasRunning, hadPanes: panes.length > 0 };
15921
17125
  }
15922
17126
  async function waitForRelay(ctx, timeoutMs) {
15923
- const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
17127
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
15924
17128
  for (let waited = 0; waited < timeoutMs; waited += 1e3) {
15925
17129
  if (await relayRunning(ctx)) return true;
15926
17130
  await sleep(1e3);
@@ -15981,7 +17185,7 @@ async function installPlugin(ctx, options = {}) {
15981
17185
  const configDir = dirResult.stdout.trim();
15982
17186
  if (!configDir) throw new CliError("Herdr did not report a plugin config directory.", "Run `herdr plugin config-dir peerband` to investigate.");
15983
17187
  await mkdir5(configDir, { recursive: true });
15984
- await writeFile6(join9(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
17188
+ await writeFile6(join10(configDir, "settings.json"), `${JSON.stringify(pluginSettings(ctx.env), null, 2)}
15985
17189
  `, { mode: 384 });
15986
17190
  ctx.out.print(`${s.green(symbols.ok)} Saved plugin settings ${s.dim(`(node ${process.execPath})`)}`);
15987
17191
  const after = await pluginInstalled(ctx);
@@ -16031,7 +17235,7 @@ var uninstallSpec = {
16031
17235
  const configDir = dirResult.code === 0 ? dirResult.stdout.trim() : "";
16032
17236
  const removed = await removePlugin(ctx);
16033
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.");
16034
- if (configDir) await rm6(join9(configDir, "settings.json"), { force: true }).catch(() => void 0);
17238
+ if (configDir) await rm6(join10(configDir, "settings.json"), { force: true }).catch(() => void 0);
16035
17239
  ctx.out.print(`${s.green(symbols.ok)} Removed the PeerBand plugin from Herdr.`);
16036
17240
  } else {
16037
17241
  ctx.out.print("The PeerBand plugin is not installed in Herdr; nothing to remove.");
@@ -16054,7 +17258,7 @@ var groupSpec = {
16054
17258
  import { hostname as hostname3 } from "node:os";
16055
17259
 
16056
17260
  // src/cli/browser.ts
16057
- import { spawn as spawn2 } from "node:child_process";
17261
+ import { spawn as spawn3 } from "node:child_process";
16058
17262
  function browserDecision(url, context) {
16059
17263
  if (context.noBrowser) return { open: false, reason: "flag" };
16060
17264
  if (context.env.SSH_CONNECTION || context.env.SSH_TTY || context.env.SSH_CLIENT) return { open: false, reason: "ssh" };
@@ -16074,16 +17278,16 @@ function openerCommand(platform, url) {
16074
17278
  }
16075
17279
  function openBrowser(url, platform = process.platform) {
16076
17280
  const { command, args } = openerCommand(platform, url);
16077
- return new Promise((resolve5) => {
17281
+ return new Promise((resolve6) => {
16078
17282
  try {
16079
- const child = spawn2(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
16080
- child.once("error", () => resolve5(false));
17283
+ const child = spawn3(command, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
17284
+ child.once("error", () => resolve6(false));
16081
17285
  child.once("spawn", () => {
16082
17286
  child.unref();
16083
- resolve5(true);
17287
+ resolve6(true);
16084
17288
  });
16085
17289
  } catch {
16086
- resolve5(false);
17290
+ resolve6(false);
16087
17291
  }
16088
17292
  });
16089
17293
  }
@@ -16096,7 +17300,7 @@ var PromptAborted = class extends Error {
16096
17300
  }
16097
17301
  };
16098
17302
  function askYesNo(stdin, stderr, prompt, defaultYes = true) {
16099
- return new Promise((resolve5, reject) => {
17303
+ return new Promise((resolve6, reject) => {
16100
17304
  let value = "";
16101
17305
  const cleanup = () => {
16102
17306
  stdin.off("data", onData);
@@ -16113,7 +17317,7 @@ function askYesNo(stdin, stderr, prompt, defaultYes = true) {
16113
17317
  if (end === -1) return;
16114
17318
  cleanup();
16115
17319
  const answer = value.trim().toLowerCase();
16116
- resolve5(answer === "" ? defaultYes : answer === "y" || answer === "yes");
17320
+ resolve6(answer === "" ? defaultYes : answer === "y" || answer === "yes");
16117
17321
  };
16118
17322
  stderr.write(prompt);
16119
17323
  stdin.resume();
@@ -16406,8 +17610,12 @@ var spec4 = {
16406
17610
  var PANE_ID2 = /^[A-Za-z0-9._:-]{1,128}$/;
16407
17611
  var START_RELAY = "Start the relay with `peerband relay`.";
16408
17612
  function callingPane(env) {
16409
- const pane = env.HERDR_PANE_ID;
16410
- return typeof pane === "string" && PANE_ID2.test(pane) ? pane : void 0;
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;
16411
17619
  }
16412
17620
  async function checkChannel(name, ctx) {
16413
17621
  const credentials = await requireCredentials(ctx);
@@ -16440,9 +17648,10 @@ async function notify(text2, json, ctx, channel, agent) {
16440
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.");
16441
17649
  if (channel !== void 0) await checkChannel(channel, ctx);
16442
17650
  const paneId = callingPane(ctx.env);
17651
+ const terminalId = callingTerminal(ctx.env);
16443
17652
  let reply;
16444
17653
  try {
16445
- reply = await requestNotify({ text: text2, ...agent !== void 0 ? { agentId: agent } : {}, ...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);
16446
17655
  } catch (error) {
16447
17656
  if (error instanceof ControlUnavailable && error.reason === "closed") {
16448
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.");
@@ -16465,14 +17674,14 @@ async function notify(text2, json, ctx, channel, agent) {
16465
17674
  }
16466
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.");
16467
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.");
16468
- const agentId = typeof reply.agentId === "string" ? reply.agentId : null;
17677
+ const agentId2 = typeof reply.agentId === "string" ? reply.agentId : null;
16469
17678
  if (json) {
16470
- ctx.out.print(JSON.stringify({ sent: true, agentId, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
17679
+ ctx.out.print(JSON.stringify({ sent: true, agentId: agentId2, eventId: typeof reply.eventId === "string" ? reply.eventId : null, ...channel !== void 0 ? { channel } : {} }, null, 2));
16471
17680
  return 0;
16472
17681
  }
16473
17682
  const s = ctx.out.stdout;
16474
17683
  const target = channel !== void 0 ? `channel ${s.bold(channel)}` : "the machine owner";
16475
- ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${agentId ? s.dim(` (from agent ${sanitize(agentId)})`) : ""}.`);
17684
+ ctx.out.print(`${s.green(symbols.ok)} Note sent to ${target}${agentId2 ? s.dim(` (from agent ${sanitize(agentId2)})`) : ""}.`);
16476
17685
  return 0;
16477
17686
  }
16478
17687
  var spec5 = {
@@ -16504,19 +17713,85 @@ var spec5 = {
16504
17713
  }
16505
17714
  };
16506
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
+
16507
17761
  // src/cli/commands/relay.ts
16508
17762
  var spec6 = {
16509
17763
  name: "relay",
16510
- summary: "Open or focus the PeerBand Relay tab in Herdr",
16511
- usage: "peerband relay",
16512
- description: "Opens the PeerBand Relay in a persistent Herdr tab, or focuses it if it is already open. The tab shows your account, connection state and metadata-only activity; closing it disconnects. Requires Herdr and the PeerBand plugin (`peerband herdr install`). If the plugin is wrong (another version, a local checkout, or a stale config directory), relay offers to repair it first.",
16513
- options: [],
16514
- examples: [["peerband relay", "Open the relay tab"]],
16515
- async run(_parsed, ctx) {
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
+ }
16516
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
+ }
16517
17793
  await ensureHerdrPlugin(ctx);
16518
17794
  await openRelay(ctx);
16519
- const s = ctx.out.stdout;
16520
17795
  ctx.out.print(`${s.green(symbols.ok)} PeerBand Relay is open in Herdr.`);
16521
17796
  printMcpHint(ctx, credentials.serverUrl);
16522
17797
  printSkillTip(ctx);
@@ -16540,8 +17815,8 @@ async function openRelay(ctx) {
16540
17815
  var SKILL_MODES = ["ask", "install", "skip"];
16541
17816
  function report(ctx, installed) {
16542
17817
  const s = ctx.out.stdout;
16543
- const where = installed.method === "skills" && installed.agents.length > 0 ? `for ${installed.agents.slice(0, 6).join(", ")}${installed.agents.length > 6 ? ` and ${installed.agents.length - 6} more` : ""}` : `in ${installed.agents.join(", ")}`;
16544
- ctx.out.print(`${s.green(symbols.ok)} Installed the PeerBand skill ${where}.`);
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}.`);
16545
17820
  ctx.out.print(s.dim(` ${installed.path}`));
16546
17821
  }
16547
17822
  function keptEdits(ctx, file) {
@@ -16636,6 +17911,10 @@ async function existingLogin(parsed, ctx) {
16636
17911
  return void 0;
16637
17912
  }
16638
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
+ }
16639
17918
  var loginOptions = spec3.options.filter((option) => option.name !== "herdr-plugin");
16640
17919
  var spec8 = {
16641
17920
  name: "setup",
@@ -16677,6 +17956,15 @@ var spec8 = {
16677
17956
  let relayOpen = false;
16678
17957
  if (flag(parsed, "no-relay")) {
16679
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
+ }
16680
17968
  } else if (herdr2 !== "ready") {
16681
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\`.`));
16682
17970
  } else {
@@ -16800,6 +18088,7 @@ async function buildStatus(ctx) {
16800
18088
  credentials = void 0;
16801
18089
  }
16802
18090
  const snapshot = await relaySnapshot(ctx.env);
18091
+ const running = snapshot?.source === "control" && snapshot.state === "running";
16803
18092
  const plugin = await checkHerdrPlugin(ctx);
16804
18093
  const messages = await loadMachineConnectorConfig(ctx).then(
16805
18094
  (config) => writesEnabled(config) ? "allowed" : "read-only",
@@ -16817,9 +18106,10 @@ async function buildStatus(ctx) {
16817
18106
  installationId: credentials?.installationId ?? null,
16818
18107
  enrolledAt: credentials?.enrolledAt ?? null,
16819
18108
  relay: {
16820
- running: snapshot?.source === "control" && snapshot.state === "running",
18109
+ running,
16821
18110
  connection: snapshot?.connectionState ?? null,
16822
- source: snapshot?.source ?? "none"
18111
+ source: snapshot?.source ?? "none",
18112
+ runtime: running ? await recordedRelayRuntime(ctx.env) : null
16823
18113
  },
16824
18114
  messages,
16825
18115
  herdr: {
@@ -16853,7 +18143,7 @@ function renderHuman(report2, ctx) {
16853
18143
  rows.push(["Installation", report2.installationId ?? ""]);
16854
18144
  if (report2.enrolledAt) rows.push(["Enrolled", report2.enrolledAt]);
16855
18145
  }
16856
- const relayLine = report2.relay.running ? colorConnection(s, report2.relay.connection) : report2.relay.source === "file" && report2.relay.connection && report2.relay.connection !== "helper-unavailable" ? `${colorConnection(s, report2.relay.connection)} ${s.dim("(last known; relay not running)")}` : s.dim(`${symbols.ring} not running ${s.dim("(open it with `peerband relay`)")}`);
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)")}`);
16857
18147
  rows.push(["Relay", relayLine]);
16858
18148
  if (report2.messages) {
16859
18149
  rows.push([
@@ -16874,8 +18164,8 @@ function renderHuman(report2, ctx) {
16874
18164
  }
16875
18165
  rows.push(["peerband", `${report2.version} ${s.dim(`(node ${report2.node})`)}`]);
16876
18166
  rows.push(["Config", s.dim(report2.configHome)]);
16877
- const width = Math.max(...rows.map(([key]) => key.length));
16878
- for (const [key, value] of rows) ctx.out.print(`${s.bold(key.padEnd(width))} ${value}`);
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}`);
16879
18169
  }
16880
18170
  var spec10 = {
16881
18171
  name: "status",
@@ -16970,8 +18260,8 @@ var spec11 = {
16970
18260
  };
16971
18261
 
16972
18262
  // src/cli/commands/update.ts
16973
- import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
16974
- import { dirname as dirname5, isAbsolute, join as join10, relative as relative2 } from "node:path";
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";
16975
18265
  var DEFAULT_REGISTRY = "https://registry.npmjs.org";
16976
18266
  var PACKAGE = "peerband";
16977
18267
  var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
@@ -17024,14 +18314,14 @@ function isInside(child, parent) {
17024
18314
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
17025
18315
  }
17026
18316
  function checkoutRoot(self) {
17027
- let dir = dirname5(self);
18317
+ let dir = dirname6(self);
17028
18318
  for (let i = 0; i < 4; i++) {
17029
18319
  try {
17030
- const pkg = JSON.parse(readFileSync2(join10(dir, "package.json"), "utf8"));
17031
- if (pkg.name === PACKAGE && existsSync2(join10(dir, ".git"))) return dir;
18320
+ const pkg = JSON.parse(readFileSync2(join12(dir, "package.json"), "utf8"));
18321
+ if (pkg.name === PACKAGE && existsSync3(join12(dir, ".git"))) return dir;
17032
18322
  } catch {
17033
18323
  }
17034
- const parent = dirname5(dir);
18324
+ const parent = dirname6(dir);
17035
18325
  if (parent === dir) break;
17036
18326
  dir = parent;
17037
18327
  }
@@ -17042,7 +18332,7 @@ async function detectInstall(ctx) {
17042
18332
  if (/[\\/]_npx[\\/]/.test(self)) return { kind: "npx", self };
17043
18333
  const npm = await (ctx.exec ?? execProgram)("npm", ["root", "-g"], { timeoutMs: 6e4, env: ctx.env });
17044
18334
  const npmRoot = npm.code === 0 ? npm.stdout.trim().split(/\r?\n/).pop()?.trim() : void 0;
17045
- if (npmRoot && isInside(self, real(join10(npmRoot, PACKAGE)))) return { kind: "npm-global", self, npmRoot };
18335
+ if (npmRoot && isInside(self, real(join12(npmRoot, PACKAGE)))) return { kind: "npm-global", self, npmRoot };
17046
18336
  const checkout = checkoutRoot(self);
17047
18337
  if (checkout) return { kind: "source", self, npmRoot, detail: checkout };
17048
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" };
@@ -17096,7 +18386,7 @@ var spec12 = {
17096
18386
  const plugin = await checkHerdrPlugin(ctx);
17097
18387
  const report2 = { current: ctx.version, latest, updateAvailable: newer, action: "none", plugin: pluginSummary(plugin) };
17098
18388
  const pluginNeedsRepair = plugin.found && plugin.installed && plugin.problems.length > 0;
17099
- const finish = (code = 0) => {
18389
+ const finish2 = (code = 0) => {
17100
18390
  if (json) ctx.out.print(JSON.stringify(report2, null, 2));
17101
18391
  return code;
17102
18392
  };
@@ -17104,7 +18394,7 @@ var spec12 = {
17104
18394
  if (newer) log(`${s.yellow(symbols.warn)} PeerBand ${latest} is available (you have ${ctx.version}). Run ${s.bold("peerband update")}.`);
17105
18395
  else log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
17106
18396
  if (pluginNeedsRepair) log(`${s.yellow(symbols.warn)} The Herdr plugin needs repair: ${plugin.problems[0].message} ${s.dim("(run `peerband update`)")}`);
17107
- return finish();
18397
+ return finish2();
17108
18398
  }
17109
18399
  if (!newer) {
17110
18400
  log(`${s.green(symbols.ok)} PeerBand ${ctx.version} is up to date ${s.dim(`(latest on npm: ${latest})`)}.`);
@@ -17118,7 +18408,7 @@ var spec12 = {
17118
18408
  } else if (plugin.installed) {
17119
18409
  log(`${s.green(symbols.ok)} The Herdr plugin matches ${s.dim(`(${plugin.source ?? "installed"})`)}.`);
17120
18410
  }
17121
- return finish();
18411
+ return finish2();
17122
18412
  }
17123
18413
  const install = await detectInstall(ctx);
17124
18414
  report2.install = install.kind;
@@ -17128,7 +18418,7 @@ var spec12 = {
17128
18418
  report2.manual = manual;
17129
18419
  if (json) {
17130
18420
  io.out.fail(manual.message, manual.hint);
17131
- return finish(1);
18421
+ return finish2(1);
17132
18422
  }
17133
18423
  throw new CliError(`PeerBand ${latest} is available (you have ${ctx.version}). ${manual.message}`, manual.hint);
17134
18424
  }
@@ -17143,7 +18433,7 @@ var spec12 = {
17143
18433
  if (!proceed) {
17144
18434
  report2.action = "cancelled";
17145
18435
  log(s.dim("Not updated."));
17146
- return finish();
18436
+ return finish2();
17147
18437
  }
17148
18438
  }
17149
18439
  const exec2 = ctx.exec ?? execProgram;
@@ -17158,8 +18448,8 @@ var spec12 = {
17158
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\`.`
17159
18449
  );
17160
18450
  }
17161
- const entry = join10(install.npmRoot, PACKAGE, "dist", "peerband.mjs");
17162
- if (!existsSync2(entry)) throw new CliError(`npm finished, but the new CLI is not at ${entry}.`, `Run \`npm install -g ${spec13}\` yourself, then \`peerband update\`.`);
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\`.`);
17163
18453
  log(`${s.green(symbols.ok)} Installed peerband ${latest}.`);
17164
18454
  report2.action = "updated";
17165
18455
  if (skillInstalled(ctx)) {
@@ -17173,11 +18463,11 @@ var spec12 = {
17173
18463
  }
17174
18464
  if (!plugin.found) {
17175
18465
  log(s.dim("Herdr was not found, so there is no plugin to update."));
17176
- return finish();
18466
+ return finish2();
17177
18467
  }
17178
18468
  if (!plugin.installed) {
17179
18469
  log(`${s.dim("Next:")} peerband herdr install ${s.dim("(adds the PeerBand plugin to Herdr)")}`);
17180
- return finish();
18470
+ return finish2();
17181
18471
  }
17182
18472
  log("Updating the Herdr plugin with the new CLI\u2026");
17183
18473
  const env = { ...ctx.env, ...io.out.stdout.enabled && ctx.env.FORCE_COLOR === void 0 ? { FORCE_COLOR: "1" } : {} };
@@ -17191,12 +18481,12 @@ var spec12 = {
17191
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`.");
17192
18482
  }
17193
18483
  report2.plugin = pluginSummary(await checkHerdrPlugin({ ...ctx, version: latest }));
17194
- return finish();
18484
+ return finish2();
17195
18485
  }
17196
18486
  };
17197
18487
 
17198
18488
  // src/cli/registry.ts
17199
- 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];
17200
18490
  var herdrCommands = [installSpec, uninstallSpec];
17201
18491
  function lookup(words) {
17202
18492
  const [first, second] = words;
@@ -17252,7 +18542,10 @@ function rootHelp(s, version) {
17252
18542
  ...section(s, "From an agent", [
17253
18543
  'peerband notify "<text>" Send the machine owner a short note (task done, blocked, result)',
17254
18544
  " --channel NAME Send it to one of the owner's channels instead (see peerband channels)",
17255
- " --agent ID Attribute a reply to this exact current agent"
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)"
17256
18549
  ]),
17257
18550
  ...section(s, "Exit codes", ["0 ok 1 failure 2 usage error 3 not logged in 130 interrupted"]),
17258
18551
  "",
@@ -17292,7 +18585,7 @@ function herdrGroupHelp(s) {
17292
18585
  }
17293
18586
 
17294
18587
  // src/cli/cli.ts
17295
- var VERSION = true ? "0.2.9" : "0.0.0-dev";
18588
+ var VERSION = true ? "0.3.0" : "0.0.0-dev";
17296
18589
  function createContext(overrides = {}) {
17297
18590
  const env = overrides.env ?? process.env;
17298
18591
  const stdout = overrides.stdout ?? process.stdout;