repoburg 1.3.285 → 1.3.286

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.
@@ -2676,7 +2676,7 @@ var require_server = __commonJS({
2676
2676
  var https = __require("node:https");
2677
2677
  var http22 = __require("node:http2");
2678
2678
  var dns = __require("node:dns");
2679
- var os4 = __require("node:os");
2679
+ var os5 = __require("node:os");
2680
2680
  var { kState, kOptions, kServerBindings, kHttp2ServerSessions } = require_symbols2();
2681
2681
  var { FSTWRN003 } = require_warnings();
2682
2682
  var { onListenHookRunner } = require_hooks();
@@ -2938,7 +2938,7 @@ var require_server = __commonJS({
2938
2938
  }
2939
2939
  function getAddresses(address) {
2940
2940
  if (address.address === "0.0.0.0") {
2941
- return Object.values(os4.networkInterfaces()).flatMap((iface) => {
2941
+ return Object.values(os5.networkInterfaces()).flatMap((iface) => {
2942
2942
  return iface.filter((iface2) => iface2.family === "IPv4");
2943
2943
  }).sort((iface) => {
2944
2944
  return iface.internal ? -1 : 1;
@@ -6124,8 +6124,8 @@ var require_req = __commonJS({
6124
6124
  if (req.originalUrl) {
6125
6125
  _req.url = req.originalUrl;
6126
6126
  } else {
6127
- const path11 = req.path;
6128
- _req.url = typeof path11 === "string" ? path11 : req.url ? req.url.path || req.url : void 0;
6127
+ const path12 = req.path;
6128
+ _req.url = typeof path12 === "string" ? path12 : req.url ? req.url.path || req.url : void 0;
6129
6129
  }
6130
6130
  if (req.query) {
6131
6131
  _req.query = req.query;
@@ -6290,14 +6290,14 @@ var require_redact = __commonJS({
6290
6290
  }
6291
6291
  return obj;
6292
6292
  }
6293
- function parsePath(path11) {
6293
+ function parsePath(path12) {
6294
6294
  const parts = [];
6295
6295
  let current = "";
6296
6296
  let inBrackets = false;
6297
6297
  let inQuotes = false;
6298
6298
  let quoteChar = "";
6299
- for (let i = 0; i < path11.length; i++) {
6300
- const char = path11[i];
6299
+ for (let i = 0; i < path12.length; i++) {
6300
+ const char = path12[i];
6301
6301
  if (!inBrackets && char === ".") {
6302
6302
  if (current) {
6303
6303
  parts.push(current);
@@ -6428,10 +6428,10 @@ var require_redact = __commonJS({
6428
6428
  return current;
6429
6429
  }
6430
6430
  function redactPaths(obj, paths, censor, remove = false) {
6431
- for (const path11 of paths) {
6432
- const parts = parsePath(path11);
6431
+ for (const path12 of paths) {
6432
+ const parts = parsePath(path12);
6433
6433
  if (parts.includes("*")) {
6434
- redactWildcardPath(obj, parts, censor, path11, remove);
6434
+ redactWildcardPath(obj, parts, censor, path12, remove);
6435
6435
  } else {
6436
6436
  if (remove) {
6437
6437
  removeKey(obj, parts);
@@ -6516,8 +6516,8 @@ var require_redact = __commonJS({
6516
6516
  }
6517
6517
  } else {
6518
6518
  if (afterWildcard.includes("*")) {
6519
- const wrappedCensor = typeof censor === "function" ? (value, path11) => {
6520
- const fullPath = [...pathArray.slice(0, pathLength), ...path11];
6519
+ const wrappedCensor = typeof censor === "function" ? (value, path12) => {
6520
+ const fullPath = [...pathArray.slice(0, pathLength), ...path12];
6521
6521
  return censor(value, fullPath);
6522
6522
  } : censor;
6523
6523
  redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove);
@@ -6552,8 +6552,8 @@ var require_redact = __commonJS({
6552
6552
  return null;
6553
6553
  }
6554
6554
  const pathStructure = /* @__PURE__ */ new Map();
6555
- for (const path11 of pathsToClone) {
6556
- const parts = parsePath(path11);
6555
+ for (const path12 of pathsToClone) {
6556
+ const parts = parsePath(path12);
6557
6557
  let current = pathStructure;
6558
6558
  for (let i = 0; i < parts.length; i++) {
6559
6559
  const part = parts[i];
@@ -6605,24 +6605,24 @@ var require_redact = __commonJS({
6605
6605
  }
6606
6606
  return cloneSelectively(obj, pathStructure);
6607
6607
  }
6608
- function validatePath(path11) {
6609
- if (typeof path11 !== "string") {
6608
+ function validatePath(path12) {
6609
+ if (typeof path12 !== "string") {
6610
6610
  throw new Error("Paths must be (non-empty) strings");
6611
6611
  }
6612
- if (path11 === "") {
6612
+ if (path12 === "") {
6613
6613
  throw new Error("Invalid redaction path ()");
6614
6614
  }
6615
- if (path11.includes("..")) {
6616
- throw new Error(`Invalid redaction path (${path11})`);
6615
+ if (path12.includes("..")) {
6616
+ throw new Error(`Invalid redaction path (${path12})`);
6617
6617
  }
6618
- if (path11.includes(",")) {
6619
- throw new Error(`Invalid redaction path (${path11})`);
6618
+ if (path12.includes(",")) {
6619
+ throw new Error(`Invalid redaction path (${path12})`);
6620
6620
  }
6621
6621
  let bracketCount = 0;
6622
6622
  let inQuotes = false;
6623
6623
  let quoteChar = "";
6624
- for (let i = 0; i < path11.length; i++) {
6625
- const char = path11[i];
6624
+ for (let i = 0; i < path12.length; i++) {
6625
+ const char = path12[i];
6626
6626
  if ((char === '"' || char === "'") && bracketCount > 0) {
6627
6627
  if (!inQuotes) {
6628
6628
  inQuotes = true;
@@ -6636,20 +6636,20 @@ var require_redact = __commonJS({
6636
6636
  } else if (char === "]" && !inQuotes) {
6637
6637
  bracketCount--;
6638
6638
  if (bracketCount < 0) {
6639
- throw new Error(`Invalid redaction path (${path11})`);
6639
+ throw new Error(`Invalid redaction path (${path12})`);
6640
6640
  }
6641
6641
  }
6642
6642
  }
6643
6643
  if (bracketCount !== 0) {
6644
- throw new Error(`Invalid redaction path (${path11})`);
6644
+ throw new Error(`Invalid redaction path (${path12})`);
6645
6645
  }
6646
6646
  }
6647
6647
  function validatePaths(paths) {
6648
6648
  if (!Array.isArray(paths)) {
6649
6649
  throw new TypeError("paths must be an array");
6650
6650
  }
6651
- for (const path11 of paths) {
6652
- validatePath(path11);
6651
+ for (const path12 of paths) {
6652
+ validatePath(path12);
6653
6653
  }
6654
6654
  }
6655
6655
  function slowRedact(options = {}) {
@@ -6817,8 +6817,8 @@ var require_redaction = __commonJS({
6817
6817
  if (shape[k] === null) {
6818
6818
  o[k] = (value) => topCensor(value, [k]);
6819
6819
  } else {
6820
- const wrappedCensor = typeof censor === "function" ? (value, path11) => {
6821
- return censor(value, [k, ...path11]);
6820
+ const wrappedCensor = typeof censor === "function" ? (value, path12) => {
6821
+ return censor(value, [k, ...path12]);
6822
6822
  } : censor;
6823
6823
  o[k] = Redact({
6824
6824
  paths: shape[k],
@@ -7036,10 +7036,10 @@ var require_atomic_sleep = __commonJS({
7036
7036
  var require_sonic_boom = __commonJS({
7037
7037
  "node_modules/sonic-boom/index.js"(exports, module) {
7038
7038
  "use strict";
7039
- var fs7 = __require("fs");
7039
+ var fs8 = __require("fs");
7040
7040
  var EventEmitter2 = __require("events");
7041
7041
  var inherits = __require("util").inherits;
7042
- var path11 = __require("path");
7042
+ var path12 = __require("path");
7043
7043
  var sleep = require_atomic_sleep();
7044
7044
  var assert = __require("assert");
7045
7045
  var BUSY_WRITE_TIMEOUT = 100;
@@ -7093,20 +7093,20 @@ var require_sonic_boom = __commonJS({
7093
7093
  const mode = sonic.mode;
7094
7094
  if (sonic.sync) {
7095
7095
  try {
7096
- if (sonic.mkdir) fs7.mkdirSync(path11.dirname(file), { recursive: true });
7097
- const fd = fs7.openSync(file, flags, mode);
7096
+ if (sonic.mkdir) fs8.mkdirSync(path12.dirname(file), { recursive: true });
7097
+ const fd = fs8.openSync(file, flags, mode);
7098
7098
  fileOpened(null, fd);
7099
7099
  } catch (err) {
7100
7100
  fileOpened(err);
7101
7101
  throw err;
7102
7102
  }
7103
7103
  } else if (sonic.mkdir) {
7104
- fs7.mkdir(path11.dirname(file), { recursive: true }, (err) => {
7104
+ fs8.mkdir(path12.dirname(file), { recursive: true }, (err) => {
7105
7105
  if (err) return fileOpened(err);
7106
- fs7.open(file, flags, mode, fileOpened);
7106
+ fs8.open(file, flags, mode, fileOpened);
7107
7107
  });
7108
7108
  } else {
7109
- fs7.open(file, flags, mode, fileOpened);
7109
+ fs8.open(file, flags, mode, fileOpened);
7110
7110
  }
7111
7111
  }
7112
7112
  function SonicBoom(opts) {
@@ -7147,8 +7147,8 @@ var require_sonic_boom = __commonJS({
7147
7147
  this.flush = flushBuffer;
7148
7148
  this.flushSync = flushBufferSync;
7149
7149
  this._actualWrite = actualWriteBuffer;
7150
- fsWriteSync = () => fs7.writeSync(this.fd, this._writingBuf);
7151
- fsWrite = () => fs7.write(this.fd, this._writingBuf, this.release);
7150
+ fsWriteSync = () => fs8.writeSync(this.fd, this._writingBuf);
7151
+ fsWrite = () => fs8.write(this.fd, this._writingBuf, this.release);
7152
7152
  } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
7153
7153
  this._writingBuf = "";
7154
7154
  this.write = write;
@@ -7157,15 +7157,15 @@ var require_sonic_boom = __commonJS({
7157
7157
  this._actualWrite = actualWrite;
7158
7158
  fsWriteSync = () => {
7159
7159
  if (Buffer.isBuffer(this._writingBuf)) {
7160
- return fs7.writeSync(this.fd, this._writingBuf);
7160
+ return fs8.writeSync(this.fd, this._writingBuf);
7161
7161
  }
7162
- return fs7.writeSync(this.fd, this._writingBuf, "utf8");
7162
+ return fs8.writeSync(this.fd, this._writingBuf, "utf8");
7163
7163
  };
7164
7164
  fsWrite = () => {
7165
7165
  if (Buffer.isBuffer(this._writingBuf)) {
7166
- return fs7.write(this.fd, this._writingBuf, this.release);
7166
+ return fs8.write(this.fd, this._writingBuf, this.release);
7167
7167
  }
7168
- return fs7.write(this.fd, this._writingBuf, "utf8", this.release);
7168
+ return fs8.write(this.fd, this._writingBuf, "utf8", this.release);
7169
7169
  };
7170
7170
  } else {
7171
7171
  throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
@@ -7222,7 +7222,7 @@ var require_sonic_boom = __commonJS({
7222
7222
  }
7223
7223
  }
7224
7224
  if (this._fsync) {
7225
- fs7.fsyncSync(this.fd);
7225
+ fs8.fsyncSync(this.fd);
7226
7226
  }
7227
7227
  const len = this._len;
7228
7228
  if (this._reopening) {
@@ -7336,7 +7336,7 @@ var require_sonic_boom = __commonJS({
7336
7336
  const onDrain = () => {
7337
7337
  if (!this._fsync) {
7338
7338
  try {
7339
- fs7.fsync(this.fd, (err) => {
7339
+ fs8.fsync(this.fd, (err) => {
7340
7340
  this._flushPending = false;
7341
7341
  cb(err);
7342
7342
  });
@@ -7438,7 +7438,7 @@ var require_sonic_boom = __commonJS({
7438
7438
  const fd = this.fd;
7439
7439
  this.once("ready", () => {
7440
7440
  if (fd !== this.fd) {
7441
- fs7.close(fd, (err) => {
7441
+ fs8.close(fd, (err) => {
7442
7442
  if (err) {
7443
7443
  return this.emit("error", err);
7444
7444
  }
@@ -7487,7 +7487,7 @@ var require_sonic_boom = __commonJS({
7487
7487
  buf = this._bufs[0];
7488
7488
  }
7489
7489
  try {
7490
- const n = Buffer.isBuffer(buf) ? fs7.writeSync(this.fd, buf) : fs7.writeSync(this.fd, buf, "utf8");
7490
+ const n = Buffer.isBuffer(buf) ? fs8.writeSync(this.fd, buf) : fs8.writeSync(this.fd, buf, "utf8");
7491
7491
  const releasedBufObj = releaseWritingBuf(buf, this._len, n);
7492
7492
  buf = releasedBufObj.writingBuf;
7493
7493
  this._len = releasedBufObj.len;
@@ -7503,7 +7503,7 @@ var require_sonic_boom = __commonJS({
7503
7503
  }
7504
7504
  }
7505
7505
  try {
7506
- fs7.fsyncSync(this.fd);
7506
+ fs8.fsyncSync(this.fd);
7507
7507
  } catch {
7508
7508
  }
7509
7509
  }
@@ -7524,7 +7524,7 @@ var require_sonic_boom = __commonJS({
7524
7524
  buf = mergeBuf(this._bufs[0], this._lens[0]);
7525
7525
  }
7526
7526
  try {
7527
- const n = fs7.writeSync(this.fd, buf);
7527
+ const n = fs8.writeSync(this.fd, buf);
7528
7528
  buf = buf.subarray(n);
7529
7529
  this._len = Math.max(this._len - n, 0);
7530
7530
  if (buf.length <= 0) {
@@ -7552,13 +7552,13 @@ var require_sonic_boom = __commonJS({
7552
7552
  this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
7553
7553
  if (this.sync) {
7554
7554
  try {
7555
- const written = Buffer.isBuffer(this._writingBuf) ? fs7.writeSync(this.fd, this._writingBuf) : fs7.writeSync(this.fd, this._writingBuf, "utf8");
7555
+ const written = Buffer.isBuffer(this._writingBuf) ? fs8.writeSync(this.fd, this._writingBuf) : fs8.writeSync(this.fd, this._writingBuf, "utf8");
7556
7556
  release(null, written);
7557
7557
  } catch (err) {
7558
7558
  release(err);
7559
7559
  }
7560
7560
  } else {
7561
- fs7.write(this.fd, this._writingBuf, release);
7561
+ fs8.write(this.fd, this._writingBuf, release);
7562
7562
  }
7563
7563
  }
7564
7564
  function actualWriteBuffer() {
@@ -7567,7 +7567,7 @@ var require_sonic_boom = __commonJS({
7567
7567
  this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
7568
7568
  if (this.sync) {
7569
7569
  try {
7570
- const written = fs7.writeSync(this.fd, this._writingBuf);
7570
+ const written = fs8.writeSync(this.fd, this._writingBuf);
7571
7571
  release(null, written);
7572
7572
  } catch (err) {
7573
7573
  release(err);
@@ -7576,7 +7576,7 @@ var require_sonic_boom = __commonJS({
7576
7576
  if (kCopyBuffer) {
7577
7577
  this._writingBuf = Buffer.from(this._writingBuf);
7578
7578
  }
7579
- fs7.write(this.fd, this._writingBuf, release);
7579
+ fs8.write(this.fd, this._writingBuf, release);
7580
7580
  }
7581
7581
  }
7582
7582
  function actualClose(sonic) {
@@ -7592,12 +7592,12 @@ var require_sonic_boom = __commonJS({
7592
7592
  sonic._lens = [];
7593
7593
  assert(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
7594
7594
  try {
7595
- fs7.fsync(sonic.fd, closeWrapped);
7595
+ fs8.fsync(sonic.fd, closeWrapped);
7596
7596
  } catch {
7597
7597
  }
7598
7598
  function closeWrapped() {
7599
7599
  if (sonic.fd !== 1 && sonic.fd !== 2) {
7600
- fs7.close(sonic.fd, done);
7600
+ fs8.close(sonic.fd, done);
7601
7601
  } else {
7602
7602
  done();
7603
7603
  }
@@ -8433,15 +8433,15 @@ var require_transport = __commonJS({
8433
8433
  if (!unquoted) {
8434
8434
  return false;
8435
8435
  }
8436
- let path11 = unquoted;
8437
- if (path11.startsWith("file://")) {
8436
+ let path12 = unquoted;
8437
+ if (path12.startsWith("file://")) {
8438
8438
  try {
8439
- path11 = fileURLToPath3(path11);
8439
+ path12 = fileURLToPath3(path12);
8440
8440
  } catch {
8441
8441
  return false;
8442
8442
  }
8443
8443
  }
8444
- return isAbsolute(path11) && !existsSync3(path11);
8444
+ return isAbsolute(path12) && !existsSync3(path12);
8445
8445
  }
8446
8446
  function stripQuotes(value) {
8447
8447
  const first = value[0];
@@ -10135,7 +10135,7 @@ var require_multistream = __commonJS({
10135
10135
  var require_pino = __commonJS({
10136
10136
  "node_modules/pino/pino.js"(exports, module) {
10137
10137
  "use strict";
10138
- var os4 = __require("node:os");
10138
+ var os5 = __require("node:os");
10139
10139
  var stdSerializers = require_pino_std_serializers();
10140
10140
  var caller = require_caller();
10141
10141
  var redaction = require_redaction();
@@ -10182,7 +10182,7 @@ var require_pino = __commonJS({
10182
10182
  } = symbols;
10183
10183
  var { epochTime, nullTime } = time;
10184
10184
  var { pid } = process;
10185
- var hostname2 = os4.hostname();
10185
+ var hostname2 = os5.hostname();
10186
10186
  var defaultErrorSerializer = stdSerializers.err;
10187
10187
  var defaultOptions = {
10188
10188
  level: "info",
@@ -11882,7 +11882,7 @@ var require_reply = __commonJS({
11882
11882
  let handled = 0;
11883
11883
  let skipped = true;
11884
11884
  let sent = false;
11885
- function send() {
11885
+ function send2() {
11886
11886
  if (handled === 0 && !sent) {
11887
11887
  sent = true;
11888
11888
  res.addTrailers(trailers);
@@ -11896,7 +11896,7 @@ var require_reply = __commonJS({
11896
11896
  handled++;
11897
11897
  if (err) reply.log.debug(err);
11898
11898
  else trailers[trailerName] = value;
11899
- process.nextTick(send);
11899
+ process.nextTick(send2);
11900
11900
  };
11901
11901
  if (typeof reply[kReplyTrailers][trailerName] !== "function") continue;
11902
11902
  skipped = false;
@@ -17117,8 +17117,8 @@ var require_utils = __commonJS({
17117
17117
  }
17118
17118
  return ind;
17119
17119
  }
17120
- function removeDotSegments(path11) {
17121
- let input = path11;
17120
+ function removeDotSegments(path12) {
17121
+ let input = path12;
17122
17122
  const output = [];
17123
17123
  let nextSlash = -1;
17124
17124
  let len = 0;
@@ -17370,8 +17370,8 @@ var require_schemes = __commonJS({
17370
17370
  wsComponent.secure = void 0;
17371
17371
  }
17372
17372
  if (wsComponent.resourceName) {
17373
- const [path11, query2] = wsComponent.resourceName.split("?");
17374
- wsComponent.path = path11 && path11 !== "/" ? path11 : void 0;
17373
+ const [path12, query2] = wsComponent.resourceName.split("?");
17374
+ wsComponent.path = path12 && path12 !== "/" ? path12 : void 0;
17375
17375
  wsComponent.query = query2;
17376
17376
  wsComponent.resourceName = void 0;
17377
17377
  }
@@ -17457,7 +17457,7 @@ var require_schemes = __commonJS({
17457
17457
  serialize: wsSerialize
17458
17458
  }
17459
17459
  );
17460
- var wss2 = (
17460
+ var wss3 = (
17461
17461
  /** @type {SchemeHandler} */
17462
17462
  {
17463
17463
  scheme: "wss",
@@ -17490,7 +17490,7 @@ var require_schemes = __commonJS({
17490
17490
  http: http3,
17491
17491
  https,
17492
17492
  ws,
17493
- wss: wss2,
17493
+ wss: wss3,
17494
17494
  urn,
17495
17495
  "urn:uuid": urnuuid
17496
17496
  }
@@ -22308,8 +22308,8 @@ var require_utils2 = __commonJS({
22308
22308
  }
22309
22309
  return ind;
22310
22310
  }
22311
- function removeDotSegments(path11) {
22312
- let input = path11;
22311
+ function removeDotSegments(path12) {
22312
+ let input = path12;
22313
22313
  const output = [];
22314
22314
  let nextSlash = -1;
22315
22315
  let len = 0;
@@ -22654,8 +22654,8 @@ var require_schemes2 = __commonJS({
22654
22654
  wsComponent.secure = void 0;
22655
22655
  }
22656
22656
  if (wsComponent.resourceName) {
22657
- const [path11, query2] = wsComponent.resourceName.split("?");
22658
- wsComponent.path = path11 && path11 !== "/" ? path11 : void 0;
22657
+ const [path12, query2] = wsComponent.resourceName.split("?");
22658
+ wsComponent.path = path12 && path12 !== "/" ? path12 : void 0;
22659
22659
  wsComponent.query = query2;
22660
22660
  wsComponent.resourceName = void 0;
22661
22661
  }
@@ -22741,7 +22741,7 @@ var require_schemes2 = __commonJS({
22741
22741
  serialize: wsSerialize
22742
22742
  }
22743
22743
  );
22744
- var wss2 = (
22744
+ var wss3 = (
22745
22745
  /** @type {SchemeHandler} */
22746
22746
  {
22747
22747
  scheme: "wss",
@@ -22774,7 +22774,7 @@ var require_schemes2 = __commonJS({
22774
22774
  http: http3,
22775
22775
  https,
22776
22776
  ws,
22777
- wss: wss2,
22777
+ wss: wss3,
22778
22778
  urn,
22779
22779
  "urn:uuid": urnuuid
22780
22780
  }
@@ -23431,12 +23431,12 @@ var require_dist = __commonJS({
23431
23431
  throw new Error(`Unknown format "${name}"`);
23432
23432
  return f;
23433
23433
  };
23434
- function addFormats(ajv, list, fs7, exportName) {
23434
+ function addFormats(ajv, list, fs8, exportName) {
23435
23435
  var _a;
23436
23436
  var _b;
23437
23437
  (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
23438
23438
  for (const f of list)
23439
- ajv.addFormat(f, fs7[f]);
23439
+ ajv.addFormat(f, fs8[f]);
23440
23440
  }
23441
23441
  module.exports = exports = formatsPlugin;
23442
23442
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -24139,8 +24139,8 @@ var require_utils3 = __commonJS({
24139
24139
  }
24140
24140
  return ind;
24141
24141
  }
24142
- function removeDotSegments(path11) {
24143
- let input = path11;
24142
+ function removeDotSegments(path12) {
24143
+ let input = path12;
24144
24144
  const output = [];
24145
24145
  let nextSlash = -1;
24146
24146
  let len = 0;
@@ -24485,8 +24485,8 @@ var require_schemes3 = __commonJS({
24485
24485
  wsComponent.secure = void 0;
24486
24486
  }
24487
24487
  if (wsComponent.resourceName) {
24488
- const [path11, query2] = wsComponent.resourceName.split("?");
24489
- wsComponent.path = path11 && path11 !== "/" ? path11 : void 0;
24488
+ const [path12, query2] = wsComponent.resourceName.split("?");
24489
+ wsComponent.path = path12 && path12 !== "/" ? path12 : void 0;
24490
24490
  wsComponent.query = query2;
24491
24491
  wsComponent.resourceName = void 0;
24492
24492
  }
@@ -24572,7 +24572,7 @@ var require_schemes3 = __commonJS({
24572
24572
  serialize: wsSerialize
24573
24573
  }
24574
24574
  );
24575
- var wss2 = (
24575
+ var wss3 = (
24576
24576
  /** @type {SchemeHandler} */
24577
24577
  {
24578
24578
  scheme: "wss",
@@ -24605,7 +24605,7 @@ var require_schemes3 = __commonJS({
24605
24605
  http: http3,
24606
24606
  https,
24607
24607
  ws,
24608
- wss: wss2,
24608
+ wss: wss3,
24609
24609
  urn,
24610
24610
  "urn:uuid": urnuuid
24611
24611
  }
@@ -32003,13 +32003,13 @@ var require_node = __commonJS({
32003
32003
  this.staticChildrenNodes[index] = node;
32004
32004
  }
32005
32005
  }
32006
- findStaticMatchingChild(path11, pathIndex) {
32007
- const charCode = path11.charCodeAt(pathIndex);
32006
+ findStaticMatchingChild(path12, pathIndex) {
32007
+ const charCode = path12.charCodeAt(pathIndex);
32008
32008
  const charCodes = this.staticChildrenCharCodes;
32009
32009
  for (let i = 0; i < charCodes.length; i++) {
32010
32010
  if (charCodes[i] === charCode) {
32011
32011
  const staticChild = this.staticChildrenNodes[i];
32012
- if (staticChild.matchPrefix(path11, pathIndex)) {
32012
+ if (staticChild.matchPrefix(path12, pathIndex)) {
32013
32013
  return staticChild;
32014
32014
  }
32015
32015
  return null;
@@ -32017,34 +32017,34 @@ var require_node = __commonJS({
32017
32017
  }
32018
32018
  return null;
32019
32019
  }
32020
- getStaticChild(path11, pathIndex = 0) {
32021
- if (path11.length === pathIndex) {
32020
+ getStaticChild(path12, pathIndex = 0) {
32021
+ if (path12.length === pathIndex) {
32022
32022
  return this;
32023
32023
  }
32024
- const staticChild = this.findStaticMatchingChild(path11, pathIndex);
32024
+ const staticChild = this.findStaticMatchingChild(path12, pathIndex);
32025
32025
  if (staticChild) {
32026
- return staticChild.getStaticChild(path11, pathIndex + staticChild.prefix.length);
32026
+ return staticChild.getStaticChild(path12, pathIndex + staticChild.prefix.length);
32027
32027
  }
32028
32028
  return null;
32029
32029
  }
32030
- createStaticChild(path11) {
32031
- if (path11.length === 0) {
32030
+ createStaticChild(path12) {
32031
+ if (path12.length === 0) {
32032
32032
  return this;
32033
32033
  }
32034
- const childIndex = this.staticChildrenCharCodes.indexOf(path11.charCodeAt(0));
32034
+ const childIndex = this.staticChildrenCharCodes.indexOf(path12.charCodeAt(0));
32035
32035
  let staticChild = childIndex === -1 ? void 0 : this.staticChildrenNodes[childIndex];
32036
32036
  if (staticChild) {
32037
32037
  let i = 1;
32038
32038
  for (; i < staticChild.prefix.length; i++) {
32039
- if (path11.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
32039
+ if (path12.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
32040
32040
  staticChild = staticChild.split(this, i);
32041
32041
  break;
32042
32042
  }
32043
32043
  }
32044
- return staticChild.createStaticChild(path11.slice(i));
32044
+ return staticChild.createStaticChild(path12.slice(i));
32045
32045
  }
32046
- const node = new StaticNode(path11);
32047
- this.setStaticChild(path11.charAt(0), node);
32046
+ const node = new StaticNode(path12);
32047
+ this.setStaticChild(path12.charAt(0), node);
32048
32048
  return node;
32049
32049
  }
32050
32050
  };
@@ -32104,8 +32104,8 @@ var require_node = __commonJS({
32104
32104
  parentNode.setStaticChild(parentPrefix.charAt(0), staticNode);
32105
32105
  return staticNode;
32106
32106
  }
32107
- getNextNode(path11, pathIndex, nodeStack, paramsCount) {
32108
- let node = this.findStaticMatchingChild(path11, pathIndex);
32107
+ getNextNode(path12, pathIndex, nodeStack, paramsCount) {
32108
+ let node = this.findStaticMatchingChild(path12, pathIndex);
32109
32109
  let parametricBrotherNodeIndex = 0;
32110
32110
  if (node === null) {
32111
32111
  if (this.parametricChildren.length === 0) {
@@ -32152,8 +32152,8 @@ var require_node = __commonJS({
32152
32152
  this.kind = NODE_TYPES.PARAMETRIC;
32153
32153
  this.nodePaths = /* @__PURE__ */ new Set([nodePath2]);
32154
32154
  }
32155
- getNextNode(path11, pathIndex) {
32156
- return this.findStaticMatchingChild(path11, pathIndex);
32155
+ getNextNode(path12, pathIndex) {
32156
+ return this.findStaticMatchingChild(path12, pathIndex);
32157
32157
  }
32158
32158
  };
32159
32159
  var WildcardNode = class extends Node {
@@ -32509,81 +32509,81 @@ var require_url_sanitizer = __commonJS({
32509
32509
  return String.fromCharCode(charCode);
32510
32510
  }
32511
32511
  var MIN_NATIVE_SCAN_LENGTH = 12;
32512
- function safeDecodeURI(path11, useSemicolonDelimiter) {
32513
- if (path11.length >= MIN_NATIVE_SCAN_LENGTH) {
32514
- return safeDecodeURINativeScan(path11, useSemicolonDelimiter);
32512
+ function safeDecodeURI(path12, useSemicolonDelimiter) {
32513
+ if (path12.length >= MIN_NATIVE_SCAN_LENGTH) {
32514
+ return safeDecodeURINativeScan(path12, useSemicolonDelimiter);
32515
32515
  }
32516
- return safeDecodeURICharScan(path11, useSemicolonDelimiter, 1);
32516
+ return safeDecodeURICharScan(path12, useSemicolonDelimiter, 1);
32517
32517
  }
32518
- function safeDecodeURINativeScan(path11, useSemicolonDelimiter) {
32519
- const percentIndex = path11.indexOf("%", 1);
32520
- let delimIndex = path11.indexOf("?", 1);
32521
- const hashIndex = path11.indexOf("#", 1);
32518
+ function safeDecodeURINativeScan(path12, useSemicolonDelimiter) {
32519
+ const percentIndex = path12.indexOf("%", 1);
32520
+ let delimIndex = path12.indexOf("?", 1);
32521
+ const hashIndex = path12.indexOf("#", 1);
32522
32522
  if (hashIndex !== -1 && (delimIndex === -1 || hashIndex < delimIndex)) {
32523
32523
  delimIndex = hashIndex;
32524
32524
  }
32525
32525
  if (useSemicolonDelimiter) {
32526
- const semicolonIndex = path11.indexOf(";", 1);
32526
+ const semicolonIndex = path12.indexOf(";", 1);
32527
32527
  if (semicolonIndex !== -1 && (delimIndex === -1 || semicolonIndex < delimIndex)) {
32528
32528
  delimIndex = semicolonIndex;
32529
32529
  }
32530
32530
  }
32531
32531
  if (percentIndex === -1 || delimIndex !== -1 && percentIndex > delimIndex) {
32532
32532
  if (delimIndex === -1) {
32533
- return { path: path11, querystring: "", shouldDecodeParam: false };
32533
+ return { path: path12, querystring: "", shouldDecodeParam: false };
32534
32534
  }
32535
32535
  return {
32536
- path: path11.slice(0, delimIndex),
32537
- querystring: path11.slice(delimIndex + 1),
32536
+ path: path12.slice(0, delimIndex),
32537
+ querystring: path12.slice(delimIndex + 1),
32538
32538
  shouldDecodeParam: false
32539
32539
  };
32540
32540
  }
32541
- return safeDecodeURIPercentScan(path11, useSemicolonDelimiter, percentIndex);
32541
+ return safeDecodeURIPercentScan(path12, useSemicolonDelimiter, percentIndex);
32542
32542
  }
32543
- function safeDecodeURICharScan(path11, useSemicolonDelimiter, startIndex) {
32544
- for (let i = startIndex; i < path11.length; i++) {
32545
- const charCode = path11.charCodeAt(i);
32543
+ function safeDecodeURICharScan(path12, useSemicolonDelimiter, startIndex) {
32544
+ for (let i = startIndex; i < path12.length; i++) {
32545
+ const charCode = path12.charCodeAt(i);
32546
32546
  if (charCode === 37) {
32547
- return safeDecodeURIPercentScan(path11, useSemicolonDelimiter, i);
32547
+ return safeDecodeURIPercentScan(path12, useSemicolonDelimiter, i);
32548
32548
  } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
32549
32549
  return {
32550
- path: path11.slice(0, i),
32551
- querystring: path11.slice(i + 1),
32550
+ path: path12.slice(0, i),
32551
+ querystring: path12.slice(i + 1),
32552
32552
  shouldDecodeParam: false
32553
32553
  };
32554
32554
  }
32555
32555
  }
32556
- return { path: path11, querystring: "", shouldDecodeParam: false };
32556
+ return { path: path12, querystring: "", shouldDecodeParam: false };
32557
32557
  }
32558
- function reencodePercentChar(path11, index) {
32559
- return path11.slice(0, index + 1) + "25" + path11.slice(index + 1);
32558
+ function reencodePercentChar(path12, index) {
32559
+ return path12.slice(0, index + 1) + "25" + path12.slice(index + 1);
32560
32560
  }
32561
- function safeDecodeURIPercentScan(path11, useSemicolonDelimiter, startIndex) {
32561
+ function safeDecodeURIPercentScan(path12, useSemicolonDelimiter, startIndex) {
32562
32562
  let shouldDecode = false;
32563
32563
  let shouldDecodeParam = false;
32564
32564
  let querystring = "";
32565
- for (let i = startIndex; i < path11.length; i++) {
32566
- const charCode = path11.charCodeAt(i);
32565
+ for (let i = startIndex; i < path12.length; i++) {
32566
+ const charCode = path12.charCodeAt(i);
32567
32567
  if (charCode === 37) {
32568
- const componentCharCode = decodeComponentCharCode(path11.charCodeAt(i + 1), path11.charCodeAt(i + 2));
32568
+ const componentCharCode = decodeComponentCharCode(path12.charCodeAt(i + 1), path12.charCodeAt(i + 2));
32569
32569
  if (componentCharCode === 0) {
32570
32570
  shouldDecode = true;
32571
32571
  } else {
32572
32572
  shouldDecodeParam = true;
32573
32573
  if (componentCharCode === 37) {
32574
32574
  shouldDecode = true;
32575
- path11 = reencodePercentChar(path11, i);
32575
+ path12 = reencodePercentChar(path12, i);
32576
32576
  i += 2;
32577
32577
  }
32578
32578
  i += 2;
32579
32579
  }
32580
32580
  } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
32581
- querystring = path11.slice(i + 1);
32582
- path11 = path11.slice(0, i);
32581
+ querystring = path12.slice(i + 1);
32582
+ path12 = path12.slice(0, i);
32583
32583
  break;
32584
32584
  }
32585
32585
  }
32586
- const decodedPath = shouldDecode ? decodeURI(path11) : path11;
32586
+ const decodedPath = shouldDecode ? decodeURI(path12) : path12;
32587
32587
  return { path: decodedPath, querystring, shouldDecodeParam };
32588
32588
  }
32589
32589
  function safeDecodeURIComponent(uriComponent) {
@@ -32678,7 +32678,7 @@ var require_find_my_way = __commonJS({
32678
32678
  this.trees = /* @__PURE__ */ Object.create(null);
32679
32679
  this._treeGET = null;
32680
32680
  }
32681
- Router.prototype.on = function on(method, path11, opts, handler, store) {
32681
+ Router.prototype.on = function on(method, path12, opts, handler, store) {
32682
32682
  if (typeof opts === "function") {
32683
32683
  if (handler !== void 0) {
32684
32684
  store = handler;
@@ -32686,34 +32686,34 @@ var require_find_my_way = __commonJS({
32686
32686
  handler = opts;
32687
32687
  opts = {};
32688
32688
  }
32689
- assert(typeof path11 === "string", "Path should be a string");
32690
- assert(path11.length > 0, "The path could not be empty");
32691
- assert(path11[0] === "/" || path11[0] === "*", "The first character of a path should be `/` or `*`");
32689
+ assert(typeof path12 === "string", "Path should be a string");
32690
+ assert(path12.length > 0, "The path could not be empty");
32691
+ assert(path12[0] === "/" || path12[0] === "*", "The first character of a path should be `/` or `*`");
32692
32692
  assert(typeof handler === "function", "Handler should be a function");
32693
- const optionalParamMatch = path11.match(OPTIONAL_PARAM_REGEXP);
32693
+ const optionalParamMatch = path12.match(OPTIONAL_PARAM_REGEXP);
32694
32694
  if (optionalParamMatch) {
32695
- assert(path11.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32696
- const pathFull = path11.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32697
- const pathOptional = path11.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32695
+ assert(path12.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32696
+ const pathFull = path12.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32697
+ const pathOptional = path12.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32698
32698
  this.on(method, pathFull, opts, handler, store);
32699
32699
  this.on(method, pathOptional, opts, handler, store);
32700
32700
  return;
32701
32701
  }
32702
- const route = path11;
32702
+ const route = path12;
32703
32703
  if (this.ignoreDuplicateSlashes) {
32704
- path11 = removeDuplicateSlashes(path11);
32704
+ path12 = removeDuplicateSlashes(path12);
32705
32705
  }
32706
32706
  if (this.ignoreTrailingSlash) {
32707
- path11 = trimLastSlash(path11);
32707
+ path12 = trimLastSlash(path12);
32708
32708
  }
32709
32709
  const methods = Array.isArray(method) ? method : [method];
32710
32710
  for (const method2 of methods) {
32711
32711
  assert(typeof method2 === "string", "Method should be a string");
32712
32712
  assert(httpMethods.includes(method2), `Method '${method2}' is not an http method.`);
32713
- this._on(method2, path11, opts, handler, store, route);
32713
+ this._on(method2, path12, opts, handler, store, route);
32714
32714
  }
32715
32715
  };
32716
- Router.prototype._on = function _on(method, path11, opts, handler, store) {
32716
+ Router.prototype._on = function _on(method, path12, opts, handler, store) {
32717
32717
  let constraints = {};
32718
32718
  if (opts.constraints !== void 0) {
32719
32719
  assert(typeof opts.constraints === "object" && opts.constraints !== null, "Constraints should be an object");
@@ -32726,7 +32726,7 @@ var require_find_my_way = __commonJS({
32726
32726
  if (this.trees[method] === void 0) {
32727
32727
  this.trees[method] = new StaticNode("/");
32728
32728
  }
32729
- let pattern = path11;
32729
+ let pattern = path12;
32730
32730
  if (pattern === "*" && this.trees[method].prefix.length !== 0) {
32731
32731
  const currentRoot = this.trees[method];
32732
32732
  this.trees[method] = new StaticNode("");
@@ -32834,19 +32834,19 @@ var require_find_my_way = __commonJS({
32834
32834
  throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`);
32835
32835
  }
32836
32836
  }
32837
- const route = { method, path: path11, pattern, params, opts, handler, store };
32837
+ const route = { method, path: path12, pattern, params, opts, handler, store };
32838
32838
  this.routes.push(route);
32839
32839
  currentNode.addRoute(route, this.constrainer);
32840
32840
  };
32841
- Router.prototype.hasRoute = function hasRoute(method, path11, constraints) {
32842
- const route = this.findRoute(method, path11, constraints);
32841
+ Router.prototype.hasRoute = function hasRoute(method, path12, constraints) {
32842
+ const route = this.findRoute(method, path12, constraints);
32843
32843
  return route !== null;
32844
32844
  };
32845
- Router.prototype.findRoute = function findNode(method, path11, constraints = {}) {
32845
+ Router.prototype.findRoute = function findNode(method, path12, constraints = {}) {
32846
32846
  if (this.trees[method] === void 0) {
32847
32847
  return null;
32848
32848
  }
32849
- let pattern = path11;
32849
+ let pattern = path12;
32850
32850
  let currentNode = this.trees[method];
32851
32851
  let parentNodePathIndex = currentNode.prefix.length;
32852
32852
  const params = [];
@@ -32967,39 +32967,39 @@ var require_find_my_way = __commonJS({
32967
32967
  this._treeGET = null;
32968
32968
  this.routes = [];
32969
32969
  };
32970
- Router.prototype.off = function off(method, path11, constraints) {
32971
- assert(typeof path11 === "string", "Path should be a string");
32972
- assert(path11.length > 0, "The path could not be empty");
32973
- assert(path11[0] === "/" || path11[0] === "*", "The first character of a path should be `/` or `*`");
32970
+ Router.prototype.off = function off(method, path12, constraints) {
32971
+ assert(typeof path12 === "string", "Path should be a string");
32972
+ assert(path12.length > 0, "The path could not be empty");
32973
+ assert(path12[0] === "/" || path12[0] === "*", "The first character of a path should be `/` or `*`");
32974
32974
  assert(
32975
32975
  typeof constraints === "undefined" || typeof constraints === "object" && !Array.isArray(constraints) && constraints !== null,
32976
32976
  "Constraints should be an object or undefined."
32977
32977
  );
32978
- const optionalParamMatch = path11.match(OPTIONAL_PARAM_REGEXP);
32978
+ const optionalParamMatch = path12.match(OPTIONAL_PARAM_REGEXP);
32979
32979
  if (optionalParamMatch) {
32980
- assert(path11.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32981
- const pathFull = path11.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32982
- const pathOptional = path11.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32980
+ assert(path12.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32981
+ const pathFull = path12.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32982
+ const pathOptional = path12.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32983
32983
  this.off(method, pathFull, constraints);
32984
32984
  this.off(method, pathOptional, constraints);
32985
32985
  return;
32986
32986
  }
32987
32987
  if (this.ignoreDuplicateSlashes) {
32988
- path11 = removeDuplicateSlashes(path11);
32988
+ path12 = removeDuplicateSlashes(path12);
32989
32989
  }
32990
32990
  if (this.ignoreTrailingSlash) {
32991
- path11 = trimLastSlash(path11);
32991
+ path12 = trimLastSlash(path12);
32992
32992
  }
32993
32993
  const methods = Array.isArray(method) ? method : [method];
32994
32994
  for (const method2 of methods) {
32995
- this._off(method2, path11, constraints);
32995
+ this._off(method2, path12, constraints);
32996
32996
  }
32997
32997
  };
32998
- Router.prototype._off = function _off(method, path11, constraints) {
32998
+ Router.prototype._off = function _off(method, path12, constraints) {
32999
32999
  assert(typeof method === "string", "Method should be a string");
33000
33000
  assert(httpMethods.includes(method), `Method '${method}' is not an http method.`);
33001
33001
  function matcherWithoutConstraints(route) {
33002
- return method !== route.method || path11 !== route.path;
33002
+ return method !== route.method || path12 !== route.path;
33003
33003
  }
33004
33004
  function matcherWithConstraints(route) {
33005
33005
  return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {});
@@ -33036,37 +33036,37 @@ var require_find_my_way = __commonJS({
33036
33036
  if (handle === null) return this._defaultRoute(req, res, ctx);
33037
33037
  return ctx === void 0 ? handle.handler(req, res, handle.params, handle.store, handle.searchParams) : handle.handler.call(ctx, req, res, handle.params, handle.store, handle.searchParams);
33038
33038
  };
33039
- Router.prototype.find = function find(method, path11, derivedConstraints) {
33039
+ Router.prototype.find = function find(method, path12, derivedConstraints) {
33040
33040
  let currentNode = method === "GET" ? this._treeGET : this.trees[method];
33041
33041
  if (currentNode == null) return null;
33042
- if (path11.charCodeAt(0) !== 47) {
33043
- path11 = path11.replace(FULL_PATH_REGEXP, "/");
33042
+ if (path12.charCodeAt(0) !== 47) {
33043
+ path12 = path12.replace(FULL_PATH_REGEXP, "/");
33044
33044
  }
33045
33045
  if (this.ignoreDuplicateSlashes) {
33046
- path11 = removeDuplicateSlashes(path11);
33046
+ path12 = removeDuplicateSlashes(path12);
33047
33047
  }
33048
33048
  let sanitizedUrl;
33049
33049
  let querystring2;
33050
33050
  let shouldDecodeParam;
33051
33051
  try {
33052
- sanitizedUrl = path11.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path11, this.useSemicolonDelimiter) : safeDecodeURICharScan(path11, this.useSemicolonDelimiter, 1);
33053
- path11 = sanitizedUrl.path;
33052
+ sanitizedUrl = path12.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path12, this.useSemicolonDelimiter) : safeDecodeURICharScan(path12, this.useSemicolonDelimiter, 1);
33053
+ path12 = sanitizedUrl.path;
33054
33054
  querystring2 = sanitizedUrl.querystring;
33055
33055
  shouldDecodeParam = sanitizedUrl.shouldDecodeParam;
33056
33056
  } catch (error) {
33057
- return this._onBadUrl(path11);
33057
+ return this._onBadUrl(path12);
33058
33058
  }
33059
33059
  if (this.ignoreTrailingSlash) {
33060
- path11 = trimLastSlash(path11);
33060
+ path12 = trimLastSlash(path12);
33061
33061
  }
33062
- const originPath = path11;
33062
+ const originPath = path12;
33063
33063
  if (this.caseSensitive === false) {
33064
- path11 = path11.toLowerCase();
33064
+ path12 = path12.toLowerCase();
33065
33065
  }
33066
33066
  const maxParamLength = this.maxParamLength;
33067
33067
  let pathIndex = currentNode.prefix.length;
33068
33068
  const params = [];
33069
- const pathLen = path11.length;
33069
+ const pathLen = path12.length;
33070
33070
  const brothersNodesStack = [];
33071
33071
  let maxParamLengthExceeded = false;
33072
33072
  while (true) {
@@ -33081,7 +33081,7 @@ var require_find_my_way = __commonJS({
33081
33081
  };
33082
33082
  }
33083
33083
  }
33084
- let node = currentNode.getNextNode(path11, pathIndex, brothersNodesStack, params.length);
33084
+ let node = currentNode.getNextNode(path12, pathIndex, brothersNodesStack, params.length);
33085
33085
  if (node === null) {
33086
33086
  if (brothersNodesStack.length === 0) {
33087
33087
  if (maxParamLengthExceeded && this.onMaxParamLength) {
@@ -33182,8 +33182,8 @@ var require_find_my_way = __commonJS({
33182
33182
  Router.prototype._rebuild = function(routes) {
33183
33183
  this.reset();
33184
33184
  for (const route of routes) {
33185
- const { method, path: path11, opts, handler, store } = route;
33186
- this._on(method, path11, opts, handler, store);
33185
+ const { method, path: path12, opts, handler, store } = route;
33186
+ this._on(method, path12, opts, handler, store);
33187
33187
  }
33188
33188
  };
33189
33189
  Router.prototype._defaultRoute = function(req, res, ctx) {
@@ -33194,24 +33194,24 @@ var require_find_my_way = __commonJS({
33194
33194
  res.end();
33195
33195
  }
33196
33196
  };
33197
- Router.prototype._onBadUrl = function(path11) {
33197
+ Router.prototype._onBadUrl = function(path12) {
33198
33198
  if (this.onBadUrl === null) {
33199
33199
  return null;
33200
33200
  }
33201
33201
  const onBadUrl = this.onBadUrl;
33202
33202
  return {
33203
- handler: (req, res, ctx) => onBadUrl(path11, req, res),
33203
+ handler: (req, res, ctx) => onBadUrl(path12, req, res),
33204
33204
  params: {},
33205
33205
  store: null
33206
33206
  };
33207
33207
  };
33208
- Router.prototype._onMaxParamLength = function(path11) {
33208
+ Router.prototype._onMaxParamLength = function(path12) {
33209
33209
  if (this.onMaxParamLength === null) {
33210
33210
  return null;
33211
33211
  }
33212
33212
  const onMaxParamLength = this.onMaxParamLength;
33213
33213
  return {
33214
- handler: (req, res, ctx) => onMaxParamLength(path11, req, res),
33214
+ handler: (req, res, ctx) => onMaxParamLength(path12, req, res),
33215
33215
  params: {},
33216
33216
  store: null
33217
33217
  };
@@ -33243,12 +33243,12 @@ var require_find_my_way = __commonJS({
33243
33243
  if (!httpMethods.hasOwnProperty(i)) continue;
33244
33244
  const m = httpMethods[i];
33245
33245
  const methodName = m.toLowerCase();
33246
- Router.prototype[methodName] = function(path11, handler, store) {
33247
- return this.on(m, path11, handler, store);
33246
+ Router.prototype[methodName] = function(path12, handler, store) {
33247
+ return this.on(m, path12, handler, store);
33248
33248
  };
33249
33249
  }
33250
- Router.prototype.all = function(path11, handler, store) {
33251
- this.on(httpMethods, path11, handler, store);
33250
+ Router.prototype.all = function(path12, handler, store) {
33251
+ this.on(httpMethods, path12, handler, store);
33252
33252
  };
33253
33253
  Router.sanitizeUrlPath = function sanitizeUrlPath(url, useSemicolonDelimiter) {
33254
33254
  const decoded = safeDecodeURI(url, useSemicolonDelimiter);
@@ -33263,14 +33263,14 @@ var require_find_my_way = __commonJS({
33263
33263
  function escapeRegExp(string) {
33264
33264
  return string.replace(ESCAPE_REGEXP, "\\$&");
33265
33265
  }
33266
- function removeDuplicateSlashes(path11) {
33267
- return path11.indexOf("//") !== -1 ? path11.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path11;
33266
+ function removeDuplicateSlashes(path12) {
33267
+ return path12.indexOf("//") !== -1 ? path12.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path12;
33268
33268
  }
33269
- function trimLastSlash(path11) {
33270
- if (path11.length > 1 && path11.charCodeAt(path11.length - 1) === 47) {
33271
- return path11.slice(0, -1);
33269
+ function trimLastSlash(path12) {
33270
+ if (path12.length > 1 && path12.charCodeAt(path12.length - 1) === 47) {
33271
+ return path12.slice(0, -1);
33272
33272
  }
33273
- return path11;
33273
+ return path12;
33274
33274
  }
33275
33275
  function trimRegExpStartAndEnd(regexString) {
33276
33276
  if (regexString.charCodeAt(1) === 94) {
@@ -33281,22 +33281,22 @@ var require_find_my_way = __commonJS({
33281
33281
  }
33282
33282
  return regexString;
33283
33283
  }
33284
- function getClosingParenthensePosition(path11, idx) {
33284
+ function getClosingParenthensePosition(path12, idx) {
33285
33285
  let parentheses = 1;
33286
- while (idx < path11.length) {
33286
+ while (idx < path12.length) {
33287
33287
  idx++;
33288
- if (path11.charCodeAt(idx) === 92) {
33288
+ if (path12.charCodeAt(idx) === 92) {
33289
33289
  idx++;
33290
33290
  continue;
33291
33291
  }
33292
- if (path11.charCodeAt(idx) === 41) {
33292
+ if (path12.charCodeAt(idx) === 41) {
33293
33293
  parentheses--;
33294
- } else if (path11.charCodeAt(idx) === 40) {
33294
+ } else if (path12.charCodeAt(idx) === 40) {
33295
33295
  parentheses++;
33296
33296
  }
33297
33297
  if (!parentheses) return idx;
33298
33298
  }
33299
- throw new TypeError('Invalid regexp expression in "' + path11 + '"');
33299
+ throw new TypeError('Invalid regexp expression in "' + path12 + '"');
33300
33300
  }
33301
33301
  function defaultBuildPrettyMeta(route) {
33302
33302
  if (!route) return {};
@@ -33331,8 +33331,8 @@ var require_head_route = __commonJS({
33331
33331
  done(null, null);
33332
33332
  return;
33333
33333
  }
33334
- const size = "" + Buffer.byteLength(payload);
33335
- reply.header("content-length", size);
33334
+ const size2 = "" + Buffer.byteLength(payload);
33335
+ reply.header("content-length", size2);
33336
33336
  done(null, null);
33337
33337
  }
33338
33338
  function parseHeadOnSendHandlers(onSendHandlers) {
@@ -33529,12 +33529,12 @@ var require_route = __commonJS({
33529
33529
  function route({ options: options2, isFastify }) {
33530
33530
  throwIfAlreadyStarted("Cannot add route!");
33531
33531
  const opts = { ...options2 };
33532
- const path11 = opts.url || opts.path || "";
33532
+ const path12 = opts.url || opts.path || "";
33533
33533
  if (!opts.handler) {
33534
- throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path11);
33534
+ throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path12);
33535
33535
  }
33536
33536
  if (opts.errorHandler !== void 0 && typeof opts.errorHandler !== "function") {
33537
- throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path11);
33537
+ throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path12);
33538
33538
  }
33539
33539
  validateBodyLimitOption(opts.bodyLimit);
33540
33540
  validateHandlerTimeoutOption(opts.handlerTimeout);
@@ -33544,22 +33544,22 @@ var require_route = __commonJS({
33544
33544
  if (Array.isArray(opts.method)) {
33545
33545
  for (let i = 0; i < opts.method.length; ++i) {
33546
33546
  opts.method[i] = normalizeAndValidateMethod.call(this, opts.method[i]);
33547
- validateSchemaBodyOption.call(this, opts.method[i], path11, opts.schema);
33547
+ validateSchemaBodyOption.call(this, opts.method[i], path12, opts.schema);
33548
33548
  isGetRoute = opts.method.includes("GET");
33549
33549
  isHeadRoute = opts.method.includes("HEAD");
33550
33550
  }
33551
33551
  } else {
33552
33552
  opts.method = normalizeAndValidateMethod.call(this, opts.method);
33553
- validateSchemaBodyOption.call(this, opts.method, path11, opts.schema);
33553
+ validateSchemaBodyOption.call(this, opts.method, path12, opts.schema);
33554
33554
  isGetRoute = opts.method === "GET";
33555
33555
  isHeadRoute = opts.method === "HEAD";
33556
33556
  }
33557
33557
  const headOpts = shouldExposeHead && isGetRoute ? { ...options2 } : null;
33558
33558
  const prefix = this[kRoutePrefix];
33559
- if (path11 === "/" && prefix.length > 0 && opts.method !== "HEAD") {
33559
+ if (path12 === "/" && prefix.length > 0 && opts.method !== "HEAD") {
33560
33560
  switch (opts.prefixTrailingSlash) {
33561
33561
  case "slash":
33562
- addNewRoute.call(this, { path: path11, isFastify });
33562
+ addNewRoute.call(this, { path: path12, isFastify });
33563
33563
  break;
33564
33564
  case "no-slash":
33565
33565
  addNewRoute.call(this, { path: "", isFastify });
@@ -33568,20 +33568,20 @@ var require_route = __commonJS({
33568
33568
  default:
33569
33569
  addNewRoute.call(this, { path: "", isFastify });
33570
33570
  if (ignoreTrailingSlash !== true && (ignoreDuplicateSlashes !== true || !prefix.endsWith("/"))) {
33571
- addNewRoute.call(this, { path: path11, prefixing: true, isFastify });
33571
+ addNewRoute.call(this, { path: path12, prefixing: true, isFastify });
33572
33572
  }
33573
33573
  }
33574
- } else if (path11[0] === "/" && prefix.endsWith("/")) {
33575
- addNewRoute.call(this, { path: path11.slice(1), isFastify });
33574
+ } else if (path12[0] === "/" && prefix.endsWith("/")) {
33575
+ addNewRoute.call(this, { path: path12.slice(1), isFastify });
33576
33576
  } else {
33577
- addNewRoute.call(this, { path: path11, isFastify });
33577
+ addNewRoute.call(this, { path: path12, isFastify });
33578
33578
  }
33579
33579
  return this;
33580
- function addNewRoute({ path: path12, prefixing = false, isFastify: isFastify2 = false }) {
33581
- const url = prefix + path12;
33580
+ function addNewRoute({ path: path13, prefixing = false, isFastify: isFastify2 = false }) {
33581
+ const url = prefix + path13;
33582
33582
  opts.url = url;
33583
33583
  opts.path = url;
33584
- opts.routePath = path12;
33584
+ opts.routePath = path13;
33585
33585
  opts.prefix = prefix;
33586
33586
  opts.logLevel = opts.logLevel || this[kLogLevel];
33587
33587
  validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger);
@@ -33713,7 +33713,7 @@ var require_route = __commonJS({
33713
33713
  });
33714
33714
  if (shouldExposeHead && isGetRoute && !isHeadRoute && !hasHEADHandler) {
33715
33715
  const onSendHandlers = parseHeadOnSendHandlers(headOpts.onSend);
33716
- prepareRoute.call(this, { method: "HEAD", url: path12, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true });
33716
+ prepareRoute.call(this, { method: "HEAD", url: path13, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true });
33717
33717
  }
33718
33718
  }
33719
33719
  }
@@ -33837,9 +33837,9 @@ var require_route = __commonJS({
33837
33837
  }
33838
33838
  return method;
33839
33839
  }
33840
- function validateSchemaBodyOption(method, path11, schema) {
33840
+ function validateSchemaBodyOption(method, path12, schema) {
33841
33841
  if (this[kSupportedHTTPMethods].bodyless.has(method) && schema?.body) {
33842
- throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path11);
33842
+ throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path12);
33843
33843
  }
33844
33844
  }
33845
33845
  function validateBodyLimitOption(bodyLimit) {
@@ -33854,11 +33854,11 @@ var require_route = __commonJS({
33854
33854
  throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout);
33855
33855
  }
33856
33856
  }
33857
- function validateLogLevelOption(logLevel, method, path11, logger) {
33857
+ function validateLogLevelOption(logLevel, method, path12, logger) {
33858
33858
  if (logLevel == null || logLevel === "") return;
33859
33859
  if (logger?.levels?.values == null) return;
33860
33860
  if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) {
33861
- throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path11, logLevel);
33861
+ throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path12, logLevel);
33862
33862
  }
33863
33863
  }
33864
33864
  function runPreParsing(err, request, reply) {
@@ -33947,7 +33947,7 @@ var require_four_oh_four = __commonJS({
33947
33947
  });
33948
33948
  }
33949
33949
  function createRouteEventHandler() {
33950
- return function onRouteEvent(path11, req, res) {
33950
+ return function onRouteEvent(path12, req, res) {
33951
33951
  const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext];
33952
33952
  const id = getGenReqId(fourOhFourContext.server, req);
33953
33953
  const childLogger = createChildLogger(fourOhFourContext, logger, req, id);
@@ -36618,19 +36618,19 @@ var require_fastify = __commonJS({
36618
36618
  }
36619
36619
  fourOhFour.router.lookup(req, res);
36620
36620
  }
36621
- function onBadUrl(path11, req, res) {
36621
+ function onBadUrl(path12, req, res) {
36622
36622
  if (options.frameworkErrors) {
36623
36623
  const id = getGenReqId(routeEventContext.server, req);
36624
36624
  const childLogger = createChildLogger(routeEventContext, options.logger, req, id);
36625
36625
  const request = new Request(id, null, req, null, childLogger, routeEventContext);
36626
36626
  const reply = new Reply(res, request, childLogger);
36627
36627
  routeEventContext.server[kLogController].incomingRequest(request, reply);
36628
- return options.frameworkErrors(new FST_ERR_BAD_URL(path11), request, reply);
36628
+ return options.frameworkErrors(new FST_ERR_BAD_URL(path12), request, reply);
36629
36629
  }
36630
36630
  const body = JSON.stringify({
36631
36631
  error: "Bad Request",
36632
36632
  code: "FST_ERR_BAD_URL",
36633
- message: `'${path11}' is not a valid url component`,
36633
+ message: `'${path12}' is not a valid url component`,
36634
36634
  statusCode: 400
36635
36635
  });
36636
36636
  res.writeHead(400, {
@@ -36639,19 +36639,19 @@ var require_fastify = __commonJS({
36639
36639
  });
36640
36640
  res.end(body);
36641
36641
  }
36642
- function onMaxParamLength(path11, req, res) {
36642
+ function onMaxParamLength(path12, req, res) {
36643
36643
  if (options.frameworkErrors) {
36644
36644
  const id = getGenReqId(routeEventContext.server, req);
36645
36645
  const childLogger = createChildLogger(routeEventContext, options.logger, req, id);
36646
36646
  const request = new Request(id, null, req, null, childLogger, routeEventContext);
36647
36647
  const reply = new Reply(res, request, childLogger);
36648
36648
  routeEventContext.server[kLogController].incomingRequest(request, reply);
36649
- return options.frameworkErrors(new FST_ERR_MAX_PARAM_LENGTH(path11), request, reply);
36649
+ return options.frameworkErrors(new FST_ERR_MAX_PARAM_LENGTH(path12), request, reply);
36650
36650
  }
36651
36651
  const body = JSON.stringify({
36652
36652
  error: "Bad Request",
36653
36653
  code: "FST_ERR_MAX_PARAM_LENGTH",
36654
- message: `'${path11}' is exceeding the max param length`,
36654
+ message: `'${path12}' is exceeding the max param length`,
36655
36655
  statusCode: 414
36656
36656
  });
36657
36657
  res.writeHead(414, {
@@ -41001,8 +41001,8 @@ var import_cors = __toESM(require_cors(), 1);
41001
41001
  // src/db/index.ts
41002
41002
  import Database from "better-sqlite3";
41003
41003
  var db;
41004
- function initDb(path11 = "data.db") {
41005
- db = new Database(path11);
41004
+ function initDb(path12 = "data.db") {
41005
+ db = new Database(path12);
41006
41006
  db.pragma("journal_mode = WAL");
41007
41007
  db.pragma("foreign_keys = ON");
41008
41008
  createTables(db);
@@ -41187,6 +41187,9 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
41187
41187
  if (!turnColumns.some((c) => c.name === "resume_attempts")) {
41188
41188
  database.exec("ALTER TABLE turns ADD COLUMN resume_attempts INTEGER NOT NULL DEFAULT 0");
41189
41189
  }
41190
+ if (!turnColumns.some((c) => c.name === "resume_at")) {
41191
+ database.exec("ALTER TABLE turns ADD COLUMN resume_at TEXT");
41192
+ }
41190
41193
  const threadColumns = database.prepare("PRAGMA table_info(discussion_threads)").all();
41191
41194
  if (!threadColumns.some((c) => c.name === "external_thread_id")) {
41192
41195
  database.exec("ALTER TABLE discussion_threads ADD COLUMN external_thread_id TEXT");
@@ -41298,8 +41301,270 @@ function broadcast(event, data) {
41298
41301
  }
41299
41302
  }
41300
41303
 
41301
- // src/routes/sessions.ts
41304
+ // ../shared/terminal-protocol.ts
41305
+ var TERMINAL_CLOSE = {
41306
+ /** The same terminal was opened elsewhere, e.g. in a duplicated tab. */
41307
+ takenOver: 4001,
41308
+ /** Too many terminals are open on this machine. */
41309
+ limit: 4002,
41310
+ /** The shell could not start; the close reason says why. */
41311
+ unavailable: 4003,
41312
+ /** The request has no usable terminal id. */
41313
+ badRequest: 4004
41314
+ };
41315
+
41316
+ // src/terminal/manager.ts
41317
+ import fs from "node:fs";
41318
+ import { createRequire as createNodeRequire } from "node:module";
41319
+ import os from "node:os";
41302
41320
  import path from "node:path";
41321
+ var MAX_TERMINALS = 8;
41322
+ var DETACHED_TTL_MS = 15 * 6e4;
41323
+ var UNACKED_HIGH = 1024 * 1024;
41324
+ var UNACKED_LOW = 128 * 1024;
41325
+ var PING_MS = 3e4;
41326
+ var CLOSE_REASON_LENGTH = 120;
41327
+ var terminals = /* @__PURE__ */ new Map();
41328
+ var nodeRequire = createNodeRequire(import.meta.url);
41329
+ var ptyModule = null;
41330
+ function loadPty() {
41331
+ ptyModule ??= import("node-pty").then((mod) => {
41332
+ ensureSpawnHelperRuns();
41333
+ return mod;
41334
+ }).catch((err) => {
41335
+ ptyModule = null;
41336
+ throw err;
41337
+ });
41338
+ return ptyModule;
41339
+ }
41340
+ function ensureSpawnHelperRuns() {
41341
+ if (process.platform === "win32") return;
41342
+ try {
41343
+ const root = path.dirname(nodeRequire.resolve("node-pty/package.json"));
41344
+ fs.chmodSync(path.join(root, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"), 493);
41345
+ } catch {
41346
+ }
41347
+ }
41348
+ function loginShell() {
41349
+ if (process.platform === "win32") return { file: process.env.COMSPEC ?? "cmd.exe", args: [] };
41350
+ return { file: process.env.SHELL || os.userInfo().shell || "/bin/sh", args: ["-l"] };
41351
+ }
41352
+ function usableDir(dir) {
41353
+ try {
41354
+ if (dir && fs.statSync(dir).isDirectory()) return dir;
41355
+ } catch {
41356
+ }
41357
+ return os.homedir();
41358
+ }
41359
+ function bundledCliDir() {
41360
+ try {
41361
+ const sdkPlatform = `@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}`;
41362
+ return path.dirname(nodeRequire.resolve(`${sdkPlatform}/package.json`));
41363
+ } catch {
41364
+ return null;
41365
+ }
41366
+ }
41367
+ function shellEnv() {
41368
+ const env = {};
41369
+ for (const [key, value] of Object.entries(process.env)) {
41370
+ if (value !== void 0 && key !== "CLAUDECODE" && !key.startsWith("CLAUDE_CODE_RESUME_")) env[key] = value;
41371
+ }
41372
+ env.TERM = "xterm-256color";
41373
+ env.COLORTERM = "truecolor";
41374
+ env.LANG ||= "en_US.UTF-8";
41375
+ const cliDir = bundledCliDir();
41376
+ if (cliDir) env.PATH = env.PATH ? `${env.PATH}${path.delimiter}${cliDir}` : cliDir;
41377
+ return env;
41378
+ }
41379
+ function send(ws, message) {
41380
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));
41381
+ }
41382
+ function setPaused(term, paused) {
41383
+ if (term.paused === paused) return;
41384
+ term.paused = paused;
41385
+ if (paused) term.pty.pause();
41386
+ else term.pty.resume();
41387
+ }
41388
+ function resize(term, cols, rows) {
41389
+ try {
41390
+ term.pty.resize(cols, rows);
41391
+ } catch {
41392
+ }
41393
+ }
41394
+ function clearExpiry(term) {
41395
+ if (term.expiry) clearTimeout(term.expiry);
41396
+ term.expiry = null;
41397
+ }
41398
+ function startShell(pty, id, request) {
41399
+ const { file, args } = loginShell();
41400
+ const term = {
41401
+ pty: pty.spawn(file, args, {
41402
+ name: "xterm-256color",
41403
+ cols: request.cols,
41404
+ rows: request.rows,
41405
+ cwd: usableDir(request.cwd),
41406
+ env: shellEnv(),
41407
+ encoding: null
41408
+ // bytes: a multi-byte character may span two chunks
41409
+ }),
41410
+ socket: null,
41411
+ unacked: 0,
41412
+ paused: false,
41413
+ expiry: null
41414
+ };
41415
+ term.pty.onData((chunk) => {
41416
+ const ws = term.socket;
41417
+ if (!ws || ws.readyState !== ws.OPEN) return;
41418
+ const bytes = chunk;
41419
+ ws.send(bytes, { binary: true });
41420
+ term.unacked += bytes.length;
41421
+ if (term.unacked > UNACKED_HIGH) setPaused(term, true);
41422
+ });
41423
+ term.pty.onExit(({ exitCode }) => {
41424
+ clearExpiry(term);
41425
+ terminals.delete(id);
41426
+ const ws = term.socket;
41427
+ term.socket = null;
41428
+ if (!ws) return;
41429
+ send(ws, { type: "exit", code: exitCode });
41430
+ ws.close(1e3);
41431
+ });
41432
+ terminals.set(id, term);
41433
+ return term;
41434
+ }
41435
+ function onClientMessage(term, data, isBinary) {
41436
+ if (isBinary) {
41437
+ term.pty.write(data);
41438
+ return;
41439
+ }
41440
+ let message;
41441
+ try {
41442
+ message = JSON.parse(data.toString());
41443
+ } catch {
41444
+ return;
41445
+ }
41446
+ if (message.type === "resize") {
41447
+ const { cols, rows } = message;
41448
+ if (Number.isInteger(cols) && Number.isInteger(rows) && cols > 0 && rows > 0) resize(term, cols, rows);
41449
+ } else if (message.type === "ack" && Number.isFinite(message.bytes)) {
41450
+ term.unacked = Math.max(0, term.unacked - message.bytes);
41451
+ if (term.unacked < UNACKED_LOW) setPaused(term, false);
41452
+ }
41453
+ }
41454
+ function attach(term, ws, attached) {
41455
+ clearExpiry(term);
41456
+ const previous = term.socket;
41457
+ term.socket = ws;
41458
+ term.unacked = 0;
41459
+ previous?.close(TERMINAL_CLOSE.takenOver, "Opened somewhere else");
41460
+ setPaused(term, false);
41461
+ let alive = true;
41462
+ const ping = setInterval(() => {
41463
+ if (!alive) {
41464
+ ws.terminate();
41465
+ return;
41466
+ }
41467
+ alive = false;
41468
+ ws.ping();
41469
+ }, PING_MS);
41470
+ ping.unref?.();
41471
+ ws.on("pong", () => {
41472
+ alive = true;
41473
+ });
41474
+ ws.on("message", (data, isBinary) => {
41475
+ if (term.socket === ws) onClientMessage(term, data, isBinary);
41476
+ });
41477
+ ws.on("close", () => {
41478
+ clearInterval(ping);
41479
+ if (term.socket !== ws) return;
41480
+ term.socket = null;
41481
+ setPaused(term, true);
41482
+ term.expiry = setTimeout(() => term.pty.kill(), DETACHED_TTL_MS);
41483
+ term.expiry.unref?.();
41484
+ });
41485
+ ws.on("error", () => ws.terminate());
41486
+ send(ws, { type: "ready", attached });
41487
+ }
41488
+ async function openTerminal(ws, request) {
41489
+ let pty;
41490
+ try {
41491
+ pty = await loadPty();
41492
+ } catch (err) {
41493
+ console.error("[terminal] node-pty is not available:", err.message);
41494
+ ws.close(TERMINAL_CLOSE.unavailable, "This machine cannot run a terminal here");
41495
+ return;
41496
+ }
41497
+ if (ws.readyState !== ws.OPEN) return;
41498
+ const running = terminals.get(request.id);
41499
+ if (running) {
41500
+ resize(running, request.cols, request.rows);
41501
+ attach(running, ws, true);
41502
+ return;
41503
+ }
41504
+ if (terminals.size >= MAX_TERMINALS) {
41505
+ ws.close(TERMINAL_CLOSE.limit, `At most ${MAX_TERMINALS} terminals can be open`);
41506
+ return;
41507
+ }
41508
+ try {
41509
+ attach(startShell(pty, request.id, request), ws, false);
41510
+ } catch (err) {
41511
+ const reason = err.message;
41512
+ console.error("[terminal] could not start a shell:", reason);
41513
+ ws.close(TERMINAL_CLOSE.unavailable, reason.slice(0, CLOSE_REASON_LENGTH));
41514
+ }
41515
+ }
41516
+ function stopAllTerminals() {
41517
+ for (const term of terminals.values()) {
41518
+ clearExpiry(term);
41519
+ term.pty.kill();
41520
+ }
41521
+ }
41522
+
41523
+ // src/terminal/ws.ts
41524
+ var TERMINAL_ID = /^[\w-]{8,64}$/;
41525
+ var DEFAULT_COLS = 80;
41526
+ var DEFAULT_ROWS = 24;
41527
+ var MAX_SIZE = 1e3;
41528
+ var wss2 = null;
41529
+ function size(value, fallback) {
41530
+ const n = Number(value);
41531
+ return Number.isInteger(n) && n > 0 && n <= MAX_SIZE ? n : fallback;
41532
+ }
41533
+ function onConnection(ws, request) {
41534
+ const { searchParams } = new URL(request.url ?? "", "http://localhost");
41535
+ const id = searchParams.get("id") ?? "";
41536
+ if (!TERMINAL_ID.test(id)) {
41537
+ ws.close(TERMINAL_CLOSE.badRequest, "Bad terminal id");
41538
+ return;
41539
+ }
41540
+ void openTerminal(ws, {
41541
+ id,
41542
+ cols: size(searchParams.get("cols"), DEFAULT_COLS),
41543
+ rows: size(searchParams.get("rows"), DEFAULT_ROWS),
41544
+ cwd: searchParams.get("cwd")
41545
+ });
41546
+ }
41547
+ function initTerminalWs(allowRequest = isLocalRequest) {
41548
+ wss2 = new import_websocket_server.default({
41549
+ noServer: true,
41550
+ verifyClient: ({ req }) => allowRequest(req.headers.origin, req.headers.host)
41551
+ });
41552
+ wss2.on("connection", onConnection);
41553
+ return wss2;
41554
+ }
41555
+ function handleTerminalUpgrade(request, socket, head) {
41556
+ const server = wss2;
41557
+ if (!server) {
41558
+ socket.destroy();
41559
+ return;
41560
+ }
41561
+ server.handleUpgrade(request, socket, head, (ws) => {
41562
+ server.emit("connection", ws, request);
41563
+ });
41564
+ }
41565
+
41566
+ // src/routes/sessions.ts
41567
+ import path2 from "node:path";
41303
41568
 
41304
41569
  // node_modules/uuid/dist/esm/stringify.js
41305
41570
  var byteToHex = [];
@@ -41589,8 +41854,8 @@ async function registerSessionRoutes(fastify) {
41589
41854
  }
41590
41855
  let workspaceChanged = false;
41591
41856
  if (cwd !== void 0) {
41592
- const oldAbs = existing.cwd ? path.resolve(existing.cwd) : null;
41593
- const newAbs = cwd ? path.resolve(cwd) : null;
41857
+ const oldAbs = existing.cwd ? path2.resolve(existing.cwd) : null;
41858
+ const newAbs = cwd ? path2.resolve(cwd) : null;
41594
41859
  workspaceChanged = oldAbs !== newAbs;
41595
41860
  if (workspaceChanged && existing.is_running) {
41596
41861
  return reply.code(409).send({ error: "Cannot change workspace while a turn is running" });
@@ -41950,12 +42215,13 @@ function markTurnInterrupted(db2, turnId, reason, opts = {}) {
41950
42215
  if (turn.status === "pending" && turn.resume_state === "waiting") return false;
41951
42216
  const now = (/* @__PURE__ */ new Date()).toISOString();
41952
42217
  const detail = opts.detail ?? null;
42218
+ const resumeAt = opts.resumeAt ?? null;
41953
42219
  const retry = turn.resume_state === "resuming";
41954
42220
  const at = retry ? turn.interrupted_at ?? now : opts.at ?? now;
41955
42221
  db2.prepare(
41956
- `UPDATE turns SET status = 'pending', resume_state = 'waiting', interrupt_reason = ?, interrupted_at = ?, error = NULL, updated_at = ?
42222
+ `UPDATE turns SET status = 'pending', resume_state = 'waiting', interrupt_reason = ?, interrupted_at = ?, resume_at = ?, error = NULL, updated_at = ?
41957
42223
  WHERE id = ?`
41958
- ).run(reason, at, now, turnId);
42224
+ ).run(reason, at, resumeAt, now, turnId);
41959
42225
  if (retry) {
41960
42226
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { reason, outcome: "waiting", detail });
41961
42227
  } else {
@@ -41974,7 +42240,8 @@ function markTurnInterrupted(db2, turnId, reason, opts = {}) {
41974
42240
  reason,
41975
42241
  interruptedAt: at,
41976
42242
  attempts: turn.resume_attempts,
41977
- detail
42243
+ detail,
42244
+ resumeAt
41978
42245
  });
41979
42246
  if (opts.notify !== false) {
41980
42247
  for (const listener of listeners) {
@@ -41995,7 +42262,7 @@ function markTurnResuming(db2, turnId, opts = {}) {
41995
42262
  const reason = turn.interrupt_reason ?? "host_restart";
41996
42263
  const now = (/* @__PURE__ */ new Date()).toISOString();
41997
42264
  db2.prepare(
41998
- `UPDATE turns SET status = 'running', resume_state = 'resuming', resume_attempts = ?, error = NULL, updated_at = ?
42265
+ `UPDATE turns SET status = 'running', resume_state = 'resuming', resume_attempts = ?, resume_at = NULL, error = NULL, updated_at = ?
41999
42266
  WHERE id = ?`
42000
42267
  ).run(attempt, now, turnId);
42001
42268
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { outcome: "resuming" });
@@ -42003,6 +42270,14 @@ function markTurnResuming(db2, turnId, opts = {}) {
42003
42270
  broadcast("turn:resuming", { sessionId: turn.session_id, turnId, attempt, reason, manual: !!opts.manual });
42004
42271
  return { sessionId: turn.session_id, attempt, reason };
42005
42272
  }
42273
+ function listSignedOutTurns(db2) {
42274
+ const rows = db2.prepare(
42275
+ `SELECT id, session_id FROM turns
42276
+ WHERE status = 'pending' AND resume_state = 'waiting' AND interrupt_reason = 'auth'
42277
+ ORDER BY interrupted_at ASC, created_at ASC`
42278
+ ).all();
42279
+ return rows.map((row) => ({ sessionId: row.session_id, turnId: row.id }));
42280
+ }
42006
42281
  function isResumable(turn, manual) {
42007
42282
  if (turn.status === "pending" && turn.resume_state === "waiting") return true;
42008
42283
  return manual && turn.status === "failed" && (turn.resume_state === "gave_up" || turn.resume_state === "skipped");
@@ -42012,7 +42287,7 @@ function markTurnResumed(db2, turnId, opts = {}) {
42012
42287
  if (!turn) return;
42013
42288
  if (turn.resume_state !== "resuming" && !(opts.settle && turn.resume_state === "waiting")) return;
42014
42289
  const now = (/* @__PURE__ */ new Date()).toISOString();
42015
- db2.prepare("UPDATE turns SET resume_state = 'resumed', updated_at = ? WHERE id = ?").run(now, turnId);
42290
+ db2.prepare("UPDATE turns SET resume_state = 'resumed', resume_at = NULL, updated_at = ? WHERE id = ?").run(now, turnId);
42016
42291
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { outcome: "resumed", resumed_at: now });
42017
42292
  broadcast("turn:resumed", { sessionId: turn.session_id, turnId, resumedAt: now });
42018
42293
  }
@@ -42020,12 +42295,9 @@ function finalizeInterruptedTurn(db2, turnId, state, error) {
42020
42295
  const turn = getTurn(db2, turnId);
42021
42296
  if (!turn || !isLive(turn.status)) return false;
42022
42297
  const now = (/* @__PURE__ */ new Date()).toISOString();
42023
- db2.prepare("UPDATE turns SET status = 'failed', resume_state = ?, error = ?, updated_at = ? WHERE id = ?").run(
42024
- state,
42025
- error,
42026
- now,
42027
- turnId
42028
- );
42298
+ db2.prepare(
42299
+ "UPDATE turns SET status = 'failed', resume_state = ?, resume_at = NULL, error = ?, updated_at = ? WHERE id = ?"
42300
+ ).run(state, error, now, turnId);
42029
42301
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { outcome: state });
42030
42302
  recomputeSessionRunning(db2, turn.session_id, "failed");
42031
42303
  broadcast("turn:failed", { sessionId: turn.session_id, turnId, error, resumeState: state });
@@ -42034,7 +42306,7 @@ function finalizeInterruptedTurn(db2, turnId, state, error) {
42034
42306
  function markResumeCancelled(db2, turnId) {
42035
42307
  const turn = getTurn(db2, turnId);
42036
42308
  if (!turn || turn.resume_state !== "waiting" && turn.resume_state !== "resuming") return;
42037
- db2.prepare("UPDATE turns SET resume_state = 'cancelled' WHERE id = ?").run(turnId);
42309
+ db2.prepare("UPDATE turns SET resume_state = 'cancelled', resume_at = NULL WHERE id = ?").run(turnId);
42038
42310
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { outcome: "cancelled" });
42039
42311
  }
42040
42312
  function recoverInterruptedTurns(db2, opts) {
@@ -42109,6 +42381,8 @@ async function probeApi(opts = {}) {
42109
42381
 
42110
42382
  // src/resume/resume-manager.ts
42111
42383
  var HOUR = 60 * 60 * 1e3;
42384
+ var RESET_MARGIN_MS = 3e4;
42385
+ var CLOCK_CHECK_MS = 6e4;
42112
42386
  function envNumber(env, name, fallback) {
42113
42387
  const raw = env[name];
42114
42388
  if (raw === void 0 || raw === "") return fallback;
@@ -42164,6 +42438,12 @@ function stopAutoResume() {
42164
42438
  config = null;
42165
42439
  rescanDelay = null;
42166
42440
  }
42441
+ function usageLimitResumeAt(resetsAt, now = Date.now()) {
42442
+ const cfg = config ?? readAutoResumeConfig();
42443
+ if (!cfg.enabled || !resetsAt) return null;
42444
+ const due = resetsAt * 1e3 + RESET_MARGIN_MS;
42445
+ return due > now && due - now <= cfg.maxAgeMs ? new Date(due).toISOString() : null;
42446
+ }
42167
42447
  function scheduleScan(delayMs) {
42168
42448
  if (!config) return;
42169
42449
  if (scanning) {
@@ -42196,21 +42476,32 @@ async function runScan() {
42196
42476
  })();
42197
42477
  return scanning;
42198
42478
  }
42479
+ function limitWaitMs(turn) {
42480
+ const resumeAt = turn.resume_at ? Date.parse(turn.resume_at) : NaN;
42481
+ return Number.isNaN(resumeAt) ? CLOCK_CHECK_MS : Math.min(resumeAt - Date.now(), CLOCK_CHECK_MS);
42482
+ }
42199
42483
  async function scan() {
42200
42484
  const cfg = config;
42201
42485
  if (!cfg || !cfg.enabled) return;
42202
42486
  await orphansReaped;
42203
42487
  const db2 = getDb();
42204
42488
  const waiting = db2.prepare(
42205
- `SELECT id, session_id, interrupted_at, resume_attempts FROM turns
42206
- WHERE status = 'pending' AND resume_state = 'waiting'
42489
+ // A signed-out turn would fail again and use up its attempts; it waits
42490
+ // for the user, without an age limit (resumeSignedOutTurns).
42491
+ `SELECT id, session_id, interrupted_at, interrupt_reason, resume_at, resume_attempts FROM turns
42492
+ WHERE status = 'pending' AND resume_state = 'waiting' AND COALESCE(interrupt_reason, '') != 'auth'
42207
42493
  ORDER BY interrupted_at ASC, created_at ASC`
42208
42494
  ).all();
42209
42495
  const due = [];
42496
+ let nextLook = null;
42210
42497
  for (const turn of waiting) {
42211
42498
  const at = turn.interrupted_at ? Date.parse(turn.interrupted_at) : NaN;
42212
42499
  if (Number.isFinite(at) && Date.now() - at > cfg.maxAgeMs) {
42213
42500
  finalizeInterruptedTurn(db2, turn.id, "skipped", "Interrupted too long ago to resume automatically");
42501
+ } else if (turn.interrupt_reason === "usage_limit") {
42502
+ const wait = limitWaitMs(turn);
42503
+ if (wait <= 0) due.push(turn);
42504
+ else nextLook = Math.min(nextLook ?? wait, wait);
42214
42505
  } else if (turn.resume_attempts >= cfg.maxAttempts) {
42215
42506
  finalizeInterruptedTurn(
42216
42507
  db2,
@@ -42222,6 +42513,7 @@ async function scan() {
42222
42513
  due.push(turn);
42223
42514
  }
42224
42515
  }
42516
+ if (nextLook !== null) scheduleScan(nextLook);
42225
42517
  if (due.length === 0) {
42226
42518
  probeFailures = 0;
42227
42519
  return;
@@ -42242,7 +42534,8 @@ async function scan() {
42242
42534
  for (let i = 0; i < due.length; i++) {
42243
42535
  if (config !== cfg) return;
42244
42536
  if (i > 0) await new Promise((resolve) => setTimeout(resolve, cfg.staggerMs));
42245
- const result = await resumeTurn(due[i].id, { manual: false, countAttempt });
42537
+ const counted = countAttempt && due[i].interrupt_reason !== "usage_limit";
42538
+ const result = await resumeTurn(due[i].id, { manual: false, countAttempt: counted });
42246
42539
  if (!result.ok && result.status === 409) {
42247
42540
  finalizeInterruptedTurn(db2, due[i].id, "skipped", result.error);
42248
42541
  }
@@ -42291,6 +42584,27 @@ async function resumeNow(sessionId, turnId) {
42291
42584
  if (!row || row.session_id !== sessionId) return { ok: false, status: 404, error: "Turn not found" };
42292
42585
  return resumeTurn(turnId, { manual: true });
42293
42586
  }
42587
+ var resumingSignedOut = null;
42588
+ function resumeSignedOutTurns() {
42589
+ const db2 = getDb();
42590
+ const turns = listSignedOutTurns(db2);
42591
+ if (!resumingSignedOut && turns.length > 0) {
42592
+ const { staggerMs } = config ?? readAutoResumeConfig();
42593
+ resumingSignedOut = (async () => {
42594
+ await orphansReaped;
42595
+ for (let i = 0; i < turns.length; i++) {
42596
+ if (i > 0) await new Promise((resolve) => setTimeout(resolve, staggerMs));
42597
+ const result = await resumeTurn(turns[i].turnId, { manual: true });
42598
+ if (!result.ok && result.status === 409) {
42599
+ finalizeInterruptedTurn(db2, turns[i].turnId, "skipped", result.error);
42600
+ }
42601
+ }
42602
+ })().catch((err) => console.error("[resume] could not resume the signed-out turns:", err)).finally(() => {
42603
+ resumingSignedOut = null;
42604
+ });
42605
+ }
42606
+ return { turns: turns.length };
42607
+ }
42294
42608
 
42295
42609
  // src/routes/turns.ts
42296
42610
  async function registerTurnRoutes(fastify) {
@@ -42408,6 +42722,9 @@ async function registerTurnRoutes(fastify) {
42408
42722
  return reply.code(202).send({ success: true });
42409
42723
  }
42410
42724
  );
42725
+ fastify.post("/api/turns/resume-signed-out", async (_request, reply) => {
42726
+ return reply.code(202).send(resumeSignedOutTurns());
42727
+ });
42411
42728
  }
42412
42729
 
42413
42730
  // src/routes/thread-turns.ts
@@ -42806,9 +43123,9 @@ async function browseFolder(input, opts = {}) {
42806
43123
  const atHome = dir === nodePath.resolve(home);
42807
43124
  const folders = await Promise.all(
42808
43125
  names.slice(0, limit).map(async (name) => {
42809
- const path11 = nodePath.join(dir, name);
43126
+ const path12 = nodePath.join(dir, name);
42810
43127
  const skipProbe = atHome && HOME_STANDARD_FOLDERS.has(name) || dir === "/Volumes";
42811
- return { name, path: path11, git: !skipProbe && await exists(nodePath.join(path11, ".git")) };
43128
+ return { name, path: path12, git: !skipProbe && await exists(nodePath.join(path12, ".git")) };
42812
43129
  })
42813
43130
  );
42814
43131
  const parent = nodePath.dirname(dir);
@@ -42846,11 +43163,11 @@ async function registerWorkspaceRoutes(fastify) {
42846
43163
  }
42847
43164
  }
42848
43165
  }, async (request, reply) => {
42849
- const { path: path11, label = null } = request.body || {};
42850
- if (!path11 || !path11.trim()) {
43166
+ const { path: path12, label = null } = request.body || {};
43167
+ if (!path12 || !path12.trim()) {
42851
43168
  return reply.code(400).send({ error: "Path is required" });
42852
43169
  }
42853
- const resolved = await resolveWorkspacePath(path11);
43170
+ const resolved = await resolveWorkspacePath(path12);
42854
43171
  if ("error" in resolved) {
42855
43172
  return reply.code(400).send({ error: resolved.error });
42856
43173
  }
@@ -42892,8 +43209,8 @@ async function registerWorkspaceRoutes(fastify) {
42892
43209
  "-e",
42893
43210
  'POSIX path of (choose folder with prompt "Select a workspace directory")'
42894
43211
  ]);
42895
- const path11 = stdout.trim().replace(/\/$/, "");
42896
- return { path: path11 };
43212
+ const path12 = stdout.trim().replace(/\/$/, "");
43213
+ return { path: path12 };
42897
43214
  } catch {
42898
43215
  return reply.code(204).send({ cancelled: true });
42899
43216
  }
@@ -42909,11 +43226,11 @@ async function registerWorkspaceRoutes(fastify) {
42909
43226
  }
42910
43227
  }
42911
43228
  }, async (request, reply) => {
42912
- const { path: path11 } = request.body || {};
42913
- if (!path11 || !path11.trim()) {
43229
+ const { path: path12 } = request.body || {};
43230
+ if (!path12 || !path12.trim()) {
42914
43231
  return reply.code(400).send({ error: "Path is required" });
42915
43232
  }
42916
- const trimmedPath = path11.trim();
43233
+ const trimmedPath = path12.trim();
42917
43234
  const db2 = getDb();
42918
43235
  const existing = db2.prepare("SELECT * FROM workspaces WHERE path = ?").get(trimmedPath);
42919
43236
  if (existing) {
@@ -43560,17 +43877,17 @@ async function registerPerfLogRoutes(fastify) {
43560
43877
  if (entries.length === 0) {
43561
43878
  return reply.send({ written: 0 });
43562
43879
  }
43563
- const path11 = perfLogPath();
43880
+ const path12 = perfLogPath();
43564
43881
  try {
43565
- mkdirSync(dirname(path11), { recursive: true });
43882
+ mkdirSync(dirname(path12), { recursive: true });
43566
43883
  try {
43567
- if (statSync(path11).size > MAX_BYTES) {
43568
- renameSync(path11, `${path11}.1`);
43884
+ if (statSync(path12).size > MAX_BYTES) {
43885
+ renameSync(path12, `${path12}.1`);
43569
43886
  }
43570
43887
  } catch {
43571
43888
  }
43572
43889
  const lines = entries.map((e) => `${new Date(e.t).toISOString()} [${oneLine(e.cat)}] ${oneLine(e.msg)}`).join("\n");
43573
- appendFileSync(path11, `${lines}
43890
+ appendFileSync(path12, `${lines}
43574
43891
  `, "utf-8");
43575
43892
  return reply.send({ written: entries.length });
43576
43893
  } catch (err) {
@@ -43646,24 +43963,24 @@ import { existsSync } from "node:fs";
43646
43963
  import http from "node:http";
43647
43964
  import net from "node:net";
43648
43965
  import crypto from "node:crypto";
43649
- import os from "node:os";
43650
- import path2 from "node:path";
43966
+ import os2 from "node:os";
43967
+ import path3 from "node:path";
43651
43968
  import { mkdir, readdir as readdir2, symlink, lstat, access, readFile, writeFile, unlink } from "node:fs/promises";
43652
- var VSCODE_WEB_DATA_DIR = path2.join(os.homedir(), ".repoburg", "vscode-web");
43969
+ var VSCODE_WEB_DATA_DIR = path3.join(os2.homedir(), ".repoburg", "vscode-web");
43653
43970
  function resolveDesktopUserDir() {
43654
43971
  if (process.platform === "darwin") {
43655
- return path2.join(os.homedir(), "Library", "Application Support", "Code", "User");
43972
+ return path3.join(os2.homedir(), "Library", "Application Support", "Code", "User");
43656
43973
  }
43657
43974
  if (process.platform === "win32" && process.env.APPDATA) {
43658
- return path2.join(process.env.APPDATA, "Code", "User");
43975
+ return path3.join(process.env.APPDATA, "Code", "User");
43659
43976
  }
43660
43977
  if (process.platform === "linux") {
43661
- return path2.join(os.homedir(), ".config", "Code", "User");
43978
+ return path3.join(os2.homedir(), ".config", "Code", "User");
43662
43979
  }
43663
43980
  return null;
43664
43981
  }
43665
43982
  async function linkUnlessExists(src, dst) {
43666
- await mkdir(path2.dirname(dst), { recursive: true });
43983
+ await mkdir(path3.dirname(dst), { recursive: true });
43667
43984
  try {
43668
43985
  await lstat(dst);
43669
43986
  return false;
@@ -43678,19 +43995,19 @@ function fileRegistryUri(dir) {
43678
43995
  }
43679
43996
  async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
43680
43997
  try {
43681
- const desktopExt = path2.join(os.homedir(), ".vscode", "extensions");
43998
+ const desktopExt = path3.join(os2.homedir(), ".vscode", "extensions");
43682
43999
  let entries;
43683
44000
  try {
43684
44001
  entries = await readdir2(desktopExt, { withFileTypes: true });
43685
44002
  } catch {
43686
44003
  return;
43687
44004
  }
43688
- const serverExt = path2.join(dataDir, "extensions");
44005
+ const serverExt = path3.join(dataDir, "extensions");
43689
44006
  const linkedFolders = [];
43690
44007
  for (const entry of entries) {
43691
44008
  if (!entry.isDirectory()) continue;
43692
- const target = path2.join(serverExt, entry.name);
43693
- await linkUnlessExists(path2.join(desktopExt, entry.name), target);
44009
+ const target = path3.join(serverExt, entry.name);
44010
+ await linkUnlessExists(path3.join(desktopExt, entry.name), target);
43694
44011
  const st = await lstat(target).catch(() => null);
43695
44012
  if (st?.isSymbolicLink()) linkedFolders.push(entry.name);
43696
44013
  }
@@ -43698,15 +44015,15 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
43698
44015
  await pruneObsolete(serverExt, linkedFolders);
43699
44016
  const desktopUser = resolveDesktopUserDir();
43700
44017
  if (!desktopUser) return;
43701
- const serverUser = path2.join(dataDir, "data", "User");
44018
+ const serverUser = path3.join(dataDir, "data", "User");
43702
44019
  for (const item of ["settings.json", "keybindings.json", "snippets"]) {
43703
- const src = path2.join(desktopUser, item);
44020
+ const src = path3.join(desktopUser, item);
43704
44021
  try {
43705
44022
  await access(src);
43706
44023
  } catch {
43707
44024
  continue;
43708
44025
  }
43709
- await linkUnlessExists(src, path2.join(serverUser, item));
44026
+ await linkUnlessExists(src, path3.join(serverUser, item));
43710
44027
  }
43711
44028
  } catch {
43712
44029
  }
@@ -43714,13 +44031,13 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
43714
44031
  async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
43715
44032
  let desktopEntries = [];
43716
44033
  try {
43717
- desktopEntries = JSON.parse(await readFile(path2.join(desktopExt, "extensions.json"), "utf8"));
44034
+ desktopEntries = JSON.parse(await readFile(path3.join(desktopExt, "extensions.json"), "utf8"));
43718
44035
  } catch {
43719
44036
  return;
43720
44037
  }
43721
44038
  const linked = new Set(linkedFolders);
43722
44039
  const toAdd = desktopEntries.filter((e) => e.identifier?.id && linked.has(e.relativeLocation));
43723
- const serverRegistryPath = path2.join(serverExt, "extensions.json");
44040
+ const serverRegistryPath = path3.join(serverExt, "extensions.json");
43724
44041
  let serverEntries = [];
43725
44042
  try {
43726
44043
  serverEntries = JSON.parse(await readFile(serverRegistryPath, "utf8"));
@@ -43730,13 +44047,13 @@ async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
43730
44047
  const additions = toAdd.filter((e) => !known.has(`${e.identifier.id.toLowerCase()}@${e.version}`));
43731
44048
  if (additions.length === 0) return;
43732
44049
  for (const entry of additions) {
43733
- const dir = path2.join(serverExt, entry.relativeLocation);
44050
+ const dir = path3.join(serverExt, entry.relativeLocation);
43734
44051
  serverEntries.push({ ...entry, location: fileRegistryUri(dir) });
43735
44052
  }
43736
44053
  await writeFile(serverRegistryPath, JSON.stringify(serverEntries));
43737
44054
  }
43738
44055
  async function pruneObsolete(serverExt, linkedFolders) {
43739
- const obsoletePath = path2.join(serverExt, ".obsolete");
44056
+ const obsoletePath = path3.join(serverExt, ".obsolete");
43740
44057
  let obsolete;
43741
44058
  try {
43742
44059
  obsolete = JSON.parse(await readFile(obsoletePath, "utf8"));
@@ -44194,17 +44511,17 @@ function proxyHandler(request, reply) {
44194
44511
  }
44195
44512
 
44196
44513
  // src/routes/apps.ts
44197
- import fs5 from "node:fs";
44198
- import path7 from "node:path";
44514
+ import fs6 from "node:fs";
44515
+ import path8 from "node:path";
44199
44516
 
44200
44517
  // src/apps/instances.ts
44201
- import fs2 from "node:fs";
44202
- import path4 from "node:path";
44518
+ import fs3 from "node:fs";
44519
+ import path5 from "node:path";
44203
44520
 
44204
44521
  // src/apps/apps-registry.ts
44205
- import fs from "node:fs";
44206
- import path3 from "node:path";
44207
- import os2 from "node:os";
44522
+ import fs2 from "node:fs";
44523
+ import path4 from "node:path";
44524
+ import os3 from "node:os";
44208
44525
  import { fileURLToPath } from "node:url";
44209
44526
 
44210
44527
  // node_modules/lucide-static/icon-nodes.json
@@ -98428,10 +98745,10 @@ function setAppsRootOverride(root) {
98428
98745
  rootOverride = root;
98429
98746
  }
98430
98747
  function appsRoot() {
98431
- return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path3.join(os2.homedir(), ".repoburg", "agent-pane", "apps");
98748
+ return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path4.join(os3.homedir(), ".repoburg", "agent-pane", "apps");
98432
98749
  }
98433
98750
  function appDir(id) {
98434
- return path3.join(appsRoot(), id);
98751
+ return path4.join(appsRoot(), id);
98435
98752
  }
98436
98753
  var examplesRootOverride = null;
98437
98754
  function setExamplesRootOverride(root) {
@@ -98440,28 +98757,28 @@ function setExamplesRootOverride(root) {
98440
98757
  function examplesRoot() {
98441
98758
  if (examplesRootOverride) return examplesRootOverride;
98442
98759
  if (process.env.AGENT_PANE_EXAMPLES_DIR) return process.env.AGENT_PANE_EXAMPLES_DIR;
98443
- const here = path3.dirname(fileURLToPath(import.meta.url));
98444
- for (const candidate of [path3.resolve(here, "../../examples"), path3.resolve(here, "../../../examples")]) {
98445
- if (fs.existsSync(candidate)) return candidate;
98760
+ const here = path4.dirname(fileURLToPath(import.meta.url));
98761
+ for (const candidate of [path4.resolve(here, "../../examples"), path4.resolve(here, "../../../examples")]) {
98762
+ if (fs2.existsSync(candidate)) return candidate;
98446
98763
  }
98447
98764
  return null;
98448
98765
  }
98449
98766
  function isInAppFolder(cwd) {
98450
98767
  if (!cwd) return false;
98451
- const rel = path3.relative(path3.resolve(appsRoot()), path3.resolve(cwd));
98452
- return rel !== "" && !path3.isAbsolute(rel) && rel.split(path3.sep)[0] !== "..";
98768
+ const rel = path4.relative(path4.resolve(appsRoot()), path4.resolve(cwd));
98769
+ return rel !== "" && !path4.isAbsolute(rel) && rel.split(path4.sep)[0] !== "..";
98453
98770
  }
98454
98771
  function appsConventions() {
98455
98772
  return APPS_MD_SKELETON;
98456
98773
  }
98457
98774
  function ensureAppsRoot() {
98458
98775
  const root = appsRoot();
98459
- fs.mkdirSync(root, { recursive: true });
98776
+ fs2.mkdirSync(root, { recursive: true });
98460
98777
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
98461
- const file = path3.join(root, name);
98778
+ const file = path4.join(root, name);
98462
98779
  try {
98463
- if (fs.existsSync(file) && fs.readFileSync(file, "utf-8") === APPS_MD_FILE) continue;
98464
- fs.writeFileSync(file, APPS_MD_FILE);
98780
+ if (fs2.existsSync(file) && fs2.readFileSync(file, "utf-8") === APPS_MD_FILE) continue;
98781
+ fs2.writeFileSync(file, APPS_MD_FILE);
98465
98782
  } catch (err) {
98466
98783
  console.warn(`[apps] could not update ${file}: ${err.message}`);
98467
98784
  }
@@ -98626,7 +98943,7 @@ folder's own CLAUDE.md / AGENTS.md. -->
98626
98943
  ${APPS_MD_SKELETON}`;
98627
98944
  function readManifestIn(dir) {
98628
98945
  try {
98629
- const raw = fs.readFileSync(path3.join(dir, "manifest.json"), "utf-8");
98946
+ const raw = fs2.readFileSync(path4.join(dir, "manifest.json"), "utf-8");
98630
98947
  const parsed = JSON.parse(raw);
98631
98948
  if (!parsed || typeof parsed.title !== "string") return null;
98632
98949
  return {
@@ -98644,7 +98961,7 @@ function readManifest(id) {
98644
98961
  }
98645
98962
  function readAppFile(id, name) {
98646
98963
  try {
98647
- return fs.readFileSync(path3.join(appDir(id), name), "utf-8");
98964
+ return fs2.readFileSync(path4.join(appDir(id), name), "utf-8");
98648
98965
  } catch {
98649
98966
  return "";
98650
98967
  }
@@ -98662,7 +98979,7 @@ function readState(id) {
98662
98979
  }
98663
98980
  function isRegularFile(p) {
98664
98981
  try {
98665
- return fs.statSync(p).isFile();
98982
+ return fs2.statSync(p).isFile();
98666
98983
  } catch {
98667
98984
  return false;
98668
98985
  }
@@ -98673,15 +98990,15 @@ var HOT_RELOAD_DEBOUNCE_MS = 250;
98673
98990
  function startAppsWatch(onAppChange) {
98674
98991
  stopAppsWatch();
98675
98992
  const root = appsRoot();
98676
- fs.mkdirSync(root, { recursive: true });
98993
+ fs2.mkdirSync(root, { recursive: true });
98677
98994
  try {
98678
- watcher = fs.watch(root, { recursive: true }, (_event, filename) => {
98995
+ watcher = fs2.watch(root, { recursive: true }, (_event, filename) => {
98679
98996
  const rel = String(filename ?? "");
98680
- const segs = rel.split(path3.sep);
98997
+ const segs = rel.split(path4.sep);
98681
98998
  const appId = segs[0];
98682
98999
  const file = segs[segs.length - 1];
98683
- if (!appId || appId === path3.basename(root) || !APP_ID_RE.test(appId) || file === "state.json") return;
98684
- if (segs.length === 1 && isRegularFile(path3.join(root, appId))) return;
99000
+ if (!appId || appId === path4.basename(root) || !APP_ID_RE.test(appId) || file === "state.json") return;
99001
+ if (segs.length === 1 && isRegularFile(path4.join(root, appId))) return;
98685
99002
  const timer2 = pendingChanges.get(appId);
98686
99003
  if (timer2) clearTimeout(timer2);
98687
99004
  pendingChanges.set(
@@ -98752,12 +99069,12 @@ function getInstanceState(appId, workspace = "") {
98752
99069
  const stored = readRow(appId, workspace);
98753
99070
  if (stored) return stored;
98754
99071
  if (workspace === "") {
98755
- const legacyFile = path4.join(appDir(appId), "state.json");
98756
- if (fs2.existsSync(legacyFile)) {
99072
+ const legacyFile = path5.join(appDir(appId), "state.json");
99073
+ if (fs3.existsSync(legacyFile)) {
98757
99074
  const legacy = readState(appId);
98758
99075
  const imported = { pinned: legacy.pinned, data: legacy.data, version: 1 };
98759
99076
  writeRow(appId, "", imported);
98760
- fs2.rmSync(legacyFile, { force: true });
99077
+ fs3.rmSync(legacyFile, { force: true });
98761
99078
  return imported;
98762
99079
  }
98763
99080
  }
@@ -98785,14 +99102,14 @@ function deleteAppInstances(appId) {
98785
99102
  }
98786
99103
 
98787
99104
  // src/apps/mcp-tools.ts
98788
- import fs4 from "node:fs";
99105
+ import fs5 from "node:fs";
98789
99106
 
98790
99107
  // src/apps/headless-runtime.ts
98791
99108
  import vm2 from "node:vm";
98792
99109
 
98793
99110
  // src/apps/app-compile.ts
98794
99111
  import vm from "node:vm";
98795
- import path5 from "node:path";
99112
+ import path6 from "node:path";
98796
99113
  import ts from "typescript";
98797
99114
 
98798
99115
  // src/apps/app-lint.ts
@@ -99084,15 +99401,15 @@ function typeCheckModules(appId, modules) {
99084
99401
  };
99085
99402
  const host = ts.createCompilerHost(options);
99086
99403
  const origReadFile = host.readFile.bind(host);
99087
- host.readFile = (fname) => path5.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
99404
+ host.readFile = (fname) => path6.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
99088
99405
  host.writeFile = () => {
99089
99406
  };
99090
- const bridgePath = path5.join(dir, BRIDGE_DTS_FILE);
99091
- const rootNames = [...modules.map((m) => path5.join(dir, m.file)), bridgePath];
99407
+ const bridgePath = path6.join(dir, BRIDGE_DTS_FILE);
99408
+ const rootNames = [...modules.map((m) => path6.join(dir, m.file)), bridgePath];
99092
99409
  const program = ts.createProgram(rootNames, options, host);
99093
99410
  const out = [];
99094
99411
  for (const mod of modules) {
99095
- const sf = program.getSourceFile(path5.join(dir, mod.file));
99412
+ const sf = program.getSourceFile(path6.join(dir, mod.file));
99096
99413
  if (!sf) continue;
99097
99414
  out.push(
99098
99415
  ...[...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)].map((d) => tsDiagnosticToFile(mod.file, d)).filter((d) => d !== null)
@@ -99173,9 +99490,9 @@ function compileAppJs(appId) {
99173
99490
 
99174
99491
  // src/apps/app-files.ts
99175
99492
  import crypto2 from "node:crypto";
99176
- import fs3 from "node:fs";
99177
- import os3 from "node:os";
99178
- import path6 from "node:path";
99493
+ import fs4 from "node:fs";
99494
+ import os4 from "node:os";
99495
+ import path7 from "node:path";
99179
99496
  var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
99180
99497
  var APP_FILE_TYPES = {
99181
99498
  "image/png": "png",
@@ -99200,11 +99517,11 @@ function setAppFilesRootOverride(root) {
99200
99517
  rootOverride2 = root;
99201
99518
  }
99202
99519
  function appFilesRoot() {
99203
- return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path6.join(os3.homedir(), ".repoburg", "agent-pane", "app-files");
99520
+ return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path7.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
99204
99521
  }
99205
99522
  function appFilesDir(appId) {
99206
99523
  if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
99207
- return path6.join(appFilesRoot(), appId);
99524
+ return path7.join(appFilesRoot(), appId);
99208
99525
  }
99209
99526
  function appFileUrl(appId, fileId) {
99210
99527
  return `/api/apps/${appId}/files/${fileId}`;
@@ -99265,12 +99582,12 @@ function saveAppFile(appId, upload) {
99265
99582
  const type = sniffImageType(bytes);
99266
99583
  if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
99267
99584
  const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
99268
- const file = path6.join(dir, fileId);
99269
- if (!fs3.existsSync(file)) {
99270
- fs3.mkdirSync(dir, { recursive: true });
99585
+ const file = path7.join(dir, fileId);
99586
+ if (!fs4.existsSync(file)) {
99587
+ fs4.mkdirSync(dir, { recursive: true });
99271
99588
  const tmp = `${file}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
99272
- fs3.writeFileSync(tmp, bytes);
99273
- fs3.renameSync(tmp, file);
99589
+ fs4.writeFileSync(tmp, bytes);
99590
+ fs4.renameSync(tmp, file);
99274
99591
  }
99275
99592
  return { id: fileId, url: appFileUrl(appId, fileId), path: file, type, size: bytes.length };
99276
99593
  }
@@ -99297,9 +99614,9 @@ function getAppFile(appId, ref) {
99297
99614
  if (!APP_ID_RE.test(appId)) return null;
99298
99615
  const fileId = appFileRefId(appId, ref);
99299
99616
  if (!fileId) return null;
99300
- const file = path6.join(appFilesDir(appId), fileId);
99617
+ const file = path7.join(appFilesDir(appId), fileId);
99301
99618
  try {
99302
- const stat2 = fs3.statSync(file);
99619
+ const stat2 = fs4.statSync(file);
99303
99620
  if (!stat2.isFile()) return null;
99304
99621
  return { id: fileId, url: appFileUrl(appId, fileId), path: file, type: fileType(fileId), size: stat2.size };
99305
99622
  } catch {
@@ -99309,14 +99626,14 @@ function getAppFile(appId, ref) {
99309
99626
  function readAppFileData(appId, fileId) {
99310
99627
  if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
99311
99628
  try {
99312
- return { bytes: fs3.readFileSync(path6.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99629
+ return { bytes: fs4.readFileSync(path7.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99313
99630
  } catch {
99314
99631
  return null;
99315
99632
  }
99316
99633
  }
99317
99634
  function deleteAppFiles(appId) {
99318
99635
  if (!APP_ID_RE.test(appId)) return;
99319
- fs3.rmSync(appFilesDir(appId), { recursive: true, force: true });
99636
+ fs4.rmSync(appFilesDir(appId), { recursive: true, force: true });
99320
99637
  }
99321
99638
 
99322
99639
  // src/apps/headless-runtime.ts
@@ -99497,7 +99814,7 @@ var TOOL_NS = "__";
99497
99814
  function listAppTools() {
99498
99815
  const tools = [];
99499
99816
  try {
99500
- for (const entry of fs4.readdirSync(appsRoot(), { withFileTypes: true })) {
99817
+ for (const entry of fs5.readdirSync(appsRoot(), { withFileTypes: true })) {
99501
99818
  if (!entry.isDirectory()) continue;
99502
99819
  const manifest = readManifest(entry.name);
99503
99820
  for (const tool of manifest?.tools ?? []) {
@@ -99573,9 +99890,9 @@ function resolveToolWorkspace(workspace) {
99573
99890
  const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99574
99891
  const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99575
99892
  if (active.includes(workspace)) return workspace;
99576
- const cwd = path7.isAbsolute(workspace) ? path7.resolve(workspace) : "";
99893
+ const cwd = path8.isAbsolute(workspace) ? path8.resolve(workspace) : "";
99577
99894
  if (isInAppFolder(cwd)) return "";
99578
- const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path7.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99895
+ const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path8.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99579
99896
  if (covering && !covering.deleted) return covering.path;
99580
99897
  throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99581
99898
  }
@@ -99630,7 +99947,7 @@ async function registerAppRoutes(fastify, opts) {
99630
99947
  fastify.get("/api/apps", async () => {
99631
99948
  try {
99632
99949
  ensureAppsRoot();
99633
- const entries = fs5.readdirSync(appsRoot(), { withFileTypes: true });
99950
+ const entries = fs6.readdirSync(appsRoot(), { withFileTypes: true });
99634
99951
  const apps = [];
99635
99952
  for (const entry of entries) {
99636
99953
  if (!entry.isDirectory() || !APP_ID_RE.test(entry.name)) continue;
@@ -99657,9 +99974,9 @@ async function registerAppRoutes(fastify, opts) {
99657
99974
  if (!exRoot) return [];
99658
99975
  const out = [];
99659
99976
  try {
99660
- for (const entry of fs5.readdirSync(exRoot, { withFileTypes: true })) {
99977
+ for (const entry of fs6.readdirSync(exRoot, { withFileTypes: true })) {
99661
99978
  if (!entry.isDirectory() || !APP_ID_RE.test(entry.name)) continue;
99662
- const manifest = readManifestIn(path7.join(exRoot, entry.name));
99979
+ const manifest = readManifestIn(path8.join(exRoot, entry.name));
99663
99980
  if (!manifest) continue;
99664
99981
  out.push({
99665
99982
  id: entry.name,
@@ -99680,11 +99997,11 @@ async function registerAppRoutes(fastify, opts) {
99680
99997
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
99681
99998
  const exRoot = examplesRoot();
99682
99999
  if (!exRoot) return reply.code(404).send({ error: "Examples catalog not available" });
99683
- const src = path7.join(exRoot, id);
100000
+ const src = path8.join(exRoot, id);
99684
100001
  if (!readManifestIn(src)) return reply.code(404).send({ error: "Example not found" });
99685
100002
  if (readManifest(id)) return reply.code(409).send({ error: "App already installed" });
99686
100003
  ensureAppsRoot();
99687
- fs5.cpSync(src, appDir(id), { recursive: true });
100004
+ fs6.cpSync(src, appDir(id), { recursive: true });
99688
100005
  return { ok: true, id };
99689
100006
  });
99690
100007
  fastify.post(
@@ -99716,10 +100033,10 @@ async function registerAppRoutes(fastify, opts) {
99716
100033
  if (readManifest(id)) return reply.code(409).send({ error: "App already exists" });
99717
100034
  ensureAppsRoot();
99718
100035
  const dir = appDir(id);
99719
- fs5.mkdirSync(dir, { recursive: true });
100036
+ fs6.mkdirSync(dir, { recursive: true });
99720
100037
  const cleanTitle2 = title.trim();
99721
- fs5.writeFileSync(
99722
- path7.join(dir, "manifest.json"),
100038
+ fs6.writeFileSync(
100039
+ path8.join(dir, "manifest.json"),
99723
100040
  JSON.stringify(
99724
100041
  {
99725
100042
  title: cleanTitle2,
@@ -99730,8 +100047,8 @@ async function registerAppRoutes(fastify, opts) {
99730
100047
  2
99731
100048
  )
99732
100049
  );
99733
- fs5.writeFileSync(path7.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
99734
- fs5.writeFileSync(path7.join(dir, "app.ts"), SKELETON_TS);
100050
+ fs6.writeFileSync(path8.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
100051
+ fs6.writeFileSync(path8.join(dir, "app.ts"), SKELETON_TS);
99735
100052
  return { ok: true, id };
99736
100053
  }
99737
100054
  );
@@ -99766,11 +100083,11 @@ async function registerAppRoutes(fastify, opts) {
99766
100083
  if (readManifest(id)) return reply.code(409).send({ error: "App already exists" });
99767
100084
  ensureAppsRoot();
99768
100085
  const dir = appDir(id);
99769
- fs5.mkdirSync(dir, { recursive: true });
100086
+ fs6.mkdirSync(dir, { recursive: true });
99770
100087
  if (!Object.hasOwn(files ?? {}, "manifest.json")) {
99771
- fs5.writeFileSync(path7.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
100088
+ fs6.writeFileSync(path8.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
99772
100089
  }
99773
- for (const [name, content] of entries) fs5.writeFileSync(path7.join(dir, name), content);
100090
+ for (const [name, content] of entries) fs6.writeFileSync(path8.join(dir, name), content);
99774
100091
  return { ok: true, id };
99775
100092
  }
99776
100093
  );
@@ -99932,7 +100249,7 @@ async function registerAppRoutes(fastify, opts) {
99932
100249
  const { id } = request.params;
99933
100250
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
99934
100251
  if (!readManifest(id)) return reply.code(404).send({ error: "App not found" });
99935
- fs5.rmSync(appDir(id), { recursive: true, force: true });
100252
+ fs6.rmSync(appDir(id), { recursive: true, force: true });
99936
100253
  deleteAppFiles(id);
99937
100254
  deleteAppInstances(id);
99938
100255
  invalidateHeadlessRuntime(id);
@@ -100445,7 +100762,7 @@ async function registerUsageRoutes(fastify) {
100445
100762
 
100446
100763
  // src/claude/session-import.ts
100447
100764
  import { readFile as readFile2, realpath } from "node:fs/promises";
100448
- import path8 from "node:path";
100765
+ import path9 from "node:path";
100449
100766
  import { getSessionInfo, listSessions } from "@anthropic-ai/claude-agent-sdk";
100450
100767
 
100451
100768
  // src/claude/claude-message-mapper.ts
@@ -100525,9 +100842,9 @@ function mapToolUse(block) {
100525
100842
  };
100526
100843
  }
100527
100844
  function deriveFileChangeData(input, toolName) {
100528
- const path11 = input.file_path ?? input.notebook_path ?? "";
100845
+ const path12 = input.file_path ?? input.notebook_path ?? "";
100529
100846
  const kind = toolName === "Write" ? "add" : "modify";
100530
- return { changes: [{ path: path11, kind }], status: "in_progress" };
100847
+ return { changes: [{ path: path12, kind }], status: "in_progress" };
100531
100848
  }
100532
100849
  function extractToolResultText(content) {
100533
100850
  if (!content) return "";
@@ -100890,7 +101207,7 @@ async function realDir(dir) {
100890
101207
  }
100891
101208
  }
100892
101209
  async function sameDir(a, realB) {
100893
- const realA = await realDir(a) ?? path8.resolve(a);
101210
+ const realA = await realDir(a) ?? path9.resolve(a);
100894
101211
  return realA === realB;
100895
101212
  }
100896
101213
  function knownClaudeSessionIds(db2) {
@@ -101125,23 +101442,23 @@ function mapTokenUsage(data) {
101125
101442
  }
101126
101443
 
101127
101444
  // src/apps/register-mcp.ts
101128
- import fs6 from "node:fs";
101129
- import path9 from "node:path";
101445
+ import fs7 from "node:fs";
101446
+ import path10 from "node:path";
101130
101447
  import { fileURLToPath as fileURLToPath2 } from "node:url";
101131
101448
  var MCP_SERVER_NAME = "agentpane-miniapps";
101132
101449
  function panePublicUrl() {
101133
101450
  return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
101134
101451
  }
101135
101452
  function stdioScriptPath() {
101136
- const here = path9.dirname(fileURLToPath2(import.meta.url));
101453
+ const here = path10.dirname(fileURLToPath2(import.meta.url));
101137
101454
  const candidates = [
101138
- path9.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
101455
+ path10.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
101139
101456
  // src/apps/ → backend/scripts
101140
- path9.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
101457
+ path10.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
101141
101458
  // dist bundle → backend/scripts
101142
101459
  ];
101143
101460
  for (const candidate of candidates) {
101144
- if (fs6.existsSync(candidate)) return candidate;
101461
+ if (fs7.existsSync(candidate)) return candidate;
101145
101462
  }
101146
101463
  return null;
101147
101464
  }
@@ -101930,7 +102247,6 @@ async function refreshContext(entry, sessionId, db2) {
101930
102247
 
101931
102248
  // src/claude/api-errors.ts
101932
102249
  var FATAL_ERRORS = /* @__PURE__ */ new Set([
101933
- "authentication_failed",
101934
102250
  "oauth_org_not_allowed",
101935
102251
  "account_on_hold",
101936
102252
  "verification_required",
@@ -101952,7 +102268,15 @@ var NETWORK_TEXTS = [
101952
102268
  /socket hang up|fetch failed|network error/i,
101953
102269
  /overloaded/i
101954
102270
  ];
101955
- function classifyApiError({ error, status, text }) {
102271
+ var SIGN_IN_ADVICE = /\/login|(sign|log) in again/i;
102272
+ var OUTSIDE_LOGIN_TEXTS = /api[ -]key|gateway|bedrock|vertex|foundry|mantle/i;
102273
+ function isSignedOut(text) {
102274
+ if (!text) return true;
102275
+ return SIGN_IN_ADVICE.test(text) || !OUTSIDE_LOGIN_TEXTS.test(text);
102276
+ }
102277
+ function classifyApiError({ error, status, text, limitRejected }) {
102278
+ if (error === "authentication_failed" || !error && status === 401) return isSignedOut(text) ? "auth" : "fatal";
102279
+ if (limitRejected && (error === "rate_limit" || !error && status === 429)) return "usage_limit";
101956
102280
  if (error && FATAL_ERRORS.has(error)) return "fatal";
101957
102281
  if (error && TRANSIENT_ERRORS.has(error)) return "network";
101958
102282
  if (typeof status === "number") {
@@ -102317,6 +102641,10 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102317
102641
  handleBackgroundTasksChanged(message, session.id, entry);
102318
102642
  continue;
102319
102643
  }
102644
+ if (message.type === "rate_limit_event") {
102645
+ entry.rateLimit = message.rate_limit_info;
102646
+ continue;
102647
+ }
102320
102648
  const currentTurnId = entry.turnId;
102321
102649
  if (!currentTurnId) {
102322
102650
  handleTaskFrame(message, session.id, entry, db2);
@@ -102869,11 +103197,18 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
102869
103197
  const apiError = entry.lastApiError;
102870
103198
  entry.lastApiError = null;
102871
103199
  if (message.is_error) {
102872
- const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
103200
+ const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
102873
103201
  if (row?.status !== "pending" && row?.status !== "running") return;
103202
+ if (row.status === "pending" && row.resume_state === "waiting") return;
102874
103203
  const text = (message.result || apiError?.text || "Claude API error").trim();
102875
- const kind = classifyApiError({ error: apiError?.error, status: message.api_error_status, text });
102876
- if (kind === "network" && !entry.threadId && markTurnInterrupted(db2, turnId, "network", { detail: text })) {
103204
+ const kind = classifyApiError({
103205
+ error: apiError?.error,
103206
+ status: message.api_error_status,
103207
+ text,
103208
+ limitRejected: entry.rateLimit?.status === "rejected"
103209
+ });
103210
+ const resumeAt = kind === "usage_limit" ? usageLimitResumeAt(entry.rateLimit?.resetsAt) : null;
103211
+ if (kind !== "fatal" && !entry.threadId && markTurnInterrupted(db2, turnId, kind, { detail: text, resumeAt })) {
102877
103212
  return;
102878
103213
  }
102879
103214
  failTurn(db2, sessionId, turnId, text);
@@ -103174,9 +103509,22 @@ async function reapOrphans() {
103174
103509
  const ended = await reapOrphanCliProcesses(getDb());
103175
103510
  if (ended > 0) console.log(`[claude] ended ${ended} CLI process(es) left by the previous host`);
103176
103511
  }
103512
+ function retireCli(sessionId, entry) {
103513
+ if (entry.turnId) streamingMessageIds.delete(entry.turnId);
103514
+ entry.turnId = null;
103515
+ entry.closeReason ??= "clear";
103516
+ clearResume(entry);
103517
+ entry.promptQueue.close();
103518
+ entry.query.close();
103519
+ sessionMap2.delete(sessionId);
103520
+ }
103177
103521
  async function resumeInterruptedTurn(session, turn, opts) {
103178
103522
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
103179
- const live = sessionMap2.get(session.id);
103523
+ let live = sessionMap2.get(session.id);
103524
+ if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
103525
+ retireCli(session.id, live);
103526
+ live = void 0;
103527
+ }
103180
103528
  if (live && !live.closeReason) {
103181
103529
  if (live.turnId && live.turnId !== turn.id) streamingMessageIds.delete(live.turnId);
103182
103530
  clearResume(live);
@@ -103352,8 +103700,8 @@ var RepoburgHttpClient = class {
103352
103700
  this.baseUrl = baseUrl.replace(/\/+$/, "");
103353
103701
  }
103354
103702
  /** Perform a JSON request. Throws a concise error on non-OK/non-JSON responses. */
103355
- async request(method, path11, body) {
103356
- const response = await fetch(`${this.baseUrl}${path11}`, {
103703
+ async request(method, path12, body) {
103704
+ const response = await fetch(`${this.baseUrl}${path12}`, {
103357
103705
  method,
103358
103706
  headers: { "Content-Type": "application/json" },
103359
103707
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -103362,17 +103710,17 @@ var RepoburgHttpClient = class {
103362
103710
  if (!response.ok) {
103363
103711
  if (isHtml(text)) {
103364
103712
  throw new Error(
103365
- `${method} ${path11} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
103713
+ `${method} ${path12} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
103366
103714
  );
103367
103715
  }
103368
- throw new Error(`${method} ${path11} failed: ${response.status} ${text}`);
103716
+ throw new Error(`${method} ${path12} failed: ${response.status} ${text}`);
103369
103717
  }
103370
103718
  if (text.length === 0) return void 0;
103371
103719
  try {
103372
103720
  return JSON.parse(text);
103373
103721
  } catch {
103374
103722
  throw new Error(
103375
- `${method} ${path11} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
103723
+ `${method} ${path12} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
103376
103724
  );
103377
103725
  }
103378
103726
  }
@@ -103427,7 +103775,7 @@ var RepoburgHttpClient = class {
103427
103775
  };
103428
103776
 
103429
103777
  // src/repoburg/backend-resolver.ts
103430
- import path10 from "node:path";
103778
+ import path11 from "node:path";
103431
103779
  var HEALTH_POLL_INTERVAL_MS = 1e3;
103432
103780
  var HEALTH_TIMEOUT_MS = 3e4;
103433
103781
  function daemonBaseUrl() {
@@ -103482,7 +103830,7 @@ async function backendHealthy(baseUrl, expectedPath) {
103482
103830
  const health = await fetchJson(`${baseUrl}/health`, void 0, 2e3);
103483
103831
  if (health.status !== "ok") return false;
103484
103832
  if (expectedPath && health.projectPath) {
103485
- return path10.resolve(health.projectPath) === path10.resolve(expectedPath);
103833
+ return path11.resolve(health.projectPath) === path11.resolve(expectedPath);
103486
103834
  }
103487
103835
  return true;
103488
103836
  } catch {
@@ -103503,7 +103851,7 @@ function serviceBaseUrl(service) {
103503
103851
  return `http://localhost:${service.port}`;
103504
103852
  }
103505
103853
  function coveringService(services, absPath) {
103506
- return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path10.sep)).sort((a, b) => b.path.length - a.path.length)[0];
103854
+ return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path11.sep)).sort((a, b) => b.path.length - a.path.length)[0];
103507
103855
  }
103508
103856
  async function restartService(daemon, name) {
103509
103857
  try {
@@ -103539,7 +103887,7 @@ async function resolveBackendUrl(projectPath, opts = {}) {
103539
103887
  if (envUrl) {
103540
103888
  return { baseUrl: envUrl.replace(/\/+$/, ""), port: 0, name: "REPOBURG_BACKEND_URL" };
103541
103889
  }
103542
- const absPath = path10.resolve(projectPath);
103890
+ const absPath = path11.resolve(projectPath);
103543
103891
  const daemon = daemonBaseUrl();
103544
103892
  const cached = resolvedCache.get(absPath);
103545
103893
  if (cached && await backendHealthy(cached.baseUrl, cached.servesPath ?? absPath)) {
@@ -104975,11 +105323,13 @@ async function createAgentPaneApp(dbPath, opts = {}) {
104975
105323
  await registerSidecarRoutes(fastify);
104976
105324
  await registerUsageRoutes(fastify);
104977
105325
  await registerClaudeSessionRoutes(fastify);
104978
- const wss2 = initWs(allowRequest);
104979
- wss2.on("connection", (ws) => {
105326
+ const wss3 = initWs(allowRequest);
105327
+ initTerminalWs(allowRequest);
105328
+ wss3.on("connection", (ws) => {
104980
105329
  ws.send(JSON.stringify({ event: "background_tasks:snapshot", data: { sessions: listAllBackgroundTasks() } }));
105330
+ ws.send(JSON.stringify({ event: "signed_out_turns:snapshot", data: { turns: listSignedOutTurns(getDb()) } }));
104981
105331
  });
104982
- return { fastify, wss: wss2 };
105332
+ return { fastify, wss: wss3 };
104983
105333
  }
104984
105334
 
104985
105335
  // src/host-lifecycle.ts
@@ -104989,11 +105339,13 @@ function startHostServices() {
104989
105339
  }
104990
105340
  async function shutdownHost() {
104991
105341
  stopAutoResume();
105342
+ stopAllTerminals();
104992
105343
  await shutdownAllProviders();
104993
105344
  await getVscodeWebManager().stopAll();
104994
105345
  }
104995
105346
  export {
104996
105347
  createAgentPaneApp,
105348
+ handleTerminalUpgrade,
104997
105349
  handleVscodeWebUpgrade,
104998
105350
  shutdownHost as shutdownAllProviders,
104999
105351
  startHostServices as startAutoResume