@fatagnus/codebuff 1.0.0 → 1.0.1

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/dist/convex.cjs CHANGED
@@ -32510,7 +32510,7 @@ var require_uri_all = __commonJS((exports3, module2) => {
32510
32510
  }
32511
32511
  var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
32512
32512
  var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
32513
- function parse2(uriString) {
32513
+ function parse(uriString) {
32514
32514
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
32515
32515
  var components = {};
32516
32516
  var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
@@ -32675,51 +32675,51 @@ var require_uri_all = __commonJS((exports3, module2) => {
32675
32675
  }
32676
32676
  return uriTokens.join("");
32677
32677
  }
32678
- function resolveComponents(base2, relative2) {
32678
+ function resolveComponents(base2, relative) {
32679
32679
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
32680
32680
  var skipNormalization = arguments[3];
32681
32681
  var target = {};
32682
32682
  if (!skipNormalization) {
32683
- base2 = parse2(serialize(base2, options), options);
32684
- relative2 = parse2(serialize(relative2, options), options);
32683
+ base2 = parse(serialize(base2, options), options);
32684
+ relative = parse(serialize(relative, options), options);
32685
32685
  }
32686
32686
  options = options || {};
32687
- if (!options.tolerant && relative2.scheme) {
32688
- target.scheme = relative2.scheme;
32689
- target.userinfo = relative2.userinfo;
32690
- target.host = relative2.host;
32691
- target.port = relative2.port;
32692
- target.path = removeDotSegments(relative2.path || "");
32693
- target.query = relative2.query;
32687
+ if (!options.tolerant && relative.scheme) {
32688
+ target.scheme = relative.scheme;
32689
+ target.userinfo = relative.userinfo;
32690
+ target.host = relative.host;
32691
+ target.port = relative.port;
32692
+ target.path = removeDotSegments(relative.path || "");
32693
+ target.query = relative.query;
32694
32694
  } else {
32695
- if (relative2.userinfo !== undefined || relative2.host !== undefined || relative2.port !== undefined) {
32696
- target.userinfo = relative2.userinfo;
32697
- target.host = relative2.host;
32698
- target.port = relative2.port;
32699
- target.path = removeDotSegments(relative2.path || "");
32700
- target.query = relative2.query;
32695
+ if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
32696
+ target.userinfo = relative.userinfo;
32697
+ target.host = relative.host;
32698
+ target.port = relative.port;
32699
+ target.path = removeDotSegments(relative.path || "");
32700
+ target.query = relative.query;
32701
32701
  } else {
32702
- if (!relative2.path) {
32702
+ if (!relative.path) {
32703
32703
  target.path = base2.path;
32704
- if (relative2.query !== undefined) {
32705
- target.query = relative2.query;
32704
+ if (relative.query !== undefined) {
32705
+ target.query = relative.query;
32706
32706
  } else {
32707
32707
  target.query = base2.query;
32708
32708
  }
32709
32709
  } else {
32710
- if (relative2.path.charAt(0) === "/") {
32711
- target.path = removeDotSegments(relative2.path);
32710
+ if (relative.path.charAt(0) === "/") {
32711
+ target.path = removeDotSegments(relative.path);
32712
32712
  } else {
32713
32713
  if ((base2.userinfo !== undefined || base2.host !== undefined || base2.port !== undefined) && !base2.path) {
32714
- target.path = "/" + relative2.path;
32714
+ target.path = "/" + relative.path;
32715
32715
  } else if (!base2.path) {
32716
- target.path = relative2.path;
32716
+ target.path = relative.path;
32717
32717
  } else {
32718
- target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative2.path;
32718
+ target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative.path;
32719
32719
  }
32720
32720
  target.path = removeDotSegments(target.path);
32721
32721
  }
32722
- target.query = relative2.query;
32722
+ target.query = relative.query;
32723
32723
  }
32724
32724
  target.userinfo = base2.userinfo;
32725
32725
  target.host = base2.host;
@@ -32727,29 +32727,29 @@ var require_uri_all = __commonJS((exports3, module2) => {
32727
32727
  }
32728
32728
  target.scheme = base2.scheme;
32729
32729
  }
32730
- target.fragment = relative2.fragment;
32730
+ target.fragment = relative.fragment;
32731
32731
  return target;
32732
32732
  }
32733
- function resolve2(baseURI, relativeURI, options) {
32733
+ function resolve(baseURI, relativeURI, options) {
32734
32734
  var schemelessOptions = assign({ scheme: "null" }, options);
32735
- return serialize(resolveComponents(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
32735
+ return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
32736
32736
  }
32737
32737
  function normalize2(uri, options) {
32738
32738
  if (typeof uri === "string") {
32739
- uri = serialize(parse2(uri, options), options);
32739
+ uri = serialize(parse(uri, options), options);
32740
32740
  } else if (typeOf(uri) === "object") {
32741
- uri = parse2(serialize(uri, options), options);
32741
+ uri = parse(serialize(uri, options), options);
32742
32742
  }
32743
32743
  return uri;
32744
32744
  }
32745
32745
  function equal(uriA, uriB, options) {
32746
32746
  if (typeof uriA === "string") {
32747
- uriA = serialize(parse2(uriA, options), options);
32747
+ uriA = serialize(parse(uriA, options), options);
32748
32748
  } else if (typeOf(uriA) === "object") {
32749
32749
  uriA = serialize(uriA, options);
32750
32750
  }
32751
32751
  if (typeof uriB === "string") {
32752
- uriB = serialize(parse2(uriB, options), options);
32752
+ uriB = serialize(parse(uriB, options), options);
32753
32753
  } else if (typeOf(uriB) === "object") {
32754
32754
  uriB = serialize(uriB, options);
32755
32755
  }
@@ -32810,8 +32810,8 @@ var require_uri_all = __commonJS((exports3, module2) => {
32810
32810
  wsComponents.secure = undefined;
32811
32811
  }
32812
32812
  if (wsComponents.resourceName) {
32813
- var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path3 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
32814
- wsComponents.path = path3 && path3 !== "/" ? path3 : undefined;
32813
+ var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path2 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
32814
+ wsComponents.path = path2 && path2 !== "/" ? path2 : undefined;
32815
32815
  wsComponents.query = query;
32816
32816
  wsComponents.resourceName = undefined;
32817
32817
  }
@@ -32994,11 +32994,11 @@ var require_uri_all = __commonJS((exports3, module2) => {
32994
32994
  exports4.SCHEMES = SCHEMES;
32995
32995
  exports4.pctEncChar = pctEncChar;
32996
32996
  exports4.pctDecChars = pctDecChars;
32997
- exports4.parse = parse2;
32997
+ exports4.parse = parse;
32998
32998
  exports4.removeDotSegments = removeDotSegments;
32999
32999
  exports4.serialize = serialize;
33000
33000
  exports4.resolveComponents = resolveComponents;
33001
- exports4.resolve = resolve2;
33001
+ exports4.resolve = resolve;
33002
33002
  exports4.normalize = normalize2;
33003
33003
  exports4.equal = equal;
33004
33004
  exports4.escapeComponent = escapeComponent;
@@ -33204,12 +33204,12 @@ var require_util4 = __commonJS((exports3, module2) => {
33204
33204
  return "'" + escapeQuotes(str) + "'";
33205
33205
  }
33206
33206
  function getPathExpr(currentPath, expr, jsonPointers, isNumber2) {
33207
- var path3 = jsonPointers ? "'/' + " + expr + (isNumber2 ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber2 ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
33208
- return joinPaths(currentPath, path3);
33207
+ var path2 = jsonPointers ? "'/' + " + expr + (isNumber2 ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber2 ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
33208
+ return joinPaths(currentPath, path2);
33209
33209
  }
33210
33210
  function getPath(currentPath, prop, jsonPointers) {
33211
- var path3 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
33212
- return joinPaths(currentPath, path3);
33211
+ var path2 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
33212
+ return joinPaths(currentPath, path2);
33213
33213
  }
33214
33214
  var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
33215
33215
  var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
@@ -33364,20 +33364,20 @@ var require_resolve = __commonJS((exports3, module2) => {
33364
33364
  var util = require_util4();
33365
33365
  var SchemaObject = require_schema_obj();
33366
33366
  var traverse = require_json_schema_traverse();
33367
- module2.exports = resolve2;
33368
- resolve2.normalizeId = normalizeId;
33369
- resolve2.fullPath = getFullPath;
33370
- resolve2.url = resolveUrl;
33371
- resolve2.ids = resolveIds;
33372
- resolve2.inlineRef = inlineRef;
33373
- resolve2.schema = resolveSchema;
33374
- function resolve2(compile, root, ref) {
33367
+ module2.exports = resolve;
33368
+ resolve.normalizeId = normalizeId;
33369
+ resolve.fullPath = getFullPath;
33370
+ resolve.url = resolveUrl;
33371
+ resolve.ids = resolveIds;
33372
+ resolve.inlineRef = inlineRef;
33373
+ resolve.schema = resolveSchema;
33374
+ function resolve(compile, root, ref) {
33375
33375
  var refVal = this._refs[ref];
33376
33376
  if (typeof refVal == "string") {
33377
33377
  if (this._refs[refVal])
33378
33378
  refVal = this._refs[refVal];
33379
33379
  else
33380
- return resolve2.call(this, compile, root, refVal);
33380
+ return resolve.call(this, compile, root, refVal);
33381
33381
  }
33382
33382
  refVal = refVal || this._schemas[ref];
33383
33383
  if (refVal instanceof SchemaObject) {
@@ -33600,7 +33600,7 @@ var require_resolve = __commonJS((exports3, module2) => {
33600
33600
 
33601
33601
  // ../node_modules/ajv/lib/compile/error_classes.js
33602
33602
  var require_error_classes = __commonJS((exports3, module2) => {
33603
- var resolve2 = require_resolve();
33603
+ var resolve = require_resolve();
33604
33604
  module2.exports = {
33605
33605
  Validation: errorSubclass(ValidationError),
33606
33606
  MissingRef: errorSubclass(MissingRefError)
@@ -33615,8 +33615,8 @@ var require_error_classes = __commonJS((exports3, module2) => {
33615
33615
  };
33616
33616
  function MissingRefError(baseId, ref, message) {
33617
33617
  this.message = message || MissingRefError.message(baseId, ref);
33618
- this.missingRef = resolve2.url(baseId, ref);
33619
- this.missingSchema = resolve2.normalizeId(resolve2.fullPath(this.missingRef));
33618
+ this.missingRef = resolve.url(baseId, ref);
33619
+ this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
33620
33620
  }
33621
33621
  function errorSubclass(Subclass) {
33622
33622
  Subclass.prototype = Object.create(Error.prototype);
@@ -34158,7 +34158,7 @@ var require_validate2 = __commonJS((exports3, module2) => {
34158
34158
 
34159
34159
  // ../node_modules/ajv/lib/compile/index.js
34160
34160
  var require_compile = __commonJS((exports3, module2) => {
34161
- var resolve2 = require_resolve();
34161
+ var resolve = require_resolve();
34162
34162
  var util = require_util4();
34163
34163
  var errorClasses = require_error_classes();
34164
34164
  var stableStringify = require_fast_json_stable_stringify();
@@ -34218,7 +34218,7 @@ var require_compile = __commonJS((exports3, module2) => {
34218
34218
  RULES,
34219
34219
  validate: validateGenerator,
34220
34220
  util,
34221
- resolve: resolve2,
34221
+ resolve,
34222
34222
  resolveRef,
34223
34223
  usePattern,
34224
34224
  useDefault,
@@ -34257,7 +34257,7 @@ var require_compile = __commonJS((exports3, module2) => {
34257
34257
  return validate;
34258
34258
  }
34259
34259
  function resolveRef(baseId2, ref, isRoot) {
34260
- ref = resolve2.url(baseId2, ref);
34260
+ ref = resolve.url(baseId2, ref);
34261
34261
  var refIndex = refs[ref];
34262
34262
  var _refVal, refCode;
34263
34263
  if (refIndex !== undefined) {
@@ -34274,11 +34274,11 @@ var require_compile = __commonJS((exports3, module2) => {
34274
34274
  }
34275
34275
  }
34276
34276
  refCode = addLocalRef(ref);
34277
- var v2 = resolve2.call(self2, localCompile, root, ref);
34277
+ var v2 = resolve.call(self2, localCompile, root, ref);
34278
34278
  if (v2 === undefined) {
34279
34279
  var localSchema = localRefs && localRefs[ref];
34280
34280
  if (localSchema) {
34281
- v2 = resolve2.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self2, localSchema, root, localRefs, baseId2);
34281
+ v2 = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self2, localSchema, root, localRefs, baseId2);
34282
34282
  }
34283
34283
  }
34284
34284
  if (v2 === undefined) {
@@ -37795,7 +37795,7 @@ var require_data2 = __commonJS((exports3, module2) => {
37795
37795
  // ../node_modules/ajv/lib/ajv.js
37796
37796
  var require_ajv = __commonJS((exports3, module2) => {
37797
37797
  var compileSchema = require_compile();
37798
- var resolve2 = require_resolve();
37798
+ var resolve = require_resolve();
37799
37799
  var Cache = require_cache();
37800
37800
  var SchemaObject = require_schema_obj();
37801
37801
  var stableStringify = require_fast_json_stable_stringify();
@@ -37887,7 +37887,7 @@ var require_ajv = __commonJS((exports3, module2) => {
37887
37887
  var id = this._getId(schema);
37888
37888
  if (id !== undefined && typeof id != "string")
37889
37889
  throw new Error("schema id must be string");
37890
- key = resolve2.normalizeId(key || id);
37890
+ key = resolve.normalizeId(key || id);
37891
37891
  checkUnique(this, key);
37892
37892
  this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
37893
37893
  return this;
@@ -37933,7 +37933,7 @@ var require_ajv = __commonJS((exports3, module2) => {
37933
37933
  }
37934
37934
  }
37935
37935
  function _getSchemaFragment(self2, ref) {
37936
- var res = resolve2.schema.call(self2, { schema: {} }, ref);
37936
+ var res = resolve.schema.call(self2, { schema: {} }, ref);
37937
37937
  if (res) {
37938
37938
  var { schema, root, baseId } = res;
37939
37939
  var v = compileSchema.call(self2, schema, root, undefined, baseId);
@@ -37949,7 +37949,7 @@ var require_ajv = __commonJS((exports3, module2) => {
37949
37949
  }
37950
37950
  }
37951
37951
  function _getSchemaObj(self2, keyRef) {
37952
- keyRef = resolve2.normalizeId(keyRef);
37952
+ keyRef = resolve.normalizeId(keyRef);
37953
37953
  return self2._schemas[keyRef] || self2._refs[keyRef] || self2._fragments[keyRef];
37954
37954
  }
37955
37955
  function removeSchema(schemaKeyRef) {
@@ -37977,7 +37977,7 @@ var require_ajv = __commonJS((exports3, module2) => {
37977
37977
  this._cache.del(cacheKey);
37978
37978
  var id = this._getId(schemaKeyRef);
37979
37979
  if (id) {
37980
- id = resolve2.normalizeId(id);
37980
+ id = resolve.normalizeId(id);
37981
37981
  delete this._schemas[id];
37982
37982
  delete this._refs[id];
37983
37983
  }
@@ -38002,14 +38002,14 @@ var require_ajv = __commonJS((exports3, module2) => {
38002
38002
  if (cached)
38003
38003
  return cached;
38004
38004
  shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
38005
- var id = resolve2.normalizeId(this._getId(schema));
38005
+ var id = resolve.normalizeId(this._getId(schema));
38006
38006
  if (id && shouldAddSchema)
38007
38007
  checkUnique(this, id);
38008
38008
  var willValidate = this._opts.validateSchema !== false && !skipValidation;
38009
38009
  var recursiveMeta;
38010
- if (willValidate && !(recursiveMeta = id && id == resolve2.normalizeId(schema.$schema)))
38010
+ if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
38011
38011
  this.validateSchema(schema, true);
38012
- var localRefs = resolve2.ids.call(this, schema);
38012
+ var localRefs = resolve.ids.call(this, schema);
38013
38013
  var schemaObj = new SchemaObject({
38014
38014
  id,
38015
38015
  schema,
@@ -38175,7 +38175,7 @@ var require_windows = __commonJS((exports3, module2) => {
38175
38175
  module2.exports = isexe;
38176
38176
  isexe.sync = sync;
38177
38177
  var fs = require("fs");
38178
- function checkPathExt(path3, options) {
38178
+ function checkPathExt(path2, options) {
38179
38179
  var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT;
38180
38180
  if (!pathext) {
38181
38181
  return true;
@@ -38186,25 +38186,25 @@ var require_windows = __commonJS((exports3, module2) => {
38186
38186
  }
38187
38187
  for (var i = 0;i < pathext.length; i++) {
38188
38188
  var p = pathext[i].toLowerCase();
38189
- if (p && path3.substr(-p.length).toLowerCase() === p) {
38189
+ if (p && path2.substr(-p.length).toLowerCase() === p) {
38190
38190
  return true;
38191
38191
  }
38192
38192
  }
38193
38193
  return false;
38194
38194
  }
38195
- function checkStat(stat, path3, options) {
38195
+ function checkStat(stat, path2, options) {
38196
38196
  if (!stat.isSymbolicLink() && !stat.isFile()) {
38197
38197
  return false;
38198
38198
  }
38199
- return checkPathExt(path3, options);
38199
+ return checkPathExt(path2, options);
38200
38200
  }
38201
- function isexe(path3, options, cb) {
38202
- fs.stat(path3, function(er, stat) {
38203
- cb(er, er ? false : checkStat(stat, path3, options));
38201
+ function isexe(path2, options, cb) {
38202
+ fs.stat(path2, function(er, stat) {
38203
+ cb(er, er ? false : checkStat(stat, path2, options));
38204
38204
  });
38205
38205
  }
38206
- function sync(path3, options) {
38207
- return checkStat(fs.statSync(path3), path3, options);
38206
+ function sync(path2, options) {
38207
+ return checkStat(fs.statSync(path2), path2, options);
38208
38208
  }
38209
38209
  });
38210
38210
 
@@ -38213,13 +38213,13 @@ var require_mode = __commonJS((exports3, module2) => {
38213
38213
  module2.exports = isexe;
38214
38214
  isexe.sync = sync;
38215
38215
  var fs = require("fs");
38216
- function isexe(path3, options, cb) {
38217
- fs.stat(path3, function(er, stat) {
38216
+ function isexe(path2, options, cb) {
38217
+ fs.stat(path2, function(er, stat) {
38218
38218
  cb(er, er ? false : checkStat(stat, options));
38219
38219
  });
38220
38220
  }
38221
- function sync(path3, options) {
38222
- return checkStat(fs.statSync(path3), options);
38221
+ function sync(path2, options) {
38222
+ return checkStat(fs.statSync(path2), options);
38223
38223
  }
38224
38224
  function checkStat(stat, options) {
38225
38225
  return stat.isFile() && checkMode(stat, options);
@@ -38250,7 +38250,7 @@ var require_isexe = __commonJS((exports3, module2) => {
38250
38250
  }
38251
38251
  module2.exports = isexe;
38252
38252
  isexe.sync = sync;
38253
- function isexe(path3, options, cb) {
38253
+ function isexe(path2, options, cb) {
38254
38254
  if (typeof options === "function") {
38255
38255
  cb = options;
38256
38256
  options = {};
@@ -38259,17 +38259,17 @@ var require_isexe = __commonJS((exports3, module2) => {
38259
38259
  if (typeof Promise !== "function") {
38260
38260
  throw new TypeError("callback not provided");
38261
38261
  }
38262
- return new Promise(function(resolve2, reject) {
38263
- isexe(path3, options || {}, function(er, is) {
38262
+ return new Promise(function(resolve, reject) {
38263
+ isexe(path2, options || {}, function(er, is) {
38264
38264
  if (er) {
38265
38265
  reject(er);
38266
38266
  } else {
38267
- resolve2(is);
38267
+ resolve(is);
38268
38268
  }
38269
38269
  });
38270
38270
  });
38271
38271
  }
38272
- core(path3, options || {}, function(er, is) {
38272
+ core(path2, options || {}, function(er, is) {
38273
38273
  if (er) {
38274
38274
  if (er.code === "EACCES" || options && options.ignoreErrors) {
38275
38275
  er = null;
@@ -38279,9 +38279,9 @@ var require_isexe = __commonJS((exports3, module2) => {
38279
38279
  cb(er, is);
38280
38280
  });
38281
38281
  }
38282
- function sync(path3, options) {
38282
+ function sync(path2, options) {
38283
38283
  try {
38284
- return core.sync(path3, options || {});
38284
+ return core.sync(path2, options || {});
38285
38285
  } catch (er) {
38286
38286
  if (options && options.ignoreErrors || er.code === "EACCES") {
38287
38287
  return false;
@@ -38295,7 +38295,7 @@ var require_isexe = __commonJS((exports3, module2) => {
38295
38295
  // ../node_modules/which/which.js
38296
38296
  var require_which = __commonJS((exports3, module2) => {
38297
38297
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
38298
- var path3 = require("path");
38298
+ var path2 = require("path");
38299
38299
  var COLON = isWindows ? ";" : ":";
38300
38300
  var isexe = require_isexe();
38301
38301
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -38326,27 +38326,27 @@ var require_which = __commonJS((exports3, module2) => {
38326
38326
  opt = {};
38327
38327
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
38328
38328
  const found = [];
38329
- const step = (i) => new Promise((resolve2, reject) => {
38329
+ const step = (i) => new Promise((resolve, reject) => {
38330
38330
  if (i === pathEnv.length)
38331
- return opt.all && found.length ? resolve2(found) : reject(getNotFoundError(cmd));
38331
+ return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
38332
38332
  const ppRaw = pathEnv[i];
38333
38333
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
38334
- const pCmd = path3.join(pathPart, cmd);
38334
+ const pCmd = path2.join(pathPart, cmd);
38335
38335
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
38336
- resolve2(subStep(p, i, 0));
38336
+ resolve(subStep(p, i, 0));
38337
38337
  });
38338
- const subStep = (p, i, ii) => new Promise((resolve2, reject) => {
38338
+ const subStep = (p, i, ii) => new Promise((resolve, reject) => {
38339
38339
  if (ii === pathExt.length)
38340
- return resolve2(step(i + 1));
38340
+ return resolve(step(i + 1));
38341
38341
  const ext = pathExt[ii];
38342
38342
  isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
38343
38343
  if (!er && is) {
38344
38344
  if (opt.all)
38345
38345
  found.push(p + ext);
38346
38346
  else
38347
- return resolve2(p + ext);
38347
+ return resolve(p + ext);
38348
38348
  }
38349
- return resolve2(subStep(p, i, ii + 1));
38349
+ return resolve(subStep(p, i, ii + 1));
38350
38350
  });
38351
38351
  });
38352
38352
  return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
@@ -38358,7 +38358,7 @@ var require_which = __commonJS((exports3, module2) => {
38358
38358
  for (let i = 0;i < pathEnv.length; i++) {
38359
38359
  const ppRaw = pathEnv[i];
38360
38360
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
38361
- const pCmd = path3.join(pathPart, cmd);
38361
+ const pCmd = path2.join(pathPart, cmd);
38362
38362
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
38363
38363
  for (let j = 0;j < pathExt.length; j++) {
38364
38364
  const cur = p + pathExt[j];
@@ -38399,7 +38399,7 @@ var require_path_key = __commonJS((exports3, module2) => {
38399
38399
 
38400
38400
  // ../node_modules/cross-spawn/lib/util/resolveCommand.js
38401
38401
  var require_resolveCommand = __commonJS((exports3, module2) => {
38402
- var path3 = require("path");
38402
+ var path2 = require("path");
38403
38403
  var which = require_which();
38404
38404
  var getPathKey = require_path_key();
38405
38405
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -38416,7 +38416,7 @@ var require_resolveCommand = __commonJS((exports3, module2) => {
38416
38416
  try {
38417
38417
  resolved = which.sync(parsed.command, {
38418
38418
  path: env2[getPathKey({ env: env2 })],
38419
- pathExt: withoutPathExt ? path3.delimiter : undefined
38419
+ pathExt: withoutPathExt ? path2.delimiter : undefined
38420
38420
  });
38421
38421
  } catch (e) {} finally {
38422
38422
  if (shouldSwitchCwd) {
@@ -38424,7 +38424,7 @@ var require_resolveCommand = __commonJS((exports3, module2) => {
38424
38424
  }
38425
38425
  }
38426
38426
  if (resolved) {
38427
- resolved = path3.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
38427
+ resolved = path2.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
38428
38428
  }
38429
38429
  return resolved;
38430
38430
  }
@@ -38469,8 +38469,8 @@ var require_shebang_command = __commonJS((exports3, module2) => {
38469
38469
  if (!match) {
38470
38470
  return null;
38471
38471
  }
38472
- const [path3, argument] = match[0].replace(/#! ?/, "").split(" ");
38473
- const binary = path3.split("/").pop();
38472
+ const [path2, argument] = match[0].replace(/#! ?/, "").split(" ");
38473
+ const binary = path2.split("/").pop();
38474
38474
  if (binary === "env") {
38475
38475
  return argument;
38476
38476
  }
@@ -38498,7 +38498,7 @@ var require_readShebang = __commonJS((exports3, module2) => {
38498
38498
 
38499
38499
  // ../node_modules/cross-spawn/lib/parse.js
38500
38500
  var require_parse3 = __commonJS((exports3, module2) => {
38501
- var path3 = require("path");
38501
+ var path2 = require("path");
38502
38502
  var resolveCommand = require_resolveCommand();
38503
38503
  var escape = require_escape();
38504
38504
  var readShebang = require_readShebang();
@@ -38523,7 +38523,7 @@ var require_parse3 = __commonJS((exports3, module2) => {
38523
38523
  const needsShell = !isExecutableRegExp.test(commandFile);
38524
38524
  if (parsed.options.forceShell || needsShell) {
38525
38525
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
38526
- parsed.command = path3.normalize(parsed.command);
38526
+ parsed.command = path2.normalize(parsed.command);
38527
38527
  parsed.command = escape.command(parsed.command);
38528
38528
  parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
38529
38529
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -38533,7 +38533,7 @@ var require_parse3 = __commonJS((exports3, module2) => {
38533
38533
  }
38534
38534
  return parsed;
38535
38535
  }
38536
- function parse2(command, args, options) {
38536
+ function parse(command, args, options) {
38537
38537
  if (args && !Array.isArray(args)) {
38538
38538
  options = args;
38539
38539
  args = null;
@@ -38552,7 +38552,7 @@ var require_parse3 = __commonJS((exports3, module2) => {
38552
38552
  };
38553
38553
  return options.shell ? parsed : parseNonShell(parsed);
38554
38554
  }
38555
- module2.exports = parse2;
38555
+ module2.exports = parse;
38556
38556
  });
38557
38557
 
38558
38558
  // ../node_modules/cross-spawn/lib/enoent.js
@@ -38605,16 +38605,16 @@ var require_enoent = __commonJS((exports3, module2) => {
38605
38605
  // ../node_modules/cross-spawn/index.js
38606
38606
  var require_cross_spawn = __commonJS((exports3, module2) => {
38607
38607
  var cp = require("child_process");
38608
- var parse2 = require_parse3();
38608
+ var parse = require_parse3();
38609
38609
  var enoent = require_enoent();
38610
38610
  function spawn(command, args, options) {
38611
- const parsed = parse2(command, args, options);
38611
+ const parsed = parse(command, args, options);
38612
38612
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
38613
38613
  enoent.hookChildProcess(spawned, parsed);
38614
38614
  return spawned;
38615
38615
  }
38616
38616
  function spawnSync(command, args, options) {
38617
- const parsed = parse2(command, args, options);
38617
+ const parsed = parse(command, args, options);
38618
38618
  const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
38619
38619
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
38620
38620
  return result;
@@ -38622,31 +38622,27 @@ var require_cross_spawn = __commonJS((exports3, module2) => {
38622
38622
  module2.exports = spawn;
38623
38623
  module2.exports.spawn = spawn;
38624
38624
  module2.exports.sync = spawnSync;
38625
- module2.exports._parse = parse2;
38625
+ module2.exports._parse = parse;
38626
38626
  module2.exports._enoent = enoent;
38627
38627
  });
38628
38628
 
38629
38629
  // src/convex.ts
38630
38630
  var exports_convex = {};
38631
38631
  __export(exports_convex, {
38632
- withMessageHistory: () => withMessageHistory,
38633
- withAdditionalMessage: () => withAdditionalMessage,
38634
- selectKnowledgeFilePaths: () => selectKnowledgeFilePaths,
38635
38632
  sanitizeErrorMessage: () => sanitizeErrorMessage,
38636
38633
  run: () => run,
38637
38634
  isRetryableStatusCode: () => isRetryableStatusCode,
38638
- initialSessionState: () => initialSessionState,
38639
38635
  getErrorStatusCode: () => getErrorStatusCode,
38640
38636
  getCustomToolDefinition: () => getCustomToolDefinition,
38641
- generateInitialRunState: () => generateInitialRunState,
38642
38637
  createServerError: () => createServerError,
38643
38638
  createPaymentRequiredError: () => createPaymentRequiredError,
38644
38639
  createNetworkError: () => createNetworkError,
38645
38640
  createHttpError: () => createHttpError,
38646
38641
  createForbiddenError: () => createForbiddenError,
38647
38642
  createAuthError: () => createAuthError,
38643
+ convexInitialSessionState: () => convexInitialSessionState,
38644
+ convexApplyOverridesToSessionState: () => convexApplyOverridesToSessionState,
38648
38645
  buildUserMessageContent: () => buildUserMessageContent,
38649
- applyOverridesToSessionState: () => applyOverridesToSessionState,
38650
38646
  WEBSITE_URL: () => WEBSITE_URL,
38651
38647
  RETRY_BACKOFF_MAX_DELAY_MS: () => RETRY_BACKOFF_MAX_DELAY_MS,
38652
38648
  RETRY_BACKOFF_BASE_DELAY_MS: () => RETRY_BACKOFF_BASE_DELAY_MS,
@@ -46610,8 +46606,6 @@ var import_lodash4 = __toESM(require_lodash());
46610
46606
  init_old_constants();
46611
46607
 
46612
46608
  // ../common/src/util/file.ts
46613
- var os = __toESM(require("os"));
46614
- var path = __toESM(require("path"));
46615
46609
  var import_v455 = require("zod/v4");
46616
46610
  var FileTreeNodeSchema = import_v455.z.object({
46617
46611
  name: import_v455.z.string(),
@@ -46688,9 +46682,9 @@ function printFileTree(nodes, depth = 0) {
46688
46682
  }
46689
46683
  return result;
46690
46684
  }
46691
- function printFileTreeWithTokens(nodes, fileTokenScores, path2 = []) {
46685
+ function printFileTreeWithTokens(nodes, fileTokenScores, path = []) {
46692
46686
  let result = "";
46693
- const depth = path2.length;
46687
+ const depth = path.length;
46694
46688
  const indentToken = " ";
46695
46689
  const indentation = indentToken.repeat(depth);
46696
46690
  const indentationWithFile = indentToken.repeat(depth + 1);
@@ -46699,8 +46693,8 @@ function printFileTreeWithTokens(nodes, fileTokenScores, path2 = []) {
46699
46693
  continue;
46700
46694
  }
46701
46695
  result += `${indentation}${node.name}${node.type === "directory" ? "/" : ""}`;
46702
- path2.push(node.name);
46703
- const filePath = path2.join("/");
46696
+ path.push(node.name);
46697
+ const filePath = path.join("/");
46704
46698
  const tokenScores = fileTokenScores[filePath];
46705
46699
  if (node.type === "file" && tokenScores) {
46706
46700
  const tokens = Object.keys(tokenScores);
@@ -46712,40 +46706,16 @@ ${indentationWithFile}${tokens.join(" ")}`;
46712
46706
  result += `
46713
46707
  `;
46714
46708
  if (node.type === "directory" && node.children) {
46715
- result += printFileTreeWithTokens(node.children, fileTokenScores, path2);
46709
+ result += printFileTreeWithTokens(node.children, fileTokenScores, path);
46716
46710
  }
46717
- path2.pop();
46711
+ path.pop();
46718
46712
  }
46719
46713
  return result;
46720
46714
  }
46721
- async function fileExists(params2) {
46722
- const { filePath, fs } = params2;
46723
- try {
46724
- await fs.stat(filePath);
46725
- return true;
46726
- } catch {
46727
- return false;
46728
- }
46729
- }
46730
46715
  var cleanMarkdownCodeBlock = (content) => {
46731
46716
  const cleanResponse = content.match(/^```(?:[a-zA-Z]+)?\n([\s\S]*)\n```$/) ? content.replace(/^```(?:[a-zA-Z]+)?\n/, "").replace(/\n```$/, "") : content;
46732
46717
  return cleanResponse;
46733
46718
  };
46734
- function isSubdir(fromPath, toPath) {
46735
- const resolvedFrom = path.resolve(fromPath);
46736
- const resolvedTo = path.resolve(toPath);
46737
- if (process.platform === "win32") {
46738
- const fromDrive = path.parse(resolvedFrom).root.toLowerCase();
46739
- const toDrive = path.parse(resolvedTo).root.toLowerCase();
46740
- if (fromDrive !== toDrive) {
46741
- return false;
46742
- }
46743
- }
46744
- return !path.relative(resolvedFrom, resolvedTo).startsWith("..");
46745
- }
46746
- function isValidProjectRoot(dir) {
46747
- return !isSubdir(dir, os.homedir());
46748
- }
46749
46719
 
46750
46720
  // ../packages/agent-runtime/src/process-file-block.ts
46751
46721
  var import_diff = require("diff");
@@ -52071,7 +52041,7 @@ function countTokensJson(text) {
52071
52041
  // ../packages/agent-runtime/src/process-file-block.ts
52072
52042
  async function processFileBlock(params2) {
52073
52043
  const {
52074
- path: path2,
52044
+ path,
52075
52045
  initialContentPromise,
52076
52046
  newContent,
52077
52047
  messages,
@@ -52086,28 +52056,28 @@ async function processFileBlock(params2) {
52086
52056
  const initialContent = await initialContentPromise;
52087
52057
  if (initialContent === null) {
52088
52058
  let cleanContent = cleanMarkdownCodeBlock(newContent);
52089
- if (hasLazyEdit(cleanContent) && !path2.endsWith(".md")) {
52090
- logger2.debug({ path: path2, newContent }, `processFileBlock: New file contained a lazy edit for ${path2}. Aborting.`);
52059
+ if (hasLazyEdit(cleanContent) && !path.endsWith(".md")) {
52060
+ logger2.debug({ path, newContent }, `processFileBlock: New file contained a lazy edit for ${path}. Aborting.`);
52091
52061
  return {
52092
52062
  tool: "write_file",
52093
- path: path2,
52063
+ path,
52094
52064
  error: "You created a new file with a placeholder comment like `// ... existing code ...` (or equivalent for other languages). Are you sure you have the file path right? You probably meant to modify an existing file instead of providing a path to a new file."
52095
52065
  };
52096
52066
  }
52097
- logger2.debug({ path: path2, cleanContent }, `processFileBlock: Created new file ${path2}`);
52067
+ logger2.debug({ path, cleanContent }, `processFileBlock: Created new file ${path}`);
52098
52068
  return {
52099
52069
  tool: "write_file",
52100
- path: path2,
52070
+ path,
52101
52071
  content: cleanContent,
52102
52072
  patch: undefined,
52103
- messages: [`Created new file ${path2}`]
52073
+ messages: [`Created new file ${path}`]
52104
52074
  };
52105
52075
  }
52106
52076
  if (newContent === initialContent) {
52107
- logger2.info({ newContent }, `processFileBlock: New was same as old, skipping ${path2}`);
52077
+ logger2.info({ newContent }, `processFileBlock: New was same as old, skipping ${path}`);
52108
52078
  return {
52109
52079
  tool: "write_file",
52110
- path: path2,
52080
+ path,
52111
52081
  error: "The new content was the same as the old content, skipping."
52112
52082
  };
52113
52083
  }
@@ -52128,12 +52098,12 @@ async function processFileBlock(params2) {
52128
52098
  ...params2,
52129
52099
  oldContent: normalizedInitialContent,
52130
52100
  editSnippet: normalizedEditSnippet,
52131
- filePath: path2
52101
+ filePath: path
52132
52102
  });
52133
52103
  if (!largeFileContent) {
52134
52104
  return {
52135
52105
  tool: "write_file",
52136
- path: path2,
52106
+ path,
52137
52107
  error: "Failed to apply the write file change to this large file. You should try using the str_replace tool instead for large files."
52138
52108
  };
52139
52109
  }
@@ -52143,12 +52113,12 @@ async function processFileBlock(params2) {
52143
52113
  ...params2,
52144
52114
  initialContent: normalizedInitialContent,
52145
52115
  editSnippet: normalizedEditSnippet,
52146
- filePath: path2,
52116
+ filePath: path,
52147
52117
  userMessage: lastUserPrompt
52148
52118
  });
52149
52119
  const shouldAddPlaceholders = await shouldAddFilePlaceholders({
52150
52120
  ...params2,
52151
- filePath: path2,
52121
+ filePath: path,
52152
52122
  oldContent: normalizedInitialContent,
52153
52123
  rewrittenNewContent: updatedContent,
52154
52124
  messageHistory: messages
@@ -52162,12 +52132,12 @@ ${placeholderComment}`;
52162
52132
  ...params2,
52163
52133
  initialContent: normalizedInitialContent,
52164
52134
  editSnippet: updatedEditSnippet,
52165
- filePath: path2,
52135
+ filePath: path,
52166
52136
  userMessage: lastUserPrompt
52167
52137
  });
52168
52138
  }
52169
52139
  }
52170
- let patch = import_diff.createPatch(path2, normalizedInitialContent, updatedContent);
52140
+ let patch = import_diff.createPatch(path, normalizedInitialContent, updatedContent);
52171
52141
  const lines = patch.split(`
52172
52142
  `);
52173
52143
  const hunkStartIndex = lines.findIndex((line) => line.startsWith("@@"));
@@ -52177,34 +52147,34 @@ ${placeholderComment}`;
52177
52147
  } else {
52178
52148
  editMessages.push("The new content was the same as the old content, skipping.");
52179
52149
  logger2.debug({
52180
- path: path2,
52150
+ path,
52181
52151
  initialContent,
52182
52152
  changes: newContent,
52183
52153
  patch,
52184
52154
  editMessages
52185
- }, `processFileBlock: No change to ${path2}`);
52155
+ }, `processFileBlock: No change to ${path}`);
52186
52156
  return {
52187
52157
  tool: "write_file",
52188
- path: path2,
52158
+ path,
52189
52159
  error: editMessages.join(`
52190
52160
 
52191
52161
  `)
52192
52162
  };
52193
52163
  }
52194
52164
  logger2.debug({
52195
- path: path2,
52165
+ path,
52196
52166
  editSnippet: newContent,
52197
52167
  updatedContent,
52198
52168
  patch,
52199
52169
  editMessages
52200
- }, `processFileBlock: Updated file ${path2}`);
52170
+ }, `processFileBlock: Updated file ${path}`);
52201
52171
  const patchOriginalLineEndings = patch.replaceAll(`
52202
52172
  `, lineEnding);
52203
52173
  const updatedContentOriginalLineEndings = updatedContent.replaceAll(`
52204
52174
  `, lineEnding);
52205
52175
  return {
52206
52176
  tool: "write_file",
52207
- path: path2,
52177
+ path,
52208
52178
  content: updatedContentOriginalLineEndings,
52209
52179
  patch: patchOriginalLineEndings,
52210
52180
  messages: editMessages
@@ -52317,21 +52287,21 @@ var handleWriteFile = async (params2) => {
52317
52287
  requestOptionalFile,
52318
52288
  writeToClient
52319
52289
  } = params2;
52320
- const { path: path2, instructions, content } = toolCall.input;
52290
+ const { path, instructions, content } = toolCall.input;
52321
52291
  const fileProcessingPromisesByPath = fileProcessingState2.promisesByPath;
52322
52292
  const fileProcessingPromises = fileProcessingState2.allPromises;
52323
- if (!fileProcessingPromisesByPath[path2]) {
52324
- fileProcessingPromisesByPath[path2] = [];
52293
+ if (!fileProcessingPromisesByPath[path]) {
52294
+ fileProcessingPromisesByPath[path] = [];
52325
52295
  }
52326
- const previousPromises = fileProcessingPromisesByPath[path2];
52296
+ const previousPromises = fileProcessingPromisesByPath[path];
52327
52297
  const previousEdit = previousPromises[previousPromises.length - 1];
52328
- const latestContentPromise = previousEdit ? previousEdit.then((maybeResult) => maybeResult && ("content" in maybeResult) ? maybeResult.content : requestOptionalFile({ ...params2, filePath: path2 })) : requestOptionalFile({ ...params2, filePath: path2 });
52298
+ const latestContentPromise = previousEdit ? previousEdit.then((maybeResult) => maybeResult && ("content" in maybeResult) ? maybeResult.content : requestOptionalFile({ ...params2, filePath: path })) : requestOptionalFile({ ...params2, filePath: path });
52329
52299
  const fileContentWithoutStartNewline = content.startsWith(`
52330
52300
  `) ? content.slice(1) : content;
52331
- logger2.debug({ path: path2, content }, `write_file ${path2}`);
52301
+ logger2.debug({ path, content }, `write_file ${path}`);
52332
52302
  const newPromise = processFileBlock({
52333
52303
  ...params2,
52334
- path: path2,
52304
+ path,
52335
52305
  instructions,
52336
52306
  initialContentPromise: latestContentPromise,
52337
52307
  newContent: fileContentWithoutStartNewline,
@@ -52345,14 +52315,14 @@ var handleWriteFile = async (params2) => {
52345
52315
  logger2.error(error, "Error processing write_file block");
52346
52316
  return {
52347
52317
  tool: "write_file",
52348
- path: path2,
52318
+ path,
52349
52319
  error: `Error: Failed to process the write_file block. ${typeof error === "string" ? error : error.msg}`
52350
52320
  };
52351
52321
  }).then(async (fileProcessingResult) => ({
52352
52322
  ...fileProcessingResult,
52353
52323
  toolCallId: toolCall.toolCallId
52354
52324
  }));
52355
- fileProcessingPromisesByPath[path2].push(newPromise);
52325
+ fileProcessingPromisesByPath[path].push(newPromise);
52356
52326
  fileProcessingPromises.push(newPromise);
52357
52327
  await previousToolCallFinished;
52358
52328
  return {
@@ -52383,12 +52353,12 @@ async function postStreamProcessing(toolCall, fileProcessingState2, writeToClien
52383
52353
  if (errors.length > 1) {
52384
52354
  throw new Error(`Internal error: Unexpected number of matching errors for ${JSON.stringify(toolCall)}, found ${errors.length}, expected 1`);
52385
52355
  }
52386
- const { path: path3, error } = errors[0];
52356
+ const { path: path2, error } = errors[0];
52387
52357
  return [
52388
52358
  {
52389
52359
  type: "json",
52390
52360
  value: {
52391
- file: path3,
52361
+ file: path2,
52392
52362
  errorMessage: error
52393
52363
  }
52394
52364
  }
@@ -52398,11 +52368,11 @@ async function postStreamProcessing(toolCall, fileProcessingState2, writeToClien
52398
52368
  if (changes.length !== 1) {
52399
52369
  throw new Error(`Internal error: Unexpected number of matching changes for ${JSON.stringify(toolCall)}, found ${changes.length}, expected 1`);
52400
52370
  }
52401
- const { patch, content, path: path2 } = changes[0];
52371
+ const { patch, content, path } = changes[0];
52402
52372
  const clientToolCall = {
52403
52373
  toolCallId: toolCall.toolCallId,
52404
52374
  toolName: toolCall.tool,
52405
- input: patch ? { type: "patch", path: path2, content: patch } : { type: "file", path: path2, content }
52375
+ input: patch ? { type: "patch", path, content: patch } : { type: "file", path, content }
52406
52376
  };
52407
52377
  return await requestClientToolCall(clientToolCall);
52408
52378
  }
@@ -52417,19 +52387,19 @@ var handleCreatePlan = async (params2) => {
52417
52387
  requestClientToolCall,
52418
52388
  writeToClient
52419
52389
  } = params2;
52420
- const { path: path2, plan } = toolCall.input;
52390
+ const { path, plan } = toolCall.input;
52421
52391
  logger2.debug({
52422
- path: path2,
52392
+ path,
52423
52393
  plan
52424
52394
  }, "Create plan");
52425
52395
  const change = {
52426
52396
  tool: "create_plan",
52427
- path: path2,
52397
+ path,
52428
52398
  content: plan,
52429
52399
  messages: [],
52430
52400
  toolCallId: toolCall.toolCallId
52431
52401
  };
52432
- fileProcessingState2.promisesByPath[path2].push(Promise.resolve(change));
52402
+ fileProcessingState2.promisesByPath[path].push(Promise.resolve(change));
52433
52403
  fileProcessingState2.allPromises.push(Promise.resolve(change));
52434
52404
  await previousToolCallFinished;
52435
52405
  return {
@@ -52452,141 +52422,6 @@ init_old_constants();
52452
52422
  var import_path2 = __toESM(require("path"));
52453
52423
  var ignore = __toESM(require("ignore"));
52454
52424
  var import_lodash5 = __toESM(require_lodash());
52455
- init_old_constants();
52456
- var DEFAULT_MAX_FILES = 1e4;
52457
- async function getProjectFileTree(params2) {
52458
- const withDefaults = { maxFiles: DEFAULT_MAX_FILES, ...params2 };
52459
- const { projectRoot, fs } = withDefaults;
52460
- let { maxFiles } = withDefaults;
52461
- const start = Date.now();
52462
- const defaultIgnore = ignore.default();
52463
- for (const pattern of DEFAULT_IGNORED_PATHS) {
52464
- defaultIgnore.add(pattern);
52465
- }
52466
- if (!isValidProjectRoot(projectRoot)) {
52467
- defaultIgnore.add(".*");
52468
- maxFiles = 0;
52469
- }
52470
- const root = {
52471
- name: import_path2.default.basename(projectRoot),
52472
- type: "directory",
52473
- children: [],
52474
- filePath: ""
52475
- };
52476
- const queue = [
52477
- {
52478
- node: root,
52479
- fullPath: projectRoot,
52480
- ignore: defaultIgnore
52481
- }
52482
- ];
52483
- let totalFiles = 0;
52484
- while (queue.length > 0 && totalFiles < maxFiles) {
52485
- const { node, fullPath, ignore: currentIgnore } = queue.shift();
52486
- const parsedIgnore = await parseGitignore({
52487
- fullDirPath: fullPath,
52488
- projectRoot,
52489
- fs
52490
- });
52491
- const mergedIgnore = ignore.default().add(currentIgnore).add(parsedIgnore);
52492
- try {
52493
- const files = await fs.readdir(fullPath);
52494
- for (const file of files) {
52495
- if (totalFiles >= maxFiles)
52496
- break;
52497
- const filePath = import_path2.default.join(fullPath, file);
52498
- const relativeFilePath = import_path2.default.relative(projectRoot, filePath);
52499
- if (mergedIgnore.ignores(relativeFilePath))
52500
- continue;
52501
- try {
52502
- const stats = await fs.stat(filePath);
52503
- if (stats.isDirectory()) {
52504
- const childNode = {
52505
- name: file,
52506
- type: "directory",
52507
- children: [],
52508
- filePath: relativeFilePath
52509
- };
52510
- node.children.push(childNode);
52511
- queue.push({
52512
- node: childNode,
52513
- fullPath: filePath,
52514
- ignore: mergedIgnore
52515
- });
52516
- } else {
52517
- const lastReadTime = stats.atimeMs;
52518
- node.children.push({
52519
- name: file,
52520
- type: "file",
52521
- lastReadTime,
52522
- filePath: relativeFilePath
52523
- });
52524
- totalFiles++;
52525
- }
52526
- } catch (error) {}
52527
- }
52528
- } catch (error) {}
52529
- }
52530
- return root.children;
52531
- }
52532
- function rebaseGitignorePattern(rawPattern, relativeDirPath) {
52533
- const isNegated = rawPattern.startsWith("!");
52534
- let pattern = isNegated ? rawPattern.slice(1) : rawPattern;
52535
- const dirOnly = pattern.endsWith("/");
52536
- const core = dirOnly ? pattern.slice(0, -1) : pattern;
52537
- const anchored = core.startsWith("/");
52538
- const coreNoLead = anchored ? core.slice(1) : core;
52539
- const hasSlash = coreNoLead.includes("/");
52540
- const base = relativeDirPath.replace(/\\/g, "/");
52541
- let rebased;
52542
- if (anchored) {
52543
- rebased = base ? `${base}/${coreNoLead}` : coreNoLead;
52544
- } else if (!hasSlash) {
52545
- if (base) {
52546
- rebased = `${base}/**/${coreNoLead}`;
52547
- } else {
52548
- rebased = coreNoLead;
52549
- }
52550
- } else {
52551
- rebased = base ? `${base}/${coreNoLead}` : coreNoLead;
52552
- }
52553
- if (dirOnly && !rebased.endsWith("/")) {
52554
- rebased += "/";
52555
- }
52556
- rebased = rebased.replace(/\\/g, "/");
52557
- return isNegated ? `!${rebased}` : rebased;
52558
- }
52559
- async function parseGitignore(params2) {
52560
- const { fullDirPath, projectRoot, fs } = params2;
52561
- const ig = ignore.default();
52562
- const relativeDirPath = import_path2.default.relative(projectRoot, fullDirPath);
52563
- const ignoreFiles = [
52564
- import_path2.default.join(fullDirPath, ".gitignore"),
52565
- import_path2.default.join(fullDirPath, ".codebuffignore"),
52566
- import_path2.default.join(fullDirPath, ".manicodeignore")
52567
- ];
52568
- for (const ignoreFilePath of ignoreFiles) {
52569
- const ignoreFileExists = await fileExists({ filePath: ignoreFilePath, fs });
52570
- if (!ignoreFileExists)
52571
- continue;
52572
- let ignoreContent;
52573
- try {
52574
- ignoreContent = await fs.readFile(ignoreFilePath, "utf8");
52575
- } catch {
52576
- continue;
52577
- }
52578
- const lines = ignoreContent.split(`
52579
- `);
52580
- for (let line of lines) {
52581
- line = line.trim();
52582
- if (line === "" || line.startsWith("#"))
52583
- continue;
52584
- const finalPattern = rebaseGitignorePattern(line, relativeDirPath);
52585
- ig.add(finalPattern);
52586
- }
52587
- }
52588
- return ig;
52589
- }
52590
52425
  function getAllFilePaths(nodes, basePath = "") {
52591
52426
  return nodes.flatMap((node) => {
52592
52427
  if (node.type === "file") {
@@ -53153,9 +52988,9 @@ async function getFileReadingUpdates(params2) {
53153
52988
  const { requestFiles, requestedFiles } = params2;
53154
52989
  const allFilePaths = import_lodash9.uniq(requestedFiles);
53155
52990
  const loadedFiles = await requestFiles({ filePaths: allFilePaths });
53156
- const addedFiles = allFilePaths.filter((path3) => loadedFiles[path3] != null && loadedFiles[path3] !== undefined).map((path3) => ({
53157
- path: path3,
53158
- content: loadedFiles[path3]
52991
+ const addedFiles = allFilePaths.filter((path2) => loadedFiles[path2] != null && loadedFiles[path2] !== undefined).map((path2) => ({
52992
+ path: path2,
52993
+ content: loadedFiles[path2]
53159
52994
  }));
53160
52995
  return addedFiles;
53161
52996
  }
@@ -53569,7 +53404,7 @@ ${systemInfo.platform === "win32" ? windowsNote + `
53569
53404
  Shell: ${systemInfo.shell}
53570
53405
 
53571
53406
  <user_shell_config_files>
53572
- ${Object.entries(shellConfigFiles).map(([path3, content]) => createMarkdownFileBlock(path3, content)).join(`
53407
+ ${Object.entries(shellConfigFiles).map(([path2, content]) => createMarkdownFileBlock(path2, content)).join(`
53573
53408
  `)}
53574
53409
  ${closeXml("user_shell_config_files")}
53575
53410
 
@@ -53863,12 +53698,12 @@ function normalizeLineEndings(params2) {
53863
53698
  `);
53864
53699
  }
53865
53700
  async function processStrReplace(params2) {
53866
- const { path: path3, replacements, initialContentPromise, logger: logger2 } = params2;
53701
+ const { path: path2, replacements, initialContentPromise, logger: logger2 } = params2;
53867
53702
  const initialContent = await initialContentPromise;
53868
53703
  if (initialContent === null) {
53869
53704
  return {
53870
53705
  tool: "str_replace",
53871
- path: path3,
53706
+ path: path2,
53872
53707
  error: "The file does not exist, skipping. Please use the write_file tool to create the file."
53873
53708
  };
53874
53709
  }
@@ -53908,19 +53743,19 @@ async function processStrReplace(params2) {
53908
53743
  `, lineEnding);
53909
53744
  if (initialContent === currentContent) {
53910
53745
  logger2.debug({
53911
- path: path3,
53746
+ path: path2,
53912
53747
  initialContent
53913
- }, `processStrReplace: No change to ${path3}`);
53748
+ }, `processStrReplace: No change to ${path2}`);
53914
53749
  messages.push("No change to the file");
53915
53750
  return {
53916
53751
  tool: "str_replace",
53917
- path: path3,
53752
+ path: path2,
53918
53753
  error: messages.join(`
53919
53754
 
53920
53755
  `)
53921
53756
  };
53922
53757
  }
53923
- let patch = import_diff2.createPatch(path3, initialContent, currentContent);
53758
+ let patch = import_diff2.createPatch(path2, initialContent, currentContent);
53924
53759
  const lines = patch.split(`
53925
53760
  `);
53926
53761
  const hunkStartIndex = lines.findIndex((line) => line.startsWith("@@"));
@@ -53930,14 +53765,14 @@ async function processStrReplace(params2) {
53930
53765
  }
53931
53766
  const finalPatch = patch;
53932
53767
  logger2.debug({
53933
- path: path3,
53768
+ path: path2,
53934
53769
  newContent: currentContent,
53935
53770
  patch: finalPatch,
53936
53771
  messages
53937
- }, `processStrReplace: Updated file ${path3}`);
53772
+ }, `processStrReplace: Updated file ${path2}`);
53938
53773
  return {
53939
53774
  tool: "str_replace",
53940
- path: path3,
53775
+ path: path2,
53941
53776
  content: currentContent,
53942
53777
  patch: finalPatch,
53943
53778
  messages
@@ -54009,17 +53844,17 @@ var handleProposeStrReplace = async (params2) => {
54009
53844
  runId,
54010
53845
  requestOptionalFile
54011
53846
  } = params2;
54012
- const { path: path3, replacements } = toolCall.input;
53847
+ const { path: path2, replacements } = toolCall.input;
54013
53848
  const getProposedOrDiskContent = async () => {
54014
- const proposedContent = getProposedContent(runId, path3);
53849
+ const proposedContent = getProposedContent(runId, path2);
54015
53850
  if (proposedContent !== undefined) {
54016
53851
  return proposedContent;
54017
53852
  }
54018
- return requestOptionalFile({ ...params2, filePath: path3 });
53853
+ return requestOptionalFile({ ...params2, filePath: path2 });
54019
53854
  };
54020
53855
  const latestContentPromise = getProposedOrDiskContent();
54021
53856
  const strReplaceResultPromise = processStrReplace({
54022
- path: path3,
53857
+ path: path2,
54023
53858
  replacements,
54024
53859
  initialContentPromise: latestContentPromise,
54025
53860
  logger: logger2
@@ -54027,11 +53862,11 @@ var handleProposeStrReplace = async (params2) => {
54027
53862
  logger2.error(error, "Error processing propose_str_replace");
54028
53863
  return {
54029
53864
  tool: "str_replace",
54030
- path: path3,
53865
+ path: path2,
54031
53866
  error: "Unknown error: Failed to process the propose_str_replace."
54032
53867
  };
54033
53868
  });
54034
- setProposedContent(runId, path3, strReplaceResultPromise.then((result) => ("content" in result) ? result.content : null));
53869
+ setProposedContent(runId, path2, strReplaceResultPromise.then((result) => ("content" in result) ? result.content : null));
54035
53870
  await previousToolCallFinished;
54036
53871
  const strReplaceResult = await strReplaceResultPromise;
54037
53872
  if ("error" in strReplaceResult) {
@@ -54040,7 +53875,7 @@ var handleProposeStrReplace = async (params2) => {
54040
53875
  {
54041
53876
  type: "json",
54042
53877
  value: {
54043
- file: path3,
53878
+ file: path2,
54044
53879
  errorMessage: strReplaceResult.error
54045
53880
  }
54046
53881
  }
@@ -54055,7 +53890,7 @@ var handleProposeStrReplace = async (params2) => {
54055
53890
  {
54056
53891
  type: "json",
54057
53892
  value: {
54058
- file: path3,
53893
+ file: path2,
54059
53894
  message,
54060
53895
  unifiedDiff: strReplaceResult.patch
54061
53896
  }
@@ -54074,21 +53909,21 @@ var handleProposeWriteFile = async (params2) => {
54074
53909
  runId,
54075
53910
  requestOptionalFile
54076
53911
  } = params2;
54077
- const { path: path3, content } = toolCall.input;
53912
+ const { path: path2, content } = toolCall.input;
54078
53913
  const getProposedOrDiskContent = async () => {
54079
- const proposedContent = getProposedContent(runId, path3);
53914
+ const proposedContent = getProposedContent(runId, path2);
54080
53915
  if (proposedContent !== undefined) {
54081
53916
  return proposedContent;
54082
53917
  }
54083
- return requestOptionalFile({ ...params2, filePath: path3 });
53918
+ return requestOptionalFile({ ...params2, filePath: path2 });
54084
53919
  };
54085
53920
  const initialContent = await getProposedOrDiskContent();
54086
53921
  const newContent = content.startsWith(`
54087
53922
  `) ? content.slice(1) : content;
54088
- setProposedContent(runId, path3, Promise.resolve(newContent));
53923
+ setProposedContent(runId, path2, Promise.resolve(newContent));
54089
53924
  await previousToolCallFinished;
54090
53925
  const oldContent = initialContent ?? "";
54091
- let patch = import_diff3.createPatch(path3, oldContent, newContent);
53926
+ let patch = import_diff3.createPatch(path2, oldContent, newContent);
54092
53927
  const lines = patch.split(`
54093
53928
  `);
54094
53929
  const hunkStartIndex = lines.findIndex((line) => line.startsWith("@@"));
@@ -54097,13 +53932,13 @@ var handleProposeWriteFile = async (params2) => {
54097
53932
  `);
54098
53933
  }
54099
53934
  const isNewFile = initialContent === null;
54100
- const message = isNewFile ? `Proposed new file ${path3}` : `Proposed changes to ${path3}`;
53935
+ const message = isNewFile ? `Proposed new file ${path2}` : `Proposed changes to ${path2}`;
54101
53936
  return {
54102
53937
  output: [
54103
53938
  {
54104
53939
  type: "json",
54105
53940
  value: {
54106
- file: path3,
53941
+ file: path2,
54107
53942
  message,
54108
53943
  unifiedDiff: patch
54109
53944
  }
@@ -54834,15 +54669,15 @@ var handleStrReplace = async (params2) => {
54834
54669
  requestOptionalFile,
54835
54670
  writeToClient
54836
54671
  } = params2;
54837
- const { path: path3, replacements } = toolCall.input;
54838
- if (!fileProcessingState2.promisesByPath[path3]) {
54839
- fileProcessingState2.promisesByPath[path3] = [];
54672
+ const { path: path2, replacements } = toolCall.input;
54673
+ if (!fileProcessingState2.promisesByPath[path2]) {
54674
+ fileProcessingState2.promisesByPath[path2] = [];
54840
54675
  }
54841
- const previousPromises = fileProcessingState2.promisesByPath[path3];
54676
+ const previousPromises = fileProcessingState2.promisesByPath[path2];
54842
54677
  const previousEdit = previousPromises[previousPromises.length - 1];
54843
- const latestContentPromise = previousEdit ? previousEdit.then((maybeResult) => maybeResult && ("content" in maybeResult) ? maybeResult.content : requestOptionalFile({ ...params2, filePath: path3 })) : requestOptionalFile({ ...params2, filePath: path3 });
54678
+ const latestContentPromise = previousEdit ? previousEdit.then((maybeResult) => maybeResult && ("content" in maybeResult) ? maybeResult.content : requestOptionalFile({ ...params2, filePath: path2 })) : requestOptionalFile({ ...params2, filePath: path2 });
54844
54679
  const newPromise = processStrReplace({
54845
- path: path3,
54680
+ path: path2,
54846
54681
  replacements,
54847
54682
  initialContentPromise: latestContentPromise,
54848
54683
  logger: logger2
@@ -54850,14 +54685,14 @@ var handleStrReplace = async (params2) => {
54850
54685
  logger2.error(error, "Error processing str_replace block");
54851
54686
  return {
54852
54687
  tool: "str_replace",
54853
- path: path3,
54688
+ path: path2,
54854
54689
  error: "Unknown error: Failed to process the str_replace block."
54855
54690
  };
54856
54691
  }).then((fileProcessingResult) => ({
54857
54692
  ...fileProcessingResult,
54858
54693
  toolCallId: toolCall.toolCallId
54859
54694
  }));
54860
- fileProcessingState2.promisesByPath[path3].push(newPromise);
54695
+ fileProcessingState2.promisesByPath[path2].push(newPromise);
54861
54696
  fileProcessingState2.allPromises.push(newPromise);
54862
54697
  await previousToolCallFinished;
54863
54698
  const strReplaceResult = await newPromise;
@@ -55930,10 +55765,10 @@ async function formatPrompt(params2) {
55930
55765
  [PLACEHOLDER.USER_INPUT_PROMPT]: () => escapeString(lastUserInput ?? ""),
55931
55766
  [PLACEHOLDER.INITIAL_AGENT_PROMPT]: () => escapeString(intitialAgentPrompt ?? ""),
55932
55767
  [PLACEHOLDER.KNOWLEDGE_FILES_CONTENTS]: () => Object.entries({
55933
- ...Object.fromEntries(Object.entries(fileContext.knowledgeFiles).filter(([path3]) => ["knowledge.md", "CLAUDE.md"].includes(path3)).map(([path3, content]) => [path3, content.trim()])),
55768
+ ...Object.fromEntries(Object.entries(fileContext.knowledgeFiles).filter(([path2]) => ["knowledge.md", "CLAUDE.md"].includes(path2)).map(([path2, content]) => [path2, content.trim()])),
55934
55769
  ...fileContext.userKnowledgeFiles
55935
- }).map(([path3, content]) => {
55936
- return `\`\`\`${path3}
55770
+ }).map(([path2, content]) => {
55771
+ return `\`\`\`${path2}
55937
55772
  ${content.trim()}
55938
55773
  \`\`\``;
55939
55774
  }).join(`
@@ -57951,7 +57786,7 @@ class Protocol {
57951
57786
  }
57952
57787
  request(request, resultSchema, options) {
57953
57788
  const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== undefined ? options : {};
57954
- return new Promise((resolve2, reject) => {
57789
+ return new Promise((resolve, reject) => {
57955
57790
  var _a, _b, _c, _d, _e, _f;
57956
57791
  if (!this._transport) {
57957
57792
  reject(new Error("Not connected"));
@@ -58002,7 +57837,7 @@ class Protocol {
58002
57837
  }
58003
57838
  try {
58004
57839
  const result = resultSchema.parse(response.result);
58005
- resolve2(result);
57840
+ resolve(result);
58006
57841
  } catch (error) {
58007
57842
  reject(error);
58008
57843
  }
@@ -59406,7 +59241,7 @@ class SSEClientTransport {
59406
59241
  _startOrAuth() {
59407
59242
  var _a, _b, _c;
59408
59243
  const fetchImpl = (_c = (_b = (_a = this === null || this === undefined ? undefined : this._eventSourceInit) === null || _a === undefined ? undefined : _a.fetch) !== null && _b !== undefined ? _b : this._fetch) !== null && _c !== undefined ? _c : fetch;
59409
- return new Promise((resolve2, reject) => {
59244
+ return new Promise((resolve, reject) => {
59410
59245
  this._eventSource = new EventSource(this._url.href, {
59411
59246
  ...this._eventSourceInit,
59412
59247
  fetch: async (url, init) => {
@@ -59426,7 +59261,7 @@ class SSEClientTransport {
59426
59261
  this._eventSource.onerror = (event) => {
59427
59262
  var _a2;
59428
59263
  if (event.code === 401 && this._authProvider) {
59429
- this._authThenStart().then(resolve2, reject);
59264
+ this._authThenStart().then(resolve, reject);
59430
59265
  return;
59431
59266
  }
59432
59267
  const error = new SseError(event.code, event.message, event);
@@ -59448,7 +59283,7 @@ class SSEClientTransport {
59448
59283
  this.close();
59449
59284
  return;
59450
59285
  }
59451
- resolve2();
59286
+ resolve();
59452
59287
  });
59453
59288
  this._eventSource.onmessage = (event) => {
59454
59289
  var _a2, _b2;
@@ -59611,7 +59446,7 @@ class StdioClientTransport {
59611
59446
  if (this._process) {
59612
59447
  throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
59613
59448
  }
59614
- return new Promise((resolve2, reject) => {
59449
+ return new Promise((resolve, reject) => {
59615
59450
  var _a, _b, _c, _d, _e;
59616
59451
  this._process = import_cross_spawn.default(this._serverParams.command, (_a = this._serverParams.args) !== null && _a !== undefined ? _a : [], {
59617
59452
  env: {
@@ -59634,7 +59469,7 @@ class StdioClientTransport {
59634
59469
  (_b2 = this.onerror) === null || _b2 === undefined || _b2.call(this, error);
59635
59470
  });
59636
59471
  this._process.on("spawn", () => {
59637
- resolve2();
59472
+ resolve();
59638
59473
  });
59639
59474
  this._process.on("close", (_code) => {
59640
59475
  var _a2;
@@ -59689,16 +59524,16 @@ class StdioClientTransport {
59689
59524
  this._readBuffer.clear();
59690
59525
  }
59691
59526
  send(message) {
59692
- return new Promise((resolve2) => {
59527
+ return new Promise((resolve) => {
59693
59528
  var _a;
59694
59529
  if (!((_a = this._process) === null || _a === undefined ? undefined : _a.stdin)) {
59695
59530
  throw new Error("Not connected");
59696
59531
  }
59697
59532
  const json = serializeMessage(message);
59698
59533
  if (this._process.stdin.write(json)) {
59699
- resolve2();
59534
+ resolve();
59700
59535
  } else {
59701
- this._process.stdin.once("drain", resolve2);
59536
+ this._process.stdin.once("drain", resolve);
59702
59537
  }
59703
59538
  });
59704
59539
  }
@@ -60180,12 +60015,216 @@ async function callMCPTool(clientId, ...args) {
60180
60015
 
60181
60016
  // src/convex.ts
60182
60017
  init_old_constants();
60183
- var import_lodash18 = __toESM(require_lodash());
60018
+ var import_lodash17 = __toESM(require_lodash());
60184
60019
 
60185
60020
  // src/constants.ts
60186
60021
  var CODEBUFF_BINARY = "codebuff";
60187
60022
  var WEBSITE_URL = env.NEXT_PUBLIC_CODEBUFF_APP_URL;
60188
60023
 
60024
+ // src/convex-session-state.ts
60025
+ var import_v460 = __toESM(require("zod/v4"));
60026
+ function processAgentDefinitions(agentDefinitions) {
60027
+ const processedAgentTemplates = {};
60028
+ agentDefinitions.forEach((definition) => {
60029
+ const processedConfig = { ...definition };
60030
+ if (processedConfig.handleSteps && typeof processedConfig.handleSteps === "function") {
60031
+ processedConfig.handleSteps = processedConfig.handleSteps.toString();
60032
+ }
60033
+ if (processedConfig.id) {
60034
+ processedAgentTemplates[processedConfig.id] = processedConfig;
60035
+ }
60036
+ });
60037
+ return processedAgentTemplates;
60038
+ }
60039
+ function processCustomToolDefinitions(customToolDefinitions) {
60040
+ return Object.fromEntries(customToolDefinitions.map((toolDefinition) => {
60041
+ const jsonSchema = import_v460.default.toJSONSchema(toolDefinition.inputSchema, {
60042
+ io: "input"
60043
+ });
60044
+ delete jsonSchema["$schema"];
60045
+ return [
60046
+ toolDefinition.toolName,
60047
+ {
60048
+ inputSchema: jsonSchema,
60049
+ description: toolDefinition.description,
60050
+ endsAgentStep: toolDefinition.endsAgentStep,
60051
+ exampleInputs: toolDefinition.exampleInputs
60052
+ }
60053
+ ];
60054
+ }));
60055
+ }
60056
+ function buildFileTree(filePaths) {
60057
+ const tree = {};
60058
+ for (const filePath of filePaths) {
60059
+ const parts = filePath.split("/");
60060
+ for (let i = 0;i < parts.length; i++) {
60061
+ const currentPath = parts.slice(0, i + 1).join("/");
60062
+ const isFile = i === parts.length - 1;
60063
+ if (!tree[currentPath]) {
60064
+ tree[currentPath] = {
60065
+ name: parts[i],
60066
+ type: isFile ? "file" : "directory",
60067
+ filePath: currentPath,
60068
+ children: isFile ? undefined : []
60069
+ };
60070
+ }
60071
+ }
60072
+ }
60073
+ const rootNodes = [];
60074
+ const processed = new Set;
60075
+ for (const [path2, node] of Object.entries(tree)) {
60076
+ if (processed.has(path2))
60077
+ continue;
60078
+ const parentPath = path2.substring(0, path2.lastIndexOf("/"));
60079
+ if (parentPath && tree[parentPath]) {
60080
+ const parent = tree[parentPath];
60081
+ if (parent.children && !parent.children.some((child) => child.filePath === path2)) {
60082
+ parent.children.push(node);
60083
+ }
60084
+ } else {
60085
+ rootNodes.push(node);
60086
+ }
60087
+ processed.add(path2);
60088
+ }
60089
+ function sortNodes(nodes) {
60090
+ nodes.sort((a, b) => {
60091
+ if (a.type !== b.type) {
60092
+ return a.type === "directory" ? -1 : 1;
60093
+ }
60094
+ return a.name.localeCompare(b.name);
60095
+ });
60096
+ for (const node of nodes) {
60097
+ if (node.children) {
60098
+ sortNodes(node.children);
60099
+ }
60100
+ }
60101
+ }
60102
+ sortNodes(rootNodes);
60103
+ return rootNodes;
60104
+ }
60105
+ function selectKnowledgeFilePaths(allFilePaths) {
60106
+ const knowledgeCandidates = allFilePaths.filter((filePath) => {
60107
+ const lowercaseFilePath = filePath.toLowerCase();
60108
+ return lowercaseFilePath.endsWith("knowledge.md") || lowercaseFilePath.endsWith("agents.md") || lowercaseFilePath.endsWith("claude.md");
60109
+ });
60110
+ const byDirectory = new Map;
60111
+ for (const filePath of knowledgeCandidates) {
60112
+ const lastSlash = filePath.lastIndexOf("/");
60113
+ const dir = lastSlash >= 0 ? filePath.substring(0, lastSlash) : "";
60114
+ if (!byDirectory.has(dir)) {
60115
+ byDirectory.set(dir, []);
60116
+ }
60117
+ byDirectory.get(dir).push(filePath);
60118
+ }
60119
+ const selectedFiles = [];
60120
+ for (const files of byDirectory.values()) {
60121
+ const knowledgeMd = files.find((f) => f.toLowerCase().endsWith("knowledge.md"));
60122
+ const agentsMd = files.find((f) => f.toLowerCase().endsWith("agents.md"));
60123
+ const claudeMd = files.find((f) => f.toLowerCase().endsWith("claude.md"));
60124
+ const selectedKnowledgeFile = knowledgeMd || agentsMd || claudeMd;
60125
+ if (selectedKnowledgeFile) {
60126
+ selectedFiles.push(selectedKnowledgeFile);
60127
+ }
60128
+ }
60129
+ return selectedFiles;
60130
+ }
60131
+ function deriveKnowledgeFiles(projectFiles) {
60132
+ const allFilePaths = Object.keys(projectFiles);
60133
+ const selectedFilePaths = selectKnowledgeFilePaths(allFilePaths);
60134
+ const knowledgeFiles = {};
60135
+ for (const filePath of selectedFilePaths) {
60136
+ knowledgeFiles[filePath] = projectFiles[filePath];
60137
+ }
60138
+ return knowledgeFiles;
60139
+ }
60140
+ async function convexInitialSessionState(params2) {
60141
+ const { cwd, maxAgentSteps, fs, spawn: spawn2, logger: logger2 } = params2;
60142
+ let { agentDefinitions, customToolDefinitions, projectFiles, knowledgeFiles } = params2;
60143
+ if (!agentDefinitions) {
60144
+ agentDefinitions = [];
60145
+ }
60146
+ if (!customToolDefinitions) {
60147
+ customToolDefinitions = [];
60148
+ }
60149
+ if (projectFiles === undefined) {
60150
+ projectFiles = {};
60151
+ }
60152
+ if (knowledgeFiles === undefined) {
60153
+ knowledgeFiles = projectFiles ? deriveKnowledgeFiles(projectFiles) : {};
60154
+ }
60155
+ const processedAgentTemplates = agentDefinitions.length > 0 ? processAgentDefinitions(agentDefinitions) : {};
60156
+ const processedCustomToolDefinitions = processCustomToolDefinitions(customToolDefinitions);
60157
+ const filePaths = Object.keys(projectFiles).sort();
60158
+ const fileTree = buildFileTree(filePaths);
60159
+ const fileTokenScores = {};
60160
+ const tokenCallers = {};
60161
+ const gitChanges = {
60162
+ status: "",
60163
+ diff: "",
60164
+ diffCached: "",
60165
+ lastCommitMessages: ""
60166
+ };
60167
+ const initialState = getInitialSessionState({
60168
+ projectRoot: cwd ?? "/convex",
60169
+ cwd: cwd ?? "/convex",
60170
+ fileTree,
60171
+ fileTokenScores,
60172
+ tokenCallers,
60173
+ knowledgeFiles,
60174
+ userKnowledgeFiles: {},
60175
+ agentTemplates: processedAgentTemplates,
60176
+ customToolDefinitions: processedCustomToolDefinitions,
60177
+ gitChanges,
60178
+ changesSinceLastChat: {},
60179
+ shellConfigFiles: {},
60180
+ systemInfo: {
60181
+ platform: "linux",
60182
+ shell: "bash",
60183
+ nodeVersion: process.version,
60184
+ arch: "x64",
60185
+ homedir: "/tmp",
60186
+ cpus: 1
60187
+ }
60188
+ });
60189
+ if (maxAgentSteps) {
60190
+ initialState.mainAgentState.stepsRemaining = maxAgentSteps;
60191
+ }
60192
+ return initialState;
60193
+ }
60194
+ async function convexApplyOverridesToSessionState(cwd, baseSessionState, overrides) {
60195
+ const sessionState = JSON.parse(JSON.stringify(baseSessionState));
60196
+ if (overrides.maxAgentSteps !== undefined) {
60197
+ sessionState.mainAgentState.stepsRemaining = overrides.maxAgentSteps;
60198
+ }
60199
+ if (overrides.projectFiles !== undefined) {
60200
+ const filePaths = Object.keys(overrides.projectFiles).sort();
60201
+ sessionState.fileContext.fileTree = buildFileTree(filePaths);
60202
+ sessionState.fileContext.fileTokenScores = {};
60203
+ sessionState.fileContext.tokenCallers = {};
60204
+ if (overrides.knowledgeFiles === undefined) {
60205
+ sessionState.fileContext.knowledgeFiles = deriveKnowledgeFiles(overrides.projectFiles);
60206
+ }
60207
+ }
60208
+ if (overrides.knowledgeFiles !== undefined) {
60209
+ sessionState.fileContext.knowledgeFiles = overrides.knowledgeFiles;
60210
+ }
60211
+ if (overrides.agentDefinitions !== undefined) {
60212
+ const processedAgentTemplates = processAgentDefinitions(overrides.agentDefinitions);
60213
+ sessionState.fileContext.agentTemplates = {
60214
+ ...sessionState.fileContext.agentTemplates,
60215
+ ...processedAgentTemplates
60216
+ };
60217
+ }
60218
+ if (overrides.customToolDefinitions !== undefined) {
60219
+ const processedCustomToolDefinitions = processCustomToolDefinitions(overrides.customToolDefinitions);
60220
+ sessionState.fileContext.customToolDefinitions = {
60221
+ ...sessionState.fileContext.customToolDefinitions,
60222
+ ...processedCustomToolDefinitions
60223
+ };
60224
+ }
60225
+ return sessionState;
60226
+ }
60227
+
60189
60228
  // src/error-utils.ts
60190
60229
  var RETRYABLE_STATUS_CODES2 = new Set([408, 429, 500, 502, 503, 504]);
60191
60230
  function createHttpError(message, statusCode) {
@@ -60250,7 +60289,7 @@ var getCiEnv = () => ({
60250
60289
  var ciEnv = getCiEnv();
60251
60290
 
60252
60291
  // src/impl/database.ts
60253
- var import_v460 = __toESM(require("zod/v4"));
60292
+ var import_v461 = __toESM(require("zod/v4"));
60254
60293
 
60255
60294
  // src/retry-config.ts
60256
60295
  var MAX_RETRIES_PER_MESSAGE = 3;
@@ -60261,8 +60300,8 @@ var RECONNECTION_RETRY_DELAY_MS = 500;
60261
60300
 
60262
60301
  // src/impl/database.ts
60263
60302
  var userInfoCache = {};
60264
- var agentsResponseSchema = import_v460.default.object({
60265
- version: import_v460.default.string(),
60303
+ var agentsResponseSchema = import_v461.default.object({
60304
+ version: import_v461.default.string(),
60266
60305
  data: DynamicAgentTemplateSchema
60267
60306
  });
60268
60307
  async function fetchWithRetry(url, options, logger2) {
@@ -60276,7 +60315,7 @@ async function fetchWithRetry(url, options, logger2) {
60276
60315
  }
60277
60316
  if (attempt < MAX_RETRIES_PER_MESSAGE) {
60278
60317
  logger2?.warn({ status: response.status, attempt: attempt + 1, url: String(url) }, `Retryable HTTP error, retrying in ${backoffDelay}ms`);
60279
- await new Promise((resolve2) => setTimeout(resolve2, backoffDelay));
60318
+ await new Promise((resolve) => setTimeout(resolve, backoffDelay));
60280
60319
  backoffDelay = Math.min(backoffDelay * 2, RETRY_BACKOFF_MAX_DELAY_MS);
60281
60320
  } else {
60282
60321
  return response;
@@ -60285,7 +60324,7 @@ async function fetchWithRetry(url, options, logger2) {
60285
60324
  lastError = error instanceof Error ? error : new Error(String(error));
60286
60325
  if (attempt < MAX_RETRIES_PER_MESSAGE) {
60287
60326
  logger2?.warn({ error: getErrorObject(lastError), attempt: attempt + 1, url: String(url) }, `Network error, retrying in ${backoffDelay}ms`);
60288
- await new Promise((resolve2) => setTimeout(resolve2, backoffDelay));
60327
+ await new Promise((resolve) => setTimeout(resolve, backoffDelay));
60289
60328
  backoffDelay = Math.min(backoffDelay * 2, RETRY_BACKOFF_MAX_DELAY_MS);
60290
60329
  }
60291
60330
  }
@@ -61338,7 +61377,7 @@ function convertToBase64(value) {
61338
61377
  }
61339
61378
 
61340
61379
  // ../packages/internal/src/openai-compatible/chat/openai-compatible-chat-language-model.ts
61341
- var import_v463 = require("zod/v4");
61380
+ var import_v464 = require("zod/v4");
61342
61381
 
61343
61382
  // ../packages/internal/src/openai-compatible/chat/convert-to-openai-compatible-chat-messages.ts
61344
61383
  function getOpenAIMetadata(message) {
@@ -61481,21 +61520,21 @@ function mapOpenAICompatibleFinishReason(finishReason) {
61481
61520
  }
61482
61521
 
61483
61522
  // ../packages/internal/src/openai-compatible/chat/openai-compatible-chat-options.ts
61484
- var import_v461 = require("zod/v4");
61485
- var openaiCompatibleProviderOptions = import_v461.z.object({
61486
- user: import_v461.z.string().optional(),
61487
- reasoningEffort: import_v461.z.string().optional(),
61488
- textVerbosity: import_v461.z.string().optional()
61523
+ var import_v462 = require("zod/v4");
61524
+ var openaiCompatibleProviderOptions = import_v462.z.object({
61525
+ user: import_v462.z.string().optional(),
61526
+ reasoningEffort: import_v462.z.string().optional(),
61527
+ textVerbosity: import_v462.z.string().optional()
61489
61528
  });
61490
61529
 
61491
61530
  // ../packages/internal/src/openai-compatible/openai-compatible-error.ts
61492
- var import_v462 = require("zod/v4");
61493
- var openaiCompatibleErrorDataSchema = import_v462.z.object({
61494
- error: import_v462.z.object({
61495
- message: import_v462.z.string(),
61496
- type: import_v462.z.string().nullish(),
61497
- param: import_v462.z.any().nullish(),
61498
- code: import_v462.z.union([import_v462.z.string(), import_v462.z.number()]).nullish()
61531
+ var import_v463 = require("zod/v4");
61532
+ var openaiCompatibleErrorDataSchema = import_v463.z.object({
61533
+ error: import_v463.z.object({
61534
+ message: import_v463.z.string(),
61535
+ type: import_v463.z.string().nullish(),
61536
+ param: import_v463.z.any().nullish(),
61537
+ code: import_v463.z.union([import_v463.z.string(), import_v463.z.number()]).nullish()
61499
61538
  })
61500
61539
  });
61501
61540
  var defaultOpenAICompatibleErrorStructure = {
@@ -61986,62 +62025,62 @@ class OpenAICompatibleChatLanguageModel {
61986
62025
  };
61987
62026
  }
61988
62027
  }
61989
- var openaiCompatibleTokenUsageSchema = import_v463.z.object({
61990
- prompt_tokens: import_v463.z.number().nullish(),
61991
- completion_tokens: import_v463.z.number().nullish(),
61992
- total_tokens: import_v463.z.number().nullish(),
61993
- prompt_tokens_details: import_v463.z.object({
61994
- cached_tokens: import_v463.z.number().nullish()
62028
+ var openaiCompatibleTokenUsageSchema = import_v464.z.object({
62029
+ prompt_tokens: import_v464.z.number().nullish(),
62030
+ completion_tokens: import_v464.z.number().nullish(),
62031
+ total_tokens: import_v464.z.number().nullish(),
62032
+ prompt_tokens_details: import_v464.z.object({
62033
+ cached_tokens: import_v464.z.number().nullish()
61995
62034
  }).nullish(),
61996
- completion_tokens_details: import_v463.z.object({
61997
- reasoning_tokens: import_v463.z.number().nullish(),
61998
- accepted_prediction_tokens: import_v463.z.number().nullish(),
61999
- rejected_prediction_tokens: import_v463.z.number().nullish()
62035
+ completion_tokens_details: import_v464.z.object({
62036
+ reasoning_tokens: import_v464.z.number().nullish(),
62037
+ accepted_prediction_tokens: import_v464.z.number().nullish(),
62038
+ rejected_prediction_tokens: import_v464.z.number().nullish()
62000
62039
  }).nullish()
62001
62040
  }).nullish();
62002
- var OpenAICompatibleChatResponseSchema = import_v463.z.object({
62003
- id: import_v463.z.string().nullish(),
62004
- created: import_v463.z.number().nullish(),
62005
- model: import_v463.z.string().nullish(),
62006
- choices: import_v463.z.array(import_v463.z.object({
62007
- message: import_v463.z.object({
62008
- role: import_v463.z.literal("assistant").nullish(),
62009
- content: import_v463.z.string().nullish(),
62010
- reasoning_content: import_v463.z.string().nullish(),
62011
- reasoning: import_v463.z.string().nullish(),
62012
- tool_calls: import_v463.z.array(import_v463.z.object({
62013
- id: import_v463.z.string().nullish(),
62014
- function: import_v463.z.object({
62015
- name: import_v463.z.string(),
62016
- arguments: import_v463.z.string()
62041
+ var OpenAICompatibleChatResponseSchema = import_v464.z.object({
62042
+ id: import_v464.z.string().nullish(),
62043
+ created: import_v464.z.number().nullish(),
62044
+ model: import_v464.z.string().nullish(),
62045
+ choices: import_v464.z.array(import_v464.z.object({
62046
+ message: import_v464.z.object({
62047
+ role: import_v464.z.literal("assistant").nullish(),
62048
+ content: import_v464.z.string().nullish(),
62049
+ reasoning_content: import_v464.z.string().nullish(),
62050
+ reasoning: import_v464.z.string().nullish(),
62051
+ tool_calls: import_v464.z.array(import_v464.z.object({
62052
+ id: import_v464.z.string().nullish(),
62053
+ function: import_v464.z.object({
62054
+ name: import_v464.z.string(),
62055
+ arguments: import_v464.z.string()
62017
62056
  })
62018
62057
  })).nullish()
62019
62058
  }),
62020
- finish_reason: import_v463.z.string().nullish()
62059
+ finish_reason: import_v464.z.string().nullish()
62021
62060
  })),
62022
62061
  usage: openaiCompatibleTokenUsageSchema
62023
62062
  });
62024
- var createOpenAICompatibleChatChunkSchema = (errorSchema) => import_v463.z.union([
62025
- import_v463.z.object({
62026
- id: import_v463.z.string().nullish(),
62027
- created: import_v463.z.number().nullish(),
62028
- model: import_v463.z.string().nullish(),
62029
- choices: import_v463.z.array(import_v463.z.object({
62030
- delta: import_v463.z.object({
62031
- role: import_v463.z.enum(["assistant"]).nullish(),
62032
- content: import_v463.z.string().nullish(),
62033
- reasoning_content: import_v463.z.string().nullish(),
62034
- reasoning: import_v463.z.string().nullish(),
62035
- tool_calls: import_v463.z.array(import_v463.z.object({
62036
- index: import_v463.z.number(),
62037
- id: import_v463.z.string().nullish(),
62038
- function: import_v463.z.object({
62039
- name: import_v463.z.string().nullish(),
62040
- arguments: import_v463.z.string().nullish()
62063
+ var createOpenAICompatibleChatChunkSchema = (errorSchema) => import_v464.z.union([
62064
+ import_v464.z.object({
62065
+ id: import_v464.z.string().nullish(),
62066
+ created: import_v464.z.number().nullish(),
62067
+ model: import_v464.z.string().nullish(),
62068
+ choices: import_v464.z.array(import_v464.z.object({
62069
+ delta: import_v464.z.object({
62070
+ role: import_v464.z.enum(["assistant"]).nullish(),
62071
+ content: import_v464.z.string().nullish(),
62072
+ reasoning_content: import_v464.z.string().nullish(),
62073
+ reasoning: import_v464.z.string().nullish(),
62074
+ tool_calls: import_v464.z.array(import_v464.z.object({
62075
+ index: import_v464.z.number(),
62076
+ id: import_v464.z.string().nullish(),
62077
+ function: import_v464.z.object({
62078
+ name: import_v464.z.string().nullish(),
62079
+ arguments: import_v464.z.string().nullish()
62041
62080
  })
62042
62081
  })).nullish()
62043
62082
  }).nullish(),
62044
- finish_reason: import_v463.z.string().nullish()
62083
+ finish_reason: import_v464.z.string().nullish()
62045
62084
  })),
62046
62085
  usage: openaiCompatibleTokenUsageSchema
62047
62086
  }),
@@ -62055,18 +62094,18 @@ var import_node_path = __toESM(require("node:path"));
62055
62094
  var import_os = __toESM(require("os"));
62056
62095
 
62057
62096
  // ../common/src/util/credentials.ts
62058
- var import_v464 = require("zod/v4");
62059
- var userSchema = import_v464.z.object({
62060
- id: import_v464.z.string(),
62061
- email: import_v464.z.string(),
62062
- name: import_v464.z.string().nullable(),
62063
- authToken: import_v464.z.string(),
62064
- fingerprintId: import_v464.z.string(),
62065
- fingerprintHash: import_v464.z.string()
62097
+ var import_v465 = require("zod/v4");
62098
+ var userSchema = import_v465.z.object({
62099
+ id: import_v465.z.string(),
62100
+ email: import_v465.z.string(),
62101
+ name: import_v465.z.string().nullable(),
62102
+ authToken: import_v465.z.string(),
62103
+ fingerprintId: import_v465.z.string(),
62104
+ fingerprintHash: import_v465.z.string()
62066
62105
  });
62067
62106
 
62068
62107
  // src/credentials.ts
62069
- var import_v465 = require("zod/v4");
62108
+ var import_v466 = require("zod/v4");
62070
62109
 
62071
62110
  // src/env.ts
62072
62111
  var getByokOpenrouterApiKeyFromEnv = () => {
@@ -62077,13 +62116,13 @@ var getClaudeOAuthTokenFromEnv = () => {
62077
62116
  };
62078
62117
 
62079
62118
  // src/credentials.ts
62080
- var claudeOAuthSchema = import_v465.z.object({
62081
- accessToken: import_v465.z.string(),
62082
- refreshToken: import_v465.z.string(),
62083
- expiresAt: import_v465.z.number(),
62084
- connectedAt: import_v465.z.number()
62119
+ var claudeOAuthSchema = import_v466.z.object({
62120
+ accessToken: import_v466.z.string(),
62121
+ refreshToken: import_v466.z.string(),
62122
+ expiresAt: import_v466.z.number(),
62123
+ connectedAt: import_v466.z.number()
62085
62124
  });
62086
- var credentialsFileSchema = import_v465.z.object({
62125
+ var credentialsFileSchema = import_v466.z.object({
62087
62126
  default: userSchema.optional(),
62088
62127
  claudeOAuth: claudeOAuthSchema.optional()
62089
62128
  });
@@ -62837,1218 +62876,6 @@ function getAgentRuntimeImpl(params2) {
62837
62876
  };
62838
62877
  }
62839
62878
 
62840
- // src/run-state.ts
62841
- var os4 = __toESM(require("os"));
62842
- var import_path6 = __toESM(require("path"));
62843
-
62844
- // ../packages/code-map/src/parse.ts
62845
- var fs4 = __toESM(require("fs"));
62846
- var path7 = __toESM(require("path"));
62847
-
62848
- // ../packages/code-map/src/languages.ts
62849
- var fs3 = __toESM(require("fs"));
62850
- var path6 = __toESM(require("path"));
62851
- var import_web_tree_sitter2 = require("web-tree-sitter");
62852
-
62853
- // ../packages/code-map/src/init-node.ts
62854
- var fs2 = __toESM(require("fs"));
62855
- var path5 = __toESM(require("path"));
62856
- var import_web_tree_sitter = require("web-tree-sitter");
62857
- async function initTreeSitterForNode() {
62858
- await import_web_tree_sitter.Parser.init({
62859
- locateFile: (name14, scriptDir) => {
62860
- if (name14 === "tree-sitter.wasm") {
62861
- const fallback = path5.join(scriptDir, name14);
62862
- if (fs2.existsSync(fallback)) {
62863
- return fallback;
62864
- }
62865
- const pkgDir = path5.dirname(require.resolve("web-tree-sitter"));
62866
- const wasm = path5.join(pkgDir, "tree-sitter.wasm");
62867
- if (fs2.existsSync(wasm)) {
62868
- return wasm;
62869
- }
62870
- throw new Error(`Internal error: web-tree-sitter/tree-sitter.wasm not found at ${wasm}. Ensure the file is included in your deployment bundle.`);
62871
- }
62872
- return path5.join(scriptDir, name14);
62873
- }
62874
- });
62875
- }
62876
-
62877
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-c_sharp-tags.scm
62878
- var tree_sitter_c_sharp_tags_default = `(class_declaration
62879
- name: (identifier) @identifier
62880
- )
62881
-
62882
- (interface_declaration
62883
- name: (identifier) @identifier
62884
- )
62885
-
62886
- (method_declaration
62887
- name: (identifier) @identifier
62888
- )
62889
-
62890
- ; Method calls
62891
- (invocation_expression
62892
- function: (identifier) @call.identifier)
62893
-
62894
- (invocation_expression
62895
- function: (member_access_expression
62896
- name: (identifier) @call.identifier))
62897
-
62898
- ; Constructor calls
62899
- (object_creation_expression
62900
- type: (identifier) @call.identifier)`;
62901
-
62902
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-cpp-tags.scm
62903
- var tree_sitter_cpp_tags_default = `(struct_specifier name: (type_identifier) @identifier)
62904
-
62905
- (declaration type: (union_specifier name: (type_identifier) @identifier))
62906
-
62907
- (function_declarator declarator: (identifier) @identifier)
62908
-
62909
- (function_declarator declarator: (field_identifier) @identifier)
62910
-
62911
- (function_declarator declarator: (qualified_identifier scope: (namespace_identifier) name: (identifier) @identifier))
62912
-
62913
- (type_definition declarator: (type_identifier) @identifier)
62914
-
62915
- (enum_specifier name: (type_identifier) @identifier)
62916
-
62917
- (class_specifier name: (type_identifier) @identifier)
62918
-
62919
- ; Function calls
62920
- (call_expression
62921
- function: (identifier) @call.identifier)
62922
-
62923
- (call_expression
62924
- function: (field_expression field: (field_identifier) @call.identifier))
62925
-
62926
- ; Constructor calls
62927
- (class_specifier
62928
- name: (type_identifier) @call.identifier)
62929
-
62930
- (new_expression
62931
- type: (type_identifier) @call.identifier)`;
62932
-
62933
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-go-tags.scm
62934
- var tree_sitter_go_tags_default = `(
62935
- (comment)*
62936
- .
62937
- (function_declaration
62938
- name: (identifier) @identifier)
62939
- )
62940
-
62941
- (
62942
- (comment)*
62943
- .
62944
- (method_declaration
62945
- name: (field_identifier) @identifier)
62946
- )
62947
-
62948
- (type_spec
62949
- name: (type_identifier) @identifier)
62950
-
62951
- (type_identifier) @identifier
62952
-
62953
- (call_expression
62954
- function: [
62955
- (identifier) @call.identifier
62956
- (parenthesized_expression (identifier) @call.identifier)
62957
- (selector_expression field: (field_identifier) @call.identifier)
62958
- (parenthesized_expression (selector_expression field: (field_identifier) @call.identifier))
62959
- ])
62960
- `;
62961
-
62962
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-java-tags.scm
62963
- var tree_sitter_java_tags_default = `(class_declaration
62964
- name: (identifier) @identifier)
62965
-
62966
- (interface_declaration
62967
- name: (identifier) @identifier) @definition.interface
62968
-
62969
- (method_declaration
62970
- name: (identifier) @identifier)
62971
-
62972
- (method_invocation
62973
- name: (identifier) @call.identifier)
62974
-
62975
- (type_list
62976
- (type_identifier) @call.identifier)
62977
-
62978
- (object_creation_expression
62979
- type: (type_identifier) @call.identifier)
62980
-
62981
- (superclass (type_identifier) @call.identifier)
62982
- `;
62983
-
62984
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-javascript-tags.scm
62985
- var tree_sitter_javascript_tags_default = `(function_declaration name: (identifier) @identifier)
62986
- (class_declaration name: (identifier) @identifier)
62987
- (method_definition name: (property_identifier) @identifier)
62988
-
62989
- (export_statement
62990
- declaration: (lexical_declaration
62991
- (variable_declarator
62992
- name: (identifier) @identifier)))
62993
- (export_statement
62994
- declaration: (variable_declaration
62995
- (variable_declarator
62996
- name: (identifier) @identifier)))
62997
-
62998
- (call_expression function: (identifier) @call.identifier)
62999
- (call_expression function: (member_expression property: (property_identifier) @call.identifier))
63000
- (new_expression constructor: (identifier) @call.identifier)
63001
- `;
63002
-
63003
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-python-tags.scm
63004
- var tree_sitter_python_tags_default = `(class_definition
63005
- name: (identifier) @identifier)
63006
-
63007
- (function_definition
63008
- name: (identifier) @identifier)
63009
-
63010
- (call
63011
- function: (identifier) @call.identifier)
63012
-
63013
- (call
63014
- function: (attribute
63015
- attribute: (identifier) @call.identifier))
63016
- `;
63017
-
63018
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-ruby-tags.scm
63019
- var tree_sitter_ruby_tags_default = `; Method definitions
63020
-
63021
- (
63022
- [
63023
- (method
63024
- name: (_) @identifier)
63025
- (singleton_method
63026
- name: (_) @identifier)
63027
- ]
63028
- )
63029
-
63030
- (alias
63031
- name: (_) @identifier)
63032
-
63033
- ; (setter
63034
- ; (identifier) @identifier)
63035
-
63036
- ; Class definitions
63037
-
63038
- (
63039
- (comment)*
63040
- .
63041
- [
63042
- (class
63043
- name: [
63044
- (constant) @identifier
63045
- (scope_resolution
63046
- name: (_) @identifier)
63047
- ])
63048
- (singleton_class
63049
- value: [
63050
- (constant) @identifier
63051
- (scope_resolution
63052
- name: (_) @identifier)
63053
- ])
63054
- ]
63055
- )
63056
-
63057
- ; Module definitions
63058
-
63059
- (
63060
- (module
63061
- name: [
63062
- (constant) @identifier
63063
- (scope_resolution
63064
- name: (_) @identifier)
63065
- ])
63066
- )
63067
-
63068
- ; Calls
63069
-
63070
- (call method: (identifier) @call.identifier)
63071
-
63072
- (
63073
- [(identifier) (constant)] @call.identifier
63074
- (#is-not? local)
63075
- (#not-match? @call.identifier "^(lambda|load|require|require_relative|__FILE__|__LINE__)$")
63076
- )
63077
- `;
63078
-
63079
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-rust-tags.scm
63080
- var tree_sitter_rust_tags_default = `(struct_item name: (type_identifier) @identifier)
63081
- (enum_item name: (type_identifier) @identifier)
63082
- (union_item name: (type_identifier) @identifier)
63083
- (type_item name: (type_identifier) @identifier)
63084
- (trait_item name: (type_identifier) @identifier)
63085
- (function_item name: (identifier) @identifier)
63086
- (macro_definition name: (identifier) @identifier)
63087
- (mod_item name: (identifier) @identifier)
63088
- (const_item name: (identifier) @identifier)
63089
- (static_item name: (identifier) @identifier)
63090
-
63091
- ; Function and macro calls
63092
- (call_expression function: (identifier) @call.identifier)
63093
- (call_expression function: (field_expression field: (field_identifier) @call.identifier))
63094
- (macro_invocation macro: (identifier) @call.identifier)
63095
-
63096
- ; Struct instantiation
63097
- (struct_expression (type_identifier) @call.identifier)
63098
-
63099
- ; Enum variant usage
63100
- (scoped_identifier path: (identifier) name: (identifier) @call.identifier)
63101
-
63102
- ; implementations
63103
-
63104
- (impl_item trait: (type_identifier) @call.identifier)
63105
- (impl_item type: (type_identifier) @call.identifier !trait)`;
63106
-
63107
- // ../packages/code-map/src/tree-sitter-queries/tree-sitter-typescript-tags.scm
63108
- var tree_sitter_typescript_tags_default = `(function_declaration name: (identifier) @identifier)
63109
- (class_declaration name: (type_identifier) @identifier)
63110
- (interface_declaration name: (type_identifier) @identifier)
63111
- (method_definition name: (property_identifier) @identifier)
63112
-
63113
- (export_statement
63114
- declaration: (function_declaration
63115
- name: (identifier) @identifier))
63116
-
63117
- (export_statement
63118
- declaration: (lexical_declaration
63119
- (variable_declarator
63120
- name: (identifier) @identifier)))
63121
-
63122
- (export_statement
63123
- declaration: (variable_declaration
63124
- (variable_declarator
63125
- name: (identifier) @identifier)))
63126
-
63127
- (call_expression function: (identifier) @call.identifier)
63128
- (call_expression function: (member_expression property: (property_identifier) @call.identifier))
63129
- (new_expression constructor: (identifier) @call.identifier)
63130
- `;
63131
-
63132
- // ../packages/code-map/src/utils.ts
63133
- function getDirnameDynamically() {
63134
- return new Function(`try { return __dirname; } catch (e) { return undefined; }`)();
63135
- }
63136
-
63137
- // ../packages/code-map/src/languages.ts
63138
- var WASM_FILES = {
63139
- "tree-sitter-c-sharp.wasm": "tree-sitter-c-sharp.wasm",
63140
- "tree-sitter-cpp.wasm": "tree-sitter-cpp.wasm",
63141
- "tree-sitter-go.wasm": "tree-sitter-go.wasm",
63142
- "tree-sitter-java.wasm": "tree-sitter-java.wasm",
63143
- "tree-sitter-javascript.wasm": "tree-sitter-javascript.wasm",
63144
- "tree-sitter-python.wasm": "tree-sitter-python.wasm",
63145
- "tree-sitter-ruby.wasm": "tree-sitter-ruby.wasm",
63146
- "tree-sitter-rust.wasm": "tree-sitter-rust.wasm",
63147
- "tree-sitter-tsx.wasm": "tree-sitter-tsx.wasm",
63148
- "tree-sitter-typescript.wasm": "tree-sitter-typescript.wasm"
63149
- };
63150
- var languageTable = [
63151
- {
63152
- extensions: [".ts"],
63153
- wasmFile: WASM_FILES["tree-sitter-typescript.wasm"],
63154
- queryPathOrContent: tree_sitter_typescript_tags_default
63155
- },
63156
- {
63157
- extensions: [".tsx"],
63158
- wasmFile: WASM_FILES["tree-sitter-tsx.wasm"],
63159
- queryPathOrContent: tree_sitter_typescript_tags_default
63160
- },
63161
- {
63162
- extensions: [".js", ".jsx"],
63163
- wasmFile: WASM_FILES["tree-sitter-javascript.wasm"],
63164
- queryPathOrContent: tree_sitter_javascript_tags_default
63165
- },
63166
- {
63167
- extensions: [".py"],
63168
- wasmFile: WASM_FILES["tree-sitter-python.wasm"],
63169
- queryPathOrContent: tree_sitter_python_tags_default
63170
- },
63171
- {
63172
- extensions: [".java"],
63173
- wasmFile: WASM_FILES["tree-sitter-java.wasm"],
63174
- queryPathOrContent: tree_sitter_java_tags_default
63175
- },
63176
- {
63177
- extensions: [".cs"],
63178
- wasmFile: WASM_FILES["tree-sitter-c-sharp.wasm"],
63179
- queryPathOrContent: tree_sitter_c_sharp_tags_default
63180
- },
63181
- {
63182
- extensions: [".cpp", ".hpp"],
63183
- wasmFile: WASM_FILES["tree-sitter-cpp.wasm"],
63184
- queryPathOrContent: tree_sitter_cpp_tags_default
63185
- },
63186
- {
63187
- extensions: [".rs"],
63188
- wasmFile: WASM_FILES["tree-sitter-rust.wasm"],
63189
- queryPathOrContent: tree_sitter_rust_tags_default
63190
- },
63191
- {
63192
- extensions: [".rb"],
63193
- wasmFile: WASM_FILES["tree-sitter-ruby.wasm"],
63194
- queryPathOrContent: tree_sitter_ruby_tags_default
63195
- },
63196
- {
63197
- extensions: [".go"],
63198
- wasmFile: WASM_FILES["tree-sitter-go.wasm"],
63199
- queryPathOrContent: tree_sitter_go_tags_default
63200
- }
63201
- ];
63202
- var customWasmDir;
63203
- function getWasmDir() {
63204
- return customWasmDir;
63205
- }
63206
- function resolveWasmPath(wasmFileName) {
63207
- const customWasmDirPath = getWasmDir();
63208
- if (customWasmDirPath) {
63209
- return path6.join(customWasmDirPath, wasmFileName);
63210
- }
63211
- const envWasmDir = process.env.CODEBUFF_WASM_DIR;
63212
- if (envWasmDir) {
63213
- return path6.join(envWasmDir, wasmFileName);
63214
- }
63215
- const moduleDir = (() => {
63216
- const dirname4 = getDirnameDynamically();
63217
- if (typeof dirname4 !== "undefined") {
63218
- return dirname4;
63219
- }
63220
- return process.cwd();
63221
- })();
63222
- const possiblePaths = [
63223
- path6.join(moduleDir, "..", "wasm", wasmFileName),
63224
- path6.join(moduleDir, "wasm", wasmFileName),
63225
- path6.join(process.cwd(), "dist", "wasm", wasmFileName)
63226
- ];
63227
- for (const wasmPath of possiblePaths) {
63228
- try {
63229
- return wasmPath;
63230
- } catch {
63231
- continue;
63232
- }
63233
- }
63234
- return possiblePaths[0];
63235
- }
63236
- function tryResolveFromPackage(wasmFileName) {
63237
- try {
63238
- return require.resolve(`@vscode/tree-sitter-wasm/wasm/${wasmFileName}`);
63239
- } catch {
63240
- return null;
63241
- }
63242
- }
63243
-
63244
- class UnifiedLanguageLoader {
63245
- parserReady;
63246
- constructor() {
63247
- this.parserReady = initTreeSitterForNode();
63248
- }
63249
- async initParser() {
63250
- await this.parserReady;
63251
- }
63252
- async loadLanguage(wasmFile) {
63253
- let wasmPath = resolveWasmPath(wasmFile);
63254
- let lang;
63255
- try {
63256
- lang = await import_web_tree_sitter2.Language.load(wasmPath);
63257
- } catch (err) {
63258
- const fallbackPath = tryResolveFromPackage(wasmFile);
63259
- if (fallbackPath) {
63260
- lang = await import_web_tree_sitter2.Language.load(fallbackPath);
63261
- } else {
63262
- throw err;
63263
- }
63264
- }
63265
- return lang;
63266
- }
63267
- }
63268
- function findLanguageConfigByExtension(filePath) {
63269
- const ext = path6.extname(filePath);
63270
- return languageTable.find((c) => c.extensions.includes(ext));
63271
- }
63272
- async function createLanguageConfig(filePath, runtimeLoader) {
63273
- const cfg = findLanguageConfigByExtension(filePath);
63274
- if (!cfg) {
63275
- return;
63276
- }
63277
- if (!cfg.parser) {
63278
- try {
63279
- await runtimeLoader.initParser();
63280
- const lang = await runtimeLoader.loadLanguage(cfg.wasmFile);
63281
- const parser = new import_web_tree_sitter2.Parser;
63282
- parser.setLanguage(lang);
63283
- const queryContent = path6.isAbsolute(cfg.queryPathOrContent) ? fs3.readFileSync(cfg.queryPathOrContent, "utf8") : cfg.queryPathOrContent;
63284
- cfg.language = lang;
63285
- cfg.parser = parser;
63286
- cfg.query = new import_web_tree_sitter2.Query(lang, queryContent);
63287
- } catch (err) {
63288
- throw err;
63289
- }
63290
- }
63291
- return cfg;
63292
- }
63293
- var unifiedLoader = new UnifiedLanguageLoader;
63294
- async function getLanguageConfig(filePath) {
63295
- try {
63296
- return await createLanguageConfig(filePath, unifiedLoader);
63297
- } catch (err) {
63298
- if (DEBUG_PARSING) {
63299
- console.error("[tree-sitter] Load error for", filePath, err);
63300
- }
63301
- return;
63302
- }
63303
- }
63304
-
63305
- // ../packages/code-map/src/parse.ts
63306
- var DEBUG_PARSING = false;
63307
- var IGNORE_TOKENS = ["__init__", "__post_init__", "__call__", "constructor"];
63308
- var MAX_CALLERS = 25;
63309
- async function getFileTokenScores(projectRoot, filePaths, readFile) {
63310
- const startTime2 = Date.now();
63311
- const tokenScores = {};
63312
- const externalCalls = {};
63313
- const fileCallsMap = new Map;
63314
- for (const filePath of filePaths) {
63315
- const fullPath = path7.join(projectRoot, filePath);
63316
- const languageConfig = await getLanguageConfig(fullPath);
63317
- if (languageConfig) {
63318
- let parseResults;
63319
- if (readFile) {
63320
- parseResults = parseTokens(filePath, languageConfig, readFile);
63321
- } else {
63322
- parseResults = parseTokens(fullPath, languageConfig);
63323
- }
63324
- const { identifiers, calls, numLines } = parseResults;
63325
- const tokenScoresForFile = {};
63326
- tokenScores[filePath] = tokenScoresForFile;
63327
- const dirs = path7.dirname(fullPath).split(path7.sep);
63328
- const depth = dirs.length;
63329
- const tokenBaseScore = 0.8 ** depth * Math.sqrt(numLines / (identifiers.length + 1));
63330
- for (const identifier of identifiers) {
63331
- if (!IGNORE_TOKENS.includes(identifier)) {
63332
- tokenScoresForFile[identifier] = tokenBaseScore;
63333
- }
63334
- }
63335
- fileCallsMap.set(filePath, calls);
63336
- for (const call of calls) {
63337
- if (!tokenScoresForFile[call]) {
63338
- externalCalls[call] = (externalCalls[call] ?? 0) + 1;
63339
- }
63340
- }
63341
- }
63342
- }
63343
- const tokenDefinitionMap = new Map;
63344
- const highestScores = new Map;
63345
- for (const [filePath, scores] of Object.entries(tokenScores)) {
63346
- for (const [token, score] of Object.entries(scores)) {
63347
- const currentHighestScore = highestScores.get(token) ?? -Infinity;
63348
- if (score > currentHighestScore) {
63349
- highestScores.set(token, score);
63350
- tokenDefinitionMap.set(token, filePath);
63351
- }
63352
- }
63353
- }
63354
- const tokenCallers = {};
63355
- for (const [callingFile, calls] of fileCallsMap.entries()) {
63356
- for (const call of calls) {
63357
- const definingFile = tokenDefinitionMap.get(call);
63358
- if (!definingFile || callingFile === definingFile) {
63359
- continue;
63360
- }
63361
- if (call in {}) {
63362
- continue;
63363
- }
63364
- if (!tokenCallers[definingFile]) {
63365
- tokenCallers[definingFile] = {};
63366
- }
63367
- if (!tokenCallers[definingFile][call]) {
63368
- tokenCallers[definingFile][call] = [];
63369
- }
63370
- const callerFiles = tokenCallers[definingFile][call];
63371
- if (callerFiles.length < MAX_CALLERS && !callerFiles.includes(callingFile)) {
63372
- callerFiles.push(callingFile);
63373
- }
63374
- }
63375
- }
63376
- for (const scores of Object.values(tokenScores)) {
63377
- for (const token of Object.keys(scores)) {
63378
- const numCalls = externalCalls[token] ?? 0;
63379
- if (typeof numCalls !== "number")
63380
- continue;
63381
- scores[token] *= 1 + Math.log(1 + numCalls);
63382
- scores[token] = Math.round(scores[token] * 1000) / 1000;
63383
- }
63384
- }
63385
- if (DEBUG_PARSING) {
63386
- const endTime = Date.now();
63387
- console.log(`Parsed ${filePaths.length} files in ${endTime - startTime2}ms`);
63388
- try {
63389
- fs4.writeFileSync("../debug/debug-parse.json", JSON.stringify({
63390
- tokenCallers,
63391
- tokenScores,
63392
- fileCallsMap,
63393
- externalCalls
63394
- }));
63395
- } catch {}
63396
- }
63397
- return { tokenScores, tokenCallers };
63398
- }
63399
- function parseTokens(filePath, languageConfig, readFile) {
63400
- const { parser, query } = languageConfig;
63401
- try {
63402
- const sourceCode = readFile ? readFile(filePath) : fs4.readFileSync(filePath, "utf8");
63403
- if (sourceCode === null) {
63404
- return {
63405
- numLines: 0,
63406
- identifiers: [],
63407
- calls: []
63408
- };
63409
- }
63410
- const numLines = sourceCode.match(/\n/g)?.length ?? 0 + 1;
63411
- if (!parser || !query) {
63412
- throw new Error("Parser or query not found");
63413
- }
63414
- const parseResults = parseFile(parser, query, sourceCode);
63415
- const identifiers = Array.from(new Set(parseResults.identifier));
63416
- const calls = Array.from(new Set(parseResults["call.identifier"]));
63417
- if (DEBUG_PARSING) {
63418
- console.log(`
63419
- Parsing ${filePath}:`);
63420
- console.log("Identifiers:", identifiers);
63421
- console.log("Calls:", calls);
63422
- }
63423
- return {
63424
- numLines,
63425
- identifiers: identifiers ?? [],
63426
- calls: calls ?? []
63427
- };
63428
- } catch (e) {
63429
- if (DEBUG_PARSING) {
63430
- console.error(`Error parsing query: ${e}`);
63431
- console.log(filePath);
63432
- }
63433
- return {
63434
- numLines: 0,
63435
- identifiers: [],
63436
- calls: []
63437
- };
63438
- }
63439
- }
63440
- function parseFile(parser, query, sourceCode) {
63441
- const tree = parser.parse(sourceCode);
63442
- if (!tree) {
63443
- return {};
63444
- }
63445
- const captures = query.captures(tree.rootNode);
63446
- const result = {};
63447
- for (const capture of captures) {
63448
- const { name: name14, node } = capture;
63449
- if (!result[name14]) {
63450
- result[name14] = [];
63451
- }
63452
- result[name14].push(node.text);
63453
- }
63454
- return result;
63455
- }
63456
-
63457
- // src/run-state.ts
63458
- var import_lodash17 = __toESM(require_lodash());
63459
- var import_v466 = __toESM(require("zod/v4"));
63460
-
63461
- // src/agents/load-agents.ts
63462
- var import_fs2 = __toESM(require("fs"));
63463
- var import_os2 = __toESM(require("os"));
63464
- var import_path5 = __toESM(require("path"));
63465
- var import_url = require("url");
63466
-
63467
- // src/validate-agents.ts
63468
- async function validateAgents2(definitions, options) {
63469
- const agentTemplates = {};
63470
- for (const [index, definition] of definitions.entries()) {
63471
- if (!definition) {
63472
- agentTemplates[`agent_${index}`] = definition;
63473
- continue;
63474
- }
63475
- const key = definition.id ? `${definition.id}_${index}` : `agent_${index}`;
63476
- agentTemplates[key] = definition;
63477
- }
63478
- const logger2 = {
63479
- debug: () => {},
63480
- info: () => {},
63481
- warn: () => {},
63482
- error: () => {}
63483
- };
63484
- let validationErrors = [];
63485
- if (options?.remote) {
63486
- const websiteUrl = options.websiteUrl || WEBSITE_URL;
63487
- try {
63488
- const response = await fetch(`${websiteUrl}/api/agents/validate`, {
63489
- method: "POST",
63490
- headers: {
63491
- "Content-Type": "application/json"
63492
- },
63493
- body: JSON.stringify({ agentDefinitions: definitions })
63494
- });
63495
- if (!response.ok) {
63496
- const errorData = await response.json().catch(() => ({}));
63497
- const errorMessage = errorData.error || `HTTP ${response.status}: ${response.statusText}`;
63498
- return {
63499
- success: false,
63500
- validationErrors: [
63501
- {
63502
- id: "network_error",
63503
- message: `Failed to validate via API: ${errorMessage}`
63504
- }
63505
- ],
63506
- errorCount: 1
63507
- };
63508
- }
63509
- const data = await response.json();
63510
- validationErrors = data.validationErrors || [];
63511
- } catch (error) {
63512
- const errorMessage = error instanceof Error ? error.message : String(error);
63513
- return {
63514
- success: false,
63515
- validationErrors: [
63516
- {
63517
- id: "network_error",
63518
- message: `Failed to connect to validation API: ${errorMessage}`
63519
- }
63520
- ],
63521
- errorCount: 1
63522
- };
63523
- }
63524
- } else {
63525
- const result = validateAgents({
63526
- agentTemplates,
63527
- logger: logger2
63528
- });
63529
- validationErrors = result.validationErrors;
63530
- }
63531
- const transformedErrors = validationErrors.map((error) => ({
63532
- id: error.filePath,
63533
- message: error.message
63534
- }));
63535
- return {
63536
- success: transformedErrors.length === 0,
63537
- validationErrors: transformedErrors,
63538
- errorCount: transformedErrors.length
63539
- };
63540
- }
63541
-
63542
- // src/agents/load-agents.ts
63543
- function resolveMcpEnv(env2, agentId, mcpServerName) {
63544
- if (!env2)
63545
- return {};
63546
- const resolved = {};
63547
- for (const [key, value] of Object.entries(env2)) {
63548
- if (value.startsWith("$")) {
63549
- const envVarName = value.slice(1);
63550
- const envName = "env";
63551
- const envValue = process[envName][envVarName];
63552
- if (envValue === undefined) {
63553
- throw new Error(`Missing environment variable '${envVarName}' required by agent '${agentId}' in mcpServers.${mcpServerName}.env.${key}`);
63554
- }
63555
- resolved[key] = envValue;
63556
- } else {
63557
- resolved[key] = value;
63558
- }
63559
- }
63560
- return resolved;
63561
- }
63562
- function resolveAgentMcpEnv(agent) {
63563
- if (!agent.mcpServers)
63564
- return;
63565
- for (const [serverName, config] of Object.entries(agent.mcpServers)) {
63566
- if ("command" in config && config.env) {
63567
- config.env = resolveMcpEnv(config.env, agent.id, serverName);
63568
- }
63569
- }
63570
- }
63571
- var agentFileExtensions = new Set([".ts", ".tsx", ".js", ".mjs", ".cjs"]);
63572
- var getAllAgentFiles = (dir) => {
63573
- const files = [];
63574
- try {
63575
- const entries = import_fs2.default.readdirSync(dir, { withFileTypes: true });
63576
- for (const entry of entries) {
63577
- const fullPath = import_path5.default.join(dir, entry.name);
63578
- if (entry.isDirectory()) {
63579
- files.push(...getAllAgentFiles(fullPath));
63580
- continue;
63581
- }
63582
- const extension = import_path5.default.extname(entry.name).toLowerCase();
63583
- const isAgentFile = entry.isFile() && agentFileExtensions.has(extension) && !entry.name.endsWith(".d.ts") && !entry.name.endsWith(".test.ts");
63584
- if (isAgentFile) {
63585
- files.push(fullPath);
63586
- }
63587
- }
63588
- } catch {}
63589
- return files;
63590
- };
63591
- var getDefaultAgentDirs = () => {
63592
- const cwdAgents = import_path5.default.join(process.cwd(), ".agents");
63593
- const parentAgents = import_path5.default.join(process.cwd(), "..", ".agents");
63594
- const homeAgents = import_path5.default.join(import_os2.default.homedir(), ".agents");
63595
- return [cwdAgents, parentAgents, homeAgents];
63596
- };
63597
- async function loadLocalAgents({
63598
- agentsPath,
63599
- verbose = false,
63600
- validate = false
63601
- }) {
63602
- const agents = {};
63603
- const agentDirs = agentsPath ? [agentsPath] : getDefaultAgentDirs();
63604
- const allAgentFiles = agentDirs.flatMap((dir) => getAllAgentFiles(dir));
63605
- if (allAgentFiles.length === 0) {
63606
- return validate ? { agents, validationErrors: [] } : agents;
63607
- }
63608
- for (const fullPath of allAgentFiles) {
63609
- try {
63610
- const agentModule = await importAgentModule(fullPath);
63611
- if (!agentModule) {
63612
- continue;
63613
- }
63614
- const agentDefinition = agentModule.default ?? agentModule;
63615
- if (!agentDefinition?.id || !agentDefinition?.model) {
63616
- if (verbose) {
63617
- console.error(`Agent definition missing required attributes (id, model): ${fullPath}`);
63618
- }
63619
- continue;
63620
- }
63621
- const processedAgentDefinition = {
63622
- ...agentDefinition,
63623
- _sourceFilePath: fullPath
63624
- };
63625
- if (agentDefinition.handleSteps) {
63626
- processedAgentDefinition.handleSteps = agentDefinition.handleSteps.toString();
63627
- }
63628
- try {
63629
- resolveAgentMcpEnv(processedAgentDefinition);
63630
- } catch (error) {
63631
- if (verbose) {
63632
- console.error(error instanceof Error ? error.message : String(error));
63633
- }
63634
- continue;
63635
- }
63636
- agents[processedAgentDefinition.id] = processedAgentDefinition;
63637
- } catch (error) {
63638
- if (verbose) {
63639
- console.error(`Error loading agent from file ${fullPath}:`, error instanceof Error ? error.message : error);
63640
- }
63641
- }
63642
- }
63643
- if (validate) {
63644
- const validationErrors = [];
63645
- if (Object.keys(agents).length > 0) {
63646
- const result = await validateAgents2(Object.values(agents));
63647
- if (!result.success) {
63648
- const errorsByAgentId = new Map;
63649
- for (const err of result.validationErrors) {
63650
- const lastUnderscoreIdx = err.id.lastIndexOf("_");
63651
- const agentId = lastUnderscoreIdx > 0 ? err.id.slice(0, lastUnderscoreIdx) : err.id;
63652
- if (!errorsByAgentId.has(agentId)) {
63653
- errorsByAgentId.set(agentId, err.message);
63654
- }
63655
- }
63656
- for (const agentId of Object.keys(agents)) {
63657
- const errorMessage = errorsByAgentId.get(agentId);
63658
- if (errorMessage) {
63659
- const agent = agents[agentId];
63660
- validationErrors.push({
63661
- agentId,
63662
- filePath: agent._sourceFilePath,
63663
- message: errorMessage
63664
- });
63665
- if (verbose) {
63666
- console.error(`Validation failed for agent '${agentId}': ${errorMessage}`);
63667
- }
63668
- delete agents[agentId];
63669
- }
63670
- }
63671
- }
63672
- }
63673
- return { agents, validationErrors };
63674
- }
63675
- return agents;
63676
- }
63677
- async function importAgentModule(fullPath) {
63678
- const urlVersion = `?update=${Date.now()}`;
63679
- return import(`${import_url.pathToFileURL(fullPath).href}${urlVersion}`);
63680
- }
63681
-
63682
- // src/run-state.ts
63683
- function processAgentDefinitions(agentDefinitions) {
63684
- const processedAgentTemplates = {};
63685
- agentDefinitions.forEach((definition) => {
63686
- const processedConfig = { ...definition };
63687
- if (processedConfig.handleSteps && typeof processedConfig.handleSteps === "function") {
63688
- processedConfig.handleSteps = processedConfig.handleSteps.toString();
63689
- }
63690
- if (processedConfig.id) {
63691
- processedAgentTemplates[processedConfig.id] = processedConfig;
63692
- }
63693
- });
63694
- return processedAgentTemplates;
63695
- }
63696
- function processCustomToolDefinitions(customToolDefinitions) {
63697
- return Object.fromEntries(customToolDefinitions.map((toolDefinition) => {
63698
- const jsonSchema = import_v466.default.toJSONSchema(toolDefinition.inputSchema, {
63699
- io: "input"
63700
- });
63701
- delete jsonSchema["$schema"];
63702
- return [
63703
- toolDefinition.toolName,
63704
- {
63705
- inputSchema: jsonSchema,
63706
- description: toolDefinition.description,
63707
- endsAgentStep: toolDefinition.endsAgentStep,
63708
- exampleInputs: toolDefinition.exampleInputs
63709
- }
63710
- ];
63711
- }));
63712
- }
63713
- async function computeProjectIndex(cwd, projectFiles) {
63714
- const filePaths = Object.keys(projectFiles).sort();
63715
- const fileTree = buildFileTree(filePaths);
63716
- let fileTokenScores = {};
63717
- let tokenCallers = {};
63718
- if (filePaths.length > 0) {
63719
- try {
63720
- const tokenData = await getFileTokenScores(cwd, filePaths, (filePath) => projectFiles[filePath] || null);
63721
- fileTokenScores = tokenData.tokenScores;
63722
- tokenCallers = tokenData.tokenCallers;
63723
- } catch (error) {
63724
- console.warn("Failed to generate parsed symbol scores:", error);
63725
- }
63726
- }
63727
- return { fileTree, fileTokenScores, tokenCallers };
63728
- }
63729
- function childProcessToPromise(proc) {
63730
- return new Promise((resolve2, reject) => {
63731
- let stdout = "";
63732
- let stderr = "";
63733
- proc.stdout?.on("data", (data) => {
63734
- stdout += data.toString();
63735
- });
63736
- proc.stderr?.on("data", (data) => {
63737
- stderr += data.toString();
63738
- });
63739
- proc.on("close", (code) => {
63740
- if (code === 0) {
63741
- resolve2({ stdout, stderr });
63742
- } else {
63743
- reject(new Error(`Command exited with code ${code}`));
63744
- }
63745
- });
63746
- proc.on("error", reject);
63747
- });
63748
- }
63749
- async function getGitChanges(params2) {
63750
- const { cwd, spawn: spawn2, logger: logger2 } = params2;
63751
- const status = childProcessToPromise(spawn2("git", ["status"], { cwd })).then(({ stdout }) => stdout).catch((error) => {
63752
- logger2.debug?.({ error }, "Failed to get git status");
63753
- return "";
63754
- });
63755
- const diff = childProcessToPromise(spawn2("git", ["diff"], { cwd })).then(({ stdout }) => stdout).catch((error) => {
63756
- logger2.debug?.({ error }, "Failed to get git diff");
63757
- return "";
63758
- });
63759
- const diffCached = childProcessToPromise(spawn2("git", ["diff", "--cached"], { cwd })).then(({ stdout }) => stdout).catch((error) => {
63760
- logger2.debug?.({ error }, "Failed to get git diff --cached");
63761
- return "";
63762
- });
63763
- const lastCommitMessages = childProcessToPromise(spawn2("git", ["shortlog", "HEAD~10..HEAD"], { cwd })).then(({ stdout }) => stdout.trim().split(`
63764
- `).slice(1).reverse().map((line) => line.trim()).join(`
63765
- `)).catch((error) => {
63766
- logger2.debug?.({ error }, "Failed to get lastCommitMessages");
63767
- return "";
63768
- });
63769
- return {
63770
- status: await status,
63771
- diff: await diff,
63772
- diffCached: await diffCached,
63773
- lastCommitMessages: await lastCommitMessages
63774
- };
63775
- }
63776
- async function discoverProjectFiles(params2) {
63777
- const { cwd, fs: fs6, logger: logger2 } = params2;
63778
- const fileTree = await getProjectFileTree({ projectRoot: cwd, fs: fs6 });
63779
- const filePaths = getAllFilePaths(fileTree);
63780
- let error;
63781
- const projectFilePromises = Object.fromEntries(filePaths.map((filePath) => [
63782
- filePath,
63783
- fs6.readFile(import_path6.default.join(cwd, filePath), "utf8").catch((err) => {
63784
- error = err;
63785
- return "[ERROR_READING_FILE]";
63786
- })
63787
- ]));
63788
- if (error) {
63789
- logger2.warn({ error: getErrorObject(error) }, "Failed to discover some project files");
63790
- }
63791
- const projectFilesResolved = {};
63792
- for (const [filePath, contentPromise] of Object.entries(projectFilePromises)) {
63793
- projectFilesResolved[filePath] = await contentPromise;
63794
- }
63795
- return projectFilesResolved;
63796
- }
63797
- function selectKnowledgeFilePaths(allFilePaths) {
63798
- const knowledgeCandidates = allFilePaths.filter((filePath) => {
63799
- const lowercaseFilePath = filePath.toLowerCase();
63800
- return lowercaseFilePath.endsWith("knowledge.md") || lowercaseFilePath.endsWith("agents.md") || lowercaseFilePath.endsWith("claude.md");
63801
- });
63802
- const byDirectory = new Map;
63803
- for (const filePath of knowledgeCandidates) {
63804
- const dir = import_path6.default.dirname(filePath);
63805
- if (!byDirectory.has(dir)) {
63806
- byDirectory.set(dir, []);
63807
- }
63808
- byDirectory.get(dir).push(filePath);
63809
- }
63810
- const selectedFiles = [];
63811
- for (const files of byDirectory.values()) {
63812
- const knowledgeMd = files.find((f) => f.toLowerCase().endsWith("knowledge.md"));
63813
- const agentsMd = files.find((f) => f.toLowerCase().endsWith("agents.md"));
63814
- const claudeMd = files.find((f) => f.toLowerCase().endsWith("claude.md"));
63815
- const selectedKnowledgeFile = knowledgeMd || agentsMd || claudeMd;
63816
- if (selectedKnowledgeFile) {
63817
- selectedFiles.push(selectedKnowledgeFile);
63818
- }
63819
- }
63820
- return selectedFiles;
63821
- }
63822
- function deriveKnowledgeFiles(projectFiles) {
63823
- const allFilePaths = Object.keys(projectFiles);
63824
- const selectedFilePaths = selectKnowledgeFilePaths(allFilePaths);
63825
- const knowledgeFiles = {};
63826
- for (const filePath of selectedFilePaths) {
63827
- knowledgeFiles[filePath] = projectFiles[filePath];
63828
- }
63829
- return knowledgeFiles;
63830
- }
63831
- async function initialSessionState(params2) {
63832
- const { cwd, maxAgentSteps } = params2;
63833
- let {
63834
- agentDefinitions,
63835
- customToolDefinitions,
63836
- projectFiles,
63837
- knowledgeFiles,
63838
- fs: fs6,
63839
- spawn: spawn2,
63840
- logger: logger2
63841
- } = params2;
63842
- if (!agentDefinitions) {
63843
- agentDefinitions = [];
63844
- }
63845
- if (!customToolDefinitions) {
63846
- customToolDefinitions = [];
63847
- }
63848
- if (!fs6) {
63849
- fs6 = require("fs").promises;
63850
- }
63851
- if (!spawn2) {
63852
- const { spawn: nodeSpawn } = require("child_process");
63853
- spawn2 = nodeSpawn;
63854
- }
63855
- if (!logger2) {
63856
- logger2 = {
63857
- debug: () => {},
63858
- info: () => {},
63859
- warn: () => {},
63860
- error: () => {}
63861
- };
63862
- }
63863
- if (projectFiles === undefined && cwd) {
63864
- projectFiles = await discoverProjectFiles({ cwd, fs: fs6, logger: logger2 });
63865
- }
63866
- if (knowledgeFiles === undefined) {
63867
- knowledgeFiles = projectFiles ? deriveKnowledgeFiles(projectFiles) : {};
63868
- }
63869
- let processedAgentTemplates = {};
63870
- if (agentDefinitions && agentDefinitions.length > 0) {
63871
- processedAgentTemplates = processAgentDefinitions(agentDefinitions);
63872
- } else {
63873
- processedAgentTemplates = await loadLocalAgents({ verbose: false });
63874
- }
63875
- const processedCustomToolDefinitions = processCustomToolDefinitions(customToolDefinitions);
63876
- let fileTree = [];
63877
- let fileTokenScores = {};
63878
- let tokenCallers = {};
63879
- if (cwd && projectFiles) {
63880
- const result = await computeProjectIndex(cwd, projectFiles);
63881
- fileTree = result.fileTree;
63882
- fileTokenScores = result.fileTokenScores;
63883
- tokenCallers = result.tokenCallers;
63884
- }
63885
- const gitChanges = cwd ? await getGitChanges({ cwd, spawn: spawn2, logger: logger2 }) : {
63886
- status: "",
63887
- diff: "",
63888
- diffCached: "",
63889
- lastCommitMessages: ""
63890
- };
63891
- const initialState = getInitialSessionState({
63892
- projectRoot: cwd ?? process.cwd(),
63893
- cwd: cwd ?? process.cwd(),
63894
- fileTree,
63895
- fileTokenScores,
63896
- tokenCallers,
63897
- knowledgeFiles,
63898
- userKnowledgeFiles: {},
63899
- agentTemplates: processedAgentTemplates,
63900
- customToolDefinitions: processedCustomToolDefinitions,
63901
- gitChanges,
63902
- changesSinceLastChat: {},
63903
- shellConfigFiles: {},
63904
- systemInfo: {
63905
- platform: process.platform,
63906
- shell: process.platform === "win32" ? "cmd.exe" : "bash",
63907
- nodeVersion: process.version,
63908
- arch: process.arch,
63909
- homedir: os4.homedir(),
63910
- cpus: os4.cpus().length ?? 1
63911
- }
63912
- });
63913
- if (maxAgentSteps) {
63914
- initialState.mainAgentState.stepsRemaining = maxAgentSteps;
63915
- }
63916
- return initialState;
63917
- }
63918
- async function generateInitialRunState({
63919
- cwd,
63920
- projectFiles,
63921
- knowledgeFiles,
63922
- agentDefinitions,
63923
- customToolDefinitions,
63924
- maxAgentSteps,
63925
- fs: fs6
63926
- }) {
63927
- return {
63928
- sessionState: await initialSessionState({
63929
- cwd,
63930
- projectFiles,
63931
- knowledgeFiles,
63932
- agentDefinitions,
63933
- customToolDefinitions,
63934
- maxAgentSteps,
63935
- fs: fs6
63936
- }),
63937
- output: {
63938
- type: "error",
63939
- message: "No output yet"
63940
- }
63941
- };
63942
- }
63943
- function withAdditionalMessage({
63944
- runState,
63945
- message
63946
- }) {
63947
- const newRunState = import_lodash17.cloneDeep(runState);
63948
- if (newRunState.sessionState) {
63949
- newRunState.sessionState.mainAgentState.messageHistory.push(message);
63950
- }
63951
- return newRunState;
63952
- }
63953
- function withMessageHistory({
63954
- runState,
63955
- messages
63956
- }) {
63957
- const newRunState = JSON.parse(JSON.stringify(runState));
63958
- if (newRunState.sessionState) {
63959
- newRunState.sessionState.mainAgentState.messageHistory = messages;
63960
- }
63961
- return newRunState;
63962
- }
63963
- async function applyOverridesToSessionState(cwd, baseSessionState, overrides) {
63964
- const sessionState = JSON.parse(JSON.stringify(baseSessionState));
63965
- if (overrides.maxAgentSteps !== undefined) {
63966
- sessionState.mainAgentState.stepsRemaining = overrides.maxAgentSteps;
63967
- }
63968
- if (overrides.projectFiles !== undefined) {
63969
- if (cwd) {
63970
- const { fileTree, fileTokenScores, tokenCallers } = await computeProjectIndex(cwd, overrides.projectFiles);
63971
- sessionState.fileContext.fileTree = fileTree;
63972
- sessionState.fileContext.fileTokenScores = fileTokenScores;
63973
- sessionState.fileContext.tokenCallers = tokenCallers;
63974
- } else {
63975
- sessionState.fileContext.fileTree = [];
63976
- sessionState.fileContext.fileTokenScores = {};
63977
- sessionState.fileContext.tokenCallers = {};
63978
- }
63979
- if (overrides.knowledgeFiles === undefined) {
63980
- sessionState.fileContext.knowledgeFiles = deriveKnowledgeFiles(overrides.projectFiles);
63981
- }
63982
- }
63983
- if (overrides.knowledgeFiles !== undefined) {
63984
- sessionState.fileContext.knowledgeFiles = overrides.knowledgeFiles;
63985
- }
63986
- if (overrides.agentDefinitions !== undefined) {
63987
- const processedAgentTemplates = processAgentDefinitions(overrides.agentDefinitions);
63988
- sessionState.fileContext.agentTemplates = {
63989
- ...sessionState.fileContext.agentTemplates,
63990
- ...processedAgentTemplates
63991
- };
63992
- }
63993
- if (overrides.customToolDefinitions !== undefined) {
63994
- const processedCustomToolDefinitions = processCustomToolDefinitions(overrides.customToolDefinitions);
63995
- sessionState.fileContext.customToolDefinitions = {
63996
- ...sessionState.fileContext.customToolDefinitions,
63997
- ...processedCustomToolDefinitions
63998
- };
63999
- }
64000
- return sessionState;
64001
- }
64002
- function buildFileTree(filePaths) {
64003
- const tree = {};
64004
- for (const filePath of filePaths) {
64005
- const parts = filePath.split("/");
64006
- for (let i = 0;i < parts.length; i++) {
64007
- const currentPath = parts.slice(0, i + 1).join("/");
64008
- const isFile = i === parts.length - 1;
64009
- if (!tree[currentPath]) {
64010
- tree[currentPath] = {
64011
- name: parts[i],
64012
- type: isFile ? "file" : "directory",
64013
- filePath: currentPath,
64014
- children: isFile ? undefined : []
64015
- };
64016
- }
64017
- }
64018
- }
64019
- const rootNodes = [];
64020
- const processed = new Set;
64021
- for (const [path10, node] of Object.entries(tree)) {
64022
- if (processed.has(path10))
64023
- continue;
64024
- const parentPath = path10.substring(0, path10.lastIndexOf("/"));
64025
- if (parentPath && tree[parentPath]) {
64026
- const parent = tree[parentPath];
64027
- if (parent.children && !parent.children.some((child) => child.filePath === path10)) {
64028
- parent.children.push(node);
64029
- }
64030
- } else {
64031
- rootNodes.push(node);
64032
- }
64033
- processed.add(path10);
64034
- }
64035
- function sortNodes(nodes) {
64036
- nodes.sort((a, b) => {
64037
- if (a.type !== b.type) {
64038
- return a.type === "directory" ? -1 : 1;
64039
- }
64040
- return a.name.localeCompare(b.name);
64041
- });
64042
- for (const node of nodes) {
64043
- if (node.children) {
64044
- sortNodes(node.children);
64045
- }
64046
- }
64047
- }
64048
- sortNodes(rootNodes);
64049
- return rootNodes;
64050
- }
64051
-
64052
62879
  // src/custom-tool.ts
64053
62880
  function getCustomToolDefinition({
64054
62881
  toolName: toolName31,
@@ -64146,19 +62973,19 @@ async function runOnce({
64146
62973
  extraToolResults,
64147
62974
  signal
64148
62975
  }) {
64149
- const fs6 = createConvexStubFs();
62976
+ const fs2 = createConvexStubFs();
64150
62977
  const spawn2 = createConvexStubSpawn();
64151
62978
  const preparedContent = wrapContentForUserMessage(content);
64152
62979
  let agentId;
64153
62980
  if (typeof agent !== "string") {
64154
- agentDefinitions = [...import_lodash18.cloneDeep(agentDefinitions) ?? [], agent];
62981
+ agentDefinitions = [...import_lodash17.cloneDeep(agentDefinitions) ?? [], agent];
64155
62982
  agentId = agent.id;
64156
62983
  } else {
64157
62984
  agentId = agent;
64158
62985
  }
64159
62986
  let sessionState;
64160
62987
  if (previousRun?.sessionState) {
64161
- sessionState = await applyOverridesToSessionState(undefined, previousRun.sessionState, {
62988
+ sessionState = await convexApplyOverridesToSessionState(undefined, previousRun.sessionState, {
64162
62989
  knowledgeFiles,
64163
62990
  agentDefinitions,
64164
62991
  customToolDefinitions,
@@ -64166,21 +62993,21 @@ async function runOnce({
64166
62993
  maxAgentSteps
64167
62994
  });
64168
62995
  } else {
64169
- sessionState = await initialSessionState({
62996
+ sessionState = await convexInitialSessionState({
64170
62997
  cwd: undefined,
64171
62998
  knowledgeFiles,
64172
62999
  agentDefinitions,
64173
63000
  customToolDefinitions,
64174
63001
  projectFiles,
64175
63002
  maxAgentSteps,
64176
- fs: fs6,
63003
+ fs: fs2,
64177
63004
  spawn: spawn2,
64178
63005
  logger: logger2
64179
63006
  });
64180
63007
  }
64181
- let resolve2 = () => {};
63008
+ let resolve = () => {};
64182
63009
  const promise = new Promise((res) => {
64183
- resolve2 = res;
63010
+ resolve = res;
64184
63011
  });
64185
63012
  async function onError(error) {
64186
63013
  if (handleEvent) {
@@ -64189,7 +63016,7 @@ async function runOnce({
64189
63016
  }
64190
63017
  let pendingAgentResponse = "";
64191
63018
  function getCancelledSessionState(message) {
64192
- const state = import_lodash18.cloneDeep(sessionState);
63019
+ const state = import_lodash17.cloneDeep(sessionState);
64193
63020
  state.mainAgentState.messageHistory.push(...getCancelledAdditionalMessages({
64194
63021
  prompt: prompt2,
64195
63022
  params: params2,
@@ -64316,7 +63143,7 @@ async function runOnce({
64316
63143
  if (action.type === "prompt-response") {
64317
63144
  handlePromptResponse({
64318
63145
  action,
64319
- resolve: resolve2,
63146
+ resolve,
64320
63147
  onError,
64321
63148
  initialSessionState: sessionState
64322
63149
  });
@@ -64325,7 +63152,7 @@ async function runOnce({
64325
63152
  if (action.type === "prompt-error") {
64326
63153
  handlePromptResponse({
64327
63154
  action,
64328
- resolve: resolve2,
63155
+ resolve,
64329
63156
  onError,
64330
63157
  initialSessionState: sessionState
64331
63158
  });
@@ -64362,7 +63189,7 @@ async function runOnce({
64362
63189
  }
64363
63190
  const userId2 = userInfo.id;
64364
63191
  signal?.addEventListener("abort", () => {
64365
- resolve2(getCancelledRunState());
63192
+ resolve(getCancelledRunState());
64366
63193
  });
64367
63194
  if (signal?.aborted) {
64368
63195
  return getCancelledRunState();
@@ -64390,7 +63217,7 @@ async function runOnce({
64390
63217
  }).catch((error) => {
64391
63218
  const errorMessage = error instanceof Error ? error.message : String(error ?? "");
64392
63219
  const statusCode = getErrorStatusCode(error);
64393
- resolve2({
63220
+ resolve({
64394
63221
  sessionState: getCancelledSessionState(errorMessage),
64395
63222
  output: {
64396
63223
  type: "error",
@@ -64504,14 +63331,14 @@ async function handleToolCall({
64504
63331
  }
64505
63332
  async function handlePromptResponse({
64506
63333
  action,
64507
- resolve: resolve2,
63334
+ resolve,
64508
63335
  onError,
64509
- initialSessionState: initialSessionState2
63336
+ initialSessionState
64510
63337
  }) {
64511
63338
  if (action.type === "prompt-error") {
64512
63339
  onError({ message: action.message });
64513
- resolve2({
64514
- sessionState: initialSessionState2,
63340
+ resolve({
63341
+ sessionState: initialSessionState,
64515
63342
  output: {
64516
63343
  type: "error",
64517
63344
  message: action.message
@@ -64527,8 +63354,8 @@ async function handlePromptResponse({
64527
63354
  ].join(`
64528
63355
  `);
64529
63356
  onError({ message });
64530
- resolve2({
64531
- sessionState: initialSessionState2,
63357
+ resolve({
63358
+ sessionState: initialSessionState,
64532
63359
  output: {
64533
63360
  type: "error",
64534
63361
  message
@@ -64544,13 +63371,13 @@ async function handlePromptResponse({
64544
63371
  message: "No output from agent"
64545
63372
  }
64546
63373
  };
64547
- resolve2(state);
63374
+ resolve(state);
64548
63375
  } else {
64549
63376
  onError({
64550
63377
  message: "Internal error: prompt response type not handled"
64551
63378
  });
64552
- resolve2({
64553
- sessionState: initialSessionState2,
63379
+ resolve({
63380
+ sessionState: initialSessionState,
64554
63381
  output: {
64555
63382
  type: "error",
64556
63383
  message: "Internal error: prompt response type not handled"
@@ -64596,5 +63423,5 @@ Provide a handleEvent function to handle this error.`);
64596
63423
  }
64597
63424
  }
64598
63425
 
64599
- //# debugId=74EA834B56EED7D064756E2164756E21
63426
+ //# debugId=BBFB92168977D73564756E2164756E21
64600
63427
  //# sourceMappingURL=convex.cjs.map