repoburg 1.3.304 → 1.3.306

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);
@@ -41228,6 +41237,12 @@ CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
41228
41237
  if (!turnColumns.some((c) => c.name === "stream_cursor")) {
41229
41238
  database.exec("ALTER TABLE turns ADD COLUMN stream_cursor TEXT");
41230
41239
  }
41240
+ if (!turnColumns.some((c) => c.name === "origin")) {
41241
+ database.exec("ALTER TABLE turns ADD COLUMN origin TEXT");
41242
+ }
41243
+ if (!turnColumns.some((c) => c.name === "origin_name")) {
41244
+ database.exec("ALTER TABLE turns ADD COLUMN origin_name TEXT");
41245
+ }
41231
41246
  const processColumns = database.prepare("PRAGMA table_info(cli_processes)").all();
41232
41247
  if (!processColumns.some((c) => c.name === "runtime")) {
41233
41248
  database.exec("ALTER TABLE cli_processes ADD COLUMN runtime TEXT NOT NULL DEFAULT 'claude'");
@@ -41690,7 +41705,7 @@ function handleTerminalUpgrade(request, socket, head) {
41690
41705
  }
41691
41706
 
41692
41707
  // src/routes/sessions.ts
41693
- import path2 from "node:path";
41708
+ import path3 from "node:path";
41694
41709
 
41695
41710
  // node_modules/uuid/dist/esm/stringify.js
41696
41711
  var byteToHex = [];
@@ -41982,6 +41997,45 @@ function startTurn(db2, session, { prompt, attachments, originAppId }) {
41982
41997
  return parsedTurn;
41983
41998
  }
41984
41999
 
42000
+ // src/providers/attachment-files.ts
42001
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
42002
+ import os2 from "node:os";
42003
+ import path2 from "node:path";
42004
+ function sessionDir(sessionId) {
42005
+ let base = path2.join(os2.tmpdir(), "agentpane");
42006
+ try {
42007
+ const file2 = getDb().name;
42008
+ if (file2 && file2 !== ":memory:") base = path2.dirname(path2.resolve(file2));
42009
+ } catch {
42010
+ }
42011
+ return path2.join(base, "attachments", sessionId.replace(/[^\w.-]/g, "_"));
42012
+ }
42013
+ function safeName(name) {
42014
+ const base = path2.basename(name || "attachment").replace(/[^\w.\- ()]/g, "_").trim();
42015
+ return base && base !== "." && base !== ".." ? base : "attachment";
42016
+ }
42017
+ function freeName(name, taken) {
42018
+ const ext = path2.extname(name);
42019
+ let free = name;
42020
+ for (let n = 2; taken.has(free.toLowerCase()); n++) free = `${name.slice(0, name.length - ext.length)}-${n}${ext}`;
42021
+ taken.add(free.toLowerCase());
42022
+ return free;
42023
+ }
42024
+ function saveAttachmentFile(sessionId, turnId, name, base643, taken = /* @__PURE__ */ new Set()) {
42025
+ const dir = path2.join(sessionDir(sessionId), turnId.replace(/[^\w.-]/g, "_"));
42026
+ mkdirSync(dir, { recursive: true });
42027
+ const file2 = path2.join(dir, freeName(safeName(name), taken));
42028
+ writeFileSync(file2, Buffer.from(base643, "base64"));
42029
+ return file2;
42030
+ }
42031
+ function removeAttachmentFiles(sessionId) {
42032
+ try {
42033
+ rmSync(sessionDir(sessionId), { recursive: true, force: true });
42034
+ } catch (err) {
42035
+ console.warn(`[attachments] could not remove the files of session ${sessionId}: ${err.message}`);
42036
+ }
42037
+ }
42038
+
41985
42039
  // src/routes/sessions.ts
41986
42040
  async function registerSessionRoutes(fastify) {
41987
42041
  fastify.get("/api/sessions", async () => {
@@ -42078,6 +42132,7 @@ async function registerSessionRoutes(fastify) {
42078
42132
  db2.prepare("DELETE FROM items WHERE turn_id IN (SELECT id FROM turns WHERE session_id = ?)").run(id);
42079
42133
  db2.prepare("DELETE FROM turns WHERE session_id = ?").run(id);
42080
42134
  db2.prepare("DELETE FROM sessions WHERE id = ?").run(id);
42135
+ removeAttachmentFiles(id);
42081
42136
  return { success: true };
42082
42137
  });
42083
42138
  fastify.patch("/api/sessions/:id", {
@@ -42143,8 +42198,8 @@ async function registerSessionRoutes(fastify) {
42143
42198
  }
42144
42199
  let workspaceChanged = false;
42145
42200
  if (cwd !== void 0) {
42146
- const oldAbs = existing.cwd ? path2.resolve(existing.cwd) : null;
42147
- const newAbs = cwd ? path2.resolve(cwd) : null;
42201
+ const oldAbs = existing.cwd ? path3.resolve(existing.cwd) : null;
42202
+ const newAbs = cwd ? path3.resolve(cwd) : null;
42148
42203
  workspaceChanged = oldAbs !== newAbs;
42149
42204
  if (workspaceChanged && existing.is_running) {
42150
42205
  return reply.code(409).send({ error: "Cannot change workspace while a turn is running" });
@@ -42338,8 +42393,8 @@ async function registerSessionRoutes(fastify) {
42338
42393
  for (const turn of turnRows) {
42339
42394
  const newTurnId = v4_default();
42340
42395
  db2.prepare(
42341
- `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, created_at, updated_at)
42342
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42396
+ `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, origin, origin_name, created_at, updated_at)
42397
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42343
42398
  ).run(
42344
42399
  newTurnId,
42345
42400
  newSessionId,
@@ -42351,6 +42406,8 @@ async function registerSessionRoutes(fastify) {
42351
42406
  turn.status,
42352
42407
  turn.error,
42353
42408
  turn.attachments,
42409
+ turn.origin ?? null,
42410
+ turn.origin_name ?? null,
42354
42411
  turn.created_at,
42355
42412
  turn.updated_at
42356
42413
  );
@@ -42592,7 +42649,7 @@ function recoverInterruptedTurns(db2, opts) {
42592
42649
  WHERE i.status = 'in_progress'`
42593
42650
  ).all();
42594
42651
  const orphaned = open.filter((i) => !skip.entries.has(runtimeEntryKey(i.session_id, i.thread_id)));
42595
- const stopTask2 = db2.prepare(
42652
+ const stopTask3 = db2.prepare(
42596
42653
  `UPDATE items SET data = json_set(COALESCE(data, '{}'), '$.status', 'stopped')
42597
42654
  WHERE id = ? AND json_valid(COALESCE(data, '{}'))`
42598
42655
  );
@@ -42600,7 +42657,7 @@ function recoverInterruptedTurns(db2, opts) {
42600
42657
  const items = { changes: 0 };
42601
42658
  db2.transaction(() => {
42602
42659
  for (const item of orphaned) {
42603
- if (item.type === "background_task") stopTask2.run(item.id);
42660
+ if (item.type === "background_task") stopTask3.run(item.id);
42604
42661
  items.changes += failItem.run(now, item.id).changes;
42605
42662
  }
42606
42663
  })();
@@ -42970,6 +43027,28 @@ async function registerTurnRoutes(fastify) {
42970
43027
  markSessionTouched(db2, id);
42971
43028
  return { success: true };
42972
43029
  });
43030
+ fastify.post(
43031
+ "/api/sessions/:id/tasks/:taskId/stop",
43032
+ async (request, reply) => {
43033
+ const { id, taskId } = request.params;
43034
+ const db2 = getDb();
43035
+ const session = db2.prepare("SELECT runtime_type FROM sessions WHERE id = ?").get(id);
43036
+ if (!session) {
43037
+ return reply.code(404).send({ error: "Session not found" });
43038
+ }
43039
+ const provider = getProvider(session.runtime_type);
43040
+ if (!provider.stopTask) {
43041
+ return reply.code(501).send({ error: `${session.runtime_type} sessions cannot stop background tasks` });
43042
+ }
43043
+ try {
43044
+ await provider.stopTask(id, taskId);
43045
+ } catch (err) {
43046
+ return reply.code(409).send({ error: err.message });
43047
+ }
43048
+ markSessionTouched(db2, id);
43049
+ return { success: true };
43050
+ }
43051
+ );
42973
43052
  fastify.post(
42974
43053
  "/api/sessions/:id/turns/:turnId/resume",
42975
43054
  async (request, reply) => {
@@ -43387,9 +43466,9 @@ async function browseFolder(input, opts = {}) {
43387
43466
  const atHome = dir === nodePath.resolve(home);
43388
43467
  const folders = await Promise.all(
43389
43468
  names.slice(0, limit).map(async (name) => {
43390
- const path17 = nodePath.join(dir, name);
43469
+ const path19 = nodePath.join(dir, name);
43391
43470
  const skipProbe = atHome && HOME_STANDARD_FOLDERS.has(name) || dir === "/Volumes";
43392
- return { name, path: path17, git: !skipProbe && await exists(nodePath.join(path17, ".git")) };
43471
+ return { name, path: path19, git: !skipProbe && await exists(nodePath.join(path19, ".git")) };
43393
43472
  })
43394
43473
  );
43395
43474
  const parent = nodePath.dirname(dir);
@@ -43427,11 +43506,11 @@ async function registerWorkspaceRoutes(fastify) {
43427
43506
  }
43428
43507
  }
43429
43508
  }, async (request, reply) => {
43430
- const { path: path17, label = null } = request.body || {};
43431
- if (!path17 || !path17.trim()) {
43509
+ const { path: path19, label = null } = request.body || {};
43510
+ if (!path19 || !path19.trim()) {
43432
43511
  return reply.code(400).send({ error: "Path is required" });
43433
43512
  }
43434
- const resolved = await resolveWorkspacePath(path17);
43513
+ const resolved = await resolveWorkspacePath(path19);
43435
43514
  if ("error" in resolved) {
43436
43515
  return reply.code(400).send({ error: resolved.error });
43437
43516
  }
@@ -43473,8 +43552,8 @@ async function registerWorkspaceRoutes(fastify) {
43473
43552
  "-e",
43474
43553
  'POSIX path of (choose folder with prompt "Select a workspace directory")'
43475
43554
  ]);
43476
- const path17 = stdout.trim().replace(/\/$/, "");
43477
- return { path: path17 };
43555
+ const path19 = stdout.trim().replace(/\/$/, "");
43556
+ return { path: path19 };
43478
43557
  } catch {
43479
43558
  return reply.code(204).send({ cancelled: true });
43480
43559
  }
@@ -43490,11 +43569,11 @@ async function registerWorkspaceRoutes(fastify) {
43490
43569
  }
43491
43570
  }
43492
43571
  }, async (request, reply) => {
43493
- const { path: path17 } = request.body || {};
43494
- if (!path17 || !path17.trim()) {
43572
+ const { path: path19 } = request.body || {};
43573
+ if (!path19 || !path19.trim()) {
43495
43574
  return reply.code(400).send({ error: "Path is required" });
43496
43575
  }
43497
- const trimmedPath = path17.trim();
43576
+ const trimmedPath = path19.trim();
43498
43577
  const db2 = getDb();
43499
43578
  const existing = db2.prepare("SELECT * FROM workspaces WHERE path = ?").get(trimmedPath);
43500
43579
  if (existing) {
@@ -44185,7 +44264,7 @@ async function registerFileRoutes(fastify) {
44185
44264
  }
44186
44265
 
44187
44266
  // src/routes/perf-log.ts
44188
- import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
44267
+ import { appendFileSync, mkdirSync as mkdirSync2, renameSync, statSync } from "node:fs";
44189
44268
  import { homedir as homedir2 } from "node:os";
44190
44269
  import { dirname, join } from "node:path";
44191
44270
  var MAX_BYTES = 5 * 1024 * 1024;
@@ -44228,17 +44307,17 @@ async function registerPerfLogRoutes(fastify) {
44228
44307
  if (entries.length === 0) {
44229
44308
  return reply.send({ written: 0 });
44230
44309
  }
44231
- const path17 = perfLogPath();
44310
+ const path19 = perfLogPath();
44232
44311
  try {
44233
- mkdirSync(dirname(path17), { recursive: true });
44312
+ mkdirSync2(dirname(path19), { recursive: true });
44234
44313
  try {
44235
- if (statSync(path17).size > MAX_BYTES) {
44236
- renameSync(path17, `${path17}.1`);
44314
+ if (statSync(path19).size > MAX_BYTES) {
44315
+ renameSync(path19, `${path19}.1`);
44237
44316
  }
44238
44317
  } catch {
44239
44318
  }
44240
44319
  const lines = entries.map((e) => `${new Date(e.t).toISOString()} [${oneLine(e.cat)}] ${oneLine(e.msg)}`).join("\n");
44241
- appendFileSync(path17, `${lines}
44320
+ appendFileSync(path19, `${lines}
44242
44321
  `, "utf-8");
44243
44322
  return reply.send({ written: entries.length });
44244
44323
  } catch (err) {
@@ -44314,24 +44393,24 @@ import { existsSync } from "node:fs";
44314
44393
  import http from "node:http";
44315
44394
  import net from "node:net";
44316
44395
  import crypto from "node:crypto";
44317
- import os2 from "node:os";
44318
- import path3 from "node:path";
44396
+ import os3 from "node:os";
44397
+ import path4 from "node:path";
44319
44398
  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");
44399
+ var VSCODE_WEB_DATA_DIR = path4.join(os3.homedir(), ".repoburg", "vscode-web");
44321
44400
  function resolveDesktopUserDir() {
44322
44401
  if (process.platform === "darwin") {
44323
- return path3.join(os2.homedir(), "Library", "Application Support", "Code", "User");
44402
+ return path4.join(os3.homedir(), "Library", "Application Support", "Code", "User");
44324
44403
  }
44325
44404
  if (process.platform === "win32" && process.env.APPDATA) {
44326
- return path3.join(process.env.APPDATA, "Code", "User");
44405
+ return path4.join(process.env.APPDATA, "Code", "User");
44327
44406
  }
44328
44407
  if (process.platform === "linux") {
44329
- return path3.join(os2.homedir(), ".config", "Code", "User");
44408
+ return path4.join(os3.homedir(), ".config", "Code", "User");
44330
44409
  }
44331
44410
  return null;
44332
44411
  }
44333
44412
  async function linkUnlessExists(src, dst) {
44334
- await mkdir(path3.dirname(dst), { recursive: true });
44413
+ await mkdir(path4.dirname(dst), { recursive: true });
44335
44414
  try {
44336
44415
  await lstat(dst);
44337
44416
  return false;
@@ -44346,19 +44425,19 @@ function fileRegistryUri(dir) {
44346
44425
  }
44347
44426
  async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44348
44427
  try {
44349
- const desktopExt = path3.join(os2.homedir(), ".vscode", "extensions");
44428
+ const desktopExt = path4.join(os3.homedir(), ".vscode", "extensions");
44350
44429
  let entries;
44351
44430
  try {
44352
44431
  entries = await readdir2(desktopExt, { withFileTypes: true });
44353
44432
  } catch {
44354
44433
  return;
44355
44434
  }
44356
- const serverExt = path3.join(dataDir, "extensions");
44435
+ const serverExt = path4.join(dataDir, "extensions");
44357
44436
  const linkedFolders = [];
44358
44437
  for (const entry of entries) {
44359
44438
  if (!entry.isDirectory()) continue;
44360
- const target = path3.join(serverExt, entry.name);
44361
- await linkUnlessExists(path3.join(desktopExt, entry.name), target);
44439
+ const target = path4.join(serverExt, entry.name);
44440
+ await linkUnlessExists(path4.join(desktopExt, entry.name), target);
44362
44441
  const st = await lstat(target).catch(() => null);
44363
44442
  if (st?.isSymbolicLink()) linkedFolders.push(entry.name);
44364
44443
  }
@@ -44366,15 +44445,15 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44366
44445
  await pruneObsolete(serverExt, linkedFolders);
44367
44446
  const desktopUser = resolveDesktopUserDir();
44368
44447
  if (!desktopUser) return;
44369
- const serverUser = path3.join(dataDir, "data", "User");
44448
+ const serverUser = path4.join(dataDir, "data", "User");
44370
44449
  for (const item of ["settings.json", "keybindings.json", "snippets"]) {
44371
- const src = path3.join(desktopUser, item);
44450
+ const src = path4.join(desktopUser, item);
44372
44451
  try {
44373
44452
  await access(src);
44374
44453
  } catch {
44375
44454
  continue;
44376
44455
  }
44377
- await linkUnlessExists(src, path3.join(serverUser, item));
44456
+ await linkUnlessExists(src, path4.join(serverUser, item));
44378
44457
  }
44379
44458
  } catch {
44380
44459
  }
@@ -44382,13 +44461,13 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44382
44461
  async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
44383
44462
  let desktopEntries = [];
44384
44463
  try {
44385
- desktopEntries = JSON.parse(await readFile(path3.join(desktopExt, "extensions.json"), "utf8"));
44464
+ desktopEntries = JSON.parse(await readFile(path4.join(desktopExt, "extensions.json"), "utf8"));
44386
44465
  } catch {
44387
44466
  return;
44388
44467
  }
44389
44468
  const linked = new Set(linkedFolders);
44390
44469
  const toAdd = desktopEntries.filter((e) => e.identifier?.id && linked.has(e.relativeLocation));
44391
- const serverRegistryPath = path3.join(serverExt, "extensions.json");
44470
+ const serverRegistryPath = path4.join(serverExt, "extensions.json");
44392
44471
  let serverEntries = [];
44393
44472
  try {
44394
44473
  serverEntries = JSON.parse(await readFile(serverRegistryPath, "utf8"));
@@ -44398,13 +44477,13 @@ async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
44398
44477
  const additions = toAdd.filter((e) => !known.has(`${e.identifier.id.toLowerCase()}@${e.version}`));
44399
44478
  if (additions.length === 0) return;
44400
44479
  for (const entry of additions) {
44401
- const dir = path3.join(serverExt, entry.relativeLocation);
44480
+ const dir = path4.join(serverExt, entry.relativeLocation);
44402
44481
  serverEntries.push({ ...entry, location: fileRegistryUri(dir) });
44403
44482
  }
44404
44483
  await writeFile(serverRegistryPath, JSON.stringify(serverEntries));
44405
44484
  }
44406
44485
  async function pruneObsolete(serverExt, linkedFolders) {
44407
- const obsoletePath = path3.join(serverExt, ".obsolete");
44486
+ const obsoletePath = path4.join(serverExt, ".obsolete");
44408
44487
  let obsolete;
44409
44488
  try {
44410
44489
  obsolete = JSON.parse(await readFile(obsoletePath, "utf8"));
@@ -44863,16 +44942,16 @@ function proxyHandler(request, reply) {
44863
44942
 
44864
44943
  // src/routes/apps.ts
44865
44944
  import fs6 from "node:fs";
44866
- import path9 from "node:path";
44945
+ import path10 from "node:path";
44867
44946
 
44868
44947
  // src/apps/instances.ts
44869
44948
  import fs3 from "node:fs";
44870
- import path5 from "node:path";
44949
+ import path6 from "node:path";
44871
44950
 
44872
44951
  // src/apps/apps-registry.ts
44873
44952
  import fs2 from "node:fs";
44874
- import path4 from "node:path";
44875
- import os3 from "node:os";
44953
+ import path5 from "node:path";
44954
+ import os4 from "node:os";
44876
44955
  import { fileURLToPath } from "node:url";
44877
44956
 
44878
44957
  // node_modules/lucide-static/icon-nodes.json
@@ -99096,10 +99175,10 @@ function setAppsRootOverride(root) {
99096
99175
  rootOverride = root;
99097
99176
  }
99098
99177
  function appsRoot() {
99099
- return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path4.join(os3.homedir(), ".repoburg", "agent-pane", "apps");
99178
+ return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path5.join(os4.homedir(), ".repoburg", "agent-pane", "apps");
99100
99179
  }
99101
99180
  function appDir(id) {
99102
- return path4.join(appsRoot(), id);
99181
+ return path5.join(appsRoot(), id);
99103
99182
  }
99104
99183
  var examplesRootOverride = null;
99105
99184
  function setExamplesRootOverride(root) {
@@ -99108,16 +99187,16 @@ function setExamplesRootOverride(root) {
99108
99187
  function examplesRoot() {
99109
99188
  if (examplesRootOverride) return examplesRootOverride;
99110
99189
  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")]) {
99190
+ const here = path5.dirname(fileURLToPath(import.meta.url));
99191
+ for (const candidate of [path5.resolve(here, "../../examples"), path5.resolve(here, "../../../examples")]) {
99113
99192
  if (fs2.existsSync(candidate)) return candidate;
99114
99193
  }
99115
99194
  return null;
99116
99195
  }
99117
99196
  function isInAppFolder(cwd) {
99118
99197
  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] !== "..";
99198
+ const rel = path5.relative(path5.resolve(appsRoot()), path5.resolve(cwd));
99199
+ return rel !== "" && !path5.isAbsolute(rel) && rel.split(path5.sep)[0] !== "..";
99121
99200
  }
99122
99201
  function appsConventions() {
99123
99202
  return APPS_MD_SKELETON;
@@ -99126,7 +99205,7 @@ function ensureAppsRoot() {
99126
99205
  const root = appsRoot();
99127
99206
  fs2.mkdirSync(root, { recursive: true });
99128
99207
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
99129
- const file2 = path4.join(root, name);
99208
+ const file2 = path5.join(root, name);
99130
99209
  try {
99131
99210
  if (fs2.existsSync(file2) && fs2.readFileSync(file2, "utf-8") === APPS_MD_FILE) continue;
99132
99211
  fs2.writeFileSync(file2, APPS_MD_FILE);
@@ -99350,7 +99429,7 @@ folder's own CLAUDE.md / AGENTS.md. -->
99350
99429
  ${APPS_MD_SKELETON}`;
99351
99430
  function readManifestIn(dir) {
99352
99431
  try {
99353
- const raw = fs2.readFileSync(path4.join(dir, "manifest.json"), "utf-8");
99432
+ const raw = fs2.readFileSync(path5.join(dir, "manifest.json"), "utf-8");
99354
99433
  const parsed = JSON.parse(raw);
99355
99434
  if (!parsed || typeof parsed.title !== "string") return null;
99356
99435
  return {
@@ -99369,7 +99448,7 @@ function readManifest(id) {
99369
99448
  }
99370
99449
  function readAppFile(id, name) {
99371
99450
  try {
99372
- return fs2.readFileSync(path4.join(appDir(id), name), "utf-8");
99451
+ return fs2.readFileSync(path5.join(appDir(id), name), "utf-8");
99373
99452
  } catch {
99374
99453
  return "";
99375
99454
  }
@@ -99402,11 +99481,11 @@ function startAppsWatch(onAppChange) {
99402
99481
  try {
99403
99482
  watcher = fs2.watch(root, { recursive: true }, (_event, filename) => {
99404
99483
  const rel = String(filename ?? "");
99405
- const segs = rel.split(path4.sep);
99484
+ const segs = rel.split(path5.sep);
99406
99485
  const appId = segs[0];
99407
99486
  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;
99487
+ if (!appId || appId === path5.basename(root) || !APP_ID_RE.test(appId) || file2 === "state.json") return;
99488
+ if (segs.length === 1 && isRegularFile(path5.join(root, appId))) return;
99410
99489
  const timer2 = pendingChanges.get(appId);
99411
99490
  if (timer2) clearTimeout(timer2);
99412
99491
  pendingChanges.set(
@@ -99477,7 +99556,7 @@ function getInstanceState(appId, workspace = "") {
99477
99556
  const stored = readRow(appId, workspace);
99478
99557
  if (stored) return stored;
99479
99558
  if (workspace === "") {
99480
- const legacyFile = path5.join(appDir(appId), "state.json");
99559
+ const legacyFile = path6.join(appDir(appId), "state.json");
99481
99560
  if (fs3.existsSync(legacyFile)) {
99482
99561
  const legacy = readState(appId);
99483
99562
  const imported = { pinned: legacy.pinned, data: legacy.data, version: 1 };
@@ -99510,9 +99589,9 @@ function resolveToolWorkspace(workspace) {
99510
99589
  const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99511
99590
  const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99512
99591
  if (active.includes(workspace)) return workspace;
99513
- const cwd = path5.isAbsolute(workspace) ? path5.resolve(workspace) : "";
99592
+ const cwd = path6.isAbsolute(workspace) ? path6.resolve(workspace) : "";
99514
99593
  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];
99594
+ 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
99595
  if (covering && !covering.deleted) return covering.path;
99517
99596
  throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99518
99597
  }
@@ -99524,7 +99603,7 @@ function deleteAppInstances(appId) {
99524
99603
  import fs5 from "node:fs";
99525
99604
 
99526
99605
  // src/apps/app-sessions.ts
99527
- import path7 from "node:path";
99606
+ import path8 from "node:path";
99528
99607
 
99529
99608
  // src/sidecar/transcript-locator.ts
99530
99609
  import { existsSync as existsSync2, readdirSync } from "node:fs";
@@ -99609,8 +99688,8 @@ function locateTranscriptCached(session) {
99609
99688
  // src/apps/app-files.ts
99610
99689
  import crypto2 from "node:crypto";
99611
99690
  import fs4 from "node:fs";
99612
- import os4 from "node:os";
99613
- import path6 from "node:path";
99691
+ import os5 from "node:os";
99692
+ import path7 from "node:path";
99614
99693
  var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
99615
99694
  var APP_FILE_TYPES = {
99616
99695
  "image/png": "png",
@@ -99635,11 +99714,11 @@ function setAppFilesRootOverride(root) {
99635
99714
  rootOverride2 = root;
99636
99715
  }
99637
99716
  function appFilesRoot() {
99638
- return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path6.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
99717
+ return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path7.join(os5.homedir(), ".repoburg", "agent-pane", "app-files");
99639
99718
  }
99640
99719
  function appFilesDir(appId) {
99641
99720
  if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
99642
- return path6.join(appFilesRoot(), appId);
99721
+ return path7.join(appFilesRoot(), appId);
99643
99722
  }
99644
99723
  function appFileUrl(appId, fileId) {
99645
99724
  return `/api/apps/${appId}/files/${fileId}`;
@@ -99700,7 +99779,7 @@ function saveAppFile(appId, upload) {
99700
99779
  const type = sniffImageType(bytes);
99701
99780
  if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
99702
99781
  const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
99703
- const file2 = path6.join(dir, fileId);
99782
+ const file2 = path7.join(dir, fileId);
99704
99783
  if (!fs4.existsSync(file2)) {
99705
99784
  fs4.mkdirSync(dir, { recursive: true });
99706
99785
  const tmp = `${file2}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
@@ -99732,7 +99811,7 @@ function getAppFile(appId, ref) {
99732
99811
  if (!APP_ID_RE.test(appId)) return null;
99733
99812
  const fileId = appFileRefId(appId, ref);
99734
99813
  if (!fileId) return null;
99735
- const file2 = path6.join(appFilesDir(appId), fileId);
99814
+ const file2 = path7.join(appFilesDir(appId), fileId);
99736
99815
  try {
99737
99816
  const stat2 = fs4.statSync(file2);
99738
99817
  if (!stat2.isFile()) return null;
@@ -99744,7 +99823,7 @@ function getAppFile(appId, ref) {
99744
99823
  function readAppFileData(appId, fileId) {
99745
99824
  if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
99746
99825
  try {
99747
- return { bytes: fs4.readFileSync(path6.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99826
+ return { bytes: fs4.readFileSync(path7.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99748
99827
  } catch {
99749
99828
  return null;
99750
99829
  }
@@ -99854,7 +99933,7 @@ function appSessionInfo(appId, sessionId) {
99854
99933
  function sessionVisibleTo(session, appId, workspace) {
99855
99934
  if (!workspace) return true;
99856
99935
  const cwd = session.cwd;
99857
- if (cwd && (cwd === workspace || cwd.startsWith(workspace.endsWith(path7.sep) ? workspace : workspace + path7.sep))) {
99936
+ if (cwd && (cwd === workspace || cwd.startsWith(workspace.endsWith(path8.sep) ? workspace : workspace + path8.sep))) {
99858
99937
  return true;
99859
99938
  }
99860
99939
  return session.origin_app_workspace === workspace && openedByApp(session, appId);
@@ -99949,7 +100028,7 @@ import vm2 from "node:vm";
99949
100028
 
99950
100029
  // src/apps/app-compile.ts
99951
100030
  import vm from "node:vm";
99952
- import path8 from "node:path";
100031
+ import path9 from "node:path";
99953
100032
  import ts from "typescript";
99954
100033
 
99955
100034
  // src/apps/app-lint.ts
@@ -100346,15 +100425,15 @@ function typeCheckModules(appId, modules) {
100346
100425
  };
100347
100426
  const host = ts.createCompilerHost(options);
100348
100427
  const origReadFile = host.readFile.bind(host);
100349
- host.readFile = (fname) => path8.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
100428
+ host.readFile = (fname) => path9.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
100350
100429
  host.writeFile = () => {
100351
100430
  };
100352
- const bridgePath = path8.join(dir, BRIDGE_DTS_FILE);
100353
- const rootNames = [...modules.map((m) => path8.join(dir, m.file)), bridgePath];
100431
+ const bridgePath = path9.join(dir, BRIDGE_DTS_FILE);
100432
+ const rootNames = [...modules.map((m) => path9.join(dir, m.file)), bridgePath];
100354
100433
  const program = ts.createProgram(rootNames, options, host);
100355
100434
  const out = [];
100356
100435
  for (const mod of modules) {
100357
- const sf = program.getSourceFile(path8.join(dir, mod.file));
100436
+ const sf = program.getSourceFile(path9.join(dir, mod.file));
100358
100437
  if (!sf) continue;
100359
100438
  out.push(
100360
100439
  ...[...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)].map((d) => tsDiagnosticToFile(mod.file, d)).filter((d) => d !== null)
@@ -100714,6 +100793,63 @@ function invalidateHeadlessRuntime(appId) {
100714
100793
  }
100715
100794
  }
100716
100795
 
100796
+ // src/providers/widget-spec.ts
100797
+ var WIDGET_TOOL_BASE_NAME = "show_widget";
100798
+ var WIDGET_CDN_ORIGINS = [
100799
+ "https://cdnjs.cloudflare.com",
100800
+ "https://cdn.jsdelivr.net",
100801
+ "https://unpkg.com",
100802
+ "https://esm.sh"
100803
+ ];
100804
+ 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.";
100805
+ var WIDGET_TOOL_DESCRIPTION = [
100806
+ "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.",
100807
+ "",
100808
+ "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.",
100809
+ "",
100810
+ `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.`,
100811
+ "",
100812
+ "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.",
100813
+ "",
100814
+ '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).',
100815
+ "",
100816
+ "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."
100817
+ ].join("\n");
100818
+ var WIDGET_SHOWN_RESULT = "The widget is now shown to the user inline in the chat.";
100819
+ var WIDGET_EMPTY_RESULT = "widget_code is empty, so nothing was shown.";
100820
+ var WIDGET_TITLE_DESCRIPTION = 'Short human-readable title shown above the widget, e.g. "Monthly revenue by region".';
100821
+ var WIDGET_CODE_DESCRIPTION = "The HTML fragment to render: <style>, then markup (HTML or inline SVG), then <script>.";
100822
+
100823
+ // src/codex/codex-widget.ts
100824
+ var CODEX_WIDGET_TOOL = {
100825
+ name: WIDGET_TOOL_BASE_NAME,
100826
+ description: `${WIDGET_INSTRUCTIONS}
100827
+
100828
+ ${WIDGET_TOOL_DESCRIPTION}`,
100829
+ inputSchema: {
100830
+ type: "object",
100831
+ properties: {
100832
+ title: { type: "string", description: WIDGET_TITLE_DESCRIPTION },
100833
+ widget_code: { type: "string", description: WIDGET_CODE_DESCRIPTION }
100834
+ },
100835
+ required: ["title", "widget_code"]
100836
+ }
100837
+ };
100838
+ function servesCodexSession(sessionId) {
100839
+ if (!sessionId) return false;
100840
+ try {
100841
+ const row = getDb().prepare("SELECT runtime_type FROM sessions WHERE id = ?").get(sessionId);
100842
+ return row?.runtime_type === "codex";
100843
+ } catch {
100844
+ return false;
100845
+ }
100846
+ }
100847
+ function answerWidgetCall(args) {
100848
+ const code = args.widget_code;
100849
+ if (typeof code !== "string" || !code.trim()) return { ok: false, error: WIDGET_EMPTY_RESULT };
100850
+ return { ok: true, text: WIDGET_SHOWN_RESULT };
100851
+ }
100852
+
100717
100853
  // src/apps/mcp-tools.ts
100718
100854
  var TOOL_CALL_TIMEOUT_MS = Number(process.env.AGENT_PANE_TOOL_TIMEOUT_MS ?? 3e4);
100719
100855
  var TOOL_NS = "__";
@@ -100736,6 +100872,14 @@ function listAppTools() {
100736
100872
  }
100737
100873
  return tools;
100738
100874
  }
100875
+ function listGatewayTools(callerSessionId) {
100876
+ const tools = listAppTools();
100877
+ return servesCodexSession(callerSessionId) ? [CODEX_WIDGET_TOOL, ...tools] : tools;
100878
+ }
100879
+ function callPaneTool(toolName, args, callerSessionId) {
100880
+ if (toolName !== CODEX_WIDGET_TOOL.name || !servesCodexSession(callerSessionId)) return null;
100881
+ return answerWidgetCall(args);
100882
+ }
100739
100883
  function splitToolName(name) {
100740
100884
  const idx = name.indexOf(TOOL_NS);
100741
100885
  if (idx <= 0 || idx === name.length - TOOL_NS.length) return null;
@@ -100866,7 +101010,10 @@ async function registerAppRoutes(fastify, opts) {
100866
101010
  }
100867
101011
  });
100868
101012
  fastify.get("/api/apps/root", async () => ({ root: appsRoot() }));
100869
- fastify.get("/api/apps/mcp/tools", async () => listAppTools());
101013
+ fastify.get(
101014
+ "/api/apps/mcp/tools",
101015
+ async (request) => listGatewayTools(request.query.session)
101016
+ );
100870
101017
  fastify.get("/api/apps/examples", async () => {
100871
101018
  const exRoot = examplesRoot();
100872
101019
  if (!exRoot) return [];
@@ -100874,7 +101021,7 @@ async function registerAppRoutes(fastify, opts) {
100874
101021
  try {
100875
101022
  for (const entry of fs6.readdirSync(exRoot, { withFileTypes: true })) {
100876
101023
  if (!entry.isDirectory() || !APP_ID_RE.test(entry.name)) continue;
100877
- const manifest = readManifestIn(path9.join(exRoot, entry.name));
101024
+ const manifest = readManifestIn(path10.join(exRoot, entry.name));
100878
101025
  if (!manifest) continue;
100879
101026
  out.push({
100880
101027
  id: entry.name,
@@ -100895,7 +101042,7 @@ async function registerAppRoutes(fastify, opts) {
100895
101042
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
100896
101043
  const exRoot = examplesRoot();
100897
101044
  if (!exRoot) return reply.code(404).send({ error: "Examples catalog not available" });
100898
- const src = path9.join(exRoot, id);
101045
+ const src = path10.join(exRoot, id);
100899
101046
  if (!readManifestIn(src)) return reply.code(404).send({ error: "Example not found" });
100900
101047
  if (readManifest(id)) return reply.code(409).send({ error: "App already installed" });
100901
101048
  ensureAppsRoot();
@@ -100934,7 +101081,7 @@ async function registerAppRoutes(fastify, opts) {
100934
101081
  fs6.mkdirSync(dir, { recursive: true });
100935
101082
  const cleanTitle2 = title.trim();
100936
101083
  fs6.writeFileSync(
100937
- path9.join(dir, "manifest.json"),
101084
+ path10.join(dir, "manifest.json"),
100938
101085
  JSON.stringify(
100939
101086
  {
100940
101087
  title: cleanTitle2,
@@ -100945,8 +101092,8 @@ async function registerAppRoutes(fastify, opts) {
100945
101092
  2
100946
101093
  )
100947
101094
  );
100948
- fs6.writeFileSync(path9.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
100949
- fs6.writeFileSync(path9.join(dir, "app.ts"), SKELETON_TS);
101095
+ fs6.writeFileSync(path10.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
101096
+ fs6.writeFileSync(path10.join(dir, "app.ts"), SKELETON_TS);
100950
101097
  return { ok: true, id };
100951
101098
  }
100952
101099
  );
@@ -100983,9 +101130,9 @@ async function registerAppRoutes(fastify, opts) {
100983
101130
  const dir = appDir(id);
100984
101131
  fs6.mkdirSync(dir, { recursive: true });
100985
101132
  if (!Object.hasOwn(files ?? {}, "manifest.json")) {
100986
- fs6.writeFileSync(path9.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
101133
+ fs6.writeFileSync(path10.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
100987
101134
  }
100988
- for (const [name, content] of entries) fs6.writeFileSync(path9.join(dir, name), content);
101135
+ for (const [name, content] of entries) fs6.writeFileSync(path10.join(dir, name), content);
100989
101136
  return { ok: true, id };
100990
101137
  }
100991
101138
  );
@@ -101007,6 +101154,8 @@ async function registerAppRoutes(fastify, opts) {
101007
101154
  },
101008
101155
  async (request, reply) => {
101009
101156
  const { tool: tool2, args, workspace, caller } = request.body || {};
101157
+ const own = callPaneTool(tool2, args ?? {}, caller?.sessionId);
101158
+ if (own) return own;
101010
101159
  try {
101011
101160
  const result = await callAppTool(tool2, args ?? {}, resolveToolWorkspace(workspace), caller?.sessionId);
101012
101161
  return { ok: true, result };
@@ -101300,7 +101449,7 @@ function buildSidecarPrompt(externalSessionId, transcriptPath, question) {
101300
101449
  }
101301
101450
 
101302
101451
  // src/routes/sidecar.ts
101303
- var SIDECAR_RUNTIMES = /* @__PURE__ */ new Set(["claude"]);
101452
+ var SIDECAR_RUNTIMES = /* @__PURE__ */ new Set(["claude", "codex"]);
101304
101453
  async function registerSidecarRoutes(fastify) {
101305
101454
  fastify.post(
101306
101455
  "/api/sessions/:sessionId/sidecar",
@@ -101915,7 +102064,7 @@ async function registerUsageRoutes(fastify) {
101915
102064
 
101916
102065
  // src/claude/session-import.ts
101917
102066
  import { readFile as readFile2, realpath } from "node:fs/promises";
101918
- import path10 from "node:path";
102067
+ import path11 from "node:path";
101919
102068
  import { getSessionInfo, listSessions } from "@anthropic-ai/claude-agent-sdk";
101920
102069
 
101921
102070
  // src/claude/widget-tool.ts
@@ -102687,10 +102836,10 @@ function mergeDefs(...defs) {
102687
102836
  function cloneDef(schema) {
102688
102837
  return mergeDefs(schema._zod.def);
102689
102838
  }
102690
- function getElementAtPath(obj2, path17) {
102691
- if (!path17)
102839
+ function getElementAtPath(obj2, path19) {
102840
+ if (!path19)
102692
102841
  return obj2;
102693
- return path17.reduce((acc, key) => acc?.[key], obj2);
102842
+ return path19.reduce((acc, key) => acc?.[key], obj2);
102694
102843
  }
102695
102844
  function promiseAllObject(promisesObj) {
102696
102845
  const keys = Object.keys(promisesObj);
@@ -103099,11 +103248,11 @@ function explicitlyAborted(x, startIndex = 0) {
103099
103248
  }
103100
103249
  return false;
103101
103250
  }
103102
- function prefixIssues(path17, issues) {
103251
+ function prefixIssues(path19, issues) {
103103
103252
  return issues.map((iss) => {
103104
103253
  var _a3;
103105
103254
  (_a3 = iss).path ?? (_a3.path = []);
103106
- iss.path.unshift(path17);
103255
+ iss.path.unshift(path19);
103107
103256
  return iss;
103108
103257
  });
103109
103258
  }
@@ -103250,16 +103399,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
103250
103399
  }
103251
103400
  function formatError(error51, mapper = (issue2) => issue2.message) {
103252
103401
  const fieldErrors = { _errors: [] };
103253
- const processError = (error52, path17 = []) => {
103402
+ const processError = (error52, path19 = []) => {
103254
103403
  for (const issue2 of error52.issues) {
103255
103404
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103256
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103405
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
103257
103406
  } else if (issue2.code === "invalid_key") {
103258
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103407
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103259
103408
  } else if (issue2.code === "invalid_element") {
103260
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103409
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103261
103410
  } else {
103262
- const fullpath = [...path17, ...issue2.path];
103411
+ const fullpath = [...path19, ...issue2.path];
103263
103412
  if (fullpath.length === 0) {
103264
103413
  fieldErrors._errors.push(mapper(issue2));
103265
103414
  } else {
@@ -103286,17 +103435,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
103286
103435
  }
103287
103436
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
103288
103437
  const result = { errors: [] };
103289
- const processError = (error52, path17 = []) => {
103438
+ const processError = (error52, path19 = []) => {
103290
103439
  var _a3, _b;
103291
103440
  for (const issue2 of error52.issues) {
103292
103441
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103293
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103442
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
103294
103443
  } else if (issue2.code === "invalid_key") {
103295
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103444
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103296
103445
  } else if (issue2.code === "invalid_element") {
103297
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103446
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103298
103447
  } else {
103299
- const fullpath = [...path17, ...issue2.path];
103448
+ const fullpath = [...path19, ...issue2.path];
103300
103449
  if (fullpath.length === 0) {
103301
103450
  result.errors.push(mapper(issue2));
103302
103451
  continue;
@@ -103328,8 +103477,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
103328
103477
  }
103329
103478
  function toDotPath(_path) {
103330
103479
  const segs = [];
103331
- const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103332
- for (const seg of path17) {
103480
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103481
+ for (const seg of path19) {
103333
103482
  if (typeof seg === "number")
103334
103483
  segs.push(`[${seg}]`);
103335
103484
  else if (typeof seg === "symbol")
@@ -116021,13 +116170,13 @@ function resolveRef(ref, ctx) {
116021
116170
  if (!ref.startsWith("#")) {
116022
116171
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
116023
116172
  }
116024
- const path17 = ref.slice(1).split("/").filter(Boolean);
116025
- if (path17.length === 0) {
116173
+ const path19 = ref.slice(1).split("/").filter(Boolean);
116174
+ if (path19.length === 0) {
116026
116175
  return ctx.rootSchema;
116027
116176
  }
116028
116177
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
116029
- if (path17[0] === defsKey) {
116030
- const key = path17[1];
116178
+ if (path19[0] === defsKey) {
116179
+ const key = path19[1];
116031
116180
  if (!key || !ctx.defs[key]) {
116032
116181
  throw new Error(`Reference not found: ${ref}`);
116033
116182
  }
@@ -116437,28 +116586,7 @@ config2(en_default());
116437
116586
 
116438
116587
  // src/claude/widget-tool.ts
116439
116588
  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.";
116589
+ var WIDGET_TOOL_NAME = `mcp__${WIDGET_SERVER_NAME}__${WIDGET_TOOL_BASE_NAME}`;
116462
116590
  function createWidgetMcpServer() {
116463
116591
  return createSdkMcpServer({
116464
116592
  name: WIDGET_SERVER_NAME,
@@ -116467,17 +116595,17 @@ function createWidgetMcpServer() {
116467
116595
  alwaysLoad: true,
116468
116596
  tools: [
116469
116597
  tool(
116470
- "show_widget",
116598
+ WIDGET_TOOL_BASE_NAME,
116471
116599
  WIDGET_TOOL_DESCRIPTION,
116472
116600
  {
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>.")
116601
+ title: external_exports.string().describe(WIDGET_TITLE_DESCRIPTION),
116602
+ widget_code: external_exports.string().describe(WIDGET_CODE_DESCRIPTION)
116475
116603
  },
116476
116604
  async ({ widget_code }) => {
116477
116605
  if (!widget_code.trim()) {
116478
- return { content: [{ type: "text", text: "widget_code is empty, so nothing was shown." }], isError: true };
116606
+ return { content: [{ type: "text", text: WIDGET_EMPTY_RESULT }], isError: true };
116479
116607
  }
116480
- return { content: [{ type: "text", text: SHOWN_RESULT }] };
116608
+ return { content: [{ type: "text", text: WIDGET_SHOWN_RESULT }] };
116481
116609
  }
116482
116610
  )
116483
116611
  ]
@@ -116573,9 +116701,9 @@ function mapToolUse(block) {
116573
116701
  };
116574
116702
  }
116575
116703
  function deriveFileChangeData(input, toolName) {
116576
- const path17 = input.file_path ?? input.notebook_path ?? "";
116704
+ const path19 = input.file_path ?? input.notebook_path ?? "";
116577
116705
  const kind = toolName === "Write" ? "add" : "modify";
116578
- return { changes: [{ path: path17, kind }], status: "in_progress" };
116706
+ return { changes: [{ path: path19, kind }], status: "in_progress" };
116579
116707
  }
116580
116708
  function extractToolResultText(content) {
116581
116709
  if (!content) return "";
@@ -116683,6 +116811,12 @@ function parseTranscript(text2) {
116683
116811
  link.origin = raw.origin ?? null;
116684
116812
  link.message = raw.message ?? null;
116685
116813
  link.toolUseResult = raw.toolUseResult;
116814
+ } else if (raw.type === "attachment") {
116815
+ const attachment = raw.attachment;
116816
+ if (attachment?.type === "queued_command" && attachment.origin?.kind === "peer") {
116817
+ link.origin = attachment.origin;
116818
+ link.queuedPrompt = typeof attachment.prompt === "string" ? attachment.prompt : "";
116819
+ }
116686
116820
  }
116687
116821
  entries.push(link);
116688
116822
  }
@@ -116756,6 +116890,21 @@ function classifyUserInput(entry) {
116756
116890
  const imageNote = images > 0 && !trimmed.includes("[Image") ? Array(images).fill("[Image]").join(" ") : "";
116757
116891
  return { kind: "prompt", text: [trimmed, imageNote].filter(Boolean).join("\n") };
116758
116892
  }
116893
+ function hasToolResult(content) {
116894
+ return Array.isArray(content) && content.some((b) => b?.type === "tool_result");
116895
+ }
116896
+ var PEER_ENVELOPE = /<cross-session-message\b[^>]*>([\s\S]*?)<\/cross-session-message>/;
116897
+ function peerMessageData(origin, content) {
116898
+ let body = typeof origin.body === "string" ? origin.body.trim() : "";
116899
+ if (!body) {
116900
+ const text2 = typeof content === "string" ? content : Array.isArray(content) ? content.map(
116901
+ (b) => b && typeof b === "object" && b.type === "text" ? String(b.text ?? "") : ""
116902
+ ).join("\n") : "";
116903
+ const enveloped = PEER_ENVELOPE.exec(text2);
116904
+ body = (enveloped ? enveloped[1] : text2).trim();
116905
+ }
116906
+ return { name: origin.name?.trim() || null, from: origin.from ?? null, body };
116907
+ }
116759
116908
  function syntheticText(content) {
116760
116909
  if (typeof content === "string") return content;
116761
116910
  if (!Array.isArray(content)) return "";
@@ -116776,6 +116925,8 @@ function buildTurns(chain) {
116776
116925
  const at = stamp(entry);
116777
116926
  const turn = {
116778
116927
  userPrompt: prompt,
116928
+ origin: null,
116929
+ originName: null,
116779
116930
  status: "completed",
116780
116931
  agentResponse: null,
116781
116932
  thoughts: null,
@@ -116808,7 +116959,25 @@ function buildTurns(chain) {
116808
116959
  }
116809
116960
  continue;
116810
116961
  }
116962
+ if (entry.type === "attachment") {
116963
+ if (entry.origin?.kind === "peer" && current) {
116964
+ addItem(current, entry, {
116965
+ type: "peer_message",
116966
+ externalId: `peer-${entry.uuid}`,
116967
+ data: peerMessageData(entry.origin, entry.queuedPrompt ?? ""),
116968
+ status: "completed"
116969
+ });
116970
+ }
116971
+ continue;
116972
+ }
116811
116973
  if (entry.type === "user") {
116974
+ if (entry.origin?.kind === "peer" && !hasToolResult(entry.message?.content)) {
116975
+ const data = peerMessageData(entry.origin, entry.message?.content);
116976
+ current = openTurn(data.body, entry);
116977
+ current.origin = "peer";
116978
+ current.originName = data.name;
116979
+ continue;
116980
+ }
116812
116981
  if (entry.isMeta || entry.isCompactSummary) continue;
116813
116982
  const content = entry.message?.content;
116814
116983
  if (Array.isArray(content) && content.some((b) => b?.type === "tool_result")) {
@@ -116940,7 +117109,7 @@ async function realDir(dir) {
116940
117109
  }
116941
117110
  }
116942
117111
  async function sameDir(a, realB) {
116943
- const realA = await realDir(a) ?? path10.resolve(a);
117112
+ const realA = await realDir(a) ?? path11.resolve(a);
116944
117113
  return realA === realB;
116945
117114
  }
116946
117115
  function knownClaudeSessionIds(db2) {
@@ -117021,8 +117190,8 @@ async function importClaudeSession(db2, claudeSessionId, workspacePath) {
117021
117190
  );
117022
117191
  const insertTurn = db2.prepare(
117023
117192
  `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status,
117024
- error, created_at, updated_at)
117025
- VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, ?)`
117193
+ error, origin, origin_name, created_at, updated_at)
117194
+ VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, ?, ?, ?)`
117026
117195
  );
117027
117196
  const insertItem2 = db2.prepare(
117028
117197
  `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
@@ -117052,6 +117221,8 @@ async function importClaudeSession(db2, claudeSessionId, workspacePath) {
117052
117221
  turn.thoughts,
117053
117222
  turn.externalTurnId,
117054
117223
  turn.status,
117224
+ turn.origin ?? null,
117225
+ turn.originName ?? null,
117055
117226
  turn.createdAt,
117056
117227
  turn.updatedAt
117057
117228
  );
@@ -117106,9 +117277,523 @@ async function registerClaudeSessionRoutes(fastify) {
117106
117277
  );
117107
117278
  }
117108
117279
 
117109
- // src/session-host/flags.ts
117280
+ // src/codex/session-import.ts
117281
+ import { realpath as realpath2 } from "node:fs/promises";
117282
+ import path13 from "node:path";
117283
+
117284
+ // src/apps/register-mcp.ts
117110
117285
  import fs7 from "node:fs";
117111
- import path11 from "node:path";
117286
+ import path12 from "node:path";
117287
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
117288
+ var MCP_SERVER_NAME = "agentpane-miniapps";
117289
+ function panePublicUrl() {
117290
+ return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
117291
+ }
117292
+ function stdioScriptPath() {
117293
+ const here = path12.dirname(fileURLToPath2(import.meta.url));
117294
+ const candidates = [
117295
+ path12.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
117296
+ // src/apps/ → backend/scripts
117297
+ path12.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
117298
+ // dist bundle → backend/scripts
117299
+ ];
117300
+ for (const candidate of candidates) {
117301
+ if (fs7.existsSync(candidate)) return candidate;
117302
+ }
117303
+ return null;
117304
+ }
117305
+ var registered = /* @__PURE__ */ new Set();
117306
+ async function registerMiniAppMcp(baseUrl, workspace = "") {
117307
+ const key = `${baseUrl}|${workspace}`;
117308
+ if (registered.has(key)) return true;
117309
+ const script = stdioScriptPath();
117310
+ if (!script) {
117311
+ console.warn("[miniapp-mcp] stdio proxy script not found \u2014 registration skipped");
117312
+ return false;
117313
+ }
117314
+ if (!anyAppHasTools()) {
117315
+ return false;
117316
+ }
117317
+ const base = baseUrl.replace(/\/+$/, "");
117318
+ try {
117319
+ try {
117320
+ const res2 = await fetch(`${base}/mcp/servers`, { signal: AbortSignal.timeout(5e3) });
117321
+ if (res2.ok) {
117322
+ const servers = await res2.json();
117323
+ const names = servers.map((s) => s.server_name ?? s.name);
117324
+ if (names.includes(MCP_SERVER_NAME)) {
117325
+ await fetch(`${base}/mcp/configs/${MCP_SERVER_NAME}`, {
117326
+ method: "DELETE",
117327
+ signal: AbortSignal.timeout(5e3)
117328
+ }).catch(() => {
117329
+ });
117330
+ }
117331
+ }
117332
+ } catch {
117333
+ }
117334
+ const body = {
117335
+ configJson: JSON.stringify({
117336
+ [MCP_SERVER_NAME]: {
117337
+ command: process.execPath,
117338
+ args: [script, panePublicUrl(), workspace],
117339
+ env: { AGENT_PANE_SESSION_ID: "" }
117340
+ }
117341
+ })
117342
+ };
117343
+ const res = await fetch(`${base}/mcp/configs`, {
117344
+ method: "POST",
117345
+ headers: { "Content-Type": "application/json" },
117346
+ body: JSON.stringify(body),
117347
+ signal: AbortSignal.timeout(1e4)
117348
+ });
117349
+ if (res.status === 201) {
117350
+ console.log(`[miniapp-mcp] gateway registered in workspace backend ${base} (workspace: ${workspace || "global"})`);
117351
+ registered.add(key);
117352
+ return true;
117353
+ }
117354
+ const text2 = await res.text();
117355
+ if (res.status === 400 && /already exists/i.test(text2)) {
117356
+ registered.add(key);
117357
+ return true;
117358
+ }
117359
+ console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
117360
+ return false;
117361
+ } catch (err) {
117362
+ console.warn(`[miniapp-mcp] registration error: ${err.message}`);
117363
+ return false;
117364
+ }
117365
+ }
117366
+ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
117367
+ const script = stdioScriptPath();
117368
+ if (!script) return null;
117369
+ return [
117370
+ // MCP tool calls must not ask for elicitation approval — nobody is
117371
+ // watching an agent-driven session to approve (feature is stable/on).
117372
+ "-c",
117373
+ "features.tool_call_mcp_elicitation=false",
117374
+ "-c",
117375
+ `mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
117376
+ "-c",
117377
+ `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
117378
+ ];
117379
+ }
117380
+
117381
+ // src/codex/item-mapper.ts
117382
+ function paneStatus(status) {
117383
+ switch (status) {
117384
+ case "inProgress":
117385
+ case "in_progress":
117386
+ return "in_progress";
117387
+ case "completed":
117388
+ return "completed";
117389
+ case "failed":
117390
+ case "declined":
117391
+ return "failed";
117392
+ default:
117393
+ return void 0;
117394
+ }
117395
+ }
117396
+ function errorText(error51) {
117397
+ if (!error51) return null;
117398
+ if (typeof error51 === "string") return error51;
117399
+ const message = error51.message;
117400
+ return typeof message === "string" ? message : JSON.stringify(error51);
117401
+ }
117402
+ function resultText(result) {
117403
+ const content = result?.content;
117404
+ if (!Array.isArray(content)) return "";
117405
+ return content.map((part) => typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
117406
+ }
117407
+ function isWidgetCall(item) {
117408
+ return item.type === "mcpToolCall" && item.server === MCP_SERVER_NAME && item.tool === WIDGET_TOOL_BASE_NAME;
117409
+ }
117410
+ var ITEM_TYPES = {
117411
+ agentMessage: "agent_message",
117412
+ userMessage: "user_message",
117413
+ agentReasoning: "reasoning",
117414
+ commandExecution: "command_execution",
117415
+ fileChange: "file_change",
117416
+ mcpToolCall: "mcp_tool_call",
117417
+ webSearch: "web_search",
117418
+ todoList: "todo_list",
117419
+ contextCompaction: "context_compaction",
117420
+ error: "error"
117421
+ };
117422
+ function mapItemType(item) {
117423
+ if (isWidgetCall(item)) return "widget";
117424
+ return ITEM_TYPES[item.type] ?? item.type;
117425
+ }
117426
+ function mapItemData(item) {
117427
+ switch (item.type) {
117428
+ case "agentMessage":
117429
+ case "agent_message":
117430
+ return { text: item.text };
117431
+ case "reasoning":
117432
+ case "agentReasoning": {
117433
+ const summary = Array.isArray(item.summary) ? item.summary.join("\n") : "";
117434
+ return { text: summary || item.text || "" };
117435
+ }
117436
+ case "commandExecution":
117437
+ case "command_execution":
117438
+ return {
117439
+ command: item.command,
117440
+ aggregated_output: item.aggregatedOutput ?? item.aggregated_output,
117441
+ exit_code: item.exitCode ?? item.exit_code ?? null,
117442
+ status: paneStatus(item.status)
117443
+ };
117444
+ case "fileChange":
117445
+ case "file_change":
117446
+ return {
117447
+ changes: item.changes,
117448
+ status: paneStatus(item.status)
117449
+ };
117450
+ case "mcpToolCall":
117451
+ case "mcp_tool_call":
117452
+ if (isWidgetCall(item)) {
117453
+ const args = item.arguments ?? {};
117454
+ const failed = paneStatus(item.status) === "failed";
117455
+ return {
117456
+ title: typeof args.title === "string" ? args.title : "",
117457
+ html: typeof args.widget_code === "string" ? args.widget_code : "",
117458
+ error: failed ? errorText(item.error) || resultText(item.result) || "Tool error" : null
117459
+ };
117460
+ }
117461
+ return {
117462
+ server: item.server,
117463
+ tool: item.tool,
117464
+ arguments: item.arguments,
117465
+ result: item.result ?? null,
117466
+ error: errorText(item.error),
117467
+ status: paneStatus(item.status)
117468
+ };
117469
+ case "webSearch":
117470
+ case "web_search":
117471
+ return { query: item.query };
117472
+ case "todoList":
117473
+ case "todo_list":
117474
+ return { items: item.items };
117475
+ case "contextCompaction":
117476
+ return { trigger: "auto", pre_tokens: null, post_tokens: null };
117477
+ case "error":
117478
+ return { message: item.message };
117479
+ default:
117480
+ return {};
117481
+ }
117482
+ }
117483
+ function getItemStatus(item) {
117484
+ if (item.type === "commandExecution" || item.type === "command_execution" || item.type === "fileChange" || item.type === "file_change" || item.type === "mcpToolCall" || item.type === "mcp_tool_call") {
117485
+ return paneStatus(item.status) ?? "completed";
117486
+ }
117487
+ if (item.type === "error") {
117488
+ return "failed";
117489
+ }
117490
+ return "completed";
117491
+ }
117492
+
117493
+ // src/codex/known-threads.ts
117494
+ var PANE_THREAD_SOURCE = "agentpane";
117495
+ function recordCodexThread(threadId, sessionId) {
117496
+ try {
117497
+ getDb().prepare("INSERT OR IGNORE INTO codex_threads (thread_id, session_id, created_at) VALUES (?, ?, ?)").run(threadId, sessionId, (/* @__PURE__ */ new Date()).toISOString());
117498
+ } catch {
117499
+ }
117500
+ }
117501
+ function knownCodexThreadIds(db2) {
117502
+ const rows = db2.prepare(
117503
+ `SELECT external_thread_id AS id FROM sessions WHERE external_thread_id IS NOT NULL
117504
+ UNION SELECT pre_rewind_thread_id FROM sessions WHERE pre_rewind_thread_id IS NOT NULL
117505
+ UNION SELECT import_source_id FROM sessions WHERE import_source_id IS NOT NULL
117506
+ UNION SELECT external_thread_id FROM discussion_threads WHERE external_thread_id IS NOT NULL
117507
+ UNION SELECT thread_id FROM codex_threads`
117508
+ ).all();
117509
+ return new Set(rows.map((row) => row.id));
117510
+ }
117511
+
117512
+ // src/codex/review-turns.ts
117513
+ function isReview(turn) {
117514
+ return (turn.items ?? []).some((item) => item.type === "enteredReviewMode");
117515
+ }
117516
+ function isInsideReview(review, turn) {
117517
+ return isReview(review) && review.completedAt != null && turn.startedAt != null && turn.startedAt < review.completedAt;
117518
+ }
117519
+ function forkThroughReview(turns, turnId) {
117520
+ const index = turns.findIndex((turn) => turn.id === turnId);
117521
+ if (index < 0 || !isReview(turns[index])) return void 0;
117522
+ let next = index + 1;
117523
+ while (next < turns.length && isInsideReview(turns[index], turns[next])) next++;
117524
+ if (next < turns.length - 1 && isInsideReview(turns[next], turns[next + 1])) next++;
117525
+ return next < turns.length ? { beforeTurnId: turns[next].id } : {};
117526
+ }
117527
+
117528
+ // src/codex/session-import.ts
117529
+ var CodexImportError = class extends Error {
117530
+ status;
117531
+ paneSessionId;
117532
+ constructor(status, message, paneSessionId = null) {
117533
+ super(message);
117534
+ this.name = "CodexImportError";
117535
+ this.status = status;
117536
+ this.paneSessionId = paneSessionId;
117537
+ }
117538
+ };
117539
+ var RECENT_MS2 = 10 * 6e4;
117540
+ var THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
117541
+ var TITLE_MAX2 = 100;
117542
+ var LIST_PAGE = 100;
117543
+ var LIST_MAX = 1e3;
117544
+ var USER_SOURCES = ["cli", "vscode", "exec", "appServer", "unknown"];
117545
+ var THROWAWAY_PROMPTS = ["Generate a concise 3-5 word title", "You are summarizing a side discussion thread"];
117546
+ async function realDir2(dir) {
117547
+ try {
117548
+ return await realpath2(dir);
117549
+ } catch {
117550
+ return null;
117551
+ }
117552
+ }
117553
+ async function workspaceDirs(workspacePath) {
117554
+ const real = await realDir2(workspacePath);
117555
+ if (!real) return null;
117556
+ const given = path13.resolve(workspacePath);
117557
+ return given === real ? [real] : [given, real];
117558
+ }
117559
+ function titleOf2(thread) {
117560
+ const raw = (thread.name || thread.preview || "").trim();
117561
+ const firstLine = raw.split("\n")[0].trim();
117562
+ return firstLine.length > TITLE_MAX2 ? `${firstLine.slice(0, TITLE_MAX2 - 1)}\u2026` : firstLine;
117563
+ }
117564
+ function isThrowaway(thread) {
117565
+ const preview = (thread.preview ?? "").trimStart();
117566
+ return THROWAWAY_PROMPTS.some((prompt) => preview.startsWith(prompt));
117567
+ }
117568
+ function paneSessionHolding2(db2, threadId) {
117569
+ const row = db2.prepare(
117570
+ `SELECT id FROM sessions WHERE import_source_id = ? OR external_thread_id = ? OR pre_rewind_thread_id = ?
117571
+ UNION ALL SELECT session_id FROM discussion_threads WHERE external_thread_id = ?
117572
+ UNION ALL SELECT session_id FROM codex_threads WHERE thread_id = ?
117573
+ LIMIT 1`
117574
+ ).get(threadId, threadId, threadId, threadId, threadId);
117575
+ return row ? { sessionId: row.id } : null;
117576
+ }
117577
+ async function listImportableCodexSessions(db2, workspacePath, now = Date.now()) {
117578
+ const dirs = await workspaceDirs(workspacePath);
117579
+ if (!dirs) return [];
117580
+ const known = knownCodexThreadIds(db2);
117581
+ const client = getSharedAppServer();
117582
+ const sessions = [];
117583
+ let cursor = null;
117584
+ let seen = 0;
117585
+ do {
117586
+ const page = await client.request("thread/list", {
117587
+ cwd: dirs,
117588
+ limit: LIST_PAGE,
117589
+ cursor,
117590
+ sortKey: "updated_at",
117591
+ sourceKinds: USER_SOURCES
117592
+ });
117593
+ for (const thread of page.data ?? []) {
117594
+ seen += 1;
117595
+ if (known.has(thread.id) || thread.parentThreadId || thread.ephemeral || isThrowaway(thread)) continue;
117596
+ const title = titleOf2(thread);
117597
+ if (!title) continue;
117598
+ const updatedMs = thread.updatedAt * 1e3;
117599
+ sessions.push({
117600
+ session_id: thread.id,
117601
+ title,
117602
+ cwd: thread.cwd,
117603
+ git_branch: thread.gitInfo?.branch ?? null,
117604
+ created_at: new Date(thread.createdAt * 1e3).toISOString(),
117605
+ last_modified: new Date(updatedMs).toISOString(),
117606
+ recently_active: now - updatedMs < RECENT_MS2
117607
+ });
117608
+ }
117609
+ cursor = page.nextCursor;
117610
+ } while (cursor && seen < LIST_MAX);
117611
+ return sessions.sort((a, b) => a.last_modified < b.last_modified ? 1 : -1);
117612
+ }
117613
+ var TURN_STATUS = {
117614
+ completed: "completed",
117615
+ failed: "failed",
117616
+ interrupted: "aborted",
117617
+ inProgress: "aborted"
117618
+ };
117619
+ function userText(item) {
117620
+ const content = Array.isArray(item.content) ? item.content : [];
117621
+ return content.map((part) => {
117622
+ if (part.type === "text" && typeof part.text === "string") return part.text;
117623
+ if (part.type === "image") return "[image]";
117624
+ if (part.type === "localImage" && typeof part.path === "string") return `[image: ${part.path}]`;
117625
+ return "";
117626
+ }).filter(Boolean).join("\n");
117627
+ }
117628
+ function skipped(item, data) {
117629
+ if (item.type === "userMessage" || item.type === "enteredReviewMode" || item.type === "exitedReviewMode") return true;
117630
+ return (item.type === "reasoning" || item.type === "agentReasoning") && !data.text;
117631
+ }
117632
+ function threadToTurns(thread) {
117633
+ const turns = [];
117634
+ const stored = thread.turns ?? [];
117635
+ let last = thread.createdAt * 1e3 - 1;
117636
+ for (const [position, turn] of stored.entries()) {
117637
+ if (position > 0 && isInsideReview(stored[position - 1], turn)) continue;
117638
+ const items = turn.items ?? [];
117639
+ const prompt = items.filter((item) => item.type === "userMessage").map(userText).filter(Boolean).join("\n\n");
117640
+ const command = items.some((item) => item.type === "enteredReviewMode") ? "/review" : items.some((item) => item.type === "contextCompaction") ? "/compact" : "";
117641
+ const output = [];
117642
+ let agentResponse = null;
117643
+ let review = null;
117644
+ let thoughts = null;
117645
+ const started = Math.max(last + 1, (turn.startedAt ?? 0) * 1e3);
117646
+ for (const [index, item] of items.entries()) {
117647
+ if (item.type === "exitedReviewMode" && typeof item.review === "string" && item.review.trim())
117648
+ review = item.review;
117649
+ const data = mapItemData(item);
117650
+ if (skipped(item, data)) continue;
117651
+ if (item.type === "agentMessage" || item.type === "agent_message") agentResponse = item.text ?? agentResponse;
117652
+ if ((item.type === "reasoning" || item.type === "agentReasoning") && typeof data.text === "string") {
117653
+ thoughts = data.text;
117654
+ }
117655
+ const status = getItemStatus(item);
117656
+ output.push({
117657
+ externalId: item.id,
117658
+ type: mapItemType(item),
117659
+ data,
117660
+ // Left open when its turn ended: it never finished.
117661
+ status: status === "in_progress" ? "failed" : status,
117662
+ createdAt: new Date(started + index).toISOString()
117663
+ });
117664
+ }
117665
+ const userPrompt = prompt || command;
117666
+ if (!userPrompt && output.length === 0) continue;
117667
+ const ended = Math.max(started, (turn.completedAt ?? 0) * 1e3);
117668
+ turns.push({
117669
+ userPrompt,
117670
+ agentResponse: agentResponse ?? review,
117671
+ thoughts,
117672
+ externalTurnId: turn.id,
117673
+ status: TURN_STATUS[turn.status] ?? "completed",
117674
+ error: turn.status === "failed" ? turn.error?.message ?? "Codex turn failed" : null,
117675
+ createdAt: new Date(started).toISOString(),
117676
+ updatedAt: new Date(ended).toISOString(),
117677
+ items: output
117678
+ });
117679
+ last = started;
117680
+ }
117681
+ return turns;
117682
+ }
117683
+ async function importCodexSession(db2, threadId, workspacePath) {
117684
+ if (!THREAD_ID.test(threadId)) throw new CodexImportError(400, "Not a Codex thread id");
117685
+ const holder = paneSessionHolding2(db2, threadId);
117686
+ if (holder) throw new CodexImportError(409, "This thread is already in the pane", holder.sessionId);
117687
+ let thread;
117688
+ try {
117689
+ ({ thread } = await getSharedAppServer().request("thread/read", {
117690
+ threadId,
117691
+ includeTurns: true
117692
+ }));
117693
+ } catch (err) {
117694
+ throw new CodexImportError(404, `Codex thread not found: ${err.message}`);
117695
+ }
117696
+ const turns = threadToTurns(thread);
117697
+ if (turns.length === 0) throw new CodexImportError(422, "This thread has no conversation to import");
117698
+ const dirs = workspacePath ? await workspaceDirs(workspacePath) : null;
117699
+ const cwd = workspacePath && dirs?.includes(thread.cwd) ? workspacePath : thread.cwd;
117700
+ const sessionId = v4_default();
117701
+ const insertSession = db2.prepare(
117702
+ `INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status,
117703
+ is_running, lifecycle, sort_order, user_touched, import_source_id, created_at, updated_at)
117704
+ VALUES (?, ?, 'codex', NULL, NULL, ?, ?, 'active', 0, 'working', ?, 1, ?, ?, ?)`
117705
+ );
117706
+ const insertTurn = db2.prepare(
117707
+ `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status,
117708
+ error, created_at, updated_at)
117709
+ VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)`
117710
+ );
117711
+ const insertItem2 = db2.prepare(
117712
+ `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
117713
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
117714
+ );
117715
+ db2.transaction(() => {
117716
+ const raced = paneSessionHolding2(db2, threadId);
117717
+ if (raced) throw new CodexImportError(409, "This thread is already in the pane", raced.sessionId);
117718
+ const { m } = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd);
117719
+ insertSession.run(
117720
+ sessionId,
117721
+ titleOf2(thread) || null,
117722
+ cwd,
117723
+ threadId,
117724
+ m + 1,
117725
+ threadId,
117726
+ turns[0].createdAt,
117727
+ turns[turns.length - 1].updatedAt
117728
+ );
117729
+ for (const turn of turns) {
117730
+ const turnId = v4_default();
117731
+ insertTurn.run(
117732
+ turnId,
117733
+ sessionId,
117734
+ turn.userPrompt,
117735
+ turn.agentResponse,
117736
+ turn.thoughts,
117737
+ turn.externalTurnId,
117738
+ turn.status,
117739
+ turn.error,
117740
+ turn.createdAt,
117741
+ turn.updatedAt
117742
+ );
117743
+ for (const item of turn.items) {
117744
+ insertItem2.run(
117745
+ v4_default(),
117746
+ turnId,
117747
+ item.externalId,
117748
+ item.type,
117749
+ JSON.stringify(trimItemData(item.data)),
117750
+ item.status,
117751
+ item.createdAt,
117752
+ item.createdAt
117753
+ );
117754
+ }
117755
+ }
117756
+ })();
117757
+ return db2.prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
117758
+ }
117759
+
117760
+ // src/routes/codex-sessions.ts
117761
+ async function registerCodexSessionRoutes(fastify) {
117762
+ fastify.get("/api/codex-sessions", async (request, reply) => {
117763
+ const workspace = request.query.workspace?.trim();
117764
+ if (!workspace) return reply.code(400).send({ error: "workspace is required" });
117765
+ try {
117766
+ return { sessions: await listImportableCodexSessions(getDb(), workspace) };
117767
+ } catch (err) {
117768
+ return reply.code(500).send({ error: `Could not list Codex sessions: ${err.message}` });
117769
+ }
117770
+ });
117771
+ fastify.post(
117772
+ "/api/codex-sessions/:id/import",
117773
+ {
117774
+ schema: {
117775
+ body: {
117776
+ type: ["object", "null"],
117777
+ properties: { workspace: { type: ["string", "null"] } }
117778
+ }
117779
+ }
117780
+ },
117781
+ async (request, reply) => {
117782
+ try {
117783
+ return await importCodexSession(getDb(), request.params.id, request.body?.workspace?.trim() || null);
117784
+ } catch (err) {
117785
+ if (err instanceof CodexImportError) {
117786
+ return reply.code(err.status).send({ error: err.message, session_id: err.paneSessionId });
117787
+ }
117788
+ return reply.code(500).send({ error: `Import failed: ${err.message}` });
117789
+ }
117790
+ }
117791
+ );
117792
+ }
117793
+
117794
+ // src/session-host/flags.ts
117795
+ import fs8 from "node:fs";
117796
+ import path14 from "node:path";
117112
117797
  var DEFAULT_FLAGS = {
117113
117798
  claude: true,
117114
117799
  codex: true,
@@ -117127,18 +117812,18 @@ function setPaneDataDir(dir) {
117127
117812
  }
117128
117813
  function sessionHostsRoot() {
117129
117814
  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;
117815
+ if (override) return path14.resolve(override);
117816
+ return paneDataDir ? path14.join(paneDataDir, "session-hosts") : null;
117132
117817
  }
117133
117818
  function flagsFilePath() {
117134
117819
  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;
117820
+ if (process.env.AGENT_PANE_SESSION_HOSTS_DIR) return path14.join(path14.dirname(root), "session-hosts.json");
117821
+ return paneDataDir ? path14.join(paneDataDir, "session-hosts.json") : null;
117137
117822
  }
117138
117823
  function readFlagFile(file2) {
117139
117824
  if (!file2) return {};
117140
117825
  try {
117141
- const parsed = JSON.parse(fs7.readFileSync(file2, "utf8"));
117826
+ const parsed = JSON.parse(fs8.readFileSync(file2, "utf8"));
117142
117827
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
117143
117828
  console.warn(`[session-host] ${file2} is not a JSON object; using the defaults`);
117144
117829
  } catch (err) {
@@ -117204,17 +117889,17 @@ var LOG_HEADER_LEN = LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS + 1;
117204
117889
 
117205
117890
  // src/session-host/registry.ts
117206
117891
  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";
117892
+ import fs10 from "node:fs";
117893
+ import path16 from "node:path";
117894
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
117210
117895
 
117211
117896
  // src/session-host/client.ts
117212
117897
  import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
117213
117898
  import { EventEmitter as EventEmitter2 } from "node:events";
117214
- import fs8 from "node:fs";
117899
+ import fs9 from "node:fs";
117215
117900
  import net2 from "node:net";
117216
- import path12 from "node:path";
117217
- import { fileURLToPath as fileURLToPath2 } from "node:url";
117901
+ import path15 from "node:path";
117902
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
117218
117903
  var HostRequestError = class extends Error {
117219
117904
  reply;
117220
117905
  constructor(reply) {
@@ -117225,36 +117910,36 @@ var HostRequestError = class extends Error {
117225
117910
  function hostScriptPath() {
117226
117911
  const override = process.env.AGENT_PANE_SESSION_HOST_SCRIPT;
117227
117912
  if (override) return override;
117228
- const here = path12.dirname(fileURLToPath2(import.meta.url));
117913
+ const here = path15.dirname(fileURLToPath3(import.meta.url));
117229
117914
  const candidates = [
117230
- path12.resolve(here, "../../scripts/session-host.mjs"),
117915
+ path15.resolve(here, "../../scripts/session-host.mjs"),
117231
117916
  // src/session-host/ → backend/scripts
117232
- path12.resolve(here, "../scripts/session-host.mjs")
117917
+ path15.resolve(here, "../scripts/session-host.mjs")
117233
117918
  // dist bundle → backend/scripts
117234
117919
  ];
117235
117920
  for (const candidate of candidates) {
117236
- if (fs8.existsSync(candidate)) return candidate;
117921
+ if (fs9.existsSync(candidate)) return candidate;
117237
117922
  }
117238
117923
  return null;
117239
117924
  }
117240
117925
  function hostSocketPath(dir) {
117241
- const direct = path12.join(dir, "sock");
117926
+ const direct = path15.join(dir, "sock");
117242
117927
  if (Buffer.byteLength(direct) < 100) return direct;
117243
117928
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
117244
- return path12.join("/tmp", `rbsh-${uid}`, path12.basename(dir), "sock");
117929
+ return path15.join("/tmp", `rbsh-${uid}`, path15.basename(dir), "sock");
117245
117930
  }
117246
117931
  function readJson(file2) {
117247
117932
  try {
117248
- return JSON.parse(fs8.readFileSync(file2, "utf8"));
117933
+ return JSON.parse(fs9.readFileSync(file2, "utf8"));
117249
117934
  } catch {
117250
117935
  return null;
117251
117936
  }
117252
117937
  }
117253
117938
  function readHostExit(dir) {
117254
- return readJson(path12.join(dir, "exit.json"));
117939
+ return readJson(path15.join(dir, "exit.json"));
117255
117940
  }
117256
117941
  function readHostChild(dir) {
117257
- return readJson(path12.join(dir, "child.json"));
117942
+ return readJson(path15.join(dir, "child.json"));
117258
117943
  }
117259
117944
  function isPidAlive(pid) {
117260
117945
  if (!pid || pid <= 0) return false;
@@ -117409,8 +118094,8 @@ function attachHost(dir, after, timeoutMs = 5e3) {
117409
118094
  function startHost(opts) {
117410
118095
  const script = hostScriptPath();
117411
118096
  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);
118097
+ fs9.mkdirSync(opts.dir, { recursive: true, mode: 448 });
118098
+ fs9.chmodSync(opts.dir, 448);
117414
118099
  const env = {};
117415
118100
  for (const [k, v] of Object.entries(opts.env)) if (v !== void 0) env[k] = v;
117416
118101
  const child = spawn4(opts.nodePath ?? process.execPath, [script, opts.dir, JSON.stringify(opts.config), opts.command, ...opts.args], {
@@ -117444,9 +118129,9 @@ async function waitForHost(dir, timeoutMs = 1e4) {
117444
118129
  function readLogOldest(dir) {
117445
118130
  let fd = null;
117446
118131
  try {
117447
- fd = fs8.openSync(path12.join(dir, "out.log"), "r");
118132
+ fd = fs9.openSync(path15.join(dir, "out.log"), "r");
117448
118133
  const buf = Buffer.alloc(LOG_HEADER_LEN);
117449
- const n = fs8.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
118134
+ const n = fs9.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
117450
118135
  const text2 = buf.subarray(0, n).toString("utf8");
117451
118136
  if (n < LOG_HEADER_LEN || !text2.startsWith(LOG_HEADER_PREFIX) || text2[LOG_HEADER_LEN - 1] !== "\n") return null;
117452
118137
  const digits = text2.slice(LOG_HEADER_PREFIX.length, LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS);
@@ -117454,14 +118139,14 @@ function readLogOldest(dir) {
117454
118139
  } catch {
117455
118140
  return null;
117456
118141
  } finally {
117457
- if (fd !== null) fs8.closeSync(fd);
118142
+ if (fd !== null) fs9.closeSync(fd);
117458
118143
  }
117459
118144
  }
117460
118145
  function readHostLog(dir, after) {
117461
118146
  const oldest = readLogOldest(dir);
117462
118147
  if (oldest === null || after < oldest) return null;
117463
118148
  try {
117464
- const all = fs8.readFileSync(path12.join(dir, "out.log"));
118149
+ const all = fs9.readFileSync(path15.join(dir, "out.log"));
117465
118150
  const start = LOG_HEADER_LEN + (after - oldest);
117466
118151
  if (start > all.length) return null;
117467
118152
  return all.subarray(start);
@@ -117471,14 +118156,14 @@ function readHostLog(dir, after) {
117471
118156
  }
117472
118157
  function removeHostDir(dir) {
117473
118158
  try {
117474
- fs8.rmSync(dir, { recursive: true, force: true });
118159
+ fs9.rmSync(dir, { recursive: true, force: true });
117475
118160
  } catch (err) {
117476
118161
  console.error(`[session-host] could not remove ${dir}:`, err.message);
117477
118162
  }
117478
- const alias = path12.dirname(hostSocketPath(dir));
118163
+ const alias = path15.dirname(hostSocketPath(dir));
117479
118164
  if (alias !== dir) {
117480
118165
  try {
117481
- fs8.unlinkSync(alias);
118166
+ fs9.unlinkSync(alias);
117482
118167
  } catch {
117483
118168
  }
117484
118169
  }
@@ -117524,6 +118209,9 @@ function setStartupGate(started) {
117524
118209
  if (startupGate === gate) startupPending = false;
117525
118210
  });
117526
118211
  }
118212
+ function noteAdoptedTurn(turnId) {
118213
+ if (startupPending) lastResult.turnIds.add(turnId);
118214
+ }
117527
118215
  function lastAdoption() {
117528
118216
  return lastResult;
117529
118217
  }
@@ -117535,16 +118223,16 @@ function newHostDir() {
117535
118223
  const root = sessionHostsRoot();
117536
118224
  if (!root) throw new Error("session hosts have no directory");
117537
118225
  const id = randomBytes(8).toString("hex");
117538
- return { id, dir: path13.join(root, id) };
118226
+ return { id, dir: path16.join(root, id) };
117539
118227
  }
117540
118228
  var cachedVersion;
117541
118229
  function runtimeVersion() {
117542
118230
  if (cachedVersion !== void 0) return cachedVersion;
117543
118231
  cachedVersion = null;
117544
- const here = path13.dirname(fileURLToPath3(import.meta.url));
118232
+ const here = path16.dirname(fileURLToPath4(import.meta.url));
117545
118233
  for (const rel of ["../../../../package.json", "../../../package.json"]) {
117546
118234
  try {
117547
- const pkg = JSON.parse(fs9.readFileSync(path13.resolve(here, rel), "utf8"));
118235
+ const pkg = JSON.parse(fs10.readFileSync(path16.resolve(here, rel), "utf8"));
117548
118236
  if (pkg.name === "repoburg" && pkg.version) {
117549
118237
  cachedVersion = pkg.version;
117550
118238
  break;
@@ -117555,15 +118243,15 @@ function runtimeVersion() {
117555
118243
  return cachedVersion;
117556
118244
  }
117557
118245
  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"));
118246
+ fs10.mkdirSync(dir, { recursive: true, mode: 448 });
118247
+ fs10.chmodSync(dir, 448);
118248
+ const tmp = path16.join(dir, "meta.json.tmp");
118249
+ fs10.writeFileSync(tmp, JSON.stringify(meta3, null, 2) + "\n", { mode: 384 });
118250
+ fs10.renameSync(tmp, path16.join(dir, "meta.json"));
117563
118251
  }
117564
118252
  function readHostMeta(dir) {
117565
118253
  try {
117566
- return JSON.parse(fs9.readFileSync(path13.join(dir, "meta.json"), "utf8"));
118254
+ return JSON.parse(fs10.readFileSync(path16.join(dir, "meta.json"), "utf8"));
117567
118255
  } catch {
117568
118256
  return null;
117569
118257
  }
@@ -117701,16 +118389,16 @@ async function runAdoption() {
117701
118389
  async function adoptHosts(db2, root, adoption, result) {
117702
118390
  let entries = [];
117703
118391
  try {
117704
- entries = fs9.readdirSync(root);
118392
+ entries = fs10.readdirSync(root);
117705
118393
  } catch (err) {
117706
118394
  if (err.code !== "ENOENT") console.error("[session-host] cannot read", root, err.message);
117707
118395
  }
117708
118396
  const seen = /* @__PURE__ */ new Set();
117709
118397
  const queue = [];
117710
118398
  for (const id of entries) {
117711
- const dir = path13.join(root, id);
118399
+ const dir = path16.join(root, id);
117712
118400
  try {
117713
- if (!fs9.statSync(dir).isDirectory()) continue;
118401
+ if (!fs10.statSync(dir).isDirectory()) continue;
117714
118402
  } catch {
117715
118403
  continue;
117716
118404
  }
@@ -117846,63 +118534,6 @@ async function registerSessionHostRoutes(fastify) {
117846
118534
  });
117847
118535
  }
117848
118536
 
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
118537
  // src/codex/codex-host.ts
117907
118538
  import { EventEmitter as EventEmitter4 } from "node:events";
117908
118539
  import { PassThrough as PassThrough2, Writable as Writable2 } from "node:stream";
@@ -118329,103 +118960,6 @@ function mapTokenUsage(data) {
118329
118960
  };
118330
118961
  }
118331
118962
 
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
118963
  // src/claude/cli-orphans.ts
118430
118964
  import { execFile as execFile4 } from "node:child_process";
118431
118965
  var TERM_GRACE_MS = 2e3;
@@ -118523,6 +119057,11 @@ function reapOrphanCliProcesses(db2, deps = defaultDeps) {
118523
119057
  }
118524
119058
 
118525
119059
  // src/codex/codex-provider.ts
119060
+ var TERMINAL_TASK_TYPE = "background_terminal";
119061
+ function taskPollMs() {
119062
+ const ms = Number(process.env.AGENT_PANE_CODEX_TASK_POLL_MS);
119063
+ return Number.isFinite(ms) && ms > 0 ? ms : 5e3;
119064
+ }
118526
119065
  var sessionMap = /* @__PURE__ */ new Map();
118527
119066
  var startingThreads = /* @__PURE__ */ new Map();
118528
119067
  var ENDED_TURNS_KEPT = 20;
@@ -118566,22 +119105,34 @@ function sandboxType(config3) {
118566
119105
  return "workspace-write";
118567
119106
  }
118568
119107
  }
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"
119108
+ function sandboxPolicy(config3) {
119109
+ if (!config3 || !config3.sandboxMode && config3.networkAccessEnabled === void 0) return null;
119110
+ const networkAccess = config3.networkAccessEnabled === true;
119111
+ switch (sandboxType(config3)) {
119112
+ case "read-only":
119113
+ return { type: "readOnly", networkAccess };
119114
+ case "danger-full-access":
119115
+ return { type: "dangerFullAccess" };
119116
+ default:
119117
+ return { type: "workspaceWrite", networkAccess };
119118
+ }
119119
+ }
119120
+ function threadConfig(config3) {
119121
+ return config3?.webSearchMode ? { web_search: config3.webSearchMode } : void 0;
119122
+ }
119123
+ function threadParams(session, cwd) {
119124
+ const config3 = parseRuntimeConfig(session);
119125
+ return {
119126
+ cwd,
119127
+ approvalPolicy: "never",
119128
+ sandbox: sandboxType(config3),
119129
+ model: session.model ?? void 0,
119130
+ config: threadConfig(config3),
119131
+ ...threadInstructionParams(cwd)
118580
119132
  };
118581
- return map2[type] ?? type;
118582
119133
  }
118583
119134
  function shouldSkipItem(type) {
118584
- return type === "userMessage" || type === "user_message";
119135
+ return type === "userMessage" || type === "user_message" || type === "enteredReviewMode" || type === "exitedReviewMode";
118585
119136
  }
118586
119137
  function isEmptyReasoning(item) {
118587
119138
  const summary = Array.isArray(item.summary) ? item.summary : [];
@@ -118623,9 +119174,32 @@ function untrackProcess(pid) {
118623
119174
  } catch {
118624
119175
  }
118625
119176
  }
119177
+ function emptyThreadState() {
119178
+ return {
119179
+ threadId: "",
119180
+ sideThreads: /* @__PURE__ */ new Map(),
119181
+ loadingSide: /* @__PURE__ */ new Map(),
119182
+ codexThreads: /* @__PURE__ */ new Set(),
119183
+ webSearch: void 0,
119184
+ contextTokens: /* @__PURE__ */ new Map(),
119185
+ compactions: /* @__PURE__ */ new Map(),
119186
+ publishedContext: null,
119187
+ tasks: /* @__PURE__ */ new Map(),
119188
+ publishedTasks: "[]",
119189
+ taskTimer: null,
119190
+ refreshing: null,
119191
+ refreshAgain: false
119192
+ };
119193
+ }
118626
119194
  function getOrCreateThread(session) {
118627
119195
  const existing = sessionMap.get(session.id);
118628
- if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
119196
+ if (existing && !existing.client.isClosed()) {
119197
+ const webSearch = threadConfig(parseRuntimeConfig(session))?.web_search;
119198
+ if (webSearch === existing.webSearch || existing.turns.length > 0 || existing.tasks.size > 0) {
119199
+ return Promise.resolve(existing);
119200
+ }
119201
+ void retireEntry(existing, "keep");
119202
+ }
118629
119203
  const pending = startingThreads.get(session.id);
118630
119204
  if (pending) return pending;
118631
119205
  const started = startThread(session).finally(() => startingThreads.delete(session.id));
@@ -118652,7 +119226,7 @@ async function startThread(session) {
118652
119226
  client,
118653
119227
  // A hosted app-server has no cli_processes row: its host supervises it.
118654
119228
  pid: host ? void 0 : client.pid,
118655
- threadId: "",
119229
+ ...emptyThreadState(),
118656
119230
  turns: [],
118657
119231
  ended: /* @__PURE__ */ new Map(),
118658
119232
  resumedTurnIds: null,
@@ -118665,33 +119239,25 @@ async function startThread(session) {
118665
119239
  listen(entry);
118666
119240
  try {
118667
119241
  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);
119242
+ autoApproveToolUserInput(client);
119243
+ const base = threadParams(session, cwd);
119244
+ entry.webSearch = base.config?.web_search;
118674
119245
  if (session.external_thread_id) {
119246
+ entry.threadId = session.external_thread_id;
119247
+ entry.codexThreads.add(entry.threadId);
118675
119248
  const result = await client.request("thread/resume", {
118676
119249
  threadId: session.external_thread_id,
118677
- cwd,
118678
- approvalPolicy: "never",
118679
- sandbox,
118680
- model: session.model ?? void 0,
118681
- ...instructions
119250
+ ...base
118682
119251
  });
118683
119252
  entry.threadId = result.thread.id;
118684
119253
  entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
118685
- noteHostThread(entry);
118686
119254
  } else {
118687
119255
  const result = await client.request("thread/start", {
118688
- cwd,
118689
- approvalPolicy: "never",
118690
- sandbox,
118691
- model: session.model ?? void 0,
118692
- ...instructions
119256
+ ...base,
119257
+ threadSource: PANE_THREAD_SOURCE
118693
119258
  });
118694
119259
  entry.threadId = result.thread.id;
119260
+ recordCodexThread(entry.threadId, session.id);
118695
119261
  const db2 = getDb();
118696
119262
  const now = (/* @__PURE__ */ new Date()).toISOString();
118697
119263
  db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
@@ -118699,8 +119265,9 @@ async function startThread(session) {
118699
119265
  now,
118700
119266
  session.id
118701
119267
  );
118702
- noteHostThread(entry);
118703
119268
  }
119269
+ entry.codexThreads.add(entry.threadId);
119270
+ noteHostThread(entry);
118704
119271
  } catch (err) {
118705
119272
  void retireEntry(entry, "keep");
118706
119273
  throw err;
@@ -118723,6 +119290,7 @@ function retireEntry(entry, left, error51 = "App-server closed") {
118723
119290
  }
118724
119291
  }
118725
119292
  }
119293
+ dropTasks(entry);
118726
119294
  entry.closing = entry.client.close().catch(() => {
118727
119295
  }).finally(async () => {
118728
119296
  untrackProcess(entry.pid);
@@ -118733,6 +119301,7 @@ function retireEntry(entry, left, error51 = "App-server closed") {
118733
119301
  function onClientClosed(entry, reason) {
118734
119302
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
118735
119303
  untrackProcess(entry.pid);
119304
+ if (!entry.closing) dropTasks(entry);
118736
119305
  if (entry.host && !entry.closing) void releaseCodexHost(entry.host);
118737
119306
  if (entry.closing || entry.turns.length === 0) return;
118738
119307
  let db2;
@@ -118765,22 +119334,45 @@ function endTurn(entry, active) {
118765
119334
  }
118766
119335
  function rememberEnded(entry, active) {
118767
119336
  if (!active.codexId) return;
118768
- entry.ended.set(active.codexId, active.id);
119337
+ rememberTurnId(entry, active.codexId, active.id);
119338
+ }
119339
+ function rememberTurnId(entry, codexId, paneTurnId) {
119340
+ entry.ended.set(codexId, paneTurnId);
118769
119341
  if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
118770
119342
  }
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;
119343
+ function runsOn(active, threadId) {
119344
+ return active.codexThreadId === null || active.codexThreadId === threadId;
119345
+ }
119346
+ function bindCodexId(active, codexId) {
119347
+ active.codexId = codexId;
119348
+ active.resolveStarted(codexId);
118778
119349
  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);
119350
+ 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
119351
  } catch {
118781
119352
  }
119353
+ }
119354
+ function liveTurnsOf(entry, threadId, codexId) {
119355
+ if (!codexId) return entry.turns.filter((t) => runsOn(t, threadId)).slice(-1);
119356
+ const known = entry.turns.filter((t) => t.codexId === codexId);
119357
+ if (known.length > 0 || entry.ended.has(codexId)) return known;
119358
+ const waiting = entry.turns.find((t) => t.codexId === null && t.kind !== "review" && runsOn(t, threadId));
119359
+ if (!waiting) return [];
119360
+ bindCodexId(waiting, codexId);
118782
119361
  return [waiting];
118783
119362
  }
119363
+ function deferToReview(entry, threadId, codexId, replay) {
119364
+ if (!codexId) return false;
119365
+ const review = entry.turns.find((t) => t.kind === "review" && t.codexId === null && t.codexThreadId === threadId);
119366
+ if (!review) return false;
119367
+ review.early.push({ codexId, replay });
119368
+ return true;
119369
+ }
119370
+ function releaseEarly(entry, active) {
119371
+ for (const event of active.early.splice(0)) {
119372
+ if (event.codexId === active.codexId) event.replay();
119373
+ else rememberTurnId(entry, event.codexId, active.id);
119374
+ }
119375
+ }
118784
119376
  function noteContinued(active) {
118785
119377
  if (!active.resuming) return;
118786
119378
  active.resuming = false;
@@ -118857,10 +119449,11 @@ function listen(entry) {
118857
119449
  const on = (method, handle) => {
118858
119450
  entry.client.onNotification(method, (params) => {
118859
119451
  const p = params;
118860
- if (!p || p.threadId !== entry.threadId) return;
119452
+ if (!p || !entry.codexThreads.has(p.threadId)) return;
118861
119453
  handle(p);
118862
119454
  });
118863
119455
  };
119456
+ on("turn/started", (p) => onTurnStarted(entry, p));
118864
119457
  on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
118865
119458
  on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
118866
119459
  on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
@@ -118870,19 +119463,57 @@ function listen(entry) {
118870
119463
  on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
118871
119464
  entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
118872
119465
  }
119466
+ function onTurnStarted(entry, p) {
119467
+ const codexId = p.turn?.id;
119468
+ if (!codexId || entry.ended.has(codexId) || entry.turns.some((t) => t.codexId === codexId)) return;
119469
+ const onThread = entry.turns.filter((t) => t.codexThreadId === p.threadId);
119470
+ const compaction = onThread.find((t) => t.kind === "compact" && t.codexId === null);
119471
+ if (compaction) {
119472
+ bindCodexId(compaction, codexId);
119473
+ return;
119474
+ }
119475
+ const review = onThread.find((t) => t.kind === "review");
119476
+ if (review?.codexId) rememberTurnId(entry, codexId, review.id);
119477
+ else if (review) review.early.push({ codexId, replay: () => {
119478
+ } });
119479
+ }
118873
119480
  function onItem(entry, p, status, event) {
118874
- const [live] = liveTurnsOf(entry, p.turnId);
119481
+ const [live] = liveTurnsOf(entry, p.threadId, p.turnId);
118875
119482
  if (live) {
118876
119483
  if (!shouldSkipItem(p.item.type)) noteContinued(live);
118877
- handleItemEvent(p, entry.sessionId, live.id, status, event);
119484
+ handleItemEvent(p, entry.sessionId, live.id, status, event, compactionData(entry, live, p, event));
118878
119485
  return;
118879
119486
  }
118880
119487
  const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
118881
- if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
119488
+ if (ended) {
119489
+ handleItemEvent(p, entry.sessionId, ended, status, event, compactionData(entry, null, p, event));
119490
+ if (event === "item:completed" && [...entry.tasks.values()].some((t) => t.commandItemId === p.item.id)) {
119491
+ refreshBackgroundTasks(entry);
119492
+ }
119493
+ return;
119494
+ }
119495
+ deferToReview(entry, p.threadId, p.turnId, () => onItem(entry, p, status, event));
119496
+ }
119497
+ function compactionData(entry, live, p, event) {
119498
+ if (p.item.type !== "contextCompaction") return void 0;
119499
+ let compaction = entry.compactions.get(p.item.id);
119500
+ if (!compaction) {
119501
+ compaction = { threadId: p.threadId, pre: entry.contextTokens.get(p.threadId) ?? null, post: null, done: false };
119502
+ entry.compactions.set(p.item.id, compaction);
119503
+ if (entry.compactions.size > ENDED_TURNS_KEPT) {
119504
+ entry.compactions.delete(entry.compactions.keys().next().value);
119505
+ }
119506
+ }
119507
+ if (event === "item:completed") compaction.done = true;
119508
+ const post = compaction.done ? compaction.post : null;
119509
+ return { trigger: live?.kind === "compact" ? "manual" : "auto", pre_tokens: compaction.pre, post_tokens: post };
118882
119510
  }
118883
119511
  function onAgentMessageDelta(entry, p) {
118884
- const [live] = liveTurnsOf(entry, p.turnId);
118885
- if (!live) return;
119512
+ const [live] = liveTurnsOf(entry, p.threadId, p.turnId);
119513
+ if (!live) {
119514
+ deferToReview(entry, p.threadId, p.turnId, () => onAgentMessageDelta(entry, p));
119515
+ return;
119516
+ }
118886
119517
  noteContinued(live);
118887
119518
  const payload = { sessionId: entry.sessionId, turnId: live.id, itemId: p.itemId, delta: p.delta };
118888
119519
  if (entry.replaying) noteDelta(payload);
@@ -118890,7 +119521,10 @@ function onAgentMessageDelta(entry, p) {
118890
119521
  }
118891
119522
  function onTurnCompleted(entry, p) {
118892
119523
  const db2 = getDb();
118893
- for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
119524
+ const codexId = p.turn?.id ?? p.turnId;
119525
+ const lives = liveTurnsOf(entry, p.threadId, codexId);
119526
+ if (lives.length === 0 && deferToReview(entry, p.threadId, codexId, () => onTurnCompleted(entry, p))) return;
119527
+ for (const live of lives) {
118894
119528
  if (p.turn?.status === "interrupted") {
118895
119529
  cancelTurn(entry, live);
118896
119530
  } else if (p.turn?.status === "failed") {
@@ -118901,16 +119535,21 @@ function onTurnCompleted(entry, p) {
118901
119535
  completeTurn(db2, entry.sessionId, live.id, p.usage);
118902
119536
  }
118903
119537
  }
119538
+ refreshBackgroundTasks(entry);
118904
119539
  }
118905
119540
  function onTurnFailed(entry, p) {
118906
119541
  const db2 = getDb();
118907
- for (const live of liveTurnsOf(entry, p.turnId)) {
119542
+ const lives = liveTurnsOf(entry, p.threadId, p.turnId);
119543
+ if (lives.length === 0 && deferToReview(entry, p.threadId, p.turnId, () => onTurnFailed(entry, p))) return;
119544
+ for (const live of lives) {
118908
119545
  endTurn(entry, live);
118909
119546
  failTurn(db2, entry.sessionId, live.id, p.error.message);
118910
119547
  }
119548
+ refreshBackgroundTasks(entry);
118911
119549
  }
118912
119550
  function onTokenUsage(entry, p) {
118913
- const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
119551
+ noteContext(entry, p);
119552
+ const turnId = liveTurnsOf(entry, p.threadId, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
118914
119553
  if (!turnId) return;
118915
119554
  const usage = mapTokenUsage(p.tokenUsage.total);
118916
119555
  const db2 = getDb();
@@ -118918,6 +119557,30 @@ function onTokenUsage(entry, p) {
118918
119557
  db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
118919
119558
  broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
118920
119559
  }
119560
+ function noteContext(entry, p) {
119561
+ const last = p.tokenUsage?.last;
119562
+ if (!last) return;
119563
+ const tokens2 = Math.max(0, (last.totalTokens ?? 0) - (last.reasoningOutputTokens ?? 0));
119564
+ entry.contextTokens.set(p.threadId, tokens2);
119565
+ for (const compaction of entry.compactions.values()) {
119566
+ if (compaction.threadId === p.threadId && !compaction.done) compaction.post = tokens2;
119567
+ }
119568
+ const window = p.tokenUsage.modelContextWindow;
119569
+ if (p.threadId !== entry.threadId || !window || window <= 0) return;
119570
+ const usage = {
119571
+ totalTokens: tokens2,
119572
+ contextWindow: window,
119573
+ percentage: Math.min(100, Math.round(tokens2 / window * 100))
119574
+ };
119575
+ const json2 = JSON.stringify(usage);
119576
+ if (json2 === entry.publishedContext) return;
119577
+ entry.publishedContext = json2;
119578
+ broadcast("turn:contextUsage", { sessionId: entry.sessionId, ...usage });
119579
+ try {
119580
+ getDb().prepare("UPDATE sessions SET context_usage = ? WHERE id = ?").run(json2, entry.sessionId);
119581
+ } catch {
119582
+ }
119583
+ }
118921
119584
  function turnAttachments2(turn) {
118922
119585
  const raw = turn.attachments;
118923
119586
  if (!raw) return [];
@@ -118931,16 +119594,14 @@ function turnAttachments2(turn) {
118931
119594
  }
118932
119595
  function buildCodexInput(turn) {
118933
119596
  const input = [{ type: "text", text: turn.user_prompt }];
119597
+ const saved = /* @__PURE__ */ new Set();
118934
119598
  for (const att of turnAttachments2(turn)) {
118935
119599
  if (!att || typeof att.data !== "string" || !att.data) continue;
118936
119600
  const type = String(att.media_type ?? "").toLowerCase();
118937
119601
  if (type.startsWith("image/")) {
118938
119602
  input.push({ type: "image", url: `data:${type};base64,${att.data}` });
118939
119603
  } 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
- });
119604
+ input.push({ type: "text", text: pdfNote(turn, att, saved) });
118944
119605
  } else {
118945
119606
  const decoded = Buffer.from(att.data, "base64").toString("utf-8");
118946
119607
  input.push({ type: "text", text: `
@@ -118951,17 +119612,76 @@ ${decoded}
118951
119612
  }
118952
119613
  return input;
118953
119614
  }
118954
- async function runTurn(session, turn, entry, input, resume) {
119615
+ function pdfNote(turn, att, saved) {
119616
+ try {
119617
+ const file2 = saveAttachmentFile(turn.session_id, turn.id, att.name || "attachment.pdf", att.data, saved);
119618
+ return `[The user attached the PDF "${att.name}". Codex cannot take PDF input, so it is saved at ${file2}; read it from there.]`;
119619
+ } catch (err) {
119620
+ return `[Attachment ${att.name} (PDF) was not sent: it could not be saved for Codex (${err.message}).]`;
119621
+ }
119622
+ }
119623
+ var CODEX_COMMANDS = [
119624
+ { name: "compact", description: "Summarize the conversation to free up the model's context" },
119625
+ {
119626
+ name: "review",
119627
+ description: "Review the uncommitted changes, the changes against a base branch, a commit, or by your instructions",
119628
+ argumentHint: "[base <branch> | commit <sha> | <instructions>]"
119629
+ }
119630
+ ];
119631
+ function parseCodexCommand(prompt) {
119632
+ const match = /^\/(compact|review)(?:\s+([\s\S]*))?$/.exec(prompt.trim());
119633
+ if (!match) return null;
119634
+ const args = (match[2] ?? "").trim();
119635
+ if (match[1] === "compact") return args ? null : { kind: "compact" };
119636
+ if (!args) return { kind: "review", target: { type: "uncommittedChanges" } };
119637
+ const base = /^base\s+(\S+)$/i.exec(args);
119638
+ if (base) return { kind: "review", target: { type: "baseBranch", branch: base[1] } };
119639
+ const commit = /^commit\s+([0-9a-f]{4,40})$/i.exec(args);
119640
+ if (commit) return { kind: "review", target: { type: "commit", sha: commit[1] } };
119641
+ return { kind: "review", target: { type: "custom", instructions: args } };
119642
+ }
119643
+ function turnRequest(turn) {
119644
+ return parseCodexCommand(turn.user_prompt) ?? { kind: "prompt", input: buildCodexInput(turn) };
119645
+ }
119646
+ async function sendTurnRequest(session, entry, threadId, request) {
119647
+ if (request.kind === "compact") {
119648
+ await entry.client.request("thread/compact/start", { threadId });
119649
+ return null;
119650
+ }
119651
+ if (request.kind === "review") {
119652
+ const result2 = await entry.client.request("review/start", {
119653
+ threadId,
119654
+ target: request.target,
119655
+ delivery: "inline"
119656
+ });
119657
+ return result2.turn.id;
119658
+ }
119659
+ const policy = sandboxPolicy(parseRuntimeConfig(session));
119660
+ const result = await entry.client.request("turn/start", {
119661
+ threadId,
119662
+ input: request.input,
119663
+ approvalPolicy: "never",
119664
+ ...policy ? { sandboxPolicy: policy } : {},
119665
+ model: session.model ?? void 0,
119666
+ effort: session.model_reasoning_effort ?? void 0
119667
+ });
119668
+ return result.turn.id;
119669
+ }
119670
+ async function runTurn(session, turn, entry, codexThreadId, request, resume) {
118955
119671
  const db2 = getDb();
118956
- const sandbox = sandboxType(parseRuntimeConfig(session));
118957
119672
  let resolveStarted;
119673
+ const started = new Promise((resolve) => {
119674
+ resolveStarted = resolve;
119675
+ });
118958
119676
  const active = {
118959
119677
  id: turn.id,
118960
119678
  discussionThreadId: turn.thread_id ?? null,
119679
+ codexThreadId,
119680
+ kind: request.kind,
118961
119681
  codexId: null,
118962
- started: new Promise((resolve) => {
118963
- resolveStarted = resolve;
118964
- }),
119682
+ started,
119683
+ resolveStarted,
119684
+ early: [],
118965
119685
  done: false,
118966
119686
  resuming: resume,
118967
119687
  hostOffset: null
@@ -118969,22 +119689,18 @@ async function runTurn(session, turn, entry, input, resume) {
118969
119689
  entry.turns.push(active);
118970
119690
  bindHostTurn(entry, active);
118971
119691
  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);
119692
+ const codexId = await sendTurnRequest(session, entry, codexThreadId, request);
119693
+ if (codexId) {
119694
+ active.codexId = codexId;
119695
+ if (active.done) rememberEnded(entry, active);
119696
+ db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
119697
+ codexId,
119698
+ (/* @__PURE__ */ new Date()).toISOString(),
119699
+ turn.id
119700
+ );
119701
+ resolveStarted(codexId);
119702
+ releaseEarly(entry, active);
119703
+ }
118988
119704
  } catch (err) {
118989
119705
  const message = err.message;
118990
119706
  const settled = active.done;
@@ -118998,8 +119714,10 @@ async function runTurn(session, turn, entry, input, resume) {
118998
119714
  async function startTurn2(session, turn) {
118999
119715
  const db2 = getDb();
119000
119716
  let entry;
119717
+ let codexThreadId;
119001
119718
  try {
119002
119719
  entry = await getOrCreateThread(session);
119720
+ codexThreadId = turn.thread_id ? await sideThreadFor(entry, session, turn.thread_id) : entry.threadId;
119003
119721
  } catch (err) {
119004
119722
  failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
119005
119723
  return;
@@ -119009,16 +119727,60 @@ async function startTurn2(session, turn) {
119009
119727
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
119010
119728
  setSessionStatus(db2, session.id, 1, "running", now);
119011
119729
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
119012
- await runTurn(session, turn, entry, buildCodexInput(turn), false);
119730
+ await runTurn(session, turn, entry, codexThreadId, turnRequest(turn), false);
119731
+ }
119732
+ function sideThreadFor(entry, session, discussionThreadId) {
119733
+ const loaded = entry.sideThreads.get(discussionThreadId);
119734
+ if (loaded) return Promise.resolve(loaded);
119735
+ const pending = entry.loadingSide.get(discussionThreadId);
119736
+ if (pending) return pending;
119737
+ const loading = loadSideThread(entry, session, discussionThreadId).finally(
119738
+ () => entry.loadingSide.delete(discussionThreadId)
119739
+ );
119740
+ entry.loadingSide.set(discussionThreadId, loading);
119741
+ return loading;
119013
119742
  }
119014
- function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
119743
+ async function loadSideThread(entry, session, discussionThreadId) {
119744
+ const db2 = getDb();
119745
+ const row = db2.prepare("SELECT external_thread_id FROM discussion_threads WHERE id = ?").get(discussionThreadId);
119746
+ const base = threadParams(session, session.cwd ?? process.cwd());
119747
+ let codexThreadId;
119748
+ if (row?.external_thread_id) {
119749
+ entry.codexThreads.add(row.external_thread_id);
119750
+ const result = await entry.client.request("thread/resume", {
119751
+ threadId: row.external_thread_id,
119752
+ ...base
119753
+ });
119754
+ codexThreadId = result.thread.id;
119755
+ } else {
119756
+ const result = await entry.client.request("thread/start", {
119757
+ ...base,
119758
+ threadSource: PANE_THREAD_SOURCE
119759
+ });
119760
+ codexThreadId = result.thread.id;
119761
+ recordCodexThread(codexThreadId, session.id);
119762
+ db2.prepare("UPDATE discussion_threads SET external_thread_id = ? WHERE id = ?").run(
119763
+ codexThreadId,
119764
+ discussionThreadId
119765
+ );
119766
+ }
119767
+ entry.sideThreads.set(discussionThreadId, codexThreadId);
119768
+ entry.codexThreads.add(codexThreadId);
119769
+ return codexThreadId;
119770
+ }
119771
+ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent, extraData) {
119015
119772
  const db2 = getDb();
119016
119773
  const now = (/* @__PURE__ */ new Date()).toISOString();
119017
119774
  const item = params.item;
119775
+ if (item.type === "exitedReviewMode" && typeof item.review === "string" && item.review.trim()) {
119776
+ db2.prepare(
119777
+ "UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ? AND (agent_response IS NULL OR agent_response = '')"
119778
+ ).run(item.review, now, turnId);
119779
+ }
119018
119780
  if (shouldSkipItem(item.type)) return;
119019
119781
  if ((item.type === "reasoning" || item.type === "agentReasoning") && isEmptyReasoning(item)) return;
119020
- const data = mapItemData(item);
119021
- const normalizedType = normalizeItemType(item.type);
119782
+ const data = { ...mapItemData(item), ...extraData };
119783
+ const normalizedType = mapItemType(item);
119022
119784
  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
119785
  let itemId;
119024
119786
  let createdAt;
@@ -119089,7 +119851,9 @@ function abortOrphanTurn(sessionId, threadId) {
119089
119851
  }
119090
119852
  }
119091
119853
  var END_COMMANDS_WAIT_MS = 5e3;
119092
- async function endTurnCommands(entry, turnId) {
119854
+ async function endTurnCommands(entry, active) {
119855
+ const turnId = active.id;
119856
+ const threadId = active.codexThreadId ?? entry.threadId;
119093
119857
  try {
119094
119858
  const rows = getDb().prepare(
119095
119859
  "SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
@@ -119099,13 +119863,13 @@ async function endTurnCommands(entry, turnId) {
119099
119863
  let cursor = null;
119100
119864
  do {
119101
119865
  const page = await entry.client.request("thread/backgroundTerminals/list", {
119102
- threadId: entry.threadId,
119866
+ threadId,
119103
119867
  cursor
119104
119868
  });
119105
119869
  for (const terminal of page.data) {
119106
119870
  if (!started.has(terminal.itemId)) continue;
119107
119871
  await entry.client.request("thread/backgroundTerminals/terminate", {
119108
- threadId: entry.threadId,
119872
+ threadId,
119109
119873
  processId: terminal.processId
119110
119874
  });
119111
119875
  }
@@ -119124,7 +119888,7 @@ async function interruptTurn(sessionId, threadId) {
119124
119888
  if (codexId && !target.done) {
119125
119889
  try {
119126
119890
  await entry.client.request("turn/interrupt", {
119127
- threadId: entry.threadId,
119891
+ threadId: target.codexThreadId ?? entry.threadId,
119128
119892
  turnId: codexId
119129
119893
  });
119130
119894
  stopped = true;
@@ -119137,7 +119901,10 @@ async function interruptTurn(sessionId, threadId) {
119137
119901
  cancelTurn(entry, target);
119138
119902
  if (!stopped) void retireEntry(entry, "fail");
119139
119903
  }
119140
- if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
119904
+ if (stopped) {
119905
+ await within(endTurnCommands(entry, target), END_COMMANDS_WAIT_MS);
119906
+ refreshBackgroundTasks(entry);
119907
+ }
119141
119908
  if (live || stopped) return true;
119142
119909
  }
119143
119910
  return abortOrphanTurn(sessionId, threadId);
@@ -119146,8 +119913,31 @@ function clearThread(sessionId) {
119146
119913
  const entry = sessionMap.get(sessionId);
119147
119914
  if (entry) void retireEntry(entry, "cancel");
119148
119915
  }
119916
+ function clearThreadBranch(sessionId, threadId) {
119917
+ const entry = sessionMap.get(sessionId);
119918
+ if (!entry) return;
119919
+ for (const active of entry.turns.filter((t) => t.discussionThreadId === threadId)) {
119920
+ if (active.codexId) {
119921
+ void entry.client.request("turn/interrupt", {
119922
+ threadId: active.codexThreadId ?? entry.threadId,
119923
+ turnId: active.codexId
119924
+ }).catch(() => {
119925
+ });
119926
+ }
119927
+ endTurn(entry, active);
119928
+ }
119929
+ const codexThreadId = entry.sideThreads.get(threadId);
119930
+ entry.sideThreads.delete(threadId);
119931
+ if (!codexThreadId || codexThreadId === entry.threadId) return;
119932
+ entry.codexThreads.delete(codexThreadId);
119933
+ void entry.client.request("thread/unsubscribe", { threadId: codexThreadId }).catch(() => {
119934
+ }).finally(() => refreshBackgroundTasks(entry));
119935
+ }
119149
119936
  function clearAllThreads() {
119150
- for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
119937
+ for (const entry of [...sessionMap.values()]) {
119938
+ stopTaskPolling(entry);
119939
+ void retireEntry(entry, "keep");
119940
+ }
119151
119941
  sessionMap.clear();
119152
119942
  startingThreads.clear();
119153
119943
  titleGenerating.clear();
@@ -119173,7 +119963,8 @@ async function generateTitleAsync(sessionId, userPrompt, agentResponse) {
119173
119963
  const initResult = await client.request("thread/start", {
119174
119964
  cwd: process.cwd(),
119175
119965
  approvalPolicy: "never",
119176
- sandbox: "read-only"
119966
+ sandbox: "read-only",
119967
+ ephemeral: true
119177
119968
  });
119178
119969
  const threadId = initResult.thread.id;
119179
119970
  const truncatedPrompt = userPrompt.slice(0, 500);
@@ -119214,7 +120005,7 @@ Agent responded: "${truncatedResponse}"`;
119214
120005
  threadId,
119215
120006
  input: [{ type: "text", text: titlePrompt }],
119216
120007
  approvalPolicy: "never",
119217
- sandbox: { type: "read-only" }
120008
+ sandboxPolicy: { type: "readOnly" }
119218
120009
  });
119219
120010
  const title = await titlePromise;
119220
120011
  clearTimeout(timeout);
@@ -119241,7 +120032,8 @@ async function summarizeCodexThread(session, _thread, transcript, directives) {
119241
120032
  const initResult = await client.request("thread/start", {
119242
120033
  cwd: session.cwd ?? process.cwd(),
119243
120034
  approvalPolicy: "never",
119244
- sandbox: "read-only"
120035
+ sandbox: "read-only",
120036
+ ephemeral: true
119245
120037
  });
119246
120038
  const threadId = initResult.thread.id;
119247
120039
  const directiveLine = directives.trim() ? `
@@ -119286,7 +120078,7 @@ Produce a concise summary of the discussion that preserves: concrete findings, f
119286
120078
  threadId,
119287
120079
  input: [{ type: "text", text: summaryPrompt }],
119288
120080
  approvalPolicy: "never",
119289
- sandbox: { type: "read-only" }
120081
+ sandboxPolicy: { type: "readOnly" }
119290
120082
  });
119291
120083
  const summary = await summaryPromise;
119292
120084
  clearTimeout(timeout);
@@ -119328,6 +120120,230 @@ async function getModels() {
119328
120120
  return [];
119329
120121
  }
119330
120122
  }
120123
+ async function getCommands() {
120124
+ return CODEX_COMMANDS;
120125
+ }
120126
+ function forkPoint(db2, sessionId, target) {
120127
+ const row = db2.prepare(
120128
+ `SELECT external_turn_id FROM turns
120129
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
120130
+ AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
120131
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`
120132
+ ).get(sessionId, target.id, target.created_at);
120133
+ return row?.external_turn_id ?? null;
120134
+ }
120135
+ async function forkSession(session, targetTurn) {
120136
+ const threadId = session.external_thread_id;
120137
+ if (!threadId) return null;
120138
+ const lastTurnId = forkPoint(getDb(), session.id, targetTurn);
120139
+ if (!lastTurnId) return null;
120140
+ const cwd = session.cwd ?? process.cwd();
120141
+ const client = new AppServerClient({ cwd });
120142
+ try {
120143
+ await client.initialize();
120144
+ const fork = (range) => client.request("thread/fork", {
120145
+ threadId,
120146
+ ...range,
120147
+ cwd,
120148
+ excludeTurns: true,
120149
+ threadSource: PANE_THREAD_SOURCE
120150
+ });
120151
+ let result;
120152
+ try {
120153
+ result = await fork({ lastTurnId });
120154
+ } catch (err) {
120155
+ const range = await client.request("thread/read", { threadId, includeTurns: true }).then(({ thread }) => forkThroughReview(thread.turns ?? [], lastTurnId), () => void 0);
120156
+ if (!range) throw err;
120157
+ result = await fork(range);
120158
+ }
120159
+ recordCodexThread(result.thread.id, session.id);
120160
+ return result.thread.id;
120161
+ } finally {
120162
+ await client.close();
120163
+ }
120164
+ }
120165
+ function refreshBackgroundTasks(entry) {
120166
+ if (entry.refreshing) {
120167
+ entry.refreshAgain = true;
120168
+ return;
120169
+ }
120170
+ entry.refreshing = (async () => {
120171
+ do {
120172
+ entry.refreshAgain = false;
120173
+ await refreshTasksOnce(entry);
120174
+ } while (entry.refreshAgain && isCurrent(entry));
120175
+ })().catch(
120176
+ (err) => console.warn(`[codex] could not list the background commands of ${entry.sessionId}: ${err.message}`)
120177
+ ).finally(() => {
120178
+ entry.refreshing = null;
120179
+ });
120180
+ }
120181
+ async function refreshTasksOnce(entry) {
120182
+ if (!isCurrent(entry) || entry.replaying) return;
120183
+ const live = /* @__PURE__ */ new Map();
120184
+ const unknown2 = /* @__PURE__ */ new Set();
120185
+ for (const codexThreadId of entry.codexThreads) {
120186
+ let cursor = null;
120187
+ try {
120188
+ do {
120189
+ const page = await entry.client.request("thread/backgroundTerminals/list", {
120190
+ threadId: codexThreadId,
120191
+ cursor
120192
+ });
120193
+ for (const terminal of page.data) {
120194
+ live.set(terminal.processId, { codexThreadId, itemId: terminal.itemId, command: terminal.command });
120195
+ }
120196
+ cursor = page.nextCursor;
120197
+ } while (cursor);
120198
+ } catch {
120199
+ unknown2.add(codexThreadId);
120200
+ }
120201
+ }
120202
+ if (!isCurrent(entry)) return;
120203
+ for (const [taskId, task] of entry.tasks) {
120204
+ if (live.has(taskId) || unknown2.has(task.codexThreadId)) continue;
120205
+ entry.tasks.delete(taskId);
120206
+ closeTaskItem(entry.sessionId, task, task.stopped ? "stopped" : "completed");
120207
+ }
120208
+ for (const [processId, terminal] of live) {
120209
+ if (entry.tasks.has(processId)) continue;
120210
+ const turnId = commandTurnOf(entry.sessionId, terminal.itemId);
120211
+ if (turnId && entry.turns.some((t) => t.id === turnId)) continue;
120212
+ const task = {
120213
+ info: { task_id: processId, task_type: TERMINAL_TASK_TYPE, description: terminal.command },
120214
+ codexThreadId: terminal.codexThreadId,
120215
+ processId,
120216
+ commandItemId: terminal.itemId,
120217
+ item: null,
120218
+ stopped: false
120219
+ };
120220
+ if (turnId) openTaskItem(entry.sessionId, turnId, task);
120221
+ entry.tasks.set(processId, task);
120222
+ }
120223
+ publishTasks(entry);
120224
+ }
120225
+ function publishTasks(entry) {
120226
+ const tasks = [...entry.tasks.values()].map((task) => task.info);
120227
+ const json2 = JSON.stringify(tasks);
120228
+ if (json2 !== entry.publishedTasks) {
120229
+ entry.publishedTasks = json2;
120230
+ broadcast("background_tasks", { sessionId: entry.sessionId, tasks });
120231
+ }
120232
+ if (tasks.length > 0 && !entry.taskTimer && isCurrent(entry)) {
120233
+ entry.taskTimer = setInterval(() => refreshBackgroundTasks(entry), taskPollMs());
120234
+ entry.taskTimer.unref?.();
120235
+ } else if (tasks.length === 0) {
120236
+ stopTaskPolling(entry);
120237
+ }
120238
+ }
120239
+ function stopTaskPolling(entry) {
120240
+ if (!entry.taskTimer) return;
120241
+ clearInterval(entry.taskTimer);
120242
+ entry.taskTimer = null;
120243
+ }
120244
+ function dropTasks(entry) {
120245
+ stopTaskPolling(entry);
120246
+ for (const task of entry.tasks.values()) closeTaskItem(entry.sessionId, task, "stopped");
120247
+ entry.tasks.clear();
120248
+ publishTasks(entry);
120249
+ }
120250
+ function commandTurnOf(sessionId, itemId) {
120251
+ try {
120252
+ const row = getDb().prepare(
120253
+ `SELECT i.turn_id FROM items i JOIN turns t ON t.id = i.turn_id
120254
+ WHERE t.session_id = ? AND i.external_item_id = ? ORDER BY i.created_at DESC LIMIT 1`
120255
+ ).get(sessionId, itemId);
120256
+ return row?.turn_id ?? null;
120257
+ } catch {
120258
+ return null;
120259
+ }
120260
+ }
120261
+ function openTaskItem(sessionId, turnId, task) {
120262
+ try {
120263
+ const db2 = getDb();
120264
+ const now = (/* @__PURE__ */ new Date()).toISOString();
120265
+ const item = {
120266
+ id: v4_default(),
120267
+ turn_id: turnId,
120268
+ external_item_id: `terminal-${task.processId}-${task.commandItemId}`,
120269
+ type: "background_task",
120270
+ data: {
120271
+ task_id: task.processId,
120272
+ description: task.info.description,
120273
+ task_type: TERMINAL_TASK_TYPE,
120274
+ status: "running",
120275
+ output: ""
120276
+ },
120277
+ status: "in_progress",
120278
+ created_at: now,
120279
+ updated_at: now
120280
+ };
120281
+ db2.prepare(
120282
+ "INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
120283
+ ).run(item.id, item.turn_id, item.external_item_id, item.type, JSON.stringify(item.data), item.status, now, now);
120284
+ task.item = { id: item.id, turnId, createdAt: now };
120285
+ broadcast("item:started", { sessionId, turnId, item });
120286
+ } catch (err) {
120287
+ console.warn(`[codex] could not record background command ${task.processId}: ${err.message}`);
120288
+ }
120289
+ }
120290
+ var TASK_OUTPUT_MAX = 2e4;
120291
+ function closeTaskItem(sessionId, task, status) {
120292
+ const ref = task.item;
120293
+ if (!ref) return;
120294
+ try {
120295
+ const db2 = getDb();
120296
+ const command = db2.prepare("SELECT data FROM items WHERE turn_id = ? AND external_item_id = ?").get(ref.turnId, task.commandItemId);
120297
+ let output = "";
120298
+ try {
120299
+ output = String(JSON.parse(command?.data ?? "{}").aggregated_output ?? "");
120300
+ } catch {
120301
+ }
120302
+ const data = {
120303
+ task_id: task.processId,
120304
+ description: task.info.description,
120305
+ task_type: TERMINAL_TASK_TYPE,
120306
+ status,
120307
+ output: output.length > TASK_OUTPUT_MAX ? output.slice(-TASK_OUTPUT_MAX) : output
120308
+ };
120309
+ const now = (/* @__PURE__ */ new Date()).toISOString();
120310
+ db2.prepare("UPDATE items SET data = ?, status = 'completed', updated_at = ? WHERE id = ?").run(
120311
+ JSON.stringify(data),
120312
+ now,
120313
+ ref.id
120314
+ );
120315
+ const item = {
120316
+ id: ref.id,
120317
+ turn_id: ref.turnId,
120318
+ external_item_id: `terminal-${task.processId}-${task.commandItemId}`,
120319
+ type: "background_task",
120320
+ data,
120321
+ status: "completed",
120322
+ created_at: ref.createdAt,
120323
+ updated_at: now
120324
+ };
120325
+ broadcast("item:completed", { sessionId, turnId: ref.turnId, item });
120326
+ } catch {
120327
+ }
120328
+ }
120329
+ async function stopTask(sessionId, taskId) {
120330
+ const entry = sessionMap.get(sessionId);
120331
+ const task = entry?.tasks.get(taskId);
120332
+ if (!entry || !task) throw new Error(`No running background command ${taskId} in this session`);
120333
+ task.stopped = true;
120334
+ await entry.client.request("thread/backgroundTerminals/terminate", {
120335
+ threadId: task.codexThreadId,
120336
+ processId: task.processId
120337
+ });
120338
+ refreshBackgroundTasks(entry);
120339
+ }
120340
+ function listBackgroundTasks() {
120341
+ const bySession = {};
120342
+ for (const entry of sessionMap.values()) {
120343
+ if (entry.tasks.size > 0) bySession[entry.sessionId] = [...entry.tasks.values()].map((task) => task.info);
120344
+ }
120345
+ return bySession;
120346
+ }
119331
120347
  async function shutdown() {
119332
120348
  let db2 = null;
119333
120349
  try {
@@ -119363,12 +120379,13 @@ async function reapOrphans() {
119363
120379
  async function resumeInterruptedTurn(session, turn, _opts) {
119364
120380
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
119365
120381
  const entry = await getOrCreateThread(session);
119366
- if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
120382
+ if (entry.turns.some((t) => !t.discussionThreadId)) throw new Error("Another turn is running in this session");
119367
120383
  if (!isTurnLive(getDb(), turn.id)) return;
120384
+ const command = parseCodexCommand(turn.user_prompt);
119368
120385
  const codexId = turn.external_turn_id;
119369
120386
  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);
120387
+ const request = command ?? (inThread ? { kind: "prompt", input: [{ type: "text", text: CODEX_CONTINUE_PROMPT }] } : { kind: "prompt", input: buildCodexInput(turn) });
120388
+ await runTurn(session, turn, entry, entry.threadId, request, true);
119372
120389
  }
119373
120390
  function hostFor(sessionId, cwd, options, onDirect) {
119374
120391
  if (!hostsEnabledFor("codex")) return null;
@@ -119435,38 +120452,65 @@ function maybeRetire(entry) {
119435
120452
  }
119436
120453
  function detachEntry(entry) {
119437
120454
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
120455
+ stopTaskPolling(entry);
119438
120456
  entry.closing = Promise.resolve();
119439
120457
  entry.client.detach();
119440
120458
  entry.host?.proc.detach();
119441
120459
  }
119442
120460
  function runningTurns(db2, sessionId) {
119443
120461
  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"
120462
+ "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
120463
  ).all(sessionId);
119446
120464
  }
120465
+ function storedContextTokens(db2, sessionId) {
120466
+ const row = db2.prepare("SELECT context_usage FROM sessions WHERE id = ?").get(sessionId);
120467
+ try {
120468
+ const tokens2 = row?.context_usage ? JSON.parse(row.context_usage).totalTokens : null;
120469
+ return typeof tokens2 === "number" ? tokens2 : null;
120470
+ } catch {
120471
+ return null;
120472
+ }
120473
+ }
119447
120474
  function adoptedEntry(db2, session, threadId, client, host) {
119448
- const turns = runningTurns(db2, session.id).map(
119449
- (row) => ({
120475
+ const sideRows = db2.prepare(
120476
+ "SELECT id, external_thread_id FROM discussion_threads WHERE session_id = ? AND external_thread_id IS NOT NULL"
120477
+ ).all(session.id);
120478
+ const sideOf = new Map(sideRows.map((row) => [row.id, row.external_thread_id]));
120479
+ const turns = runningTurns(db2, session.id).map((row) => {
120480
+ const kind = parseCodexCommand(row.user_prompt)?.kind ?? "prompt";
120481
+ return {
119450
120482
  id: row.id,
119451
120483
  discussionThreadId: row.thread_id,
120484
+ codexThreadId: row.thread_id ? sideOf.get(row.thread_id) ?? null : threadId,
120485
+ // A review whose answer went to the previous daemon takes the first id it sees.
120486
+ kind: kind === "review" && !row.external_turn_id ? "prompt" : kind,
119452
120487
  codexId: row.external_turn_id,
119453
120488
  started: Promise.resolve(row.external_turn_id),
120489
+ resolveStarted: () => {
120490
+ },
120491
+ early: [],
119454
120492
  done: false,
119455
120493
  resuming: row.resume_state === "resuming",
119456
120494
  hostOffset: null
119457
- })
119458
- );
120495
+ };
120496
+ });
119459
120497
  const ended = /* @__PURE__ */ new Map();
119460
120498
  const endedRows = db2.prepare(
119461
120499
  "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
120500
  ).all(session.id, ENDED_TURNS_KEPT);
119463
120501
  for (const row of endedRows.reverse()) ended.set(row.external_turn_id, row.id);
119464
120502
  const known = db2.prepare("SELECT external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL").all(session.id);
120503
+ const state = emptyThreadState();
120504
+ const fill = storedContextTokens(db2, session.id);
119465
120505
  return {
119466
120506
  sessionId: session.id,
119467
120507
  client,
119468
120508
  pid: void 0,
120509
+ ...state,
119469
120510
  threadId,
120511
+ codexThreads: /* @__PURE__ */ new Set([threadId, ...sideOf.values()]),
120512
+ contextTokens: new Map(fill === null ? [] : [[threadId, fill]]),
120513
+ webSearch: threadConfig(parseRuntimeConfig(session))?.web_search,
119470
120514
  turns,
119471
120515
  ended,
119472
120516
  // A turn resumed on this app-server later continues with the continue
@@ -119539,7 +120583,7 @@ var codexHostAdopter = {
119539
120583
  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
120584
  sessionMap.set(session.id, entry);
119541
120585
  listen(entry);
119542
- if (session.origin_app_id) autoApproveToolUserInput(client);
120586
+ autoApproveToolUserInput(client);
119543
120587
  await replayDone(client, `session ${session.id}`);
119544
120588
  entry.replaying = false;
119545
120589
  if (!isCurrent(entry)) {
@@ -119550,6 +120594,7 @@ var codexHostAdopter = {
119550
120594
  recomputeSessionRunning(db2, session.id);
119551
120595
  broadcast("session:resync", { sessionId: session.id });
119552
120596
  resendStreams(session.id);
120597
+ refreshBackgroundTasks(entry);
119553
120598
  const running = entry.turns.map((t) => ({ id: t.id, threadId: t.discussionThreadId }));
119554
120599
  console.log(
119555
120600
  `[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 +120635,13 @@ var codexProvider = {
119590
120635
  startTurn: startTurn2,
119591
120636
  interruptTurn,
119592
120637
  clearThread,
120638
+ clearThreadBranch,
119593
120639
  clearAllThreads,
119594
120640
  getModels,
120641
+ getCommands,
120642
+ forkSession,
120643
+ stopTask,
120644
+ listBackgroundTasks,
119595
120645
  summarizeThread: summarizeCodexThread,
119596
120646
  resumeInterruptedTurn,
119597
120647
  reapOrphans,
@@ -120142,7 +121192,7 @@ function dropBackgroundTasks(sessionId, entry) {
120142
121192
  entry.backgroundTasks = [];
120143
121193
  publishBackgroundTasks(sessionId);
120144
121194
  }
120145
- function listBackgroundTasks() {
121195
+ function listBackgroundTasks2() {
120146
121196
  const bySession = {};
120147
121197
  for (const [key, entry] of sessionMap2) {
120148
121198
  if (!entry.backgroundTasks?.length) continue;
@@ -120175,7 +121225,11 @@ function rescueWaitMs() {
120175
121225
  }
120176
121226
  var RESCUE_ENV = ["CLAUDE_CODE_RESUME_INTERRUPTED_TURN", "CLAUDE_CODE_RESUME_REASON"];
120177
121227
  function spawnEnv(sessionId, resume) {
120178
- const env = { ...process.env, AGENT_PANE_SESSION_ID: sessionId };
121228
+ const env = {
121229
+ ...process.env,
121230
+ AGENT_PANE_SESSION_ID: sessionId,
121231
+ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1"
121232
+ };
120179
121233
  for (const k of RESCUE_ENV) delete env[k];
120180
121234
  if (resume) {
120181
121235
  env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN = "1";
@@ -120358,6 +121412,9 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume, ad
120358
121412
  permissionMode: "bypassPermissions",
120359
121413
  allowDangerouslySkipPermissions: true,
120360
121414
  includePartialMessages: true,
121415
+ // Echo user messages: a message from another Claude session (SendMessage)
121416
+ // reaches the pane only this way, with its sender in `origin` (MUH-102).
121417
+ extraArgs: { "replay-user-messages": null },
120361
121418
  // Inline visuals: the model's show_widget calls render in the chat.
120362
121419
  mcpServers: { [WIDGET_SERVER_NAME]: createWidgetMcpServer() },
120363
121420
  ...CLI_OVERRIDE,
@@ -120465,12 +121522,26 @@ async function dispatchFrame(entry, sessionId, message, db2, opts = {}) {
120465
121522
  entry.rateLimit = message.rate_limit_info;
120466
121523
  return;
120467
121524
  }
121525
+ const state = sessionStateOf(message);
121526
+ if (state) {
121527
+ handleSessionState(entry, state, db2);
121528
+ return;
121529
+ }
121530
+ const peer = peerOriginOf(message);
121531
+ if (peer) {
121532
+ handlePeerMessage(entry, sessionId, message, peer, db2);
121533
+ return;
121534
+ }
121535
+ if (entry.selfStarted && isModelFrame(message)) reopenForFollowUp(entry, sessionId, db2);
120468
121536
  const currentTurnId = entry.turnId;
120469
121537
  if (!currentTurnId) {
120470
121538
  handleTaskFrame(message, sessionId, entry, db2);
120471
121539
  return;
120472
121540
  }
120473
121541
  if (entry.resume && !trackResumeFrame(entry, message, db2)) return;
121542
+ if (message.type === "result" && !message.parent_tool_use_id) {
121543
+ entry.resultTurnId = currentTurnId;
121544
+ }
120474
121545
  if (opts.awaitResult && message.type === "result") {
120475
121546
  await handleResultMessage(message, sessionId, currentTurnId, entry, db2);
120476
121547
  return;
@@ -120481,6 +121552,119 @@ function isTurnLive2(db2, turnId) {
120481
121552
  const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
120482
121553
  return row?.status === "pending" || row?.status === "running";
120483
121554
  }
121555
+ function sessionStateOf(message) {
121556
+ if (message.type !== "system") return null;
121557
+ const m = message;
121558
+ if (m.subtype !== "session_state_changed") return null;
121559
+ return m.state === "idle" || m.state === "running" || m.state === "requires_action" ? m.state : null;
121560
+ }
121561
+ function peerOriginOf(message) {
121562
+ if (message.type !== "user") return null;
121563
+ if (message.parent_tool_use_id) return null;
121564
+ const origin = message.origin;
121565
+ return origin?.kind === "peer" ? origin : null;
121566
+ }
121567
+ var PEER_ENVELOPE2 = /<cross-session-message\b[^>]*>([\s\S]*?)<\/cross-session-message>/;
121568
+ function peerMessageBody(content, origin) {
121569
+ if (typeof origin.body === "string" && origin.body.trim()) return origin.body.trim();
121570
+ let text2 = "";
121571
+ if (typeof content === "string") text2 = content;
121572
+ else if (Array.isArray(content)) {
121573
+ text2 = content.map((b) => b && typeof b === "object" && b.type === "text" ? String(b.text ?? "") : "").join("\n");
121574
+ }
121575
+ const enveloped = PEER_ENVELOPE2.exec(text2);
121576
+ return (enveloped ? enveloped[1] : text2).trim();
121577
+ }
121578
+ function turnInProgress(entry, db2) {
121579
+ return !!entry.turnId && entry.resultTurnId !== entry.turnId && isTurnLive2(db2, entry.turnId);
121580
+ }
121581
+ function handleSessionState(entry, state, db2) {
121582
+ if (state === "running") {
121583
+ entry.selfStarted = !entry.resume && !turnInProgress(entry, db2);
121584
+ } else if (state === "idle") {
121585
+ entry.selfStarted = false;
121586
+ }
121587
+ }
121588
+ function handlePeerMessage(entry, sessionId, message, origin, db2) {
121589
+ const uuid3 = message.uuid ?? null;
121590
+ const body = peerMessageBody(message.message?.content, origin);
121591
+ const name = origin.name?.trim() || null;
121592
+ entry.selfStarted = false;
121593
+ if (uuid3) {
121594
+ const known = db2.prepare("SELECT id FROM turns WHERE session_id = ? AND runtime_input_ids = ?").get(sessionId, JSON.stringify([uuid3]));
121595
+ if (known) {
121596
+ entry.turnId = known.id;
121597
+ return;
121598
+ }
121599
+ }
121600
+ if (entry.turnId && turnInProgress(entry, db2)) {
121601
+ upsertItem(
121602
+ db2,
121603
+ { type: "peer_message", data: { name, from: origin.from ?? null, body }, externalId: `peer-${uuid3 ?? v4_default()}` },
121604
+ sessionId,
121605
+ entry.turnId,
121606
+ "completed",
121607
+ "item:completed"
121608
+ );
121609
+ return;
121610
+ }
121611
+ openPeerTurn(entry, sessionId, { body, name, uuid: uuid3 }, db2);
121612
+ }
121613
+ function openPeerTurn(entry, sessionId, peer, db2) {
121614
+ const previous = entry.turnId;
121615
+ if (previous && previous !== entry.resultTurnId && isTurnLive2(db2, previous)) {
121616
+ const prev = db2.prepare("SELECT token_usage FROM turns WHERE id = ?").get(previous);
121617
+ completeTurn2(db2, sessionId, previous, prev?.token_usage ? JSON.parse(prev.token_usage) : null);
121618
+ }
121619
+ if (previous) streamingMessageIds.delete(previous);
121620
+ const threadId = entry.threadId ?? null;
121621
+ const turnId = v4_default();
121622
+ const now = (/* @__PURE__ */ new Date()).toISOString();
121623
+ const inputIds = peer.uuid ? JSON.stringify([peer.uuid]) : null;
121624
+ db2.prepare(
121625
+ `INSERT INTO turns (id, session_id, user_prompt, status, thread_id, runtime_input_ids, origin, origin_name, created_at, updated_at)
121626
+ VALUES (?, ?, ?, 'running', ?, ?, 'peer', ?, ?, ?)`
121627
+ ).run(turnId, sessionId, peer.body, threadId, inputIds, peer.name, now, now);
121628
+ entry.turnId = turnId;
121629
+ entry.lastApiError = null;
121630
+ entry.reopenedTurnId = null;
121631
+ bindHostTurn2(entry, turnId);
121632
+ setSessionStatus2(db2, sessionId, 1, "running", now);
121633
+ const row = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turnId);
121634
+ const turn = {
121635
+ ...row,
121636
+ token_usage: null,
121637
+ attachments: null,
121638
+ runtime_input_ids: peer.uuid ? [peer.uuid] : null,
121639
+ items: []
121640
+ };
121641
+ if (threadId) {
121642
+ db2.prepare("UPDATE discussion_threads SET updated_at = ? WHERE id = ?").run(now, threadId);
121643
+ broadcast("thread:followup", { sessionId, threadId, turn });
121644
+ } else {
121645
+ broadcast("turn:created", { sessionId, turn });
121646
+ }
121647
+ broadcast("turn:started", { sessionId, turnId });
121648
+ }
121649
+ function reopenForFollowUp(entry, sessionId, db2) {
121650
+ entry.selfStarted = false;
121651
+ const turnId = entry.turnId;
121652
+ if (!turnId) return;
121653
+ entry.reopenedTurnId = turnId;
121654
+ const reopen = () => {
121655
+ if (entry.turnId !== turnId || entry.reopenedTurnId !== turnId || entry.closeReason) return;
121656
+ const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
121657
+ if (row?.status !== "completed") return;
121658
+ const now = (/* @__PURE__ */ new Date()).toISOString();
121659
+ db2.prepare("UPDATE turns SET status = 'running', updated_at = ? WHERE id = ?").run(now, turnId);
121660
+ if (entry.resultTurnId === turnId) entry.resultTurnId = null;
121661
+ bindHostTurn2(entry, turnId);
121662
+ setSessionStatus2(db2, sessionId, 1, "running", now);
121663
+ broadcast("turn:started", { sessionId, turnId });
121664
+ };
121665
+ if (entry.settling) void entry.settling.then(reopen, reopen);
121666
+ else reopen();
121667
+ }
120484
121668
  async function startTurn3(session, turn) {
120485
121669
  if (isAdoptionPending()) await waitForAdoption();
120486
121670
  const db2 = getDb();
@@ -120521,6 +121705,9 @@ async function startTurn3(session, turn) {
120521
121705
  }
120522
121706
  entry.turnId = turn.id;
120523
121707
  entry.lastApiError = null;
121708
+ entry.reopenedTurnId = null;
121709
+ entry.resultTurnId = null;
121710
+ entry.selfStarted = false;
120524
121711
  clearResume(entry);
120525
121712
  bindHostTurn2(entry, turn.id);
120526
121713
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
@@ -120988,14 +122175,25 @@ function handleBackgroundTasksChanged(message, sessionId, entry) {
120988
122175
  async function handleResultMessage(message, sessionId, turnId, entry, db2) {
120989
122176
  const parentToolUseId = message.parent_tool_use_id ?? null;
120990
122177
  if (parentToolUseId) return;
122178
+ const followUp = entry.reopenedTurnId === turnId;
122179
+ const settling = settleResult(message, sessionId, turnId, entry, db2, followUp);
122180
+ const tracked = settling.then(
122181
+ () => {
122182
+ },
122183
+ () => {
122184
+ }
122185
+ );
122186
+ entry.settling = tracked;
120991
122187
  try {
120992
- await settleResult(message, sessionId, turnId, entry, db2);
122188
+ await settling;
120993
122189
  } finally {
122190
+ if (followUp && entry.reopenedTurnId === turnId) entry.reopenedTurnId = null;
122191
+ if (entry.settling === tracked) entry.settling = null;
120994
122192
  settleHostTurn2(entry);
120995
122193
  maybeRetire2(entry);
120996
122194
  }
120997
122195
  }
120998
- async function settleResult(message, sessionId, turnId, entry, db2) {
122196
+ async function settleResult(message, sessionId, turnId, entry, db2, followUp = false) {
120999
122197
  if (message.subtype === "success") {
121000
122198
  const usage = mapUsage(message.usage);
121001
122199
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -121006,6 +122204,10 @@ async function settleResult(message, sessionId, turnId, entry, db2) {
121006
122204
  if (message.is_error) {
121007
122205
  const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
121008
122206
  if (!row || row.status === "pending" && row.resume_state === "waiting") return;
122207
+ if (followUp && row.status === "running") {
122208
+ completeTurn2(db2, sessionId, turnId, null);
122209
+ row.status = "completed";
122210
+ }
121009
122211
  const text2 = (message.result || apiError?.text || "Claude API error").trim();
121010
122212
  const kind = classifyApiError({
121011
122213
  error: apiError?.error,
@@ -121173,7 +122375,7 @@ function clearThread2(sessionId) {
121173
122375
  }
121174
122376
  publishBackgroundTasks(sessionId);
121175
122377
  }
121176
- function clearThreadBranch(sessionId, threadId) {
122378
+ function clearThreadBranch2(sessionId, threadId) {
121177
122379
  const key = `${sessionId}:thread:${threadId}`;
121178
122380
  const entry = sessionMap2.get(key);
121179
122381
  if (entry) closeEntry(key, entry);
@@ -121253,7 +122455,7 @@ async function setModel(sessionId, model) {
121253
122455
  await entry.query.setModel(model);
121254
122456
  void refreshContext(entry, sessionId, getDb());
121255
122457
  }
121256
- async function stopTask(sessionId, taskId) {
122458
+ async function stopTask2(sessionId, taskId) {
121257
122459
  const entry = sessionMap2.get(sessionId);
121258
122460
  if (!entry) return;
121259
122461
  await entry.query.stopTask(taskId);
@@ -121288,7 +122490,7 @@ async function getModels2() {
121288
122490
  return [];
121289
122491
  }
121290
122492
  }
121291
- async function getCommands() {
122493
+ async function getCommands2() {
121292
122494
  if (cachedCommands) return cachedCommands;
121293
122495
  await getModels2();
121294
122496
  return cachedCommands ?? [];
@@ -121554,6 +122756,7 @@ function bindHostTurn2(entry, turnId) {
121554
122756
  const host = entry.host;
121555
122757
  const proc = host?.proc;
121556
122758
  if (!host || !proc?.hosted) return;
122759
+ noteAdoptedTurn(turnId);
121557
122760
  const offset = proc.consumedLineEnd;
121558
122761
  try {
121559
122762
  setHostTurn(getDb(), host.id, turnId, offset);
@@ -121701,15 +122904,15 @@ var claudeProvider = {
121701
122904
  startTurn: startTurn3,
121702
122905
  interruptTurn: interruptTurn2,
121703
122906
  clearThread: clearThread2,
121704
- clearThreadBranch,
122907
+ clearThreadBranch: clearThreadBranch2,
121705
122908
  clearAllThreads: clearAllThreads2,
121706
122909
  getModels: getModels2,
121707
- getCommands,
122910
+ getCommands: getCommands2,
121708
122911
  forkSession: forkClaudeSession,
121709
122912
  summarizeThread: summarizeClaudeThread,
121710
122913
  setModel,
121711
- stopTask,
121712
- listBackgroundTasks,
122914
+ stopTask: stopTask2,
122915
+ listBackgroundTasks: listBackgroundTasks2,
121713
122916
  resumeInterruptedTurn: resumeInterruptedTurn2,
121714
122917
  reapOrphans: reapOrphans2,
121715
122918
  shutdown: shutdown2
@@ -121730,8 +122933,8 @@ var RepoburgHttpClient = class {
121730
122933
  this.baseUrl = baseUrl.replace(/\/+$/, "");
121731
122934
  }
121732
122935
  /** 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}`, {
122936
+ async request(method, path19, body) {
122937
+ const response = await fetch(`${this.baseUrl}${path19}`, {
121735
122938
  method,
121736
122939
  headers: { "Content-Type": "application/json" },
121737
122940
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -121740,17 +122943,17 @@ var RepoburgHttpClient = class {
121740
122943
  if (!response.ok) {
121741
122944
  if (isHtml(text2)) {
121742
122945
  throw new Error(
121743
- `${method} ${path17} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
122946
+ `${method} ${path19} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121744
122947
  );
121745
122948
  }
121746
- throw new Error(`${method} ${path17} failed: ${response.status} ${text2}`);
122949
+ throw new Error(`${method} ${path19} failed: ${response.status} ${text2}`);
121747
122950
  }
121748
122951
  if (text2.length === 0) return void 0;
121749
122952
  try {
121750
122953
  return JSON.parse(text2);
121751
122954
  } catch {
121752
122955
  throw new Error(
121753
- `${method} ${path17} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
122956
+ `${method} ${path19} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121754
122957
  );
121755
122958
  }
121756
122959
  }
@@ -121805,7 +123008,7 @@ var RepoburgHttpClient = class {
121805
123008
  };
121806
123009
 
121807
123010
  // src/repoburg/backend-resolver.ts
121808
- import path15 from "node:path";
123011
+ import path17 from "node:path";
121809
123012
  var HEALTH_POLL_INTERVAL_MS = 1e3;
121810
123013
  var HEALTH_TIMEOUT_MS = 3e4;
121811
123014
  function daemonBaseUrl() {
@@ -121860,7 +123063,7 @@ async function backendHealthy(baseUrl, expectedPath) {
121860
123063
  const health = await fetchJson(`${baseUrl}/health`, void 0, 2e3);
121861
123064
  if (health.status !== "ok") return false;
121862
123065
  if (expectedPath && health.projectPath) {
121863
- return path15.resolve(health.projectPath) === path15.resolve(expectedPath);
123066
+ return path17.resolve(health.projectPath) === path17.resolve(expectedPath);
121864
123067
  }
121865
123068
  return true;
121866
123069
  } catch {
@@ -121881,7 +123084,7 @@ function serviceBaseUrl(service) {
121881
123084
  return `http://localhost:${service.port}`;
121882
123085
  }
121883
123086
  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];
123087
+ return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path17.sep)).sort((a, b) => b.path.length - a.path.length)[0];
121885
123088
  }
121886
123089
  async function restartService(daemon, name) {
121887
123090
  try {
@@ -121917,7 +123120,7 @@ async function resolveBackendUrl(projectPath, opts = {}) {
121917
123120
  if (envUrl) {
121918
123121
  return { baseUrl: envUrl.replace(/\/+$/, ""), port: 0, name: "REPOBURG_BACKEND_URL" };
121919
123122
  }
121920
- const absPath = path15.resolve(projectPath);
123123
+ const absPath = path17.resolve(projectPath);
121921
123124
  const daemon = daemonBaseUrl();
121922
123125
  const cached3 = resolvedCache.get(absPath);
121923
123126
  if (cached3 && await backendHealthy(cached3.baseUrl, cached3.servesPath ?? absPath)) {
@@ -123470,7 +124673,7 @@ function clearThread3(sessionId) {
123470
124673
  sessionMap3.delete(key);
123471
124674
  }
123472
124675
  }
123473
- function clearThreadBranch2(sessionId, threadId) {
124676
+ function clearThreadBranch3(sessionId, threadId) {
123474
124677
  const key = `${sessionId}:thread:${threadId}`;
123475
124678
  const entry = sessionMap3.get(key);
123476
124679
  if (entry) {
@@ -123519,7 +124722,7 @@ async function resolveClient(session) {
123519
124722
  if (!resolved) throw new Error("No repoburg backend resolved.");
123520
124723
  return new RepoburgHttpClient(resolved.baseUrl);
123521
124724
  }
123522
- async function forkSession(session, targetTurn) {
124725
+ async function forkSession2(session, targetTurn) {
123523
124726
  if (!session.external_thread_id) return null;
123524
124727
  const anchor = parseRuntimeInputIds(targetTurn).pop();
123525
124728
  if (!anchor) {
@@ -123559,7 +124762,7 @@ async function getModels3(cwd) {
123559
124762
  return [];
123560
124763
  }
123561
124764
  }
123562
- async function getCommands2(cwd) {
124765
+ async function getCommands3(cwd) {
123563
124766
  try {
123564
124767
  const resolved = await resolveBackendUrl(cwd ?? process.cwd(), { autoStart: false });
123565
124768
  if (!resolved) return [];
@@ -123580,12 +124783,12 @@ var repoburgProvider = {
123580
124783
  startTurn: startTurn4,
123581
124784
  interruptTurn: interruptTurn3,
123582
124785
  clearThread: clearThread3,
123583
- clearThreadBranch: clearThreadBranch2,
124786
+ clearThreadBranch: clearThreadBranch3,
123584
124787
  clearAllThreads: clearAllThreads3,
123585
124788
  getModels: getModels3,
123586
- getCommands: getCommands2,
124789
+ getCommands: getCommands3,
123587
124790
  rewindRuntime,
123588
- forkSession,
124791
+ forkSession: forkSession2,
123589
124792
  shutdown: shutdown3
123590
124793
  };
123591
124794
 
@@ -123598,7 +124801,7 @@ registerProvider("repoburg", repoburgProvider);
123598
124801
  async function createAgentPaneApp(dbPath, opts = {}) {
123599
124802
  const allowRequest = opts.allowRequest ?? isLocalRequest;
123600
124803
  initDb(dbPath);
123601
- setPaneDataDir(dbPath === ":memory:" ? null : path16.dirname(path16.resolve(dbPath)));
124804
+ setPaneDataDir(dbPath === ":memory:" ? null : path18.dirname(path18.resolve(dbPath)));
123602
124805
  const fastify = (0, import_fastify.default)({ logger: true, bodyLimit: 50 * 1024 * 1024 });
123603
124806
  fastify.addHook("onRequest", async (request, reply) => {
123604
124807
  if (!allowRequest(request.headers.origin, request.headers.host)) {
@@ -123624,6 +124827,7 @@ async function createAgentPaneApp(dbPath, opts = {}) {
123624
124827
  await registerSidecarRoutes(fastify);
123625
124828
  await registerUsageRoutes(fastify);
123626
124829
  await registerClaudeSessionRoutes(fastify);
124830
+ await registerCodexSessionRoutes(fastify);
123627
124831
  await registerSessionHostRoutes(fastify);
123628
124832
  const wss3 = initWs(allowRequest);
123629
124833
  initTerminalWs(allowRequest);