repoburg 1.3.303 → 1.3.304

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.
Files changed (35) hide show
  1. package/agent-pane/backend/dist/index.js +2656 -434
  2. package/agent-pane/backend/dist/server.js +2751 -434
  3. package/agent-pane/backend/scripts/session-host.mjs +860 -0
  4. package/agent-pane/frontend/dist/assets/{TerminalView-C6AkFuDP.js → TerminalView-BN_4GKd9.js} +1 -1
  5. package/agent-pane/frontend/dist/assets/index-CaUGqLNi.js +836 -0
  6. package/agent-pane/frontend/dist/index.html +1 -1
  7. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.d.ts +30 -2
  8. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js +108 -6
  9. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js.map +1 -1
  10. package/backend/dist/src/agent-runtime/agent-runtime.controller.d.ts +4 -2
  11. package/backend/dist/src/agent-runtime/agent-runtime.controller.js +49 -9
  12. package/backend/dist/src/agent-runtime/agent-runtime.controller.js.map +1 -1
  13. package/backend/dist/src/agent-runtime/agent-runtime.types.d.ts +20 -1
  14. package/backend/dist/src/interactive-chat/chat.service.js +9 -2
  15. package/backend/dist/src/interactive-chat/chat.service.js.map +1 -1
  16. package/backend/dist/src/session-inputs/session-inputs.module.js +2 -0
  17. package/backend/dist/src/session-inputs/session-inputs.module.js.map +1 -1
  18. package/backend/dist/src/session-inputs/session-inputs.service.d.ts +4 -1
  19. package/backend/dist/src/session-inputs/session-inputs.service.js +15 -2
  20. package/backend/dist/src/session-inputs/session-inputs.service.js.map +1 -1
  21. package/backend/dist/tsconfig.build.tsbuildinfo +1 -1
  22. package/daemon/dist/agentPane.js +6 -2
  23. package/daemon/dist/agents.js +74 -0
  24. package/daemon/dist/agents.spec.js +90 -0
  25. package/daemon/dist/api/agents.js +38 -0
  26. package/daemon/dist/api/services.js +25 -0
  27. package/daemon/dist/index.js +7 -3
  28. package/daemon/dist/serviceManager.js +28 -2
  29. package/daemon/dist/serviceRoller.js +133 -0
  30. package/daemon/dist/serviceRoller.spec.js +132 -0
  31. package/package.json +2 -1
  32. package/tabtape/extension/dist/build-info.json +3 -3
  33. package/tabtape/extension/dist/manifest.json +1 -1
  34. package/tabtape/ui/dist/build-info.json +3 -3
  35. package/agent-pane/frontend/dist/assets/index-DoReiVY-.js +0 -834
@@ -732,7 +732,7 @@ var require_is_promise_like = __commonJS({
732
732
  var require_plugin = __commonJS({
733
733
  "node_modules/avvio/lib/plugin.js"(exports, module) {
734
734
  "use strict";
735
- var { EventEmitter: EventEmitter2 } = __require("node:events");
735
+ var { EventEmitter: EventEmitter5 } = __require("node:events");
736
736
  var { inherits } = __require("node:util");
737
737
  var { debug } = require_debug();
738
738
  var { createPromise } = require_create_promise();
@@ -753,7 +753,7 @@ var require_plugin = __commonJS({
753
753
  this._promise = null;
754
754
  this.startTime = null;
755
755
  }
756
- inherits(Plugin, EventEmitter2);
756
+ inherits(Plugin, EventEmitter5);
757
757
  Plugin.prototype.exec = function(server, callback) {
758
758
  debug("exec", this.name);
759
759
  this.server = server;
@@ -6128,8 +6128,8 @@ var require_req = __commonJS({
6128
6128
  if (req.originalUrl) {
6129
6129
  _req.url = req.originalUrl;
6130
6130
  } else {
6131
- const path13 = req.path;
6132
- _req.url = typeof path13 === "string" ? path13 : req.url ? req.url.path || req.url : void 0;
6131
+ const path17 = req.path;
6132
+ _req.url = typeof path17 === "string" ? path17 : req.url ? req.url.path || req.url : void 0;
6133
6133
  }
6134
6134
  if (req.query) {
6135
6135
  _req.query = req.query;
@@ -6294,14 +6294,14 @@ var require_redact = __commonJS({
6294
6294
  }
6295
6295
  return obj2;
6296
6296
  }
6297
- function parsePath(path13) {
6297
+ function parsePath(path17) {
6298
6298
  const parts = [];
6299
6299
  let current = "";
6300
6300
  let inBrackets = false;
6301
6301
  let inQuotes = false;
6302
6302
  let quoteChar = "";
6303
- for (let i = 0; i < path13.length; i++) {
6304
- const char = path13[i];
6303
+ for (let i = 0; i < path17.length; i++) {
6304
+ const char = path17[i];
6305
6305
  if (!inBrackets && char === ".") {
6306
6306
  if (current) {
6307
6307
  parts.push(current);
@@ -6432,10 +6432,10 @@ var require_redact = __commonJS({
6432
6432
  return current;
6433
6433
  }
6434
6434
  function redactPaths(obj2, paths, censor, remove = false) {
6435
- for (const path13 of paths) {
6436
- const parts = parsePath(path13);
6435
+ for (const path17 of paths) {
6436
+ const parts = parsePath(path17);
6437
6437
  if (parts.includes("*")) {
6438
- redactWildcardPath(obj2, parts, censor, path13, remove);
6438
+ redactWildcardPath(obj2, parts, censor, path17, remove);
6439
6439
  } else {
6440
6440
  if (remove) {
6441
6441
  removeKey(obj2, parts);
@@ -6520,8 +6520,8 @@ var require_redact = __commonJS({
6520
6520
  }
6521
6521
  } else {
6522
6522
  if (afterWildcard.includes("*")) {
6523
- const wrappedCensor = typeof censor === "function" ? (value, path13) => {
6524
- const fullPath = [...pathArray.slice(0, pathLength), ...path13];
6523
+ const wrappedCensor = typeof censor === "function" ? (value, path17) => {
6524
+ const fullPath = [...pathArray.slice(0, pathLength), ...path17];
6525
6525
  return censor(value, fullPath);
6526
6526
  } : censor;
6527
6527
  redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove);
@@ -6556,8 +6556,8 @@ var require_redact = __commonJS({
6556
6556
  return null;
6557
6557
  }
6558
6558
  const pathStructure = /* @__PURE__ */ new Map();
6559
- for (const path13 of pathsToClone) {
6560
- const parts = parsePath(path13);
6559
+ for (const path17 of pathsToClone) {
6560
+ const parts = parsePath(path17);
6561
6561
  let current = pathStructure;
6562
6562
  for (let i = 0; i < parts.length; i++) {
6563
6563
  const part = parts[i];
@@ -6609,24 +6609,24 @@ var require_redact = __commonJS({
6609
6609
  }
6610
6610
  return cloneSelectively(obj2, pathStructure);
6611
6611
  }
6612
- function validatePath(path13) {
6613
- if (typeof path13 !== "string") {
6612
+ function validatePath(path17) {
6613
+ if (typeof path17 !== "string") {
6614
6614
  throw new Error("Paths must be (non-empty) strings");
6615
6615
  }
6616
- if (path13 === "") {
6616
+ if (path17 === "") {
6617
6617
  throw new Error("Invalid redaction path ()");
6618
6618
  }
6619
- if (path13.includes("..")) {
6620
- throw new Error(`Invalid redaction path (${path13})`);
6619
+ if (path17.includes("..")) {
6620
+ throw new Error(`Invalid redaction path (${path17})`);
6621
6621
  }
6622
- if (path13.includes(",")) {
6623
- throw new Error(`Invalid redaction path (${path13})`);
6622
+ if (path17.includes(",")) {
6623
+ throw new Error(`Invalid redaction path (${path17})`);
6624
6624
  }
6625
6625
  let bracketCount = 0;
6626
6626
  let inQuotes = false;
6627
6627
  let quoteChar = "";
6628
- for (let i = 0; i < path13.length; i++) {
6629
- const char = path13[i];
6628
+ for (let i = 0; i < path17.length; i++) {
6629
+ const char = path17[i];
6630
6630
  if ((char === '"' || char === "'") && bracketCount > 0) {
6631
6631
  if (!inQuotes) {
6632
6632
  inQuotes = true;
@@ -6640,20 +6640,20 @@ var require_redact = __commonJS({
6640
6640
  } else if (char === "]" && !inQuotes) {
6641
6641
  bracketCount--;
6642
6642
  if (bracketCount < 0) {
6643
- throw new Error(`Invalid redaction path (${path13})`);
6643
+ throw new Error(`Invalid redaction path (${path17})`);
6644
6644
  }
6645
6645
  }
6646
6646
  }
6647
6647
  if (bracketCount !== 0) {
6648
- throw new Error(`Invalid redaction path (${path13})`);
6648
+ throw new Error(`Invalid redaction path (${path17})`);
6649
6649
  }
6650
6650
  }
6651
6651
  function validatePaths(paths) {
6652
6652
  if (!Array.isArray(paths)) {
6653
6653
  throw new TypeError("paths must be an array");
6654
6654
  }
6655
- for (const path13 of paths) {
6656
- validatePath(path13);
6655
+ for (const path17 of paths) {
6656
+ validatePath(path17);
6657
6657
  }
6658
6658
  }
6659
6659
  function slowRedact(options = {}) {
@@ -6821,8 +6821,8 @@ var require_redaction = __commonJS({
6821
6821
  if (shape[k] === null) {
6822
6822
  o[k] = (value) => topCensor(value, [k]);
6823
6823
  } else {
6824
- const wrappedCensor = typeof censor === "function" ? (value, path13) => {
6825
- return censor(value, [k, ...path13]);
6824
+ const wrappedCensor = typeof censor === "function" ? (value, path17) => {
6825
+ return censor(value, [k, ...path17]);
6826
6826
  } : censor;
6827
6827
  o[k] = Redact({
6828
6828
  paths: shape[k],
@@ -6874,9 +6874,9 @@ var require_time = __commonJS({
6874
6874
  const month = (date5.getUTCMonth() + 1).toString().padStart(2, "0");
6875
6875
  const day = date5.getUTCDate().toString().padStart(2, "0");
6876
6876
  const hours = date5.getUTCHours().toString().padStart(2, "0");
6877
- const minutes = date5.getUTCMinutes().toString().padStart(2, "0");
6877
+ const minutes2 = date5.getUTCMinutes().toString().padStart(2, "0");
6878
6878
  const seconds = date5.getUTCSeconds().toString().padStart(2, "0");
6879
- return `,"time":"${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${nanosWithinSecond.toString().padStart(9, "0")}Z"`;
6879
+ return `,"time":"${year}-${month}-${day}T${hours}:${minutes2}:${seconds}.${nanosWithinSecond.toString().padStart(9, "0")}Z"`;
6880
6880
  };
6881
6881
  module.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano };
6882
6882
  }
@@ -7006,7 +7006,7 @@ var require_atomic_sleep = __commonJS({
7006
7006
  "node_modules/atomic-sleep/index.js"(exports, module) {
7007
7007
  "use strict";
7008
7008
  if (typeof SharedArrayBuffer !== "undefined" && typeof Atomics !== "undefined") {
7009
- let sleep = function(ms) {
7009
+ let sleep2 = function(ms) {
7010
7010
  const valid = ms > 0 && ms < Infinity;
7011
7011
  if (valid === false) {
7012
7012
  if (typeof ms !== "number" && typeof ms !== "bigint") {
@@ -7017,9 +7017,9 @@ var require_atomic_sleep = __commonJS({
7017
7017
  Atomics.wait(nil, 0, 0, Number(ms));
7018
7018
  };
7019
7019
  const nil = new Int32Array(new SharedArrayBuffer(4));
7020
- module.exports = sleep;
7020
+ module.exports = sleep2;
7021
7021
  } else {
7022
- let sleep = function(ms) {
7022
+ let sleep2 = function(ms) {
7023
7023
  const valid = ms > 0 && ms < Infinity;
7024
7024
  if (valid === false) {
7025
7025
  if (typeof ms !== "number" && typeof ms !== "bigint") {
@@ -7031,7 +7031,7 @@ var require_atomic_sleep = __commonJS({
7031
7031
  while (target > Date.now()) {
7032
7032
  }
7033
7033
  };
7034
- module.exports = sleep;
7034
+ module.exports = sleep2;
7035
7035
  }
7036
7036
  }
7037
7037
  });
@@ -7040,11 +7040,11 @@ var require_atomic_sleep = __commonJS({
7040
7040
  var require_sonic_boom = __commonJS({
7041
7041
  "node_modules/sonic-boom/index.js"(exports, module) {
7042
7042
  "use strict";
7043
- var fs8 = __require("fs");
7044
- var EventEmitter2 = __require("events");
7043
+ var fs11 = __require("fs");
7044
+ var EventEmitter5 = __require("events");
7045
7045
  var inherits = __require("util").inherits;
7046
- var path13 = __require("path");
7047
- var sleep = require_atomic_sleep();
7046
+ var path17 = __require("path");
7047
+ var sleep2 = require_atomic_sleep();
7048
7048
  var assert2 = __require("assert");
7049
7049
  var BUSY_WRITE_TIMEOUT = 100;
7050
7050
  var kEmptyBuffer = Buffer.allocUnsafe(0);
@@ -7097,20 +7097,20 @@ var require_sonic_boom = __commonJS({
7097
7097
  const mode = sonic.mode;
7098
7098
  if (sonic.sync) {
7099
7099
  try {
7100
- if (sonic.mkdir) fs8.mkdirSync(path13.dirname(file2), { recursive: true });
7101
- const fd = fs8.openSync(file2, flags, mode);
7100
+ if (sonic.mkdir) fs11.mkdirSync(path17.dirname(file2), { recursive: true });
7101
+ const fd = fs11.openSync(file2, flags, mode);
7102
7102
  fileOpened(null, fd);
7103
7103
  } catch (err) {
7104
7104
  fileOpened(err);
7105
7105
  throw err;
7106
7106
  }
7107
7107
  } else if (sonic.mkdir) {
7108
- fs8.mkdir(path13.dirname(file2), { recursive: true }, (err) => {
7108
+ fs11.mkdir(path17.dirname(file2), { recursive: true }, (err) => {
7109
7109
  if (err) return fileOpened(err);
7110
- fs8.open(file2, flags, mode, fileOpened);
7110
+ fs11.open(file2, flags, mode, fileOpened);
7111
7111
  });
7112
7112
  } else {
7113
- fs8.open(file2, flags, mode, fileOpened);
7113
+ fs11.open(file2, flags, mode, fileOpened);
7114
7114
  }
7115
7115
  }
7116
7116
  function SonicBoom(opts) {
@@ -7151,8 +7151,8 @@ var require_sonic_boom = __commonJS({
7151
7151
  this.flush = flushBuffer;
7152
7152
  this.flushSync = flushBufferSync;
7153
7153
  this._actualWrite = actualWriteBuffer;
7154
- fsWriteSync = () => fs8.writeSync(this.fd, this._writingBuf);
7155
- fsWrite = () => fs8.write(this.fd, this._writingBuf, this.release);
7154
+ fsWriteSync = () => fs11.writeSync(this.fd, this._writingBuf);
7155
+ fsWrite = () => fs11.write(this.fd, this._writingBuf, this.release);
7156
7156
  } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
7157
7157
  this._writingBuf = "";
7158
7158
  this.write = write;
@@ -7161,15 +7161,15 @@ var require_sonic_boom = __commonJS({
7161
7161
  this._actualWrite = actualWrite;
7162
7162
  fsWriteSync = () => {
7163
7163
  if (Buffer.isBuffer(this._writingBuf)) {
7164
- return fs8.writeSync(this.fd, this._writingBuf);
7164
+ return fs11.writeSync(this.fd, this._writingBuf);
7165
7165
  }
7166
- return fs8.writeSync(this.fd, this._writingBuf, "utf8");
7166
+ return fs11.writeSync(this.fd, this._writingBuf, "utf8");
7167
7167
  };
7168
7168
  fsWrite = () => {
7169
7169
  if (Buffer.isBuffer(this._writingBuf)) {
7170
- return fs8.write(this.fd, this._writingBuf, this.release);
7170
+ return fs11.write(this.fd, this._writingBuf, this.release);
7171
7171
  }
7172
- return fs8.write(this.fd, this._writingBuf, "utf8", this.release);
7172
+ return fs11.write(this.fd, this._writingBuf, "utf8", this.release);
7173
7173
  };
7174
7174
  } else {
7175
7175
  throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
@@ -7190,7 +7190,7 @@ var require_sonic_boom = __commonJS({
7190
7190
  if ((err.code === "EAGAIN" || err.code === "EBUSY") && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {
7191
7191
  if (this.sync) {
7192
7192
  try {
7193
- sleep(BUSY_WRITE_TIMEOUT);
7193
+ sleep2(BUSY_WRITE_TIMEOUT);
7194
7194
  this.release(void 0, 0);
7195
7195
  } catch (err2) {
7196
7196
  this.release(err2);
@@ -7226,7 +7226,7 @@ var require_sonic_boom = __commonJS({
7226
7226
  }
7227
7227
  }
7228
7228
  if (this._fsync) {
7229
- fs8.fsyncSync(this.fd);
7229
+ fs11.fsyncSync(this.fd);
7230
7230
  }
7231
7231
  const len = this._len;
7232
7232
  if (this._reopening) {
@@ -7278,7 +7278,7 @@ var require_sonic_boom = __commonJS({
7278
7278
  sonic._asyncDrainScheduled = false;
7279
7279
  sonic.emit("drain");
7280
7280
  }
7281
- inherits(SonicBoom, EventEmitter2);
7281
+ inherits(SonicBoom, EventEmitter5);
7282
7282
  function mergeBuf(bufs, len) {
7283
7283
  if (bufs.length === 0) {
7284
7284
  return kEmptyBuffer;
@@ -7340,7 +7340,7 @@ var require_sonic_boom = __commonJS({
7340
7340
  const onDrain = () => {
7341
7341
  if (!this._fsync) {
7342
7342
  try {
7343
- fs8.fsync(this.fd, (err) => {
7343
+ fs11.fsync(this.fd, (err) => {
7344
7344
  this._flushPending = false;
7345
7345
  cb(err);
7346
7346
  });
@@ -7442,7 +7442,7 @@ var require_sonic_boom = __commonJS({
7442
7442
  const fd = this.fd;
7443
7443
  this.once("ready", () => {
7444
7444
  if (fd !== this.fd) {
7445
- fs8.close(fd, (err) => {
7445
+ fs11.close(fd, (err) => {
7446
7446
  if (err) {
7447
7447
  return this.emit("error", err);
7448
7448
  }
@@ -7491,7 +7491,7 @@ var require_sonic_boom = __commonJS({
7491
7491
  buf = this._bufs[0];
7492
7492
  }
7493
7493
  try {
7494
- const n = Buffer.isBuffer(buf) ? fs8.writeSync(this.fd, buf) : fs8.writeSync(this.fd, buf, "utf8");
7494
+ const n = Buffer.isBuffer(buf) ? fs11.writeSync(this.fd, buf) : fs11.writeSync(this.fd, buf, "utf8");
7495
7495
  const releasedBufObj = releaseWritingBuf(buf, this._len, n);
7496
7496
  buf = releasedBufObj.writingBuf;
7497
7497
  this._len = releasedBufObj.len;
@@ -7503,11 +7503,11 @@ var require_sonic_boom = __commonJS({
7503
7503
  if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
7504
7504
  throw err;
7505
7505
  }
7506
- sleep(BUSY_WRITE_TIMEOUT);
7506
+ sleep2(BUSY_WRITE_TIMEOUT);
7507
7507
  }
7508
7508
  }
7509
7509
  try {
7510
- fs8.fsyncSync(this.fd);
7510
+ fs11.fsyncSync(this.fd);
7511
7511
  } catch {
7512
7512
  }
7513
7513
  }
@@ -7528,7 +7528,7 @@ var require_sonic_boom = __commonJS({
7528
7528
  buf = mergeBuf(this._bufs[0], this._lens[0]);
7529
7529
  }
7530
7530
  try {
7531
- const n = fs8.writeSync(this.fd, buf);
7531
+ const n = fs11.writeSync(this.fd, buf);
7532
7532
  buf = buf.subarray(n);
7533
7533
  this._len = Math.max(this._len - n, 0);
7534
7534
  if (buf.length <= 0) {
@@ -7540,7 +7540,7 @@ var require_sonic_boom = __commonJS({
7540
7540
  if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
7541
7541
  throw err;
7542
7542
  }
7543
- sleep(BUSY_WRITE_TIMEOUT);
7543
+ sleep2(BUSY_WRITE_TIMEOUT);
7544
7544
  }
7545
7545
  }
7546
7546
  }
@@ -7556,13 +7556,13 @@ var require_sonic_boom = __commonJS({
7556
7556
  this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
7557
7557
  if (this.sync) {
7558
7558
  try {
7559
- const written = Buffer.isBuffer(this._writingBuf) ? fs8.writeSync(this.fd, this._writingBuf) : fs8.writeSync(this.fd, this._writingBuf, "utf8");
7559
+ const written = Buffer.isBuffer(this._writingBuf) ? fs11.writeSync(this.fd, this._writingBuf) : fs11.writeSync(this.fd, this._writingBuf, "utf8");
7560
7560
  release(null, written);
7561
7561
  } catch (err) {
7562
7562
  release(err);
7563
7563
  }
7564
7564
  } else {
7565
- fs8.write(this.fd, this._writingBuf, release);
7565
+ fs11.write(this.fd, this._writingBuf, release);
7566
7566
  }
7567
7567
  }
7568
7568
  function actualWriteBuffer() {
@@ -7571,7 +7571,7 @@ var require_sonic_boom = __commonJS({
7571
7571
  this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
7572
7572
  if (this.sync) {
7573
7573
  try {
7574
- const written = fs8.writeSync(this.fd, this._writingBuf);
7574
+ const written = fs11.writeSync(this.fd, this._writingBuf);
7575
7575
  release(null, written);
7576
7576
  } catch (err) {
7577
7577
  release(err);
@@ -7580,7 +7580,7 @@ var require_sonic_boom = __commonJS({
7580
7580
  if (kCopyBuffer) {
7581
7581
  this._writingBuf = Buffer.from(this._writingBuf);
7582
7582
  }
7583
- fs8.write(this.fd, this._writingBuf, release);
7583
+ fs11.write(this.fd, this._writingBuf, release);
7584
7584
  }
7585
7585
  }
7586
7586
  function actualClose(sonic) {
@@ -7596,12 +7596,12 @@ var require_sonic_boom = __commonJS({
7596
7596
  sonic._lens = [];
7597
7597
  assert2(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
7598
7598
  try {
7599
- fs8.fsync(sonic.fd, closeWrapped);
7599
+ fs11.fsync(sonic.fd, closeWrapped);
7600
7600
  } catch {
7601
7601
  }
7602
7602
  function closeWrapped() {
7603
7603
  if (sonic.fd !== 1 && sonic.fd !== 2) {
7604
- fs8.close(sonic.fd, done);
7604
+ fs11.close(sonic.fd, done);
7605
7605
  } else {
7606
7606
  done();
7607
7607
  }
@@ -7852,7 +7852,7 @@ var require_thread_stream = __commonJS({
7852
7852
  "node_modules/thread-stream/index.js"(exports, module) {
7853
7853
  "use strict";
7854
7854
  var { version: version2 } = require_package();
7855
- var { EventEmitter: EventEmitter2 } = __require("events");
7855
+ var { EventEmitter: EventEmitter5 } = __require("events");
7856
7856
  var { Worker } = __require("worker_threads");
7857
7857
  var { join: join6 } = __require("path");
7858
7858
  var { pathToFileURL } = __require("url");
@@ -8026,7 +8026,7 @@ var require_thread_stream = __commonJS({
8026
8026
  stream.worker.off("exit", onWorkerExit);
8027
8027
  destroy(stream, code !== 0 ? new Error("the worker thread exited") : null);
8028
8028
  }
8029
- var ThreadStream = class extends EventEmitter2 {
8029
+ var ThreadStream = class extends EventEmitter5 {
8030
8030
  constructor(opts = {}) {
8031
8031
  super();
8032
8032
  if (opts.bufferSize < 4) {
@@ -8374,8 +8374,8 @@ var require_transport = __commonJS({
8374
8374
  var { existsSync: existsSync3 } = __require("node:fs");
8375
8375
  var getCallers = require_caller();
8376
8376
  var { join: join6, isAbsolute, sep } = __require("node:path");
8377
- var { fileURLToPath: fileURLToPath3 } = __require("node:url");
8378
- var sleep = require_atomic_sleep();
8377
+ var { fileURLToPath: fileURLToPath5 } = __require("node:url");
8378
+ var sleep2 = require_atomic_sleep();
8379
8379
  var onExit = require_on_exit_leak_free();
8380
8380
  var ThreadStream = require_thread_stream();
8381
8381
  function setupOnExit(stream) {
@@ -8437,15 +8437,15 @@ var require_transport = __commonJS({
8437
8437
  if (!unquoted) {
8438
8438
  return false;
8439
8439
  }
8440
- let path13 = unquoted;
8441
- if (path13.startsWith("file://")) {
8440
+ let path17 = unquoted;
8441
+ if (path17.startsWith("file://")) {
8442
8442
  try {
8443
- path13 = fileURLToPath3(path13);
8443
+ path17 = fileURLToPath5(path17);
8444
8444
  } catch {
8445
8445
  return false;
8446
8446
  }
8447
8447
  }
8448
- return isAbsolute(path13) && !existsSync3(path13);
8448
+ return isAbsolute(path17) && !existsSync3(path17);
8449
8449
  }
8450
8450
  function stripQuotes(value) {
8451
8451
  const first = value[0];
@@ -8498,7 +8498,7 @@ var require_transport = __commonJS({
8498
8498
  return;
8499
8499
  }
8500
8500
  stream.flushSync();
8501
- sleep(100);
8501
+ sleep2(100);
8502
8502
  stream.end();
8503
8503
  }
8504
8504
  return stream;
@@ -9145,7 +9145,7 @@ var require_meta = __commonJS({
9145
9145
  var require_proto = __commonJS({
9146
9146
  "node_modules/pino/lib/proto.js"(exports, module) {
9147
9147
  "use strict";
9148
- var { EventEmitter: EventEmitter2 } = __require("node:events");
9148
+ var { EventEmitter: EventEmitter5 } = __require("node:events");
9149
9149
  var {
9150
9150
  lsCacheSym,
9151
9151
  levelValSym,
@@ -9226,7 +9226,7 @@ var require_proto = __commonJS({
9226
9226
  [getLevelSym]: getLevel,
9227
9227
  [setLevelSym]: setLevel
9228
9228
  };
9229
- Object.setPrototypeOf(prototype, EventEmitter2.prototype);
9229
+ Object.setPrototypeOf(prototype, EventEmitter5.prototype);
9230
9230
  module.exports = function() {
9231
9231
  return Object.create(prototype);
9232
9232
  };
@@ -10008,11 +10008,11 @@ var require_multistream = __commonJS({
10008
10008
  function write(data) {
10009
10009
  let dest;
10010
10010
  const level = this.lastLevel;
10011
- const { streams } = this;
10011
+ const { streams: streams2 } = this;
10012
10012
  let recordedLevel = 0;
10013
10013
  let stream;
10014
- for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {
10015
- dest = streams[i];
10014
+ for (let i = initLoopVar(streams2.length, opts.dedupe); checkLoopVar(i, streams2.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {
10015
+ dest = streams2[i];
10016
10016
  if (dest.level <= level) {
10017
10017
  if (recordedLevel !== 0 && recordedLevel !== dest.level) {
10018
10018
  break;
@@ -10058,7 +10058,7 @@ var require_multistream = __commonJS({
10058
10058
  if (!isStream) {
10059
10059
  throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");
10060
10060
  }
10061
- const { streams, streamLevels: streamLevels2 } = this;
10061
+ const { streams: streams2, streamLevels: streamLevels2 } = this;
10062
10062
  let level;
10063
10063
  if (typeof dest.levelVal === "number") {
10064
10064
  level = dest.levelVal;
@@ -10075,18 +10075,18 @@ var require_multistream = __commonJS({
10075
10075
  levelVal: void 0,
10076
10076
  id: ++res.lastId
10077
10077
  };
10078
- streams.unshift(dest_);
10079
- streams.sort(compareByLevel);
10080
- this.minLevel = streams[0].level;
10078
+ streams2.unshift(dest_);
10079
+ streams2.sort(compareByLevel);
10080
+ this.minLevel = streams2[0].level;
10081
10081
  return res;
10082
10082
  }
10083
10083
  function remove(id) {
10084
- const { streams } = this;
10085
- const index = streams.findIndex((s) => s.id === id);
10084
+ const { streams: streams2 } = this;
10085
+ const index = streams2.findIndex((s) => s.id === id);
10086
10086
  if (index >= 0) {
10087
- streams.splice(index, 1);
10088
- streams.sort(compareByLevel);
10089
- this.minLevel = streams.length > 0 ? streams[0].level : -1;
10087
+ streams2.splice(index, 1);
10088
+ streams2.sort(compareByLevel);
10089
+ this.minLevel = streams2.length > 0 ? streams2[0].level : -1;
10090
10090
  }
10091
10091
  return res;
10092
10092
  }
@@ -10099,9 +10099,9 @@ var require_multistream = __commonJS({
10099
10099
  }
10100
10100
  }
10101
10101
  function clone2(level) {
10102
- const streams = new Array(this.streams.length);
10103
- for (let i = 0; i < streams.length; i++) {
10104
- streams[i] = {
10102
+ const streams2 = new Array(this.streams.length);
10103
+ for (let i = 0; i < streams2.length; i++) {
10104
+ streams2[i] = {
10105
10105
  level,
10106
10106
  stream: this.streams[i].stream
10107
10107
  };
@@ -10111,7 +10111,7 @@ var require_multistream = __commonJS({
10111
10111
  add,
10112
10112
  remove,
10113
10113
  minLevel: level,
10114
- streams,
10114
+ streams: streams2,
10115
10115
  clone: clone2,
10116
10116
  emit,
10117
10117
  flushSync,
@@ -10722,8 +10722,8 @@ var require_serializer = __commonJS({
10722
10722
  return "" + num3;
10723
10723
  }
10724
10724
  }
10725
- asBoolean(bool) {
10726
- return bool && "true" || "false";
10725
+ asBoolean(bool2) {
10726
+ return bool2 && "true" || "false";
10727
10727
  }
10728
10728
  asDateTime(date5) {
10729
10729
  if (date5 === null) return '""';
@@ -13683,8 +13683,8 @@ var require_content_type_parser = __commonJS({
13683
13683
  };
13684
13684
  ContentTypeParser.prototype.getParser = function(contentType) {
13685
13685
  if (typeof contentType === "string") {
13686
- const cached2 = this.cache.get(contentType);
13687
- if (cached2 !== void 0) return cached2;
13686
+ const cached3 = this.cache.get(contentType);
13687
+ if (cached3 !== void 0) return cached3;
13688
13688
  contentType = new ContentType(contentType);
13689
13689
  }
13690
13690
  const ct = contentType.toString();
@@ -17121,8 +17121,8 @@ var require_utils = __commonJS({
17121
17121
  }
17122
17122
  return ind;
17123
17123
  }
17124
- function removeDotSegments(path13) {
17125
- let input = path13;
17124
+ function removeDotSegments(path17) {
17125
+ let input = path17;
17126
17126
  const output = [];
17127
17127
  let nextSlash = -1;
17128
17128
  let len = 0;
@@ -17374,8 +17374,8 @@ var require_schemes = __commonJS({
17374
17374
  wsComponent.secure = void 0;
17375
17375
  }
17376
17376
  if (wsComponent.resourceName) {
17377
- const [path13, query2] = wsComponent.resourceName.split("?");
17378
- wsComponent.path = path13 && path13 !== "/" ? path13 : void 0;
17377
+ const [path17, query2] = wsComponent.resourceName.split("?");
17378
+ wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
17379
17379
  wsComponent.query = query2;
17380
17380
  wsComponent.resourceName = void 0;
17381
17381
  }
@@ -22031,10 +22031,10 @@ var require_parse = __commonJS({
22031
22031
  skipWhitespace(cxt);
22032
22032
  gen.if((0, codegen_1._)`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
22033
22033
  }
22034
- function parseBooleanToken(bool, fail) {
22034
+ function parseBooleanToken(bool2, fail) {
22035
22035
  return (cxt) => {
22036
22036
  const { gen, data } = cxt;
22037
- tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
22037
+ tryParseToken(cxt, `${bool2}`, () => fail(cxt), () => gen.assign(data, bool2));
22038
22038
  };
22039
22039
  }
22040
22040
  function parseRef(cxt) {
@@ -22312,8 +22312,8 @@ var require_utils2 = __commonJS({
22312
22312
  }
22313
22313
  return ind;
22314
22314
  }
22315
- function removeDotSegments(path13) {
22316
- let input = path13;
22315
+ function removeDotSegments(path17) {
22316
+ let input = path17;
22317
22317
  const output = [];
22318
22318
  let nextSlash = -1;
22319
22319
  let len = 0;
@@ -22658,8 +22658,8 @@ var require_schemes2 = __commonJS({
22658
22658
  wsComponent.secure = void 0;
22659
22659
  }
22660
22660
  if (wsComponent.resourceName) {
22661
- const [path13, query2] = wsComponent.resourceName.split("?");
22662
- wsComponent.path = path13 && path13 !== "/" ? path13 : void 0;
22661
+ const [path17, query2] = wsComponent.resourceName.split("?");
22662
+ wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
22663
22663
  wsComponent.query = query2;
22664
22664
  wsComponent.resourceName = void 0;
22665
22665
  }
@@ -23435,12 +23435,12 @@ var require_dist = __commonJS({
23435
23435
  throw new Error(`Unknown format "${name}"`);
23436
23436
  return f;
23437
23437
  };
23438
- function addFormats(ajv, list, fs8, exportName) {
23438
+ function addFormats(ajv, list, fs11, exportName) {
23439
23439
  var _a3;
23440
23440
  var _b;
23441
23441
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
23442
23442
  for (const f of list)
23443
- ajv.addFormat(f, fs8[f]);
23443
+ ajv.addFormat(f, fs11[f]);
23444
23444
  }
23445
23445
  module.exports = exports = formatsPlugin;
23446
23446
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -24143,8 +24143,8 @@ var require_utils3 = __commonJS({
24143
24143
  }
24144
24144
  return ind;
24145
24145
  }
24146
- function removeDotSegments(path13) {
24147
- let input = path13;
24146
+ function removeDotSegments(path17) {
24147
+ let input = path17;
24148
24148
  const output = [];
24149
24149
  let nextSlash = -1;
24150
24150
  let len = 0;
@@ -24489,8 +24489,8 @@ var require_schemes3 = __commonJS({
24489
24489
  wsComponent.secure = void 0;
24490
24490
  }
24491
24491
  if (wsComponent.resourceName) {
24492
- const [path13, query2] = wsComponent.resourceName.split("?");
24493
- wsComponent.path = path13 && path13 !== "/" ? path13 : void 0;
24492
+ const [path17, query2] = wsComponent.resourceName.split("?");
24493
+ wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
24494
24494
  wsComponent.query = query2;
24495
24495
  wsComponent.resourceName = void 0;
24496
24496
  }
@@ -28889,9 +28889,9 @@ var require_range = __commonJS({
28889
28889
  range = range.replace(BUILDSTRIPRE, "");
28890
28890
  const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
28891
28891
  const memoKey = memoOpts + ":" + range;
28892
- const cached2 = cache4.get(memoKey);
28893
- if (cached2) {
28894
- return cached2;
28892
+ const cached3 = cache4.get(memoKey);
28893
+ if (cached3) {
28894
+ return cached3;
28895
28895
  }
28896
28896
  const loose = this.options.loose;
28897
28897
  const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
@@ -32007,13 +32007,13 @@ var require_node = __commonJS({
32007
32007
  this.staticChildrenNodes[index] = node;
32008
32008
  }
32009
32009
  }
32010
- findStaticMatchingChild(path13, pathIndex) {
32011
- const charCode = path13.charCodeAt(pathIndex);
32010
+ findStaticMatchingChild(path17, pathIndex) {
32011
+ const charCode = path17.charCodeAt(pathIndex);
32012
32012
  const charCodes = this.staticChildrenCharCodes;
32013
32013
  for (let i = 0; i < charCodes.length; i++) {
32014
32014
  if (charCodes[i] === charCode) {
32015
32015
  const staticChild = this.staticChildrenNodes[i];
32016
- if (staticChild.matchPrefix(path13, pathIndex)) {
32016
+ if (staticChild.matchPrefix(path17, pathIndex)) {
32017
32017
  return staticChild;
32018
32018
  }
32019
32019
  return null;
@@ -32021,34 +32021,34 @@ var require_node = __commonJS({
32021
32021
  }
32022
32022
  return null;
32023
32023
  }
32024
- getStaticChild(path13, pathIndex = 0) {
32025
- if (path13.length === pathIndex) {
32024
+ getStaticChild(path17, pathIndex = 0) {
32025
+ if (path17.length === pathIndex) {
32026
32026
  return this;
32027
32027
  }
32028
- const staticChild = this.findStaticMatchingChild(path13, pathIndex);
32028
+ const staticChild = this.findStaticMatchingChild(path17, pathIndex);
32029
32029
  if (staticChild) {
32030
- return staticChild.getStaticChild(path13, pathIndex + staticChild.prefix.length);
32030
+ return staticChild.getStaticChild(path17, pathIndex + staticChild.prefix.length);
32031
32031
  }
32032
32032
  return null;
32033
32033
  }
32034
- createStaticChild(path13) {
32035
- if (path13.length === 0) {
32034
+ createStaticChild(path17) {
32035
+ if (path17.length === 0) {
32036
32036
  return this;
32037
32037
  }
32038
- const childIndex = this.staticChildrenCharCodes.indexOf(path13.charCodeAt(0));
32038
+ const childIndex = this.staticChildrenCharCodes.indexOf(path17.charCodeAt(0));
32039
32039
  let staticChild = childIndex === -1 ? void 0 : this.staticChildrenNodes[childIndex];
32040
32040
  if (staticChild) {
32041
32041
  let i = 1;
32042
32042
  for (; i < staticChild.prefix.length; i++) {
32043
- if (path13.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
32043
+ if (path17.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
32044
32044
  staticChild = staticChild.split(this, i);
32045
32045
  break;
32046
32046
  }
32047
32047
  }
32048
- return staticChild.createStaticChild(path13.slice(i));
32048
+ return staticChild.createStaticChild(path17.slice(i));
32049
32049
  }
32050
- const node = new StaticNode(path13);
32051
- this.setStaticChild(path13.charAt(0), node);
32050
+ const node = new StaticNode(path17);
32051
+ this.setStaticChild(path17.charAt(0), node);
32052
32052
  return node;
32053
32053
  }
32054
32054
  };
@@ -32108,8 +32108,8 @@ var require_node = __commonJS({
32108
32108
  parentNode.setStaticChild(parentPrefix.charAt(0), staticNode);
32109
32109
  return staticNode;
32110
32110
  }
32111
- getNextNode(path13, pathIndex, nodeStack, paramsCount) {
32112
- let node = this.findStaticMatchingChild(path13, pathIndex);
32111
+ getNextNode(path17, pathIndex, nodeStack, paramsCount) {
32112
+ let node = this.findStaticMatchingChild(path17, pathIndex);
32113
32113
  let parametricBrotherNodeIndex = 0;
32114
32114
  if (node === null) {
32115
32115
  if (this.parametricChildren.length === 0) {
@@ -32156,8 +32156,8 @@ var require_node = __commonJS({
32156
32156
  this.kind = NODE_TYPES.PARAMETRIC;
32157
32157
  this.nodePaths = /* @__PURE__ */ new Set([nodePath2]);
32158
32158
  }
32159
- getNextNode(path13, pathIndex) {
32160
- return this.findStaticMatchingChild(path13, pathIndex);
32159
+ getNextNode(path17, pathIndex) {
32160
+ return this.findStaticMatchingChild(path17, pathIndex);
32161
32161
  }
32162
32162
  };
32163
32163
  var WildcardNode = class extends Node {
@@ -32513,81 +32513,81 @@ var require_url_sanitizer = __commonJS({
32513
32513
  return String.fromCharCode(charCode);
32514
32514
  }
32515
32515
  var MIN_NATIVE_SCAN_LENGTH = 12;
32516
- function safeDecodeURI(path13, useSemicolonDelimiter) {
32517
- if (path13.length >= MIN_NATIVE_SCAN_LENGTH) {
32518
- return safeDecodeURINativeScan(path13, useSemicolonDelimiter);
32516
+ function safeDecodeURI(path17, useSemicolonDelimiter) {
32517
+ if (path17.length >= MIN_NATIVE_SCAN_LENGTH) {
32518
+ return safeDecodeURINativeScan(path17, useSemicolonDelimiter);
32519
32519
  }
32520
- return safeDecodeURICharScan(path13, useSemicolonDelimiter, 1);
32520
+ return safeDecodeURICharScan(path17, useSemicolonDelimiter, 1);
32521
32521
  }
32522
- function safeDecodeURINativeScan(path13, useSemicolonDelimiter) {
32523
- const percentIndex = path13.indexOf("%", 1);
32524
- let delimIndex = path13.indexOf("?", 1);
32525
- const hashIndex = path13.indexOf("#", 1);
32522
+ function safeDecodeURINativeScan(path17, useSemicolonDelimiter) {
32523
+ const percentIndex = path17.indexOf("%", 1);
32524
+ let delimIndex = path17.indexOf("?", 1);
32525
+ const hashIndex = path17.indexOf("#", 1);
32526
32526
  if (hashIndex !== -1 && (delimIndex === -1 || hashIndex < delimIndex)) {
32527
32527
  delimIndex = hashIndex;
32528
32528
  }
32529
32529
  if (useSemicolonDelimiter) {
32530
- const semicolonIndex = path13.indexOf(";", 1);
32530
+ const semicolonIndex = path17.indexOf(";", 1);
32531
32531
  if (semicolonIndex !== -1 && (delimIndex === -1 || semicolonIndex < delimIndex)) {
32532
32532
  delimIndex = semicolonIndex;
32533
32533
  }
32534
32534
  }
32535
32535
  if (percentIndex === -1 || delimIndex !== -1 && percentIndex > delimIndex) {
32536
32536
  if (delimIndex === -1) {
32537
- return { path: path13, querystring: "", shouldDecodeParam: false };
32537
+ return { path: path17, querystring: "", shouldDecodeParam: false };
32538
32538
  }
32539
32539
  return {
32540
- path: path13.slice(0, delimIndex),
32541
- querystring: path13.slice(delimIndex + 1),
32540
+ path: path17.slice(0, delimIndex),
32541
+ querystring: path17.slice(delimIndex + 1),
32542
32542
  shouldDecodeParam: false
32543
32543
  };
32544
32544
  }
32545
- return safeDecodeURIPercentScan(path13, useSemicolonDelimiter, percentIndex);
32545
+ return safeDecodeURIPercentScan(path17, useSemicolonDelimiter, percentIndex);
32546
32546
  }
32547
- function safeDecodeURICharScan(path13, useSemicolonDelimiter, startIndex) {
32548
- for (let i = startIndex; i < path13.length; i++) {
32549
- const charCode = path13.charCodeAt(i);
32547
+ function safeDecodeURICharScan(path17, useSemicolonDelimiter, startIndex) {
32548
+ for (let i = startIndex; i < path17.length; i++) {
32549
+ const charCode = path17.charCodeAt(i);
32550
32550
  if (charCode === 37) {
32551
- return safeDecodeURIPercentScan(path13, useSemicolonDelimiter, i);
32551
+ return safeDecodeURIPercentScan(path17, useSemicolonDelimiter, i);
32552
32552
  } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
32553
32553
  return {
32554
- path: path13.slice(0, i),
32555
- querystring: path13.slice(i + 1),
32554
+ path: path17.slice(0, i),
32555
+ querystring: path17.slice(i + 1),
32556
32556
  shouldDecodeParam: false
32557
32557
  };
32558
32558
  }
32559
32559
  }
32560
- return { path: path13, querystring: "", shouldDecodeParam: false };
32560
+ return { path: path17, querystring: "", shouldDecodeParam: false };
32561
32561
  }
32562
- function reencodePercentChar(path13, index) {
32563
- return path13.slice(0, index + 1) + "25" + path13.slice(index + 1);
32562
+ function reencodePercentChar(path17, index) {
32563
+ return path17.slice(0, index + 1) + "25" + path17.slice(index + 1);
32564
32564
  }
32565
- function safeDecodeURIPercentScan(path13, useSemicolonDelimiter, startIndex) {
32565
+ function safeDecodeURIPercentScan(path17, useSemicolonDelimiter, startIndex) {
32566
32566
  let shouldDecode = false;
32567
32567
  let shouldDecodeParam = false;
32568
32568
  let querystring = "";
32569
- for (let i = startIndex; i < path13.length; i++) {
32570
- const charCode = path13.charCodeAt(i);
32569
+ for (let i = startIndex; i < path17.length; i++) {
32570
+ const charCode = path17.charCodeAt(i);
32571
32571
  if (charCode === 37) {
32572
- const componentCharCode = decodeComponentCharCode(path13.charCodeAt(i + 1), path13.charCodeAt(i + 2));
32572
+ const componentCharCode = decodeComponentCharCode(path17.charCodeAt(i + 1), path17.charCodeAt(i + 2));
32573
32573
  if (componentCharCode === 0) {
32574
32574
  shouldDecode = true;
32575
32575
  } else {
32576
32576
  shouldDecodeParam = true;
32577
32577
  if (componentCharCode === 37) {
32578
32578
  shouldDecode = true;
32579
- path13 = reencodePercentChar(path13, i);
32579
+ path17 = reencodePercentChar(path17, i);
32580
32580
  i += 2;
32581
32581
  }
32582
32582
  i += 2;
32583
32583
  }
32584
32584
  } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
32585
- querystring = path13.slice(i + 1);
32586
- path13 = path13.slice(0, i);
32585
+ querystring = path17.slice(i + 1);
32586
+ path17 = path17.slice(0, i);
32587
32587
  break;
32588
32588
  }
32589
32589
  }
32590
- const decodedPath = shouldDecode ? decodeURI(path13) : path13;
32590
+ const decodedPath = shouldDecode ? decodeURI(path17) : path17;
32591
32591
  return { path: decodedPath, querystring, shouldDecodeParam };
32592
32592
  }
32593
32593
  function safeDecodeURIComponent(uriComponent) {
@@ -32682,7 +32682,7 @@ var require_find_my_way = __commonJS({
32682
32682
  this.trees = /* @__PURE__ */ Object.create(null);
32683
32683
  this._treeGET = null;
32684
32684
  }
32685
- Router.prototype.on = function on(method, path13, opts, handler, store) {
32685
+ Router.prototype.on = function on(method, path17, opts, handler, store) {
32686
32686
  if (typeof opts === "function") {
32687
32687
  if (handler !== void 0) {
32688
32688
  store = handler;
@@ -32690,34 +32690,34 @@ var require_find_my_way = __commonJS({
32690
32690
  handler = opts;
32691
32691
  opts = {};
32692
32692
  }
32693
- assert2(typeof path13 === "string", "Path should be a string");
32694
- assert2(path13.length > 0, "The path could not be empty");
32695
- assert2(path13[0] === "/" || path13[0] === "*", "The first character of a path should be `/` or `*`");
32693
+ assert2(typeof path17 === "string", "Path should be a string");
32694
+ assert2(path17.length > 0, "The path could not be empty");
32695
+ assert2(path17[0] === "/" || path17[0] === "*", "The first character of a path should be `/` or `*`");
32696
32696
  assert2(typeof handler === "function", "Handler should be a function");
32697
- const optionalParamMatch = path13.match(OPTIONAL_PARAM_REGEXP);
32697
+ const optionalParamMatch = path17.match(OPTIONAL_PARAM_REGEXP);
32698
32698
  if (optionalParamMatch) {
32699
- assert2(path13.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32700
- const pathFull = path13.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32701
- const pathOptional = path13.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32699
+ assert2(path17.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32700
+ const pathFull = path17.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32701
+ const pathOptional = path17.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32702
32702
  this.on(method, pathFull, opts, handler, store);
32703
32703
  this.on(method, pathOptional, opts, handler, store);
32704
32704
  return;
32705
32705
  }
32706
- const route = path13;
32706
+ const route = path17;
32707
32707
  if (this.ignoreDuplicateSlashes) {
32708
- path13 = removeDuplicateSlashes(path13);
32708
+ path17 = removeDuplicateSlashes(path17);
32709
32709
  }
32710
32710
  if (this.ignoreTrailingSlash) {
32711
- path13 = trimLastSlash(path13);
32711
+ path17 = trimLastSlash(path17);
32712
32712
  }
32713
32713
  const methods = Array.isArray(method) ? method : [method];
32714
32714
  for (const method2 of methods) {
32715
32715
  assert2(typeof method2 === "string", "Method should be a string");
32716
32716
  assert2(httpMethods.includes(method2), `Method '${method2}' is not an http method.`);
32717
- this._on(method2, path13, opts, handler, store, route);
32717
+ this._on(method2, path17, opts, handler, store, route);
32718
32718
  }
32719
32719
  };
32720
- Router.prototype._on = function _on(method, path13, opts, handler, store) {
32720
+ Router.prototype._on = function _on(method, path17, opts, handler, store) {
32721
32721
  let constraints = {};
32722
32722
  if (opts.constraints !== void 0) {
32723
32723
  assert2(typeof opts.constraints === "object" && opts.constraints !== null, "Constraints should be an object");
@@ -32730,7 +32730,7 @@ var require_find_my_way = __commonJS({
32730
32730
  if (this.trees[method] === void 0) {
32731
32731
  this.trees[method] = new StaticNode("/");
32732
32732
  }
32733
- let pattern = path13;
32733
+ let pattern = path17;
32734
32734
  if (pattern === "*" && this.trees[method].prefix.length !== 0) {
32735
32735
  const currentRoot = this.trees[method];
32736
32736
  this.trees[method] = new StaticNode("");
@@ -32838,19 +32838,19 @@ var require_find_my_way = __commonJS({
32838
32838
  throw new Error(`Method '${method}' already declared for route '${pattern}' with constraints '${JSON.stringify(constraints)}'`);
32839
32839
  }
32840
32840
  }
32841
- const route = { method, path: path13, pattern, params, opts, handler, store };
32841
+ const route = { method, path: path17, pattern, params, opts, handler, store };
32842
32842
  this.routes.push(route);
32843
32843
  currentNode.addRoute(route, this.constrainer);
32844
32844
  };
32845
- Router.prototype.hasRoute = function hasRoute(method, path13, constraints) {
32846
- const route = this.findRoute(method, path13, constraints);
32845
+ Router.prototype.hasRoute = function hasRoute(method, path17, constraints) {
32846
+ const route = this.findRoute(method, path17, constraints);
32847
32847
  return route !== null;
32848
32848
  };
32849
- Router.prototype.findRoute = function findNode(method, path13, constraints = {}) {
32849
+ Router.prototype.findRoute = function findNode(method, path17, constraints = {}) {
32850
32850
  if (this.trees[method] === void 0) {
32851
32851
  return null;
32852
32852
  }
32853
- let pattern = path13;
32853
+ let pattern = path17;
32854
32854
  let currentNode = this.trees[method];
32855
32855
  let parentNodePathIndex = currentNode.prefix.length;
32856
32856
  const params = [];
@@ -32971,39 +32971,39 @@ var require_find_my_way = __commonJS({
32971
32971
  this._treeGET = null;
32972
32972
  this.routes = [];
32973
32973
  };
32974
- Router.prototype.off = function off(method, path13, constraints) {
32975
- assert2(typeof path13 === "string", "Path should be a string");
32976
- assert2(path13.length > 0, "The path could not be empty");
32977
- assert2(path13[0] === "/" || path13[0] === "*", "The first character of a path should be `/` or `*`");
32974
+ Router.prototype.off = function off(method, path17, constraints) {
32975
+ assert2(typeof path17 === "string", "Path should be a string");
32976
+ assert2(path17.length > 0, "The path could not be empty");
32977
+ assert2(path17[0] === "/" || path17[0] === "*", "The first character of a path should be `/` or `*`");
32978
32978
  assert2(
32979
32979
  typeof constraints === "undefined" || typeof constraints === "object" && !Array.isArray(constraints) && constraints !== null,
32980
32980
  "Constraints should be an object or undefined."
32981
32981
  );
32982
- const optionalParamMatch = path13.match(OPTIONAL_PARAM_REGEXP);
32982
+ const optionalParamMatch = path17.match(OPTIONAL_PARAM_REGEXP);
32983
32983
  if (optionalParamMatch) {
32984
- assert2(path13.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32985
- const pathFull = path13.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32986
- const pathOptional = path13.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32984
+ assert2(path17.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32985
+ const pathFull = path17.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32986
+ const pathOptional = path17.replace(OPTIONAL_PARAM_REGEXP, "$2") || "/";
32987
32987
  this.off(method, pathFull, constraints);
32988
32988
  this.off(method, pathOptional, constraints);
32989
32989
  return;
32990
32990
  }
32991
32991
  if (this.ignoreDuplicateSlashes) {
32992
- path13 = removeDuplicateSlashes(path13);
32992
+ path17 = removeDuplicateSlashes(path17);
32993
32993
  }
32994
32994
  if (this.ignoreTrailingSlash) {
32995
- path13 = trimLastSlash(path13);
32995
+ path17 = trimLastSlash(path17);
32996
32996
  }
32997
32997
  const methods = Array.isArray(method) ? method : [method];
32998
32998
  for (const method2 of methods) {
32999
- this._off(method2, path13, constraints);
32999
+ this._off(method2, path17, constraints);
33000
33000
  }
33001
33001
  };
33002
- Router.prototype._off = function _off(method, path13, constraints) {
33002
+ Router.prototype._off = function _off(method, path17, constraints) {
33003
33003
  assert2(typeof method === "string", "Method should be a string");
33004
33004
  assert2(httpMethods.includes(method), `Method '${method}' is not an http method.`);
33005
33005
  function matcherWithoutConstraints(route) {
33006
- return method !== route.method || path13 !== route.path;
33006
+ return method !== route.method || path17 !== route.path;
33007
33007
  }
33008
33008
  function matcherWithConstraints(route) {
33009
33009
  return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {});
@@ -33040,37 +33040,37 @@ var require_find_my_way = __commonJS({
33040
33040
  if (handle === null) return this._defaultRoute(req, res, ctx);
33041
33041
  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);
33042
33042
  };
33043
- Router.prototype.find = function find(method, path13, derivedConstraints) {
33043
+ Router.prototype.find = function find(method, path17, derivedConstraints) {
33044
33044
  let currentNode = method === "GET" ? this._treeGET : this.trees[method];
33045
33045
  if (currentNode == null) return null;
33046
- if (path13.charCodeAt(0) !== 47) {
33047
- path13 = path13.replace(FULL_PATH_REGEXP, "/");
33046
+ if (path17.charCodeAt(0) !== 47) {
33047
+ path17 = path17.replace(FULL_PATH_REGEXP, "/");
33048
33048
  }
33049
33049
  if (this.ignoreDuplicateSlashes) {
33050
- path13 = removeDuplicateSlashes(path13);
33050
+ path17 = removeDuplicateSlashes(path17);
33051
33051
  }
33052
33052
  let sanitizedUrl;
33053
33053
  let querystring2;
33054
33054
  let shouldDecodeParam;
33055
33055
  try {
33056
- sanitizedUrl = path13.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path13, this.useSemicolonDelimiter) : safeDecodeURICharScan(path13, this.useSemicolonDelimiter, 1);
33057
- path13 = sanitizedUrl.path;
33056
+ sanitizedUrl = path17.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path17, this.useSemicolonDelimiter) : safeDecodeURICharScan(path17, this.useSemicolonDelimiter, 1);
33057
+ path17 = sanitizedUrl.path;
33058
33058
  querystring2 = sanitizedUrl.querystring;
33059
33059
  shouldDecodeParam = sanitizedUrl.shouldDecodeParam;
33060
33060
  } catch (error51) {
33061
- return this._onBadUrl(path13);
33061
+ return this._onBadUrl(path17);
33062
33062
  }
33063
33063
  if (this.ignoreTrailingSlash) {
33064
- path13 = trimLastSlash(path13);
33064
+ path17 = trimLastSlash(path17);
33065
33065
  }
33066
- const originPath = path13;
33066
+ const originPath = path17;
33067
33067
  if (this.caseSensitive === false) {
33068
- path13 = path13.toLowerCase();
33068
+ path17 = path17.toLowerCase();
33069
33069
  }
33070
33070
  const maxParamLength = this.maxParamLength;
33071
33071
  let pathIndex = currentNode.prefix.length;
33072
33072
  const params = [];
33073
- const pathLen = path13.length;
33073
+ const pathLen = path17.length;
33074
33074
  const brothersNodesStack = [];
33075
33075
  let maxParamLengthExceeded = false;
33076
33076
  while (true) {
@@ -33085,7 +33085,7 @@ var require_find_my_way = __commonJS({
33085
33085
  };
33086
33086
  }
33087
33087
  }
33088
- let node = currentNode.getNextNode(path13, pathIndex, brothersNodesStack, params.length);
33088
+ let node = currentNode.getNextNode(path17, pathIndex, brothersNodesStack, params.length);
33089
33089
  if (node === null) {
33090
33090
  if (brothersNodesStack.length === 0) {
33091
33091
  if (maxParamLengthExceeded && this.onMaxParamLength) {
@@ -33186,8 +33186,8 @@ var require_find_my_way = __commonJS({
33186
33186
  Router.prototype._rebuild = function(routes) {
33187
33187
  this.reset();
33188
33188
  for (const route of routes) {
33189
- const { method, path: path13, opts, handler, store } = route;
33190
- this._on(method, path13, opts, handler, store);
33189
+ const { method, path: path17, opts, handler, store } = route;
33190
+ this._on(method, path17, opts, handler, store);
33191
33191
  }
33192
33192
  };
33193
33193
  Router.prototype._defaultRoute = function(req, res, ctx) {
@@ -33198,24 +33198,24 @@ var require_find_my_way = __commonJS({
33198
33198
  res.end();
33199
33199
  }
33200
33200
  };
33201
- Router.prototype._onBadUrl = function(path13) {
33201
+ Router.prototype._onBadUrl = function(path17) {
33202
33202
  if (this.onBadUrl === null) {
33203
33203
  return null;
33204
33204
  }
33205
33205
  const onBadUrl = this.onBadUrl;
33206
33206
  return {
33207
- handler: (req, res, ctx) => onBadUrl(path13, req, res),
33207
+ handler: (req, res, ctx) => onBadUrl(path17, req, res),
33208
33208
  params: {},
33209
33209
  store: null
33210
33210
  };
33211
33211
  };
33212
- Router.prototype._onMaxParamLength = function(path13) {
33212
+ Router.prototype._onMaxParamLength = function(path17) {
33213
33213
  if (this.onMaxParamLength === null) {
33214
33214
  return null;
33215
33215
  }
33216
33216
  const onMaxParamLength = this.onMaxParamLength;
33217
33217
  return {
33218
- handler: (req, res, ctx) => onMaxParamLength(path13, req, res),
33218
+ handler: (req, res, ctx) => onMaxParamLength(path17, req, res),
33219
33219
  params: {},
33220
33220
  store: null
33221
33221
  };
@@ -33247,12 +33247,12 @@ var require_find_my_way = __commonJS({
33247
33247
  if (!httpMethods.hasOwnProperty(i)) continue;
33248
33248
  const m = httpMethods[i];
33249
33249
  const methodName = m.toLowerCase();
33250
- Router.prototype[methodName] = function(path13, handler, store) {
33251
- return this.on(m, path13, handler, store);
33250
+ Router.prototype[methodName] = function(path17, handler, store) {
33251
+ return this.on(m, path17, handler, store);
33252
33252
  };
33253
33253
  }
33254
- Router.prototype.all = function(path13, handler, store) {
33255
- this.on(httpMethods, path13, handler, store);
33254
+ Router.prototype.all = function(path17, handler, store) {
33255
+ this.on(httpMethods, path17, handler, store);
33256
33256
  };
33257
33257
  Router.sanitizeUrlPath = function sanitizeUrlPath(url2, useSemicolonDelimiter) {
33258
33258
  const decoded = safeDecodeURI(url2, useSemicolonDelimiter);
@@ -33267,14 +33267,14 @@ var require_find_my_way = __commonJS({
33267
33267
  function escapeRegExp(string4) {
33268
33268
  return string4.replace(ESCAPE_REGEXP, "\\$&");
33269
33269
  }
33270
- function removeDuplicateSlashes(path13) {
33271
- return path13.indexOf("//") !== -1 ? path13.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path13;
33270
+ function removeDuplicateSlashes(path17) {
33271
+ return path17.indexOf("//") !== -1 ? path17.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path17;
33272
33272
  }
33273
- function trimLastSlash(path13) {
33274
- if (path13.length > 1 && path13.charCodeAt(path13.length - 1) === 47) {
33275
- return path13.slice(0, -1);
33273
+ function trimLastSlash(path17) {
33274
+ if (path17.length > 1 && path17.charCodeAt(path17.length - 1) === 47) {
33275
+ return path17.slice(0, -1);
33276
33276
  }
33277
- return path13;
33277
+ return path17;
33278
33278
  }
33279
33279
  function trimRegExpStartAndEnd(regexString) {
33280
33280
  if (regexString.charCodeAt(1) === 94) {
@@ -33285,22 +33285,22 @@ var require_find_my_way = __commonJS({
33285
33285
  }
33286
33286
  return regexString;
33287
33287
  }
33288
- function getClosingParenthensePosition(path13, idx) {
33288
+ function getClosingParenthensePosition(path17, idx) {
33289
33289
  let parentheses = 1;
33290
- while (idx < path13.length) {
33290
+ while (idx < path17.length) {
33291
33291
  idx++;
33292
- if (path13.charCodeAt(idx) === 92) {
33292
+ if (path17.charCodeAt(idx) === 92) {
33293
33293
  idx++;
33294
33294
  continue;
33295
33295
  }
33296
- if (path13.charCodeAt(idx) === 41) {
33296
+ if (path17.charCodeAt(idx) === 41) {
33297
33297
  parentheses--;
33298
- } else if (path13.charCodeAt(idx) === 40) {
33298
+ } else if (path17.charCodeAt(idx) === 40) {
33299
33299
  parentheses++;
33300
33300
  }
33301
33301
  if (!parentheses) return idx;
33302
33302
  }
33303
- throw new TypeError('Invalid regexp expression in "' + path13 + '"');
33303
+ throw new TypeError('Invalid regexp expression in "' + path17 + '"');
33304
33304
  }
33305
33305
  function defaultBuildPrettyMeta(route) {
33306
33306
  if (!route) return {};
@@ -33533,12 +33533,12 @@ var require_route = __commonJS({
33533
33533
  function route({ options: options2, isFastify }) {
33534
33534
  throwIfAlreadyStarted("Cannot add route!");
33535
33535
  const opts = { ...options2 };
33536
- const path13 = opts.url || opts.path || "";
33536
+ const path17 = opts.url || opts.path || "";
33537
33537
  if (!opts.handler) {
33538
- throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path13);
33538
+ throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path17);
33539
33539
  }
33540
33540
  if (opts.errorHandler !== void 0 && typeof opts.errorHandler !== "function") {
33541
- throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path13);
33541
+ throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path17);
33542
33542
  }
33543
33543
  validateBodyLimitOption(opts.bodyLimit);
33544
33544
  validateHandlerTimeoutOption(opts.handlerTimeout);
@@ -33548,22 +33548,22 @@ var require_route = __commonJS({
33548
33548
  if (Array.isArray(opts.method)) {
33549
33549
  for (let i = 0; i < opts.method.length; ++i) {
33550
33550
  opts.method[i] = normalizeAndValidateMethod.call(this, opts.method[i]);
33551
- validateSchemaBodyOption.call(this, opts.method[i], path13, opts.schema);
33551
+ validateSchemaBodyOption.call(this, opts.method[i], path17, opts.schema);
33552
33552
  isGetRoute = opts.method.includes("GET");
33553
33553
  isHeadRoute = opts.method.includes("HEAD");
33554
33554
  }
33555
33555
  } else {
33556
33556
  opts.method = normalizeAndValidateMethod.call(this, opts.method);
33557
- validateSchemaBodyOption.call(this, opts.method, path13, opts.schema);
33557
+ validateSchemaBodyOption.call(this, opts.method, path17, opts.schema);
33558
33558
  isGetRoute = opts.method === "GET";
33559
33559
  isHeadRoute = opts.method === "HEAD";
33560
33560
  }
33561
33561
  const headOpts = shouldExposeHead && isGetRoute ? { ...options2 } : null;
33562
33562
  const prefix = this[kRoutePrefix];
33563
- if (path13 === "/" && prefix.length > 0 && opts.method !== "HEAD") {
33563
+ if (path17 === "/" && prefix.length > 0 && opts.method !== "HEAD") {
33564
33564
  switch (opts.prefixTrailingSlash) {
33565
33565
  case "slash":
33566
- addNewRoute.call(this, { path: path13, isFastify });
33566
+ addNewRoute.call(this, { path: path17, isFastify });
33567
33567
  break;
33568
33568
  case "no-slash":
33569
33569
  addNewRoute.call(this, { path: "", isFastify });
@@ -33572,20 +33572,20 @@ var require_route = __commonJS({
33572
33572
  default:
33573
33573
  addNewRoute.call(this, { path: "", isFastify });
33574
33574
  if (ignoreTrailingSlash !== true && (ignoreDuplicateSlashes !== true || !prefix.endsWith("/"))) {
33575
- addNewRoute.call(this, { path: path13, prefixing: true, isFastify });
33575
+ addNewRoute.call(this, { path: path17, prefixing: true, isFastify });
33576
33576
  }
33577
33577
  }
33578
- } else if (path13[0] === "/" && prefix.endsWith("/")) {
33579
- addNewRoute.call(this, { path: path13.slice(1), isFastify });
33578
+ } else if (path17[0] === "/" && prefix.endsWith("/")) {
33579
+ addNewRoute.call(this, { path: path17.slice(1), isFastify });
33580
33580
  } else {
33581
- addNewRoute.call(this, { path: path13, isFastify });
33581
+ addNewRoute.call(this, { path: path17, isFastify });
33582
33582
  }
33583
33583
  return this;
33584
- function addNewRoute({ path: path14, prefixing = false, isFastify: isFastify2 = false }) {
33585
- const url2 = prefix + path14;
33584
+ function addNewRoute({ path: path18, prefixing = false, isFastify: isFastify2 = false }) {
33585
+ const url2 = prefix + path18;
33586
33586
  opts.url = url2;
33587
33587
  opts.path = url2;
33588
- opts.routePath = path14;
33588
+ opts.routePath = path18;
33589
33589
  opts.prefix = prefix;
33590
33590
  opts.logLevel = opts.logLevel || this[kLogLevel];
33591
33591
  validateLogLevelOption(opts.logLevel, opts.method, opts.url, logger);
@@ -33717,7 +33717,7 @@ var require_route = __commonJS({
33717
33717
  });
33718
33718
  if (shouldExposeHead && isGetRoute && !isHeadRoute && !hasHEADHandler) {
33719
33719
  const onSendHandlers = parseHeadOnSendHandlers(headOpts.onSend);
33720
- prepareRoute.call(this, { method: "HEAD", url: path14, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true });
33720
+ prepareRoute.call(this, { method: "HEAD", url: path18, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true });
33721
33721
  }
33722
33722
  }
33723
33723
  }
@@ -33841,9 +33841,9 @@ var require_route = __commonJS({
33841
33841
  }
33842
33842
  return method;
33843
33843
  }
33844
- function validateSchemaBodyOption(method, path13, schema) {
33844
+ function validateSchemaBodyOption(method, path17, schema) {
33845
33845
  if (this[kSupportedHTTPMethods].bodyless.has(method) && schema?.body) {
33846
- throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path13);
33846
+ throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path17);
33847
33847
  }
33848
33848
  }
33849
33849
  function validateBodyLimitOption(bodyLimit) {
@@ -33858,11 +33858,11 @@ var require_route = __commonJS({
33858
33858
  throw new FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT(handlerTimeout);
33859
33859
  }
33860
33860
  }
33861
- function validateLogLevelOption(logLevel, method, path13, logger) {
33861
+ function validateLogLevelOption(logLevel, method, path17, logger) {
33862
33862
  if (logLevel == null || logLevel === "") return;
33863
33863
  if (logger?.levels?.values == null) return;
33864
33864
  if (typeof logLevel !== "string" || logger.levels.values[logLevel] === void 0) {
33865
- throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path13, logLevel);
33865
+ throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path17, logLevel);
33866
33866
  }
33867
33867
  }
33868
33868
  function runPreParsing(err, request, reply) {
@@ -33951,7 +33951,7 @@ var require_four_oh_four = __commonJS({
33951
33951
  });
33952
33952
  }
33953
33953
  function createRouteEventHandler() {
33954
- return function onRouteEvent(path13, req, res) {
33954
+ return function onRouteEvent(path17, req, res) {
33955
33955
  const fourOhFourContext = this[kFourOhFourLevelInstance][kFourOhFourContext];
33956
33956
  const id = getGenReqId(fourOhFourContext.server, req);
33957
33957
  const childLogger = createChildLogger(fourOhFourContext, logger, req, id);
@@ -34470,7 +34470,7 @@ var require_parse_url = __commonJS({
34470
34470
  var require_form_data = __commonJS({
34471
34471
  "node_modules/light-my-request/lib/form-data.js"(exports, module) {
34472
34472
  "use strict";
34473
- var { randomUUID: randomUUID2 } = __require("node:crypto");
34473
+ var { randomUUID: randomUUID3 } = __require("node:crypto");
34474
34474
  var { Readable } = __require("node:stream");
34475
34475
  var textEncoder;
34476
34476
  function isFormDataLike(payload) {
@@ -34478,7 +34478,7 @@ var require_form_data = __commonJS({
34478
34478
  }
34479
34479
  function formDataToStream(formdata) {
34480
34480
  textEncoder = textEncoder ?? new TextEncoder();
34481
- const boundary = `----formdata-${randomUUID2()}`;
34481
+ const boundary = `----formdata-${randomUUID3()}`;
34482
34482
  const prefix = `--${boundary}\r
34483
34483
  Content-Disposition: form-data`;
34484
34484
  const escape2 = (str2) => str2.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
@@ -34532,7 +34532,7 @@ var require_request2 = __commonJS({
34532
34532
  var { createDeprecation } = require_process_warning2();
34533
34533
  var parseURL = require_parse_url();
34534
34534
  var { isFormDataLike, formDataToStream } = require_form_data();
34535
- var { EventEmitter: EventEmitter2 } = __require("node:events");
34535
+ var { EventEmitter: EventEmitter5 } = __require("node:events");
34536
34536
  var FST_LIGHTMYREQUEST_DEP01 = createDeprecation({
34537
34537
  name: "FastifyDeprecationLightMyRequest",
34538
34538
  code: "FST_LIGHTMYREQUEST_DEP01",
@@ -34541,7 +34541,7 @@ var require_request2 = __commonJS({
34541
34541
  function hostHeaderFromURL(parsedURL) {
34542
34542
  return parsedURL.port ? parsedURL.host : parsedURL.hostname + (parsedURL.protocol === "https:" ? ":443" : ":80");
34543
34543
  }
34544
- var MockSocket = class extends EventEmitter2 {
34544
+ var MockSocket = class extends EventEmitter5 {
34545
34545
  constructor(remoteAddress) {
34546
34546
  super();
34547
34547
  this.remoteAddress = remoteAddress;
@@ -34900,7 +34900,7 @@ var require_response = __commonJS({
34900
34900
  "node_modules/light-my-request/lib/response.js"(exports, module) {
34901
34901
  "use strict";
34902
34902
  var http3 = __require("node:http");
34903
- var { Writable, Readable, addAbortSignal } = __require("node:stream");
34903
+ var { Writable: Writable3, Readable, addAbortSignal } = __require("node:stream");
34904
34904
  var util = __require("node:util");
34905
34905
  var setCookie = require_set_cookie();
34906
34906
  function Response(req, onEnd, reject) {
@@ -35058,7 +35058,7 @@ var require_response = __commonJS({
35058
35058
  return res;
35059
35059
  }
35060
35060
  function getNullSocket() {
35061
- return new Writable({
35061
+ return new Writable3({
35062
35062
  write(_chunk, _encoding, callback) {
35063
35063
  setImmediate(callback);
35064
35064
  }
@@ -36622,19 +36622,19 @@ var require_fastify = __commonJS({
36622
36622
  }
36623
36623
  fourOhFour.router.lookup(req, res);
36624
36624
  }
36625
- function onBadUrl(path13, req, res) {
36625
+ function onBadUrl(path17, req, res) {
36626
36626
  if (options.frameworkErrors) {
36627
36627
  const id = getGenReqId(routeEventContext.server, req);
36628
36628
  const childLogger = createChildLogger(routeEventContext, options.logger, req, id);
36629
36629
  const request = new Request(id, null, req, null, childLogger, routeEventContext);
36630
36630
  const reply = new Reply(res, request, childLogger);
36631
36631
  routeEventContext.server[kLogController].incomingRequest(request, reply);
36632
- return options.frameworkErrors(new FST_ERR_BAD_URL(path13), request, reply);
36632
+ return options.frameworkErrors(new FST_ERR_BAD_URL(path17), request, reply);
36633
36633
  }
36634
36634
  const body = JSON.stringify({
36635
36635
  error: "Bad Request",
36636
36636
  code: "FST_ERR_BAD_URL",
36637
- message: `'${path13}' is not a valid url component`,
36637
+ message: `'${path17}' is not a valid url component`,
36638
36638
  statusCode: 400
36639
36639
  });
36640
36640
  res.writeHead(400, {
@@ -36643,19 +36643,19 @@ var require_fastify = __commonJS({
36643
36643
  });
36644
36644
  res.end(body);
36645
36645
  }
36646
- function onMaxParamLength(path13, req, res) {
36646
+ function onMaxParamLength(path17, req, res) {
36647
36647
  if (options.frameworkErrors) {
36648
36648
  const id = getGenReqId(routeEventContext.server, req);
36649
36649
  const childLogger = createChildLogger(routeEventContext, options.logger, req, id);
36650
36650
  const request = new Request(id, null, req, null, childLogger, routeEventContext);
36651
36651
  const reply = new Reply(res, request, childLogger);
36652
36652
  routeEventContext.server[kLogController].incomingRequest(request, reply);
36653
- return options.frameworkErrors(new FST_ERR_MAX_PARAM_LENGTH(path13), request, reply);
36653
+ return options.frameworkErrors(new FST_ERR_MAX_PARAM_LENGTH(path17), request, reply);
36654
36654
  }
36655
36655
  const body = JSON.stringify({
36656
36656
  error: "Bad Request",
36657
36657
  code: "FST_ERR_MAX_PARAM_LENGTH",
36658
- message: `'${path13}' is exceeding the max param length`,
36658
+ message: `'${path17}' is exceeding the max param length`,
36659
36659
  statusCode: 414
36660
36660
  });
36661
36661
  res.writeHead(414, {
@@ -37069,9 +37069,9 @@ var require_vary = __commonJS({
37069
37069
  headerCache.set(header, null);
37070
37070
  }
37071
37071
  }
37072
- const cached2 = headerCache.get(header);
37073
- if (cached2 !== null) {
37074
- reply.header("Vary", cached2);
37072
+ const cached3 = headerCache.get(header);
37073
+ if (cached3 !== null) {
37074
+ reply.header("Vary", cached3);
37075
37075
  }
37076
37076
  };
37077
37077
  }
@@ -38064,7 +38064,7 @@ var require_validation3 = __commonJS({
38064
38064
  var require_receiver = __commonJS({
38065
38065
  "node_modules/ws/lib/receiver.js"(exports, module) {
38066
38066
  "use strict";
38067
- var { Writable } = __require("stream");
38067
+ var { Writable: Writable3 } = __require("stream");
38068
38068
  var PerMessageDeflate2 = require_permessage_deflate();
38069
38069
  var {
38070
38070
  BINARY_TYPES,
@@ -38082,7 +38082,7 @@ var require_receiver = __commonJS({
38082
38082
  var GET_DATA = 4;
38083
38083
  var INFLATING = 5;
38084
38084
  var DEFER_EVENT = 6;
38085
- var Receiver2 = class extends Writable {
38085
+ var Receiver2 = class extends Writable3 {
38086
38086
  /**
38087
38087
  * Creates a Receiver instance.
38088
38088
  *
@@ -39562,12 +39562,12 @@ var require_extension = __commonJS({
39562
39562
  var require_websocket = __commonJS({
39563
39563
  "node_modules/ws/lib/websocket.js"(exports, module) {
39564
39564
  "use strict";
39565
- var EventEmitter2 = __require("events");
39565
+ var EventEmitter5 = __require("events");
39566
39566
  var https = __require("https");
39567
39567
  var http3 = __require("http");
39568
- var net2 = __require("net");
39568
+ var net3 = __require("net");
39569
39569
  var tls = __require("tls");
39570
- var { randomBytes, createHash } = __require("crypto");
39570
+ var { randomBytes: randomBytes2, createHash } = __require("crypto");
39571
39571
  var { Duplex, Readable } = __require("stream");
39572
39572
  var { URL: URL2 } = __require("url");
39573
39573
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -39594,7 +39594,7 @@ var require_websocket = __commonJS({
39594
39594
  var protocolVersions = [8, 13];
39595
39595
  var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
39596
39596
  var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
39597
- var WebSocket2 = class _WebSocket extends EventEmitter2 {
39597
+ var WebSocket2 = class _WebSocket extends EventEmitter5 {
39598
39598
  /**
39599
39599
  * Create a new `WebSocket`.
39600
39600
  *
@@ -40105,7 +40105,7 @@ var require_websocket = __commonJS({
40105
40105
  }
40106
40106
  }
40107
40107
  const defaultPort = isSecure ? 443 : 80;
40108
- const key = randomBytes(16).toString("base64");
40108
+ const key = randomBytes2(16).toString("base64");
40109
40109
  const request = isSecure ? https.request : http3.request;
40110
40110
  const protocolSet = /* @__PURE__ */ new Set();
40111
40111
  let perMessageDeflate;
@@ -40309,12 +40309,12 @@ var require_websocket = __commonJS({
40309
40309
  }
40310
40310
  function netConnect(options) {
40311
40311
  options.path = options.socketPath;
40312
- return net2.connect(options);
40312
+ return net3.connect(options);
40313
40313
  }
40314
40314
  function tlsConnect(options) {
40315
40315
  options.path = void 0;
40316
40316
  if (!options.servername && options.servername !== "") {
40317
- options.servername = net2.isIP(options.host) ? "" : options.host;
40317
+ options.servername = net3.isIP(options.host) ? "" : options.host;
40318
40318
  }
40319
40319
  return tls.connect(options);
40320
40320
  }
@@ -40601,7 +40601,7 @@ var require_subprotocol = __commonJS({
40601
40601
  var require_websocket_server = __commonJS({
40602
40602
  "node_modules/ws/lib/websocket-server.js"(exports, module) {
40603
40603
  "use strict";
40604
- var EventEmitter2 = __require("events");
40604
+ var EventEmitter5 = __require("events");
40605
40605
  var http3 = __require("http");
40606
40606
  var { Duplex } = __require("stream");
40607
40607
  var { createHash } = __require("crypto");
@@ -40614,7 +40614,7 @@ var require_websocket_server = __commonJS({
40614
40614
  var RUNNING = 0;
40615
40615
  var CLOSING = 1;
40616
40616
  var CLOSED = 2;
40617
- var WebSocketServer2 = class extends EventEmitter2 {
40617
+ var WebSocketServer2 = class extends EventEmitter5 {
40618
40618
  /**
40619
40619
  * Create a `WebSocketServer` instance.
40620
40620
  *
@@ -41001,12 +41001,13 @@ var require_websocket_server = __commonJS({
41001
41001
  // src/server.ts
41002
41002
  var import_fastify = __toESM(require_fastify(), 1);
41003
41003
  var import_cors = __toESM(require_cors(), 1);
41004
+ import path16 from "node:path";
41004
41005
 
41005
41006
  // src/db/index.ts
41006
41007
  import Database from "better-sqlite3";
41007
41008
  var db;
41008
- function initDb(path13 = "data.db") {
41009
- db = new Database(path13);
41009
+ function initDb(path17 = "data.db") {
41010
+ db = new Database(path17);
41010
41011
  db.pragma("journal_mode = WAL");
41011
41012
  db.pragma("foreign_keys = ON");
41012
41013
  createTables(db);
@@ -41111,6 +41112,33 @@ function createTables(database) {
41111
41112
  created_at TEXT NOT NULL
41112
41113
  );
41113
41114
 
41115
+ -- Runtime processes running under a session host (session-host/), which
41116
+ -- outlive the daemon. The next daemon adopts them from these rows. An
41117
+ -- older daemon ignores the table; its hosts stop themselves (downgrade
41118
+ -- guard). replay_offset: where replay starts when the host is adopted,
41119
+ -- the start of the running turn or the end of the last one.
41120
+ -- background_tasks: the runtime's last live background-task set (JSON),
41121
+ -- which it reports only when the set changes.
41122
+ CREATE TABLE IF NOT EXISTS session_hosts (
41123
+ id TEXT PRIMARY KEY,
41124
+ runtime TEXT NOT NULL,
41125
+ session_id TEXT NOT NULL,
41126
+ entry_key TEXT NOT NULL,
41127
+ thread_id TEXT,
41128
+ turn_id TEXT,
41129
+ replay_offset INTEGER NOT NULL DEFAULT 0,
41130
+ external_id TEXT,
41131
+ host_pid INTEGER,
41132
+ child_pid INTEGER,
41133
+ command TEXT,
41134
+ runtime_version TEXT,
41135
+ protocol INTEGER NOT NULL DEFAULT 1,
41136
+ generation INTEGER NOT NULL DEFAULT 0,
41137
+ background_tasks TEXT,
41138
+ created_at TEXT NOT NULL,
41139
+ updated_at TEXT NOT NULL
41140
+ );
41141
+
41114
41142
  CREATE INDEX IF NOT EXISTS idx_turns_session_id ON turns(session_id);
41115
41143
  CREATE INDEX IF NOT EXISTS idx_items_turn_id ON items(turn_id);
41116
41144
  CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
@@ -41197,6 +41225,9 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
41197
41225
  if (!turnColumns.some((c) => c.name === "resume_at")) {
41198
41226
  database.exec("ALTER TABLE turns ADD COLUMN resume_at TEXT");
41199
41227
  }
41228
+ if (!turnColumns.some((c) => c.name === "stream_cursor")) {
41229
+ database.exec("ALTER TABLE turns ADD COLUMN stream_cursor TEXT");
41230
+ }
41200
41231
  const processColumns = database.prepare("PRAGMA table_info(cli_processes)").all();
41201
41232
  if (!processColumns.some((c) => c.name === "runtime")) {
41202
41233
  database.exec("ALTER TABLE cli_processes ADD COLUMN runtime TEXT NOT NULL DEFAULT 'claude'");
@@ -41320,6 +41351,64 @@ function broadcast(event, data) {
41320
41351
  }
41321
41352
  }
41322
41353
 
41354
+ // src/ws/streams.ts
41355
+ var TURN_ENDS = /* @__PURE__ */ new Set(["turn:completed", "turn:failed", "turn:cancelled", "turn:interrupted", "turn:resuming"]);
41356
+ var streams = /* @__PURE__ */ new Map();
41357
+ function keyOf(sessionId, turnId, itemId) {
41358
+ return `${sessionId}
41359
+ ${turnId}
41360
+ ${itemId}`;
41361
+ }
41362
+ function noteDelta(p) {
41363
+ if (!p.sessionId || !p.turnId || !p.itemId || typeof p.delta !== "string") return;
41364
+ const key = keyOf(p.sessionId, p.turnId, p.itemId);
41365
+ const stream = streams.get(key);
41366
+ if (stream) stream.text += p.delta;
41367
+ else streams.set(key, { sessionId: p.sessionId, turnId: p.turnId, itemId: p.itemId, text: p.delta });
41368
+ }
41369
+ function noteItem(p) {
41370
+ const itemId = p.item?.external_item_id;
41371
+ if (!p.sessionId || !p.turnId || !itemId) return;
41372
+ const key = keyOf(p.sessionId, p.turnId, itemId);
41373
+ if (p.item?.status === "in_progress") {
41374
+ const text2 = p.item.data?.text;
41375
+ if (typeof text2 === "string") streams.set(key, { sessionId: p.sessionId, turnId: p.turnId, itemId, text: text2 });
41376
+ return;
41377
+ }
41378
+ streams.delete(key);
41379
+ }
41380
+ function dropTurn(p) {
41381
+ for (const [key, stream] of streams) {
41382
+ if (stream.turnId === p.turnId && stream.sessionId === p.sessionId) streams.delete(key);
41383
+ }
41384
+ }
41385
+ function forgetStreams(sessionId) {
41386
+ for (const [key, stream] of streams) if (stream.sessionId === sessionId) streams.delete(key);
41387
+ }
41388
+ function liveStreams(sessionId) {
41389
+ return [...streams.values()].filter((stream) => sessionId === void 0 || stream.sessionId === sessionId).map((stream) => ({ ...stream }));
41390
+ }
41391
+ function streamsSnapshot() {
41392
+ return { sessionId: null, streams: liveStreams() };
41393
+ }
41394
+ function resendStreams(sessionId) {
41395
+ const snapshot = { sessionId, streams: liveStreams(sessionId) };
41396
+ broadcast("streams:snapshot", snapshot);
41397
+ }
41398
+ var untap = null;
41399
+ function trackStreams() {
41400
+ if (untap) return;
41401
+ untap = tapBroadcast((event, data) => {
41402
+ try {
41403
+ if (event === "item:delta") noteDelta(data);
41404
+ else if (event === "item:started" || event === "item:updated" || event === "item:completed") {
41405
+ noteItem(data);
41406
+ } else if (TURN_ENDS.has(event)) dropTurn(data);
41407
+ } catch {
41408
+ }
41409
+ });
41410
+ }
41411
+
41323
41412
  // ../shared/terminal-protocol.ts
41324
41413
  var TERMINAL_CLOSE = {
41325
41414
  /** The same terminal was opened elsewhere, e.g. in a duplicated tab. */
@@ -42467,7 +42556,11 @@ function markResumeCancelled(db2, turnId) {
42467
42556
  db2.prepare("UPDATE turns SET resume_state = 'cancelled', resume_at = NULL WHERE id = ?").run(turnId);
42468
42557
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { outcome: "cancelled" });
42469
42558
  }
42559
+ function runtimeEntryKey(sessionId, threadId) {
42560
+ return threadId ? `${sessionId}\0${threadId}` : sessionId;
42561
+ }
42470
42562
  function recoverInterruptedTurns(db2, opts) {
42563
+ const skip = opts.skip ?? { turnIds: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
42471
42564
  const live = db2.prepare(
42472
42565
  `SELECT t.id, t.session_id, t.status, t.thread_id, t.interrupted_at, t.interrupt_reason, t.resume_state,
42473
42566
  t.resume_attempts, t.updated_at, s.runtime_type,
@@ -42475,13 +42568,25 @@ function recoverInterruptedTurns(db2, opts) {
42475
42568
  FROM turns t JOIN sessions s ON s.id = t.session_id
42476
42569
  WHERE t.status IN ('pending', 'running')
42477
42570
  ORDER BY t.created_at ASC`
42478
- ).all();
42571
+ ).all().filter((t) => !skip.turnIds.has(t.id));
42479
42572
  const now = (/* @__PURE__ */ new Date()).toISOString();
42480
- db2.prepare(
42573
+ const open = db2.prepare(
42574
+ `SELECT i.id, i.type, t.session_id, t.thread_id FROM items i JOIN turns t ON t.id = i.turn_id
42575
+ WHERE i.status = 'in_progress'`
42576
+ ).all();
42577
+ const orphaned = open.filter((i) => !skip.entries.has(runtimeEntryKey(i.session_id, i.thread_id)));
42578
+ const stopTask2 = db2.prepare(
42481
42579
  `UPDATE items SET data = json_set(COALESCE(data, '{}'), '$.status', 'stopped')
42482
- WHERE status = 'in_progress' AND type = 'background_task' AND json_valid(COALESCE(data, '{}'))`
42483
- ).run();
42484
- const items = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE status = 'in_progress'").run(now);
42580
+ WHERE id = ? AND json_valid(COALESCE(data, '{}'))`
42581
+ );
42582
+ const failItem = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE id = ?");
42583
+ const items = { changes: 0 };
42584
+ db2.transaction(() => {
42585
+ for (const item of orphaned) {
42586
+ if (item.type === "background_task") stopTask2.run(item.id);
42587
+ items.changes += failItem.run(now, item.id).changes;
42588
+ }
42589
+ })();
42485
42590
  let waiting = 0;
42486
42591
  let failed = 0;
42487
42592
  for (const turn of live) {
@@ -42580,7 +42685,7 @@ function startAutoResume(opts = {}) {
42580
42685
  orphansReaped = reapAllOrphans().catch((err) => {
42581
42686
  console.error("[resume] could not clean up after the previous host:", err);
42582
42687
  });
42583
- const summary = recoverInterruptedTurns(getDb(), { canResume: canResumeRuntime });
42688
+ const summary = recoverInterruptedTurns(getDb(), { canResume: canResumeRuntime, skip: opts.skip });
42584
42689
  unsubscribe = onTurnInterrupted((event) => {
42585
42690
  scheduleScan(event.reason === "network" ? cfg.networkDelayMs : cfg.delayMs);
42586
42691
  });
@@ -43265,9 +43370,9 @@ async function browseFolder(input, opts = {}) {
43265
43370
  const atHome = dir === nodePath.resolve(home);
43266
43371
  const folders = await Promise.all(
43267
43372
  names.slice(0, limit).map(async (name) => {
43268
- const path13 = nodePath.join(dir, name);
43373
+ const path17 = nodePath.join(dir, name);
43269
43374
  const skipProbe = atHome && HOME_STANDARD_FOLDERS.has(name) || dir === "/Volumes";
43270
- return { name, path: path13, git: !skipProbe && await exists(nodePath.join(path13, ".git")) };
43375
+ return { name, path: path17, git: !skipProbe && await exists(nodePath.join(path17, ".git")) };
43271
43376
  })
43272
43377
  );
43273
43378
  const parent = nodePath.dirname(dir);
@@ -43305,11 +43410,11 @@ async function registerWorkspaceRoutes(fastify) {
43305
43410
  }
43306
43411
  }
43307
43412
  }, async (request, reply) => {
43308
- const { path: path13, label = null } = request.body || {};
43309
- if (!path13 || !path13.trim()) {
43413
+ const { path: path17, label = null } = request.body || {};
43414
+ if (!path17 || !path17.trim()) {
43310
43415
  return reply.code(400).send({ error: "Path is required" });
43311
43416
  }
43312
- const resolved = await resolveWorkspacePath(path13);
43417
+ const resolved = await resolveWorkspacePath(path17);
43313
43418
  if ("error" in resolved) {
43314
43419
  return reply.code(400).send({ error: resolved.error });
43315
43420
  }
@@ -43351,8 +43456,8 @@ async function registerWorkspaceRoutes(fastify) {
43351
43456
  "-e",
43352
43457
  'POSIX path of (choose folder with prompt "Select a workspace directory")'
43353
43458
  ]);
43354
- const path13 = stdout.trim().replace(/\/$/, "");
43355
- return { path: path13 };
43459
+ const path17 = stdout.trim().replace(/\/$/, "");
43460
+ return { path: path17 };
43356
43461
  } catch {
43357
43462
  return reply.code(204).send({ cancelled: true });
43358
43463
  }
@@ -43368,11 +43473,11 @@ async function registerWorkspaceRoutes(fastify) {
43368
43473
  }
43369
43474
  }
43370
43475
  }, async (request, reply) => {
43371
- const { path: path13 } = request.body || {};
43372
- if (!path13 || !path13.trim()) {
43476
+ const { path: path17 } = request.body || {};
43477
+ if (!path17 || !path17.trim()) {
43373
43478
  return reply.code(400).send({ error: "Path is required" });
43374
43479
  }
43375
- const trimmedPath = path13.trim();
43480
+ const trimmedPath = path17.trim();
43376
43481
  const db2 = getDb();
43377
43482
  const existing = db2.prepare("SELECT * FROM workspaces WHERE path = ?").get(trimmedPath);
43378
43483
  if (existing) {
@@ -43627,11 +43732,18 @@ import { readFileSync } from "node:fs";
43627
43732
  // src/codex/app-server-client.ts
43628
43733
  import { spawn } from "node:child_process";
43629
43734
  import { EventEmitter } from "node:events";
43735
+ var REPLAY_DONE_METHOD = "agentpane/replayDone";
43736
+ var REPLAY_MARKER = JSON.stringify({ method: REPLAY_DONE_METHOD });
43630
43737
  var REQUEST_TIMEOUT_MS = 3e4;
43631
43738
  var CLOSE_GRACE_MS = 2e3;
43739
+ function appServerCommand(options) {
43740
+ const binary = options.binaryPath ?? process.env.CODEX_BIN ?? "codex";
43741
+ const args = ["app-server", ...options.launchArgs ?? []];
43742
+ return /\.m?js$/.test(binary) ? { command: process.execPath, args: [binary, ...args] } : { command: binary, args };
43743
+ }
43632
43744
  var AppServerClient = class {
43633
43745
  proc;
43634
- nextId = 1;
43746
+ nextId;
43635
43747
  pending = /* @__PURE__ */ new Map();
43636
43748
  notificationHandlers = /* @__PURE__ */ new Map();
43637
43749
  requestHandlers = /* @__PURE__ */ new Map();
@@ -43642,15 +43754,22 @@ var AppServerClient = class {
43642
43754
  clientInfo;
43643
43755
  /** Bound stdout listener — removed in close() so stale data is not processed. */
43644
43756
  stdoutListener = (chunk) => this.onStdoutData(chunk);
43757
+ /** Replaying (attach): server requests wait here for the replay's end. */
43758
+ replay;
43645
43759
  events = new EventEmitter();
43646
43760
  constructor(options) {
43647
- const binary = options.binaryPath ?? "codex";
43648
- const args = ["app-server", ...options.launchArgs ?? []];
43649
- this.proc = spawn(binary, args, {
43650
- cwd: options.cwd,
43651
- env: { ...process.env, ...options.env },
43652
- stdio: ["pipe", "pipe", "pipe"]
43653
- });
43761
+ this.nextId = options.firstRequestId ?? 1;
43762
+ this.replay = options.replaying ? /* @__PURE__ */ new Map() : null;
43763
+ if (options.process) {
43764
+ this.proc = options.process;
43765
+ } else {
43766
+ const { command, args } = appServerCommand(options);
43767
+ this.proc = spawn(command, args, {
43768
+ cwd: options.cwd,
43769
+ env: { ...process.env, ...options.env },
43770
+ stdio: ["pipe", "pipe", "pipe"]
43771
+ });
43772
+ }
43654
43773
  this.clientInfo = options.clientInfo ?? { name: "agentpane", title: "AgentPane", version: "1.0.0" };
43655
43774
  this.proc.stdin?.on("error", () => {
43656
43775
  });
@@ -43721,6 +43840,23 @@ var AppServerClient = class {
43721
43840
  isClosed() {
43722
43841
  return this.closed;
43723
43842
  }
43843
+ /** True until the replay marker of an attached process. */
43844
+ get replaying() {
43845
+ return this.replay !== null;
43846
+ }
43847
+ /** Stop talking to the process and leave it running (the daemon goes away
43848
+ * and its session host keeps the app-server). Pending requests fail;
43849
+ * nothing is sent to the process. */
43850
+ detach() {
43851
+ if (this.closed) return;
43852
+ this.closed = true;
43853
+ this.proc.stdout?.removeListener("data", this.stdoutListener);
43854
+ for (const [id, entry] of this.pending) {
43855
+ clearTimeout(entry.timer);
43856
+ entry.reject(new Error("AppServerClient detached"));
43857
+ this.pending.delete(id);
43858
+ }
43859
+ }
43724
43860
  /** Pid of the app-server process (the codex launcher), undefined when it never started. */
43725
43861
  get pid() {
43726
43862
  return this.proc.pid;
@@ -43787,8 +43923,13 @@ var AppServerClient = class {
43787
43923
  }
43788
43924
  const hasId = "id" in msg && typeof msg.id === "number";
43789
43925
  const hasMethod = "method" in msg && typeof msg.method === "string";
43926
+ if (msg.method === REPLAY_DONE_METHOD && !hasId) {
43927
+ this.endReplay();
43928
+ return;
43929
+ }
43790
43930
  if (hasId && hasMethod) {
43791
- this.handleServerRequest(msg.method, msg.id, msg.params);
43931
+ if (this.replay) this.replay.set(msg.id, { method: msg.method, params: msg.params });
43932
+ else this.handleServerRequest(msg.method, msg.id, msg.params);
43792
43933
  return;
43793
43934
  }
43794
43935
  if (hasId) {
@@ -43807,6 +43948,10 @@ var AppServerClient = class {
43807
43948
  }
43808
43949
  if (hasMethod) {
43809
43950
  const method = msg.method;
43951
+ if (method === "serverRequest/resolved" && this.replay) {
43952
+ const requestId = msg.params?.requestId;
43953
+ if (typeof requestId === "number") this.replay.delete(requestId);
43954
+ }
43810
43955
  const handlers = this.notificationHandlers.get(method);
43811
43956
  if (handlers) {
43812
43957
  for (const handler of handlers) {
@@ -43817,6 +43962,15 @@ var AppServerClient = class {
43817
43962
  return;
43818
43963
  }
43819
43964
  }
43965
+ /** The replay is over: answer the server requests that are still open,
43966
+ * then go live. */
43967
+ endReplay() {
43968
+ const held = this.replay;
43969
+ if (!held) return;
43970
+ this.replay = null;
43971
+ for (const [id, request] of held) this.handleServerRequest(request.method, id, request.params);
43972
+ this.events.emit("replayDone");
43973
+ }
43820
43974
  /**
43821
43975
  * Handle a server→client JSON-RPC request. The last registered handler
43822
43976
  * runs and its result is sent back; unhandled requests are declined with
@@ -44057,17 +44211,17 @@ async function registerPerfLogRoutes(fastify) {
44057
44211
  if (entries.length === 0) {
44058
44212
  return reply.send({ written: 0 });
44059
44213
  }
44060
- const path13 = perfLogPath();
44214
+ const path17 = perfLogPath();
44061
44215
  try {
44062
- mkdirSync(dirname(path13), { recursive: true });
44216
+ mkdirSync(dirname(path17), { recursive: true });
44063
44217
  try {
44064
- if (statSync(path13).size > MAX_BYTES) {
44065
- renameSync(path13, `${path13}.1`);
44218
+ if (statSync(path17).size > MAX_BYTES) {
44219
+ renameSync(path17, `${path17}.1`);
44066
44220
  }
44067
44221
  } catch {
44068
44222
  }
44069
44223
  const lines = entries.map((e) => `${new Date(e.t).toISOString()} [${oneLine(e.cat)}] ${oneLine(e.msg)}`).join("\n");
44070
- appendFileSync(path13, `${lines}
44224
+ appendFileSync(path17, `${lines}
44071
44225
  `, "utf-8");
44072
44226
  return reply.send({ written: entries.length });
44073
44227
  } catch (err) {
@@ -100210,8 +100364,8 @@ function checkJsSyntax(js) {
100210
100364
  }
100211
100365
  }
100212
100366
  function compileAppJs(appId) {
100213
- const cached2 = cache.get(appId);
100214
- if (cached2) return cached2;
100367
+ const cached3 = cache.get(appId);
100368
+ if (cached3) return cached3;
100215
100369
  const tsSource = readAppFile(appId, APP_TS);
100216
100370
  let result;
100217
100371
  let logicFiles = [];
@@ -100297,8 +100451,8 @@ var runtimes = /* @__PURE__ */ new Map();
100297
100451
  var pendingCalls = /* @__PURE__ */ new Map();
100298
100452
  function loadRuntime(appId, workspace) {
100299
100453
  const key = runtimeKey(appId, workspace);
100300
- const cached2 = runtimes.get(key);
100301
- if (cached2) return cached2;
100454
+ const cached3 = runtimes.get(key);
100455
+ if (cached3) return cached3;
100302
100456
  const js = compileAppJs(appId).js;
100303
100457
  if (!js.trim()) return null;
100304
100458
  const manifest = readManifest(appId);
@@ -100512,7 +100666,7 @@ function handleUnhandledRejection(reason, promise2) {
100512
100666
  var stopSessionEvents = null;
100513
100667
  function startHeadlessEvents() {
100514
100668
  stopHeadlessEvents();
100515
- const untap = tapBroadcast((event, data) => {
100669
+ const untap2 = tapBroadcast((event, data) => {
100516
100670
  if (!SESSION_EVENTS.has(event)) return;
100517
100671
  setImmediate(() => {
100518
100672
  try {
@@ -100524,7 +100678,7 @@ function startHeadlessEvents() {
100524
100678
  });
100525
100679
  process.on("unhandledRejection", handleUnhandledRejection);
100526
100680
  stopSessionEvents = () => {
100527
- untap();
100681
+ untap2();
100528
100682
  process.off("unhandledRejection", handleUnhandledRejection);
100529
100683
  };
100530
100684
  }
@@ -101333,8 +101487,8 @@ async function loadFresh(timezone) {
101333
101487
  var cache2 = /* @__PURE__ */ new Map();
101334
101488
  var inflight = /* @__PURE__ */ new Map();
101335
101489
  function loadCcusage(timezone, fresh) {
101336
- const cached2 = cache2.get(timezone);
101337
- if (cached2 && !fresh) return Promise.resolve(cached2);
101490
+ const cached3 = cache2.get(timezone);
101491
+ if (cached3 && !fresh) return Promise.resolve(cached3);
101338
101492
  let run = inflight.get(timezone);
101339
101493
  if (!run) {
101340
101494
  run = loadFresh(timezone).then((result) => {
@@ -102516,10 +102670,10 @@ function mergeDefs(...defs) {
102516
102670
  function cloneDef(schema) {
102517
102671
  return mergeDefs(schema._zod.def);
102518
102672
  }
102519
- function getElementAtPath(obj2, path13) {
102520
- if (!path13)
102673
+ function getElementAtPath(obj2, path17) {
102674
+ if (!path17)
102521
102675
  return obj2;
102522
- return path13.reduce((acc, key) => acc?.[key], obj2);
102676
+ return path17.reduce((acc, key) => acc?.[key], obj2);
102523
102677
  }
102524
102678
  function promiseAllObject(promisesObj) {
102525
102679
  const keys = Object.keys(promisesObj);
@@ -102928,11 +103082,11 @@ function explicitlyAborted(x, startIndex = 0) {
102928
103082
  }
102929
103083
  return false;
102930
103084
  }
102931
- function prefixIssues(path13, issues) {
103085
+ function prefixIssues(path17, issues) {
102932
103086
  return issues.map((iss) => {
102933
103087
  var _a3;
102934
103088
  (_a3 = iss).path ?? (_a3.path = []);
102935
- iss.path.unshift(path13);
103089
+ iss.path.unshift(path17);
102936
103090
  return iss;
102937
103091
  });
102938
103092
  }
@@ -103079,16 +103233,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
103079
103233
  }
103080
103234
  function formatError(error51, mapper = (issue2) => issue2.message) {
103081
103235
  const fieldErrors = { _errors: [] };
103082
- const processError = (error52, path13 = []) => {
103236
+ const processError = (error52, path17 = []) => {
103083
103237
  for (const issue2 of error52.issues) {
103084
103238
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103085
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
103239
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103086
103240
  } else if (issue2.code === "invalid_key") {
103087
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103241
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103088
103242
  } else if (issue2.code === "invalid_element") {
103089
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103243
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103090
103244
  } else {
103091
- const fullpath = [...path13, ...issue2.path];
103245
+ const fullpath = [...path17, ...issue2.path];
103092
103246
  if (fullpath.length === 0) {
103093
103247
  fieldErrors._errors.push(mapper(issue2));
103094
103248
  } else {
@@ -103115,17 +103269,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
103115
103269
  }
103116
103270
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
103117
103271
  const result = { errors: [] };
103118
- const processError = (error52, path13 = []) => {
103272
+ const processError = (error52, path17 = []) => {
103119
103273
  var _a3, _b;
103120
103274
  for (const issue2 of error52.issues) {
103121
103275
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103122
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
103276
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103123
103277
  } else if (issue2.code === "invalid_key") {
103124
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103278
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103125
103279
  } else if (issue2.code === "invalid_element") {
103126
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103280
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103127
103281
  } else {
103128
- const fullpath = [...path13, ...issue2.path];
103282
+ const fullpath = [...path17, ...issue2.path];
103129
103283
  if (fullpath.length === 0) {
103130
103284
  result.errors.push(mapper(issue2));
103131
103285
  continue;
@@ -103157,8 +103311,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
103157
103311
  }
103158
103312
  function toDotPath(_path) {
103159
103313
  const segs = [];
103160
- const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103161
- for (const seg of path13) {
103314
+ const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103315
+ for (const seg of path17) {
103162
103316
  if (typeof seg === "number")
103163
103317
  segs.push(`[${seg}]`);
103164
103318
  else if (typeof seg === "symbol")
@@ -115850,13 +116004,13 @@ function resolveRef(ref, ctx) {
115850
116004
  if (!ref.startsWith("#")) {
115851
116005
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
115852
116006
  }
115853
- const path13 = ref.slice(1).split("/").filter(Boolean);
115854
- if (path13.length === 0) {
116007
+ const path17 = ref.slice(1).split("/").filter(Boolean);
116008
+ if (path17.length === 0) {
115855
116009
  return ctx.rootSchema;
115856
116010
  }
115857
116011
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
115858
- if (path13[0] === defsKey) {
115859
- const key = path13[1];
116012
+ if (path17[0] === defsKey) {
116013
+ const key = path17[1];
115860
116014
  if (!key || !ctx.defs[key]) {
115861
116015
  throw new Error(`Reference not found: ${ref}`);
115862
116016
  }
@@ -116402,9 +116556,9 @@ function mapToolUse(block) {
116402
116556
  };
116403
116557
  }
116404
116558
  function deriveFileChangeData(input, toolName) {
116405
- const path13 = input.file_path ?? input.notebook_path ?? "";
116559
+ const path17 = input.file_path ?? input.notebook_path ?? "";
116406
116560
  const kind = toolName === "Write" ? "add" : "modify";
116407
- return { changes: [{ path: path13, kind }], status: "in_progress" };
116561
+ return { changes: [{ path: path17, kind }], status: "in_progress" };
116408
116562
  }
116409
116563
  function extractToolResultText(content) {
116410
116564
  if (!content) return "";
@@ -116935,6 +117089,776 @@ async function registerClaudeSessionRoutes(fastify) {
116935
117089
  );
116936
117090
  }
116937
117091
 
117092
+ // src/session-host/flags.ts
117093
+ import fs7 from "node:fs";
117094
+ import path11 from "node:path";
117095
+ var DEFAULT_FLAGS = {
117096
+ claude: true,
117097
+ codex: true,
117098
+ repoburg: true,
117099
+ adoption: true,
117100
+ noHostBusyMs: 30 * 6e4,
117101
+ noHostIdleMs: 5 * 6e4
117102
+ };
117103
+ var MIN_LIMIT_MS = 1e3;
117104
+ var MAX_LIMIT_MS = 7 * 24 * 60 * 6e4;
117105
+ var paneDataDir = null;
117106
+ var cached2 = null;
117107
+ function setPaneDataDir(dir) {
117108
+ paneDataDir = dir;
117109
+ cached2 = null;
117110
+ }
117111
+ function sessionHostsRoot() {
117112
+ const override = process.env.AGENT_PANE_SESSION_HOSTS_DIR;
117113
+ if (override) return path11.resolve(override);
117114
+ return paneDataDir ? path11.join(paneDataDir, "session-hosts") : null;
117115
+ }
117116
+ function flagsFilePath() {
117117
+ const root = sessionHostsRoot();
117118
+ if (process.env.AGENT_PANE_SESSION_HOSTS_DIR) return path11.join(path11.dirname(root), "session-hosts.json");
117119
+ return paneDataDir ? path11.join(paneDataDir, "session-hosts.json") : null;
117120
+ }
117121
+ function readFlagFile(file2) {
117122
+ if (!file2) return {};
117123
+ try {
117124
+ const parsed = JSON.parse(fs7.readFileSync(file2, "utf8"));
117125
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
117126
+ console.warn(`[session-host] ${file2} is not a JSON object; using the defaults`);
117127
+ } catch (err) {
117128
+ if (err.code !== "ENOENT") {
117129
+ console.warn(`[session-host] ${file2} could not be read (${err.message}); using the defaults`);
117130
+ }
117131
+ }
117132
+ return {};
117133
+ }
117134
+ function bool(value, fallback) {
117135
+ return typeof value === "boolean" ? value : fallback;
117136
+ }
117137
+ function minutes(value, fallbackMs) {
117138
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallbackMs;
117139
+ const ms = Math.round(value * 6e4);
117140
+ return ms >= MIN_LIMIT_MS && ms <= MAX_LIMIT_MS ? ms : fallbackMs;
117141
+ }
117142
+ function envBool(name) {
117143
+ const v = process.env[name];
117144
+ if (v === "0" || v === "false") return false;
117145
+ if (v === "1" || v === "true") return true;
117146
+ return void 0;
117147
+ }
117148
+ function envMs(name) {
117149
+ const v = Number(process.env[name]);
117150
+ return Number.isFinite(v) && v >= MIN_LIMIT_MS && v <= MAX_LIMIT_MS ? Math.round(v) : void 0;
117151
+ }
117152
+ function resolveFlags(file2) {
117153
+ const flags = {
117154
+ claude: bool(file2.claude, DEFAULT_FLAGS.claude),
117155
+ codex: bool(file2.codex, DEFAULT_FLAGS.codex),
117156
+ repoburg: bool(file2.repoburg, DEFAULT_FLAGS.repoburg),
117157
+ adoption: bool(file2.adoption, DEFAULT_FLAGS.adoption),
117158
+ noHostBusyMs: minutes(file2.noHostBusyMin, DEFAULT_FLAGS.noHostBusyMs),
117159
+ noHostIdleMs: minutes(file2.noHostIdleMin, DEFAULT_FLAGS.noHostIdleMs)
117160
+ };
117161
+ if (envBool("AGENT_PANE_SESSION_HOSTS") === false) {
117162
+ flags.claude = false;
117163
+ flags.codex = false;
117164
+ }
117165
+ flags.claude = envBool("AGENT_PANE_SESSION_HOSTS_CLAUDE") ?? flags.claude;
117166
+ flags.codex = envBool("AGENT_PANE_SESSION_HOSTS_CODEX") ?? flags.codex;
117167
+ flags.repoburg = envBool("AGENT_PANE_SESSION_HOSTS_REPOBURG") ?? flags.repoburg;
117168
+ flags.adoption = envBool("AGENT_PANE_SESSION_HOSTS_ADOPTION") ?? flags.adoption;
117169
+ flags.noHostBusyMs = envMs("AGENT_PANE_SESSION_HOST_BUSY_MS") ?? flags.noHostBusyMs;
117170
+ flags.noHostIdleMs = envMs("AGENT_PANE_SESSION_HOST_IDLE_MS") ?? flags.noHostIdleMs;
117171
+ return flags;
117172
+ }
117173
+ function sessionHostFlags() {
117174
+ if (!cached2) cached2 = resolveFlags(readFlagFile(flagsFilePath()));
117175
+ return cached2;
117176
+ }
117177
+ function hostsEnabledFor(runtime) {
117178
+ return sessionHostsRoot() !== null && sessionHostFlags()[runtime];
117179
+ }
117180
+
117181
+ // src/session-host/protocol.ts
117182
+ var SESSION_HOST_PROTOCOL = 1;
117183
+ var SUPPORTED_PROTOCOLS = [1];
117184
+ var LOG_HEADER_PREFIX = "session-host-log v1 oldest=";
117185
+ var LOG_HEADER_DIGITS = 20;
117186
+ var LOG_HEADER_LEN = LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS + 1;
117187
+
117188
+ // src/session-host/registry.ts
117189
+ import { randomBytes, randomUUID as randomUUID2 } from "node:crypto";
117190
+ import fs9 from "node:fs";
117191
+ import path13 from "node:path";
117192
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
117193
+
117194
+ // src/session-host/client.ts
117195
+ import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
117196
+ import { EventEmitter as EventEmitter2 } from "node:events";
117197
+ import fs8 from "node:fs";
117198
+ import net2 from "node:net";
117199
+ import path12 from "node:path";
117200
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
117201
+ var HostRequestError = class extends Error {
117202
+ reply;
117203
+ constructor(reply) {
117204
+ super(`session host refused: ${reply.error}`);
117205
+ this.reply = reply;
117206
+ }
117207
+ };
117208
+ function hostScriptPath() {
117209
+ const override = process.env.AGENT_PANE_SESSION_HOST_SCRIPT;
117210
+ if (override) return override;
117211
+ const here = path12.dirname(fileURLToPath2(import.meta.url));
117212
+ const candidates = [
117213
+ path12.resolve(here, "../../scripts/session-host.mjs"),
117214
+ // src/session-host/ → backend/scripts
117215
+ path12.resolve(here, "../scripts/session-host.mjs")
117216
+ // dist bundle → backend/scripts
117217
+ ];
117218
+ for (const candidate of candidates) {
117219
+ if (fs8.existsSync(candidate)) return candidate;
117220
+ }
117221
+ return null;
117222
+ }
117223
+ function hostSocketPath(dir) {
117224
+ const direct = path12.join(dir, "sock");
117225
+ if (Buffer.byteLength(direct) < 100) return direct;
117226
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
117227
+ return path12.join("/tmp", `rbsh-${uid}`, path12.basename(dir), "sock");
117228
+ }
117229
+ function readJson(file2) {
117230
+ try {
117231
+ return JSON.parse(fs8.readFileSync(file2, "utf8"));
117232
+ } catch {
117233
+ return null;
117234
+ }
117235
+ }
117236
+ function readHostExit(dir) {
117237
+ return readJson(path12.join(dir, "exit.json"));
117238
+ }
117239
+ function readHostChild(dir) {
117240
+ return readJson(path12.join(dir, "child.json"));
117241
+ }
117242
+ function isPidAlive(pid) {
117243
+ if (!pid || pid <= 0) return false;
117244
+ try {
117245
+ process.kill(pid, 0);
117246
+ return true;
117247
+ } catch (err) {
117248
+ return err.code === "EPERM";
117249
+ }
117250
+ }
117251
+ function processStartTime(pid) {
117252
+ return new Promise((resolve) => {
117253
+ execFile3("ps", ["-o", "etime=", "-p", String(pid)], (err, stdout) => {
117254
+ const m = err ? null : /^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
117255
+ if (!m) {
117256
+ resolve(null);
117257
+ return;
117258
+ }
117259
+ const secs = Number(m[1] ?? 0) * 86400 + Number(m[2] ?? 0) * 3600 + Number(m[3]) * 60 + Number(m[4]);
117260
+ resolve(Date.now() - secs * 1e3);
117261
+ });
117262
+ });
117263
+ }
117264
+ var PID_START_TOLERANCE_MS = 3e4;
117265
+ async function verifiedHostPids(dir) {
117266
+ const info = readHostChild(dir);
117267
+ const started = info ? Date.parse(info.startedAt) : NaN;
117268
+ const check2 = async (pid) => {
117269
+ if (!pid || !Number.isFinite(started) || !isPidAlive(pid)) return null;
117270
+ const at = await processStartTime(pid);
117271
+ return at !== null && Math.abs(at - started) <= PID_START_TOLERANCE_MS ? pid : null;
117272
+ };
117273
+ const [hostPid, childPid] = await Promise.all([check2(info?.hostPid), check2(info?.pid)]);
117274
+ return { hostPid, childPid };
117275
+ }
117276
+ function requestHost(dir, body, timeoutMs = 2e3) {
117277
+ return new Promise((resolve, reject) => {
117278
+ const sock = net2.connect(hostSocketPath(dir));
117279
+ let buf = "";
117280
+ let settled = false;
117281
+ const timer2 = setTimeout(() => finish(Object.assign(new Error("session host timed out"), { code: "ETIMEDOUT" })), timeoutMs);
117282
+ const finish = (err, value) => {
117283
+ if (settled) return;
117284
+ settled = true;
117285
+ clearTimeout(timer2);
117286
+ sock.destroy();
117287
+ if (err) reject(err);
117288
+ else resolve(value);
117289
+ };
117290
+ sock.setEncoding("utf8");
117291
+ sock.on("connect", () => sock.write(JSON.stringify({ v: SESSION_HOST_PROTOCOL, ...body }) + "\n"));
117292
+ sock.on("data", (chunk) => {
117293
+ buf += chunk;
117294
+ const nl = buf.indexOf("\n");
117295
+ if (nl === -1) return;
117296
+ let reply;
117297
+ try {
117298
+ reply = JSON.parse(buf.slice(0, nl));
117299
+ } catch {
117300
+ finish(new Error("session host sent a bad reply"));
117301
+ return;
117302
+ }
117303
+ const r = reply;
117304
+ if (r && r.ok === true) finish(null, reply);
117305
+ else finish(new HostRequestError(reply));
117306
+ });
117307
+ sock.on("error", (err) => finish(err));
117308
+ sock.on("close", () => finish(Object.assign(new Error("session host closed the connection"), { code: "ECONNRESET" })));
117309
+ });
117310
+ }
117311
+ var hostStatus = (dir, timeoutMs) => requestHost(dir, { op: "status" }, timeoutMs);
117312
+ var signalHost = (dir, signal) => requestHost(dir, { op: "signal", signal });
117313
+ var eofHost = (dir) => requestHost(dir, { op: "eof" });
117314
+ var ackHost = (dir, upto) => requestHost(dir, { op: "ack", upto });
117315
+ var limitHost = (dir, noHostMs) => requestHost(dir, { op: "limit", noHostMs: Math.round(noHostMs) });
117316
+ function isHostGone(err) {
117317
+ const code = err?.code;
117318
+ return code === "ECONNREFUSED" || code === "ENOENT" || code === "ENOTSOCK";
117319
+ }
117320
+ var HostAttachment = class extends EventEmitter2 {
117321
+ header;
117322
+ socket;
117323
+ constructor(header, socket) {
117324
+ super();
117325
+ this.header = header;
117326
+ this.socket = socket;
117327
+ }
117328
+ write(data, cb) {
117329
+ return this.socket.write(data, cb);
117330
+ }
117331
+ close() {
117332
+ this.socket.destroy();
117333
+ }
117334
+ };
117335
+ function attachHost(dir, after, timeoutMs = 5e3) {
117336
+ return new Promise((resolve, reject) => {
117337
+ const sock = net2.connect(hostSocketPath(dir));
117338
+ let head = Buffer.alloc(0);
117339
+ let settled = false;
117340
+ const timer2 = setTimeout(() => fail(Object.assign(new Error("session host attach timed out"), { code: "ETIMEDOUT" })), timeoutMs);
117341
+ const fail = (err) => {
117342
+ if (settled) return;
117343
+ settled = true;
117344
+ clearTimeout(timer2);
117345
+ sock.destroy();
117346
+ reject(err);
117347
+ };
117348
+ const onData = (chunk) => {
117349
+ head = head.length ? Buffer.concat([head, chunk]) : chunk;
117350
+ const nl = head.indexOf(10);
117351
+ if (nl === -1) {
117352
+ if (head.length > 64 * 1024) fail(new Error("session host sent a bad header"));
117353
+ return;
117354
+ }
117355
+ sock.off("data", onData);
117356
+ sock.pause();
117357
+ let header;
117358
+ try {
117359
+ header = JSON.parse(head.subarray(0, nl).toString("utf8"));
117360
+ } catch {
117361
+ fail(new Error("session host sent a bad header"));
117362
+ return;
117363
+ }
117364
+ if (!header || header.ok !== true) {
117365
+ fail(new HostRequestError(header));
117366
+ return;
117367
+ }
117368
+ settled = true;
117369
+ clearTimeout(timer2);
117370
+ sock.off("error", fail);
117371
+ sock.off("close", onEarlyClose);
117372
+ const attachment = new HostAttachment(header, sock);
117373
+ const rest = Buffer.from(head.subarray(nl + 1));
117374
+ sock.on("error", (err) => attachment.emit("error", err));
117375
+ sock.on("close", () => attachment.emit("close"));
117376
+ sock.on("data", (chunk2) => attachment.emit("data", chunk2));
117377
+ resolve(attachment);
117378
+ setImmediate(() => {
117379
+ if (rest.length > 0) attachment.emit("data", rest);
117380
+ sock.resume();
117381
+ });
117382
+ };
117383
+ const onEarlyClose = () => fail(Object.assign(new Error("session host closed the connection"), { code: "ECONNRESET" }));
117384
+ sock.on("connect", () => {
117385
+ sock.write(JSON.stringify({ v: SESSION_HOST_PROTOCOL, op: "attach", after }) + "\n");
117386
+ });
117387
+ sock.on("data", onData);
117388
+ sock.on("error", fail);
117389
+ sock.on("close", onEarlyClose);
117390
+ });
117391
+ }
117392
+ function startHost(opts) {
117393
+ const script = hostScriptPath();
117394
+ if (!script) throw new Error("session host script not found");
117395
+ fs8.mkdirSync(opts.dir, { recursive: true, mode: 448 });
117396
+ fs8.chmodSync(opts.dir, 448);
117397
+ const env = {};
117398
+ for (const [k, v] of Object.entries(opts.env)) if (v !== void 0) env[k] = v;
117399
+ const child = spawn4(opts.nodePath ?? process.execPath, [script, opts.dir, JSON.stringify(opts.config), opts.command, ...opts.args], {
117400
+ cwd: opts.cwd,
117401
+ env,
117402
+ detached: true,
117403
+ stdio: "ignore"
117404
+ });
117405
+ child.on("error", () => {
117406
+ });
117407
+ child.unref();
117408
+ if (!child.pid) throw new Error("session host did not start");
117409
+ return { hostPid: child.pid };
117410
+ }
117411
+ async function waitForHost(dir, timeoutMs = 1e4) {
117412
+ const deadline = Date.now() + timeoutMs;
117413
+ let lastErr = null;
117414
+ while (Date.now() < deadline) {
117415
+ try {
117416
+ return await hostStatus(dir, 1e3);
117417
+ } catch (err) {
117418
+ lastErr = err;
117419
+ if (readHostExit(dir)) break;
117420
+ await new Promise((r) => setTimeout(r, 25));
117421
+ }
117422
+ }
117423
+ const exit = readHostExit(dir);
117424
+ if (exit) throw new Error(`session host child exited at start: ${exit.error ?? `code ${exit.code}, signal ${exit.signal}`}`);
117425
+ throw new Error(`session host did not come up: ${lastErr?.message ?? "timeout"}`);
117426
+ }
117427
+ function readLogOldest(dir) {
117428
+ let fd = null;
117429
+ try {
117430
+ fd = fs8.openSync(path12.join(dir, "out.log"), "r");
117431
+ const buf = Buffer.alloc(LOG_HEADER_LEN);
117432
+ const n = fs8.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
117433
+ const text2 = buf.subarray(0, n).toString("utf8");
117434
+ if (n < LOG_HEADER_LEN || !text2.startsWith(LOG_HEADER_PREFIX) || text2[LOG_HEADER_LEN - 1] !== "\n") return null;
117435
+ const digits = text2.slice(LOG_HEADER_PREFIX.length, LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS);
117436
+ return /^\d+$/.test(digits) ? Number(digits) : null;
117437
+ } catch {
117438
+ return null;
117439
+ } finally {
117440
+ if (fd !== null) fs8.closeSync(fd);
117441
+ }
117442
+ }
117443
+ function readHostLog(dir, after) {
117444
+ const oldest = readLogOldest(dir);
117445
+ if (oldest === null || after < oldest) return null;
117446
+ try {
117447
+ const all = fs8.readFileSync(path12.join(dir, "out.log"));
117448
+ const start = LOG_HEADER_LEN + (after - oldest);
117449
+ if (start > all.length) return null;
117450
+ return all.subarray(start);
117451
+ } catch {
117452
+ return null;
117453
+ }
117454
+ }
117455
+ function removeHostDir(dir) {
117456
+ try {
117457
+ fs8.rmSync(dir, { recursive: true, force: true });
117458
+ } catch (err) {
117459
+ console.error(`[session-host] could not remove ${dir}:`, err.message);
117460
+ }
117461
+ const alias = path12.dirname(hostSocketPath(dir));
117462
+ if (alias !== dir) {
117463
+ try {
117464
+ fs8.unlinkSync(alias);
117465
+ } catch {
117466
+ }
117467
+ }
117468
+ }
117469
+
117470
+ // src/session-host/registry.ts
117471
+ function emptyResult() {
117472
+ return { turnIds: /* @__PURE__ */ new Set(), sessionIds: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
117473
+ }
117474
+ var adopters = /* @__PURE__ */ new Map();
117475
+ var runtimeAdopters = /* @__PURE__ */ new Map();
117476
+ var daemonUrl = (process.env.AGENT_PANE_SESSION_HOSTS_DAEMON_URL || process.env.REPOBURG_DAEMON_URL || "http://127.0.0.1:9998").replace(/\/+$/, "");
117477
+ var DAEMON_BOOT_ID = randomUUID2();
117478
+ var startupGate = Promise.resolve();
117479
+ var startupPending = false;
117480
+ var lastResult = emptyResult();
117481
+ function registerHostAdopter(adopter) {
117482
+ adopters.set(adopter.runtime, adopter);
117483
+ }
117484
+ function registerRuntimeAdopter(runtime, adopter) {
117485
+ runtimeAdopters.set(runtime, adopter);
117486
+ }
117487
+ function setSessionHostDaemonUrl(url2) {
117488
+ if (url2) daemonUrl = url2.replace(/\/+$/, "");
117489
+ }
117490
+ function sessionHostDaemonUrl() {
117491
+ return daemonUrl;
117492
+ }
117493
+ function waitForAdoption() {
117494
+ return startupGate;
117495
+ }
117496
+ function isAdoptionPending() {
117497
+ return startupPending;
117498
+ }
117499
+ function setStartupGate(started) {
117500
+ const gate = started.then(
117501
+ () => void 0,
117502
+ () => void 0
117503
+ );
117504
+ startupGate = gate;
117505
+ startupPending = true;
117506
+ void gate.then(() => {
117507
+ if (startupGate === gate) startupPending = false;
117508
+ });
117509
+ }
117510
+ function lastAdoption() {
117511
+ return lastResult;
117512
+ }
117513
+ function hostConfig(busy) {
117514
+ const flags = sessionHostFlags();
117515
+ return { noHostMs: busy ? flags.noHostBusyMs : flags.noHostIdleMs, daemonUrl };
117516
+ }
117517
+ function newHostDir() {
117518
+ const root = sessionHostsRoot();
117519
+ if (!root) throw new Error("session hosts have no directory");
117520
+ const id = randomBytes(8).toString("hex");
117521
+ return { id, dir: path13.join(root, id) };
117522
+ }
117523
+ var cachedVersion;
117524
+ function runtimeVersion() {
117525
+ if (cachedVersion !== void 0) return cachedVersion;
117526
+ cachedVersion = null;
117527
+ const here = path13.dirname(fileURLToPath3(import.meta.url));
117528
+ for (const rel of ["../../../../package.json", "../../../package.json"]) {
117529
+ try {
117530
+ const pkg = JSON.parse(fs9.readFileSync(path13.resolve(here, rel), "utf8"));
117531
+ if (pkg.name === "repoburg" && pkg.version) {
117532
+ cachedVersion = pkg.version;
117533
+ break;
117534
+ }
117535
+ } catch {
117536
+ }
117537
+ }
117538
+ return cachedVersion;
117539
+ }
117540
+ function writeHostMeta(dir, meta3) {
117541
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
117542
+ fs9.chmodSync(dir, 448);
117543
+ const tmp = path13.join(dir, "meta.json.tmp");
117544
+ fs9.writeFileSync(tmp, JSON.stringify(meta3, null, 2) + "\n", { mode: 384 });
117545
+ fs9.renameSync(tmp, path13.join(dir, "meta.json"));
117546
+ }
117547
+ function readHostMeta(dir) {
117548
+ try {
117549
+ return JSON.parse(fs9.readFileSync(path13.join(dir, "meta.json"), "utf8"));
117550
+ } catch {
117551
+ return null;
117552
+ }
117553
+ }
117554
+ function insertHostRow(db2, row) {
117555
+ const now = (/* @__PURE__ */ new Date()).toISOString();
117556
+ db2.prepare(
117557
+ `INSERT INTO session_hosts (id, runtime, session_id, entry_key, thread_id, turn_id, replay_offset, external_id, host_pid, command, runtime_version, protocol, generation, created_at, updated_at)
117558
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
117559
+ ).run(
117560
+ row.id,
117561
+ row.runtime,
117562
+ row.session_id,
117563
+ row.entry_key,
117564
+ row.thread_id,
117565
+ row.turn_id ?? null,
117566
+ row.replay_offset ?? 0,
117567
+ row.external_id ?? null,
117568
+ row.host_pid,
117569
+ row.command,
117570
+ row.runtime_version,
117571
+ SESSION_HOST_PROTOCOL,
117572
+ row.generation ?? 0,
117573
+ now,
117574
+ now
117575
+ );
117576
+ }
117577
+ function getHostRow(db2, id) {
117578
+ return db2.prepare("SELECT * FROM session_hosts WHERE id = ?").get(id);
117579
+ }
117580
+ function listHostRows(db2) {
117581
+ return db2.prepare("SELECT * FROM session_hosts ORDER BY created_at").all();
117582
+ }
117583
+ function setHostTurn(db2, id, turnId, replayOffset) {
117584
+ db2.prepare("UPDATE session_hosts SET turn_id = ?, replay_offset = ?, updated_at = ? WHERE id = ?").run(
117585
+ turnId,
117586
+ replayOffset,
117587
+ (/* @__PURE__ */ new Date()).toISOString(),
117588
+ id
117589
+ );
117590
+ }
117591
+ function updateHostRow(db2, id, fields) {
117592
+ const keys = Object.keys(fields);
117593
+ if (keys.length === 0) return;
117594
+ const sets = keys.map((k) => `${k} = ?`).join(", ");
117595
+ db2.prepare(`UPDATE session_hosts SET ${sets}, updated_at = ? WHERE id = ?`).run(
117596
+ ...keys.map((k) => fields[k] ?? null),
117597
+ (/* @__PURE__ */ new Date()).toISOString(),
117598
+ id
117599
+ );
117600
+ }
117601
+ function setHostBackgroundTasks(db2, id, json2) {
117602
+ db2.prepare("UPDATE session_hosts SET background_tasks = ?, updated_at = ? WHERE id = ?").run(json2, (/* @__PURE__ */ new Date()).toISOString(), id);
117603
+ }
117604
+ function deleteHostRow(db2, id) {
117605
+ db2.prepare("DELETE FROM session_hosts WHERE id = ?").run(id);
117606
+ }
117607
+ function forgetHost(id, dir) {
117608
+ try {
117609
+ deleteHostRow(getDb(), id);
117610
+ } catch (err) {
117611
+ console.error(`[session-host] could not delete row ${id}:`, err.message);
117612
+ }
117613
+ if (dir) removeHostDir(dir);
117614
+ }
117615
+ async function shutDownHost(dir, opts = {}) {
117616
+ const graceMs = opts.graceMs ?? 5e3;
117617
+ const verified = await verifiedHostPids(dir);
117618
+ const pids = [verified.childPid, verified.hostPid].filter((p) => !!p);
117619
+ const alive = () => pids.some((p) => isPidAlive(p));
117620
+ if (opts.eof) {
117621
+ try {
117622
+ await signalOrEof(dir, "eof");
117623
+ const eofDeadline = Date.now() + Math.min(graceMs, 2e3);
117624
+ while (alive() && Date.now() < eofDeadline) await sleep(50);
117625
+ } catch {
117626
+ }
117627
+ }
117628
+ try {
117629
+ if (alive()) await signalOrEof(dir, "SIGTERM");
117630
+ } catch {
117631
+ }
117632
+ const deadline = Date.now() + graceMs;
117633
+ while (alive() && Date.now() < deadline) await sleep(50);
117634
+ if (alive()) {
117635
+ for (const pid of pids) {
117636
+ try {
117637
+ process.kill(pid, "SIGKILL");
117638
+ } catch {
117639
+ }
117640
+ }
117641
+ const killDeadline = Date.now() + 2e3;
117642
+ while (alive() && Date.now() < killDeadline) await sleep(50);
117643
+ }
117644
+ }
117645
+ async function signalOrEof(dir, what) {
117646
+ if (what === "eof") await eofHost(dir);
117647
+ else await signalHost(dir, what);
117648
+ }
117649
+ function sleep(ms) {
117650
+ return new Promise((r) => setTimeout(r, ms));
117651
+ }
117652
+ function adoptSessionHosts() {
117653
+ const run = runAdoption();
117654
+ setStartupGate(run);
117655
+ return run;
117656
+ }
117657
+ var ADOPT_CONCURRENCY = 4;
117658
+ async function runAdoption() {
117659
+ const result = emptyResult();
117660
+ lastResult = result;
117661
+ let db2;
117662
+ try {
117663
+ db2 = getDb();
117664
+ } catch {
117665
+ return result;
117666
+ }
117667
+ const flags = sessionHostFlags();
117668
+ if (flags.adoption) {
117669
+ for (const [runtime, adopter] of runtimeAdopters) {
117670
+ try {
117671
+ await adopter(db2, result);
117672
+ } catch (err) {
117673
+ console.error(`[session-host] adoption of ${runtime} turns failed; recovery takes them:`, err.message);
117674
+ }
117675
+ }
117676
+ }
117677
+ const root = sessionHostsRoot();
117678
+ if (root) await adoptHosts(db2, root, flags.adoption, result);
117679
+ if (result.turnIds.size || result.sessionIds.size) {
117680
+ console.log(`[session-host] adopted ${result.sessionIds.size} runtime(s), ${result.turnIds.size} running turn(s)`);
117681
+ }
117682
+ return result;
117683
+ }
117684
+ async function adoptHosts(db2, root, adoption, result) {
117685
+ let entries = [];
117686
+ try {
117687
+ entries = fs9.readdirSync(root);
117688
+ } catch (err) {
117689
+ if (err.code !== "ENOENT") console.error("[session-host] cannot read", root, err.message);
117690
+ }
117691
+ const seen = /* @__PURE__ */ new Set();
117692
+ const queue = [];
117693
+ for (const id of entries) {
117694
+ const dir = path13.join(root, id);
117695
+ try {
117696
+ if (!fs9.statSync(dir).isDirectory()) continue;
117697
+ } catch {
117698
+ continue;
117699
+ }
117700
+ seen.add(id);
117701
+ queue.push({ id, dir });
117702
+ }
117703
+ const worker = async () => {
117704
+ for (let next = queue.shift(); next; next = queue.shift()) {
117705
+ const { id, dir } = next;
117706
+ try {
117707
+ await adoptOne(db2, id, dir, adoption, result);
117708
+ } catch (err) {
117709
+ console.error(`[session-host] adoption of ${id} failed; the turn takes the resume path:`, err.message);
117710
+ await shutDownHost(dir, { eof: endsOnEof(db2, id, dir) }).catch(() => {
117711
+ });
117712
+ forgetHost(id, dir);
117713
+ }
117714
+ }
117715
+ };
117716
+ await Promise.all(Array.from({ length: ADOPT_CONCURRENCY }, worker));
117717
+ for (const row of listHostRows(db2)) {
117718
+ if (!seen.has(row.id)) deleteHostRow(db2, row.id);
117719
+ }
117720
+ }
117721
+ async function adoptOne(db2, id, dir, adoption, result) {
117722
+ const row = getHostRow(db2, id);
117723
+ const meta3 = readHostMeta(dir);
117724
+ let status = null;
117725
+ try {
117726
+ status = await hostStatus(dir, 2e3);
117727
+ } catch (err) {
117728
+ if (!isHostGone(err)) {
117729
+ console.error(`[session-host] ${id} does not answer (${err.message}); shutting it down`);
117730
+ await shutDownHost(dir);
117731
+ forgetHost(id, dir);
117732
+ return;
117733
+ }
117734
+ }
117735
+ if (status?.exited) {
117736
+ const hostPid = status.hostPid;
117737
+ const deadline = Date.now() + 4e3;
117738
+ while (isPidAlive(hostPid) && Date.now() < deadline) await sleep(50);
117739
+ status = null;
117740
+ }
117741
+ const session = row ? db2.prepare("SELECT id FROM sessions WHERE id = ?").get(row.session_id) : void 0;
117742
+ if (!row || !session || !adoption) {
117743
+ const why = !row ? "no DB row" : !session ? "session gone" : "adoption is off";
117744
+ console.log(`[session-host] ${id}: ${why}; shutting it down`);
117745
+ if (status) await shutDownHost(dir, { eof: row?.runtime === "codex" });
117746
+ else await endOrphanedChild(dir);
117747
+ forgetHost(id, dir);
117748
+ return;
117749
+ }
117750
+ const adopter = adopters.get(row.runtime);
117751
+ if (status) {
117752
+ const supported = SUPPORTED_PROTOCOLS.includes(status.v) && (!meta3 || SUPPORTED_PROTOCOLS.includes(meta3.protocol));
117753
+ if (!adopter || !supported || status.lossy) {
117754
+ const why = !adopter ? "no adopter" : !supported ? "unsupported protocol" : `lossy log (${status.lossyReason})`;
117755
+ console.log(`[session-host] ${id}: ${why}; shutting it down, the turn takes the resume path`);
117756
+ await shutDownHost(dir, { eof: row.runtime === "codex" });
117757
+ forgetHost(id, dir);
117758
+ return;
117759
+ }
117760
+ if (process.env.AGENT_PANE_SESSION_HOSTS_FAIL_ADOPT === "1") throw new Error("adoption failure injected");
117761
+ const { turnId, otherTurns } = await adopter.adoptLive(row, dir, status);
117762
+ result.sessionIds.add(row.session_id);
117763
+ result.entries.add(runtimeEntryKey(row.session_id, row.thread_id));
117764
+ if (turnId) result.turnIds.add(turnId);
117765
+ for (const other of otherTurns ?? []) {
117766
+ result.turnIds.add(other.id);
117767
+ result.entries.add(runtimeEntryKey(row.session_id, other.threadId));
117768
+ }
117769
+ return;
117770
+ }
117771
+ await endOrphanedChild(dir);
117772
+ const exit = readHostExit(dir);
117773
+ const log = readHostLog(dir, row.replay_offset);
117774
+ try {
117775
+ if (adopter) await adopter.adoptDead(row, dir, log, exit);
117776
+ } finally {
117777
+ forgetHost(id, dir);
117778
+ }
117779
+ }
117780
+ function endsOnEof(db2, id, dir) {
117781
+ try {
117782
+ return (getHostRow(db2, id)?.runtime ?? readHostMeta(dir)?.runtime) === "codex";
117783
+ } catch {
117784
+ return readHostMeta(dir)?.runtime === "codex";
117785
+ }
117786
+ }
117787
+ async function endOrphanedChild(dir) {
117788
+ if (readHostExit(dir)) return;
117789
+ const { hostPid, childPid } = await verifiedHostPids(dir);
117790
+ if (!childPid || hostPid) return;
117791
+ console.log(`[session-host] ending orphaned runtime process ${childPid} of a dead host`);
117792
+ for (const sig of ["SIGTERM", "SIGKILL"]) {
117793
+ try {
117794
+ process.kill(childPid, sig);
117795
+ } catch {
117796
+ return;
117797
+ }
117798
+ const deadline = Date.now() + 2e3;
117799
+ while (isPidAlive(childPid) && Date.now() < deadline) await sleep(25);
117800
+ if (!isPidAlive(childPid)) return;
117801
+ }
117802
+ }
117803
+ async function shutDownAllHosts() {
117804
+ const root = sessionHostsRoot();
117805
+ if (!root) return 0;
117806
+ let entries = [];
117807
+ try {
117808
+ entries = fs9.readdirSync(root);
117809
+ } catch {
117810
+ return 0;
117811
+ }
117812
+ let count2 = 0;
117813
+ let db2 = null;
117814
+ try {
117815
+ db2 = getDb();
117816
+ } catch {
117817
+ db2 = null;
117818
+ }
117819
+ await Promise.all(
117820
+ entries.map(async (id) => {
117821
+ const dir = path13.join(root, id);
117822
+ const row = db2 ? getHostRow(db2, id) : void 0;
117823
+ try {
117824
+ await shutDownHost(dir, { eof: row?.runtime === "codex" });
117825
+ count2 += 1;
117826
+ } finally {
117827
+ forgetHost(id, dir);
117828
+ }
117829
+ })
117830
+ );
117831
+ return count2;
117832
+ }
117833
+
117834
+ // src/routes/session-hosts.ts
117835
+ async function registerSessionHostRoutes(fastify) {
117836
+ fastify.get("/api/session-hosts/protocol", async () => ({
117837
+ protocols: SUPPORTED_PROTOCOLS,
117838
+ bootId: DAEMON_BOOT_ID
117839
+ }));
117840
+ fastify.get("/api/session-hosts", async () => {
117841
+ const adopted = lastAdoption();
117842
+ return {
117843
+ root: sessionHostsRoot(),
117844
+ flags: sessionHostFlags(),
117845
+ bootId: DAEMON_BOOT_ID,
117846
+ adopted: { sessions: adopted.sessionIds.size, turns: adopted.turnIds.size },
117847
+ hosts: listHostRows(getDb()).map((row) => ({
117848
+ id: row.id,
117849
+ runtime: row.runtime,
117850
+ sessionId: row.session_id,
117851
+ threadId: row.thread_id,
117852
+ turnId: row.turn_id,
117853
+ hostPid: row.host_pid,
117854
+ childPid: row.child_pid,
117855
+ runtimeVersion: row.runtime_version,
117856
+ createdAt: row.created_at
117857
+ }))
117858
+ };
117859
+ });
117860
+ }
117861
+
116938
117862
  // src/codex/item-mapper.ts
116939
117863
  function mapItemData(item) {
116940
117864
  switch (item.type) {
@@ -116992,6 +117916,421 @@ function getItemStatus(item) {
116992
117916
  return "completed";
116993
117917
  }
116994
117918
 
117919
+ // src/codex/codex-host.ts
117920
+ import { EventEmitter as EventEmitter4 } from "node:events";
117921
+ import { PassThrough as PassThrough2, Writable as Writable2 } from "node:stream";
117922
+
117923
+ // src/session-host/spawned-process.ts
117924
+ import { spawn as spawn5 } from "node:child_process";
117925
+ import { EventEmitter as EventEmitter3 } from "node:events";
117926
+ import { PassThrough, Writable } from "node:stream";
117927
+ var ORPHAN_TERM_WAIT_MS = 3e3;
117928
+ var EOF_DELAY_MS = 100;
117929
+ var HostedProcess = class extends EventEmitter3 {
117930
+ stdin;
117931
+ stdout;
117932
+ pid;
117933
+ killed = false;
117934
+ exitCode = null;
117935
+ signalCode = null;
117936
+ /** Logical offset after the last stdout byte delivered to `stdout`. */
117937
+ consumed;
117938
+ /** Logical offset after the last complete line delivered to `stdout`. */
117939
+ consumedLineEnd;
117940
+ /** Resolves once attached (or running directly); rejects when neither works. */
117941
+ ready;
117942
+ /** Set when 'exit' is emitted. */
117943
+ endReason = null;
117944
+ dir;
117945
+ opts;
117946
+ attachment = null;
117947
+ direct = null;
117948
+ detaching = false;
117949
+ exited = false;
117950
+ stdinEnded = false;
117951
+ eofSent = false;
117952
+ partial = [];
117953
+ queued = [];
117954
+ replayEnd = null;
117955
+ reconnecting = false;
117956
+ constructor(opts) {
117957
+ super();
117958
+ this.opts = opts;
117959
+ this.dir = opts.dir;
117960
+ this.consumed = opts.start ? 0 : opts.after ?? 0;
117961
+ this.consumedLineEnd = this.consumed;
117962
+ this.stdout = new PassThrough();
117963
+ this.stdin = new Writable({
117964
+ write: (chunk, _enc, cb) => {
117965
+ this.writeStdin(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
117966
+ cb();
117967
+ },
117968
+ final: (cb) => {
117969
+ this.endStdin();
117970
+ cb();
117971
+ }
117972
+ });
117973
+ this.ready = this.firstConnect();
117974
+ this.ready.catch(() => {
117975
+ });
117976
+ }
117977
+ /** True while the process runs behind a host (false after a direct fallback). */
117978
+ get hosted() {
117979
+ return this.direct === null;
117980
+ }
117981
+ /** The daemon goes away: leave the child running. */
117982
+ detach() {
117983
+ if (this.exited) return;
117984
+ this.detaching = true;
117985
+ if (this.direct) {
117986
+ return;
117987
+ }
117988
+ const att = this.attachment;
117989
+ this.attachment = null;
117990
+ att?.close();
117991
+ this.finishExit(0, null, "detached");
117992
+ }
117993
+ kill(signal = "SIGTERM") {
117994
+ if (this.exited) return false;
117995
+ if (this.direct) {
117996
+ this.killed = true;
117997
+ return this.direct.kill(signal);
117998
+ }
117999
+ if (this.detaching) return true;
118000
+ this.killed = true;
118001
+ signalHost(this.dir, signal).catch(() => {
118002
+ });
118003
+ return true;
118004
+ }
118005
+ // ---------------------------------------------------------------------------
118006
+ async firstConnect() {
118007
+ const start = this.opts.start;
118008
+ if (start) {
118009
+ try {
118010
+ startHost({ dir: this.dir, command: start.command, args: start.args, cwd: start.cwd, env: start.env, config: start.config });
118011
+ await waitForHost(this.dir);
118012
+ } catch (err) {
118013
+ await this.abandonHost();
118014
+ if (this.detaching) return;
118015
+ this.runDirect(start, err.message);
118016
+ return;
118017
+ }
118018
+ }
118019
+ try {
118020
+ await this.connect(false);
118021
+ } catch (err) {
118022
+ if (start) {
118023
+ await this.abandonHost();
118024
+ if (this.detaching) return;
118025
+ this.runDirect(start, err.message);
118026
+ return;
118027
+ }
118028
+ this.fail(err);
118029
+ throw err;
118030
+ }
118031
+ }
118032
+ async connect(reattach) {
118033
+ const att = await attachHost(this.dir, this.consumed);
118034
+ if (this.detaching || this.exited) {
118035
+ att.close();
118036
+ return;
118037
+ }
118038
+ this.attachment = att;
118039
+ this.pid = att.header.child.pid ?? void 0;
118040
+ if (!reattach && this.opts.replayMarker && !this.opts.start) {
118041
+ this.replayEnd = att.header.end;
118042
+ if (this.replayEnd <= this.consumed) this.pushMarker();
118043
+ }
118044
+ att.on("data", (chunk) => {
118045
+ if (this.attachment === att) this.onStdout(chunk);
118046
+ });
118047
+ att.on("error", () => {
118048
+ });
118049
+ att.on("close", () => {
118050
+ if (this.attachment !== att) return;
118051
+ this.attachment = null;
118052
+ void this.onClose();
118053
+ });
118054
+ this.opts.onAttach?.(att.header, reattach);
118055
+ for (const lines of this.queued.splice(0)) att.write(lines);
118056
+ if (this.stdinEnded) this.sendEof();
118057
+ }
118058
+ onStdout(chunk) {
118059
+ if (this.replayEnd === null) {
118060
+ this.push(chunk);
118061
+ return;
118062
+ }
118063
+ const from = Math.max(0, this.replayEnd - 1 - this.consumed);
118064
+ const atBoundary = this.consumed >= this.replayEnd && this.consumed === this.consumedLineEnd;
118065
+ if (atBoundary) {
118066
+ this.pushMarker();
118067
+ this.push(chunk);
118068
+ return;
118069
+ }
118070
+ const idx = chunk.indexOf(10, from);
118071
+ if (idx === -1) {
118072
+ this.push(chunk);
118073
+ return;
118074
+ }
118075
+ this.push(chunk.subarray(0, idx + 1));
118076
+ this.pushMarker();
118077
+ if (idx + 1 < chunk.length) this.push(chunk.subarray(idx + 1));
118078
+ }
118079
+ push(buf) {
118080
+ if (buf.length === 0) return;
118081
+ const nl = buf.lastIndexOf(10);
118082
+ if (nl !== -1) this.consumedLineEnd = this.consumed + nl + 1;
118083
+ this.consumed += buf.length;
118084
+ if (!this.stdout.write(buf)) {
118085
+ const att = this.attachment;
118086
+ if (att) {
118087
+ att.socket.pause();
118088
+ this.stdout.once("drain", () => att.socket.resume());
118089
+ }
118090
+ }
118091
+ }
118092
+ pushMarker() {
118093
+ this.replayEnd = null;
118094
+ if (this.opts.replayMarker) this.stdout.write(this.opts.replayMarker + "\n");
118095
+ }
118096
+ writeStdin(chunk) {
118097
+ if (this.exited || this.stdinEnded) return;
118098
+ if (this.direct) {
118099
+ this.direct.stdin?.write(chunk);
118100
+ return;
118101
+ }
118102
+ const nl = chunk.lastIndexOf(10);
118103
+ if (nl === -1) {
118104
+ this.partial.push(chunk);
118105
+ return;
118106
+ }
118107
+ this.partial.push(chunk.subarray(0, nl + 1));
118108
+ const lines = Buffer.concat(this.partial);
118109
+ this.partial = nl + 1 < chunk.length ? [Buffer.from(chunk.subarray(nl + 1))] : [];
118110
+ if (this.attachment) this.attachment.write(lines);
118111
+ else this.queued.push(lines);
118112
+ }
118113
+ endStdin() {
118114
+ if (this.stdinEnded) return;
118115
+ this.stdinEnded = true;
118116
+ if (this.direct) {
118117
+ this.direct.stdin?.end();
118118
+ return;
118119
+ }
118120
+ if (this.detaching || this.exited) return;
118121
+ if (this.attachment) this.sendEof();
118122
+ }
118123
+ /** Ask the host to close the child's stdin, after the lines written so far
118124
+ * had time to arrive on the attach socket. */
118125
+ sendEof() {
118126
+ if (this.eofSent || this.detaching) return;
118127
+ this.eofSent = true;
118128
+ const att = this.attachment;
118129
+ const send2 = () => {
118130
+ setTimeout(() => {
118131
+ if (this.detaching || this.exited) return;
118132
+ eofHost(this.dir).catch(() => {
118133
+ });
118134
+ }, EOF_DELAY_MS).unref();
118135
+ };
118136
+ if (att) att.write("", () => send2());
118137
+ else send2();
118138
+ }
118139
+ async onClose() {
118140
+ if (this.exited || this.detaching || this.reconnecting) return;
118141
+ if (this.settleFromExitFile()) return;
118142
+ this.reconnecting = true;
118143
+ try {
118144
+ const deadline = Date.now() + (this.opts.reattachWindowMs ?? 5e3);
118145
+ while (Date.now() < deadline && !this.detaching && !this.exited) {
118146
+ let gone = false;
118147
+ try {
118148
+ const status = await hostStatus(this.dir, 1e3);
118149
+ if (!status.exited && !status.hostAttached) {
118150
+ await this.connect(true);
118151
+ return;
118152
+ }
118153
+ if (status.hostAttached) {
118154
+ console.error(`[session-host] ${this.dir}: another daemon is attached; giving the host up`);
118155
+ this.finishExit(null, null, "attached-elsewhere");
118156
+ return;
118157
+ }
118158
+ } catch (err) {
118159
+ gone = isHostGone(err);
118160
+ }
118161
+ if (this.settleFromExitFile()) return;
118162
+ if (gone) break;
118163
+ await new Promise((r) => setTimeout(r, 100));
118164
+ }
118165
+ if (this.detaching || this.exited) return;
118166
+ if (this.settleFromExitFile()) return;
118167
+ await this.endOrphan();
118168
+ } finally {
118169
+ this.reconnecting = false;
118170
+ }
118171
+ }
118172
+ /** The child exited and the host is gone or going: deliver what the log
118173
+ * holds past `consumed`, then emit 'exit' with the real code. */
118174
+ settleFromExitFile() {
118175
+ const exit = readHostExit(this.dir);
118176
+ if (!exit) return false;
118177
+ const rest = readHostLog(this.dir, this.consumed);
118178
+ if (rest && rest.length > 0) this.onStdout(rest);
118179
+ if (this.replayEnd !== null) this.pushMarker();
118180
+ this.finishExit(exit.code, exit.signal ?? null, "exit");
118181
+ return true;
118182
+ }
118183
+ /** The host died with its child still running: end the child here. */
118184
+ async endOrphan() {
118185
+ const pid = this.pid ?? readHostChild(this.dir)?.pid ?? void 0;
118186
+ let detail = "session host died";
118187
+ if (pid && isPidAlive(pid)) {
118188
+ detail = `session host died; ended its orphaned child ${pid}`;
118189
+ try {
118190
+ process.kill(pid, "SIGTERM");
118191
+ } catch {
118192
+ }
118193
+ const deadline = Date.now() + ORPHAN_TERM_WAIT_MS;
118194
+ while (isPidAlive(pid) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
118195
+ if (isPidAlive(pid)) {
118196
+ try {
118197
+ process.kill(pid, "SIGKILL");
118198
+ } catch {
118199
+ }
118200
+ const killDeadline = Date.now() + ORPHAN_TERM_WAIT_MS;
118201
+ while (isPidAlive(pid) && Date.now() < killDeadline) await new Promise((r) => setTimeout(r, 50));
118202
+ }
118203
+ }
118204
+ console.error(`[session-host] ${this.dir}: ${detail}`);
118205
+ this.opts.onHostLost?.(detail);
118206
+ this.finishExit(null, "SIGKILL", "host-lost");
118207
+ }
118208
+ /** Kill a host that did not come up, and its child, before running directly. */
118209
+ async abandonHost() {
118210
+ const info = readHostChild(this.dir);
118211
+ for (const pid of [info?.hostPid, info?.pid]) {
118212
+ if (pid && isPidAlive(pid)) {
118213
+ try {
118214
+ process.kill(pid, "SIGKILL");
118215
+ } catch {
118216
+ }
118217
+ }
118218
+ }
118219
+ }
118220
+ runDirect(start, reason) {
118221
+ console.error(`[session-host] host did not start (${reason}); running the process directly`);
118222
+ const child = spawn5(start.command, start.args, { cwd: start.cwd, env: start.env, stdio: ["pipe", "pipe", "pipe"] });
118223
+ this.direct = child;
118224
+ this.pid = child.pid;
118225
+ child.stdout?.on("data", (chunk) => this.push(chunk));
118226
+ child.stderr?.on("data", () => {
118227
+ });
118228
+ child.stdin?.on("error", () => {
118229
+ });
118230
+ child.on("error", (err) => this.fail(err));
118231
+ child.on("exit", (code, signal) => this.finishExit(code, signal, "exit"));
118232
+ for (const lines of this.queued.splice(0)) child.stdin?.write(lines);
118233
+ if (this.partial.length) child.stdin?.write(Buffer.concat(this.partial.splice(0)));
118234
+ if (this.stdinEnded) child.stdin?.end();
118235
+ this.opts.onDirect?.(child.pid, reason);
118236
+ }
118237
+ fail(err) {
118238
+ if (this.exited) return;
118239
+ if (this.listenerCount("error") > 0) this.emit("error", err);
118240
+ this.finishExit(1, null, "error");
118241
+ }
118242
+ finishExit(code, signal, reason) {
118243
+ if (this.exited) return;
118244
+ this.exited = true;
118245
+ this.endReason = reason;
118246
+ this.exitCode = code;
118247
+ this.signalCode = signal;
118248
+ this.emit("exit", code, signal);
118249
+ this.stdout.end();
118250
+ }
118251
+ };
118252
+
118253
+ // src/codex/codex-host.ts
118254
+ var IDS_PER_GENERATION = 1e9;
118255
+ function requestIdBase(generation) {
118256
+ return generation * IDS_PER_GENERATION + 1;
118257
+ }
118258
+ function startCodexHost(db2, start) {
118259
+ const { id, dir } = newHostDir();
118260
+ const version2 = runtimeVersion();
118261
+ try {
118262
+ writeHostMeta(dir, {
118263
+ protocol: SESSION_HOST_PROTOCOL,
118264
+ hostId: id,
118265
+ runtime: "codex",
118266
+ entryKey: start.sessionId,
118267
+ sessionId: start.sessionId,
118268
+ threadId: null,
118269
+ command: start.command,
118270
+ runtimeVersion: version2,
118271
+ daemonUrl: sessionHostDaemonUrl(),
118272
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
118273
+ });
118274
+ insertHostRow(db2, {
118275
+ id,
118276
+ runtime: "codex",
118277
+ session_id: start.sessionId,
118278
+ entry_key: start.sessionId,
118279
+ thread_id: null,
118280
+ command: start.command,
118281
+ runtime_version: version2,
118282
+ host_pid: null
118283
+ });
118284
+ } catch (err) {
118285
+ forgetHost(id, dir);
118286
+ throw err;
118287
+ }
118288
+ const proc = new HostedProcess({
118289
+ dir,
118290
+ start: { command: start.command, args: start.args, cwd: start.cwd, env: start.env, config: hostConfig(true) },
118291
+ onAttach: (header) => {
118292
+ try {
118293
+ updateHostRow(db2, id, { host_pid: header.hostPid, child_pid: header.child.pid });
118294
+ } catch {
118295
+ }
118296
+ },
118297
+ onDirect: (pid) => {
118298
+ forgetHost(id, dir);
118299
+ start.onDirect(pid);
118300
+ }
118301
+ });
118302
+ return { id, dir, proc, runtimeVersion: version2 };
118303
+ }
118304
+ async function releaseCodexHost(binding) {
118305
+ const proc = binding.proc;
118306
+ if (proc.endReason === "detached" || proc.endReason === "attached-elsewhere") return;
118307
+ if (proc.hosted) {
118308
+ try {
118309
+ await shutDownHost(binding.dir, { graceMs: 3e3, eof: true });
118310
+ } catch (err) {
118311
+ console.error(`[codex] could not stop session host ${binding.id}:`, err.message);
118312
+ }
118313
+ }
118314
+ forgetHost(binding.id, binding.dir);
118315
+ }
118316
+ var LoggedAppServer = class extends EventEmitter4 {
118317
+ stdin = new Writable2({
118318
+ write: (_chunk, _enc, cb) => cb()
118319
+ });
118320
+ stdout = new PassThrough2();
118321
+ pid = void 0;
118322
+ kill() {
118323
+ return false;
118324
+ }
118325
+ /** Feed the log; resolves once the client has read all of it. */
118326
+ play(log) {
118327
+ return new Promise((resolve) => {
118328
+ this.stdout.once("end", () => resolve());
118329
+ this.stdout.end(log);
118330
+ });
118331
+ }
118332
+ };
118333
+
116995
118334
  // src/codex/app-server-types.ts
116996
118335
  function mapTokenUsage(data) {
116997
118336
  return {
@@ -117004,23 +118343,23 @@ function mapTokenUsage(data) {
117004
118343
  }
117005
118344
 
117006
118345
  // src/apps/register-mcp.ts
117007
- import fs7 from "node:fs";
117008
- import path11 from "node:path";
117009
- import { fileURLToPath as fileURLToPath2 } from "node:url";
118346
+ import fs10 from "node:fs";
118347
+ import path14 from "node:path";
118348
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
117010
118349
  var MCP_SERVER_NAME = "agentpane-miniapps";
117011
118350
  function panePublicUrl() {
117012
118351
  return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
117013
118352
  }
117014
118353
  function stdioScriptPath() {
117015
- const here = path11.dirname(fileURLToPath2(import.meta.url));
118354
+ const here = path14.dirname(fileURLToPath4(import.meta.url));
117016
118355
  const candidates = [
117017
- path11.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
118356
+ path14.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
117018
118357
  // src/apps/ → backend/scripts
117019
- path11.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
118358
+ path14.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
117020
118359
  // dist bundle → backend/scripts
117021
118360
  ];
117022
118361
  for (const candidate of candidates) {
117023
- if (fs7.existsSync(candidate)) return candidate;
118362
+ if (fs10.existsSync(candidate)) return candidate;
117024
118363
  }
117025
118364
  return null;
117026
118365
  }
@@ -117101,12 +118440,12 @@ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
117101
118440
  }
117102
118441
 
117103
118442
  // src/claude/cli-orphans.ts
117104
- import { execFile as execFile3 } from "node:child_process";
118443
+ import { execFile as execFile4 } from "node:child_process";
117105
118444
  var TERM_GRACE_MS = 2e3;
117106
118445
  var POLL_MS = 100;
117107
118446
  function inspectProcess(pid) {
117108
118447
  return new Promise((resolve) => {
117109
- execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
118448
+ execFile4("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
117110
118449
  const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
117111
118450
  resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
117112
118451
  });
@@ -117114,7 +118453,7 @@ function inspectProcess(pid) {
117114
118453
  }
117115
118454
  function listDescendants(pid) {
117116
118455
  return new Promise((resolve) => {
117117
- execFile3("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
118456
+ execFile4("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
117118
118457
  if (err) {
117119
118458
  resolve([]);
117120
118459
  return;
@@ -117307,17 +118646,33 @@ function getOrCreateThread(session) {
117307
118646
  return started;
117308
118647
  }
117309
118648
  async function startThread(session) {
118649
+ if (isAdoptionPending()) {
118650
+ await waitForAdoption();
118651
+ const adopted = sessionMap.get(session.id);
118652
+ if (adopted && !adopted.client.isClosed()) return adopted;
118653
+ }
117310
118654
  const cwd = session.cwd ?? process.cwd();
117311
- const client = new AppServerClient(appServerClientOptions(session, cwd));
117312
- const entry = {
118655
+ const options = appServerClientOptions(session, cwd);
118656
+ let entry = null;
118657
+ const host = hostFor(session.id, cwd, options, (pid) => {
118658
+ if (!entry) return;
118659
+ entry.pid = pid;
118660
+ trackProcess(pid, session.id);
118661
+ });
118662
+ const client = new AppServerClient(host ? { ...options, process: host.proc } : options);
118663
+ entry = {
117313
118664
  sessionId: session.id,
117314
118665
  client,
117315
- pid: client.pid,
118666
+ // A hosted app-server has no cli_processes row: its host supervises it.
118667
+ pid: host ? void 0 : client.pid,
117316
118668
  threadId: "",
117317
118669
  turns: [],
117318
118670
  ended: /* @__PURE__ */ new Map(),
117319
118671
  resumedTurnIds: null,
117320
- closing: null
118672
+ closing: null,
118673
+ host,
118674
+ replaying: false,
118675
+ retireWhenIdle: null
117321
118676
  };
117322
118677
  trackProcess(entry.pid, session.id);
117323
118678
  listen(entry);
@@ -117340,6 +118695,7 @@ async function startThread(session) {
117340
118695
  });
117341
118696
  entry.threadId = result.thread.id;
117342
118697
  entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
118698
+ noteHostThread(entry);
117343
118699
  } else {
117344
118700
  const result = await client.request("thread/start", {
117345
118701
  cwd,
@@ -117356,6 +118712,7 @@ async function startThread(session) {
117356
118712
  now,
117357
118713
  session.id
117358
118714
  );
118715
+ noteHostThread(entry);
117359
118716
  }
117360
118717
  } catch (err) {
117361
118718
  void retireEntry(entry, "keep");
@@ -117380,12 +118737,16 @@ function retireEntry(entry, left, error51 = "App-server closed") {
117380
118737
  }
117381
118738
  }
117382
118739
  entry.closing = entry.client.close().catch(() => {
117383
- }).finally(() => untrackProcess(entry.pid));
118740
+ }).finally(async () => {
118741
+ untrackProcess(entry.pid);
118742
+ if (entry.host) await releaseCodexHost(entry.host);
118743
+ });
117384
118744
  return entry.closing;
117385
118745
  }
117386
118746
  function onClientClosed(entry, reason) {
117387
118747
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
117388
118748
  untrackProcess(entry.pid);
118749
+ if (entry.host && !entry.closing) void releaseCodexHost(entry.host);
117389
118750
  if (entry.closing || entry.turns.length === 0) return;
117390
118751
  let db2;
117391
118752
  try {
@@ -117412,6 +118773,8 @@ function endTurn(entry, active) {
117412
118773
  active.done = true;
117413
118774
  entry.turns = entry.turns.filter((t) => t !== active);
117414
118775
  rememberEnded(entry, active);
118776
+ settleHostTurn(entry);
118777
+ maybeRetire(entry);
117415
118778
  }
117416
118779
  function rememberEnded(entry, active) {
117417
118780
  if (!active.codexId) return;
@@ -117425,6 +118788,10 @@ function liveTurnsOf(entry, codexId) {
117425
118788
  const waiting = entry.turns.find((t) => t.codexId === null);
117426
118789
  if (!waiting) return [];
117427
118790
  waiting.codexId = codexId;
118791
+ try {
118792
+ getDb().prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ? AND external_turn_id IS NULL").run(codexId, (/* @__PURE__ */ new Date()).toISOString(), waiting.id);
118793
+ } catch {
118794
+ }
117428
118795
  return [waiting];
117429
118796
  }
117430
118797
  function noteContinued(active) {
@@ -117530,12 +118897,9 @@ function onAgentMessageDelta(entry, p) {
117530
118897
  const [live] = liveTurnsOf(entry, p.turnId);
117531
118898
  if (!live) return;
117532
118899
  noteContinued(live);
117533
- broadcast("item:delta", {
117534
- sessionId: entry.sessionId,
117535
- turnId: live.id,
117536
- itemId: p.itemId,
117537
- delta: p.delta
117538
- });
118900
+ const payload = { sessionId: entry.sessionId, turnId: live.id, itemId: p.itemId, delta: p.delta };
118901
+ if (entry.replaying) noteDelta(payload);
118902
+ else broadcast("item:delta", payload);
117539
118903
  }
117540
118904
  function onTurnCompleted(entry, p) {
117541
118905
  const db2 = getDb();
@@ -117612,9 +118976,11 @@ async function runTurn(session, turn, entry, input, resume) {
117612
118976
  resolveStarted = resolve;
117613
118977
  }),
117614
118978
  done: false,
117615
- resuming: resume
118979
+ resuming: resume,
118980
+ hostOffset: null
117616
118981
  };
117617
118982
  entry.turns.push(active);
118983
+ bindHostTurn(entry, active);
117618
118984
  try {
117619
118985
  const result = await entry.client.request("turn/start", {
117620
118986
  threadId: entry.threadId,
@@ -117984,6 +119350,10 @@ async function shutdown() {
117984
119350
  }
117985
119351
  const closing = [closeSharedAppServer()];
117986
119352
  for (const entry of [...sessionMap.values()]) {
119353
+ if (entry.host?.proc.hosted && !entry.closing) {
119354
+ detachEntry(entry);
119355
+ continue;
119356
+ }
117987
119357
  for (const active of [...entry.turns]) {
117988
119358
  if (active.discussionThreadId) continue;
117989
119359
  endTurn(entry, active);
@@ -118013,6 +119383,222 @@ async function resumeInterruptedTurn(session, turn, _opts) {
118013
119383
  const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
118014
119384
  await runTurn(session, turn, entry, input, true);
118015
119385
  }
119386
+ function hostFor(sessionId, cwd, options, onDirect) {
119387
+ if (!hostsEnabledFor("codex")) return null;
119388
+ try {
119389
+ const { command, args } = appServerCommand(options);
119390
+ return startCodexHost(getDb(), { sessionId, cwd, command, args, env: { ...process.env }, onDirect });
119391
+ } catch (err) {
119392
+ console.error(`[codex] no session host for ${sessionId} (${err.message}); running the app-server directly`);
119393
+ return null;
119394
+ }
119395
+ }
119396
+ function isCurrent(entry) {
119397
+ return sessionMap.get(entry.sessionId) === entry && !entry.closing && !entry.client.isClosed();
119398
+ }
119399
+ function noteHostThread(entry) {
119400
+ if (!entry.host?.proc.hosted) return;
119401
+ try {
119402
+ updateHostRow(getDb(), entry.host.id, { external_id: entry.threadId });
119403
+ } catch {
119404
+ }
119405
+ }
119406
+ function refreshHostLimit(entry) {
119407
+ const host = entry.host;
119408
+ if (!host?.proc.hosted) return;
119409
+ const flags = sessionHostFlags();
119410
+ void limitHost(host.dir, entry.turns.length > 0 ? flags.noHostBusyMs : flags.noHostIdleMs).catch(() => {
119411
+ });
119412
+ }
119413
+ function bindHostTurn(entry, active) {
119414
+ const host = entry.host;
119415
+ if (!host?.proc.hosted || !isCurrent(entry)) return;
119416
+ active.hostOffset = host.proc.consumedLineEnd;
119417
+ if (entry.turns.length > 1) {
119418
+ refreshHostLimit(entry);
119419
+ return;
119420
+ }
119421
+ try {
119422
+ setHostTurn(getDb(), host.id, active.id, active.hostOffset);
119423
+ } catch (err) {
119424
+ console.error(`[codex] could not bind turn ${active.id} to its session host:`, err.message);
119425
+ }
119426
+ void ackHost(host.dir, active.hostOffset).catch(() => {
119427
+ });
119428
+ refreshHostLimit(entry);
119429
+ }
119430
+ function settleHostTurn(entry) {
119431
+ const host = entry.host;
119432
+ if (!host?.proc.hosted || !isCurrent(entry) || entry.replaying) return;
119433
+ const oldest = entry.turns.find((t) => t.hostOffset !== null);
119434
+ const upto = oldest?.hostOffset ?? host.proc.consumedLineEnd;
119435
+ try {
119436
+ setHostTurn(getDb(), host.id, oldest?.id ?? null, upto);
119437
+ } catch {
119438
+ }
119439
+ void ackHost(host.dir, upto).catch(() => {
119440
+ });
119441
+ refreshHostLimit(entry);
119442
+ }
119443
+ function maybeRetire(entry) {
119444
+ const why = entry.retireWhenIdle;
119445
+ if (!why || entry.replaying || entry.turns.length > 0 || !isCurrent(entry)) return;
119446
+ console.log(`[codex] closing the idle app-server of session ${entry.sessionId} (${why}); the next prompt starts a new one`);
119447
+ void retireEntry(entry, "keep");
119448
+ }
119449
+ function detachEntry(entry) {
119450
+ if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
119451
+ entry.closing = Promise.resolve();
119452
+ entry.client.detach();
119453
+ entry.host?.proc.detach();
119454
+ }
119455
+ function runningTurns(db2, sessionId) {
119456
+ return db2.prepare(
119457
+ "SELECT id, thread_id, external_turn_id, resume_state FROM turns WHERE session_id = ? AND status = 'running' ORDER BY created_at, rowid"
119458
+ ).all(sessionId);
119459
+ }
119460
+ function adoptedEntry(db2, session, threadId, client, host) {
119461
+ const turns = runningTurns(db2, session.id).map(
119462
+ (row) => ({
119463
+ id: row.id,
119464
+ discussionThreadId: row.thread_id,
119465
+ codexId: row.external_turn_id,
119466
+ started: Promise.resolve(row.external_turn_id),
119467
+ done: false,
119468
+ resuming: row.resume_state === "resuming",
119469
+ hostOffset: null
119470
+ })
119471
+ );
119472
+ const ended = /* @__PURE__ */ new Map();
119473
+ const endedRows = db2.prepare(
119474
+ "SELECT id, external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL AND status != 'running' ORDER BY created_at DESC, rowid DESC LIMIT ?"
119475
+ ).all(session.id, ENDED_TURNS_KEPT);
119476
+ for (const row of endedRows.reverse()) ended.set(row.external_turn_id, row.id);
119477
+ const known = db2.prepare("SELECT external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL").all(session.id);
119478
+ return {
119479
+ sessionId: session.id,
119480
+ client,
119481
+ pid: void 0,
119482
+ threadId,
119483
+ turns,
119484
+ ended,
119485
+ // A turn resumed on this app-server later continues with the continue
119486
+ // prompt when Codex has it.
119487
+ resumedTurnIds: new Set(known.map((row) => row.external_turn_id)),
119488
+ closing: null,
119489
+ host,
119490
+ replaying: true,
119491
+ retireWhenIdle: null
119492
+ };
119493
+ }
119494
+ var REPLAY_WAIT_MS = 3e4;
119495
+ function replayDone(client, what) {
119496
+ if (!client.replaying || client.isClosed()) return Promise.resolve();
119497
+ return new Promise((resolve) => {
119498
+ const done = () => {
119499
+ clearTimeout(timer2);
119500
+ client.events.off("replayDone", done);
119501
+ client.events.off("closed", done);
119502
+ resolve();
119503
+ };
119504
+ const timer2 = setTimeout(() => {
119505
+ console.error(`[codex] the replay of ${what} takes long; startup goes on`);
119506
+ done();
119507
+ }, REPLAY_WAIT_MS);
119508
+ timer2.unref?.();
119509
+ client.events.once("replayDone", done);
119510
+ client.events.once("closed", done);
119511
+ });
119512
+ }
119513
+ function describeExit(exit) {
119514
+ if (!exit) return "the session host died with its app-server";
119515
+ if (exit.error) return `App-server process could not start: ${exit.error}`;
119516
+ if (exit.signal) return `App-server process exited (signal ${exit.signal})`;
119517
+ return `App-server process exited (code ${exit.code})`;
119518
+ }
119519
+ var codexHostAdopter = {
119520
+ runtime: "codex",
119521
+ async adoptLive(row, dir) {
119522
+ const db2 = getDb();
119523
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
119524
+ if (!session || session.runtime_type !== "codex") throw new Error("the session is not a Codex session any more");
119525
+ if (sessionMap.has(session.id)) throw new Error(`an app-server already runs for session ${session.id}`);
119526
+ const threadId = row.external_id ?? session.external_thread_id;
119527
+ if (!threadId) throw new Error("the app-server has no Codex thread");
119528
+ const generation = row.generation + 1;
119529
+ updateHostRow(db2, row.id, { generation });
119530
+ const proc = new HostedProcess({
119531
+ dir,
119532
+ after: row.replay_offset,
119533
+ replayMarker: REPLAY_MARKER,
119534
+ onAttach: (header) => {
119535
+ try {
119536
+ updateHostRow(getDb(), row.id, { host_pid: header.hostPid, child_pid: header.child.pid });
119537
+ } catch {
119538
+ }
119539
+ }
119540
+ });
119541
+ await proc.ready;
119542
+ forgetStreams(session.id);
119543
+ const client = new AppServerClient({
119544
+ cwd: session.cwd ?? process.cwd(),
119545
+ process: proc,
119546
+ firstRequestId: requestIdBase(generation),
119547
+ replaying: true
119548
+ });
119549
+ const host = { id: row.id, dir, proc, runtimeVersion: row.runtime_version };
119550
+ const entry = adoptedEntry(db2, session, threadId, client, host);
119551
+ const version2 = runtimeVersion();
119552
+ entry.retireWhenIdle = !sessionHostFlags().codex ? "session hosts are off for Codex" : row.runtime_version !== version2 ? `started by runtime ${row.runtime_version ?? "unknown"}, this is ${version2 ?? "unknown"}` : null;
119553
+ sessionMap.set(session.id, entry);
119554
+ listen(entry);
119555
+ if (session.origin_app_id) autoApproveToolUserInput(client);
119556
+ await replayDone(client, `session ${session.id}`);
119557
+ entry.replaying = false;
119558
+ if (!isCurrent(entry)) {
119559
+ return { turnId: null };
119560
+ }
119561
+ for (const active of entry.turns) active.hostOffset = row.replay_offset;
119562
+ settleHostTurn(entry);
119563
+ recomputeSessionRunning(db2, session.id);
119564
+ broadcast("session:resync", { sessionId: session.id });
119565
+ resendStreams(session.id);
119566
+ const running = entry.turns.map((t) => ({ id: t.id, threadId: t.discussionThreadId }));
119567
+ console.log(
119568
+ `[codex] adopted the app-server of session ${session.id} (pid ${proc.pid ?? "?"})${running.length ? `, ${running.length} turn(s) go on` : ""}${entry.retireWhenIdle ? `; it closes once idle: ${entry.retireWhenIdle}` : ""}`
119569
+ );
119570
+ maybeRetire(entry);
119571
+ return { turnId: running[0]?.id ?? null, otherTurns: running.slice(1) };
119572
+ },
119573
+ async adoptDead(row, _dir, log, exit) {
119574
+ const db2 = getDb();
119575
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
119576
+ if (!session || session.runtime_type !== "codex") return;
119577
+ const detail = describeExit(exit);
119578
+ const threadId = row.external_id ?? session.external_thread_id;
119579
+ console.log(`[codex] the app-server of session ${session.id} ended with no daemon attached (${detail}); replaying its log`);
119580
+ if (log && log.length > 0 && threadId) {
119581
+ const logged = new LoggedAppServer();
119582
+ const client = new AppServerClient({ cwd: session.cwd ?? process.cwd(), process: logged, replaying: true });
119583
+ const entry = adoptedEntry(db2, session, threadId, client, null);
119584
+ listen(entry);
119585
+ forgetStreams(session.id);
119586
+ try {
119587
+ await logged.play(log);
119588
+ } finally {
119589
+ client.detach();
119590
+ forgetStreams(session.id);
119591
+ }
119592
+ broadcast("session:resync", { sessionId: session.id });
119593
+ }
119594
+ for (const turn of runningTurns(db2, session.id)) {
119595
+ if (turn.thread_id) continue;
119596
+ failOpenItems(db2, session.id, turn.id);
119597
+ markTurnInterrupted(db2, turn.id, "process_exit", { detail, notify: false });
119598
+ }
119599
+ }
119600
+ };
119601
+ registerHostAdopter(codexHostAdopter);
118016
119602
  var codexProvider = {
118017
119603
  startTurn: startTurn2,
118018
119604
  interruptTurn,
@@ -118283,6 +119869,22 @@ function recordApiUsage(entry, sessionId, db2, apiMessageId, usage) {
118283
119869
  ctx.seq++;
118284
119870
  publish(entry, sessionId, db2);
118285
119871
  }
119872
+ function restoreContext(entry, stored) {
119873
+ if (entry.threadId || !stored) return;
119874
+ let saved;
119875
+ try {
119876
+ saved = JSON.parse(stored);
119877
+ } catch {
119878
+ return;
119879
+ }
119880
+ if (typeof saved.totalTokens !== "number" || typeof saved.contextWindow !== "number") return;
119881
+ const ctx = counterOf(entry);
119882
+ ctx.tokens = saved.totalTokens;
119883
+ ctx.measured = true;
119884
+ ctx.window = saved.contextWindow;
119885
+ ctx.autoCompactThreshold = typeof saved.autoCompactThreshold === "number" ? saved.autoCompactThreshold : null;
119886
+ ctx.lastPublished = stored;
119887
+ }
118286
119888
  function resetContext(entry, sessionId, db2) {
118287
119889
  if (entry.threadId) return;
118288
119890
  const ctx = counterOf(entry);
@@ -118353,6 +119955,112 @@ function classifyApiError({ error: error51, status, text: text2, limitRejected }
118353
119955
  return "fatal";
118354
119956
  }
118355
119957
 
119958
+ // src/claude/claude-host.ts
119959
+ import { spawn as spawn6 } from "node:child_process";
119960
+ var REPLAY_DONE_SUBTYPE = "agentpane_replay_done";
119961
+ var REPLAY_MARKER2 = JSON.stringify({ type: "system", subtype: REPLAY_DONE_SUBTYPE });
119962
+ function isReplayMarker(message) {
119963
+ return message.type === "system" && message.subtype === REPLAY_DONE_SUBTYPE;
119964
+ }
119965
+ var SDK_INTERNAL_FRAMES = /* @__PURE__ */ new Set([
119966
+ "control_request",
119967
+ "control_response",
119968
+ "control_cancel_request",
119969
+ "keep_alive",
119970
+ "transcript_mirror"
119971
+ ]);
119972
+ function* logFrames(log) {
119973
+ let start = 0;
119974
+ while (start < log.length) {
119975
+ const nl = log.indexOf(10, start);
119976
+ if (nl === -1) return;
119977
+ const line = log.subarray(start, nl).toString("utf8").trim();
119978
+ start = nl + 1;
119979
+ if (!line.startsWith("{")) continue;
119980
+ let message;
119981
+ try {
119982
+ message = JSON.parse(line);
119983
+ } catch {
119984
+ continue;
119985
+ }
119986
+ const type = message?.type;
119987
+ if (typeof type !== "string" || SDK_INTERNAL_FRAMES.has(type)) continue;
119988
+ yield message;
119989
+ }
119990
+ }
119991
+ function hostedSpawner(db2, binding, info) {
119992
+ return (opts) => {
119993
+ if (binding.proc) return binding.proc;
119994
+ const cwd = opts.cwd ?? info.cwd;
119995
+ try {
119996
+ writeHostMeta(binding.dir, {
119997
+ protocol: SESSION_HOST_PROTOCOL,
119998
+ hostId: binding.id,
119999
+ runtime: "claude",
120000
+ entryKey: info.entryKey,
120001
+ sessionId: info.sessionId,
120002
+ threadId: info.threadId,
120003
+ command: opts.command,
120004
+ runtimeVersion: binding.runtimeVersion,
120005
+ daemonUrl: sessionHostDaemonUrl(),
120006
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
120007
+ });
120008
+ insertHostRow(db2, {
120009
+ id: binding.id,
120010
+ runtime: "claude",
120011
+ session_id: info.sessionId,
120012
+ entry_key: info.entryKey,
120013
+ thread_id: info.threadId,
120014
+ turn_id: info.turnId,
120015
+ command: opts.command,
120016
+ runtime_version: binding.runtimeVersion,
120017
+ host_pid: null
120018
+ });
120019
+ } catch (err) {
120020
+ console.error(`[claude] no session host for ${info.entryKey} (${err.message}); running the CLI directly`);
120021
+ forgetHost(binding.id, binding.dir);
120022
+ const child = spawn6(opts.command, opts.args, { cwd, env: opts.env, signal: opts.signal, stdio: ["pipe", "pipe", "ignore"] });
120023
+ info.onDirect(child.pid);
120024
+ return child;
120025
+ }
120026
+ const proc = new HostedProcess({
120027
+ dir: binding.dir,
120028
+ start: { command: opts.command, args: opts.args, cwd, env: opts.env, config: hostConfig(true) },
120029
+ onAttach: (header) => {
120030
+ try {
120031
+ updateHostRow(db2, binding.id, { host_pid: header.hostPid, child_pid: header.child.pid });
120032
+ } catch {
120033
+ }
120034
+ },
120035
+ onDirect: (pid) => {
120036
+ forgetHost(binding.id, binding.dir);
120037
+ info.onDirect(pid);
120038
+ }
120039
+ });
120040
+ opts.signal?.addEventListener("abort", () => proc.kill("SIGTERM"), { once: true });
120041
+ binding.proc = proc;
120042
+ return proc;
120043
+ };
120044
+ }
120045
+ function attachedSpawner(proc) {
120046
+ return (opts) => {
120047
+ opts.signal?.addEventListener("abort", () => proc.kill("SIGTERM"), { once: true });
120048
+ return proc;
120049
+ };
120050
+ }
120051
+ async function releaseHost(binding) {
120052
+ const proc = binding.proc;
120053
+ if (proc?.endReason === "detached" || proc?.endReason === "attached-elsewhere") return;
120054
+ if (proc && proc.hosted) {
120055
+ try {
120056
+ await shutDownHost(binding.dir, { graceMs: 3e3 });
120057
+ } catch (err) {
120058
+ console.error(`[claude] could not stop session host ${binding.id}:`, err.message);
120059
+ }
120060
+ }
120061
+ forgetHost(binding.id, binding.dir);
120062
+ }
120063
+
118356
120064
  // src/claude/claude-provider.ts
118357
120065
  var PromptQueue = class {
118358
120066
  buffer = [];
@@ -118404,6 +120112,7 @@ function widgetStreamOf(entry) {
118404
120112
  let tracker = widgetStreams.get(entry);
118405
120113
  if (!tracker) {
118406
120114
  tracker = new WidgetStreamTracker(WIDGET_TOOL_NAME, (preview, target) => {
120115
+ if (target.muted) return;
118407
120116
  broadcast("widget:delta", {
118408
120117
  sessionId: target.sessionId,
118409
120118
  turnId: target.turnId,
@@ -118423,6 +120132,10 @@ function sessionIdOfKey(key) {
118423
120132
  const i = key.indexOf(THREAD_KEY_SEPARATOR);
118424
120133
  return i === -1 ? key : key.slice(0, i);
118425
120134
  }
120135
+ function threadIdOfKey(key) {
120136
+ const i = key.indexOf(THREAD_KEY_SEPARATOR);
120137
+ return i === -1 ? null : key.slice(i + THREAD_KEY_SEPARATOR.length);
120138
+ }
118426
120139
  function sessionBackgroundTasks(sessionId) {
118427
120140
  const tasks = [];
118428
120141
  for (const [key, entry] of sessionMap2) {
@@ -118618,15 +120331,42 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
118618
120331
  }
118619
120332
  }
118620
120333
  }
118621
- async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
120334
+ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume, adopt) {
118622
120335
  const db2 = getDb();
118623
120336
  const key = mapKey ?? session.id;
120337
+ const cwd = session.cwd ?? process.cwd();
118624
120338
  const resumeId = mapKey !== void 0 ? resumeSessionId : resumeSessionId ?? session.external_thread_id ?? void 0;
118625
120339
  const rescue = resume && resumeId ? resume : void 0;
118626
120340
  const env = spawnEnv(session.id, rescue);
118627
120341
  let cliPid = null;
120342
+ let host = null;
120343
+ let spawner;
120344
+ if (adopt) {
120345
+ host = { id: adopt.row.id, dir: adopt.dir, proc: adopt.proc, runtimeVersion: adopt.row.runtime_version };
120346
+ spawner = attachedSpawner(adopt.proc);
120347
+ } else if (hostsEnabledFor("claude")) {
120348
+ try {
120349
+ const { id, dir } = newHostDir();
120350
+ host = { id, dir, proc: null, runtimeVersion: runtimeVersion() };
120351
+ spawner = hostedSpawner(db2, host, {
120352
+ sessionId: session.id,
120353
+ entryKey: key,
120354
+ threadId: threadIdOfKey(key),
120355
+ turnId: resume?.turnId ?? null,
120356
+ cwd,
120357
+ onDirect: (pid) => {
120358
+ if (!pid) return;
120359
+ cliPid = pid;
120360
+ recordCliProcess(db2, pid, session.id);
120361
+ }
120362
+ });
120363
+ } catch (err) {
120364
+ console.error(`[claude] no session host for ${key}:`, err.message);
120365
+ host = null;
120366
+ }
120367
+ }
118628
120368
  const options = {
118629
- cwd: session.cwd ?? process.cwd(),
120369
+ cwd,
118630
120370
  model: session.model ?? void 0,
118631
120371
  permissionMode: "bypassPermissions",
118632
120372
  allowDangerouslySkipPermissions: true,
@@ -118637,24 +120377,36 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118637
120377
  ...session.model_reasoning_effort ? { effort: session.model_reasoning_effort } : {},
118638
120378
  ...resumeId ? { resume: resumeId } : {},
118639
120379
  ...env ? { env } : {},
120380
+ // Only the SDK's own spawner calls this; a hosted CLI has no
120381
+ // cli_processes row (its host supervises it).
118640
120382
  onProcessSpawned: (pid) => {
118641
120383
  cliPid = pid;
118642
120384
  recordCliProcess(db2, pid, session.id);
118643
- }
120385
+ },
120386
+ ...spawner ? { spawnClaudeCodeProcess: spawner } : {}
118644
120387
  };
118645
120388
  const promptQueue = new PromptQueue();
118646
120389
  const q = query({ prompt: promptQueue, options });
118647
120390
  const entry = {
118648
120391
  query: q,
118649
- sessionId: null,
118650
- turnId: resume?.turnId ?? null,
118651
- cwd: session.cwd ?? process.cwd(),
120392
+ sessionId: adopt?.row.external_id ?? null,
120393
+ turnId: adopt ? adopt.row.turn_id : resume?.turnId ?? null,
120394
+ cwd,
118652
120395
  promptQueue,
118653
120396
  messageLoop: null,
118654
120397
  closeReason: null,
118655
- resume: resume ? { turnId: resume.turnId, phase: rescue ? "awaiting_rescue" : "continuing", watchdog: null } : null,
118656
- lastApiError: null
120398
+ resume: resume ? { turnId: resume.turnId, phase: rescue ? "awaiting_rescue" : "continuing", watchdog: null } : adopt?.resuming && adopt.row.turn_id ? { turnId: adopt.row.turn_id, phase: "awaiting_rescue", watchdog: null } : null,
120399
+ lastApiError: null,
120400
+ host,
120401
+ ...adopt ? { threadId: adopt.row.thread_id, retireWhenIdle: adopt.retire } : {}
118657
120402
  };
120403
+ if (adopt) {
120404
+ restoreBackgroundTasks(entry, adopt.row.background_tasks);
120405
+ const stored = db2.prepare("SELECT context_usage FROM sessions WHERE id = ?").get(session.id);
120406
+ restoreContext(entry, stored?.context_usage);
120407
+ forgetStreams(session.id);
120408
+ startReplay(entry);
120409
+ }
118658
120410
  sessionMap2.set(key, entry);
118659
120411
  startFinishedSweep();
118660
120412
  if (rescue) {
@@ -118669,22 +120421,11 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118669
120421
  entry.messageLoop = (async () => {
118670
120422
  try {
118671
120423
  for await (const message of q) {
118672
- trackIdle(entry, message);
118673
- if (isBackgroundTasksChanged(message)) {
118674
- handleBackgroundTasksChanged(message, session.id, entry);
118675
- continue;
118676
- }
118677
- if (message.type === "rate_limit_event") {
118678
- entry.rateLimit = message.rate_limit_info;
118679
- continue;
118680
- }
118681
- const currentTurnId = entry.turnId;
118682
- if (!currentTurnId) {
118683
- handleTaskFrame(message, session.id, entry, db2);
120424
+ if (isReplayMarker(message)) {
120425
+ finishReplay(entry, session.id, db2);
118684
120426
  continue;
118685
120427
  }
118686
- if (entry.resume && !trackResumeFrame(entry, message, db2)) continue;
118687
- await handleMessage(message, session.id, currentTurnId, entry, db2);
120428
+ await dispatchFrame(entry, session.id, message, db2);
118688
120429
  }
118689
120430
  if (entry.closeReason === "shutdown") return;
118690
120431
  if (entry.turnId) {
@@ -118706,6 +120447,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118706
120447
  console.error(`[claude] cleanup after loop error failed for session ${session.id}:`, cleanupErr);
118707
120448
  }
118708
120449
  } finally {
120450
+ entry.endReplay?.();
118709
120451
  clearResume(entry);
118710
120452
  if (entry.turnId) {
118711
120453
  streamingMessageIds.delete(entry.turnId);
@@ -118720,12 +120462,40 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118720
120462
  } catch (err) {
118721
120463
  console.error(`[claude] cleanup after CLI exit failed for session ${session.id}:`, err.message);
118722
120464
  }
120465
+ if (entry.host) void releaseHost(entry.host);
118723
120466
  }
118724
120467
  }
118725
120468
  })();
118726
120469
  return entry;
118727
120470
  }
120471
+ async function dispatchFrame(entry, sessionId, message, db2, opts = {}) {
120472
+ trackIdle(entry, message);
120473
+ if (isBackgroundTasksChanged(message)) {
120474
+ handleBackgroundTasksChanged(message, sessionId, entry);
120475
+ return;
120476
+ }
120477
+ if (message.type === "rate_limit_event") {
120478
+ entry.rateLimit = message.rate_limit_info;
120479
+ return;
120480
+ }
120481
+ const currentTurnId = entry.turnId;
120482
+ if (!currentTurnId) {
120483
+ handleTaskFrame(message, sessionId, entry, db2);
120484
+ return;
120485
+ }
120486
+ if (entry.resume && !trackResumeFrame(entry, message, db2)) return;
120487
+ if (opts.awaitResult && message.type === "result") {
120488
+ await handleResultMessage(message, sessionId, currentTurnId, entry, db2);
120489
+ return;
120490
+ }
120491
+ await handleMessage(message, sessionId, currentTurnId, entry, db2);
120492
+ }
120493
+ function isTurnLive2(db2, turnId) {
120494
+ const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
120495
+ return row?.status === "pending" || row?.status === "running";
120496
+ }
118728
120497
  async function startTurn3(session, turn) {
120498
+ if (isAdoptionPending()) await waitForAdoption();
118729
120499
  const db2 = getDb();
118730
120500
  const now = (/* @__PURE__ */ new Date()).toISOString();
118731
120501
  const mapKey = turn.thread_id ? `${session.id}:thread:${turn.thread_id}` : session.id;
@@ -118765,6 +120535,7 @@ async function startTurn3(session, turn) {
118765
120535
  entry.turnId = turn.id;
118766
120536
  entry.lastApiError = null;
118767
120537
  clearResume(entry);
120538
+ bindHostTurn2(entry, turn.id);
118768
120539
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
118769
120540
  setSessionStatus2(db2, session.id, 1, "running", now);
118770
120541
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
@@ -118821,6 +120592,12 @@ async function handleMessage(message, sessionId, turnId, entry, db2) {
118821
120592
  const sub = message.subtype;
118822
120593
  if (sub === "init") {
118823
120594
  entry.sessionId = message.session_id;
120595
+ if (entry.host?.proc?.hosted) {
120596
+ try {
120597
+ updateHostRow(db2, entry.host.id, { external_id: entry.sessionId });
120598
+ } catch {
120599
+ }
120600
+ }
118824
120601
  if (!entry.threadId) {
118825
120602
  const now = (/* @__PURE__ */ new Date()).toISOString();
118826
120603
  db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
@@ -118853,6 +120630,7 @@ async function handleMessage(message, sessionId, turnId, entry, db2) {
118853
120630
  handleTaskFrame(message, sessionId, entry, db2);
118854
120631
  } else if (sub === "api_retry") {
118855
120632
  const m = message;
120633
+ if (entry.replaying) break;
118856
120634
  broadcast("turn:retrying", {
118857
120635
  sessionId,
118858
120636
  turnId,
@@ -118993,19 +120771,16 @@ function handleStreamEvent(message, sessionId, turnId, entry, db2) {
118993
120771
  }
118994
120772
  }
118995
120773
  if (!parentToolUseId) {
118996
- widgetStreamOf(entry).handle(message.event, { sessionId, turnId });
120774
+ widgetStreamOf(entry).handle(message.event, { sessionId, turnId, muted: !!entry.replaying });
118997
120775
  }
118998
120776
  const delta = mapPartialDelta(message.event);
118999
120777
  if (!delta) return;
119000
120778
  if (parentToolUseId) return;
119001
120779
  if (delta.kind === "text") {
119002
120780
  const msgId = streamingMessageIds.get(turnId) ?? `stream-text-${turnId}`;
119003
- broadcast("item:delta", {
119004
- sessionId,
119005
- turnId,
119006
- itemId: msgId,
119007
- delta: delta.text
119008
- });
120781
+ const payload = { sessionId, turnId, itemId: msgId, delta: delta.text };
120782
+ if (entry.replaying) noteDelta(payload);
120783
+ else broadcast("item:delta", payload);
119009
120784
  }
119010
120785
  if (delta.kind === "thinking") {
119011
120786
  let msgMap = thinkingAccumulator.get(message.uuid);
@@ -119220,10 +120995,20 @@ function handleBackgroundTasksChanged(message, sessionId, entry) {
119220
120995
  entry.backgroundTasks = tasks.filter((t) => !t.ambient).map((t) => ({ task_id: t.task_id, task_type: t.task_type, description: t.description }));
119221
120996
  publishBackgroundTasks(sessionId);
119222
120997
  if (endedIds.length > 0) closeTaskItemsSoon(sessionId, entry.threadId ?? null, endedIds);
120998
+ persistBackgroundTasks(entry);
120999
+ if (entry.backgroundTasks.length === 0) maybeRetire2(entry);
119223
121000
  }
119224
121001
  async function handleResultMessage(message, sessionId, turnId, entry, db2) {
119225
121002
  const parentToolUseId = message.parent_tool_use_id ?? null;
119226
121003
  if (parentToolUseId) return;
121004
+ try {
121005
+ await settleResult(message, sessionId, turnId, entry, db2);
121006
+ } finally {
121007
+ settleHostTurn2(entry);
121008
+ maybeRetire2(entry);
121009
+ }
121010
+ }
121011
+ async function settleResult(message, sessionId, turnId, entry, db2) {
119227
121012
  if (message.subtype === "success") {
119228
121013
  const usage = mapUsage(message.usage);
119229
121014
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -119344,6 +121129,8 @@ async function interruptTurn2(sessionId, threadId) {
119344
121129
  streamingMessageIds.delete(turnId);
119345
121130
  entry.turnId = null;
119346
121131
  entry.idleSince = Date.now();
121132
+ settleHostTurn2(entry);
121133
+ maybeRetire2(entry);
119347
121134
  return true;
119348
121135
  } catch {
119349
121136
  entry.closeReason = "clear";
@@ -119402,16 +121189,18 @@ function clearThread2(sessionId) {
119402
121189
  function clearThreadBranch(sessionId, threadId) {
119403
121190
  const key = `${sessionId}:thread:${threadId}`;
119404
121191
  const entry = sessionMap2.get(key);
119405
- if (entry) {
119406
- entry.closeReason ??= "clear";
119407
- entry.promptQueue.close();
119408
- entry.query.close();
119409
- if (entry.turnId) {
119410
- streamingMessageIds.delete(entry.turnId);
119411
- }
119412
- sessionMap2.delete(key);
119413
- dropBackgroundTasks(sessionId, entry);
121192
+ if (entry) closeEntry(key, entry);
121193
+ }
121194
+ function closeEntry(key, entry) {
121195
+ entry.closeReason ??= "clear";
121196
+ clearResume(entry);
121197
+ entry.promptQueue.close();
121198
+ entry.query.close();
121199
+ if (entry.turnId) {
121200
+ streamingMessageIds.delete(entry.turnId);
119414
121201
  }
121202
+ if (sessionMap2.get(key) === entry) sessionMap2.delete(key);
121203
+ dropBackgroundTasks(sessionIdOfKey(key), entry);
119415
121204
  }
119416
121205
  function clearAllThreads2() {
119417
121206
  for (const [, entry] of sessionMap2) {
@@ -119535,6 +121324,10 @@ async function shutdown2() {
119535
121324
  for (const entry of sessionMap2.values()) {
119536
121325
  entry.closeReason = "shutdown";
119537
121326
  clearResume(entry);
121327
+ if (entry.host?.proc?.hosted) {
121328
+ entry.host.proc.detach();
121329
+ continue;
121330
+ }
119538
121331
  if (db2 && entry.turnId && !entry.threadId) {
119539
121332
  try {
119540
121333
  markTurnInterrupted(db2, entry.turnId, "host_shutdown", { notify: false });
@@ -119560,6 +121353,7 @@ function retireCli(sessionId, entry) {
119560
121353
  }
119561
121354
  async function resumeInterruptedTurn2(session, turn, opts) {
119562
121355
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
121356
+ if (isAdoptionPending()) await waitForAdoption();
119563
121357
  let live = sessionMap2.get(session.id);
119564
121358
  if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
119565
121359
  retireCli(session.id, live);
@@ -119572,11 +121366,13 @@ async function resumeInterruptedTurn2(session, turn, opts) {
119572
121366
  live.threadId = null;
119573
121367
  live.lastApiError = null;
119574
121368
  live.resume = { turnId: turn.id, phase: "continuing", watchdog: null };
121369
+ bindHostTurn2(live, turn.id);
119575
121370
  pushPrompt(live, CONTINUE_PROMPT);
119576
121371
  return;
119577
121372
  }
119578
121373
  const entry = await ensureSessionStarted(session, void 0, void 0, { turnId: turn.id, reason: opts.reason });
119579
121374
  entry.threadId = null;
121375
+ bindHostTurn2(entry, turn.id);
119580
121376
  if (entry.resume?.phase === "continuing") pushPrompt(entry, buildUserContent(turn));
119581
121377
  }
119582
121378
  function syncThreadTitle2(sessionId) {
@@ -119707,6 +121503,213 @@ async function forkClaudeSession(session, targetTurn) {
119707
121503
  return null;
119708
121504
  }
119709
121505
  }
121506
+ var REPLAY_WAIT_MS2 = 3e4;
121507
+ function startReplay(entry) {
121508
+ let done = () => {
121509
+ };
121510
+ entry.replayDone = new Promise((resolve) => {
121511
+ done = resolve;
121512
+ });
121513
+ entry.replaying = true;
121514
+ entry.endReplay = () => {
121515
+ entry.replaying = false;
121516
+ done();
121517
+ };
121518
+ }
121519
+ function finishReplay(entry, sessionId, db2) {
121520
+ if (!entry.replaying) return;
121521
+ entry.endReplay?.();
121522
+ try {
121523
+ if (entry.idleSince === void 0 && !(entry.turnId && isTurnLive2(db2, entry.turnId))) entry.idleSince = Date.now();
121524
+ if (entry.resume?.phase === "awaiting_rescue") armRescueWatchdog(entry);
121525
+ publishBackgroundTasks(sessionId);
121526
+ const row = db2.prepare("SELECT status FROM sessions WHERE id = ?").get(sessionId);
121527
+ const idleStatus = row && row.status !== "running" && row.status !== "interrupted" ? row.status : "active";
121528
+ recomputeSessionRunning(db2, sessionId, idleStatus);
121529
+ } catch (err) {
121530
+ console.error(`[claude] after the replay of session ${sessionId}:`, err.message);
121531
+ }
121532
+ broadcast("session:resync", { sessionId });
121533
+ resendStreams(sessionId);
121534
+ maybeRetire2(entry);
121535
+ }
121536
+ function restoreBackgroundTasks(entry, json2) {
121537
+ if (!json2) return;
121538
+ try {
121539
+ const saved = JSON.parse(json2);
121540
+ entry.backgroundTasks = Array.isArray(saved.tasks) ? saved.tasks : [];
121541
+ entry.liveTaskIds = Array.isArray(saved.live) ? saved.live : [];
121542
+ } catch {
121543
+ }
121544
+ }
121545
+ function persistBackgroundTasks(entry) {
121546
+ const host = entry.host;
121547
+ if (!host?.proc?.hosted || entry.closeReason) return;
121548
+ try {
121549
+ setHostBackgroundTasks(
121550
+ getDb(),
121551
+ host.id,
121552
+ JSON.stringify({ tasks: entry.backgroundTasks ?? [], live: entry.liveTaskIds ?? [] })
121553
+ );
121554
+ } catch {
121555
+ }
121556
+ refreshHostLimit2(entry);
121557
+ }
121558
+ function refreshHostLimit2(entry, busy) {
121559
+ const host = entry.host;
121560
+ if (!host?.proc?.hosted || entry.closeReason) return;
121561
+ const flags = sessionHostFlags();
121562
+ const isBusy = busy ?? !!entry.backgroundTasks?.length;
121563
+ void limitHost(host.dir, isBusy ? flags.noHostBusyMs : flags.noHostIdleMs).catch(() => {
121564
+ });
121565
+ }
121566
+ function bindHostTurn2(entry, turnId) {
121567
+ const host = entry.host;
121568
+ const proc = host?.proc;
121569
+ if (!host || !proc?.hosted) return;
121570
+ const offset = proc.consumedLineEnd;
121571
+ try {
121572
+ setHostTurn(getDb(), host.id, turnId, offset);
121573
+ } catch (err) {
121574
+ console.error(`[claude] could not bind turn ${turnId} to its session host:`, err.message);
121575
+ }
121576
+ void ackHost(host.dir, offset).catch(() => {
121577
+ });
121578
+ refreshHostLimit2(entry, true);
121579
+ }
121580
+ function settleHostTurn2(entry) {
121581
+ const host = entry.host;
121582
+ const proc = host?.proc;
121583
+ if (!host || !proc?.hosted || entry.closeReason) return;
121584
+ const upto = proc.consumedLineEnd;
121585
+ try {
121586
+ setHostTurn(getDb(), host.id, entry.turnId, upto);
121587
+ } catch {
121588
+ }
121589
+ void ackHost(host.dir, upto).catch(() => {
121590
+ });
121591
+ refreshHostLimit2(entry);
121592
+ }
121593
+ function keyOfEntry(entry) {
121594
+ for (const [key, candidate] of sessionMap2) {
121595
+ if (candidate === entry) return key;
121596
+ }
121597
+ return null;
121598
+ }
121599
+ function maybeRetire2(entry) {
121600
+ const why = entry.retireWhenIdle;
121601
+ if (!why || entry.replaying || entry.closeReason || entry.resume) return;
121602
+ if (entry.backgroundTasks?.length || entry.idleSince === null) return;
121603
+ try {
121604
+ if (entry.turnId && isTurnLive2(getDb(), entry.turnId)) return;
121605
+ } catch {
121606
+ return;
121607
+ }
121608
+ const key = keyOfEntry(entry);
121609
+ if (!key) return;
121610
+ console.log(`[claude] closing the idle CLI of ${key} (${why}); the next prompt starts a new one`);
121611
+ closeEntry(key, entry);
121612
+ }
121613
+ function describeExit2(exit) {
121614
+ if (!exit) return "the session host died with its CLI";
121615
+ if (exit.error) return `Claude Code process could not start: ${exit.error}`;
121616
+ if (exit.signal) return `Claude Code process terminated by signal ${exit.signal}`;
121617
+ return `Claude Code process exited with code ${exit.code}`;
121618
+ }
121619
+ function deadEntry(session, row) {
121620
+ const gone = () => Promise.reject(new Error("the CLI is gone"));
121621
+ const entry = {
121622
+ query: { getContextUsage: gone, interrupt: gone, setModel: gone, stopTask: gone, close: () => {
121623
+ } },
121624
+ sessionId: row.external_id,
121625
+ turnId: row.turn_id,
121626
+ cwd: session.cwd ?? process.cwd(),
121627
+ promptQueue: { push: () => {
121628
+ }, close: () => {
121629
+ } },
121630
+ messageLoop: null,
121631
+ threadId: row.thread_id,
121632
+ closeReason: null,
121633
+ resume: null,
121634
+ lastApiError: null,
121635
+ replaying: true
121636
+ };
121637
+ restoreBackgroundTasks(entry, row.background_tasks);
121638
+ return entry;
121639
+ }
121640
+ var claudeHostAdopter = {
121641
+ runtime: "claude",
121642
+ async adoptLive(row, dir) {
121643
+ const db2 = getDb();
121644
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
121645
+ if (!session || session.runtime_type !== "claude") throw new Error("the session is not a Claude session any more");
121646
+ if (sessionMap2.has(row.entry_key)) throw new Error(`a CLI already runs for ${row.entry_key}`);
121647
+ const turn = row.turn_id ? db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(row.turn_id) : void 0;
121648
+ const running = !!turn && (turn.status === "running" || turn.status === "pending" && turn.resume_state !== "waiting");
121649
+ const proc = new HostedProcess({
121650
+ dir,
121651
+ after: row.replay_offset,
121652
+ replayMarker: REPLAY_MARKER2,
121653
+ onAttach: (header) => {
121654
+ try {
121655
+ updateHostRow(getDb(), row.id, { host_pid: header.hostPid, child_pid: header.child.pid });
121656
+ } catch {
121657
+ }
121658
+ }
121659
+ });
121660
+ await proc.ready;
121661
+ const version2 = runtimeVersion();
121662
+ const retire = !sessionHostFlags().claude ? "session hosts are off for Claude" : row.runtime_version !== version2 ? `started by runtime ${row.runtime_version ?? "unknown"}, this is ${version2 ?? "unknown"}` : null;
121663
+ const entry = await ensureSessionStarted(session, row.thread_id ? row.entry_key : void 0, void 0, void 0, {
121664
+ row,
121665
+ dir,
121666
+ proc,
121667
+ resuming: running && turn?.resume_state === "resuming" && !row.thread_id,
121668
+ retire
121669
+ });
121670
+ refreshHostLimit2(entry, running);
121671
+ let timer2 = null;
121672
+ await Promise.race([
121673
+ entry.replayDone,
121674
+ new Promise((resolve) => {
121675
+ timer2 = setTimeout(() => {
121676
+ console.error(`[claude] the replay of ${row.entry_key} takes long; startup goes on`);
121677
+ resolve();
121678
+ }, REPLAY_WAIT_MS2);
121679
+ timer2.unref?.();
121680
+ })
121681
+ ]);
121682
+ if (timer2) clearTimeout(timer2);
121683
+ console.log(
121684
+ `[claude] adopted the CLI of ${row.entry_key} (pid ${proc.pid ?? "?"})${running ? `, turn ${row.turn_id} goes on` : ""}${retire ? `; it closes once idle: ${retire}` : ""}`
121685
+ );
121686
+ return { turnId: running ? row.turn_id : null };
121687
+ },
121688
+ async adoptDead(row, _dir, log, exit) {
121689
+ const db2 = getDb();
121690
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
121691
+ if (!session || session.runtime_type !== "claude") return;
121692
+ const detail = describeExit2(exit);
121693
+ console.log(`[claude] the CLI of ${row.entry_key} ended with no daemon attached (${detail}); replaying its log`);
121694
+ if (log && log.length > 0) {
121695
+ const entry = deadEntry(session, row);
121696
+ forgetStreams(session.id);
121697
+ for (const message of logFrames(log)) {
121698
+ try {
121699
+ await dispatchFrame(entry, session.id, message, db2, { awaitResult: true });
121700
+ } catch (err) {
121701
+ console.error(`[claude] replay of ${row.entry_key} failed at a frame:`, err.message);
121702
+ }
121703
+ }
121704
+ forgetStreams(session.id);
121705
+ broadcast("session:resync", { sessionId: session.id });
121706
+ }
121707
+ if (row.turn_id && !row.thread_id && isTurnLive2(db2, row.turn_id)) {
121708
+ markTurnInterrupted(db2, row.turn_id, "process_exit", { detail, notify: false });
121709
+ }
121710
+ }
121711
+ };
121712
+ registerHostAdopter(claudeHostAdopter);
119710
121713
  var claudeProvider = {
119711
121714
  startTurn: startTurn3,
119712
121715
  interruptTurn: interruptTurn2,
@@ -119740,8 +121743,8 @@ var RepoburgHttpClient = class {
119740
121743
  this.baseUrl = baseUrl.replace(/\/+$/, "");
119741
121744
  }
119742
121745
  /** Perform a JSON request. Throws a concise error on non-OK/non-JSON responses. */
119743
- async request(method, path13, body) {
119744
- const response = await fetch(`${this.baseUrl}${path13}`, {
121746
+ async request(method, path17, body) {
121747
+ const response = await fetch(`${this.baseUrl}${path17}`, {
119745
121748
  method,
119746
121749
  headers: { "Content-Type": "application/json" },
119747
121750
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -119750,17 +121753,17 @@ var RepoburgHttpClient = class {
119750
121753
  if (!response.ok) {
119751
121754
  if (isHtml(text2)) {
119752
121755
  throw new Error(
119753
- `${method} ${path13} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121756
+ `${method} ${path17} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
119754
121757
  );
119755
121758
  }
119756
- throw new Error(`${method} ${path13} failed: ${response.status} ${text2}`);
121759
+ throw new Error(`${method} ${path17} failed: ${response.status} ${text2}`);
119757
121760
  }
119758
121761
  if (text2.length === 0) return void 0;
119759
121762
  try {
119760
121763
  return JSON.parse(text2);
119761
121764
  } catch {
119762
121765
  throw new Error(
119763
- `${method} ${path13} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121766
+ `${method} ${path17} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
119764
121767
  );
119765
121768
  }
119766
121769
  }
@@ -119815,7 +121818,7 @@ var RepoburgHttpClient = class {
119815
121818
  };
119816
121819
 
119817
121820
  // src/repoburg/backend-resolver.ts
119818
- import path12 from "node:path";
121821
+ import path15 from "node:path";
119819
121822
  var HEALTH_POLL_INTERVAL_MS = 1e3;
119820
121823
  var HEALTH_TIMEOUT_MS = 3e4;
119821
121824
  function daemonBaseUrl() {
@@ -119870,7 +121873,7 @@ async function backendHealthy(baseUrl, expectedPath) {
119870
121873
  const health = await fetchJson(`${baseUrl}/health`, void 0, 2e3);
119871
121874
  if (health.status !== "ok") return false;
119872
121875
  if (expectedPath && health.projectPath) {
119873
- return path12.resolve(health.projectPath) === path12.resolve(expectedPath);
121876
+ return path15.resolve(health.projectPath) === path15.resolve(expectedPath);
119874
121877
  }
119875
121878
  return true;
119876
121879
  } catch {
@@ -119891,7 +121894,7 @@ function serviceBaseUrl(service) {
119891
121894
  return `http://localhost:${service.port}`;
119892
121895
  }
119893
121896
  function coveringService(services, absPath) {
119894
- return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path12.sep)).sort((a, b) => b.path.length - a.path.length)[0];
121897
+ return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path15.sep)).sort((a, b) => b.path.length - a.path.length)[0];
119895
121898
  }
119896
121899
  async function restartService(daemon, name) {
119897
121900
  try {
@@ -119927,11 +121930,11 @@ async function resolveBackendUrl(projectPath, opts = {}) {
119927
121930
  if (envUrl) {
119928
121931
  return { baseUrl: envUrl.replace(/\/+$/, ""), port: 0, name: "REPOBURG_BACKEND_URL" };
119929
121932
  }
119930
- const absPath = path12.resolve(projectPath);
121933
+ const absPath = path15.resolve(projectPath);
119931
121934
  const daemon = daemonBaseUrl();
119932
- const cached2 = resolvedCache.get(absPath);
119933
- if (cached2 && await backendHealthy(cached2.baseUrl, cached2.servesPath ?? absPath)) {
119934
- return cached2;
121935
+ const cached3 = resolvedCache.get(absPath);
121936
+ if (cached3 && await backendHealthy(cached3.baseUrl, cached3.servesPath ?? absPath)) {
121937
+ return cached3;
119935
121938
  }
119936
121939
  try {
119937
121940
  await fetchJson(`${daemon}/health`, void 0, 3e3);
@@ -120205,7 +122208,12 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
120205
122208
  if (opts.signal?.aborted) return "aborted";
120206
122209
  let response;
120207
122210
  try {
120208
- response = await fetch(url2, { method: "GET", signal: opts.signal });
122211
+ const lastEventId = opts.lastEventId?.() ?? null;
122212
+ response = await fetch(url2, {
122213
+ method: "GET",
122214
+ signal: opts.signal,
122215
+ ...lastEventId === null ? {} : { headers: { "Last-Event-ID": String(lastEventId) } }
122216
+ });
120209
122217
  } catch (err) {
120210
122218
  if (opts.signal?.aborted || err.name === "AbortError") {
120211
122219
  return "aborted";
@@ -120267,6 +122275,23 @@ async function readBody(body, onMessage, opts) {
120267
122275
  }
120268
122276
  }
120269
122277
  }
122278
+ async function getAgentRuntimeState(baseUrl, sessionId, timeoutMs = 5e3) {
122279
+ const url2 = `${baseUrl.replace(/\/+$/, "")}/agent-runtime/sessions/${sessionId}/state`;
122280
+ const response = await fetch(url2, { signal: AbortSignal.timeout(timeoutMs) });
122281
+ if (!response.ok) return null;
122282
+ try {
122283
+ const state = await response.json();
122284
+ if (typeof state.bootId !== "string" || typeof state.lastSeq !== "number") return null;
122285
+ return {
122286
+ bootId: state.bootId,
122287
+ lastSeq: state.lastSeq,
122288
+ turnInFlight: state.turnInFlight === true,
122289
+ lastResult: state.lastResult ?? null
122290
+ };
122291
+ } catch {
122292
+ return null;
122293
+ }
122294
+ }
120270
122295
  function reconnectDelay(delayMs, signal) {
120271
122296
  return new Promise((resolve) => {
120272
122297
  if (signal?.aborted) return resolve();
@@ -120299,16 +122324,25 @@ var TurnProjector = class {
120299
122324
  /** Context fill of the LAST LLM round (input tokens of the full prompt) —
120300
122325
  * drives the status-bar total-token counter at turn completion. */
120301
122326
  lastContextTokens = null;
122327
+ /** Messages that arrived while a gap recovery runs; null otherwise. */
122328
+ held = null;
122329
+ recovery = null;
122330
+ /** Another gap arrived while a recovery ran: fetch the snapshot again. */
122331
+ gapAgain = false;
120302
122332
  get isDone() {
120303
122333
  return this.done;
120304
122334
  }
120305
122335
  /** Main entry — dispatch one agent-runtime message. */
120306
122336
  handle(message) {
120307
122337
  if (this.done) return;
122338
+ if (this.held) {
122339
+ this.held.push(message);
122340
+ return;
122341
+ }
120308
122342
  switch (message.type) {
120309
122343
  case "system":
120310
122344
  break;
120311
- // init — connection marker only
122345
+ // init — connection marker only; gaps go to recoverGap
120312
122346
  case "stream_event":
120313
122347
  this.handleStreamEvent(message);
120314
122348
  break;
@@ -120336,6 +122370,61 @@ var TurnProjector = class {
120336
122370
  this.clearWatchdog();
120337
122371
  this.done = true;
120338
122372
  }
122373
+ /**
122374
+ * The backend no longer keeps some of the turn's messages. Project the
122375
+ * lost rounds from the REST snapshot (idempotent upserts), then the
122376
+ * messages held meanwhile. A turn that ended within the gap finishes from
122377
+ * the backend's last result, or from the snapshot when that is not this
122378
+ * turn's.
122379
+ */
122380
+ recoverGap() {
122381
+ if (this.done) return Promise.resolve();
122382
+ if (this.recovery) {
122383
+ this.gapAgain = true;
122384
+ return this.recovery;
122385
+ }
122386
+ this.held = [];
122387
+ this.recovery = this.runGapRecovery().finally(() => {
122388
+ this.recovery = null;
122389
+ });
122390
+ return this.recovery;
122391
+ }
122392
+ /** Resolves when no gap recovery holds messages back. */
122393
+ settled() {
122394
+ return this.recovery ?? Promise.resolve();
122395
+ }
122396
+ async runGapRecovery() {
122397
+ let state = null;
122398
+ try {
122399
+ do {
122400
+ this.gapAgain = false;
122401
+ const { client, repoburgSessionId } = this.deps;
122402
+ const [inputs, current] = await Promise.all([
122403
+ client.getSessionInputs(repoburgSessionId),
122404
+ getAgentRuntimeState(client.baseUrl, repoburgSessionId)
122405
+ ]);
122406
+ state = current;
122407
+ if (this.done) return;
122408
+ for (const input of inputs) {
122409
+ if (input.role === "model") this.projectSnapshotRound(input);
122410
+ }
122411
+ } while (this.gapAgain && !this.done);
122412
+ } catch (err) {
122413
+ console.error("[repoburg] gap recovery failed:", err);
122414
+ state = null;
122415
+ } finally {
122416
+ const held = this.held ?? [];
122417
+ this.held = null;
122418
+ for (const message of held) this.handle(message);
122419
+ }
122420
+ if (this.done || !state || state.turnInFlight) return;
122421
+ const last = state.lastResult;
122422
+ if (last && this.deps.firstSeq !== void 0 && typeof last.seq === "number" && last.seq >= this.deps.firstSeq) {
122423
+ this.handleResult(last);
122424
+ } else {
122425
+ await this.reconcileFromSnapshot();
122426
+ }
122427
+ }
120339
122428
  // -------------------------------------------------------------------------
120340
122429
  // Message handlers
120341
122430
  // -------------------------------------------------------------------------
@@ -120385,7 +122474,12 @@ var TurnProjector = class {
120385
122474
  else info.thoughts += msg.delta.text;
120386
122475
  const externalId = kind === "text" ? info.messageExternalId : info.reasoningExternalId;
120387
122476
  const type = kind === "text" ? "agent_message" : "reasoning";
120388
- const itemId = kind === "text" ? info.messageItemId : info.reasoningItemId;
122477
+ let itemId = kind === "text" ? info.messageItemId : info.reasoningItemId;
122478
+ if (!itemId) {
122479
+ itemId = this.existingItemId(externalId);
122480
+ if (kind === "text") info.messageItemId = itemId;
122481
+ else info.reasoningItemId = itemId;
122482
+ }
120389
122483
  if (!itemId) {
120390
122484
  const item = insertItem(
120391
122485
  db2,
@@ -120418,8 +122512,8 @@ var TurnProjector = class {
120418
122512
  const thinking = msg.content.filter((b) => b.type === "thinking").map((b) => b.thinking).join("");
120419
122513
  if (text2) info.text = text2;
120420
122514
  if (thinking) info.thoughts = thinking;
120421
- this.upsertCompletedTextItem(info, "message", info.text);
120422
122515
  this.upsertCompletedTextItem(info, "reasoning", info.thoughts);
122516
+ this.upsertCompletedTextItem(info, "message", info.text);
120423
122517
  this.touch();
120424
122518
  }
120425
122519
  /** Complete a round's text/thoughts item — creates it when deltas were
@@ -120437,8 +122531,16 @@ var TurnProjector = class {
120437
122531
  return;
120438
122532
  }
120439
122533
  }
120440
- const existing = db2.prepare("SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?").get(this.deps.turnId, externalId);
120441
- if (existing) return;
122534
+ const existing = db2.prepare("SELECT * FROM items WHERE turn_id = ? AND external_item_id = ?").get(this.deps.turnId, externalId);
122535
+ if (existing) {
122536
+ if (kind === "message") info.messageItemId = existing.id;
122537
+ else info.reasoningItemId = existing.id;
122538
+ const data = existing.data ? JSON.parse(existing.data) : {};
122539
+ if (existing.status !== "completed" || data.text !== text2) {
122540
+ completeItem(db2, this.deps.agentPaneSessionId, this.deps.turnId, { ...existing, data }, { text: text2 }, "completed");
122541
+ }
122542
+ return;
122543
+ }
120442
122544
  const item = insertItem(
120443
122545
  db2,
120444
122546
  this.deps.agentPaneSessionId,
@@ -120452,6 +122554,10 @@ var TurnProjector = class {
120452
122554
  if (kind === "message") info.messageItemId = item.id;
120453
122555
  else info.reasoningItemId = item.id;
120454
122556
  }
122557
+ existingItemId(externalId) {
122558
+ const row = getDb().prepare("SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?").get(this.deps.turnId, externalId);
122559
+ return row?.id ?? null;
122560
+ }
120455
122561
  handleUser(msg) {
120456
122562
  const db2 = getDb();
120457
122563
  for (const block of msg.content) {
@@ -120834,8 +122940,8 @@ var TurnProjector = class {
120834
122940
  const info = this.round(input.id);
120835
122941
  info.text = info.text || (input.raw_llm_response ?? "");
120836
122942
  info.thoughts = info.thoughts || (input.thoughts ?? "");
120837
- this.upsertCompletedTextItem(info, "message", info.text);
120838
122943
  this.upsertCompletedTextItem(info, "reasoning", info.thoughts);
122944
+ this.upsertCompletedTextItem(info, "message", info.text);
120839
122945
  const actions = [...input.aiActions ?? []].sort(
120840
122946
  (a, b) => (a.order_of_execution ?? 0) - (b.order_of_execution ?? 0)
120841
122947
  );
@@ -121049,9 +123155,9 @@ function failTurn3(entry, error51) {
121049
123155
  broadcast("turn:failed", { sessionId: entry.agentPaneSessionId, turnId: active.turnId, error: error51 });
121050
123156
  }
121051
123157
  async function runStreamLoop(entry, projector) {
121052
- const isCurrent = () => entry.activeTurn?.projector === projector && !projector.isDone;
123158
+ const isCurrent2 = () => entry.activeTurn?.projector === projector && !projector.isDone;
121053
123159
  const lose = (error51) => {
121054
- if (isCurrent()) failTurn3(entry, error51);
123160
+ if (isCurrent2()) failTurn3(entry, error51);
121055
123161
  };
121056
123162
  let lostTimer = null;
121057
123163
  const clearLostTimer = () => {
@@ -121059,7 +123165,7 @@ async function runStreamLoop(entry, projector) {
121059
123165
  lostTimer = null;
121060
123166
  };
121061
123167
  try {
121062
- while (isCurrent()) {
123168
+ while (isCurrent2()) {
121063
123169
  const active = entry.activeTurn;
121064
123170
  const controller = new AbortController();
121065
123171
  active.sseAbort = controller;
@@ -121070,12 +123176,23 @@ async function runStreamLoop(entry, projector) {
121070
123176
  };
121071
123177
  resetStall();
121072
123178
  const onMessage = (message) => {
123179
+ if (message.type === "system" && message.subtype === "gap") {
123180
+ void projector.recoverGap().then(() => {
123181
+ if (projector.isDone) controller.abort();
123182
+ });
123183
+ return;
123184
+ }
121073
123185
  if (message.type === "system") {
121074
123186
  clearLostTimer();
121075
123187
  const bootId = message.bootId ?? null;
121076
123188
  if (active.bootId === void 0) active.bootId = bootId;
121077
123189
  else if (bootId !== active.bootId) return lose(BACKEND_RESTARTED_ERROR);
121078
123190
  }
123191
+ const seq = messageSeq(message);
123192
+ if (seq !== null) {
123193
+ if (active.lastSeq !== null && seq <= active.lastSeq) return;
123194
+ active.lastSeq = seq;
123195
+ }
121079
123196
  projector.handle(message);
121080
123197
  };
121081
123198
  const onDisconnect = () => {
@@ -121089,10 +123206,12 @@ async function runStreamLoop(entry, projector) {
121089
123206
  const reason = await streamAgentRuntimeMessages(entry.baseUrl, entry.repoburgSessionId, onMessage, {
121090
123207
  signal: controller.signal,
121091
123208
  onActivity: resetStall,
121092
- onDisconnect
123209
+ onDisconnect,
123210
+ lastEventId: () => active.lastSeq
121093
123211
  });
121094
123212
  if (stallTimer) clearTimeout(stallTimer);
121095
- if (!isCurrent()) return;
123213
+ await projector.settled();
123214
+ if (!isCurrent2()) return;
121096
123215
  if (reason === "session-not-found") {
121097
123216
  failTurn3(entry, "Repoburg session no longer exists on the backend.");
121098
123217
  return;
@@ -121106,6 +123225,10 @@ async function runStreamLoop(entry, projector) {
121106
123225
  clearLostTimer();
121107
123226
  }
121108
123227
  }
123228
+ function messageSeq(message) {
123229
+ const seq = message.seq;
123230
+ return typeof seq === "number" ? seq : null;
123231
+ }
121109
123232
  function turnImageDataUrls(turn) {
121110
123233
  const raw = turn.attachments;
121111
123234
  if (!raw) return [];
@@ -121141,12 +123264,6 @@ async function startTurn4(session, turn) {
121141
123264
  failTurnBeforeStart(db2, session.id, turn.id, `Failed to resolve repoburg backend: ${err.message}`);
121142
123265
  return;
121143
123266
  }
121144
- const pinned = sessionMap3.get(session.id);
121145
- if (pinned && pinned.baseUrl !== baseUrl) {
121146
- console.warn(
121147
- `[repoburg] resolved backend ${baseUrl} differs from pinned ${pinned.baseUrl} for session ${session.id} \u2014 keeping the pinned entry.`
121148
- );
121149
- }
121150
123267
  void registerMiniAppMcp(baseUrl, session.cwd ?? "");
121151
123268
  const firstInput = !turn.thread_id && !sessionMap3.has(session.id) && !session.external_thread_id;
121152
123269
  let entry;
@@ -121157,6 +123274,11 @@ async function startTurn4(session, turn) {
121157
123274
  failTurnBeforeStart(db2, session.id, turn.id, `Failed to create repoburg session: ${err.message}`);
121158
123275
  return;
121159
123276
  }
123277
+ if (entry.baseUrl !== baseUrl && (!entry.activeTurn || entry.activeTurn.projector.isDone)) {
123278
+ console.warn(`[repoburg] session ${session.id}: backend moved from ${entry.baseUrl} to ${baseUrl}`);
123279
+ entry.baseUrl = baseUrl;
123280
+ entry.client = client;
123281
+ }
121160
123282
  const wantedModel = session.model ?? null;
121161
123283
  const wantedEffort = mapReasoningEffort(session.model, session.model_reasoning_effort);
121162
123284
  if (wantedModel !== entry.modelId || wantedEffort !== entry.reasoningEffort) {
@@ -121176,6 +123298,16 @@ async function startTurn4(session, turn) {
121176
123298
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
121177
123299
  setSessionStatus3(db2, session.id, 1, "running", now);
121178
123300
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
123301
+ const state = await getAgentRuntimeState(entry.baseUrl, entry.repoburgSessionId).catch(() => null);
123302
+ if (state) {
123303
+ const cursor = {
123304
+ bootId: state.bootId,
123305
+ firstSeq: state.lastSeq + 1,
123306
+ baseUrl: entry.baseUrl,
123307
+ runtimeSessionId: entry.repoburgSessionId
123308
+ };
123309
+ db2.prepare("UPDATE turns SET stream_cursor = ? WHERE id = ?").run(JSON.stringify(cursor), turn.id);
123310
+ }
121179
123311
  const projector = new TurnProjector({
121180
123312
  agentPaneSessionId: session.id,
121181
123313
  turnId: turn.id,
@@ -121183,9 +123315,19 @@ async function startTurn4(session, turn) {
121183
123315
  client: entry.client,
121184
123316
  // Late-bound — the window resolves from the runtime catalog while the
121185
123317
  // turn streams and is read at turn completion.
121186
- getContextWindow: () => entry.contextWindow
123318
+ getContextWindow: () => entry.contextWindow,
123319
+ ...state ? { firstSeq: state.lastSeq + 1 } : {}
121187
123320
  });
121188
- entry.activeTurn = { turnId: turn.id, projector, sseAbort: new AbortController(), cancelled: false };
123321
+ entry.activeTurn = {
123322
+ turnId: turn.id,
123323
+ projector,
123324
+ sseAbort: new AbortController(),
123325
+ cancelled: false,
123326
+ // The stream opens after this point: messages the turn emits before it
123327
+ // connects are sent again (Last-Event-ID).
123328
+ ...state ? { bootId: state.bootId } : {},
123329
+ lastSeq: state ? state.lastSeq : null
123330
+ };
121189
123331
  void ensureContextWindow(entry);
121190
123332
  runStreamLoop(entry, projector).catch((err) => {
121191
123333
  console.error("[repoburg] stream loop crashed:", err);
@@ -121203,6 +123345,102 @@ async function startTurn4(session, turn) {
121203
123345
  failTurn3(entry, err.message);
121204
123346
  }
121205
123347
  }
123348
+ function parseCursor(raw) {
123349
+ if (!raw) return null;
123350
+ try {
123351
+ const cursor = JSON.parse(raw);
123352
+ if (typeof cursor.bootId !== "string" || typeof cursor.firstSeq !== "number" || typeof cursor.baseUrl !== "string" || typeof cursor.runtimeSessionId !== "string") {
123353
+ return null;
123354
+ }
123355
+ return cursor;
123356
+ } catch {
123357
+ return null;
123358
+ }
123359
+ }
123360
+ var ADOPT_STATE_ATTEMPTS = 3;
123361
+ var ADOPT_STATE_RETRY_MS = 300;
123362
+ async function adoptionState(cursor) {
123363
+ for (let attempt = 1; ; attempt++) {
123364
+ try {
123365
+ return await getAgentRuntimeState(cursor.baseUrl, cursor.runtimeSessionId);
123366
+ } catch (err) {
123367
+ if (attempt >= ADOPT_STATE_ATTEMPTS) throw err;
123368
+ await new Promise((resolve) => setTimeout(resolve, ADOPT_STATE_RETRY_MS));
123369
+ }
123370
+ }
123371
+ }
123372
+ async function adoptRepoburgTurns(db2, result) {
123373
+ if (!sessionHostFlags().repoburg) return;
123374
+ const rows = db2.prepare(
123375
+ `SELECT t.id, t.session_id, t.thread_id, t.stream_cursor, s.model
123376
+ FROM turns t JOIN sessions s ON s.id = t.session_id
123377
+ WHERE t.status = 'running' AND s.runtime_type = 'repoburg' AND t.stream_cursor IS NOT NULL`
123378
+ ).all();
123379
+ for (const row of rows) {
123380
+ const cursor = parseCursor(row.stream_cursor);
123381
+ if (!cursor) continue;
123382
+ let state;
123383
+ try {
123384
+ state = await adoptionState(cursor);
123385
+ } catch (err) {
123386
+ console.warn(`[repoburg] backend of turn ${row.id} unreachable; recovery takes it:`, err.message);
123387
+ continue;
123388
+ }
123389
+ if (!state) continue;
123390
+ if (state.bootId !== cursor.bootId) {
123391
+ db2.prepare("UPDATE items SET status = ?, updated_at = ? WHERE turn_id = ? AND status = ?").run(
123392
+ "failed",
123393
+ (/* @__PURE__ */ new Date()).toISOString(),
123394
+ row.id,
123395
+ "in_progress"
123396
+ );
123397
+ failTurnBeforeStart(db2, row.session_id, row.id, BACKEND_RESTARTED_ERROR);
123398
+ result.turnIds.add(row.id);
123399
+ continue;
123400
+ }
123401
+ const entry = {
123402
+ agentPaneSessionId: row.session_id,
123403
+ repoburgSessionId: cursor.runtimeSessionId,
123404
+ client: new RepoburgHttpClient(cursor.baseUrl),
123405
+ baseUrl: cursor.baseUrl,
123406
+ modelId: row.model,
123407
+ reasoningEffort: void 0,
123408
+ // re-pushed on the next turn
123409
+ threadId: row.thread_id,
123410
+ contextWindow: null,
123411
+ modelsResolved: false,
123412
+ activeTurn: null
123413
+ };
123414
+ sessionMap3.set(row.thread_id ? `${row.session_id}:thread:${row.thread_id}` : row.session_id, entry);
123415
+ const projector = new TurnProjector({
123416
+ agentPaneSessionId: row.session_id,
123417
+ turnId: row.id,
123418
+ repoburgSessionId: cursor.runtimeSessionId,
123419
+ client: entry.client,
123420
+ getContextWindow: () => entry.contextWindow,
123421
+ firstSeq: cursor.firstSeq
123422
+ });
123423
+ entry.activeTurn = {
123424
+ turnId: row.id,
123425
+ projector,
123426
+ sseAbort: new AbortController(),
123427
+ cancelled: false,
123428
+ bootId: cursor.bootId,
123429
+ // The backend sends the turn's messages again from its first one.
123430
+ lastSeq: cursor.firstSeq - 1
123431
+ };
123432
+ void ensureContextWindow(entry);
123433
+ runStreamLoop(entry, projector).catch((err) => {
123434
+ console.error("[repoburg] stream loop crashed:", err);
123435
+ failTurn3(entry, `Stream loop failed: ${err.message}`);
123436
+ });
123437
+ result.turnIds.add(row.id);
123438
+ result.sessionIds.add(row.session_id);
123439
+ result.entries.add(runtimeEntryKey(row.session_id, row.thread_id));
123440
+ console.log(`[repoburg] adopted turn ${row.id}: replaying from message ${cursor.firstSeq}`);
123441
+ }
123442
+ }
123443
+ registerRuntimeAdopter("repoburg", adoptRepoburgTurns);
121206
123444
  async function interruptTurn3(sessionId, threadId) {
121207
123445
  let entry = threadId ? sessionMap3.get(`${sessionId}:thread:${threadId}`) : sessionMap3.get(sessionId);
121208
123446
  if (!threadId && !entry?.activeTurn) {
@@ -121373,6 +123611,7 @@ registerProvider("repoburg", repoburgProvider);
121373
123611
  async function createAgentPaneApp(dbPath, opts = {}) {
121374
123612
  const allowRequest = opts.allowRequest ?? isLocalRequest;
121375
123613
  initDb(dbPath);
123614
+ setPaneDataDir(dbPath === ":memory:" ? null : path16.dirname(path16.resolve(dbPath)));
121376
123615
  const fastify = (0, import_fastify.default)({ logger: true, bodyLimit: 50 * 1024 * 1024 });
121377
123616
  fastify.addHook("onRequest", async (request, reply) => {
121378
123617
  if (!allowRequest(request.headers.origin, request.headers.host)) {
@@ -121398,19 +123637,32 @@ async function createAgentPaneApp(dbPath, opts = {}) {
121398
123637
  await registerSidecarRoutes(fastify);
121399
123638
  await registerUsageRoutes(fastify);
121400
123639
  await registerClaudeSessionRoutes(fastify);
123640
+ await registerSessionHostRoutes(fastify);
121401
123641
  const wss3 = initWs(allowRequest);
121402
123642
  initTerminalWs(allowRequest);
123643
+ trackStreams();
121403
123644
  wss3.on("connection", (ws) => {
121404
123645
  ws.send(JSON.stringify({ event: "background_tasks:snapshot", data: { sessions: listAllBackgroundTasks() } }));
121405
123646
  ws.send(JSON.stringify({ event: "signed_out_turns:snapshot", data: { turns: listSignedOutTurns(getDb()) } }));
123647
+ ws.send(JSON.stringify({ event: "streams:snapshot", data: streamsSnapshot() }));
121406
123648
  });
121407
123649
  return { fastify, wss: wss3 };
121408
123650
  }
121409
123651
 
121410
123652
  // src/host-lifecycle.ts
121411
- function startHostServices() {
121412
- startAutoResume();
123653
+ function startHostServices(opts = {}) {
123654
+ setSessionHostDaemonUrl(opts.daemonUrl);
123655
+ const started = adoptSessionHosts().catch((err) => {
123656
+ console.error("[session-host] adoption failed:", err);
123657
+ return lastAdoption();
123658
+ }).then((adopted) => {
123659
+ startAutoResume({ skip: adopted });
123660
+ }).catch((err) => {
123661
+ console.error("[resume] automatic resume failed to start:", err);
123662
+ });
123663
+ setStartupGate(started);
121413
123664
  void getVscodeWebManager().reapOrphans();
123665
+ return started;
121414
123666
  }
121415
123667
  async function shutdownHost() {
121416
123668
  stopAutoResume();
@@ -121418,12 +123670,77 @@ async function shutdownHost() {
121418
123670
  await shutdownAllProviders();
121419
123671
  await getVscodeWebManager().stopAll();
121420
123672
  }
123673
+
123674
+ // src/providers/agents.ts
123675
+ function runningAgents(db2 = getDb()) {
123676
+ const rows = db2.prepare(
123677
+ `SELECT s.runtime_type AS runtime, COUNT(*) AS n
123678
+ FROM turns t JOIN sessions s ON s.id = t.session_id
123679
+ WHERE t.status = 'running'
123680
+ GROUP BY s.runtime_type`
123681
+ ).all();
123682
+ const counts = { claude: 0, codex: 0, repoburg: 0 };
123683
+ for (const row of rows) {
123684
+ if (row.runtime === "claude" || row.runtime === "codex" || row.runtime === "repoburg") counts[row.runtime] = row.n;
123685
+ }
123686
+ return counts;
123687
+ }
123688
+ function liveTurns(db2) {
123689
+ return db2.prepare(
123690
+ `SELECT t.id, t.session_id, t.thread_id, s.runtime_type
123691
+ FROM turns t JOIN sessions s ON s.id = t.session_id
123692
+ WHERE t.status IN ('pending', 'running')
123693
+ ORDER BY t.created_at`
123694
+ ).all();
123695
+ }
123696
+ function abortLeftover(db2, turn) {
123697
+ const now = (/* @__PURE__ */ new Date()).toISOString();
123698
+ db2.prepare("UPDATE turns SET status = 'aborted', updated_at = ? WHERE id = ? AND status IN ('pending', 'running')").run(
123699
+ now,
123700
+ turn.id
123701
+ );
123702
+ markResumeCancelled(db2, turn.id);
123703
+ recomputeSessionRunning(db2, turn.session_id);
123704
+ broadcast("turn:cancelled", { sessionId: turn.session_id, turnId: turn.id });
123705
+ }
123706
+ async function stopAllAgents() {
123707
+ const db2 = getDb();
123708
+ const stopped = /* @__PURE__ */ new Set();
123709
+ for (let round = 0; round < 3; round++) {
123710
+ const turns = liveTurns(db2).filter((t) => !stopped.has(t.id));
123711
+ if (turns.length === 0) break;
123712
+ for (const turn of turns) {
123713
+ if (!hasProvider(turn.runtime_type)) continue;
123714
+ try {
123715
+ await getProvider(turn.runtime_type).interruptTurn(turn.session_id, turn.thread_id ?? void 0);
123716
+ } catch (err) {
123717
+ console.error(`[agents] could not stop turn ${turn.id}:`, err.message);
123718
+ }
123719
+ }
123720
+ for (const turn of turns) {
123721
+ const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turn.id);
123722
+ if (row && row.status !== "pending" && row.status !== "running") stopped.add(turn.id);
123723
+ }
123724
+ }
123725
+ for (const turn of liveTurns(db2)) {
123726
+ abortLeftover(db2, turn);
123727
+ stopped.add(turn.id);
123728
+ }
123729
+ const hosts = await shutDownAllHosts();
123730
+ const failItem = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE turn_id = ? AND status = 'in_progress'");
123731
+ const now = (/* @__PURE__ */ new Date()).toISOString();
123732
+ for (const id of stopped) failItem.run(now, id);
123733
+ console.log(`[agents] stopped ${stopped.size} turn(s) and ${hosts} session host(s)`);
123734
+ return { turns: stopped.size, hosts };
123735
+ }
121421
123736
  export {
121422
123737
  createAgentPaneApp,
121423
123738
  handleTerminalUpgrade,
121424
123739
  handleVscodeWebUpgrade,
123740
+ runningAgents,
121425
123741
  shutdownHost as shutdownAllProviders,
121426
- startHostServices as startAutoResume
123742
+ startHostServices as startAutoResume,
123743
+ stopAllAgents
121427
123744
  };
121428
123745
  /*! Bundled license information:
121429
123746