repoburg 1.3.304 → 1.3.305

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.
@@ -2680,7 +2680,7 @@ var require_server = __commonJS({
2680
2680
  var https = __require("node:https");
2681
2681
  var http22 = __require("node:http2");
2682
2682
  var dns = __require("node:dns");
2683
- var os5 = __require("node:os");
2683
+ var os6 = __require("node:os");
2684
2684
  var { kState, kOptions, kServerBindings, kHttp2ServerSessions } = require_symbols2();
2685
2685
  var { FSTWRN003 } = require_warnings();
2686
2686
  var { onListenHookRunner } = require_hooks();
@@ -2942,7 +2942,7 @@ var require_server = __commonJS({
2942
2942
  }
2943
2943
  function getAddresses(address) {
2944
2944
  if (address.address === "0.0.0.0") {
2945
- return Object.values(os5.networkInterfaces()).flatMap((iface) => {
2945
+ return Object.values(os6.networkInterfaces()).flatMap((iface) => {
2946
2946
  return iface.filter((iface2) => iface2.family === "IPv4");
2947
2947
  }).sort((iface) => {
2948
2948
  return iface.internal ? -1 : 1;
@@ -6128,8 +6128,8 @@ var require_req = __commonJS({
6128
6128
  if (req.originalUrl) {
6129
6129
  _req.url = req.originalUrl;
6130
6130
  } else {
6131
- const path17 = req.path;
6132
- _req.url = typeof path17 === "string" ? path17 : req.url ? req.url.path || req.url : void 0;
6131
+ const path19 = req.path;
6132
+ _req.url = typeof path19 === "string" ? path19 : 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(path17) {
6297
+ function parsePath(path19) {
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 < path17.length; i++) {
6304
- const char = path17[i];
6303
+ for (let i = 0; i < path19.length; i++) {
6304
+ const char = path19[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 path17 of paths) {
6436
- const parts = parsePath(path17);
6435
+ for (const path19 of paths) {
6436
+ const parts = parsePath(path19);
6437
6437
  if (parts.includes("*")) {
6438
- redactWildcardPath(obj2, parts, censor, path17, remove);
6438
+ redactWildcardPath(obj2, parts, censor, path19, 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, path17) => {
6524
- const fullPath = [...pathArray.slice(0, pathLength), ...path17];
6523
+ const wrappedCensor = typeof censor === "function" ? (value, path19) => {
6524
+ const fullPath = [...pathArray.slice(0, pathLength), ...path19];
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 path17 of pathsToClone) {
6560
- const parts = parsePath(path17);
6559
+ for (const path19 of pathsToClone) {
6560
+ const parts = parsePath(path19);
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(path17) {
6613
- if (typeof path17 !== "string") {
6612
+ function validatePath(path19) {
6613
+ if (typeof path19 !== "string") {
6614
6614
  throw new Error("Paths must be (non-empty) strings");
6615
6615
  }
6616
- if (path17 === "") {
6616
+ if (path19 === "") {
6617
6617
  throw new Error("Invalid redaction path ()");
6618
6618
  }
6619
- if (path17.includes("..")) {
6620
- throw new Error(`Invalid redaction path (${path17})`);
6619
+ if (path19.includes("..")) {
6620
+ throw new Error(`Invalid redaction path (${path19})`);
6621
6621
  }
6622
- if (path17.includes(",")) {
6623
- throw new Error(`Invalid redaction path (${path17})`);
6622
+ if (path19.includes(",")) {
6623
+ throw new Error(`Invalid redaction path (${path19})`);
6624
6624
  }
6625
6625
  let bracketCount = 0;
6626
6626
  let inQuotes = false;
6627
6627
  let quoteChar = "";
6628
- for (let i = 0; i < path17.length; i++) {
6629
- const char = path17[i];
6628
+ for (let i = 0; i < path19.length; i++) {
6629
+ const char = path19[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 (${path17})`);
6643
+ throw new Error(`Invalid redaction path (${path19})`);
6644
6644
  }
6645
6645
  }
6646
6646
  }
6647
6647
  if (bracketCount !== 0) {
6648
- throw new Error(`Invalid redaction path (${path17})`);
6648
+ throw new Error(`Invalid redaction path (${path19})`);
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 path17 of paths) {
6656
- validatePath(path17);
6655
+ for (const path19 of paths) {
6656
+ validatePath(path19);
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, path17) => {
6825
- return censor(value, [k, ...path17]);
6824
+ const wrappedCensor = typeof censor === "function" ? (value, path19) => {
6825
+ return censor(value, [k, ...path19]);
6826
6826
  } : censor;
6827
6827
  o[k] = Redact({
6828
6828
  paths: shape[k],
@@ -7043,7 +7043,7 @@ var require_sonic_boom = __commonJS({
7043
7043
  var fs11 = __require("fs");
7044
7044
  var EventEmitter5 = __require("events");
7045
7045
  var inherits = __require("util").inherits;
7046
- var path17 = __require("path");
7046
+ var path19 = __require("path");
7047
7047
  var sleep2 = require_atomic_sleep();
7048
7048
  var assert2 = __require("assert");
7049
7049
  var BUSY_WRITE_TIMEOUT = 100;
@@ -7097,7 +7097,7 @@ var require_sonic_boom = __commonJS({
7097
7097
  const mode = sonic.mode;
7098
7098
  if (sonic.sync) {
7099
7099
  try {
7100
- if (sonic.mkdir) fs11.mkdirSync(path17.dirname(file2), { recursive: true });
7100
+ if (sonic.mkdir) fs11.mkdirSync(path19.dirname(file2), { recursive: true });
7101
7101
  const fd = fs11.openSync(file2, flags, mode);
7102
7102
  fileOpened(null, fd);
7103
7103
  } catch (err) {
@@ -7105,7 +7105,7 @@ var require_sonic_boom = __commonJS({
7105
7105
  throw err;
7106
7106
  }
7107
7107
  } else if (sonic.mkdir) {
7108
- fs11.mkdir(path17.dirname(file2), { recursive: true }, (err) => {
7108
+ fs11.mkdir(path19.dirname(file2), { recursive: true }, (err) => {
7109
7109
  if (err) return fileOpened(err);
7110
7110
  fs11.open(file2, flags, mode, fileOpened);
7111
7111
  });
@@ -8437,15 +8437,15 @@ var require_transport = __commonJS({
8437
8437
  if (!unquoted) {
8438
8438
  return false;
8439
8439
  }
8440
- let path17 = unquoted;
8441
- if (path17.startsWith("file://")) {
8440
+ let path19 = unquoted;
8441
+ if (path19.startsWith("file://")) {
8442
8442
  try {
8443
- path17 = fileURLToPath5(path17);
8443
+ path19 = fileURLToPath5(path19);
8444
8444
  } catch {
8445
8445
  return false;
8446
8446
  }
8447
8447
  }
8448
- return isAbsolute(path17) && !existsSync3(path17);
8448
+ return isAbsolute(path19) && !existsSync3(path19);
8449
8449
  }
8450
8450
  function stripQuotes(value) {
8451
8451
  const first = value[0];
@@ -10139,7 +10139,7 @@ var require_multistream = __commonJS({
10139
10139
  var require_pino = __commonJS({
10140
10140
  "node_modules/pino/pino.js"(exports, module) {
10141
10141
  "use strict";
10142
- var os5 = __require("node:os");
10142
+ var os6 = __require("node:os");
10143
10143
  var stdSerializers = require_pino_std_serializers();
10144
10144
  var caller = require_caller();
10145
10145
  var redaction = require_redaction();
@@ -10186,7 +10186,7 @@ var require_pino = __commonJS({
10186
10186
  } = symbols;
10187
10187
  var { epochTime, nullTime } = time3;
10188
10188
  var { pid } = process;
10189
- var hostname4 = os5.hostname();
10189
+ var hostname4 = os6.hostname();
10190
10190
  var defaultErrorSerializer = stdSerializers.err;
10191
10191
  var defaultOptions = {
10192
10192
  level: "info",
@@ -11884,7 +11884,7 @@ var require_reply = __commonJS({
11884
11884
  const trailerHeaders = Object.keys(reply[kReplyTrailers]);
11885
11885
  const trailers = {};
11886
11886
  let handled = 0;
11887
- let skipped = true;
11887
+ let skipped2 = true;
11888
11888
  let sent = false;
11889
11889
  function send2() {
11890
11890
  if (handled === 0 && !sent) {
@@ -11903,7 +11903,7 @@ var require_reply = __commonJS({
11903
11903
  process.nextTick(send2);
11904
11904
  };
11905
11905
  if (typeof reply[kReplyTrailers][trailerName] !== "function") continue;
11906
- skipped = false;
11906
+ skipped2 = false;
11907
11907
  handled--;
11908
11908
  let cbAlreadyCalled = false;
11909
11909
  const result = reply[kReplyTrailers][trailerName](reply, payload, cb);
@@ -11911,7 +11911,7 @@ var require_reply = __commonJS({
11911
11911
  result.then((v) => cb(null, v), cb);
11912
11912
  }
11913
11913
  }
11914
- if (skipped) res.end(null, null, null);
11914
+ if (skipped2) res.end(null, null, null);
11915
11915
  }
11916
11916
  function sendStreamTrailer(payload, res, reply) {
11917
11917
  if (reply[kReplyTrailers] === null) return;
@@ -17121,8 +17121,8 @@ var require_utils = __commonJS({
17121
17121
  }
17122
17122
  return ind;
17123
17123
  }
17124
- function removeDotSegments(path17) {
17125
- let input = path17;
17124
+ function removeDotSegments(path19) {
17125
+ let input = path19;
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 [path17, query2] = wsComponent.resourceName.split("?");
17378
- wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
17377
+ const [path19, query2] = wsComponent.resourceName.split("?");
17378
+ wsComponent.path = path19 && path19 !== "/" ? path19 : void 0;
17379
17379
  wsComponent.query = query2;
17380
17380
  wsComponent.resourceName = void 0;
17381
17381
  }
@@ -22312,8 +22312,8 @@ var require_utils2 = __commonJS({
22312
22312
  }
22313
22313
  return ind;
22314
22314
  }
22315
- function removeDotSegments(path17) {
22316
- let input = path17;
22315
+ function removeDotSegments(path19) {
22316
+ let input = path19;
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 [path17, query2] = wsComponent.resourceName.split("?");
22662
- wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
22661
+ const [path19, query2] = wsComponent.resourceName.split("?");
22662
+ wsComponent.path = path19 && path19 !== "/" ? path19 : void 0;
22663
22663
  wsComponent.query = query2;
22664
22664
  wsComponent.resourceName = void 0;
22665
22665
  }
@@ -24143,8 +24143,8 @@ var require_utils3 = __commonJS({
24143
24143
  }
24144
24144
  return ind;
24145
24145
  }
24146
- function removeDotSegments(path17) {
24147
- let input = path17;
24146
+ function removeDotSegments(path19) {
24147
+ let input = path19;
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 [path17, query2] = wsComponent.resourceName.split("?");
24493
- wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
24492
+ const [path19, query2] = wsComponent.resourceName.split("?");
24493
+ wsComponent.path = path19 && path19 !== "/" ? path19 : void 0;
24494
24494
  wsComponent.query = query2;
24495
24495
  wsComponent.resourceName = void 0;
24496
24496
  }
@@ -32007,13 +32007,13 @@ var require_node = __commonJS({
32007
32007
  this.staticChildrenNodes[index] = node;
32008
32008
  }
32009
32009
  }
32010
- findStaticMatchingChild(path17, pathIndex) {
32011
- const charCode = path17.charCodeAt(pathIndex);
32010
+ findStaticMatchingChild(path19, pathIndex) {
32011
+ const charCode = path19.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(path17, pathIndex)) {
32016
+ if (staticChild.matchPrefix(path19, 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(path17, pathIndex = 0) {
32025
- if (path17.length === pathIndex) {
32024
+ getStaticChild(path19, pathIndex = 0) {
32025
+ if (path19.length === pathIndex) {
32026
32026
  return this;
32027
32027
  }
32028
- const staticChild = this.findStaticMatchingChild(path17, pathIndex);
32028
+ const staticChild = this.findStaticMatchingChild(path19, pathIndex);
32029
32029
  if (staticChild) {
32030
- return staticChild.getStaticChild(path17, pathIndex + staticChild.prefix.length);
32030
+ return staticChild.getStaticChild(path19, pathIndex + staticChild.prefix.length);
32031
32031
  }
32032
32032
  return null;
32033
32033
  }
32034
- createStaticChild(path17) {
32035
- if (path17.length === 0) {
32034
+ createStaticChild(path19) {
32035
+ if (path19.length === 0) {
32036
32036
  return this;
32037
32037
  }
32038
- const childIndex = this.staticChildrenCharCodes.indexOf(path17.charCodeAt(0));
32038
+ const childIndex = this.staticChildrenCharCodes.indexOf(path19.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 (path17.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
32043
+ if (path19.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
32044
32044
  staticChild = staticChild.split(this, i);
32045
32045
  break;
32046
32046
  }
32047
32047
  }
32048
- return staticChild.createStaticChild(path17.slice(i));
32048
+ return staticChild.createStaticChild(path19.slice(i));
32049
32049
  }
32050
- const node = new StaticNode(path17);
32051
- this.setStaticChild(path17.charAt(0), node);
32050
+ const node = new StaticNode(path19);
32051
+ this.setStaticChild(path19.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(path17, pathIndex, nodeStack, paramsCount) {
32112
- let node = this.findStaticMatchingChild(path17, pathIndex);
32111
+ getNextNode(path19, pathIndex, nodeStack, paramsCount) {
32112
+ let node = this.findStaticMatchingChild(path19, 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(path17, pathIndex) {
32160
- return this.findStaticMatchingChild(path17, pathIndex);
32159
+ getNextNode(path19, pathIndex) {
32160
+ return this.findStaticMatchingChild(path19, 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(path17, useSemicolonDelimiter) {
32517
- if (path17.length >= MIN_NATIVE_SCAN_LENGTH) {
32518
- return safeDecodeURINativeScan(path17, useSemicolonDelimiter);
32516
+ function safeDecodeURI(path19, useSemicolonDelimiter) {
32517
+ if (path19.length >= MIN_NATIVE_SCAN_LENGTH) {
32518
+ return safeDecodeURINativeScan(path19, useSemicolonDelimiter);
32519
32519
  }
32520
- return safeDecodeURICharScan(path17, useSemicolonDelimiter, 1);
32520
+ return safeDecodeURICharScan(path19, useSemicolonDelimiter, 1);
32521
32521
  }
32522
- function safeDecodeURINativeScan(path17, useSemicolonDelimiter) {
32523
- const percentIndex = path17.indexOf("%", 1);
32524
- let delimIndex = path17.indexOf("?", 1);
32525
- const hashIndex = path17.indexOf("#", 1);
32522
+ function safeDecodeURINativeScan(path19, useSemicolonDelimiter) {
32523
+ const percentIndex = path19.indexOf("%", 1);
32524
+ let delimIndex = path19.indexOf("?", 1);
32525
+ const hashIndex = path19.indexOf("#", 1);
32526
32526
  if (hashIndex !== -1 && (delimIndex === -1 || hashIndex < delimIndex)) {
32527
32527
  delimIndex = hashIndex;
32528
32528
  }
32529
32529
  if (useSemicolonDelimiter) {
32530
- const semicolonIndex = path17.indexOf(";", 1);
32530
+ const semicolonIndex = path19.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: path17, querystring: "", shouldDecodeParam: false };
32537
+ return { path: path19, querystring: "", shouldDecodeParam: false };
32538
32538
  }
32539
32539
  return {
32540
- path: path17.slice(0, delimIndex),
32541
- querystring: path17.slice(delimIndex + 1),
32540
+ path: path19.slice(0, delimIndex),
32541
+ querystring: path19.slice(delimIndex + 1),
32542
32542
  shouldDecodeParam: false
32543
32543
  };
32544
32544
  }
32545
- return safeDecodeURIPercentScan(path17, useSemicolonDelimiter, percentIndex);
32545
+ return safeDecodeURIPercentScan(path19, useSemicolonDelimiter, percentIndex);
32546
32546
  }
32547
- function safeDecodeURICharScan(path17, useSemicolonDelimiter, startIndex) {
32548
- for (let i = startIndex; i < path17.length; i++) {
32549
- const charCode = path17.charCodeAt(i);
32547
+ function safeDecodeURICharScan(path19, useSemicolonDelimiter, startIndex) {
32548
+ for (let i = startIndex; i < path19.length; i++) {
32549
+ const charCode = path19.charCodeAt(i);
32550
32550
  if (charCode === 37) {
32551
- return safeDecodeURIPercentScan(path17, useSemicolonDelimiter, i);
32551
+ return safeDecodeURIPercentScan(path19, useSemicolonDelimiter, i);
32552
32552
  } else if (charCode === 63 || charCode === 35 || charCode === 59 && useSemicolonDelimiter) {
32553
32553
  return {
32554
- path: path17.slice(0, i),
32555
- querystring: path17.slice(i + 1),
32554
+ path: path19.slice(0, i),
32555
+ querystring: path19.slice(i + 1),
32556
32556
  shouldDecodeParam: false
32557
32557
  };
32558
32558
  }
32559
32559
  }
32560
- return { path: path17, querystring: "", shouldDecodeParam: false };
32560
+ return { path: path19, querystring: "", shouldDecodeParam: false };
32561
32561
  }
32562
- function reencodePercentChar(path17, index) {
32563
- return path17.slice(0, index + 1) + "25" + path17.slice(index + 1);
32562
+ function reencodePercentChar(path19, index) {
32563
+ return path19.slice(0, index + 1) + "25" + path19.slice(index + 1);
32564
32564
  }
32565
- function safeDecodeURIPercentScan(path17, useSemicolonDelimiter, startIndex) {
32565
+ function safeDecodeURIPercentScan(path19, useSemicolonDelimiter, startIndex) {
32566
32566
  let shouldDecode = false;
32567
32567
  let shouldDecodeParam = false;
32568
32568
  let querystring = "";
32569
- for (let i = startIndex; i < path17.length; i++) {
32570
- const charCode = path17.charCodeAt(i);
32569
+ for (let i = startIndex; i < path19.length; i++) {
32570
+ const charCode = path19.charCodeAt(i);
32571
32571
  if (charCode === 37) {
32572
- const componentCharCode = decodeComponentCharCode(path17.charCodeAt(i + 1), path17.charCodeAt(i + 2));
32572
+ const componentCharCode = decodeComponentCharCode(path19.charCodeAt(i + 1), path19.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
- path17 = reencodePercentChar(path17, i);
32579
+ path19 = reencodePercentChar(path19, 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 = path17.slice(i + 1);
32586
- path17 = path17.slice(0, i);
32585
+ querystring = path19.slice(i + 1);
32586
+ path19 = path19.slice(0, i);
32587
32587
  break;
32588
32588
  }
32589
32589
  }
32590
- const decodedPath = shouldDecode ? decodeURI(path17) : path17;
32590
+ const decodedPath = shouldDecode ? decodeURI(path19) : path19;
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, path17, opts, handler, store) {
32685
+ Router.prototype.on = function on(method, path19, 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 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 `*`");
32693
+ assert2(typeof path19 === "string", "Path should be a string");
32694
+ assert2(path19.length > 0, "The path could not be empty");
32695
+ assert2(path19[0] === "/" || path19[0] === "*", "The first character of a path should be `/` or `*`");
32696
32696
  assert2(typeof handler === "function", "Handler should be a function");
32697
- const optionalParamMatch = path17.match(OPTIONAL_PARAM_REGEXP);
32697
+ const optionalParamMatch = path19.match(OPTIONAL_PARAM_REGEXP);
32698
32698
  if (optionalParamMatch) {
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") || "/";
32699
+ assert2(path19.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32700
+ const pathFull = path19.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32701
+ const pathOptional = path19.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 = path17;
32706
+ const route = path19;
32707
32707
  if (this.ignoreDuplicateSlashes) {
32708
- path17 = removeDuplicateSlashes(path17);
32708
+ path19 = removeDuplicateSlashes(path19);
32709
32709
  }
32710
32710
  if (this.ignoreTrailingSlash) {
32711
- path17 = trimLastSlash(path17);
32711
+ path19 = trimLastSlash(path19);
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, path17, opts, handler, store, route);
32717
+ this._on(method2, path19, opts, handler, store, route);
32718
32718
  }
32719
32719
  };
32720
- Router.prototype._on = function _on(method, path17, opts, handler, store) {
32720
+ Router.prototype._on = function _on(method, path19, 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 = path17;
32733
+ let pattern = path19;
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: path17, pattern, params, opts, handler, store };
32841
+ const route = { method, path: path19, 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, path17, constraints) {
32846
- const route = this.findRoute(method, path17, constraints);
32845
+ Router.prototype.hasRoute = function hasRoute(method, path19, constraints) {
32846
+ const route = this.findRoute(method, path19, constraints);
32847
32847
  return route !== null;
32848
32848
  };
32849
- Router.prototype.findRoute = function findNode(method, path17, constraints = {}) {
32849
+ Router.prototype.findRoute = function findNode(method, path19, constraints = {}) {
32850
32850
  if (this.trees[method] === void 0) {
32851
32851
  return null;
32852
32852
  }
32853
- let pattern = path17;
32853
+ let pattern = path19;
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, 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 `*`");
32974
+ Router.prototype.off = function off(method, path19, constraints) {
32975
+ assert2(typeof path19 === "string", "Path should be a string");
32976
+ assert2(path19.length > 0, "The path could not be empty");
32977
+ assert2(path19[0] === "/" || path19[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 = path17.match(OPTIONAL_PARAM_REGEXP);
32982
+ const optionalParamMatch = path19.match(OPTIONAL_PARAM_REGEXP);
32983
32983
  if (optionalParamMatch) {
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") || "/";
32984
+ assert2(path19.length === optionalParamMatch.index + optionalParamMatch[0].length, "Optional Parameter needs to be the last parameter of the path");
32985
+ const pathFull = path19.replace(OPTIONAL_PARAM_REGEXP, "$1$2");
32986
+ const pathOptional = path19.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
- path17 = removeDuplicateSlashes(path17);
32992
+ path19 = removeDuplicateSlashes(path19);
32993
32993
  }
32994
32994
  if (this.ignoreTrailingSlash) {
32995
- path17 = trimLastSlash(path17);
32995
+ path19 = trimLastSlash(path19);
32996
32996
  }
32997
32997
  const methods = Array.isArray(method) ? method : [method];
32998
32998
  for (const method2 of methods) {
32999
- this._off(method2, path17, constraints);
32999
+ this._off(method2, path19, constraints);
33000
33000
  }
33001
33001
  };
33002
- Router.prototype._off = function _off(method, path17, constraints) {
33002
+ Router.prototype._off = function _off(method, path19, 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 || path17 !== route.path;
33006
+ return method !== route.method || path19 !== 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, path17, derivedConstraints) {
33043
+ Router.prototype.find = function find(method, path19, derivedConstraints) {
33044
33044
  let currentNode = method === "GET" ? this._treeGET : this.trees[method];
33045
33045
  if (currentNode == null) return null;
33046
- if (path17.charCodeAt(0) !== 47) {
33047
- path17 = path17.replace(FULL_PATH_REGEXP, "/");
33046
+ if (path19.charCodeAt(0) !== 47) {
33047
+ path19 = path19.replace(FULL_PATH_REGEXP, "/");
33048
33048
  }
33049
33049
  if (this.ignoreDuplicateSlashes) {
33050
- path17 = removeDuplicateSlashes(path17);
33050
+ path19 = removeDuplicateSlashes(path19);
33051
33051
  }
33052
33052
  let sanitizedUrl;
33053
33053
  let querystring2;
33054
33054
  let shouldDecodeParam;
33055
33055
  try {
33056
- sanitizedUrl = path17.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path17, this.useSemicolonDelimiter) : safeDecodeURICharScan(path17, this.useSemicolonDelimiter, 1);
33057
- path17 = sanitizedUrl.path;
33056
+ sanitizedUrl = path19.length >= MIN_NATIVE_SCAN_LENGTH ? safeDecodeURINativeScan(path19, this.useSemicolonDelimiter) : safeDecodeURICharScan(path19, this.useSemicolonDelimiter, 1);
33057
+ path19 = sanitizedUrl.path;
33058
33058
  querystring2 = sanitizedUrl.querystring;
33059
33059
  shouldDecodeParam = sanitizedUrl.shouldDecodeParam;
33060
33060
  } catch (error51) {
33061
- return this._onBadUrl(path17);
33061
+ return this._onBadUrl(path19);
33062
33062
  }
33063
33063
  if (this.ignoreTrailingSlash) {
33064
- path17 = trimLastSlash(path17);
33064
+ path19 = trimLastSlash(path19);
33065
33065
  }
33066
- const originPath = path17;
33066
+ const originPath = path19;
33067
33067
  if (this.caseSensitive === false) {
33068
- path17 = path17.toLowerCase();
33068
+ path19 = path19.toLowerCase();
33069
33069
  }
33070
33070
  const maxParamLength = this.maxParamLength;
33071
33071
  let pathIndex = currentNode.prefix.length;
33072
33072
  const params = [];
33073
- const pathLen = path17.length;
33073
+ const pathLen = path19.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(path17, pathIndex, brothersNodesStack, params.length);
33088
+ let node = currentNode.getNextNode(path19, 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: path17, opts, handler, store } = route;
33190
- this._on(method, path17, opts, handler, store);
33189
+ const { method, path: path19, opts, handler, store } = route;
33190
+ this._on(method, path19, 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(path17) {
33201
+ Router.prototype._onBadUrl = function(path19) {
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(path17, req, res),
33207
+ handler: (req, res, ctx) => onBadUrl(path19, req, res),
33208
33208
  params: {},
33209
33209
  store: null
33210
33210
  };
33211
33211
  };
33212
- Router.prototype._onMaxParamLength = function(path17) {
33212
+ Router.prototype._onMaxParamLength = function(path19) {
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(path17, req, res),
33218
+ handler: (req, res, ctx) => onMaxParamLength(path19, 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(path17, handler, store) {
33251
- return this.on(m, path17, handler, store);
33250
+ Router.prototype[methodName] = function(path19, handler, store) {
33251
+ return this.on(m, path19, handler, store);
33252
33252
  };
33253
33253
  }
33254
- Router.prototype.all = function(path17, handler, store) {
33255
- this.on(httpMethods, path17, handler, store);
33254
+ Router.prototype.all = function(path19, handler, store) {
33255
+ this.on(httpMethods, path19, 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(path17) {
33271
- return path17.indexOf("//") !== -1 ? path17.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path17;
33270
+ function removeDuplicateSlashes(path19) {
33271
+ return path19.indexOf("//") !== -1 ? path19.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, "/") : path19;
33272
33272
  }
33273
- function trimLastSlash(path17) {
33274
- if (path17.length > 1 && path17.charCodeAt(path17.length - 1) === 47) {
33275
- return path17.slice(0, -1);
33273
+ function trimLastSlash(path19) {
33274
+ if (path19.length > 1 && path19.charCodeAt(path19.length - 1) === 47) {
33275
+ return path19.slice(0, -1);
33276
33276
  }
33277
- return path17;
33277
+ return path19;
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(path17, idx) {
33288
+ function getClosingParenthensePosition(path19, idx) {
33289
33289
  let parentheses = 1;
33290
- while (idx < path17.length) {
33290
+ while (idx < path19.length) {
33291
33291
  idx++;
33292
- if (path17.charCodeAt(idx) === 92) {
33292
+ if (path19.charCodeAt(idx) === 92) {
33293
33293
  idx++;
33294
33294
  continue;
33295
33295
  }
33296
- if (path17.charCodeAt(idx) === 41) {
33296
+ if (path19.charCodeAt(idx) === 41) {
33297
33297
  parentheses--;
33298
- } else if (path17.charCodeAt(idx) === 40) {
33298
+ } else if (path19.charCodeAt(idx) === 40) {
33299
33299
  parentheses++;
33300
33300
  }
33301
33301
  if (!parentheses) return idx;
33302
33302
  }
33303
- throw new TypeError('Invalid regexp expression in "' + path17 + '"');
33303
+ throw new TypeError('Invalid regexp expression in "' + path19 + '"');
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 path17 = opts.url || opts.path || "";
33536
+ const path19 = opts.url || opts.path || "";
33537
33537
  if (!opts.handler) {
33538
- throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path17);
33538
+ throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path19);
33539
33539
  }
33540
33540
  if (opts.errorHandler !== void 0 && typeof opts.errorHandler !== "function") {
33541
- throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path17);
33541
+ throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path19);
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], path17, opts.schema);
33551
+ validateSchemaBodyOption.call(this, opts.method[i], path19, 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, path17, opts.schema);
33557
+ validateSchemaBodyOption.call(this, opts.method, path19, 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 (path17 === "/" && prefix.length > 0 && opts.method !== "HEAD") {
33563
+ if (path19 === "/" && prefix.length > 0 && opts.method !== "HEAD") {
33564
33564
  switch (opts.prefixTrailingSlash) {
33565
33565
  case "slash":
33566
- addNewRoute.call(this, { path: path17, isFastify });
33566
+ addNewRoute.call(this, { path: path19, 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: path17, prefixing: true, isFastify });
33575
+ addNewRoute.call(this, { path: path19, prefixing: true, isFastify });
33576
33576
  }
33577
33577
  }
33578
- } else if (path17[0] === "/" && prefix.endsWith("/")) {
33579
- addNewRoute.call(this, { path: path17.slice(1), isFastify });
33578
+ } else if (path19[0] === "/" && prefix.endsWith("/")) {
33579
+ addNewRoute.call(this, { path: path19.slice(1), isFastify });
33580
33580
  } else {
33581
- addNewRoute.call(this, { path: path17, isFastify });
33581
+ addNewRoute.call(this, { path: path19, isFastify });
33582
33582
  }
33583
33583
  return this;
33584
- function addNewRoute({ path: path18, prefixing = false, isFastify: isFastify2 = false }) {
33585
- const url2 = prefix + path18;
33584
+ function addNewRoute({ path: path20, prefixing = false, isFastify: isFastify2 = false }) {
33585
+ const url2 = prefix + path20;
33586
33586
  opts.url = url2;
33587
33587
  opts.path = url2;
33588
- opts.routePath = path18;
33588
+ opts.routePath = path20;
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: path18, options: { ...headOpts, onSend: onSendHandlers }, isFastify: true });
33720
+ prepareRoute.call(this, { method: "HEAD", url: path20, 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, path17, schema) {
33844
+ function validateSchemaBodyOption(method, path19, schema) {
33845
33845
  if (this[kSupportedHTTPMethods].bodyless.has(method) && schema?.body) {
33846
- throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path17);
33846
+ throw new FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED(method, path19);
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, path17, logger) {
33861
+ function validateLogLevelOption(logLevel, method, path19, 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, path17, logLevel);
33865
+ throw new FST_ERR_ROUTE_LOG_LEVEL_INVALID(method, path19, 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(path17, req, res) {
33954
+ return function onRouteEvent(path19, 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);
@@ -36622,19 +36622,19 @@ var require_fastify = __commonJS({
36622
36622
  }
36623
36623
  fourOhFour.router.lookup(req, res);
36624
36624
  }
36625
- function onBadUrl(path17, req, res) {
36625
+ function onBadUrl(path19, 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(path17), request, reply);
36632
+ return options.frameworkErrors(new FST_ERR_BAD_URL(path19), request, reply);
36633
36633
  }
36634
36634
  const body = JSON.stringify({
36635
36635
  error: "Bad Request",
36636
36636
  code: "FST_ERR_BAD_URL",
36637
- message: `'${path17}' is not a valid url component`,
36637
+ message: `'${path19}' 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(path17, req, res) {
36646
+ function onMaxParamLength(path19, 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(path17), request, reply);
36653
+ return options.frameworkErrors(new FST_ERR_MAX_PARAM_LENGTH(path19), 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: `'${path17}' is exceeding the max param length`,
36658
+ message: `'${path19}' is exceeding the max param length`,
36659
36659
  statusCode: 414
36660
36660
  });
36661
36661
  res.writeHead(414, {
@@ -41001,13 +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
+ import path18 from "node:path";
41005
41005
 
41006
41006
  // src/db/index.ts
41007
41007
  import Database from "better-sqlite3";
41008
41008
  var db;
41009
- function initDb(path17 = "data.db") {
41010
- db = new Database(path17);
41009
+ function initDb(path19 = "data.db") {
41010
+ db = new Database(path19);
41011
41011
  db.pragma("journal_mode = WAL");
41012
41012
  db.pragma("foreign_keys = ON");
41013
41013
  createTables(db);
@@ -41139,6 +41139,15 @@ function createTables(database) {
41139
41139
  updated_at TEXT NOT NULL
41140
41140
  );
41141
41141
 
41142
+ -- Codex threads the pane started or forked (main threads, rewind and
41143
+ -- branch forks, discussion threads), kept after the session or thread that
41144
+ -- used them is gone: the Codex import never lists them as outside work.
41145
+ CREATE TABLE IF NOT EXISTS codex_threads (
41146
+ thread_id TEXT PRIMARY KEY,
41147
+ session_id TEXT,
41148
+ created_at TEXT NOT NULL
41149
+ );
41150
+
41142
41151
  CREATE INDEX IF NOT EXISTS idx_turns_session_id ON turns(session_id);
41143
41152
  CREATE INDEX IF NOT EXISTS idx_items_turn_id ON items(turn_id);
41144
41153
  CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
@@ -41690,7 +41699,7 @@ function handleTerminalUpgrade(request, socket, head) {
41690
41699
  }
41691
41700
 
41692
41701
  // src/routes/sessions.ts
41693
- import path2 from "node:path";
41702
+ import path3 from "node:path";
41694
41703
 
41695
41704
  // node_modules/uuid/dist/esm/stringify.js
41696
41705
  var byteToHex = [];
@@ -41982,6 +41991,45 @@ function startTurn(db2, session, { prompt, attachments, originAppId }) {
41982
41991
  return parsedTurn;
41983
41992
  }
41984
41993
 
41994
+ // src/providers/attachment-files.ts
41995
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
41996
+ import os2 from "node:os";
41997
+ import path2 from "node:path";
41998
+ function sessionDir(sessionId) {
41999
+ let base = path2.join(os2.tmpdir(), "agentpane");
42000
+ try {
42001
+ const file2 = getDb().name;
42002
+ if (file2 && file2 !== ":memory:") base = path2.dirname(path2.resolve(file2));
42003
+ } catch {
42004
+ }
42005
+ return path2.join(base, "attachments", sessionId.replace(/[^\w.-]/g, "_"));
42006
+ }
42007
+ function safeName(name) {
42008
+ const base = path2.basename(name || "attachment").replace(/[^\w.\- ()]/g, "_").trim();
42009
+ return base && base !== "." && base !== ".." ? base : "attachment";
42010
+ }
42011
+ function freeName(name, taken) {
42012
+ const ext = path2.extname(name);
42013
+ let free = name;
42014
+ for (let n = 2; taken.has(free.toLowerCase()); n++) free = `${name.slice(0, name.length - ext.length)}-${n}${ext}`;
42015
+ taken.add(free.toLowerCase());
42016
+ return free;
42017
+ }
42018
+ function saveAttachmentFile(sessionId, turnId, name, base643, taken = /* @__PURE__ */ new Set()) {
42019
+ const dir = path2.join(sessionDir(sessionId), turnId.replace(/[^\w.-]/g, "_"));
42020
+ mkdirSync(dir, { recursive: true });
42021
+ const file2 = path2.join(dir, freeName(safeName(name), taken));
42022
+ writeFileSync(file2, Buffer.from(base643, "base64"));
42023
+ return file2;
42024
+ }
42025
+ function removeAttachmentFiles(sessionId) {
42026
+ try {
42027
+ rmSync(sessionDir(sessionId), { recursive: true, force: true });
42028
+ } catch (err) {
42029
+ console.warn(`[attachments] could not remove the files of session ${sessionId}: ${err.message}`);
42030
+ }
42031
+ }
42032
+
41985
42033
  // src/routes/sessions.ts
41986
42034
  async function registerSessionRoutes(fastify) {
41987
42035
  fastify.get("/api/sessions", async () => {
@@ -42078,6 +42126,7 @@ async function registerSessionRoutes(fastify) {
42078
42126
  db2.prepare("DELETE FROM items WHERE turn_id IN (SELECT id FROM turns WHERE session_id = ?)").run(id);
42079
42127
  db2.prepare("DELETE FROM turns WHERE session_id = ?").run(id);
42080
42128
  db2.prepare("DELETE FROM sessions WHERE id = ?").run(id);
42129
+ removeAttachmentFiles(id);
42081
42130
  return { success: true };
42082
42131
  });
42083
42132
  fastify.patch("/api/sessions/:id", {
@@ -42143,8 +42192,8 @@ async function registerSessionRoutes(fastify) {
42143
42192
  }
42144
42193
  let workspaceChanged = false;
42145
42194
  if (cwd !== void 0) {
42146
- const oldAbs = existing.cwd ? path2.resolve(existing.cwd) : null;
42147
- const newAbs = cwd ? path2.resolve(cwd) : null;
42195
+ const oldAbs = existing.cwd ? path3.resolve(existing.cwd) : null;
42196
+ const newAbs = cwd ? path3.resolve(cwd) : null;
42148
42197
  workspaceChanged = oldAbs !== newAbs;
42149
42198
  if (workspaceChanged && existing.is_running) {
42150
42199
  return reply.code(409).send({ error: "Cannot change workspace while a turn is running" });
@@ -42592,7 +42641,7 @@ function recoverInterruptedTurns(db2, opts) {
42592
42641
  WHERE i.status = 'in_progress'`
42593
42642
  ).all();
42594
42643
  const orphaned = open.filter((i) => !skip.entries.has(runtimeEntryKey(i.session_id, i.thread_id)));
42595
- const stopTask2 = db2.prepare(
42644
+ const stopTask3 = db2.prepare(
42596
42645
  `UPDATE items SET data = json_set(COALESCE(data, '{}'), '$.status', 'stopped')
42597
42646
  WHERE id = ? AND json_valid(COALESCE(data, '{}'))`
42598
42647
  );
@@ -42600,7 +42649,7 @@ function recoverInterruptedTurns(db2, opts) {
42600
42649
  const items = { changes: 0 };
42601
42650
  db2.transaction(() => {
42602
42651
  for (const item of orphaned) {
42603
- if (item.type === "background_task") stopTask2.run(item.id);
42652
+ if (item.type === "background_task") stopTask3.run(item.id);
42604
42653
  items.changes += failItem.run(now, item.id).changes;
42605
42654
  }
42606
42655
  })();
@@ -42970,6 +43019,28 @@ async function registerTurnRoutes(fastify) {
42970
43019
  markSessionTouched(db2, id);
42971
43020
  return { success: true };
42972
43021
  });
43022
+ fastify.post(
43023
+ "/api/sessions/:id/tasks/:taskId/stop",
43024
+ async (request, reply) => {
43025
+ const { id, taskId } = request.params;
43026
+ const db2 = getDb();
43027
+ const session = db2.prepare("SELECT runtime_type FROM sessions WHERE id = ?").get(id);
43028
+ if (!session) {
43029
+ return reply.code(404).send({ error: "Session not found" });
43030
+ }
43031
+ const provider = getProvider(session.runtime_type);
43032
+ if (!provider.stopTask) {
43033
+ return reply.code(501).send({ error: `${session.runtime_type} sessions cannot stop background tasks` });
43034
+ }
43035
+ try {
43036
+ await provider.stopTask(id, taskId);
43037
+ } catch (err) {
43038
+ return reply.code(409).send({ error: err.message });
43039
+ }
43040
+ markSessionTouched(db2, id);
43041
+ return { success: true };
43042
+ }
43043
+ );
42973
43044
  fastify.post(
42974
43045
  "/api/sessions/:id/turns/:turnId/resume",
42975
43046
  async (request, reply) => {
@@ -43387,9 +43458,9 @@ async function browseFolder(input, opts = {}) {
43387
43458
  const atHome = dir === nodePath.resolve(home);
43388
43459
  const folders = await Promise.all(
43389
43460
  names.slice(0, limit).map(async (name) => {
43390
- const path17 = nodePath.join(dir, name);
43461
+ const path19 = nodePath.join(dir, name);
43391
43462
  const skipProbe = atHome && HOME_STANDARD_FOLDERS.has(name) || dir === "/Volumes";
43392
- return { name, path: path17, git: !skipProbe && await exists(nodePath.join(path17, ".git")) };
43463
+ return { name, path: path19, git: !skipProbe && await exists(nodePath.join(path19, ".git")) };
43393
43464
  })
43394
43465
  );
43395
43466
  const parent = nodePath.dirname(dir);
@@ -43427,11 +43498,11 @@ async function registerWorkspaceRoutes(fastify) {
43427
43498
  }
43428
43499
  }
43429
43500
  }, async (request, reply) => {
43430
- const { path: path17, label = null } = request.body || {};
43431
- if (!path17 || !path17.trim()) {
43501
+ const { path: path19, label = null } = request.body || {};
43502
+ if (!path19 || !path19.trim()) {
43432
43503
  return reply.code(400).send({ error: "Path is required" });
43433
43504
  }
43434
- const resolved = await resolveWorkspacePath(path17);
43505
+ const resolved = await resolveWorkspacePath(path19);
43435
43506
  if ("error" in resolved) {
43436
43507
  return reply.code(400).send({ error: resolved.error });
43437
43508
  }
@@ -43473,8 +43544,8 @@ async function registerWorkspaceRoutes(fastify) {
43473
43544
  "-e",
43474
43545
  'POSIX path of (choose folder with prompt "Select a workspace directory")'
43475
43546
  ]);
43476
- const path17 = stdout.trim().replace(/\/$/, "");
43477
- return { path: path17 };
43547
+ const path19 = stdout.trim().replace(/\/$/, "");
43548
+ return { path: path19 };
43478
43549
  } catch {
43479
43550
  return reply.code(204).send({ cancelled: true });
43480
43551
  }
@@ -43490,11 +43561,11 @@ async function registerWorkspaceRoutes(fastify) {
43490
43561
  }
43491
43562
  }
43492
43563
  }, async (request, reply) => {
43493
- const { path: path17 } = request.body || {};
43494
- if (!path17 || !path17.trim()) {
43564
+ const { path: path19 } = request.body || {};
43565
+ if (!path19 || !path19.trim()) {
43495
43566
  return reply.code(400).send({ error: "Path is required" });
43496
43567
  }
43497
- const trimmedPath = path17.trim();
43568
+ const trimmedPath = path19.trim();
43498
43569
  const db2 = getDb();
43499
43570
  const existing = db2.prepare("SELECT * FROM workspaces WHERE path = ?").get(trimmedPath);
43500
43571
  if (existing) {
@@ -44185,7 +44256,7 @@ async function registerFileRoutes(fastify) {
44185
44256
  }
44186
44257
 
44187
44258
  // src/routes/perf-log.ts
44188
- import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
44259
+ import { appendFileSync, mkdirSync as mkdirSync2, renameSync, statSync } from "node:fs";
44189
44260
  import { homedir as homedir2 } from "node:os";
44190
44261
  import { dirname, join } from "node:path";
44191
44262
  var MAX_BYTES = 5 * 1024 * 1024;
@@ -44228,17 +44299,17 @@ async function registerPerfLogRoutes(fastify) {
44228
44299
  if (entries.length === 0) {
44229
44300
  return reply.send({ written: 0 });
44230
44301
  }
44231
- const path17 = perfLogPath();
44302
+ const path19 = perfLogPath();
44232
44303
  try {
44233
- mkdirSync(dirname(path17), { recursive: true });
44304
+ mkdirSync2(dirname(path19), { recursive: true });
44234
44305
  try {
44235
- if (statSync(path17).size > MAX_BYTES) {
44236
- renameSync(path17, `${path17}.1`);
44306
+ if (statSync(path19).size > MAX_BYTES) {
44307
+ renameSync(path19, `${path19}.1`);
44237
44308
  }
44238
44309
  } catch {
44239
44310
  }
44240
44311
  const lines = entries.map((e) => `${new Date(e.t).toISOString()} [${oneLine(e.cat)}] ${oneLine(e.msg)}`).join("\n");
44241
- appendFileSync(path17, `${lines}
44312
+ appendFileSync(path19, `${lines}
44242
44313
  `, "utf-8");
44243
44314
  return reply.send({ written: entries.length });
44244
44315
  } catch (err) {
@@ -44314,24 +44385,24 @@ import { existsSync } from "node:fs";
44314
44385
  import http from "node:http";
44315
44386
  import net from "node:net";
44316
44387
  import crypto from "node:crypto";
44317
- import os2 from "node:os";
44318
- import path3 from "node:path";
44388
+ import os3 from "node:os";
44389
+ import path4 from "node:path";
44319
44390
  import { mkdir, readdir as readdir2, symlink, lstat, access, readFile, writeFile, unlink } from "node:fs/promises";
44320
- var VSCODE_WEB_DATA_DIR = path3.join(os2.homedir(), ".repoburg", "vscode-web");
44391
+ var VSCODE_WEB_DATA_DIR = path4.join(os3.homedir(), ".repoburg", "vscode-web");
44321
44392
  function resolveDesktopUserDir() {
44322
44393
  if (process.platform === "darwin") {
44323
- return path3.join(os2.homedir(), "Library", "Application Support", "Code", "User");
44394
+ return path4.join(os3.homedir(), "Library", "Application Support", "Code", "User");
44324
44395
  }
44325
44396
  if (process.platform === "win32" && process.env.APPDATA) {
44326
- return path3.join(process.env.APPDATA, "Code", "User");
44397
+ return path4.join(process.env.APPDATA, "Code", "User");
44327
44398
  }
44328
44399
  if (process.platform === "linux") {
44329
- return path3.join(os2.homedir(), ".config", "Code", "User");
44400
+ return path4.join(os3.homedir(), ".config", "Code", "User");
44330
44401
  }
44331
44402
  return null;
44332
44403
  }
44333
44404
  async function linkUnlessExists(src, dst) {
44334
- await mkdir(path3.dirname(dst), { recursive: true });
44405
+ await mkdir(path4.dirname(dst), { recursive: true });
44335
44406
  try {
44336
44407
  await lstat(dst);
44337
44408
  return false;
@@ -44346,19 +44417,19 @@ function fileRegistryUri(dir) {
44346
44417
  }
44347
44418
  async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44348
44419
  try {
44349
- const desktopExt = path3.join(os2.homedir(), ".vscode", "extensions");
44420
+ const desktopExt = path4.join(os3.homedir(), ".vscode", "extensions");
44350
44421
  let entries;
44351
44422
  try {
44352
44423
  entries = await readdir2(desktopExt, { withFileTypes: true });
44353
44424
  } catch {
44354
44425
  return;
44355
44426
  }
44356
- const serverExt = path3.join(dataDir, "extensions");
44427
+ const serverExt = path4.join(dataDir, "extensions");
44357
44428
  const linkedFolders = [];
44358
44429
  for (const entry of entries) {
44359
44430
  if (!entry.isDirectory()) continue;
44360
- const target = path3.join(serverExt, entry.name);
44361
- await linkUnlessExists(path3.join(desktopExt, entry.name), target);
44431
+ const target = path4.join(serverExt, entry.name);
44432
+ await linkUnlessExists(path4.join(desktopExt, entry.name), target);
44362
44433
  const st = await lstat(target).catch(() => null);
44363
44434
  if (st?.isSymbolicLink()) linkedFolders.push(entry.name);
44364
44435
  }
@@ -44366,15 +44437,15 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44366
44437
  await pruneObsolete(serverExt, linkedFolders);
44367
44438
  const desktopUser = resolveDesktopUserDir();
44368
44439
  if (!desktopUser) return;
44369
- const serverUser = path3.join(dataDir, "data", "User");
44440
+ const serverUser = path4.join(dataDir, "data", "User");
44370
44441
  for (const item of ["settings.json", "keybindings.json", "snippets"]) {
44371
- const src = path3.join(desktopUser, item);
44442
+ const src = path4.join(desktopUser, item);
44372
44443
  try {
44373
44444
  await access(src);
44374
44445
  } catch {
44375
44446
  continue;
44376
44447
  }
44377
- await linkUnlessExists(src, path3.join(serverUser, item));
44448
+ await linkUnlessExists(src, path4.join(serverUser, item));
44378
44449
  }
44379
44450
  } catch {
44380
44451
  }
@@ -44382,13 +44453,13 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44382
44453
  async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
44383
44454
  let desktopEntries = [];
44384
44455
  try {
44385
- desktopEntries = JSON.parse(await readFile(path3.join(desktopExt, "extensions.json"), "utf8"));
44456
+ desktopEntries = JSON.parse(await readFile(path4.join(desktopExt, "extensions.json"), "utf8"));
44386
44457
  } catch {
44387
44458
  return;
44388
44459
  }
44389
44460
  const linked = new Set(linkedFolders);
44390
44461
  const toAdd = desktopEntries.filter((e) => e.identifier?.id && linked.has(e.relativeLocation));
44391
- const serverRegistryPath = path3.join(serverExt, "extensions.json");
44462
+ const serverRegistryPath = path4.join(serverExt, "extensions.json");
44392
44463
  let serverEntries = [];
44393
44464
  try {
44394
44465
  serverEntries = JSON.parse(await readFile(serverRegistryPath, "utf8"));
@@ -44398,13 +44469,13 @@ async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
44398
44469
  const additions = toAdd.filter((e) => !known.has(`${e.identifier.id.toLowerCase()}@${e.version}`));
44399
44470
  if (additions.length === 0) return;
44400
44471
  for (const entry of additions) {
44401
- const dir = path3.join(serverExt, entry.relativeLocation);
44472
+ const dir = path4.join(serverExt, entry.relativeLocation);
44402
44473
  serverEntries.push({ ...entry, location: fileRegistryUri(dir) });
44403
44474
  }
44404
44475
  await writeFile(serverRegistryPath, JSON.stringify(serverEntries));
44405
44476
  }
44406
44477
  async function pruneObsolete(serverExt, linkedFolders) {
44407
- const obsoletePath = path3.join(serverExt, ".obsolete");
44478
+ const obsoletePath = path4.join(serverExt, ".obsolete");
44408
44479
  let obsolete;
44409
44480
  try {
44410
44481
  obsolete = JSON.parse(await readFile(obsoletePath, "utf8"));
@@ -44863,16 +44934,16 @@ function proxyHandler(request, reply) {
44863
44934
 
44864
44935
  // src/routes/apps.ts
44865
44936
  import fs6 from "node:fs";
44866
- import path9 from "node:path";
44937
+ import path10 from "node:path";
44867
44938
 
44868
44939
  // src/apps/instances.ts
44869
44940
  import fs3 from "node:fs";
44870
- import path5 from "node:path";
44941
+ import path6 from "node:path";
44871
44942
 
44872
44943
  // src/apps/apps-registry.ts
44873
44944
  import fs2 from "node:fs";
44874
- import path4 from "node:path";
44875
- import os3 from "node:os";
44945
+ import path5 from "node:path";
44946
+ import os4 from "node:os";
44876
44947
  import { fileURLToPath } from "node:url";
44877
44948
 
44878
44949
  // node_modules/lucide-static/icon-nodes.json
@@ -99096,10 +99167,10 @@ function setAppsRootOverride(root) {
99096
99167
  rootOverride = root;
99097
99168
  }
99098
99169
  function appsRoot() {
99099
- return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path4.join(os3.homedir(), ".repoburg", "agent-pane", "apps");
99170
+ return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path5.join(os4.homedir(), ".repoburg", "agent-pane", "apps");
99100
99171
  }
99101
99172
  function appDir(id) {
99102
- return path4.join(appsRoot(), id);
99173
+ return path5.join(appsRoot(), id);
99103
99174
  }
99104
99175
  var examplesRootOverride = null;
99105
99176
  function setExamplesRootOverride(root) {
@@ -99108,16 +99179,16 @@ function setExamplesRootOverride(root) {
99108
99179
  function examplesRoot() {
99109
99180
  if (examplesRootOverride) return examplesRootOverride;
99110
99181
  if (process.env.AGENT_PANE_EXAMPLES_DIR) return process.env.AGENT_PANE_EXAMPLES_DIR;
99111
- const here = path4.dirname(fileURLToPath(import.meta.url));
99112
- for (const candidate of [path4.resolve(here, "../../examples"), path4.resolve(here, "../../../examples")]) {
99182
+ const here = path5.dirname(fileURLToPath(import.meta.url));
99183
+ for (const candidate of [path5.resolve(here, "../../examples"), path5.resolve(here, "../../../examples")]) {
99113
99184
  if (fs2.existsSync(candidate)) return candidate;
99114
99185
  }
99115
99186
  return null;
99116
99187
  }
99117
99188
  function isInAppFolder(cwd) {
99118
99189
  if (!cwd) return false;
99119
- const rel = path4.relative(path4.resolve(appsRoot()), path4.resolve(cwd));
99120
- return rel !== "" && !path4.isAbsolute(rel) && rel.split(path4.sep)[0] !== "..";
99190
+ const rel = path5.relative(path5.resolve(appsRoot()), path5.resolve(cwd));
99191
+ return rel !== "" && !path5.isAbsolute(rel) && rel.split(path5.sep)[0] !== "..";
99121
99192
  }
99122
99193
  function appsConventions() {
99123
99194
  return APPS_MD_SKELETON;
@@ -99126,7 +99197,7 @@ function ensureAppsRoot() {
99126
99197
  const root = appsRoot();
99127
99198
  fs2.mkdirSync(root, { recursive: true });
99128
99199
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
99129
- const file2 = path4.join(root, name);
99200
+ const file2 = path5.join(root, name);
99130
99201
  try {
99131
99202
  if (fs2.existsSync(file2) && fs2.readFileSync(file2, "utf-8") === APPS_MD_FILE) continue;
99132
99203
  fs2.writeFileSync(file2, APPS_MD_FILE);
@@ -99350,7 +99421,7 @@ folder's own CLAUDE.md / AGENTS.md. -->
99350
99421
  ${APPS_MD_SKELETON}`;
99351
99422
  function readManifestIn(dir) {
99352
99423
  try {
99353
- const raw = fs2.readFileSync(path4.join(dir, "manifest.json"), "utf-8");
99424
+ const raw = fs2.readFileSync(path5.join(dir, "manifest.json"), "utf-8");
99354
99425
  const parsed = JSON.parse(raw);
99355
99426
  if (!parsed || typeof parsed.title !== "string") return null;
99356
99427
  return {
@@ -99369,7 +99440,7 @@ function readManifest(id) {
99369
99440
  }
99370
99441
  function readAppFile(id, name) {
99371
99442
  try {
99372
- return fs2.readFileSync(path4.join(appDir(id), name), "utf-8");
99443
+ return fs2.readFileSync(path5.join(appDir(id), name), "utf-8");
99373
99444
  } catch {
99374
99445
  return "";
99375
99446
  }
@@ -99402,11 +99473,11 @@ function startAppsWatch(onAppChange) {
99402
99473
  try {
99403
99474
  watcher = fs2.watch(root, { recursive: true }, (_event, filename) => {
99404
99475
  const rel = String(filename ?? "");
99405
- const segs = rel.split(path4.sep);
99476
+ const segs = rel.split(path5.sep);
99406
99477
  const appId = segs[0];
99407
99478
  const file2 = segs[segs.length - 1];
99408
- if (!appId || appId === path4.basename(root) || !APP_ID_RE.test(appId) || file2 === "state.json") return;
99409
- if (segs.length === 1 && isRegularFile(path4.join(root, appId))) return;
99479
+ if (!appId || appId === path5.basename(root) || !APP_ID_RE.test(appId) || file2 === "state.json") return;
99480
+ if (segs.length === 1 && isRegularFile(path5.join(root, appId))) return;
99410
99481
  const timer2 = pendingChanges.get(appId);
99411
99482
  if (timer2) clearTimeout(timer2);
99412
99483
  pendingChanges.set(
@@ -99477,7 +99548,7 @@ function getInstanceState(appId, workspace = "") {
99477
99548
  const stored = readRow(appId, workspace);
99478
99549
  if (stored) return stored;
99479
99550
  if (workspace === "") {
99480
- const legacyFile = path5.join(appDir(appId), "state.json");
99551
+ const legacyFile = path6.join(appDir(appId), "state.json");
99481
99552
  if (fs3.existsSync(legacyFile)) {
99482
99553
  const legacy = readState(appId);
99483
99554
  const imported = { pinned: legacy.pinned, data: legacy.data, version: 1 };
@@ -99510,9 +99581,9 @@ function resolveToolWorkspace(workspace) {
99510
99581
  const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99511
99582
  const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99512
99583
  if (active.includes(workspace)) return workspace;
99513
- const cwd = path5.isAbsolute(workspace) ? path5.resolve(workspace) : "";
99584
+ const cwd = path6.isAbsolute(workspace) ? path6.resolve(workspace) : "";
99514
99585
  if (isInAppFolder(cwd)) return "";
99515
- const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path5.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99586
+ const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path6.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99516
99587
  if (covering && !covering.deleted) return covering.path;
99517
99588
  throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99518
99589
  }
@@ -99524,7 +99595,7 @@ function deleteAppInstances(appId) {
99524
99595
  import fs5 from "node:fs";
99525
99596
 
99526
99597
  // src/apps/app-sessions.ts
99527
- import path7 from "node:path";
99598
+ import path8 from "node:path";
99528
99599
 
99529
99600
  // src/sidecar/transcript-locator.ts
99530
99601
  import { existsSync as existsSync2, readdirSync } from "node:fs";
@@ -99609,8 +99680,8 @@ function locateTranscriptCached(session) {
99609
99680
  // src/apps/app-files.ts
99610
99681
  import crypto2 from "node:crypto";
99611
99682
  import fs4 from "node:fs";
99612
- import os4 from "node:os";
99613
- import path6 from "node:path";
99683
+ import os5 from "node:os";
99684
+ import path7 from "node:path";
99614
99685
  var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
99615
99686
  var APP_FILE_TYPES = {
99616
99687
  "image/png": "png",
@@ -99635,11 +99706,11 @@ function setAppFilesRootOverride(root) {
99635
99706
  rootOverride2 = root;
99636
99707
  }
99637
99708
  function appFilesRoot() {
99638
- return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path6.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
99709
+ return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path7.join(os5.homedir(), ".repoburg", "agent-pane", "app-files");
99639
99710
  }
99640
99711
  function appFilesDir(appId) {
99641
99712
  if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
99642
- return path6.join(appFilesRoot(), appId);
99713
+ return path7.join(appFilesRoot(), appId);
99643
99714
  }
99644
99715
  function appFileUrl(appId, fileId) {
99645
99716
  return `/api/apps/${appId}/files/${fileId}`;
@@ -99700,7 +99771,7 @@ function saveAppFile(appId, upload) {
99700
99771
  const type = sniffImageType(bytes);
99701
99772
  if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
99702
99773
  const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
99703
- const file2 = path6.join(dir, fileId);
99774
+ const file2 = path7.join(dir, fileId);
99704
99775
  if (!fs4.existsSync(file2)) {
99705
99776
  fs4.mkdirSync(dir, { recursive: true });
99706
99777
  const tmp = `${file2}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
@@ -99732,7 +99803,7 @@ function getAppFile(appId, ref) {
99732
99803
  if (!APP_ID_RE.test(appId)) return null;
99733
99804
  const fileId = appFileRefId(appId, ref);
99734
99805
  if (!fileId) return null;
99735
- const file2 = path6.join(appFilesDir(appId), fileId);
99806
+ const file2 = path7.join(appFilesDir(appId), fileId);
99736
99807
  try {
99737
99808
  const stat2 = fs4.statSync(file2);
99738
99809
  if (!stat2.isFile()) return null;
@@ -99744,7 +99815,7 @@ function getAppFile(appId, ref) {
99744
99815
  function readAppFileData(appId, fileId) {
99745
99816
  if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
99746
99817
  try {
99747
- return { bytes: fs4.readFileSync(path6.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99818
+ return { bytes: fs4.readFileSync(path7.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99748
99819
  } catch {
99749
99820
  return null;
99750
99821
  }
@@ -99854,7 +99925,7 @@ function appSessionInfo(appId, sessionId) {
99854
99925
  function sessionVisibleTo(session, appId, workspace) {
99855
99926
  if (!workspace) return true;
99856
99927
  const cwd = session.cwd;
99857
- if (cwd && (cwd === workspace || cwd.startsWith(workspace.endsWith(path7.sep) ? workspace : workspace + path7.sep))) {
99928
+ if (cwd && (cwd === workspace || cwd.startsWith(workspace.endsWith(path8.sep) ? workspace : workspace + path8.sep))) {
99858
99929
  return true;
99859
99930
  }
99860
99931
  return session.origin_app_workspace === workspace && openedByApp(session, appId);
@@ -99949,7 +100020,7 @@ import vm2 from "node:vm";
99949
100020
 
99950
100021
  // src/apps/app-compile.ts
99951
100022
  import vm from "node:vm";
99952
- import path8 from "node:path";
100023
+ import path9 from "node:path";
99953
100024
  import ts from "typescript";
99954
100025
 
99955
100026
  // src/apps/app-lint.ts
@@ -100346,15 +100417,15 @@ function typeCheckModules(appId, modules) {
100346
100417
  };
100347
100418
  const host = ts.createCompilerHost(options);
100348
100419
  const origReadFile = host.readFile.bind(host);
100349
- host.readFile = (fname) => path8.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
100420
+ host.readFile = (fname) => path9.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
100350
100421
  host.writeFile = () => {
100351
100422
  };
100352
- const bridgePath = path8.join(dir, BRIDGE_DTS_FILE);
100353
- const rootNames = [...modules.map((m) => path8.join(dir, m.file)), bridgePath];
100423
+ const bridgePath = path9.join(dir, BRIDGE_DTS_FILE);
100424
+ const rootNames = [...modules.map((m) => path9.join(dir, m.file)), bridgePath];
100354
100425
  const program = ts.createProgram(rootNames, options, host);
100355
100426
  const out = [];
100356
100427
  for (const mod of modules) {
100357
- const sf = program.getSourceFile(path8.join(dir, mod.file));
100428
+ const sf = program.getSourceFile(path9.join(dir, mod.file));
100358
100429
  if (!sf) continue;
100359
100430
  out.push(
100360
100431
  ...[...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)].map((d) => tsDiagnosticToFile(mod.file, d)).filter((d) => d !== null)
@@ -100714,6 +100785,63 @@ function invalidateHeadlessRuntime(appId) {
100714
100785
  }
100715
100786
  }
100716
100787
 
100788
+ // src/providers/widget-spec.ts
100789
+ var WIDGET_TOOL_BASE_NAME = "show_widget";
100790
+ var WIDGET_CDN_ORIGINS = [
100791
+ "https://cdnjs.cloudflare.com",
100792
+ "https://cdn.jsdelivr.net",
100793
+ "https://unpkg.com",
100794
+ "https://esm.sh"
100795
+ ];
100796
+ var WIDGET_INSTRUCTIONS = "AgentPane shows the result of show_widget inline in the chat, as a live visual. Use it when the user asks for a chart, diagram or other visual, and on your own when a visual explains something clearly better than text: numbers to compare, an architecture or flow to follow, a concept to explore. Keep routine progress updates and plain answers as text.";
100797
+ var WIDGET_TOOL_DESCRIPTION = [
100798
+ "Show a visual inline in the chat: a chart, diagram, flow, timeline, comparison, interactive explainer or small UI mockup, drawn from the HTML/SVG you pass. The user sees it right away, so do not repeat its content in your reply.",
100799
+ "",
100800
+ "widget_code is an HTML fragment, not a document: no <!DOCTYPE>, <html>, <head> or <body>. Order it <style> first, then the markup, then <script> last. The markup renders while you write it; scripts run once, after the whole fragment has arrived, and DOMContentLoaded and load fire again for them.",
100801
+ "",
100802
+ `Where it renders: a sandboxed iframe as wide as the chat column (up to 720px, narrower on small screens, so lay out fluidly; give SVG a viewBox and width 100%). The frame grows to fit the content, so never size anything from the frame: no 100vh, and give canvas charts a fixed-height wrapper (Chart.js: <div style="position:relative;height:320px"><canvas></canvas></div>). The background is transparent over the chat. The widget is offline except for these CDNs, which may serve scripts, stylesheets, fonts and data files: ${WIDGET_CDN_ORIGINS.join(", ")} (e.g. Chart.js, D3, Mermaid). Embed your data; storage, cookies and form submission do not work. Links open in a new browser tab.`,
100803
+ "",
100804
+ "Style with the chat's CSS variables, not hard-coded colors, so the widget matches it: --color-text-primary, --color-text-secondary, --color-text-muted, --color-background-primary (cards), --color-background-secondary (subtle fills), --color-border, --color-accent, --font-sans, --font-mono, --radius. Text defaults to 14px var(--font-sans) in --color-text-primary. Keep it calm: no gradients or heavy shadows, font weights 400-600, sentence case.",
100805
+ "",
100806
+ 'Charts: color series with --color-series-1 to --color-series-8 (SVG: fill="var(--color-series-1)"), in that order (never skip or cycle; past 8 series, group the rest as "Other"). One y-axis per chart. A legend for 2+ series. Text, values and labels in text colors, never in series colors. Hover tooltips with exact values. --color-good, --color-warning, --color-serious and --color-critical are for states only, never for series. Read CSS variables in scripts with getComputedStyle(document.documentElement).getPropertyValue(name).',
100807
+ "",
100808
+ "Buttons, sliders, toggles and hover effects work inside the widget. Each call shows a new widget; to change one, call again with the complete new code."
100809
+ ].join("\n");
100810
+ var WIDGET_SHOWN_RESULT = "The widget is now shown to the user inline in the chat.";
100811
+ var WIDGET_EMPTY_RESULT = "widget_code is empty, so nothing was shown.";
100812
+ var WIDGET_TITLE_DESCRIPTION = 'Short human-readable title shown above the widget, e.g. "Monthly revenue by region".';
100813
+ var WIDGET_CODE_DESCRIPTION = "The HTML fragment to render: <style>, then markup (HTML or inline SVG), then <script>.";
100814
+
100815
+ // src/codex/codex-widget.ts
100816
+ var CODEX_WIDGET_TOOL = {
100817
+ name: WIDGET_TOOL_BASE_NAME,
100818
+ description: `${WIDGET_INSTRUCTIONS}
100819
+
100820
+ ${WIDGET_TOOL_DESCRIPTION}`,
100821
+ inputSchema: {
100822
+ type: "object",
100823
+ properties: {
100824
+ title: { type: "string", description: WIDGET_TITLE_DESCRIPTION },
100825
+ widget_code: { type: "string", description: WIDGET_CODE_DESCRIPTION }
100826
+ },
100827
+ required: ["title", "widget_code"]
100828
+ }
100829
+ };
100830
+ function servesCodexSession(sessionId) {
100831
+ if (!sessionId) return false;
100832
+ try {
100833
+ const row = getDb().prepare("SELECT runtime_type FROM sessions WHERE id = ?").get(sessionId);
100834
+ return row?.runtime_type === "codex";
100835
+ } catch {
100836
+ return false;
100837
+ }
100838
+ }
100839
+ function answerWidgetCall(args) {
100840
+ const code = args.widget_code;
100841
+ if (typeof code !== "string" || !code.trim()) return { ok: false, error: WIDGET_EMPTY_RESULT };
100842
+ return { ok: true, text: WIDGET_SHOWN_RESULT };
100843
+ }
100844
+
100717
100845
  // src/apps/mcp-tools.ts
100718
100846
  var TOOL_CALL_TIMEOUT_MS = Number(process.env.AGENT_PANE_TOOL_TIMEOUT_MS ?? 3e4);
100719
100847
  var TOOL_NS = "__";
@@ -100736,6 +100864,14 @@ function listAppTools() {
100736
100864
  }
100737
100865
  return tools;
100738
100866
  }
100867
+ function listGatewayTools(callerSessionId) {
100868
+ const tools = listAppTools();
100869
+ return servesCodexSession(callerSessionId) ? [CODEX_WIDGET_TOOL, ...tools] : tools;
100870
+ }
100871
+ function callPaneTool(toolName, args, callerSessionId) {
100872
+ if (toolName !== CODEX_WIDGET_TOOL.name || !servesCodexSession(callerSessionId)) return null;
100873
+ return answerWidgetCall(args);
100874
+ }
100739
100875
  function splitToolName(name) {
100740
100876
  const idx = name.indexOf(TOOL_NS);
100741
100877
  if (idx <= 0 || idx === name.length - TOOL_NS.length) return null;
@@ -100866,7 +101002,10 @@ async function registerAppRoutes(fastify, opts) {
100866
101002
  }
100867
101003
  });
100868
101004
  fastify.get("/api/apps/root", async () => ({ root: appsRoot() }));
100869
- fastify.get("/api/apps/mcp/tools", async () => listAppTools());
101005
+ fastify.get(
101006
+ "/api/apps/mcp/tools",
101007
+ async (request) => listGatewayTools(request.query.session)
101008
+ );
100870
101009
  fastify.get("/api/apps/examples", async () => {
100871
101010
  const exRoot = examplesRoot();
100872
101011
  if (!exRoot) return [];
@@ -100874,7 +101013,7 @@ async function registerAppRoutes(fastify, opts) {
100874
101013
  try {
100875
101014
  for (const entry of fs6.readdirSync(exRoot, { withFileTypes: true })) {
100876
101015
  if (!entry.isDirectory() || !APP_ID_RE.test(entry.name)) continue;
100877
- const manifest = readManifestIn(path9.join(exRoot, entry.name));
101016
+ const manifest = readManifestIn(path10.join(exRoot, entry.name));
100878
101017
  if (!manifest) continue;
100879
101018
  out.push({
100880
101019
  id: entry.name,
@@ -100895,7 +101034,7 @@ async function registerAppRoutes(fastify, opts) {
100895
101034
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
100896
101035
  const exRoot = examplesRoot();
100897
101036
  if (!exRoot) return reply.code(404).send({ error: "Examples catalog not available" });
100898
- const src = path9.join(exRoot, id);
101037
+ const src = path10.join(exRoot, id);
100899
101038
  if (!readManifestIn(src)) return reply.code(404).send({ error: "Example not found" });
100900
101039
  if (readManifest(id)) return reply.code(409).send({ error: "App already installed" });
100901
101040
  ensureAppsRoot();
@@ -100934,7 +101073,7 @@ async function registerAppRoutes(fastify, opts) {
100934
101073
  fs6.mkdirSync(dir, { recursive: true });
100935
101074
  const cleanTitle2 = title.trim();
100936
101075
  fs6.writeFileSync(
100937
- path9.join(dir, "manifest.json"),
101076
+ path10.join(dir, "manifest.json"),
100938
101077
  JSON.stringify(
100939
101078
  {
100940
101079
  title: cleanTitle2,
@@ -100945,8 +101084,8 @@ async function registerAppRoutes(fastify, opts) {
100945
101084
  2
100946
101085
  )
100947
101086
  );
100948
- fs6.writeFileSync(path9.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
100949
- fs6.writeFileSync(path9.join(dir, "app.ts"), SKELETON_TS);
101087
+ fs6.writeFileSync(path10.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
101088
+ fs6.writeFileSync(path10.join(dir, "app.ts"), SKELETON_TS);
100950
101089
  return { ok: true, id };
100951
101090
  }
100952
101091
  );
@@ -100983,9 +101122,9 @@ async function registerAppRoutes(fastify, opts) {
100983
101122
  const dir = appDir(id);
100984
101123
  fs6.mkdirSync(dir, { recursive: true });
100985
101124
  if (!Object.hasOwn(files ?? {}, "manifest.json")) {
100986
- fs6.writeFileSync(path9.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
101125
+ fs6.writeFileSync(path10.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
100987
101126
  }
100988
- for (const [name, content] of entries) fs6.writeFileSync(path9.join(dir, name), content);
101127
+ for (const [name, content] of entries) fs6.writeFileSync(path10.join(dir, name), content);
100989
101128
  return { ok: true, id };
100990
101129
  }
100991
101130
  );
@@ -101007,6 +101146,8 @@ async function registerAppRoutes(fastify, opts) {
101007
101146
  },
101008
101147
  async (request, reply) => {
101009
101148
  const { tool: tool2, args, workspace, caller } = request.body || {};
101149
+ const own = callPaneTool(tool2, args ?? {}, caller?.sessionId);
101150
+ if (own) return own;
101010
101151
  try {
101011
101152
  const result = await callAppTool(tool2, args ?? {}, resolveToolWorkspace(workspace), caller?.sessionId);
101012
101153
  return { ok: true, result };
@@ -101300,7 +101441,7 @@ function buildSidecarPrompt(externalSessionId, transcriptPath, question) {
101300
101441
  }
101301
101442
 
101302
101443
  // src/routes/sidecar.ts
101303
- var SIDECAR_RUNTIMES = /* @__PURE__ */ new Set(["claude"]);
101444
+ var SIDECAR_RUNTIMES = /* @__PURE__ */ new Set(["claude", "codex"]);
101304
101445
  async function registerSidecarRoutes(fastify) {
101305
101446
  fastify.post(
101306
101447
  "/api/sessions/:sessionId/sidecar",
@@ -101915,7 +102056,7 @@ async function registerUsageRoutes(fastify) {
101915
102056
 
101916
102057
  // src/claude/session-import.ts
101917
102058
  import { readFile as readFile2, realpath } from "node:fs/promises";
101918
- import path10 from "node:path";
102059
+ import path11 from "node:path";
101919
102060
  import { getSessionInfo, listSessions } from "@anthropic-ai/claude-agent-sdk";
101920
102061
 
101921
102062
  // src/claude/widget-tool.ts
@@ -102687,10 +102828,10 @@ function mergeDefs(...defs) {
102687
102828
  function cloneDef(schema) {
102688
102829
  return mergeDefs(schema._zod.def);
102689
102830
  }
102690
- function getElementAtPath(obj2, path17) {
102691
- if (!path17)
102831
+ function getElementAtPath(obj2, path19) {
102832
+ if (!path19)
102692
102833
  return obj2;
102693
- return path17.reduce((acc, key) => acc?.[key], obj2);
102834
+ return path19.reduce((acc, key) => acc?.[key], obj2);
102694
102835
  }
102695
102836
  function promiseAllObject(promisesObj) {
102696
102837
  const keys = Object.keys(promisesObj);
@@ -103099,11 +103240,11 @@ function explicitlyAborted(x, startIndex = 0) {
103099
103240
  }
103100
103241
  return false;
103101
103242
  }
103102
- function prefixIssues(path17, issues) {
103243
+ function prefixIssues(path19, issues) {
103103
103244
  return issues.map((iss) => {
103104
103245
  var _a3;
103105
103246
  (_a3 = iss).path ?? (_a3.path = []);
103106
- iss.path.unshift(path17);
103247
+ iss.path.unshift(path19);
103107
103248
  return iss;
103108
103249
  });
103109
103250
  }
@@ -103250,16 +103391,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
103250
103391
  }
103251
103392
  function formatError(error51, mapper = (issue2) => issue2.message) {
103252
103393
  const fieldErrors = { _errors: [] };
103253
- const processError = (error52, path17 = []) => {
103394
+ const processError = (error52, path19 = []) => {
103254
103395
  for (const issue2 of error52.issues) {
103255
103396
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103256
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103397
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
103257
103398
  } else if (issue2.code === "invalid_key") {
103258
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103399
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103259
103400
  } else if (issue2.code === "invalid_element") {
103260
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103401
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103261
103402
  } else {
103262
- const fullpath = [...path17, ...issue2.path];
103403
+ const fullpath = [...path19, ...issue2.path];
103263
103404
  if (fullpath.length === 0) {
103264
103405
  fieldErrors._errors.push(mapper(issue2));
103265
103406
  } else {
@@ -103286,17 +103427,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
103286
103427
  }
103287
103428
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
103288
103429
  const result = { errors: [] };
103289
- const processError = (error52, path17 = []) => {
103430
+ const processError = (error52, path19 = []) => {
103290
103431
  var _a3, _b;
103291
103432
  for (const issue2 of error52.issues) {
103292
103433
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103293
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103434
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
103294
103435
  } else if (issue2.code === "invalid_key") {
103295
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103436
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103296
103437
  } else if (issue2.code === "invalid_element") {
103297
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103438
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103298
103439
  } else {
103299
- const fullpath = [...path17, ...issue2.path];
103440
+ const fullpath = [...path19, ...issue2.path];
103300
103441
  if (fullpath.length === 0) {
103301
103442
  result.errors.push(mapper(issue2));
103302
103443
  continue;
@@ -103328,8 +103469,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
103328
103469
  }
103329
103470
  function toDotPath(_path) {
103330
103471
  const segs = [];
103331
- const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103332
- for (const seg of path17) {
103472
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103473
+ for (const seg of path19) {
103333
103474
  if (typeof seg === "number")
103334
103475
  segs.push(`[${seg}]`);
103335
103476
  else if (typeof seg === "symbol")
@@ -116021,13 +116162,13 @@ function resolveRef(ref, ctx) {
116021
116162
  if (!ref.startsWith("#")) {
116022
116163
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
116023
116164
  }
116024
- const path17 = ref.slice(1).split("/").filter(Boolean);
116025
- if (path17.length === 0) {
116165
+ const path19 = ref.slice(1).split("/").filter(Boolean);
116166
+ if (path19.length === 0) {
116026
116167
  return ctx.rootSchema;
116027
116168
  }
116028
116169
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
116029
- if (path17[0] === defsKey) {
116030
- const key = path17[1];
116170
+ if (path19[0] === defsKey) {
116171
+ const key = path19[1];
116031
116172
  if (!key || !ctx.defs[key]) {
116032
116173
  throw new Error(`Reference not found: ${ref}`);
116033
116174
  }
@@ -116437,28 +116578,7 @@ config2(en_default());
116437
116578
 
116438
116579
  // src/claude/widget-tool.ts
116439
116580
  var WIDGET_SERVER_NAME = "agentpane";
116440
- var WIDGET_TOOL_NAME = `mcp__${WIDGET_SERVER_NAME}__show_widget`;
116441
- var WIDGET_CDN_ORIGINS = [
116442
- "https://cdnjs.cloudflare.com",
116443
- "https://cdn.jsdelivr.net",
116444
- "https://unpkg.com",
116445
- "https://esm.sh"
116446
- ];
116447
- var WIDGET_INSTRUCTIONS = "AgentPane shows the result of show_widget inline in the chat, as a live visual. Use it when the user asks for a chart, diagram or other visual, and on your own when a visual explains something clearly better than text: numbers to compare, an architecture or flow to follow, a concept to explore. Keep routine progress updates and plain answers as text.";
116448
- var WIDGET_TOOL_DESCRIPTION = [
116449
- "Show a visual inline in the chat: a chart, diagram, flow, timeline, comparison, interactive explainer or small UI mockup, drawn from the HTML/SVG you pass. The user sees it right away, so do not repeat its content in your reply.",
116450
- "",
116451
- "widget_code is an HTML fragment, not a document: no <!DOCTYPE>, <html>, <head> or <body>. Order it <style> first, then the markup, then <script> last. The markup renders while you write it; scripts run once, after the whole fragment has arrived, and DOMContentLoaded and load fire again for them.",
116452
- "",
116453
- `Where it renders: a sandboxed iframe as wide as the chat column (up to 720px, narrower on small screens, so lay out fluidly; give SVG a viewBox and width 100%). The frame grows to fit the content, so never size anything from the frame: no 100vh, and give canvas charts a fixed-height wrapper (Chart.js: <div style="position:relative;height:320px"><canvas></canvas></div>). The background is transparent over the chat. The widget is offline except for these CDNs, which may serve scripts, stylesheets, fonts and data files: ${WIDGET_CDN_ORIGINS.join(", ")} (e.g. Chart.js, D3, Mermaid). Embed your data; storage, cookies and form submission do not work. Links open in a new browser tab.`,
116454
- "",
116455
- "Style with the chat's CSS variables, not hard-coded colors, so the widget matches it: --color-text-primary, --color-text-secondary, --color-text-muted, --color-background-primary (cards), --color-background-secondary (subtle fills), --color-border, --color-accent, --font-sans, --font-mono, --radius. Text defaults to 14px var(--font-sans) in --color-text-primary. Keep it calm: no gradients or heavy shadows, font weights 400-600, sentence case.",
116456
- "",
116457
- 'Charts: color series with --color-series-1 to --color-series-8 (SVG: fill="var(--color-series-1)"), in that order (never skip or cycle; past 8 series, group the rest as "Other"). One y-axis per chart. A legend for 2+ series. Text, values and labels in text colors, never in series colors. Hover tooltips with exact values. --color-good, --color-warning, --color-serious and --color-critical are for states only, never for series. Read CSS variables in scripts with getComputedStyle(document.documentElement).getPropertyValue(name).',
116458
- "",
116459
- "Buttons, sliders, toggles and hover effects work inside the widget. Each call shows a new widget; to change one, call again with the complete new code."
116460
- ].join("\n");
116461
- var SHOWN_RESULT = "The widget is now shown to the user inline in the chat.";
116581
+ var WIDGET_TOOL_NAME = `mcp__${WIDGET_SERVER_NAME}__${WIDGET_TOOL_BASE_NAME}`;
116462
116582
  function createWidgetMcpServer() {
116463
116583
  return createSdkMcpServer({
116464
116584
  name: WIDGET_SERVER_NAME,
@@ -116467,17 +116587,17 @@ function createWidgetMcpServer() {
116467
116587
  alwaysLoad: true,
116468
116588
  tools: [
116469
116589
  tool(
116470
- "show_widget",
116590
+ WIDGET_TOOL_BASE_NAME,
116471
116591
  WIDGET_TOOL_DESCRIPTION,
116472
116592
  {
116473
- title: external_exports.string().describe('Short human-readable title shown above the widget, e.g. "Monthly revenue by region".'),
116474
- widget_code: external_exports.string().describe("The HTML fragment to render: <style>, then markup (HTML or inline SVG), then <script>.")
116593
+ title: external_exports.string().describe(WIDGET_TITLE_DESCRIPTION),
116594
+ widget_code: external_exports.string().describe(WIDGET_CODE_DESCRIPTION)
116475
116595
  },
116476
116596
  async ({ widget_code }) => {
116477
116597
  if (!widget_code.trim()) {
116478
- return { content: [{ type: "text", text: "widget_code is empty, so nothing was shown." }], isError: true };
116598
+ return { content: [{ type: "text", text: WIDGET_EMPTY_RESULT }], isError: true };
116479
116599
  }
116480
- return { content: [{ type: "text", text: SHOWN_RESULT }] };
116600
+ return { content: [{ type: "text", text: WIDGET_SHOWN_RESULT }] };
116481
116601
  }
116482
116602
  )
116483
116603
  ]
@@ -116573,9 +116693,9 @@ function mapToolUse(block) {
116573
116693
  };
116574
116694
  }
116575
116695
  function deriveFileChangeData(input, toolName) {
116576
- const path17 = input.file_path ?? input.notebook_path ?? "";
116696
+ const path19 = input.file_path ?? input.notebook_path ?? "";
116577
116697
  const kind = toolName === "Write" ? "add" : "modify";
116578
- return { changes: [{ path: path17, kind }], status: "in_progress" };
116698
+ return { changes: [{ path: path19, kind }], status: "in_progress" };
116579
116699
  }
116580
116700
  function extractToolResultText(content) {
116581
116701
  if (!content) return "";
@@ -116940,7 +117060,7 @@ async function realDir(dir) {
116940
117060
  }
116941
117061
  }
116942
117062
  async function sameDir(a, realB) {
116943
- const realA = await realDir(a) ?? path10.resolve(a);
117063
+ const realA = await realDir(a) ?? path11.resolve(a);
116944
117064
  return realA === realB;
116945
117065
  }
116946
117066
  function knownClaudeSessionIds(db2) {
@@ -117106,9 +117226,523 @@ async function registerClaudeSessionRoutes(fastify) {
117106
117226
  );
117107
117227
  }
117108
117228
 
117109
- // src/session-host/flags.ts
117229
+ // src/codex/session-import.ts
117230
+ import { realpath as realpath2 } from "node:fs/promises";
117231
+ import path13 from "node:path";
117232
+
117233
+ // src/apps/register-mcp.ts
117110
117234
  import fs7 from "node:fs";
117111
- import path11 from "node:path";
117235
+ import path12 from "node:path";
117236
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
117237
+ var MCP_SERVER_NAME = "agentpane-miniapps";
117238
+ function panePublicUrl() {
117239
+ return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
117240
+ }
117241
+ function stdioScriptPath() {
117242
+ const here = path12.dirname(fileURLToPath2(import.meta.url));
117243
+ const candidates = [
117244
+ path12.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
117245
+ // src/apps/ → backend/scripts
117246
+ path12.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
117247
+ // dist bundle → backend/scripts
117248
+ ];
117249
+ for (const candidate of candidates) {
117250
+ if (fs7.existsSync(candidate)) return candidate;
117251
+ }
117252
+ return null;
117253
+ }
117254
+ var registered = /* @__PURE__ */ new Set();
117255
+ async function registerMiniAppMcp(baseUrl, workspace = "") {
117256
+ const key = `${baseUrl}|${workspace}`;
117257
+ if (registered.has(key)) return true;
117258
+ const script = stdioScriptPath();
117259
+ if (!script) {
117260
+ console.warn("[miniapp-mcp] stdio proxy script not found \u2014 registration skipped");
117261
+ return false;
117262
+ }
117263
+ if (!anyAppHasTools()) {
117264
+ return false;
117265
+ }
117266
+ const base = baseUrl.replace(/\/+$/, "");
117267
+ try {
117268
+ try {
117269
+ const res2 = await fetch(`${base}/mcp/servers`, { signal: AbortSignal.timeout(5e3) });
117270
+ if (res2.ok) {
117271
+ const servers = await res2.json();
117272
+ const names = servers.map((s) => s.server_name ?? s.name);
117273
+ if (names.includes(MCP_SERVER_NAME)) {
117274
+ await fetch(`${base}/mcp/configs/${MCP_SERVER_NAME}`, {
117275
+ method: "DELETE",
117276
+ signal: AbortSignal.timeout(5e3)
117277
+ }).catch(() => {
117278
+ });
117279
+ }
117280
+ }
117281
+ } catch {
117282
+ }
117283
+ const body = {
117284
+ configJson: JSON.stringify({
117285
+ [MCP_SERVER_NAME]: {
117286
+ command: process.execPath,
117287
+ args: [script, panePublicUrl(), workspace],
117288
+ env: { AGENT_PANE_SESSION_ID: "" }
117289
+ }
117290
+ })
117291
+ };
117292
+ const res = await fetch(`${base}/mcp/configs`, {
117293
+ method: "POST",
117294
+ headers: { "Content-Type": "application/json" },
117295
+ body: JSON.stringify(body),
117296
+ signal: AbortSignal.timeout(1e4)
117297
+ });
117298
+ if (res.status === 201) {
117299
+ console.log(`[miniapp-mcp] gateway registered in workspace backend ${base} (workspace: ${workspace || "global"})`);
117300
+ registered.add(key);
117301
+ return true;
117302
+ }
117303
+ const text2 = await res.text();
117304
+ if (res.status === 400 && /already exists/i.test(text2)) {
117305
+ registered.add(key);
117306
+ return true;
117307
+ }
117308
+ console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
117309
+ return false;
117310
+ } catch (err) {
117311
+ console.warn(`[miniapp-mcp] registration error: ${err.message}`);
117312
+ return false;
117313
+ }
117314
+ }
117315
+ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
117316
+ const script = stdioScriptPath();
117317
+ if (!script) return null;
117318
+ return [
117319
+ // MCP tool calls must not ask for elicitation approval — nobody is
117320
+ // watching an agent-driven session to approve (feature is stable/on).
117321
+ "-c",
117322
+ "features.tool_call_mcp_elicitation=false",
117323
+ "-c",
117324
+ `mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
117325
+ "-c",
117326
+ `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
117327
+ ];
117328
+ }
117329
+
117330
+ // src/codex/item-mapper.ts
117331
+ function paneStatus(status) {
117332
+ switch (status) {
117333
+ case "inProgress":
117334
+ case "in_progress":
117335
+ return "in_progress";
117336
+ case "completed":
117337
+ return "completed";
117338
+ case "failed":
117339
+ case "declined":
117340
+ return "failed";
117341
+ default:
117342
+ return void 0;
117343
+ }
117344
+ }
117345
+ function errorText(error51) {
117346
+ if (!error51) return null;
117347
+ if (typeof error51 === "string") return error51;
117348
+ const message = error51.message;
117349
+ return typeof message === "string" ? message : JSON.stringify(error51);
117350
+ }
117351
+ function resultText(result) {
117352
+ const content = result?.content;
117353
+ if (!Array.isArray(content)) return "";
117354
+ return content.map((part) => typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
117355
+ }
117356
+ function isWidgetCall(item) {
117357
+ return item.type === "mcpToolCall" && item.server === MCP_SERVER_NAME && item.tool === WIDGET_TOOL_BASE_NAME;
117358
+ }
117359
+ var ITEM_TYPES = {
117360
+ agentMessage: "agent_message",
117361
+ userMessage: "user_message",
117362
+ agentReasoning: "reasoning",
117363
+ commandExecution: "command_execution",
117364
+ fileChange: "file_change",
117365
+ mcpToolCall: "mcp_tool_call",
117366
+ webSearch: "web_search",
117367
+ todoList: "todo_list",
117368
+ contextCompaction: "context_compaction",
117369
+ error: "error"
117370
+ };
117371
+ function mapItemType(item) {
117372
+ if (isWidgetCall(item)) return "widget";
117373
+ return ITEM_TYPES[item.type] ?? item.type;
117374
+ }
117375
+ function mapItemData(item) {
117376
+ switch (item.type) {
117377
+ case "agentMessage":
117378
+ case "agent_message":
117379
+ return { text: item.text };
117380
+ case "reasoning":
117381
+ case "agentReasoning": {
117382
+ const summary = Array.isArray(item.summary) ? item.summary.join("\n") : "";
117383
+ return { text: summary || item.text || "" };
117384
+ }
117385
+ case "commandExecution":
117386
+ case "command_execution":
117387
+ return {
117388
+ command: item.command,
117389
+ aggregated_output: item.aggregatedOutput ?? item.aggregated_output,
117390
+ exit_code: item.exitCode ?? item.exit_code ?? null,
117391
+ status: paneStatus(item.status)
117392
+ };
117393
+ case "fileChange":
117394
+ case "file_change":
117395
+ return {
117396
+ changes: item.changes,
117397
+ status: paneStatus(item.status)
117398
+ };
117399
+ case "mcpToolCall":
117400
+ case "mcp_tool_call":
117401
+ if (isWidgetCall(item)) {
117402
+ const args = item.arguments ?? {};
117403
+ const failed = paneStatus(item.status) === "failed";
117404
+ return {
117405
+ title: typeof args.title === "string" ? args.title : "",
117406
+ html: typeof args.widget_code === "string" ? args.widget_code : "",
117407
+ error: failed ? errorText(item.error) || resultText(item.result) || "Tool error" : null
117408
+ };
117409
+ }
117410
+ return {
117411
+ server: item.server,
117412
+ tool: item.tool,
117413
+ arguments: item.arguments,
117414
+ result: item.result ?? null,
117415
+ error: errorText(item.error),
117416
+ status: paneStatus(item.status)
117417
+ };
117418
+ case "webSearch":
117419
+ case "web_search":
117420
+ return { query: item.query };
117421
+ case "todoList":
117422
+ case "todo_list":
117423
+ return { items: item.items };
117424
+ case "contextCompaction":
117425
+ return { trigger: "auto", pre_tokens: null, post_tokens: null };
117426
+ case "error":
117427
+ return { message: item.message };
117428
+ default:
117429
+ return {};
117430
+ }
117431
+ }
117432
+ function getItemStatus(item) {
117433
+ if (item.type === "commandExecution" || item.type === "command_execution" || item.type === "fileChange" || item.type === "file_change" || item.type === "mcpToolCall" || item.type === "mcp_tool_call") {
117434
+ return paneStatus(item.status) ?? "completed";
117435
+ }
117436
+ if (item.type === "error") {
117437
+ return "failed";
117438
+ }
117439
+ return "completed";
117440
+ }
117441
+
117442
+ // src/codex/known-threads.ts
117443
+ var PANE_THREAD_SOURCE = "agentpane";
117444
+ function recordCodexThread(threadId, sessionId) {
117445
+ try {
117446
+ getDb().prepare("INSERT OR IGNORE INTO codex_threads (thread_id, session_id, created_at) VALUES (?, ?, ?)").run(threadId, sessionId, (/* @__PURE__ */ new Date()).toISOString());
117447
+ } catch {
117448
+ }
117449
+ }
117450
+ function knownCodexThreadIds(db2) {
117451
+ const rows = db2.prepare(
117452
+ `SELECT external_thread_id AS id FROM sessions WHERE external_thread_id IS NOT NULL
117453
+ UNION SELECT pre_rewind_thread_id FROM sessions WHERE pre_rewind_thread_id IS NOT NULL
117454
+ UNION SELECT import_source_id FROM sessions WHERE import_source_id IS NOT NULL
117455
+ UNION SELECT external_thread_id FROM discussion_threads WHERE external_thread_id IS NOT NULL
117456
+ UNION SELECT thread_id FROM codex_threads`
117457
+ ).all();
117458
+ return new Set(rows.map((row) => row.id));
117459
+ }
117460
+
117461
+ // src/codex/review-turns.ts
117462
+ function isReview(turn) {
117463
+ return (turn.items ?? []).some((item) => item.type === "enteredReviewMode");
117464
+ }
117465
+ function isInsideReview(review, turn) {
117466
+ return isReview(review) && review.completedAt != null && turn.startedAt != null && turn.startedAt < review.completedAt;
117467
+ }
117468
+ function forkThroughReview(turns, turnId) {
117469
+ const index = turns.findIndex((turn) => turn.id === turnId);
117470
+ if (index < 0 || !isReview(turns[index])) return void 0;
117471
+ let next = index + 1;
117472
+ while (next < turns.length && isInsideReview(turns[index], turns[next])) next++;
117473
+ if (next < turns.length - 1 && isInsideReview(turns[next], turns[next + 1])) next++;
117474
+ return next < turns.length ? { beforeTurnId: turns[next].id } : {};
117475
+ }
117476
+
117477
+ // src/codex/session-import.ts
117478
+ var CodexImportError = class extends Error {
117479
+ status;
117480
+ paneSessionId;
117481
+ constructor(status, message, paneSessionId = null) {
117482
+ super(message);
117483
+ this.name = "CodexImportError";
117484
+ this.status = status;
117485
+ this.paneSessionId = paneSessionId;
117486
+ }
117487
+ };
117488
+ var RECENT_MS2 = 10 * 6e4;
117489
+ var THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
117490
+ var TITLE_MAX2 = 100;
117491
+ var LIST_PAGE = 100;
117492
+ var LIST_MAX = 1e3;
117493
+ var USER_SOURCES = ["cli", "vscode", "exec", "appServer", "unknown"];
117494
+ var THROWAWAY_PROMPTS = ["Generate a concise 3-5 word title", "You are summarizing a side discussion thread"];
117495
+ async function realDir2(dir) {
117496
+ try {
117497
+ return await realpath2(dir);
117498
+ } catch {
117499
+ return null;
117500
+ }
117501
+ }
117502
+ async function workspaceDirs(workspacePath) {
117503
+ const real = await realDir2(workspacePath);
117504
+ if (!real) return null;
117505
+ const given = path13.resolve(workspacePath);
117506
+ return given === real ? [real] : [given, real];
117507
+ }
117508
+ function titleOf2(thread) {
117509
+ const raw = (thread.name || thread.preview || "").trim();
117510
+ const firstLine = raw.split("\n")[0].trim();
117511
+ return firstLine.length > TITLE_MAX2 ? `${firstLine.slice(0, TITLE_MAX2 - 1)}\u2026` : firstLine;
117512
+ }
117513
+ function isThrowaway(thread) {
117514
+ const preview = (thread.preview ?? "").trimStart();
117515
+ return THROWAWAY_PROMPTS.some((prompt) => preview.startsWith(prompt));
117516
+ }
117517
+ function paneSessionHolding2(db2, threadId) {
117518
+ const row = db2.prepare(
117519
+ `SELECT id FROM sessions WHERE import_source_id = ? OR external_thread_id = ? OR pre_rewind_thread_id = ?
117520
+ UNION ALL SELECT session_id FROM discussion_threads WHERE external_thread_id = ?
117521
+ UNION ALL SELECT session_id FROM codex_threads WHERE thread_id = ?
117522
+ LIMIT 1`
117523
+ ).get(threadId, threadId, threadId, threadId, threadId);
117524
+ return row ? { sessionId: row.id } : null;
117525
+ }
117526
+ async function listImportableCodexSessions(db2, workspacePath, now = Date.now()) {
117527
+ const dirs = await workspaceDirs(workspacePath);
117528
+ if (!dirs) return [];
117529
+ const known = knownCodexThreadIds(db2);
117530
+ const client = getSharedAppServer();
117531
+ const sessions = [];
117532
+ let cursor = null;
117533
+ let seen = 0;
117534
+ do {
117535
+ const page = await client.request("thread/list", {
117536
+ cwd: dirs,
117537
+ limit: LIST_PAGE,
117538
+ cursor,
117539
+ sortKey: "updated_at",
117540
+ sourceKinds: USER_SOURCES
117541
+ });
117542
+ for (const thread of page.data ?? []) {
117543
+ seen += 1;
117544
+ if (known.has(thread.id) || thread.parentThreadId || thread.ephemeral || isThrowaway(thread)) continue;
117545
+ const title = titleOf2(thread);
117546
+ if (!title) continue;
117547
+ const updatedMs = thread.updatedAt * 1e3;
117548
+ sessions.push({
117549
+ session_id: thread.id,
117550
+ title,
117551
+ cwd: thread.cwd,
117552
+ git_branch: thread.gitInfo?.branch ?? null,
117553
+ created_at: new Date(thread.createdAt * 1e3).toISOString(),
117554
+ last_modified: new Date(updatedMs).toISOString(),
117555
+ recently_active: now - updatedMs < RECENT_MS2
117556
+ });
117557
+ }
117558
+ cursor = page.nextCursor;
117559
+ } while (cursor && seen < LIST_MAX);
117560
+ return sessions.sort((a, b) => a.last_modified < b.last_modified ? 1 : -1);
117561
+ }
117562
+ var TURN_STATUS = {
117563
+ completed: "completed",
117564
+ failed: "failed",
117565
+ interrupted: "aborted",
117566
+ inProgress: "aborted"
117567
+ };
117568
+ function userText(item) {
117569
+ const content = Array.isArray(item.content) ? item.content : [];
117570
+ return content.map((part) => {
117571
+ if (part.type === "text" && typeof part.text === "string") return part.text;
117572
+ if (part.type === "image") return "[image]";
117573
+ if (part.type === "localImage" && typeof part.path === "string") return `[image: ${part.path}]`;
117574
+ return "";
117575
+ }).filter(Boolean).join("\n");
117576
+ }
117577
+ function skipped(item, data) {
117578
+ if (item.type === "userMessage" || item.type === "enteredReviewMode" || item.type === "exitedReviewMode") return true;
117579
+ return (item.type === "reasoning" || item.type === "agentReasoning") && !data.text;
117580
+ }
117581
+ function threadToTurns(thread) {
117582
+ const turns = [];
117583
+ const stored = thread.turns ?? [];
117584
+ let last = thread.createdAt * 1e3 - 1;
117585
+ for (const [position, turn] of stored.entries()) {
117586
+ if (position > 0 && isInsideReview(stored[position - 1], turn)) continue;
117587
+ const items = turn.items ?? [];
117588
+ const prompt = items.filter((item) => item.type === "userMessage").map(userText).filter(Boolean).join("\n\n");
117589
+ const command = items.some((item) => item.type === "enteredReviewMode") ? "/review" : items.some((item) => item.type === "contextCompaction") ? "/compact" : "";
117590
+ const output = [];
117591
+ let agentResponse = null;
117592
+ let review = null;
117593
+ let thoughts = null;
117594
+ const started = Math.max(last + 1, (turn.startedAt ?? 0) * 1e3);
117595
+ for (const [index, item] of items.entries()) {
117596
+ if (item.type === "exitedReviewMode" && typeof item.review === "string" && item.review.trim())
117597
+ review = item.review;
117598
+ const data = mapItemData(item);
117599
+ if (skipped(item, data)) continue;
117600
+ if (item.type === "agentMessage" || item.type === "agent_message") agentResponse = item.text ?? agentResponse;
117601
+ if ((item.type === "reasoning" || item.type === "agentReasoning") && typeof data.text === "string") {
117602
+ thoughts = data.text;
117603
+ }
117604
+ const status = getItemStatus(item);
117605
+ output.push({
117606
+ externalId: item.id,
117607
+ type: mapItemType(item),
117608
+ data,
117609
+ // Left open when its turn ended: it never finished.
117610
+ status: status === "in_progress" ? "failed" : status,
117611
+ createdAt: new Date(started + index).toISOString()
117612
+ });
117613
+ }
117614
+ const userPrompt = prompt || command;
117615
+ if (!userPrompt && output.length === 0) continue;
117616
+ const ended = Math.max(started, (turn.completedAt ?? 0) * 1e3);
117617
+ turns.push({
117618
+ userPrompt,
117619
+ agentResponse: agentResponse ?? review,
117620
+ thoughts,
117621
+ externalTurnId: turn.id,
117622
+ status: TURN_STATUS[turn.status] ?? "completed",
117623
+ error: turn.status === "failed" ? turn.error?.message ?? "Codex turn failed" : null,
117624
+ createdAt: new Date(started).toISOString(),
117625
+ updatedAt: new Date(ended).toISOString(),
117626
+ items: output
117627
+ });
117628
+ last = started;
117629
+ }
117630
+ return turns;
117631
+ }
117632
+ async function importCodexSession(db2, threadId, workspacePath) {
117633
+ if (!THREAD_ID.test(threadId)) throw new CodexImportError(400, "Not a Codex thread id");
117634
+ const holder = paneSessionHolding2(db2, threadId);
117635
+ if (holder) throw new CodexImportError(409, "This thread is already in the pane", holder.sessionId);
117636
+ let thread;
117637
+ try {
117638
+ ({ thread } = await getSharedAppServer().request("thread/read", {
117639
+ threadId,
117640
+ includeTurns: true
117641
+ }));
117642
+ } catch (err) {
117643
+ throw new CodexImportError(404, `Codex thread not found: ${err.message}`);
117644
+ }
117645
+ const turns = threadToTurns(thread);
117646
+ if (turns.length === 0) throw new CodexImportError(422, "This thread has no conversation to import");
117647
+ const dirs = workspacePath ? await workspaceDirs(workspacePath) : null;
117648
+ const cwd = workspacePath && dirs?.includes(thread.cwd) ? workspacePath : thread.cwd;
117649
+ const sessionId = v4_default();
117650
+ const insertSession = db2.prepare(
117651
+ `INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status,
117652
+ is_running, lifecycle, sort_order, user_touched, import_source_id, created_at, updated_at)
117653
+ VALUES (?, ?, 'codex', NULL, NULL, ?, ?, 'active', 0, 'working', ?, 1, ?, ?, ?)`
117654
+ );
117655
+ const insertTurn = db2.prepare(
117656
+ `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status,
117657
+ error, created_at, updated_at)
117658
+ VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)`
117659
+ );
117660
+ const insertItem2 = db2.prepare(
117661
+ `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
117662
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
117663
+ );
117664
+ db2.transaction(() => {
117665
+ const raced = paneSessionHolding2(db2, threadId);
117666
+ if (raced) throw new CodexImportError(409, "This thread is already in the pane", raced.sessionId);
117667
+ const { m } = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd);
117668
+ insertSession.run(
117669
+ sessionId,
117670
+ titleOf2(thread) || null,
117671
+ cwd,
117672
+ threadId,
117673
+ m + 1,
117674
+ threadId,
117675
+ turns[0].createdAt,
117676
+ turns[turns.length - 1].updatedAt
117677
+ );
117678
+ for (const turn of turns) {
117679
+ const turnId = v4_default();
117680
+ insertTurn.run(
117681
+ turnId,
117682
+ sessionId,
117683
+ turn.userPrompt,
117684
+ turn.agentResponse,
117685
+ turn.thoughts,
117686
+ turn.externalTurnId,
117687
+ turn.status,
117688
+ turn.error,
117689
+ turn.createdAt,
117690
+ turn.updatedAt
117691
+ );
117692
+ for (const item of turn.items) {
117693
+ insertItem2.run(
117694
+ v4_default(),
117695
+ turnId,
117696
+ item.externalId,
117697
+ item.type,
117698
+ JSON.stringify(trimItemData(item.data)),
117699
+ item.status,
117700
+ item.createdAt,
117701
+ item.createdAt
117702
+ );
117703
+ }
117704
+ }
117705
+ })();
117706
+ return db2.prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
117707
+ }
117708
+
117709
+ // src/routes/codex-sessions.ts
117710
+ async function registerCodexSessionRoutes(fastify) {
117711
+ fastify.get("/api/codex-sessions", async (request, reply) => {
117712
+ const workspace = request.query.workspace?.trim();
117713
+ if (!workspace) return reply.code(400).send({ error: "workspace is required" });
117714
+ try {
117715
+ return { sessions: await listImportableCodexSessions(getDb(), workspace) };
117716
+ } catch (err) {
117717
+ return reply.code(500).send({ error: `Could not list Codex sessions: ${err.message}` });
117718
+ }
117719
+ });
117720
+ fastify.post(
117721
+ "/api/codex-sessions/:id/import",
117722
+ {
117723
+ schema: {
117724
+ body: {
117725
+ type: ["object", "null"],
117726
+ properties: { workspace: { type: ["string", "null"] } }
117727
+ }
117728
+ }
117729
+ },
117730
+ async (request, reply) => {
117731
+ try {
117732
+ return await importCodexSession(getDb(), request.params.id, request.body?.workspace?.trim() || null);
117733
+ } catch (err) {
117734
+ if (err instanceof CodexImportError) {
117735
+ return reply.code(err.status).send({ error: err.message, session_id: err.paneSessionId });
117736
+ }
117737
+ return reply.code(500).send({ error: `Import failed: ${err.message}` });
117738
+ }
117739
+ }
117740
+ );
117741
+ }
117742
+
117743
+ // src/session-host/flags.ts
117744
+ import fs8 from "node:fs";
117745
+ import path14 from "node:path";
117112
117746
  var DEFAULT_FLAGS = {
117113
117747
  claude: true,
117114
117748
  codex: true,
@@ -117127,18 +117761,18 @@ function setPaneDataDir(dir) {
117127
117761
  }
117128
117762
  function sessionHostsRoot() {
117129
117763
  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;
117764
+ if (override) return path14.resolve(override);
117765
+ return paneDataDir ? path14.join(paneDataDir, "session-hosts") : null;
117132
117766
  }
117133
117767
  function flagsFilePath() {
117134
117768
  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;
117769
+ if (process.env.AGENT_PANE_SESSION_HOSTS_DIR) return path14.join(path14.dirname(root), "session-hosts.json");
117770
+ return paneDataDir ? path14.join(paneDataDir, "session-hosts.json") : null;
117137
117771
  }
117138
117772
  function readFlagFile(file2) {
117139
117773
  if (!file2) return {};
117140
117774
  try {
117141
- const parsed = JSON.parse(fs7.readFileSync(file2, "utf8"));
117775
+ const parsed = JSON.parse(fs8.readFileSync(file2, "utf8"));
117142
117776
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
117143
117777
  console.warn(`[session-host] ${file2} is not a JSON object; using the defaults`);
117144
117778
  } catch (err) {
@@ -117204,17 +117838,17 @@ var LOG_HEADER_LEN = LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS + 1;
117204
117838
 
117205
117839
  // src/session-host/registry.ts
117206
117840
  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";
117841
+ import fs10 from "node:fs";
117842
+ import path16 from "node:path";
117843
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
117210
117844
 
117211
117845
  // src/session-host/client.ts
117212
117846
  import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
117213
117847
  import { EventEmitter as EventEmitter2 } from "node:events";
117214
- import fs8 from "node:fs";
117848
+ import fs9 from "node:fs";
117215
117849
  import net2 from "node:net";
117216
- import path12 from "node:path";
117217
- import { fileURLToPath as fileURLToPath2 } from "node:url";
117850
+ import path15 from "node:path";
117851
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
117218
117852
  var HostRequestError = class extends Error {
117219
117853
  reply;
117220
117854
  constructor(reply) {
@@ -117225,36 +117859,36 @@ var HostRequestError = class extends Error {
117225
117859
  function hostScriptPath() {
117226
117860
  const override = process.env.AGENT_PANE_SESSION_HOST_SCRIPT;
117227
117861
  if (override) return override;
117228
- const here = path12.dirname(fileURLToPath2(import.meta.url));
117862
+ const here = path15.dirname(fileURLToPath3(import.meta.url));
117229
117863
  const candidates = [
117230
- path12.resolve(here, "../../scripts/session-host.mjs"),
117864
+ path15.resolve(here, "../../scripts/session-host.mjs"),
117231
117865
  // src/session-host/ → backend/scripts
117232
- path12.resolve(here, "../scripts/session-host.mjs")
117866
+ path15.resolve(here, "../scripts/session-host.mjs")
117233
117867
  // dist bundle → backend/scripts
117234
117868
  ];
117235
117869
  for (const candidate of candidates) {
117236
- if (fs8.existsSync(candidate)) return candidate;
117870
+ if (fs9.existsSync(candidate)) return candidate;
117237
117871
  }
117238
117872
  return null;
117239
117873
  }
117240
117874
  function hostSocketPath(dir) {
117241
- const direct = path12.join(dir, "sock");
117875
+ const direct = path15.join(dir, "sock");
117242
117876
  if (Buffer.byteLength(direct) < 100) return direct;
117243
117877
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
117244
- return path12.join("/tmp", `rbsh-${uid}`, path12.basename(dir), "sock");
117878
+ return path15.join("/tmp", `rbsh-${uid}`, path15.basename(dir), "sock");
117245
117879
  }
117246
117880
  function readJson(file2) {
117247
117881
  try {
117248
- return JSON.parse(fs8.readFileSync(file2, "utf8"));
117882
+ return JSON.parse(fs9.readFileSync(file2, "utf8"));
117249
117883
  } catch {
117250
117884
  return null;
117251
117885
  }
117252
117886
  }
117253
117887
  function readHostExit(dir) {
117254
- return readJson(path12.join(dir, "exit.json"));
117888
+ return readJson(path15.join(dir, "exit.json"));
117255
117889
  }
117256
117890
  function readHostChild(dir) {
117257
- return readJson(path12.join(dir, "child.json"));
117891
+ return readJson(path15.join(dir, "child.json"));
117258
117892
  }
117259
117893
  function isPidAlive(pid) {
117260
117894
  if (!pid || pid <= 0) return false;
@@ -117409,8 +118043,8 @@ function attachHost(dir, after, timeoutMs = 5e3) {
117409
118043
  function startHost(opts) {
117410
118044
  const script = hostScriptPath();
117411
118045
  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);
118046
+ fs9.mkdirSync(opts.dir, { recursive: true, mode: 448 });
118047
+ fs9.chmodSync(opts.dir, 448);
117414
118048
  const env = {};
117415
118049
  for (const [k, v] of Object.entries(opts.env)) if (v !== void 0) env[k] = v;
117416
118050
  const child = spawn4(opts.nodePath ?? process.execPath, [script, opts.dir, JSON.stringify(opts.config), opts.command, ...opts.args], {
@@ -117444,9 +118078,9 @@ async function waitForHost(dir, timeoutMs = 1e4) {
117444
118078
  function readLogOldest(dir) {
117445
118079
  let fd = null;
117446
118080
  try {
117447
- fd = fs8.openSync(path12.join(dir, "out.log"), "r");
118081
+ fd = fs9.openSync(path15.join(dir, "out.log"), "r");
117448
118082
  const buf = Buffer.alloc(LOG_HEADER_LEN);
117449
- const n = fs8.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
118083
+ const n = fs9.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
117450
118084
  const text2 = buf.subarray(0, n).toString("utf8");
117451
118085
  if (n < LOG_HEADER_LEN || !text2.startsWith(LOG_HEADER_PREFIX) || text2[LOG_HEADER_LEN - 1] !== "\n") return null;
117452
118086
  const digits = text2.slice(LOG_HEADER_PREFIX.length, LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS);
@@ -117454,14 +118088,14 @@ function readLogOldest(dir) {
117454
118088
  } catch {
117455
118089
  return null;
117456
118090
  } finally {
117457
- if (fd !== null) fs8.closeSync(fd);
118091
+ if (fd !== null) fs9.closeSync(fd);
117458
118092
  }
117459
118093
  }
117460
118094
  function readHostLog(dir, after) {
117461
118095
  const oldest = readLogOldest(dir);
117462
118096
  if (oldest === null || after < oldest) return null;
117463
118097
  try {
117464
- const all = fs8.readFileSync(path12.join(dir, "out.log"));
118098
+ const all = fs9.readFileSync(path15.join(dir, "out.log"));
117465
118099
  const start = LOG_HEADER_LEN + (after - oldest);
117466
118100
  if (start > all.length) return null;
117467
118101
  return all.subarray(start);
@@ -117471,14 +118105,14 @@ function readHostLog(dir, after) {
117471
118105
  }
117472
118106
  function removeHostDir(dir) {
117473
118107
  try {
117474
- fs8.rmSync(dir, { recursive: true, force: true });
118108
+ fs9.rmSync(dir, { recursive: true, force: true });
117475
118109
  } catch (err) {
117476
118110
  console.error(`[session-host] could not remove ${dir}:`, err.message);
117477
118111
  }
117478
- const alias = path12.dirname(hostSocketPath(dir));
118112
+ const alias = path15.dirname(hostSocketPath(dir));
117479
118113
  if (alias !== dir) {
117480
118114
  try {
117481
- fs8.unlinkSync(alias);
118115
+ fs9.unlinkSync(alias);
117482
118116
  } catch {
117483
118117
  }
117484
118118
  }
@@ -117535,16 +118169,16 @@ function newHostDir() {
117535
118169
  const root = sessionHostsRoot();
117536
118170
  if (!root) throw new Error("session hosts have no directory");
117537
118171
  const id = randomBytes(8).toString("hex");
117538
- return { id, dir: path13.join(root, id) };
118172
+ return { id, dir: path16.join(root, id) };
117539
118173
  }
117540
118174
  var cachedVersion;
117541
118175
  function runtimeVersion() {
117542
118176
  if (cachedVersion !== void 0) return cachedVersion;
117543
118177
  cachedVersion = null;
117544
- const here = path13.dirname(fileURLToPath3(import.meta.url));
118178
+ const here = path16.dirname(fileURLToPath4(import.meta.url));
117545
118179
  for (const rel of ["../../../../package.json", "../../../package.json"]) {
117546
118180
  try {
117547
- const pkg = JSON.parse(fs9.readFileSync(path13.resolve(here, rel), "utf8"));
118181
+ const pkg = JSON.parse(fs10.readFileSync(path16.resolve(here, rel), "utf8"));
117548
118182
  if (pkg.name === "repoburg" && pkg.version) {
117549
118183
  cachedVersion = pkg.version;
117550
118184
  break;
@@ -117555,15 +118189,15 @@ function runtimeVersion() {
117555
118189
  return cachedVersion;
117556
118190
  }
117557
118191
  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"));
118192
+ fs10.mkdirSync(dir, { recursive: true, mode: 448 });
118193
+ fs10.chmodSync(dir, 448);
118194
+ const tmp = path16.join(dir, "meta.json.tmp");
118195
+ fs10.writeFileSync(tmp, JSON.stringify(meta3, null, 2) + "\n", { mode: 384 });
118196
+ fs10.renameSync(tmp, path16.join(dir, "meta.json"));
117563
118197
  }
117564
118198
  function readHostMeta(dir) {
117565
118199
  try {
117566
- return JSON.parse(fs9.readFileSync(path13.join(dir, "meta.json"), "utf8"));
118200
+ return JSON.parse(fs10.readFileSync(path16.join(dir, "meta.json"), "utf8"));
117567
118201
  } catch {
117568
118202
  return null;
117569
118203
  }
@@ -117701,16 +118335,16 @@ async function runAdoption() {
117701
118335
  async function adoptHosts(db2, root, adoption, result) {
117702
118336
  let entries = [];
117703
118337
  try {
117704
- entries = fs9.readdirSync(root);
118338
+ entries = fs10.readdirSync(root);
117705
118339
  } catch (err) {
117706
118340
  if (err.code !== "ENOENT") console.error("[session-host] cannot read", root, err.message);
117707
118341
  }
117708
118342
  const seen = /* @__PURE__ */ new Set();
117709
118343
  const queue = [];
117710
118344
  for (const id of entries) {
117711
- const dir = path13.join(root, id);
118345
+ const dir = path16.join(root, id);
117712
118346
  try {
117713
- if (!fs9.statSync(dir).isDirectory()) continue;
118347
+ if (!fs10.statSync(dir).isDirectory()) continue;
117714
118348
  } catch {
117715
118349
  continue;
117716
118350
  }
@@ -117846,63 +118480,6 @@ async function registerSessionHostRoutes(fastify) {
117846
118480
  });
117847
118481
  }
117848
118482
 
117849
- // src/codex/item-mapper.ts
117850
- function mapItemData(item) {
117851
- switch (item.type) {
117852
- case "agentMessage":
117853
- case "agent_message":
117854
- return { text: item.text };
117855
- case "reasoning":
117856
- case "agentReasoning": {
117857
- const summary = Array.isArray(item.summary) ? item.summary.join("\n") : "";
117858
- return { text: summary || item.text || "" };
117859
- }
117860
- case "commandExecution":
117861
- case "command_execution":
117862
- return {
117863
- command: item.command,
117864
- aggregated_output: item.aggregated_output,
117865
- exit_code: item.exit_code ?? null,
117866
- status: item.status
117867
- };
117868
- case "fileChange":
117869
- case "file_change":
117870
- return {
117871
- changes: item.changes,
117872
- status: item.status
117873
- };
117874
- case "mcpToolCall":
117875
- case "mcp_tool_call":
117876
- return {
117877
- server: item.server,
117878
- tool: item.tool,
117879
- arguments: item.arguments,
117880
- result: item.result ?? null,
117881
- error: item.error ?? null,
117882
- status: item.status
117883
- };
117884
- case "webSearch":
117885
- case "web_search":
117886
- return { query: item.query };
117887
- case "todoList":
117888
- case "todo_list":
117889
- return { items: item.items };
117890
- case "error":
117891
- return { message: item.message };
117892
- default:
117893
- return {};
117894
- }
117895
- }
117896
- function getItemStatus(item) {
117897
- if (item.type === "commandExecution" || item.type === "command_execution" || item.type === "fileChange" || item.type === "file_change" || item.type === "mcpToolCall" || item.type === "mcp_tool_call") {
117898
- return item.status ?? "completed";
117899
- }
117900
- if (item.type === "error") {
117901
- return "failed";
117902
- }
117903
- return "completed";
117904
- }
117905
-
117906
118483
  // src/codex/codex-host.ts
117907
118484
  import { EventEmitter as EventEmitter4 } from "node:events";
117908
118485
  import { PassThrough as PassThrough2, Writable as Writable2 } from "node:stream";
@@ -118329,103 +118906,6 @@ function mapTokenUsage(data) {
118329
118906
  };
118330
118907
  }
118331
118908
 
118332
- // src/apps/register-mcp.ts
118333
- import fs10 from "node:fs";
118334
- import path14 from "node:path";
118335
- import { fileURLToPath as fileURLToPath4 } from "node:url";
118336
- var MCP_SERVER_NAME = "agentpane-miniapps";
118337
- function panePublicUrl() {
118338
- return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
118339
- }
118340
- function stdioScriptPath() {
118341
- const here = path14.dirname(fileURLToPath4(import.meta.url));
118342
- const candidates = [
118343
- path14.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
118344
- // src/apps/ → backend/scripts
118345
- path14.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
118346
- // dist bundle → backend/scripts
118347
- ];
118348
- for (const candidate of candidates) {
118349
- if (fs10.existsSync(candidate)) return candidate;
118350
- }
118351
- return null;
118352
- }
118353
- var registered = /* @__PURE__ */ new Set();
118354
- async function registerMiniAppMcp(baseUrl, workspace = "") {
118355
- const key = `${baseUrl}|${workspace}`;
118356
- if (registered.has(key)) return true;
118357
- const script = stdioScriptPath();
118358
- if (!script) {
118359
- console.warn("[miniapp-mcp] stdio proxy script not found \u2014 registration skipped");
118360
- return false;
118361
- }
118362
- if (!anyAppHasTools()) {
118363
- return false;
118364
- }
118365
- const base = baseUrl.replace(/\/+$/, "");
118366
- try {
118367
- try {
118368
- const res2 = await fetch(`${base}/mcp/servers`, { signal: AbortSignal.timeout(5e3) });
118369
- if (res2.ok) {
118370
- const servers = await res2.json();
118371
- const names = servers.map((s) => s.server_name ?? s.name);
118372
- if (names.includes(MCP_SERVER_NAME)) {
118373
- await fetch(`${base}/mcp/configs/${MCP_SERVER_NAME}`, {
118374
- method: "DELETE",
118375
- signal: AbortSignal.timeout(5e3)
118376
- }).catch(() => {
118377
- });
118378
- }
118379
- }
118380
- } catch {
118381
- }
118382
- const body = {
118383
- configJson: JSON.stringify({
118384
- [MCP_SERVER_NAME]: {
118385
- command: process.execPath,
118386
- args: [script, panePublicUrl(), workspace],
118387
- env: { AGENT_PANE_SESSION_ID: "" }
118388
- }
118389
- })
118390
- };
118391
- const res = await fetch(`${base}/mcp/configs`, {
118392
- method: "POST",
118393
- headers: { "Content-Type": "application/json" },
118394
- body: JSON.stringify(body),
118395
- signal: AbortSignal.timeout(1e4)
118396
- });
118397
- if (res.status === 201) {
118398
- console.log(`[miniapp-mcp] gateway registered in workspace backend ${base} (workspace: ${workspace || "global"})`);
118399
- registered.add(key);
118400
- return true;
118401
- }
118402
- const text2 = await res.text();
118403
- if (res.status === 400 && /already exists/i.test(text2)) {
118404
- registered.add(key);
118405
- return true;
118406
- }
118407
- console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
118408
- return false;
118409
- } catch (err) {
118410
- console.warn(`[miniapp-mcp] registration error: ${err.message}`);
118411
- return false;
118412
- }
118413
- }
118414
- function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
118415
- const script = stdioScriptPath();
118416
- if (!script || !anyAppHasTools()) return null;
118417
- return [
118418
- // MCP tool calls must not ask for elicitation approval — nobody is
118419
- // watching an agent-driven session to approve (feature is stable/on).
118420
- "-c",
118421
- "features.tool_call_mcp_elicitation=false",
118422
- "-c",
118423
- `mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
118424
- "-c",
118425
- `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
118426
- ];
118427
- }
118428
-
118429
118909
  // src/claude/cli-orphans.ts
118430
118910
  import { execFile as execFile4 } from "node:child_process";
118431
118911
  var TERM_GRACE_MS = 2e3;
@@ -118523,6 +119003,11 @@ function reapOrphanCliProcesses(db2, deps = defaultDeps) {
118523
119003
  }
118524
119004
 
118525
119005
  // src/codex/codex-provider.ts
119006
+ var TERMINAL_TASK_TYPE = "background_terminal";
119007
+ function taskPollMs() {
119008
+ const ms = Number(process.env.AGENT_PANE_CODEX_TASK_POLL_MS);
119009
+ return Number.isFinite(ms) && ms > 0 ? ms : 5e3;
119010
+ }
118526
119011
  var sessionMap = /* @__PURE__ */ new Map();
118527
119012
  var startingThreads = /* @__PURE__ */ new Map();
118528
119013
  var ENDED_TURNS_KEPT = 20;
@@ -118566,22 +119051,34 @@ function sandboxType(config3) {
118566
119051
  return "workspace-write";
118567
119052
  }
118568
119053
  }
118569
- function normalizeItemType(type) {
118570
- const map2 = {
118571
- agentMessage: "agent_message",
118572
- userMessage: "user_message",
118573
- agentReasoning: "reasoning",
118574
- commandExecution: "command_execution",
118575
- fileChange: "file_change",
118576
- mcpToolCall: "mcp_tool_call",
118577
- webSearch: "web_search",
118578
- todoList: "todo_list",
118579
- error: "error"
119054
+ function sandboxPolicy(config3) {
119055
+ if (!config3 || !config3.sandboxMode && config3.networkAccessEnabled === void 0) return null;
119056
+ const networkAccess = config3.networkAccessEnabled === true;
119057
+ switch (sandboxType(config3)) {
119058
+ case "read-only":
119059
+ return { type: "readOnly", networkAccess };
119060
+ case "danger-full-access":
119061
+ return { type: "dangerFullAccess" };
119062
+ default:
119063
+ return { type: "workspaceWrite", networkAccess };
119064
+ }
119065
+ }
119066
+ function threadConfig(config3) {
119067
+ return config3?.webSearchMode ? { web_search: config3.webSearchMode } : void 0;
119068
+ }
119069
+ function threadParams(session, cwd) {
119070
+ const config3 = parseRuntimeConfig(session);
119071
+ return {
119072
+ cwd,
119073
+ approvalPolicy: "never",
119074
+ sandbox: sandboxType(config3),
119075
+ model: session.model ?? void 0,
119076
+ config: threadConfig(config3),
119077
+ ...threadInstructionParams(cwd)
118580
119078
  };
118581
- return map2[type] ?? type;
118582
119079
  }
118583
119080
  function shouldSkipItem(type) {
118584
- return type === "userMessage" || type === "user_message";
119081
+ return type === "userMessage" || type === "user_message" || type === "enteredReviewMode" || type === "exitedReviewMode";
118585
119082
  }
118586
119083
  function isEmptyReasoning(item) {
118587
119084
  const summary = Array.isArray(item.summary) ? item.summary : [];
@@ -118623,9 +119120,32 @@ function untrackProcess(pid) {
118623
119120
  } catch {
118624
119121
  }
118625
119122
  }
119123
+ function emptyThreadState() {
119124
+ return {
119125
+ threadId: "",
119126
+ sideThreads: /* @__PURE__ */ new Map(),
119127
+ loadingSide: /* @__PURE__ */ new Map(),
119128
+ codexThreads: /* @__PURE__ */ new Set(),
119129
+ webSearch: void 0,
119130
+ contextTokens: /* @__PURE__ */ new Map(),
119131
+ compactions: /* @__PURE__ */ new Map(),
119132
+ publishedContext: null,
119133
+ tasks: /* @__PURE__ */ new Map(),
119134
+ publishedTasks: "[]",
119135
+ taskTimer: null,
119136
+ refreshing: null,
119137
+ refreshAgain: false
119138
+ };
119139
+ }
118626
119140
  function getOrCreateThread(session) {
118627
119141
  const existing = sessionMap.get(session.id);
118628
- if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
119142
+ if (existing && !existing.client.isClosed()) {
119143
+ const webSearch = threadConfig(parseRuntimeConfig(session))?.web_search;
119144
+ if (webSearch === existing.webSearch || existing.turns.length > 0 || existing.tasks.size > 0) {
119145
+ return Promise.resolve(existing);
119146
+ }
119147
+ void retireEntry(existing, "keep");
119148
+ }
118629
119149
  const pending = startingThreads.get(session.id);
118630
119150
  if (pending) return pending;
118631
119151
  const started = startThread(session).finally(() => startingThreads.delete(session.id));
@@ -118652,7 +119172,7 @@ async function startThread(session) {
118652
119172
  client,
118653
119173
  // A hosted app-server has no cli_processes row: its host supervises it.
118654
119174
  pid: host ? void 0 : client.pid,
118655
- threadId: "",
119175
+ ...emptyThreadState(),
118656
119176
  turns: [],
118657
119177
  ended: /* @__PURE__ */ new Map(),
118658
119178
  resumedTurnIds: null,
@@ -118665,33 +119185,25 @@ async function startThread(session) {
118665
119185
  listen(entry);
118666
119186
  try {
118667
119187
  await client.initialize();
118668
- if (session.origin_app_id) {
118669
- autoApproveToolUserInput(client);
118670
- }
118671
- const config3 = parseRuntimeConfig(session);
118672
- const sandbox = sandboxType(config3);
118673
- const instructions = threadInstructionParams(cwd);
119188
+ autoApproveToolUserInput(client);
119189
+ const base = threadParams(session, cwd);
119190
+ entry.webSearch = base.config?.web_search;
118674
119191
  if (session.external_thread_id) {
119192
+ entry.threadId = session.external_thread_id;
119193
+ entry.codexThreads.add(entry.threadId);
118675
119194
  const result = await client.request("thread/resume", {
118676
119195
  threadId: session.external_thread_id,
118677
- cwd,
118678
- approvalPolicy: "never",
118679
- sandbox,
118680
- model: session.model ?? void 0,
118681
- ...instructions
119196
+ ...base
118682
119197
  });
118683
119198
  entry.threadId = result.thread.id;
118684
119199
  entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
118685
- noteHostThread(entry);
118686
119200
  } else {
118687
119201
  const result = await client.request("thread/start", {
118688
- cwd,
118689
- approvalPolicy: "never",
118690
- sandbox,
118691
- model: session.model ?? void 0,
118692
- ...instructions
119202
+ ...base,
119203
+ threadSource: PANE_THREAD_SOURCE
118693
119204
  });
118694
119205
  entry.threadId = result.thread.id;
119206
+ recordCodexThread(entry.threadId, session.id);
118695
119207
  const db2 = getDb();
118696
119208
  const now = (/* @__PURE__ */ new Date()).toISOString();
118697
119209
  db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
@@ -118699,8 +119211,9 @@ async function startThread(session) {
118699
119211
  now,
118700
119212
  session.id
118701
119213
  );
118702
- noteHostThread(entry);
118703
119214
  }
119215
+ entry.codexThreads.add(entry.threadId);
119216
+ noteHostThread(entry);
118704
119217
  } catch (err) {
118705
119218
  void retireEntry(entry, "keep");
118706
119219
  throw err;
@@ -118723,6 +119236,7 @@ function retireEntry(entry, left, error51 = "App-server closed") {
118723
119236
  }
118724
119237
  }
118725
119238
  }
119239
+ dropTasks(entry);
118726
119240
  entry.closing = entry.client.close().catch(() => {
118727
119241
  }).finally(async () => {
118728
119242
  untrackProcess(entry.pid);
@@ -118733,6 +119247,7 @@ function retireEntry(entry, left, error51 = "App-server closed") {
118733
119247
  function onClientClosed(entry, reason) {
118734
119248
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
118735
119249
  untrackProcess(entry.pid);
119250
+ if (!entry.closing) dropTasks(entry);
118736
119251
  if (entry.host && !entry.closing) void releaseCodexHost(entry.host);
118737
119252
  if (entry.closing || entry.turns.length === 0) return;
118738
119253
  let db2;
@@ -118765,22 +119280,45 @@ function endTurn(entry, active) {
118765
119280
  }
118766
119281
  function rememberEnded(entry, active) {
118767
119282
  if (!active.codexId) return;
118768
- entry.ended.set(active.codexId, active.id);
119283
+ rememberTurnId(entry, active.codexId, active.id);
119284
+ }
119285
+ function rememberTurnId(entry, codexId, paneTurnId) {
119286
+ entry.ended.set(codexId, paneTurnId);
118769
119287
  if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
118770
119288
  }
118771
- function liveTurnsOf(entry, codexId) {
118772
- if (!codexId) return entry.turns.slice(-1);
118773
- const known = entry.turns.filter((t) => t.codexId === codexId);
118774
- if (known.length > 0 || entry.ended.has(codexId)) return known;
118775
- const waiting = entry.turns.find((t) => t.codexId === null);
118776
- if (!waiting) return [];
118777
- waiting.codexId = codexId;
119289
+ function runsOn(active, threadId) {
119290
+ return active.codexThreadId === null || active.codexThreadId === threadId;
119291
+ }
119292
+ function bindCodexId(active, codexId) {
119293
+ active.codexId = codexId;
119294
+ active.resolveStarted(codexId);
118778
119295
  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);
119296
+ getDb().prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ? AND external_turn_id IS NULL").run(codexId, (/* @__PURE__ */ new Date()).toISOString(), active.id);
118780
119297
  } catch {
118781
119298
  }
119299
+ }
119300
+ function liveTurnsOf(entry, threadId, codexId) {
119301
+ if (!codexId) return entry.turns.filter((t) => runsOn(t, threadId)).slice(-1);
119302
+ const known = entry.turns.filter((t) => t.codexId === codexId);
119303
+ if (known.length > 0 || entry.ended.has(codexId)) return known;
119304
+ const waiting = entry.turns.find((t) => t.codexId === null && t.kind !== "review" && runsOn(t, threadId));
119305
+ if (!waiting) return [];
119306
+ bindCodexId(waiting, codexId);
118782
119307
  return [waiting];
118783
119308
  }
119309
+ function deferToReview(entry, threadId, codexId, replay) {
119310
+ if (!codexId) return false;
119311
+ const review = entry.turns.find((t) => t.kind === "review" && t.codexId === null && t.codexThreadId === threadId);
119312
+ if (!review) return false;
119313
+ review.early.push({ codexId, replay });
119314
+ return true;
119315
+ }
119316
+ function releaseEarly(entry, active) {
119317
+ for (const event of active.early.splice(0)) {
119318
+ if (event.codexId === active.codexId) event.replay();
119319
+ else rememberTurnId(entry, event.codexId, active.id);
119320
+ }
119321
+ }
118784
119322
  function noteContinued(active) {
118785
119323
  if (!active.resuming) return;
118786
119324
  active.resuming = false;
@@ -118857,10 +119395,11 @@ function listen(entry) {
118857
119395
  const on = (method, handle) => {
118858
119396
  entry.client.onNotification(method, (params) => {
118859
119397
  const p = params;
118860
- if (!p || p.threadId !== entry.threadId) return;
119398
+ if (!p || !entry.codexThreads.has(p.threadId)) return;
118861
119399
  handle(p);
118862
119400
  });
118863
119401
  };
119402
+ on("turn/started", (p) => onTurnStarted(entry, p));
118864
119403
  on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
118865
119404
  on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
118866
119405
  on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
@@ -118870,19 +119409,57 @@ function listen(entry) {
118870
119409
  on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
118871
119410
  entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
118872
119411
  }
119412
+ function onTurnStarted(entry, p) {
119413
+ const codexId = p.turn?.id;
119414
+ if (!codexId || entry.ended.has(codexId) || entry.turns.some((t) => t.codexId === codexId)) return;
119415
+ const onThread = entry.turns.filter((t) => t.codexThreadId === p.threadId);
119416
+ const compaction = onThread.find((t) => t.kind === "compact" && t.codexId === null);
119417
+ if (compaction) {
119418
+ bindCodexId(compaction, codexId);
119419
+ return;
119420
+ }
119421
+ const review = onThread.find((t) => t.kind === "review");
119422
+ if (review?.codexId) rememberTurnId(entry, codexId, review.id);
119423
+ else if (review) review.early.push({ codexId, replay: () => {
119424
+ } });
119425
+ }
118873
119426
  function onItem(entry, p, status, event) {
118874
- const [live] = liveTurnsOf(entry, p.turnId);
119427
+ const [live] = liveTurnsOf(entry, p.threadId, p.turnId);
118875
119428
  if (live) {
118876
119429
  if (!shouldSkipItem(p.item.type)) noteContinued(live);
118877
- handleItemEvent(p, entry.sessionId, live.id, status, event);
119430
+ handleItemEvent(p, entry.sessionId, live.id, status, event, compactionData(entry, live, p, event));
118878
119431
  return;
118879
119432
  }
118880
119433
  const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
118881
- if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
119434
+ if (ended) {
119435
+ handleItemEvent(p, entry.sessionId, ended, status, event, compactionData(entry, null, p, event));
119436
+ if (event === "item:completed" && [...entry.tasks.values()].some((t) => t.commandItemId === p.item.id)) {
119437
+ refreshBackgroundTasks(entry);
119438
+ }
119439
+ return;
119440
+ }
119441
+ deferToReview(entry, p.threadId, p.turnId, () => onItem(entry, p, status, event));
119442
+ }
119443
+ function compactionData(entry, live, p, event) {
119444
+ if (p.item.type !== "contextCompaction") return void 0;
119445
+ let compaction = entry.compactions.get(p.item.id);
119446
+ if (!compaction) {
119447
+ compaction = { threadId: p.threadId, pre: entry.contextTokens.get(p.threadId) ?? null, post: null, done: false };
119448
+ entry.compactions.set(p.item.id, compaction);
119449
+ if (entry.compactions.size > ENDED_TURNS_KEPT) {
119450
+ entry.compactions.delete(entry.compactions.keys().next().value);
119451
+ }
119452
+ }
119453
+ if (event === "item:completed") compaction.done = true;
119454
+ const post = compaction.done ? compaction.post : null;
119455
+ return { trigger: live?.kind === "compact" ? "manual" : "auto", pre_tokens: compaction.pre, post_tokens: post };
118882
119456
  }
118883
119457
  function onAgentMessageDelta(entry, p) {
118884
- const [live] = liveTurnsOf(entry, p.turnId);
118885
- if (!live) return;
119458
+ const [live] = liveTurnsOf(entry, p.threadId, p.turnId);
119459
+ if (!live) {
119460
+ deferToReview(entry, p.threadId, p.turnId, () => onAgentMessageDelta(entry, p));
119461
+ return;
119462
+ }
118886
119463
  noteContinued(live);
118887
119464
  const payload = { sessionId: entry.sessionId, turnId: live.id, itemId: p.itemId, delta: p.delta };
118888
119465
  if (entry.replaying) noteDelta(payload);
@@ -118890,7 +119467,10 @@ function onAgentMessageDelta(entry, p) {
118890
119467
  }
118891
119468
  function onTurnCompleted(entry, p) {
118892
119469
  const db2 = getDb();
118893
- for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
119470
+ const codexId = p.turn?.id ?? p.turnId;
119471
+ const lives = liveTurnsOf(entry, p.threadId, codexId);
119472
+ if (lives.length === 0 && deferToReview(entry, p.threadId, codexId, () => onTurnCompleted(entry, p))) return;
119473
+ for (const live of lives) {
118894
119474
  if (p.turn?.status === "interrupted") {
118895
119475
  cancelTurn(entry, live);
118896
119476
  } else if (p.turn?.status === "failed") {
@@ -118901,16 +119481,21 @@ function onTurnCompleted(entry, p) {
118901
119481
  completeTurn(db2, entry.sessionId, live.id, p.usage);
118902
119482
  }
118903
119483
  }
119484
+ refreshBackgroundTasks(entry);
118904
119485
  }
118905
119486
  function onTurnFailed(entry, p) {
118906
119487
  const db2 = getDb();
118907
- for (const live of liveTurnsOf(entry, p.turnId)) {
119488
+ const lives = liveTurnsOf(entry, p.threadId, p.turnId);
119489
+ if (lives.length === 0 && deferToReview(entry, p.threadId, p.turnId, () => onTurnFailed(entry, p))) return;
119490
+ for (const live of lives) {
118908
119491
  endTurn(entry, live);
118909
119492
  failTurn(db2, entry.sessionId, live.id, p.error.message);
118910
119493
  }
119494
+ refreshBackgroundTasks(entry);
118911
119495
  }
118912
119496
  function onTokenUsage(entry, p) {
118913
- const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
119497
+ noteContext(entry, p);
119498
+ const turnId = liveTurnsOf(entry, p.threadId, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
118914
119499
  if (!turnId) return;
118915
119500
  const usage = mapTokenUsage(p.tokenUsage.total);
118916
119501
  const db2 = getDb();
@@ -118918,6 +119503,30 @@ function onTokenUsage(entry, p) {
118918
119503
  db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
118919
119504
  broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
118920
119505
  }
119506
+ function noteContext(entry, p) {
119507
+ const last = p.tokenUsage?.last;
119508
+ if (!last) return;
119509
+ const tokens2 = Math.max(0, (last.totalTokens ?? 0) - (last.reasoningOutputTokens ?? 0));
119510
+ entry.contextTokens.set(p.threadId, tokens2);
119511
+ for (const compaction of entry.compactions.values()) {
119512
+ if (compaction.threadId === p.threadId && !compaction.done) compaction.post = tokens2;
119513
+ }
119514
+ const window = p.tokenUsage.modelContextWindow;
119515
+ if (p.threadId !== entry.threadId || !window || window <= 0) return;
119516
+ const usage = {
119517
+ totalTokens: tokens2,
119518
+ contextWindow: window,
119519
+ percentage: Math.min(100, Math.round(tokens2 / window * 100))
119520
+ };
119521
+ const json2 = JSON.stringify(usage);
119522
+ if (json2 === entry.publishedContext) return;
119523
+ entry.publishedContext = json2;
119524
+ broadcast("turn:contextUsage", { sessionId: entry.sessionId, ...usage });
119525
+ try {
119526
+ getDb().prepare("UPDATE sessions SET context_usage = ? WHERE id = ?").run(json2, entry.sessionId);
119527
+ } catch {
119528
+ }
119529
+ }
118921
119530
  function turnAttachments2(turn) {
118922
119531
  const raw = turn.attachments;
118923
119532
  if (!raw) return [];
@@ -118931,16 +119540,14 @@ function turnAttachments2(turn) {
118931
119540
  }
118932
119541
  function buildCodexInput(turn) {
118933
119542
  const input = [{ type: "text", text: turn.user_prompt }];
119543
+ const saved = /* @__PURE__ */ new Set();
118934
119544
  for (const att of turnAttachments2(turn)) {
118935
119545
  if (!att || typeof att.data !== "string" || !att.data) continue;
118936
119546
  const type = String(att.media_type ?? "").toLowerCase();
118937
119547
  if (type.startsWith("image/")) {
118938
119548
  input.push({ type: "image", url: `data:${type};base64,${att.data}` });
118939
119549
  } else if (type === "application/pdf") {
118940
- input.push({
118941
- type: "text",
118942
- text: `[Attachment ${att.name} (PDF) was not sent: Codex does not accept PDF files.]`
118943
- });
119550
+ input.push({ type: "text", text: pdfNote(turn, att, saved) });
118944
119551
  } else {
118945
119552
  const decoded = Buffer.from(att.data, "base64").toString("utf-8");
118946
119553
  input.push({ type: "text", text: `
@@ -118951,17 +119558,76 @@ ${decoded}
118951
119558
  }
118952
119559
  return input;
118953
119560
  }
118954
- async function runTurn(session, turn, entry, input, resume) {
119561
+ function pdfNote(turn, att, saved) {
119562
+ try {
119563
+ const file2 = saveAttachmentFile(turn.session_id, turn.id, att.name || "attachment.pdf", att.data, saved);
119564
+ return `[The user attached the PDF "${att.name}". Codex cannot take PDF input, so it is saved at ${file2}; read it from there.]`;
119565
+ } catch (err) {
119566
+ return `[Attachment ${att.name} (PDF) was not sent: it could not be saved for Codex (${err.message}).]`;
119567
+ }
119568
+ }
119569
+ var CODEX_COMMANDS = [
119570
+ { name: "compact", description: "Summarize the conversation to free up the model's context" },
119571
+ {
119572
+ name: "review",
119573
+ description: "Review the uncommitted changes, the changes against a base branch, a commit, or by your instructions",
119574
+ argumentHint: "[base <branch> | commit <sha> | <instructions>]"
119575
+ }
119576
+ ];
119577
+ function parseCodexCommand(prompt) {
119578
+ const match = /^\/(compact|review)(?:\s+([\s\S]*))?$/.exec(prompt.trim());
119579
+ if (!match) return null;
119580
+ const args = (match[2] ?? "").trim();
119581
+ if (match[1] === "compact") return args ? null : { kind: "compact" };
119582
+ if (!args) return { kind: "review", target: { type: "uncommittedChanges" } };
119583
+ const base = /^base\s+(\S+)$/i.exec(args);
119584
+ if (base) return { kind: "review", target: { type: "baseBranch", branch: base[1] } };
119585
+ const commit = /^commit\s+([0-9a-f]{4,40})$/i.exec(args);
119586
+ if (commit) return { kind: "review", target: { type: "commit", sha: commit[1] } };
119587
+ return { kind: "review", target: { type: "custom", instructions: args } };
119588
+ }
119589
+ function turnRequest(turn) {
119590
+ return parseCodexCommand(turn.user_prompt) ?? { kind: "prompt", input: buildCodexInput(turn) };
119591
+ }
119592
+ async function sendTurnRequest(session, entry, threadId, request) {
119593
+ if (request.kind === "compact") {
119594
+ await entry.client.request("thread/compact/start", { threadId });
119595
+ return null;
119596
+ }
119597
+ if (request.kind === "review") {
119598
+ const result2 = await entry.client.request("review/start", {
119599
+ threadId,
119600
+ target: request.target,
119601
+ delivery: "inline"
119602
+ });
119603
+ return result2.turn.id;
119604
+ }
119605
+ const policy = sandboxPolicy(parseRuntimeConfig(session));
119606
+ const result = await entry.client.request("turn/start", {
119607
+ threadId,
119608
+ input: request.input,
119609
+ approvalPolicy: "never",
119610
+ ...policy ? { sandboxPolicy: policy } : {},
119611
+ model: session.model ?? void 0,
119612
+ effort: session.model_reasoning_effort ?? void 0
119613
+ });
119614
+ return result.turn.id;
119615
+ }
119616
+ async function runTurn(session, turn, entry, codexThreadId, request, resume) {
118955
119617
  const db2 = getDb();
118956
- const sandbox = sandboxType(parseRuntimeConfig(session));
118957
119618
  let resolveStarted;
119619
+ const started = new Promise((resolve) => {
119620
+ resolveStarted = resolve;
119621
+ });
118958
119622
  const active = {
118959
119623
  id: turn.id,
118960
119624
  discussionThreadId: turn.thread_id ?? null,
119625
+ codexThreadId,
119626
+ kind: request.kind,
118961
119627
  codexId: null,
118962
- started: new Promise((resolve) => {
118963
- resolveStarted = resolve;
118964
- }),
119628
+ started,
119629
+ resolveStarted,
119630
+ early: [],
118965
119631
  done: false,
118966
119632
  resuming: resume,
118967
119633
  hostOffset: null
@@ -118969,22 +119635,18 @@ async function runTurn(session, turn, entry, input, resume) {
118969
119635
  entry.turns.push(active);
118970
119636
  bindHostTurn(entry, active);
118971
119637
  try {
118972
- const result = await entry.client.request("turn/start", {
118973
- threadId: entry.threadId,
118974
- input,
118975
- approvalPolicy: "never",
118976
- sandbox: { type: sandbox },
118977
- model: session.model ?? void 0,
118978
- effort: session.model_reasoning_effort ?? void 0
118979
- });
118980
- active.codexId = result.turn.id;
118981
- if (active.done) rememberEnded(entry, active);
118982
- db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
118983
- result.turn.id,
118984
- (/* @__PURE__ */ new Date()).toISOString(),
118985
- turn.id
118986
- );
118987
- resolveStarted(result.turn.id);
119638
+ const codexId = await sendTurnRequest(session, entry, codexThreadId, request);
119639
+ if (codexId) {
119640
+ active.codexId = codexId;
119641
+ if (active.done) rememberEnded(entry, active);
119642
+ db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
119643
+ codexId,
119644
+ (/* @__PURE__ */ new Date()).toISOString(),
119645
+ turn.id
119646
+ );
119647
+ resolveStarted(codexId);
119648
+ releaseEarly(entry, active);
119649
+ }
118988
119650
  } catch (err) {
118989
119651
  const message = err.message;
118990
119652
  const settled = active.done;
@@ -118998,8 +119660,10 @@ async function runTurn(session, turn, entry, input, resume) {
118998
119660
  async function startTurn2(session, turn) {
118999
119661
  const db2 = getDb();
119000
119662
  let entry;
119663
+ let codexThreadId;
119001
119664
  try {
119002
119665
  entry = await getOrCreateThread(session);
119666
+ codexThreadId = turn.thread_id ? await sideThreadFor(entry, session, turn.thread_id) : entry.threadId;
119003
119667
  } catch (err) {
119004
119668
  failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
119005
119669
  return;
@@ -119009,16 +119673,60 @@ async function startTurn2(session, turn) {
119009
119673
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
119010
119674
  setSessionStatus(db2, session.id, 1, "running", now);
119011
119675
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
119012
- await runTurn(session, turn, entry, buildCodexInput(turn), false);
119676
+ await runTurn(session, turn, entry, codexThreadId, turnRequest(turn), false);
119677
+ }
119678
+ function sideThreadFor(entry, session, discussionThreadId) {
119679
+ const loaded = entry.sideThreads.get(discussionThreadId);
119680
+ if (loaded) return Promise.resolve(loaded);
119681
+ const pending = entry.loadingSide.get(discussionThreadId);
119682
+ if (pending) return pending;
119683
+ const loading = loadSideThread(entry, session, discussionThreadId).finally(
119684
+ () => entry.loadingSide.delete(discussionThreadId)
119685
+ );
119686
+ entry.loadingSide.set(discussionThreadId, loading);
119687
+ return loading;
119688
+ }
119689
+ async function loadSideThread(entry, session, discussionThreadId) {
119690
+ const db2 = getDb();
119691
+ const row = db2.prepare("SELECT external_thread_id FROM discussion_threads WHERE id = ?").get(discussionThreadId);
119692
+ const base = threadParams(session, session.cwd ?? process.cwd());
119693
+ let codexThreadId;
119694
+ if (row?.external_thread_id) {
119695
+ entry.codexThreads.add(row.external_thread_id);
119696
+ const result = await entry.client.request("thread/resume", {
119697
+ threadId: row.external_thread_id,
119698
+ ...base
119699
+ });
119700
+ codexThreadId = result.thread.id;
119701
+ } else {
119702
+ const result = await entry.client.request("thread/start", {
119703
+ ...base,
119704
+ threadSource: PANE_THREAD_SOURCE
119705
+ });
119706
+ codexThreadId = result.thread.id;
119707
+ recordCodexThread(codexThreadId, session.id);
119708
+ db2.prepare("UPDATE discussion_threads SET external_thread_id = ? WHERE id = ?").run(
119709
+ codexThreadId,
119710
+ discussionThreadId
119711
+ );
119712
+ }
119713
+ entry.sideThreads.set(discussionThreadId, codexThreadId);
119714
+ entry.codexThreads.add(codexThreadId);
119715
+ return codexThreadId;
119013
119716
  }
119014
- function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
119717
+ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent, extraData) {
119015
119718
  const db2 = getDb();
119016
119719
  const now = (/* @__PURE__ */ new Date()).toISOString();
119017
119720
  const item = params.item;
119721
+ if (item.type === "exitedReviewMode" && typeof item.review === "string" && item.review.trim()) {
119722
+ db2.prepare(
119723
+ "UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ? AND (agent_response IS NULL OR agent_response = '')"
119724
+ ).run(item.review, now, turnId);
119725
+ }
119018
119726
  if (shouldSkipItem(item.type)) return;
119019
119727
  if ((item.type === "reasoning" || item.type === "agentReasoning") && isEmptyReasoning(item)) return;
119020
- const data = mapItemData(item);
119021
- const normalizedType = normalizeItemType(item.type);
119728
+ const data = { ...mapItemData(item), ...extraData };
119729
+ const normalizedType = mapItemType(item);
119022
119730
  const result = db2.prepare("UPDATE items SET data = ?, status = ?, updated_at = ? WHERE external_item_id = ? AND turn_id = ?").run(JSON.stringify(data), status, now, item.id, turnId);
119023
119731
  let itemId;
119024
119732
  let createdAt;
@@ -119089,7 +119797,9 @@ function abortOrphanTurn(sessionId, threadId) {
119089
119797
  }
119090
119798
  }
119091
119799
  var END_COMMANDS_WAIT_MS = 5e3;
119092
- async function endTurnCommands(entry, turnId) {
119800
+ async function endTurnCommands(entry, active) {
119801
+ const turnId = active.id;
119802
+ const threadId = active.codexThreadId ?? entry.threadId;
119093
119803
  try {
119094
119804
  const rows = getDb().prepare(
119095
119805
  "SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
@@ -119099,13 +119809,13 @@ async function endTurnCommands(entry, turnId) {
119099
119809
  let cursor = null;
119100
119810
  do {
119101
119811
  const page = await entry.client.request("thread/backgroundTerminals/list", {
119102
- threadId: entry.threadId,
119812
+ threadId,
119103
119813
  cursor
119104
119814
  });
119105
119815
  for (const terminal of page.data) {
119106
119816
  if (!started.has(terminal.itemId)) continue;
119107
119817
  await entry.client.request("thread/backgroundTerminals/terminate", {
119108
- threadId: entry.threadId,
119818
+ threadId,
119109
119819
  processId: terminal.processId
119110
119820
  });
119111
119821
  }
@@ -119124,7 +119834,7 @@ async function interruptTurn(sessionId, threadId) {
119124
119834
  if (codexId && !target.done) {
119125
119835
  try {
119126
119836
  await entry.client.request("turn/interrupt", {
119127
- threadId: entry.threadId,
119837
+ threadId: target.codexThreadId ?? entry.threadId,
119128
119838
  turnId: codexId
119129
119839
  });
119130
119840
  stopped = true;
@@ -119137,7 +119847,10 @@ async function interruptTurn(sessionId, threadId) {
119137
119847
  cancelTurn(entry, target);
119138
119848
  if (!stopped) void retireEntry(entry, "fail");
119139
119849
  }
119140
- if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
119850
+ if (stopped) {
119851
+ await within(endTurnCommands(entry, target), END_COMMANDS_WAIT_MS);
119852
+ refreshBackgroundTasks(entry);
119853
+ }
119141
119854
  if (live || stopped) return true;
119142
119855
  }
119143
119856
  return abortOrphanTurn(sessionId, threadId);
@@ -119146,8 +119859,31 @@ function clearThread(sessionId) {
119146
119859
  const entry = sessionMap.get(sessionId);
119147
119860
  if (entry) void retireEntry(entry, "cancel");
119148
119861
  }
119862
+ function clearThreadBranch(sessionId, threadId) {
119863
+ const entry = sessionMap.get(sessionId);
119864
+ if (!entry) return;
119865
+ for (const active of entry.turns.filter((t) => t.discussionThreadId === threadId)) {
119866
+ if (active.codexId) {
119867
+ void entry.client.request("turn/interrupt", {
119868
+ threadId: active.codexThreadId ?? entry.threadId,
119869
+ turnId: active.codexId
119870
+ }).catch(() => {
119871
+ });
119872
+ }
119873
+ endTurn(entry, active);
119874
+ }
119875
+ const codexThreadId = entry.sideThreads.get(threadId);
119876
+ entry.sideThreads.delete(threadId);
119877
+ if (!codexThreadId || codexThreadId === entry.threadId) return;
119878
+ entry.codexThreads.delete(codexThreadId);
119879
+ void entry.client.request("thread/unsubscribe", { threadId: codexThreadId }).catch(() => {
119880
+ }).finally(() => refreshBackgroundTasks(entry));
119881
+ }
119149
119882
  function clearAllThreads() {
119150
- for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
119883
+ for (const entry of [...sessionMap.values()]) {
119884
+ stopTaskPolling(entry);
119885
+ void retireEntry(entry, "keep");
119886
+ }
119151
119887
  sessionMap.clear();
119152
119888
  startingThreads.clear();
119153
119889
  titleGenerating.clear();
@@ -119173,7 +119909,8 @@ async function generateTitleAsync(sessionId, userPrompt, agentResponse) {
119173
119909
  const initResult = await client.request("thread/start", {
119174
119910
  cwd: process.cwd(),
119175
119911
  approvalPolicy: "never",
119176
- sandbox: "read-only"
119912
+ sandbox: "read-only",
119913
+ ephemeral: true
119177
119914
  });
119178
119915
  const threadId = initResult.thread.id;
119179
119916
  const truncatedPrompt = userPrompt.slice(0, 500);
@@ -119214,7 +119951,7 @@ Agent responded: "${truncatedResponse}"`;
119214
119951
  threadId,
119215
119952
  input: [{ type: "text", text: titlePrompt }],
119216
119953
  approvalPolicy: "never",
119217
- sandbox: { type: "read-only" }
119954
+ sandboxPolicy: { type: "readOnly" }
119218
119955
  });
119219
119956
  const title = await titlePromise;
119220
119957
  clearTimeout(timeout);
@@ -119241,7 +119978,8 @@ async function summarizeCodexThread(session, _thread, transcript, directives) {
119241
119978
  const initResult = await client.request("thread/start", {
119242
119979
  cwd: session.cwd ?? process.cwd(),
119243
119980
  approvalPolicy: "never",
119244
- sandbox: "read-only"
119981
+ sandbox: "read-only",
119982
+ ephemeral: true
119245
119983
  });
119246
119984
  const threadId = initResult.thread.id;
119247
119985
  const directiveLine = directives.trim() ? `
@@ -119286,7 +120024,7 @@ Produce a concise summary of the discussion that preserves: concrete findings, f
119286
120024
  threadId,
119287
120025
  input: [{ type: "text", text: summaryPrompt }],
119288
120026
  approvalPolicy: "never",
119289
- sandbox: { type: "read-only" }
120027
+ sandboxPolicy: { type: "readOnly" }
119290
120028
  });
119291
120029
  const summary = await summaryPromise;
119292
120030
  clearTimeout(timeout);
@@ -119328,6 +120066,230 @@ async function getModels() {
119328
120066
  return [];
119329
120067
  }
119330
120068
  }
120069
+ async function getCommands() {
120070
+ return CODEX_COMMANDS;
120071
+ }
120072
+ function forkPoint(db2, sessionId, target) {
120073
+ const row = db2.prepare(
120074
+ `SELECT external_turn_id FROM turns
120075
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
120076
+ AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
120077
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`
120078
+ ).get(sessionId, target.id, target.created_at);
120079
+ return row?.external_turn_id ?? null;
120080
+ }
120081
+ async function forkSession(session, targetTurn) {
120082
+ const threadId = session.external_thread_id;
120083
+ if (!threadId) return null;
120084
+ const lastTurnId = forkPoint(getDb(), session.id, targetTurn);
120085
+ if (!lastTurnId) return null;
120086
+ const cwd = session.cwd ?? process.cwd();
120087
+ const client = new AppServerClient({ cwd });
120088
+ try {
120089
+ await client.initialize();
120090
+ const fork = (range) => client.request("thread/fork", {
120091
+ threadId,
120092
+ ...range,
120093
+ cwd,
120094
+ excludeTurns: true,
120095
+ threadSource: PANE_THREAD_SOURCE
120096
+ });
120097
+ let result;
120098
+ try {
120099
+ result = await fork({ lastTurnId });
120100
+ } catch (err) {
120101
+ const range = await client.request("thread/read", { threadId, includeTurns: true }).then(({ thread }) => forkThroughReview(thread.turns ?? [], lastTurnId), () => void 0);
120102
+ if (!range) throw err;
120103
+ result = await fork(range);
120104
+ }
120105
+ recordCodexThread(result.thread.id, session.id);
120106
+ return result.thread.id;
120107
+ } finally {
120108
+ await client.close();
120109
+ }
120110
+ }
120111
+ function refreshBackgroundTasks(entry) {
120112
+ if (entry.refreshing) {
120113
+ entry.refreshAgain = true;
120114
+ return;
120115
+ }
120116
+ entry.refreshing = (async () => {
120117
+ do {
120118
+ entry.refreshAgain = false;
120119
+ await refreshTasksOnce(entry);
120120
+ } while (entry.refreshAgain && isCurrent(entry));
120121
+ })().catch(
120122
+ (err) => console.warn(`[codex] could not list the background commands of ${entry.sessionId}: ${err.message}`)
120123
+ ).finally(() => {
120124
+ entry.refreshing = null;
120125
+ });
120126
+ }
120127
+ async function refreshTasksOnce(entry) {
120128
+ if (!isCurrent(entry) || entry.replaying) return;
120129
+ const live = /* @__PURE__ */ new Map();
120130
+ const unknown2 = /* @__PURE__ */ new Set();
120131
+ for (const codexThreadId of entry.codexThreads) {
120132
+ let cursor = null;
120133
+ try {
120134
+ do {
120135
+ const page = await entry.client.request("thread/backgroundTerminals/list", {
120136
+ threadId: codexThreadId,
120137
+ cursor
120138
+ });
120139
+ for (const terminal of page.data) {
120140
+ live.set(terminal.processId, { codexThreadId, itemId: terminal.itemId, command: terminal.command });
120141
+ }
120142
+ cursor = page.nextCursor;
120143
+ } while (cursor);
120144
+ } catch {
120145
+ unknown2.add(codexThreadId);
120146
+ }
120147
+ }
120148
+ if (!isCurrent(entry)) return;
120149
+ for (const [taskId, task] of entry.tasks) {
120150
+ if (live.has(taskId) || unknown2.has(task.codexThreadId)) continue;
120151
+ entry.tasks.delete(taskId);
120152
+ closeTaskItem(entry.sessionId, task, task.stopped ? "stopped" : "completed");
120153
+ }
120154
+ for (const [processId, terminal] of live) {
120155
+ if (entry.tasks.has(processId)) continue;
120156
+ const turnId = commandTurnOf(entry.sessionId, terminal.itemId);
120157
+ if (turnId && entry.turns.some((t) => t.id === turnId)) continue;
120158
+ const task = {
120159
+ info: { task_id: processId, task_type: TERMINAL_TASK_TYPE, description: terminal.command },
120160
+ codexThreadId: terminal.codexThreadId,
120161
+ processId,
120162
+ commandItemId: terminal.itemId,
120163
+ item: null,
120164
+ stopped: false
120165
+ };
120166
+ if (turnId) openTaskItem(entry.sessionId, turnId, task);
120167
+ entry.tasks.set(processId, task);
120168
+ }
120169
+ publishTasks(entry);
120170
+ }
120171
+ function publishTasks(entry) {
120172
+ const tasks = [...entry.tasks.values()].map((task) => task.info);
120173
+ const json2 = JSON.stringify(tasks);
120174
+ if (json2 !== entry.publishedTasks) {
120175
+ entry.publishedTasks = json2;
120176
+ broadcast("background_tasks", { sessionId: entry.sessionId, tasks });
120177
+ }
120178
+ if (tasks.length > 0 && !entry.taskTimer && isCurrent(entry)) {
120179
+ entry.taskTimer = setInterval(() => refreshBackgroundTasks(entry), taskPollMs());
120180
+ entry.taskTimer.unref?.();
120181
+ } else if (tasks.length === 0) {
120182
+ stopTaskPolling(entry);
120183
+ }
120184
+ }
120185
+ function stopTaskPolling(entry) {
120186
+ if (!entry.taskTimer) return;
120187
+ clearInterval(entry.taskTimer);
120188
+ entry.taskTimer = null;
120189
+ }
120190
+ function dropTasks(entry) {
120191
+ stopTaskPolling(entry);
120192
+ for (const task of entry.tasks.values()) closeTaskItem(entry.sessionId, task, "stopped");
120193
+ entry.tasks.clear();
120194
+ publishTasks(entry);
120195
+ }
120196
+ function commandTurnOf(sessionId, itemId) {
120197
+ try {
120198
+ const row = getDb().prepare(
120199
+ `SELECT i.turn_id FROM items i JOIN turns t ON t.id = i.turn_id
120200
+ WHERE t.session_id = ? AND i.external_item_id = ? ORDER BY i.created_at DESC LIMIT 1`
120201
+ ).get(sessionId, itemId);
120202
+ return row?.turn_id ?? null;
120203
+ } catch {
120204
+ return null;
120205
+ }
120206
+ }
120207
+ function openTaskItem(sessionId, turnId, task) {
120208
+ try {
120209
+ const db2 = getDb();
120210
+ const now = (/* @__PURE__ */ new Date()).toISOString();
120211
+ const item = {
120212
+ id: v4_default(),
120213
+ turn_id: turnId,
120214
+ external_item_id: `terminal-${task.processId}-${task.commandItemId}`,
120215
+ type: "background_task",
120216
+ data: {
120217
+ task_id: task.processId,
120218
+ description: task.info.description,
120219
+ task_type: TERMINAL_TASK_TYPE,
120220
+ status: "running",
120221
+ output: ""
120222
+ },
120223
+ status: "in_progress",
120224
+ created_at: now,
120225
+ updated_at: now
120226
+ };
120227
+ db2.prepare(
120228
+ "INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
120229
+ ).run(item.id, item.turn_id, item.external_item_id, item.type, JSON.stringify(item.data), item.status, now, now);
120230
+ task.item = { id: item.id, turnId, createdAt: now };
120231
+ broadcast("item:started", { sessionId, turnId, item });
120232
+ } catch (err) {
120233
+ console.warn(`[codex] could not record background command ${task.processId}: ${err.message}`);
120234
+ }
120235
+ }
120236
+ var TASK_OUTPUT_MAX = 2e4;
120237
+ function closeTaskItem(sessionId, task, status) {
120238
+ const ref = task.item;
120239
+ if (!ref) return;
120240
+ try {
120241
+ const db2 = getDb();
120242
+ const command = db2.prepare("SELECT data FROM items WHERE turn_id = ? AND external_item_id = ?").get(ref.turnId, task.commandItemId);
120243
+ let output = "";
120244
+ try {
120245
+ output = String(JSON.parse(command?.data ?? "{}").aggregated_output ?? "");
120246
+ } catch {
120247
+ }
120248
+ const data = {
120249
+ task_id: task.processId,
120250
+ description: task.info.description,
120251
+ task_type: TERMINAL_TASK_TYPE,
120252
+ status,
120253
+ output: output.length > TASK_OUTPUT_MAX ? output.slice(-TASK_OUTPUT_MAX) : output
120254
+ };
120255
+ const now = (/* @__PURE__ */ new Date()).toISOString();
120256
+ db2.prepare("UPDATE items SET data = ?, status = 'completed', updated_at = ? WHERE id = ?").run(
120257
+ JSON.stringify(data),
120258
+ now,
120259
+ ref.id
120260
+ );
120261
+ const item = {
120262
+ id: ref.id,
120263
+ turn_id: ref.turnId,
120264
+ external_item_id: `terminal-${task.processId}-${task.commandItemId}`,
120265
+ type: "background_task",
120266
+ data,
120267
+ status: "completed",
120268
+ created_at: ref.createdAt,
120269
+ updated_at: now
120270
+ };
120271
+ broadcast("item:completed", { sessionId, turnId: ref.turnId, item });
120272
+ } catch {
120273
+ }
120274
+ }
120275
+ async function stopTask(sessionId, taskId) {
120276
+ const entry = sessionMap.get(sessionId);
120277
+ const task = entry?.tasks.get(taskId);
120278
+ if (!entry || !task) throw new Error(`No running background command ${taskId} in this session`);
120279
+ task.stopped = true;
120280
+ await entry.client.request("thread/backgroundTerminals/terminate", {
120281
+ threadId: task.codexThreadId,
120282
+ processId: task.processId
120283
+ });
120284
+ refreshBackgroundTasks(entry);
120285
+ }
120286
+ function listBackgroundTasks() {
120287
+ const bySession = {};
120288
+ for (const entry of sessionMap.values()) {
120289
+ if (entry.tasks.size > 0) bySession[entry.sessionId] = [...entry.tasks.values()].map((task) => task.info);
120290
+ }
120291
+ return bySession;
120292
+ }
119331
120293
  async function shutdown() {
119332
120294
  let db2 = null;
119333
120295
  try {
@@ -119363,12 +120325,13 @@ async function reapOrphans() {
119363
120325
  async function resumeInterruptedTurn(session, turn, _opts) {
119364
120326
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
119365
120327
  const entry = await getOrCreateThread(session);
119366
- if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
120328
+ if (entry.turns.some((t) => !t.discussionThreadId)) throw new Error("Another turn is running in this session");
119367
120329
  if (!isTurnLive(getDb(), turn.id)) return;
120330
+ const command = parseCodexCommand(turn.user_prompt);
119368
120331
  const codexId = turn.external_turn_id;
119369
120332
  const inThread = !!codexId && (!!entry.resumedTurnIds?.has(codexId) || entry.ended.has(codexId));
119370
- const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
119371
- await runTurn(session, turn, entry, input, true);
120333
+ const request = command ?? (inThread ? { kind: "prompt", input: [{ type: "text", text: CODEX_CONTINUE_PROMPT }] } : { kind: "prompt", input: buildCodexInput(turn) });
120334
+ await runTurn(session, turn, entry, entry.threadId, request, true);
119372
120335
  }
119373
120336
  function hostFor(sessionId, cwd, options, onDirect) {
119374
120337
  if (!hostsEnabledFor("codex")) return null;
@@ -119435,38 +120398,65 @@ function maybeRetire(entry) {
119435
120398
  }
119436
120399
  function detachEntry(entry) {
119437
120400
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
120401
+ stopTaskPolling(entry);
119438
120402
  entry.closing = Promise.resolve();
119439
120403
  entry.client.detach();
119440
120404
  entry.host?.proc.detach();
119441
120405
  }
119442
120406
  function runningTurns(db2, sessionId) {
119443
120407
  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"
120408
+ "SELECT id, thread_id, external_turn_id, resume_state, user_prompt FROM turns WHERE session_id = ? AND status = 'running' ORDER BY created_at, rowid"
119445
120409
  ).all(sessionId);
119446
120410
  }
120411
+ function storedContextTokens(db2, sessionId) {
120412
+ const row = db2.prepare("SELECT context_usage FROM sessions WHERE id = ?").get(sessionId);
120413
+ try {
120414
+ const tokens2 = row?.context_usage ? JSON.parse(row.context_usage).totalTokens : null;
120415
+ return typeof tokens2 === "number" ? tokens2 : null;
120416
+ } catch {
120417
+ return null;
120418
+ }
120419
+ }
119447
120420
  function adoptedEntry(db2, session, threadId, client, host) {
119448
- const turns = runningTurns(db2, session.id).map(
119449
- (row) => ({
120421
+ const sideRows = db2.prepare(
120422
+ "SELECT id, external_thread_id FROM discussion_threads WHERE session_id = ? AND external_thread_id IS NOT NULL"
120423
+ ).all(session.id);
120424
+ const sideOf = new Map(sideRows.map((row) => [row.id, row.external_thread_id]));
120425
+ const turns = runningTurns(db2, session.id).map((row) => {
120426
+ const kind = parseCodexCommand(row.user_prompt)?.kind ?? "prompt";
120427
+ return {
119450
120428
  id: row.id,
119451
120429
  discussionThreadId: row.thread_id,
120430
+ codexThreadId: row.thread_id ? sideOf.get(row.thread_id) ?? null : threadId,
120431
+ // A review whose answer went to the previous daemon takes the first id it sees.
120432
+ kind: kind === "review" && !row.external_turn_id ? "prompt" : kind,
119452
120433
  codexId: row.external_turn_id,
119453
120434
  started: Promise.resolve(row.external_turn_id),
120435
+ resolveStarted: () => {
120436
+ },
120437
+ early: [],
119454
120438
  done: false,
119455
120439
  resuming: row.resume_state === "resuming",
119456
120440
  hostOffset: null
119457
- })
119458
- );
120441
+ };
120442
+ });
119459
120443
  const ended = /* @__PURE__ */ new Map();
119460
120444
  const endedRows = db2.prepare(
119461
120445
  "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
120446
  ).all(session.id, ENDED_TURNS_KEPT);
119463
120447
  for (const row of endedRows.reverse()) ended.set(row.external_turn_id, row.id);
119464
120448
  const known = db2.prepare("SELECT external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL").all(session.id);
120449
+ const state = emptyThreadState();
120450
+ const fill = storedContextTokens(db2, session.id);
119465
120451
  return {
119466
120452
  sessionId: session.id,
119467
120453
  client,
119468
120454
  pid: void 0,
120455
+ ...state,
119469
120456
  threadId,
120457
+ codexThreads: /* @__PURE__ */ new Set([threadId, ...sideOf.values()]),
120458
+ contextTokens: new Map(fill === null ? [] : [[threadId, fill]]),
120459
+ webSearch: threadConfig(parseRuntimeConfig(session))?.web_search,
119470
120460
  turns,
119471
120461
  ended,
119472
120462
  // A turn resumed on this app-server later continues with the continue
@@ -119539,7 +120529,7 @@ var codexHostAdopter = {
119539
120529
  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
120530
  sessionMap.set(session.id, entry);
119541
120531
  listen(entry);
119542
- if (session.origin_app_id) autoApproveToolUserInput(client);
120532
+ autoApproveToolUserInput(client);
119543
120533
  await replayDone(client, `session ${session.id}`);
119544
120534
  entry.replaying = false;
119545
120535
  if (!isCurrent(entry)) {
@@ -119550,6 +120540,7 @@ var codexHostAdopter = {
119550
120540
  recomputeSessionRunning(db2, session.id);
119551
120541
  broadcast("session:resync", { sessionId: session.id });
119552
120542
  resendStreams(session.id);
120543
+ refreshBackgroundTasks(entry);
119553
120544
  const running = entry.turns.map((t) => ({ id: t.id, threadId: t.discussionThreadId }));
119554
120545
  console.log(
119555
120546
  `[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}` : ""}`
@@ -119590,8 +120581,13 @@ var codexProvider = {
119590
120581
  startTurn: startTurn2,
119591
120582
  interruptTurn,
119592
120583
  clearThread,
120584
+ clearThreadBranch,
119593
120585
  clearAllThreads,
119594
120586
  getModels,
120587
+ getCommands,
120588
+ forkSession,
120589
+ stopTask,
120590
+ listBackgroundTasks,
119595
120591
  summarizeThread: summarizeCodexThread,
119596
120592
  resumeInterruptedTurn,
119597
120593
  reapOrphans,
@@ -120142,7 +121138,7 @@ function dropBackgroundTasks(sessionId, entry) {
120142
121138
  entry.backgroundTasks = [];
120143
121139
  publishBackgroundTasks(sessionId);
120144
121140
  }
120145
- function listBackgroundTasks() {
121141
+ function listBackgroundTasks2() {
120146
121142
  const bySession = {};
120147
121143
  for (const [key, entry] of sessionMap2) {
120148
121144
  if (!entry.backgroundTasks?.length) continue;
@@ -121173,7 +122169,7 @@ function clearThread2(sessionId) {
121173
122169
  }
121174
122170
  publishBackgroundTasks(sessionId);
121175
122171
  }
121176
- function clearThreadBranch(sessionId, threadId) {
122172
+ function clearThreadBranch2(sessionId, threadId) {
121177
122173
  const key = `${sessionId}:thread:${threadId}`;
121178
122174
  const entry = sessionMap2.get(key);
121179
122175
  if (entry) closeEntry(key, entry);
@@ -121253,7 +122249,7 @@ async function setModel(sessionId, model) {
121253
122249
  await entry.query.setModel(model);
121254
122250
  void refreshContext(entry, sessionId, getDb());
121255
122251
  }
121256
- async function stopTask(sessionId, taskId) {
122252
+ async function stopTask2(sessionId, taskId) {
121257
122253
  const entry = sessionMap2.get(sessionId);
121258
122254
  if (!entry) return;
121259
122255
  await entry.query.stopTask(taskId);
@@ -121288,7 +122284,7 @@ async function getModels2() {
121288
122284
  return [];
121289
122285
  }
121290
122286
  }
121291
- async function getCommands() {
122287
+ async function getCommands2() {
121292
122288
  if (cachedCommands) return cachedCommands;
121293
122289
  await getModels2();
121294
122290
  return cachedCommands ?? [];
@@ -121701,15 +122697,15 @@ var claudeProvider = {
121701
122697
  startTurn: startTurn3,
121702
122698
  interruptTurn: interruptTurn2,
121703
122699
  clearThread: clearThread2,
121704
- clearThreadBranch,
122700
+ clearThreadBranch: clearThreadBranch2,
121705
122701
  clearAllThreads: clearAllThreads2,
121706
122702
  getModels: getModels2,
121707
- getCommands,
122703
+ getCommands: getCommands2,
121708
122704
  forkSession: forkClaudeSession,
121709
122705
  summarizeThread: summarizeClaudeThread,
121710
122706
  setModel,
121711
- stopTask,
121712
- listBackgroundTasks,
122707
+ stopTask: stopTask2,
122708
+ listBackgroundTasks: listBackgroundTasks2,
121713
122709
  resumeInterruptedTurn: resumeInterruptedTurn2,
121714
122710
  reapOrphans: reapOrphans2,
121715
122711
  shutdown: shutdown2
@@ -121730,8 +122726,8 @@ var RepoburgHttpClient = class {
121730
122726
  this.baseUrl = baseUrl.replace(/\/+$/, "");
121731
122727
  }
121732
122728
  /** Perform a JSON request. Throws a concise error on non-OK/non-JSON responses. */
121733
- async request(method, path17, body) {
121734
- const response = await fetch(`${this.baseUrl}${path17}`, {
122729
+ async request(method, path19, body) {
122730
+ const response = await fetch(`${this.baseUrl}${path19}`, {
121735
122731
  method,
121736
122732
  headers: { "Content-Type": "application/json" },
121737
122733
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -121740,17 +122736,17 @@ var RepoburgHttpClient = class {
121740
122736
  if (!response.ok) {
121741
122737
  if (isHtml(text2)) {
121742
122738
  throw new Error(
121743
- `${method} ${path17} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
122739
+ `${method} ${path19} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121744
122740
  );
121745
122741
  }
121746
- throw new Error(`${method} ${path17} failed: ${response.status} ${text2}`);
122742
+ throw new Error(`${method} ${path19} failed: ${response.status} ${text2}`);
121747
122743
  }
121748
122744
  if (text2.length === 0) return void 0;
121749
122745
  try {
121750
122746
  return JSON.parse(text2);
121751
122747
  } catch {
121752
122748
  throw new Error(
121753
- `${method} ${path17} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
122749
+ `${method} ${path19} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121754
122750
  );
121755
122751
  }
121756
122752
  }
@@ -121805,7 +122801,7 @@ var RepoburgHttpClient = class {
121805
122801
  };
121806
122802
 
121807
122803
  // src/repoburg/backend-resolver.ts
121808
- import path15 from "node:path";
122804
+ import path17 from "node:path";
121809
122805
  var HEALTH_POLL_INTERVAL_MS = 1e3;
121810
122806
  var HEALTH_TIMEOUT_MS = 3e4;
121811
122807
  function daemonBaseUrl() {
@@ -121860,7 +122856,7 @@ async function backendHealthy(baseUrl, expectedPath) {
121860
122856
  const health = await fetchJson(`${baseUrl}/health`, void 0, 2e3);
121861
122857
  if (health.status !== "ok") return false;
121862
122858
  if (expectedPath && health.projectPath) {
121863
- return path15.resolve(health.projectPath) === path15.resolve(expectedPath);
122859
+ return path17.resolve(health.projectPath) === path17.resolve(expectedPath);
121864
122860
  }
121865
122861
  return true;
121866
122862
  } catch {
@@ -121881,7 +122877,7 @@ function serviceBaseUrl(service) {
121881
122877
  return `http://localhost:${service.port}`;
121882
122878
  }
121883
122879
  function coveringService(services, absPath) {
121884
- return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path15.sep)).sort((a, b) => b.path.length - a.path.length)[0];
122880
+ return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path17.sep)).sort((a, b) => b.path.length - a.path.length)[0];
121885
122881
  }
121886
122882
  async function restartService(daemon, name) {
121887
122883
  try {
@@ -121917,7 +122913,7 @@ async function resolveBackendUrl(projectPath, opts = {}) {
121917
122913
  if (envUrl) {
121918
122914
  return { baseUrl: envUrl.replace(/\/+$/, ""), port: 0, name: "REPOBURG_BACKEND_URL" };
121919
122915
  }
121920
- const absPath = path15.resolve(projectPath);
122916
+ const absPath = path17.resolve(projectPath);
121921
122917
  const daemon = daemonBaseUrl();
121922
122918
  const cached3 = resolvedCache.get(absPath);
121923
122919
  if (cached3 && await backendHealthy(cached3.baseUrl, cached3.servesPath ?? absPath)) {
@@ -123470,7 +124466,7 @@ function clearThread3(sessionId) {
123470
124466
  sessionMap3.delete(key);
123471
124467
  }
123472
124468
  }
123473
- function clearThreadBranch2(sessionId, threadId) {
124469
+ function clearThreadBranch3(sessionId, threadId) {
123474
124470
  const key = `${sessionId}:thread:${threadId}`;
123475
124471
  const entry = sessionMap3.get(key);
123476
124472
  if (entry) {
@@ -123519,7 +124515,7 @@ async function resolveClient(session) {
123519
124515
  if (!resolved) throw new Error("No repoburg backend resolved.");
123520
124516
  return new RepoburgHttpClient(resolved.baseUrl);
123521
124517
  }
123522
- async function forkSession(session, targetTurn) {
124518
+ async function forkSession2(session, targetTurn) {
123523
124519
  if (!session.external_thread_id) return null;
123524
124520
  const anchor = parseRuntimeInputIds(targetTurn).pop();
123525
124521
  if (!anchor) {
@@ -123559,7 +124555,7 @@ async function getModels3(cwd) {
123559
124555
  return [];
123560
124556
  }
123561
124557
  }
123562
- async function getCommands2(cwd) {
124558
+ async function getCommands3(cwd) {
123563
124559
  try {
123564
124560
  const resolved = await resolveBackendUrl(cwd ?? process.cwd(), { autoStart: false });
123565
124561
  if (!resolved) return [];
@@ -123580,12 +124576,12 @@ var repoburgProvider = {
123580
124576
  startTurn: startTurn4,
123581
124577
  interruptTurn: interruptTurn3,
123582
124578
  clearThread: clearThread3,
123583
- clearThreadBranch: clearThreadBranch2,
124579
+ clearThreadBranch: clearThreadBranch3,
123584
124580
  clearAllThreads: clearAllThreads3,
123585
124581
  getModels: getModels3,
123586
- getCommands: getCommands2,
124582
+ getCommands: getCommands3,
123587
124583
  rewindRuntime,
123588
- forkSession,
124584
+ forkSession: forkSession2,
123589
124585
  shutdown: shutdown3
123590
124586
  };
123591
124587
 
@@ -123598,7 +124594,7 @@ registerProvider("repoburg", repoburgProvider);
123598
124594
  async function createAgentPaneApp(dbPath, opts = {}) {
123599
124595
  const allowRequest = opts.allowRequest ?? isLocalRequest;
123600
124596
  initDb(dbPath);
123601
- setPaneDataDir(dbPath === ":memory:" ? null : path16.dirname(path16.resolve(dbPath)));
124597
+ setPaneDataDir(dbPath === ":memory:" ? null : path18.dirname(path18.resolve(dbPath)));
123602
124598
  const fastify = (0, import_fastify.default)({ logger: true, bodyLimit: 50 * 1024 * 1024 });
123603
124599
  fastify.addHook("onRequest", async (request, reply) => {
123604
124600
  if (!allowRequest(request.headers.origin, request.headers.host)) {
@@ -123624,6 +124620,7 @@ async function createAgentPaneApp(dbPath, opts = {}) {
123624
124620
  await registerSidecarRoutes(fastify);
123625
124621
  await registerUsageRoutes(fastify);
123626
124622
  await registerClaudeSessionRoutes(fastify);
124623
+ await registerCodexSessionRoutes(fastify);
123627
124624
  await registerSessionHostRoutes(fastify);
123628
124625
  const wss3 = initWs(allowRequest);
123629
124626
  initTerminalWs(allowRequest);