repoburg 1.3.302 → 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 (37) 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 +4 -4
  33. package/tabtape/extension/dist/manifest.json +1 -1
  34. package/tabtape/extension/dist/recorder.js +51 -39
  35. package/tabtape/extension/dist/recorder.js.map +1 -1
  36. package/tabtape/ui/dist/build-info.json +4 -4
  37. 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'");
@@ -41333,6 +41364,64 @@ function getWss() {
41333
41364
  return wss;
41334
41365
  }
41335
41366
 
41367
+ // src/ws/streams.ts
41368
+ var TURN_ENDS = /* @__PURE__ */ new Set(["turn:completed", "turn:failed", "turn:cancelled", "turn:interrupted", "turn:resuming"]);
41369
+ var streams = /* @__PURE__ */ new Map();
41370
+ function keyOf(sessionId, turnId, itemId) {
41371
+ return `${sessionId}
41372
+ ${turnId}
41373
+ ${itemId}`;
41374
+ }
41375
+ function noteDelta(p) {
41376
+ if (!p.sessionId || !p.turnId || !p.itemId || typeof p.delta !== "string") return;
41377
+ const key = keyOf(p.sessionId, p.turnId, p.itemId);
41378
+ const stream = streams.get(key);
41379
+ if (stream) stream.text += p.delta;
41380
+ else streams.set(key, { sessionId: p.sessionId, turnId: p.turnId, itemId: p.itemId, text: p.delta });
41381
+ }
41382
+ function noteItem(p) {
41383
+ const itemId = p.item?.external_item_id;
41384
+ if (!p.sessionId || !p.turnId || !itemId) return;
41385
+ const key = keyOf(p.sessionId, p.turnId, itemId);
41386
+ if (p.item?.status === "in_progress") {
41387
+ const text2 = p.item.data?.text;
41388
+ if (typeof text2 === "string") streams.set(key, { sessionId: p.sessionId, turnId: p.turnId, itemId, text: text2 });
41389
+ return;
41390
+ }
41391
+ streams.delete(key);
41392
+ }
41393
+ function dropTurn(p) {
41394
+ for (const [key, stream] of streams) {
41395
+ if (stream.turnId === p.turnId && stream.sessionId === p.sessionId) streams.delete(key);
41396
+ }
41397
+ }
41398
+ function forgetStreams(sessionId) {
41399
+ for (const [key, stream] of streams) if (stream.sessionId === sessionId) streams.delete(key);
41400
+ }
41401
+ function liveStreams(sessionId) {
41402
+ return [...streams.values()].filter((stream) => sessionId === void 0 || stream.sessionId === sessionId).map((stream) => ({ ...stream }));
41403
+ }
41404
+ function streamsSnapshot() {
41405
+ return { sessionId: null, streams: liveStreams() };
41406
+ }
41407
+ function resendStreams(sessionId) {
41408
+ const snapshot = { sessionId, streams: liveStreams(sessionId) };
41409
+ broadcast("streams:snapshot", snapshot);
41410
+ }
41411
+ var untap = null;
41412
+ function trackStreams() {
41413
+ if (untap) return;
41414
+ untap = tapBroadcast((event, data) => {
41415
+ try {
41416
+ if (event === "item:delta") noteDelta(data);
41417
+ else if (event === "item:started" || event === "item:updated" || event === "item:completed") {
41418
+ noteItem(data);
41419
+ } else if (TURN_ENDS.has(event)) dropTurn(data);
41420
+ } catch {
41421
+ }
41422
+ });
41423
+ }
41424
+
41336
41425
  // ../shared/terminal-protocol.ts
41337
41426
  var TERMINAL_WS_PATH = "/ws/terminal";
41338
41427
  var TERMINAL_CLOSE = {
@@ -42484,7 +42573,11 @@ function markResumeCancelled(db2, turnId) {
42484
42573
  db2.prepare("UPDATE turns SET resume_state = 'cancelled', resume_at = NULL WHERE id = ?").run(turnId);
42485
42574
  updateLatestInterruptionItem(db2, turn.session_id, turnId, { outcome: "cancelled" });
42486
42575
  }
42576
+ function runtimeEntryKey(sessionId, threadId) {
42577
+ return threadId ? `${sessionId}\0${threadId}` : sessionId;
42578
+ }
42487
42579
  function recoverInterruptedTurns(db2, opts) {
42580
+ const skip = opts.skip ?? { turnIds: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
42488
42581
  const live = db2.prepare(
42489
42582
  `SELECT t.id, t.session_id, t.status, t.thread_id, t.interrupted_at, t.interrupt_reason, t.resume_state,
42490
42583
  t.resume_attempts, t.updated_at, s.runtime_type,
@@ -42492,13 +42585,25 @@ function recoverInterruptedTurns(db2, opts) {
42492
42585
  FROM turns t JOIN sessions s ON s.id = t.session_id
42493
42586
  WHERE t.status IN ('pending', 'running')
42494
42587
  ORDER BY t.created_at ASC`
42495
- ).all();
42588
+ ).all().filter((t) => !skip.turnIds.has(t.id));
42496
42589
  const now = (/* @__PURE__ */ new Date()).toISOString();
42497
- db2.prepare(
42590
+ const open = db2.prepare(
42591
+ `SELECT i.id, i.type, t.session_id, t.thread_id FROM items i JOIN turns t ON t.id = i.turn_id
42592
+ WHERE i.status = 'in_progress'`
42593
+ ).all();
42594
+ const orphaned = open.filter((i) => !skip.entries.has(runtimeEntryKey(i.session_id, i.thread_id)));
42595
+ const stopTask2 = db2.prepare(
42498
42596
  `UPDATE items SET data = json_set(COALESCE(data, '{}'), '$.status', 'stopped')
42499
- WHERE status = 'in_progress' AND type = 'background_task' AND json_valid(COALESCE(data, '{}'))`
42500
- ).run();
42501
- const items = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE status = 'in_progress'").run(now);
42597
+ WHERE id = ? AND json_valid(COALESCE(data, '{}'))`
42598
+ );
42599
+ const failItem = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE id = ?");
42600
+ const items = { changes: 0 };
42601
+ db2.transaction(() => {
42602
+ for (const item of orphaned) {
42603
+ if (item.type === "background_task") stopTask2.run(item.id);
42604
+ items.changes += failItem.run(now, item.id).changes;
42605
+ }
42606
+ })();
42502
42607
  let waiting = 0;
42503
42608
  let failed = 0;
42504
42609
  for (const turn of live) {
@@ -42597,7 +42702,7 @@ function startAutoResume(opts = {}) {
42597
42702
  orphansReaped = reapAllOrphans().catch((err) => {
42598
42703
  console.error("[resume] could not clean up after the previous host:", err);
42599
42704
  });
42600
- const summary = recoverInterruptedTurns(getDb(), { canResume: canResumeRuntime });
42705
+ const summary = recoverInterruptedTurns(getDb(), { canResume: canResumeRuntime, skip: opts.skip });
42601
42706
  unsubscribe = onTurnInterrupted((event) => {
42602
42707
  scheduleScan(event.reason === "network" ? cfg.networkDelayMs : cfg.delayMs);
42603
42708
  });
@@ -43282,9 +43387,9 @@ async function browseFolder(input, opts = {}) {
43282
43387
  const atHome = dir === nodePath.resolve(home);
43283
43388
  const folders = await Promise.all(
43284
43389
  names.slice(0, limit).map(async (name) => {
43285
- const path13 = nodePath.join(dir, name);
43390
+ const path17 = nodePath.join(dir, name);
43286
43391
  const skipProbe = atHome && HOME_STANDARD_FOLDERS.has(name) || dir === "/Volumes";
43287
- return { name, path: path13, git: !skipProbe && await exists(nodePath.join(path13, ".git")) };
43392
+ return { name, path: path17, git: !skipProbe && await exists(nodePath.join(path17, ".git")) };
43288
43393
  })
43289
43394
  );
43290
43395
  const parent = nodePath.dirname(dir);
@@ -43322,11 +43427,11 @@ async function registerWorkspaceRoutes(fastify) {
43322
43427
  }
43323
43428
  }
43324
43429
  }, async (request, reply) => {
43325
- const { path: path13, label = null } = request.body || {};
43326
- if (!path13 || !path13.trim()) {
43430
+ const { path: path17, label = null } = request.body || {};
43431
+ if (!path17 || !path17.trim()) {
43327
43432
  return reply.code(400).send({ error: "Path is required" });
43328
43433
  }
43329
- const resolved = await resolveWorkspacePath(path13);
43434
+ const resolved = await resolveWorkspacePath(path17);
43330
43435
  if ("error" in resolved) {
43331
43436
  return reply.code(400).send({ error: resolved.error });
43332
43437
  }
@@ -43368,8 +43473,8 @@ async function registerWorkspaceRoutes(fastify) {
43368
43473
  "-e",
43369
43474
  'POSIX path of (choose folder with prompt "Select a workspace directory")'
43370
43475
  ]);
43371
- const path13 = stdout.trim().replace(/\/$/, "");
43372
- return { path: path13 };
43476
+ const path17 = stdout.trim().replace(/\/$/, "");
43477
+ return { path: path17 };
43373
43478
  } catch {
43374
43479
  return reply.code(204).send({ cancelled: true });
43375
43480
  }
@@ -43385,11 +43490,11 @@ async function registerWorkspaceRoutes(fastify) {
43385
43490
  }
43386
43491
  }
43387
43492
  }, async (request, reply) => {
43388
- const { path: path13 } = request.body || {};
43389
- if (!path13 || !path13.trim()) {
43493
+ const { path: path17 } = request.body || {};
43494
+ if (!path17 || !path17.trim()) {
43390
43495
  return reply.code(400).send({ error: "Path is required" });
43391
43496
  }
43392
- const trimmedPath = path13.trim();
43497
+ const trimmedPath = path17.trim();
43393
43498
  const db2 = getDb();
43394
43499
  const existing = db2.prepare("SELECT * FROM workspaces WHERE path = ?").get(trimmedPath);
43395
43500
  if (existing) {
@@ -43644,11 +43749,18 @@ import { readFileSync } from "node:fs";
43644
43749
  // src/codex/app-server-client.ts
43645
43750
  import { spawn } from "node:child_process";
43646
43751
  import { EventEmitter } from "node:events";
43752
+ var REPLAY_DONE_METHOD = "agentpane/replayDone";
43753
+ var REPLAY_MARKER = JSON.stringify({ method: REPLAY_DONE_METHOD });
43647
43754
  var REQUEST_TIMEOUT_MS = 3e4;
43648
43755
  var CLOSE_GRACE_MS = 2e3;
43756
+ function appServerCommand(options) {
43757
+ const binary = options.binaryPath ?? process.env.CODEX_BIN ?? "codex";
43758
+ const args = ["app-server", ...options.launchArgs ?? []];
43759
+ return /\.m?js$/.test(binary) ? { command: process.execPath, args: [binary, ...args] } : { command: binary, args };
43760
+ }
43649
43761
  var AppServerClient = class {
43650
43762
  proc;
43651
- nextId = 1;
43763
+ nextId;
43652
43764
  pending = /* @__PURE__ */ new Map();
43653
43765
  notificationHandlers = /* @__PURE__ */ new Map();
43654
43766
  requestHandlers = /* @__PURE__ */ new Map();
@@ -43659,15 +43771,22 @@ var AppServerClient = class {
43659
43771
  clientInfo;
43660
43772
  /** Bound stdout listener — removed in close() so stale data is not processed. */
43661
43773
  stdoutListener = (chunk) => this.onStdoutData(chunk);
43774
+ /** Replaying (attach): server requests wait here for the replay's end. */
43775
+ replay;
43662
43776
  events = new EventEmitter();
43663
43777
  constructor(options) {
43664
- const binary = options.binaryPath ?? "codex";
43665
- const args = ["app-server", ...options.launchArgs ?? []];
43666
- this.proc = spawn(binary, args, {
43667
- cwd: options.cwd,
43668
- env: { ...process.env, ...options.env },
43669
- stdio: ["pipe", "pipe", "pipe"]
43670
- });
43778
+ this.nextId = options.firstRequestId ?? 1;
43779
+ this.replay = options.replaying ? /* @__PURE__ */ new Map() : null;
43780
+ if (options.process) {
43781
+ this.proc = options.process;
43782
+ } else {
43783
+ const { command, args } = appServerCommand(options);
43784
+ this.proc = spawn(command, args, {
43785
+ cwd: options.cwd,
43786
+ env: { ...process.env, ...options.env },
43787
+ stdio: ["pipe", "pipe", "pipe"]
43788
+ });
43789
+ }
43671
43790
  this.clientInfo = options.clientInfo ?? { name: "agentpane", title: "AgentPane", version: "1.0.0" };
43672
43791
  this.proc.stdin?.on("error", () => {
43673
43792
  });
@@ -43738,6 +43857,23 @@ var AppServerClient = class {
43738
43857
  isClosed() {
43739
43858
  return this.closed;
43740
43859
  }
43860
+ /** True until the replay marker of an attached process. */
43861
+ get replaying() {
43862
+ return this.replay !== null;
43863
+ }
43864
+ /** Stop talking to the process and leave it running (the daemon goes away
43865
+ * and its session host keeps the app-server). Pending requests fail;
43866
+ * nothing is sent to the process. */
43867
+ detach() {
43868
+ if (this.closed) return;
43869
+ this.closed = true;
43870
+ this.proc.stdout?.removeListener("data", this.stdoutListener);
43871
+ for (const [id, entry] of this.pending) {
43872
+ clearTimeout(entry.timer);
43873
+ entry.reject(new Error("AppServerClient detached"));
43874
+ this.pending.delete(id);
43875
+ }
43876
+ }
43741
43877
  /** Pid of the app-server process (the codex launcher), undefined when it never started. */
43742
43878
  get pid() {
43743
43879
  return this.proc.pid;
@@ -43804,8 +43940,13 @@ var AppServerClient = class {
43804
43940
  }
43805
43941
  const hasId = "id" in msg && typeof msg.id === "number";
43806
43942
  const hasMethod = "method" in msg && typeof msg.method === "string";
43943
+ if (msg.method === REPLAY_DONE_METHOD && !hasId) {
43944
+ this.endReplay();
43945
+ return;
43946
+ }
43807
43947
  if (hasId && hasMethod) {
43808
- this.handleServerRequest(msg.method, msg.id, msg.params);
43948
+ if (this.replay) this.replay.set(msg.id, { method: msg.method, params: msg.params });
43949
+ else this.handleServerRequest(msg.method, msg.id, msg.params);
43809
43950
  return;
43810
43951
  }
43811
43952
  if (hasId) {
@@ -43824,6 +43965,10 @@ var AppServerClient = class {
43824
43965
  }
43825
43966
  if (hasMethod) {
43826
43967
  const method = msg.method;
43968
+ if (method === "serverRequest/resolved" && this.replay) {
43969
+ const requestId = msg.params?.requestId;
43970
+ if (typeof requestId === "number") this.replay.delete(requestId);
43971
+ }
43827
43972
  const handlers = this.notificationHandlers.get(method);
43828
43973
  if (handlers) {
43829
43974
  for (const handler of handlers) {
@@ -43834,6 +43979,15 @@ var AppServerClient = class {
43834
43979
  return;
43835
43980
  }
43836
43981
  }
43982
+ /** The replay is over: answer the server requests that are still open,
43983
+ * then go live. */
43984
+ endReplay() {
43985
+ const held = this.replay;
43986
+ if (!held) return;
43987
+ this.replay = null;
43988
+ for (const [id, request] of held) this.handleServerRequest(request.method, id, request.params);
43989
+ this.events.emit("replayDone");
43990
+ }
43837
43991
  /**
43838
43992
  * Handle a server→client JSON-RPC request. The last registered handler
43839
43993
  * runs and its result is sent back; unhandled requests are declined with
@@ -44074,17 +44228,17 @@ async function registerPerfLogRoutes(fastify) {
44074
44228
  if (entries.length === 0) {
44075
44229
  return reply.send({ written: 0 });
44076
44230
  }
44077
- const path13 = perfLogPath();
44231
+ const path17 = perfLogPath();
44078
44232
  try {
44079
- mkdirSync(dirname(path13), { recursive: true });
44233
+ mkdirSync(dirname(path17), { recursive: true });
44080
44234
  try {
44081
- if (statSync(path13).size > MAX_BYTES) {
44082
- renameSync(path13, `${path13}.1`);
44235
+ if (statSync(path17).size > MAX_BYTES) {
44236
+ renameSync(path17, `${path17}.1`);
44083
44237
  }
44084
44238
  } catch {
44085
44239
  }
44086
44240
  const lines = entries.map((e) => `${new Date(e.t).toISOString()} [${oneLine(e.cat)}] ${oneLine(e.msg)}`).join("\n");
44087
- appendFileSync(path13, `${lines}
44241
+ appendFileSync(path17, `${lines}
44088
44242
  `, "utf-8");
44089
44243
  return reply.send({ written: entries.length });
44090
44244
  } catch (err) {
@@ -100227,8 +100381,8 @@ function checkJsSyntax(js) {
100227
100381
  }
100228
100382
  }
100229
100383
  function compileAppJs(appId) {
100230
- const cached2 = cache.get(appId);
100231
- if (cached2) return cached2;
100384
+ const cached3 = cache.get(appId);
100385
+ if (cached3) return cached3;
100232
100386
  const tsSource = readAppFile(appId, APP_TS);
100233
100387
  let result;
100234
100388
  let logicFiles = [];
@@ -100314,8 +100468,8 @@ var runtimes = /* @__PURE__ */ new Map();
100314
100468
  var pendingCalls = /* @__PURE__ */ new Map();
100315
100469
  function loadRuntime(appId, workspace) {
100316
100470
  const key = runtimeKey(appId, workspace);
100317
- const cached2 = runtimes.get(key);
100318
- if (cached2) return cached2;
100471
+ const cached3 = runtimes.get(key);
100472
+ if (cached3) return cached3;
100319
100473
  const js = compileAppJs(appId).js;
100320
100474
  if (!js.trim()) return null;
100321
100475
  const manifest = readManifest(appId);
@@ -100529,7 +100683,7 @@ function handleUnhandledRejection(reason, promise2) {
100529
100683
  var stopSessionEvents = null;
100530
100684
  function startHeadlessEvents() {
100531
100685
  stopHeadlessEvents();
100532
- const untap = tapBroadcast((event, data) => {
100686
+ const untap2 = tapBroadcast((event, data) => {
100533
100687
  if (!SESSION_EVENTS.has(event)) return;
100534
100688
  setImmediate(() => {
100535
100689
  try {
@@ -100541,7 +100695,7 @@ function startHeadlessEvents() {
100541
100695
  });
100542
100696
  process.on("unhandledRejection", handleUnhandledRejection);
100543
100697
  stopSessionEvents = () => {
100544
- untap();
100698
+ untap2();
100545
100699
  process.off("unhandledRejection", handleUnhandledRejection);
100546
100700
  };
100547
100701
  }
@@ -101350,8 +101504,8 @@ async function loadFresh(timezone) {
101350
101504
  var cache2 = /* @__PURE__ */ new Map();
101351
101505
  var inflight = /* @__PURE__ */ new Map();
101352
101506
  function loadCcusage(timezone, fresh) {
101353
- const cached2 = cache2.get(timezone);
101354
- if (cached2 && !fresh) return Promise.resolve(cached2);
101507
+ const cached3 = cache2.get(timezone);
101508
+ if (cached3 && !fresh) return Promise.resolve(cached3);
101355
101509
  let run = inflight.get(timezone);
101356
101510
  if (!run) {
101357
101511
  run = loadFresh(timezone).then((result) => {
@@ -102533,10 +102687,10 @@ function mergeDefs(...defs) {
102533
102687
  function cloneDef(schema) {
102534
102688
  return mergeDefs(schema._zod.def);
102535
102689
  }
102536
- function getElementAtPath(obj2, path13) {
102537
- if (!path13)
102690
+ function getElementAtPath(obj2, path17) {
102691
+ if (!path17)
102538
102692
  return obj2;
102539
- return path13.reduce((acc, key) => acc?.[key], obj2);
102693
+ return path17.reduce((acc, key) => acc?.[key], obj2);
102540
102694
  }
102541
102695
  function promiseAllObject(promisesObj) {
102542
102696
  const keys = Object.keys(promisesObj);
@@ -102945,11 +103099,11 @@ function explicitlyAborted(x, startIndex = 0) {
102945
103099
  }
102946
103100
  return false;
102947
103101
  }
102948
- function prefixIssues(path13, issues) {
103102
+ function prefixIssues(path17, issues) {
102949
103103
  return issues.map((iss) => {
102950
103104
  var _a3;
102951
103105
  (_a3 = iss).path ?? (_a3.path = []);
102952
- iss.path.unshift(path13);
103106
+ iss.path.unshift(path17);
102953
103107
  return iss;
102954
103108
  });
102955
103109
  }
@@ -103096,16 +103250,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
103096
103250
  }
103097
103251
  function formatError(error51, mapper = (issue2) => issue2.message) {
103098
103252
  const fieldErrors = { _errors: [] };
103099
- const processError = (error52, path13 = []) => {
103253
+ const processError = (error52, path17 = []) => {
103100
103254
  for (const issue2 of error52.issues) {
103101
103255
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103102
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
103256
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103103
103257
  } else if (issue2.code === "invalid_key") {
103104
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103258
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103105
103259
  } else if (issue2.code === "invalid_element") {
103106
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103260
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103107
103261
  } else {
103108
- const fullpath = [...path13, ...issue2.path];
103262
+ const fullpath = [...path17, ...issue2.path];
103109
103263
  if (fullpath.length === 0) {
103110
103264
  fieldErrors._errors.push(mapper(issue2));
103111
103265
  } else {
@@ -103132,17 +103286,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
103132
103286
  }
103133
103287
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
103134
103288
  const result = { errors: [] };
103135
- const processError = (error52, path13 = []) => {
103289
+ const processError = (error52, path17 = []) => {
103136
103290
  var _a3, _b;
103137
103291
  for (const issue2 of error52.issues) {
103138
103292
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103139
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
103293
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103140
103294
  } else if (issue2.code === "invalid_key") {
103141
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103295
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103142
103296
  } else if (issue2.code === "invalid_element") {
103143
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
103297
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103144
103298
  } else {
103145
- const fullpath = [...path13, ...issue2.path];
103299
+ const fullpath = [...path17, ...issue2.path];
103146
103300
  if (fullpath.length === 0) {
103147
103301
  result.errors.push(mapper(issue2));
103148
103302
  continue;
@@ -103174,8 +103328,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
103174
103328
  }
103175
103329
  function toDotPath(_path) {
103176
103330
  const segs = [];
103177
- const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103178
- for (const seg of path13) {
103331
+ const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103332
+ for (const seg of path17) {
103179
103333
  if (typeof seg === "number")
103180
103334
  segs.push(`[${seg}]`);
103181
103335
  else if (typeof seg === "symbol")
@@ -115867,13 +116021,13 @@ function resolveRef(ref, ctx) {
115867
116021
  if (!ref.startsWith("#")) {
115868
116022
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
115869
116023
  }
115870
- const path13 = ref.slice(1).split("/").filter(Boolean);
115871
- if (path13.length === 0) {
116024
+ const path17 = ref.slice(1).split("/").filter(Boolean);
116025
+ if (path17.length === 0) {
115872
116026
  return ctx.rootSchema;
115873
116027
  }
115874
116028
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
115875
- if (path13[0] === defsKey) {
115876
- const key = path13[1];
116029
+ if (path17[0] === defsKey) {
116030
+ const key = path17[1];
115877
116031
  if (!key || !ctx.defs[key]) {
115878
116032
  throw new Error(`Reference not found: ${ref}`);
115879
116033
  }
@@ -116419,9 +116573,9 @@ function mapToolUse(block) {
116419
116573
  };
116420
116574
  }
116421
116575
  function deriveFileChangeData(input, toolName) {
116422
- const path13 = input.file_path ?? input.notebook_path ?? "";
116576
+ const path17 = input.file_path ?? input.notebook_path ?? "";
116423
116577
  const kind = toolName === "Write" ? "add" : "modify";
116424
- return { changes: [{ path: path13, kind }], status: "in_progress" };
116578
+ return { changes: [{ path: path17, kind }], status: "in_progress" };
116425
116579
  }
116426
116580
  function extractToolResultText(content) {
116427
116581
  if (!content) return "";
@@ -116952,6 +117106,746 @@ async function registerClaudeSessionRoutes(fastify) {
116952
117106
  );
116953
117107
  }
116954
117108
 
117109
+ // src/session-host/flags.ts
117110
+ import fs7 from "node:fs";
117111
+ import path11 from "node:path";
117112
+ var DEFAULT_FLAGS = {
117113
+ claude: true,
117114
+ codex: true,
117115
+ repoburg: true,
117116
+ adoption: true,
117117
+ noHostBusyMs: 30 * 6e4,
117118
+ noHostIdleMs: 5 * 6e4
117119
+ };
117120
+ var MIN_LIMIT_MS = 1e3;
117121
+ var MAX_LIMIT_MS = 7 * 24 * 60 * 6e4;
117122
+ var paneDataDir = null;
117123
+ var cached2 = null;
117124
+ function setPaneDataDir(dir) {
117125
+ paneDataDir = dir;
117126
+ cached2 = null;
117127
+ }
117128
+ function sessionHostsRoot() {
117129
+ const override = process.env.AGENT_PANE_SESSION_HOSTS_DIR;
117130
+ if (override) return path11.resolve(override);
117131
+ return paneDataDir ? path11.join(paneDataDir, "session-hosts") : null;
117132
+ }
117133
+ function flagsFilePath() {
117134
+ const root = sessionHostsRoot();
117135
+ if (process.env.AGENT_PANE_SESSION_HOSTS_DIR) return path11.join(path11.dirname(root), "session-hosts.json");
117136
+ return paneDataDir ? path11.join(paneDataDir, "session-hosts.json") : null;
117137
+ }
117138
+ function readFlagFile(file2) {
117139
+ if (!file2) return {};
117140
+ try {
117141
+ const parsed = JSON.parse(fs7.readFileSync(file2, "utf8"));
117142
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
117143
+ console.warn(`[session-host] ${file2} is not a JSON object; using the defaults`);
117144
+ } catch (err) {
117145
+ if (err.code !== "ENOENT") {
117146
+ console.warn(`[session-host] ${file2} could not be read (${err.message}); using the defaults`);
117147
+ }
117148
+ }
117149
+ return {};
117150
+ }
117151
+ function bool(value, fallback) {
117152
+ return typeof value === "boolean" ? value : fallback;
117153
+ }
117154
+ function minutes(value, fallbackMs) {
117155
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallbackMs;
117156
+ const ms = Math.round(value * 6e4);
117157
+ return ms >= MIN_LIMIT_MS && ms <= MAX_LIMIT_MS ? ms : fallbackMs;
117158
+ }
117159
+ function envBool(name) {
117160
+ const v = process.env[name];
117161
+ if (v === "0" || v === "false") return false;
117162
+ if (v === "1" || v === "true") return true;
117163
+ return void 0;
117164
+ }
117165
+ function envMs(name) {
117166
+ const v = Number(process.env[name]);
117167
+ return Number.isFinite(v) && v >= MIN_LIMIT_MS && v <= MAX_LIMIT_MS ? Math.round(v) : void 0;
117168
+ }
117169
+ function resolveFlags(file2) {
117170
+ const flags = {
117171
+ claude: bool(file2.claude, DEFAULT_FLAGS.claude),
117172
+ codex: bool(file2.codex, DEFAULT_FLAGS.codex),
117173
+ repoburg: bool(file2.repoburg, DEFAULT_FLAGS.repoburg),
117174
+ adoption: bool(file2.adoption, DEFAULT_FLAGS.adoption),
117175
+ noHostBusyMs: minutes(file2.noHostBusyMin, DEFAULT_FLAGS.noHostBusyMs),
117176
+ noHostIdleMs: minutes(file2.noHostIdleMin, DEFAULT_FLAGS.noHostIdleMs)
117177
+ };
117178
+ if (envBool("AGENT_PANE_SESSION_HOSTS") === false) {
117179
+ flags.claude = false;
117180
+ flags.codex = false;
117181
+ }
117182
+ flags.claude = envBool("AGENT_PANE_SESSION_HOSTS_CLAUDE") ?? flags.claude;
117183
+ flags.codex = envBool("AGENT_PANE_SESSION_HOSTS_CODEX") ?? flags.codex;
117184
+ flags.repoburg = envBool("AGENT_PANE_SESSION_HOSTS_REPOBURG") ?? flags.repoburg;
117185
+ flags.adoption = envBool("AGENT_PANE_SESSION_HOSTS_ADOPTION") ?? flags.adoption;
117186
+ flags.noHostBusyMs = envMs("AGENT_PANE_SESSION_HOST_BUSY_MS") ?? flags.noHostBusyMs;
117187
+ flags.noHostIdleMs = envMs("AGENT_PANE_SESSION_HOST_IDLE_MS") ?? flags.noHostIdleMs;
117188
+ return flags;
117189
+ }
117190
+ function sessionHostFlags() {
117191
+ if (!cached2) cached2 = resolveFlags(readFlagFile(flagsFilePath()));
117192
+ return cached2;
117193
+ }
117194
+ function hostsEnabledFor(runtime) {
117195
+ return sessionHostsRoot() !== null && sessionHostFlags()[runtime];
117196
+ }
117197
+
117198
+ // src/session-host/protocol.ts
117199
+ var SESSION_HOST_PROTOCOL = 1;
117200
+ var SUPPORTED_PROTOCOLS = [1];
117201
+ var LOG_HEADER_PREFIX = "session-host-log v1 oldest=";
117202
+ var LOG_HEADER_DIGITS = 20;
117203
+ var LOG_HEADER_LEN = LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS + 1;
117204
+
117205
+ // src/session-host/registry.ts
117206
+ import { randomBytes, randomUUID as randomUUID2 } from "node:crypto";
117207
+ import fs9 from "node:fs";
117208
+ import path13 from "node:path";
117209
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
117210
+
117211
+ // src/session-host/client.ts
117212
+ import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
117213
+ import { EventEmitter as EventEmitter2 } from "node:events";
117214
+ import fs8 from "node:fs";
117215
+ import net2 from "node:net";
117216
+ import path12 from "node:path";
117217
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
117218
+ var HostRequestError = class extends Error {
117219
+ reply;
117220
+ constructor(reply) {
117221
+ super(`session host refused: ${reply.error}`);
117222
+ this.reply = reply;
117223
+ }
117224
+ };
117225
+ function hostScriptPath() {
117226
+ const override = process.env.AGENT_PANE_SESSION_HOST_SCRIPT;
117227
+ if (override) return override;
117228
+ const here = path12.dirname(fileURLToPath2(import.meta.url));
117229
+ const candidates = [
117230
+ path12.resolve(here, "../../scripts/session-host.mjs"),
117231
+ // src/session-host/ → backend/scripts
117232
+ path12.resolve(here, "../scripts/session-host.mjs")
117233
+ // dist bundle → backend/scripts
117234
+ ];
117235
+ for (const candidate of candidates) {
117236
+ if (fs8.existsSync(candidate)) return candidate;
117237
+ }
117238
+ return null;
117239
+ }
117240
+ function hostSocketPath(dir) {
117241
+ const direct = path12.join(dir, "sock");
117242
+ if (Buffer.byteLength(direct) < 100) return direct;
117243
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
117244
+ return path12.join("/tmp", `rbsh-${uid}`, path12.basename(dir), "sock");
117245
+ }
117246
+ function readJson(file2) {
117247
+ try {
117248
+ return JSON.parse(fs8.readFileSync(file2, "utf8"));
117249
+ } catch {
117250
+ return null;
117251
+ }
117252
+ }
117253
+ function readHostExit(dir) {
117254
+ return readJson(path12.join(dir, "exit.json"));
117255
+ }
117256
+ function readHostChild(dir) {
117257
+ return readJson(path12.join(dir, "child.json"));
117258
+ }
117259
+ function isPidAlive(pid) {
117260
+ if (!pid || pid <= 0) return false;
117261
+ try {
117262
+ process.kill(pid, 0);
117263
+ return true;
117264
+ } catch (err) {
117265
+ return err.code === "EPERM";
117266
+ }
117267
+ }
117268
+ function processStartTime(pid) {
117269
+ return new Promise((resolve) => {
117270
+ execFile3("ps", ["-o", "etime=", "-p", String(pid)], (err, stdout) => {
117271
+ const m = err ? null : /^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
117272
+ if (!m) {
117273
+ resolve(null);
117274
+ return;
117275
+ }
117276
+ const secs = Number(m[1] ?? 0) * 86400 + Number(m[2] ?? 0) * 3600 + Number(m[3]) * 60 + Number(m[4]);
117277
+ resolve(Date.now() - secs * 1e3);
117278
+ });
117279
+ });
117280
+ }
117281
+ var PID_START_TOLERANCE_MS = 3e4;
117282
+ async function verifiedHostPids(dir) {
117283
+ const info = readHostChild(dir);
117284
+ const started = info ? Date.parse(info.startedAt) : NaN;
117285
+ const check2 = async (pid) => {
117286
+ if (!pid || !Number.isFinite(started) || !isPidAlive(pid)) return null;
117287
+ const at = await processStartTime(pid);
117288
+ return at !== null && Math.abs(at - started) <= PID_START_TOLERANCE_MS ? pid : null;
117289
+ };
117290
+ const [hostPid, childPid] = await Promise.all([check2(info?.hostPid), check2(info?.pid)]);
117291
+ return { hostPid, childPid };
117292
+ }
117293
+ function requestHost(dir, body, timeoutMs = 2e3) {
117294
+ return new Promise((resolve, reject) => {
117295
+ const sock = net2.connect(hostSocketPath(dir));
117296
+ let buf = "";
117297
+ let settled = false;
117298
+ const timer2 = setTimeout(() => finish(Object.assign(new Error("session host timed out"), { code: "ETIMEDOUT" })), timeoutMs);
117299
+ const finish = (err, value) => {
117300
+ if (settled) return;
117301
+ settled = true;
117302
+ clearTimeout(timer2);
117303
+ sock.destroy();
117304
+ if (err) reject(err);
117305
+ else resolve(value);
117306
+ };
117307
+ sock.setEncoding("utf8");
117308
+ sock.on("connect", () => sock.write(JSON.stringify({ v: SESSION_HOST_PROTOCOL, ...body }) + "\n"));
117309
+ sock.on("data", (chunk) => {
117310
+ buf += chunk;
117311
+ const nl = buf.indexOf("\n");
117312
+ if (nl === -1) return;
117313
+ let reply;
117314
+ try {
117315
+ reply = JSON.parse(buf.slice(0, nl));
117316
+ } catch {
117317
+ finish(new Error("session host sent a bad reply"));
117318
+ return;
117319
+ }
117320
+ const r = reply;
117321
+ if (r && r.ok === true) finish(null, reply);
117322
+ else finish(new HostRequestError(reply));
117323
+ });
117324
+ sock.on("error", (err) => finish(err));
117325
+ sock.on("close", () => finish(Object.assign(new Error("session host closed the connection"), { code: "ECONNRESET" })));
117326
+ });
117327
+ }
117328
+ var hostStatus = (dir, timeoutMs) => requestHost(dir, { op: "status" }, timeoutMs);
117329
+ var signalHost = (dir, signal) => requestHost(dir, { op: "signal", signal });
117330
+ var eofHost = (dir) => requestHost(dir, { op: "eof" });
117331
+ var ackHost = (dir, upto) => requestHost(dir, { op: "ack", upto });
117332
+ var limitHost = (dir, noHostMs) => requestHost(dir, { op: "limit", noHostMs: Math.round(noHostMs) });
117333
+ function isHostGone(err) {
117334
+ const code = err?.code;
117335
+ return code === "ECONNREFUSED" || code === "ENOENT" || code === "ENOTSOCK";
117336
+ }
117337
+ var HostAttachment = class extends EventEmitter2 {
117338
+ header;
117339
+ socket;
117340
+ constructor(header, socket) {
117341
+ super();
117342
+ this.header = header;
117343
+ this.socket = socket;
117344
+ }
117345
+ write(data, cb) {
117346
+ return this.socket.write(data, cb);
117347
+ }
117348
+ close() {
117349
+ this.socket.destroy();
117350
+ }
117351
+ };
117352
+ function attachHost(dir, after, timeoutMs = 5e3) {
117353
+ return new Promise((resolve, reject) => {
117354
+ const sock = net2.connect(hostSocketPath(dir));
117355
+ let head = Buffer.alloc(0);
117356
+ let settled = false;
117357
+ const timer2 = setTimeout(() => fail(Object.assign(new Error("session host attach timed out"), { code: "ETIMEDOUT" })), timeoutMs);
117358
+ const fail = (err) => {
117359
+ if (settled) return;
117360
+ settled = true;
117361
+ clearTimeout(timer2);
117362
+ sock.destroy();
117363
+ reject(err);
117364
+ };
117365
+ const onData = (chunk) => {
117366
+ head = head.length ? Buffer.concat([head, chunk]) : chunk;
117367
+ const nl = head.indexOf(10);
117368
+ if (nl === -1) {
117369
+ if (head.length > 64 * 1024) fail(new Error("session host sent a bad header"));
117370
+ return;
117371
+ }
117372
+ sock.off("data", onData);
117373
+ sock.pause();
117374
+ let header;
117375
+ try {
117376
+ header = JSON.parse(head.subarray(0, nl).toString("utf8"));
117377
+ } catch {
117378
+ fail(new Error("session host sent a bad header"));
117379
+ return;
117380
+ }
117381
+ if (!header || header.ok !== true) {
117382
+ fail(new HostRequestError(header));
117383
+ return;
117384
+ }
117385
+ settled = true;
117386
+ clearTimeout(timer2);
117387
+ sock.off("error", fail);
117388
+ sock.off("close", onEarlyClose);
117389
+ const attachment = new HostAttachment(header, sock);
117390
+ const rest = Buffer.from(head.subarray(nl + 1));
117391
+ sock.on("error", (err) => attachment.emit("error", err));
117392
+ sock.on("close", () => attachment.emit("close"));
117393
+ sock.on("data", (chunk2) => attachment.emit("data", chunk2));
117394
+ resolve(attachment);
117395
+ setImmediate(() => {
117396
+ if (rest.length > 0) attachment.emit("data", rest);
117397
+ sock.resume();
117398
+ });
117399
+ };
117400
+ const onEarlyClose = () => fail(Object.assign(new Error("session host closed the connection"), { code: "ECONNRESET" }));
117401
+ sock.on("connect", () => {
117402
+ sock.write(JSON.stringify({ v: SESSION_HOST_PROTOCOL, op: "attach", after }) + "\n");
117403
+ });
117404
+ sock.on("data", onData);
117405
+ sock.on("error", fail);
117406
+ sock.on("close", onEarlyClose);
117407
+ });
117408
+ }
117409
+ function startHost(opts) {
117410
+ const script = hostScriptPath();
117411
+ if (!script) throw new Error("session host script not found");
117412
+ fs8.mkdirSync(opts.dir, { recursive: true, mode: 448 });
117413
+ fs8.chmodSync(opts.dir, 448);
117414
+ const env = {};
117415
+ for (const [k, v] of Object.entries(opts.env)) if (v !== void 0) env[k] = v;
117416
+ const child = spawn4(opts.nodePath ?? process.execPath, [script, opts.dir, JSON.stringify(opts.config), opts.command, ...opts.args], {
117417
+ cwd: opts.cwd,
117418
+ env,
117419
+ detached: true,
117420
+ stdio: "ignore"
117421
+ });
117422
+ child.on("error", () => {
117423
+ });
117424
+ child.unref();
117425
+ if (!child.pid) throw new Error("session host did not start");
117426
+ return { hostPid: child.pid };
117427
+ }
117428
+ async function waitForHost(dir, timeoutMs = 1e4) {
117429
+ const deadline = Date.now() + timeoutMs;
117430
+ let lastErr = null;
117431
+ while (Date.now() < deadline) {
117432
+ try {
117433
+ return await hostStatus(dir, 1e3);
117434
+ } catch (err) {
117435
+ lastErr = err;
117436
+ if (readHostExit(dir)) break;
117437
+ await new Promise((r) => setTimeout(r, 25));
117438
+ }
117439
+ }
117440
+ const exit = readHostExit(dir);
117441
+ if (exit) throw new Error(`session host child exited at start: ${exit.error ?? `code ${exit.code}, signal ${exit.signal}`}`);
117442
+ throw new Error(`session host did not come up: ${lastErr?.message ?? "timeout"}`);
117443
+ }
117444
+ function readLogOldest(dir) {
117445
+ let fd = null;
117446
+ try {
117447
+ fd = fs8.openSync(path12.join(dir, "out.log"), "r");
117448
+ const buf = Buffer.alloc(LOG_HEADER_LEN);
117449
+ const n = fs8.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
117450
+ const text2 = buf.subarray(0, n).toString("utf8");
117451
+ if (n < LOG_HEADER_LEN || !text2.startsWith(LOG_HEADER_PREFIX) || text2[LOG_HEADER_LEN - 1] !== "\n") return null;
117452
+ const digits = text2.slice(LOG_HEADER_PREFIX.length, LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS);
117453
+ return /^\d+$/.test(digits) ? Number(digits) : null;
117454
+ } catch {
117455
+ return null;
117456
+ } finally {
117457
+ if (fd !== null) fs8.closeSync(fd);
117458
+ }
117459
+ }
117460
+ function readHostLog(dir, after) {
117461
+ const oldest = readLogOldest(dir);
117462
+ if (oldest === null || after < oldest) return null;
117463
+ try {
117464
+ const all = fs8.readFileSync(path12.join(dir, "out.log"));
117465
+ const start = LOG_HEADER_LEN + (after - oldest);
117466
+ if (start > all.length) return null;
117467
+ return all.subarray(start);
117468
+ } catch {
117469
+ return null;
117470
+ }
117471
+ }
117472
+ function removeHostDir(dir) {
117473
+ try {
117474
+ fs8.rmSync(dir, { recursive: true, force: true });
117475
+ } catch (err) {
117476
+ console.error(`[session-host] could not remove ${dir}:`, err.message);
117477
+ }
117478
+ const alias = path12.dirname(hostSocketPath(dir));
117479
+ if (alias !== dir) {
117480
+ try {
117481
+ fs8.unlinkSync(alias);
117482
+ } catch {
117483
+ }
117484
+ }
117485
+ }
117486
+
117487
+ // src/session-host/registry.ts
117488
+ function emptyResult() {
117489
+ return { turnIds: /* @__PURE__ */ new Set(), sessionIds: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
117490
+ }
117491
+ var adopters = /* @__PURE__ */ new Map();
117492
+ var runtimeAdopters = /* @__PURE__ */ new Map();
117493
+ var daemonUrl = (process.env.AGENT_PANE_SESSION_HOSTS_DAEMON_URL || process.env.REPOBURG_DAEMON_URL || "http://127.0.0.1:9998").replace(/\/+$/, "");
117494
+ var DAEMON_BOOT_ID = randomUUID2();
117495
+ var startupGate = Promise.resolve();
117496
+ var startupPending = false;
117497
+ var lastResult = emptyResult();
117498
+ function registerHostAdopter(adopter) {
117499
+ adopters.set(adopter.runtime, adopter);
117500
+ }
117501
+ function registerRuntimeAdopter(runtime, adopter) {
117502
+ runtimeAdopters.set(runtime, adopter);
117503
+ }
117504
+ function setSessionHostDaemonUrl(url2) {
117505
+ if (url2) daemonUrl = url2.replace(/\/+$/, "");
117506
+ }
117507
+ function sessionHostDaemonUrl() {
117508
+ return daemonUrl;
117509
+ }
117510
+ function waitForAdoption() {
117511
+ return startupGate;
117512
+ }
117513
+ function isAdoptionPending() {
117514
+ return startupPending;
117515
+ }
117516
+ function setStartupGate(started) {
117517
+ const gate = started.then(
117518
+ () => void 0,
117519
+ () => void 0
117520
+ );
117521
+ startupGate = gate;
117522
+ startupPending = true;
117523
+ void gate.then(() => {
117524
+ if (startupGate === gate) startupPending = false;
117525
+ });
117526
+ }
117527
+ function lastAdoption() {
117528
+ return lastResult;
117529
+ }
117530
+ function hostConfig(busy) {
117531
+ const flags = sessionHostFlags();
117532
+ return { noHostMs: busy ? flags.noHostBusyMs : flags.noHostIdleMs, daemonUrl };
117533
+ }
117534
+ function newHostDir() {
117535
+ const root = sessionHostsRoot();
117536
+ if (!root) throw new Error("session hosts have no directory");
117537
+ const id = randomBytes(8).toString("hex");
117538
+ return { id, dir: path13.join(root, id) };
117539
+ }
117540
+ var cachedVersion;
117541
+ function runtimeVersion() {
117542
+ if (cachedVersion !== void 0) return cachedVersion;
117543
+ cachedVersion = null;
117544
+ const here = path13.dirname(fileURLToPath3(import.meta.url));
117545
+ for (const rel of ["../../../../package.json", "../../../package.json"]) {
117546
+ try {
117547
+ const pkg = JSON.parse(fs9.readFileSync(path13.resolve(here, rel), "utf8"));
117548
+ if (pkg.name === "repoburg" && pkg.version) {
117549
+ cachedVersion = pkg.version;
117550
+ break;
117551
+ }
117552
+ } catch {
117553
+ }
117554
+ }
117555
+ return cachedVersion;
117556
+ }
117557
+ function writeHostMeta(dir, meta3) {
117558
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
117559
+ fs9.chmodSync(dir, 448);
117560
+ const tmp = path13.join(dir, "meta.json.tmp");
117561
+ fs9.writeFileSync(tmp, JSON.stringify(meta3, null, 2) + "\n", { mode: 384 });
117562
+ fs9.renameSync(tmp, path13.join(dir, "meta.json"));
117563
+ }
117564
+ function readHostMeta(dir) {
117565
+ try {
117566
+ return JSON.parse(fs9.readFileSync(path13.join(dir, "meta.json"), "utf8"));
117567
+ } catch {
117568
+ return null;
117569
+ }
117570
+ }
117571
+ function insertHostRow(db2, row) {
117572
+ const now = (/* @__PURE__ */ new Date()).toISOString();
117573
+ db2.prepare(
117574
+ `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)
117575
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
117576
+ ).run(
117577
+ row.id,
117578
+ row.runtime,
117579
+ row.session_id,
117580
+ row.entry_key,
117581
+ row.thread_id,
117582
+ row.turn_id ?? null,
117583
+ row.replay_offset ?? 0,
117584
+ row.external_id ?? null,
117585
+ row.host_pid,
117586
+ row.command,
117587
+ row.runtime_version,
117588
+ SESSION_HOST_PROTOCOL,
117589
+ row.generation ?? 0,
117590
+ now,
117591
+ now
117592
+ );
117593
+ }
117594
+ function getHostRow(db2, id) {
117595
+ return db2.prepare("SELECT * FROM session_hosts WHERE id = ?").get(id);
117596
+ }
117597
+ function listHostRows(db2) {
117598
+ return db2.prepare("SELECT * FROM session_hosts ORDER BY created_at").all();
117599
+ }
117600
+ function setHostTurn(db2, id, turnId, replayOffset) {
117601
+ db2.prepare("UPDATE session_hosts SET turn_id = ?, replay_offset = ?, updated_at = ? WHERE id = ?").run(
117602
+ turnId,
117603
+ replayOffset,
117604
+ (/* @__PURE__ */ new Date()).toISOString(),
117605
+ id
117606
+ );
117607
+ }
117608
+ function updateHostRow(db2, id, fields) {
117609
+ const keys = Object.keys(fields);
117610
+ if (keys.length === 0) return;
117611
+ const sets = keys.map((k) => `${k} = ?`).join(", ");
117612
+ db2.prepare(`UPDATE session_hosts SET ${sets}, updated_at = ? WHERE id = ?`).run(
117613
+ ...keys.map((k) => fields[k] ?? null),
117614
+ (/* @__PURE__ */ new Date()).toISOString(),
117615
+ id
117616
+ );
117617
+ }
117618
+ function setHostBackgroundTasks(db2, id, json2) {
117619
+ db2.prepare("UPDATE session_hosts SET background_tasks = ?, updated_at = ? WHERE id = ?").run(json2, (/* @__PURE__ */ new Date()).toISOString(), id);
117620
+ }
117621
+ function deleteHostRow(db2, id) {
117622
+ db2.prepare("DELETE FROM session_hosts WHERE id = ?").run(id);
117623
+ }
117624
+ function forgetHost(id, dir) {
117625
+ try {
117626
+ deleteHostRow(getDb(), id);
117627
+ } catch (err) {
117628
+ console.error(`[session-host] could not delete row ${id}:`, err.message);
117629
+ }
117630
+ if (dir) removeHostDir(dir);
117631
+ }
117632
+ async function shutDownHost(dir, opts = {}) {
117633
+ const graceMs = opts.graceMs ?? 5e3;
117634
+ const verified = await verifiedHostPids(dir);
117635
+ const pids = [verified.childPid, verified.hostPid].filter((p) => !!p);
117636
+ const alive = () => pids.some((p) => isPidAlive(p));
117637
+ if (opts.eof) {
117638
+ try {
117639
+ await signalOrEof(dir, "eof");
117640
+ const eofDeadline = Date.now() + Math.min(graceMs, 2e3);
117641
+ while (alive() && Date.now() < eofDeadline) await sleep(50);
117642
+ } catch {
117643
+ }
117644
+ }
117645
+ try {
117646
+ if (alive()) await signalOrEof(dir, "SIGTERM");
117647
+ } catch {
117648
+ }
117649
+ const deadline = Date.now() + graceMs;
117650
+ while (alive() && Date.now() < deadline) await sleep(50);
117651
+ if (alive()) {
117652
+ for (const pid of pids) {
117653
+ try {
117654
+ process.kill(pid, "SIGKILL");
117655
+ } catch {
117656
+ }
117657
+ }
117658
+ const killDeadline = Date.now() + 2e3;
117659
+ while (alive() && Date.now() < killDeadline) await sleep(50);
117660
+ }
117661
+ }
117662
+ async function signalOrEof(dir, what) {
117663
+ if (what === "eof") await eofHost(dir);
117664
+ else await signalHost(dir, what);
117665
+ }
117666
+ function sleep(ms) {
117667
+ return new Promise((r) => setTimeout(r, ms));
117668
+ }
117669
+ function adoptSessionHosts() {
117670
+ const run = runAdoption();
117671
+ setStartupGate(run);
117672
+ return run;
117673
+ }
117674
+ var ADOPT_CONCURRENCY = 4;
117675
+ async function runAdoption() {
117676
+ const result = emptyResult();
117677
+ lastResult = result;
117678
+ let db2;
117679
+ try {
117680
+ db2 = getDb();
117681
+ } catch {
117682
+ return result;
117683
+ }
117684
+ const flags = sessionHostFlags();
117685
+ if (flags.adoption) {
117686
+ for (const [runtime, adopter] of runtimeAdopters) {
117687
+ try {
117688
+ await adopter(db2, result);
117689
+ } catch (err) {
117690
+ console.error(`[session-host] adoption of ${runtime} turns failed; recovery takes them:`, err.message);
117691
+ }
117692
+ }
117693
+ }
117694
+ const root = sessionHostsRoot();
117695
+ if (root) await adoptHosts(db2, root, flags.adoption, result);
117696
+ if (result.turnIds.size || result.sessionIds.size) {
117697
+ console.log(`[session-host] adopted ${result.sessionIds.size} runtime(s), ${result.turnIds.size} running turn(s)`);
117698
+ }
117699
+ return result;
117700
+ }
117701
+ async function adoptHosts(db2, root, adoption, result) {
117702
+ let entries = [];
117703
+ try {
117704
+ entries = fs9.readdirSync(root);
117705
+ } catch (err) {
117706
+ if (err.code !== "ENOENT") console.error("[session-host] cannot read", root, err.message);
117707
+ }
117708
+ const seen = /* @__PURE__ */ new Set();
117709
+ const queue = [];
117710
+ for (const id of entries) {
117711
+ const dir = path13.join(root, id);
117712
+ try {
117713
+ if (!fs9.statSync(dir).isDirectory()) continue;
117714
+ } catch {
117715
+ continue;
117716
+ }
117717
+ seen.add(id);
117718
+ queue.push({ id, dir });
117719
+ }
117720
+ const worker = async () => {
117721
+ for (let next = queue.shift(); next; next = queue.shift()) {
117722
+ const { id, dir } = next;
117723
+ try {
117724
+ await adoptOne(db2, id, dir, adoption, result);
117725
+ } catch (err) {
117726
+ console.error(`[session-host] adoption of ${id} failed; the turn takes the resume path:`, err.message);
117727
+ await shutDownHost(dir, { eof: endsOnEof(db2, id, dir) }).catch(() => {
117728
+ });
117729
+ forgetHost(id, dir);
117730
+ }
117731
+ }
117732
+ };
117733
+ await Promise.all(Array.from({ length: ADOPT_CONCURRENCY }, worker));
117734
+ for (const row of listHostRows(db2)) {
117735
+ if (!seen.has(row.id)) deleteHostRow(db2, row.id);
117736
+ }
117737
+ }
117738
+ async function adoptOne(db2, id, dir, adoption, result) {
117739
+ const row = getHostRow(db2, id);
117740
+ const meta3 = readHostMeta(dir);
117741
+ let status = null;
117742
+ try {
117743
+ status = await hostStatus(dir, 2e3);
117744
+ } catch (err) {
117745
+ if (!isHostGone(err)) {
117746
+ console.error(`[session-host] ${id} does not answer (${err.message}); shutting it down`);
117747
+ await shutDownHost(dir);
117748
+ forgetHost(id, dir);
117749
+ return;
117750
+ }
117751
+ }
117752
+ if (status?.exited) {
117753
+ const hostPid = status.hostPid;
117754
+ const deadline = Date.now() + 4e3;
117755
+ while (isPidAlive(hostPid) && Date.now() < deadline) await sleep(50);
117756
+ status = null;
117757
+ }
117758
+ const session = row ? db2.prepare("SELECT id FROM sessions WHERE id = ?").get(row.session_id) : void 0;
117759
+ if (!row || !session || !adoption) {
117760
+ const why = !row ? "no DB row" : !session ? "session gone" : "adoption is off";
117761
+ console.log(`[session-host] ${id}: ${why}; shutting it down`);
117762
+ if (status) await shutDownHost(dir, { eof: row?.runtime === "codex" });
117763
+ else await endOrphanedChild(dir);
117764
+ forgetHost(id, dir);
117765
+ return;
117766
+ }
117767
+ const adopter = adopters.get(row.runtime);
117768
+ if (status) {
117769
+ const supported = SUPPORTED_PROTOCOLS.includes(status.v) && (!meta3 || SUPPORTED_PROTOCOLS.includes(meta3.protocol));
117770
+ if (!adopter || !supported || status.lossy) {
117771
+ const why = !adopter ? "no adopter" : !supported ? "unsupported protocol" : `lossy log (${status.lossyReason})`;
117772
+ console.log(`[session-host] ${id}: ${why}; shutting it down, the turn takes the resume path`);
117773
+ await shutDownHost(dir, { eof: row.runtime === "codex" });
117774
+ forgetHost(id, dir);
117775
+ return;
117776
+ }
117777
+ if (process.env.AGENT_PANE_SESSION_HOSTS_FAIL_ADOPT === "1") throw new Error("adoption failure injected");
117778
+ const { turnId, otherTurns } = await adopter.adoptLive(row, dir, status);
117779
+ result.sessionIds.add(row.session_id);
117780
+ result.entries.add(runtimeEntryKey(row.session_id, row.thread_id));
117781
+ if (turnId) result.turnIds.add(turnId);
117782
+ for (const other of otherTurns ?? []) {
117783
+ result.turnIds.add(other.id);
117784
+ result.entries.add(runtimeEntryKey(row.session_id, other.threadId));
117785
+ }
117786
+ return;
117787
+ }
117788
+ await endOrphanedChild(dir);
117789
+ const exit = readHostExit(dir);
117790
+ const log = readHostLog(dir, row.replay_offset);
117791
+ try {
117792
+ if (adopter) await adopter.adoptDead(row, dir, log, exit);
117793
+ } finally {
117794
+ forgetHost(id, dir);
117795
+ }
117796
+ }
117797
+ function endsOnEof(db2, id, dir) {
117798
+ try {
117799
+ return (getHostRow(db2, id)?.runtime ?? readHostMeta(dir)?.runtime) === "codex";
117800
+ } catch {
117801
+ return readHostMeta(dir)?.runtime === "codex";
117802
+ }
117803
+ }
117804
+ async function endOrphanedChild(dir) {
117805
+ if (readHostExit(dir)) return;
117806
+ const { hostPid, childPid } = await verifiedHostPids(dir);
117807
+ if (!childPid || hostPid) return;
117808
+ console.log(`[session-host] ending orphaned runtime process ${childPid} of a dead host`);
117809
+ for (const sig of ["SIGTERM", "SIGKILL"]) {
117810
+ try {
117811
+ process.kill(childPid, sig);
117812
+ } catch {
117813
+ return;
117814
+ }
117815
+ const deadline = Date.now() + 2e3;
117816
+ while (isPidAlive(childPid) && Date.now() < deadline) await sleep(25);
117817
+ if (!isPidAlive(childPid)) return;
117818
+ }
117819
+ }
117820
+
117821
+ // src/routes/session-hosts.ts
117822
+ async function registerSessionHostRoutes(fastify) {
117823
+ fastify.get("/api/session-hosts/protocol", async () => ({
117824
+ protocols: SUPPORTED_PROTOCOLS,
117825
+ bootId: DAEMON_BOOT_ID
117826
+ }));
117827
+ fastify.get("/api/session-hosts", async () => {
117828
+ const adopted = lastAdoption();
117829
+ return {
117830
+ root: sessionHostsRoot(),
117831
+ flags: sessionHostFlags(),
117832
+ bootId: DAEMON_BOOT_ID,
117833
+ adopted: { sessions: adopted.sessionIds.size, turns: adopted.turnIds.size },
117834
+ hosts: listHostRows(getDb()).map((row) => ({
117835
+ id: row.id,
117836
+ runtime: row.runtime,
117837
+ sessionId: row.session_id,
117838
+ threadId: row.thread_id,
117839
+ turnId: row.turn_id,
117840
+ hostPid: row.host_pid,
117841
+ childPid: row.child_pid,
117842
+ runtimeVersion: row.runtime_version,
117843
+ createdAt: row.created_at
117844
+ }))
117845
+ };
117846
+ });
117847
+ }
117848
+
116955
117849
  // src/codex/item-mapper.ts
116956
117850
  function mapItemData(item) {
116957
117851
  switch (item.type) {
@@ -117009,6 +117903,421 @@ function getItemStatus(item) {
117009
117903
  return "completed";
117010
117904
  }
117011
117905
 
117906
+ // src/codex/codex-host.ts
117907
+ import { EventEmitter as EventEmitter4 } from "node:events";
117908
+ import { PassThrough as PassThrough2, Writable as Writable2 } from "node:stream";
117909
+
117910
+ // src/session-host/spawned-process.ts
117911
+ import { spawn as spawn5 } from "node:child_process";
117912
+ import { EventEmitter as EventEmitter3 } from "node:events";
117913
+ import { PassThrough, Writable } from "node:stream";
117914
+ var ORPHAN_TERM_WAIT_MS = 3e3;
117915
+ var EOF_DELAY_MS = 100;
117916
+ var HostedProcess = class extends EventEmitter3 {
117917
+ stdin;
117918
+ stdout;
117919
+ pid;
117920
+ killed = false;
117921
+ exitCode = null;
117922
+ signalCode = null;
117923
+ /** Logical offset after the last stdout byte delivered to `stdout`. */
117924
+ consumed;
117925
+ /** Logical offset after the last complete line delivered to `stdout`. */
117926
+ consumedLineEnd;
117927
+ /** Resolves once attached (or running directly); rejects when neither works. */
117928
+ ready;
117929
+ /** Set when 'exit' is emitted. */
117930
+ endReason = null;
117931
+ dir;
117932
+ opts;
117933
+ attachment = null;
117934
+ direct = null;
117935
+ detaching = false;
117936
+ exited = false;
117937
+ stdinEnded = false;
117938
+ eofSent = false;
117939
+ partial = [];
117940
+ queued = [];
117941
+ replayEnd = null;
117942
+ reconnecting = false;
117943
+ constructor(opts) {
117944
+ super();
117945
+ this.opts = opts;
117946
+ this.dir = opts.dir;
117947
+ this.consumed = opts.start ? 0 : opts.after ?? 0;
117948
+ this.consumedLineEnd = this.consumed;
117949
+ this.stdout = new PassThrough();
117950
+ this.stdin = new Writable({
117951
+ write: (chunk, _enc, cb) => {
117952
+ this.writeStdin(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
117953
+ cb();
117954
+ },
117955
+ final: (cb) => {
117956
+ this.endStdin();
117957
+ cb();
117958
+ }
117959
+ });
117960
+ this.ready = this.firstConnect();
117961
+ this.ready.catch(() => {
117962
+ });
117963
+ }
117964
+ /** True while the process runs behind a host (false after a direct fallback). */
117965
+ get hosted() {
117966
+ return this.direct === null;
117967
+ }
117968
+ /** The daemon goes away: leave the child running. */
117969
+ detach() {
117970
+ if (this.exited) return;
117971
+ this.detaching = true;
117972
+ if (this.direct) {
117973
+ return;
117974
+ }
117975
+ const att = this.attachment;
117976
+ this.attachment = null;
117977
+ att?.close();
117978
+ this.finishExit(0, null, "detached");
117979
+ }
117980
+ kill(signal = "SIGTERM") {
117981
+ if (this.exited) return false;
117982
+ if (this.direct) {
117983
+ this.killed = true;
117984
+ return this.direct.kill(signal);
117985
+ }
117986
+ if (this.detaching) return true;
117987
+ this.killed = true;
117988
+ signalHost(this.dir, signal).catch(() => {
117989
+ });
117990
+ return true;
117991
+ }
117992
+ // ---------------------------------------------------------------------------
117993
+ async firstConnect() {
117994
+ const start = this.opts.start;
117995
+ if (start) {
117996
+ try {
117997
+ startHost({ dir: this.dir, command: start.command, args: start.args, cwd: start.cwd, env: start.env, config: start.config });
117998
+ await waitForHost(this.dir);
117999
+ } catch (err) {
118000
+ await this.abandonHost();
118001
+ if (this.detaching) return;
118002
+ this.runDirect(start, err.message);
118003
+ return;
118004
+ }
118005
+ }
118006
+ try {
118007
+ await this.connect(false);
118008
+ } catch (err) {
118009
+ if (start) {
118010
+ await this.abandonHost();
118011
+ if (this.detaching) return;
118012
+ this.runDirect(start, err.message);
118013
+ return;
118014
+ }
118015
+ this.fail(err);
118016
+ throw err;
118017
+ }
118018
+ }
118019
+ async connect(reattach) {
118020
+ const att = await attachHost(this.dir, this.consumed);
118021
+ if (this.detaching || this.exited) {
118022
+ att.close();
118023
+ return;
118024
+ }
118025
+ this.attachment = att;
118026
+ this.pid = att.header.child.pid ?? void 0;
118027
+ if (!reattach && this.opts.replayMarker && !this.opts.start) {
118028
+ this.replayEnd = att.header.end;
118029
+ if (this.replayEnd <= this.consumed) this.pushMarker();
118030
+ }
118031
+ att.on("data", (chunk) => {
118032
+ if (this.attachment === att) this.onStdout(chunk);
118033
+ });
118034
+ att.on("error", () => {
118035
+ });
118036
+ att.on("close", () => {
118037
+ if (this.attachment !== att) return;
118038
+ this.attachment = null;
118039
+ void this.onClose();
118040
+ });
118041
+ this.opts.onAttach?.(att.header, reattach);
118042
+ for (const lines of this.queued.splice(0)) att.write(lines);
118043
+ if (this.stdinEnded) this.sendEof();
118044
+ }
118045
+ onStdout(chunk) {
118046
+ if (this.replayEnd === null) {
118047
+ this.push(chunk);
118048
+ return;
118049
+ }
118050
+ const from = Math.max(0, this.replayEnd - 1 - this.consumed);
118051
+ const atBoundary = this.consumed >= this.replayEnd && this.consumed === this.consumedLineEnd;
118052
+ if (atBoundary) {
118053
+ this.pushMarker();
118054
+ this.push(chunk);
118055
+ return;
118056
+ }
118057
+ const idx = chunk.indexOf(10, from);
118058
+ if (idx === -1) {
118059
+ this.push(chunk);
118060
+ return;
118061
+ }
118062
+ this.push(chunk.subarray(0, idx + 1));
118063
+ this.pushMarker();
118064
+ if (idx + 1 < chunk.length) this.push(chunk.subarray(idx + 1));
118065
+ }
118066
+ push(buf) {
118067
+ if (buf.length === 0) return;
118068
+ const nl = buf.lastIndexOf(10);
118069
+ if (nl !== -1) this.consumedLineEnd = this.consumed + nl + 1;
118070
+ this.consumed += buf.length;
118071
+ if (!this.stdout.write(buf)) {
118072
+ const att = this.attachment;
118073
+ if (att) {
118074
+ att.socket.pause();
118075
+ this.stdout.once("drain", () => att.socket.resume());
118076
+ }
118077
+ }
118078
+ }
118079
+ pushMarker() {
118080
+ this.replayEnd = null;
118081
+ if (this.opts.replayMarker) this.stdout.write(this.opts.replayMarker + "\n");
118082
+ }
118083
+ writeStdin(chunk) {
118084
+ if (this.exited || this.stdinEnded) return;
118085
+ if (this.direct) {
118086
+ this.direct.stdin?.write(chunk);
118087
+ return;
118088
+ }
118089
+ const nl = chunk.lastIndexOf(10);
118090
+ if (nl === -1) {
118091
+ this.partial.push(chunk);
118092
+ return;
118093
+ }
118094
+ this.partial.push(chunk.subarray(0, nl + 1));
118095
+ const lines = Buffer.concat(this.partial);
118096
+ this.partial = nl + 1 < chunk.length ? [Buffer.from(chunk.subarray(nl + 1))] : [];
118097
+ if (this.attachment) this.attachment.write(lines);
118098
+ else this.queued.push(lines);
118099
+ }
118100
+ endStdin() {
118101
+ if (this.stdinEnded) return;
118102
+ this.stdinEnded = true;
118103
+ if (this.direct) {
118104
+ this.direct.stdin?.end();
118105
+ return;
118106
+ }
118107
+ if (this.detaching || this.exited) return;
118108
+ if (this.attachment) this.sendEof();
118109
+ }
118110
+ /** Ask the host to close the child's stdin, after the lines written so far
118111
+ * had time to arrive on the attach socket. */
118112
+ sendEof() {
118113
+ if (this.eofSent || this.detaching) return;
118114
+ this.eofSent = true;
118115
+ const att = this.attachment;
118116
+ const send2 = () => {
118117
+ setTimeout(() => {
118118
+ if (this.detaching || this.exited) return;
118119
+ eofHost(this.dir).catch(() => {
118120
+ });
118121
+ }, EOF_DELAY_MS).unref();
118122
+ };
118123
+ if (att) att.write("", () => send2());
118124
+ else send2();
118125
+ }
118126
+ async onClose() {
118127
+ if (this.exited || this.detaching || this.reconnecting) return;
118128
+ if (this.settleFromExitFile()) return;
118129
+ this.reconnecting = true;
118130
+ try {
118131
+ const deadline = Date.now() + (this.opts.reattachWindowMs ?? 5e3);
118132
+ while (Date.now() < deadline && !this.detaching && !this.exited) {
118133
+ let gone = false;
118134
+ try {
118135
+ const status = await hostStatus(this.dir, 1e3);
118136
+ if (!status.exited && !status.hostAttached) {
118137
+ await this.connect(true);
118138
+ return;
118139
+ }
118140
+ if (status.hostAttached) {
118141
+ console.error(`[session-host] ${this.dir}: another daemon is attached; giving the host up`);
118142
+ this.finishExit(null, null, "attached-elsewhere");
118143
+ return;
118144
+ }
118145
+ } catch (err) {
118146
+ gone = isHostGone(err);
118147
+ }
118148
+ if (this.settleFromExitFile()) return;
118149
+ if (gone) break;
118150
+ await new Promise((r) => setTimeout(r, 100));
118151
+ }
118152
+ if (this.detaching || this.exited) return;
118153
+ if (this.settleFromExitFile()) return;
118154
+ await this.endOrphan();
118155
+ } finally {
118156
+ this.reconnecting = false;
118157
+ }
118158
+ }
118159
+ /** The child exited and the host is gone or going: deliver what the log
118160
+ * holds past `consumed`, then emit 'exit' with the real code. */
118161
+ settleFromExitFile() {
118162
+ const exit = readHostExit(this.dir);
118163
+ if (!exit) return false;
118164
+ const rest = readHostLog(this.dir, this.consumed);
118165
+ if (rest && rest.length > 0) this.onStdout(rest);
118166
+ if (this.replayEnd !== null) this.pushMarker();
118167
+ this.finishExit(exit.code, exit.signal ?? null, "exit");
118168
+ return true;
118169
+ }
118170
+ /** The host died with its child still running: end the child here. */
118171
+ async endOrphan() {
118172
+ const pid = this.pid ?? readHostChild(this.dir)?.pid ?? void 0;
118173
+ let detail = "session host died";
118174
+ if (pid && isPidAlive(pid)) {
118175
+ detail = `session host died; ended its orphaned child ${pid}`;
118176
+ try {
118177
+ process.kill(pid, "SIGTERM");
118178
+ } catch {
118179
+ }
118180
+ const deadline = Date.now() + ORPHAN_TERM_WAIT_MS;
118181
+ while (isPidAlive(pid) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
118182
+ if (isPidAlive(pid)) {
118183
+ try {
118184
+ process.kill(pid, "SIGKILL");
118185
+ } catch {
118186
+ }
118187
+ const killDeadline = Date.now() + ORPHAN_TERM_WAIT_MS;
118188
+ while (isPidAlive(pid) && Date.now() < killDeadline) await new Promise((r) => setTimeout(r, 50));
118189
+ }
118190
+ }
118191
+ console.error(`[session-host] ${this.dir}: ${detail}`);
118192
+ this.opts.onHostLost?.(detail);
118193
+ this.finishExit(null, "SIGKILL", "host-lost");
118194
+ }
118195
+ /** Kill a host that did not come up, and its child, before running directly. */
118196
+ async abandonHost() {
118197
+ const info = readHostChild(this.dir);
118198
+ for (const pid of [info?.hostPid, info?.pid]) {
118199
+ if (pid && isPidAlive(pid)) {
118200
+ try {
118201
+ process.kill(pid, "SIGKILL");
118202
+ } catch {
118203
+ }
118204
+ }
118205
+ }
118206
+ }
118207
+ runDirect(start, reason) {
118208
+ console.error(`[session-host] host did not start (${reason}); running the process directly`);
118209
+ const child = spawn5(start.command, start.args, { cwd: start.cwd, env: start.env, stdio: ["pipe", "pipe", "pipe"] });
118210
+ this.direct = child;
118211
+ this.pid = child.pid;
118212
+ child.stdout?.on("data", (chunk) => this.push(chunk));
118213
+ child.stderr?.on("data", () => {
118214
+ });
118215
+ child.stdin?.on("error", () => {
118216
+ });
118217
+ child.on("error", (err) => this.fail(err));
118218
+ child.on("exit", (code, signal) => this.finishExit(code, signal, "exit"));
118219
+ for (const lines of this.queued.splice(0)) child.stdin?.write(lines);
118220
+ if (this.partial.length) child.stdin?.write(Buffer.concat(this.partial.splice(0)));
118221
+ if (this.stdinEnded) child.stdin?.end();
118222
+ this.opts.onDirect?.(child.pid, reason);
118223
+ }
118224
+ fail(err) {
118225
+ if (this.exited) return;
118226
+ if (this.listenerCount("error") > 0) this.emit("error", err);
118227
+ this.finishExit(1, null, "error");
118228
+ }
118229
+ finishExit(code, signal, reason) {
118230
+ if (this.exited) return;
118231
+ this.exited = true;
118232
+ this.endReason = reason;
118233
+ this.exitCode = code;
118234
+ this.signalCode = signal;
118235
+ this.emit("exit", code, signal);
118236
+ this.stdout.end();
118237
+ }
118238
+ };
118239
+
118240
+ // src/codex/codex-host.ts
118241
+ var IDS_PER_GENERATION = 1e9;
118242
+ function requestIdBase(generation) {
118243
+ return generation * IDS_PER_GENERATION + 1;
118244
+ }
118245
+ function startCodexHost(db2, start) {
118246
+ const { id, dir } = newHostDir();
118247
+ const version2 = runtimeVersion();
118248
+ try {
118249
+ writeHostMeta(dir, {
118250
+ protocol: SESSION_HOST_PROTOCOL,
118251
+ hostId: id,
118252
+ runtime: "codex",
118253
+ entryKey: start.sessionId,
118254
+ sessionId: start.sessionId,
118255
+ threadId: null,
118256
+ command: start.command,
118257
+ runtimeVersion: version2,
118258
+ daemonUrl: sessionHostDaemonUrl(),
118259
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
118260
+ });
118261
+ insertHostRow(db2, {
118262
+ id,
118263
+ runtime: "codex",
118264
+ session_id: start.sessionId,
118265
+ entry_key: start.sessionId,
118266
+ thread_id: null,
118267
+ command: start.command,
118268
+ runtime_version: version2,
118269
+ host_pid: null
118270
+ });
118271
+ } catch (err) {
118272
+ forgetHost(id, dir);
118273
+ throw err;
118274
+ }
118275
+ const proc = new HostedProcess({
118276
+ dir,
118277
+ start: { command: start.command, args: start.args, cwd: start.cwd, env: start.env, config: hostConfig(true) },
118278
+ onAttach: (header) => {
118279
+ try {
118280
+ updateHostRow(db2, id, { host_pid: header.hostPid, child_pid: header.child.pid });
118281
+ } catch {
118282
+ }
118283
+ },
118284
+ onDirect: (pid) => {
118285
+ forgetHost(id, dir);
118286
+ start.onDirect(pid);
118287
+ }
118288
+ });
118289
+ return { id, dir, proc, runtimeVersion: version2 };
118290
+ }
118291
+ async function releaseCodexHost(binding) {
118292
+ const proc = binding.proc;
118293
+ if (proc.endReason === "detached" || proc.endReason === "attached-elsewhere") return;
118294
+ if (proc.hosted) {
118295
+ try {
118296
+ await shutDownHost(binding.dir, { graceMs: 3e3, eof: true });
118297
+ } catch (err) {
118298
+ console.error(`[codex] could not stop session host ${binding.id}:`, err.message);
118299
+ }
118300
+ }
118301
+ forgetHost(binding.id, binding.dir);
118302
+ }
118303
+ var LoggedAppServer = class extends EventEmitter4 {
118304
+ stdin = new Writable2({
118305
+ write: (_chunk, _enc, cb) => cb()
118306
+ });
118307
+ stdout = new PassThrough2();
118308
+ pid = void 0;
118309
+ kill() {
118310
+ return false;
118311
+ }
118312
+ /** Feed the log; resolves once the client has read all of it. */
118313
+ play(log) {
118314
+ return new Promise((resolve) => {
118315
+ this.stdout.once("end", () => resolve());
118316
+ this.stdout.end(log);
118317
+ });
118318
+ }
118319
+ };
118320
+
117012
118321
  // src/codex/app-server-types.ts
117013
118322
  function mapTokenUsage(data) {
117014
118323
  return {
@@ -117021,23 +118330,23 @@ function mapTokenUsage(data) {
117021
118330
  }
117022
118331
 
117023
118332
  // src/apps/register-mcp.ts
117024
- import fs7 from "node:fs";
117025
- import path11 from "node:path";
117026
- import { fileURLToPath as fileURLToPath2 } from "node:url";
118333
+ import fs10 from "node:fs";
118334
+ import path14 from "node:path";
118335
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
117027
118336
  var MCP_SERVER_NAME = "agentpane-miniapps";
117028
118337
  function panePublicUrl() {
117029
118338
  return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
117030
118339
  }
117031
118340
  function stdioScriptPath() {
117032
- const here = path11.dirname(fileURLToPath2(import.meta.url));
118341
+ const here = path14.dirname(fileURLToPath4(import.meta.url));
117033
118342
  const candidates = [
117034
- path11.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
118343
+ path14.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
117035
118344
  // src/apps/ → backend/scripts
117036
- path11.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
118345
+ path14.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
117037
118346
  // dist bundle → backend/scripts
117038
118347
  ];
117039
118348
  for (const candidate of candidates) {
117040
- if (fs7.existsSync(candidate)) return candidate;
118349
+ if (fs10.existsSync(candidate)) return candidate;
117041
118350
  }
117042
118351
  return null;
117043
118352
  }
@@ -117118,12 +118427,12 @@ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
117118
118427
  }
117119
118428
 
117120
118429
  // src/claude/cli-orphans.ts
117121
- import { execFile as execFile3 } from "node:child_process";
118430
+ import { execFile as execFile4 } from "node:child_process";
117122
118431
  var TERM_GRACE_MS = 2e3;
117123
118432
  var POLL_MS = 100;
117124
118433
  function inspectProcess(pid) {
117125
118434
  return new Promise((resolve) => {
117126
- execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
118435
+ execFile4("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
117127
118436
  const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
117128
118437
  resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
117129
118438
  });
@@ -117131,7 +118440,7 @@ function inspectProcess(pid) {
117131
118440
  }
117132
118441
  function listDescendants(pid) {
117133
118442
  return new Promise((resolve) => {
117134
- execFile3("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
118443
+ execFile4("ps", ["-A", "-o", "pid=", "-o", "ppid="], (err, stdout) => {
117135
118444
  if (err) {
117136
118445
  resolve([]);
117137
118446
  return;
@@ -117324,17 +118633,33 @@ function getOrCreateThread(session) {
117324
118633
  return started;
117325
118634
  }
117326
118635
  async function startThread(session) {
118636
+ if (isAdoptionPending()) {
118637
+ await waitForAdoption();
118638
+ const adopted = sessionMap.get(session.id);
118639
+ if (adopted && !adopted.client.isClosed()) return adopted;
118640
+ }
117327
118641
  const cwd = session.cwd ?? process.cwd();
117328
- const client = new AppServerClient(appServerClientOptions(session, cwd));
117329
- const entry = {
118642
+ const options = appServerClientOptions(session, cwd);
118643
+ let entry = null;
118644
+ const host = hostFor(session.id, cwd, options, (pid) => {
118645
+ if (!entry) return;
118646
+ entry.pid = pid;
118647
+ trackProcess(pid, session.id);
118648
+ });
118649
+ const client = new AppServerClient(host ? { ...options, process: host.proc } : options);
118650
+ entry = {
117330
118651
  sessionId: session.id,
117331
118652
  client,
117332
- pid: client.pid,
118653
+ // A hosted app-server has no cli_processes row: its host supervises it.
118654
+ pid: host ? void 0 : client.pid,
117333
118655
  threadId: "",
117334
118656
  turns: [],
117335
118657
  ended: /* @__PURE__ */ new Map(),
117336
118658
  resumedTurnIds: null,
117337
- closing: null
118659
+ closing: null,
118660
+ host,
118661
+ replaying: false,
118662
+ retireWhenIdle: null
117338
118663
  };
117339
118664
  trackProcess(entry.pid, session.id);
117340
118665
  listen(entry);
@@ -117357,6 +118682,7 @@ async function startThread(session) {
117357
118682
  });
117358
118683
  entry.threadId = result.thread.id;
117359
118684
  entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
118685
+ noteHostThread(entry);
117360
118686
  } else {
117361
118687
  const result = await client.request("thread/start", {
117362
118688
  cwd,
@@ -117373,6 +118699,7 @@ async function startThread(session) {
117373
118699
  now,
117374
118700
  session.id
117375
118701
  );
118702
+ noteHostThread(entry);
117376
118703
  }
117377
118704
  } catch (err) {
117378
118705
  void retireEntry(entry, "keep");
@@ -117397,12 +118724,16 @@ function retireEntry(entry, left, error51 = "App-server closed") {
117397
118724
  }
117398
118725
  }
117399
118726
  entry.closing = entry.client.close().catch(() => {
117400
- }).finally(() => untrackProcess(entry.pid));
118727
+ }).finally(async () => {
118728
+ untrackProcess(entry.pid);
118729
+ if (entry.host) await releaseCodexHost(entry.host);
118730
+ });
117401
118731
  return entry.closing;
117402
118732
  }
117403
118733
  function onClientClosed(entry, reason) {
117404
118734
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
117405
118735
  untrackProcess(entry.pid);
118736
+ if (entry.host && !entry.closing) void releaseCodexHost(entry.host);
117406
118737
  if (entry.closing || entry.turns.length === 0) return;
117407
118738
  let db2;
117408
118739
  try {
@@ -117429,6 +118760,8 @@ function endTurn(entry, active) {
117429
118760
  active.done = true;
117430
118761
  entry.turns = entry.turns.filter((t) => t !== active);
117431
118762
  rememberEnded(entry, active);
118763
+ settleHostTurn(entry);
118764
+ maybeRetire(entry);
117432
118765
  }
117433
118766
  function rememberEnded(entry, active) {
117434
118767
  if (!active.codexId) return;
@@ -117442,6 +118775,10 @@ function liveTurnsOf(entry, codexId) {
117442
118775
  const waiting = entry.turns.find((t) => t.codexId === null);
117443
118776
  if (!waiting) return [];
117444
118777
  waiting.codexId = codexId;
118778
+ try {
118779
+ 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);
118780
+ } catch {
118781
+ }
117445
118782
  return [waiting];
117446
118783
  }
117447
118784
  function noteContinued(active) {
@@ -117547,12 +118884,9 @@ function onAgentMessageDelta(entry, p) {
117547
118884
  const [live] = liveTurnsOf(entry, p.turnId);
117548
118885
  if (!live) return;
117549
118886
  noteContinued(live);
117550
- broadcast("item:delta", {
117551
- sessionId: entry.sessionId,
117552
- turnId: live.id,
117553
- itemId: p.itemId,
117554
- delta: p.delta
117555
- });
118887
+ const payload = { sessionId: entry.sessionId, turnId: live.id, itemId: p.itemId, delta: p.delta };
118888
+ if (entry.replaying) noteDelta(payload);
118889
+ else broadcast("item:delta", payload);
117556
118890
  }
117557
118891
  function onTurnCompleted(entry, p) {
117558
118892
  const db2 = getDb();
@@ -117629,9 +118963,11 @@ async function runTurn(session, turn, entry, input, resume) {
117629
118963
  resolveStarted = resolve;
117630
118964
  }),
117631
118965
  done: false,
117632
- resuming: resume
118966
+ resuming: resume,
118967
+ hostOffset: null
117633
118968
  };
117634
118969
  entry.turns.push(active);
118970
+ bindHostTurn(entry, active);
117635
118971
  try {
117636
118972
  const result = await entry.client.request("turn/start", {
117637
118973
  threadId: entry.threadId,
@@ -118001,6 +119337,10 @@ async function shutdown() {
118001
119337
  }
118002
119338
  const closing = [closeSharedAppServer()];
118003
119339
  for (const entry of [...sessionMap.values()]) {
119340
+ if (entry.host?.proc.hosted && !entry.closing) {
119341
+ detachEntry(entry);
119342
+ continue;
119343
+ }
118004
119344
  for (const active of [...entry.turns]) {
118005
119345
  if (active.discussionThreadId) continue;
118006
119346
  endTurn(entry, active);
@@ -118030,6 +119370,222 @@ async function resumeInterruptedTurn(session, turn, _opts) {
118030
119370
  const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
118031
119371
  await runTurn(session, turn, entry, input, true);
118032
119372
  }
119373
+ function hostFor(sessionId, cwd, options, onDirect) {
119374
+ if (!hostsEnabledFor("codex")) return null;
119375
+ try {
119376
+ const { command, args } = appServerCommand(options);
119377
+ return startCodexHost(getDb(), { sessionId, cwd, command, args, env: { ...process.env }, onDirect });
119378
+ } catch (err) {
119379
+ console.error(`[codex] no session host for ${sessionId} (${err.message}); running the app-server directly`);
119380
+ return null;
119381
+ }
119382
+ }
119383
+ function isCurrent(entry) {
119384
+ return sessionMap.get(entry.sessionId) === entry && !entry.closing && !entry.client.isClosed();
119385
+ }
119386
+ function noteHostThread(entry) {
119387
+ if (!entry.host?.proc.hosted) return;
119388
+ try {
119389
+ updateHostRow(getDb(), entry.host.id, { external_id: entry.threadId });
119390
+ } catch {
119391
+ }
119392
+ }
119393
+ function refreshHostLimit(entry) {
119394
+ const host = entry.host;
119395
+ if (!host?.proc.hosted) return;
119396
+ const flags = sessionHostFlags();
119397
+ void limitHost(host.dir, entry.turns.length > 0 ? flags.noHostBusyMs : flags.noHostIdleMs).catch(() => {
119398
+ });
119399
+ }
119400
+ function bindHostTurn(entry, active) {
119401
+ const host = entry.host;
119402
+ if (!host?.proc.hosted || !isCurrent(entry)) return;
119403
+ active.hostOffset = host.proc.consumedLineEnd;
119404
+ if (entry.turns.length > 1) {
119405
+ refreshHostLimit(entry);
119406
+ return;
119407
+ }
119408
+ try {
119409
+ setHostTurn(getDb(), host.id, active.id, active.hostOffset);
119410
+ } catch (err) {
119411
+ console.error(`[codex] could not bind turn ${active.id} to its session host:`, err.message);
119412
+ }
119413
+ void ackHost(host.dir, active.hostOffset).catch(() => {
119414
+ });
119415
+ refreshHostLimit(entry);
119416
+ }
119417
+ function settleHostTurn(entry) {
119418
+ const host = entry.host;
119419
+ if (!host?.proc.hosted || !isCurrent(entry) || entry.replaying) return;
119420
+ const oldest = entry.turns.find((t) => t.hostOffset !== null);
119421
+ const upto = oldest?.hostOffset ?? host.proc.consumedLineEnd;
119422
+ try {
119423
+ setHostTurn(getDb(), host.id, oldest?.id ?? null, upto);
119424
+ } catch {
119425
+ }
119426
+ void ackHost(host.dir, upto).catch(() => {
119427
+ });
119428
+ refreshHostLimit(entry);
119429
+ }
119430
+ function maybeRetire(entry) {
119431
+ const why = entry.retireWhenIdle;
119432
+ if (!why || entry.replaying || entry.turns.length > 0 || !isCurrent(entry)) return;
119433
+ console.log(`[codex] closing the idle app-server of session ${entry.sessionId} (${why}); the next prompt starts a new one`);
119434
+ void retireEntry(entry, "keep");
119435
+ }
119436
+ function detachEntry(entry) {
119437
+ if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
119438
+ entry.closing = Promise.resolve();
119439
+ entry.client.detach();
119440
+ entry.host?.proc.detach();
119441
+ }
119442
+ function runningTurns(db2, sessionId) {
119443
+ return db2.prepare(
119444
+ "SELECT id, thread_id, external_turn_id, resume_state FROM turns WHERE session_id = ? AND status = 'running' ORDER BY created_at, rowid"
119445
+ ).all(sessionId);
119446
+ }
119447
+ function adoptedEntry(db2, session, threadId, client, host) {
119448
+ const turns = runningTurns(db2, session.id).map(
119449
+ (row) => ({
119450
+ id: row.id,
119451
+ discussionThreadId: row.thread_id,
119452
+ codexId: row.external_turn_id,
119453
+ started: Promise.resolve(row.external_turn_id),
119454
+ done: false,
119455
+ resuming: row.resume_state === "resuming",
119456
+ hostOffset: null
119457
+ })
119458
+ );
119459
+ const ended = /* @__PURE__ */ new Map();
119460
+ const endedRows = db2.prepare(
119461
+ "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 ?"
119462
+ ).all(session.id, ENDED_TURNS_KEPT);
119463
+ for (const row of endedRows.reverse()) ended.set(row.external_turn_id, row.id);
119464
+ const known = db2.prepare("SELECT external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL").all(session.id);
119465
+ return {
119466
+ sessionId: session.id,
119467
+ client,
119468
+ pid: void 0,
119469
+ threadId,
119470
+ turns,
119471
+ ended,
119472
+ // A turn resumed on this app-server later continues with the continue
119473
+ // prompt when Codex has it.
119474
+ resumedTurnIds: new Set(known.map((row) => row.external_turn_id)),
119475
+ closing: null,
119476
+ host,
119477
+ replaying: true,
119478
+ retireWhenIdle: null
119479
+ };
119480
+ }
119481
+ var REPLAY_WAIT_MS = 3e4;
119482
+ function replayDone(client, what) {
119483
+ if (!client.replaying || client.isClosed()) return Promise.resolve();
119484
+ return new Promise((resolve) => {
119485
+ const done = () => {
119486
+ clearTimeout(timer2);
119487
+ client.events.off("replayDone", done);
119488
+ client.events.off("closed", done);
119489
+ resolve();
119490
+ };
119491
+ const timer2 = setTimeout(() => {
119492
+ console.error(`[codex] the replay of ${what} takes long; startup goes on`);
119493
+ done();
119494
+ }, REPLAY_WAIT_MS);
119495
+ timer2.unref?.();
119496
+ client.events.once("replayDone", done);
119497
+ client.events.once("closed", done);
119498
+ });
119499
+ }
119500
+ function describeExit(exit) {
119501
+ if (!exit) return "the session host died with its app-server";
119502
+ if (exit.error) return `App-server process could not start: ${exit.error}`;
119503
+ if (exit.signal) return `App-server process exited (signal ${exit.signal})`;
119504
+ return `App-server process exited (code ${exit.code})`;
119505
+ }
119506
+ var codexHostAdopter = {
119507
+ runtime: "codex",
119508
+ async adoptLive(row, dir) {
119509
+ const db2 = getDb();
119510
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
119511
+ if (!session || session.runtime_type !== "codex") throw new Error("the session is not a Codex session any more");
119512
+ if (sessionMap.has(session.id)) throw new Error(`an app-server already runs for session ${session.id}`);
119513
+ const threadId = row.external_id ?? session.external_thread_id;
119514
+ if (!threadId) throw new Error("the app-server has no Codex thread");
119515
+ const generation = row.generation + 1;
119516
+ updateHostRow(db2, row.id, { generation });
119517
+ const proc = new HostedProcess({
119518
+ dir,
119519
+ after: row.replay_offset,
119520
+ replayMarker: REPLAY_MARKER,
119521
+ onAttach: (header) => {
119522
+ try {
119523
+ updateHostRow(getDb(), row.id, { host_pid: header.hostPid, child_pid: header.child.pid });
119524
+ } catch {
119525
+ }
119526
+ }
119527
+ });
119528
+ await proc.ready;
119529
+ forgetStreams(session.id);
119530
+ const client = new AppServerClient({
119531
+ cwd: session.cwd ?? process.cwd(),
119532
+ process: proc,
119533
+ firstRequestId: requestIdBase(generation),
119534
+ replaying: true
119535
+ });
119536
+ const host = { id: row.id, dir, proc, runtimeVersion: row.runtime_version };
119537
+ const entry = adoptedEntry(db2, session, threadId, client, host);
119538
+ const version2 = runtimeVersion();
119539
+ 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;
119540
+ sessionMap.set(session.id, entry);
119541
+ listen(entry);
119542
+ if (session.origin_app_id) autoApproveToolUserInput(client);
119543
+ await replayDone(client, `session ${session.id}`);
119544
+ entry.replaying = false;
119545
+ if (!isCurrent(entry)) {
119546
+ return { turnId: null };
119547
+ }
119548
+ for (const active of entry.turns) active.hostOffset = row.replay_offset;
119549
+ settleHostTurn(entry);
119550
+ recomputeSessionRunning(db2, session.id);
119551
+ broadcast("session:resync", { sessionId: session.id });
119552
+ resendStreams(session.id);
119553
+ const running = entry.turns.map((t) => ({ id: t.id, threadId: t.discussionThreadId }));
119554
+ console.log(
119555
+ `[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}` : ""}`
119556
+ );
119557
+ maybeRetire(entry);
119558
+ return { turnId: running[0]?.id ?? null, otherTurns: running.slice(1) };
119559
+ },
119560
+ async adoptDead(row, _dir, log, exit) {
119561
+ const db2 = getDb();
119562
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
119563
+ if (!session || session.runtime_type !== "codex") return;
119564
+ const detail = describeExit(exit);
119565
+ const threadId = row.external_id ?? session.external_thread_id;
119566
+ console.log(`[codex] the app-server of session ${session.id} ended with no daemon attached (${detail}); replaying its log`);
119567
+ if (log && log.length > 0 && threadId) {
119568
+ const logged = new LoggedAppServer();
119569
+ const client = new AppServerClient({ cwd: session.cwd ?? process.cwd(), process: logged, replaying: true });
119570
+ const entry = adoptedEntry(db2, session, threadId, client, null);
119571
+ listen(entry);
119572
+ forgetStreams(session.id);
119573
+ try {
119574
+ await logged.play(log);
119575
+ } finally {
119576
+ client.detach();
119577
+ forgetStreams(session.id);
119578
+ }
119579
+ broadcast("session:resync", { sessionId: session.id });
119580
+ }
119581
+ for (const turn of runningTurns(db2, session.id)) {
119582
+ if (turn.thread_id) continue;
119583
+ failOpenItems(db2, session.id, turn.id);
119584
+ markTurnInterrupted(db2, turn.id, "process_exit", { detail, notify: false });
119585
+ }
119586
+ }
119587
+ };
119588
+ registerHostAdopter(codexHostAdopter);
118033
119589
  var codexProvider = {
118034
119590
  startTurn: startTurn2,
118035
119591
  interruptTurn,
@@ -118300,6 +119856,22 @@ function recordApiUsage(entry, sessionId, db2, apiMessageId, usage) {
118300
119856
  ctx.seq++;
118301
119857
  publish(entry, sessionId, db2);
118302
119858
  }
119859
+ function restoreContext(entry, stored) {
119860
+ if (entry.threadId || !stored) return;
119861
+ let saved;
119862
+ try {
119863
+ saved = JSON.parse(stored);
119864
+ } catch {
119865
+ return;
119866
+ }
119867
+ if (typeof saved.totalTokens !== "number" || typeof saved.contextWindow !== "number") return;
119868
+ const ctx = counterOf(entry);
119869
+ ctx.tokens = saved.totalTokens;
119870
+ ctx.measured = true;
119871
+ ctx.window = saved.contextWindow;
119872
+ ctx.autoCompactThreshold = typeof saved.autoCompactThreshold === "number" ? saved.autoCompactThreshold : null;
119873
+ ctx.lastPublished = stored;
119874
+ }
118303
119875
  function resetContext(entry, sessionId, db2) {
118304
119876
  if (entry.threadId) return;
118305
119877
  const ctx = counterOf(entry);
@@ -118370,6 +119942,112 @@ function classifyApiError({ error: error51, status, text: text2, limitRejected }
118370
119942
  return "fatal";
118371
119943
  }
118372
119944
 
119945
+ // src/claude/claude-host.ts
119946
+ import { spawn as spawn6 } from "node:child_process";
119947
+ var REPLAY_DONE_SUBTYPE = "agentpane_replay_done";
119948
+ var REPLAY_MARKER2 = JSON.stringify({ type: "system", subtype: REPLAY_DONE_SUBTYPE });
119949
+ function isReplayMarker(message) {
119950
+ return message.type === "system" && message.subtype === REPLAY_DONE_SUBTYPE;
119951
+ }
119952
+ var SDK_INTERNAL_FRAMES = /* @__PURE__ */ new Set([
119953
+ "control_request",
119954
+ "control_response",
119955
+ "control_cancel_request",
119956
+ "keep_alive",
119957
+ "transcript_mirror"
119958
+ ]);
119959
+ function* logFrames(log) {
119960
+ let start = 0;
119961
+ while (start < log.length) {
119962
+ const nl = log.indexOf(10, start);
119963
+ if (nl === -1) return;
119964
+ const line = log.subarray(start, nl).toString("utf8").trim();
119965
+ start = nl + 1;
119966
+ if (!line.startsWith("{")) continue;
119967
+ let message;
119968
+ try {
119969
+ message = JSON.parse(line);
119970
+ } catch {
119971
+ continue;
119972
+ }
119973
+ const type = message?.type;
119974
+ if (typeof type !== "string" || SDK_INTERNAL_FRAMES.has(type)) continue;
119975
+ yield message;
119976
+ }
119977
+ }
119978
+ function hostedSpawner(db2, binding, info) {
119979
+ return (opts) => {
119980
+ if (binding.proc) return binding.proc;
119981
+ const cwd = opts.cwd ?? info.cwd;
119982
+ try {
119983
+ writeHostMeta(binding.dir, {
119984
+ protocol: SESSION_HOST_PROTOCOL,
119985
+ hostId: binding.id,
119986
+ runtime: "claude",
119987
+ entryKey: info.entryKey,
119988
+ sessionId: info.sessionId,
119989
+ threadId: info.threadId,
119990
+ command: opts.command,
119991
+ runtimeVersion: binding.runtimeVersion,
119992
+ daemonUrl: sessionHostDaemonUrl(),
119993
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
119994
+ });
119995
+ insertHostRow(db2, {
119996
+ id: binding.id,
119997
+ runtime: "claude",
119998
+ session_id: info.sessionId,
119999
+ entry_key: info.entryKey,
120000
+ thread_id: info.threadId,
120001
+ turn_id: info.turnId,
120002
+ command: opts.command,
120003
+ runtime_version: binding.runtimeVersion,
120004
+ host_pid: null
120005
+ });
120006
+ } catch (err) {
120007
+ console.error(`[claude] no session host for ${info.entryKey} (${err.message}); running the CLI directly`);
120008
+ forgetHost(binding.id, binding.dir);
120009
+ const child = spawn6(opts.command, opts.args, { cwd, env: opts.env, signal: opts.signal, stdio: ["pipe", "pipe", "ignore"] });
120010
+ info.onDirect(child.pid);
120011
+ return child;
120012
+ }
120013
+ const proc = new HostedProcess({
120014
+ dir: binding.dir,
120015
+ start: { command: opts.command, args: opts.args, cwd, env: opts.env, config: hostConfig(true) },
120016
+ onAttach: (header) => {
120017
+ try {
120018
+ updateHostRow(db2, binding.id, { host_pid: header.hostPid, child_pid: header.child.pid });
120019
+ } catch {
120020
+ }
120021
+ },
120022
+ onDirect: (pid) => {
120023
+ forgetHost(binding.id, binding.dir);
120024
+ info.onDirect(pid);
120025
+ }
120026
+ });
120027
+ opts.signal?.addEventListener("abort", () => proc.kill("SIGTERM"), { once: true });
120028
+ binding.proc = proc;
120029
+ return proc;
120030
+ };
120031
+ }
120032
+ function attachedSpawner(proc) {
120033
+ return (opts) => {
120034
+ opts.signal?.addEventListener("abort", () => proc.kill("SIGTERM"), { once: true });
120035
+ return proc;
120036
+ };
120037
+ }
120038
+ async function releaseHost(binding) {
120039
+ const proc = binding.proc;
120040
+ if (proc?.endReason === "detached" || proc?.endReason === "attached-elsewhere") return;
120041
+ if (proc && proc.hosted) {
120042
+ try {
120043
+ await shutDownHost(binding.dir, { graceMs: 3e3 });
120044
+ } catch (err) {
120045
+ console.error(`[claude] could not stop session host ${binding.id}:`, err.message);
120046
+ }
120047
+ }
120048
+ forgetHost(binding.id, binding.dir);
120049
+ }
120050
+
118373
120051
  // src/claude/claude-provider.ts
118374
120052
  var PromptQueue = class {
118375
120053
  buffer = [];
@@ -118421,6 +120099,7 @@ function widgetStreamOf(entry) {
118421
120099
  let tracker = widgetStreams.get(entry);
118422
120100
  if (!tracker) {
118423
120101
  tracker = new WidgetStreamTracker(WIDGET_TOOL_NAME, (preview, target) => {
120102
+ if (target.muted) return;
118424
120103
  broadcast("widget:delta", {
118425
120104
  sessionId: target.sessionId,
118426
120105
  turnId: target.turnId,
@@ -118440,6 +120119,10 @@ function sessionIdOfKey(key) {
118440
120119
  const i = key.indexOf(THREAD_KEY_SEPARATOR);
118441
120120
  return i === -1 ? key : key.slice(0, i);
118442
120121
  }
120122
+ function threadIdOfKey(key) {
120123
+ const i = key.indexOf(THREAD_KEY_SEPARATOR);
120124
+ return i === -1 ? null : key.slice(i + THREAD_KEY_SEPARATOR.length);
120125
+ }
118443
120126
  function sessionBackgroundTasks(sessionId) {
118444
120127
  const tasks = [];
118445
120128
  for (const [key, entry] of sessionMap2) {
@@ -118635,15 +120318,42 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
118635
120318
  }
118636
120319
  }
118637
120320
  }
118638
- async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
120321
+ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume, adopt) {
118639
120322
  const db2 = getDb();
118640
120323
  const key = mapKey ?? session.id;
120324
+ const cwd = session.cwd ?? process.cwd();
118641
120325
  const resumeId = mapKey !== void 0 ? resumeSessionId : resumeSessionId ?? session.external_thread_id ?? void 0;
118642
120326
  const rescue = resume && resumeId ? resume : void 0;
118643
120327
  const env = spawnEnv(session.id, rescue);
118644
120328
  let cliPid = null;
120329
+ let host = null;
120330
+ let spawner;
120331
+ if (adopt) {
120332
+ host = { id: adopt.row.id, dir: adopt.dir, proc: adopt.proc, runtimeVersion: adopt.row.runtime_version };
120333
+ spawner = attachedSpawner(adopt.proc);
120334
+ } else if (hostsEnabledFor("claude")) {
120335
+ try {
120336
+ const { id, dir } = newHostDir();
120337
+ host = { id, dir, proc: null, runtimeVersion: runtimeVersion() };
120338
+ spawner = hostedSpawner(db2, host, {
120339
+ sessionId: session.id,
120340
+ entryKey: key,
120341
+ threadId: threadIdOfKey(key),
120342
+ turnId: resume?.turnId ?? null,
120343
+ cwd,
120344
+ onDirect: (pid) => {
120345
+ if (!pid) return;
120346
+ cliPid = pid;
120347
+ recordCliProcess(db2, pid, session.id);
120348
+ }
120349
+ });
120350
+ } catch (err) {
120351
+ console.error(`[claude] no session host for ${key}:`, err.message);
120352
+ host = null;
120353
+ }
120354
+ }
118645
120355
  const options = {
118646
- cwd: session.cwd ?? process.cwd(),
120356
+ cwd,
118647
120357
  model: session.model ?? void 0,
118648
120358
  permissionMode: "bypassPermissions",
118649
120359
  allowDangerouslySkipPermissions: true,
@@ -118654,24 +120364,36 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118654
120364
  ...session.model_reasoning_effort ? { effort: session.model_reasoning_effort } : {},
118655
120365
  ...resumeId ? { resume: resumeId } : {},
118656
120366
  ...env ? { env } : {},
120367
+ // Only the SDK's own spawner calls this; a hosted CLI has no
120368
+ // cli_processes row (its host supervises it).
118657
120369
  onProcessSpawned: (pid) => {
118658
120370
  cliPid = pid;
118659
120371
  recordCliProcess(db2, pid, session.id);
118660
- }
120372
+ },
120373
+ ...spawner ? { spawnClaudeCodeProcess: spawner } : {}
118661
120374
  };
118662
120375
  const promptQueue = new PromptQueue();
118663
120376
  const q = query({ prompt: promptQueue, options });
118664
120377
  const entry = {
118665
120378
  query: q,
118666
- sessionId: null,
118667
- turnId: resume?.turnId ?? null,
118668
- cwd: session.cwd ?? process.cwd(),
120379
+ sessionId: adopt?.row.external_id ?? null,
120380
+ turnId: adopt ? adopt.row.turn_id : resume?.turnId ?? null,
120381
+ cwd,
118669
120382
  promptQueue,
118670
120383
  messageLoop: null,
118671
120384
  closeReason: null,
118672
- resume: resume ? { turnId: resume.turnId, phase: rescue ? "awaiting_rescue" : "continuing", watchdog: null } : null,
118673
- lastApiError: null
120385
+ 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,
120386
+ lastApiError: null,
120387
+ host,
120388
+ ...adopt ? { threadId: adopt.row.thread_id, retireWhenIdle: adopt.retire } : {}
118674
120389
  };
120390
+ if (adopt) {
120391
+ restoreBackgroundTasks(entry, adopt.row.background_tasks);
120392
+ const stored = db2.prepare("SELECT context_usage FROM sessions WHERE id = ?").get(session.id);
120393
+ restoreContext(entry, stored?.context_usage);
120394
+ forgetStreams(session.id);
120395
+ startReplay(entry);
120396
+ }
118675
120397
  sessionMap2.set(key, entry);
118676
120398
  startFinishedSweep();
118677
120399
  if (rescue) {
@@ -118686,22 +120408,11 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118686
120408
  entry.messageLoop = (async () => {
118687
120409
  try {
118688
120410
  for await (const message of q) {
118689
- trackIdle(entry, message);
118690
- if (isBackgroundTasksChanged(message)) {
118691
- handleBackgroundTasksChanged(message, session.id, entry);
118692
- continue;
118693
- }
118694
- if (message.type === "rate_limit_event") {
118695
- entry.rateLimit = message.rate_limit_info;
118696
- continue;
118697
- }
118698
- const currentTurnId = entry.turnId;
118699
- if (!currentTurnId) {
118700
- handleTaskFrame(message, session.id, entry, db2);
120411
+ if (isReplayMarker(message)) {
120412
+ finishReplay(entry, session.id, db2);
118701
120413
  continue;
118702
120414
  }
118703
- if (entry.resume && !trackResumeFrame(entry, message, db2)) continue;
118704
- await handleMessage(message, session.id, currentTurnId, entry, db2);
120415
+ await dispatchFrame(entry, session.id, message, db2);
118705
120416
  }
118706
120417
  if (entry.closeReason === "shutdown") return;
118707
120418
  if (entry.turnId) {
@@ -118723,6 +120434,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118723
120434
  console.error(`[claude] cleanup after loop error failed for session ${session.id}:`, cleanupErr);
118724
120435
  }
118725
120436
  } finally {
120437
+ entry.endReplay?.();
118726
120438
  clearResume(entry);
118727
120439
  if (entry.turnId) {
118728
120440
  streamingMessageIds.delete(entry.turnId);
@@ -118737,12 +120449,40 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
118737
120449
  } catch (err) {
118738
120450
  console.error(`[claude] cleanup after CLI exit failed for session ${session.id}:`, err.message);
118739
120451
  }
120452
+ if (entry.host) void releaseHost(entry.host);
118740
120453
  }
118741
120454
  }
118742
120455
  })();
118743
120456
  return entry;
118744
120457
  }
120458
+ async function dispatchFrame(entry, sessionId, message, db2, opts = {}) {
120459
+ trackIdle(entry, message);
120460
+ if (isBackgroundTasksChanged(message)) {
120461
+ handleBackgroundTasksChanged(message, sessionId, entry);
120462
+ return;
120463
+ }
120464
+ if (message.type === "rate_limit_event") {
120465
+ entry.rateLimit = message.rate_limit_info;
120466
+ return;
120467
+ }
120468
+ const currentTurnId = entry.turnId;
120469
+ if (!currentTurnId) {
120470
+ handleTaskFrame(message, sessionId, entry, db2);
120471
+ return;
120472
+ }
120473
+ if (entry.resume && !trackResumeFrame(entry, message, db2)) return;
120474
+ if (opts.awaitResult && message.type === "result") {
120475
+ await handleResultMessage(message, sessionId, currentTurnId, entry, db2);
120476
+ return;
120477
+ }
120478
+ await handleMessage(message, sessionId, currentTurnId, entry, db2);
120479
+ }
120480
+ function isTurnLive2(db2, turnId) {
120481
+ const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
120482
+ return row?.status === "pending" || row?.status === "running";
120483
+ }
118745
120484
  async function startTurn3(session, turn) {
120485
+ if (isAdoptionPending()) await waitForAdoption();
118746
120486
  const db2 = getDb();
118747
120487
  const now = (/* @__PURE__ */ new Date()).toISOString();
118748
120488
  const mapKey = turn.thread_id ? `${session.id}:thread:${turn.thread_id}` : session.id;
@@ -118782,6 +120522,7 @@ async function startTurn3(session, turn) {
118782
120522
  entry.turnId = turn.id;
118783
120523
  entry.lastApiError = null;
118784
120524
  clearResume(entry);
120525
+ bindHostTurn2(entry, turn.id);
118785
120526
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
118786
120527
  setSessionStatus2(db2, session.id, 1, "running", now);
118787
120528
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
@@ -118838,6 +120579,12 @@ async function handleMessage(message, sessionId, turnId, entry, db2) {
118838
120579
  const sub = message.subtype;
118839
120580
  if (sub === "init") {
118840
120581
  entry.sessionId = message.session_id;
120582
+ if (entry.host?.proc?.hosted) {
120583
+ try {
120584
+ updateHostRow(db2, entry.host.id, { external_id: entry.sessionId });
120585
+ } catch {
120586
+ }
120587
+ }
118841
120588
  if (!entry.threadId) {
118842
120589
  const now = (/* @__PURE__ */ new Date()).toISOString();
118843
120590
  db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
@@ -118870,6 +120617,7 @@ async function handleMessage(message, sessionId, turnId, entry, db2) {
118870
120617
  handleTaskFrame(message, sessionId, entry, db2);
118871
120618
  } else if (sub === "api_retry") {
118872
120619
  const m = message;
120620
+ if (entry.replaying) break;
118873
120621
  broadcast("turn:retrying", {
118874
120622
  sessionId,
118875
120623
  turnId,
@@ -119010,19 +120758,16 @@ function handleStreamEvent(message, sessionId, turnId, entry, db2) {
119010
120758
  }
119011
120759
  }
119012
120760
  if (!parentToolUseId) {
119013
- widgetStreamOf(entry).handle(message.event, { sessionId, turnId });
120761
+ widgetStreamOf(entry).handle(message.event, { sessionId, turnId, muted: !!entry.replaying });
119014
120762
  }
119015
120763
  const delta = mapPartialDelta(message.event);
119016
120764
  if (!delta) return;
119017
120765
  if (parentToolUseId) return;
119018
120766
  if (delta.kind === "text") {
119019
120767
  const msgId = streamingMessageIds.get(turnId) ?? `stream-text-${turnId}`;
119020
- broadcast("item:delta", {
119021
- sessionId,
119022
- turnId,
119023
- itemId: msgId,
119024
- delta: delta.text
119025
- });
120768
+ const payload = { sessionId, turnId, itemId: msgId, delta: delta.text };
120769
+ if (entry.replaying) noteDelta(payload);
120770
+ else broadcast("item:delta", payload);
119026
120771
  }
119027
120772
  if (delta.kind === "thinking") {
119028
120773
  let msgMap = thinkingAccumulator.get(message.uuid);
@@ -119237,10 +120982,20 @@ function handleBackgroundTasksChanged(message, sessionId, entry) {
119237
120982
  entry.backgroundTasks = tasks.filter((t) => !t.ambient).map((t) => ({ task_id: t.task_id, task_type: t.task_type, description: t.description }));
119238
120983
  publishBackgroundTasks(sessionId);
119239
120984
  if (endedIds.length > 0) closeTaskItemsSoon(sessionId, entry.threadId ?? null, endedIds);
120985
+ persistBackgroundTasks(entry);
120986
+ if (entry.backgroundTasks.length === 0) maybeRetire2(entry);
119240
120987
  }
119241
120988
  async function handleResultMessage(message, sessionId, turnId, entry, db2) {
119242
120989
  const parentToolUseId = message.parent_tool_use_id ?? null;
119243
120990
  if (parentToolUseId) return;
120991
+ try {
120992
+ await settleResult(message, sessionId, turnId, entry, db2);
120993
+ } finally {
120994
+ settleHostTurn2(entry);
120995
+ maybeRetire2(entry);
120996
+ }
120997
+ }
120998
+ async function settleResult(message, sessionId, turnId, entry, db2) {
119244
120999
  if (message.subtype === "success") {
119245
121000
  const usage = mapUsage(message.usage);
119246
121001
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -119361,6 +121116,8 @@ async function interruptTurn2(sessionId, threadId) {
119361
121116
  streamingMessageIds.delete(turnId);
119362
121117
  entry.turnId = null;
119363
121118
  entry.idleSince = Date.now();
121119
+ settleHostTurn2(entry);
121120
+ maybeRetire2(entry);
119364
121121
  return true;
119365
121122
  } catch {
119366
121123
  entry.closeReason = "clear";
@@ -119419,16 +121176,18 @@ function clearThread2(sessionId) {
119419
121176
  function clearThreadBranch(sessionId, threadId) {
119420
121177
  const key = `${sessionId}:thread:${threadId}`;
119421
121178
  const entry = sessionMap2.get(key);
119422
- if (entry) {
119423
- entry.closeReason ??= "clear";
119424
- entry.promptQueue.close();
119425
- entry.query.close();
119426
- if (entry.turnId) {
119427
- streamingMessageIds.delete(entry.turnId);
119428
- }
119429
- sessionMap2.delete(key);
119430
- dropBackgroundTasks(sessionId, entry);
121179
+ if (entry) closeEntry(key, entry);
121180
+ }
121181
+ function closeEntry(key, entry) {
121182
+ entry.closeReason ??= "clear";
121183
+ clearResume(entry);
121184
+ entry.promptQueue.close();
121185
+ entry.query.close();
121186
+ if (entry.turnId) {
121187
+ streamingMessageIds.delete(entry.turnId);
119431
121188
  }
121189
+ if (sessionMap2.get(key) === entry) sessionMap2.delete(key);
121190
+ dropBackgroundTasks(sessionIdOfKey(key), entry);
119432
121191
  }
119433
121192
  function clearAllThreads2() {
119434
121193
  for (const [, entry] of sessionMap2) {
@@ -119552,6 +121311,10 @@ async function shutdown2() {
119552
121311
  for (const entry of sessionMap2.values()) {
119553
121312
  entry.closeReason = "shutdown";
119554
121313
  clearResume(entry);
121314
+ if (entry.host?.proc?.hosted) {
121315
+ entry.host.proc.detach();
121316
+ continue;
121317
+ }
119555
121318
  if (db2 && entry.turnId && !entry.threadId) {
119556
121319
  try {
119557
121320
  markTurnInterrupted(db2, entry.turnId, "host_shutdown", { notify: false });
@@ -119577,6 +121340,7 @@ function retireCli(sessionId, entry) {
119577
121340
  }
119578
121341
  async function resumeInterruptedTurn2(session, turn, opts) {
119579
121342
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
121343
+ if (isAdoptionPending()) await waitForAdoption();
119580
121344
  let live = sessionMap2.get(session.id);
119581
121345
  if (live && opts.reason === "auth" && !live.backgroundTasks?.length) {
119582
121346
  retireCli(session.id, live);
@@ -119589,11 +121353,13 @@ async function resumeInterruptedTurn2(session, turn, opts) {
119589
121353
  live.threadId = null;
119590
121354
  live.lastApiError = null;
119591
121355
  live.resume = { turnId: turn.id, phase: "continuing", watchdog: null };
121356
+ bindHostTurn2(live, turn.id);
119592
121357
  pushPrompt(live, CONTINUE_PROMPT);
119593
121358
  return;
119594
121359
  }
119595
121360
  const entry = await ensureSessionStarted(session, void 0, void 0, { turnId: turn.id, reason: opts.reason });
119596
121361
  entry.threadId = null;
121362
+ bindHostTurn2(entry, turn.id);
119597
121363
  if (entry.resume?.phase === "continuing") pushPrompt(entry, buildUserContent(turn));
119598
121364
  }
119599
121365
  function syncThreadTitle2(sessionId) {
@@ -119724,6 +121490,213 @@ async function forkClaudeSession(session, targetTurn) {
119724
121490
  return null;
119725
121491
  }
119726
121492
  }
121493
+ var REPLAY_WAIT_MS2 = 3e4;
121494
+ function startReplay(entry) {
121495
+ let done = () => {
121496
+ };
121497
+ entry.replayDone = new Promise((resolve) => {
121498
+ done = resolve;
121499
+ });
121500
+ entry.replaying = true;
121501
+ entry.endReplay = () => {
121502
+ entry.replaying = false;
121503
+ done();
121504
+ };
121505
+ }
121506
+ function finishReplay(entry, sessionId, db2) {
121507
+ if (!entry.replaying) return;
121508
+ entry.endReplay?.();
121509
+ try {
121510
+ if (entry.idleSince === void 0 && !(entry.turnId && isTurnLive2(db2, entry.turnId))) entry.idleSince = Date.now();
121511
+ if (entry.resume?.phase === "awaiting_rescue") armRescueWatchdog(entry);
121512
+ publishBackgroundTasks(sessionId);
121513
+ const row = db2.prepare("SELECT status FROM sessions WHERE id = ?").get(sessionId);
121514
+ const idleStatus = row && row.status !== "running" && row.status !== "interrupted" ? row.status : "active";
121515
+ recomputeSessionRunning(db2, sessionId, idleStatus);
121516
+ } catch (err) {
121517
+ console.error(`[claude] after the replay of session ${sessionId}:`, err.message);
121518
+ }
121519
+ broadcast("session:resync", { sessionId });
121520
+ resendStreams(sessionId);
121521
+ maybeRetire2(entry);
121522
+ }
121523
+ function restoreBackgroundTasks(entry, json2) {
121524
+ if (!json2) return;
121525
+ try {
121526
+ const saved = JSON.parse(json2);
121527
+ entry.backgroundTasks = Array.isArray(saved.tasks) ? saved.tasks : [];
121528
+ entry.liveTaskIds = Array.isArray(saved.live) ? saved.live : [];
121529
+ } catch {
121530
+ }
121531
+ }
121532
+ function persistBackgroundTasks(entry) {
121533
+ const host = entry.host;
121534
+ if (!host?.proc?.hosted || entry.closeReason) return;
121535
+ try {
121536
+ setHostBackgroundTasks(
121537
+ getDb(),
121538
+ host.id,
121539
+ JSON.stringify({ tasks: entry.backgroundTasks ?? [], live: entry.liveTaskIds ?? [] })
121540
+ );
121541
+ } catch {
121542
+ }
121543
+ refreshHostLimit2(entry);
121544
+ }
121545
+ function refreshHostLimit2(entry, busy) {
121546
+ const host = entry.host;
121547
+ if (!host?.proc?.hosted || entry.closeReason) return;
121548
+ const flags = sessionHostFlags();
121549
+ const isBusy = busy ?? !!entry.backgroundTasks?.length;
121550
+ void limitHost(host.dir, isBusy ? flags.noHostBusyMs : flags.noHostIdleMs).catch(() => {
121551
+ });
121552
+ }
121553
+ function bindHostTurn2(entry, turnId) {
121554
+ const host = entry.host;
121555
+ const proc = host?.proc;
121556
+ if (!host || !proc?.hosted) return;
121557
+ const offset = proc.consumedLineEnd;
121558
+ try {
121559
+ setHostTurn(getDb(), host.id, turnId, offset);
121560
+ } catch (err) {
121561
+ console.error(`[claude] could not bind turn ${turnId} to its session host:`, err.message);
121562
+ }
121563
+ void ackHost(host.dir, offset).catch(() => {
121564
+ });
121565
+ refreshHostLimit2(entry, true);
121566
+ }
121567
+ function settleHostTurn2(entry) {
121568
+ const host = entry.host;
121569
+ const proc = host?.proc;
121570
+ if (!host || !proc?.hosted || entry.closeReason) return;
121571
+ const upto = proc.consumedLineEnd;
121572
+ try {
121573
+ setHostTurn(getDb(), host.id, entry.turnId, upto);
121574
+ } catch {
121575
+ }
121576
+ void ackHost(host.dir, upto).catch(() => {
121577
+ });
121578
+ refreshHostLimit2(entry);
121579
+ }
121580
+ function keyOfEntry(entry) {
121581
+ for (const [key, candidate] of sessionMap2) {
121582
+ if (candidate === entry) return key;
121583
+ }
121584
+ return null;
121585
+ }
121586
+ function maybeRetire2(entry) {
121587
+ const why = entry.retireWhenIdle;
121588
+ if (!why || entry.replaying || entry.closeReason || entry.resume) return;
121589
+ if (entry.backgroundTasks?.length || entry.idleSince === null) return;
121590
+ try {
121591
+ if (entry.turnId && isTurnLive2(getDb(), entry.turnId)) return;
121592
+ } catch {
121593
+ return;
121594
+ }
121595
+ const key = keyOfEntry(entry);
121596
+ if (!key) return;
121597
+ console.log(`[claude] closing the idle CLI of ${key} (${why}); the next prompt starts a new one`);
121598
+ closeEntry(key, entry);
121599
+ }
121600
+ function describeExit2(exit) {
121601
+ if (!exit) return "the session host died with its CLI";
121602
+ if (exit.error) return `Claude Code process could not start: ${exit.error}`;
121603
+ if (exit.signal) return `Claude Code process terminated by signal ${exit.signal}`;
121604
+ return `Claude Code process exited with code ${exit.code}`;
121605
+ }
121606
+ function deadEntry(session, row) {
121607
+ const gone = () => Promise.reject(new Error("the CLI is gone"));
121608
+ const entry = {
121609
+ query: { getContextUsage: gone, interrupt: gone, setModel: gone, stopTask: gone, close: () => {
121610
+ } },
121611
+ sessionId: row.external_id,
121612
+ turnId: row.turn_id,
121613
+ cwd: session.cwd ?? process.cwd(),
121614
+ promptQueue: { push: () => {
121615
+ }, close: () => {
121616
+ } },
121617
+ messageLoop: null,
121618
+ threadId: row.thread_id,
121619
+ closeReason: null,
121620
+ resume: null,
121621
+ lastApiError: null,
121622
+ replaying: true
121623
+ };
121624
+ restoreBackgroundTasks(entry, row.background_tasks);
121625
+ return entry;
121626
+ }
121627
+ var claudeHostAdopter = {
121628
+ runtime: "claude",
121629
+ async adoptLive(row, dir) {
121630
+ const db2 = getDb();
121631
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
121632
+ if (!session || session.runtime_type !== "claude") throw new Error("the session is not a Claude session any more");
121633
+ if (sessionMap2.has(row.entry_key)) throw new Error(`a CLI already runs for ${row.entry_key}`);
121634
+ const turn = row.turn_id ? db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(row.turn_id) : void 0;
121635
+ const running = !!turn && (turn.status === "running" || turn.status === "pending" && turn.resume_state !== "waiting");
121636
+ const proc = new HostedProcess({
121637
+ dir,
121638
+ after: row.replay_offset,
121639
+ replayMarker: REPLAY_MARKER2,
121640
+ onAttach: (header) => {
121641
+ try {
121642
+ updateHostRow(getDb(), row.id, { host_pid: header.hostPid, child_pid: header.child.pid });
121643
+ } catch {
121644
+ }
121645
+ }
121646
+ });
121647
+ await proc.ready;
121648
+ const version2 = runtimeVersion();
121649
+ 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;
121650
+ const entry = await ensureSessionStarted(session, row.thread_id ? row.entry_key : void 0, void 0, void 0, {
121651
+ row,
121652
+ dir,
121653
+ proc,
121654
+ resuming: running && turn?.resume_state === "resuming" && !row.thread_id,
121655
+ retire
121656
+ });
121657
+ refreshHostLimit2(entry, running);
121658
+ let timer2 = null;
121659
+ await Promise.race([
121660
+ entry.replayDone,
121661
+ new Promise((resolve) => {
121662
+ timer2 = setTimeout(() => {
121663
+ console.error(`[claude] the replay of ${row.entry_key} takes long; startup goes on`);
121664
+ resolve();
121665
+ }, REPLAY_WAIT_MS2);
121666
+ timer2.unref?.();
121667
+ })
121668
+ ]);
121669
+ if (timer2) clearTimeout(timer2);
121670
+ console.log(
121671
+ `[claude] adopted the CLI of ${row.entry_key} (pid ${proc.pid ?? "?"})${running ? `, turn ${row.turn_id} goes on` : ""}${retire ? `; it closes once idle: ${retire}` : ""}`
121672
+ );
121673
+ return { turnId: running ? row.turn_id : null };
121674
+ },
121675
+ async adoptDead(row, _dir, log, exit) {
121676
+ const db2 = getDb();
121677
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(row.session_id);
121678
+ if (!session || session.runtime_type !== "claude") return;
121679
+ const detail = describeExit2(exit);
121680
+ console.log(`[claude] the CLI of ${row.entry_key} ended with no daemon attached (${detail}); replaying its log`);
121681
+ if (log && log.length > 0) {
121682
+ const entry = deadEntry(session, row);
121683
+ forgetStreams(session.id);
121684
+ for (const message of logFrames(log)) {
121685
+ try {
121686
+ await dispatchFrame(entry, session.id, message, db2, { awaitResult: true });
121687
+ } catch (err) {
121688
+ console.error(`[claude] replay of ${row.entry_key} failed at a frame:`, err.message);
121689
+ }
121690
+ }
121691
+ forgetStreams(session.id);
121692
+ broadcast("session:resync", { sessionId: session.id });
121693
+ }
121694
+ if (row.turn_id && !row.thread_id && isTurnLive2(db2, row.turn_id)) {
121695
+ markTurnInterrupted(db2, row.turn_id, "process_exit", { detail, notify: false });
121696
+ }
121697
+ }
121698
+ };
121699
+ registerHostAdopter(claudeHostAdopter);
119727
121700
  var claudeProvider = {
119728
121701
  startTurn: startTurn3,
119729
121702
  interruptTurn: interruptTurn2,
@@ -119757,8 +121730,8 @@ var RepoburgHttpClient = class {
119757
121730
  this.baseUrl = baseUrl.replace(/\/+$/, "");
119758
121731
  }
119759
121732
  /** Perform a JSON request. Throws a concise error on non-OK/non-JSON responses. */
119760
- async request(method, path13, body) {
119761
- const response = await fetch(`${this.baseUrl}${path13}`, {
121733
+ async request(method, path17, body) {
121734
+ const response = await fetch(`${this.baseUrl}${path17}`, {
119762
121735
  method,
119763
121736
  headers: { "Content-Type": "application/json" },
119764
121737
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -119767,17 +121740,17 @@ var RepoburgHttpClient = class {
119767
121740
  if (!response.ok) {
119768
121741
  if (isHtml(text2)) {
119769
121742
  throw new Error(
119770
- `${method} ${path13} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121743
+ `${method} ${path17} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
119771
121744
  );
119772
121745
  }
119773
- throw new Error(`${method} ${path13} failed: ${response.status} ${text2}`);
121746
+ throw new Error(`${method} ${path17} failed: ${response.status} ${text2}`);
119774
121747
  }
119775
121748
  if (text2.length === 0) return void 0;
119776
121749
  try {
119777
121750
  return JSON.parse(text2);
119778
121751
  } catch {
119779
121752
  throw new Error(
119780
- `${method} ${path13} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121753
+ `${method} ${path17} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
119781
121754
  );
119782
121755
  }
119783
121756
  }
@@ -119832,7 +121805,7 @@ var RepoburgHttpClient = class {
119832
121805
  };
119833
121806
 
119834
121807
  // src/repoburg/backend-resolver.ts
119835
- import path12 from "node:path";
121808
+ import path15 from "node:path";
119836
121809
  var HEALTH_POLL_INTERVAL_MS = 1e3;
119837
121810
  var HEALTH_TIMEOUT_MS = 3e4;
119838
121811
  function daemonBaseUrl() {
@@ -119887,7 +121860,7 @@ async function backendHealthy(baseUrl, expectedPath) {
119887
121860
  const health = await fetchJson(`${baseUrl}/health`, void 0, 2e3);
119888
121861
  if (health.status !== "ok") return false;
119889
121862
  if (expectedPath && health.projectPath) {
119890
- return path12.resolve(health.projectPath) === path12.resolve(expectedPath);
121863
+ return path15.resolve(health.projectPath) === path15.resolve(expectedPath);
119891
121864
  }
119892
121865
  return true;
119893
121866
  } catch {
@@ -119908,7 +121881,7 @@ function serviceBaseUrl(service) {
119908
121881
  return `http://localhost:${service.port}`;
119909
121882
  }
119910
121883
  function coveringService(services, absPath) {
119911
- return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path12.sep)).sort((a, b) => b.path.length - a.path.length)[0];
121884
+ return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path15.sep)).sort((a, b) => b.path.length - a.path.length)[0];
119912
121885
  }
119913
121886
  async function restartService(daemon, name) {
119914
121887
  try {
@@ -119944,11 +121917,11 @@ async function resolveBackendUrl(projectPath, opts = {}) {
119944
121917
  if (envUrl) {
119945
121918
  return { baseUrl: envUrl.replace(/\/+$/, ""), port: 0, name: "REPOBURG_BACKEND_URL" };
119946
121919
  }
119947
- const absPath = path12.resolve(projectPath);
121920
+ const absPath = path15.resolve(projectPath);
119948
121921
  const daemon = daemonBaseUrl();
119949
- const cached2 = resolvedCache.get(absPath);
119950
- if (cached2 && await backendHealthy(cached2.baseUrl, cached2.servesPath ?? absPath)) {
119951
- return cached2;
121922
+ const cached3 = resolvedCache.get(absPath);
121923
+ if (cached3 && await backendHealthy(cached3.baseUrl, cached3.servesPath ?? absPath)) {
121924
+ return cached3;
119952
121925
  }
119953
121926
  try {
119954
121927
  await fetchJson(`${daemon}/health`, void 0, 3e3);
@@ -120222,7 +122195,12 @@ async function streamAgentRuntimeMessages(baseUrl, sessionId, onMessage, opts =
120222
122195
  if (opts.signal?.aborted) return "aborted";
120223
122196
  let response;
120224
122197
  try {
120225
- response = await fetch(url2, { method: "GET", signal: opts.signal });
122198
+ const lastEventId = opts.lastEventId?.() ?? null;
122199
+ response = await fetch(url2, {
122200
+ method: "GET",
122201
+ signal: opts.signal,
122202
+ ...lastEventId === null ? {} : { headers: { "Last-Event-ID": String(lastEventId) } }
122203
+ });
120226
122204
  } catch (err) {
120227
122205
  if (opts.signal?.aborted || err.name === "AbortError") {
120228
122206
  return "aborted";
@@ -120284,6 +122262,23 @@ async function readBody(body, onMessage, opts) {
120284
122262
  }
120285
122263
  }
120286
122264
  }
122265
+ async function getAgentRuntimeState(baseUrl, sessionId, timeoutMs = 5e3) {
122266
+ const url2 = `${baseUrl.replace(/\/+$/, "")}/agent-runtime/sessions/${sessionId}/state`;
122267
+ const response = await fetch(url2, { signal: AbortSignal.timeout(timeoutMs) });
122268
+ if (!response.ok) return null;
122269
+ try {
122270
+ const state = await response.json();
122271
+ if (typeof state.bootId !== "string" || typeof state.lastSeq !== "number") return null;
122272
+ return {
122273
+ bootId: state.bootId,
122274
+ lastSeq: state.lastSeq,
122275
+ turnInFlight: state.turnInFlight === true,
122276
+ lastResult: state.lastResult ?? null
122277
+ };
122278
+ } catch {
122279
+ return null;
122280
+ }
122281
+ }
120287
122282
  function reconnectDelay(delayMs, signal) {
120288
122283
  return new Promise((resolve) => {
120289
122284
  if (signal?.aborted) return resolve();
@@ -120316,16 +122311,25 @@ var TurnProjector = class {
120316
122311
  /** Context fill of the LAST LLM round (input tokens of the full prompt) —
120317
122312
  * drives the status-bar total-token counter at turn completion. */
120318
122313
  lastContextTokens = null;
122314
+ /** Messages that arrived while a gap recovery runs; null otherwise. */
122315
+ held = null;
122316
+ recovery = null;
122317
+ /** Another gap arrived while a recovery ran: fetch the snapshot again. */
122318
+ gapAgain = false;
120319
122319
  get isDone() {
120320
122320
  return this.done;
120321
122321
  }
120322
122322
  /** Main entry — dispatch one agent-runtime message. */
120323
122323
  handle(message) {
120324
122324
  if (this.done) return;
122325
+ if (this.held) {
122326
+ this.held.push(message);
122327
+ return;
122328
+ }
120325
122329
  switch (message.type) {
120326
122330
  case "system":
120327
122331
  break;
120328
- // init — connection marker only
122332
+ // init — connection marker only; gaps go to recoverGap
120329
122333
  case "stream_event":
120330
122334
  this.handleStreamEvent(message);
120331
122335
  break;
@@ -120353,6 +122357,61 @@ var TurnProjector = class {
120353
122357
  this.clearWatchdog();
120354
122358
  this.done = true;
120355
122359
  }
122360
+ /**
122361
+ * The backend no longer keeps some of the turn's messages. Project the
122362
+ * lost rounds from the REST snapshot (idempotent upserts), then the
122363
+ * messages held meanwhile. A turn that ended within the gap finishes from
122364
+ * the backend's last result, or from the snapshot when that is not this
122365
+ * turn's.
122366
+ */
122367
+ recoverGap() {
122368
+ if (this.done) return Promise.resolve();
122369
+ if (this.recovery) {
122370
+ this.gapAgain = true;
122371
+ return this.recovery;
122372
+ }
122373
+ this.held = [];
122374
+ this.recovery = this.runGapRecovery().finally(() => {
122375
+ this.recovery = null;
122376
+ });
122377
+ return this.recovery;
122378
+ }
122379
+ /** Resolves when no gap recovery holds messages back. */
122380
+ settled() {
122381
+ return this.recovery ?? Promise.resolve();
122382
+ }
122383
+ async runGapRecovery() {
122384
+ let state = null;
122385
+ try {
122386
+ do {
122387
+ this.gapAgain = false;
122388
+ const { client, repoburgSessionId } = this.deps;
122389
+ const [inputs, current] = await Promise.all([
122390
+ client.getSessionInputs(repoburgSessionId),
122391
+ getAgentRuntimeState(client.baseUrl, repoburgSessionId)
122392
+ ]);
122393
+ state = current;
122394
+ if (this.done) return;
122395
+ for (const input of inputs) {
122396
+ if (input.role === "model") this.projectSnapshotRound(input);
122397
+ }
122398
+ } while (this.gapAgain && !this.done);
122399
+ } catch (err) {
122400
+ console.error("[repoburg] gap recovery failed:", err);
122401
+ state = null;
122402
+ } finally {
122403
+ const held = this.held ?? [];
122404
+ this.held = null;
122405
+ for (const message of held) this.handle(message);
122406
+ }
122407
+ if (this.done || !state || state.turnInFlight) return;
122408
+ const last = state.lastResult;
122409
+ if (last && this.deps.firstSeq !== void 0 && typeof last.seq === "number" && last.seq >= this.deps.firstSeq) {
122410
+ this.handleResult(last);
122411
+ } else {
122412
+ await this.reconcileFromSnapshot();
122413
+ }
122414
+ }
120356
122415
  // -------------------------------------------------------------------------
120357
122416
  // Message handlers
120358
122417
  // -------------------------------------------------------------------------
@@ -120402,7 +122461,12 @@ var TurnProjector = class {
120402
122461
  else info.thoughts += msg.delta.text;
120403
122462
  const externalId = kind === "text" ? info.messageExternalId : info.reasoningExternalId;
120404
122463
  const type = kind === "text" ? "agent_message" : "reasoning";
120405
- const itemId = kind === "text" ? info.messageItemId : info.reasoningItemId;
122464
+ let itemId = kind === "text" ? info.messageItemId : info.reasoningItemId;
122465
+ if (!itemId) {
122466
+ itemId = this.existingItemId(externalId);
122467
+ if (kind === "text") info.messageItemId = itemId;
122468
+ else info.reasoningItemId = itemId;
122469
+ }
120406
122470
  if (!itemId) {
120407
122471
  const item = insertItem(
120408
122472
  db2,
@@ -120435,8 +122499,8 @@ var TurnProjector = class {
120435
122499
  const thinking = msg.content.filter((b) => b.type === "thinking").map((b) => b.thinking).join("");
120436
122500
  if (text2) info.text = text2;
120437
122501
  if (thinking) info.thoughts = thinking;
120438
- this.upsertCompletedTextItem(info, "message", info.text);
120439
122502
  this.upsertCompletedTextItem(info, "reasoning", info.thoughts);
122503
+ this.upsertCompletedTextItem(info, "message", info.text);
120440
122504
  this.touch();
120441
122505
  }
120442
122506
  /** Complete a round's text/thoughts item — creates it when deltas were
@@ -120454,8 +122518,16 @@ var TurnProjector = class {
120454
122518
  return;
120455
122519
  }
120456
122520
  }
120457
- const existing = db2.prepare("SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?").get(this.deps.turnId, externalId);
120458
- if (existing) return;
122521
+ const existing = db2.prepare("SELECT * FROM items WHERE turn_id = ? AND external_item_id = ?").get(this.deps.turnId, externalId);
122522
+ if (existing) {
122523
+ if (kind === "message") info.messageItemId = existing.id;
122524
+ else info.reasoningItemId = existing.id;
122525
+ const data = existing.data ? JSON.parse(existing.data) : {};
122526
+ if (existing.status !== "completed" || data.text !== text2) {
122527
+ completeItem(db2, this.deps.agentPaneSessionId, this.deps.turnId, { ...existing, data }, { text: text2 }, "completed");
122528
+ }
122529
+ return;
122530
+ }
120459
122531
  const item = insertItem(
120460
122532
  db2,
120461
122533
  this.deps.agentPaneSessionId,
@@ -120469,6 +122541,10 @@ var TurnProjector = class {
120469
122541
  if (kind === "message") info.messageItemId = item.id;
120470
122542
  else info.reasoningItemId = item.id;
120471
122543
  }
122544
+ existingItemId(externalId) {
122545
+ const row = getDb().prepare("SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?").get(this.deps.turnId, externalId);
122546
+ return row?.id ?? null;
122547
+ }
120472
122548
  handleUser(msg) {
120473
122549
  const db2 = getDb();
120474
122550
  for (const block of msg.content) {
@@ -120851,8 +122927,8 @@ var TurnProjector = class {
120851
122927
  const info = this.round(input.id);
120852
122928
  info.text = info.text || (input.raw_llm_response ?? "");
120853
122929
  info.thoughts = info.thoughts || (input.thoughts ?? "");
120854
- this.upsertCompletedTextItem(info, "message", info.text);
120855
122930
  this.upsertCompletedTextItem(info, "reasoning", info.thoughts);
122931
+ this.upsertCompletedTextItem(info, "message", info.text);
120856
122932
  const actions = [...input.aiActions ?? []].sort(
120857
122933
  (a, b) => (a.order_of_execution ?? 0) - (b.order_of_execution ?? 0)
120858
122934
  );
@@ -121066,9 +123142,9 @@ function failTurn3(entry, error51) {
121066
123142
  broadcast("turn:failed", { sessionId: entry.agentPaneSessionId, turnId: active.turnId, error: error51 });
121067
123143
  }
121068
123144
  async function runStreamLoop(entry, projector) {
121069
- const isCurrent = () => entry.activeTurn?.projector === projector && !projector.isDone;
123145
+ const isCurrent2 = () => entry.activeTurn?.projector === projector && !projector.isDone;
121070
123146
  const lose = (error51) => {
121071
- if (isCurrent()) failTurn3(entry, error51);
123147
+ if (isCurrent2()) failTurn3(entry, error51);
121072
123148
  };
121073
123149
  let lostTimer = null;
121074
123150
  const clearLostTimer = () => {
@@ -121076,7 +123152,7 @@ async function runStreamLoop(entry, projector) {
121076
123152
  lostTimer = null;
121077
123153
  };
121078
123154
  try {
121079
- while (isCurrent()) {
123155
+ while (isCurrent2()) {
121080
123156
  const active = entry.activeTurn;
121081
123157
  const controller = new AbortController();
121082
123158
  active.sseAbort = controller;
@@ -121087,12 +123163,23 @@ async function runStreamLoop(entry, projector) {
121087
123163
  };
121088
123164
  resetStall();
121089
123165
  const onMessage = (message) => {
123166
+ if (message.type === "system" && message.subtype === "gap") {
123167
+ void projector.recoverGap().then(() => {
123168
+ if (projector.isDone) controller.abort();
123169
+ });
123170
+ return;
123171
+ }
121090
123172
  if (message.type === "system") {
121091
123173
  clearLostTimer();
121092
123174
  const bootId = message.bootId ?? null;
121093
123175
  if (active.bootId === void 0) active.bootId = bootId;
121094
123176
  else if (bootId !== active.bootId) return lose(BACKEND_RESTARTED_ERROR);
121095
123177
  }
123178
+ const seq = messageSeq(message);
123179
+ if (seq !== null) {
123180
+ if (active.lastSeq !== null && seq <= active.lastSeq) return;
123181
+ active.lastSeq = seq;
123182
+ }
121096
123183
  projector.handle(message);
121097
123184
  };
121098
123185
  const onDisconnect = () => {
@@ -121106,10 +123193,12 @@ async function runStreamLoop(entry, projector) {
121106
123193
  const reason = await streamAgentRuntimeMessages(entry.baseUrl, entry.repoburgSessionId, onMessage, {
121107
123194
  signal: controller.signal,
121108
123195
  onActivity: resetStall,
121109
- onDisconnect
123196
+ onDisconnect,
123197
+ lastEventId: () => active.lastSeq
121110
123198
  });
121111
123199
  if (stallTimer) clearTimeout(stallTimer);
121112
- if (!isCurrent()) return;
123200
+ await projector.settled();
123201
+ if (!isCurrent2()) return;
121113
123202
  if (reason === "session-not-found") {
121114
123203
  failTurn3(entry, "Repoburg session no longer exists on the backend.");
121115
123204
  return;
@@ -121123,6 +123212,10 @@ async function runStreamLoop(entry, projector) {
121123
123212
  clearLostTimer();
121124
123213
  }
121125
123214
  }
123215
+ function messageSeq(message) {
123216
+ const seq = message.seq;
123217
+ return typeof seq === "number" ? seq : null;
123218
+ }
121126
123219
  function turnImageDataUrls(turn) {
121127
123220
  const raw = turn.attachments;
121128
123221
  if (!raw) return [];
@@ -121158,12 +123251,6 @@ async function startTurn4(session, turn) {
121158
123251
  failTurnBeforeStart(db2, session.id, turn.id, `Failed to resolve repoburg backend: ${err.message}`);
121159
123252
  return;
121160
123253
  }
121161
- const pinned = sessionMap3.get(session.id);
121162
- if (pinned && pinned.baseUrl !== baseUrl) {
121163
- console.warn(
121164
- `[repoburg] resolved backend ${baseUrl} differs from pinned ${pinned.baseUrl} for session ${session.id} \u2014 keeping the pinned entry.`
121165
- );
121166
- }
121167
123254
  void registerMiniAppMcp(baseUrl, session.cwd ?? "");
121168
123255
  const firstInput = !turn.thread_id && !sessionMap3.has(session.id) && !session.external_thread_id;
121169
123256
  let entry;
@@ -121174,6 +123261,11 @@ async function startTurn4(session, turn) {
121174
123261
  failTurnBeforeStart(db2, session.id, turn.id, `Failed to create repoburg session: ${err.message}`);
121175
123262
  return;
121176
123263
  }
123264
+ if (entry.baseUrl !== baseUrl && (!entry.activeTurn || entry.activeTurn.projector.isDone)) {
123265
+ console.warn(`[repoburg] session ${session.id}: backend moved from ${entry.baseUrl} to ${baseUrl}`);
123266
+ entry.baseUrl = baseUrl;
123267
+ entry.client = client;
123268
+ }
121177
123269
  const wantedModel = session.model ?? null;
121178
123270
  const wantedEffort = mapReasoningEffort(session.model, session.model_reasoning_effort);
121179
123271
  if (wantedModel !== entry.modelId || wantedEffort !== entry.reasoningEffort) {
@@ -121193,6 +123285,16 @@ async function startTurn4(session, turn) {
121193
123285
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
121194
123286
  setSessionStatus3(db2, session.id, 1, "running", now);
121195
123287
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
123288
+ const state = await getAgentRuntimeState(entry.baseUrl, entry.repoburgSessionId).catch(() => null);
123289
+ if (state) {
123290
+ const cursor = {
123291
+ bootId: state.bootId,
123292
+ firstSeq: state.lastSeq + 1,
123293
+ baseUrl: entry.baseUrl,
123294
+ runtimeSessionId: entry.repoburgSessionId
123295
+ };
123296
+ db2.prepare("UPDATE turns SET stream_cursor = ? WHERE id = ?").run(JSON.stringify(cursor), turn.id);
123297
+ }
121196
123298
  const projector = new TurnProjector({
121197
123299
  agentPaneSessionId: session.id,
121198
123300
  turnId: turn.id,
@@ -121200,9 +123302,19 @@ async function startTurn4(session, turn) {
121200
123302
  client: entry.client,
121201
123303
  // Late-bound — the window resolves from the runtime catalog while the
121202
123304
  // turn streams and is read at turn completion.
121203
- getContextWindow: () => entry.contextWindow
123305
+ getContextWindow: () => entry.contextWindow,
123306
+ ...state ? { firstSeq: state.lastSeq + 1 } : {}
121204
123307
  });
121205
- entry.activeTurn = { turnId: turn.id, projector, sseAbort: new AbortController(), cancelled: false };
123308
+ entry.activeTurn = {
123309
+ turnId: turn.id,
123310
+ projector,
123311
+ sseAbort: new AbortController(),
123312
+ cancelled: false,
123313
+ // The stream opens after this point: messages the turn emits before it
123314
+ // connects are sent again (Last-Event-ID).
123315
+ ...state ? { bootId: state.bootId } : {},
123316
+ lastSeq: state ? state.lastSeq : null
123317
+ };
121206
123318
  void ensureContextWindow(entry);
121207
123319
  runStreamLoop(entry, projector).catch((err) => {
121208
123320
  console.error("[repoburg] stream loop crashed:", err);
@@ -121220,6 +123332,102 @@ async function startTurn4(session, turn) {
121220
123332
  failTurn3(entry, err.message);
121221
123333
  }
121222
123334
  }
123335
+ function parseCursor(raw) {
123336
+ if (!raw) return null;
123337
+ try {
123338
+ const cursor = JSON.parse(raw);
123339
+ if (typeof cursor.bootId !== "string" || typeof cursor.firstSeq !== "number" || typeof cursor.baseUrl !== "string" || typeof cursor.runtimeSessionId !== "string") {
123340
+ return null;
123341
+ }
123342
+ return cursor;
123343
+ } catch {
123344
+ return null;
123345
+ }
123346
+ }
123347
+ var ADOPT_STATE_ATTEMPTS = 3;
123348
+ var ADOPT_STATE_RETRY_MS = 300;
123349
+ async function adoptionState(cursor) {
123350
+ for (let attempt = 1; ; attempt++) {
123351
+ try {
123352
+ return await getAgentRuntimeState(cursor.baseUrl, cursor.runtimeSessionId);
123353
+ } catch (err) {
123354
+ if (attempt >= ADOPT_STATE_ATTEMPTS) throw err;
123355
+ await new Promise((resolve) => setTimeout(resolve, ADOPT_STATE_RETRY_MS));
123356
+ }
123357
+ }
123358
+ }
123359
+ async function adoptRepoburgTurns(db2, result) {
123360
+ if (!sessionHostFlags().repoburg) return;
123361
+ const rows = db2.prepare(
123362
+ `SELECT t.id, t.session_id, t.thread_id, t.stream_cursor, s.model
123363
+ FROM turns t JOIN sessions s ON s.id = t.session_id
123364
+ WHERE t.status = 'running' AND s.runtime_type = 'repoburg' AND t.stream_cursor IS NOT NULL`
123365
+ ).all();
123366
+ for (const row of rows) {
123367
+ const cursor = parseCursor(row.stream_cursor);
123368
+ if (!cursor) continue;
123369
+ let state;
123370
+ try {
123371
+ state = await adoptionState(cursor);
123372
+ } catch (err) {
123373
+ console.warn(`[repoburg] backend of turn ${row.id} unreachable; recovery takes it:`, err.message);
123374
+ continue;
123375
+ }
123376
+ if (!state) continue;
123377
+ if (state.bootId !== cursor.bootId) {
123378
+ db2.prepare("UPDATE items SET status = ?, updated_at = ? WHERE turn_id = ? AND status = ?").run(
123379
+ "failed",
123380
+ (/* @__PURE__ */ new Date()).toISOString(),
123381
+ row.id,
123382
+ "in_progress"
123383
+ );
123384
+ failTurnBeforeStart(db2, row.session_id, row.id, BACKEND_RESTARTED_ERROR);
123385
+ result.turnIds.add(row.id);
123386
+ continue;
123387
+ }
123388
+ const entry = {
123389
+ agentPaneSessionId: row.session_id,
123390
+ repoburgSessionId: cursor.runtimeSessionId,
123391
+ client: new RepoburgHttpClient(cursor.baseUrl),
123392
+ baseUrl: cursor.baseUrl,
123393
+ modelId: row.model,
123394
+ reasoningEffort: void 0,
123395
+ // re-pushed on the next turn
123396
+ threadId: row.thread_id,
123397
+ contextWindow: null,
123398
+ modelsResolved: false,
123399
+ activeTurn: null
123400
+ };
123401
+ sessionMap3.set(row.thread_id ? `${row.session_id}:thread:${row.thread_id}` : row.session_id, entry);
123402
+ const projector = new TurnProjector({
123403
+ agentPaneSessionId: row.session_id,
123404
+ turnId: row.id,
123405
+ repoburgSessionId: cursor.runtimeSessionId,
123406
+ client: entry.client,
123407
+ getContextWindow: () => entry.contextWindow,
123408
+ firstSeq: cursor.firstSeq
123409
+ });
123410
+ entry.activeTurn = {
123411
+ turnId: row.id,
123412
+ projector,
123413
+ sseAbort: new AbortController(),
123414
+ cancelled: false,
123415
+ bootId: cursor.bootId,
123416
+ // The backend sends the turn's messages again from its first one.
123417
+ lastSeq: cursor.firstSeq - 1
123418
+ };
123419
+ void ensureContextWindow(entry);
123420
+ runStreamLoop(entry, projector).catch((err) => {
123421
+ console.error("[repoburg] stream loop crashed:", err);
123422
+ failTurn3(entry, `Stream loop failed: ${err.message}`);
123423
+ });
123424
+ result.turnIds.add(row.id);
123425
+ result.sessionIds.add(row.session_id);
123426
+ result.entries.add(runtimeEntryKey(row.session_id, row.thread_id));
123427
+ console.log(`[repoburg] adopted turn ${row.id}: replaying from message ${cursor.firstSeq}`);
123428
+ }
123429
+ }
123430
+ registerRuntimeAdopter("repoburg", adoptRepoburgTurns);
121223
123431
  async function interruptTurn3(sessionId, threadId) {
121224
123432
  let entry = threadId ? sessionMap3.get(`${sessionId}:thread:${threadId}`) : sessionMap3.get(sessionId);
121225
123433
  if (!threadId && !entry?.activeTurn) {
@@ -121390,6 +123598,7 @@ registerProvider("repoburg", repoburgProvider);
121390
123598
  async function createAgentPaneApp(dbPath, opts = {}) {
121391
123599
  const allowRequest = opts.allowRequest ?? isLocalRequest;
121392
123600
  initDb(dbPath);
123601
+ setPaneDataDir(dbPath === ":memory:" ? null : path16.dirname(path16.resolve(dbPath)));
121393
123602
  const fastify = (0, import_fastify.default)({ logger: true, bodyLimit: 50 * 1024 * 1024 });
121394
123603
  fastify.addHook("onRequest", async (request, reply) => {
121395
123604
  if (!allowRequest(request.headers.origin, request.headers.host)) {
@@ -121415,20 +123624,33 @@ async function createAgentPaneApp(dbPath, opts = {}) {
121415
123624
  await registerSidecarRoutes(fastify);
121416
123625
  await registerUsageRoutes(fastify);
121417
123626
  await registerClaudeSessionRoutes(fastify);
123627
+ await registerSessionHostRoutes(fastify);
121418
123628
  const wss3 = initWs(allowRequest);
121419
123629
  initTerminalWs(allowRequest);
123630
+ trackStreams();
121420
123631
  wss3.on("connection", (ws) => {
121421
123632
  ws.send(JSON.stringify({ event: "background_tasks:snapshot", data: { sessions: listAllBackgroundTasks() } }));
121422
123633
  ws.send(JSON.stringify({ event: "signed_out_turns:snapshot", data: { turns: listSignedOutTurns(getDb()) } }));
123634
+ ws.send(JSON.stringify({ event: "streams:snapshot", data: streamsSnapshot() }));
121423
123635
  });
121424
123636
  return { fastify, wss: wss3 };
121425
123637
  }
121426
123638
 
121427
123639
  // src/host-lifecycle.ts
121428
123640
  var CLOSE_TIMEOUT_MS = 3e3;
121429
- function startHostServices() {
121430
- startAutoResume();
123641
+ function startHostServices(opts = {}) {
123642
+ setSessionHostDaemonUrl(opts.daemonUrl);
123643
+ const started = adoptSessionHosts().catch((err) => {
123644
+ console.error("[session-host] adoption failed:", err);
123645
+ return lastAdoption();
123646
+ }).then((adopted) => {
123647
+ startAutoResume({ skip: adopted });
123648
+ }).catch((err) => {
123649
+ console.error("[resume] automatic resume failed to start:", err);
123650
+ });
123651
+ setStartupGate(started);
121431
123652
  void getVscodeWebManager().reapOrphans();
123653
+ return started;
121432
123654
  }
121433
123655
  async function shutdownHost() {
121434
123656
  stopAutoResume();
@@ -121479,7 +123701,7 @@ async function main() {
121479
123701
  fastify.log.error(err);
121480
123702
  process.exit(1);
121481
123703
  }
121482
- startHostServices();
123704
+ void startHostServices({ daemonUrl: `http://127.0.0.1:${PORT}` });
121483
123705
  async function gracefulShutdown(signal) {
121484
123706
  fastify.log.info(`Received ${signal}, shutting down...`);
121485
123707
  await shutdownHost();