meshy-node 0.3.2 → 0.3.4

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.
package/main.cjs CHANGED
@@ -6629,8 +6629,8 @@ var require_node2 = __commonJS({
6629
6629
  }
6630
6630
  break;
6631
6631
  case "FILE":
6632
- var fs21 = require("fs");
6633
- stream2 = new fs21.SyncWriteStream(fd2, { autoClose: false });
6632
+ var fs22 = require("fs");
6633
+ stream2 = new fs22.SyncWriteStream(fd2, { autoClose: false });
6634
6634
  stream2._type = "fs";
6635
6635
  break;
6636
6636
  case "PIPE":
@@ -10057,13 +10057,13 @@ var require_extend_node = __commonJS({
10057
10057
  return length;
10058
10058
  };
10059
10059
  if (iconv.supportsStreams) {
10060
- var Readable = require("stream").Readable;
10061
- original.ReadableSetEncoding = Readable.prototype.setEncoding;
10062
- Readable.prototype.setEncoding = function setEncoding(enc, options) {
10060
+ var Readable3 = require("stream").Readable;
10061
+ original.ReadableSetEncoding = Readable3.prototype.setEncoding;
10062
+ Readable3.prototype.setEncoding = function setEncoding(enc, options) {
10063
10063
  this._readableState.decoder = iconv.getDecoder(enc, options);
10064
10064
  this._readableState.encoding = enc;
10065
10065
  };
10066
- Readable.prototype.collect = iconv._collect;
10066
+ Readable3.prototype.collect = iconv._collect;
10067
10067
  }
10068
10068
  };
10069
10069
  iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() {
@@ -10080,9 +10080,9 @@ var require_extend_node = __commonJS({
10080
10080
  Buffer2.prototype.toString = original.BufferToString;
10081
10081
  Buffer2.prototype.write = original.BufferWrite;
10082
10082
  if (iconv.supportsStreams) {
10083
- var Readable = require("stream").Readable;
10084
- Readable.prototype.setEncoding = original.ReadableSetEncoding;
10085
- delete Readable.prototype.collect;
10083
+ var Readable3 = require("stream").Readable;
10084
+ Readable3.prototype.setEncoding = original.ReadableSetEncoding;
10085
+ delete Readable3.prototype.collect;
10086
10086
  }
10087
10087
  original = void 0;
10088
10088
  };
@@ -19420,11 +19420,11 @@ var require_mime_types = __commonJS({
19420
19420
  }
19421
19421
  return exts[0];
19422
19422
  }
19423
- function lookup(path22) {
19424
- if (!path22 || typeof path22 !== "string") {
19423
+ function lookup(path23) {
19424
+ if (!path23 || typeof path23 !== "string") {
19425
19425
  return false;
19426
19426
  }
19427
- var extension2 = extname3("x." + path22).toLowerCase().substr(1);
19427
+ var extension2 = extname3("x." + path23).toLowerCase().substr(1);
19428
19428
  if (!extension2) {
19429
19429
  return false;
19430
19430
  }
@@ -22624,8 +22624,8 @@ var require_escape_html = __commonJS({
22624
22624
  "../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js"(exports2, module2) {
22625
22625
  "use strict";
22626
22626
  var matchHtmlRegExp = /["'&<>]/;
22627
- module2.exports = escapeHtml;
22628
- function escapeHtml(string) {
22627
+ module2.exports = escapeHtml2;
22628
+ function escapeHtml2(string) {
22629
22629
  var str = "" + string;
22630
22630
  var match = matchHtmlRegExp.exec(str);
22631
22631
  if (!match) {
@@ -22756,7 +22756,7 @@ var require_finalhandler = __commonJS({
22756
22756
  "use strict";
22757
22757
  var debug = require_src2()("finalhandler");
22758
22758
  var encodeUrl = require_encodeurl();
22759
- var escapeHtml = require_escape_html();
22759
+ var escapeHtml2 = require_escape_html();
22760
22760
  var onFinished = require_on_finished();
22761
22761
  var parseUrl = require_parseurl();
22762
22762
  var statuses = require_statuses();
@@ -22768,7 +22768,7 @@ var require_finalhandler = __commonJS({
22768
22768
  };
22769
22769
  var isFinished = onFinished.isFinished;
22770
22770
  function createHtmlDocument(message) {
22771
- var body = escapeHtml(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;");
22771
+ var body = escapeHtml2(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;");
22772
22772
  return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>' + body + "</pre>\n</body>\n</html>\n";
22773
22773
  }
22774
22774
  module2.exports = finalhandler;
@@ -22942,7 +22942,7 @@ var require_path_to_regexp = __commonJS({
22942
22942
  "use strict";
22943
22943
  module2.exports = pathToRegexp;
22944
22944
  var MATCHING_GROUP_REGEXP = /\\.|\((?:\?<(.*?)>)?(?!\?)/g;
22945
- function pathToRegexp(path22, keys, options) {
22945
+ function pathToRegexp(path23, keys, options) {
22946
22946
  options = options || {};
22947
22947
  keys = keys || [];
22948
22948
  var strict = options.strict;
@@ -22956,8 +22956,8 @@ var require_path_to_regexp = __commonJS({
22956
22956
  var pos = 0;
22957
22957
  var backtrack = "";
22958
22958
  var m;
22959
- if (path22 instanceof RegExp) {
22960
- while (m = MATCHING_GROUP_REGEXP.exec(path22.source)) {
22959
+ if (path23 instanceof RegExp) {
22960
+ while (m = MATCHING_GROUP_REGEXP.exec(path23.source)) {
22961
22961
  if (m[0][0] === "\\") continue;
22962
22962
  keys.push({
22963
22963
  name: m[1] || name2++,
@@ -22965,18 +22965,18 @@ var require_path_to_regexp = __commonJS({
22965
22965
  offset: m.index
22966
22966
  });
22967
22967
  }
22968
- return path22;
22968
+ return path23;
22969
22969
  }
22970
- if (Array.isArray(path22)) {
22971
- path22 = path22.map(function(value) {
22970
+ if (Array.isArray(path23)) {
22971
+ path23 = path23.map(function(value) {
22972
22972
  return pathToRegexp(value, keys, options).source;
22973
22973
  });
22974
- return new RegExp(path22.join("|"), flags);
22974
+ return new RegExp(path23.join("|"), flags);
22975
22975
  }
22976
- if (typeof path22 !== "string") {
22976
+ if (typeof path23 !== "string") {
22977
22977
  throw new TypeError("path must be a string, array of strings, or regular expression");
22978
22978
  }
22979
- path22 = path22.replace(
22979
+ path23 = path23.replace(
22980
22980
  /\\.|(\/)?(\.)?:(\w+)(\(.*?\))?(\*)?(\?)?|[.*]|\/\(/g,
22981
22981
  function(match, slash, format, key, capture, star, optional, offset) {
22982
22982
  if (match[0] === "\\") {
@@ -22993,7 +22993,7 @@ var require_path_to_regexp = __commonJS({
22993
22993
  if (slash || format) {
22994
22994
  backtrack = "";
22995
22995
  } else {
22996
- backtrack += path22.slice(pos, offset);
22996
+ backtrack += path23.slice(pos, offset);
22997
22997
  }
22998
22998
  pos = offset + match.length;
22999
22999
  if (match === "*") {
@@ -23023,7 +23023,7 @@ var require_path_to_regexp = __commonJS({
23023
23023
  return result;
23024
23024
  }
23025
23025
  );
23026
- while (m = MATCHING_GROUP_REGEXP.exec(path22)) {
23026
+ while (m = MATCHING_GROUP_REGEXP.exec(path23)) {
23027
23027
  if (m[0][0] === "\\") continue;
23028
23028
  if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) {
23029
23029
  keys.splice(keysOffset + i, 0, {
@@ -23035,13 +23035,13 @@ var require_path_to_regexp = __commonJS({
23035
23035
  }
23036
23036
  i++;
23037
23037
  }
23038
- path22 += strict ? "" : path22[path22.length - 1] === "/" ? "?" : "/?";
23038
+ path23 += strict ? "" : path23[path23.length - 1] === "/" ? "?" : "/?";
23039
23039
  if (end) {
23040
- path22 += "$";
23041
- } else if (path22[path22.length - 1] !== "/") {
23042
- path22 += lookahead ? "(?=/|$)" : "(?:/|$)";
23040
+ path23 += "$";
23041
+ } else if (path23[path23.length - 1] !== "/") {
23042
+ path23 += lookahead ? "(?=/|$)" : "(?:/|$)";
23043
23043
  }
23044
- return new RegExp("^" + path22, flags);
23044
+ return new RegExp("^" + path23, flags);
23045
23045
  }
23046
23046
  }
23047
23047
  });
@@ -23054,19 +23054,19 @@ var require_layer = __commonJS({
23054
23054
  var debug = require_src2()("express:router:layer");
23055
23055
  var hasOwnProperty = Object.prototype.hasOwnProperty;
23056
23056
  module2.exports = Layer;
23057
- function Layer(path22, options, fn) {
23057
+ function Layer(path23, options, fn) {
23058
23058
  if (!(this instanceof Layer)) {
23059
- return new Layer(path22, options, fn);
23059
+ return new Layer(path23, options, fn);
23060
23060
  }
23061
- debug("new %o", path22);
23061
+ debug("new %o", path23);
23062
23062
  var opts = options || {};
23063
23063
  this.handle = fn;
23064
23064
  this.name = fn.name || "<anonymous>";
23065
23065
  this.params = void 0;
23066
23066
  this.path = void 0;
23067
- this.regexp = pathRegexp(path22, this.keys = [], opts);
23068
- this.regexp.fast_star = path22 === "*";
23069
- this.regexp.fast_slash = path22 === "/" && opts.end === false;
23067
+ this.regexp = pathRegexp(path23, this.keys = [], opts);
23068
+ this.regexp.fast_star = path23 === "*";
23069
+ this.regexp.fast_slash = path23 === "/" && opts.end === false;
23070
23070
  }
23071
23071
  Layer.prototype.handle_error = function handle_error(error, req, res, next) {
23072
23072
  var fn = this.handle;
@@ -23090,20 +23090,20 @@ var require_layer = __commonJS({
23090
23090
  next(err);
23091
23091
  }
23092
23092
  };
23093
- Layer.prototype.match = function match(path22) {
23093
+ Layer.prototype.match = function match(path23) {
23094
23094
  var match2;
23095
- if (path22 != null) {
23095
+ if (path23 != null) {
23096
23096
  if (this.regexp.fast_slash) {
23097
23097
  this.params = {};
23098
23098
  this.path = "";
23099
23099
  return true;
23100
23100
  }
23101
23101
  if (this.regexp.fast_star) {
23102
- this.params = { "0": decode_param(path22) };
23103
- this.path = path22;
23102
+ this.params = { "0": decode_param(path23) };
23103
+ this.path = path23;
23104
23104
  return true;
23105
23105
  }
23106
- match2 = this.regexp.exec(path22);
23106
+ match2 = this.regexp.exec(path23);
23107
23107
  }
23108
23108
  if (!match2) {
23109
23109
  this.params = void 0;
@@ -23196,10 +23196,10 @@ var require_route = __commonJS({
23196
23196
  var slice = Array.prototype.slice;
23197
23197
  var toString = Object.prototype.toString;
23198
23198
  module2.exports = Route;
23199
- function Route(path22) {
23200
- this.path = path22;
23199
+ function Route(path23) {
23200
+ this.path = path23;
23201
23201
  this.stack = [];
23202
- debug("new %o", path22);
23202
+ debug("new %o", path23);
23203
23203
  this.methods = {};
23204
23204
  }
23205
23205
  Route.prototype._handles_method = function _handles_method(method) {
@@ -23412,8 +23412,8 @@ var require_router = __commonJS({
23412
23412
  if (++sync > 100) {
23413
23413
  return setImmediate(next, err);
23414
23414
  }
23415
- var path22 = getPathname(req);
23416
- if (path22 == null) {
23415
+ var path23 = getPathname(req);
23416
+ if (path23 == null) {
23417
23417
  return done(layerError);
23418
23418
  }
23419
23419
  var layer;
@@ -23421,7 +23421,7 @@ var require_router = __commonJS({
23421
23421
  var route;
23422
23422
  while (match !== true && idx < stack.length) {
23423
23423
  layer = stack[idx++];
23424
- match = matchLayer(layer, path22);
23424
+ match = matchLayer(layer, path23);
23425
23425
  route = layer.route;
23426
23426
  if (typeof match !== "boolean") {
23427
23427
  layerError = layerError || match;
@@ -23459,18 +23459,18 @@ var require_router = __commonJS({
23459
23459
  } else if (route) {
23460
23460
  layer.handle_request(req, res, next);
23461
23461
  } else {
23462
- trim_prefix(layer, layerError, layerPath, path22);
23462
+ trim_prefix(layer, layerError, layerPath, path23);
23463
23463
  }
23464
23464
  sync = 0;
23465
23465
  });
23466
23466
  }
23467
- function trim_prefix(layer, layerError, layerPath, path22) {
23467
+ function trim_prefix(layer, layerError, layerPath, path23) {
23468
23468
  if (layerPath.length !== 0) {
23469
- if (layerPath !== path22.slice(0, layerPath.length)) {
23469
+ if (layerPath !== path23.slice(0, layerPath.length)) {
23470
23470
  next(layerError);
23471
23471
  return;
23472
23472
  }
23473
- var c = path22[layerPath.length];
23473
+ var c = path23[layerPath.length];
23474
23474
  if (c && c !== "/" && c !== ".") return next(layerError);
23475
23475
  debug("trim prefix (%s) from url %s", layerPath, req.url);
23476
23476
  removed = layerPath;
@@ -23548,7 +23548,7 @@ var require_router = __commonJS({
23548
23548
  };
23549
23549
  proto.use = function use(fn) {
23550
23550
  var offset = 0;
23551
- var path22 = "/";
23551
+ var path23 = "/";
23552
23552
  if (typeof fn !== "function") {
23553
23553
  var arg = fn;
23554
23554
  while (Array.isArray(arg) && arg.length !== 0) {
@@ -23556,7 +23556,7 @@ var require_router = __commonJS({
23556
23556
  }
23557
23557
  if (typeof arg !== "function") {
23558
23558
  offset = 1;
23559
- path22 = fn;
23559
+ path23 = fn;
23560
23560
  }
23561
23561
  }
23562
23562
  var callbacks = flatten(slice.call(arguments, offset));
@@ -23568,8 +23568,8 @@ var require_router = __commonJS({
23568
23568
  if (typeof fn !== "function") {
23569
23569
  throw new TypeError("Router.use() requires a middleware function but got a " + gettype(fn));
23570
23570
  }
23571
- debug("use %o %s", path22, fn.name || "<anonymous>");
23572
- var layer = new Layer(path22, {
23571
+ debug("use %o %s", path23, fn.name || "<anonymous>");
23572
+ var layer = new Layer(path23, {
23573
23573
  sensitive: this.caseSensitive,
23574
23574
  strict: false,
23575
23575
  end: false
@@ -23579,9 +23579,9 @@ var require_router = __commonJS({
23579
23579
  }
23580
23580
  return this;
23581
23581
  };
23582
- proto.route = function route(path22) {
23583
- var route2 = new Route(path22);
23584
- var layer = new Layer(path22, {
23582
+ proto.route = function route(path23) {
23583
+ var route2 = new Route(path23);
23584
+ var layer = new Layer(path23, {
23585
23585
  sensitive: this.caseSensitive,
23586
23586
  strict: this.strict,
23587
23587
  end: true
@@ -23591,8 +23591,8 @@ var require_router = __commonJS({
23591
23591
  return route2;
23592
23592
  };
23593
23593
  methods.concat("all").forEach(function(method) {
23594
- proto[method] = function(path22) {
23595
- var route = this.route(path22);
23594
+ proto[method] = function(path23) {
23595
+ var route = this.route(path23);
23596
23596
  route[method].apply(route, slice.call(arguments, 1));
23597
23597
  return this;
23598
23598
  };
@@ -23628,9 +23628,9 @@ var require_router = __commonJS({
23628
23628
  }
23629
23629
  return toString.call(obj).replace(objectRegExp, "$1");
23630
23630
  }
23631
- function matchLayer(layer, path22) {
23631
+ function matchLayer(layer, path23) {
23632
23632
  try {
23633
- return layer.match(path22);
23633
+ return layer.match(path23);
23634
23634
  } catch (err) {
23635
23635
  return err;
23636
23636
  }
@@ -23748,13 +23748,13 @@ var require_view = __commonJS({
23748
23748
  "../../node_modules/.pnpm/express@4.22.1/node_modules/express/lib/view.js"(exports2, module2) {
23749
23749
  "use strict";
23750
23750
  var debug = require_src2()("express:view");
23751
- var path22 = require("path");
23752
- var fs21 = require("fs");
23753
- var dirname7 = path22.dirname;
23754
- var basename4 = path22.basename;
23755
- var extname3 = path22.extname;
23756
- var join17 = path22.join;
23757
- var resolve14 = path22.resolve;
23751
+ var path23 = require("path");
23752
+ var fs22 = require("fs");
23753
+ var dirname7 = path23.dirname;
23754
+ var basename5 = path23.basename;
23755
+ var extname3 = path23.extname;
23756
+ var join18 = path23.join;
23757
+ var resolve14 = path23.resolve;
23758
23758
  module2.exports = View;
23759
23759
  function View(name2, options) {
23760
23760
  var opts = options || {};
@@ -23783,17 +23783,17 @@ var require_view = __commonJS({
23783
23783
  this.path = this.lookup(fileName);
23784
23784
  }
23785
23785
  View.prototype.lookup = function lookup(name2) {
23786
- var path23;
23786
+ var path24;
23787
23787
  var roots = [].concat(this.root);
23788
23788
  debug('lookup "%s"', name2);
23789
- for (var i = 0; i < roots.length && !path23; i++) {
23789
+ for (var i = 0; i < roots.length && !path24; i++) {
23790
23790
  var root = roots[i];
23791
23791
  var loc = resolve14(root, name2);
23792
23792
  var dir = dirname7(loc);
23793
- var file = basename4(loc);
23794
- path23 = this.resolve(dir, file);
23793
+ var file = basename5(loc);
23794
+ path24 = this.resolve(dir, file);
23795
23795
  }
23796
- return path23;
23796
+ return path24;
23797
23797
  };
23798
23798
  View.prototype.render = function render(options, callback) {
23799
23799
  debug('render "%s"', this.path);
@@ -23801,21 +23801,21 @@ var require_view = __commonJS({
23801
23801
  };
23802
23802
  View.prototype.resolve = function resolve15(dir, file) {
23803
23803
  var ext = this.ext;
23804
- var path23 = join17(dir, file);
23805
- var stat = tryStat(path23);
23804
+ var path24 = join18(dir, file);
23805
+ var stat = tryStat(path24);
23806
23806
  if (stat && stat.isFile()) {
23807
- return path23;
23807
+ return path24;
23808
23808
  }
23809
- path23 = join17(dir, basename4(file, ext), "index" + ext);
23810
- stat = tryStat(path23);
23809
+ path24 = join18(dir, basename5(file, ext), "index" + ext);
23810
+ stat = tryStat(path24);
23811
23811
  if (stat && stat.isFile()) {
23812
- return path23;
23812
+ return path24;
23813
23813
  }
23814
23814
  };
23815
- function tryStat(path23) {
23816
- debug('stat "%s"', path23);
23815
+ function tryStat(path24) {
23816
+ debug('stat "%s"', path24);
23817
23817
  try {
23818
- return fs21.statSync(path23);
23818
+ return fs22.statSync(path24);
23819
23819
  } catch (e) {
23820
23820
  return void 0;
23821
23821
  }
@@ -23829,7 +23829,7 @@ var require_content_disposition = __commonJS({
23829
23829
  "use strict";
23830
23830
  module2.exports = contentDisposition;
23831
23831
  module2.exports.parse = parse;
23832
- var basename4 = require("path").basename;
23832
+ var basename5 = require("path").basename;
23833
23833
  var Buffer2 = require_safe_buffer().Buffer;
23834
23834
  var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g;
23835
23835
  var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/;
@@ -23865,9 +23865,9 @@ var require_content_disposition = __commonJS({
23865
23865
  if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) {
23866
23866
  throw new TypeError("fallback must be ISO-8859-1 string");
23867
23867
  }
23868
- var name2 = basename4(filename);
23868
+ var name2 = basename5(filename);
23869
23869
  var isQuotedString = TEXT_REGEXP.test(name2);
23870
- var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name2) : basename4(fallback);
23870
+ var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name2) : basename5(fallback);
23871
23871
  var hasFallback = typeof fallbackName === "string" && fallbackName !== name2;
23872
23872
  if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name2)) {
23873
23873
  params["filename*"] = name2;
@@ -24112,8 +24112,8 @@ var require_types = __commonJS({
24112
24112
  var require_mime = __commonJS({
24113
24113
  "../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js"(exports2, module2) {
24114
24114
  "use strict";
24115
- var path22 = require("path");
24116
- var fs21 = require("fs");
24115
+ var path23 = require("path");
24116
+ var fs22 = require("fs");
24117
24117
  function Mime() {
24118
24118
  this.types = /* @__PURE__ */ Object.create(null);
24119
24119
  this.extensions = /* @__PURE__ */ Object.create(null);
@@ -24134,7 +24134,7 @@ var require_mime = __commonJS({
24134
24134
  };
24135
24135
  Mime.prototype.load = function(file) {
24136
24136
  this._loading = file;
24137
- var map = {}, content = fs21.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
24137
+ var map = {}, content = fs22.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
24138
24138
  lines.forEach(function(line) {
24139
24139
  var fields = line.replace(/\s*#.*|^\s*|\s*$/g, "").split(/\s+/);
24140
24140
  map[fields.shift()] = fields;
@@ -24142,8 +24142,8 @@ var require_mime = __commonJS({
24142
24142
  this.define(map);
24143
24143
  this._loading = null;
24144
24144
  };
24145
- Mime.prototype.lookup = function(path23, fallback) {
24146
- var ext = path23.replace(/^.*[\.\/\\]/, "").toLowerCase();
24145
+ Mime.prototype.lookup = function(path24, fallback) {
24146
+ var ext = path24.replace(/^.*[\.\/\\]/, "").toLowerCase();
24147
24147
  return this.types[ext] || fallback || this.default_type;
24148
24148
  };
24149
24149
  Mime.prototype.extension = function(mimeType) {
@@ -24253,36 +24253,36 @@ var require_send = __commonJS({
24253
24253
  var deprecate = require_depd()("send");
24254
24254
  var destroy2 = require_destroy();
24255
24255
  var encodeUrl = require_encodeurl();
24256
- var escapeHtml = require_escape_html();
24256
+ var escapeHtml2 = require_escape_html();
24257
24257
  var etag = require_etag();
24258
24258
  var fresh = require_fresh();
24259
- var fs21 = require("fs");
24259
+ var fs22 = require("fs");
24260
24260
  var mime = require_mime();
24261
24261
  var ms = require_ms();
24262
24262
  var onFinished = require_on_finished();
24263
24263
  var parseRange = require_range_parser();
24264
- var path22 = require("path");
24264
+ var path23 = require("path");
24265
24265
  var statuses = require_statuses();
24266
24266
  var Stream = require("stream");
24267
24267
  var util3 = require("util");
24268
- var extname3 = path22.extname;
24269
- var join17 = path22.join;
24270
- var normalize = path22.normalize;
24271
- var resolve14 = path22.resolve;
24272
- var sep4 = path22.sep;
24268
+ var extname3 = path23.extname;
24269
+ var join18 = path23.join;
24270
+ var normalize = path23.normalize;
24271
+ var resolve14 = path23.resolve;
24272
+ var sep4 = path23.sep;
24273
24273
  var BYTES_RANGE_REGEXP = /^ *bytes=/;
24274
24274
  var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
24275
24275
  var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
24276
24276
  module2.exports = send;
24277
24277
  module2.exports.mime = mime;
24278
- function send(req, path23, options) {
24279
- return new SendStream(req, path23, options);
24278
+ function send(req, path24, options) {
24279
+ return new SendStream(req, path24, options);
24280
24280
  }
24281
- function SendStream(req, path23, options) {
24281
+ function SendStream(req, path24, options) {
24282
24282
  Stream.call(this);
24283
24283
  var opts = options || {};
24284
24284
  this.options = opts;
24285
- this.path = path23;
24285
+ this.path = path24;
24286
24286
  this.req = req;
24287
24287
  this._acceptRanges = opts.acceptRanges !== void 0 ? Boolean(opts.acceptRanges) : true;
24288
24288
  this._cacheControl = opts.cacheControl !== void 0 ? Boolean(opts.cacheControl) : true;
@@ -24328,8 +24328,8 @@ var require_send = __commonJS({
24328
24328
  this._index = index2;
24329
24329
  return this;
24330
24330
  }, "send.index: pass index as option");
24331
- SendStream.prototype.root = function root(path23) {
24332
- this._root = resolve14(String(path23));
24331
+ SendStream.prototype.root = function root(path24) {
24332
+ this._root = resolve14(String(path24));
24333
24333
  debug("root %s", this._root);
24334
24334
  return this;
24335
24335
  };
@@ -24353,7 +24353,7 @@ var require_send = __commonJS({
24353
24353
  }
24354
24354
  var res = this.res;
24355
24355
  var msg = statuses.message[status] || String(status);
24356
- var doc = createHtmlDocument("Error", escapeHtml(msg));
24356
+ var doc = createHtmlDocument("Error", escapeHtml2(msg));
24357
24357
  clearHeaders(res);
24358
24358
  if (err && err.headers) {
24359
24359
  setHeaders(res, err.headers);
@@ -24442,10 +24442,10 @@ var require_send = __commonJS({
24442
24442
  var lastModified = this.res.getHeader("Last-Modified");
24443
24443
  return parseHttpDate(lastModified) <= parseHttpDate(ifRange);
24444
24444
  };
24445
- SendStream.prototype.redirect = function redirect(path23) {
24445
+ SendStream.prototype.redirect = function redirect(path24) {
24446
24446
  var res = this.res;
24447
24447
  if (hasListeners(this, "directory")) {
24448
- this.emit("directory", res, path23);
24448
+ this.emit("directory", res, path24);
24449
24449
  return;
24450
24450
  }
24451
24451
  if (this.hasTrailingSlash()) {
@@ -24453,7 +24453,7 @@ var require_send = __commonJS({
24453
24453
  return;
24454
24454
  }
24455
24455
  var loc = encodeUrl(collapseLeadingSlashes(this.path + "/"));
24456
- var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc));
24456
+ var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
24457
24457
  res.statusCode = 301;
24458
24458
  res.setHeader("Content-Type", "text/html; charset=UTF-8");
24459
24459
  res.setHeader("Content-Length", Buffer.byteLength(doc));
@@ -24465,42 +24465,42 @@ var require_send = __commonJS({
24465
24465
  SendStream.prototype.pipe = function pipe(res) {
24466
24466
  var root = this._root;
24467
24467
  this.res = res;
24468
- var path23 = decode(this.path);
24469
- if (path23 === -1) {
24468
+ var path24 = decode(this.path);
24469
+ if (path24 === -1) {
24470
24470
  this.error(400);
24471
24471
  return res;
24472
24472
  }
24473
- if (~path23.indexOf("\0")) {
24473
+ if (~path24.indexOf("\0")) {
24474
24474
  this.error(400);
24475
24475
  return res;
24476
24476
  }
24477
24477
  var parts;
24478
24478
  if (root !== null) {
24479
- if (path23) {
24480
- path23 = normalize("." + sep4 + path23);
24479
+ if (path24) {
24480
+ path24 = normalize("." + sep4 + path24);
24481
24481
  }
24482
- if (UP_PATH_REGEXP.test(path23)) {
24483
- debug('malicious path "%s"', path23);
24482
+ if (UP_PATH_REGEXP.test(path24)) {
24483
+ debug('malicious path "%s"', path24);
24484
24484
  this.error(403);
24485
24485
  return res;
24486
24486
  }
24487
- parts = path23.split(sep4);
24488
- path23 = normalize(join17(root, path23));
24487
+ parts = path24.split(sep4);
24488
+ path24 = normalize(join18(root, path24));
24489
24489
  } else {
24490
- if (UP_PATH_REGEXP.test(path23)) {
24491
- debug('malicious path "%s"', path23);
24490
+ if (UP_PATH_REGEXP.test(path24)) {
24491
+ debug('malicious path "%s"', path24);
24492
24492
  this.error(403);
24493
24493
  return res;
24494
24494
  }
24495
- parts = normalize(path23).split(sep4);
24496
- path23 = resolve14(path23);
24495
+ parts = normalize(path24).split(sep4);
24496
+ path24 = resolve14(path24);
24497
24497
  }
24498
24498
  if (containsDotFile(parts)) {
24499
24499
  var access = this._dotfiles;
24500
24500
  if (access === void 0) {
24501
24501
  access = parts[parts.length - 1][0] === "." ? this._hidden ? "allow" : "ignore" : "allow";
24502
24502
  }
24503
- debug('%s dotfile "%s"', access, path23);
24503
+ debug('%s dotfile "%s"', access, path24);
24504
24504
  switch (access) {
24505
24505
  case "allow":
24506
24506
  break;
@@ -24514,13 +24514,13 @@ var require_send = __commonJS({
24514
24514
  }
24515
24515
  }
24516
24516
  if (this._index.length && this.hasTrailingSlash()) {
24517
- this.sendIndex(path23);
24517
+ this.sendIndex(path24);
24518
24518
  return res;
24519
24519
  }
24520
- this.sendFile(path23);
24520
+ this.sendFile(path24);
24521
24521
  return res;
24522
24522
  };
24523
- SendStream.prototype.send = function send2(path23, stat) {
24523
+ SendStream.prototype.send = function send2(path24, stat) {
24524
24524
  var len = stat.size;
24525
24525
  var options = this.options;
24526
24526
  var opts = {};
@@ -24532,9 +24532,9 @@ var require_send = __commonJS({
24532
24532
  this.headersAlreadySent();
24533
24533
  return;
24534
24534
  }
24535
- debug('pipe "%s"', path23);
24536
- this.setHeader(path23, stat);
24537
- this.type(path23);
24535
+ debug('pipe "%s"', path24);
24536
+ this.setHeader(path24, stat);
24537
+ this.type(path24);
24538
24538
  if (this.isConditionalGET()) {
24539
24539
  if (this.isPreconditionFailure()) {
24540
24540
  this.error(412);
@@ -24583,28 +24583,28 @@ var require_send = __commonJS({
24583
24583
  res.end();
24584
24584
  return;
24585
24585
  }
24586
- this.stream(path23, opts);
24586
+ this.stream(path24, opts);
24587
24587
  };
24588
- SendStream.prototype.sendFile = function sendFile(path23) {
24588
+ SendStream.prototype.sendFile = function sendFile(path24) {
24589
24589
  var i = 0;
24590
24590
  var self2 = this;
24591
- debug('stat "%s"', path23);
24592
- fs21.stat(path23, function onstat(err, stat) {
24593
- if (err && err.code === "ENOENT" && !extname3(path23) && path23[path23.length - 1] !== sep4) {
24591
+ debug('stat "%s"', path24);
24592
+ fs22.stat(path24, function onstat(err, stat) {
24593
+ if (err && err.code === "ENOENT" && !extname3(path24) && path24[path24.length - 1] !== sep4) {
24594
24594
  return next(err);
24595
24595
  }
24596
24596
  if (err) return self2.onStatError(err);
24597
- if (stat.isDirectory()) return self2.redirect(path23);
24598
- self2.emit("file", path23, stat);
24599
- self2.send(path23, stat);
24597
+ if (stat.isDirectory()) return self2.redirect(path24);
24598
+ self2.emit("file", path24, stat);
24599
+ self2.send(path24, stat);
24600
24600
  });
24601
24601
  function next(err) {
24602
24602
  if (self2._extensions.length <= i) {
24603
24603
  return err ? self2.onStatError(err) : self2.error(404);
24604
24604
  }
24605
- var p = path23 + "." + self2._extensions[i++];
24605
+ var p = path24 + "." + self2._extensions[i++];
24606
24606
  debug('stat "%s"', p);
24607
- fs21.stat(p, function(err2, stat) {
24607
+ fs22.stat(p, function(err2, stat) {
24608
24608
  if (err2) return next(err2);
24609
24609
  if (stat.isDirectory()) return next();
24610
24610
  self2.emit("file", p, stat);
@@ -24612,7 +24612,7 @@ var require_send = __commonJS({
24612
24612
  });
24613
24613
  }
24614
24614
  };
24615
- SendStream.prototype.sendIndex = function sendIndex(path23) {
24615
+ SendStream.prototype.sendIndex = function sendIndex(path24) {
24616
24616
  var i = -1;
24617
24617
  var self2 = this;
24618
24618
  function next(err) {
@@ -24620,9 +24620,9 @@ var require_send = __commonJS({
24620
24620
  if (err) return self2.onStatError(err);
24621
24621
  return self2.error(404);
24622
24622
  }
24623
- var p = join17(path23, self2._index[i]);
24623
+ var p = join18(path24, self2._index[i]);
24624
24624
  debug('stat "%s"', p);
24625
- fs21.stat(p, function(err2, stat) {
24625
+ fs22.stat(p, function(err2, stat) {
24626
24626
  if (err2) return next(err2);
24627
24627
  if (stat.isDirectory()) return next();
24628
24628
  self2.emit("file", p, stat);
@@ -24631,10 +24631,10 @@ var require_send = __commonJS({
24631
24631
  }
24632
24632
  next();
24633
24633
  };
24634
- SendStream.prototype.stream = function stream(path23, options) {
24634
+ SendStream.prototype.stream = function stream(path24, options) {
24635
24635
  var self2 = this;
24636
24636
  var res = this.res;
24637
- var stream2 = fs21.createReadStream(path23, options);
24637
+ var stream2 = fs22.createReadStream(path24, options);
24638
24638
  this.emit("stream", stream2);
24639
24639
  stream2.pipe(res);
24640
24640
  function cleanup() {
@@ -24649,10 +24649,10 @@ var require_send = __commonJS({
24649
24649
  self2.emit("end");
24650
24650
  });
24651
24651
  };
24652
- SendStream.prototype.type = function type(path23) {
24652
+ SendStream.prototype.type = function type(path24) {
24653
24653
  var res = this.res;
24654
24654
  if (res.getHeader("Content-Type")) return;
24655
- var type2 = mime.lookup(path23);
24655
+ var type2 = mime.lookup(path24);
24656
24656
  if (!type2) {
24657
24657
  debug("no content-type");
24658
24658
  return;
@@ -24661,9 +24661,9 @@ var require_send = __commonJS({
24661
24661
  debug("content-type %s", type2);
24662
24662
  res.setHeader("Content-Type", type2 + (charset ? "; charset=" + charset : ""));
24663
24663
  };
24664
- SendStream.prototype.setHeader = function setHeader(path23, stat) {
24664
+ SendStream.prototype.setHeader = function setHeader(path24, stat) {
24665
24665
  var res = this.res;
24666
- this.emit("headers", res, path23, stat);
24666
+ this.emit("headers", res, path24, stat);
24667
24667
  if (this._acceptRanges && !res.getHeader("Accept-Ranges")) {
24668
24668
  debug("accept ranges");
24669
24669
  res.setHeader("Accept-Ranges", "bytes");
@@ -24722,9 +24722,9 @@ var require_send = __commonJS({
24722
24722
  }
24723
24723
  return err instanceof Error ? createError(status, err, { expose: false }) : createError(status, err);
24724
24724
  }
24725
- function decode(path23) {
24725
+ function decode(path24) {
24726
24726
  try {
24727
- return decodeURIComponent(path23);
24727
+ return decodeURIComponent(path24);
24728
24728
  } catch (err) {
24729
24729
  return -1;
24730
24730
  }
@@ -25634,10 +25634,10 @@ var require_utils2 = __commonJS({
25634
25634
  var querystring = require("querystring");
25635
25635
  exports2.etag = createETagGenerator({ weak: false });
25636
25636
  exports2.wetag = createETagGenerator({ weak: true });
25637
- exports2.isAbsolute = function(path22) {
25638
- if ("/" === path22[0]) return true;
25639
- if (":" === path22[1] && ("\\" === path22[2] || "/" === path22[2])) return true;
25640
- if ("\\\\" === path22.substring(0, 2)) return true;
25637
+ exports2.isAbsolute = function(path23) {
25638
+ if ("/" === path23[0]) return true;
25639
+ if (":" === path23[1] && ("\\" === path23[2] || "/" === path23[2])) return true;
25640
+ if ("\\\\" === path23.substring(0, 2)) return true;
25641
25641
  };
25642
25642
  exports2.flatten = deprecate.function(
25643
25643
  flatten,
@@ -25760,7 +25760,7 @@ var require_application = __commonJS({
25760
25760
  "../../node_modules/.pnpm/express@4.22.1/node_modules/express/lib/application.js"(exports2, module2) {
25761
25761
  "use strict";
25762
25762
  var finalhandler = require_finalhandler();
25763
- var Router13 = require_router();
25763
+ var Router14 = require_router();
25764
25764
  var methods = require_methods();
25765
25765
  var middleware = require_init();
25766
25766
  var query = require_query();
@@ -25825,7 +25825,7 @@ var require_application = __commonJS({
25825
25825
  };
25826
25826
  app.lazyrouter = function lazyrouter() {
25827
25827
  if (!this._router) {
25828
- this._router = new Router13({
25828
+ this._router = new Router14({
25829
25829
  caseSensitive: this.enabled("case sensitive routing"),
25830
25830
  strict: this.enabled("strict routing")
25831
25831
  });
@@ -25848,7 +25848,7 @@ var require_application = __commonJS({
25848
25848
  };
25849
25849
  app.use = function use(fn) {
25850
25850
  var offset = 0;
25851
- var path22 = "/";
25851
+ var path23 = "/";
25852
25852
  if (typeof fn !== "function") {
25853
25853
  var arg = fn;
25854
25854
  while (Array.isArray(arg) && arg.length !== 0) {
@@ -25856,7 +25856,7 @@ var require_application = __commonJS({
25856
25856
  }
25857
25857
  if (typeof arg !== "function") {
25858
25858
  offset = 1;
25859
- path22 = fn;
25859
+ path23 = fn;
25860
25860
  }
25861
25861
  }
25862
25862
  var fns = flatten(slice.call(arguments, offset));
@@ -25867,12 +25867,12 @@ var require_application = __commonJS({
25867
25867
  var router = this._router;
25868
25868
  fns.forEach(function(fn2) {
25869
25869
  if (!fn2 || !fn2.handle || !fn2.set) {
25870
- return router.use(path22, fn2);
25870
+ return router.use(path23, fn2);
25871
25871
  }
25872
- debug(".use app under %s", path22);
25873
- fn2.mountpath = path22;
25872
+ debug(".use app under %s", path23);
25873
+ fn2.mountpath = path23;
25874
25874
  fn2.parent = this;
25875
- router.use(path22, function mounted_app(req, res, next) {
25875
+ router.use(path23, function mounted_app(req, res, next) {
25876
25876
  var orig = req.app;
25877
25877
  fn2.handle(req, res, function(err) {
25878
25878
  setPrototypeOf(req, orig.request);
@@ -25884,9 +25884,9 @@ var require_application = __commonJS({
25884
25884
  }, this);
25885
25885
  return this;
25886
25886
  };
25887
- app.route = function route(path22) {
25887
+ app.route = function route(path23) {
25888
25888
  this.lazyrouter();
25889
- return this._router.route(path22);
25889
+ return this._router.route(path23);
25890
25890
  };
25891
25891
  app.engine = function engine(ext, fn) {
25892
25892
  if (typeof fn !== "function") {
@@ -25937,7 +25937,7 @@ var require_application = __commonJS({
25937
25937
  }
25938
25938
  return this;
25939
25939
  };
25940
- app.path = function path22() {
25940
+ app.path = function path23() {
25941
25941
  return this.parent ? this.parent.path() + this.mountpath : "";
25942
25942
  };
25943
25943
  app.enabled = function enabled2(setting) {
@@ -25953,19 +25953,19 @@ var require_application = __commonJS({
25953
25953
  return this.set(setting, false);
25954
25954
  };
25955
25955
  methods.forEach(function(method) {
25956
- app[method] = function(path22) {
25956
+ app[method] = function(path23) {
25957
25957
  if (method === "get" && arguments.length === 1) {
25958
- return this.set(path22);
25958
+ return this.set(path23);
25959
25959
  }
25960
25960
  this.lazyrouter();
25961
- var route = this._router.route(path22);
25961
+ var route = this._router.route(path23);
25962
25962
  route[method].apply(route, slice.call(arguments, 1));
25963
25963
  return this;
25964
25964
  };
25965
25965
  });
25966
- app.all = function all(path22) {
25966
+ app.all = function all(path23) {
25967
25967
  this.lazyrouter();
25968
- var route = this._router.route(path22);
25968
+ var route = this._router.route(path23);
25969
25969
  var args = slice.call(arguments, 1);
25970
25970
  for (var i = 0; i < methods.length; i++) {
25971
25971
  route[methods[i]].apply(route, args);
@@ -26724,7 +26724,7 @@ var require_request = __commonJS({
26724
26724
  var subdomains2 = !isIP(hostname3) ? hostname3.split(".").reverse() : [hostname3];
26725
26725
  return subdomains2.slice(offset);
26726
26726
  });
26727
- defineGetter(req, "path", function path22() {
26727
+ defineGetter(req, "path", function path23() {
26728
26728
  return parse(this).pathname;
26729
26729
  });
26730
26730
  defineGetter(req, "hostname", function hostname3() {
@@ -27043,11 +27043,11 @@ var require_response = __commonJS({
27043
27043
  var createError = require_http_errors();
27044
27044
  var deprecate = require_depd()("express");
27045
27045
  var encodeUrl = require_encodeurl();
27046
- var escapeHtml = require_escape_html();
27046
+ var escapeHtml2 = require_escape_html();
27047
27047
  var http3 = require("http");
27048
27048
  var isAbsolute4 = require_utils2().isAbsolute;
27049
27049
  var onFinished = require_on_finished();
27050
- var path22 = require("path");
27050
+ var path23 = require("path");
27051
27051
  var statuses = require_statuses();
27052
27052
  var merge = require_utils_merge();
27053
27053
  var sign = require_cookie_signature().sign;
@@ -27056,9 +27056,9 @@ var require_response = __commonJS({
27056
27056
  var setCharset = require_utils2().setCharset;
27057
27057
  var cookie = require_cookie();
27058
27058
  var send = require_send();
27059
- var extname3 = path22.extname;
27059
+ var extname3 = path23.extname;
27060
27060
  var mime = send.mime;
27061
- var resolve14 = path22.resolve;
27061
+ var resolve14 = path23.resolve;
27062
27062
  var vary = require_vary();
27063
27063
  var res = Object.create(http3.ServerResponse.prototype);
27064
27064
  module2.exports = res;
@@ -27235,26 +27235,26 @@ var require_response = __commonJS({
27235
27235
  this.type("txt");
27236
27236
  return this.send(body);
27237
27237
  };
27238
- res.sendFile = function sendFile(path23, options, callback) {
27238
+ res.sendFile = function sendFile(path24, options, callback) {
27239
27239
  var done = callback;
27240
27240
  var req = this.req;
27241
27241
  var res2 = this;
27242
27242
  var next = req.next;
27243
27243
  var opts = options || {};
27244
- if (!path23) {
27244
+ if (!path24) {
27245
27245
  throw new TypeError("path argument is required to res.sendFile");
27246
27246
  }
27247
- if (typeof path23 !== "string") {
27247
+ if (typeof path24 !== "string") {
27248
27248
  throw new TypeError("path must be a string to res.sendFile");
27249
27249
  }
27250
27250
  if (typeof options === "function") {
27251
27251
  done = options;
27252
27252
  opts = {};
27253
27253
  }
27254
- if (!opts.root && !isAbsolute4(path23)) {
27254
+ if (!opts.root && !isAbsolute4(path24)) {
27255
27255
  throw new TypeError("path must be absolute or specify root to res.sendFile");
27256
27256
  }
27257
- var pathname = encodeURI(path23);
27257
+ var pathname = encodeURI(path24);
27258
27258
  var file = send(req, pathname, opts);
27259
27259
  sendfile(res2, file, opts, function(err) {
27260
27260
  if (done) return done(err);
@@ -27264,7 +27264,7 @@ var require_response = __commonJS({
27264
27264
  }
27265
27265
  });
27266
27266
  };
27267
- res.sendfile = function(path23, options, callback) {
27267
+ res.sendfile = function(path24, options, callback) {
27268
27268
  var done = callback;
27269
27269
  var req = this.req;
27270
27270
  var res2 = this;
@@ -27274,7 +27274,7 @@ var require_response = __commonJS({
27274
27274
  done = options;
27275
27275
  opts = {};
27276
27276
  }
27277
- var file = send(req, path23, opts);
27277
+ var file = send(req, path24, opts);
27278
27278
  sendfile(res2, file, opts, function(err) {
27279
27279
  if (done) return done(err);
27280
27280
  if (err && err.code === "EISDIR") return next();
@@ -27287,7 +27287,7 @@ var require_response = __commonJS({
27287
27287
  res.sendfile,
27288
27288
  "res.sendfile: Use res.sendFile instead"
27289
27289
  );
27290
- res.download = function download(path23, filename, options, callback) {
27290
+ res.download = function download(path24, filename, options, callback) {
27291
27291
  var done = callback;
27292
27292
  var name2 = filename;
27293
27293
  var opts = options || null;
@@ -27304,7 +27304,7 @@ var require_response = __commonJS({
27304
27304
  opts = filename;
27305
27305
  }
27306
27306
  var headers = {
27307
- "Content-Disposition": contentDisposition(name2 || path23)
27307
+ "Content-Disposition": contentDisposition(name2 || path24)
27308
27308
  };
27309
27309
  if (opts && opts.headers) {
27310
27310
  var keys = Object.keys(opts.headers);
@@ -27317,7 +27317,7 @@ var require_response = __commonJS({
27317
27317
  }
27318
27318
  opts = Object.create(opts);
27319
27319
  opts.headers = headers;
27320
- var fullPath = !opts.root ? resolve14(path23) : path23;
27320
+ var fullPath = !opts.root ? resolve14(path24) : path24;
27321
27321
  return this.sendFile(fullPath, opts, done);
27322
27322
  };
27323
27323
  res.contentType = res.type = function contentType(type) {
@@ -27449,7 +27449,7 @@ var require_response = __commonJS({
27449
27449
  body = statuses.message[status] + ". Redirecting to " + address;
27450
27450
  },
27451
27451
  html: function() {
27452
- var u = escapeHtml(address);
27452
+ var u = escapeHtml2(address);
27453
27453
  body = "<p>" + statuses.message[status] + ". Redirecting to " + u + "</p>";
27454
27454
  },
27455
27455
  default: function() {
@@ -27581,7 +27581,7 @@ var require_serve_static = __commonJS({
27581
27581
  "../../node_modules/.pnpm/serve-static@1.16.3/node_modules/serve-static/index.js"(exports2, module2) {
27582
27582
  "use strict";
27583
27583
  var encodeUrl = require_encodeurl();
27584
- var escapeHtml = require_escape_html();
27584
+ var escapeHtml2 = require_escape_html();
27585
27585
  var parseUrl = require_parseurl();
27586
27586
  var resolve14 = require("path").resolve;
27587
27587
  var send = require_send();
@@ -27618,11 +27618,11 @@ var require_serve_static = __commonJS({
27618
27618
  }
27619
27619
  var forwardError = !fallthrough;
27620
27620
  var originalUrl = parseUrl.original(req);
27621
- var path22 = parseUrl(req).pathname;
27622
- if (path22 === "/" && originalUrl.pathname.substr(-1) !== "/") {
27623
- path22 = "";
27621
+ var path23 = parseUrl(req).pathname;
27622
+ if (path23 === "/" && originalUrl.pathname.substr(-1) !== "/") {
27623
+ path23 = "";
27624
27624
  }
27625
- var stream = send(req, path22, opts);
27625
+ var stream = send(req, path23, opts);
27626
27626
  stream.on("directory", onDirectory);
27627
27627
  if (setHeaders) {
27628
27628
  stream.on("headers", setHeaders);
@@ -27668,7 +27668,7 @@ var require_serve_static = __commonJS({
27668
27668
  originalUrl.path = null;
27669
27669
  originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/");
27670
27670
  var loc = encodeUrl(url.format(originalUrl));
27671
- var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc));
27671
+ var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
27672
27672
  res.statusCode = 301;
27673
27673
  res.setHeader("Content-Type", "text/html; charset=UTF-8");
27674
27674
  res.setHeader("Content-Length", Buffer.byteLength(doc));
@@ -27690,7 +27690,7 @@ var require_express = __commonJS({
27690
27690
  var mixin = require_merge_descriptors();
27691
27691
  var proto = require_application();
27692
27692
  var Route = require_route();
27693
- var Router13 = require_router();
27693
+ var Router14 = require_router();
27694
27694
  var req = require_request();
27695
27695
  var res = require_response();
27696
27696
  exports2 = module2.exports = createApplication;
@@ -27713,7 +27713,7 @@ var require_express = __commonJS({
27713
27713
  exports2.request = req;
27714
27714
  exports2.response = res;
27715
27715
  exports2.Route = Route;
27716
- exports2.Router = Router13;
27716
+ exports2.Router = Router14;
27717
27717
  exports2.json = bodyParser.json;
27718
27718
  exports2.query = require_query();
27719
27719
  exports2.raw = bodyParser.raw;
@@ -32265,11 +32265,11 @@ function persistNodeStartupTransport(storagePath, transport) {
32265
32265
  transport
32266
32266
  });
32267
32267
  }
32268
- function persistNodeStartupJoin(storagePath, join17) {
32268
+ function persistNodeStartupJoin(storagePath, join18) {
32269
32269
  const startup = resolveNodeStartupMetadata(storagePath);
32270
32270
  persistNodeStartupMetadata(storagePath, {
32271
32271
  ...startup,
32272
- join: join17
32272
+ join: join18
32273
32273
  });
32274
32274
  }
32275
32275
  function resolvePersistedDevTunnelId(storagePath, kind) {
@@ -33266,19 +33266,19 @@ async function fetchWithTimeout(url, init, timeoutMs = DEFAULT_NODE_REQUEST_TIME
33266
33266
  cleanup();
33267
33267
  }
33268
33268
  }
33269
- async function fetchNodeWithFallback(node, path22, init, timeoutMs = DEFAULT_NODE_REQUEST_TIMEOUT_MS, trace, options) {
33269
+ async function fetchNodeWithFallback(node, path23, init, timeoutMs = DEFAULT_NODE_REQUEST_TIMEOUT_MS, trace, options) {
33270
33270
  let lastError;
33271
33271
  const endpoints = getNodeRequestEndpoints(node, options);
33272
33272
  for (const [index, endpoint] of endpoints.entries()) {
33273
33273
  const attempt = index + 1;
33274
- trace?.onAttempt?.({ attempt, endpoint, path: path22, timeoutMs, totalEndpoints: endpoints.length });
33274
+ trace?.onAttempt?.({ attempt, endpoint, path: path23, timeoutMs, totalEndpoints: endpoints.length });
33275
33275
  try {
33276
- const response = await fetchWithTimeout(`${endpoint}${path22}`, init, timeoutMs);
33277
- trace?.onResponse?.({ attempt, endpoint, path: path22, response, timeoutMs, totalEndpoints: endpoints.length });
33276
+ const response = await fetchWithTimeout(`${endpoint}${path23}`, init, timeoutMs);
33277
+ trace?.onResponse?.({ attempt, endpoint, path: path23, response, timeoutMs, totalEndpoints: endpoints.length });
33278
33278
  return { endpoint, response };
33279
33279
  } catch (error) {
33280
33280
  lastError = error;
33281
- trace?.onError?.({ attempt, endpoint, error, path: path22, timeoutMs, totalEndpoints: endpoints.length });
33281
+ trace?.onError?.({ attempt, endpoint, error, path: path23, timeoutMs, totalEndpoints: endpoints.length });
33282
33282
  }
33283
33283
  }
33284
33284
  throw lastError instanceof Error ? lastError : new Error("No reachable node endpoint");
@@ -34555,6 +34555,7 @@ var NODE_KIND_BY_LEGACY = {
34555
34555
  "node-workdir-branch-create": "node.workdir.branch-create",
34556
34556
  "node-sessions-list": "node.sessions.list",
34557
34557
  devtunnel: "node.transport.set",
34558
+ "node-agent-upgrade": "node.agent.upgrade",
34558
34559
  "task-cancel": "task.cancel",
34559
34560
  "task-logs": "task.logs",
34560
34561
  "task-output-summary": "task.output.summary",
@@ -35320,9 +35321,9 @@ var DataRouter = class {
35320
35321
  /**
35321
35322
  * Returns true if the request should be proxied to the leader.
35322
35323
  */
35323
- shouldProxy(method, path22) {
35324
+ shouldProxy(method, path23) {
35324
35325
  if (this.election.isLeader()) return false;
35325
- if (this.isExcludedPath(path22)) return false;
35326
+ if (this.isExcludedPath(path23)) return false;
35326
35327
  if (method.toUpperCase() === "GET") return false;
35327
35328
  return WRITE_METHODS.has(method.toUpperCase());
35328
35329
  }
@@ -35426,8 +35427,8 @@ var DataRouter = class {
35426
35427
  };
35427
35428
  }
35428
35429
  // ── Helpers ───────────────────────────────────────────────────────────
35429
- isExcludedPath(path22) {
35430
- return EXCLUDED_PATH_PREFIXES.some((prefix) => path22.startsWith(prefix)) || EXCLUDED_PATH_SUFFIXES.some((suffix) => path22.endsWith(suffix));
35430
+ isExcludedPath(path23) {
35431
+ return EXCLUDED_PATH_PREFIXES.some((prefix) => path23.startsWith(prefix)) || EXCLUDED_PATH_SUFFIXES.some((suffix) => path23.endsWith(suffix));
35431
35432
  }
35432
35433
  };
35433
35434
 
@@ -35601,6 +35602,9 @@ function compareUpdatedSessions(left, right) {
35601
35602
  const rightTime = right.updatedAt ? Date.parse(right.updatedAt) : 0;
35602
35603
  return rightTime - leftTime || left.sessionId.localeCompare(right.sessionId);
35603
35604
  }
35605
+ function getNativeHomeDir() {
35606
+ return process.env.HOME || process.env.USERPROFILE || os4.homedir();
35607
+ }
35604
35608
  function findMatchingFiles(rootDir, predicate) {
35605
35609
  if (!fs7.existsSync(rootDir)) {
35606
35610
  return [];
@@ -35747,7 +35751,7 @@ function findClaudeSessionSummary(entries, sessionId) {
35747
35751
  };
35748
35752
  }
35749
35753
  function loadCodexSessionIndex() {
35750
- const indexPath = path7.join(os4.homedir(), ".codex", "session_index.jsonl");
35754
+ const indexPath = path7.join(getNativeHomeDir(), ".codex", "session_index.jsonl");
35751
35755
  const index = /* @__PURE__ */ new Map();
35752
35756
  for (const entry of readJsonLines(indexPath)) {
35753
35757
  if (typeof entry.id !== "string" || !entry.id.trim()) {
@@ -35797,7 +35801,7 @@ function findCodexSessionSummary(entries, filePath, sessionIndex) {
35797
35801
  };
35798
35802
  }
35799
35803
  function loadClaudeSessionHistory(sessionId) {
35800
- const projectsDir = path7.join(os4.homedir(), ".claude", "projects");
35804
+ const projectsDir = path7.join(getNativeHomeDir(), ".claude", "projects");
35801
35805
  const sessionFile = findFirstMatchingFile(projectsDir, (filePath) => {
35802
35806
  if (filePath.includes(`${path7.sep}subagents${path7.sep}`)) {
35803
35807
  return false;
@@ -35816,7 +35820,7 @@ function loadClaudeSessionHistory(sessionId) {
35816
35820
  return { logs, sourcePath: sessionFile };
35817
35821
  }
35818
35822
  function loadCodexSessionHistory(sessionId) {
35819
- const sessionsDir = path7.join(os4.homedir(), ".codex", "sessions");
35823
+ const sessionsDir = path7.join(getNativeHomeDir(), ".codex", "sessions");
35820
35824
  const sessionFile = findFirstMatchingFile(sessionsDir, (filePath) => path7.basename(filePath).toLowerCase().includes(sessionId.toLowerCase()) && filePath.toLowerCase().endsWith(".jsonl"));
35821
35825
  if (!sessionFile) {
35822
35826
  return { logs: [], sourcePath: null };
@@ -35852,7 +35856,7 @@ function loadNativeSessionHistory(input) {
35852
35856
  function listNativeSessions(input) {
35853
35857
  const limit = Math.min(Math.max(1, input.limit ?? 50), 100);
35854
35858
  if (input.agent === "claudecode") {
35855
- const projectsDir = path7.join(os4.homedir(), ".claude", "projects");
35859
+ const projectsDir = path7.join(getNativeHomeDir(), ".claude", "projects");
35856
35860
  return findMatchingFiles(projectsDir, (filePath) => {
35857
35861
  if (filePath.includes(`${path7.sep}subagents${path7.sep}`)) {
35858
35862
  return false;
@@ -35871,7 +35875,7 @@ function listNativeSessions(input) {
35871
35875
  }).filter((session) => session !== null).sort(compareUpdatedSessions).slice(0, limit);
35872
35876
  }
35873
35877
  const sessionIndex = loadCodexSessionIndex();
35874
- const sessionsDir = path7.join(os4.homedir(), ".codex", "sessions");
35878
+ const sessionsDir = path7.join(getNativeHomeDir(), ".codex", "sessions");
35875
35879
  return findMatchingFiles(sessionsDir, (filePath) => filePath.toLowerCase().endsWith(".jsonl")).map((filePath) => {
35876
35880
  const summary = findCodexSessionSummary(readJsonLines(filePath), filePath, sessionIndex);
35877
35881
  if (!summary) {
@@ -37103,6 +37107,7 @@ var LEGACY_FILES = [
37103
37107
  "nodes.json",
37104
37108
  "tasks.json",
37105
37109
  "shares.json",
37110
+ "node-operations.json",
37106
37111
  "election.json"
37107
37112
  ];
37108
37113
  var LEGACY_DIRS = ["logs", "task-logs"];
@@ -38287,7 +38292,7 @@ async function apiFetch(ctx, port, apiPath) {
38287
38292
  const body = await res.json().catch(() => null);
38288
38293
  throw new Error(body?.error?.message ?? `API error: ${res.status} ${res.statusText}`);
38289
38294
  }
38290
- return res.json();
38295
+ return await res.json();
38291
38296
  }
38292
38297
  async function apiWrite(ctx, method, port, apiPath, body) {
38293
38298
  const res = await ctx.fetchImpl(`http://localhost:${port}${apiPath}`, {
@@ -38299,7 +38304,7 @@ async function apiWrite(ctx, method, port, apiPath, body) {
38299
38304
  const data = await res.json().catch(() => null);
38300
38305
  throw new Error(data?.error?.message ?? `HTTP ${res.status}`);
38301
38306
  }
38302
- return res.json();
38307
+ return await res.json();
38303
38308
  }
38304
38309
  function writeLines(stream, lines) {
38305
38310
  stream.write(`${lines.join("\n")}
@@ -39201,8 +39206,8 @@ function getErrorMap() {
39201
39206
 
39202
39207
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
39203
39208
  var makeIssue = (params) => {
39204
- const { data, path: path22, errorMaps, issueData } = params;
39205
- const fullPath = [...path22, ...issueData.path || []];
39209
+ const { data, path: path23, errorMaps, issueData } = params;
39210
+ const fullPath = [...path23, ...issueData.path || []];
39206
39211
  const fullIssue = {
39207
39212
  ...issueData,
39208
39213
  path: fullPath
@@ -39318,11 +39323,11 @@ var errorUtil;
39318
39323
 
39319
39324
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
39320
39325
  var ParseInputLazyPath = class {
39321
- constructor(parent, value, path22, key) {
39326
+ constructor(parent, value, path23, key) {
39322
39327
  this._cachedPath = [];
39323
39328
  this.parent = parent;
39324
39329
  this.data = value;
39325
- this._path = path22;
39330
+ this._path = path23;
39326
39331
  this._key = key;
39327
39332
  }
39328
39333
  get path() {
@@ -42827,7 +42832,15 @@ var SystemAgentInfoSchema = external_exports.object({
42827
42832
  version: external_exports.string().nullable(),
42828
42833
  checkedAt: external_exports.string(),
42829
42834
  detail: external_exports.string().nullable().optional(),
42830
- metadataStatus: external_exports.string().nullable().optional()
42835
+ metadataStatus: external_exports.string().nullable().optional(),
42836
+ update: external_exports.object({
42837
+ packageName: external_exports.string(),
42838
+ currentVersion: external_exports.string().nullable(),
42839
+ latestVersion: external_exports.string().nullable(),
42840
+ updateAvailable: external_exports.boolean(),
42841
+ checkedAt: external_exports.string(),
42842
+ detail: external_exports.string().nullable().optional()
42843
+ }).optional()
42831
42844
  });
42832
42845
  var NodeSettingsSnapshotSchema = external_exports.object({
42833
42846
  collectedAt: external_exports.number(),
@@ -43207,16 +43220,17 @@ var TaskOutputContentQuery = external_exports.object({
43207
43220
  });
43208
43221
  var TaskOutputDownloadQuery = TaskOutputContentQuery;
43209
43222
  var TaskPreviewSessionBody = external_exports.object({
43210
- path: external_exports.string().min(1).optional()
43223
+ path: external_exports.string().min(1).optional(),
43224
+ port: external_exports.coerce.number().int().min(1).max(65535).optional()
43211
43225
  });
43212
43226
  var BatchTaskIdsBody = external_exports.object({
43213
43227
  ids: external_exports.array(external_exports.string().min(1)).min(1).max(50)
43214
43228
  });
43215
43229
 
43216
43230
  // ../../packages/api/src/app/server.ts
43217
- var path19 = __toESM(require("path"), 1);
43218
- var fs18 = __toESM(require("fs"), 1);
43219
- var import_express13 = __toESM(require_express2(), 1);
43231
+ var path20 = __toESM(require("path"), 1);
43232
+ var fs19 = __toESM(require("fs"), 1);
43233
+ var import_express14 = __toESM(require_express2(), 1);
43220
43234
 
43221
43235
  // ../../packages/api/src/middleware/auth.ts
43222
43236
  var SKIP_AUTH_PATHS = ["/api/system/health"];
@@ -43342,8 +43356,91 @@ function createAuthMiddleware(config) {
43342
43356
  }
43343
43357
 
43344
43358
  // ../../packages/api/src/middleware/routing.ts
43345
- function createRoutingMiddleware(dataRouter) {
43346
- return dataRouter.createMiddleware();
43359
+ function isRoutingMiddlewareDeps(input) {
43360
+ return "dataRouter" in input;
43361
+ }
43362
+ function decodePathSegment(value) {
43363
+ try {
43364
+ return decodeURIComponent(value);
43365
+ } catch {
43366
+ return value;
43367
+ }
43368
+ }
43369
+ function getSingleTaskDeleteId(path23) {
43370
+ const match = /^\/api\/tasks\/([^/]+)$/.exec(path23);
43371
+ return match ? decodePathSegment(match[1]) : null;
43372
+ }
43373
+ function getSuccessfulBatchDeleteIds(body) {
43374
+ if (!body || typeof body !== "object" || !Array.isArray(body.results)) {
43375
+ return [];
43376
+ }
43377
+ return body.results.flatMap((result) => {
43378
+ if (!result || typeof result !== "object") return [];
43379
+ const item = result;
43380
+ return item.ok === true && typeof item.id === "string" ? [item.id] : [];
43381
+ });
43382
+ }
43383
+ function getProxiedDeleteIds(req, result) {
43384
+ if (result.status < 200 || result.status >= 300) {
43385
+ return [];
43386
+ }
43387
+ const method = req.method.toUpperCase();
43388
+ if (method === "DELETE") {
43389
+ const taskId = getSingleTaskDeleteId(req.path);
43390
+ return taskId ? [taskId] : [];
43391
+ }
43392
+ if (method === "POST" && req.path === "/api/tasks/batch/delete") {
43393
+ return getSuccessfulBatchDeleteIds(result.body);
43394
+ }
43395
+ return [];
43396
+ }
43397
+ function evictLocalTaskMirrors(taskEngine, logger27, taskIds) {
43398
+ if (!taskEngine || taskIds.length === 0) return;
43399
+ for (const taskId of taskIds) {
43400
+ try {
43401
+ taskEngine.deleteTask(taskId);
43402
+ } catch (err) {
43403
+ logger27?.child("routing")?.warn("failed to evict follower-local task mirror after proxied delete", {
43404
+ taskId,
43405
+ error: err instanceof Error ? err.message : String(err)
43406
+ });
43407
+ }
43408
+ }
43409
+ }
43410
+ function createRoutingMiddleware(input) {
43411
+ const deps = isRoutingMiddlewareDeps(input) ? input : { dataRouter: input };
43412
+ const { dataRouter, taskEngine, logger: logger27 } = deps;
43413
+ return async (req, res, next) => {
43414
+ if (!dataRouter.shouldProxy(req.method, req.path)) {
43415
+ next();
43416
+ return;
43417
+ }
43418
+ const leaderEndpoint = dataRouter.getLeaderEndpoint();
43419
+ if (!leaderEndpoint) {
43420
+ res.status(503).json({
43421
+ error: { code: "NO_LEADER", message: "No leader available" }
43422
+ });
43423
+ return;
43424
+ }
43425
+ try {
43426
+ const result = await dataRouter.proxyToLeader(req);
43427
+ evictLocalTaskMirrors(taskEngine, logger27, getProxiedDeleteIds(req, result));
43428
+ for (const [key, value] of Object.entries(result.headers)) {
43429
+ res.setHeader(key, value);
43430
+ }
43431
+ res.status(result.status).json(result.body);
43432
+ } catch (err) {
43433
+ if (err instanceof MeshyError) {
43434
+ res.status(err.statusCode).json({
43435
+ error: { code: err.code, message: err.message }
43436
+ });
43437
+ return;
43438
+ }
43439
+ res.status(502).json({
43440
+ error: { code: "NODE_OFFLINE", message: "Leader unreachable" }
43441
+ });
43442
+ }
43443
+ };
43347
43444
  }
43348
43445
 
43349
43446
  // ../../packages/api/src/middleware/error.ts
@@ -43894,9 +43991,33 @@ function detectHtmlEntries(root) {
43894
43991
  }
43895
43992
  return entries;
43896
43993
  }
43994
+ function detectMarkdownEntries(root) {
43995
+ const entries = [];
43996
+ try {
43997
+ const topLevel = fs14.readdirSync(root, { withFileTypes: true });
43998
+ for (const f of topLevel) {
43999
+ if (f.isFile() && !f.name.startsWith(".") && /\.mdx?$/i.test(f.name)) {
44000
+ entries.push({ path: f.name, label: f.name });
44001
+ }
44002
+ }
44003
+ const subdirs = topLevel.filter((e) => e.isDirectory() && !e.name.startsWith("."));
44004
+ for (const dir of subdirs) {
44005
+ for (const fileName of ["README.md", "readme.md"]) {
44006
+ const readmePath = path15.join(root, dir.name, fileName);
44007
+ if (fs14.existsSync(readmePath)) {
44008
+ entries.push({ path: `${dir.name}/${fileName}`, label: `${dir.name}/${fileName}` });
44009
+ break;
44010
+ }
44011
+ }
44012
+ }
44013
+ } catch {
44014
+ }
44015
+ return entries;
44016
+ }
43897
44017
  function getOutputSummary(root) {
43898
44018
  const rootName = path15.basename(root);
43899
44019
  const htmlEntries = detectHtmlEntries(root);
44020
+ const markdownEntries = detectMarkdownEntries(root);
43900
44021
  let fileCount;
43901
44022
  try {
43902
44023
  const entries = fs14.readdirSync(root, { withFileTypes: true });
@@ -43909,6 +44030,7 @@ function getOutputSummary(root) {
43909
44030
  rootName,
43910
44031
  fileCount,
43911
44032
  htmlEntries,
44033
+ markdownEntries,
43912
44034
  git: null
43913
44035
  // filled in by Git diff API later
43914
44036
  };
@@ -44152,7 +44274,7 @@ function getGitDiff(dirPath) {
44152
44274
  const branch = git2(["rev-parse", "--abbrev-ref", "HEAD"], dirPath) || null;
44153
44275
  const staged = git2(["diff", "--cached"], dirPath);
44154
44276
  const unstaged = git2(["diff"], dirPath);
44155
- const statusOutput = git2(["status", "--porcelain"], dirPath);
44277
+ const statusOutput = git2(["status", "--porcelain", "-uall"], dirPath);
44156
44278
  const changedFiles = [];
44157
44279
  const untrackedFiles = [];
44158
44280
  for (const line of statusOutput.split("\n")) {
@@ -44377,6 +44499,8 @@ function sendLocalNodeWorkDirBranchCreate(req, res, nodeId, options = {}) {
44377
44499
 
44378
44500
  // ../../packages/api/src/tasks/task-route-utils.ts
44379
44501
  var fs15 = __toESM(require("fs"), 1);
44502
+ var import_node_stream2 = require("stream");
44503
+ var import_promises5 = require("stream/promises");
44380
44504
 
44381
44505
  // ../../packages/api/src/node/node-message-compat.ts
44382
44506
  var LEGACY_KIND_BY_NODE_MESSAGE = {
@@ -44385,6 +44509,7 @@ var LEGACY_KIND_BY_NODE_MESSAGE = {
44385
44509
  "node.workdir.branch-create": "node-workdir-branch-create",
44386
44510
  "node.sessions.list": "node-sessions-list",
44387
44511
  "node.transport.set": "devtunnel",
44512
+ "node.agent.upgrade": "node-agent-upgrade",
44388
44513
  "task.cancel": "task-cancel",
44389
44514
  "task.logs": "task-logs",
44390
44515
  "task.output.summary": "task-output-summary",
@@ -44608,10 +44733,27 @@ async function sendProxyResponse(res, proxyRes) {
44608
44733
  const contentType = proxyRes.headers.get("content-type");
44609
44734
  const contentDisposition = proxyRes.headers.get("content-disposition");
44610
44735
  const cacheControl = proxyRes.headers.get("cache-control");
44611
- const body = Buffer.from(await proxyRes.arrayBuffer());
44612
44736
  if (contentType) res.setHeader("Content-Type", contentType);
44613
44737
  if (contentDisposition) res.setHeader("Content-Disposition", contentDisposition);
44614
44738
  if (cacheControl) res.setHeader("Cache-Control", cacheControl);
44739
+ if (contentType?.split(";")[0]?.trim().toLowerCase() === "text/event-stream") {
44740
+ if (!cacheControl) res.setHeader("Cache-Control", "no-cache");
44741
+ res.status(proxyRes.status);
44742
+ res.flushHeaders();
44743
+ if (!proxyRes.body) {
44744
+ res.end();
44745
+ return;
44746
+ }
44747
+ try {
44748
+ await (0, import_promises5.pipeline)(import_node_stream2.Readable.fromWeb(proxyRes.body), res);
44749
+ } catch (error) {
44750
+ if (!res.destroyed && !res.writableEnded) {
44751
+ throw error;
44752
+ }
44753
+ }
44754
+ return;
44755
+ }
44756
+ const body = Buffer.from(await proxyRes.arrayBuffer());
44615
44757
  res.status(proxyRes.status).send(body);
44616
44758
  }
44617
44759
  async function maybeProxyReadToLeader(req, res, options = {}) {
@@ -44720,6 +44862,114 @@ var crypto3 = __toESM(require("crypto"), 1);
44720
44862
  var fs16 = __toESM(require("fs"), 1);
44721
44863
  var path17 = __toESM(require("path"), 1);
44722
44864
  var http2 = __toESM(require("http"), 1);
44865
+ var import_node_stream3 = require("stream");
44866
+ var import_promises6 = require("stream/promises");
44867
+
44868
+ // ../../packages/api/src/preview/preview-request.ts
44869
+ var PREVIEW_AUTHORIZATION_HEADER = "x-meshy-preview-authorization";
44870
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
44871
+ "connection",
44872
+ "keep-alive",
44873
+ "proxy-authenticate",
44874
+ "proxy-authorization",
44875
+ "te",
44876
+ "trailer",
44877
+ "transfer-encoding",
44878
+ "upgrade"
44879
+ ]);
44880
+ function isReadOnlyPreviewMethod(method) {
44881
+ const normalizedMethod = method?.toUpperCase() ?? "GET";
44882
+ return normalizedMethod === "GET" || normalizedMethod === "HEAD";
44883
+ }
44884
+ function methodAllowsRequestBody(method) {
44885
+ return !isReadOnlyPreviewMethod(method);
44886
+ }
44887
+ function toArrayBuffer(value) {
44888
+ const copy = new Uint8Array(value.byteLength);
44889
+ copy.set(value);
44890
+ return copy.buffer;
44891
+ }
44892
+ function getParsedRequestBody(req) {
44893
+ const body = req.body;
44894
+ if (body === void 0) {
44895
+ return void 0;
44896
+ }
44897
+ if (typeof body === "string" || body instanceof URLSearchParams || body instanceof Blob || body instanceof FormData) {
44898
+ return body;
44899
+ }
44900
+ if (Buffer.isBuffer(body)) {
44901
+ return toArrayBuffer(body);
44902
+ }
44903
+ if (body instanceof Uint8Array) {
44904
+ return toArrayBuffer(body);
44905
+ }
44906
+ return JSON.stringify(body);
44907
+ }
44908
+ async function readPreviewRequestBody(req) {
44909
+ if (!req || !methodAllowsRequestBody(req.method)) {
44910
+ return void 0;
44911
+ }
44912
+ const parsedBody = getParsedRequestBody(req);
44913
+ if (parsedBody !== void 0) {
44914
+ return parsedBody;
44915
+ }
44916
+ const chunks = [];
44917
+ for await (const chunk of req) {
44918
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
44919
+ }
44920
+ return chunks.length > 0 ? toArrayBuffer(Buffer.concat(chunks)) : void 0;
44921
+ }
44922
+ function buildServiceProxyHeaders(req) {
44923
+ const headers = {};
44924
+ if (!req) {
44925
+ return headers;
44926
+ }
44927
+ let previewAuthorization;
44928
+ for (const [key, value] of Object.entries(req.headers)) {
44929
+ const normalizedKey = key.toLowerCase();
44930
+ if (HOP_BY_HOP_HEADERS.has(normalizedKey) || normalizedKey === "host" || normalizedKey === "content-length" || normalizedKey === "forwarded" || normalizedKey === "x-real-ip" || normalizedKey.startsWith("x-forwarded-") || normalizedKey === MESHY_AUTHORIZATION_HEADER) {
44931
+ continue;
44932
+ }
44933
+ if (normalizedKey === PREVIEW_AUTHORIZATION_HEADER) {
44934
+ previewAuthorization = Array.isArray(value) ? value[0] : value;
44935
+ continue;
44936
+ }
44937
+ if (Array.isArray(value)) {
44938
+ headers[key] = value.join(", ");
44939
+ } else if (typeof value === "string") {
44940
+ headers[key] = value;
44941
+ }
44942
+ }
44943
+ if (previewAuthorization && !headers.authorization) {
44944
+ headers.authorization = previewAuthorization;
44945
+ }
44946
+ return headers;
44947
+ }
44948
+ function buildPreviewWorkerProxyHeaders(req) {
44949
+ const headers = {};
44950
+ let previewAuthorization;
44951
+ for (const [key, value] of Object.entries(req.headers)) {
44952
+ const normalizedKey = key.toLowerCase();
44953
+ if (HOP_BY_HOP_HEADERS.has(normalizedKey) || normalizedKey === "host" || normalizedKey === "content-length" || normalizedKey === MESHY_AUTHORIZATION_HEADER || normalizedKey === PREVIEW_AUTHORIZATION_HEADER) {
44954
+ continue;
44955
+ }
44956
+ if (normalizedKey === "authorization") {
44957
+ previewAuthorization = Array.isArray(value) ? value[0] : value;
44958
+ continue;
44959
+ }
44960
+ if (Array.isArray(value)) {
44961
+ headers[key] = value.join(", ");
44962
+ } else if (typeof value === "string") {
44963
+ headers[key] = value;
44964
+ }
44965
+ }
44966
+ if (previewAuthorization) {
44967
+ headers[PREVIEW_AUTHORIZATION_HEADER] = previewAuthorization;
44968
+ }
44969
+ return headers;
44970
+ }
44971
+
44972
+ // ../../packages/api/src/preview/preview-server.ts
44723
44973
  function resolvePreviewPath(rootPath, relativePath) {
44724
44974
  const sanitizedPath = relativePath.replace(/\\/g, "/");
44725
44975
  const resolvedPath = path17.resolve(rootPath, sanitizedPath);
@@ -44739,22 +44989,58 @@ function resolvePreviewEntryPath(rootPath, entryPath) {
44739
44989
  }
44740
44990
  return normalizedPath;
44741
44991
  }
44992
+ function normalizeServiceEntryPath(entryPath) {
44993
+ if (!entryPath || entryPath === "/") {
44994
+ return "";
44995
+ }
44996
+ return entryPath.replace(/\\/g, "/").replace(/^\/+/, "");
44997
+ }
44998
+ function assertPreviewServicePort(port) {
44999
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
45000
+ throw new Error("Invalid preview service port");
45001
+ }
45002
+ return port;
45003
+ }
44742
45004
  function buildPreviewUrl(origin, session) {
45005
+ return buildPreviewRouteUrl(origin, "preview", session);
45006
+ }
45007
+ function buildPreviewOpenUrl(origin, session) {
45008
+ return buildPreviewRouteUrl(origin, "preview-open", session);
45009
+ }
45010
+ function buildPreviewRouteUrl(origin, route, session) {
44743
45011
  const encodedEntryPath = session.entryPath.split("/").filter(Boolean).map((segment) => encodeURIComponent(segment)).join("/");
44744
- return `${origin.replace(/\/+$/, "")}/preview/${session.token}/${encodedEntryPath}`;
45012
+ const suffix = encodedEntryPath.length > 0 ? `/${encodedEntryPath}` : session.kind === "service" ? "/" : "";
45013
+ return `${origin.replace(/\/+$/, "")}/${route}/${session.token}${suffix}`;
44745
45014
  }
44746
45015
  var DEFAULT_TTL_MS = 15 * 60 * 1e3;
44747
45016
  var PreviewSessionManager = class {
44748
45017
  sessions = /* @__PURE__ */ new Map();
44749
45018
  create(options) {
44750
45019
  const token = crypto3.randomBytes(32).toString("hex");
45020
+ const expiresAt = Date.now() + (options.ttlMs ?? DEFAULT_TTL_MS);
45021
+ if (options.port !== void 0) {
45022
+ const session2 = {
45023
+ token,
45024
+ taskId: options.taskId,
45025
+ kind: "service",
45026
+ port: assertPreviewServicePort(options.port),
45027
+ entryPath: normalizeServiceEntryPath(options.entryPath),
45028
+ expiresAt
45029
+ };
45030
+ this.sessions.set(token, session2);
45031
+ return session2;
45032
+ }
45033
+ if (!options.rootPath) {
45034
+ throw new Error("Preview root path is required");
45035
+ }
44751
45036
  const entryPath = resolvePreviewEntryPath(options.rootPath, options.entryPath);
44752
45037
  const session = {
44753
45038
  token,
44754
45039
  taskId: options.taskId,
45040
+ kind: "file",
44755
45041
  rootPath: options.rootPath,
44756
45042
  entryPath,
44757
- expiresAt: Date.now() + (options.ttlMs ?? DEFAULT_TTL_MS)
45043
+ expiresAt
44758
45044
  };
44759
45045
  this.sessions.set(token, session);
44760
45046
  return session;
@@ -44795,19 +45081,353 @@ var MIME_MAP2 = {
44795
45081
  ".woff2": "font/woff2",
44796
45082
  ".ttf": "font/ttf",
44797
45083
  ".eot": "application/vnd.ms-fontobject",
44798
- ".pdf": "application/pdf"
45084
+ ".pdf": "application/pdf",
45085
+ ".md": "text/markdown",
45086
+ ".mdx": "text/markdown"
44799
45087
  };
44800
45088
  function getMime(filePath) {
44801
45089
  return MIME_MAP2[path17.extname(filePath).toLowerCase()] ?? "application/octet-stream";
44802
45090
  }
44803
- function sendPreviewAssetResponse(sessionManager, token, requestedPath, res) {
45091
+ function escapeHtml(value) {
45092
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
45093
+ }
45094
+ function renderInlineMarkdown(value) {
45095
+ let rendered = escapeHtml(value);
45096
+ rendered = rendered.replace(/!\[([^\]]*)]\(([^\s)]+)\)/g, '<img alt="$1" src="$2">');
45097
+ rendered = rendered.replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\[([^\]]+)]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" rel="noreferrer noopener" target="_blank">$1</a>');
45098
+ return rendered;
45099
+ }
45100
+ function renderMarkdownBody(markdown) {
45101
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
45102
+ const blocks = [];
45103
+ let paragraph = [];
45104
+ let listItems = [];
45105
+ let codeLines = null;
45106
+ const flushParagraph = () => {
45107
+ if (paragraph.length === 0) return;
45108
+ blocks.push(`<p>${renderInlineMarkdown(paragraph.join(" "))}</p>`);
45109
+ paragraph = [];
45110
+ };
45111
+ const flushList = () => {
45112
+ if (listItems.length === 0) return;
45113
+ blocks.push(`<ul>${listItems.map((item) => `<li>${renderInlineMarkdown(item)}</li>`).join("")}</ul>`);
45114
+ listItems = [];
45115
+ };
45116
+ for (const line of lines) {
45117
+ if (line.trim().startsWith("```")) {
45118
+ if (codeLines) {
45119
+ blocks.push(`<pre><code>${escapeHtml(codeLines.join("\n"))}</code></pre>`);
45120
+ codeLines = null;
45121
+ } else {
45122
+ flushParagraph();
45123
+ flushList();
45124
+ codeLines = [];
45125
+ }
45126
+ continue;
45127
+ }
45128
+ if (codeLines) {
45129
+ codeLines.push(line);
45130
+ continue;
45131
+ }
45132
+ const trimmed = line.trim();
45133
+ if (!trimmed) {
45134
+ flushParagraph();
45135
+ flushList();
45136
+ continue;
45137
+ }
45138
+ const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
45139
+ if (heading) {
45140
+ flushParagraph();
45141
+ flushList();
45142
+ const level = heading[1].length;
45143
+ blocks.push(`<h${level}>${renderInlineMarkdown(heading[2])}</h${level}>`);
45144
+ continue;
45145
+ }
45146
+ const listItem = trimmed.match(/^[-*]\s+(.+)$/);
45147
+ if (listItem) {
45148
+ flushParagraph();
45149
+ listItems.push(listItem[1]);
45150
+ continue;
45151
+ }
45152
+ flushList();
45153
+ paragraph.push(trimmed);
45154
+ }
45155
+ if (codeLines) {
45156
+ blocks.push(`<pre><code>${escapeHtml(codeLines.join("\n"))}</code></pre>`);
45157
+ }
45158
+ flushParagraph();
45159
+ flushList();
45160
+ return blocks.join("\n");
45161
+ }
45162
+ function renderMarkdownDocument(markdown, title) {
45163
+ const body = renderMarkdownBody(markdown);
45164
+ return Buffer.from(`<!doctype html>
45165
+ <html>
45166
+ <head>
45167
+ <meta charset="utf-8">
45168
+ <meta name="viewport" content="width=device-width, initial-scale=1">
45169
+ <title>${escapeHtml(title)}</title>
45170
+ <style>
45171
+ body { box-sizing: border-box; max-width: 860px; margin: 0 auto; padding: 32px; color: #111827; font: 16px/1.65 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
45172
+ h1, h2, h3, h4, h5, h6 { line-height: 1.25; margin: 1.5em 0 0.5em; }
45173
+ h1 { border-bottom: 1px solid #e5e7eb; padding-bottom: 0.3em; }
45174
+ pre { overflow: auto; border-radius: 8px; background: #111827; color: #f9fafb; padding: 16px; }
45175
+ code { border-radius: 4px; background: #f3f4f6; padding: 0.1em 0.25em; }
45176
+ pre code { background: transparent; padding: 0; }
45177
+ img { max-width: 100%; }
45178
+ a { color: #2563eb; }
45179
+ </style>
45180
+ </head>
45181
+ <body>
45182
+ ${body}
45183
+ </body>
45184
+ </html>`, "utf8");
45185
+ }
45186
+ function splitPreviewPathAndSearch(value) {
45187
+ const marker = value.indexOf("?");
45188
+ if (marker === -1) {
45189
+ return { pathname: value, search: "" };
45190
+ }
45191
+ return { pathname: value.slice(0, marker), search: value.slice(marker) };
45192
+ }
45193
+ function normalizeServiceRequestPath(pathname) {
45194
+ const normalized = pathname.replace(/\\/g, "/");
45195
+ if (!normalized || normalized === "/") {
45196
+ return "/";
45197
+ }
45198
+ return `/${normalized.replace(/^\/+/, "")}`;
45199
+ }
45200
+ function rewriteServiceRootRelativeUrls(value, token) {
45201
+ const previewRoot = `/preview/${token}/`;
45202
+ return value.replace(/\b(src|href|action)=(['"])\/(?!\/|preview\/)/gi, `$1=$2${previewRoot}`).replace(/url\((['"]?)\/(?!\/|preview\/)/gi, `url($1${previewRoot}`).replace(/\bimport\((['"])\/(?!\/|preview\/)/gi, `import($1${previewRoot}`).replace(/\bfrom\s+(['"])\/(?!\/|preview\/)/gi, `from $1${previewRoot}`).replace(/(['"])\/(assets\/[^'"]+)\1/g, `$1${previewRoot}$2$1`);
45203
+ }
45204
+ function escapeHtmlAttribute(value) {
45205
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
45206
+ }
45207
+ function buildServicePreviewBridge(token) {
45208
+ const previewRoot = `/preview/${token}/`;
45209
+ const previewBase = previewRoot.replace(/\/$/, "");
45210
+ const script = [
45211
+ "(()=>{",
45212
+ "if(window.top===window)return;",
45213
+ `const previewBase=${JSON.stringify(previewBase)};`,
45214
+ `const previewRoot=${JSON.stringify(previewRoot)};`,
45215
+ "const rewritePreviewRequestUrl=(value)=>{",
45216
+ "if(value==null)return value;",
45217
+ "let raw;",
45218
+ 'try{raw=value instanceof URL?value.href:typeof value==="string"?value:value&&typeof value.url==="string"?value.url:undefined;}catch{return value;}',
45219
+ "if(!raw)return value;",
45220
+ "let url;",
45221
+ "try{url=new URL(raw,window.location.href);}catch{return value;}",
45222
+ "if(url.origin!==window.location.origin)return value;",
45223
+ 'if(url.pathname===previewBase||url.pathname.startsWith(previewRoot)||url.pathname.startsWith("/preview-open/"))return value;',
45224
+ 'return previewRoot+url.pathname.replace(/^\\/+/,"")+url.search+url.hash;',
45225
+ "};",
45226
+ "const rewritePreviewRequestInput=(input)=>{",
45227
+ "const next=rewritePreviewRequestUrl(input);",
45228
+ "if(next===input)return input;",
45229
+ 'if(typeof Request==="function"&&input instanceof Request)return new Request(next,input);',
45230
+ "return next;",
45231
+ "};",
45232
+ "const originalFetch=window.fetch;",
45233
+ 'if(typeof originalFetch==="function")window.fetch=(input,init)=>originalFetch.call(window,rewritePreviewRequestInput(input),init);',
45234
+ "const XHR=window.XMLHttpRequest;",
45235
+ "if(XHR&&XHR.prototype){const open=XHR.prototype.open;XMLHttpRequest.prototype.open=function(method,url,...rest){return open.call(this,method,rewritePreviewRequestUrl(url),...rest);};}",
45236
+ "const OriginalEventSource=window.EventSource;",
45237
+ 'if(typeof OriginalEventSource==="function"){window.EventSource=function(url,config){return new OriginalEventSource(rewritePreviewRequestUrl(url),config);};window.EventSource.prototype=OriginalEventSource.prototype;}',
45238
+ "const currentPath=window.location.pathname;",
45239
+ "if(currentPath===previewBase||currentPath.startsWith(previewRoot)){",
45240
+ "const suffix=currentPath===previewBase?'':currentPath.slice(previewRoot.length);",
45241
+ "const servicePath=suffix?'/' + suffix:'/';",
45242
+ "window.history.replaceState(window.history.state,'',servicePath+window.location.search+window.location.hash);",
45243
+ "}",
45244
+ "})();"
45245
+ ].join("");
45246
+ return `<base data-meshy-preview-base href="${escapeHtmlAttribute(previewRoot)}"><script data-meshy-preview-bridge>${script}</script>`;
45247
+ }
45248
+ function injectServicePreviewBridge(value, token) {
45249
+ const bridge = buildServicePreviewBridge(token);
45250
+ const headPattern = /<head(?:\s[^>]*)?>/i;
45251
+ if (headPattern.test(value)) {
45252
+ return value.replace(headPattern, (match) => `${match}${bridge}`);
45253
+ }
45254
+ const htmlPattern = /<html(?:\s[^>]*)?>/i;
45255
+ if (htmlPattern.test(value)) {
45256
+ return value.replace(htmlPattern, (match) => `${match}<head>${bridge}</head>`);
45257
+ }
45258
+ return `${bridge}${value}`;
45259
+ }
45260
+ function normalizeContentType(contentType) {
45261
+ return contentType?.split(";")[0]?.trim().toLowerCase();
45262
+ }
45263
+ function isServiceHtmlContentType(contentType) {
45264
+ return normalizeContentType(contentType) === "text/html";
45265
+ }
45266
+ function isServiceEventStreamContentType(contentType) {
45267
+ return normalizeContentType(contentType) === "text/event-stream";
45268
+ }
45269
+ function isServiceJavaScriptContentType(normalizedType) {
45270
+ return normalizedType === "text/javascript" || normalizedType === "application/javascript" || normalizedType === "application/x-javascript";
45271
+ }
45272
+ function rewriteServiceJavaScriptRuntimeUrls(value, token) {
45273
+ if (!value.includes("__vite__mapDeps")) {
45274
+ return value;
45275
+ }
45276
+ const previewRoot = `/preview/${token}/`;
45277
+ return value.replace(
45278
+ /return\s*(['"])\/\1\s*\+\s*([A-Za-z_$][\w$]*)/g,
45279
+ (_match, quote, argumentName) => `return${quote}${previewRoot}${quote}+${argumentName}`
45280
+ );
45281
+ }
45282
+ function rewriteServiceResponseContent(content, contentType, token) {
45283
+ const normalizedType = normalizeContentType(contentType);
45284
+ if (normalizedType !== "text/html" && normalizedType !== "text/css" && !isServiceJavaScriptContentType(normalizedType)) {
45285
+ return content;
45286
+ }
45287
+ const source = content.toString("utf8");
45288
+ const bridged = normalizedType === "text/html" ? injectServicePreviewBridge(source, token) : source;
45289
+ const rewritten = rewriteServiceRootRelativeUrls(bridged, token);
45290
+ return Buffer.from(
45291
+ isServiceJavaScriptContentType(normalizedType) ? rewriteServiceJavaScriptRuntimeUrls(rewritten, token) : rewritten,
45292
+ "utf8"
45293
+ );
45294
+ }
45295
+ function rewriteServiceRedirectLocation(value, session) {
45296
+ const previewRoot = `/preview/${session.token}`;
45297
+ if (value.startsWith("/preview/")) {
45298
+ return value;
45299
+ }
45300
+ if (value.startsWith("/")) {
45301
+ return `${previewRoot}${value}`;
45302
+ }
45303
+ try {
45304
+ const url = new URL(value);
45305
+ const isLocalService = (url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]") && url.port === String(session.port);
45306
+ if (isLocalService) {
45307
+ return `${previewRoot}${url.pathname}${url.search}${url.hash}`;
45308
+ }
45309
+ } catch {
45310
+ }
45311
+ return value;
45312
+ }
45313
+ function buildServiceResponseHeaders(upstream, session, isHtml) {
45314
+ const headers = {};
45315
+ upstream.headers.forEach((value, key) => {
45316
+ const normalizedKey = key.toLowerCase();
45317
+ if (HOP_BY_HOP_HEADERS.has(normalizedKey) || normalizedKey === "content-length" || normalizedKey === "content-encoding" || isHtml && normalizedKey === "content-security-policy" || isHtml && normalizedKey === "content-security-policy-report-only" || isHtml && normalizedKey === "x-frame-options") {
45318
+ return;
45319
+ }
45320
+ if (normalizedKey === "location") {
45321
+ headers[key] = rewriteServiceRedirectLocation(value, session);
45322
+ return;
45323
+ }
45324
+ headers[key] = value;
45325
+ });
45326
+ if (typeof headers["cache-control"] !== "string") {
45327
+ headers["cache-control"] = "no-cache";
45328
+ }
45329
+ return headers;
45330
+ }
45331
+ async function pipeServiceResponseBody(upstream, res) {
45332
+ if (!upstream.body) {
45333
+ res.end();
45334
+ return;
45335
+ }
45336
+ try {
45337
+ await (0, import_promises6.pipeline)(import_node_stream3.Readable.fromWeb(upstream.body), res);
45338
+ } catch (error) {
45339
+ if (!res.destroyed && !res.writableEnded) {
45340
+ throw error;
45341
+ }
45342
+ }
45343
+ }
45344
+ async function sendServicePreviewResponse(session, requestedPath, req, res) {
45345
+ const decodedPath = decodeURIComponent(requestedPath ?? session.entryPath);
45346
+ const { pathname, search } = splitPreviewPathAndSearch(decodedPath);
45347
+ const targetPath = normalizeServiceRequestPath(pathname || session.entryPath);
45348
+ const targetUrl = `http://127.0.0.1:${session.port}${targetPath}${search}`;
45349
+ let upstream;
45350
+ try {
45351
+ const body = await readPreviewRequestBody(req);
45352
+ upstream = await fetch(targetUrl, {
45353
+ method: req?.method ?? "GET",
45354
+ headers: buildServiceProxyHeaders(req),
45355
+ ...body !== void 0 ? { body } : {},
45356
+ redirect: "manual"
45357
+ });
45358
+ } catch {
45359
+ res.writeHead(502, { "Content-Type": "text/plain" });
45360
+ res.end("Preview service unavailable");
45361
+ return;
45362
+ }
45363
+ const upstreamContentType = upstream.headers.get("content-type");
45364
+ const isHtml = isServiceHtmlContentType(upstreamContentType);
45365
+ const headers = buildServiceResponseHeaders(upstream, session, isHtml);
45366
+ if (isServiceEventStreamContentType(upstreamContentType)) {
45367
+ res.writeHead(upstream.status, headers);
45368
+ await pipeServiceResponseBody(upstream, res);
45369
+ return;
45370
+ }
45371
+ const content = rewriteServiceResponseContent(Buffer.from(await upstream.arrayBuffer()), upstreamContentType, session.token);
45372
+ headers["content-length"] = content.length;
45373
+ res.writeHead(upstream.status, headers);
45374
+ res.end(content);
45375
+ }
45376
+ function buildPreviewUrlForRequest(token, requestedPath, session) {
45377
+ const { pathname, search } = splitPreviewPathAndSearch(requestedPath ?? session.entryPath);
45378
+ return `${buildPreviewUrl("", { token, entryPath: pathname, kind: session.kind })}${search}`;
45379
+ }
45380
+ function renderPreviewOpenDocument(previewUrl) {
45381
+ const safePreviewUrl = escapeHtmlAttribute(previewUrl);
45382
+ return Buffer.from(`<!doctype html>
45383
+ <html>
45384
+ <head>
45385
+ <meta charset="utf-8">
45386
+ <meta name="viewport" content="width=device-width, initial-scale=1">
45387
+ <title>Preview</title>
45388
+ <style>
45389
+ html, body { width: 100%; height: 100%; margin: 0; background: #fff; }
45390
+ iframe { display: block; width: 100%; height: 100%; border: 0; }
45391
+ </style>
45392
+ </head>
45393
+ <body>
45394
+ <iframe src="${safePreviewUrl}" title="Preview"></iframe>
45395
+ </body>
45396
+ </html>`, "utf8");
45397
+ }
45398
+ function sendPreviewOpenResponse(sessionManager, token, requestedPath, res) {
44804
45399
  const session = sessionManager.get(token);
44805
45400
  if (!session) {
44806
45401
  res.writeHead(403, { "Content-Type": "text/plain" });
44807
45402
  res.end("Invalid or expired preview token");
44808
45403
  return;
44809
45404
  }
44810
- const resolvedRequestedPath = decodeURIComponent(requestedPath ?? session.entryPath);
45405
+ const content = renderPreviewOpenDocument(buildPreviewUrlForRequest(token, requestedPath, session));
45406
+ res.writeHead(200, {
45407
+ "Content-Type": "text/html",
45408
+ "Content-Length": content.length,
45409
+ "Cache-Control": "no-cache"
45410
+ });
45411
+ res.end(content);
45412
+ }
45413
+ async function sendPreviewAssetResponse(sessionManager, token, requestedPath, res, req) {
45414
+ const session = sessionManager.get(token);
45415
+ if (!session) {
45416
+ res.writeHead(403, { "Content-Type": "text/plain" });
45417
+ res.end("Invalid or expired preview token");
45418
+ return;
45419
+ }
45420
+ if (session.kind === "service") {
45421
+ await sendServicePreviewResponse(session, requestedPath, req, res);
45422
+ return;
45423
+ }
45424
+ if (!isReadOnlyPreviewMethod(req?.method)) {
45425
+ res.writeHead(405, { "Content-Type": "text/plain" });
45426
+ res.end("Method not allowed");
45427
+ return;
45428
+ }
45429
+ const { pathname } = splitPreviewPathAndSearch(decodeURIComponent(requestedPath ?? session.entryPath));
45430
+ const resolvedRequestedPath = pathname || session.entryPath;
44811
45431
  let resolved;
44812
45432
  try {
44813
45433
  resolved = resolvePreviewPath(session.rootPath, resolvedRequestedPath).absolutePath;
@@ -44821,8 +45441,9 @@ function sendPreviewAssetResponse(sessionManager, token, requestedPath, res) {
44821
45441
  res.end("File not found");
44822
45442
  return;
44823
45443
  }
44824
- const mime = getMime(resolved);
44825
- const content = fs16.readFileSync(resolved);
45444
+ const ext = path17.extname(resolved).toLowerCase();
45445
+ const mime = ext === ".md" || ext === ".mdx" ? "text/html" : getMime(resolved);
45446
+ const content = ext === ".md" || ext === ".mdx" ? renderMarkdownDocument(fs16.readFileSync(resolved, "utf8"), path17.basename(resolved)) : fs16.readFileSync(resolved);
44826
45447
  res.writeHead(200, {
44827
45448
  "Content-Type": mime,
44828
45449
  "Content-Length": content.length,
@@ -44830,14 +45451,20 @@ function sendPreviewAssetResponse(sessionManager, token, requestedPath, res) {
44830
45451
  });
44831
45452
  res.end(content);
44832
45453
  }
44833
- function handlePreviewRequest(sessionManager, req, res) {
45454
+ async function handlePreviewRequest(sessionManager, req, res) {
44834
45455
  const url = new URL(req.url ?? "/", "http://localhost");
44835
- if (!url.pathname.startsWith("/preview/")) {
45456
+ if (!url.pathname.startsWith("/preview/") && !url.pathname.startsWith("/preview-open/")) {
44836
45457
  return false;
44837
45458
  }
44838
- if (req.method !== "GET") {
44839
- res.writeHead(405, { "Content-Type": "text/plain" });
44840
- res.end("Method not allowed");
45459
+ const openMatch = url.pathname.match(/^\/preview-open\/([a-f0-9]+)(?:\/(.*))?$/i);
45460
+ if (openMatch?.[1]) {
45461
+ if (!isReadOnlyPreviewMethod(req.method)) {
45462
+ res.writeHead(405, { "Content-Type": "text/plain" });
45463
+ res.end("Method not allowed");
45464
+ return true;
45465
+ }
45466
+ const requestedPath2 = openMatch[2];
45467
+ sendPreviewOpenResponse(sessionManager, openMatch[1], requestedPath2 ? `${requestedPath2}${url.search}` : url.search || void 0, res);
44841
45468
  return true;
44842
45469
  }
44843
45470
  const match = url.pathname.match(/^\/preview\/([a-f0-9]+)(?:\/(.*))?$/i);
@@ -44847,7 +45474,8 @@ function handlePreviewRequest(sessionManager, req, res) {
44847
45474
  res.end("Preview not found");
44848
45475
  return true;
44849
45476
  }
44850
- sendPreviewAssetResponse(sessionManager, token, match?.[2], res);
45477
+ const requestedPath = match?.[2];
45478
+ await sendPreviewAssetResponse(sessionManager, token, requestedPath ? `${requestedPath}${url.search}` : url.search || void 0, res, req);
44851
45479
  return true;
44852
45480
  }
44853
45481
 
@@ -44912,15 +45540,30 @@ function createPreviewAssetProxyTrace(log2, token, nodeId, requestPath, proxyPat
44912
45540
  };
44913
45541
  }
44914
45542
  function parsePreviewRequest(previewUrl) {
44915
- const pathname = new URL(previewUrl, "http://localhost").pathname;
44916
- const match = pathname.match(/^\/preview\/([a-f0-9]+)(?:\/(.*))?$/i);
45543
+ const url = new URL(previewUrl, "http://localhost");
45544
+ const match = url.pathname.match(/^\/preview\/([a-f0-9]+)(?:\/(.*))?$/i);
44917
45545
  const token = match?.[1];
44918
45546
  if (!token) {
44919
45547
  return null;
44920
45548
  }
45549
+ const requestedPath = match?.[2];
44921
45550
  return {
44922
45551
  token,
44923
- requestedPath: match?.[2]
45552
+ requestedPath: requestedPath ? `${requestedPath}${url.search}` : url.search || void 0
45553
+ };
45554
+ }
45555
+ function parsePreviewOpenRequest(previewUrl) {
45556
+ const url = new URL(previewUrl, "http://localhost");
45557
+ const match = url.pathname.match(/^\/preview-open\/([a-f0-9]+)(?:\/(.*))?$/i);
45558
+ const token = match?.[1];
45559
+ if (!token) {
45560
+ return null;
45561
+ }
45562
+ const requestedPath = match?.[2];
45563
+ const suffix = requestedPath !== void 0 ? `/${requestedPath}` : "";
45564
+ return {
45565
+ token,
45566
+ previewUrl: `/preview/${token}${suffix}${url.search}`
44924
45567
  };
44925
45568
  }
44926
45569
  function extractPreviewToken(previewUrl) {
@@ -44968,12 +45611,34 @@ function rewritePreviewSessionPayloadForProxy(manager, payload, nodeId) {
44968
45611
  ...payload,
44969
45612
  previewUrl: buildPreviewUrl("", {
44970
45613
  token,
44971
- entryPath: payload.entryPath
44972
- })
45614
+ entryPath: payload.entryPath,
45615
+ kind: payload.kind
45616
+ }),
45617
+ ...payload.kind === "service" || payload.openUrl ? {
45618
+ openUrl: buildPreviewOpenUrl("", {
45619
+ token,
45620
+ entryPath: payload.entryPath,
45621
+ kind: payload.kind
45622
+ })
45623
+ } : {}
44973
45624
  };
44974
45625
  }
44975
45626
  async function handlePreviewProxyRequest(manager, nodeRegistry, logger27, req, res) {
44976
45627
  const requestPath = req.originalUrl ?? req.url;
45628
+ const previewOpenRequest = parsePreviewOpenRequest(requestPath);
45629
+ if (previewOpenRequest) {
45630
+ const session2 = manager.get(previewOpenRequest.token);
45631
+ if (!session2) {
45632
+ return false;
45633
+ }
45634
+ const content = renderPreviewOpenDocument(previewOpenRequest.previewUrl);
45635
+ res.status(200).set({
45636
+ "Content-Type": "text/html",
45637
+ "Content-Length": String(content.length),
45638
+ "Cache-Control": "no-cache"
45639
+ }).send(content);
45640
+ return true;
45641
+ }
44977
45642
  const previewRequest = parsePreviewRequest(requestPath);
44978
45643
  if (!previewRequest) {
44979
45644
  return false;
@@ -44989,10 +45654,15 @@ async function handlePreviewProxyRequest(manager, nodeRegistry, logger27, req, r
44989
45654
  const previewLog = logger27.child("preview-proxy");
44990
45655
  const proxyPath = buildPreviewAssetProxyPath(previewRequest.token, previewRequest.requestedPath);
44991
45656
  try {
45657
+ const body = await readPreviewRequestBody(req);
44992
45658
  const { endpoint, response } = await fetchNodeWithFallback(
44993
45659
  node,
44994
45660
  proxyPath,
44995
- void 0,
45661
+ {
45662
+ method: req.method,
45663
+ headers: buildPreviewWorkerProxyHeaders(req),
45664
+ ...body !== void 0 ? { body } : {}
45665
+ },
44996
45666
  PREVIEW_ASSET_PROXY_TIMEOUT_MS,
44997
45667
  createPreviewAssetProxyTrace(previewLog, previewRequest.token, session.nodeId, requestPath, proxyPath),
44998
45668
  { preferPublicEndpoint: true }
@@ -45122,16 +45792,21 @@ function getLocalTaskOutputDiff(taskEngine, taskId) {
45122
45792
  const rootPath = getTaskOutputRoot(taskEngine, taskId);
45123
45793
  return getGitDiff(rootPath);
45124
45794
  }
45125
- async function createPreviewSessionPayload(deps, taskId, entryPath, requestOrigin) {
45795
+ async function createPreviewSessionPayload(deps, taskId, optionsOrPath, requestOrigin) {
45126
45796
  const previewManager = deps.previewSessionManager;
45127
45797
  if (!previewManager) {
45128
45798
  throw new MeshyError("VALIDATION_ERROR", "Preview not available on this node", 400);
45129
45799
  }
45130
- const rootPath = getTaskOutputRoot(deps.taskEngine, taskId);
45131
- const session = previewManager.create({
45800
+ const options = typeof optionsOrPath === "string" ? { path: optionsOrPath } : optionsOrPath ?? {};
45801
+ getTask(deps.taskEngine, taskId);
45802
+ const session = options.port !== void 0 ? previewManager.create({
45132
45803
  taskId,
45133
- rootPath,
45134
- entryPath
45804
+ port: options.port,
45805
+ entryPath: options.path
45806
+ }) : previewManager.create({
45807
+ taskId,
45808
+ rootPath: getTaskOutputRoot(deps.taskEngine, taskId),
45809
+ entryPath: options.path
45135
45810
  });
45136
45811
  const origin = requestOrigin ?? deps.dashboardOrigin ?? deps.localDashboardOrigin;
45137
45812
  if (!origin) {
@@ -45139,11 +45814,555 @@ async function createPreviewSessionPayload(deps, taskId, entryPath, requestOrigi
45139
45814
  }
45140
45815
  return {
45141
45816
  previewUrl: buildPreviewUrl(origin, session),
45817
+ ...session.kind === "service" ? { openUrl: buildPreviewOpenUrl(origin, session) } : {},
45142
45818
  expiresAt: session.expiresAt,
45143
- entryPath: session.entryPath
45819
+ entryPath: session.entryPath,
45820
+ kind: session.kind,
45821
+ ...session.kind === "service" ? { port: session.port } : {}
45822
+ };
45823
+ }
45824
+
45825
+ // ../../packages/api/src/node/agent-upgrade-service.ts
45826
+ var import_node_child_process9 = require("child_process");
45827
+
45828
+ // ../../packages/api/src/app/system-info.ts
45829
+ var os6 = __toESM(require("os"), 1);
45830
+ var import_node_child_process8 = require("child_process");
45831
+ var RUNTIME_TOOLS = [
45832
+ { id: "claude", label: "Claude Code", command: "claude", packageName: "@anthropic-ai/claude-code" },
45833
+ { id: "codex", label: "Codex", command: "codex", packageName: "@openai/codex" }
45834
+ ];
45835
+ var runtimeToolUpdateCache = /* @__PURE__ */ new Map();
45836
+ function clearRuntimeToolUpdateCache(packageName) {
45837
+ if (packageName) {
45838
+ runtimeToolUpdateCache.delete(packageName);
45839
+ return;
45840
+ }
45841
+ runtimeToolUpdateCache.clear();
45842
+ }
45843
+ function runRuntimeToolCommand(command, args, platform2) {
45844
+ const result = (0, import_node_child_process8.spawnSync)(command, args, {
45845
+ encoding: "utf-8",
45846
+ shell: platform2 === "win32" && command !== "where",
45847
+ windowsHide: true,
45848
+ timeout: 2500
45849
+ });
45850
+ return {
45851
+ status: result.status,
45852
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
45853
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
45854
+ error: result.error?.message ?? null
45855
+ };
45856
+ }
45857
+ function normalizeOutput(output) {
45858
+ if (!output) {
45859
+ return null;
45860
+ }
45861
+ const firstLine = output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
45862
+ return firstLine ?? null;
45863
+ }
45864
+ function formatLocalDate(date) {
45865
+ const year = date.getFullYear();
45866
+ const month = String(date.getMonth() + 1).padStart(2, "0");
45867
+ const day = String(date.getDate()).padStart(2, "0");
45868
+ return `${year}-${month}-${day}`;
45869
+ }
45870
+ function resolveCommandPath(command, commandRunner, platform2) {
45871
+ const lookupCommand = platform2 === "win32" ? "where" : "which";
45872
+ const result = commandRunner(lookupCommand, [command]);
45873
+ if (result.status === 0) {
45874
+ return { path: normalizeOutput(result.stdout) };
45875
+ }
45876
+ return {
45877
+ path: null,
45878
+ detail: normalizeOutput(result.stderr) ?? result.error ?? null
45879
+ };
45880
+ }
45881
+ function extractSemver(value) {
45882
+ return value?.match(/\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?/)?.[0] ?? null;
45883
+ }
45884
+ function normalizePackageVersion(output) {
45885
+ if (!output) return null;
45886
+ const trimmed = output.trim();
45887
+ try {
45888
+ const parsed = JSON.parse(trimmed);
45889
+ if (typeof parsed === "string") {
45890
+ return parsed.trim() || null;
45891
+ }
45892
+ } catch {
45893
+ }
45894
+ return normalizeOutput(trimmed);
45895
+ }
45896
+ function normalizeInstalledPackageVersion(output, packageName) {
45897
+ if (!output) return null;
45898
+ const trimmed = output.trim();
45899
+ try {
45900
+ const parsed = JSON.parse(trimmed);
45901
+ const version2 = parsed.dependencies?.[packageName]?.version;
45902
+ if (typeof version2 === "string") {
45903
+ return version2.trim() || null;
45904
+ }
45905
+ } catch {
45906
+ }
45907
+ return extractSemver(normalizeOutput(trimmed));
45908
+ }
45909
+ function resolveInstalledPackageVersion(definition, commandRunner) {
45910
+ const result = commandRunner("npm", ["list", "-g", definition.packageName, "--depth=0", "--json"]);
45911
+ return normalizeInstalledPackageVersion(result.stdout ?? null, definition.packageName);
45912
+ }
45913
+ function compareSemver(left, right) {
45914
+ const leftParts = left.split(/[.-]/).map((part) => Number.parseInt(part, 10));
45915
+ const rightParts = right.split(/[.-]/).map((part) => Number.parseInt(part, 10));
45916
+ for (let index = 0; index < 3; index += 1) {
45917
+ const delta = (leftParts[index] || 0) - (rightParts[index] || 0);
45918
+ if (delta !== 0) return delta;
45919
+ }
45920
+ return 0;
45921
+ }
45922
+ function checkToolUpdate(definition, installedVersion, checkedAt, commandRunner, checkedOn, updateCache) {
45923
+ const currentVersion = extractSemver(installedVersion);
45924
+ const cached = updateCache.get(definition.packageName);
45925
+ let latestVersion = cached?.latestVersion ?? null;
45926
+ let detail = cached?.detail ?? null;
45927
+ let updateCheckedAt = cached?.checkedAt ?? checkedAt;
45928
+ if (cached?.checkedOn !== checkedOn) {
45929
+ const latestResult = commandRunner("npm", ["view", definition.packageName, "version", "--json"]);
45930
+ latestVersion = latestResult.status === 0 ? normalizePackageVersion(latestResult.stdout ?? null) : null;
45931
+ detail = latestResult.status === 0 ? null : normalizeOutput(latestResult.stderr) ?? latestResult.error ?? "Update check failed";
45932
+ updateCheckedAt = checkedAt;
45933
+ updateCache.set(definition.packageName, {
45934
+ checkedOn,
45935
+ checkedAt,
45936
+ latestVersion,
45937
+ detail
45938
+ });
45939
+ }
45940
+ return {
45941
+ packageName: definition.packageName,
45942
+ currentVersion,
45943
+ latestVersion,
45944
+ updateAvailable: Boolean(currentVersion && latestVersion && compareSemver(latestVersion, currentVersion) > 0),
45945
+ checkedAt: updateCheckedAt,
45946
+ detail
45947
+ };
45948
+ }
45949
+ function inspectTool(definition, commandRunner, checkedAt, checkedOn, updateCache, platform2) {
45950
+ const resolved = resolveCommandPath(definition.command, commandRunner, platform2);
45951
+ if (!resolved.path) {
45952
+ return {
45953
+ id: definition.id,
45954
+ label: definition.label,
45955
+ command: definition.command,
45956
+ available: false,
45957
+ path: null,
45958
+ version: null,
45959
+ checkedAt,
45960
+ detail: resolved.detail ?? "Command not found on PATH",
45961
+ update: checkToolUpdate(definition, null, checkedAt, commandRunner, checkedOn, updateCache)
45962
+ };
45963
+ }
45964
+ const versionResult = commandRunner(definition.command, ["--version"]);
45965
+ const commandVersion = normalizeOutput(versionResult.stdout) ?? normalizeOutput(versionResult.stderr);
45966
+ const version2 = extractSemver(commandVersion) ? commandVersion : resolveInstalledPackageVersion(definition, commandRunner);
45967
+ const detail = versionResult.status === 0 ? null : normalizeOutput(versionResult.stderr) ?? versionResult.error ?? "Version check failed";
45968
+ return {
45969
+ id: definition.id,
45970
+ label: definition.label,
45971
+ command: definition.command,
45972
+ available: true,
45973
+ path: resolved.path,
45974
+ version: version2,
45975
+ checkedAt,
45976
+ detail,
45977
+ update: checkToolUpdate(definition, version2, checkedAt, commandRunner, checkedOn, updateCache)
45978
+ };
45979
+ }
45980
+ function inspectRuntimeTools(options = {}) {
45981
+ const platform2 = options.platform ?? process.platform;
45982
+ const commandRunner = options.commandRunner ?? ((command, args) => runRuntimeToolCommand(command, args, platform2));
45983
+ const now = options.now ?? /* @__PURE__ */ new Date();
45984
+ const checkedAt = now.toISOString();
45985
+ const checkedOn = formatLocalDate(now);
45986
+ const updateCache = options.updateCache ?? runtimeToolUpdateCache;
45987
+ return RUNTIME_TOOLS.map((definition) => inspectTool(definition, commandRunner, checkedAt, checkedOn, updateCache, platform2));
45988
+ }
45989
+ function getOsSnapshot() {
45990
+ const cpus2 = os6.cpus();
45991
+ return {
45992
+ platform: os6.platform(),
45993
+ release: os6.release(),
45994
+ arch: os6.arch(),
45995
+ hostname: os6.hostname(),
45996
+ cpuModel: cpus2[0]?.model ?? null,
45997
+ cpuCount: cpus2.length,
45998
+ totalMemoryBytes: os6.totalmem(),
45999
+ freeMemoryBytes: os6.freemem()
46000
+ };
46001
+ }
46002
+ function buildNodeSettingsSnapshot(options) {
46003
+ const uptime = process.uptime();
46004
+ const runtimeMetadata = options.runtimeMetadata;
46005
+ const agents = (options.inspectRuntimeTools?.() ?? inspectRuntimeTools()).map((agent) => ({
46006
+ ...agent,
46007
+ metadataStatus: runtimeMetadata?.components?.[agent.id]?.status ?? null
46008
+ }));
46009
+ return {
46010
+ collectedAt: Date.now(),
46011
+ version: runtimeMetadata?.packageVersion ?? "0.1.0",
46012
+ packageName: runtimeMetadata?.packageName ?? "meshy",
46013
+ uptime,
46014
+ auth: options.auth,
46015
+ os: getOsSnapshot(),
46016
+ runtime: {
46017
+ nodeVersion: process.version,
46018
+ pid: process.pid,
46019
+ startedAt: Date.now() - Math.floor(uptime * 1e3),
46020
+ cwd: process.cwd(),
46021
+ workDir: options.workDir ?? null,
46022
+ storagePath: options.storagePath ?? null,
46023
+ localDashboardOrigin: options.localDashboardOrigin ?? null
46024
+ },
46025
+ agents,
46026
+ startupRequirements: {
46027
+ lastCheckedAt: runtimeMetadata?.startupRequirementsLastCheckedAt,
46028
+ lastCheckedOn: runtimeMetadata?.startupRequirementsLastCheckedOn,
46029
+ components: runtimeMetadata?.components ?? {}
46030
+ },
46031
+ components: runtimeMetadata?.components ?? {},
46032
+ repository: runtimeMetadata?.repository ?? {},
46033
+ packages: runtimeMetadata?.packages ?? {}
45144
46034
  };
45145
46035
  }
45146
46036
 
46037
+ // ../../packages/api/src/node/agent-upgrade-service.ts
46038
+ var AGENT_PACKAGES = {
46039
+ claude: "@anthropic-ai/claude-code",
46040
+ codex: "@openai/codex"
46041
+ };
46042
+ var OUTPUT_LIMIT = 4e3;
46043
+ function summarizeOutput(value) {
46044
+ const text = value ?? "";
46045
+ return text.length > OUTPUT_LIMIT ? `${text.slice(0, OUTPUT_LIMIT)}\u2026` : text;
46046
+ }
46047
+ function defaultCommandRunner(command, args) {
46048
+ const result = (0, import_node_child_process9.spawnSync)(command, args, {
46049
+ encoding: "utf-8",
46050
+ shell: process.platform === "win32",
46051
+ windowsHide: true,
46052
+ timeout: 18e4
46053
+ });
46054
+ return {
46055
+ status: result.status,
46056
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
46057
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
46058
+ error: result.error?.message ?? null
46059
+ };
46060
+ }
46061
+ function isRuntimeAgentId(value) {
46062
+ return value === "claude" || value === "codex";
46063
+ }
46064
+ function buildUpgradeArgs(agent, packageName) {
46065
+ const args = ["install", "-g", `${packageName}@latest`];
46066
+ if (agent === "claude") {
46067
+ args.push("--include=optional", "--ignore-scripts=false");
46068
+ }
46069
+ return args;
46070
+ }
46071
+ function upgradeRuntimeAgent(agent, options = {}) {
46072
+ const packageName = AGENT_PACKAGES[agent];
46073
+ if (!packageName) {
46074
+ throw new MeshyError("VALIDATION_ERROR", `Unsupported upgrade agent: ${agent}`, 400);
46075
+ }
46076
+ const command = "npm";
46077
+ const args = buildUpgradeArgs(agent, packageName);
46078
+ const result = (options.commandRunner ?? defaultCommandRunner)(command, args);
46079
+ const ok = result.status === 0 && !result.error;
46080
+ if (ok) {
46081
+ clearRuntimeToolUpdateCache(packageName);
46082
+ }
46083
+ const detail = result.error ?? (summarizeOutput(result.stderr) || "Agent upgrade failed");
46084
+ return {
46085
+ ok,
46086
+ agent,
46087
+ packageName,
46088
+ command,
46089
+ args,
46090
+ status: result.status,
46091
+ stdout: summarizeOutput(result.stdout),
46092
+ stderr: summarizeOutput(result.stderr),
46093
+ detail: ok ? null : detail
46094
+ };
46095
+ }
46096
+ function upgradeRuntimeAgentForDeps(deps, agent) {
46097
+ const result = deps.upgradeRuntimeAgent?.(agent) ?? upgradeRuntimeAgent(agent);
46098
+ if (result.ok) {
46099
+ const settingsSnapshot = deps.refreshSettingsSnapshot?.();
46100
+ if (settingsSnapshot) {
46101
+ deps.nodeRegistry.updateSettingsSnapshot(deps.nodeRegistry.getSelf().id, settingsSnapshot);
46102
+ return { ...result, settingsSnapshot };
46103
+ }
46104
+ }
46105
+ return result;
46106
+ }
46107
+
46108
+ // ../../packages/api/src/node/node-operation-service.ts
46109
+ var fs18 = __toESM(require("fs"), 1);
46110
+ var path19 = __toESM(require("path"), 1);
46111
+ var import_node_crypto7 = require("crypto");
46112
+ var NodeOperationFailure = class extends Error {
46113
+ constructor(message, result) {
46114
+ super(message);
46115
+ this.result = result;
46116
+ }
46117
+ };
46118
+ var InMemoryNodeOperationStore = class {
46119
+ operations = /* @__PURE__ */ new Map();
46120
+ get(id) {
46121
+ const operation = this.operations.get(id);
46122
+ return operation ? clone2(operation) : null;
46123
+ }
46124
+ list(filter = {}) {
46125
+ return Array.from(this.operations.values()).filter((operation) => matchesFilter(operation, filter)).sort((a, b) => b.createdAt - a.createdAt).map((operation) => clone2(operation));
46126
+ }
46127
+ upsert(operation) {
46128
+ const copy = clone2(operation);
46129
+ this.operations.set(copy.id, copy);
46130
+ return clone2(copy);
46131
+ }
46132
+ update(id, updates) {
46133
+ const current = this.operations.get(id);
46134
+ if (!current) return null;
46135
+ const next = { ...current, ...clone2(updates), id, createdAt: current.createdAt };
46136
+ this.operations.set(id, next);
46137
+ return clone2(next);
46138
+ }
46139
+ };
46140
+ var FileNodeOperationStore = class {
46141
+ constructor(storagePath) {
46142
+ this.storagePath = storagePath;
46143
+ }
46144
+ operations = /* @__PURE__ */ new Map();
46145
+ loaded = false;
46146
+ get(id) {
46147
+ this.load();
46148
+ const operation = this.operations.get(id);
46149
+ return operation ? clone2(operation) : null;
46150
+ }
46151
+ list(filter = {}) {
46152
+ this.load();
46153
+ return Array.from(this.operations.values()).filter((operation) => matchesFilter(operation, filter)).sort((a, b) => b.createdAt - a.createdAt).map((operation) => clone2(operation));
46154
+ }
46155
+ upsert(operation) {
46156
+ this.load();
46157
+ const copy = clone2(operation);
46158
+ this.operations.set(copy.id, copy);
46159
+ this.persist();
46160
+ return clone2(copy);
46161
+ }
46162
+ update(id, updates) {
46163
+ this.load();
46164
+ const current = this.operations.get(id);
46165
+ if (!current) return null;
46166
+ const next = { ...current, ...clone2(updates), id, createdAt: current.createdAt };
46167
+ this.operations.set(id, next);
46168
+ this.persist();
46169
+ return clone2(next);
46170
+ }
46171
+ load() {
46172
+ if (this.loaded) return;
46173
+ this.loaded = true;
46174
+ if (!fs18.existsSync(this.filePath)) return;
46175
+ const raw = JSON.parse(fs18.readFileSync(this.filePath, "utf-8"));
46176
+ const entries = Array.isArray(raw) ? raw : Object.values(raw);
46177
+ for (const entry of entries) {
46178
+ if (isNodeOperation(entry)) {
46179
+ this.operations.set(entry.id, clone2(entry));
46180
+ }
46181
+ }
46182
+ }
46183
+ persist() {
46184
+ fs18.mkdirSync(this.storagePath, { recursive: true });
46185
+ const body = JSON.stringify(Object.fromEntries(this.operations), null, 2);
46186
+ const tmpPath = `${this.filePath}.tmp`;
46187
+ fs18.writeFileSync(tmpPath, body, "utf-8");
46188
+ fs18.renameSync(tmpPath, this.filePath);
46189
+ }
46190
+ get filePath() {
46191
+ return path19.join(this.storagePath, "node-operations.json");
46192
+ }
46193
+ };
46194
+ var NodeOperationService = class {
46195
+ constructor(deps, store) {
46196
+ this.deps = deps;
46197
+ this.store = store;
46198
+ this.registerHandler("agent.upgrade", runAgentUpgradeOperation);
46199
+ }
46200
+ handlers = /* @__PURE__ */ new Map();
46201
+ registerHandler(kind, handler) {
46202
+ this.handlers.set(kind, handler);
46203
+ }
46204
+ create(kind, nodeId, payload) {
46205
+ const now = Date.now();
46206
+ const operation = {
46207
+ id: (0, import_node_crypto7.randomUUID)(),
46208
+ kind,
46209
+ nodeId,
46210
+ requestedByNodeId: this.deps.nodeRegistry.getSelf().id,
46211
+ status: "queued",
46212
+ payload,
46213
+ createdAt: now,
46214
+ updatedAt: now
46215
+ };
46216
+ const saved = this.store.upsert(operation);
46217
+ this.deps.eventBus.emit("node.operation.created", { operation: saved });
46218
+ return saved;
46219
+ }
46220
+ get(id) {
46221
+ return this.store.get(id);
46222
+ }
46223
+ list(filter) {
46224
+ return this.store.list(filter);
46225
+ }
46226
+ accept(operation) {
46227
+ const current = this.store.get(operation.id);
46228
+ if (current) {
46229
+ if (current.status === "queued") this.scheduleRun(current.id);
46230
+ return current;
46231
+ }
46232
+ const saved = this.store.upsert({ ...operation, status: "queued", updatedAt: Date.now() });
46233
+ this.deps.eventBus.emit("node.operation.created", { operation: saved });
46234
+ this.scheduleRun(saved.id);
46235
+ return saved;
46236
+ }
46237
+ runLocal(id) {
46238
+ this.scheduleRun(id);
46239
+ }
46240
+ applyRemoteUpdate(operation) {
46241
+ const current = this.store.get(operation.id);
46242
+ const saved = this.store.upsert(current ? { ...current, ...operation } : operation);
46243
+ this.applyOperationSideEffects(saved);
46244
+ this.deps.eventBus.emit("node.operation.updated", { operation: saved });
46245
+ return saved;
46246
+ }
46247
+ markFailed(id, error) {
46248
+ return this.update(id, {
46249
+ status: "failed",
46250
+ error,
46251
+ completedAt: Date.now()
46252
+ });
46253
+ }
46254
+ scheduleRun(id) {
46255
+ setTimeout(() => {
46256
+ void this.run(id);
46257
+ }, 0);
46258
+ }
46259
+ async run(id) {
46260
+ const operation = this.store.get(id);
46261
+ if (!operation || operation.status !== "queued") return;
46262
+ const running = this.update(id, { status: "running", startedAt: Date.now() });
46263
+ if (!running) return;
46264
+ try {
46265
+ const handler = this.handlers.get(running.kind);
46266
+ if (!handler) throw new Error(`No node operation handler registered for kind: ${running.kind}`);
46267
+ const result = await handler(running, this.deps);
46268
+ this.update(id, { status: "succeeded", result, completedAt: Date.now() });
46269
+ } catch (err) {
46270
+ this.update(id, {
46271
+ status: "failed",
46272
+ result: err instanceof NodeOperationFailure ? err.result : void 0,
46273
+ error: err instanceof Error ? err.message : String(err),
46274
+ completedAt: Date.now()
46275
+ });
46276
+ }
46277
+ }
46278
+ update(id, updates) {
46279
+ const saved = this.store.update(id, { ...updates, updatedAt: Date.now() });
46280
+ if (!saved) return null;
46281
+ this.applyOperationSideEffects(saved);
46282
+ this.deps.eventBus.emit("node.operation.updated", { operation: saved });
46283
+ void this.reportToLeader(saved);
46284
+ return saved;
46285
+ }
46286
+ applyOperationSideEffects(operation) {
46287
+ if (operation.kind !== "agent.upgrade" || operation.status !== "succeeded") return;
46288
+ const settingsSnapshot = readSettingsSnapshot(operation.result);
46289
+ if (settingsSnapshot) {
46290
+ this.deps.nodeRegistry.updateSettingsSnapshot(operation.nodeId, settingsSnapshot);
46291
+ }
46292
+ }
46293
+ async reportToLeader(operation) {
46294
+ if (this.deps.nodeRegistry.isLeader()) return;
46295
+ const leaderEndpoint = this.deps.nodeRegistry.getLeaderEndpoint?.();
46296
+ if (!leaderEndpoint) return;
46297
+ try {
46298
+ await fetch(`${leaderEndpoint}/api/worker/node-operations/${operation.id}`, applyRequestAuthHeaders({
46299
+ method: "POST",
46300
+ headers: { "Content-Type": "application/json" },
46301
+ body: JSON.stringify(operation)
46302
+ }));
46303
+ } catch (err) {
46304
+ this.deps.logger.child("node-operation").warn("failed to report node operation update to leader", {
46305
+ operationId: operation.id,
46306
+ kind: operation.kind,
46307
+ error: err instanceof Error ? err.message : String(err)
46308
+ });
46309
+ }
46310
+ }
46311
+ };
46312
+ function getNodeOperationService(deps) {
46313
+ if (deps.nodeOperationService) return deps.nodeOperationService;
46314
+ const store = deps.nodeOperationStore ?? (deps.storagePath ? new FileNodeOperationStore(deps.storagePath) : new InMemoryNodeOperationStore());
46315
+ const service = new NodeOperationService(deps, store);
46316
+ deps.nodeOperationStore = store;
46317
+ deps.nodeOperationService = service;
46318
+ return service;
46319
+ }
46320
+ async function dispatchNodeOperation(deps, operation, node) {
46321
+ const message = createNodeMessage("node.operation.execute", { operation });
46322
+ const heartbeat = deps.heartbeat;
46323
+ if (heartbeat.canPushToNode?.(node.id) === false) {
46324
+ if (!heartbeat.enqueueNodeMessage) throw new Error(`Cannot queue node operation for ${node.id}`);
46325
+ heartbeat.enqueueNodeMessage(node.id, message);
46326
+ return;
46327
+ }
46328
+ const client = new NodeMessageClient({
46329
+ heartbeat: heartbeat.enqueueNodeMessage ? { enqueueNodeMessage: heartbeat.enqueueNodeMessage.bind(heartbeat) } : void 0,
46330
+ logger: deps.logger
46331
+ });
46332
+ await client.send(node, message);
46333
+ }
46334
+ function runAgentUpgradeOperation(operation, deps) {
46335
+ const agent = readPayloadString(operation, "agent");
46336
+ if (!isRuntimeAgentId(agent)) throw new Error(`Unsupported upgrade agent: ${agent}`);
46337
+ const result = upgradeRuntimeAgentForDeps(deps, agent);
46338
+ if (!result.ok) {
46339
+ throw new NodeOperationFailure(result.detail ?? `${agent} upgrade failed`, result);
46340
+ }
46341
+ return result;
46342
+ }
46343
+ function readPayloadString(operation, key) {
46344
+ const payload = operation.payload;
46345
+ if (!payload || typeof payload !== "object") return "";
46346
+ const value = payload[key];
46347
+ return typeof value === "string" ? value : "";
46348
+ }
46349
+ function readSettingsSnapshot(value) {
46350
+ if (!value || typeof value !== "object") return void 0;
46351
+ const snapshot = value.settingsSnapshot;
46352
+ return snapshot && typeof snapshot === "object" ? snapshot : void 0;
46353
+ }
46354
+ function matchesFilter(operation, filter) {
46355
+ return (!filter.nodeId || operation.nodeId === filter.nodeId) && (!filter.status || operation.status === filter.status) && (!filter.kind || operation.kind === filter.kind);
46356
+ }
46357
+ function isNodeOperation(value) {
46358
+ if (!value || typeof value !== "object") return false;
46359
+ const record = value;
46360
+ return typeof record.id === "string" && typeof record.kind === "string" && typeof record.nodeId === "string" && typeof record.status === "string" && typeof record.createdAt === "number" && typeof record.updatedAt === "number";
46361
+ }
46362
+ function clone2(value) {
46363
+ return JSON.parse(JSON.stringify(value));
46364
+ }
46365
+
45147
46366
  // ../../packages/api/src/node/worker-control.ts
45148
46367
  function jsonResponse(requestId, statusCode, body) {
45149
46368
  return {
@@ -45303,6 +46522,23 @@ async function executeWorkerControlRequest(deps, request) {
45303
46522
  });
45304
46523
  break;
45305
46524
  }
46525
+ case "node.agent.upgrade": {
46526
+ const agent = payloadValue(request, "agent", "");
46527
+ if (!isRuntimeAgentId(agent)) {
46528
+ throw new MeshyError("VALIDATION_ERROR", `Unsupported upgrade agent: ${agent}`, 400);
46529
+ }
46530
+ response = jsonResponse(request.id, 200, upgradeRuntimeAgentForDeps(deps, agent));
46531
+ break;
46532
+ }
46533
+ case "node.operation.execute": {
46534
+ const operation = payloadValue(request, "operation", null);
46535
+ if (!operation || typeof operation !== "object") {
46536
+ throw new MeshyError("VALIDATION_ERROR", "node.operation.execute requires an operation payload", 400);
46537
+ }
46538
+ const accepted = getNodeOperationService(deps).accept(operation);
46539
+ response = jsonResponse(request.id, 202, { operationId: accepted.id, accepted: true });
46540
+ break;
46541
+ }
45306
46542
  case "task.cancel": {
45307
46543
  const taskId = payloadValue(request, "taskId", "");
45308
46544
  const result = cancelTaskOnCurrentNode({
@@ -45371,10 +46607,15 @@ async function executeWorkerControlRequest(deps, request) {
45371
46607
  break;
45372
46608
  }
45373
46609
  case "task.preview.create": {
46610
+ const previewPath = payloadValue(request, "path", void 0);
46611
+ const previewPort = payloadValue(request, "port", void 0);
45374
46612
  response = jsonResponse(
45375
46613
  request.id,
45376
46614
  200,
45377
- await createPreviewSessionPayload(deps, payloadValue(request, "taskId", ""), payloadValue(request, "path", void 0))
46615
+ await createPreviewSessionPayload(deps, payloadValue(request, "taskId", ""), {
46616
+ path: typeof previewPath === "string" ? previewPath : void 0,
46617
+ port: typeof previewPort === "number" ? previewPort : void 0
46618
+ })
45378
46619
  );
45379
46620
  break;
45380
46621
  }
@@ -45446,6 +46687,38 @@ function sendLocalNodeNativeSessions(req, res, nodeId, options = {}) {
45446
46687
  res.json(getLocalNodeNativeSessions(self2.id, query.agent, query.limit));
45447
46688
  }
45448
46689
 
46690
+ // ../../packages/api/src/routes/node-agent-upgrade.ts
46691
+ function parseAgent(value) {
46692
+ if (isRuntimeAgentId(value)) return value;
46693
+ throw new MeshyError("VALIDATION_ERROR", `Unsupported upgrade agent: ${value}`, 400);
46694
+ }
46695
+ async function sendNodeAgentUpgrade(req, res, nodeId, agentParam) {
46696
+ const deps = req.app.locals.deps;
46697
+ const agent = parseAgent(agentParam);
46698
+ const self2 = deps.nodeRegistry.getSelf();
46699
+ const isSelf = nodeId === self2.id;
46700
+ if (!isSelf && !deps.election.isLeader()) {
46701
+ throw new MeshyError("NOT_LEADER", "Only the leader can upgrade agents on other nodes", 403);
46702
+ }
46703
+ const node = isSelf ? self2 : deps.nodeRegistry.getNode(nodeId);
46704
+ if (!node) {
46705
+ throw new MeshyError("NODE_NOT_FOUND", `Node ${nodeId} not found`, 404);
46706
+ }
46707
+ const operations = getNodeOperationService(deps);
46708
+ const operation = operations.create("agent.upgrade", nodeId, { agent });
46709
+ if (isSelf) {
46710
+ operations.runLocal(operation.id);
46711
+ } else {
46712
+ try {
46713
+ await dispatchNodeOperation(deps, operation, node);
46714
+ } catch (err) {
46715
+ operations.markFailed(operation.id, err instanceof Error ? err.message : String(err));
46716
+ throw new MeshyError("NODE_OFFLINE", `Cannot reach node ${nodeId} to upgrade ${agent}`, 502);
46717
+ }
46718
+ }
46719
+ res.status(202).json(operation);
46720
+ }
46721
+
45449
46722
  // ../../packages/api/src/routes/nodes.ts
45450
46723
  var NODE_WORKDIR_PROXY_TIMEOUT_MS = 1e4;
45451
46724
  var NODE_WORKDIR_BRANCH_PROXY_TIMEOUT_MS = 25e3;
@@ -45785,35 +47058,38 @@ function createNodeRoutes() {
45785
47058
  const query = NodeListQuery.parse(req.query);
45786
47059
  let nodes = nodeRegistry.getAllNodes();
45787
47060
  if (query.status) {
45788
- nodes = nodes.filter((n) => n.status === query.status);
47061
+ nodes = nodes.filter((node) => node.status === query.status);
45789
47062
  }
45790
- if (query.capability) {
47063
+ const capability = query.capability;
47064
+ if (capability) {
45791
47065
  nodes = nodes.filter(
45792
- (n) => n.capabilities && n.capabilities.includes(query.capability)
47066
+ (node) => node.capabilities && node.capabilities.includes(capability)
45793
47067
  );
45794
47068
  }
45795
47069
  res.json({ nodes });
45796
47070
  }));
45797
47071
  router.get("/:id", asyncHandler3(async (req, res) => {
45798
47072
  const { nodeRegistry } = req.app.locals.deps;
45799
- const node = nodeRegistry.getNode(req.params.id);
47073
+ const nodeId = req.params.id;
47074
+ const node = nodeRegistry.getNode(nodeId);
45800
47075
  if (!node) {
45801
- throw new MeshyError("NODE_NOT_FOUND", `Node ${req.params.id} not found`, 404);
47076
+ throw new MeshyError("NODE_NOT_FOUND", `Node ${nodeId} not found`, 404);
45802
47077
  }
45803
47078
  res.json(node);
45804
47079
  }));
45805
47080
  router.get("/:id/status", asyncHandler3(async (req, res) => {
45806
47081
  const { nodeRegistry, taskEngine } = req.app.locals.deps;
45807
- const node = nodeRegistry.getNode(req.params.id);
47082
+ const nodeId = req.params.id;
47083
+ const node = nodeRegistry.getNode(nodeId);
45808
47084
  if (!node) {
45809
- throw new MeshyError("NODE_NOT_FOUND", `Node ${req.params.id} not found`, 404);
45810
- }
45811
- const { tasks } = taskEngine.listTasks({ assignedTo: req.params.id });
45812
- const taskSummary = tasks.map((t) => ({
45813
- id: t.id,
45814
- title: t.title,
45815
- status: t.status,
45816
- priority: t.priority
47085
+ throw new MeshyError("NODE_NOT_FOUND", `Node ${nodeId} not found`, 404);
47086
+ }
47087
+ const { tasks } = taskEngine.listTasks({ assignedTo: nodeId });
47088
+ const taskSummary = tasks.map((task) => ({
47089
+ id: task.id,
47090
+ title: task.title,
47091
+ status: task.status,
47092
+ priority: task.priority
45817
47093
  }));
45818
47094
  res.json({ node, tasks: taskSummary });
45819
47095
  }));
@@ -45849,6 +47125,9 @@ function createNodeRoutes() {
45849
47125
  }
45850
47126
  sendLocalNodeWorkDirBranchCreate(req, res, nodeId);
45851
47127
  }));
47128
+ router.post("/:id/agents/:agent/upgrade", asyncHandler3(async (req, res) => {
47129
+ await sendNodeAgentUpgrade(req, res, req.params.id, req.params.agent);
47130
+ }));
45852
47131
  router.patch("/:id", asyncHandler3(async (req, res) => {
45853
47132
  const { nodeRegistry, persistNodeNamePreference } = req.app.locals.deps;
45854
47133
  const updates = UpdateNodeBody.parse(req.body);
@@ -45874,14 +47153,15 @@ function createNodeRoutes() {
45874
47153
  }));
45875
47154
  router.delete("/:id", asyncHandler3(async (req, res) => {
45876
47155
  const { nodeRegistry, election } = req.app.locals.deps;
47156
+ const nodeId = req.params.id;
45877
47157
  if (!election.isLeader()) {
45878
47158
  throw new MeshyError("NOT_LEADER", "Only the leader node can delete nodes", 403);
45879
47159
  }
45880
- const node = nodeRegistry.getNode(req.params.id);
47160
+ const node = nodeRegistry.getNode(nodeId);
45881
47161
  if (!node) {
45882
- throw new MeshyError("NODE_NOT_FOUND", `Node ${req.params.id} not found`, 404);
47162
+ throw new MeshyError("NODE_NOT_FOUND", `Node ${nodeId} not found`, 404);
45883
47163
  }
45884
- nodeRegistry.removeNode(req.params.id);
47164
+ nodeRegistry.removeNode(nodeId);
45885
47165
  res.json({ ok: true });
45886
47166
  }));
45887
47167
  router.post("/:id/devtunnel", asyncHandler3(async (req, res) => {
@@ -46371,14 +47651,15 @@ async function sendTaskLogsResponse(req, res, taskId) {
46371
47651
  selfId
46372
47652
  });
46373
47653
  }
46374
- if (needsProxy) {
46375
- const node = nodeRegistry.getNode(task.assignedTo);
47654
+ const assignedTo = task.assignedTo;
47655
+ if (needsProxy && assignedTo) {
47656
+ const node = nodeRegistry.getNode(assignedTo);
46376
47657
  log2.debug("proxy target", { nodeId: node?.id, endpoint: node?.endpoint, devtunnel: node?.devtunnelEndpoint, status: node?.status });
46377
47658
  if (node) {
46378
47659
  const seededLogs = await seedTaskSnapshotOnWorker(task, [], node, log2).catch((err) => {
46379
47660
  log2.warn("failed to seed task snapshot before task logs proxy", {
46380
47661
  taskId,
46381
- assignedTo: task.assignedTo,
47662
+ assignedTo,
46382
47663
  ...describeProxyError3(err)
46383
47664
  });
46384
47665
  return [];
@@ -46397,24 +47678,24 @@ async function sendTaskLogsResponse(req, res, taskId) {
46397
47678
  const proxyUrl = `${endpoint}${proxyPath}`;
46398
47679
  log2.info("proxying task logs request", {
46399
47680
  taskId,
46400
- assignedTo: task.assignedTo,
47681
+ assignedTo,
46401
47682
  endpoint,
46402
47683
  proxyPath,
46403
47684
  url: proxyUrl
46404
47685
  });
46405
47686
  if (!proxyRes.ok) throw new MeshyError("NODE_OFFLINE", `Worker log proxy failed (${proxyRes.status})`, 502);
46406
47687
  const data = await proxyRes.json();
46407
- log2.debug("proxy returned", { logs: data?.logs?.length ?? 0, total: data?.total });
47688
+ log2.debug("proxy returned", { logs: data.logs?.length ?? 0, total: data.total });
46408
47689
  res.json(data);
46409
47690
  return;
46410
47691
  } catch (err) {
46411
47692
  log2.warn("task logs proxy failed; falling back to keepalive control", {
46412
47693
  taskId,
46413
- assignedTo: task.assignedTo,
47694
+ assignedTo,
46414
47695
  timeoutMs: TASK_LOG_PROXY_TIMEOUT_MS,
46415
47696
  ...describeProxyError3(err)
46416
47697
  });
46417
- const fallback = await requestTaskLogsOverKeepalive(heartbeat, task.assignedTo, task, after);
47698
+ const fallback = await requestTaskLogsOverKeepalive(heartbeat, assignedTo, task, after);
46418
47699
  if (fallback) {
46419
47700
  sendWorkerControlResponse(res, fallback);
46420
47701
  return;
@@ -46790,12 +48071,12 @@ function createTaskOutputRoutes(options = {}) {
46790
48071
  method: "POST",
46791
48072
  headers: { "Content-Type": "application/json" },
46792
48073
  body: JSON.stringify(body)
46793
- }, createNodeMessage("task.preview.create", { taskId, path: body.path }, { expectsResponse: true }));
48074
+ }, createNodeMessage("task.preview.create", { taskId, path: body.path, port: body.port }, { expectsResponse: true }));
46794
48075
  if (handled) {
46795
48076
  return;
46796
48077
  }
46797
48078
  }
46798
- res.json(await createPreviewSessionPayload(req.app.locals.deps, taskId, body.path, resolveRequestOrigin(req)));
48079
+ res.json(await createPreviewSessionPayload(req.app.locals.deps, taskId, body, resolveRequestOrigin(req)));
46799
48080
  }));
46800
48081
  return router;
46801
48082
  }
@@ -47062,13 +48343,14 @@ function createTaskRoutes() {
47062
48343
  const { taskEngine, nodeRegistry, logger: rootLogger } = req.app.locals.deps;
47063
48344
  const log2 = rootLogger.child("tasks/patch");
47064
48345
  const updates = UpdateTaskBody.parse(req.body);
47065
- const existing = taskEngine.getTask(req.params.id);
48346
+ const taskId = req.params.id;
48347
+ const existing = taskEngine.getTask(taskId);
47066
48348
  if (!existing) {
47067
- throw new MeshyError("TASK_NOT_FOUND", `Task ${req.params.id} not found`, 404);
48349
+ throw new MeshyError("TASK_NOT_FOUND", `Task ${taskId} not found`, 404);
47068
48350
  }
47069
48351
  if (updates.status !== void 0 && TERMINAL_STATUSES3.has(existing.status) && ACTIVE_STATUSES.has(updates.status)) {
47070
48352
  log2.warn("ignoring stale status regression for terminal task", {
47071
- taskId: req.params.id,
48353
+ taskId,
47072
48354
  currentStatus: existing.status,
47073
48355
  incomingStatus: updates.status
47074
48356
  });
@@ -47084,33 +48366,35 @@ function createTaskRoutes() {
47084
48366
  }
47085
48367
  if (updates.status !== void 0 && existing.status === "archived" && updates.status !== "archived") {
47086
48368
  log2.warn("ignoring status change for archived task", {
47087
- taskId: req.params.id,
48369
+ taskId,
47088
48370
  currentStatus: existing.status,
47089
48371
  incomingStatus: updates.status
47090
48372
  });
47091
48373
  res.json(withAssignedNodeMetadata(existing, nodeRegistry));
47092
48374
  return;
47093
48375
  }
47094
- const task = taskEngine.updateTask(req.params.id, updates);
48376
+ const task = taskEngine.updateTask(taskId, updates);
47095
48377
  if (!task) {
47096
- throw new MeshyError("TASK_NOT_FOUND", `Task ${req.params.id} not found`, 404);
48378
+ throw new MeshyError("TASK_NOT_FOUND", `Task ${taskId} not found`, 404);
47097
48379
  }
47098
48380
  res.json(withAssignedNodeMetadata(task, nodeRegistry));
47099
48381
  }));
47100
48382
  router.delete("/:id", asyncHandler6(async (req, res) => {
47101
48383
  const { taskEngine } = req.app.locals.deps;
47102
- const result = taskEngine.deleteTask(req.params.id);
48384
+ const taskId = req.params.id;
48385
+ const result = taskEngine.deleteTask(taskId);
47103
48386
  if (!result) {
47104
- throw new MeshyError("TASK_NOT_FOUND", `Task ${req.params.id} not found`, 404);
48387
+ throw new MeshyError("TASK_NOT_FOUND", `Task ${taskId} not found`, 404);
47105
48388
  }
47106
48389
  res.json({ ok: true });
47107
48390
  }));
47108
48391
  router.post("/:id/cancel", asyncHandler6(async (req, res) => {
47109
48392
  const { taskEngine, nodeRegistry, engineRegistry, heartbeat, logger: rootLogger } = req.app.locals.deps;
47110
48393
  const log2 = rootLogger.child("tasks/cancel");
47111
- const task = taskEngine.getTask(req.params.id);
48394
+ const taskId = req.params.id;
48395
+ const task = taskEngine.getTask(taskId);
47112
48396
  if (!task) {
47113
- throw new MeshyError("TASK_NOT_FOUND", `Task ${req.params.id} not found`, 404);
48397
+ throw new MeshyError("TASK_NOT_FOUND", `Task ${taskId} not found`, 404);
47114
48398
  }
47115
48399
  if (TERMINAL_STATUSES3.has(task.status)) {
47116
48400
  throw new MeshyError("VALIDATION_ERROR", `Task ${task.id} cannot be cancelled (status: ${task.status})`, 400);
@@ -47160,9 +48444,10 @@ function createTaskRoutes() {
47160
48444
  const { taskEngine, engineRegistry, nodeRegistry, heartbeat, logger: rootLogger } = req.app.locals.deps;
47161
48445
  const log2 = rootLogger.child("tasks/message");
47162
48446
  const body = SendMessageBody.parse(req.body);
47163
- const task = taskEngine.getTask(req.params.id);
48447
+ const taskId = req.params.id;
48448
+ const task = taskEngine.getTask(taskId);
47164
48449
  if (!task) {
47165
- throw new MeshyError("TASK_NOT_FOUND", `Task ${req.params.id} not found`, 404);
48450
+ throw new MeshyError("TASK_NOT_FOUND", `Task ${taskId} not found`, 404);
47166
48451
  }
47167
48452
  if (!supportsFollowUpAgent(task.agent)) {
47168
48453
  throw new MeshyError("VALIDATION_ERROR", `Agent ${task.agent} does not support chat messages`, 400);
@@ -47356,13 +48641,16 @@ function createSharedRoutes() {
47356
48641
  const shareId = req.params.shareId;
47357
48642
  const share = assertActiveShare(taskEngine.getTaskShare(shareId));
47358
48643
  assertFilesPreviewShare(share);
48644
+ if (body.port !== void 0) {
48645
+ throw new MeshyError("VALIDATION_ERROR", "Shared previews only support task output files", 403);
48646
+ }
47359
48647
  const handled = await maybeHandleRemoteTaskOutputRequest(req, res, share.taskId, "/preview-sessions", {
47360
48648
  method: "POST",
47361
48649
  headers: { "Content-Type": "application/json" },
47362
48650
  body: JSON.stringify(body)
47363
48651
  }, createNodeMessage("task.preview.create", { taskId: share.taskId, path: body.path }, { expectsResponse: true }));
47364
48652
  if (handled) return;
47365
- res.json(await createPreviewSessionPayload(req.app.locals.deps, share.taskId, body.path, resolveRequestOrigin(req)));
48653
+ res.json(await createPreviewSessionPayload(req.app.locals.deps, share.taskId, body, resolveRequestOrigin(req)));
47366
48654
  }));
47367
48655
  return router;
47368
48656
  }
@@ -47380,6 +48668,15 @@ function asyncHandler8(fn) {
47380
48668
  }
47381
48669
  function createWorkerRoutes() {
47382
48670
  const router = (0, import_express10.Router)();
48671
+ router.post("/node-operations/:id", asyncHandler8(async (req, res) => {
48672
+ const deps = req.app.locals.deps;
48673
+ const operation = req.body;
48674
+ if (!operation || operation.id !== req.params.id) {
48675
+ throw new MeshyError("VALIDATION_ERROR", "Node operation update id mismatch", 400);
48676
+ }
48677
+ const saved = getNodeOperationService(deps).applyRemoteUpdate(operation);
48678
+ res.json({ ok: true, operation: saved });
48679
+ }));
47383
48680
  router.post("/execute", asyncHandler8(async (req, res) => {
47384
48681
  const { taskEngine, engineRegistry, nodeRegistry, eventBus, logger: rootLogger, workDir } = req.app.locals.deps;
47385
48682
  const log2 = rootLogger.child("worker/execute");
@@ -47551,20 +48848,20 @@ function createWorkerRoutes() {
47551
48848
  const payload = await createPreviewSessionPayload(
47552
48849
  req.app.locals.deps,
47553
48850
  body.taskId,
47554
- body.path,
48851
+ body,
47555
48852
  resolveRequestOrigin(req)
47556
48853
  );
47557
- log2.info("created preview session", { taskId: body.taskId, entryPath: payload.entryPath });
48854
+ log2.info("created preview session", { taskId: body.taskId, entryPath: payload.entryPath, kind: payload.kind, port: payload.port });
47558
48855
  res.json(payload);
47559
48856
  }));
47560
- router.get("/preview-asset", asyncHandler8(async (req, res) => {
48857
+ router.all("/preview-asset", asyncHandler8(async (req, res) => {
47561
48858
  const { previewSessionManager } = req.app.locals.deps;
47562
48859
  if (!previewSessionManager) {
47563
48860
  throw new MeshyError("VALIDATION_ERROR", "Preview not available on this node", 400);
47564
48861
  }
47565
48862
  const token = external_exports.string().min(1).parse(req.query.token);
47566
48863
  const requestedPath = typeof req.query.path === "string" && req.query.path.length > 0 ? req.query.path : void 0;
47567
- sendPreviewAssetResponse(previewSessionManager, token, requestedPath, res);
48864
+ await sendPreviewAssetResponse(previewSessionManager, token, requestedPath, res, req);
47568
48865
  }));
47569
48866
  router.post("/control-response", asyncHandler8(async (req, res) => {
47570
48867
  const { heartbeat, logger: rootLogger } = req.app.locals.deps;
@@ -47594,123 +48891,6 @@ function normalizeNodeMessageResponse(value) {
47594
48891
 
47595
48892
  // ../../packages/api/src/routes/system.ts
47596
48893
  var import_express11 = __toESM(require_express2(), 1);
47597
-
47598
- // ../../packages/api/src/app/system-info.ts
47599
- var os6 = __toESM(require("os"), 1);
47600
- var import_node_child_process8 = require("child_process");
47601
- var RUNTIME_TOOLS = [
47602
- { id: "claude", label: "Claude Code", command: "claude" },
47603
- { id: "codex", label: "Codex", command: "codex" }
47604
- ];
47605
- function normalizeOutput(output) {
47606
- if (!output) {
47607
- return null;
47608
- }
47609
- const firstLine = output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
47610
- return firstLine ?? null;
47611
- }
47612
- function resolveCommandPath(command) {
47613
- const lookupCommand = process.platform === "win32" ? "where" : "which";
47614
- const result = (0, import_node_child_process8.spawnSync)(lookupCommand, [command], {
47615
- encoding: "utf-8",
47616
- shell: false,
47617
- windowsHide: true,
47618
- timeout: 1500
47619
- });
47620
- if (result.status === 0) {
47621
- return { path: normalizeOutput(result.stdout) };
47622
- }
47623
- return {
47624
- path: null,
47625
- detail: normalizeOutput(result.stderr) ?? result.error?.message ?? null
47626
- };
47627
- }
47628
- function inspectTool(definition) {
47629
- const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
47630
- const resolved = resolveCommandPath(definition.command);
47631
- if (!resolved.path) {
47632
- return {
47633
- id: definition.id,
47634
- label: definition.label,
47635
- command: definition.command,
47636
- available: false,
47637
- path: null,
47638
- version: null,
47639
- checkedAt,
47640
- detail: resolved.detail ?? "Command not found on PATH"
47641
- };
47642
- }
47643
- const versionResult = (0, import_node_child_process8.spawnSync)(definition.command, ["--version"], {
47644
- encoding: "utf-8",
47645
- shell: process.platform === "win32",
47646
- windowsHide: true,
47647
- timeout: 2500
47648
- });
47649
- const version2 = normalizeOutput(versionResult.stdout) ?? normalizeOutput(versionResult.stderr);
47650
- const detail = versionResult.status === 0 ? null : normalizeOutput(versionResult.stderr) ?? versionResult.error?.message ?? "Version check failed";
47651
- return {
47652
- id: definition.id,
47653
- label: definition.label,
47654
- command: definition.command,
47655
- available: true,
47656
- path: resolved.path,
47657
- version: version2,
47658
- checkedAt,
47659
- detail
47660
- };
47661
- }
47662
- function inspectRuntimeTools() {
47663
- return RUNTIME_TOOLS.map(inspectTool);
47664
- }
47665
- function getOsSnapshot() {
47666
- const cpus2 = os6.cpus();
47667
- return {
47668
- platform: os6.platform(),
47669
- release: os6.release(),
47670
- arch: os6.arch(),
47671
- hostname: os6.hostname(),
47672
- cpuModel: cpus2[0]?.model ?? null,
47673
- cpuCount: cpus2.length,
47674
- totalMemoryBytes: os6.totalmem(),
47675
- freeMemoryBytes: os6.freemem()
47676
- };
47677
- }
47678
- function buildNodeSettingsSnapshot(options) {
47679
- const uptime = process.uptime();
47680
- const runtimeMetadata = options.runtimeMetadata;
47681
- const agents = (options.inspectRuntimeTools?.() ?? inspectRuntimeTools()).map((agent) => ({
47682
- ...agent,
47683
- metadataStatus: runtimeMetadata?.components?.[agent.id]?.status ?? null
47684
- }));
47685
- return {
47686
- collectedAt: Date.now(),
47687
- version: runtimeMetadata?.packageVersion ?? "0.1.0",
47688
- packageName: runtimeMetadata?.packageName ?? "meshy",
47689
- uptime,
47690
- auth: options.auth,
47691
- os: getOsSnapshot(),
47692
- runtime: {
47693
- nodeVersion: process.version,
47694
- pid: process.pid,
47695
- startedAt: Date.now() - Math.floor(uptime * 1e3),
47696
- cwd: process.cwd(),
47697
- workDir: options.workDir ?? null,
47698
- storagePath: options.storagePath ?? null,
47699
- localDashboardOrigin: options.localDashboardOrigin ?? null
47700
- },
47701
- agents,
47702
- startupRequirements: {
47703
- lastCheckedAt: runtimeMetadata?.startupRequirementsLastCheckedAt,
47704
- lastCheckedOn: runtimeMetadata?.startupRequirementsLastCheckedOn,
47705
- components: runtimeMetadata?.components ?? {}
47706
- },
47707
- components: runtimeMetadata?.components ?? {},
47708
- repository: runtimeMetadata?.repository ?? {},
47709
- packages: runtimeMetadata?.packages ?? {}
47710
- };
47711
- }
47712
-
47713
- // ../../packages/api/src/routes/system.ts
47714
48894
  function asyncHandler9(fn) {
47715
48895
  return (req, res, next) => fn(req, res, next).catch(next);
47716
48896
  }
@@ -47776,8 +48956,8 @@ function createSystemRoutes() {
47776
48956
  return;
47777
48957
  }
47778
48958
  const { type } = req.body;
47779
- if (!type || !["direct", "devtunnel", "tailscale"].includes(type)) {
47780
- res.status(400).json({ error: "Invalid transport type. Must be: direct, devtunnel, or tailscale" });
48959
+ if (!type || !["direct", "devtunnel"].includes(type)) {
48960
+ res.status(400).json({ error: "Invalid transport type. Must be: direct or devtunnel" });
47781
48961
  return;
47782
48962
  }
47783
48963
  const newEndpoint = await switchTransport(type);
@@ -47824,15 +49004,17 @@ function createSystemRoutes() {
47824
49004
  var import_express12 = __toESM(require_express2(), 1);
47825
49005
  var HEARTBEAT_INTERVAL_MS = 15e3;
47826
49006
  var CATEGORY_MAP = {
47827
- tasks: "task.",
47828
- nodes: "node.",
47829
- elections: "election.",
47830
- cluster: "cluster."
49007
+ tasks: ["task."],
49008
+ nodes: ["node.", "transport."],
49009
+ elections: ["election."],
49010
+ cluster: ["cluster."]
47831
49011
  };
47832
49012
  var ALL_EVENT_NAMES = [
47833
49013
  "node.joined",
47834
49014
  "node.left",
47835
49015
  "node.status",
49016
+ "node.operation.created",
49017
+ "node.operation.updated",
47836
49018
  "task.created",
47837
49019
  "task.assigned",
47838
49020
  "task.status",
@@ -47841,7 +49023,8 @@ var ALL_EVENT_NAMES = [
47841
49023
  "task.output",
47842
49024
  "election.started",
47843
49025
  "election.complete",
47844
- "cluster.state"
49026
+ "cluster.state",
49027
+ "transport.changed"
47845
49028
  ];
47846
49029
  function parseFilter(filterParam) {
47847
49030
  if (typeof filterParam !== "string" || filterParam.trim() === "") {
@@ -47852,14 +49035,15 @@ function parseFilter(filterParam) {
47852
49035
  function shouldIncludeEvent(eventName, categories) {
47853
49036
  if (!categories) return true;
47854
49037
  return categories.some((cat) => {
47855
- const prefix = CATEGORY_MAP[cat];
47856
- return prefix != null && eventName.startsWith(prefix);
49038
+ const prefixes = CATEGORY_MAP[cat];
49039
+ return prefixes != null && prefixes.some((prefix) => eventName.startsWith(prefix));
47857
49040
  });
47858
49041
  }
47859
49042
  function createEventRoutes() {
47860
49043
  const router = (0, import_express12.Router)();
47861
49044
  router.get("/", (req, res) => {
47862
49045
  const { eventBus } = req.app.locals.deps;
49046
+ const stream = res;
47863
49047
  const categories = parseFilter(req.query.filter);
47864
49048
  res.writeHead(200, {
47865
49049
  "Content-Type": "text/event-stream",
@@ -47876,20 +49060,14 @@ data: ${JSON.stringify(data)}
47876
49060
 
47877
49061
  `;
47878
49062
  res.write(payload);
47879
- if (typeof res.flush === "function") {
47880
- ;
47881
- res.flush();
47882
- }
49063
+ stream.flush?.();
47883
49064
  };
47884
49065
  listeners.set(eventName, listener);
47885
49066
  eventBus.on(eventName, listener);
47886
49067
  }
47887
49068
  const heartbeatTimer = setInterval(() => {
47888
49069
  res.write(": heartbeat\n\n");
47889
- if (typeof res.flush === "function") {
47890
- ;
47891
- res.flush();
47892
- }
49070
+ stream.flush?.();
47893
49071
  }, HEARTBEAT_INTERVAL_MS);
47894
49072
  req.on("close", () => {
47895
49073
  clearInterval(heartbeatTimer);
@@ -47902,6 +49080,37 @@ data: ${JSON.stringify(data)}
47902
49080
  return router;
47903
49081
  }
47904
49082
 
49083
+ // ../../packages/api/src/routes/node-operations.ts
49084
+ var import_express13 = __toESM(require_express2(), 1);
49085
+ function asyncHandler10(fn) {
49086
+ return (req, res, next) => fn(req, res, next).catch(next);
49087
+ }
49088
+ function parseStatus(value) {
49089
+ if (value === "queued" || value === "running" || value === "succeeded" || value === "failed") return value;
49090
+ return void 0;
49091
+ }
49092
+ function createNodeOperationRoutes() {
49093
+ const router = (0, import_express13.Router)();
49094
+ router.get("/", asyncHandler10(async (req, res) => {
49095
+ const deps = req.app.locals.deps;
49096
+ const operations = getNodeOperationService(deps).list({
49097
+ nodeId: typeof req.query.nodeId === "string" ? req.query.nodeId : void 0,
49098
+ status: parseStatus(req.query.status),
49099
+ kind: typeof req.query.kind === "string" ? req.query.kind : void 0
49100
+ });
49101
+ res.json({ operations });
49102
+ }));
49103
+ router.get("/:id", asyncHandler10(async (req, res) => {
49104
+ const deps = req.app.locals.deps;
49105
+ const operation = getNodeOperationService(deps).get(req.params.id);
49106
+ if (!operation) {
49107
+ throw new MeshyError("NODE_NOT_FOUND", `Node operation ${req.params.id} not found`, 404);
49108
+ }
49109
+ res.json(operation);
49110
+ }));
49111
+ return router;
49112
+ }
49113
+
47905
49114
  // ../../packages/api/src/app/server.ts
47906
49115
  var JSON_BODY_LIMIT = "1mb";
47907
49116
  var JSON_BODY_LIMIT_LARGE = "25mb";
@@ -47939,11 +49148,18 @@ function isShareHostRequest(req, shareOrigin) {
47939
49148
  function isAllowedSharePath(pathname) {
47940
49149
  return pathname === "/favicon.ico" || pathname === "/api/shared" || pathname.startsWith("/api/shared/") || pathname === "/preview" || pathname.startsWith("/preview/") || pathname === "/shared" || pathname.startsWith("/shared/") || pathname === "/assets" || pathname.startsWith("/assets/");
47941
49150
  }
49151
+ function hasAuthorizationHeader(req) {
49152
+ const header = req.headers[MESHY_AUTHORIZATION_HEADER] ?? req.headers.authorization;
49153
+ if (Array.isArray(header)) {
49154
+ return header.some((value) => value.trim().length > 0);
49155
+ }
49156
+ return typeof header === "string" && header.trim().length > 0;
49157
+ }
47942
49158
  function resolveRuntimeBaseDir() {
47943
49159
  const entryPath = process.argv[1];
47944
49160
  if (typeof entryPath === "string" && entryPath.length > 0) {
47945
- const resolved = fs18.realpathSync(path19.resolve(entryPath));
47946
- return path19.dirname(resolved);
49161
+ const resolved = fs19.realpathSync(path20.resolve(entryPath));
49162
+ return path20.dirname(resolved);
47947
49163
  }
47948
49164
  return process.cwd();
47949
49165
  }
@@ -47951,25 +49167,25 @@ function resolveStaticDir(baseDir) {
47951
49167
  const envStaticDir = process.env.MESHY_STATIC_DIR;
47952
49168
  const candidateDirs = [
47953
49169
  envStaticDir,
47954
- path19.resolve(baseDir, "dashboard"),
47955
- path19.resolve(baseDir, "../dashboard"),
47956
- path19.resolve(baseDir, "../../dashboard/dist"),
47957
- path19.resolve(baseDir, "../../../packages/dashboard/dist"),
47958
- path19.resolve(baseDir, "../public"),
47959
- path19.resolve(baseDir, "../../packages/api/public"),
47960
- path19.resolve(baseDir, "../../../packages/api/public"),
47961
- path19.resolve(process.cwd(), "packages/dashboard/dist"),
47962
- path19.resolve(process.cwd(), "packages/api/public")
49170
+ path20.resolve(baseDir, "dashboard"),
49171
+ path20.resolve(baseDir, "../dashboard"),
49172
+ path20.resolve(baseDir, "../../dashboard/dist"),
49173
+ path20.resolve(baseDir, "../../../packages/dashboard/dist"),
49174
+ path20.resolve(baseDir, "../public"),
49175
+ path20.resolve(baseDir, "../../packages/api/public"),
49176
+ path20.resolve(baseDir, "../../../packages/api/public"),
49177
+ path20.resolve(process.cwd(), "packages/dashboard/dist"),
49178
+ path20.resolve(process.cwd(), "packages/api/public")
47963
49179
  ].filter((value) => typeof value === "string" && value.length > 0);
47964
49180
  for (const candidate of candidateDirs) {
47965
- if (fs18.existsSync(candidate)) {
49181
+ if (fs19.existsSync(candidate)) {
47966
49182
  return candidate;
47967
49183
  }
47968
49184
  }
47969
49185
  return null;
47970
49186
  }
47971
49187
  function createServer2(deps) {
47972
- const app = (0, import_express13.default)();
49188
+ const app = (0, import_express14.default)();
47973
49189
  app.locals.deps = deps;
47974
49190
  if (typeof deps.heartbeat.setNodeMessageHandler === "function") {
47975
49191
  deps.heartbeat.setNodeMessageHandler((message) => handleNodeMessage(deps, message));
@@ -47995,7 +49211,9 @@ function createServer2(deps) {
47995
49211
  }
47996
49212
  };
47997
49213
  const isApiRequest = (req) => req.path === "/api" || req.path.startsWith("/api/");
49214
+ const isPreviewRequest = (req) => req.path.startsWith("/preview/") || req.path.startsWith("/preview-open/");
47998
49215
  const canServeDashboard = (req) => !deps.config.validateBearerToken || isTrustedDashboardRequest(req, authConfig);
49216
+ const canServePreview = (req) => canServeDashboard(req) || hasAuthorizationHeader(req);
47999
49217
  app.use((req, res, next) => {
48000
49218
  if (!isShareHostRequest(req, deps.shareOrigin)) {
48001
49219
  next();
@@ -48010,9 +49228,9 @@ function createServer2(deps) {
48010
49228
  const runtimeBaseDir = resolveRuntimeBaseDir();
48011
49229
  const staticDir = resolveStaticDir(runtimeBaseDir);
48012
49230
  if (staticDir) {
48013
- const staticMiddleware = import_express13.default.static(staticDir);
49231
+ const staticMiddleware = import_express14.default.static(staticDir);
48014
49232
  app.use((req, res, next) => {
48015
- if (isApiRequest(req)) {
49233
+ if (isApiRequest(req) || isPreviewRequest(req)) {
48016
49234
  next();
48017
49235
  return;
48018
49236
  }
@@ -48023,29 +49241,33 @@ function createServer2(deps) {
48023
49241
  staticMiddleware(req, res, next);
48024
49242
  });
48025
49243
  }
48026
- app.use(import_express13.default.json({ limit: JSON_BODY_LIMIT }));
49244
+ app.use(import_express14.default.json({ limit: JSON_BODY_LIMIT }));
48027
49245
  app.use(createAuthMiddleware(authConfig));
48028
49246
  app.use((req, res, next) => {
48029
49247
  void (async () => {
48030
- if (!req.path.startsWith("/preview/")) {
49248
+ if (!isPreviewRequest(req)) {
48031
49249
  next();
48032
49250
  return;
48033
49251
  }
48034
- if (!canServeDashboard(req)) {
49252
+ if (!canServePreview(req)) {
48035
49253
  res.status(404).type("text/plain").send("Not Found");
48036
49254
  return;
48037
49255
  }
48038
49256
  if (deps.previewProxyManager && await handlePreviewProxyRequest(deps.previewProxyManager, deps.nodeRegistry, deps.logger, req, res)) {
48039
49257
  return;
48040
49258
  }
48041
- if (deps.previewSessionManager && handlePreviewRequest(deps.previewSessionManager, req, res)) {
49259
+ if (deps.previewSessionManager && await handlePreviewRequest(deps.previewSessionManager, req, res)) {
48042
49260
  return;
48043
49261
  }
48044
49262
  next();
48045
49263
  })().catch(next);
48046
49264
  });
48047
- app.use(createRoutingMiddleware(deps.dataRouter));
48048
- const largeBodyParser = import_express13.default.json({ limit: JSON_BODY_LIMIT_LARGE });
49265
+ app.use(createRoutingMiddleware({
49266
+ dataRouter: deps.dataRouter,
49267
+ taskEngine: deps.taskEngine,
49268
+ logger: deps.logger
49269
+ }));
49270
+ const largeBodyParser = import_express14.default.json({ limit: JSON_BODY_LIMIT_LARGE });
48049
49271
  app.use("/api/cluster", createClusterRoutes());
48050
49272
  app.use("/api/cluster-control", createClusterControlRoutes());
48051
49273
  app.use("/api/node", largeBodyParser, createNodeMessageRoutes());
@@ -48054,10 +49276,11 @@ function createServer2(deps) {
48054
49276
  app.use("/api/shared", createSharedRoutes());
48055
49277
  app.use("/api/worker", largeBodyParser, createWorkerRoutes());
48056
49278
  app.use("/api/system", createSystemRoutes());
49279
+ app.use("/api/node-operations", createNodeOperationRoutes());
48057
49280
  app.use("/api/events", createEventRoutes());
48058
49281
  if (staticDir) {
48059
- const indexPath = path19.join(staticDir, "index.html");
48060
- if (fs18.existsSync(indexPath)) {
49282
+ const indexPath = path20.join(staticDir, "index.html");
49283
+ if (fs19.existsSync(indexPath)) {
48061
49284
  app.get("*", (req, res, next) => {
48062
49285
  if (isApiRequest(req)) {
48063
49286
  next();
@@ -48141,10 +49364,10 @@ var DirectTransport = class {
48141
49364
  };
48142
49365
 
48143
49366
  // ../../packages/transport/src/devtunnel.ts
48144
- var import_node_child_process9 = require("child_process");
49367
+ var import_node_child_process10 = require("child_process");
48145
49368
  function isInstalled(cmd) {
48146
49369
  try {
48147
- (0, import_node_child_process9.execSync)(process.platform === "win32" ? `where ${cmd}` : `command -v ${cmd}`, { stdio: "pipe" });
49370
+ (0, import_node_child_process10.execSync)(process.platform === "win32" ? `where ${cmd}` : `command -v ${cmd}`, { stdio: "pipe" });
48148
49371
  return true;
48149
49372
  } catch {
48150
49373
  return false;
@@ -48167,14 +49390,14 @@ var DevTunnelTransport = class {
48167
49390
  );
48168
49391
  }
48169
49392
  try {
48170
- (0, import_node_child_process9.execSync)("devtunnel user show", { stdio: "pipe" });
49393
+ (0, import_node_child_process10.execSync)("devtunnel user show", { stdio: "pipe" });
48171
49394
  } catch {
48172
49395
  throw new Error(
48173
49396
  "Not logged in to devtunnel. Run: devtunnel user login"
48174
49397
  );
48175
49398
  }
48176
49399
  const hostArgs = this.buildHostArgs(localPort);
48177
- const child = (0, import_node_child_process9.spawn)("devtunnel", hostArgs, {
49400
+ const child = (0, import_node_child_process10.spawn)("devtunnel", hostArgs, {
48178
49401
  stdio: ["pipe", "pipe", "pipe"]
48179
49402
  });
48180
49403
  this.process = child;
@@ -48279,7 +49502,7 @@ ${lines.join("")}`
48279
49502
  return;
48280
49503
  }
48281
49504
  try {
48282
- (0, import_node_child_process9.execFileSync)("devtunnel", ["access", "create", tunnelId, "--tenant"], { stdio: "pipe" });
49505
+ (0, import_node_child_process10.execFileSync)("devtunnel", ["access", "create", tunnelId, "--tenant"], { stdio: "pipe" });
48283
49506
  } catch (err) {
48284
49507
  if (isExistingTenantAccessError(err)) {
48285
49508
  return;
@@ -48295,7 +49518,7 @@ ${lines.join("")}`
48295
49518
  return void 0;
48296
49519
  }
48297
49520
  try {
48298
- (0, import_node_child_process9.execFileSync)("devtunnel", ["show", tunnelId], { stdio: "pipe" });
49521
+ (0, import_node_child_process10.execFileSync)("devtunnel", ["show", tunnelId], { stdio: "pipe" });
48299
49522
  return tunnelId;
48300
49523
  } catch {
48301
49524
  const createArgs = ["create", tunnelId];
@@ -48303,7 +49526,7 @@ ${lines.join("")}`
48303
49526
  createArgs.push("-a");
48304
49527
  }
48305
49528
  try {
48306
- (0, import_node_child_process9.execFileSync)("devtunnel", createArgs, { stdio: "pipe" });
49529
+ (0, import_node_child_process10.execFileSync)("devtunnel", createArgs, { stdio: "pipe" });
48307
49530
  return tunnelId;
48308
49531
  } catch (err) {
48309
49532
  throw new Error(
@@ -48315,13 +49538,13 @@ ${lines.join("")}`
48315
49538
  ensureTunnelPort(tunnelId, localPort) {
48316
49539
  const ports = this.listTunnelPorts(tunnelId);
48317
49540
  for (const stalePort of ports.filter((p) => p !== localPort)) {
48318
- (0, import_node_child_process9.execFileSync)("devtunnel", ["port", "delete", tunnelId, "-p", String(stalePort)], { stdio: "pipe" });
49541
+ (0, import_node_child_process10.execFileSync)("devtunnel", ["port", "delete", tunnelId, "-p", String(stalePort)], { stdio: "pipe" });
48319
49542
  }
48320
49543
  if (ports.includes(localPort)) {
48321
49544
  return;
48322
49545
  }
48323
49546
  try {
48324
- (0, import_node_child_process9.execFileSync)(
49547
+ (0, import_node_child_process10.execFileSync)(
48325
49548
  "devtunnel",
48326
49549
  ["port", "create", tunnelId, "-p", String(localPort), "--protocol", "http"],
48327
49550
  { stdio: "pipe" }
@@ -48337,7 +49560,7 @@ ${lines.join("")}`
48337
49560
  }
48338
49561
  listTunnelPorts(tunnelId) {
48339
49562
  try {
48340
- const output = (0, import_node_child_process9.execFileSync)("devtunnel", ["port", "list", tunnelId, "-j"], { stdio: "pipe" });
49563
+ const output = (0, import_node_child_process10.execFileSync)("devtunnel", ["port", "list", tunnelId, "-j"], { stdio: "pipe" });
48341
49564
  const parsed = JSON.parse(output.toString());
48342
49565
  const items = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" && Array.isArray(parsed.ports) ? parsed.ports : parsed && typeof parsed === "object" && Array.isArray(parsed.value) ? parsed.value : [];
48343
49566
  return items.map((item) => getPortNumber(item)).filter((value) => value !== void 0);
@@ -48349,7 +49572,7 @@ ${lines.join("")}`
48349
49572
  }
48350
49573
  hasTunnelPort(tunnelId, localPort) {
48351
49574
  try {
48352
- (0, import_node_child_process9.execFileSync)(
49575
+ (0, import_node_child_process10.execFileSync)(
48353
49576
  "devtunnel",
48354
49577
  ["port", "show", tunnelId, "-p", String(localPort), "-j"],
48355
49578
  { stdio: "pipe" }
@@ -48426,16 +49649,42 @@ function createTransport(config) {
48426
49649
  }
48427
49650
  }
48428
49651
 
49652
+ // src/bootstrap/terminal-writer.ts
49653
+ function formatDetail(detail) {
49654
+ if (detail instanceof Error) {
49655
+ return detail.stack ?? detail.message;
49656
+ }
49657
+ if (typeof detail === "string") {
49658
+ return detail;
49659
+ }
49660
+ try {
49661
+ return JSON.stringify(detail);
49662
+ } catch {
49663
+ return String(detail);
49664
+ }
49665
+ }
49666
+ var terminalWriter = {
49667
+ error(message, ...details) {
49668
+ const suffix = details.length > 0 ? ` ${details.map(formatDetail).join(" ")}` : "";
49669
+ process.stderr.write(`${message}${suffix}
49670
+ `);
49671
+ },
49672
+ line(message = "") {
49673
+ process.stdout.write(`${message}
49674
+ `);
49675
+ }
49676
+ };
49677
+
48429
49678
  // src/startup.ts
48430
- var fs19 = __toESM(require("fs"), 1);
48431
- var path20 = __toESM(require("path"), 1);
49679
+ var fs20 = __toESM(require("fs"), 1);
49680
+ var path21 = __toESM(require("path"), 1);
48432
49681
  var readline = __toESM(require("readline/promises"), 1);
48433
- var import_node_child_process10 = require("child_process");
49682
+ var import_node_child_process11 = require("child_process");
48434
49683
  function getDefaultNodeName() {
48435
49684
  return getDeviceNodeName();
48436
49685
  }
48437
49686
  var DEFAULT_NODE_NAME = getDefaultNodeName();
48438
- var SUPPORTED_TRANSPORTS = ["direct", "devtunnel", "tailscale"];
49687
+ var SUPPORTED_TRANSPORTS = ["direct", "devtunnel"];
48439
49688
  var STARTUP_REQUIREMENTS = ["az", "devtunnel", "claude", "codex"];
48440
49689
  function createDefaultConfig(storagePath = resolveDefaultStoragePath(), nodeName = DEFAULT_NODE_NAME) {
48441
49690
  return {
@@ -48476,7 +49725,7 @@ function createPromptSession(prompt) {
48476
49725
  }
48477
49726
  function createDefaultCommandRunner(platform2) {
48478
49727
  return (command, args, interactive = false) => {
48479
- const result = (0, import_node_child_process10.spawnSync)(command, args, {
49728
+ const result = (0, import_node_child_process11.spawnSync)(command, args, {
48480
49729
  encoding: "utf-8",
48481
49730
  shell: platform2 === "win32",
48482
49731
  stdio: interactive ? "inherit" : "pipe"
@@ -48491,21 +49740,21 @@ function createDefaultCommandRunner(platform2) {
48491
49740
  };
48492
49741
  }
48493
49742
  function getNodeMetadataPath2(storagePath) {
48494
- return path20.join(storagePath, "metadata.json");
49743
+ return path21.join(storagePath, "metadata.json");
48495
49744
  }
48496
49745
  function readStartupMetadataFile(storagePath) {
48497
49746
  try {
48498
- const raw = JSON.parse(fs19.readFileSync(getNodeMetadataPath2(storagePath), "utf-8"));
49747
+ const raw = JSON.parse(fs20.readFileSync(getNodeMetadataPath2(storagePath), "utf-8"));
48499
49748
  return typeof raw === "object" && raw !== null ? raw : {};
48500
49749
  } catch {
48501
49750
  return {};
48502
49751
  }
48503
49752
  }
48504
49753
  function writeStartupMetadataFile(storagePath, metadata) {
48505
- fs19.mkdirSync(storagePath, { recursive: true });
48506
- fs19.writeFileSync(getNodeMetadataPath2(storagePath), JSON.stringify(metadata, null, 2) + "\n", "utf-8");
49754
+ fs20.mkdirSync(storagePath, { recursive: true });
49755
+ fs20.writeFileSync(getNodeMetadataPath2(storagePath), JSON.stringify(metadata, null, 2) + "\n", "utf-8");
48507
49756
  }
48508
- function formatLocalDate(now) {
49757
+ function formatLocalDate2(now) {
48509
49758
  const year = now.getFullYear();
48510
49759
  const month = String(now.getMonth() + 1).padStart(2, "0");
48511
49760
  const day = String(now.getDate()).padStart(2, "0");
@@ -48596,7 +49845,7 @@ function resolveStartupRequirementsMetadata(storagePath) {
48596
49845
  }
48597
49846
  function shouldSkipStartupRequirementsCheck(storagePath, now = /* @__PURE__ */ new Date()) {
48598
49847
  const metadata = resolveStartupRequirementsMetadata(storagePath);
48599
- if (metadata.lastCheckedOn !== formatLocalDate(now)) {
49848
+ if (metadata.lastCheckedOn !== formatLocalDate2(now)) {
48600
49849
  return false;
48601
49850
  }
48602
49851
  return STARTUP_REQUIREMENTS.every((requirement) => isRequirementSatisfied(requirement, metadata.components?.[requirement]));
@@ -48680,7 +49929,7 @@ async function ensureStartupRequirements(storagePath, options = {}) {
48680
49929
  await current.close();
48681
49930
  };
48682
49931
  const checkedAt = now.toISOString();
48683
- const checkedOn = formatLocalDate(now);
49932
+ const checkedOn = formatLocalDate2(now);
48684
49933
  const components = {};
48685
49934
  try {
48686
49935
  for (const requirement of STARTUP_REQUIREMENTS) {
@@ -48742,9 +49991,9 @@ async function ensureStartupRequirements(storagePath, options = {}) {
48742
49991
  metadata
48743
49992
  };
48744
49993
  }
48745
- function loadConfigFile(path22) {
49994
+ function loadConfigFile(path23) {
48746
49995
  try {
48747
- const raw = fs19.readFileSync(path22, "utf-8");
49996
+ const raw = fs20.readFileSync(path23, "utf-8");
48748
49997
  return JSON.parse(raw);
48749
49998
  } catch {
48750
49999
  return {};
@@ -48820,13 +50069,13 @@ async function promptStartOptions(args, fileConfig, defaults, prompt) {
48820
50069
  result.port = port;
48821
50070
  break;
48822
50071
  }
48823
- console.log("Invalid port. Enter a positive integer.");
50072
+ terminalWriter.line("Invalid port. Enter a positive integer.");
48824
50073
  }
48825
50074
  }
48826
50075
  if (result.transport === void 0) {
48827
50076
  while (true) {
48828
50077
  const input = normalizePromptValue(
48829
- await ask(formatPrompt("Transport (direct/devtunnel/tailscale)", merged.transport.type))
50078
+ await ask(formatPrompt("Transport (direct/devtunnel)", merged.transport.type))
48830
50079
  );
48831
50080
  if (!input) {
48832
50081
  result.transport = merged.transport.type;
@@ -48836,7 +50085,7 @@ async function promptStartOptions(args, fileConfig, defaults, prompt) {
48836
50085
  result.transport = input;
48837
50086
  break;
48838
50087
  }
48839
- console.log("Invalid transport. Use direct, devtunnel, or tailscale.");
50088
+ terminalWriter.line("Invalid transport. Use direct or devtunnel.");
48840
50089
  }
48841
50090
  }
48842
50091
  if (result.join === void 0) {
@@ -48922,26 +50171,26 @@ function formatLoadedStartMetadata(info, authEnabled) {
48922
50171
  }
48923
50172
 
48924
50173
  // src/runtime-metadata.ts
48925
- var fs20 = __toESM(require("fs"), 1);
48926
- var path21 = __toESM(require("path"), 1);
48927
- var import_node_child_process11 = require("child_process");
50174
+ var fs21 = __toESM(require("fs"), 1);
50175
+ var path22 = __toESM(require("path"), 1);
50176
+ var import_node_child_process12 = require("child_process");
48928
50177
  var runtimeDir = resolveRuntimeDir();
48929
50178
  var appRoot = resolveAppRoot(runtimeDir);
48930
- var repoRoot = path21.resolve(appRoot, "../..");
50179
+ var repoRoot = path22.resolve(appRoot, "../..");
48931
50180
  function resolveRuntimeDir() {
48932
50181
  const entryPath = process.argv[1];
48933
50182
  if (typeof entryPath === "string" && entryPath.length > 0) {
48934
50183
  try {
48935
- return path21.dirname(fs20.realpathSync(path21.resolve(entryPath)));
50184
+ return path22.dirname(fs21.realpathSync(path22.resolve(entryPath)));
48936
50185
  } catch {
48937
- return path21.dirname(path21.resolve(entryPath));
50186
+ return path22.dirname(path22.resolve(entryPath));
48938
50187
  }
48939
50188
  }
48940
50189
  return process.cwd();
48941
50190
  }
48942
50191
  function readJsonFile(filePath) {
48943
50192
  try {
48944
- return JSON.parse(fs20.readFileSync(filePath, "utf-8"));
50193
+ return JSON.parse(fs21.readFileSync(filePath, "utf-8"));
48945
50194
  } catch {
48946
50195
  return null;
48947
50196
  }
@@ -48951,9 +50200,9 @@ function readPackageManifest(filePath) {
48951
50200
  }
48952
50201
  function readEmbeddedRuntimeMetadata() {
48953
50202
  const candidates = [
48954
- path21.join(appRoot, "runtime-metadata.json"),
48955
- path21.join(runtimeDir, "runtime-metadata.json"),
48956
- path21.resolve(process.cwd(), "apps/node/dist/runtime-metadata.json")
50203
+ path22.join(appRoot, "runtime-metadata.json"),
50204
+ path22.join(runtimeDir, "runtime-metadata.json"),
50205
+ path22.resolve(process.cwd(), "apps/node/dist/runtime-metadata.json")
48957
50206
  ];
48958
50207
  for (const candidate of candidates) {
48959
50208
  const metadata = readJsonFile(candidate);
@@ -48966,23 +50215,23 @@ function readEmbeddedRuntimeMetadata() {
48966
50215
  function resolveAppRoot(baseDir) {
48967
50216
  const candidates = [
48968
50217
  baseDir,
48969
- path21.resolve(baseDir, ".."),
48970
- path21.resolve(process.cwd(), "apps/node/dist"),
48971
- path21.resolve(process.cwd(), "apps/node"),
50218
+ path22.resolve(baseDir, ".."),
50219
+ path22.resolve(process.cwd(), "apps/node/dist"),
50220
+ path22.resolve(process.cwd(), "apps/node"),
48972
50221
  process.cwd()
48973
50222
  ];
48974
50223
  for (const candidate of candidates) {
48975
- const manifest = readPackageManifest(path21.join(candidate, "package.json"));
50224
+ const manifest = readPackageManifest(path22.join(candidate, "package.json"));
48976
50225
  if (manifest?.name === "@meshy/node" || manifest?.name === "meshy-node") {
48977
50226
  return candidate;
48978
50227
  }
48979
50228
  }
48980
50229
  for (const candidate of candidates) {
48981
- if (fs20.existsSync(path21.join(candidate, "package.json"))) {
50230
+ if (fs21.existsSync(path22.join(candidate, "package.json"))) {
48982
50231
  return candidate;
48983
50232
  }
48984
50233
  }
48985
- return path21.resolve(baseDir, "..");
50234
+ return path22.resolve(baseDir, "..");
48986
50235
  }
48987
50236
  function toPackageInfo(filePath) {
48988
50237
  const manifest = readPackageManifest(filePath);
@@ -49020,7 +50269,7 @@ function readRepositoryUrlFromManifest(manifest) {
49020
50269
  }
49021
50270
  function readGitValue(args) {
49022
50271
  try {
49023
- const output = (0, import_node_child_process11.execFileSync)("git", args, {
50272
+ const output = (0, import_node_child_process12.execFileSync)("git", args, {
49024
50273
  cwd: repoRoot,
49025
50274
  encoding: "utf-8",
49026
50275
  stdio: ["ignore", "pipe", "ignore"],
@@ -49042,8 +50291,8 @@ function buildRuntimeMetadata(storagePath) {
49042
50291
  components: startupRequirements.components
49043
50292
  };
49044
50293
  }
49045
- const appPackage = toPackageInfo(path21.join(appRoot, "package.json"));
49046
- const workspaceManifest = readPackageManifest(path21.join(repoRoot, "package.json"));
50294
+ const appPackage = toPackageInfo(path22.join(appRoot, "package.json"));
50295
+ const workspaceManifest = readPackageManifest(path22.join(repoRoot, "package.json"));
49047
50296
  return {
49048
50297
  packageName: appPackage?.name ?? "meshy",
49049
50298
  packageVersion: appPackage?.version ?? "0.1.0",
@@ -49051,11 +50300,11 @@ function buildRuntimeMetadata(storagePath) {
49051
50300
  startupRequirementsLastCheckedOn: startupRequirements.lastCheckedOn,
49052
50301
  components: startupRequirements.components,
49053
50302
  packages: {
49054
- workspace: toPackageInfo(path21.join(repoRoot, "package.json")),
50303
+ workspace: toPackageInfo(path22.join(repoRoot, "package.json")),
49055
50304
  node: appPackage,
49056
- core: toPackageInfo(path21.join(repoRoot, "packages/core/package.json")),
49057
- dashboard: toPackageInfo(path21.join(repoRoot, "packages/dashboard/package.json")),
49058
- api: toPackageInfo(path21.join(repoRoot, "packages/api/package.json"))
50305
+ core: toPackageInfo(path22.join(repoRoot, "packages/core/package.json")),
50306
+ dashboard: toPackageInfo(path22.join(repoRoot, "packages/dashboard/package.json")),
50307
+ api: toPackageInfo(path22.join(repoRoot, "packages/api/package.json"))
49059
50308
  },
49060
50309
  repository: {
49061
50310
  url: normalizeRepositoryUrl(readGitValue(["config", "--get", "remote.upstream.url"])) ?? normalizeRepositoryUrl(readGitValue(["config", "--get", "remote.origin.url"])) ?? readRepositoryUrlFromManifest(workspaceManifest),
@@ -49069,11 +50318,7 @@ function buildRuntimeMetadata(storagePath) {
49069
50318
  function createSettingsSnapshotProvider(options) {
49070
50319
  let cachedSnapshot = null;
49071
50320
  let cachedSnapshotAt = 0;
49072
- return function getSettingsSnapshot() {
49073
- const now = Date.now();
49074
- if (cachedSnapshot && now - cachedSnapshotAt < 3e4) {
49075
- return structuredClone(cachedSnapshot);
49076
- }
50321
+ function buildSnapshot() {
49077
50322
  cachedSnapshot = buildNodeSettingsSnapshot({
49078
50323
  auth: options.authMetadata,
49079
50324
  localDashboardOrigin: options.localDashboardOrigin,
@@ -49081,8 +50326,23 @@ function createSettingsSnapshotProvider(options) {
49081
50326
  storagePath: options.storagePath,
49082
50327
  workDir: options.workDir
49083
50328
  });
49084
- cachedSnapshotAt = now;
50329
+ cachedSnapshotAt = Date.now();
49085
50330
  return structuredClone(cachedSnapshot);
50331
+ }
50332
+ function getSettingsSnapshot() {
50333
+ const now = Date.now();
50334
+ if (cachedSnapshot && now - cachedSnapshotAt < 3e4) {
50335
+ return structuredClone(cachedSnapshot);
50336
+ }
50337
+ return buildSnapshot();
50338
+ }
50339
+ return {
50340
+ getSettingsSnapshot,
50341
+ refreshSettingsSnapshot: () => {
50342
+ cachedSnapshot = null;
50343
+ cachedSnapshotAt = 0;
50344
+ return buildSnapshot();
50345
+ }
49086
50346
  };
49087
50347
  }
49088
50348
  async function resolveStartConfig(args) {
@@ -49369,13 +50629,13 @@ function registerShutdownHandlers(options) {
49369
50629
  let shuttingDown = false;
49370
50630
  async function shutdown() {
49371
50631
  if (shuttingDown) {
49372
- console.log("Force exit.");
50632
+ terminalWriter.line("Force exit.");
49373
50633
  process.exit(130);
49374
50634
  }
49375
50635
  shuttingDown = true;
49376
- console.log("\nShutting down...");
50636
+ terminalWriter.line("\nShutting down...");
49377
50637
  const forceExitTimer = setTimeout(() => {
49378
- console.log("Force exit.");
50638
+ terminalWriter.line("Force exit.");
49379
50639
  process.exit(0);
49380
50640
  }, 1e4);
49381
50641
  forceExitTimer.unref?.();
@@ -49385,10 +50645,10 @@ function registerShutdownHandlers(options) {
49385
50645
  await options.tunnelManager.stop();
49386
50646
  await options.meshyNode.stop();
49387
50647
  clearTimeout(forceExitTimer);
49388
- console.log("Goodbye!");
50648
+ terminalWriter.line("Goodbye!");
49389
50649
  process.exit(0);
49390
50650
  } catch (err) {
49391
- console.error("Error during shutdown:", err);
50651
+ terminalWriter.error("Error during shutdown:", err);
49392
50652
  process.exit(1);
49393
50653
  }
49394
50654
  }
@@ -49397,9 +50657,9 @@ function registerShutdownHandlers(options) {
49397
50657
  }
49398
50658
  async function startNode(args) {
49399
50659
  const { authMetadata, config, hydratedArgs, runtimeMetadata, storageRoot } = await resolveStartConfig(args);
49400
- console.log("Checking startup requirements (az, devtunnel, claude, codex)...");
50660
+ terminalWriter.line("Checking startup requirements (az, devtunnel, claude, codex)...");
49401
50661
  const startupRequirements = await ensureStartupRequirements(config.storage.path);
49402
- console.log(
50662
+ terminalWriter.line(
49403
50663
  startupRequirements.skipped ? "Startup requirements already verified today; skipping checks." : "Startup requirements check complete."
49404
50664
  );
49405
50665
  const localDashboardOrigin = `http://localhost:${config.node.port}`;
@@ -49413,9 +50673,9 @@ async function startNode(args) {
49413
50673
  settingsProvider: () => authMetadata
49414
50674
  });
49415
50675
  if (hydratedArgs.loaded) {
49416
- console.log("");
49417
- console.log(formatLoadedStartMetadata(hydratedArgs.loaded, authMetadata.enabled));
49418
- console.log("");
50676
+ terminalWriter.line("");
50677
+ terminalWriter.line(formatLoadedStartMetadata(hydratedArgs.loaded, authMetadata.enabled));
50678
+ terminalWriter.line("");
49419
50679
  }
49420
50680
  if (authMetadata.enabled) {
49421
50681
  await nodeAuth.warmup();
@@ -49423,13 +50683,14 @@ async function startNode(args) {
49423
50683
  } else {
49424
50684
  setRequestAuthHeadersProvider(null);
49425
50685
  }
49426
- const getSettingsSnapshot = createSettingsSnapshotProvider({
50686
+ const settingsSnapshotProvider = createSettingsSnapshotProvider({
49427
50687
  authMetadata,
49428
50688
  localDashboardOrigin,
49429
50689
  runtimeMetadata,
49430
50690
  storagePath: config.storage.path,
49431
50691
  workDir: nodePath2.resolve(config.node.workDir ?? process.cwd())
49432
50692
  });
50693
+ const { getSettingsSnapshot, refreshSettingsSnapshot } = settingsSnapshotProvider;
49433
50694
  const meshyNode = new MeshyNode(config, {
49434
50695
  logger: logger27,
49435
50696
  transportFactory: createTransport,
@@ -49512,6 +50773,8 @@ async function startNode(args) {
49512
50773
  },
49513
50774
  isDevTunnelEnabled: () => meshyNode.isDevTunnelEnabled(),
49514
50775
  localDashboardOrigin,
50776
+ upgradeRuntimeAgent,
50777
+ refreshSettingsSnapshot,
49515
50778
  dashboardOrigin: tunnelManager.getDashboardOrigin(),
49516
50779
  shareOrigin: tunnelManager.getShareOrigin(),
49517
50780
  ensureShareTunnel: () => tunnelManager.ensureShareTunnel(),
@@ -49539,9 +50802,9 @@ async function startNode(args) {
49539
50802
  port: config.node.port,
49540
50803
  dashboardOrigin: tunnelManager.getDashboardOrigin()
49541
50804
  });
49542
- console.log("");
49543
- console.log(banner);
49544
- console.log("");
50805
+ terminalWriter.line("");
50806
+ terminalWriter.line(banner);
50807
+ terminalWriter.line("");
49545
50808
  });
49546
50809
  registerShutdownHandlers({
49547
50810
  server,