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'");
@@ -41673,7 +41688,7 @@ function handleTerminalUpgrade(request, socket, head) {
41673
41688
  }
41674
41689
 
41675
41690
  // src/routes/sessions.ts
41676
- import path2 from "node:path";
41691
+ import path3 from "node:path";
41677
41692
 
41678
41693
  // node_modules/uuid/dist/esm/stringify.js
41679
41694
  var byteToHex = [];
@@ -41965,6 +41980,45 @@ function startTurn(db2, session, { prompt, attachments, originAppId }) {
41965
41980
  return parsedTurn;
41966
41981
  }
41967
41982
 
41983
+ // src/providers/attachment-files.ts
41984
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
41985
+ import os2 from "node:os";
41986
+ import path2 from "node:path";
41987
+ function sessionDir(sessionId) {
41988
+ let base = path2.join(os2.tmpdir(), "agentpane");
41989
+ try {
41990
+ const file2 = getDb().name;
41991
+ if (file2 && file2 !== ":memory:") base = path2.dirname(path2.resolve(file2));
41992
+ } catch {
41993
+ }
41994
+ return path2.join(base, "attachments", sessionId.replace(/[^\w.-]/g, "_"));
41995
+ }
41996
+ function safeName(name) {
41997
+ const base = path2.basename(name || "attachment").replace(/[^\w.\- ()]/g, "_").trim();
41998
+ return base && base !== "." && base !== ".." ? base : "attachment";
41999
+ }
42000
+ function freeName(name, taken) {
42001
+ const ext = path2.extname(name);
42002
+ let free = name;
42003
+ for (let n = 2; taken.has(free.toLowerCase()); n++) free = `${name.slice(0, name.length - ext.length)}-${n}${ext}`;
42004
+ taken.add(free.toLowerCase());
42005
+ return free;
42006
+ }
42007
+ function saveAttachmentFile(sessionId, turnId, name, base643, taken = /* @__PURE__ */ new Set()) {
42008
+ const dir = path2.join(sessionDir(sessionId), turnId.replace(/[^\w.-]/g, "_"));
42009
+ mkdirSync(dir, { recursive: true });
42010
+ const file2 = path2.join(dir, freeName(safeName(name), taken));
42011
+ writeFileSync(file2, Buffer.from(base643, "base64"));
42012
+ return file2;
42013
+ }
42014
+ function removeAttachmentFiles(sessionId) {
42015
+ try {
42016
+ rmSync(sessionDir(sessionId), { recursive: true, force: true });
42017
+ } catch (err) {
42018
+ console.warn(`[attachments] could not remove the files of session ${sessionId}: ${err.message}`);
42019
+ }
42020
+ }
42021
+
41968
42022
  // src/routes/sessions.ts
41969
42023
  async function registerSessionRoutes(fastify) {
41970
42024
  fastify.get("/api/sessions", async () => {
@@ -42061,6 +42115,7 @@ async function registerSessionRoutes(fastify) {
42061
42115
  db2.prepare("DELETE FROM items WHERE turn_id IN (SELECT id FROM turns WHERE session_id = ?)").run(id);
42062
42116
  db2.prepare("DELETE FROM turns WHERE session_id = ?").run(id);
42063
42117
  db2.prepare("DELETE FROM sessions WHERE id = ?").run(id);
42118
+ removeAttachmentFiles(id);
42064
42119
  return { success: true };
42065
42120
  });
42066
42121
  fastify.patch("/api/sessions/:id", {
@@ -42126,8 +42181,8 @@ async function registerSessionRoutes(fastify) {
42126
42181
  }
42127
42182
  let workspaceChanged = false;
42128
42183
  if (cwd !== void 0) {
42129
- const oldAbs = existing.cwd ? path2.resolve(existing.cwd) : null;
42130
- const newAbs = cwd ? path2.resolve(cwd) : null;
42184
+ const oldAbs = existing.cwd ? path3.resolve(existing.cwd) : null;
42185
+ const newAbs = cwd ? path3.resolve(cwd) : null;
42131
42186
  workspaceChanged = oldAbs !== newAbs;
42132
42187
  if (workspaceChanged && existing.is_running) {
42133
42188
  return reply.code(409).send({ error: "Cannot change workspace while a turn is running" });
@@ -42321,8 +42376,8 @@ async function registerSessionRoutes(fastify) {
42321
42376
  for (const turn of turnRows) {
42322
42377
  const newTurnId = v4_default();
42323
42378
  db2.prepare(
42324
- `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status, error, attachments, created_at, updated_at)
42325
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42379
+ `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)
42380
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
42326
42381
  ).run(
42327
42382
  newTurnId,
42328
42383
  newSessionId,
@@ -42334,6 +42389,8 @@ async function registerSessionRoutes(fastify) {
42334
42389
  turn.status,
42335
42390
  turn.error,
42336
42391
  turn.attachments,
42392
+ turn.origin ?? null,
42393
+ turn.origin_name ?? null,
42337
42394
  turn.created_at,
42338
42395
  turn.updated_at
42339
42396
  );
@@ -42575,7 +42632,7 @@ function recoverInterruptedTurns(db2, opts) {
42575
42632
  WHERE i.status = 'in_progress'`
42576
42633
  ).all();
42577
42634
  const orphaned = open.filter((i) => !skip.entries.has(runtimeEntryKey(i.session_id, i.thread_id)));
42578
- const stopTask2 = db2.prepare(
42635
+ const stopTask3 = db2.prepare(
42579
42636
  `UPDATE items SET data = json_set(COALESCE(data, '{}'), '$.status', 'stopped')
42580
42637
  WHERE id = ? AND json_valid(COALESCE(data, '{}'))`
42581
42638
  );
@@ -42583,7 +42640,7 @@ function recoverInterruptedTurns(db2, opts) {
42583
42640
  const items = { changes: 0 };
42584
42641
  db2.transaction(() => {
42585
42642
  for (const item of orphaned) {
42586
- if (item.type === "background_task") stopTask2.run(item.id);
42643
+ if (item.type === "background_task") stopTask3.run(item.id);
42587
42644
  items.changes += failItem.run(now, item.id).changes;
42588
42645
  }
42589
42646
  })();
@@ -42953,6 +43010,28 @@ async function registerTurnRoutes(fastify) {
42953
43010
  markSessionTouched(db2, id);
42954
43011
  return { success: true };
42955
43012
  });
43013
+ fastify.post(
43014
+ "/api/sessions/:id/tasks/:taskId/stop",
43015
+ async (request, reply) => {
43016
+ const { id, taskId } = request.params;
43017
+ const db2 = getDb();
43018
+ const session = db2.prepare("SELECT runtime_type FROM sessions WHERE id = ?").get(id);
43019
+ if (!session) {
43020
+ return reply.code(404).send({ error: "Session not found" });
43021
+ }
43022
+ const provider = getProvider(session.runtime_type);
43023
+ if (!provider.stopTask) {
43024
+ return reply.code(501).send({ error: `${session.runtime_type} sessions cannot stop background tasks` });
43025
+ }
43026
+ try {
43027
+ await provider.stopTask(id, taskId);
43028
+ } catch (err) {
43029
+ return reply.code(409).send({ error: err.message });
43030
+ }
43031
+ markSessionTouched(db2, id);
43032
+ return { success: true };
43033
+ }
43034
+ );
42956
43035
  fastify.post(
42957
43036
  "/api/sessions/:id/turns/:turnId/resume",
42958
43037
  async (request, reply) => {
@@ -43370,9 +43449,9 @@ async function browseFolder(input, opts = {}) {
43370
43449
  const atHome = dir === nodePath.resolve(home);
43371
43450
  const folders = await Promise.all(
43372
43451
  names.slice(0, limit).map(async (name) => {
43373
- const path17 = nodePath.join(dir, name);
43452
+ const path19 = nodePath.join(dir, name);
43374
43453
  const skipProbe = atHome && HOME_STANDARD_FOLDERS.has(name) || dir === "/Volumes";
43375
- return { name, path: path17, git: !skipProbe && await exists(nodePath.join(path17, ".git")) };
43454
+ return { name, path: path19, git: !skipProbe && await exists(nodePath.join(path19, ".git")) };
43376
43455
  })
43377
43456
  );
43378
43457
  const parent = nodePath.dirname(dir);
@@ -43410,11 +43489,11 @@ async function registerWorkspaceRoutes(fastify) {
43410
43489
  }
43411
43490
  }
43412
43491
  }, async (request, reply) => {
43413
- const { path: path17, label = null } = request.body || {};
43414
- if (!path17 || !path17.trim()) {
43492
+ const { path: path19, label = null } = request.body || {};
43493
+ if (!path19 || !path19.trim()) {
43415
43494
  return reply.code(400).send({ error: "Path is required" });
43416
43495
  }
43417
- const resolved = await resolveWorkspacePath(path17);
43496
+ const resolved = await resolveWorkspacePath(path19);
43418
43497
  if ("error" in resolved) {
43419
43498
  return reply.code(400).send({ error: resolved.error });
43420
43499
  }
@@ -43456,8 +43535,8 @@ async function registerWorkspaceRoutes(fastify) {
43456
43535
  "-e",
43457
43536
  'POSIX path of (choose folder with prompt "Select a workspace directory")'
43458
43537
  ]);
43459
- const path17 = stdout.trim().replace(/\/$/, "");
43460
- return { path: path17 };
43538
+ const path19 = stdout.trim().replace(/\/$/, "");
43539
+ return { path: path19 };
43461
43540
  } catch {
43462
43541
  return reply.code(204).send({ cancelled: true });
43463
43542
  }
@@ -43473,11 +43552,11 @@ async function registerWorkspaceRoutes(fastify) {
43473
43552
  }
43474
43553
  }
43475
43554
  }, async (request, reply) => {
43476
- const { path: path17 } = request.body || {};
43477
- if (!path17 || !path17.trim()) {
43555
+ const { path: path19 } = request.body || {};
43556
+ if (!path19 || !path19.trim()) {
43478
43557
  return reply.code(400).send({ error: "Path is required" });
43479
43558
  }
43480
- const trimmedPath = path17.trim();
43559
+ const trimmedPath = path19.trim();
43481
43560
  const db2 = getDb();
43482
43561
  const existing = db2.prepare("SELECT * FROM workspaces WHERE path = ?").get(trimmedPath);
43483
43562
  if (existing) {
@@ -44168,7 +44247,7 @@ async function registerFileRoutes(fastify) {
44168
44247
  }
44169
44248
 
44170
44249
  // src/routes/perf-log.ts
44171
- import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
44250
+ import { appendFileSync, mkdirSync as mkdirSync2, renameSync, statSync } from "node:fs";
44172
44251
  import { homedir as homedir2 } from "node:os";
44173
44252
  import { dirname, join } from "node:path";
44174
44253
  var MAX_BYTES = 5 * 1024 * 1024;
@@ -44211,17 +44290,17 @@ async function registerPerfLogRoutes(fastify) {
44211
44290
  if (entries.length === 0) {
44212
44291
  return reply.send({ written: 0 });
44213
44292
  }
44214
- const path17 = perfLogPath();
44293
+ const path19 = perfLogPath();
44215
44294
  try {
44216
- mkdirSync(dirname(path17), { recursive: true });
44295
+ mkdirSync2(dirname(path19), { recursive: true });
44217
44296
  try {
44218
- if (statSync(path17).size > MAX_BYTES) {
44219
- renameSync(path17, `${path17}.1`);
44297
+ if (statSync(path19).size > MAX_BYTES) {
44298
+ renameSync(path19, `${path19}.1`);
44220
44299
  }
44221
44300
  } catch {
44222
44301
  }
44223
44302
  const lines = entries.map((e) => `${new Date(e.t).toISOString()} [${oneLine(e.cat)}] ${oneLine(e.msg)}`).join("\n");
44224
- appendFileSync(path17, `${lines}
44303
+ appendFileSync(path19, `${lines}
44225
44304
  `, "utf-8");
44226
44305
  return reply.send({ written: entries.length });
44227
44306
  } catch (err) {
@@ -44297,24 +44376,24 @@ import { existsSync } from "node:fs";
44297
44376
  import http from "node:http";
44298
44377
  import net from "node:net";
44299
44378
  import crypto from "node:crypto";
44300
- import os2 from "node:os";
44301
- import path3 from "node:path";
44379
+ import os3 from "node:os";
44380
+ import path4 from "node:path";
44302
44381
  import { mkdir, readdir as readdir2, symlink, lstat, access, readFile, writeFile, unlink } from "node:fs/promises";
44303
- var VSCODE_WEB_DATA_DIR = path3.join(os2.homedir(), ".repoburg", "vscode-web");
44382
+ var VSCODE_WEB_DATA_DIR = path4.join(os3.homedir(), ".repoburg", "vscode-web");
44304
44383
  function resolveDesktopUserDir() {
44305
44384
  if (process.platform === "darwin") {
44306
- return path3.join(os2.homedir(), "Library", "Application Support", "Code", "User");
44385
+ return path4.join(os3.homedir(), "Library", "Application Support", "Code", "User");
44307
44386
  }
44308
44387
  if (process.platform === "win32" && process.env.APPDATA) {
44309
- return path3.join(process.env.APPDATA, "Code", "User");
44388
+ return path4.join(process.env.APPDATA, "Code", "User");
44310
44389
  }
44311
44390
  if (process.platform === "linux") {
44312
- return path3.join(os2.homedir(), ".config", "Code", "User");
44391
+ return path4.join(os3.homedir(), ".config", "Code", "User");
44313
44392
  }
44314
44393
  return null;
44315
44394
  }
44316
44395
  async function linkUnlessExists(src, dst) {
44317
- await mkdir(path3.dirname(dst), { recursive: true });
44396
+ await mkdir(path4.dirname(dst), { recursive: true });
44318
44397
  try {
44319
44398
  await lstat(dst);
44320
44399
  return false;
@@ -44329,19 +44408,19 @@ function fileRegistryUri(dir) {
44329
44408
  }
44330
44409
  async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44331
44410
  try {
44332
- const desktopExt = path3.join(os2.homedir(), ".vscode", "extensions");
44411
+ const desktopExt = path4.join(os3.homedir(), ".vscode", "extensions");
44333
44412
  let entries;
44334
44413
  try {
44335
44414
  entries = await readdir2(desktopExt, { withFileTypes: true });
44336
44415
  } catch {
44337
44416
  return;
44338
44417
  }
44339
- const serverExt = path3.join(dataDir, "extensions");
44418
+ const serverExt = path4.join(dataDir, "extensions");
44340
44419
  const linkedFolders = [];
44341
44420
  for (const entry of entries) {
44342
44421
  if (!entry.isDirectory()) continue;
44343
- const target = path3.join(serverExt, entry.name);
44344
- await linkUnlessExists(path3.join(desktopExt, entry.name), target);
44422
+ const target = path4.join(serverExt, entry.name);
44423
+ await linkUnlessExists(path4.join(desktopExt, entry.name), target);
44345
44424
  const st = await lstat(target).catch(() => null);
44346
44425
  if (st?.isSymbolicLink()) linkedFolders.push(entry.name);
44347
44426
  }
@@ -44349,15 +44428,15 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44349
44428
  await pruneObsolete(serverExt, linkedFolders);
44350
44429
  const desktopUser = resolveDesktopUserDir();
44351
44430
  if (!desktopUser) return;
44352
- const serverUser = path3.join(dataDir, "data", "User");
44431
+ const serverUser = path4.join(dataDir, "data", "User");
44353
44432
  for (const item of ["settings.json", "keybindings.json", "snippets"]) {
44354
- const src = path3.join(desktopUser, item);
44433
+ const src = path4.join(desktopUser, item);
44355
44434
  try {
44356
44435
  await access(src);
44357
44436
  } catch {
44358
44437
  continue;
44359
44438
  }
44360
- await linkUnlessExists(src, path3.join(serverUser, item));
44439
+ await linkUnlessExists(src, path4.join(serverUser, item));
44361
44440
  }
44362
44441
  } catch {
44363
44442
  }
@@ -44365,13 +44444,13 @@ async function syncProfile(dataDir = VSCODE_WEB_DATA_DIR) {
44365
44444
  async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
44366
44445
  let desktopEntries = [];
44367
44446
  try {
44368
- desktopEntries = JSON.parse(await readFile(path3.join(desktopExt, "extensions.json"), "utf8"));
44447
+ desktopEntries = JSON.parse(await readFile(path4.join(desktopExt, "extensions.json"), "utf8"));
44369
44448
  } catch {
44370
44449
  return;
44371
44450
  }
44372
44451
  const linked = new Set(linkedFolders);
44373
44452
  const toAdd = desktopEntries.filter((e) => e.identifier?.id && linked.has(e.relativeLocation));
44374
- const serverRegistryPath = path3.join(serverExt, "extensions.json");
44453
+ const serverRegistryPath = path4.join(serverExt, "extensions.json");
44375
44454
  let serverEntries = [];
44376
44455
  try {
44377
44456
  serverEntries = JSON.parse(await readFile(serverRegistryPath, "utf8"));
@@ -44381,13 +44460,13 @@ async function mergeExtensionRegistry(desktopExt, serverExt, linkedFolders) {
44381
44460
  const additions = toAdd.filter((e) => !known.has(`${e.identifier.id.toLowerCase()}@${e.version}`));
44382
44461
  if (additions.length === 0) return;
44383
44462
  for (const entry of additions) {
44384
- const dir = path3.join(serverExt, entry.relativeLocation);
44463
+ const dir = path4.join(serverExt, entry.relativeLocation);
44385
44464
  serverEntries.push({ ...entry, location: fileRegistryUri(dir) });
44386
44465
  }
44387
44466
  await writeFile(serverRegistryPath, JSON.stringify(serverEntries));
44388
44467
  }
44389
44468
  async function pruneObsolete(serverExt, linkedFolders) {
44390
- const obsoletePath = path3.join(serverExt, ".obsolete");
44469
+ const obsoletePath = path4.join(serverExt, ".obsolete");
44391
44470
  let obsolete;
44392
44471
  try {
44393
44472
  obsolete = JSON.parse(await readFile(obsoletePath, "utf8"));
@@ -44846,16 +44925,16 @@ function proxyHandler(request, reply) {
44846
44925
 
44847
44926
  // src/routes/apps.ts
44848
44927
  import fs6 from "node:fs";
44849
- import path9 from "node:path";
44928
+ import path10 from "node:path";
44850
44929
 
44851
44930
  // src/apps/instances.ts
44852
44931
  import fs3 from "node:fs";
44853
- import path5 from "node:path";
44932
+ import path6 from "node:path";
44854
44933
 
44855
44934
  // src/apps/apps-registry.ts
44856
44935
  import fs2 from "node:fs";
44857
- import path4 from "node:path";
44858
- import os3 from "node:os";
44936
+ import path5 from "node:path";
44937
+ import os4 from "node:os";
44859
44938
  import { fileURLToPath } from "node:url";
44860
44939
 
44861
44940
  // node_modules/lucide-static/icon-nodes.json
@@ -99079,10 +99158,10 @@ function setAppsRootOverride(root) {
99079
99158
  rootOverride = root;
99080
99159
  }
99081
99160
  function appsRoot() {
99082
- return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path4.join(os3.homedir(), ".repoburg", "agent-pane", "apps");
99161
+ return rootOverride ?? process.env.AGENT_PANE_APPS_DIR ?? path5.join(os4.homedir(), ".repoburg", "agent-pane", "apps");
99083
99162
  }
99084
99163
  function appDir(id) {
99085
- return path4.join(appsRoot(), id);
99164
+ return path5.join(appsRoot(), id);
99086
99165
  }
99087
99166
  var examplesRootOverride = null;
99088
99167
  function setExamplesRootOverride(root) {
@@ -99091,16 +99170,16 @@ function setExamplesRootOverride(root) {
99091
99170
  function examplesRoot() {
99092
99171
  if (examplesRootOverride) return examplesRootOverride;
99093
99172
  if (process.env.AGENT_PANE_EXAMPLES_DIR) return process.env.AGENT_PANE_EXAMPLES_DIR;
99094
- const here = path4.dirname(fileURLToPath(import.meta.url));
99095
- for (const candidate of [path4.resolve(here, "../../examples"), path4.resolve(here, "../../../examples")]) {
99173
+ const here = path5.dirname(fileURLToPath(import.meta.url));
99174
+ for (const candidate of [path5.resolve(here, "../../examples"), path5.resolve(here, "../../../examples")]) {
99096
99175
  if (fs2.existsSync(candidate)) return candidate;
99097
99176
  }
99098
99177
  return null;
99099
99178
  }
99100
99179
  function isInAppFolder(cwd) {
99101
99180
  if (!cwd) return false;
99102
- const rel = path4.relative(path4.resolve(appsRoot()), path4.resolve(cwd));
99103
- return rel !== "" && !path4.isAbsolute(rel) && rel.split(path4.sep)[0] !== "..";
99181
+ const rel = path5.relative(path5.resolve(appsRoot()), path5.resolve(cwd));
99182
+ return rel !== "" && !path5.isAbsolute(rel) && rel.split(path5.sep)[0] !== "..";
99104
99183
  }
99105
99184
  function appsConventions() {
99106
99185
  return APPS_MD_SKELETON;
@@ -99109,7 +99188,7 @@ function ensureAppsRoot() {
99109
99188
  const root = appsRoot();
99110
99189
  fs2.mkdirSync(root, { recursive: true });
99111
99190
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
99112
- const file2 = path4.join(root, name);
99191
+ const file2 = path5.join(root, name);
99113
99192
  try {
99114
99193
  if (fs2.existsSync(file2) && fs2.readFileSync(file2, "utf-8") === APPS_MD_FILE) continue;
99115
99194
  fs2.writeFileSync(file2, APPS_MD_FILE);
@@ -99333,7 +99412,7 @@ folder's own CLAUDE.md / AGENTS.md. -->
99333
99412
  ${APPS_MD_SKELETON}`;
99334
99413
  function readManifestIn(dir) {
99335
99414
  try {
99336
- const raw = fs2.readFileSync(path4.join(dir, "manifest.json"), "utf-8");
99415
+ const raw = fs2.readFileSync(path5.join(dir, "manifest.json"), "utf-8");
99337
99416
  const parsed = JSON.parse(raw);
99338
99417
  if (!parsed || typeof parsed.title !== "string") return null;
99339
99418
  return {
@@ -99352,7 +99431,7 @@ function readManifest(id) {
99352
99431
  }
99353
99432
  function readAppFile(id, name) {
99354
99433
  try {
99355
- return fs2.readFileSync(path4.join(appDir(id), name), "utf-8");
99434
+ return fs2.readFileSync(path5.join(appDir(id), name), "utf-8");
99356
99435
  } catch {
99357
99436
  return "";
99358
99437
  }
@@ -99385,11 +99464,11 @@ function startAppsWatch(onAppChange) {
99385
99464
  try {
99386
99465
  watcher = fs2.watch(root, { recursive: true }, (_event, filename) => {
99387
99466
  const rel = String(filename ?? "");
99388
- const segs = rel.split(path4.sep);
99467
+ const segs = rel.split(path5.sep);
99389
99468
  const appId = segs[0];
99390
99469
  const file2 = segs[segs.length - 1];
99391
- if (!appId || appId === path4.basename(root) || !APP_ID_RE.test(appId) || file2 === "state.json") return;
99392
- if (segs.length === 1 && isRegularFile(path4.join(root, appId))) return;
99470
+ if (!appId || appId === path5.basename(root) || !APP_ID_RE.test(appId) || file2 === "state.json") return;
99471
+ if (segs.length === 1 && isRegularFile(path5.join(root, appId))) return;
99393
99472
  const timer2 = pendingChanges.get(appId);
99394
99473
  if (timer2) clearTimeout(timer2);
99395
99474
  pendingChanges.set(
@@ -99460,7 +99539,7 @@ function getInstanceState(appId, workspace = "") {
99460
99539
  const stored = readRow(appId, workspace);
99461
99540
  if (stored) return stored;
99462
99541
  if (workspace === "") {
99463
- const legacyFile = path5.join(appDir(appId), "state.json");
99542
+ const legacyFile = path6.join(appDir(appId), "state.json");
99464
99543
  if (fs3.existsSync(legacyFile)) {
99465
99544
  const legacy = readState(appId);
99466
99545
  const imported = { pinned: legacy.pinned, data: legacy.data, version: 1 };
@@ -99493,9 +99572,9 @@ function resolveToolWorkspace(workspace) {
99493
99572
  const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99494
99573
  const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99495
99574
  if (active.includes(workspace)) return workspace;
99496
- const cwd = path5.isAbsolute(workspace) ? path5.resolve(workspace) : "";
99575
+ const cwd = path6.isAbsolute(workspace) ? path6.resolve(workspace) : "";
99497
99576
  if (isInAppFolder(cwd)) return "";
99498
- const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path5.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99577
+ const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path6.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99499
99578
  if (covering && !covering.deleted) return covering.path;
99500
99579
  throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99501
99580
  }
@@ -99507,7 +99586,7 @@ function deleteAppInstances(appId) {
99507
99586
  import fs5 from "node:fs";
99508
99587
 
99509
99588
  // src/apps/app-sessions.ts
99510
- import path7 from "node:path";
99589
+ import path8 from "node:path";
99511
99590
 
99512
99591
  // src/sidecar/transcript-locator.ts
99513
99592
  import { existsSync as existsSync2, readdirSync } from "node:fs";
@@ -99592,8 +99671,8 @@ function locateTranscriptCached(session) {
99592
99671
  // src/apps/app-files.ts
99593
99672
  import crypto2 from "node:crypto";
99594
99673
  import fs4 from "node:fs";
99595
- import os4 from "node:os";
99596
- import path6 from "node:path";
99674
+ import os5 from "node:os";
99675
+ import path7 from "node:path";
99597
99676
  var APP_FILE_MAX_BYTES = 5 * 1024 * 1024;
99598
99677
  var APP_FILE_TYPES = {
99599
99678
  "image/png": "png",
@@ -99618,11 +99697,11 @@ function setAppFilesRootOverride(root) {
99618
99697
  rootOverride2 = root;
99619
99698
  }
99620
99699
  function appFilesRoot() {
99621
- return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path6.join(os4.homedir(), ".repoburg", "agent-pane", "app-files");
99700
+ return rootOverride2 ?? process.env.AGENT_PANE_APP_FILES_DIR ?? path7.join(os5.homedir(), ".repoburg", "agent-pane", "app-files");
99622
99701
  }
99623
99702
  function appFilesDir(appId) {
99624
99703
  if (!APP_ID_RE.test(appId)) throw new AppFileError("Invalid app id", 400);
99625
- return path6.join(appFilesRoot(), appId);
99704
+ return path7.join(appFilesRoot(), appId);
99626
99705
  }
99627
99706
  function appFileUrl(appId, fileId) {
99628
99707
  return `/api/apps/${appId}/files/${fileId}`;
@@ -99683,7 +99762,7 @@ function saveAppFile(appId, upload) {
99683
99762
  const type = sniffImageType(bytes);
99684
99763
  if (!type) throw new AppFileError(`The file is not a ${ACCEPTED} image`, 400);
99685
99764
  const fileId = `${crypto2.createHash("sha256").update(bytes).digest("hex")}.${APP_FILE_TYPES[type]}`;
99686
- const file2 = path6.join(dir, fileId);
99765
+ const file2 = path7.join(dir, fileId);
99687
99766
  if (!fs4.existsSync(file2)) {
99688
99767
  fs4.mkdirSync(dir, { recursive: true });
99689
99768
  const tmp = `${file2}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
@@ -99715,7 +99794,7 @@ function getAppFile(appId, ref) {
99715
99794
  if (!APP_ID_RE.test(appId)) return null;
99716
99795
  const fileId = appFileRefId(appId, ref);
99717
99796
  if (!fileId) return null;
99718
- const file2 = path6.join(appFilesDir(appId), fileId);
99797
+ const file2 = path7.join(appFilesDir(appId), fileId);
99719
99798
  try {
99720
99799
  const stat2 = fs4.statSync(file2);
99721
99800
  if (!stat2.isFile()) return null;
@@ -99727,7 +99806,7 @@ function getAppFile(appId, ref) {
99727
99806
  function readAppFileData(appId, fileId) {
99728
99807
  if (!APP_ID_RE.test(appId) || !APP_FILE_ID_RE.test(fileId)) return null;
99729
99808
  try {
99730
- return { bytes: fs4.readFileSync(path6.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99809
+ return { bytes: fs4.readFileSync(path7.join(appFilesDir(appId), fileId)), type: fileType(fileId) };
99731
99810
  } catch {
99732
99811
  return null;
99733
99812
  }
@@ -99837,7 +99916,7 @@ function appSessionInfo(appId, sessionId) {
99837
99916
  function sessionVisibleTo(session, appId, workspace) {
99838
99917
  if (!workspace) return true;
99839
99918
  const cwd = session.cwd;
99840
- if (cwd && (cwd === workspace || cwd.startsWith(workspace.endsWith(path7.sep) ? workspace : workspace + path7.sep))) {
99919
+ if (cwd && (cwd === workspace || cwd.startsWith(workspace.endsWith(path8.sep) ? workspace : workspace + path8.sep))) {
99841
99920
  return true;
99842
99921
  }
99843
99922
  return session.origin_app_workspace === workspace && openedByApp(session, appId);
@@ -99932,7 +100011,7 @@ import vm2 from "node:vm";
99932
100011
 
99933
100012
  // src/apps/app-compile.ts
99934
100013
  import vm from "node:vm";
99935
- import path8 from "node:path";
100014
+ import path9 from "node:path";
99936
100015
  import ts from "typescript";
99937
100016
 
99938
100017
  // src/apps/app-lint.ts
@@ -100329,15 +100408,15 @@ function typeCheckModules(appId, modules) {
100329
100408
  };
100330
100409
  const host = ts.createCompilerHost(options);
100331
100410
  const origReadFile = host.readFile.bind(host);
100332
- host.readFile = (fname) => path8.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
100411
+ host.readFile = (fname) => path9.basename(fname) === BRIDGE_DTS_FILE ? BRIDGE_DTS : origReadFile(fname);
100333
100412
  host.writeFile = () => {
100334
100413
  };
100335
- const bridgePath = path8.join(dir, BRIDGE_DTS_FILE);
100336
- const rootNames = [...modules.map((m) => path8.join(dir, m.file)), bridgePath];
100414
+ const bridgePath = path9.join(dir, BRIDGE_DTS_FILE);
100415
+ const rootNames = [...modules.map((m) => path9.join(dir, m.file)), bridgePath];
100337
100416
  const program = ts.createProgram(rootNames, options, host);
100338
100417
  const out = [];
100339
100418
  for (const mod of modules) {
100340
- const sf = program.getSourceFile(path8.join(dir, mod.file));
100419
+ const sf = program.getSourceFile(path9.join(dir, mod.file));
100341
100420
  if (!sf) continue;
100342
100421
  out.push(
100343
100422
  ...[...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)].map((d) => tsDiagnosticToFile(mod.file, d)).filter((d) => d !== null)
@@ -100697,6 +100776,63 @@ function invalidateHeadlessRuntime(appId) {
100697
100776
  }
100698
100777
  }
100699
100778
 
100779
+ // src/providers/widget-spec.ts
100780
+ var WIDGET_TOOL_BASE_NAME = "show_widget";
100781
+ var WIDGET_CDN_ORIGINS = [
100782
+ "https://cdnjs.cloudflare.com",
100783
+ "https://cdn.jsdelivr.net",
100784
+ "https://unpkg.com",
100785
+ "https://esm.sh"
100786
+ ];
100787
+ 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.";
100788
+ var WIDGET_TOOL_DESCRIPTION = [
100789
+ "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.",
100790
+ "",
100791
+ "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.",
100792
+ "",
100793
+ `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.`,
100794
+ "",
100795
+ "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.",
100796
+ "",
100797
+ '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).',
100798
+ "",
100799
+ "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."
100800
+ ].join("\n");
100801
+ var WIDGET_SHOWN_RESULT = "The widget is now shown to the user inline in the chat.";
100802
+ var WIDGET_EMPTY_RESULT = "widget_code is empty, so nothing was shown.";
100803
+ var WIDGET_TITLE_DESCRIPTION = 'Short human-readable title shown above the widget, e.g. "Monthly revenue by region".';
100804
+ var WIDGET_CODE_DESCRIPTION = "The HTML fragment to render: <style>, then markup (HTML or inline SVG), then <script>.";
100805
+
100806
+ // src/codex/codex-widget.ts
100807
+ var CODEX_WIDGET_TOOL = {
100808
+ name: WIDGET_TOOL_BASE_NAME,
100809
+ description: `${WIDGET_INSTRUCTIONS}
100810
+
100811
+ ${WIDGET_TOOL_DESCRIPTION}`,
100812
+ inputSchema: {
100813
+ type: "object",
100814
+ properties: {
100815
+ title: { type: "string", description: WIDGET_TITLE_DESCRIPTION },
100816
+ widget_code: { type: "string", description: WIDGET_CODE_DESCRIPTION }
100817
+ },
100818
+ required: ["title", "widget_code"]
100819
+ }
100820
+ };
100821
+ function servesCodexSession(sessionId) {
100822
+ if (!sessionId) return false;
100823
+ try {
100824
+ const row = getDb().prepare("SELECT runtime_type FROM sessions WHERE id = ?").get(sessionId);
100825
+ return row?.runtime_type === "codex";
100826
+ } catch {
100827
+ return false;
100828
+ }
100829
+ }
100830
+ function answerWidgetCall(args) {
100831
+ const code = args.widget_code;
100832
+ if (typeof code !== "string" || !code.trim()) return { ok: false, error: WIDGET_EMPTY_RESULT };
100833
+ return { ok: true, text: WIDGET_SHOWN_RESULT };
100834
+ }
100835
+
100700
100836
  // src/apps/mcp-tools.ts
100701
100837
  var TOOL_CALL_TIMEOUT_MS = Number(process.env.AGENT_PANE_TOOL_TIMEOUT_MS ?? 3e4);
100702
100838
  var TOOL_NS = "__";
@@ -100719,6 +100855,14 @@ function listAppTools() {
100719
100855
  }
100720
100856
  return tools;
100721
100857
  }
100858
+ function listGatewayTools(callerSessionId) {
100859
+ const tools = listAppTools();
100860
+ return servesCodexSession(callerSessionId) ? [CODEX_WIDGET_TOOL, ...tools] : tools;
100861
+ }
100862
+ function callPaneTool(toolName, args, callerSessionId) {
100863
+ if (toolName !== CODEX_WIDGET_TOOL.name || !servesCodexSession(callerSessionId)) return null;
100864
+ return answerWidgetCall(args);
100865
+ }
100722
100866
  function splitToolName(name) {
100723
100867
  const idx = name.indexOf(TOOL_NS);
100724
100868
  if (idx <= 0 || idx === name.length - TOOL_NS.length) return null;
@@ -100849,7 +100993,10 @@ async function registerAppRoutes(fastify, opts) {
100849
100993
  }
100850
100994
  });
100851
100995
  fastify.get("/api/apps/root", async () => ({ root: appsRoot() }));
100852
- fastify.get("/api/apps/mcp/tools", async () => listAppTools());
100996
+ fastify.get(
100997
+ "/api/apps/mcp/tools",
100998
+ async (request) => listGatewayTools(request.query.session)
100999
+ );
100853
101000
  fastify.get("/api/apps/examples", async () => {
100854
101001
  const exRoot = examplesRoot();
100855
101002
  if (!exRoot) return [];
@@ -100857,7 +101004,7 @@ async function registerAppRoutes(fastify, opts) {
100857
101004
  try {
100858
101005
  for (const entry of fs6.readdirSync(exRoot, { withFileTypes: true })) {
100859
101006
  if (!entry.isDirectory() || !APP_ID_RE.test(entry.name)) continue;
100860
- const manifest = readManifestIn(path9.join(exRoot, entry.name));
101007
+ const manifest = readManifestIn(path10.join(exRoot, entry.name));
100861
101008
  if (!manifest) continue;
100862
101009
  out.push({
100863
101010
  id: entry.name,
@@ -100878,7 +101025,7 @@ async function registerAppRoutes(fastify, opts) {
100878
101025
  if (!APP_ID_RE.test(id)) return reply.code(400).send({ error: "Invalid app id" });
100879
101026
  const exRoot = examplesRoot();
100880
101027
  if (!exRoot) return reply.code(404).send({ error: "Examples catalog not available" });
100881
- const src = path9.join(exRoot, id);
101028
+ const src = path10.join(exRoot, id);
100882
101029
  if (!readManifestIn(src)) return reply.code(404).send({ error: "Example not found" });
100883
101030
  if (readManifest(id)) return reply.code(409).send({ error: "App already installed" });
100884
101031
  ensureAppsRoot();
@@ -100917,7 +101064,7 @@ async function registerAppRoutes(fastify, opts) {
100917
101064
  fs6.mkdirSync(dir, { recursive: true });
100918
101065
  const cleanTitle2 = title.trim();
100919
101066
  fs6.writeFileSync(
100920
- path9.join(dir, "manifest.json"),
101067
+ path10.join(dir, "manifest.json"),
100921
101068
  JSON.stringify(
100922
101069
  {
100923
101070
  title: cleanTitle2,
@@ -100928,8 +101075,8 @@ async function registerAppRoutes(fastify, opts) {
100928
101075
  2
100929
101076
  )
100930
101077
  );
100931
- fs6.writeFileSync(path9.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
100932
- fs6.writeFileSync(path9.join(dir, "app.ts"), SKELETON_TS);
101078
+ fs6.writeFileSync(path10.join(dir, "index.html"), SKELETON_HTML.replaceAll("__TITLE__", cleanTitle2));
101079
+ fs6.writeFileSync(path10.join(dir, "app.ts"), SKELETON_TS);
100933
101080
  return { ok: true, id };
100934
101081
  }
100935
101082
  );
@@ -100966,9 +101113,9 @@ async function registerAppRoutes(fastify, opts) {
100966
101113
  const dir = appDir(id);
100967
101114
  fs6.mkdirSync(dir, { recursive: true });
100968
101115
  if (!Object.hasOwn(files ?? {}, "manifest.json")) {
100969
- fs6.writeFileSync(path9.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
101116
+ fs6.writeFileSync(path10.join(dir, "manifest.json"), JSON.stringify({ title: id }, null, 2));
100970
101117
  }
100971
- for (const [name, content] of entries) fs6.writeFileSync(path9.join(dir, name), content);
101118
+ for (const [name, content] of entries) fs6.writeFileSync(path10.join(dir, name), content);
100972
101119
  return { ok: true, id };
100973
101120
  }
100974
101121
  );
@@ -100990,6 +101137,8 @@ async function registerAppRoutes(fastify, opts) {
100990
101137
  },
100991
101138
  async (request, reply) => {
100992
101139
  const { tool: tool2, args, workspace, caller } = request.body || {};
101140
+ const own = callPaneTool(tool2, args ?? {}, caller?.sessionId);
101141
+ if (own) return own;
100993
101142
  try {
100994
101143
  const result = await callAppTool(tool2, args ?? {}, resolveToolWorkspace(workspace), caller?.sessionId);
100995
101144
  return { ok: true, result };
@@ -101283,7 +101432,7 @@ function buildSidecarPrompt(externalSessionId, transcriptPath, question) {
101283
101432
  }
101284
101433
 
101285
101434
  // src/routes/sidecar.ts
101286
- var SIDECAR_RUNTIMES = /* @__PURE__ */ new Set(["claude"]);
101435
+ var SIDECAR_RUNTIMES = /* @__PURE__ */ new Set(["claude", "codex"]);
101287
101436
  async function registerSidecarRoutes(fastify) {
101288
101437
  fastify.post(
101289
101438
  "/api/sessions/:sessionId/sidecar",
@@ -101898,7 +102047,7 @@ async function registerUsageRoutes(fastify) {
101898
102047
 
101899
102048
  // src/claude/session-import.ts
101900
102049
  import { readFile as readFile2, realpath } from "node:fs/promises";
101901
- import path10 from "node:path";
102050
+ import path11 from "node:path";
101902
102051
  import { getSessionInfo, listSessions } from "@anthropic-ai/claude-agent-sdk";
101903
102052
 
101904
102053
  // src/claude/widget-tool.ts
@@ -102670,10 +102819,10 @@ function mergeDefs(...defs) {
102670
102819
  function cloneDef(schema) {
102671
102820
  return mergeDefs(schema._zod.def);
102672
102821
  }
102673
- function getElementAtPath(obj2, path17) {
102674
- if (!path17)
102822
+ function getElementAtPath(obj2, path19) {
102823
+ if (!path19)
102675
102824
  return obj2;
102676
- return path17.reduce((acc, key) => acc?.[key], obj2);
102825
+ return path19.reduce((acc, key) => acc?.[key], obj2);
102677
102826
  }
102678
102827
  function promiseAllObject(promisesObj) {
102679
102828
  const keys = Object.keys(promisesObj);
@@ -103082,11 +103231,11 @@ function explicitlyAborted(x, startIndex = 0) {
103082
103231
  }
103083
103232
  return false;
103084
103233
  }
103085
- function prefixIssues(path17, issues) {
103234
+ function prefixIssues(path19, issues) {
103086
103235
  return issues.map((iss) => {
103087
103236
  var _a3;
103088
103237
  (_a3 = iss).path ?? (_a3.path = []);
103089
- iss.path.unshift(path17);
103238
+ iss.path.unshift(path19);
103090
103239
  return iss;
103091
103240
  });
103092
103241
  }
@@ -103233,16 +103382,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
103233
103382
  }
103234
103383
  function formatError(error51, mapper = (issue2) => issue2.message) {
103235
103384
  const fieldErrors = { _errors: [] };
103236
- const processError = (error52, path17 = []) => {
103385
+ const processError = (error52, path19 = []) => {
103237
103386
  for (const issue2 of error52.issues) {
103238
103387
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103239
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103388
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
103240
103389
  } else if (issue2.code === "invalid_key") {
103241
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103390
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103242
103391
  } else if (issue2.code === "invalid_element") {
103243
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103392
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103244
103393
  } else {
103245
- const fullpath = [...path17, ...issue2.path];
103394
+ const fullpath = [...path19, ...issue2.path];
103246
103395
  if (fullpath.length === 0) {
103247
103396
  fieldErrors._errors.push(mapper(issue2));
103248
103397
  } else {
@@ -103269,17 +103418,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
103269
103418
  }
103270
103419
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
103271
103420
  const result = { errors: [] };
103272
- const processError = (error52, path17 = []) => {
103421
+ const processError = (error52, path19 = []) => {
103273
103422
  var _a3, _b;
103274
103423
  for (const issue2 of error52.issues) {
103275
103424
  if (issue2.code === "invalid_union" && issue2.errors.length) {
103276
- issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
103425
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
103277
103426
  } else if (issue2.code === "invalid_key") {
103278
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103427
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103279
103428
  } else if (issue2.code === "invalid_element") {
103280
- processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
103429
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
103281
103430
  } else {
103282
- const fullpath = [...path17, ...issue2.path];
103431
+ const fullpath = [...path19, ...issue2.path];
103283
103432
  if (fullpath.length === 0) {
103284
103433
  result.errors.push(mapper(issue2));
103285
103434
  continue;
@@ -103311,8 +103460,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
103311
103460
  }
103312
103461
  function toDotPath(_path) {
103313
103462
  const segs = [];
103314
- const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103315
- for (const seg of path17) {
103463
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
103464
+ for (const seg of path19) {
103316
103465
  if (typeof seg === "number")
103317
103466
  segs.push(`[${seg}]`);
103318
103467
  else if (typeof seg === "symbol")
@@ -116004,13 +116153,13 @@ function resolveRef(ref, ctx) {
116004
116153
  if (!ref.startsWith("#")) {
116005
116154
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
116006
116155
  }
116007
- const path17 = ref.slice(1).split("/").filter(Boolean);
116008
- if (path17.length === 0) {
116156
+ const path19 = ref.slice(1).split("/").filter(Boolean);
116157
+ if (path19.length === 0) {
116009
116158
  return ctx.rootSchema;
116010
116159
  }
116011
116160
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
116012
- if (path17[0] === defsKey) {
116013
- const key = path17[1];
116161
+ if (path19[0] === defsKey) {
116162
+ const key = path19[1];
116014
116163
  if (!key || !ctx.defs[key]) {
116015
116164
  throw new Error(`Reference not found: ${ref}`);
116016
116165
  }
@@ -116420,28 +116569,7 @@ config2(en_default());
116420
116569
 
116421
116570
  // src/claude/widget-tool.ts
116422
116571
  var WIDGET_SERVER_NAME = "agentpane";
116423
- var WIDGET_TOOL_NAME = `mcp__${WIDGET_SERVER_NAME}__show_widget`;
116424
- var WIDGET_CDN_ORIGINS = [
116425
- "https://cdnjs.cloudflare.com",
116426
- "https://cdn.jsdelivr.net",
116427
- "https://unpkg.com",
116428
- "https://esm.sh"
116429
- ];
116430
- 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.";
116431
- var WIDGET_TOOL_DESCRIPTION = [
116432
- "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.",
116433
- "",
116434
- "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.",
116435
- "",
116436
- `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.`,
116437
- "",
116438
- "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.",
116439
- "",
116440
- '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).',
116441
- "",
116442
- "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."
116443
- ].join("\n");
116444
- var SHOWN_RESULT = "The widget is now shown to the user inline in the chat.";
116572
+ var WIDGET_TOOL_NAME = `mcp__${WIDGET_SERVER_NAME}__${WIDGET_TOOL_BASE_NAME}`;
116445
116573
  function createWidgetMcpServer() {
116446
116574
  return createSdkMcpServer({
116447
116575
  name: WIDGET_SERVER_NAME,
@@ -116450,17 +116578,17 @@ function createWidgetMcpServer() {
116450
116578
  alwaysLoad: true,
116451
116579
  tools: [
116452
116580
  tool(
116453
- "show_widget",
116581
+ WIDGET_TOOL_BASE_NAME,
116454
116582
  WIDGET_TOOL_DESCRIPTION,
116455
116583
  {
116456
- title: external_exports.string().describe('Short human-readable title shown above the widget, e.g. "Monthly revenue by region".'),
116457
- widget_code: external_exports.string().describe("The HTML fragment to render: <style>, then markup (HTML or inline SVG), then <script>.")
116584
+ title: external_exports.string().describe(WIDGET_TITLE_DESCRIPTION),
116585
+ widget_code: external_exports.string().describe(WIDGET_CODE_DESCRIPTION)
116458
116586
  },
116459
116587
  async ({ widget_code }) => {
116460
116588
  if (!widget_code.trim()) {
116461
- return { content: [{ type: "text", text: "widget_code is empty, so nothing was shown." }], isError: true };
116589
+ return { content: [{ type: "text", text: WIDGET_EMPTY_RESULT }], isError: true };
116462
116590
  }
116463
- return { content: [{ type: "text", text: SHOWN_RESULT }] };
116591
+ return { content: [{ type: "text", text: WIDGET_SHOWN_RESULT }] };
116464
116592
  }
116465
116593
  )
116466
116594
  ]
@@ -116556,9 +116684,9 @@ function mapToolUse(block) {
116556
116684
  };
116557
116685
  }
116558
116686
  function deriveFileChangeData(input, toolName) {
116559
- const path17 = input.file_path ?? input.notebook_path ?? "";
116687
+ const path19 = input.file_path ?? input.notebook_path ?? "";
116560
116688
  const kind = toolName === "Write" ? "add" : "modify";
116561
- return { changes: [{ path: path17, kind }], status: "in_progress" };
116689
+ return { changes: [{ path: path19, kind }], status: "in_progress" };
116562
116690
  }
116563
116691
  function extractToolResultText(content) {
116564
116692
  if (!content) return "";
@@ -116666,6 +116794,12 @@ function parseTranscript(text2) {
116666
116794
  link.origin = raw.origin ?? null;
116667
116795
  link.message = raw.message ?? null;
116668
116796
  link.toolUseResult = raw.toolUseResult;
116797
+ } else if (raw.type === "attachment") {
116798
+ const attachment = raw.attachment;
116799
+ if (attachment?.type === "queued_command" && attachment.origin?.kind === "peer") {
116800
+ link.origin = attachment.origin;
116801
+ link.queuedPrompt = typeof attachment.prompt === "string" ? attachment.prompt : "";
116802
+ }
116669
116803
  }
116670
116804
  entries.push(link);
116671
116805
  }
@@ -116739,6 +116873,21 @@ function classifyUserInput(entry) {
116739
116873
  const imageNote = images > 0 && !trimmed.includes("[Image") ? Array(images).fill("[Image]").join(" ") : "";
116740
116874
  return { kind: "prompt", text: [trimmed, imageNote].filter(Boolean).join("\n") };
116741
116875
  }
116876
+ function hasToolResult(content) {
116877
+ return Array.isArray(content) && content.some((b) => b?.type === "tool_result");
116878
+ }
116879
+ var PEER_ENVELOPE = /<cross-session-message\b[^>]*>([\s\S]*?)<\/cross-session-message>/;
116880
+ function peerMessageData(origin, content) {
116881
+ let body = typeof origin.body === "string" ? origin.body.trim() : "";
116882
+ if (!body) {
116883
+ const text2 = typeof content === "string" ? content : Array.isArray(content) ? content.map(
116884
+ (b) => b && typeof b === "object" && b.type === "text" ? String(b.text ?? "") : ""
116885
+ ).join("\n") : "";
116886
+ const enveloped = PEER_ENVELOPE.exec(text2);
116887
+ body = (enveloped ? enveloped[1] : text2).trim();
116888
+ }
116889
+ return { name: origin.name?.trim() || null, from: origin.from ?? null, body };
116890
+ }
116742
116891
  function syntheticText(content) {
116743
116892
  if (typeof content === "string") return content;
116744
116893
  if (!Array.isArray(content)) return "";
@@ -116759,6 +116908,8 @@ function buildTurns(chain) {
116759
116908
  const at = stamp(entry);
116760
116909
  const turn = {
116761
116910
  userPrompt: prompt,
116911
+ origin: null,
116912
+ originName: null,
116762
116913
  status: "completed",
116763
116914
  agentResponse: null,
116764
116915
  thoughts: null,
@@ -116791,7 +116942,25 @@ function buildTurns(chain) {
116791
116942
  }
116792
116943
  continue;
116793
116944
  }
116945
+ if (entry.type === "attachment") {
116946
+ if (entry.origin?.kind === "peer" && current) {
116947
+ addItem(current, entry, {
116948
+ type: "peer_message",
116949
+ externalId: `peer-${entry.uuid}`,
116950
+ data: peerMessageData(entry.origin, entry.queuedPrompt ?? ""),
116951
+ status: "completed"
116952
+ });
116953
+ }
116954
+ continue;
116955
+ }
116794
116956
  if (entry.type === "user") {
116957
+ if (entry.origin?.kind === "peer" && !hasToolResult(entry.message?.content)) {
116958
+ const data = peerMessageData(entry.origin, entry.message?.content);
116959
+ current = openTurn(data.body, entry);
116960
+ current.origin = "peer";
116961
+ current.originName = data.name;
116962
+ continue;
116963
+ }
116795
116964
  if (entry.isMeta || entry.isCompactSummary) continue;
116796
116965
  const content = entry.message?.content;
116797
116966
  if (Array.isArray(content) && content.some((b) => b?.type === "tool_result")) {
@@ -116923,7 +117092,7 @@ async function realDir(dir) {
116923
117092
  }
116924
117093
  }
116925
117094
  async function sameDir(a, realB) {
116926
- const realA = await realDir(a) ?? path10.resolve(a);
117095
+ const realA = await realDir(a) ?? path11.resolve(a);
116927
117096
  return realA === realB;
116928
117097
  }
116929
117098
  function knownClaudeSessionIds(db2) {
@@ -117004,8 +117173,8 @@ async function importClaudeSession(db2, claudeSessionId, workspacePath) {
117004
117173
  );
117005
117174
  const insertTurn = db2.prepare(
117006
117175
  `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status,
117007
- error, created_at, updated_at)
117008
- VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, ?)`
117176
+ error, origin, origin_name, created_at, updated_at)
117177
+ VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, ?, ?, ?)`
117009
117178
  );
117010
117179
  const insertItem2 = db2.prepare(
117011
117180
  `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
@@ -117035,6 +117204,8 @@ async function importClaudeSession(db2, claudeSessionId, workspacePath) {
117035
117204
  turn.thoughts,
117036
117205
  turn.externalTurnId,
117037
117206
  turn.status,
117207
+ turn.origin ?? null,
117208
+ turn.originName ?? null,
117038
117209
  turn.createdAt,
117039
117210
  turn.updatedAt
117040
117211
  );
@@ -117089,9 +117260,523 @@ async function registerClaudeSessionRoutes(fastify) {
117089
117260
  );
117090
117261
  }
117091
117262
 
117092
- // src/session-host/flags.ts
117263
+ // src/codex/session-import.ts
117264
+ import { realpath as realpath2 } from "node:fs/promises";
117265
+ import path13 from "node:path";
117266
+
117267
+ // src/apps/register-mcp.ts
117093
117268
  import fs7 from "node:fs";
117094
- import path11 from "node:path";
117269
+ import path12 from "node:path";
117270
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
117271
+ var MCP_SERVER_NAME = "agentpane-miniapps";
117272
+ function panePublicUrl() {
117273
+ return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
117274
+ }
117275
+ function stdioScriptPath() {
117276
+ const here = path12.dirname(fileURLToPath2(import.meta.url));
117277
+ const candidates = [
117278
+ path12.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
117279
+ // src/apps/ → backend/scripts
117280
+ path12.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
117281
+ // dist bundle → backend/scripts
117282
+ ];
117283
+ for (const candidate of candidates) {
117284
+ if (fs7.existsSync(candidate)) return candidate;
117285
+ }
117286
+ return null;
117287
+ }
117288
+ var registered = /* @__PURE__ */ new Set();
117289
+ async function registerMiniAppMcp(baseUrl, workspace = "") {
117290
+ const key = `${baseUrl}|${workspace}`;
117291
+ if (registered.has(key)) return true;
117292
+ const script = stdioScriptPath();
117293
+ if (!script) {
117294
+ console.warn("[miniapp-mcp] stdio proxy script not found \u2014 registration skipped");
117295
+ return false;
117296
+ }
117297
+ if (!anyAppHasTools()) {
117298
+ return false;
117299
+ }
117300
+ const base = baseUrl.replace(/\/+$/, "");
117301
+ try {
117302
+ try {
117303
+ const res2 = await fetch(`${base}/mcp/servers`, { signal: AbortSignal.timeout(5e3) });
117304
+ if (res2.ok) {
117305
+ const servers = await res2.json();
117306
+ const names = servers.map((s) => s.server_name ?? s.name);
117307
+ if (names.includes(MCP_SERVER_NAME)) {
117308
+ await fetch(`${base}/mcp/configs/${MCP_SERVER_NAME}`, {
117309
+ method: "DELETE",
117310
+ signal: AbortSignal.timeout(5e3)
117311
+ }).catch(() => {
117312
+ });
117313
+ }
117314
+ }
117315
+ } catch {
117316
+ }
117317
+ const body = {
117318
+ configJson: JSON.stringify({
117319
+ [MCP_SERVER_NAME]: {
117320
+ command: process.execPath,
117321
+ args: [script, panePublicUrl(), workspace],
117322
+ env: { AGENT_PANE_SESSION_ID: "" }
117323
+ }
117324
+ })
117325
+ };
117326
+ const res = await fetch(`${base}/mcp/configs`, {
117327
+ method: "POST",
117328
+ headers: { "Content-Type": "application/json" },
117329
+ body: JSON.stringify(body),
117330
+ signal: AbortSignal.timeout(1e4)
117331
+ });
117332
+ if (res.status === 201) {
117333
+ console.log(`[miniapp-mcp] gateway registered in workspace backend ${base} (workspace: ${workspace || "global"})`);
117334
+ registered.add(key);
117335
+ return true;
117336
+ }
117337
+ const text2 = await res.text();
117338
+ if (res.status === 400 && /already exists/i.test(text2)) {
117339
+ registered.add(key);
117340
+ return true;
117341
+ }
117342
+ console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
117343
+ return false;
117344
+ } catch (err) {
117345
+ console.warn(`[miniapp-mcp] registration error: ${err.message}`);
117346
+ return false;
117347
+ }
117348
+ }
117349
+ function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
117350
+ const script = stdioScriptPath();
117351
+ if (!script) return null;
117352
+ return [
117353
+ // MCP tool calls must not ask for elicitation approval — nobody is
117354
+ // watching an agent-driven session to approve (feature is stable/on).
117355
+ "-c",
117356
+ "features.tool_call_mcp_elicitation=false",
117357
+ "-c",
117358
+ `mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
117359
+ "-c",
117360
+ `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
117361
+ ];
117362
+ }
117363
+
117364
+ // src/codex/item-mapper.ts
117365
+ function paneStatus(status) {
117366
+ switch (status) {
117367
+ case "inProgress":
117368
+ case "in_progress":
117369
+ return "in_progress";
117370
+ case "completed":
117371
+ return "completed";
117372
+ case "failed":
117373
+ case "declined":
117374
+ return "failed";
117375
+ default:
117376
+ return void 0;
117377
+ }
117378
+ }
117379
+ function errorText(error51) {
117380
+ if (!error51) return null;
117381
+ if (typeof error51 === "string") return error51;
117382
+ const message = error51.message;
117383
+ return typeof message === "string" ? message : JSON.stringify(error51);
117384
+ }
117385
+ function resultText(result) {
117386
+ const content = result?.content;
117387
+ if (!Array.isArray(content)) return "";
117388
+ return content.map((part) => typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
117389
+ }
117390
+ function isWidgetCall(item) {
117391
+ return item.type === "mcpToolCall" && item.server === MCP_SERVER_NAME && item.tool === WIDGET_TOOL_BASE_NAME;
117392
+ }
117393
+ var ITEM_TYPES = {
117394
+ agentMessage: "agent_message",
117395
+ userMessage: "user_message",
117396
+ agentReasoning: "reasoning",
117397
+ commandExecution: "command_execution",
117398
+ fileChange: "file_change",
117399
+ mcpToolCall: "mcp_tool_call",
117400
+ webSearch: "web_search",
117401
+ todoList: "todo_list",
117402
+ contextCompaction: "context_compaction",
117403
+ error: "error"
117404
+ };
117405
+ function mapItemType(item) {
117406
+ if (isWidgetCall(item)) return "widget";
117407
+ return ITEM_TYPES[item.type] ?? item.type;
117408
+ }
117409
+ function mapItemData(item) {
117410
+ switch (item.type) {
117411
+ case "agentMessage":
117412
+ case "agent_message":
117413
+ return { text: item.text };
117414
+ case "reasoning":
117415
+ case "agentReasoning": {
117416
+ const summary = Array.isArray(item.summary) ? item.summary.join("\n") : "";
117417
+ return { text: summary || item.text || "" };
117418
+ }
117419
+ case "commandExecution":
117420
+ case "command_execution":
117421
+ return {
117422
+ command: item.command,
117423
+ aggregated_output: item.aggregatedOutput ?? item.aggregated_output,
117424
+ exit_code: item.exitCode ?? item.exit_code ?? null,
117425
+ status: paneStatus(item.status)
117426
+ };
117427
+ case "fileChange":
117428
+ case "file_change":
117429
+ return {
117430
+ changes: item.changes,
117431
+ status: paneStatus(item.status)
117432
+ };
117433
+ case "mcpToolCall":
117434
+ case "mcp_tool_call":
117435
+ if (isWidgetCall(item)) {
117436
+ const args = item.arguments ?? {};
117437
+ const failed = paneStatus(item.status) === "failed";
117438
+ return {
117439
+ title: typeof args.title === "string" ? args.title : "",
117440
+ html: typeof args.widget_code === "string" ? args.widget_code : "",
117441
+ error: failed ? errorText(item.error) || resultText(item.result) || "Tool error" : null
117442
+ };
117443
+ }
117444
+ return {
117445
+ server: item.server,
117446
+ tool: item.tool,
117447
+ arguments: item.arguments,
117448
+ result: item.result ?? null,
117449
+ error: errorText(item.error),
117450
+ status: paneStatus(item.status)
117451
+ };
117452
+ case "webSearch":
117453
+ case "web_search":
117454
+ return { query: item.query };
117455
+ case "todoList":
117456
+ case "todo_list":
117457
+ return { items: item.items };
117458
+ case "contextCompaction":
117459
+ return { trigger: "auto", pre_tokens: null, post_tokens: null };
117460
+ case "error":
117461
+ return { message: item.message };
117462
+ default:
117463
+ return {};
117464
+ }
117465
+ }
117466
+ function getItemStatus(item) {
117467
+ if (item.type === "commandExecution" || item.type === "command_execution" || item.type === "fileChange" || item.type === "file_change" || item.type === "mcpToolCall" || item.type === "mcp_tool_call") {
117468
+ return paneStatus(item.status) ?? "completed";
117469
+ }
117470
+ if (item.type === "error") {
117471
+ return "failed";
117472
+ }
117473
+ return "completed";
117474
+ }
117475
+
117476
+ // src/codex/known-threads.ts
117477
+ var PANE_THREAD_SOURCE = "agentpane";
117478
+ function recordCodexThread(threadId, sessionId) {
117479
+ try {
117480
+ getDb().prepare("INSERT OR IGNORE INTO codex_threads (thread_id, session_id, created_at) VALUES (?, ?, ?)").run(threadId, sessionId, (/* @__PURE__ */ new Date()).toISOString());
117481
+ } catch {
117482
+ }
117483
+ }
117484
+ function knownCodexThreadIds(db2) {
117485
+ const rows = db2.prepare(
117486
+ `SELECT external_thread_id AS id FROM sessions WHERE external_thread_id IS NOT NULL
117487
+ UNION SELECT pre_rewind_thread_id FROM sessions WHERE pre_rewind_thread_id IS NOT NULL
117488
+ UNION SELECT import_source_id FROM sessions WHERE import_source_id IS NOT NULL
117489
+ UNION SELECT external_thread_id FROM discussion_threads WHERE external_thread_id IS NOT NULL
117490
+ UNION SELECT thread_id FROM codex_threads`
117491
+ ).all();
117492
+ return new Set(rows.map((row) => row.id));
117493
+ }
117494
+
117495
+ // src/codex/review-turns.ts
117496
+ function isReview(turn) {
117497
+ return (turn.items ?? []).some((item) => item.type === "enteredReviewMode");
117498
+ }
117499
+ function isInsideReview(review, turn) {
117500
+ return isReview(review) && review.completedAt != null && turn.startedAt != null && turn.startedAt < review.completedAt;
117501
+ }
117502
+ function forkThroughReview(turns, turnId) {
117503
+ const index = turns.findIndex((turn) => turn.id === turnId);
117504
+ if (index < 0 || !isReview(turns[index])) return void 0;
117505
+ let next = index + 1;
117506
+ while (next < turns.length && isInsideReview(turns[index], turns[next])) next++;
117507
+ if (next < turns.length - 1 && isInsideReview(turns[next], turns[next + 1])) next++;
117508
+ return next < turns.length ? { beforeTurnId: turns[next].id } : {};
117509
+ }
117510
+
117511
+ // src/codex/session-import.ts
117512
+ var CodexImportError = class extends Error {
117513
+ status;
117514
+ paneSessionId;
117515
+ constructor(status, message, paneSessionId = null) {
117516
+ super(message);
117517
+ this.name = "CodexImportError";
117518
+ this.status = status;
117519
+ this.paneSessionId = paneSessionId;
117520
+ }
117521
+ };
117522
+ var RECENT_MS2 = 10 * 6e4;
117523
+ var THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
117524
+ var TITLE_MAX2 = 100;
117525
+ var LIST_PAGE = 100;
117526
+ var LIST_MAX = 1e3;
117527
+ var USER_SOURCES = ["cli", "vscode", "exec", "appServer", "unknown"];
117528
+ var THROWAWAY_PROMPTS = ["Generate a concise 3-5 word title", "You are summarizing a side discussion thread"];
117529
+ async function realDir2(dir) {
117530
+ try {
117531
+ return await realpath2(dir);
117532
+ } catch {
117533
+ return null;
117534
+ }
117535
+ }
117536
+ async function workspaceDirs(workspacePath) {
117537
+ const real = await realDir2(workspacePath);
117538
+ if (!real) return null;
117539
+ const given = path13.resolve(workspacePath);
117540
+ return given === real ? [real] : [given, real];
117541
+ }
117542
+ function titleOf2(thread) {
117543
+ const raw = (thread.name || thread.preview || "").trim();
117544
+ const firstLine = raw.split("\n")[0].trim();
117545
+ return firstLine.length > TITLE_MAX2 ? `${firstLine.slice(0, TITLE_MAX2 - 1)}\u2026` : firstLine;
117546
+ }
117547
+ function isThrowaway(thread) {
117548
+ const preview = (thread.preview ?? "").trimStart();
117549
+ return THROWAWAY_PROMPTS.some((prompt) => preview.startsWith(prompt));
117550
+ }
117551
+ function paneSessionHolding2(db2, threadId) {
117552
+ const row = db2.prepare(
117553
+ `SELECT id FROM sessions WHERE import_source_id = ? OR external_thread_id = ? OR pre_rewind_thread_id = ?
117554
+ UNION ALL SELECT session_id FROM discussion_threads WHERE external_thread_id = ?
117555
+ UNION ALL SELECT session_id FROM codex_threads WHERE thread_id = ?
117556
+ LIMIT 1`
117557
+ ).get(threadId, threadId, threadId, threadId, threadId);
117558
+ return row ? { sessionId: row.id } : null;
117559
+ }
117560
+ async function listImportableCodexSessions(db2, workspacePath, now = Date.now()) {
117561
+ const dirs = await workspaceDirs(workspacePath);
117562
+ if (!dirs) return [];
117563
+ const known = knownCodexThreadIds(db2);
117564
+ const client = getSharedAppServer();
117565
+ const sessions = [];
117566
+ let cursor = null;
117567
+ let seen = 0;
117568
+ do {
117569
+ const page = await client.request("thread/list", {
117570
+ cwd: dirs,
117571
+ limit: LIST_PAGE,
117572
+ cursor,
117573
+ sortKey: "updated_at",
117574
+ sourceKinds: USER_SOURCES
117575
+ });
117576
+ for (const thread of page.data ?? []) {
117577
+ seen += 1;
117578
+ if (known.has(thread.id) || thread.parentThreadId || thread.ephemeral || isThrowaway(thread)) continue;
117579
+ const title = titleOf2(thread);
117580
+ if (!title) continue;
117581
+ const updatedMs = thread.updatedAt * 1e3;
117582
+ sessions.push({
117583
+ session_id: thread.id,
117584
+ title,
117585
+ cwd: thread.cwd,
117586
+ git_branch: thread.gitInfo?.branch ?? null,
117587
+ created_at: new Date(thread.createdAt * 1e3).toISOString(),
117588
+ last_modified: new Date(updatedMs).toISOString(),
117589
+ recently_active: now - updatedMs < RECENT_MS2
117590
+ });
117591
+ }
117592
+ cursor = page.nextCursor;
117593
+ } while (cursor && seen < LIST_MAX);
117594
+ return sessions.sort((a, b) => a.last_modified < b.last_modified ? 1 : -1);
117595
+ }
117596
+ var TURN_STATUS = {
117597
+ completed: "completed",
117598
+ failed: "failed",
117599
+ interrupted: "aborted",
117600
+ inProgress: "aborted"
117601
+ };
117602
+ function userText(item) {
117603
+ const content = Array.isArray(item.content) ? item.content : [];
117604
+ return content.map((part) => {
117605
+ if (part.type === "text" && typeof part.text === "string") return part.text;
117606
+ if (part.type === "image") return "[image]";
117607
+ if (part.type === "localImage" && typeof part.path === "string") return `[image: ${part.path}]`;
117608
+ return "";
117609
+ }).filter(Boolean).join("\n");
117610
+ }
117611
+ function skipped(item, data) {
117612
+ if (item.type === "userMessage" || item.type === "enteredReviewMode" || item.type === "exitedReviewMode") return true;
117613
+ return (item.type === "reasoning" || item.type === "agentReasoning") && !data.text;
117614
+ }
117615
+ function threadToTurns(thread) {
117616
+ const turns = [];
117617
+ const stored = thread.turns ?? [];
117618
+ let last = thread.createdAt * 1e3 - 1;
117619
+ for (const [position, turn] of stored.entries()) {
117620
+ if (position > 0 && isInsideReview(stored[position - 1], turn)) continue;
117621
+ const items = turn.items ?? [];
117622
+ const prompt = items.filter((item) => item.type === "userMessage").map(userText).filter(Boolean).join("\n\n");
117623
+ const command = items.some((item) => item.type === "enteredReviewMode") ? "/review" : items.some((item) => item.type === "contextCompaction") ? "/compact" : "";
117624
+ const output = [];
117625
+ let agentResponse = null;
117626
+ let review = null;
117627
+ let thoughts = null;
117628
+ const started = Math.max(last + 1, (turn.startedAt ?? 0) * 1e3);
117629
+ for (const [index, item] of items.entries()) {
117630
+ if (item.type === "exitedReviewMode" && typeof item.review === "string" && item.review.trim())
117631
+ review = item.review;
117632
+ const data = mapItemData(item);
117633
+ if (skipped(item, data)) continue;
117634
+ if (item.type === "agentMessage" || item.type === "agent_message") agentResponse = item.text ?? agentResponse;
117635
+ if ((item.type === "reasoning" || item.type === "agentReasoning") && typeof data.text === "string") {
117636
+ thoughts = data.text;
117637
+ }
117638
+ const status = getItemStatus(item);
117639
+ output.push({
117640
+ externalId: item.id,
117641
+ type: mapItemType(item),
117642
+ data,
117643
+ // Left open when its turn ended: it never finished.
117644
+ status: status === "in_progress" ? "failed" : status,
117645
+ createdAt: new Date(started + index).toISOString()
117646
+ });
117647
+ }
117648
+ const userPrompt = prompt || command;
117649
+ if (!userPrompt && output.length === 0) continue;
117650
+ const ended = Math.max(started, (turn.completedAt ?? 0) * 1e3);
117651
+ turns.push({
117652
+ userPrompt,
117653
+ agentResponse: agentResponse ?? review,
117654
+ thoughts,
117655
+ externalTurnId: turn.id,
117656
+ status: TURN_STATUS[turn.status] ?? "completed",
117657
+ error: turn.status === "failed" ? turn.error?.message ?? "Codex turn failed" : null,
117658
+ createdAt: new Date(started).toISOString(),
117659
+ updatedAt: new Date(ended).toISOString(),
117660
+ items: output
117661
+ });
117662
+ last = started;
117663
+ }
117664
+ return turns;
117665
+ }
117666
+ async function importCodexSession(db2, threadId, workspacePath) {
117667
+ if (!THREAD_ID.test(threadId)) throw new CodexImportError(400, "Not a Codex thread id");
117668
+ const holder = paneSessionHolding2(db2, threadId);
117669
+ if (holder) throw new CodexImportError(409, "This thread is already in the pane", holder.sessionId);
117670
+ let thread;
117671
+ try {
117672
+ ({ thread } = await getSharedAppServer().request("thread/read", {
117673
+ threadId,
117674
+ includeTurns: true
117675
+ }));
117676
+ } catch (err) {
117677
+ throw new CodexImportError(404, `Codex thread not found: ${err.message}`);
117678
+ }
117679
+ const turns = threadToTurns(thread);
117680
+ if (turns.length === 0) throw new CodexImportError(422, "This thread has no conversation to import");
117681
+ const dirs = workspacePath ? await workspaceDirs(workspacePath) : null;
117682
+ const cwd = workspacePath && dirs?.includes(thread.cwd) ? workspacePath : thread.cwd;
117683
+ const sessionId = v4_default();
117684
+ const insertSession = db2.prepare(
117685
+ `INSERT INTO sessions (id, title, runtime_type, model, model_reasoning_effort, cwd, external_thread_id, status,
117686
+ is_running, lifecycle, sort_order, user_touched, import_source_id, created_at, updated_at)
117687
+ VALUES (?, ?, 'codex', NULL, NULL, ?, ?, 'active', 0, 'working', ?, 1, ?, ?, ?)`
117688
+ );
117689
+ const insertTurn = db2.prepare(
117690
+ `INSERT INTO turns (id, session_id, user_prompt, agent_response, thoughts, token_usage, external_turn_id, status,
117691
+ error, created_at, updated_at)
117692
+ VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)`
117693
+ );
117694
+ const insertItem2 = db2.prepare(
117695
+ `INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at)
117696
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
117697
+ );
117698
+ db2.transaction(() => {
117699
+ const raced = paneSessionHolding2(db2, threadId);
117700
+ if (raced) throw new CodexImportError(409, "This thread is already in the pane", raced.sessionId);
117701
+ const { m } = db2.prepare("SELECT COALESCE(MAX(sort_order), 0) AS m FROM sessions WHERE cwd = ?").get(cwd);
117702
+ insertSession.run(
117703
+ sessionId,
117704
+ titleOf2(thread) || null,
117705
+ cwd,
117706
+ threadId,
117707
+ m + 1,
117708
+ threadId,
117709
+ turns[0].createdAt,
117710
+ turns[turns.length - 1].updatedAt
117711
+ );
117712
+ for (const turn of turns) {
117713
+ const turnId = v4_default();
117714
+ insertTurn.run(
117715
+ turnId,
117716
+ sessionId,
117717
+ turn.userPrompt,
117718
+ turn.agentResponse,
117719
+ turn.thoughts,
117720
+ turn.externalTurnId,
117721
+ turn.status,
117722
+ turn.error,
117723
+ turn.createdAt,
117724
+ turn.updatedAt
117725
+ );
117726
+ for (const item of turn.items) {
117727
+ insertItem2.run(
117728
+ v4_default(),
117729
+ turnId,
117730
+ item.externalId,
117731
+ item.type,
117732
+ JSON.stringify(trimItemData(item.data)),
117733
+ item.status,
117734
+ item.createdAt,
117735
+ item.createdAt
117736
+ );
117737
+ }
117738
+ }
117739
+ })();
117740
+ return db2.prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
117741
+ }
117742
+
117743
+ // src/routes/codex-sessions.ts
117744
+ async function registerCodexSessionRoutes(fastify) {
117745
+ fastify.get("/api/codex-sessions", async (request, reply) => {
117746
+ const workspace = request.query.workspace?.trim();
117747
+ if (!workspace) return reply.code(400).send({ error: "workspace is required" });
117748
+ try {
117749
+ return { sessions: await listImportableCodexSessions(getDb(), workspace) };
117750
+ } catch (err) {
117751
+ return reply.code(500).send({ error: `Could not list Codex sessions: ${err.message}` });
117752
+ }
117753
+ });
117754
+ fastify.post(
117755
+ "/api/codex-sessions/:id/import",
117756
+ {
117757
+ schema: {
117758
+ body: {
117759
+ type: ["object", "null"],
117760
+ properties: { workspace: { type: ["string", "null"] } }
117761
+ }
117762
+ }
117763
+ },
117764
+ async (request, reply) => {
117765
+ try {
117766
+ return await importCodexSession(getDb(), request.params.id, request.body?.workspace?.trim() || null);
117767
+ } catch (err) {
117768
+ if (err instanceof CodexImportError) {
117769
+ return reply.code(err.status).send({ error: err.message, session_id: err.paneSessionId });
117770
+ }
117771
+ return reply.code(500).send({ error: `Import failed: ${err.message}` });
117772
+ }
117773
+ }
117774
+ );
117775
+ }
117776
+
117777
+ // src/session-host/flags.ts
117778
+ import fs8 from "node:fs";
117779
+ import path14 from "node:path";
117095
117780
  var DEFAULT_FLAGS = {
117096
117781
  claude: true,
117097
117782
  codex: true,
@@ -117110,18 +117795,18 @@ function setPaneDataDir(dir) {
117110
117795
  }
117111
117796
  function sessionHostsRoot() {
117112
117797
  const override = process.env.AGENT_PANE_SESSION_HOSTS_DIR;
117113
- if (override) return path11.resolve(override);
117114
- return paneDataDir ? path11.join(paneDataDir, "session-hosts") : null;
117798
+ if (override) return path14.resolve(override);
117799
+ return paneDataDir ? path14.join(paneDataDir, "session-hosts") : null;
117115
117800
  }
117116
117801
  function flagsFilePath() {
117117
117802
  const root = sessionHostsRoot();
117118
- if (process.env.AGENT_PANE_SESSION_HOSTS_DIR) return path11.join(path11.dirname(root), "session-hosts.json");
117119
- return paneDataDir ? path11.join(paneDataDir, "session-hosts.json") : null;
117803
+ if (process.env.AGENT_PANE_SESSION_HOSTS_DIR) return path14.join(path14.dirname(root), "session-hosts.json");
117804
+ return paneDataDir ? path14.join(paneDataDir, "session-hosts.json") : null;
117120
117805
  }
117121
117806
  function readFlagFile(file2) {
117122
117807
  if (!file2) return {};
117123
117808
  try {
117124
- const parsed = JSON.parse(fs7.readFileSync(file2, "utf8"));
117809
+ const parsed = JSON.parse(fs8.readFileSync(file2, "utf8"));
117125
117810
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
117126
117811
  console.warn(`[session-host] ${file2} is not a JSON object; using the defaults`);
117127
117812
  } catch (err) {
@@ -117187,17 +117872,17 @@ var LOG_HEADER_LEN = LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS + 1;
117187
117872
 
117188
117873
  // src/session-host/registry.ts
117189
117874
  import { randomBytes, randomUUID as randomUUID2 } from "node:crypto";
117190
- import fs9 from "node:fs";
117191
- import path13 from "node:path";
117192
- import { fileURLToPath as fileURLToPath3 } from "node:url";
117875
+ import fs10 from "node:fs";
117876
+ import path16 from "node:path";
117877
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
117193
117878
 
117194
117879
  // src/session-host/client.ts
117195
117880
  import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
117196
117881
  import { EventEmitter as EventEmitter2 } from "node:events";
117197
- import fs8 from "node:fs";
117882
+ import fs9 from "node:fs";
117198
117883
  import net2 from "node:net";
117199
- import path12 from "node:path";
117200
- import { fileURLToPath as fileURLToPath2 } from "node:url";
117884
+ import path15 from "node:path";
117885
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
117201
117886
  var HostRequestError = class extends Error {
117202
117887
  reply;
117203
117888
  constructor(reply) {
@@ -117208,36 +117893,36 @@ var HostRequestError = class extends Error {
117208
117893
  function hostScriptPath() {
117209
117894
  const override = process.env.AGENT_PANE_SESSION_HOST_SCRIPT;
117210
117895
  if (override) return override;
117211
- const here = path12.dirname(fileURLToPath2(import.meta.url));
117896
+ const here = path15.dirname(fileURLToPath3(import.meta.url));
117212
117897
  const candidates = [
117213
- path12.resolve(here, "../../scripts/session-host.mjs"),
117898
+ path15.resolve(here, "../../scripts/session-host.mjs"),
117214
117899
  // src/session-host/ → backend/scripts
117215
- path12.resolve(here, "../scripts/session-host.mjs")
117900
+ path15.resolve(here, "../scripts/session-host.mjs")
117216
117901
  // dist bundle → backend/scripts
117217
117902
  ];
117218
117903
  for (const candidate of candidates) {
117219
- if (fs8.existsSync(candidate)) return candidate;
117904
+ if (fs9.existsSync(candidate)) return candidate;
117220
117905
  }
117221
117906
  return null;
117222
117907
  }
117223
117908
  function hostSocketPath(dir) {
117224
- const direct = path12.join(dir, "sock");
117909
+ const direct = path15.join(dir, "sock");
117225
117910
  if (Buffer.byteLength(direct) < 100) return direct;
117226
117911
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
117227
- return path12.join("/tmp", `rbsh-${uid}`, path12.basename(dir), "sock");
117912
+ return path15.join("/tmp", `rbsh-${uid}`, path15.basename(dir), "sock");
117228
117913
  }
117229
117914
  function readJson(file2) {
117230
117915
  try {
117231
- return JSON.parse(fs8.readFileSync(file2, "utf8"));
117916
+ return JSON.parse(fs9.readFileSync(file2, "utf8"));
117232
117917
  } catch {
117233
117918
  return null;
117234
117919
  }
117235
117920
  }
117236
117921
  function readHostExit(dir) {
117237
- return readJson(path12.join(dir, "exit.json"));
117922
+ return readJson(path15.join(dir, "exit.json"));
117238
117923
  }
117239
117924
  function readHostChild(dir) {
117240
- return readJson(path12.join(dir, "child.json"));
117925
+ return readJson(path15.join(dir, "child.json"));
117241
117926
  }
117242
117927
  function isPidAlive(pid) {
117243
117928
  if (!pid || pid <= 0) return false;
@@ -117392,8 +118077,8 @@ function attachHost(dir, after, timeoutMs = 5e3) {
117392
118077
  function startHost(opts) {
117393
118078
  const script = hostScriptPath();
117394
118079
  if (!script) throw new Error("session host script not found");
117395
- fs8.mkdirSync(opts.dir, { recursive: true, mode: 448 });
117396
- fs8.chmodSync(opts.dir, 448);
118080
+ fs9.mkdirSync(opts.dir, { recursive: true, mode: 448 });
118081
+ fs9.chmodSync(opts.dir, 448);
117397
118082
  const env = {};
117398
118083
  for (const [k, v] of Object.entries(opts.env)) if (v !== void 0) env[k] = v;
117399
118084
  const child = spawn4(opts.nodePath ?? process.execPath, [script, opts.dir, JSON.stringify(opts.config), opts.command, ...opts.args], {
@@ -117427,9 +118112,9 @@ async function waitForHost(dir, timeoutMs = 1e4) {
117427
118112
  function readLogOldest(dir) {
117428
118113
  let fd = null;
117429
118114
  try {
117430
- fd = fs8.openSync(path12.join(dir, "out.log"), "r");
118115
+ fd = fs9.openSync(path15.join(dir, "out.log"), "r");
117431
118116
  const buf = Buffer.alloc(LOG_HEADER_LEN);
117432
- const n = fs8.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
118117
+ const n = fs9.readSync(fd, buf, 0, LOG_HEADER_LEN, 0);
117433
118118
  const text2 = buf.subarray(0, n).toString("utf8");
117434
118119
  if (n < LOG_HEADER_LEN || !text2.startsWith(LOG_HEADER_PREFIX) || text2[LOG_HEADER_LEN - 1] !== "\n") return null;
117435
118120
  const digits = text2.slice(LOG_HEADER_PREFIX.length, LOG_HEADER_PREFIX.length + LOG_HEADER_DIGITS);
@@ -117437,14 +118122,14 @@ function readLogOldest(dir) {
117437
118122
  } catch {
117438
118123
  return null;
117439
118124
  } finally {
117440
- if (fd !== null) fs8.closeSync(fd);
118125
+ if (fd !== null) fs9.closeSync(fd);
117441
118126
  }
117442
118127
  }
117443
118128
  function readHostLog(dir, after) {
117444
118129
  const oldest = readLogOldest(dir);
117445
118130
  if (oldest === null || after < oldest) return null;
117446
118131
  try {
117447
- const all = fs8.readFileSync(path12.join(dir, "out.log"));
118132
+ const all = fs9.readFileSync(path15.join(dir, "out.log"));
117448
118133
  const start = LOG_HEADER_LEN + (after - oldest);
117449
118134
  if (start > all.length) return null;
117450
118135
  return all.subarray(start);
@@ -117454,14 +118139,14 @@ function readHostLog(dir, after) {
117454
118139
  }
117455
118140
  function removeHostDir(dir) {
117456
118141
  try {
117457
- fs8.rmSync(dir, { recursive: true, force: true });
118142
+ fs9.rmSync(dir, { recursive: true, force: true });
117458
118143
  } catch (err) {
117459
118144
  console.error(`[session-host] could not remove ${dir}:`, err.message);
117460
118145
  }
117461
- const alias = path12.dirname(hostSocketPath(dir));
118146
+ const alias = path15.dirname(hostSocketPath(dir));
117462
118147
  if (alias !== dir) {
117463
118148
  try {
117464
- fs8.unlinkSync(alias);
118149
+ fs9.unlinkSync(alias);
117465
118150
  } catch {
117466
118151
  }
117467
118152
  }
@@ -117507,6 +118192,9 @@ function setStartupGate(started) {
117507
118192
  if (startupGate === gate) startupPending = false;
117508
118193
  });
117509
118194
  }
118195
+ function noteAdoptedTurn(turnId) {
118196
+ if (startupPending) lastResult.turnIds.add(turnId);
118197
+ }
117510
118198
  function lastAdoption() {
117511
118199
  return lastResult;
117512
118200
  }
@@ -117518,16 +118206,16 @@ function newHostDir() {
117518
118206
  const root = sessionHostsRoot();
117519
118207
  if (!root) throw new Error("session hosts have no directory");
117520
118208
  const id = randomBytes(8).toString("hex");
117521
- return { id, dir: path13.join(root, id) };
118209
+ return { id, dir: path16.join(root, id) };
117522
118210
  }
117523
118211
  var cachedVersion;
117524
118212
  function runtimeVersion() {
117525
118213
  if (cachedVersion !== void 0) return cachedVersion;
117526
118214
  cachedVersion = null;
117527
- const here = path13.dirname(fileURLToPath3(import.meta.url));
118215
+ const here = path16.dirname(fileURLToPath4(import.meta.url));
117528
118216
  for (const rel of ["../../../../package.json", "../../../package.json"]) {
117529
118217
  try {
117530
- const pkg = JSON.parse(fs9.readFileSync(path13.resolve(here, rel), "utf8"));
118218
+ const pkg = JSON.parse(fs10.readFileSync(path16.resolve(here, rel), "utf8"));
117531
118219
  if (pkg.name === "repoburg" && pkg.version) {
117532
118220
  cachedVersion = pkg.version;
117533
118221
  break;
@@ -117538,15 +118226,15 @@ function runtimeVersion() {
117538
118226
  return cachedVersion;
117539
118227
  }
117540
118228
  function writeHostMeta(dir, meta3) {
117541
- fs9.mkdirSync(dir, { recursive: true, mode: 448 });
117542
- fs9.chmodSync(dir, 448);
117543
- const tmp = path13.join(dir, "meta.json.tmp");
117544
- fs9.writeFileSync(tmp, JSON.stringify(meta3, null, 2) + "\n", { mode: 384 });
117545
- fs9.renameSync(tmp, path13.join(dir, "meta.json"));
118229
+ fs10.mkdirSync(dir, { recursive: true, mode: 448 });
118230
+ fs10.chmodSync(dir, 448);
118231
+ const tmp = path16.join(dir, "meta.json.tmp");
118232
+ fs10.writeFileSync(tmp, JSON.stringify(meta3, null, 2) + "\n", { mode: 384 });
118233
+ fs10.renameSync(tmp, path16.join(dir, "meta.json"));
117546
118234
  }
117547
118235
  function readHostMeta(dir) {
117548
118236
  try {
117549
- return JSON.parse(fs9.readFileSync(path13.join(dir, "meta.json"), "utf8"));
118237
+ return JSON.parse(fs10.readFileSync(path16.join(dir, "meta.json"), "utf8"));
117550
118238
  } catch {
117551
118239
  return null;
117552
118240
  }
@@ -117684,16 +118372,16 @@ async function runAdoption() {
117684
118372
  async function adoptHosts(db2, root, adoption, result) {
117685
118373
  let entries = [];
117686
118374
  try {
117687
- entries = fs9.readdirSync(root);
118375
+ entries = fs10.readdirSync(root);
117688
118376
  } catch (err) {
117689
118377
  if (err.code !== "ENOENT") console.error("[session-host] cannot read", root, err.message);
117690
118378
  }
117691
118379
  const seen = /* @__PURE__ */ new Set();
117692
118380
  const queue = [];
117693
118381
  for (const id of entries) {
117694
- const dir = path13.join(root, id);
118382
+ const dir = path16.join(root, id);
117695
118383
  try {
117696
- if (!fs9.statSync(dir).isDirectory()) continue;
118384
+ if (!fs10.statSync(dir).isDirectory()) continue;
117697
118385
  } catch {
117698
118386
  continue;
117699
118387
  }
@@ -117805,7 +118493,7 @@ async function shutDownAllHosts() {
117805
118493
  if (!root) return 0;
117806
118494
  let entries = [];
117807
118495
  try {
117808
- entries = fs9.readdirSync(root);
118496
+ entries = fs10.readdirSync(root);
117809
118497
  } catch {
117810
118498
  return 0;
117811
118499
  }
@@ -117818,7 +118506,7 @@ async function shutDownAllHosts() {
117818
118506
  }
117819
118507
  await Promise.all(
117820
118508
  entries.map(async (id) => {
117821
- const dir = path13.join(root, id);
118509
+ const dir = path16.join(root, id);
117822
118510
  const row = db2 ? getHostRow(db2, id) : void 0;
117823
118511
  try {
117824
118512
  await shutDownHost(dir, { eof: row?.runtime === "codex" });
@@ -117859,63 +118547,6 @@ async function registerSessionHostRoutes(fastify) {
117859
118547
  });
117860
118548
  }
117861
118549
 
117862
- // src/codex/item-mapper.ts
117863
- function mapItemData(item) {
117864
- switch (item.type) {
117865
- case "agentMessage":
117866
- case "agent_message":
117867
- return { text: item.text };
117868
- case "reasoning":
117869
- case "agentReasoning": {
117870
- const summary = Array.isArray(item.summary) ? item.summary.join("\n") : "";
117871
- return { text: summary || item.text || "" };
117872
- }
117873
- case "commandExecution":
117874
- case "command_execution":
117875
- return {
117876
- command: item.command,
117877
- aggregated_output: item.aggregated_output,
117878
- exit_code: item.exit_code ?? null,
117879
- status: item.status
117880
- };
117881
- case "fileChange":
117882
- case "file_change":
117883
- return {
117884
- changes: item.changes,
117885
- status: item.status
117886
- };
117887
- case "mcpToolCall":
117888
- case "mcp_tool_call":
117889
- return {
117890
- server: item.server,
117891
- tool: item.tool,
117892
- arguments: item.arguments,
117893
- result: item.result ?? null,
117894
- error: item.error ?? null,
117895
- status: item.status
117896
- };
117897
- case "webSearch":
117898
- case "web_search":
117899
- return { query: item.query };
117900
- case "todoList":
117901
- case "todo_list":
117902
- return { items: item.items };
117903
- case "error":
117904
- return { message: item.message };
117905
- default:
117906
- return {};
117907
- }
117908
- }
117909
- function getItemStatus(item) {
117910
- if (item.type === "commandExecution" || item.type === "command_execution" || item.type === "fileChange" || item.type === "file_change" || item.type === "mcpToolCall" || item.type === "mcp_tool_call") {
117911
- return item.status ?? "completed";
117912
- }
117913
- if (item.type === "error") {
117914
- return "failed";
117915
- }
117916
- return "completed";
117917
- }
117918
-
117919
118550
  // src/codex/codex-host.ts
117920
118551
  import { EventEmitter as EventEmitter4 } from "node:events";
117921
118552
  import { PassThrough as PassThrough2, Writable as Writable2 } from "node:stream";
@@ -118342,103 +118973,6 @@ function mapTokenUsage(data) {
118342
118973
  };
118343
118974
  }
118344
118975
 
118345
- // src/apps/register-mcp.ts
118346
- import fs10 from "node:fs";
118347
- import path14 from "node:path";
118348
- import { fileURLToPath as fileURLToPath4 } from "node:url";
118349
- var MCP_SERVER_NAME = "agentpane-miniapps";
118350
- function panePublicUrl() {
118351
- return (process.env.AGENT_PANE_PUBLIC_URL || process.env.REPOBURG_DAEMON_URL || "http://localhost:9998").replace(/\/+$/, "");
118352
- }
118353
- function stdioScriptPath() {
118354
- const here = path14.dirname(fileURLToPath4(import.meta.url));
118355
- const candidates = [
118356
- path14.resolve(here, "../../scripts/miniapp-mcp-stdio.mjs"),
118357
- // src/apps/ → backend/scripts
118358
- path14.resolve(here, "../scripts/miniapp-mcp-stdio.mjs")
118359
- // dist bundle → backend/scripts
118360
- ];
118361
- for (const candidate of candidates) {
118362
- if (fs10.existsSync(candidate)) return candidate;
118363
- }
118364
- return null;
118365
- }
118366
- var registered = /* @__PURE__ */ new Set();
118367
- async function registerMiniAppMcp(baseUrl, workspace = "") {
118368
- const key = `${baseUrl}|${workspace}`;
118369
- if (registered.has(key)) return true;
118370
- const script = stdioScriptPath();
118371
- if (!script) {
118372
- console.warn("[miniapp-mcp] stdio proxy script not found \u2014 registration skipped");
118373
- return false;
118374
- }
118375
- if (!anyAppHasTools()) {
118376
- return false;
118377
- }
118378
- const base = baseUrl.replace(/\/+$/, "");
118379
- try {
118380
- try {
118381
- const res2 = await fetch(`${base}/mcp/servers`, { signal: AbortSignal.timeout(5e3) });
118382
- if (res2.ok) {
118383
- const servers = await res2.json();
118384
- const names = servers.map((s) => s.server_name ?? s.name);
118385
- if (names.includes(MCP_SERVER_NAME)) {
118386
- await fetch(`${base}/mcp/configs/${MCP_SERVER_NAME}`, {
118387
- method: "DELETE",
118388
- signal: AbortSignal.timeout(5e3)
118389
- }).catch(() => {
118390
- });
118391
- }
118392
- }
118393
- } catch {
118394
- }
118395
- const body = {
118396
- configJson: JSON.stringify({
118397
- [MCP_SERVER_NAME]: {
118398
- command: process.execPath,
118399
- args: [script, panePublicUrl(), workspace],
118400
- env: { AGENT_PANE_SESSION_ID: "" }
118401
- }
118402
- })
118403
- };
118404
- const res = await fetch(`${base}/mcp/configs`, {
118405
- method: "POST",
118406
- headers: { "Content-Type": "application/json" },
118407
- body: JSON.stringify(body),
118408
- signal: AbortSignal.timeout(1e4)
118409
- });
118410
- if (res.status === 201) {
118411
- console.log(`[miniapp-mcp] gateway registered in workspace backend ${base} (workspace: ${workspace || "global"})`);
118412
- registered.add(key);
118413
- return true;
118414
- }
118415
- const text2 = await res.text();
118416
- if (res.status === 400 && /already exists/i.test(text2)) {
118417
- registered.add(key);
118418
- return true;
118419
- }
118420
- console.warn(`[miniapp-mcp] registration failed (${res.status}): ${text2.slice(0, 200)}`);
118421
- return false;
118422
- } catch (err) {
118423
- console.warn(`[miniapp-mcp] registration error: ${err.message}`);
118424
- return false;
118425
- }
118426
- }
118427
- function codexMiniAppLaunchArgs(workspace = "", sessionId = "") {
118428
- const script = stdioScriptPath();
118429
- if (!script || !anyAppHasTools()) return null;
118430
- return [
118431
- // MCP tool calls must not ask for elicitation approval — nobody is
118432
- // watching an agent-driven session to approve (feature is stable/on).
118433
- "-c",
118434
- "features.tool_call_mcp_elicitation=false",
118435
- "-c",
118436
- `mcp_servers.${MCP_SERVER_NAME}.command=${JSON.stringify(process.execPath)}`,
118437
- "-c",
118438
- `mcp_servers.${MCP_SERVER_NAME}.args=${JSON.stringify([script, panePublicUrl(), workspace, ...sessionId ? [sessionId] : []])}`
118439
- ];
118440
- }
118441
-
118442
118976
  // src/claude/cli-orphans.ts
118443
118977
  import { execFile as execFile4 } from "node:child_process";
118444
118978
  var TERM_GRACE_MS = 2e3;
@@ -118536,6 +119070,11 @@ function reapOrphanCliProcesses(db2, deps = defaultDeps) {
118536
119070
  }
118537
119071
 
118538
119072
  // src/codex/codex-provider.ts
119073
+ var TERMINAL_TASK_TYPE = "background_terminal";
119074
+ function taskPollMs() {
119075
+ const ms = Number(process.env.AGENT_PANE_CODEX_TASK_POLL_MS);
119076
+ return Number.isFinite(ms) && ms > 0 ? ms : 5e3;
119077
+ }
118539
119078
  var sessionMap = /* @__PURE__ */ new Map();
118540
119079
  var startingThreads = /* @__PURE__ */ new Map();
118541
119080
  var ENDED_TURNS_KEPT = 20;
@@ -118579,22 +119118,34 @@ function sandboxType(config3) {
118579
119118
  return "workspace-write";
118580
119119
  }
118581
119120
  }
118582
- function normalizeItemType(type) {
118583
- const map2 = {
118584
- agentMessage: "agent_message",
118585
- userMessage: "user_message",
118586
- agentReasoning: "reasoning",
118587
- commandExecution: "command_execution",
118588
- fileChange: "file_change",
118589
- mcpToolCall: "mcp_tool_call",
118590
- webSearch: "web_search",
118591
- todoList: "todo_list",
118592
- error: "error"
119121
+ function sandboxPolicy(config3) {
119122
+ if (!config3 || !config3.sandboxMode && config3.networkAccessEnabled === void 0) return null;
119123
+ const networkAccess = config3.networkAccessEnabled === true;
119124
+ switch (sandboxType(config3)) {
119125
+ case "read-only":
119126
+ return { type: "readOnly", networkAccess };
119127
+ case "danger-full-access":
119128
+ return { type: "dangerFullAccess" };
119129
+ default:
119130
+ return { type: "workspaceWrite", networkAccess };
119131
+ }
119132
+ }
119133
+ function threadConfig(config3) {
119134
+ return config3?.webSearchMode ? { web_search: config3.webSearchMode } : void 0;
119135
+ }
119136
+ function threadParams(session, cwd) {
119137
+ const config3 = parseRuntimeConfig(session);
119138
+ return {
119139
+ cwd,
119140
+ approvalPolicy: "never",
119141
+ sandbox: sandboxType(config3),
119142
+ model: session.model ?? void 0,
119143
+ config: threadConfig(config3),
119144
+ ...threadInstructionParams(cwd)
118593
119145
  };
118594
- return map2[type] ?? type;
118595
119146
  }
118596
119147
  function shouldSkipItem(type) {
118597
- return type === "userMessage" || type === "user_message";
119148
+ return type === "userMessage" || type === "user_message" || type === "enteredReviewMode" || type === "exitedReviewMode";
118598
119149
  }
118599
119150
  function isEmptyReasoning(item) {
118600
119151
  const summary = Array.isArray(item.summary) ? item.summary : [];
@@ -118636,9 +119187,32 @@ function untrackProcess(pid) {
118636
119187
  } catch {
118637
119188
  }
118638
119189
  }
119190
+ function emptyThreadState() {
119191
+ return {
119192
+ threadId: "",
119193
+ sideThreads: /* @__PURE__ */ new Map(),
119194
+ loadingSide: /* @__PURE__ */ new Map(),
119195
+ codexThreads: /* @__PURE__ */ new Set(),
119196
+ webSearch: void 0,
119197
+ contextTokens: /* @__PURE__ */ new Map(),
119198
+ compactions: /* @__PURE__ */ new Map(),
119199
+ publishedContext: null,
119200
+ tasks: /* @__PURE__ */ new Map(),
119201
+ publishedTasks: "[]",
119202
+ taskTimer: null,
119203
+ refreshing: null,
119204
+ refreshAgain: false
119205
+ };
119206
+ }
118639
119207
  function getOrCreateThread(session) {
118640
119208
  const existing = sessionMap.get(session.id);
118641
- if (existing && !existing.client.isClosed()) return Promise.resolve(existing);
119209
+ if (existing && !existing.client.isClosed()) {
119210
+ const webSearch = threadConfig(parseRuntimeConfig(session))?.web_search;
119211
+ if (webSearch === existing.webSearch || existing.turns.length > 0 || existing.tasks.size > 0) {
119212
+ return Promise.resolve(existing);
119213
+ }
119214
+ void retireEntry(existing, "keep");
119215
+ }
118642
119216
  const pending = startingThreads.get(session.id);
118643
119217
  if (pending) return pending;
118644
119218
  const started = startThread(session).finally(() => startingThreads.delete(session.id));
@@ -118665,7 +119239,7 @@ async function startThread(session) {
118665
119239
  client,
118666
119240
  // A hosted app-server has no cli_processes row: its host supervises it.
118667
119241
  pid: host ? void 0 : client.pid,
118668
- threadId: "",
119242
+ ...emptyThreadState(),
118669
119243
  turns: [],
118670
119244
  ended: /* @__PURE__ */ new Map(),
118671
119245
  resumedTurnIds: null,
@@ -118678,33 +119252,25 @@ async function startThread(session) {
118678
119252
  listen(entry);
118679
119253
  try {
118680
119254
  await client.initialize();
118681
- if (session.origin_app_id) {
118682
- autoApproveToolUserInput(client);
118683
- }
118684
- const config3 = parseRuntimeConfig(session);
118685
- const sandbox = sandboxType(config3);
118686
- const instructions = threadInstructionParams(cwd);
119255
+ autoApproveToolUserInput(client);
119256
+ const base = threadParams(session, cwd);
119257
+ entry.webSearch = base.config?.web_search;
118687
119258
  if (session.external_thread_id) {
119259
+ entry.threadId = session.external_thread_id;
119260
+ entry.codexThreads.add(entry.threadId);
118688
119261
  const result = await client.request("thread/resume", {
118689
119262
  threadId: session.external_thread_id,
118690
- cwd,
118691
- approvalPolicy: "never",
118692
- sandbox,
118693
- model: session.model ?? void 0,
118694
- ...instructions
119263
+ ...base
118695
119264
  });
118696
119265
  entry.threadId = result.thread.id;
118697
119266
  entry.resumedTurnIds = new Set((result.thread.turns ?? []).map((t) => t.id));
118698
- noteHostThread(entry);
118699
119267
  } else {
118700
119268
  const result = await client.request("thread/start", {
118701
- cwd,
118702
- approvalPolicy: "never",
118703
- sandbox,
118704
- model: session.model ?? void 0,
118705
- ...instructions
119269
+ ...base,
119270
+ threadSource: PANE_THREAD_SOURCE
118706
119271
  });
118707
119272
  entry.threadId = result.thread.id;
119273
+ recordCodexThread(entry.threadId, session.id);
118708
119274
  const db2 = getDb();
118709
119275
  const now = (/* @__PURE__ */ new Date()).toISOString();
118710
119276
  db2.prepare("UPDATE sessions SET external_thread_id = ?, updated_at = ? WHERE id = ?").run(
@@ -118712,8 +119278,9 @@ async function startThread(session) {
118712
119278
  now,
118713
119279
  session.id
118714
119280
  );
118715
- noteHostThread(entry);
118716
119281
  }
119282
+ entry.codexThreads.add(entry.threadId);
119283
+ noteHostThread(entry);
118717
119284
  } catch (err) {
118718
119285
  void retireEntry(entry, "keep");
118719
119286
  throw err;
@@ -118736,6 +119303,7 @@ function retireEntry(entry, left, error51 = "App-server closed") {
118736
119303
  }
118737
119304
  }
118738
119305
  }
119306
+ dropTasks(entry);
118739
119307
  entry.closing = entry.client.close().catch(() => {
118740
119308
  }).finally(async () => {
118741
119309
  untrackProcess(entry.pid);
@@ -118746,6 +119314,7 @@ function retireEntry(entry, left, error51 = "App-server closed") {
118746
119314
  function onClientClosed(entry, reason) {
118747
119315
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
118748
119316
  untrackProcess(entry.pid);
119317
+ if (!entry.closing) dropTasks(entry);
118749
119318
  if (entry.host && !entry.closing) void releaseCodexHost(entry.host);
118750
119319
  if (entry.closing || entry.turns.length === 0) return;
118751
119320
  let db2;
@@ -118778,22 +119347,45 @@ function endTurn(entry, active) {
118778
119347
  }
118779
119348
  function rememberEnded(entry, active) {
118780
119349
  if (!active.codexId) return;
118781
- entry.ended.set(active.codexId, active.id);
119350
+ rememberTurnId(entry, active.codexId, active.id);
119351
+ }
119352
+ function rememberTurnId(entry, codexId, paneTurnId) {
119353
+ entry.ended.set(codexId, paneTurnId);
118782
119354
  if (entry.ended.size > ENDED_TURNS_KEPT) entry.ended.delete(entry.ended.keys().next().value);
118783
119355
  }
118784
- function liveTurnsOf(entry, codexId) {
118785
- if (!codexId) return entry.turns.slice(-1);
118786
- const known = entry.turns.filter((t) => t.codexId === codexId);
118787
- if (known.length > 0 || entry.ended.has(codexId)) return known;
118788
- const waiting = entry.turns.find((t) => t.codexId === null);
118789
- if (!waiting) return [];
118790
- waiting.codexId = codexId;
119356
+ function runsOn(active, threadId) {
119357
+ return active.codexThreadId === null || active.codexThreadId === threadId;
119358
+ }
119359
+ function bindCodexId(active, codexId) {
119360
+ active.codexId = codexId;
119361
+ active.resolveStarted(codexId);
118791
119362
  try {
118792
- getDb().prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ? AND external_turn_id IS NULL").run(codexId, (/* @__PURE__ */ new Date()).toISOString(), waiting.id);
119363
+ 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);
118793
119364
  } catch {
118794
119365
  }
119366
+ }
119367
+ function liveTurnsOf(entry, threadId, codexId) {
119368
+ if (!codexId) return entry.turns.filter((t) => runsOn(t, threadId)).slice(-1);
119369
+ const known = entry.turns.filter((t) => t.codexId === codexId);
119370
+ if (known.length > 0 || entry.ended.has(codexId)) return known;
119371
+ const waiting = entry.turns.find((t) => t.codexId === null && t.kind !== "review" && runsOn(t, threadId));
119372
+ if (!waiting) return [];
119373
+ bindCodexId(waiting, codexId);
118795
119374
  return [waiting];
118796
119375
  }
119376
+ function deferToReview(entry, threadId, codexId, replay) {
119377
+ if (!codexId) return false;
119378
+ const review = entry.turns.find((t) => t.kind === "review" && t.codexId === null && t.codexThreadId === threadId);
119379
+ if (!review) return false;
119380
+ review.early.push({ codexId, replay });
119381
+ return true;
119382
+ }
119383
+ function releaseEarly(entry, active) {
119384
+ for (const event of active.early.splice(0)) {
119385
+ if (event.codexId === active.codexId) event.replay();
119386
+ else rememberTurnId(entry, event.codexId, active.id);
119387
+ }
119388
+ }
118797
119389
  function noteContinued(active) {
118798
119390
  if (!active.resuming) return;
118799
119391
  active.resuming = false;
@@ -118870,10 +119462,11 @@ function listen(entry) {
118870
119462
  const on = (method, handle) => {
118871
119463
  entry.client.onNotification(method, (params) => {
118872
119464
  const p = params;
118873
- if (!p || p.threadId !== entry.threadId) return;
119465
+ if (!p || !entry.codexThreads.has(p.threadId)) return;
118874
119466
  handle(p);
118875
119467
  });
118876
119468
  };
119469
+ on("turn/started", (p) => onTurnStarted(entry, p));
118877
119470
  on("item/started", (p) => onItem(entry, p, "in_progress", "item:started"));
118878
119471
  on("item/updated", (p) => onItem(entry, p, "in_progress", "item:updated"));
118879
119472
  on("item/completed", (p) => onItem(entry, p, getItemStatus(p.item), "item:completed"));
@@ -118883,19 +119476,57 @@ function listen(entry) {
118883
119476
  on("thread/tokenUsage/updated", (p) => onTokenUsage(entry, p));
118884
119477
  entry.client.events.once("closed", (reason) => onClientClosed(entry, reason));
118885
119478
  }
119479
+ function onTurnStarted(entry, p) {
119480
+ const codexId = p.turn?.id;
119481
+ if (!codexId || entry.ended.has(codexId) || entry.turns.some((t) => t.codexId === codexId)) return;
119482
+ const onThread = entry.turns.filter((t) => t.codexThreadId === p.threadId);
119483
+ const compaction = onThread.find((t) => t.kind === "compact" && t.codexId === null);
119484
+ if (compaction) {
119485
+ bindCodexId(compaction, codexId);
119486
+ return;
119487
+ }
119488
+ const review = onThread.find((t) => t.kind === "review");
119489
+ if (review?.codexId) rememberTurnId(entry, codexId, review.id);
119490
+ else if (review) review.early.push({ codexId, replay: () => {
119491
+ } });
119492
+ }
118886
119493
  function onItem(entry, p, status, event) {
118887
- const [live] = liveTurnsOf(entry, p.turnId);
119494
+ const [live] = liveTurnsOf(entry, p.threadId, p.turnId);
118888
119495
  if (live) {
118889
119496
  if (!shouldSkipItem(p.item.type)) noteContinued(live);
118890
- handleItemEvent(p, entry.sessionId, live.id, status, event);
119497
+ handleItemEvent(p, entry.sessionId, live.id, status, event, compactionData(entry, live, p, event));
118891
119498
  return;
118892
119499
  }
118893
119500
  const ended = p.turnId ? entry.ended.get(p.turnId) : void 0;
118894
- if (ended) handleItemEvent(p, entry.sessionId, ended, status, event);
119501
+ if (ended) {
119502
+ handleItemEvent(p, entry.sessionId, ended, status, event, compactionData(entry, null, p, event));
119503
+ if (event === "item:completed" && [...entry.tasks.values()].some((t) => t.commandItemId === p.item.id)) {
119504
+ refreshBackgroundTasks(entry);
119505
+ }
119506
+ return;
119507
+ }
119508
+ deferToReview(entry, p.threadId, p.turnId, () => onItem(entry, p, status, event));
119509
+ }
119510
+ function compactionData(entry, live, p, event) {
119511
+ if (p.item.type !== "contextCompaction") return void 0;
119512
+ let compaction = entry.compactions.get(p.item.id);
119513
+ if (!compaction) {
119514
+ compaction = { threadId: p.threadId, pre: entry.contextTokens.get(p.threadId) ?? null, post: null, done: false };
119515
+ entry.compactions.set(p.item.id, compaction);
119516
+ if (entry.compactions.size > ENDED_TURNS_KEPT) {
119517
+ entry.compactions.delete(entry.compactions.keys().next().value);
119518
+ }
119519
+ }
119520
+ if (event === "item:completed") compaction.done = true;
119521
+ const post = compaction.done ? compaction.post : null;
119522
+ return { trigger: live?.kind === "compact" ? "manual" : "auto", pre_tokens: compaction.pre, post_tokens: post };
118895
119523
  }
118896
119524
  function onAgentMessageDelta(entry, p) {
118897
- const [live] = liveTurnsOf(entry, p.turnId);
118898
- if (!live) return;
119525
+ const [live] = liveTurnsOf(entry, p.threadId, p.turnId);
119526
+ if (!live) {
119527
+ deferToReview(entry, p.threadId, p.turnId, () => onAgentMessageDelta(entry, p));
119528
+ return;
119529
+ }
118899
119530
  noteContinued(live);
118900
119531
  const payload = { sessionId: entry.sessionId, turnId: live.id, itemId: p.itemId, delta: p.delta };
118901
119532
  if (entry.replaying) noteDelta(payload);
@@ -118903,7 +119534,10 @@ function onAgentMessageDelta(entry, p) {
118903
119534
  }
118904
119535
  function onTurnCompleted(entry, p) {
118905
119536
  const db2 = getDb();
118906
- for (const live of liveTurnsOf(entry, p.turn?.id ?? p.turnId)) {
119537
+ const codexId = p.turn?.id ?? p.turnId;
119538
+ const lives = liveTurnsOf(entry, p.threadId, codexId);
119539
+ if (lives.length === 0 && deferToReview(entry, p.threadId, codexId, () => onTurnCompleted(entry, p))) return;
119540
+ for (const live of lives) {
118907
119541
  if (p.turn?.status === "interrupted") {
118908
119542
  cancelTurn(entry, live);
118909
119543
  } else if (p.turn?.status === "failed") {
@@ -118914,16 +119548,21 @@ function onTurnCompleted(entry, p) {
118914
119548
  completeTurn(db2, entry.sessionId, live.id, p.usage);
118915
119549
  }
118916
119550
  }
119551
+ refreshBackgroundTasks(entry);
118917
119552
  }
118918
119553
  function onTurnFailed(entry, p) {
118919
119554
  const db2 = getDb();
118920
- for (const live of liveTurnsOf(entry, p.turnId)) {
119555
+ const lives = liveTurnsOf(entry, p.threadId, p.turnId);
119556
+ if (lives.length === 0 && deferToReview(entry, p.threadId, p.turnId, () => onTurnFailed(entry, p))) return;
119557
+ for (const live of lives) {
118921
119558
  endTurn(entry, live);
118922
119559
  failTurn(db2, entry.sessionId, live.id, p.error.message);
118923
119560
  }
119561
+ refreshBackgroundTasks(entry);
118924
119562
  }
118925
119563
  function onTokenUsage(entry, p) {
118926
- const turnId = liveTurnsOf(entry, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
119564
+ noteContext(entry, p);
119565
+ const turnId = liveTurnsOf(entry, p.threadId, p.turnId)[0]?.id ?? (p.turnId ? entry.ended.get(p.turnId) : void 0);
118927
119566
  if (!turnId) return;
118928
119567
  const usage = mapTokenUsage(p.tokenUsage.total);
118929
119568
  const db2 = getDb();
@@ -118931,6 +119570,30 @@ function onTokenUsage(entry, p) {
118931
119570
  db2.prepare("UPDATE turns SET token_usage = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(usage), now, turnId);
118932
119571
  broadcast("turn:tokenUsage", { sessionId: entry.sessionId, turnId, usage });
118933
119572
  }
119573
+ function noteContext(entry, p) {
119574
+ const last = p.tokenUsage?.last;
119575
+ if (!last) return;
119576
+ const tokens2 = Math.max(0, (last.totalTokens ?? 0) - (last.reasoningOutputTokens ?? 0));
119577
+ entry.contextTokens.set(p.threadId, tokens2);
119578
+ for (const compaction of entry.compactions.values()) {
119579
+ if (compaction.threadId === p.threadId && !compaction.done) compaction.post = tokens2;
119580
+ }
119581
+ const window = p.tokenUsage.modelContextWindow;
119582
+ if (p.threadId !== entry.threadId || !window || window <= 0) return;
119583
+ const usage = {
119584
+ totalTokens: tokens2,
119585
+ contextWindow: window,
119586
+ percentage: Math.min(100, Math.round(tokens2 / window * 100))
119587
+ };
119588
+ const json2 = JSON.stringify(usage);
119589
+ if (json2 === entry.publishedContext) return;
119590
+ entry.publishedContext = json2;
119591
+ broadcast("turn:contextUsage", { sessionId: entry.sessionId, ...usage });
119592
+ try {
119593
+ getDb().prepare("UPDATE sessions SET context_usage = ? WHERE id = ?").run(json2, entry.sessionId);
119594
+ } catch {
119595
+ }
119596
+ }
118934
119597
  function turnAttachments2(turn) {
118935
119598
  const raw = turn.attachments;
118936
119599
  if (!raw) return [];
@@ -118944,16 +119607,14 @@ function turnAttachments2(turn) {
118944
119607
  }
118945
119608
  function buildCodexInput(turn) {
118946
119609
  const input = [{ type: "text", text: turn.user_prompt }];
119610
+ const saved = /* @__PURE__ */ new Set();
118947
119611
  for (const att of turnAttachments2(turn)) {
118948
119612
  if (!att || typeof att.data !== "string" || !att.data) continue;
118949
119613
  const type = String(att.media_type ?? "").toLowerCase();
118950
119614
  if (type.startsWith("image/")) {
118951
119615
  input.push({ type: "image", url: `data:${type};base64,${att.data}` });
118952
119616
  } else if (type === "application/pdf") {
118953
- input.push({
118954
- type: "text",
118955
- text: `[Attachment ${att.name} (PDF) was not sent: Codex does not accept PDF files.]`
118956
- });
119617
+ input.push({ type: "text", text: pdfNote(turn, att, saved) });
118957
119618
  } else {
118958
119619
  const decoded = Buffer.from(att.data, "base64").toString("utf-8");
118959
119620
  input.push({ type: "text", text: `
@@ -118964,17 +119625,76 @@ ${decoded}
118964
119625
  }
118965
119626
  return input;
118966
119627
  }
118967
- async function runTurn(session, turn, entry, input, resume) {
119628
+ function pdfNote(turn, att, saved) {
119629
+ try {
119630
+ const file2 = saveAttachmentFile(turn.session_id, turn.id, att.name || "attachment.pdf", att.data, saved);
119631
+ return `[The user attached the PDF "${att.name}". Codex cannot take PDF input, so it is saved at ${file2}; read it from there.]`;
119632
+ } catch (err) {
119633
+ return `[Attachment ${att.name} (PDF) was not sent: it could not be saved for Codex (${err.message}).]`;
119634
+ }
119635
+ }
119636
+ var CODEX_COMMANDS = [
119637
+ { name: "compact", description: "Summarize the conversation to free up the model's context" },
119638
+ {
119639
+ name: "review",
119640
+ description: "Review the uncommitted changes, the changes against a base branch, a commit, or by your instructions",
119641
+ argumentHint: "[base <branch> | commit <sha> | <instructions>]"
119642
+ }
119643
+ ];
119644
+ function parseCodexCommand(prompt) {
119645
+ const match = /^\/(compact|review)(?:\s+([\s\S]*))?$/.exec(prompt.trim());
119646
+ if (!match) return null;
119647
+ const args = (match[2] ?? "").trim();
119648
+ if (match[1] === "compact") return args ? null : { kind: "compact" };
119649
+ if (!args) return { kind: "review", target: { type: "uncommittedChanges" } };
119650
+ const base = /^base\s+(\S+)$/i.exec(args);
119651
+ if (base) return { kind: "review", target: { type: "baseBranch", branch: base[1] } };
119652
+ const commit = /^commit\s+([0-9a-f]{4,40})$/i.exec(args);
119653
+ if (commit) return { kind: "review", target: { type: "commit", sha: commit[1] } };
119654
+ return { kind: "review", target: { type: "custom", instructions: args } };
119655
+ }
119656
+ function turnRequest(turn) {
119657
+ return parseCodexCommand(turn.user_prompt) ?? { kind: "prompt", input: buildCodexInput(turn) };
119658
+ }
119659
+ async function sendTurnRequest(session, entry, threadId, request) {
119660
+ if (request.kind === "compact") {
119661
+ await entry.client.request("thread/compact/start", { threadId });
119662
+ return null;
119663
+ }
119664
+ if (request.kind === "review") {
119665
+ const result2 = await entry.client.request("review/start", {
119666
+ threadId,
119667
+ target: request.target,
119668
+ delivery: "inline"
119669
+ });
119670
+ return result2.turn.id;
119671
+ }
119672
+ const policy = sandboxPolicy(parseRuntimeConfig(session));
119673
+ const result = await entry.client.request("turn/start", {
119674
+ threadId,
119675
+ input: request.input,
119676
+ approvalPolicy: "never",
119677
+ ...policy ? { sandboxPolicy: policy } : {},
119678
+ model: session.model ?? void 0,
119679
+ effort: session.model_reasoning_effort ?? void 0
119680
+ });
119681
+ return result.turn.id;
119682
+ }
119683
+ async function runTurn(session, turn, entry, codexThreadId, request, resume) {
118968
119684
  const db2 = getDb();
118969
- const sandbox = sandboxType(parseRuntimeConfig(session));
118970
119685
  let resolveStarted;
119686
+ const started = new Promise((resolve) => {
119687
+ resolveStarted = resolve;
119688
+ });
118971
119689
  const active = {
118972
119690
  id: turn.id,
118973
119691
  discussionThreadId: turn.thread_id ?? null,
119692
+ codexThreadId,
119693
+ kind: request.kind,
118974
119694
  codexId: null,
118975
- started: new Promise((resolve) => {
118976
- resolveStarted = resolve;
118977
- }),
119695
+ started,
119696
+ resolveStarted,
119697
+ early: [],
118978
119698
  done: false,
118979
119699
  resuming: resume,
118980
119700
  hostOffset: null
@@ -118982,22 +119702,18 @@ async function runTurn(session, turn, entry, input, resume) {
118982
119702
  entry.turns.push(active);
118983
119703
  bindHostTurn(entry, active);
118984
119704
  try {
118985
- const result = await entry.client.request("turn/start", {
118986
- threadId: entry.threadId,
118987
- input,
118988
- approvalPolicy: "never",
118989
- sandbox: { type: sandbox },
118990
- model: session.model ?? void 0,
118991
- effort: session.model_reasoning_effort ?? void 0
118992
- });
118993
- active.codexId = result.turn.id;
118994
- if (active.done) rememberEnded(entry, active);
118995
- db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
118996
- result.turn.id,
118997
- (/* @__PURE__ */ new Date()).toISOString(),
118998
- turn.id
118999
- );
119000
- resolveStarted(result.turn.id);
119705
+ const codexId = await sendTurnRequest(session, entry, codexThreadId, request);
119706
+ if (codexId) {
119707
+ active.codexId = codexId;
119708
+ if (active.done) rememberEnded(entry, active);
119709
+ db2.prepare("UPDATE turns SET external_turn_id = ?, updated_at = ? WHERE id = ?").run(
119710
+ codexId,
119711
+ (/* @__PURE__ */ new Date()).toISOString(),
119712
+ turn.id
119713
+ );
119714
+ resolveStarted(codexId);
119715
+ releaseEarly(entry, active);
119716
+ }
119001
119717
  } catch (err) {
119002
119718
  const message = err.message;
119003
119719
  const settled = active.done;
@@ -119011,8 +119727,10 @@ async function runTurn(session, turn, entry, input, resume) {
119011
119727
  async function startTurn2(session, turn) {
119012
119728
  const db2 = getDb();
119013
119729
  let entry;
119730
+ let codexThreadId;
119014
119731
  try {
119015
119732
  entry = await getOrCreateThread(session);
119733
+ codexThreadId = turn.thread_id ? await sideThreadFor(entry, session, turn.thread_id) : entry.threadId;
119016
119734
  } catch (err) {
119017
119735
  failTurn(db2, session.id, turn.id, `Failed to create app-server thread: ${err.message}`);
119018
119736
  return;
@@ -119022,16 +119740,60 @@ async function startTurn2(session, turn) {
119022
119740
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
119023
119741
  setSessionStatus(db2, session.id, 1, "running", now);
119024
119742
  broadcast("turn:started", { sessionId: session.id, turnId: turn.id });
119025
- await runTurn(session, turn, entry, buildCodexInput(turn), false);
119743
+ await runTurn(session, turn, entry, codexThreadId, turnRequest(turn), false);
119744
+ }
119745
+ function sideThreadFor(entry, session, discussionThreadId) {
119746
+ const loaded = entry.sideThreads.get(discussionThreadId);
119747
+ if (loaded) return Promise.resolve(loaded);
119748
+ const pending = entry.loadingSide.get(discussionThreadId);
119749
+ if (pending) return pending;
119750
+ const loading = loadSideThread(entry, session, discussionThreadId).finally(
119751
+ () => entry.loadingSide.delete(discussionThreadId)
119752
+ );
119753
+ entry.loadingSide.set(discussionThreadId, loading);
119754
+ return loading;
119026
119755
  }
119027
- function handleItemEvent(params, sessionId, turnId, status, broadcastEvent) {
119756
+ async function loadSideThread(entry, session, discussionThreadId) {
119757
+ const db2 = getDb();
119758
+ const row = db2.prepare("SELECT external_thread_id FROM discussion_threads WHERE id = ?").get(discussionThreadId);
119759
+ const base = threadParams(session, session.cwd ?? process.cwd());
119760
+ let codexThreadId;
119761
+ if (row?.external_thread_id) {
119762
+ entry.codexThreads.add(row.external_thread_id);
119763
+ const result = await entry.client.request("thread/resume", {
119764
+ threadId: row.external_thread_id,
119765
+ ...base
119766
+ });
119767
+ codexThreadId = result.thread.id;
119768
+ } else {
119769
+ const result = await entry.client.request("thread/start", {
119770
+ ...base,
119771
+ threadSource: PANE_THREAD_SOURCE
119772
+ });
119773
+ codexThreadId = result.thread.id;
119774
+ recordCodexThread(codexThreadId, session.id);
119775
+ db2.prepare("UPDATE discussion_threads SET external_thread_id = ? WHERE id = ?").run(
119776
+ codexThreadId,
119777
+ discussionThreadId
119778
+ );
119779
+ }
119780
+ entry.sideThreads.set(discussionThreadId, codexThreadId);
119781
+ entry.codexThreads.add(codexThreadId);
119782
+ return codexThreadId;
119783
+ }
119784
+ function handleItemEvent(params, sessionId, turnId, status, broadcastEvent, extraData) {
119028
119785
  const db2 = getDb();
119029
119786
  const now = (/* @__PURE__ */ new Date()).toISOString();
119030
119787
  const item = params.item;
119788
+ if (item.type === "exitedReviewMode" && typeof item.review === "string" && item.review.trim()) {
119789
+ db2.prepare(
119790
+ "UPDATE turns SET agent_response = ?, updated_at = ? WHERE id = ? AND (agent_response IS NULL OR agent_response = '')"
119791
+ ).run(item.review, now, turnId);
119792
+ }
119031
119793
  if (shouldSkipItem(item.type)) return;
119032
119794
  if ((item.type === "reasoning" || item.type === "agentReasoning") && isEmptyReasoning(item)) return;
119033
- const data = mapItemData(item);
119034
- const normalizedType = normalizeItemType(item.type);
119795
+ const data = { ...mapItemData(item), ...extraData };
119796
+ const normalizedType = mapItemType(item);
119035
119797
  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);
119036
119798
  let itemId;
119037
119799
  let createdAt;
@@ -119102,7 +119864,9 @@ function abortOrphanTurn(sessionId, threadId) {
119102
119864
  }
119103
119865
  }
119104
119866
  var END_COMMANDS_WAIT_MS = 5e3;
119105
- async function endTurnCommands(entry, turnId) {
119867
+ async function endTurnCommands(entry, active) {
119868
+ const turnId = active.id;
119869
+ const threadId = active.codexThreadId ?? entry.threadId;
119106
119870
  try {
119107
119871
  const rows = getDb().prepare(
119108
119872
  "SELECT external_item_id AS id FROM items WHERE turn_id = ? AND type = 'command_execution' AND external_item_id IS NOT NULL"
@@ -119112,13 +119876,13 @@ async function endTurnCommands(entry, turnId) {
119112
119876
  let cursor = null;
119113
119877
  do {
119114
119878
  const page = await entry.client.request("thread/backgroundTerminals/list", {
119115
- threadId: entry.threadId,
119879
+ threadId,
119116
119880
  cursor
119117
119881
  });
119118
119882
  for (const terminal of page.data) {
119119
119883
  if (!started.has(terminal.itemId)) continue;
119120
119884
  await entry.client.request("thread/backgroundTerminals/terminate", {
119121
- threadId: entry.threadId,
119885
+ threadId,
119122
119886
  processId: terminal.processId
119123
119887
  });
119124
119888
  }
@@ -119137,7 +119901,7 @@ async function interruptTurn(sessionId, threadId) {
119137
119901
  if (codexId && !target.done) {
119138
119902
  try {
119139
119903
  await entry.client.request("turn/interrupt", {
119140
- threadId: entry.threadId,
119904
+ threadId: target.codexThreadId ?? entry.threadId,
119141
119905
  turnId: codexId
119142
119906
  });
119143
119907
  stopped = true;
@@ -119150,7 +119914,10 @@ async function interruptTurn(sessionId, threadId) {
119150
119914
  cancelTurn(entry, target);
119151
119915
  if (!stopped) void retireEntry(entry, "fail");
119152
119916
  }
119153
- if (stopped) await within(endTurnCommands(entry, target.id), END_COMMANDS_WAIT_MS);
119917
+ if (stopped) {
119918
+ await within(endTurnCommands(entry, target), END_COMMANDS_WAIT_MS);
119919
+ refreshBackgroundTasks(entry);
119920
+ }
119154
119921
  if (live || stopped) return true;
119155
119922
  }
119156
119923
  return abortOrphanTurn(sessionId, threadId);
@@ -119159,8 +119926,31 @@ function clearThread(sessionId) {
119159
119926
  const entry = sessionMap.get(sessionId);
119160
119927
  if (entry) void retireEntry(entry, "cancel");
119161
119928
  }
119929
+ function clearThreadBranch(sessionId, threadId) {
119930
+ const entry = sessionMap.get(sessionId);
119931
+ if (!entry) return;
119932
+ for (const active of entry.turns.filter((t) => t.discussionThreadId === threadId)) {
119933
+ if (active.codexId) {
119934
+ void entry.client.request("turn/interrupt", {
119935
+ threadId: active.codexThreadId ?? entry.threadId,
119936
+ turnId: active.codexId
119937
+ }).catch(() => {
119938
+ });
119939
+ }
119940
+ endTurn(entry, active);
119941
+ }
119942
+ const codexThreadId = entry.sideThreads.get(threadId);
119943
+ entry.sideThreads.delete(threadId);
119944
+ if (!codexThreadId || codexThreadId === entry.threadId) return;
119945
+ entry.codexThreads.delete(codexThreadId);
119946
+ void entry.client.request("thread/unsubscribe", { threadId: codexThreadId }).catch(() => {
119947
+ }).finally(() => refreshBackgroundTasks(entry));
119948
+ }
119162
119949
  function clearAllThreads() {
119163
- for (const entry of [...sessionMap.values()]) void retireEntry(entry, "keep");
119950
+ for (const entry of [...sessionMap.values()]) {
119951
+ stopTaskPolling(entry);
119952
+ void retireEntry(entry, "keep");
119953
+ }
119164
119954
  sessionMap.clear();
119165
119955
  startingThreads.clear();
119166
119956
  titleGenerating.clear();
@@ -119186,7 +119976,8 @@ async function generateTitleAsync(sessionId, userPrompt, agentResponse) {
119186
119976
  const initResult = await client.request("thread/start", {
119187
119977
  cwd: process.cwd(),
119188
119978
  approvalPolicy: "never",
119189
- sandbox: "read-only"
119979
+ sandbox: "read-only",
119980
+ ephemeral: true
119190
119981
  });
119191
119982
  const threadId = initResult.thread.id;
119192
119983
  const truncatedPrompt = userPrompt.slice(0, 500);
@@ -119227,7 +120018,7 @@ Agent responded: "${truncatedResponse}"`;
119227
120018
  threadId,
119228
120019
  input: [{ type: "text", text: titlePrompt }],
119229
120020
  approvalPolicy: "never",
119230
- sandbox: { type: "read-only" }
120021
+ sandboxPolicy: { type: "readOnly" }
119231
120022
  });
119232
120023
  const title = await titlePromise;
119233
120024
  clearTimeout(timeout);
@@ -119254,7 +120045,8 @@ async function summarizeCodexThread(session, _thread, transcript, directives) {
119254
120045
  const initResult = await client.request("thread/start", {
119255
120046
  cwd: session.cwd ?? process.cwd(),
119256
120047
  approvalPolicy: "never",
119257
- sandbox: "read-only"
120048
+ sandbox: "read-only",
120049
+ ephemeral: true
119258
120050
  });
119259
120051
  const threadId = initResult.thread.id;
119260
120052
  const directiveLine = directives.trim() ? `
@@ -119299,7 +120091,7 @@ Produce a concise summary of the discussion that preserves: concrete findings, f
119299
120091
  threadId,
119300
120092
  input: [{ type: "text", text: summaryPrompt }],
119301
120093
  approvalPolicy: "never",
119302
- sandbox: { type: "read-only" }
120094
+ sandboxPolicy: { type: "readOnly" }
119303
120095
  });
119304
120096
  const summary = await summaryPromise;
119305
120097
  clearTimeout(timeout);
@@ -119341,6 +120133,230 @@ async function getModels() {
119341
120133
  return [];
119342
120134
  }
119343
120135
  }
120136
+ async function getCommands() {
120137
+ return CODEX_COMMANDS;
120138
+ }
120139
+ function forkPoint(db2, sessionId, target) {
120140
+ const row = db2.prepare(
120141
+ `SELECT external_turn_id FROM turns
120142
+ WHERE session_id = ? AND thread_id IS NULL AND external_turn_id IS NOT NULL
120143
+ AND status NOT IN ('pending', 'running') AND (id = ? OR created_at < ?)
120144
+ ORDER BY created_at DESC, rowid DESC LIMIT 1`
120145
+ ).get(sessionId, target.id, target.created_at);
120146
+ return row?.external_turn_id ?? null;
120147
+ }
120148
+ async function forkSession(session, targetTurn) {
120149
+ const threadId = session.external_thread_id;
120150
+ if (!threadId) return null;
120151
+ const lastTurnId = forkPoint(getDb(), session.id, targetTurn);
120152
+ if (!lastTurnId) return null;
120153
+ const cwd = session.cwd ?? process.cwd();
120154
+ const client = new AppServerClient({ cwd });
120155
+ try {
120156
+ await client.initialize();
120157
+ const fork = (range) => client.request("thread/fork", {
120158
+ threadId,
120159
+ ...range,
120160
+ cwd,
120161
+ excludeTurns: true,
120162
+ threadSource: PANE_THREAD_SOURCE
120163
+ });
120164
+ let result;
120165
+ try {
120166
+ result = await fork({ lastTurnId });
120167
+ } catch (err) {
120168
+ const range = await client.request("thread/read", { threadId, includeTurns: true }).then(({ thread }) => forkThroughReview(thread.turns ?? [], lastTurnId), () => void 0);
120169
+ if (!range) throw err;
120170
+ result = await fork(range);
120171
+ }
120172
+ recordCodexThread(result.thread.id, session.id);
120173
+ return result.thread.id;
120174
+ } finally {
120175
+ await client.close();
120176
+ }
120177
+ }
120178
+ function refreshBackgroundTasks(entry) {
120179
+ if (entry.refreshing) {
120180
+ entry.refreshAgain = true;
120181
+ return;
120182
+ }
120183
+ entry.refreshing = (async () => {
120184
+ do {
120185
+ entry.refreshAgain = false;
120186
+ await refreshTasksOnce(entry);
120187
+ } while (entry.refreshAgain && isCurrent(entry));
120188
+ })().catch(
120189
+ (err) => console.warn(`[codex] could not list the background commands of ${entry.sessionId}: ${err.message}`)
120190
+ ).finally(() => {
120191
+ entry.refreshing = null;
120192
+ });
120193
+ }
120194
+ async function refreshTasksOnce(entry) {
120195
+ if (!isCurrent(entry) || entry.replaying) return;
120196
+ const live = /* @__PURE__ */ new Map();
120197
+ const unknown2 = /* @__PURE__ */ new Set();
120198
+ for (const codexThreadId of entry.codexThreads) {
120199
+ let cursor = null;
120200
+ try {
120201
+ do {
120202
+ const page = await entry.client.request("thread/backgroundTerminals/list", {
120203
+ threadId: codexThreadId,
120204
+ cursor
120205
+ });
120206
+ for (const terminal of page.data) {
120207
+ live.set(terminal.processId, { codexThreadId, itemId: terminal.itemId, command: terminal.command });
120208
+ }
120209
+ cursor = page.nextCursor;
120210
+ } while (cursor);
120211
+ } catch {
120212
+ unknown2.add(codexThreadId);
120213
+ }
120214
+ }
120215
+ if (!isCurrent(entry)) return;
120216
+ for (const [taskId, task] of entry.tasks) {
120217
+ if (live.has(taskId) || unknown2.has(task.codexThreadId)) continue;
120218
+ entry.tasks.delete(taskId);
120219
+ closeTaskItem(entry.sessionId, task, task.stopped ? "stopped" : "completed");
120220
+ }
120221
+ for (const [processId, terminal] of live) {
120222
+ if (entry.tasks.has(processId)) continue;
120223
+ const turnId = commandTurnOf(entry.sessionId, terminal.itemId);
120224
+ if (turnId && entry.turns.some((t) => t.id === turnId)) continue;
120225
+ const task = {
120226
+ info: { task_id: processId, task_type: TERMINAL_TASK_TYPE, description: terminal.command },
120227
+ codexThreadId: terminal.codexThreadId,
120228
+ processId,
120229
+ commandItemId: terminal.itemId,
120230
+ item: null,
120231
+ stopped: false
120232
+ };
120233
+ if (turnId) openTaskItem(entry.sessionId, turnId, task);
120234
+ entry.tasks.set(processId, task);
120235
+ }
120236
+ publishTasks(entry);
120237
+ }
120238
+ function publishTasks(entry) {
120239
+ const tasks = [...entry.tasks.values()].map((task) => task.info);
120240
+ const json2 = JSON.stringify(tasks);
120241
+ if (json2 !== entry.publishedTasks) {
120242
+ entry.publishedTasks = json2;
120243
+ broadcast("background_tasks", { sessionId: entry.sessionId, tasks });
120244
+ }
120245
+ if (tasks.length > 0 && !entry.taskTimer && isCurrent(entry)) {
120246
+ entry.taskTimer = setInterval(() => refreshBackgroundTasks(entry), taskPollMs());
120247
+ entry.taskTimer.unref?.();
120248
+ } else if (tasks.length === 0) {
120249
+ stopTaskPolling(entry);
120250
+ }
120251
+ }
120252
+ function stopTaskPolling(entry) {
120253
+ if (!entry.taskTimer) return;
120254
+ clearInterval(entry.taskTimer);
120255
+ entry.taskTimer = null;
120256
+ }
120257
+ function dropTasks(entry) {
120258
+ stopTaskPolling(entry);
120259
+ for (const task of entry.tasks.values()) closeTaskItem(entry.sessionId, task, "stopped");
120260
+ entry.tasks.clear();
120261
+ publishTasks(entry);
120262
+ }
120263
+ function commandTurnOf(sessionId, itemId) {
120264
+ try {
120265
+ const row = getDb().prepare(
120266
+ `SELECT i.turn_id FROM items i JOIN turns t ON t.id = i.turn_id
120267
+ WHERE t.session_id = ? AND i.external_item_id = ? ORDER BY i.created_at DESC LIMIT 1`
120268
+ ).get(sessionId, itemId);
120269
+ return row?.turn_id ?? null;
120270
+ } catch {
120271
+ return null;
120272
+ }
120273
+ }
120274
+ function openTaskItem(sessionId, turnId, task) {
120275
+ try {
120276
+ const db2 = getDb();
120277
+ const now = (/* @__PURE__ */ new Date()).toISOString();
120278
+ const item = {
120279
+ id: v4_default(),
120280
+ turn_id: turnId,
120281
+ external_item_id: `terminal-${task.processId}-${task.commandItemId}`,
120282
+ type: "background_task",
120283
+ data: {
120284
+ task_id: task.processId,
120285
+ description: task.info.description,
120286
+ task_type: TERMINAL_TASK_TYPE,
120287
+ status: "running",
120288
+ output: ""
120289
+ },
120290
+ status: "in_progress",
120291
+ created_at: now,
120292
+ updated_at: now
120293
+ };
120294
+ db2.prepare(
120295
+ "INSERT INTO items (id, turn_id, external_item_id, type, data, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
120296
+ ).run(item.id, item.turn_id, item.external_item_id, item.type, JSON.stringify(item.data), item.status, now, now);
120297
+ task.item = { id: item.id, turnId, createdAt: now };
120298
+ broadcast("item:started", { sessionId, turnId, item });
120299
+ } catch (err) {
120300
+ console.warn(`[codex] could not record background command ${task.processId}: ${err.message}`);
120301
+ }
120302
+ }
120303
+ var TASK_OUTPUT_MAX = 2e4;
120304
+ function closeTaskItem(sessionId, task, status) {
120305
+ const ref = task.item;
120306
+ if (!ref) return;
120307
+ try {
120308
+ const db2 = getDb();
120309
+ const command = db2.prepare("SELECT data FROM items WHERE turn_id = ? AND external_item_id = ?").get(ref.turnId, task.commandItemId);
120310
+ let output = "";
120311
+ try {
120312
+ output = String(JSON.parse(command?.data ?? "{}").aggregated_output ?? "");
120313
+ } catch {
120314
+ }
120315
+ const data = {
120316
+ task_id: task.processId,
120317
+ description: task.info.description,
120318
+ task_type: TERMINAL_TASK_TYPE,
120319
+ status,
120320
+ output: output.length > TASK_OUTPUT_MAX ? output.slice(-TASK_OUTPUT_MAX) : output
120321
+ };
120322
+ const now = (/* @__PURE__ */ new Date()).toISOString();
120323
+ db2.prepare("UPDATE items SET data = ?, status = 'completed', updated_at = ? WHERE id = ?").run(
120324
+ JSON.stringify(data),
120325
+ now,
120326
+ ref.id
120327
+ );
120328
+ const item = {
120329
+ id: ref.id,
120330
+ turn_id: ref.turnId,
120331
+ external_item_id: `terminal-${task.processId}-${task.commandItemId}`,
120332
+ type: "background_task",
120333
+ data,
120334
+ status: "completed",
120335
+ created_at: ref.createdAt,
120336
+ updated_at: now
120337
+ };
120338
+ broadcast("item:completed", { sessionId, turnId: ref.turnId, item });
120339
+ } catch {
120340
+ }
120341
+ }
120342
+ async function stopTask(sessionId, taskId) {
120343
+ const entry = sessionMap.get(sessionId);
120344
+ const task = entry?.tasks.get(taskId);
120345
+ if (!entry || !task) throw new Error(`No running background command ${taskId} in this session`);
120346
+ task.stopped = true;
120347
+ await entry.client.request("thread/backgroundTerminals/terminate", {
120348
+ threadId: task.codexThreadId,
120349
+ processId: task.processId
120350
+ });
120351
+ refreshBackgroundTasks(entry);
120352
+ }
120353
+ function listBackgroundTasks() {
120354
+ const bySession = {};
120355
+ for (const entry of sessionMap.values()) {
120356
+ if (entry.tasks.size > 0) bySession[entry.sessionId] = [...entry.tasks.values()].map((task) => task.info);
120357
+ }
120358
+ return bySession;
120359
+ }
119344
120360
  async function shutdown() {
119345
120361
  let db2 = null;
119346
120362
  try {
@@ -119376,12 +120392,13 @@ async function reapOrphans() {
119376
120392
  async function resumeInterruptedTurn(session, turn, _opts) {
119377
120393
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
119378
120394
  const entry = await getOrCreateThread(session);
119379
- if (entry.turns.length > 0) throw new Error("Another turn is running in this session");
120395
+ if (entry.turns.some((t) => !t.discussionThreadId)) throw new Error("Another turn is running in this session");
119380
120396
  if (!isTurnLive(getDb(), turn.id)) return;
120397
+ const command = parseCodexCommand(turn.user_prompt);
119381
120398
  const codexId = turn.external_turn_id;
119382
120399
  const inThread = !!codexId && (!!entry.resumedTurnIds?.has(codexId) || entry.ended.has(codexId));
119383
- const input = inThread ? [{ type: "text", text: CODEX_CONTINUE_PROMPT }] : buildCodexInput(turn);
119384
- await runTurn(session, turn, entry, input, true);
120400
+ const request = command ?? (inThread ? { kind: "prompt", input: [{ type: "text", text: CODEX_CONTINUE_PROMPT }] } : { kind: "prompt", input: buildCodexInput(turn) });
120401
+ await runTurn(session, turn, entry, entry.threadId, request, true);
119385
120402
  }
119386
120403
  function hostFor(sessionId, cwd, options, onDirect) {
119387
120404
  if (!hostsEnabledFor("codex")) return null;
@@ -119448,38 +120465,65 @@ function maybeRetire(entry) {
119448
120465
  }
119449
120466
  function detachEntry(entry) {
119450
120467
  if (sessionMap.get(entry.sessionId) === entry) sessionMap.delete(entry.sessionId);
120468
+ stopTaskPolling(entry);
119451
120469
  entry.closing = Promise.resolve();
119452
120470
  entry.client.detach();
119453
120471
  entry.host?.proc.detach();
119454
120472
  }
119455
120473
  function runningTurns(db2, sessionId) {
119456
120474
  return db2.prepare(
119457
- "SELECT id, thread_id, external_turn_id, resume_state FROM turns WHERE session_id = ? AND status = 'running' ORDER BY created_at, rowid"
120475
+ "SELECT id, thread_id, external_turn_id, resume_state, user_prompt FROM turns WHERE session_id = ? AND status = 'running' ORDER BY created_at, rowid"
119458
120476
  ).all(sessionId);
119459
120477
  }
120478
+ function storedContextTokens(db2, sessionId) {
120479
+ const row = db2.prepare("SELECT context_usage FROM sessions WHERE id = ?").get(sessionId);
120480
+ try {
120481
+ const tokens2 = row?.context_usage ? JSON.parse(row.context_usage).totalTokens : null;
120482
+ return typeof tokens2 === "number" ? tokens2 : null;
120483
+ } catch {
120484
+ return null;
120485
+ }
120486
+ }
119460
120487
  function adoptedEntry(db2, session, threadId, client, host) {
119461
- const turns = runningTurns(db2, session.id).map(
119462
- (row) => ({
120488
+ const sideRows = db2.prepare(
120489
+ "SELECT id, external_thread_id FROM discussion_threads WHERE session_id = ? AND external_thread_id IS NOT NULL"
120490
+ ).all(session.id);
120491
+ const sideOf = new Map(sideRows.map((row) => [row.id, row.external_thread_id]));
120492
+ const turns = runningTurns(db2, session.id).map((row) => {
120493
+ const kind = parseCodexCommand(row.user_prompt)?.kind ?? "prompt";
120494
+ return {
119463
120495
  id: row.id,
119464
120496
  discussionThreadId: row.thread_id,
120497
+ codexThreadId: row.thread_id ? sideOf.get(row.thread_id) ?? null : threadId,
120498
+ // A review whose answer went to the previous daemon takes the first id it sees.
120499
+ kind: kind === "review" && !row.external_turn_id ? "prompt" : kind,
119465
120500
  codexId: row.external_turn_id,
119466
120501
  started: Promise.resolve(row.external_turn_id),
120502
+ resolveStarted: () => {
120503
+ },
120504
+ early: [],
119467
120505
  done: false,
119468
120506
  resuming: row.resume_state === "resuming",
119469
120507
  hostOffset: null
119470
- })
119471
- );
120508
+ };
120509
+ });
119472
120510
  const ended = /* @__PURE__ */ new Map();
119473
120511
  const endedRows = db2.prepare(
119474
120512
  "SELECT id, external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL AND status != 'running' ORDER BY created_at DESC, rowid DESC LIMIT ?"
119475
120513
  ).all(session.id, ENDED_TURNS_KEPT);
119476
120514
  for (const row of endedRows.reverse()) ended.set(row.external_turn_id, row.id);
119477
120515
  const known = db2.prepare("SELECT external_turn_id FROM turns WHERE session_id = ? AND external_turn_id IS NOT NULL").all(session.id);
120516
+ const state = emptyThreadState();
120517
+ const fill = storedContextTokens(db2, session.id);
119478
120518
  return {
119479
120519
  sessionId: session.id,
119480
120520
  client,
119481
120521
  pid: void 0,
120522
+ ...state,
119482
120523
  threadId,
120524
+ codexThreads: /* @__PURE__ */ new Set([threadId, ...sideOf.values()]),
120525
+ contextTokens: new Map(fill === null ? [] : [[threadId, fill]]),
120526
+ webSearch: threadConfig(parseRuntimeConfig(session))?.web_search,
119483
120527
  turns,
119484
120528
  ended,
119485
120529
  // A turn resumed on this app-server later continues with the continue
@@ -119552,7 +120596,7 @@ var codexHostAdopter = {
119552
120596
  entry.retireWhenIdle = !sessionHostFlags().codex ? "session hosts are off for Codex" : row.runtime_version !== version2 ? `started by runtime ${row.runtime_version ?? "unknown"}, this is ${version2 ?? "unknown"}` : null;
119553
120597
  sessionMap.set(session.id, entry);
119554
120598
  listen(entry);
119555
- if (session.origin_app_id) autoApproveToolUserInput(client);
120599
+ autoApproveToolUserInput(client);
119556
120600
  await replayDone(client, `session ${session.id}`);
119557
120601
  entry.replaying = false;
119558
120602
  if (!isCurrent(entry)) {
@@ -119563,6 +120607,7 @@ var codexHostAdopter = {
119563
120607
  recomputeSessionRunning(db2, session.id);
119564
120608
  broadcast("session:resync", { sessionId: session.id });
119565
120609
  resendStreams(session.id);
120610
+ refreshBackgroundTasks(entry);
119566
120611
  const running = entry.turns.map((t) => ({ id: t.id, threadId: t.discussionThreadId }));
119567
120612
  console.log(
119568
120613
  `[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}` : ""}`
@@ -119603,8 +120648,13 @@ var codexProvider = {
119603
120648
  startTurn: startTurn2,
119604
120649
  interruptTurn,
119605
120650
  clearThread,
120651
+ clearThreadBranch,
119606
120652
  clearAllThreads,
119607
120653
  getModels,
120654
+ getCommands,
120655
+ forkSession,
120656
+ stopTask,
120657
+ listBackgroundTasks,
119608
120658
  summarizeThread: summarizeCodexThread,
119609
120659
  resumeInterruptedTurn,
119610
120660
  reapOrphans,
@@ -120155,7 +121205,7 @@ function dropBackgroundTasks(sessionId, entry) {
120155
121205
  entry.backgroundTasks = [];
120156
121206
  publishBackgroundTasks(sessionId);
120157
121207
  }
120158
- function listBackgroundTasks() {
121208
+ function listBackgroundTasks2() {
120159
121209
  const bySession = {};
120160
121210
  for (const [key, entry] of sessionMap2) {
120161
121211
  if (!entry.backgroundTasks?.length) continue;
@@ -120188,7 +121238,11 @@ function rescueWaitMs() {
120188
121238
  }
120189
121239
  var RESCUE_ENV = ["CLAUDE_CODE_RESUME_INTERRUPTED_TURN", "CLAUDE_CODE_RESUME_REASON"];
120190
121240
  function spawnEnv(sessionId, resume) {
120191
- const env = { ...process.env, AGENT_PANE_SESSION_ID: sessionId };
121241
+ const env = {
121242
+ ...process.env,
121243
+ AGENT_PANE_SESSION_ID: sessionId,
121244
+ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1"
121245
+ };
120192
121246
  for (const k of RESCUE_ENV) delete env[k];
120193
121247
  if (resume) {
120194
121248
  env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN = "1";
@@ -120371,6 +121425,9 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume, ad
120371
121425
  permissionMode: "bypassPermissions",
120372
121426
  allowDangerouslySkipPermissions: true,
120373
121427
  includePartialMessages: true,
121428
+ // Echo user messages: a message from another Claude session (SendMessage)
121429
+ // reaches the pane only this way, with its sender in `origin` (MUH-102).
121430
+ extraArgs: { "replay-user-messages": null },
120374
121431
  // Inline visuals: the model's show_widget calls render in the chat.
120375
121432
  mcpServers: { [WIDGET_SERVER_NAME]: createWidgetMcpServer() },
120376
121433
  ...CLI_OVERRIDE,
@@ -120478,12 +121535,26 @@ async function dispatchFrame(entry, sessionId, message, db2, opts = {}) {
120478
121535
  entry.rateLimit = message.rate_limit_info;
120479
121536
  return;
120480
121537
  }
121538
+ const state = sessionStateOf(message);
121539
+ if (state) {
121540
+ handleSessionState(entry, state, db2);
121541
+ return;
121542
+ }
121543
+ const peer = peerOriginOf(message);
121544
+ if (peer) {
121545
+ handlePeerMessage(entry, sessionId, message, peer, db2);
121546
+ return;
121547
+ }
121548
+ if (entry.selfStarted && isModelFrame(message)) reopenForFollowUp(entry, sessionId, db2);
120481
121549
  const currentTurnId = entry.turnId;
120482
121550
  if (!currentTurnId) {
120483
121551
  handleTaskFrame(message, sessionId, entry, db2);
120484
121552
  return;
120485
121553
  }
120486
121554
  if (entry.resume && !trackResumeFrame(entry, message, db2)) return;
121555
+ if (message.type === "result" && !message.parent_tool_use_id) {
121556
+ entry.resultTurnId = currentTurnId;
121557
+ }
120487
121558
  if (opts.awaitResult && message.type === "result") {
120488
121559
  await handleResultMessage(message, sessionId, currentTurnId, entry, db2);
120489
121560
  return;
@@ -120494,6 +121565,119 @@ function isTurnLive2(db2, turnId) {
120494
121565
  const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
120495
121566
  return row?.status === "pending" || row?.status === "running";
120496
121567
  }
121568
+ function sessionStateOf(message) {
121569
+ if (message.type !== "system") return null;
121570
+ const m = message;
121571
+ if (m.subtype !== "session_state_changed") return null;
121572
+ return m.state === "idle" || m.state === "running" || m.state === "requires_action" ? m.state : null;
121573
+ }
121574
+ function peerOriginOf(message) {
121575
+ if (message.type !== "user") return null;
121576
+ if (message.parent_tool_use_id) return null;
121577
+ const origin = message.origin;
121578
+ return origin?.kind === "peer" ? origin : null;
121579
+ }
121580
+ var PEER_ENVELOPE2 = /<cross-session-message\b[^>]*>([\s\S]*?)<\/cross-session-message>/;
121581
+ function peerMessageBody(content, origin) {
121582
+ if (typeof origin.body === "string" && origin.body.trim()) return origin.body.trim();
121583
+ let text2 = "";
121584
+ if (typeof content === "string") text2 = content;
121585
+ else if (Array.isArray(content)) {
121586
+ text2 = content.map((b) => b && typeof b === "object" && b.type === "text" ? String(b.text ?? "") : "").join("\n");
121587
+ }
121588
+ const enveloped = PEER_ENVELOPE2.exec(text2);
121589
+ return (enveloped ? enveloped[1] : text2).trim();
121590
+ }
121591
+ function turnInProgress(entry, db2) {
121592
+ return !!entry.turnId && entry.resultTurnId !== entry.turnId && isTurnLive2(db2, entry.turnId);
121593
+ }
121594
+ function handleSessionState(entry, state, db2) {
121595
+ if (state === "running") {
121596
+ entry.selfStarted = !entry.resume && !turnInProgress(entry, db2);
121597
+ } else if (state === "idle") {
121598
+ entry.selfStarted = false;
121599
+ }
121600
+ }
121601
+ function handlePeerMessage(entry, sessionId, message, origin, db2) {
121602
+ const uuid3 = message.uuid ?? null;
121603
+ const body = peerMessageBody(message.message?.content, origin);
121604
+ const name = origin.name?.trim() || null;
121605
+ entry.selfStarted = false;
121606
+ if (uuid3) {
121607
+ const known = db2.prepare("SELECT id FROM turns WHERE session_id = ? AND runtime_input_ids = ?").get(sessionId, JSON.stringify([uuid3]));
121608
+ if (known) {
121609
+ entry.turnId = known.id;
121610
+ return;
121611
+ }
121612
+ }
121613
+ if (entry.turnId && turnInProgress(entry, db2)) {
121614
+ upsertItem(
121615
+ db2,
121616
+ { type: "peer_message", data: { name, from: origin.from ?? null, body }, externalId: `peer-${uuid3 ?? v4_default()}` },
121617
+ sessionId,
121618
+ entry.turnId,
121619
+ "completed",
121620
+ "item:completed"
121621
+ );
121622
+ return;
121623
+ }
121624
+ openPeerTurn(entry, sessionId, { body, name, uuid: uuid3 }, db2);
121625
+ }
121626
+ function openPeerTurn(entry, sessionId, peer, db2) {
121627
+ const previous = entry.turnId;
121628
+ if (previous && previous !== entry.resultTurnId && isTurnLive2(db2, previous)) {
121629
+ const prev = db2.prepare("SELECT token_usage FROM turns WHERE id = ?").get(previous);
121630
+ completeTurn2(db2, sessionId, previous, prev?.token_usage ? JSON.parse(prev.token_usage) : null);
121631
+ }
121632
+ if (previous) streamingMessageIds.delete(previous);
121633
+ const threadId = entry.threadId ?? null;
121634
+ const turnId = v4_default();
121635
+ const now = (/* @__PURE__ */ new Date()).toISOString();
121636
+ const inputIds = peer.uuid ? JSON.stringify([peer.uuid]) : null;
121637
+ db2.prepare(
121638
+ `INSERT INTO turns (id, session_id, user_prompt, status, thread_id, runtime_input_ids, origin, origin_name, created_at, updated_at)
121639
+ VALUES (?, ?, ?, 'running', ?, ?, 'peer', ?, ?, ?)`
121640
+ ).run(turnId, sessionId, peer.body, threadId, inputIds, peer.name, now, now);
121641
+ entry.turnId = turnId;
121642
+ entry.lastApiError = null;
121643
+ entry.reopenedTurnId = null;
121644
+ bindHostTurn2(entry, turnId);
121645
+ setSessionStatus2(db2, sessionId, 1, "running", now);
121646
+ const row = db2.prepare("SELECT * FROM turns WHERE id = ?").get(turnId);
121647
+ const turn = {
121648
+ ...row,
121649
+ token_usage: null,
121650
+ attachments: null,
121651
+ runtime_input_ids: peer.uuid ? [peer.uuid] : null,
121652
+ items: []
121653
+ };
121654
+ if (threadId) {
121655
+ db2.prepare("UPDATE discussion_threads SET updated_at = ? WHERE id = ?").run(now, threadId);
121656
+ broadcast("thread:followup", { sessionId, threadId, turn });
121657
+ } else {
121658
+ broadcast("turn:created", { sessionId, turn });
121659
+ }
121660
+ broadcast("turn:started", { sessionId, turnId });
121661
+ }
121662
+ function reopenForFollowUp(entry, sessionId, db2) {
121663
+ entry.selfStarted = false;
121664
+ const turnId = entry.turnId;
121665
+ if (!turnId) return;
121666
+ entry.reopenedTurnId = turnId;
121667
+ const reopen = () => {
121668
+ if (entry.turnId !== turnId || entry.reopenedTurnId !== turnId || entry.closeReason) return;
121669
+ const row = db2.prepare("SELECT status FROM turns WHERE id = ?").get(turnId);
121670
+ if (row?.status !== "completed") return;
121671
+ const now = (/* @__PURE__ */ new Date()).toISOString();
121672
+ db2.prepare("UPDATE turns SET status = 'running', updated_at = ? WHERE id = ?").run(now, turnId);
121673
+ if (entry.resultTurnId === turnId) entry.resultTurnId = null;
121674
+ bindHostTurn2(entry, turnId);
121675
+ setSessionStatus2(db2, sessionId, 1, "running", now);
121676
+ broadcast("turn:started", { sessionId, turnId });
121677
+ };
121678
+ if (entry.settling) void entry.settling.then(reopen, reopen);
121679
+ else reopen();
121680
+ }
120497
121681
  async function startTurn3(session, turn) {
120498
121682
  if (isAdoptionPending()) await waitForAdoption();
120499
121683
  const db2 = getDb();
@@ -120534,6 +121718,9 @@ async function startTurn3(session, turn) {
120534
121718
  }
120535
121719
  entry.turnId = turn.id;
120536
121720
  entry.lastApiError = null;
121721
+ entry.reopenedTurnId = null;
121722
+ entry.resultTurnId = null;
121723
+ entry.selfStarted = false;
120537
121724
  clearResume(entry);
120538
121725
  bindHostTurn2(entry, turn.id);
120539
121726
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("running", now, turn.id);
@@ -121001,14 +122188,25 @@ function handleBackgroundTasksChanged(message, sessionId, entry) {
121001
122188
  async function handleResultMessage(message, sessionId, turnId, entry, db2) {
121002
122189
  const parentToolUseId = message.parent_tool_use_id ?? null;
121003
122190
  if (parentToolUseId) return;
122191
+ const followUp = entry.reopenedTurnId === turnId;
122192
+ const settling = settleResult(message, sessionId, turnId, entry, db2, followUp);
122193
+ const tracked = settling.then(
122194
+ () => {
122195
+ },
122196
+ () => {
122197
+ }
122198
+ );
122199
+ entry.settling = tracked;
121004
122200
  try {
121005
- await settleResult(message, sessionId, turnId, entry, db2);
122201
+ await settling;
121006
122202
  } finally {
122203
+ if (followUp && entry.reopenedTurnId === turnId) entry.reopenedTurnId = null;
122204
+ if (entry.settling === tracked) entry.settling = null;
121007
122205
  settleHostTurn2(entry);
121008
122206
  maybeRetire2(entry);
121009
122207
  }
121010
122208
  }
121011
- async function settleResult(message, sessionId, turnId, entry, db2) {
122209
+ async function settleResult(message, sessionId, turnId, entry, db2, followUp = false) {
121012
122210
  if (message.subtype === "success") {
121013
122211
  const usage = mapUsage(message.usage);
121014
122212
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -121019,6 +122217,10 @@ async function settleResult(message, sessionId, turnId, entry, db2) {
121019
122217
  if (message.is_error) {
121020
122218
  const row = db2.prepare("SELECT status, resume_state FROM turns WHERE id = ?").get(turnId);
121021
122219
  if (!row || row.status === "pending" && row.resume_state === "waiting") return;
122220
+ if (followUp && row.status === "running") {
122221
+ completeTurn2(db2, sessionId, turnId, null);
122222
+ row.status = "completed";
122223
+ }
121022
122224
  const text2 = (message.result || apiError?.text || "Claude API error").trim();
121023
122225
  const kind = classifyApiError({
121024
122226
  error: apiError?.error,
@@ -121186,7 +122388,7 @@ function clearThread2(sessionId) {
121186
122388
  }
121187
122389
  publishBackgroundTasks(sessionId);
121188
122390
  }
121189
- function clearThreadBranch(sessionId, threadId) {
122391
+ function clearThreadBranch2(sessionId, threadId) {
121190
122392
  const key = `${sessionId}:thread:${threadId}`;
121191
122393
  const entry = sessionMap2.get(key);
121192
122394
  if (entry) closeEntry(key, entry);
@@ -121266,7 +122468,7 @@ async function setModel(sessionId, model) {
121266
122468
  await entry.query.setModel(model);
121267
122469
  void refreshContext(entry, sessionId, getDb());
121268
122470
  }
121269
- async function stopTask(sessionId, taskId) {
122471
+ async function stopTask2(sessionId, taskId) {
121270
122472
  const entry = sessionMap2.get(sessionId);
121271
122473
  if (!entry) return;
121272
122474
  await entry.query.stopTask(taskId);
@@ -121301,7 +122503,7 @@ async function getModels2() {
121301
122503
  return [];
121302
122504
  }
121303
122505
  }
121304
- async function getCommands() {
122506
+ async function getCommands2() {
121305
122507
  if (cachedCommands) return cachedCommands;
121306
122508
  await getModels2();
121307
122509
  return cachedCommands ?? [];
@@ -121567,6 +122769,7 @@ function bindHostTurn2(entry, turnId) {
121567
122769
  const host = entry.host;
121568
122770
  const proc = host?.proc;
121569
122771
  if (!host || !proc?.hosted) return;
122772
+ noteAdoptedTurn(turnId);
121570
122773
  const offset = proc.consumedLineEnd;
121571
122774
  try {
121572
122775
  setHostTurn(getDb(), host.id, turnId, offset);
@@ -121714,15 +122917,15 @@ var claudeProvider = {
121714
122917
  startTurn: startTurn3,
121715
122918
  interruptTurn: interruptTurn2,
121716
122919
  clearThread: clearThread2,
121717
- clearThreadBranch,
122920
+ clearThreadBranch: clearThreadBranch2,
121718
122921
  clearAllThreads: clearAllThreads2,
121719
122922
  getModels: getModels2,
121720
- getCommands,
122923
+ getCommands: getCommands2,
121721
122924
  forkSession: forkClaudeSession,
121722
122925
  summarizeThread: summarizeClaudeThread,
121723
122926
  setModel,
121724
- stopTask,
121725
- listBackgroundTasks,
122927
+ stopTask: stopTask2,
122928
+ listBackgroundTasks: listBackgroundTasks2,
121726
122929
  resumeInterruptedTurn: resumeInterruptedTurn2,
121727
122930
  reapOrphans: reapOrphans2,
121728
122931
  shutdown: shutdown2
@@ -121743,8 +122946,8 @@ var RepoburgHttpClient = class {
121743
122946
  this.baseUrl = baseUrl.replace(/\/+$/, "");
121744
122947
  }
121745
122948
  /** Perform a JSON request. Throws a concise error on non-OK/non-JSON responses. */
121746
- async request(method, path17, body) {
121747
- const response = await fetch(`${this.baseUrl}${path17}`, {
122949
+ async request(method, path19, body) {
122950
+ const response = await fetch(`${this.baseUrl}${path19}`, {
121748
122951
  method,
121749
122952
  headers: { "Content-Type": "application/json" },
121750
122953
  body: body === void 0 ? void 0 : JSON.stringify(body)
@@ -121753,17 +122956,17 @@ var RepoburgHttpClient = class {
121753
122956
  if (!response.ok) {
121754
122957
  if (isHtml(text2)) {
121755
122958
  throw new Error(
121756
- `${method} ${path17} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
122959
+ `${method} ${path19} failed: ${response.status} HTML response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121757
122960
  );
121758
122961
  }
121759
- throw new Error(`${method} ${path17} failed: ${response.status} ${text2}`);
122962
+ throw new Error(`${method} ${path19} failed: ${response.status} ${text2}`);
121760
122963
  }
121761
122964
  if (text2.length === 0) return void 0;
121762
122965
  try {
121763
122966
  return JSON.parse(text2);
121764
122967
  } catch {
121765
122968
  throw new Error(
121766
- `${method} ${path17} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
122969
+ `${method} ${path19} failed: non-JSON response from ${this.baseUrl} \u2014 the URL points to the wrong server`
121767
122970
  );
121768
122971
  }
121769
122972
  }
@@ -121818,7 +123021,7 @@ var RepoburgHttpClient = class {
121818
123021
  };
121819
123022
 
121820
123023
  // src/repoburg/backend-resolver.ts
121821
- import path15 from "node:path";
123024
+ import path17 from "node:path";
121822
123025
  var HEALTH_POLL_INTERVAL_MS = 1e3;
121823
123026
  var HEALTH_TIMEOUT_MS = 3e4;
121824
123027
  function daemonBaseUrl() {
@@ -121873,7 +123076,7 @@ async function backendHealthy(baseUrl, expectedPath) {
121873
123076
  const health = await fetchJson(`${baseUrl}/health`, void 0, 2e3);
121874
123077
  if (health.status !== "ok") return false;
121875
123078
  if (expectedPath && health.projectPath) {
121876
- return path15.resolve(health.projectPath) === path15.resolve(expectedPath);
123079
+ return path17.resolve(health.projectPath) === path17.resolve(expectedPath);
121877
123080
  }
121878
123081
  return true;
121879
123082
  } catch {
@@ -121894,7 +123097,7 @@ function serviceBaseUrl(service) {
121894
123097
  return `http://localhost:${service.port}`;
121895
123098
  }
121896
123099
  function coveringService(services, absPath) {
121897
- return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path15.sep)).sort((a, b) => b.path.length - a.path.length)[0];
123100
+ return services.filter((s) => absPath === s.path || absPath.startsWith(s.path + path17.sep)).sort((a, b) => b.path.length - a.path.length)[0];
121898
123101
  }
121899
123102
  async function restartService(daemon, name) {
121900
123103
  try {
@@ -121930,7 +123133,7 @@ async function resolveBackendUrl(projectPath, opts = {}) {
121930
123133
  if (envUrl) {
121931
123134
  return { baseUrl: envUrl.replace(/\/+$/, ""), port: 0, name: "REPOBURG_BACKEND_URL" };
121932
123135
  }
121933
- const absPath = path15.resolve(projectPath);
123136
+ const absPath = path17.resolve(projectPath);
121934
123137
  const daemon = daemonBaseUrl();
121935
123138
  const cached3 = resolvedCache.get(absPath);
121936
123139
  if (cached3 && await backendHealthy(cached3.baseUrl, cached3.servesPath ?? absPath)) {
@@ -123483,7 +124686,7 @@ function clearThread3(sessionId) {
123483
124686
  sessionMap3.delete(key);
123484
124687
  }
123485
124688
  }
123486
- function clearThreadBranch2(sessionId, threadId) {
124689
+ function clearThreadBranch3(sessionId, threadId) {
123487
124690
  const key = `${sessionId}:thread:${threadId}`;
123488
124691
  const entry = sessionMap3.get(key);
123489
124692
  if (entry) {
@@ -123532,7 +124735,7 @@ async function resolveClient(session) {
123532
124735
  if (!resolved) throw new Error("No repoburg backend resolved.");
123533
124736
  return new RepoburgHttpClient(resolved.baseUrl);
123534
124737
  }
123535
- async function forkSession(session, targetTurn) {
124738
+ async function forkSession2(session, targetTurn) {
123536
124739
  if (!session.external_thread_id) return null;
123537
124740
  const anchor = parseRuntimeInputIds(targetTurn).pop();
123538
124741
  if (!anchor) {
@@ -123572,7 +124775,7 @@ async function getModels3(cwd) {
123572
124775
  return [];
123573
124776
  }
123574
124777
  }
123575
- async function getCommands2(cwd) {
124778
+ async function getCommands3(cwd) {
123576
124779
  try {
123577
124780
  const resolved = await resolveBackendUrl(cwd ?? process.cwd(), { autoStart: false });
123578
124781
  if (!resolved) return [];
@@ -123593,12 +124796,12 @@ var repoburgProvider = {
123593
124796
  startTurn: startTurn4,
123594
124797
  interruptTurn: interruptTurn3,
123595
124798
  clearThread: clearThread3,
123596
- clearThreadBranch: clearThreadBranch2,
124799
+ clearThreadBranch: clearThreadBranch3,
123597
124800
  clearAllThreads: clearAllThreads3,
123598
124801
  getModels: getModels3,
123599
- getCommands: getCommands2,
124802
+ getCommands: getCommands3,
123600
124803
  rewindRuntime,
123601
- forkSession,
124804
+ forkSession: forkSession2,
123602
124805
  shutdown: shutdown3
123603
124806
  };
123604
124807
 
@@ -123611,7 +124814,7 @@ registerProvider("repoburg", repoburgProvider);
123611
124814
  async function createAgentPaneApp(dbPath, opts = {}) {
123612
124815
  const allowRequest = opts.allowRequest ?? isLocalRequest;
123613
124816
  initDb(dbPath);
123614
- setPaneDataDir(dbPath === ":memory:" ? null : path16.dirname(path16.resolve(dbPath)));
124817
+ setPaneDataDir(dbPath === ":memory:" ? null : path18.dirname(path18.resolve(dbPath)));
123615
124818
  const fastify = (0, import_fastify.default)({ logger: true, bodyLimit: 50 * 1024 * 1024 });
123616
124819
  fastify.addHook("onRequest", async (request, reply) => {
123617
124820
  if (!allowRequest(request.headers.origin, request.headers.host)) {
@@ -123637,6 +124840,7 @@ async function createAgentPaneApp(dbPath, opts = {}) {
123637
124840
  await registerSidecarRoutes(fastify);
123638
124841
  await registerUsageRoutes(fastify);
123639
124842
  await registerClaudeSessionRoutes(fastify);
124843
+ await registerCodexSessionRoutes(fastify);
123640
124844
  await registerSessionHostRoutes(fastify);
123641
124845
  const wss3 = initWs(allowRequest);
123642
124846
  initTerminalWs(allowRequest);