@google/gemini-cli-a2a-server 0.44.0-nightly.20260521.g57c42a5c4 → 0.44.0

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.
@@ -6856,7 +6856,7 @@ var require_file = __commonJS({
6856
6856
  stat(callback) {
6857
6857
  const target = this._getFile();
6858
6858
  const fullpath = path98.join(this.dirname, target);
6859
- fs89.stat(fullpath, (err2, stat6) => {
6859
+ fs89.stat(fullpath, (err2, stat7) => {
6860
6860
  if (err2 && err2.code === "ENOENT") {
6861
6861
  debug2("ENOENT\xA0ok", fullpath);
6862
6862
  this.filename = target;
@@ -6866,11 +6866,11 @@ var require_file = __commonJS({
6866
6866
  debug2(`err ${err2.code} ${fullpath}`);
6867
6867
  return callback(err2);
6868
6868
  }
6869
- if (!stat6 || this._needsNewFile(stat6.size)) {
6869
+ if (!stat7 || this._needsNewFile(stat7.size)) {
6870
6870
  return this._incFile(() => this.stat(callback));
6871
6871
  }
6872
6872
  this.filename = target;
6873
- callback(null, stat6.size);
6873
+ callback(null, stat7.size);
6874
6874
  });
6875
6875
  }
6876
6876
  /**
@@ -31345,13 +31345,13 @@ var require_view = __commonJS({
31345
31345
  View.prototype.resolve = function resolve24(dir, file) {
31346
31346
  var ext2 = this.ext;
31347
31347
  var path99 = join40(dir, file);
31348
- var stat6 = tryStat(path99);
31349
- if (stat6 && stat6.isFile()) {
31348
+ var stat7 = tryStat(path99);
31349
+ if (stat7 && stat7.isFile()) {
31350
31350
  return path99;
31351
31351
  }
31352
31352
  path99 = join40(dir, basename12(file, ext2), "index" + ext2);
31353
- stat6 = tryStat(path99);
31354
- if (stat6 && stat6.isFile()) {
31353
+ stat7 = tryStat(path99);
31354
+ if (stat7 && stat7.isFile()) {
31355
31355
  return path99;
31356
31356
  }
31357
31357
  };
@@ -31400,9 +31400,9 @@ var require_etag = __commonJS({
31400
31400
  }
31401
31401
  return obj && typeof obj === "object" && "ctime" in obj && toString2.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString2.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
31402
31402
  }
31403
- function stattag(stat6) {
31404
- var mtime = stat6.mtime.getTime().toString(16);
31405
- var size = stat6.size.toString(16);
31403
+ function stattag(stat7) {
31404
+ var mtime = stat7.mtime.getTime().toString(16);
31405
+ var size = stat7.size.toString(16);
31406
31406
  return '"' + size + "-" + mtime + '"';
31407
31407
  }
31408
31408
  }
@@ -35211,8 +35211,8 @@ var require_send = __commonJS({
35211
35211
  this.sendFile(path99);
35212
35212
  return res;
35213
35213
  };
35214
- SendStream.prototype.send = function send2(path99, stat6) {
35215
- var len = stat6.size;
35214
+ SendStream.prototype.send = function send2(path99, stat7) {
35215
+ var len = stat7.size;
35216
35216
  var options = this.options;
35217
35217
  var opts = {};
35218
35218
  var res = this.res;
@@ -35224,7 +35224,7 @@ var require_send = __commonJS({
35224
35224
  return;
35225
35225
  }
35226
35226
  debug2('pipe "%s"', path99);
35227
- this.setHeader(path99, stat6);
35227
+ this.setHeader(path99, stat7);
35228
35228
  this.type(path99);
35229
35229
  if (this.isConditionalGET()) {
35230
35230
  if (this.isPreconditionFailure()) {
@@ -35280,16 +35280,16 @@ var require_send = __commonJS({
35280
35280
  var i4 = 0;
35281
35281
  var self2 = this;
35282
35282
  debug2('stat "%s"', path99);
35283
- fs89.stat(path99, function onstat(err2, stat6) {
35283
+ fs89.stat(path99, function onstat(err2, stat7) {
35284
35284
  var pathEndsWithSep = path99[path99.length - 1] === sep8;
35285
35285
  if (err2 && err2.code === "ENOENT" && !extname2(path99) && !pathEndsWithSep) {
35286
35286
  return next(err2);
35287
35287
  }
35288
35288
  if (err2) return self2.onStatError(err2);
35289
- if (stat6.isDirectory()) return self2.redirect(path99);
35289
+ if (stat7.isDirectory()) return self2.redirect(path99);
35290
35290
  if (pathEndsWithSep) return self2.error(404);
35291
- self2.emit("file", path99, stat6);
35292
- self2.send(path99, stat6);
35291
+ self2.emit("file", path99, stat7);
35292
+ self2.send(path99, stat7);
35293
35293
  });
35294
35294
  function next(err2) {
35295
35295
  if (self2._extensions.length <= i4) {
@@ -35297,11 +35297,11 @@ var require_send = __commonJS({
35297
35297
  }
35298
35298
  var p3 = path99 + "." + self2._extensions[i4++];
35299
35299
  debug2('stat "%s"', p3);
35300
- fs89.stat(p3, function(err3, stat6) {
35300
+ fs89.stat(p3, function(err3, stat7) {
35301
35301
  if (err3) return next(err3);
35302
- if (stat6.isDirectory()) return next();
35303
- self2.emit("file", p3, stat6);
35304
- self2.send(p3, stat6);
35302
+ if (stat7.isDirectory()) return next();
35303
+ self2.emit("file", p3, stat7);
35304
+ self2.send(p3, stat7);
35305
35305
  });
35306
35306
  }
35307
35307
  };
@@ -35315,11 +35315,11 @@ var require_send = __commonJS({
35315
35315
  }
35316
35316
  var p3 = join40(path99, self2._index[i4]);
35317
35317
  debug2('stat "%s"', p3);
35318
- fs89.stat(p3, function(err3, stat6) {
35318
+ fs89.stat(p3, function(err3, stat7) {
35319
35319
  if (err3) return next(err3);
35320
- if (stat6.isDirectory()) return next();
35321
- self2.emit("file", p3, stat6);
35322
- self2.send(p3, stat6);
35320
+ if (stat7.isDirectory()) return next();
35321
+ self2.emit("file", p3, stat7);
35322
+ self2.send(p3, stat7);
35323
35323
  });
35324
35324
  }
35325
35325
  next();
@@ -35350,9 +35350,9 @@ var require_send = __commonJS({
35350
35350
  debug2("content-type %s", type3);
35351
35351
  res.setHeader("Content-Type", type3);
35352
35352
  };
35353
- SendStream.prototype.setHeader = function setHeader(path99, stat6) {
35353
+ SendStream.prototype.setHeader = function setHeader(path99, stat7) {
35354
35354
  var res = this.res;
35355
- this.emit("headers", res, path99, stat6);
35355
+ this.emit("headers", res, path99, stat7);
35356
35356
  if (this._acceptRanges && !res.getHeader("Accept-Ranges")) {
35357
35357
  debug2("accept ranges");
35358
35358
  res.setHeader("Accept-Ranges", "bytes");
@@ -35366,12 +35366,12 @@ var require_send = __commonJS({
35366
35366
  res.setHeader("Cache-Control", cacheControl);
35367
35367
  }
35368
35368
  if (this._lastModified && !res.getHeader("Last-Modified")) {
35369
- var modified = stat6.mtime.toUTCString();
35369
+ var modified = stat7.mtime.toUTCString();
35370
35370
  debug2("modified %s", modified);
35371
35371
  res.setHeader("Last-Modified", modified);
35372
35372
  }
35373
35373
  if (this._etag && !res.getHeader("ETag")) {
35374
- var val = etag(stat6);
35374
+ var val = etag(stat7);
35375
35375
  debug2("etag %s", val);
35376
35376
  res.setHeader("ETag", val);
35377
35377
  }
@@ -45891,7 +45891,7 @@ var require_src5 = __commonJS({
45891
45891
  var jws = require_jws();
45892
45892
  var path98 = __require("path");
45893
45893
  var util_1 = __require("util");
45894
- var readFile11 = fs89.readFile ? (0, util_1.promisify)(fs89.readFile) : async () => {
45894
+ var readFile12 = fs89.readFile ? (0, util_1.promisify)(fs89.readFile) : async () => {
45895
45895
  throw new ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
45896
45896
  };
45897
45897
  var GOOGLE_TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
@@ -45980,7 +45980,7 @@ var require_src5 = __commonJS({
45980
45980
  const ext2 = path98.extname(keyFile);
45981
45981
  switch (ext2) {
45982
45982
  case ".json": {
45983
- const key = await readFile11(keyFile, "utf8");
45983
+ const key = await readFile12(keyFile, "utf8");
45984
45984
  const body2 = JSON.parse(key);
45985
45985
  const privateKey = body2.private_key;
45986
45986
  const clientEmail = body2.client_email;
@@ -45992,7 +45992,7 @@ var require_src5 = __commonJS({
45992
45992
  case ".der":
45993
45993
  case ".crt":
45994
45994
  case ".pem": {
45995
- const privateKey = await readFile11(keyFile, "utf8");
45995
+ const privateKey = await readFile12(keyFile, "utf8");
45996
45996
  return { privateKey };
45997
45997
  }
45998
45998
  case ".p12":
@@ -47449,7 +47449,7 @@ var require_filesubjecttokensupplier = __commonJS({
47449
47449
  exports2.FileSubjectTokenSupplier = void 0;
47450
47450
  var util_1 = __require("util");
47451
47451
  var fs89 = __require("fs");
47452
- var readFile11 = (0, util_1.promisify)((_a4 = fs89.readFile) !== null && _a4 !== void 0 ? _a4 : () => {
47452
+ var readFile12 = (0, util_1.promisify)((_a4 = fs89.readFile) !== null && _a4 !== void 0 ? _a4 : () => {
47453
47453
  });
47454
47454
  var realpath2 = (0, util_1.promisify)((_b = fs89.realpath) !== null && _b !== void 0 ? _b : () => {
47455
47455
  });
@@ -47486,7 +47486,7 @@ var require_filesubjecttokensupplier = __commonJS({
47486
47486
  throw err2;
47487
47487
  }
47488
47488
  let subjectToken;
47489
- const rawText = await readFile11(parsedFilePath, { encoding: "utf8" });
47489
+ const rawText = await readFile12(parsedFilePath, { encoding: "utf8" });
47490
47490
  if (this.formatType === "text") {
47491
47491
  subjectToken = rawText;
47492
47492
  } else if (this.formatType === "json" && this.subjectTokenFieldName) {
@@ -53528,8 +53528,8 @@ var require_graceful_fs = __commonJS({
53528
53528
  fs90.createReadStream = createReadStream6;
53529
53529
  fs90.createWriteStream = createWriteStream5;
53530
53530
  var fs$readFile = fs90.readFile;
53531
- fs90.readFile = readFile11;
53532
- function readFile11(path98, options, cb) {
53531
+ fs90.readFile = readFile12;
53532
+ function readFile12(path98, options, cb) {
53533
53533
  if (typeof options === "function")
53534
53534
  cb = options, options = null;
53535
53535
  return go$readFile(path98, options, cb);
@@ -53705,7 +53705,7 @@ var require_graceful_fs = __commonJS({
53705
53705
  }
53706
53706
  function ReadStream$open() {
53707
53707
  var that = this;
53708
- open4(that.path, that.flags, that.mode, function(err2, fd) {
53708
+ open5(that.path, that.flags, that.mode, function(err2, fd) {
53709
53709
  if (err2) {
53710
53710
  if (that.autoClose)
53711
53711
  that.destroy();
@@ -53725,7 +53725,7 @@ var require_graceful_fs = __commonJS({
53725
53725
  }
53726
53726
  function WriteStream$open() {
53727
53727
  var that = this;
53728
- open4(that.path, that.flags, that.mode, function(err2, fd) {
53728
+ open5(that.path, that.flags, that.mode, function(err2, fd) {
53729
53729
  if (err2) {
53730
53730
  that.destroy();
53731
53731
  that.emit("error", err2);
@@ -53742,8 +53742,8 @@ var require_graceful_fs = __commonJS({
53742
53742
  return new fs90.WriteStream(path98, options);
53743
53743
  }
53744
53744
  var fs$open = fs90.open;
53745
- fs90.open = open4;
53746
- function open4(path98, flags2, mode, cb) {
53745
+ fs90.open = open5;
53746
+ function open5(path98, flags2, mode, cb) {
53747
53747
  if (typeof mode === "function")
53748
53748
  cb = mode, mode = null;
53749
53749
  return go$open(path98, flags2, mode, cb);
@@ -54185,7 +54185,7 @@ var require_copy = __commonJS({
54185
54185
  var { mkdirs } = require_mkdirs();
54186
54186
  var { pathExists: pathExists2 } = require_path_exists();
54187
54187
  var { utimesMillis } = require_utimes();
54188
- var stat6 = require_stat();
54188
+ var stat7 = require_stat();
54189
54189
  async function copy(src, dest, opts = {}) {
54190
54190
  if (typeof opts === "function") {
54191
54191
  opts = { filter: opts };
@@ -54199,8 +54199,8 @@ var require_copy = __commonJS({
54199
54199
  "fs-extra-WARN0001"
54200
54200
  );
54201
54201
  }
54202
- const { srcStat, destStat } = await stat6.checkPaths(src, dest, "copy", opts);
54203
- await stat6.checkParentPaths(src, srcStat, dest, "copy");
54202
+ const { srcStat, destStat } = await stat7.checkPaths(src, dest, "copy", opts);
54203
+ await stat7.checkParentPaths(src, srcStat, dest, "copy");
54204
54204
  const include = await runFilter(src, dest, opts);
54205
54205
  if (!include) return;
54206
54206
  const destParent = path98.dirname(dest);
@@ -54262,7 +54262,7 @@ var require_copy = __commonJS({
54262
54262
  promises10.push(
54263
54263
  runFilter(srcItem, destItem, opts).then((include) => {
54264
54264
  if (include) {
54265
- return stat6.checkPaths(srcItem, destItem, "copy", opts).then(({ destStat: destStat2 }) => {
54265
+ return stat7.checkPaths(srcItem, destItem, "copy", opts).then(({ destStat: destStat2 }) => {
54266
54266
  return getStatsAndPerformCopy(destStat2, srcItem, destItem, opts);
54267
54267
  });
54268
54268
  }
@@ -54292,10 +54292,10 @@ var require_copy = __commonJS({
54292
54292
  if (opts.dereference) {
54293
54293
  resolvedDest = path98.resolve(process.cwd(), resolvedDest);
54294
54294
  }
54295
- if (stat6.isSrcSubdir(resolvedSrc, resolvedDest)) {
54295
+ if (stat7.isSrcSubdir(resolvedSrc, resolvedDest)) {
54296
54296
  throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);
54297
54297
  }
54298
- if (stat6.isSrcSubdir(resolvedDest, resolvedSrc)) {
54298
+ if (stat7.isSrcSubdir(resolvedDest, resolvedSrc)) {
54299
54299
  throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`);
54300
54300
  }
54301
54301
  await fs89.unlink(dest);
@@ -54313,7 +54313,7 @@ var require_copy_sync = __commonJS({
54313
54313
  var path98 = __require("path");
54314
54314
  var mkdirsSync = require_mkdirs().mkdirsSync;
54315
54315
  var utimesMillisSync = require_utimes().utimesMillisSync;
54316
- var stat6 = require_stat();
54316
+ var stat7 = require_stat();
54317
54317
  function copySync(src, dest, opts) {
54318
54318
  if (typeof opts === "function") {
54319
54319
  opts = { filter: opts };
@@ -54328,8 +54328,8 @@ var require_copy_sync = __commonJS({
54328
54328
  "fs-extra-WARN0002"
54329
54329
  );
54330
54330
  }
54331
- const { srcStat, destStat } = stat6.checkPathsSync(src, dest, "copy", opts);
54332
- stat6.checkParentPathsSync(src, srcStat, dest, "copy");
54331
+ const { srcStat, destStat } = stat7.checkPathsSync(src, dest, "copy", opts);
54332
+ stat7.checkParentPathsSync(src, srcStat, dest, "copy");
54333
54333
  if (opts.filter && !opts.filter(src, dest)) return;
54334
54334
  const destParent = path98.dirname(dest);
54335
54335
  if (!fs89.existsSync(destParent)) mkdirsSync(destParent);
@@ -54403,7 +54403,7 @@ var require_copy_sync = __commonJS({
54403
54403
  const srcItem = path98.join(src, item);
54404
54404
  const destItem = path98.join(dest, item);
54405
54405
  if (opts.filter && !opts.filter(srcItem, destItem)) return;
54406
- const { destStat } = stat6.checkPathsSync(srcItem, destItem, "copy", opts);
54406
+ const { destStat } = stat7.checkPathsSync(srcItem, destItem, "copy", opts);
54407
54407
  return getStats(destStat, srcItem, destItem, opts);
54408
54408
  }
54409
54409
  function onLink(destStat, src, dest, opts) {
@@ -54424,10 +54424,10 @@ var require_copy_sync = __commonJS({
54424
54424
  if (opts.dereference) {
54425
54425
  resolvedDest = path98.resolve(process.cwd(), resolvedDest);
54426
54426
  }
54427
- if (stat6.isSrcSubdir(resolvedSrc, resolvedDest)) {
54427
+ if (stat7.isSrcSubdir(resolvedSrc, resolvedDest)) {
54428
54428
  throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);
54429
54429
  }
54430
- if (stat6.isSrcSubdir(resolvedDest, resolvedSrc)) {
54430
+ if (stat7.isSrcSubdir(resolvedDest, resolvedSrc)) {
54431
54431
  throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`);
54432
54432
  }
54433
54433
  return copyLink(resolvedSrc, dest);
@@ -54897,7 +54897,7 @@ var require_jsonfile = __commonJS({
54897
54897
  }
54898
54898
  return obj;
54899
54899
  }
54900
- var readFile11 = universalify.fromPromise(_readFile);
54900
+ var readFile12 = universalify.fromPromise(_readFile);
54901
54901
  function readFileSync10(file, options = {}) {
54902
54902
  if (typeof options === "string") {
54903
54903
  options = { encoding: options };
@@ -54929,7 +54929,7 @@ var require_jsonfile = __commonJS({
54929
54929
  return fs89.writeFileSync(file, str2, options);
54930
54930
  }
54931
54931
  module2.exports = {
54932
- readFile: readFile11,
54932
+ readFile: readFile12,
54933
54933
  readFileSync: readFileSync10,
54934
54934
  writeFile: writeFile9,
54935
54935
  writeFileSync: writeFileSync7
@@ -55038,11 +55038,11 @@ var require_move = __commonJS({
55038
55038
  var { remove: remove3 } = require_remove();
55039
55039
  var { mkdirp } = require_mkdirs();
55040
55040
  var { pathExists: pathExists2 } = require_path_exists();
55041
- var stat6 = require_stat();
55041
+ var stat7 = require_stat();
55042
55042
  async function move(src, dest, opts = {}) {
55043
55043
  const overwrite = opts.overwrite || opts.clobber || false;
55044
- const { srcStat, isChangingCase = false } = await stat6.checkPaths(src, dest, "move", opts);
55045
- await stat6.checkParentPaths(src, srcStat, dest, "move");
55044
+ const { srcStat, isChangingCase = false } = await stat7.checkPaths(src, dest, "move", opts);
55045
+ await stat7.checkParentPaths(src, srcStat, dest, "move");
55046
55046
  const destParent = path98.dirname(dest);
55047
55047
  const parsedParentPath = path98.parse(destParent);
55048
55048
  if (parsedParentPath.root !== destParent) {
@@ -55089,12 +55089,12 @@ var require_move_sync = __commonJS({
55089
55089
  var copySync = require_copy2().copySync;
55090
55090
  var removeSync = require_remove().removeSync;
55091
55091
  var mkdirpSync = require_mkdirs().mkdirpSync;
55092
- var stat6 = require_stat();
55092
+ var stat7 = require_stat();
55093
55093
  function moveSync(src, dest, opts) {
55094
55094
  opts = opts || {};
55095
55095
  const overwrite = opts.overwrite || opts.clobber || false;
55096
- const { srcStat, isChangingCase = false } = stat6.checkPathsSync(src, dest, "move", opts);
55097
- stat6.checkParentPathsSync(src, srcStat, dest, "move");
55096
+ const { srcStat, isChangingCase = false } = stat7.checkPathsSync(src, dest, "move", opts);
55097
+ stat7.checkParentPathsSync(src, srcStat, dest, "move");
55098
55098
  if (!isParentRoot(dest)) mkdirpSync(path98.dirname(dest));
55099
55099
  return doRename(src, dest, overwrite, isChangingCase);
55100
55100
  }
@@ -65590,8 +65590,8 @@ var require_lib8 = __commonJS({
65590
65590
  }
65591
65591
  async function isBinaryFile2(file, size) {
65592
65592
  if (isString2(file)) {
65593
- const stat6 = await statAsync(file);
65594
- isStatFile(stat6);
65593
+ const stat7 = await statAsync(file);
65594
+ isStatFile(stat7);
65595
65595
  const fileDescriptor = await openAsync(file, "r");
65596
65596
  const allocBuffer = Buffer.alloc(MAX_BYTES + UTF8_BOUNDARY_RESERVE);
65597
65597
  return new Promise((fulfill, reject) => {
@@ -65618,8 +65618,8 @@ var require_lib8 = __commonJS({
65618
65618
  exports2.isBinaryFile = isBinaryFile2;
65619
65619
  function isBinaryFileSync(file, size) {
65620
65620
  if (isString2(file)) {
65621
- const stat6 = fs89.statSync(file);
65622
- isStatFile(stat6);
65621
+ const stat7 = fs89.statSync(file);
65622
+ isStatFile(stat7);
65623
65623
  const fileDescriptor = fs89.openSync(file, "r");
65624
65624
  const allocBuffer = Buffer.alloc(MAX_BYTES + UTF8_BOUNDARY_RESERVE);
65625
65625
  const bytesRead = fs89.readSync(fileDescriptor, allocBuffer, 0, MAX_BYTES + UTF8_BOUNDARY_RESERVE, 0);
@@ -65700,8 +65700,8 @@ var require_lib8 = __commonJS({
65700
65700
  function isString2(x3) {
65701
65701
  return typeof x3 === "string";
65702
65702
  }
65703
- function isStatFile(stat6) {
65704
- if (!stat6.isFile()) {
65703
+ function isStatFile(stat7) {
65704
+ if (!stat7.isFile()) {
65705
65705
  throw new Error(`Path provided was not a file!`);
65706
65706
  }
65707
65707
  }
@@ -66456,8 +66456,8 @@ function robustRealpath(p3, visited = /* @__PURE__ */ new Set()) {
66456
66456
  } catch (e3) {
66457
66457
  if (e3 && typeof e3 === "object" && "code" in e3 && (e3.code === "ENOENT" || e3.code === "EISDIR" || e3.code === "ENAMETOOLONG" || e3.code === "ENOTDIR")) {
66458
66458
  try {
66459
- const stat6 = fs6.lstatSync(p3);
66460
- if (stat6.isSymbolicLink()) {
66459
+ const stat7 = fs6.lstatSync(p3);
66460
+ if (stat7.isSymbolicLink()) {
66461
66461
  const target = fs6.readlinkSync(p3);
66462
66462
  const resolvedTarget = path2.resolve(path2.dirname(p3), target);
66463
66463
  return robustRealpath(resolvedTarget, visited);
@@ -66503,10 +66503,11 @@ function toPathKey(p3) {
66503
66503
  }
66504
66504
  function isTrustedSystemPath(filePath) {
66505
66505
  const normPath = normalizePath(filePath);
66506
+ const isHermeticEnv = !!process.env["TEST_SRCDIR"] || !!process.env["TEST_WORKSPACE"] || !!process.env["BAZEL_TEST"] || !!process.env["RUNFILES_DIR"];
66506
66507
  const normCwd = normalizePath(process.cwd());
66507
66508
  const isRoot = normCwd === "/" || /^[a-zA-Z]:[\\/]?$/.test(normCwd);
66508
66509
  if (!isRoot && isSubpath(normCwd, normPath)) {
66509
- return false;
66510
+ return isHermeticEnv;
66510
66511
  }
66511
66512
  const platform10 = process.platform;
66512
66513
  if (platform10 === "win32") {
@@ -66525,7 +66526,10 @@ function isTrustedSystemPath(filePath) {
66525
66526
  "/opt/homebrew/Cellar",
66526
66527
  "/usr/local/Cellar",
66527
66528
  "/usr/sbin",
66528
- "/sbin"
66529
+ "/sbin",
66530
+ // 1P internal hermetic execution paths
66531
+ "/google/bin",
66532
+ "/google/src/cloud"
66529
66533
  ].map((p3) => normalizePath(p3));
66530
66534
  return trustedPrefixes.some((prefix) => normPath === prefix || normPath.startsWith(prefix + "/"));
66531
66535
  }
@@ -66967,11 +66971,11 @@ var require_mtime_precision = __commonJS({
66967
66971
  function probe(file, fs89, callback) {
66968
66972
  const cachedPrecision = fs89[cacheSymbol];
66969
66973
  if (cachedPrecision) {
66970
- return fs89.stat(file, (err2, stat6) => {
66974
+ return fs89.stat(file, (err2, stat7) => {
66971
66975
  if (err2) {
66972
66976
  return callback(err2);
66973
66977
  }
66974
- callback(null, stat6.mtime, cachedPrecision);
66978
+ callback(null, stat7.mtime, cachedPrecision);
66975
66979
  });
66976
66980
  }
66977
66981
  const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
@@ -66979,13 +66983,13 @@ var require_mtime_precision = __commonJS({
66979
66983
  if (err2) {
66980
66984
  return callback(err2);
66981
66985
  }
66982
- fs89.stat(file, (err3, stat6) => {
66986
+ fs89.stat(file, (err3, stat7) => {
66983
66987
  if (err3) {
66984
66988
  return callback(err3);
66985
66989
  }
66986
- const precision = stat6.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
66990
+ const precision = stat7.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
66987
66991
  Object.defineProperty(fs89, cacheSymbol, { value: precision });
66988
- callback(null, stat6.mtime, precision);
66992
+ callback(null, stat7.mtime, precision);
66989
66993
  });
66990
66994
  });
66991
66995
  }
@@ -67039,14 +67043,14 @@ var require_lockfile = __commonJS({
67039
67043
  if (options.stale <= 0) {
67040
67044
  return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
67041
67045
  }
67042
- options.fs.stat(lockfilePath, (err3, stat6) => {
67046
+ options.fs.stat(lockfilePath, (err3, stat7) => {
67043
67047
  if (err3) {
67044
67048
  if (err3.code === "ENOENT") {
67045
67049
  return acquireLock(file, { ...options, stale: 0 }, callback);
67046
67050
  }
67047
67051
  return callback(err3);
67048
67052
  }
67049
- if (!isLockStale(stat6, options)) {
67053
+ if (!isLockStale(stat7, options)) {
67050
67054
  return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
67051
67055
  }
67052
67056
  removeLock(file, options, (err4) => {
@@ -67058,8 +67062,8 @@ var require_lockfile = __commonJS({
67058
67062
  });
67059
67063
  });
67060
67064
  }
67061
- function isLockStale(stat6, options) {
67062
- return stat6.mtime.getTime() < Date.now() - options.stale;
67065
+ function isLockStale(stat7, options) {
67066
+ return stat7.mtime.getTime() < Date.now() - options.stale;
67063
67067
  }
67064
67068
  function removeLock(file, options, callback) {
67065
67069
  options.fs.rmdir(getLockFile(file, options), (err2) => {
@@ -67077,7 +67081,7 @@ var require_lockfile = __commonJS({
67077
67081
  lock4.updateDelay = lock4.updateDelay || options.update;
67078
67082
  lock4.updateTimeout = setTimeout(() => {
67079
67083
  lock4.updateTimeout = null;
67080
- options.fs.stat(lock4.lockfilePath, (err2, stat6) => {
67084
+ options.fs.stat(lock4.lockfilePath, (err2, stat7) => {
67081
67085
  const isOverThreshold = lock4.lastUpdate + options.stale < Date.now();
67082
67086
  if (err2) {
67083
67087
  if (err2.code === "ENOENT" || isOverThreshold) {
@@ -67086,7 +67090,7 @@ var require_lockfile = __commonJS({
67086
67090
  lock4.updateDelay = 1e3;
67087
67091
  return updateLock(file, options);
67088
67092
  }
67089
- const isMtimeOurs = lock4.mtime.getTime() === stat6.mtime.getTime();
67093
+ const isMtimeOurs = lock4.mtime.getTime() === stat7.mtime.getTime();
67090
67094
  if (!isMtimeOurs) {
67091
67095
  return setLockAsCompromised(
67092
67096
  file,
@@ -67211,11 +67215,11 @@ var require_lockfile = __commonJS({
67211
67215
  if (err2) {
67212
67216
  return callback(err2);
67213
67217
  }
67214
- options.fs.stat(getLockFile(file2, options), (err3, stat6) => {
67218
+ options.fs.stat(getLockFile(file2, options), (err3, stat7) => {
67215
67219
  if (err3) {
67216
67220
  return err3.code === "ENOENT" ? callback(null, false) : callback(err3);
67217
67221
  }
67218
- return callback(null, !isLockStale(stat6, options));
67222
+ return callback(null, !isLockStale(stat7, options));
67219
67223
  });
67220
67224
  });
67221
67225
  }
@@ -68998,12 +69002,23 @@ import fs11 from "node:fs";
68998
69002
  import path9 from "node:path";
68999
69003
  import { spawn, spawnSync } from "node:child_process";
69000
69004
  import * as readline from "node:readline";
69005
+ function stripHupGuard(command) {
69006
+ const trimmed2 = command.trimStart();
69007
+ const prefix = `${BASH_HUP_GUARD} `;
69008
+ if (trimmed2.startsWith(prefix)) {
69009
+ return trimmed2.slice(prefix.length);
69010
+ }
69011
+ if (trimmed2 === BASH_HUP_GUARD) {
69012
+ return "";
69013
+ }
69014
+ return command;
69015
+ }
69001
69016
  async function getCommandName(command, args2) {
69002
69017
  await initializeShellParsers();
69003
69018
  const fullCmd = [command, ...args2].join(" ");
69004
69019
  const stripped = stripShellWrapper(fullCmd);
69005
69020
  const roots = getCommandRoots(stripped).filter((r4) => r4 !== "shopt" && r4 !== "set");
69006
- if (roots.length > 0) {
69021
+ if (roots.length === 1) {
69007
69022
  return roots[0];
69008
69023
  }
69009
69024
  return path9.basename(command);
@@ -69369,13 +69384,14 @@ function parseCommandDetails(command) {
69369
69384
  }
69370
69385
  function getShellConfiguration() {
69371
69386
  if (isWindows()) {
69387
+ const powershellArgsPrefix = ["-NoProfile", "-NonInteractive", "-Command"];
69372
69388
  const comSpec = process.env["ComSpec"];
69373
69389
  if (comSpec) {
69374
69390
  const executable = comSpec.toLowerCase();
69375
69391
  if (executable.endsWith("powershell.exe") || executable.endsWith("pwsh.exe")) {
69376
69392
  return {
69377
69393
  executable: comSpec,
69378
- argsPrefix: ["-NoProfile", "-Command"],
69394
+ argsPrefix: powershellArgsPrefix,
69379
69395
  shell: "powershell"
69380
69396
  };
69381
69397
  }
@@ -69390,7 +69406,7 @@ function getShellConfiguration() {
69390
69406
  }
69391
69407
  return {
69392
69408
  executable: "powershell.exe",
69393
- argsPrefix: ["-NoProfile", "-Command"],
69409
+ argsPrefix: powershellArgsPrefix,
69394
69410
  shell: "powershell"
69395
69411
  };
69396
69412
  }
@@ -69466,14 +69482,17 @@ function getCommandRoots(command) {
69466
69482
  function stripShellWrapper(command) {
69467
69483
  const pattern = /^\s*(?:(?:(?:\S+\/)?(?:sh|bash|zsh))\s+-c|cmd\.exe\s+\/c|powershell(?:\.exe)?\s+(?:-NoProfile\s+)?-Command|pwsh(?:\.exe)?\s+(?:-NoProfile\s+)?-Command)\s+/i;
69468
69484
  const match2 = command.match(pattern);
69485
+ let result2;
69469
69486
  if (match2) {
69470
69487
  let newCommand = command.substring(match2[0].length).trim();
69471
69488
  if (newCommand.startsWith('"') && newCommand.endsWith('"') || newCommand.startsWith("'") && newCommand.endsWith("'")) {
69472
69489
  newCommand = newCommand.substring(1, newCommand.length - 1);
69473
69490
  }
69474
- return newCommand;
69491
+ result2 = newCommand;
69492
+ } else {
69493
+ result2 = command.trim();
69475
69494
  }
69476
- return command.trim();
69495
+ return stripHupGuard(result2);
69477
69496
  }
69478
69497
  async function* execStreaming(command, args2, options) {
69479
69498
  const sandboxManager = options?.sandboxManager ?? new NoopSandboxManager();
@@ -69673,7 +69692,7 @@ function detectPowerShellSubstitution(command) {
69673
69692
  }
69674
69693
  return false;
69675
69694
  }
69676
- var import_shell_quote, SHELL_TOOL_NAMES, bashLanguage, treeSitterInitialization, treeSitterInitializationError, ShellParserInitializationError, POWERSHELL_COMMAND_ENV, PARSE_TIMEOUT_MICROS, POWERSHELL_PARSER_SCRIPT, REDIRECTION_NAMES, isWindows, spawnAsync, POWERSHELL_KEYWORD_RE;
69695
+ var import_shell_quote, BASH_HUP_GUARD, SHELL_TOOL_NAMES, bashLanguage, treeSitterInitialization, treeSitterInitializationError, ShellParserInitializationError, POWERSHELL_COMMAND_ENV, PARSE_TIMEOUT_MICROS, POWERSHELL_PARSER_SCRIPT, REDIRECTION_NAMES, isWindows, spawnAsync, POWERSHELL_KEYWORD_RE;
69677
69696
  var init_shell_utils = __esm({
69678
69697
  "packages/core/dist/src/utils/shell-utils.js"() {
69679
69698
  "use strict";
@@ -69682,6 +69701,7 @@ var init_shell_utils = __esm({
69682
69701
  init_fileUtils();
69683
69702
  init_debugLogger();
69684
69703
  init_sandboxManager();
69704
+ BASH_HUP_GUARD = `trap '' HUP;`;
69685
69705
  SHELL_TOOL_NAMES = ["run_shell_command", "ShellTool"];
69686
69706
  bashLanguage = null;
69687
69707
  treeSitterInitialization = null;
@@ -70472,7 +70492,7 @@ async function getCommandName2(req) {
70472
70492
  const fullCmd = [req.command, ...req.args].join(" ");
70473
70493
  const stripped = stripShellWrapper(fullCmd);
70474
70494
  const roots = getCommandRoots(stripped).filter((r4) => r4 !== "shopt" && r4 !== "set");
70475
- if (roots.length > 0) {
70495
+ if (roots.length === 1) {
70476
70496
  return roots[0];
70477
70497
  }
70478
70498
  return path12.basename(req.command);
@@ -72288,8 +72308,8 @@ async function buildBwrapArgs(options) {
72288
72308
  if (!fs13.existsSync(p3))
72289
72309
  continue;
72290
72310
  try {
72291
- const stat6 = fs13.statSync(p3);
72292
- if (stat6.isDirectory()) {
72311
+ const stat7 = fs13.statSync(p3);
72312
+ if (stat7.isDirectory()) {
72293
72313
  mounts.push({ type: "--tmpfs-ro", dest: p3 });
72294
72314
  } else {
72295
72315
  mounts.push({ type: "--ro-bind", src: "/dev/null", dest: p3 });
@@ -79157,21 +79177,21 @@ var init_from = __esm({
79157
79177
  init_fetch_blob();
79158
79178
  ({ stat } = fs20);
79159
79179
  blobFromSync = (path98, type2) => fromBlob(statSync(path98), path98, type2);
79160
- blobFrom = (path98, type2) => stat(path98).then((stat6) => fromBlob(stat6, path98, type2));
79161
- fileFrom = (path98, type2) => stat(path98).then((stat6) => fromFile(stat6, path98, type2));
79180
+ blobFrom = (path98, type2) => stat(path98).then((stat7) => fromBlob(stat7, path98, type2));
79181
+ fileFrom = (path98, type2) => stat(path98).then((stat7) => fromFile(stat7, path98, type2));
79162
79182
  fileFromSync = (path98, type2) => fromFile(statSync(path98), path98, type2);
79163
- fromBlob = (stat6, path98, type2 = "") => new fetch_blob_default([new BlobDataItem({
79183
+ fromBlob = (stat7, path98, type2 = "") => new fetch_blob_default([new BlobDataItem({
79164
79184
  path: path98,
79165
- size: stat6.size,
79166
- lastModified: stat6.mtimeMs,
79185
+ size: stat7.size,
79186
+ lastModified: stat7.mtimeMs,
79167
79187
  start: 0
79168
79188
  })], { type: type2 });
79169
- fromFile = (stat6, path98, type2 = "") => new file_default([new BlobDataItem({
79189
+ fromFile = (stat7, path98, type2 = "") => new file_default([new BlobDataItem({
79170
79190
  path: path98,
79171
- size: stat6.size,
79172
- lastModified: stat6.mtimeMs,
79191
+ size: stat7.size,
79192
+ lastModified: stat7.mtimeMs,
79173
79193
  start: 0
79174
- })], basename3(path98), { type: type2, lastModified: stat6.mtimeMs });
79194
+ })], basename3(path98), { type: type2, lastModified: stat7.mtimeMs });
79175
79195
  BlobDataItem = class _BlobDataItem {
79176
79196
  #path;
79177
79197
  #start;
@@ -83909,7 +83929,7 @@ var require_src15 = __commonJS({
83909
83929
  });
83910
83930
  };
83911
83931
  }
83912
- var readFile11 = fs89.readFile ? (0, _util.promisify)(fs89.readFile) : /* @__PURE__ */ _asyncToGenerator(/* @__PURE__ */ _regenerator().m(function _callee() {
83932
+ var readFile12 = fs89.readFile ? (0, _util.promisify)(fs89.readFile) : /* @__PURE__ */ _asyncToGenerator(/* @__PURE__ */ _regenerator().m(function _callee() {
83913
83933
  return _regenerator().w(function(_context) {
83914
83934
  while (1) switch (_context.n) {
83915
83935
  case 0:
@@ -84049,7 +84069,7 @@ var require_src15 = __commonJS({
84049
84069
  break;
84050
84070
  case 1:
84051
84071
  _context2.n = 2;
84052
- return readFile11(keyFile, "utf8");
84072
+ return readFile12(keyFile, "utf8");
84053
84073
  case 2:
84054
84074
  key = _context2.v;
84055
84075
  body2 = JSON.parse(key);
@@ -84067,7 +84087,7 @@ var require_src15 = __commonJS({
84067
84087
  });
84068
84088
  case 4:
84069
84089
  _context2.n = 5;
84070
- return readFile11(keyFile, "utf8");
84090
+ return readFile12(keyFile, "utf8");
84071
84091
  case 5:
84072
84092
  _privateKey = _context2.v;
84073
84093
  return _context2.a(2, {
@@ -85664,7 +85684,7 @@ var require_filesubjecttokensupplier2 = __commonJS({
85664
85684
  exports2.FileSubjectTokenSupplier = void 0;
85665
85685
  var util_1 = __require("util");
85666
85686
  var fs89 = __require("fs");
85667
- var readFile11 = (0, util_1.promisify)(fs89.readFile ?? (() => {
85687
+ var readFile12 = (0, util_1.promisify)(fs89.readFile ?? (() => {
85668
85688
  }));
85669
85689
  var realpath2 = (0, util_1.promisify)(fs89.realpath ?? (() => {
85670
85690
  }));
@@ -85704,7 +85724,7 @@ var require_filesubjecttokensupplier2 = __commonJS({
85704
85724
  throw err2;
85705
85725
  }
85706
85726
  let subjectToken;
85707
- const rawText = await readFile11(parsedFilePath, { encoding: "utf8" });
85727
+ const rawText = await readFile12(parsedFilePath, { encoding: "utf8" });
85708
85728
  if (this.formatType === "text") {
85709
85729
  subjectToken = rawText;
85710
85730
  } else if (this.formatType === "json" && this.subjectTokenFieldName) {
@@ -90493,7 +90513,7 @@ var require_websocket = __commonJS({
90493
90513
  var http5 = __require("http");
90494
90514
  var net2 = __require("net");
90495
90515
  var tls = __require("tls");
90496
- var { randomBytes: randomBytes5, createHash: createHash17 } = __require("crypto");
90516
+ var { randomBytes: randomBytes5, createHash: createHash18 } = __require("crypto");
90497
90517
  var { Duplex, Readable: Readable7 } = __require("stream");
90498
90518
  var { URL: URL10 } = __require("url");
90499
90519
  var PerMessageDeflate = require_permessage_deflate();
@@ -91150,7 +91170,7 @@ var require_websocket = __commonJS({
91150
91170
  abortHandshake(websocket, socket, "Invalid Upgrade header");
91151
91171
  return;
91152
91172
  }
91153
- const digest = createHash17("sha1").update(key + GUID).digest("base64");
91173
+ const digest = createHash18("sha1").update(key + GUID).digest("base64");
91154
91174
  if (res.headers["sec-websocket-accept"] !== digest) {
91155
91175
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
91156
91176
  return;
@@ -91429,7 +91449,7 @@ var require_stream3 = __commonJS({
91429
91449
  };
91430
91450
  duplex._final = function(callback) {
91431
91451
  if (ws3.readyState === ws3.CONNECTING) {
91432
- ws3.once("open", function open4() {
91452
+ ws3.once("open", function open5() {
91433
91453
  duplex._final(callback);
91434
91454
  });
91435
91455
  return;
@@ -91450,7 +91470,7 @@ var require_stream3 = __commonJS({
91450
91470
  };
91451
91471
  duplex._write = function(chunk, encoding, callback) {
91452
91472
  if (ws3.readyState === ws3.CONNECTING) {
91453
- ws3.once("open", function open4() {
91473
+ ws3.once("open", function open5() {
91454
91474
  duplex._write(chunk, encoding, callback);
91455
91475
  });
91456
91476
  return;
@@ -91517,7 +91537,7 @@ var require_websocket_server = __commonJS({
91517
91537
  var EventEmitter11 = __require("events");
91518
91538
  var http5 = __require("http");
91519
91539
  var { Duplex } = __require("stream");
91520
- var { createHash: createHash17 } = __require("crypto");
91540
+ var { createHash: createHash18 } = __require("crypto");
91521
91541
  var extension = require_extension();
91522
91542
  var PerMessageDeflate = require_permessage_deflate();
91523
91543
  var subprotocol = require_subprotocol();
@@ -91814,7 +91834,7 @@ var require_websocket_server = __commonJS({
91814
91834
  );
91815
91835
  }
91816
91836
  if (this._state > RUNNING) return abortHandshake(socket, 503);
91817
- const digest = createHash17("sha1").update(key + GUID).digest("base64");
91837
+ const digest = createHash18("sha1").update(key + GUID).digest("base64");
91818
91838
  const headers = [
91819
91839
  "HTTP/1.1 101 Switching Protocols",
91820
91840
  "Upgrade: websocket",
@@ -168491,14 +168511,14 @@ var require_require_in_the_middle = __commonJS({
168491
168511
  moduleName = parsedPath.name;
168492
168512
  basedir = parsedPath.dir;
168493
168513
  } else {
168494
- const stat6 = moduleDetailsFromPath(filename);
168495
- if (stat6 === void 0) {
168514
+ const stat7 = moduleDetailsFromPath(filename);
168515
+ if (stat7 === void 0) {
168496
168516
  debug2("could not parse filename: %s", filename);
168497
168517
  return exports3;
168498
168518
  }
168499
- moduleName = stat6.name;
168500
- basedir = stat6.basedir;
168501
- const fullModuleName = resolveModuleName(stat6);
168519
+ moduleName = stat7.name;
168520
+ basedir = stat7.basedir;
168521
+ const fullModuleName = resolveModuleName(stat7);
168502
168522
  debug2("resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)", moduleName, id, fullModuleName, basedir);
168503
168523
  let matchFound = false;
168504
168524
  if (hasWhitelist) {
@@ -168560,9 +168580,9 @@ var require_require_in_the_middle = __commonJS({
168560
168580
  }
168561
168581
  }
168562
168582
  };
168563
- function resolveModuleName(stat6) {
168564
- const normalizedPath = path98.sep !== "/" ? stat6.path.split(path98.sep).join("/") : stat6.path;
168565
- return path98.posix.join(stat6.name, normalizedPath).replace(normalize7, "");
168583
+ function resolveModuleName(stat7) {
168584
+ const normalizedPath = path98.sep !== "/" ? stat7.path.split(path98.sep).join("/") : stat7.path;
168585
+ return path98.posix.join(stat7.name, normalizedPath).replace(normalize7, "");
168566
168586
  }
168567
168587
  }
168568
168588
  });
@@ -211631,8 +211651,8 @@ var GIT_COMMIT_INFO, CLI_VERSION;
211631
211651
  var init_git_commit = __esm({
211632
211652
  "packages/core/dist/src/generated/git-commit.js"() {
211633
211653
  "use strict";
211634
- GIT_COMMIT_INFO = "57c42a5c4";
211635
- CLI_VERSION = "0.44.0-nightly.20260521.g57c42a5c4";
211654
+ GIT_COMMIT_INFO = "b82ca5f8d";
211655
+ CLI_VERSION = "0.44.0";
211636
211656
  }
211637
211657
  });
211638
211658
 
@@ -218328,7 +218348,7 @@ var require_discovery = __commonJS({
218328
218348
  var util5 = __require("util");
218329
218349
  var apirequest_1 = require_apirequest();
218330
218350
  var endpoint_1 = require_endpoint();
218331
- var readFile11 = util5.promisify(fs89.readFile);
218351
+ var readFile12 = util5.promisify(fs89.readFile);
218332
218352
  var Discovery = class {
218333
218353
  /**
218334
218354
  * Discovery for discovering API endpoints
@@ -218415,7 +218435,7 @@ var require_discovery = __commonJS({
218415
218435
  const parts2 = resolve23.parse(apiDiscoveryUrl);
218416
218436
  if (apiDiscoveryUrl && !parts2.protocol) {
218417
218437
  this.log("Reading from file " + apiDiscoveryUrl);
218418
- const file = await readFile11(apiDiscoveryUrl, { encoding: "utf8" });
218438
+ const file = await readFile12(apiDiscoveryUrl, { encoding: "utf8" });
218419
218439
  return this.makeEndpoint(JSON.parse(file));
218420
218440
  } else {
218421
218441
  this.log("Requesting " + apiDiscoveryUrl);
@@ -239391,7 +239411,7 @@ var require_metadata5 = __commonJS({
239391
239411
  var gcpMetadata = require_src4();
239392
239412
  var google_auth_library_1 = require_src6();
239393
239413
  var util_1 = __require("util");
239394
- var readFile11 = (0, util_1.promisify)(fs89.readFile);
239414
+ var readFile12 = (0, util_1.promisify)(fs89.readFile);
239395
239415
  function zoneFromQualifiedZone(qualified) {
239396
239416
  return qualified.split("/").pop();
239397
239417
  }
@@ -239460,7 +239480,7 @@ var require_metadata5 = __commonJS({
239460
239480
  const location = zoneFromQualifiedZone(qualifiedZone);
239461
239481
  let namespace = "";
239462
239482
  try {
239463
- namespace = await readFile11(exports2.KUBERNETES_NAMESPACE_ID_PATH, "utf8");
239483
+ namespace = await readFile12(exports2.KUBERNETES_NAMESPACE_ID_PATH, "utf8");
239464
239484
  } catch (err2) {
239465
239485
  }
239466
239486
  return {
@@ -282254,9 +282274,23 @@ var init_thoughtUtils = __esm({
282254
282274
  }
282255
282275
  });
282256
282276
 
282277
+ // packages/core/dist/src/services/chatRecordingTypes.js
282278
+ var SESSION_FILE_PREFIX, MAX_TOOL_OUTPUT_SIZE;
282279
+ var init_chatRecordingTypes = __esm({
282280
+ "packages/core/dist/src/services/chatRecordingTypes.js"() {
282281
+ "use strict";
282282
+ init_thoughtUtils();
282283
+ SESSION_FILE_PREFIX = "session-";
282284
+ MAX_TOOL_OUTPUT_SIZE = 50 * 1024;
282285
+ }
282286
+ });
282287
+
282257
282288
  // packages/core/dist/src/utils/sessionOperations.js
282258
282289
  import * as fs33 from "node:fs/promises";
282259
282290
  import path27 from "node:path";
282291
+ function isSessionIdRecord(record2) {
282292
+ return record2 !== null && typeof record2 === "object" && "sessionId" in record2 && typeof record2.sessionId === "string";
282293
+ }
282260
282294
  function validateAndSanitizeSessionId(sessionId) {
282261
282295
  if (!sessionId || sessionId === "." || sessionId === "..") {
282262
282296
  throw new Error(`Invalid sessionId: ${sessionId}`);
@@ -282282,11 +282316,14 @@ async function deleteSessionArtifactsAsync(sessionId, tempDir) {
282282
282316
  if (err2.code !== "ENOENT")
282283
282317
  throw err2;
282284
282318
  });
282285
- const sessionDir = path27.join(tempDir, safeSessionId);
282286
- await fs33.rm(sessionDir, { recursive: true, force: true }).catch((err2) => {
282287
- if (err2.code !== "ENOENT")
282288
- throw err2;
282289
- });
282319
+ const hasSeparator = safeSessionId.includes(path27.sep) || safeSessionId.includes("/") || safeSessionId.includes("\\");
282320
+ if (!hasSeparator && !RESERVED_SESSION_DIR_NAMES.has(safeSessionId.toLowerCase())) {
282321
+ const sessionDir = path27.join(tempDir, safeSessionId);
282322
+ await fs33.rm(sessionDir, { recursive: true, force: true }).catch((err2) => {
282323
+ if (err2.code !== "ENOENT")
282324
+ throw err2;
282325
+ });
282326
+ }
282290
282327
  } catch (error2) {
282291
282328
  debugLogger.error(`Error deleting session artifacts for ${sessionId}:`, error2);
282292
282329
  }
@@ -282319,25 +282356,116 @@ async function deleteSubagentSessionDirAndArtifactsAsync(parentSessionId, chatsD
282319
282356
  });
282320
282357
  }
282321
282358
  }
282322
- var LOGS_DIR, TOOL_OUTPUTS_DIR2;
282359
+ function deriveSessionShortId(sessionIdOrBasename) {
282360
+ let shortId = sessionIdOrBasename;
282361
+ if (sessionIdOrBasename.startsWith(SESSION_FILE_PREFIX)) {
282362
+ const withoutExt = sessionIdOrBasename.replace(/\.jsonl?$/, "");
282363
+ const parts2 = withoutExt.split("-");
282364
+ shortId = parts2[parts2.length - 1];
282365
+ } else if (sessionIdOrBasename.length >= 8) {
282366
+ shortId = sessionIdOrBasename.slice(0, 8);
282367
+ } else {
282368
+ throw new Error("Invalid sessionId or basename provided for deletion");
282369
+ }
282370
+ if (shortId.length !== 8) {
282371
+ throw new Error("Derived shortId must be exactly 8 characters");
282372
+ }
282373
+ return shortId;
282374
+ }
282375
+ async function getMatchingSessionFiles(chatsDir, shortId) {
282376
+ const files = await fs33.readdir(chatsDir);
282377
+ return files.filter((f4) => f4.startsWith(SESSION_FILE_PREFIX) && (f4.endsWith(`-${shortId}.json`) || f4.endsWith(`-${shortId}.jsonl`)));
282378
+ }
282379
+ async function deleteSessionFileAndArtifacts(chatsDir, file, tempDir) {
282380
+ const filePath = path27.join(chatsDir, file);
282381
+ let fullSessionId;
282382
+ try {
282383
+ const CHUNK_SIZE = 4096;
282384
+ const buffer = Buffer.alloc(CHUNK_SIZE);
282385
+ let firstLine;
282386
+ let fd;
282387
+ try {
282388
+ fd = await fs33.open(filePath, "r");
282389
+ const { bytesRead } = await fd.read(buffer, 0, CHUNK_SIZE, 0);
282390
+ if (bytesRead > 0) {
282391
+ const contentChunk = buffer.toString("utf8", 0, bytesRead);
282392
+ const newlineIndex = contentChunk.indexOf("\n");
282393
+ firstLine = newlineIndex !== -1 ? contentChunk.substring(0, newlineIndex) : contentChunk;
282394
+ try {
282395
+ const content = JSON.parse(firstLine);
282396
+ if (isSessionIdRecord(content)) {
282397
+ fullSessionId = content.sessionId;
282398
+ }
282399
+ } catch {
282400
+ }
282401
+ }
282402
+ } finally {
282403
+ if (fd !== void 0) {
282404
+ await fd.close();
282405
+ }
282406
+ }
282407
+ if (!fullSessionId) {
282408
+ try {
282409
+ const fileContent = await fs33.readFile(filePath, "utf8");
282410
+ const parsed = JSON.parse(fileContent);
282411
+ if (isSessionIdRecord(parsed)) {
282412
+ fullSessionId = parsed.sessionId;
282413
+ }
282414
+ } catch {
282415
+ }
282416
+ }
282417
+ if (fullSessionId) {
282418
+ await deleteSessionArtifactsAsync(fullSessionId, tempDir);
282419
+ await deleteSubagentSessionDirAndArtifactsAsync(fullSessionId, chatsDir, tempDir);
282420
+ }
282421
+ } catch (error2) {
282422
+ if (!isNodeError(error2) || error2.code !== "ENOENT") {
282423
+ debugLogger.error(`Error deleting artifacts for session file ${file}:`, error2);
282424
+ }
282425
+ } finally {
282426
+ try {
282427
+ await fs33.unlink(filePath);
282428
+ } catch (error2) {
282429
+ if (isNodeError(error2) && error2.code !== "ENOENT") {
282430
+ debugLogger.error(`Error unlinking session file ${file}:`, error2);
282431
+ }
282432
+ }
282433
+ }
282434
+ }
282435
+ async function deleteStoredSession(config3, sessionIdOrBasename) {
282436
+ try {
282437
+ const tempDir = config3.storage.getProjectTempDir();
282438
+ const chatsDir = path27.join(tempDir, "chats");
282439
+ const shortId = deriveSessionShortId(sessionIdOrBasename);
282440
+ const chatsDirStat = await fs33.stat(chatsDir).catch(() => null);
282441
+ if (!chatsDirStat || !chatsDirStat.isDirectory()) {
282442
+ return;
282443
+ }
282444
+ const matchingFiles = await getMatchingSessionFiles(chatsDir, shortId);
282445
+ for (const file of matchingFiles) {
282446
+ await deleteSessionFileAndArtifacts(chatsDir, file, tempDir);
282447
+ }
282448
+ } catch (error2) {
282449
+ debugLogger.error("Error deleting session file.", error2);
282450
+ throw error2;
282451
+ }
282452
+ }
282453
+ var LOGS_DIR, TOOL_OUTPUTS_DIR2, CHATS_DIR, RESERVED_SESSION_DIR_NAMES;
282323
282454
  var init_sessionOperations = __esm({
282324
282455
  "packages/core/dist/src/utils/sessionOperations.js"() {
282325
282456
  "use strict";
282326
282457
  init_fileUtils();
282327
282458
  init_debugLogger();
282459
+ init_errors2();
282460
+ init_chatRecordingTypes();
282328
282461
  LOGS_DIR = "logs";
282329
282462
  TOOL_OUTPUTS_DIR2 = "tool-outputs";
282330
- }
282331
- });
282332
-
282333
- // packages/core/dist/src/services/chatRecordingTypes.js
282334
- var SESSION_FILE_PREFIX, MAX_TOOL_OUTPUT_SIZE;
282335
- var init_chatRecordingTypes = __esm({
282336
- "packages/core/dist/src/services/chatRecordingTypes.js"() {
282337
- "use strict";
282338
- init_thoughtUtils();
282339
- SESSION_FILE_PREFIX = "session-";
282340
- MAX_TOOL_OUTPUT_SIZE = 50 * 1024;
282463
+ CHATS_DIR = "chats";
282464
+ RESERVED_SESSION_DIR_NAMES = /* @__PURE__ */ new Set([
282465
+ CHATS_DIR,
282466
+ LOGS_DIR,
282467
+ TOOL_OUTPUTS_DIR2
282468
+ ]);
282341
282469
  }
282342
282470
  });
282343
282471
 
@@ -282370,9 +282498,6 @@ function isPartialMetadataRecord(record2) {
282370
282498
  function isTextPart(part) {
282371
282499
  return isStringProperty(part, "text");
282372
282500
  }
282373
- function isSessionIdRecord(record2) {
282374
- return isStringProperty(record2, "sessionId");
282375
- }
282376
282501
  async function loadConversationRecord(filePath, options) {
282377
282502
  if (!fs34.existsSync(filePath)) {
282378
282503
  return null;
@@ -282460,12 +282585,61 @@ async function loadConversationRecord(filePath, options) {
282460
282585
  isTrackingMemoryScratchpadFreshness = Boolean(record2.$set.memoryScratchpad);
282461
282586
  memoryScratchpadIsStale = false;
282462
282587
  }
282588
+ if (hasProperty(record2.$set, "messages") && Array.isArray(record2.$set.messages)) {
282589
+ messagesMap.clear();
282590
+ if (options?.metadataOnly) {
282591
+ messageIds.length = 0;
282592
+ messageKinds.clear();
282593
+ }
282594
+ for (const msg of record2.$set.messages) {
282595
+ if (isMessageRecord(msg)) {
282596
+ const id = msg.id;
282597
+ const isUser = msg.type === "user";
282598
+ const isUserOrAssistant = msg.type === "user" || msg.type === "gemini";
282599
+ if (options?.metadataOnly) {
282600
+ messageIds.push(id);
282601
+ messageKinds.set(id, { isUser, isUserOrAssistant });
282602
+ } else {
282603
+ messagesMap.set(id, msg);
282604
+ }
282605
+ if (!firstUserMessageStr && isUser && msg.content && (Array.isArray(msg.content) || typeof msg.content === "string")) {
282606
+ if (Array.isArray(msg.content)) {
282607
+ firstUserMessageStr = msg.content.map((p3) => isTextPart(p3) ? p3.text : "").join("");
282608
+ } else {
282609
+ firstUserMessageStr = msg.content;
282610
+ }
282611
+ }
282612
+ }
282613
+ }
282614
+ }
282463
282615
  metadata2 = {
282464
282616
  ...metadata2,
282465
282617
  ...record2.$set
282466
282618
  };
282467
282619
  } else if (isPartialMetadataRecord(record2)) {
282468
282620
  metadata2 = { ...metadata2, ...record2 };
282621
+ if (hasProperty(record2, "messages") && Array.isArray(record2.messages)) {
282622
+ for (const msg of record2.messages) {
282623
+ if (isMessageRecord(msg)) {
282624
+ const id = msg.id;
282625
+ const isUser = msg.type === "user";
282626
+ const isUserOrAssistant = msg.type === "user" || msg.type === "gemini";
282627
+ if (options?.metadataOnly) {
282628
+ messageIds.push(id);
282629
+ messageKinds.set(id, { isUser, isUserOrAssistant });
282630
+ } else {
282631
+ messagesMap.set(id, msg);
282632
+ }
282633
+ if (!firstUserMessageStr && isUser && msg.content && (Array.isArray(msg.content) || typeof msg.content === "string")) {
282634
+ if (Array.isArray(msg.content)) {
282635
+ firstUserMessageStr = msg.content.map((p3) => isTextPart(p3) ? p3.text : "").join("");
282636
+ } else {
282637
+ firstUserMessageStr = msg.content;
282638
+ }
282639
+ }
282640
+ }
282641
+ }
282642
+ }
282469
282643
  }
282470
282644
  } catch {
282471
282645
  }
@@ -282473,9 +282647,8 @@ async function loadConversationRecord(filePath, options) {
282473
282647
  if (!metadata2.sessionId || !metadata2.projectHash) {
282474
282648
  return await parseLegacyRecordFallback(filePath, options);
282475
282649
  }
282476
- const metadataMessages = Array.isArray(metadata2.messages) ? metadata2.messages : [];
282477
- const loadedMessages = metadataMessages.length > 0 ? metadataMessages : Array.from(messagesMap.values());
282478
- const metadataFirstUserMessage = metadataMessages.find((message) => message.type === "user") ?? null;
282650
+ const loadedMessages = Array.from(messagesMap.values());
282651
+ const metadataFirstUserMessage = loadedMessages.find((message) => message.type === "user") ?? null;
282479
282652
  let fallbackFirstUserMessage = firstUserMessageStr;
282480
282653
  if (!fallbackFirstUserMessage && metadataFirstUserMessage) {
282481
282654
  const rawContent = metadataFirstUserMessage.content;
@@ -282497,11 +282670,11 @@ async function loadConversationRecord(filePath, options) {
282497
282670
  directories: metadata2.directories,
282498
282671
  kind: metadata2.kind,
282499
282672
  messages: options?.metadataOnly ? [] : loadedMessages,
282500
- messageCount: options?.metadataOnly ? metadataMessages.length || messageIds.length : loadedMessages.length,
282501
- userMessageCount: options?.metadataOnly && metadataMessages.length > 0 ? metadataMessages.filter((m3) => m3.type === "user").length : userMessageCount,
282673
+ messageCount: options?.metadataOnly ? loadedMessages.length || messageIds.length : loadedMessages.length,
282674
+ userMessageCount,
282502
282675
  memoryScratchpadIsStale: isTrackingMemoryScratchpadFreshness ? memoryScratchpadIsStale : void 0,
282503
282676
  firstUserMessage: fallbackFirstUserMessage,
282504
- hasUserOrAssistantMessage: options?.metadataOnly && metadataMessages.length > 0 ? metadataMessages.some((m3) => m3.type === "user" || m3.type === "gemini") : hasUserOrAssistant
282677
+ hasUserOrAssistantMessage: hasUserOrAssistant
282505
282678
  };
282506
282679
  } catch (error2) {
282507
282680
  debugLogger.error("Error loading conversation record from JSONL:", error2);
@@ -282862,98 +283035,7 @@ var init_chatRecordingService = __esm({
282862
283035
  * @throws {Error} If shortId validation fails.
282863
283036
  */
282864
283037
  async deleteSession(sessionIdOrBasename) {
282865
- try {
282866
- const tempDir = this.context.config.storage.getProjectTempDir();
282867
- const chatsDir = path28.join(tempDir, "chats");
282868
- const shortId = this.deriveShortId(sessionIdOrBasename);
282869
- if (!await fs34.promises.stat(chatsDir).catch(() => null)) {
282870
- return;
282871
- }
282872
- const matchingFiles = await this.getMatchingSessionFiles(chatsDir, shortId);
282873
- for (const file of matchingFiles) {
282874
- await this.deleteSessionAndArtifacts(chatsDir, file, tempDir);
282875
- }
282876
- } catch (error2) {
282877
- debugLogger.error("Error deleting session file.", error2);
282878
- throw error2;
282879
- }
282880
- }
282881
- deriveShortId(sessionIdOrBasename) {
282882
- let shortId = sessionIdOrBasename;
282883
- if (sessionIdOrBasename.startsWith(SESSION_FILE_PREFIX)) {
282884
- const withoutExt = sessionIdOrBasename.replace(/\.jsonl?$/, "");
282885
- const parts2 = withoutExt.split("-");
282886
- shortId = parts2[parts2.length - 1];
282887
- } else if (sessionIdOrBasename.length >= 8) {
282888
- shortId = sessionIdOrBasename.slice(0, 8);
282889
- } else {
282890
- throw new Error("Invalid sessionId or basename provided for deletion");
282891
- }
282892
- if (shortId.length !== 8) {
282893
- throw new Error("Derived shortId must be exactly 8 characters");
282894
- }
282895
- return shortId;
282896
- }
282897
- async getMatchingSessionFiles(chatsDir, shortId) {
282898
- const files = await fs34.promises.readdir(chatsDir);
282899
- return files.filter((f4) => f4.startsWith(SESSION_FILE_PREFIX) && (f4.endsWith(`-${shortId}.json`) || f4.endsWith(`-${shortId}.jsonl`)));
282900
- }
282901
- /**
282902
- * Deletes a single session file and its associated logs, tool-outputs, and directory.
282903
- */
282904
- async deleteSessionAndArtifacts(chatsDir, file, tempDir) {
282905
- const filePath = path28.join(chatsDir, file);
282906
- let fullSessionId;
282907
- try {
282908
- const CHUNK_SIZE = 4096;
282909
- const buffer = Buffer.alloc(CHUNK_SIZE);
282910
- let firstLine;
282911
- let fd;
282912
- try {
282913
- fd = await fs34.promises.open(filePath, "r");
282914
- const { bytesRead } = await fd.read(buffer, 0, CHUNK_SIZE, 0);
282915
- if (bytesRead > 0) {
282916
- const contentChunk = buffer.toString("utf8", 0, bytesRead);
282917
- const newlineIndex = contentChunk.indexOf("\n");
282918
- firstLine = newlineIndex !== -1 ? contentChunk.substring(0, newlineIndex) : contentChunk;
282919
- try {
282920
- const content = JSON.parse(firstLine);
282921
- if (isSessionIdRecord(content)) {
282922
- fullSessionId = content.sessionId;
282923
- }
282924
- } catch {
282925
- }
282926
- }
282927
- } finally {
282928
- if (fd !== void 0) {
282929
- await fd.close();
282930
- }
282931
- }
282932
- if (!fullSessionId) {
282933
- try {
282934
- const fileContent = await fs34.promises.readFile(filePath, "utf8");
282935
- const parsed = JSON.parse(fileContent);
282936
- if (isSessionIdRecord(parsed)) {
282937
- fullSessionId = parsed.sessionId;
282938
- }
282939
- } catch {
282940
- }
282941
- }
282942
- if (fullSessionId) {
282943
- await deleteSessionArtifactsAsync(fullSessionId, tempDir);
282944
- await deleteSubagentSessionDirAndArtifactsAsync(fullSessionId, chatsDir, tempDir);
282945
- }
282946
- } catch (error2) {
282947
- debugLogger.error(`Error deleting artifacts for session file ${file}:`, error2);
282948
- } finally {
282949
- try {
282950
- await fs34.promises.unlink(filePath);
282951
- } catch (error2) {
282952
- if (isNodeError(error2) && error2.code !== "ENOENT") {
282953
- debugLogger.error(`Error unlinking session file ${file}:`, error2);
282954
- }
282955
- }
282956
- }
283038
+ return deleteStoredSession(this.context.config, sessionIdOrBasename);
282957
283039
  }
282958
283040
  /**
282959
283041
  * Asynchronously deletes the current session's chat file and tool outputs.
@@ -301850,15 +301932,15 @@ var require_windows = __commonJS({
301850
301932
  }
301851
301933
  return false;
301852
301934
  }
301853
- function checkStat(stat6, path98, options) {
301854
- if (!stat6.isSymbolicLink() && !stat6.isFile()) {
301935
+ function checkStat(stat7, path98, options) {
301936
+ if (!stat7.isSymbolicLink() && !stat7.isFile()) {
301855
301937
  return false;
301856
301938
  }
301857
301939
  return checkPathExt(path98, options);
301858
301940
  }
301859
301941
  function isexe(path98, options, cb) {
301860
- fs89.stat(path98, function(er2, stat6) {
301861
- cb(er2, er2 ? false : checkStat(stat6, path98, options));
301942
+ fs89.stat(path98, function(er2, stat7) {
301943
+ cb(er2, er2 ? false : checkStat(stat7, path98, options));
301862
301944
  });
301863
301945
  }
301864
301946
  function sync2(path98, options) {
@@ -301874,20 +301956,20 @@ var require_mode = __commonJS({
301874
301956
  isexe.sync = sync2;
301875
301957
  var fs89 = __require("fs");
301876
301958
  function isexe(path98, options, cb) {
301877
- fs89.stat(path98, function(er2, stat6) {
301878
- cb(er2, er2 ? false : checkStat(stat6, options));
301959
+ fs89.stat(path98, function(er2, stat7) {
301960
+ cb(er2, er2 ? false : checkStat(stat7, options));
301879
301961
  });
301880
301962
  }
301881
301963
  function sync2(path98, options) {
301882
301964
  return checkStat(fs89.statSync(path98), options);
301883
301965
  }
301884
- function checkStat(stat6, options) {
301885
- return stat6.isFile() && checkMode(stat6, options);
301966
+ function checkStat(stat7, options) {
301967
+ return stat7.isFile() && checkMode(stat7, options);
301886
301968
  }
301887
- function checkMode(stat6, options) {
301888
- var mod = stat6.mode;
301889
- var uid = stat6.uid;
301890
- var gid = stat6.gid;
301969
+ function checkMode(stat7, options) {
301970
+ var mod = stat7.mode;
301971
+ var uid = stat7.uid;
301972
+ var gid = stat7.gid;
301891
301973
  var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
301892
301974
  var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
301893
301975
  var u2 = parseInt("100", 8);
@@ -316002,7 +316084,7 @@ var require_snapshot_utils = __commonJS({
316002
316084
  var require_snapshot_recorder = __commonJS({
316003
316085
  "node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
316004
316086
  "use strict";
316005
- var { writeFile: writeFile9, readFile: readFile11, mkdir: mkdir11 } = __require("node:fs/promises");
316087
+ var { writeFile: writeFile9, readFile: readFile12, mkdir: mkdir11 } = __require("node:fs/promises");
316006
316088
  var { dirname: dirname23, resolve: resolve23 } = __require("node:path");
316007
316089
  var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = __require("node:timers");
316008
316090
  var { InvalidArgumentError, UndiciError } = require_errors7();
@@ -316204,7 +316286,7 @@ var require_snapshot_recorder = __commonJS({
316204
316286
  throw new InvalidArgumentError("Snapshot path is required");
316205
316287
  }
316206
316288
  try {
316207
- const data = await readFile11(resolve23(path98), "utf8");
316289
+ const data = await readFile12(resolve23(path98), "utf8");
316208
316290
  const parsed = JSON.parse(data);
316209
316291
  if (Array.isArray(parsed)) {
316210
316292
  this.#snapshots.clear();
@@ -327566,9 +327648,9 @@ var require_picocolors = __commonJS({
327566
327648
  var argv = p3.argv || [];
327567
327649
  var env = p3.env || {};
327568
327650
  var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p3.platform === "win32" || (p3.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
327569
- var formatter = (open4, close, replace = open4) => (input) => {
327570
- let string4 = "" + input, index = string4.indexOf(close, open4.length);
327571
- return ~index ? open4 + replaceClose(string4, close, replace, index) + close : open4 + string4 + close;
327651
+ var formatter = (open5, close, replace = open5) => (input) => {
327652
+ let string4 = "" + input, index = string4.indexOf(close, open5.length);
327653
+ return ~index ? open5 + replaceClose(string4, close, replace, index) + close : open5 + string4 + close;
327572
327654
  };
327573
327655
  var replaceClose = (string4, close, replace, index) => {
327574
327656
  let result2 = "", cursor = 0;
@@ -332595,7 +332677,7 @@ function getVersion() {
332595
332677
  }
332596
332678
  versionPromise = (async () => {
332597
332679
  const pkgJson = await getPackageJson(__dirname4);
332598
- return "0.44.0-nightly.20260521.g57c42a5c4";
332680
+ return "0.44.0";
332599
332681
  })();
332600
332682
  return versionPromise;
332601
332683
  }
@@ -333735,8 +333817,13 @@ async function handleFallback(config3, failedModel, authType, error2) {
333735
333817
  return void 0;
333736
333818
  return { service: availability, policy: failedPolicy };
333737
333819
  };
333820
+ const activeModel = config3.getActiveModel();
333738
333821
  let fallbackModel;
333739
333822
  if (!candidates.length) {
333823
+ if (failedModel !== activeModel && availability.snapshot(activeModel).available) {
333824
+ applyAvailabilityTransition(getAvailabilityContext, failureKind);
333825
+ return processIntent(config3, "retry_always", activeModel, failedModel);
333826
+ }
333740
333827
  fallbackModel = failedModel;
333741
333828
  } else {
333742
333829
  const selection = availability.selectFirstAvailable(candidates.map((policy) => policy.model));
@@ -333748,9 +333835,10 @@ async function handleFallback(config3, failedModel, authType, error2) {
333748
333835
  }
333749
333836
  fallbackModel = selectedFallbackModel;
333750
333837
  const action = resolvePolicyAction(failureKind, selectedPolicy);
333751
- if (action === "silent") {
333838
+ if (action === "silent" || fallbackModel === activeModel && failedModel !== activeModel) {
333752
333839
  applyAvailabilityTransition(getAvailabilityContext, failureKind);
333753
- return processIntent(config3, "retry_always", fallbackModel);
333840
+ const overrideFailedModel = failedModel !== activeModel ? failedModel : void 0;
333841
+ return processIntent(config3, "retry_always", fallbackModel, overrideFailedModel);
333754
333842
  }
333755
333843
  const recommendation = {
333756
333844
  ...selection,
@@ -333771,7 +333859,7 @@ async function handleFallback(config3, failedModel, authType, error2) {
333771
333859
  if (intent === "retry_always" || intent === "retry_once") {
333772
333860
  applyAvailabilityTransition(getAvailabilityContext, failureKind);
333773
333861
  }
333774
- return await processIntent(config3, intent, fallbackModel);
333862
+ return await processIntent(config3, intent, fallbackModel, failedModel !== activeModel ? failedModel : void 0);
333775
333863
  } catch (handlerError) {
333776
333864
  debugLogger.error("Fallback handler failed:", handlerError);
333777
333865
  return null;
@@ -333788,10 +333876,10 @@ async function handleUpgrade() {
333788
333876
  debugLogger.warn("Failed to open browser automatically:", getErrorMessage(error2));
333789
333877
  }
333790
333878
  }
333791
- async function processIntent(config3, intent, fallbackModel) {
333879
+ async function processIntent(config3, intent, fallbackModel, failedModel) {
333792
333880
  switch (intent) {
333793
333881
  case "retry_always":
333794
- config3.activateFallbackMode(fallbackModel);
333882
+ config3.activateFallbackMode(fallbackModel, failedModel);
333795
333883
  return true;
333796
333884
  case "retry_once":
333797
333885
  return true;
@@ -339630,8 +339718,8 @@ var init_fileDiscoveryService = __esm({
339630
339718
  const paths = [];
339631
339719
  if (this.gitIgnoreFilter && this.defaultFilterFileOptions.respectGitIgnore) {
339632
339720
  const gitIgnorePath = path50.join(this.projectRoot, ".gitignore");
339633
- const stat6 = fs46.statSync(gitIgnorePath, { throwIfNoEntry: false });
339634
- if (stat6?.isFile()) {
339721
+ const stat7 = fs46.statSync(gitIgnorePath, { throwIfNoEntry: false });
339722
+ if (stat7?.isFile()) {
339635
339723
  paths.push(gitIgnorePath);
339636
339724
  }
339637
339725
  }
@@ -341750,10 +341838,10 @@ var init_esm7 = __esm({
341750
341838
  }
341751
341839
  return filtered.join("/");
341752
341840
  }).join("|");
341753
- const [open4, close] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
341754
- re3 = "^" + open4 + re3 + close + "$";
341841
+ const [open5, close] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
341842
+ re3 = "^" + open5 + re3 + close + "$";
341755
341843
  if (this.partial) {
341756
- re3 = "^(?:\\/|" + open4 + re3.slice(1, -1) + close + ")$";
341844
+ re3 = "^(?:\\/|" + open5 + re3.slice(1, -1) + close + ")$";
341757
341845
  }
341758
341846
  if (this.negate)
341759
341847
  re3 = "^(?!" + re3 + ").+$";
@@ -347642,9 +347730,13 @@ async function resolveRipgrepPath() {
347642
347730
  const arch3 = os27.arch();
347643
347731
  const binName = `rg-${platform10}-${arch3}${platform10 === "win32" ? ".exe" : ""}`;
347644
347732
  const candidatePaths = [
347645
- // 1. SEA runtime layout: everything is flattened into the root dir
347733
+ // 1. SEA runtime layout (Flattened): everything is in the root dir
347734
+ path54.resolve(__dirname6, binName),
347735
+ // 2. SEA runtime layout (Subdirectory): bundled into a vendor/ripgrep dir
347646
347736
  path54.resolve(__dirname6, "vendor/ripgrep", binName),
347647
- // 2. Dev/Dist layout: packages/core/dist/tools/ripGrep.js -> packages/core/vendor/ripgrep
347737
+ // 3. Dev/Dist layout (Actual): dist/src/tools/ripGrep.js -> packages/core/vendor/ripgrep
347738
+ path54.resolve(__dirname6, "../../../vendor/ripgrep", binName),
347739
+ // 4. Dev/Dist layout (Assumed/Bundled): dist/tools/ripGrep.js -> packages/core/vendor/ripgrep
347648
347740
  path54.resolve(__dirname6, "../../vendor/ripgrep", binName)
347649
347741
  ];
347650
347742
  for (const candidate of candidatePaths) {
@@ -352934,6 +353026,17 @@ function injectUtf8CodepageForPty(command, shell, isWindows2, usingPty) {
352934
353026
  }
352935
353027
  return command;
352936
353028
  }
353029
+ function ensureHupIgnored(command, shell) {
353030
+ if (shell !== "bash") {
353031
+ return command;
353032
+ }
353033
+ const trimmed2 = command.trimStart();
353034
+ const prefix = `${BASH_HUP_GUARD} `;
353035
+ if (trimmed2.startsWith(prefix) || trimmed2 === BASH_HUP_GUARD) {
353036
+ return command;
353037
+ }
353038
+ return `${BASH_HUP_GUARD} ${command}`;
353039
+ }
352937
353040
  var import_headless2, Terminal, MAX_CHILD_PROCESS_BUFFER_SIZE, GEMINI_CLI_IDENTIFICATION_ENV_VAR, GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE, SCROLLBACK_LIMIT, BASH_SHOPT_OPTIONS, BASH_SHOPT_GUARD, findLastContentLine, getFullBufferText, writeBufferToLogStream, ShellExecutionService;
352938
353041
  var init_shellExecutionService = __esm({
352939
353042
  "packages/core/dist/src/services/shellExecutionService.js"() {
@@ -353123,8 +353226,9 @@ ${truncated}`;
353123
353226
  executable = "cmd.exe";
353124
353227
  }
353125
353228
  const resolvedExecutable = resolveExecutable(executable) ?? executable;
353126
- const guardedCommand = ensurePromptvarsDisabled(commandToExecute, shell);
353127
- const finalCommand = injectUtf8CodepageForPty(guardedCommand, shell, isWindows2, usingPty);
353229
+ const promptGuarded = ensurePromptvarsDisabled(commandToExecute, shell);
353230
+ const hupGuarded = !isWindows2 ? ensureHupIgnored(promptGuarded, shell) : promptGuarded;
353231
+ const finalCommand = injectUtf8CodepageForPty(hupGuarded, shell, isWindows2, usingPty);
353128
353232
  const spawnArgs = [...argsPrefix, finalCommand];
353129
353233
  const gitConfigKeys = [];
353130
353234
  if (!isInteractive) {
@@ -353481,13 +353585,23 @@ ${truncated}`;
353481
353585
  const prepared = await this.prepareExecution(commandToExecute, cwd, shellExecutionConfig, true, true);
353482
353586
  cmdCleanup = prepared.cleanup;
353483
353587
  const { program: finalExecutable, args: finalArgs, env: finalEnv, cwd: finalCwd } = prepared;
353588
+ const isWindowsPlatform = os29.platform() === "win32";
353484
353589
  const ptyProcess = ptyInfo.module.spawn(finalExecutable, finalArgs, {
353485
353590
  cwd: finalCwd,
353486
353591
  name: "xterm-256color",
353487
353592
  cols,
353488
353593
  rows,
353489
353594
  env: finalEnv,
353490
- handleFlowControl: true
353595
+ // handleFlowControl intercepts XON/XOFF (Ctrl+S/Q) and prevents them
353596
+ // from reaching the child. On Windows, the flag can interfere with
353597
+ // ConPTY's internal input routing and cause interactive TUI tools to
353598
+ // miss key events, so we disable it there.
353599
+ handleFlowControl: !isWindowsPlatform,
353600
+ // On Windows, explicitly request ConPTY (introduced in Windows 10 1809).
353601
+ // Without this, @lydell/node-pty may silently fall back to WinPTY, which
353602
+ // has known incompatibilities with interactive Node.js TUI applications
353603
+ // that rely on VT-sequence-based arrow-key navigation.
353604
+ ...isWindowsPlatform ? { useConpty: true } : {}
353491
353605
  });
353492
353606
  spawnedPty = ptyProcess;
353493
353607
  const ptyPid = Number(ptyProcess.pid);
@@ -353523,6 +353637,9 @@ ${truncated}`;
353523
353637
  });
353524
353638
  },
353525
353639
  isActive: () => {
353640
+ if (_ShellExecutionService.activePtys.has(ptyPid)) {
353641
+ return true;
353642
+ }
353526
353643
  try {
353527
353644
  return process.kill(ptyPid, 0);
353528
353645
  } catch {
@@ -354146,15 +354263,16 @@ var init_shell = __esm({
354146
354263
  this.context = context2;
354147
354264
  }
354148
354265
  /**
354149
- * Wraps a command in a subshell `()` to capture background process IDs (PIDs) using pgrep.
354150
- * Uses newlines to prevent breaking heredocs or trailing comments.
354266
+ * Wraps a command in a subshell to capture background process IDs (PIDs)
354267
+ * using an EXIT trap. Uses newlines to prevent breaking heredocs or trailing
354268
+ * comments.
354151
354269
  *
354152
354270
  * @param command The raw command string to execute.
354153
354271
  * @param tempFilePath Path to the temporary file where PIDs will be written.
354154
354272
  * @param isWindows Whether the current platform is Windows (if true, the command is returned as-is).
354155
354273
  * @returns The wrapped command string.
354156
354274
  */
354157
- wrapCommandForPgrep(command, tempFilePath, isWindows2) {
354275
+ wrapCommandForBackgroundPIDs(command, tempFilePath, isWindows2) {
354158
354276
  if (isWindows2) {
354159
354277
  return command;
354160
354278
  }
@@ -354166,10 +354284,13 @@ var init_shell = __esm({
354166
354284
  trimmed2 += " ";
354167
354285
  }
354168
354286
  const escapedTempFilePath = escapeShellArg(tempFilePath, "bash");
354169
- return `(
354287
+ return `_bgpids_file=${escapedTempFilePath}
354288
+ (
354289
+ trap 'jobs -p > "$_bgpids_file"' EXIT
354170
354290
  ${trimmed2}
354171
354291
  )
354172
- __code=$?; pgrep -g 0 >${escapedTempFilePath} 2>&1; exit $__code;`;
354292
+ __code=$?
354293
+ exit $__code`;
354173
354294
  }
354174
354295
  getContextualDetails() {
354175
354296
  let details = "";
@@ -354415,8 +354536,8 @@ __code=$?; pgrep -g 0 >${escapedTempFilePath} 2>&1; exit $__code;`;
354415
354536
  const onAbort = () => combinedController.abort();
354416
354537
  try {
354417
354538
  tempDir = fs53.mkdtempSync(path60.join(os31.tmpdir(), "gemini-shell-"));
354418
- tempFilePath = path60.join(tempDir, "pgrep.tmp");
354419
- const commandToExecute = this.wrapCommandForPgrep(strippedCommand, tempFilePath, isWindows2);
354539
+ tempFilePath = path60.join(tempDir, "bgpids.tmp");
354540
+ const commandToExecute = this.wrapCommandForBackgroundPIDs(strippedCommand, tempFilePath, isWindows2);
354420
354541
  const cwd = this.params.dir_path ? path60.resolve(this.context.config.getTargetDir(), this.params.dir_path) : this.context.config.getTargetDir();
354421
354542
  const validationError = this.context.config.validatePathAccess(cwd);
354422
354543
  if (validationError) {
@@ -354528,7 +354649,7 @@ __code=$?; pgrep -g 0 >${escapedTempFilePath} 2>&1; exit $__code;`;
354528
354649
  if (shouldUpdate && !this.params.is_background) {
354529
354650
  flushOutput();
354530
354651
  }
354531
- }, combinedController.signal, this.context.config.getEnableInteractiveShell(), {
354652
+ }, combinedController.signal, this.context.config.isInteractiveShellEnabled(), {
354532
354653
  ...shellExecutionConfig,
354533
354654
  sessionId: this.context.config?.getSessionId?.() ?? "default",
354534
354655
  pager: "cat",
@@ -354590,14 +354711,14 @@ ${cumulativeOutput}`,
354590
354711
  tempFileExists = false;
354591
354712
  }
354592
354713
  if (tempFileExists) {
354593
- const pgrepContent = await fsPromises9.readFile(tempFilePath, "utf8");
354594
- const pgrepLines = pgrepContent.split("\n").map((line) => line.trim()).filter(Boolean);
354595
- for (const line of pgrepLines) {
354714
+ const backgroundPIDContent = await fsPromises9.readFile(tempFilePath, "utf8");
354715
+ const backgroundPIDLines = backgroundPIDContent.split("\n").map((line) => line.trim()).filter(Boolean);
354716
+ for (const line of backgroundPIDLines) {
354596
354717
  if (!/^\d+$/.test(line)) {
354597
354718
  if (line.includes("sysmond service not found") || line.includes("Cannot get process list") || line.includes("sysmon request failed")) {
354598
354719
  continue;
354599
354720
  }
354600
- debugLogger.error(`pgrep: ${line}`);
354721
+ debugLogger.error(`background pid output: ${line}`);
354601
354722
  }
354602
354723
  const pid2 = Number(line);
354603
354724
  if (pid2 !== result2.pid) {
@@ -354606,7 +354727,7 @@ ${cumulativeOutput}`,
354606
354727
  }
354607
354728
  } else {
354608
354729
  if (!signal.aborted && !result2.backgrounded) {
354609
- debugLogger.error("missing pgrep output");
354730
+ debugLogger.error("missing background pid output");
354610
354731
  }
354611
354732
  }
354612
354733
  }
@@ -354837,7 +354958,7 @@ ${result2.output}`;
354837
354958
  constructor(context2, messageBus) {
354838
354959
  void initializeShellParsers().catch(() => {
354839
354960
  });
354840
- const definition = getShellDefinition(context2.config.getEnableInteractiveShell(), context2.config.getEnableShellOutputEfficiency(), context2.config.getSandboxEnabled());
354961
+ const definition = getShellDefinition(context2.config.isInteractiveShellEnabled(), context2.config.getEnableShellOutputEfficiency(), context2.config.getSandboxEnabled());
354841
354962
  super(
354842
354963
  _ShellTool.Name,
354843
354964
  "Shell",
@@ -354865,7 +354986,7 @@ ${result2.output}`;
354865
354986
  return new ShellToolInvocation(this.context, params, messageBus, _toolName, _toolDisplayName);
354866
354987
  }
354867
354988
  getSchema(modelId) {
354868
- const definition = getShellDefinition(this.context.config.getEnableInteractiveShell(), this.context.config.getEnableShellOutputEfficiency(), this.context.config.getSandboxEnabled());
354989
+ const definition = getShellDefinition(this.context.config.isInteractiveShellEnabled(), this.context.config.getEnableShellOutputEfficiency(), this.context.config.getSandboxEnabled());
354869
354990
  return resolveToolDeclaration(definition, modelId);
354870
354991
  }
354871
354992
  };
@@ -361306,39 +361427,24 @@ var init_agentChatHistory = __esm({
361306
361427
  "use strict";
361307
361428
  AgentChatHistory = class {
361308
361429
  history = [];
361309
- listeners = /* @__PURE__ */ new Set();
361310
361430
  constructor(initialTurns = []) {
361311
361431
  this.history = [...initialTurns];
361312
361432
  }
361313
- subscribe(listener) {
361314
- this.listeners.add(listener);
361315
- listener({ type: "SYNC_FULL", payload: this.history });
361316
- return () => this.listeners.delete(listener);
361317
- }
361318
- notify(type2, payload) {
361319
- const event = { type: type2, payload };
361320
- for (const listener of this.listeners) {
361321
- listener(event);
361322
- }
361323
- }
361324
361433
  /**
361325
361434
  * Adds a new turn to the history.
361326
361435
  * Every turn must have a durable ID, usually provided by the ChatRecordingService.
361327
361436
  */
361328
361437
  push(turn) {
361329
361438
  this.history.push(turn);
361330
- this.notify("PUSH", [turn]);
361331
361439
  }
361332
361440
  /**
361333
361441
  * Overwrites the entire history with a new list of turns.
361334
361442
  */
361335
- set(turns, options = {}) {
361443
+ set(turns) {
361336
361444
  this.history = [...turns];
361337
- this.notify(options.silent ? "SILENT_SYNC" : "SYNC_FULL", this.history);
361338
361445
  }
361339
361446
  clear() {
361340
361447
  this.history = [];
361341
- this.notify("CLEAR", []);
361342
361448
  }
361343
361449
  get() {
361344
361450
  return this.history;
@@ -361439,12 +361545,12 @@ function pairToolsAndEnforceSignatures(history, sentinels) {
361439
361545
  const nextTurn = work[i4 + 1];
361440
361546
  const missing = [];
361441
361547
  for (const call of callParts) {
361442
- const id = call.functionCall.id || "undefined";
361548
+ const id = call.functionCall.id;
361443
361549
  const name3 = call.functionCall.name || "unknown";
361444
361550
  const hasResponse = nextTurn?.content.role === "user" && nextTurn.content.parts?.some((p3) => p3.functionResponse?.id === id && p3.functionResponse?.name === name3);
361445
361551
  if (!hasResponse) {
361446
361552
  debugLogger.log(`[HistoryHardener] Call id='${id}' (name='${name3}') has no matching response in next turn.`);
361447
- missing.push({ id, name: name3 });
361553
+ missing.push({ id: id || "", name: name3 });
361448
361554
  }
361449
361555
  }
361450
361556
  if (missing.length > 0) {
@@ -361464,7 +361570,7 @@ function pairToolsAndEnforceSignatures(history, sentinels) {
361464
361570
  targetUserTurn.content.parts.push({
361465
361571
  functionResponse: {
361466
361572
  name: m3.name,
361467
- id: m3.id,
361573
+ id: m3.id || void 0,
361468
361574
  response: {
361469
361575
  error: sentinels.lostToolResponse
361470
361576
  }
@@ -361589,10 +361695,13 @@ function enforceRoleConstraints(history, sentinels) {
361589
361695
  function scrubHistory(history) {
361590
361696
  return history.map((turn) => ({
361591
361697
  id: turn.id,
361592
- content: {
361593
- role: turn.content.role,
361594
- parts: (turn.content.parts || []).map((p3) => scrubPart(p3))
361595
- }
361698
+ content: scrubContents([turn.content])[0]
361699
+ }));
361700
+ }
361701
+ function scrubContents(contents) {
361702
+ return contents.map((content) => ({
361703
+ role: content.role,
361704
+ parts: (content.parts || []).map((p3) => scrubPart(p3))
361596
361705
  }));
361597
361706
  }
361598
361707
  function isThoughtPart(part) {
@@ -361668,6 +361777,59 @@ var init_geminiRequest = __esm({
361668
361777
  }
361669
361778
  });
361670
361779
 
361780
+ // packages/core/dist/src/utils/sessionUtils.js
361781
+ function ensureStableToolIds(history) {
361782
+ for (let i4 = 0; i4 < history.length; i4++) {
361783
+ const turn = history[i4];
361784
+ const parts2 = turn.content.parts || [];
361785
+ for (let partIdx = 0; partIdx < parts2.length; partIdx++) {
361786
+ const part = parts2[partIdx];
361787
+ if (part.functionCall && !part.functionCall.id) {
361788
+ const name3 = part.functionCall.name;
361789
+ const nextTurn = history[i4 + 1];
361790
+ let pairedId;
361791
+ if (nextTurn?.content.role === "user") {
361792
+ const matchingResp = nextTurn.content.parts?.find((p3) => p3.functionResponse && p3.functionResponse.name === name3 && !p3.functionResponse.id);
361793
+ if (matchingResp) {
361794
+ pairedId = `synth_${name3}_${deriveStableId([turn.id, i4.toString(), partIdx.toString()])}`;
361795
+ part.functionCall.id = pairedId;
361796
+ matchingResp.functionResponse.id = pairedId;
361797
+ }
361798
+ }
361799
+ if (!part.functionCall.id) {
361800
+ part.functionCall.id = `synth_${name3}_${deriveStableId([turn.id, i4.toString(), partIdx.toString()])}`;
361801
+ }
361802
+ }
361803
+ if (part.functionResponse && !part.functionResponse.id) {
361804
+ const name3 = part.functionResponse.name;
361805
+ const prevTurn = history[i4 - 1];
361806
+ if (prevTurn?.content.role === "model") {
361807
+ const matchingCall = prevTurn.content.parts?.find((p3) => p3.functionCall && p3.functionCall.name === name3 && !p3.functionCall.id);
361808
+ if (matchingCall) {
361809
+ const pairedId = `synth_${name3}_${deriveStableId([prevTurn.id, (i4 - 1).toString(), partIdx.toString()])}`;
361810
+ matchingCall.functionCall.id = pairedId;
361811
+ part.functionResponse.id = pairedId;
361812
+ }
361813
+ }
361814
+ if (!part.functionResponse.id) {
361815
+ part.functionResponse.id = `synth_orph_${name3}_${deriveStableId([turn.id, i4.toString(), partIdx.toString()])}`;
361816
+ }
361817
+ }
361818
+ }
361819
+ }
361820
+ }
361821
+ var init_sessionUtils = __esm({
361822
+ "packages/core/dist/src/utils/sessionUtils.js"() {
361823
+ "use strict";
361824
+ init_node();
361825
+ init_chatRecordingService();
361826
+ init_geminiRequest();
361827
+ init_geminiRequest();
361828
+ init_agentChatHistory();
361829
+ init_cryptoUtils();
361830
+ }
361831
+ });
361832
+
361671
361833
  // packages/core/dist/src/core/geminiChat.js
361672
361834
  import { randomUUID as randomUUID7 } from "node:crypto";
361673
361835
  function isIndexedPart(part) {
@@ -361792,12 +361954,11 @@ var init_geminiChat = __esm({
361792
361954
  init_handler();
361793
361955
  init_messageInspectors();
361794
361956
  init_historyHardening();
361795
- init_geminiRequest();
361957
+ init_sessionUtils();
361796
361958
  init_generateContentResponseUtilities();
361797
361959
  init_tokenCalculation();
361798
361960
  init_policyHelpers();
361799
361961
  init_events();
361800
- init_debugLogger();
361801
361962
  (function(StreamEventType2) {
361802
361963
  StreamEventType2["CHUNK"] = "chunk";
361803
361964
  StreamEventType2["RETRY"] = "retry";
@@ -361873,6 +362034,7 @@ var init_geminiChat = __esm({
361873
362034
  initialHistory = [];
361874
362035
  }
361875
362036
  this.agentHistory = new AgentChatHistory(initialHistory);
362037
+ ensureStableToolIds(this.agentHistory.get());
361876
362038
  this.chatRecordingService = new ChatRecordingService(context2);
361877
362039
  this.lastPromptTokenCount = estimateTokenCountSync(this.agentHistory.flatMap((c4) => c4.content.parts || []));
361878
362040
  }
@@ -361915,7 +362077,7 @@ var init_geminiChat = __esm({
361915
362077
  * }
361916
362078
  * ```
361917
362079
  */
361918
- async sendMessageStream(modelConfigKey, message, prompt_id, signal, role, displayContent) {
362080
+ async sendMessageStream(modelConfigKey, message, prompt_id, signal, role, displayContent, apiHistoryOverride) {
361919
362081
  await this.sendPromise;
361920
362082
  let streamDoneResolver;
361921
362083
  const streamDonePromise = new Promise((resolve23) => {
@@ -361924,6 +362086,7 @@ var init_geminiChat = __esm({
361924
362086
  this.sendPromise = streamDonePromise;
361925
362087
  let userContent = createUserContent(message);
361926
362088
  const { model } = this.context.config.modelConfigService.getResolvedConfig(modelConfigKey);
362089
+ const isContextManagementEnabled = this.context.config.isContextManagementEnabled();
361927
362090
  if (!isFunctionResponse(userContent)) {
361928
362091
  const userMessageParts = userContent.parts || [];
361929
362092
  const userMessageContent = partListUnionToString(userMessageParts);
@@ -361935,46 +362098,68 @@ var init_geminiChat = __esm({
361935
362098
  finalDisplayContent = displayParts;
361936
362099
  }
361937
362100
  }
361938
- const id = this.chatRecordingService.recordMessage({
361939
- model,
361940
- type: "user",
361941
- content: userMessageParts,
361942
- displayContent: finalDisplayContent
361943
- });
361944
- this.agentHistory.push({ id, content: userContent });
362101
+ if (!isContextManagementEnabled) {
362102
+ const id = this.chatRecordingService.recordMessage({
362103
+ model,
362104
+ type: "user",
362105
+ content: userMessageParts,
362106
+ displayContent: finalDisplayContent
362107
+ });
362108
+ this.agentHistory.push({ id, content: userContent });
362109
+ } else {
362110
+ const history = this.agentHistory.get();
362111
+ const lastTurn = history[history.length - 1];
362112
+ if (!lastTurn || partListUnionToString(lastTurn.content.parts || []) !== userMessageContent) {
362113
+ const id = this.chatRecordingService.recordMessage({
362114
+ model,
362115
+ type: "user",
362116
+ content: userMessageParts,
362117
+ displayContent: finalDisplayContent
362118
+ });
362119
+ this.agentHistory.push({ id, content: userContent });
362120
+ }
362121
+ }
361945
362122
  } else {
361946
362123
  const id = this.chatRecordingService.recordSyntheticMessage("user", userContent.parts || []);
361947
- const binaryParts = this.extractBinaryInjections(userContent.parts);
361948
- if (binaryParts) {
361949
- this.agentHistory.push({ id, content: userContent });
361950
- const modelId = this.chatRecordingService.recordSyntheticMessage("gemini", [
361951
- {
361952
- text: "Binary content received. Proceeding with analysis.",
361953
- thought: true,
361954
- thoughtSignature: SYNTHETIC_THOUGHT_SIGNATURE2
361955
- }
361956
- ]);
361957
- this.agentHistory.push({
361958
- id: modelId,
361959
- content: {
361960
- role: "model",
361961
- parts: [
361962
- {
361963
- text: "Binary content received. Proceeding with analysis.",
361964
- thought: true,
361965
- thoughtSignature: SYNTHETIC_THOUGHT_SIGNATURE2
361966
- }
361967
- ]
361968
- }
361969
- });
361970
- const binaryId = this.chatRecordingService.recordSyntheticMessage("info", binaryParts);
361971
- userContent = {
361972
- role: "user",
361973
- parts: binaryParts
361974
- };
361975
- this.agentHistory.push({ id: binaryId, content: userContent });
362124
+ if (!isContextManagementEnabled) {
362125
+ const binaryParts = this.extractBinaryInjections(userContent.parts);
362126
+ if (binaryParts) {
362127
+ this.agentHistory.push({ id, content: userContent });
362128
+ const modelId = this.chatRecordingService.recordSyntheticMessage("gemini", [
362129
+ {
362130
+ text: "Binary content received. Proceeding with analysis.",
362131
+ thought: true,
362132
+ thoughtSignature: SYNTHETIC_THOUGHT_SIGNATURE2
362133
+ }
362134
+ ]);
362135
+ this.agentHistory.push({
362136
+ id: modelId,
362137
+ content: {
362138
+ role: "model",
362139
+ parts: [
362140
+ {
362141
+ text: "Binary content received. Proceeding with analysis.",
362142
+ thought: true,
362143
+ thoughtSignature: SYNTHETIC_THOUGHT_SIGNATURE2
362144
+ }
362145
+ ]
362146
+ }
362147
+ });
362148
+ const binaryId = this.chatRecordingService.recordSyntheticMessage("info", binaryParts);
362149
+ userContent = {
362150
+ role: "user",
362151
+ parts: binaryParts
362152
+ };
362153
+ this.agentHistory.push({ id: binaryId, content: userContent });
362154
+ } else {
362155
+ this.agentHistory.push({ id, content: userContent });
362156
+ }
361976
362157
  } else {
361977
- this.agentHistory.push({ id, content: userContent });
362158
+ const history = this.agentHistory.get();
362159
+ const lastTurn = history[history.length - 1];
362160
+ if (!lastTurn || partListUnionToString(lastTurn.content.parts || []) !== partListUnionToString(userContent.parts || [])) {
362161
+ this.agentHistory.push({ id, content: userContent });
362162
+ }
361978
362163
  }
361979
362164
  }
361980
362165
  const requestHistory = this.getHistoryTurns(true);
@@ -361989,7 +362174,7 @@ var init_geminiChat = __esm({
361989
362174
  }
361990
362175
  const currentConfigKey = attempt > 0 ? { ...modelConfigKey, isRetry: true } : modelConfigKey;
361991
362176
  isConnectionPhase = true;
361992
- const stream2 = await this.makeApiCallAndProcessStream(currentConfigKey, requestHistory, prompt_id, signal, role);
362177
+ const stream2 = await this.makeApiCallAndProcessStream(currentConfigKey, requestHistory, prompt_id, signal, role, apiHistoryOverride);
361993
362178
  isConnectionPhase = false;
361994
362179
  for await (const chunk of stream2) {
361995
362180
  yield { type: StreamEventType.CHUNK, value: chunk };
@@ -362072,11 +362257,11 @@ var init_geminiChat = __esm({
362072
362257
  }
362073
362258
  return binaryParts.length > 0 ? binaryParts : void 0;
362074
362259
  }
362075
- async makeApiCallAndProcessStream(modelConfigKey, requestHistory, prompt_id, abortSignal, role) {
362260
+ async makeApiCallAndProcessStream(modelConfigKey, requestHistory, prompt_id, abortSignal, role, apiHistoryOverride) {
362076
362261
  const scrubbedHistory = this.context.config.isContextManagementEnabled() ? scrubHistory([...requestHistory]) : [...requestHistory];
362077
362262
  const scrubbedContents = scrubbedHistory.map((h3) => h3.content);
362078
- const contentsForPreviewModel = this.ensureActiveLoopHasThoughtSignatures(scrubbedContents);
362079
- const requestContents = scrubbedContents;
362263
+ const requestContents = apiHistoryOverride ? scrubContents(apiHistoryOverride) : scrubbedContents;
362264
+ const contentsForPreviewModel = this.ensureActiveLoopHasThoughtSignatures(requestContents);
362080
362265
  const { model: availabilityFinalModel, config: newAvailabilityConfig, maxAttempts: availabilityMaxAttempts } = applyModelSelection(this.context.config, modelConfigKey);
362081
362266
  let lastModelToUse = availabilityFinalModel;
362082
362267
  let currentGenerateContentConfig = newAvailabilityConfig;
@@ -362246,8 +362431,9 @@ var init_geminiChat = __esm({
362246
362431
  const id = this.chatRecordingService.recordSyntheticMessage(content.role === "user" ? "user" : "gemini", content.parts || []);
362247
362432
  this.agentHistory.push({ id, content });
362248
362433
  }
362434
+ ensureStableToolIds(this.agentHistory.get());
362249
362435
  }
362250
- setHistory(history, options = {}) {
362436
+ setHistory(history) {
362251
362437
  const wrappedHistory = history.map((item) => {
362252
362438
  if ("id" in item && "content" in item) {
362253
362439
  return item;
@@ -362255,7 +362441,8 @@ var init_geminiChat = __esm({
362255
362441
  const id = this.chatRecordingService.recordSyntheticMessage(item.role === "user" ? "user" : "gemini", item.parts || []);
362256
362442
  return { id, content: item };
362257
362443
  });
362258
- this.agentHistory.set(wrappedHistory, options);
362444
+ ensureStableToolIds(wrappedHistory);
362445
+ this.agentHistory.set(wrappedHistory);
362259
362446
  this.lastPromptTokenCount = estimateTokenCountSync(this.agentHistory.flatMap((c4) => c4.content.parts || []));
362260
362447
  this.chatRecordingService.updateMessagesFromHistory(this.agentHistory.get());
362261
362448
  }
@@ -362368,7 +362555,6 @@ This error was probably caused by cyclic schema references in one of the followi
362368
362555
  if (!id2) {
362369
362556
  id2 = `synth_${this.context.promptId}_${Date.now()}_${this.callCounter++}`;
362370
362557
  callIndexToId.set(globalIndex, id2);
362371
- debugLogger.log(`[GeminiChat] Assigned synthetic ID: ${id2} to tool at index ${globalIndex}: ${fnCall.name}`);
362372
362558
  }
362373
362559
  fnCall.id = id2;
362374
362560
  }
@@ -362439,7 +362625,6 @@ This error was probably caused by cyclic schema references in one of the followi
362439
362625
  const finalFunctionCalls = this.context.config.isContextManagementEnabled() ? Array.from(finalFunctionCallsMap.values()) : legacyFunctionCalls;
362440
362626
  let currentCallSourceIndex = -1;
362441
362627
  if (this.context.config.isContextManagementEnabled()) {
362442
- debugLogger.log(`[GeminiChat] Starting consolidation for ${modelResponseParts.length} raw parts and ${finalFunctionCalls.length} assembled function calls.`);
362443
362628
  for (const part of modelResponseParts) {
362444
362629
  if (part.functionCall) {
362445
362630
  const partIndex = isIndexedPart(part) ? part.callIndex : void 0;
@@ -362707,9 +362892,10 @@ var init_turn = __esm({
362707
362892
  this.prompt_id = prompt_id;
362708
362893
  }
362709
362894
  // The run method yields simpler events suitable for server logic
362710
- async *run(modelConfigKey, req, signal, displayContent, role = LlmRole.MAIN) {
362895
+ async *run(modelConfigKey, req, signal, options = {}) {
362896
+ const { displayContent, role = LlmRole.MAIN, apiHistoryOverride } = options;
362711
362897
  try {
362712
- const responseStream = await this.chat.sendMessageStream(modelConfigKey, req, this.prompt_id, signal, role, displayContent);
362898
+ const responseStream = await this.chat.sendMessageStream(modelConfigKey, req, this.prompt_id, signal, role, displayContent, apiHistoryOverride);
362713
362899
  for await (const streamEvent of responseStream) {
362714
362900
  if (signal?.aborted) {
362715
362901
  yield { type: GeminiEventType.UserCancelled };
@@ -364719,12 +364905,23 @@ ${environmentMemory}
364719
364905
  return initialParts;
364720
364906
  }
364721
364907
  async function getInitialChatHistory(config3, extraHistory) {
364908
+ const envId = deriveStableId(["environment-context"]);
364909
+ if (extraHistory && extraHistory.length > 0) {
364910
+ const first2 = extraHistory[0];
364911
+ const firstId = "id" in first2 ? first2.id : void 0;
364912
+ if (firstId === envId) {
364913
+ return [...extraHistory];
364914
+ }
364915
+ }
364722
364916
  const envParts = await getEnvironmentContext(config3);
364723
364917
  const envContextString = envParts.map((part) => part.text || "").join("\n\n");
364724
364918
  return [
364725
364919
  {
364726
- role: "user",
364727
- parts: [{ text: envContextString }]
364920
+ id: deriveStableId(["environment-context"]),
364921
+ content: {
364922
+ role: "user",
364923
+ parts: [{ text: envContextString }]
364924
+ }
364728
364925
  },
364729
364926
  ...extraHistory ?? []
364730
364927
  ];
@@ -364733,6 +364930,7 @@ var init_environmentContext = __esm({
364733
364930
  "packages/core/dist/src/utils/environmentContext.js"() {
364734
364931
  "use strict";
364735
364932
  init_getFolderStructure();
364933
+ init_cryptoUtils();
364736
364934
  }
364737
364935
  });
364738
364936
 
@@ -374127,6 +374325,9 @@ var init_modelConfigService = __esm({
374127
374325
  registerRuntimeModelOverride(override) {
374128
374326
  this.runtimeOverrides.push(override);
374129
374327
  }
374328
+ clearRuntimeOverrides() {
374329
+ this.runtimeOverrides.length = 0;
374330
+ }
374130
374331
  /**
374131
374332
  * Resolves a model configuration by merging settings from aliases and applying overrides.
374132
374333
  *
@@ -377890,6 +378091,9 @@ function createStateSnapshotProcessor(id, env, options) {
377890
378091
  const targetIds = new Set(targets.map((t4) => t4.id));
377891
378092
  const isValid2 = consumedIds.every((id2) => targetIds.has(id2));
377892
378093
  if (isValid2) {
378094
+ env.tracer.logEvent("StateSnapshotProcessor", "Snapshot Spliced from Inbox", {
378095
+ snapshotText: newText
378096
+ });
377893
378097
  debugLogger.log(`[StateSnapshotProcessor] Successfully spliced PROPOSED_SNAPSHOT from Inbox into Graph. Consumed ${consumedIds.length} nodes.`);
377894
378098
  const newId = deriveStableId(consumedIds);
377895
378099
  const snapshotNode = {
@@ -377952,6 +378156,9 @@ function createStateSnapshotProcessor(id, env, options) {
377952
378156
  maxSummaryTurns: options.maxSummaryTurns,
377953
378157
  maxStateTokens: options.maxStateTokens
377954
378158
  });
378159
+ env.tracer.logEvent("StateSnapshotProcessor", "Snapshot Synthesized", {
378160
+ snapshotText
378161
+ });
377955
378162
  const consumedIds = nodesToSummarize.map((n2) => n2.id);
377956
378163
  if (baselineIdToConsume && !consumedIds.includes(baselineIdToConsume)) {
377957
378164
  consumedIds.push(baselineIdToConsume);
@@ -378054,6 +378261,9 @@ function createStateSnapshotAsyncProcessor(id, env, options) {
378054
378261
  maxSummaryTurns: options.maxSummaryTurns,
378055
378262
  maxStateTokens: options.maxStateTokens
378056
378263
  });
378264
+ env.tracer.logEvent("StateSnapshotAsyncProcessor", "Snapshot Synthesized", {
378265
+ snapshotText
378266
+ });
378057
378267
  const newConsumedIds = [
378058
378268
  ...previousConsumedIds,
378059
378269
  ...targets.map((t4) => t4.id)
@@ -378189,8 +378399,8 @@ var init_profiles = __esm({
378189
378399
  name: "Stress Test",
378190
378400
  config: {
378191
378401
  budget: {
378192
- retainedTokens: 4e3,
378193
- maxTokens: 1e4
378402
+ retainedTokens: 1500,
378403
+ maxTokens: 5e3
378194
378404
  },
378195
378405
  processorOptions: {
378196
378406
  ToolMasking: {
@@ -378482,49 +378692,118 @@ var init_inbox = __esm({
378482
378692
  });
378483
378693
 
378484
378694
  // packages/core/dist/src/context/graph/toGraph.js
378695
+ import { createHash as createHash15 } from "node:crypto";
378485
378696
  function isTextPart2(part) {
378486
378697
  return typeof part.text === "string";
378487
378698
  }
378699
+ function isInlineDataPart(part) {
378700
+ return typeof part.inlineData === "object" && part.inlineData !== null && typeof part.inlineData.data === "string";
378701
+ }
378702
+ function isFileDataPart(part) {
378703
+ return typeof part.fileData === "object" && part.fileData !== null && typeof part.fileData.fileUri === "string";
378704
+ }
378488
378705
  function isFunctionCallPart(part) {
378489
378706
  return typeof part.functionCall === "object" && part.functionCall !== null && typeof part.functionCall.name === "string";
378490
378707
  }
378491
378708
  function isFunctionResponsePart(part) {
378492
378709
  return typeof part.functionResponse === "object" && part.functionResponse !== null && typeof part.functionResponse.name === "string";
378493
378710
  }
378494
- var ContextGraphBuilder;
378711
+ function isExecutableCodePart(part) {
378712
+ return typeof part.executableCode === "object" && part.executableCode !== null && typeof part.executableCode.code === "string" && typeof part.executableCode.language === "string";
378713
+ }
378714
+ function isCodeExecutionResultPart(part) {
378715
+ return typeof part.codeExecutionResult === "object" && part.codeExecutionResult !== null && typeof part.codeExecutionResult.output === "string" && typeof part.codeExecutionResult.outcome === "string";
378716
+ }
378717
+ function getStableId(obj, idService, turnSalt = "", partIdx = 0) {
378718
+ let id = idService.get(obj);
378719
+ if (id)
378720
+ return id;
378721
+ const cachedHash = PART_HASH_CACHE.get(obj);
378722
+ if (cachedHash) {
378723
+ id = `${cachedHash}_${turnSalt}_${partIdx}`;
378724
+ idService.set(obj, id);
378725
+ return id;
378726
+ }
378727
+ const part = obj;
378728
+ let contentHash;
378729
+ if (isTextPart2(part)) {
378730
+ contentHash = createHash15("sha256").update(part.text).digest("hex");
378731
+ id = `text_${contentHash}_${turnSalt}_${partIdx}`;
378732
+ } else if (isInlineDataPart(part)) {
378733
+ contentHash = createHash15("sha256").update(part.inlineData.data).digest("hex");
378734
+ id = `media_${contentHash}_${turnSalt}_${partIdx}`;
378735
+ } else if (isFileDataPart(part)) {
378736
+ contentHash = createHash15("sha256").update(part.fileData.fileUri).digest("hex");
378737
+ id = `file_${contentHash}_${turnSalt}_${partIdx}`;
378738
+ } else if (isFunctionCallPart(part)) {
378739
+ if (part.functionCall.id) {
378740
+ id = `call_${part.functionCall.id}`;
378741
+ } else {
378742
+ contentHash = createHash15("sha256").update(`call:${part.functionCall.name}:${JSON.stringify(part.functionCall.args)}`).digest("hex");
378743
+ id = `call_h_${contentHash}_${turnSalt}_${partIdx}`;
378744
+ }
378745
+ } else if (isFunctionResponsePart(part)) {
378746
+ if (part.functionResponse.id) {
378747
+ id = `resp_${part.functionResponse.id}`;
378748
+ } else {
378749
+ contentHash = createHash15("sha256").update(`resp:${part.functionResponse.name}:${JSON.stringify(part.functionResponse.response)}`).digest("hex");
378750
+ id = `resp_h_${contentHash}_${turnSalt}_${partIdx}`;
378751
+ }
378752
+ } else if (isExecutableCodePart(part)) {
378753
+ contentHash = createHash15("sha256").update(`exec:${part.executableCode.language}:${part.executableCode.code}`).digest("hex");
378754
+ id = `exec_${contentHash}_${turnSalt}_${partIdx}`;
378755
+ } else if (isCodeExecutionResultPart(part)) {
378756
+ contentHash = createHash15("sha256").update(`result:${part.codeExecutionResult.outcome}:${part.codeExecutionResult.output}`).digest("hex");
378757
+ id = `result_${contentHash}_${turnSalt}_${partIdx}`;
378758
+ }
378759
+ if (contentHash) {
378760
+ PART_HASH_CACHE.set(obj, contentHash);
378761
+ }
378762
+ if (!id) {
378763
+ if (turnSalt && partIdx === -1) {
378764
+ id = `turn_${turnSalt}`;
378765
+ } else {
378766
+ id = `${turnSalt}_f_${partIdx}`;
378767
+ }
378768
+ }
378769
+ idService.set(obj, id);
378770
+ return id;
378771
+ }
378772
+ var PART_HASH_CACHE, ContextGraphBuilder;
378495
378773
  var init_toGraph = __esm({
378496
378774
  "packages/core/dist/src/context/graph/toGraph.js"() {
378497
378775
  "use strict";
378498
378776
  init_types15();
378499
378777
  init_debugLogger();
378500
378778
  init_snapshotGenerator();
378779
+ init_cryptoUtils();
378780
+ init_sessionUtils();
378781
+ PART_HASH_CACHE = /* @__PURE__ */ new WeakMap();
378501
378782
  ContextGraphBuilder = class {
378502
378783
  idService;
378503
378784
  constructor(idService) {
378504
378785
  this.idService = idService;
378505
378786
  }
378506
378787
  processHistory(history) {
378788
+ ensureStableToolIds(history);
378507
378789
  const nodes = [];
378508
378790
  for (let turnIdx = 0; turnIdx < history.length; turnIdx++) {
378509
378791
  const turn = history[turnIdx];
378510
378792
  const msg = turn.content;
378511
378793
  if (!msg.parts)
378512
378794
  continue;
378513
- if (msg.role === "user" && msg.parts.length === 1) {
378514
- const text = msg.parts[0].text;
378515
- if (text?.startsWith("<session_context>") && text?.includes("This is the Gemini CLI")) {
378516
- debugLogger.log("[ContextGraphBuilder] Skipping legacy environment header turn from graph.");
378517
- continue;
378518
- }
378519
- }
378520
378795
  const turnSalt = turn.id;
378521
- const turnId = `turn_${turnSalt}`;
378796
+ const turnId = turnSalt.startsWith("turn_") ? turnSalt : `turn_${turnSalt}`;
378522
378797
  if (msg.role === "user") {
378523
378798
  for (let partIdx = 0; partIdx < msg.parts.length; partIdx++) {
378524
378799
  const part = msg.parts[partIdx];
378525
- const apiId = isFunctionResponsePart(part) && typeof part.functionResponse.id === "string" ? part.functionResponse.id : isFunctionCallPart(part) && typeof part.functionCall.id === "string" ? part.functionCall.id : void 0;
378800
+ const envTurnId = deriveStableId(["environment-context"]);
378801
+ if (isTextPart2(part) && part.text.trim().startsWith("<session_context>") && turnSalt !== envTurnId) {
378802
+ debugLogger.log("[ContextGraphBuilder] Skipping legacy environment header turn from graph.");
378803
+ continue;
378804
+ }
378526
378805
  const isSnapshot = isTextPart2(part) && isSnapshotState(part.text);
378527
- const id = apiId ? `${apiId}_${turnSalt}_${partIdx}` : `${turnSalt}_${partIdx}`;
378806
+ const id = getStableId(part, this.idService, turnSalt, partIdx);
378528
378807
  const node = {
378529
378808
  id,
378530
378809
  timestamp: Date.now(),
@@ -378534,13 +378813,11 @@ var init_toGraph = __esm({
378534
378813
  turnId
378535
378814
  };
378536
378815
  nodes.push(node);
378537
- this.idService.set(part, id);
378538
378816
  }
378539
378817
  } else if (msg.role === "model") {
378540
378818
  for (let partIdx = 0; partIdx < msg.parts.length; partIdx++) {
378541
378819
  const part = msg.parts[partIdx];
378542
- const apiId = isFunctionCallPart(part) && typeof part.functionCall.id === "string" ? part.functionCall.id : void 0;
378543
- const id = apiId ? `${apiId}_${turnSalt}_${partIdx}` : `${turnSalt}_${partIdx}`;
378820
+ const id = getStableId(part, this.idService, turnSalt, partIdx);
378544
378821
  const node = {
378545
378822
  id,
378546
378823
  timestamp: Date.now(),
@@ -378550,7 +378827,6 @@ var init_toGraph = __esm({
378550
378827
  turnId
378551
378828
  };
378552
378829
  nodes.push(node);
378553
- this.idService.set(part, id);
378554
378830
  }
378555
378831
  }
378556
378832
  }
@@ -378632,8 +378908,8 @@ var init_mapper = __esm({
378632
378908
  constructor() {
378633
378909
  this.builder = new ContextGraphBuilder(this.idService);
378634
378910
  }
378635
- applyEvent(event) {
378636
- return this.builder.processHistory(event.payload);
378911
+ sync(turns) {
378912
+ return this.builder.processHistory(turns);
378637
378913
  }
378638
378914
  fromGraph(nodes) {
378639
378915
  return fromGraph(nodes, this.idService);
@@ -378933,20 +379209,17 @@ var init_orchestrator = __esm({
378933
379209
  pipelines;
378934
379210
  asyncPipelines;
378935
379211
  env;
378936
- eventBus;
378937
379212
  tracer;
378938
379213
  activeTimers = [];
378939
379214
  pendingPipelines = /* @__PURE__ */ new Map();
378940
379215
  pipelineMutex = /* @__PURE__ */ new Map();
378941
379216
  pipelineScheduled = /* @__PURE__ */ new Set();
378942
379217
  nodeProvider;
378943
- constructor(pipelines, asyncPipelines, env, eventBus, tracer) {
379218
+ constructor(pipelines, asyncPipelines, env, tracer) {
378944
379219
  this.pipelines = pipelines;
378945
379220
  this.asyncPipelines = asyncPipelines;
378946
379221
  this.env = env;
378947
- this.eventBus = eventBus;
378948
379222
  this.tracer = tracer;
378949
- this.setupTriggers();
378950
379223
  }
378951
379224
  /**
378952
379225
  * Sets the provider for the latest live nodes.
@@ -378969,105 +379242,6 @@ var init_orchestrator = __esm({
378969
379242
  isNodeAllowed(node, triggerTargets, protectedTurnIds = /* @__PURE__ */ new Set()) {
378970
379243
  return triggerTargets.has(node.id) && !protectedTurnIds.has(node.id) && !protectedTurnIds.has(node.turnId);
378971
379244
  }
378972
- setupTriggers() {
378973
- const bindTriggers = (pipelines, executeFn) => {
378974
- for (const pipeline3 of pipelines) {
378975
- for (const trigger of pipeline3.triggers) {
378976
- if (typeof trigger === "object" && trigger.type === "timer") {
378977
- const timer = setInterval(() => {
378978
- }, trigger.intervalMs);
378979
- this.activeTimers.push(timer);
378980
- } else if (trigger === "retained_exceeded" || trigger === "nodes_aged_out") {
378981
- this.eventBus.onConsolidationNeeded((event) => {
378982
- void executeFn(pipeline3, event.nodes, event.targetNodeIds, /* @__PURE__ */ new Set());
378983
- });
378984
- } else if (trigger === "new_message" || trigger === "nodes_added") {
378985
- this.eventBus.onChunkReceived((event) => {
378986
- void executeFn(pipeline3, event.nodes, event.targetNodeIds, /* @__PURE__ */ new Set());
378987
- });
378988
- }
378989
- }
378990
- }
378991
- };
378992
- const handleSyncExecution = async (pipeline3, nodes, targets, protectedIds) => {
378993
- if (this.pipelineScheduled.has(pipeline3.name)) {
378994
- debugLogger.log(`[Orchestrator] Pipeline ${pipeline3.name} already scheduled (sync), dropping.`);
378995
- return;
378996
- }
378997
- this.pipelineScheduled.add(pipeline3.name);
378998
- const existing = this.pipelineMutex.get(pipeline3.name) || Promise.resolve();
378999
- const nextPromise = (async () => {
379000
- try {
379001
- await existing;
379002
- this.pipelineScheduled.delete(pipeline3.name);
379003
- const latestNodes = this.nodeProvider ? this.nodeProvider() : nodes;
379004
- const latestTargets = latestNodes.filter((n2) => targets.has(n2.id));
379005
- debugLogger.log(`[Orchestrator] Executing sync pipeline ${pipeline3.name} with ${latestTargets.length} latest targets.`);
379006
- if (latestTargets.length === 0) {
379007
- debugLogger.log(`[Orchestrator] No latest targets for sync pipeline ${pipeline3.name}, returning.`);
379008
- return;
379009
- }
379010
- await this.executePipelineAsync(pipeline3, latestNodes, new Set(targets), new Set(protectedIds));
379011
- } catch (e3) {
379012
- debugLogger.error(`Sync pipeline chain ${pipeline3.name} failed:`, e3);
379013
- }
379014
- })();
379015
- this.pipelineMutex.set(pipeline3.name, nextPromise);
379016
- const pipelineId = `${pipeline3.name}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
379017
- this.pendingPipelines.set(pipelineId, nextPromise);
379018
- void nextPromise.finally(() => {
379019
- this.pendingPipelines.delete(pipelineId);
379020
- if (this.pipelineMutex.get(pipeline3.name) === nextPromise) {
379021
- this.pipelineMutex.delete(pipeline3.name);
379022
- }
379023
- });
379024
- };
379025
- const handleAsyncExecution = async (pipeline3, nodes, targets) => {
379026
- if (this.pipelineScheduled.has(pipeline3.name)) {
379027
- debugLogger.log(`[Orchestrator] Pipeline ${pipeline3.name} already scheduled (async), dropping.`);
379028
- return;
379029
- }
379030
- this.pipelineScheduled.add(pipeline3.name);
379031
- const existing = this.pipelineMutex.get(pipeline3.name) || Promise.resolve();
379032
- const nextPromise = (async () => {
379033
- try {
379034
- await existing;
379035
- this.pipelineScheduled.delete(pipeline3.name);
379036
- const latestNodes = this.nodeProvider ? this.nodeProvider() : nodes;
379037
- const latestTargets = latestNodes.filter((n2) => targets.has(n2.id));
379038
- debugLogger.log(`[Orchestrator] Executing async pipeline ${pipeline3.name} with ${latestTargets.length} latest targets.`);
379039
- const inboxSnapshot = new InboxSnapshotImpl(this.env.inbox.getMessages() || []);
379040
- for (const processor of pipeline3.processors) {
379041
- debugLogger.log(`[Orchestrator] Running async processor ${processor.id}`);
379042
- await processor.process({
379043
- targets: latestTargets,
379044
- inbox: inboxSnapshot,
379045
- buffer: ContextWorkingBufferImpl.initialize(latestNodes)
379046
- });
379047
- }
379048
- this.env.inbox.drainConsumed(inboxSnapshot.getConsumedIds());
379049
- } catch (e3) {
379050
- debugLogger.error(`Async pipeline chain ${pipeline3.name} failed:`, e3);
379051
- }
379052
- })();
379053
- this.pipelineMutex.set(pipeline3.name, nextPromise);
379054
- const pipelineId = `${pipeline3.name}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
379055
- this.pendingPipelines.set(pipelineId, nextPromise);
379056
- void nextPromise.finally(() => {
379057
- this.pendingPipelines.delete(pipelineId);
379058
- if (this.pipelineMutex.get(pipeline3.name) === nextPromise) {
379059
- this.pipelineMutex.delete(pipeline3.name);
379060
- }
379061
- });
379062
- };
379063
- bindTriggers(this.pipelines, (pipeline3, nodes, targets, protectedIds) => handleSyncExecution(pipeline3, nodes, targets, protectedIds));
379064
- bindTriggers(this.asyncPipelines, (pipeline3, nodes, targets) => handleAsyncExecution(pipeline3, nodes, targets));
379065
- }
379066
- shutdown() {
379067
- for (const timer of this.activeTimers) {
379068
- clearInterval(timer);
379069
- }
379070
- }
379071
379245
  async executeTriggerSync(trigger, nodes, triggerTargets, protectedTurnIds = /* @__PURE__ */ new Set()) {
379072
379246
  this.tracer.logEvent("Orchestrator", "Strategy Intent", {
379073
379247
  trigger,
@@ -379107,117 +379281,57 @@ var init_orchestrator = __esm({
379107
379281
  }
379108
379282
  }
379109
379283
  }
379284
+ void this.executeTriggerAsync(trigger, currentBuffer.nodes, triggerTargets);
379110
379285
  this.env.inbox.drainConsumed(inboxSnapshot.getConsumedIds());
379111
379286
  return currentBuffer.nodes;
379112
379287
  }
379113
- async executePipelineAsync(pipeline3, nodes, triggerTargets, protectedTurnIds = /* @__PURE__ */ new Set()) {
379114
- this.tracer.logEvent("Orchestrator", `Triggering async pipeline: ${pipeline3.name}`, {
379115
- triggerTargets: triggerTargets.size,
379116
- totalNodes: nodes.length
379117
- });
379118
- if (!nodes || nodes.length === 0)
379119
- return;
379120
- let currentBuffer = ContextWorkingBufferImpl.initialize(nodes);
379121
- const inboxSnapshot = new InboxSnapshotImpl(this.env.inbox.getMessages() || []);
379122
- for (const processor of pipeline3.processors) {
379123
- try {
379124
- this.tracer.logEvent("Orchestrator", `Executing processor: ${processor.id} (async)`, { nodeCountBefore: currentBuffer.nodes.length });
379125
- const allowedTargets = currentBuffer.nodes.filter((n2) => this.isNodeAllowed(n2, triggerTargets, protectedTurnIds));
379126
- const returnedNodes = await processor.process({
379127
- buffer: currentBuffer,
379128
- targets: allowedTargets,
379129
- inbox: inboxSnapshot
379130
- });
379131
- currentBuffer = currentBuffer.applyProcessorResult(processor.id, allowedTargets, returnedNodes);
379132
- const addedNodes = returnedNodes.filter((n2) => !allowedTargets.some((at2) => at2.id === n2.id));
379133
- const removedNodes = allowedTargets.filter((at2) => !returnedNodes.some((n2) => n2.id === at2.id));
379134
- this.tracer.logEvent("Orchestrator", "Transformation Lineage (Async)", {
379135
- processorId: processor.id,
379136
- inputNodeCount: allowedTargets.length,
379137
- outputNodeCount: returnedNodes.length,
379138
- removedNodeIds: removedNodes.map((n2) => n2.id),
379139
- addedNodes: addedNodes.map((n2) => ({
379140
- id: n2.id,
379141
- replacesId: n2.replacesId,
379142
- abstractsIds: n2.abstractsIds,
379143
- approxTokens: this.env.tokenCalculator.calculateConcreteListTokens([
379144
- n2
379145
- ])
379146
- }))
379147
- });
379148
- this.eventBus.emitProcessorResult({
379149
- processorId: processor.id,
379150
- targets: allowedTargets,
379151
- returnedNodes
379152
- });
379153
- } catch (error2) {
379154
- debugLogger.error(`Pipeline ${pipeline3.name} failed async at ${processor.id}:`, error2);
379155
- return;
379156
- }
379288
+ async executeTriggerAsync(trigger, nodes, triggerTargets) {
379289
+ const asyncPipelines = this.asyncPipelines.filter((p3) => p3.triggers.includes(trigger));
379290
+ for (const pipeline3 of asyncPipelines) {
379291
+ void this.handleAsyncExecution(pipeline3, nodes, triggerTargets);
379157
379292
  }
379158
- this.env.inbox.drainConsumed(inboxSnapshot.getConsumedIds());
379159
379293
  }
379160
- };
379161
- }
379162
- });
379163
-
379164
- // packages/core/dist/src/context/historyObserver.js
379165
- var HistoryObserver;
379166
- var init_historyObserver = __esm({
379167
- "packages/core/dist/src/context/historyObserver.js"() {
379168
- "use strict";
379169
- HistoryObserver = class {
379170
- chatHistory;
379171
- eventBus;
379172
- tracer;
379173
- graphMapper;
379174
- unsubscribeHistory;
379175
- seenNodeIds = /* @__PURE__ */ new Set();
379176
- constructor(chatHistory, eventBus, tracer, graphMapper) {
379177
- this.chatHistory = chatHistory;
379178
- this.eventBus = eventBus;
379179
- this.tracer = tracer;
379180
- this.graphMapper = graphMapper;
379181
- }
379182
- processEvent = (event) => {
379183
- if (event.type === "CLEAR") {
379184
- this.seenNodeIds.clear();
379185
- }
379186
- if (event.type === "SILENT_SYNC") {
379294
+ async handleAsyncExecution(pipeline3, nodes, targets) {
379295
+ if (this.pipelineScheduled.has(pipeline3.name)) {
379187
379296
  return;
379188
379297
  }
379189
- const fullHistory = this.chatHistory.get();
379190
- const nodes = this.graphMapper.applyEvent({
379191
- ...event,
379192
- payload: fullHistory
379193
- });
379194
- const newNodes = /* @__PURE__ */ new Set();
379195
- for (const node of nodes) {
379196
- if (!this.seenNodeIds.has(node.id)) {
379197
- newNodes.add(node.id);
379198
- this.seenNodeIds.add(node.id);
379298
+ this.pipelineScheduled.add(pipeline3.name);
379299
+ const existing = this.pipelineMutex.get(pipeline3.name) || Promise.resolve();
379300
+ const nextPromise = (async () => {
379301
+ try {
379302
+ await existing;
379303
+ this.pipelineScheduled.delete(pipeline3.name);
379304
+ const latestNodes = this.nodeProvider ? this.nodeProvider() : nodes;
379305
+ const latestTargets = latestNodes.filter((n2) => targets.has(n2.id));
379306
+ if (latestTargets.length === 0)
379307
+ return;
379308
+ debugLogger.log(`[Orchestrator] Executing async pipeline ${pipeline3.name}`);
379309
+ const inboxSnapshot = new InboxSnapshotImpl(this.env.inbox.getMessages() || []);
379310
+ for (const processor of pipeline3.processors) {
379311
+ await processor.process({
379312
+ targets: latestTargets,
379313
+ inbox: inboxSnapshot,
379314
+ buffer: ContextWorkingBufferImpl.initialize(latestNodes)
379315
+ });
379316
+ }
379317
+ this.env.inbox.drainConsumed(inboxSnapshot.getConsumedIds());
379318
+ } catch (e3) {
379319
+ debugLogger.error(`Async pipeline chain ${pipeline3.name} failed:`, e3);
379320
+ }
379321
+ })();
379322
+ this.pipelineMutex.set(pipeline3.name, nextPromise);
379323
+ const pipelineId = `${pipeline3.name}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
379324
+ this.pendingPipelines.set(pipelineId, nextPromise);
379325
+ void nextPromise.finally(() => {
379326
+ this.pendingPipelines.delete(pipelineId);
379327
+ if (this.pipelineMutex.get(pipeline3.name) === nextPromise) {
379328
+ this.pipelineMutex.delete(pipeline3.name);
379199
379329
  }
379200
- }
379201
- this.tracer.logEvent("HistoryObserver", `Rebuilt pristine graph from ${event.type} event`, { nodesSize: nodes.length, newNodesCount: newNodes.size });
379202
- this.eventBus.emitPristineHistoryUpdated({
379203
- nodes,
379204
- newNodes
379205
379330
  });
379206
- };
379207
- start() {
379208
- if (this.unsubscribeHistory) {
379209
- this.unsubscribeHistory();
379210
- }
379211
- this.unsubscribeHistory = this.chatHistory.subscribe(this.processEvent);
379212
- const existing = this.chatHistory.get();
379213
- if (existing && existing.length > 0) {
379214
- this.processEvent({ type: "SYNC_FULL", payload: existing });
379215
- }
379216
379331
  }
379217
- stop() {
379218
- if (this.unsubscribeHistory) {
379219
- this.unsubscribeHistory();
379220
- this.unsubscribeHistory = void 0;
379332
+ shutdown() {
379333
+ for (const timer of this.activeTimers) {
379334
+ clearInterval(timer);
379221
379335
  }
379222
379336
  }
379223
379337
  };
@@ -379259,7 +379373,8 @@ var init_tokenCalibration = __esm({
379259
379373
  });
379260
379374
 
379261
379375
  // packages/core/dist/src/context/graph/render.js
379262
- async function render2(nodes, orchestrator, sidecar, tracer, env, advancedTokenCalculator, protectionReasons = /* @__PURE__ */ new Map(), header, previewNodeIds = /* @__PURE__ */ new Set()) {
379376
+ async function render2(nodes, orchestrator, sidecar, tracer, env, advancedTokenCalculator, options = {}) {
379377
+ const { protectionReasons = /* @__PURE__ */ new Map(), header, lateBindPrompt } = options;
379263
379378
  let headerTokens = 0;
379264
379379
  let headerBaseUnits = 0;
379265
379380
  if (header) {
@@ -379267,22 +379382,28 @@ async function render2(nodes, orchestrator, sidecar, tracer, env, advancedTokenC
379267
379382
  headerTokens = costs.tokens;
379268
379383
  headerBaseUnits = costs.baseUnits;
379269
379384
  }
379385
+ const lastTurnId = nodes[nodes.length - 1]?.turnId;
379270
379386
  if (!sidecar.config.budget) {
379271
- const visibleNodes2 = nodes.filter((n2) => !previewNodeIds.has(n2.id));
379272
- const contents2 = env.graphMapper.fromGraph(visibleNodes2);
379387
+ const allVisibleNodes2 = nodes;
379388
+ const managedNodes2 = lateBindPrompt && lastTurnId ? allVisibleNodes2.filter((n2) => n2.turnId !== lastTurnId) : allVisibleNodes2;
379389
+ const pendingNodes2 = lateBindPrompt && lastTurnId ? allVisibleNodes2.filter((n2) => n2.turnId === lastTurnId) : [];
379390
+ const history2 = env.graphMapper.fromGraph(managedNodes2);
379391
+ const pendingHistory2 = env.graphMapper.fromGraph(pendingNodes2);
379273
379392
  tracer.logEvent("Render", "Render Context to LLM (No Budget)", {
379274
- renderedContext: contents2
379393
+ renderedContext: history2,
379394
+ pendingContext: pendingHistory2
379275
379395
  });
379276
- const baseUnits = advancedTokenCalculator.getRawBaseUnits(nodes) + headerBaseUnits;
379396
+ const baseUnits = advancedTokenCalculator.getRawBaseUnits(allVisibleNodes2) + headerBaseUnits;
379277
379397
  return {
379278
- history: contents2,
379398
+ history: history2,
379399
+ pendingHistory: pendingHistory2,
379279
379400
  didApplyManagement: false,
379280
379401
  baseUnits,
379281
379402
  processedNodes: nodes
379282
379403
  };
379283
379404
  }
379284
379405
  const maxTokens = sidecar.config.budget.maxTokens;
379285
- const { tokens: graphTokens, baseUnits: graphBaseUnits } = advancedTokenCalculator.calculateTokensAndBaseUnits(nodes);
379406
+ const { tokens: graphTokens } = advancedTokenCalculator.calculateTokensAndBaseUnits(nodes);
379286
379407
  const currentTokens = graphTokens + headerTokens;
379287
379408
  const protectedIds = new Set(protectionReasons.keys());
379288
379409
  tracer.logEvent("Render", "Budget Audit", {
@@ -379302,21 +379423,30 @@ async function render2(nodes, orchestrator, sidecar, tracer, env, advancedTokenC
379302
379423
  });
379303
379424
  if (currentTokens <= maxTokens) {
379304
379425
  tracer.logEvent("Render", `View is within maxTokens (${currentTokens} <= ${maxTokens}). Returning view.`);
379305
- const visibleNodes2 = nodes.filter((n2) => !previewNodeIds.has(n2.id));
379306
- const contents2 = env.graphMapper.fromGraph(visibleNodes2);
379426
+ const allVisibleNodes2 = nodes;
379427
+ const managedNodes2 = lateBindPrompt && lastTurnId ? allVisibleNodes2.filter((n2) => n2.turnId !== lastTurnId) : allVisibleNodes2;
379428
+ const pendingNodes2 = lateBindPrompt && lastTurnId ? allVisibleNodes2.filter((n2) => n2.turnId === lastTurnId) : [];
379429
+ const history2 = env.graphMapper.fromGraph(managedNodes2);
379430
+ const pendingHistory2 = env.graphMapper.fromGraph(pendingNodes2);
379307
379431
  tracer.logEvent("Render", "Render Context for LLM", {
379308
- renderedContext: contents2
379432
+ renderedContext: history2,
379433
+ pendingContext: pendingHistory2
379309
379434
  });
379310
- performCalibration(env, visibleNodes2, contents2.map((h3) => h3.content));
379435
+ performCalibration(env, allVisibleNodes2, [
379436
+ ...history2.map((h3) => h3.content),
379437
+ ...pendingHistory2.map((h3) => h3.content)
379438
+ ]);
379311
379439
  return {
379312
- history: contents2,
379440
+ history: history2,
379441
+ pendingHistory: pendingHistory2,
379313
379442
  didApplyManagement: false,
379314
- baseUnits: graphBaseUnits + headerBaseUnits,
379443
+ baseUnits: advancedTokenCalculator.getRawBaseUnits(allVisibleNodes2) + headerBaseUnits,
379315
379444
  processedNodes: nodes
379316
379445
  };
379317
379446
  }
379318
379447
  const targetDelta = currentTokens - sidecar.config.budget.retainedTokens;
379319
379448
  tracer.logEvent("Render", `View exceeds maxTokens (${currentTokens} > ${maxTokens}). Hitting Synchronous Pressure Barrier.`, { targetDelta });
379449
+ debugLogger.log(`Context Manager Synchronous Barrier triggered: View at ${currentTokens} tokens (limit: ${maxTokens}).`);
379320
379450
  const agedOutNodes = /* @__PURE__ */ new Set();
379321
379451
  let rollingTokens = 0;
379322
379452
  for (let i4 = nodes.length - 1; i4 >= 0; i4--) {
@@ -379328,6 +379458,13 @@ async function render2(nodes, orchestrator, sidecar, tracer, env, advancedTokenC
379328
379458
  agedOutNodes.add(node.id);
379329
379459
  }
379330
379460
  }
379461
+ if (lateBindPrompt && lastTurnId) {
379462
+ for (const node of nodes) {
379463
+ if (node.turnId === lastTurnId) {
379464
+ agedOutNodes.delete(node.id);
379465
+ }
379466
+ }
379467
+ }
379331
379468
  const processedNodes = await orchestrator.executeTriggerSync("gc_backstop", nodes, agedOutNodes, protectedIds);
379332
379469
  const skipList = /* @__PURE__ */ new Set();
379333
379470
  for (const node of processedNodes) {
@@ -379336,22 +379473,33 @@ async function render2(nodes, orchestrator, sidecar, tracer, env, advancedTokenC
379336
379473
  skipList.add(id);
379337
379474
  }
379338
379475
  }
379339
- const visibleNodes = processedNodes.filter((n2) => !skipList.has(n2.id) && !previewNodeIds.has(n2.id));
379340
- const contents = env.graphMapper.fromGraph(visibleNodes);
379476
+ const allVisibleNodes = processedNodes.filter((n2) => !skipList.has(n2.id));
379477
+ const managedNodes = lateBindPrompt && lastTurnId ? allVisibleNodes.filter((n2) => n2.turnId !== lastTurnId) : allVisibleNodes;
379478
+ const pendingNodes = lateBindPrompt && lastTurnId ? allVisibleNodes.filter((n2) => n2.turnId === lastTurnId) : [];
379479
+ const history = env.graphMapper.fromGraph(managedNodes);
379480
+ const pendingHistory = env.graphMapper.fromGraph(pendingNodes);
379481
+ const finalTokens = advancedTokenCalculator.calculateConcreteListTokens(allVisibleNodes);
379341
379482
  tracer.logEvent("Render", "Render Sanitized Context for LLM", {
379342
- renderedContextSanitized: contents
379483
+ renderedContextSanitized: history,
379484
+ pendingContextSanitized: pendingHistory
379343
379485
  });
379344
- performCalibration(env, visibleNodes, contents.map((h3) => h3.content));
379486
+ debugLogger.log(`Context Manager finished. Final actual token count: ${finalTokens}.`);
379487
+ performCalibration(env, allVisibleNodes, [
379488
+ ...history.map((h3) => h3.content),
379489
+ ...pendingHistory.map((h3) => h3.content)
379490
+ ]);
379345
379491
  return {
379346
- history: contents,
379492
+ history,
379493
+ pendingHistory,
379347
379494
  didApplyManagement: true,
379348
- baseUnits: advancedTokenCalculator.getRawBaseUnits(visibleNodes) + headerBaseUnits,
379495
+ baseUnits: advancedTokenCalculator.getRawBaseUnits(allVisibleNodes) + headerBaseUnits,
379349
379496
  processedNodes
379350
379497
  };
379351
379498
  }
379352
379499
  var init_render = __esm({
379353
379500
  "packages/core/dist/src/context/graph/render.js"() {
379354
379501
  "use strict";
379502
+ init_debugLogger();
379355
379503
  init_tokenCalibration();
379356
379504
  }
379357
379505
  });
@@ -379392,24 +379540,25 @@ var ContextManager;
379392
379540
  var init_contextManager = __esm({
379393
379541
  "packages/core/dist/src/context/contextManager.js"() {
379394
379542
  "use strict";
379395
- init_historyObserver();
379396
379543
  init_render();
379397
379544
  init_contextWorkingBuffer();
379398
379545
  init_debugLogger();
379546
+ init_cryptoUtils();
379399
379547
  init_historyHardening();
379400
379548
  init_invariantChecker();
379401
379549
  ContextManager = class {
379402
379550
  sidecar;
379403
379551
  env;
379404
379552
  tracer;
379553
+ chatHistory;
379405
379554
  advancedTokenCalculator;
379406
379555
  headerProvider;
379407
- // The master state containing the pristine graph and current active graph.
379556
+ // Master state containing the pristine graph and current active graph.
379408
379557
  buffer = ContextWorkingBufferImpl.initialize([]);
379409
379558
  eventBus;
379410
- // Internal sub-components
379411
379559
  orchestrator;
379412
- historyObserver;
379560
+ // Track what IDs have been evaluated for triggers to prevent redundant processing
379561
+ evaluatedNodeIds = /* @__PURE__ */ new Set();
379413
379562
  // Hysteresis tracking to prevent utility call churn
379414
379563
  lastTriggeredDeficit = 0;
379415
379564
  // Cache for Anomaly 3 (Redundant Renders)
@@ -379419,16 +379568,12 @@ var init_contextManager = __esm({
379419
379568
  this.sidecar = sidecar;
379420
379569
  this.env = env;
379421
379570
  this.tracer = tracer;
379571
+ this.chatHistory = chatHistory;
379422
379572
  this.advancedTokenCalculator = advancedTokenCalculator;
379423
379573
  this.headerProvider = headerProvider;
379424
379574
  this.eventBus = env.eventBus;
379425
379575
  this.orchestrator = orchestrator;
379426
379576
  this.orchestrator.setNodeProvider(() => this.buffer.nodes);
379427
- this.historyObserver = new HistoryObserver(chatHistory, this.env.eventBus, this.tracer, this.env.graphMapper);
379428
- this.eventBus.onPristineHistoryUpdated((event) => {
379429
- this.buffer = this.buffer.syncPristineHistory(event.nodes);
379430
- this.evaluateTriggers(event.newNodes);
379431
- });
379432
379577
  this.eventBus.onProcessorResult((event) => {
379433
379578
  const currentIds = new Set(this.buffer.nodes.map((n2) => n2.id));
379434
379579
  const allTargetsPresent = event.targets.every((t4) => currentIds.has(t4.id));
@@ -379438,7 +379583,6 @@ var init_contextManager = __esm({
379438
379583
  }
379439
379584
  this.buffer = this.buffer.applyProcessorResult(event.processorId, event.targets, event.returnedNodes);
379440
379585
  });
379441
- this.historyObserver.start();
379442
379586
  }
379443
379587
  /**
379444
379588
  * Returns a promise that resolves when all currently executing async pipelines have finished.
@@ -379451,29 +379595,22 @@ var init_contextManager = __esm({
379451
379595
  */
379452
379596
  shutdown() {
379453
379597
  this.orchestrator.shutdown();
379454
- this.historyObserver.stop();
379455
379598
  }
379456
379599
  /**
379457
379600
  * Evaluates if the current working buffer exceeds configured budget thresholds,
379458
379601
  * firing consolidation events if necessary.
379459
379602
  */
379460
- evaluateTriggers(newNodes) {
379603
+ async evaluateTriggers(newNodes) {
379461
379604
  if (!this.sidecar.config.budget)
379462
379605
  return;
379463
379606
  if (newNodes.size > 0) {
379464
- this.eventBus.emitChunkReceived({
379465
- nodes: this.buffer.nodes,
379466
- targetNodeIds: newNodes
379467
- });
379607
+ await this.orchestrator.executeTriggerSync("new_message", this.buffer.nodes, newNodes);
379468
379608
  }
379469
379609
  const currentTokens = this.env.tokenCalculator.calculateConcreteListTokens(this.buffer.nodes);
379470
379610
  if (currentTokens > this.sidecar.config.budget.retainedTokens) {
379471
379611
  const agedOutNodes = /* @__PURE__ */ new Set();
379472
379612
  let rollingTokens = 0;
379473
379613
  const protectedIds = this.getProtectedNodeIds(this.buffer.nodes);
379474
- if (protectedIds.size > 0) {
379475
- debugLogger.log(`[ContextManager] Pinning ${protectedIds.size} nodes (recent_turn or external_active_task) to prevent truncation.`);
379476
- }
379477
379614
  for (let i4 = this.buffer.nodes.length - 1; i4 >= 0; i4--) {
379478
379615
  const node = this.buffer.nodes[i4];
379479
379616
  const priorTokens = rollingTokens;
@@ -379496,32 +379633,25 @@ var init_contextManager = __esm({
379496
379633
  if (targetDeficit >= threshold && (growthSinceLast >= threshold || this.lastTriggeredDeficit === 0)) {
379497
379634
  this.lastTriggeredDeficit = targetDeficit;
379498
379635
  this.env.tokenCalculator.garbageCollectCache(new Set(this.buffer.nodes.map((n2) => n2.id)));
379499
- this.eventBus.emitConsolidationNeeded({
379500
- nodes: this.buffer.nodes,
379501
- targetDeficit,
379502
- targetNodeIds: agedOutNodes
379503
- });
379636
+ await this.orchestrator.executeTriggerSync("nodes_aged_out", this.buffer.nodes, agedOutNodes, new Set(protectedIds.keys()));
379504
379637
  }
379505
379638
  } else {
379506
379639
  this.lastTriggeredDeficit = 0;
379507
379640
  }
379508
379641
  }
379509
379642
  }
379510
- /**
379511
- * Identifies 'pinned' nodes that should not be truncated.
379512
- * This includes:
379513
- * 1. The entire last turn (Recent context).
379514
- * 2. Active tool calls (calls without responses in the graph).
379515
- */
379516
379643
  getProtectedNodeIds(nodes, extraProtectedIds = /* @__PURE__ */ new Set()) {
379517
379644
  const protectionMap = /* @__PURE__ */ new Map();
379518
379645
  if (nodes.length === 0)
379519
379646
  return protectionMap;
379520
379647
  const lastNode = nodes[nodes.length - 1];
379521
379648
  const lastTurnId = lastNode.turnId;
379649
+ const envTurnId = `turn_${deriveStableId(["environment-context"])}`;
379522
379650
  for (const node of nodes) {
379523
379651
  if (node.turnId === lastTurnId) {
379524
379652
  protectionMap.set(node.id, "recent_turn");
379653
+ } else if (node.turnId === envTurnId) {
379654
+ protectionMap.set(node.id, "environment_context");
379525
379655
  }
379526
379656
  }
379527
379657
  for (const id of extraProtectedIds) {
@@ -379529,11 +379659,6 @@ var init_contextManager = __esm({
379529
379659
  }
379530
379660
  return protectionMap;
379531
379661
  }
379532
- /**
379533
- * Retrieves the raw, uncompressed Episodic Context Graph graph.
379534
- * Useful for internal tool rendering (like the trace viewer).
379535
- * Note: This is an expensive, deep clone operation.
379536
- */
379537
379662
  getPristineGraph() {
379538
379663
  const pristineSet = /* @__PURE__ */ new Map();
379539
379664
  for (const node of this.buffer.nodes) {
@@ -379544,31 +379669,32 @@ var init_contextManager = __esm({
379544
379669
  }
379545
379670
  return Array.from(pristineSet.values()).sort((a, b3) => a.timestamp - b3.timestamp);
379546
379671
  }
379547
- /**
379548
- * Generates a virtual view of the pristine graph, substituting in variants
379549
- * up to the configured token budget.
379550
- * This is the view that will eventually be projected back to the LLM.
379551
- */
379552
379672
  getNodes() {
379553
379673
  return [...this.buffer.nodes];
379554
379674
  }
379555
- getEnvironment() {
379556
- return this.env;
379557
- }
379558
379675
  /**
379559
- * Executes the final 'gc_backstop' pipeline if necessary, enforcing the token budget,
379560
- * and maps the Episodic Context Graph back into a raw Gemini Content[] array for transmission.
379561
- * This is the primary method called by the agent framework before sending a request.
379676
+ * Generates a virtual view of the pristine graph, substituting in variants
379677
+ * up to the configured token budget.
379562
379678
  */
379563
379679
  async renderHistory(pendingRequest, activeTaskIds = /* @__PURE__ */ new Set(), abortSignal) {
379564
379680
  this.tracer.logEvent("ContextManager", "Starting rendering of LLM context");
379681
+ const currentHistory = this.chatHistory.get();
379682
+ const pristineNodes = this.env.graphMapper.sync(currentHistory);
379683
+ this.buffer = this.buffer.syncPristineHistory(pristineNodes);
379684
+ const newPrimalNodes = /* @__PURE__ */ new Set();
379685
+ for (const node of pristineNodes) {
379686
+ if (!this.evaluatedNodeIds.has(node.id)) {
379687
+ newPrimalNodes.add(node.id);
379688
+ this.evaluatedNodeIds.add(node.id);
379689
+ }
379690
+ }
379565
379691
  let previewNodes = [];
379566
379692
  if (pendingRequest) {
379567
- previewNodes = this.env.graphMapper.applyEvent({
379568
- type: "PUSH",
379569
- payload: [pendingRequest]
379570
- });
379693
+ previewNodes = this.env.graphMapper.sync([pendingRequest]);
379694
+ const previewNodeIds2 = new Set(previewNodes.map((n2) => n2.id));
379695
+ previewNodes = await this.orchestrator.executeTriggerSync("new_message", previewNodes, previewNodeIds2);
379571
379696
  }
379697
+ await this.evaluateTriggers(newPrimalNodes);
379572
379698
  const hotStartPromise = (async () => {
379573
379699
  if (!this.hasPerformedHotStart) {
379574
379700
  this.hasPerformedHotStart = true;
@@ -379596,68 +379722,70 @@ var init_contextManager = __esm({
379596
379722
  return this.lastRenderCache.result;
379597
379723
  }
379598
379724
  const protectionReasons = this.getProtectedNodeIds(nodes, activeTaskIds);
379599
- const renderResult = await render2(nodes, this.orchestrator, this.sidecar, this.tracer, this.env, this.advancedTokenCalculator, protectionReasons, header, previewNodeIds);
379600
- const { history: renderedHistory, didApplyManagement, baseUnits, processedNodes } = renderResult;
379725
+ const renderResult = await render2(nodes, this.orchestrator, this.sidecar, this.tracer, this.env, this.advancedTokenCalculator, {
379726
+ protectionReasons,
379727
+ header,
379728
+ lateBindPrompt: !!pendingRequest
379729
+ });
379730
+ const { history: renderedHistory, pendingHistory, didApplyManagement, baseUnits, processedNodes } = renderResult;
379601
379731
  if (didApplyManagement) {
379602
379732
  this.buffer = this.buffer.applyProcessorResult("sync_backstop", this.buffer.nodes, processedNodes.filter((n2) => !previewNodeIds.has(n2.id)));
379603
379733
  }
379604
379734
  checkContextInvariants(this.buffer.nodes, "RenderHistory");
379605
379735
  this.tracer.logEvent("ContextManager", "Finished rendering");
379606
- const fullHistoryToHarden = pendingRequest ? [...renderedHistory, pendingRequest] : renderedHistory;
379607
- const hardenedHistory = hardenHistory(fullHistoryToHarden, {
379736
+ const allHistory = [...renderedHistory, ...pendingHistory];
379737
+ const hardenedAllHistory = hardenHistory(allHistory, {
379608
379738
  sentinels: this.sidecar.sentinels
379609
379739
  });
379610
- if (pendingRequest) {
379611
- const last2 = hardenedHistory[hardenedHistory.length - 1];
379612
- if (last2 && last2.content.parts) {
379613
- const numPartsToRemove = pendingRequest.content.parts?.length || 0;
379614
- if (numPartsToRemove > 0 && last2.content.parts.length > numPartsToRemove) {
379615
- last2.content.parts.splice(-numPartsToRemove);
379616
- } else {
379617
- hardenedHistory.pop();
379618
- }
379619
- } else {
379620
- hardenedHistory.pop();
379740
+ const firstPendingId = pendingHistory[0]?.id;
379741
+ let splitIndex = renderedHistory.length;
379742
+ if (firstPendingId) {
379743
+ const foundIndex = hardenedAllHistory.findIndex((h3) => h3.id === firstPendingId);
379744
+ if (foundIndex !== -1) {
379745
+ splitIndex = foundIndex;
379621
379746
  }
379622
379747
  }
379623
- const apiHistory = hardenedHistory.map((h3) => h3.content);
379748
+ const apiHistory = hardenedAllHistory.slice(0, splitIndex).map((h3) => h3.content);
379749
+ const pendingApiHistory = hardenedAllHistory.slice(splitIndex).map((h3) => h3.content);
379624
379750
  if (header) {
379625
379751
  apiHistory.unshift(header);
379626
379752
  }
379627
379753
  const result2 = {
379628
- history: hardenedHistory,
379754
+ history: renderedHistory,
379629
379755
  apiHistory,
379756
+ pendingApiHistory,
379630
379757
  didApplyManagement,
379631
379758
  baseUnits,
379632
379759
  processedNodes
379633
379760
  };
379634
- this.lastRenderCache = { nodesHash: totalHash, result: result2 };
379761
+ this.lastRenderCache = {
379762
+ nodesHash: totalHash,
379763
+ result: result2
379764
+ };
379635
379765
  return result2;
379636
379766
  }
379637
379767
  async performHotStartCalibration(nodes, abortSignal) {
379768
+ const history = this.env.graphMapper.fromGraph(nodes);
379769
+ const contents = history.map((h3) => h3.content);
379638
379770
  try {
379639
- this.tracer.logEvent("ContextManager", "Performing Hot Start Token Calibration");
379640
- const contents = this.env.graphMapper.fromGraph(nodes);
379641
- const rawContents = contents.map((h3) => h3.content);
379642
- const header = this.headerProvider ? await this.headerProvider() : void 0;
379643
- const combinedHistory = header ? [header, ...rawContents] : rawContents;
379644
- const baseUnits = this.advancedTokenCalculator.getRawBaseUnits(nodes) + (header ? this.advancedTokenCalculator.getRawBaseUnitsForContent(header) : 0);
379645
- if (combinedHistory.length > 0) {
379646
- const result2 = await this.env.llmClient.countTokens({
379647
- contents: combinedHistory,
379648
- abortSignal
379771
+ const { totalTokens } = await this.env.llmClient.countTokens({
379772
+ modelConfigKey: { model: "context-calibrator" },
379773
+ contents,
379774
+ abortSignal
379775
+ });
379776
+ if (totalTokens !== void 0) {
379777
+ this.env.eventBus.emitTokenGroundTruth({
379778
+ actualTokens: totalTokens,
379779
+ promptBaseUnits: this.advancedTokenCalculator.getRawBaseUnits(nodes)
379649
379780
  });
379650
- if (result2.totalTokens > 0) {
379651
- this.env.eventBus.emitTokenGroundTruth({
379652
- actualTokens: result2.totalTokens,
379653
- promptBaseUnits: baseUnits
379654
- });
379655
- }
379656
379781
  }
379657
- } catch (error2) {
379658
- this.tracer.logEvent("ContextManager", "Hot Start Token Calibration Failed (Ignored)", { error: error2 });
379782
+ } catch (e3) {
379783
+ debugLogger.warn("[ContextManager] Hot start calibration failed", e3);
379659
379784
  }
379660
379785
  }
379786
+ getEnvironment() {
379787
+ return this.env;
379788
+ }
379661
379789
  };
379662
379790
  }
379663
379791
  });
@@ -380146,11 +380274,8 @@ async function initializeContextManager(config3, chat, lastPromptId) {
380146
380274
  const env = new ContextEnvironmentImpl(() => config3.getBaseLlmClient(), config3.getSessionId(), lastPromptId, logDir, projectTempDir, tracer, charsPerToken, eventBus, calculator, behaviorRegistry, {
380147
380275
  calibrateTokenCalculation: !!process.env["GEMINI_CONTEXT_CALIBRATE_TOKEN_CALCULATIONS"]
380148
380276
  });
380149
- const orchestrator = new PipelineOrchestrator(sidecarProfile.buildPipelines(env), sidecarProfile.buildAsyncPipelines(env), env, eventBus, tracer);
380150
- return new ContextManager(sidecarProfile, env, tracer, orchestrator, chat.agentHistory, calculator, async () => {
380151
- const parts2 = await getEnvironmentContext(config3);
380152
- return { role: "user", parts: parts2 };
380153
- });
380277
+ const orchestrator = new PipelineOrchestrator(sidecarProfile.buildPipelines(env), sidecarProfile.buildAsyncPipelines(env), env, tracer);
380278
+ return new ContextManager(sidecarProfile, env, tracer, orchestrator, chat.agentHistory, calculator);
380154
380279
  }
380155
380280
  var init_initializer = __esm({
380156
380281
  "packages/core/dist/src/context/initializer.js"() {
@@ -380170,7 +380295,6 @@ var init_initializer = __esm({
380170
380295
  init_stateSnapshotProcessor();
380171
380296
  init_stateSnapshotAsyncProcessor();
380172
380297
  init_rollingSummaryProcessor();
380173
- init_environmentContext();
380174
380298
  init_adaptiveTokenCalculator();
380175
380299
  init_loggingContentGenerator();
380176
380300
  init_behaviorRegistry();
@@ -380415,7 +380539,7 @@ var init_client4 = __esm({
380415
380539
  const toolRegistry = this.context.toolRegistry;
380416
380540
  const toolDeclarations = toolRegistry.getFunctionDeclarations();
380417
380541
  const tools = [{ functionDeclarations: toolDeclarations }];
380418
- const history = this.config.getContextManagementConfig().enabled ? extraHistory ?? [] : await getInitialChatHistory(this.config, extraHistory);
380542
+ const history = await getInitialChatHistory(this.config, extraHistory);
380419
380543
  try {
380420
380544
  const systemMemory = this.config.getSystemInstructionMemory();
380421
380545
  const systemInstruction = getCoreSystemPrompt3(this.config, systemMemory);
@@ -380576,18 +380700,21 @@ var init_client4 = __esm({
380576
380700
  }
380577
380701
  const modelForLimitCheck = this._getActiveModelForCurrentTurn();
380578
380702
  let currentBaseUnits = 0;
380703
+ let apiHistoryOverride = void 0;
380579
380704
  if (this.config.getContextManagementConfig().enabled) {
380580
380705
  if (this.contextManager) {
380581
380706
  const rawPendingRequest = createUserContent(request);
380582
380707
  const pendingRequest = {
380583
- id: this.getChatRecordingService()?.recordSyntheticMessage("user", rawPendingRequest.parts || []) || randomUUID12(),
380708
+ id: randomUUID12(),
380584
380709
  content: rawPendingRequest
380585
380710
  };
380586
- const { history: newHistory, didApplyManagement, baseUnits } = await this.contextManager.renderHistory(pendingRequest, void 0, signal);
380711
+ const { history: newHistory, apiHistory, pendingApiHistory, baseUnits } = await this.contextManager.renderHistory(pendingRequest, void 0, signal);
380587
380712
  currentBaseUnits = baseUnits;
380588
- if (didApplyManagement) {
380589
- this.getChat().setHistory(newHistory, { silent: true });
380590
- }
380713
+ const finalPendingContent = pendingApiHistory.length > 0 ? pendingApiHistory[0] : rawPendingRequest;
380714
+ apiHistoryOverride = [...apiHistory, finalPendingContent];
380715
+ this.getChat().setHistory(newHistory);
380716
+ displayContent = rawPendingRequest.parts || [];
380717
+ request = finalPendingContent.parts || [];
380591
380718
  } else {
380592
380719
  const newHistory = await this.agentHistoryProvider.manageHistory(this.getHistory(), signal);
380593
380720
  if (newHistory.length !== this.getHistory().length) {
@@ -380664,7 +380791,11 @@ var init_client4 = __esm({
380664
380791
  }
380665
380792
  this.currentSequenceModel = modelToUse;
380666
380793
  await this.setTools(modelToUse);
380667
- const resultStream = turn.run(modelConfigKey, request, signal, displayContent);
380794
+ const resultStream = turn.run(modelConfigKey, request, signal, {
380795
+ displayContent,
380796
+ role: LlmRole.MAIN,
380797
+ apiHistoryOverride
380798
+ });
380668
380799
  let isError = false;
380669
380800
  let loopDetectedAbort = false;
380670
380801
  let loopRecoverResult;
@@ -382416,12 +382547,13 @@ var init_message_bus = __esm({
382416
382547
  MessageBus = class _MessageBus extends EventEmitter7 {
382417
382548
  policyEngine;
382418
382549
  debug;
382550
+ isTrusted;
382419
382551
  listenerToAbortCleanup = /* @__PURE__ */ new WeakMap();
382420
- constructor(policyEngine, debug2 = false) {
382552
+ constructor(policyEngine, debug2 = false, isTrusted = true) {
382421
382553
  super();
382422
382554
  this.policyEngine = policyEngine;
382423
382555
  this.debug = debug2;
382424
- this.debug = debug2;
382556
+ this.isTrusted = isTrusted;
382425
382557
  }
382426
382558
  isValidMessage(message) {
382427
382559
  if (!message || !message.type) {
@@ -382437,13 +382569,15 @@ var init_message_bus = __esm({
382437
382569
  }
382438
382570
  /**
382439
382571
  * Derives a child message bus scoped to a specific subagent.
382572
+ * Derived buses are untrusted.
382440
382573
  */
382441
382574
  derive(subagentName) {
382442
- const bus = new _MessageBus(this.policyEngine, this.debug);
382575
+ const bus = new _MessageBus(this.policyEngine, this.debug, false);
382443
382576
  bus.publish = async (message) => {
382444
382577
  if (message.type === MessageBusType.TOOL_CONFIRMATION_REQUEST) {
382578
+ const { forcedDecision: _forcedDecision, subagent: _subagent, serverName: _serverName, toolAnnotations: _toolAnnotations, details: _details, ...otherFields } = message;
382445
382579
  return this.publish({
382446
- ...message,
382580
+ ...otherFields,
382447
382581
  subagent: message.subagent ? `${subagentName}/${message.subagent}` : subagentName
382448
382582
  });
382449
382583
  }
@@ -382469,7 +382603,7 @@ var init_message_bus = __esm({
382469
382603
  }
382470
382604
  if (message.type === MessageBusType.TOOL_CONFIRMATION_REQUEST) {
382471
382605
  const { decision: policyDecision } = await this.policyEngine.check(message.toolCall, message.serverName, message.toolAnnotations, message.subagent);
382472
- const decision = message.forcedDecision ?? policyDecision;
382606
+ const decision = (this.isTrusted ? message.forcedDecision : void 0) ?? policyDecision;
382473
382607
  switch (decision) {
382474
382608
  case PolicyDecision.ALLOW:
382475
382609
  this.emitMessage({
@@ -388212,12 +388346,12 @@ var require_src59 = __commonJS({
388212
388346
  function check2(path98, isFile, isDirectory) {
388213
388347
  log(`checking %s`, path98);
388214
388348
  try {
388215
- const stat6 = fs_1.statSync(path98);
388216
- if (stat6.isFile() && isFile) {
388349
+ const stat7 = fs_1.statSync(path98);
388350
+ if (stat7.isFile() && isFile) {
388217
388351
  log(`[OK] path represents a file`);
388218
388352
  return true;
388219
388353
  }
388220
- if (stat6.isDirectory() && isDirectory) {
388354
+ if (stat7.isDirectory() && isDirectory) {
388221
388355
  log(`[OK] path represents a directory`);
388222
388356
  return true;
388223
388357
  }
@@ -393173,7 +393307,7 @@ var init_esm18 = __esm({
393173
393307
  // packages/core/dist/src/services/gitService.js
393174
393308
  import * as fs68 from "node:fs/promises";
393175
393309
  import * as path77 from "node:path";
393176
- var SHADOW_REPO_AUTHOR_NAME, SHADOW_REPO_AUTHOR_EMAIL, SHADOW_REPO_GIT_OPTIONS, GitService;
393310
+ var SHADOW_REPO_AUTHOR_NAME, SHADOW_REPO_AUTHOR_EMAIL, SHADOW_REPO_UNSAFE_OPTIONS, SHADOW_REPO_GIT_OPTIONS, GitService;
393177
393311
  var init_gitService = __esm({
393178
393312
  "packages/core/dist/src/services/gitService.js"() {
393179
393313
  "use strict";
@@ -393184,29 +393318,30 @@ var init_gitService = __esm({
393184
393318
  init_environmentSanitization();
393185
393319
  SHADOW_REPO_AUTHOR_NAME = "Gemini CLI";
393186
393320
  SHADOW_REPO_AUTHOR_EMAIL = "gemini-cli@google.com";
393321
+ SHADOW_REPO_UNSAFE_OPTIONS = {
393322
+ allowUnsafeAlias: true,
393323
+ allowUnsafeAskPass: true,
393324
+ allowUnsafeConfigEnvCount: true,
393325
+ allowUnsafeConfigPaths: true,
393326
+ allowUnsafeCredentialHelper: true,
393327
+ allowUnsafeCustomBinary: true,
393328
+ allowUnsafeDiffExternal: true,
393329
+ allowUnsafeDiffTextConv: true,
393330
+ allowUnsafeEditor: true,
393331
+ allowUnsafeFilter: true,
393332
+ allowUnsafeFsMonitor: true,
393333
+ allowUnsafeGitProxy: true,
393334
+ allowUnsafeGpgProgram: true,
393335
+ allowUnsafeHooksPath: true,
393336
+ allowUnsafeMergeDriver: true,
393337
+ allowUnsafePack: true,
393338
+ allowUnsafePager: true,
393339
+ allowUnsafeProtocolOverride: true,
393340
+ allowUnsafeSshCommand: true,
393341
+ allowUnsafeTemplateDir: true
393342
+ };
393187
393343
  SHADOW_REPO_GIT_OPTIONS = {
393188
- unsafe: {
393189
- allowUnsafeAlias: true,
393190
- allowUnsafeAskPass: true,
393191
- allowUnsafeConfigEnvCount: true,
393192
- allowUnsafeConfigPaths: true,
393193
- allowUnsafeCredentialHelper: true,
393194
- allowUnsafeCustomBinary: true,
393195
- allowUnsafeDiffExternal: true,
393196
- allowUnsafeDiffTextConv: true,
393197
- allowUnsafeEditor: true,
393198
- allowUnsafeFilter: true,
393199
- allowUnsafeFsMonitor: true,
393200
- allowUnsafeGitProxy: true,
393201
- allowUnsafeGpgProgram: true,
393202
- allowUnsafeHooksPath: true,
393203
- allowUnsafeMergeDriver: true,
393204
- allowUnsafePack: true,
393205
- allowUnsafePager: true,
393206
- allowUnsafeProtocolOverride: true,
393207
- allowUnsafeSshCommand: true,
393208
- allowUnsafeTemplateDir: true
393209
- }
393344
+ unsafe: SHADOW_REPO_UNSAFE_OPTIONS
393210
393345
  };
393211
393346
  GitService = class _GitService {
393212
393347
  projectRoot;
@@ -396350,8 +396485,8 @@ async function loadJitSubdirectoryMemory(targetPath, trustedRoots, alreadyLoaded
396350
396485
  debugLogger.debug("[DEBUG] [MemoryDiscovery] Loading JIT memory for", resolvedTarget, `(Trusted root: ${bestRoot}, Ceiling: ${resolvedCeiling}${gitRoot ? " [git root]" : " [trusted root, no git]"})`);
396351
396486
  let startDir = resolvedTarget;
396352
396487
  try {
396353
- const stat6 = await fs71.stat(resolvedTarget);
396354
- if (stat6.isFile()) {
396488
+ const stat7 = await fs71.stat(resolvedTarget);
396489
+ if (stat7.isFile()) {
396355
396490
  startDir = path79.dirname(resolvedTarget);
396356
396491
  }
396357
396492
  } catch {
@@ -399406,6 +399541,66 @@ var init_admin_controls = __esm({
399406
399541
  }
399407
399542
  });
399408
399543
 
399544
+ // packages/core/dist/src/utils/path-validator.js
399545
+ function validatePath(pathStr) {
399546
+ if (!pathStr || typeof pathStr !== "string") {
399547
+ return { isValid: false, error: "Path must be a non-empty string." };
399548
+ }
399549
+ if (/[\n\r\0\t]/.test(pathStr)) {
399550
+ return {
399551
+ isValid: false,
399552
+ error: "Path contains invalid characters (newlines or control characters)."
399553
+ };
399554
+ }
399555
+ const logMarkerRegexes = [
399556
+ /(^|[/\\])AssertionError:/,
399557
+ /(^|[/\\])FAIL /,
399558
+ /(^|[/\\])✓ /,
399559
+ /(^|[/\\])× /,
399560
+ /(^|[/\\])TestingLibraryElementError:/
399561
+ ];
399562
+ for (const regex2 of logMarkerRegexes) {
399563
+ if (regex2.test(pathStr)) {
399564
+ return {
399565
+ isValid: false,
399566
+ error: "Path appears to be a misinterpreted log fragment."
399567
+ };
399568
+ }
399569
+ }
399570
+ if (pathStr.includes('"') || pathStr.includes("...")) {
399571
+ if (pathStr.length > 20) {
399572
+ return {
399573
+ isValid: false,
399574
+ error: "Path contains suspicious characters (double quotes or ellipses) and is too long to be a simple filename."
399575
+ };
399576
+ }
399577
+ }
399578
+ if (pathStr.length > MAX_PATH_LENGTH) {
399579
+ return {
399580
+ isValid: false,
399581
+ error: `Path is too long (maximum ${MAX_PATH_LENGTH} characters).`
399582
+ };
399583
+ }
399584
+ const components = pathStr.split(/[/\\]/);
399585
+ for (const component of components) {
399586
+ if (component.length > MAX_COMPONENT_LENGTH) {
399587
+ return {
399588
+ isValid: false,
399589
+ error: `Path component "${component.substring(0, 20)}..." is too long (maximum ${MAX_COMPONENT_LENGTH} characters).`
399590
+ };
399591
+ }
399592
+ }
399593
+ return { isValid: true };
399594
+ }
399595
+ var MAX_PATH_LENGTH, MAX_COMPONENT_LENGTH;
399596
+ var init_path_validator = __esm({
399597
+ "packages/core/dist/src/utils/path-validator.js"() {
399598
+ "use strict";
399599
+ MAX_PATH_LENGTH = 4096;
399600
+ MAX_COMPONENT_LENGTH = 255;
399601
+ }
399602
+ });
399603
+
399409
399604
  // packages/core/dist/src/config/injectionService.js
399410
399605
  var InjectionService;
399411
399606
  var init_injectionService = __esm({
@@ -401478,11 +401673,11 @@ var init_dist5 = __esm({
401478
401673
  return;
401479
401674
  }
401480
401675
  const decoder = new TextDecoder(), reader = body2.getReader();
401481
- let open4 = true;
401676
+ let open5 = true;
401482
401677
  do {
401483
401678
  const { done, value } = await reader.read();
401484
- value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open4 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
401485
- } while (open4);
401679
+ value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open5 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
401680
+ } while (open5);
401486
401681
  }), __privateAdd(this, _onFetchError, (err2) => {
401487
401682
  __privateSet(this, _controller, void 0), !(err2.name === "AbortError" || err2.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err2));
401488
401683
  }), __privateAdd(this, _onEvent, (event) => {
@@ -402068,13 +402263,13 @@ var init_sa_impersonation_provider = __esm({
402068
402263
  }
402069
402264
  });
402070
402265
 
402071
- // packages/core/dist/src/tools/xcode-mcp-fix-transport.js
402266
+ // packages/core/dist/src/tools/mcp-compliance-transport.js
402072
402267
  import { EventEmitter as EventEmitter9 } from "node:events";
402073
- var XcodeMcpBridgeFixTransport;
402074
- var init_xcode_mcp_fix_transport = __esm({
402075
- "packages/core/dist/src/tools/xcode-mcp-fix-transport.js"() {
402268
+ var McpComplianceTransport;
402269
+ var init_mcp_compliance_transport = __esm({
402270
+ "packages/core/dist/src/tools/mcp-compliance-transport.js"() {
402076
402271
  "use strict";
402077
- XcodeMcpBridgeFixTransport = class extends EventEmitter9 {
402272
+ McpComplianceTransport = class extends EventEmitter9 {
402078
402273
  transport;
402079
402274
  constructor(transport) {
402080
402275
  super();
@@ -402784,7 +402979,8 @@ async function createTransportWithOAuth(mcpServerName, mcpServerConfig, accessTo
402784
402979
  const transportOptions = {
402785
402980
  requestInit: createTransportRequestInit(mcpServerConfig, headers, cliConfig.sanitizationConfig)
402786
402981
  };
402787
- return createUrlTransport(mcpServerName, mcpServerConfig, transportOptions);
402982
+ const transport = createUrlTransport(mcpServerName, mcpServerConfig, transportOptions);
402983
+ return transport ? new McpComplianceTransport(transport) : null;
402788
402984
  } catch (error2) {
402789
402985
  cliConfig.emitMcpDiagnostic("error", `Failed to create OAuth transport for server '${mcpServerName}': ${getErrorMessage(error2)}`, error2, mcpServerName);
402790
402986
  return null;
@@ -403237,7 +403433,7 @@ async function createTransport(mcpServerName, mcpServerConfig, debugMode, cliCon
403237
403433
  requestInit: createTransportRequestInit(mcpServerConfig, headers, cliConfig.sanitizationConfig),
403238
403434
  authProvider
403239
403435
  };
403240
- return createUrlTransport(mcpServerName, mcpServerConfig, transportOptions);
403436
+ return new McpComplianceTransport(createUrlTransport(mcpServerName, mcpServerConfig, transportOptions));
403241
403437
  }
403242
403438
  if (mcpServerConfig.command) {
403243
403439
  if (!cliConfig.isTrustedFolder()) {
@@ -403263,21 +403459,15 @@ async function createTransport(mcpServerName, mcpServerConfig, debugMode, cliCon
403263
403459
  finalEnv[key] = expandEnvVars(value, expansionEnv);
403264
403460
  }
403265
403461
  }
403266
- let transport = new StdioClientTransport({
403462
+ const transport = new McpComplianceTransport(new StdioClientTransport({
403267
403463
  command: mcpServerConfig.command,
403268
403464
  args: mcpServerConfig.args || [],
403269
403465
  env: finalEnv,
403270
403466
  cwd: mcpServerConfig.cwd,
403271
403467
  stderr: "pipe"
403272
- });
403273
- if (mcpServerConfig.command === "xcrun" && mcpServerConfig.args?.includes("mcpbridge")) {
403274
- transport = new XcodeMcpBridgeFixTransport(transport);
403275
- }
403468
+ }));
403276
403469
  if (debugMode) {
403277
- const underlyingTransport = transport instanceof XcodeMcpBridgeFixTransport ? (
403278
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-type-assertion
403279
- transport.transport
403280
- ) : transport;
403470
+ const underlyingTransport = transport instanceof McpComplianceTransport ? transport.transport : transport;
403281
403471
  if (underlyingTransport instanceof StdioClientTransport && underlyingTransport.stderr) {
403282
403472
  underlyingTransport.stderr.on("data", (data) => {
403283
403473
  const stderrStr = data.toString().trim();
@@ -403327,7 +403517,7 @@ var init_mcp_client = __esm({
403327
403517
  init_google_auth_provider();
403328
403518
  init_sa_impersonation_provider();
403329
403519
  init_mcp_tool();
403330
- init_xcode_mcp_fix_transport();
403520
+ init_mcp_compliance_transport();
403331
403521
  init_oauth_token_storage();
403332
403522
  init_oauth_provider();
403333
403523
  init_stored_token_provider();
@@ -403859,7 +404049,7 @@ var init_mcp_client = __esm({
403859
404049
  });
403860
404050
 
403861
404051
  // packages/core/dist/src/tools/mcp-client-manager.js
403862
- import { createHash as createHash16 } from "node:crypto";
404052
+ import { createHash as createHash17 } from "node:crypto";
403863
404053
  var McpClientManager;
403864
404054
  var init_mcp_client_manager = __esm({
403865
404055
  "packages/core/dist/src/tools/mcp-client-manager.js"() {
@@ -404076,7 +404266,7 @@ var init_mcp_client_manager = __esm({
404076
404266
  config: rest,
404077
404267
  extensionId: extension?.id
404078
404268
  };
404079
- return createHash16("sha256").update(stableStringify(keyData)).digest("hex");
404269
+ return createHash17("sha256").update(stableStringify(keyData)).digest("hex");
404080
404270
  }
404081
404271
  /**
404082
404272
  * Merges two MCP configurations. The second configuration (override)
@@ -409085,6 +409275,7 @@ var init_config4 = __esm({
409085
409275
  init_startupProfiler();
409086
409276
  init_admin_controls();
409087
409277
  init_paths();
409278
+ init_path_validator();
409088
409279
  init_injectionService();
409089
409280
  init_executionLifecycleService();
409090
409281
  init_config3();
@@ -409250,6 +409441,7 @@ var init_config4 = __esm({
409250
409441
  folderTrust;
409251
409442
  ideMode;
409252
409443
  _activeModel;
409444
+ fallbackOverrides = /* @__PURE__ */ new Map();
409253
409445
  maxSessionTurns;
409254
409446
  listSessions;
409255
409447
  deleteSession;
@@ -409777,6 +409969,8 @@ var init_config4 = __esm({
409777
409969
  }
409778
409970
  async refreshAuth(authMethod, apiKey, baseUrl, customHeaders) {
409779
409971
  this.modelAvailabilityService.reset();
409972
+ this.fallbackOverrides.clear();
409973
+ this.modelConfigService.clearRuntimeOverrides();
409780
409974
  if (this.contentGeneratorConfig?.authType === AuthType2.USE_GEMINI && authMethod !== AuthType2.USE_GEMINI) {
409781
409975
  this._geminiClient.stripThoughtsFromHistory();
409782
409976
  }
@@ -409946,6 +410140,8 @@ var init_config4 = __esm({
409946
410140
  this._sessionId = sessionId;
409947
410141
  this.storage.setSessionId(sessionId);
409948
410142
  this.trackerService = void 0;
410143
+ this.fallbackOverrides.clear();
410144
+ this.modelConfigService.clearRuntimeOverrides();
409949
410145
  this.approvedPlanPath = void 0;
409950
410146
  this.topicState.reset();
409951
410147
  this.skillManager.reset();
@@ -410021,13 +410217,34 @@ var init_config4 = __esm({
410021
410217
  }
410022
410218
  this.modelAvailabilityService.reset();
410023
410219
  }
410024
- activateFallbackMode(model) {
410025
- this.setModel(model, true);
410220
+ activateFallbackMode(model, failedModel) {
410221
+ if (this.getActiveModel() !== model) {
410222
+ this.setModel(model, true);
410223
+ }
410224
+ if (failedModel) {
410225
+ for (const [source, target] of this.fallbackOverrides.entries()) {
410226
+ if (target === failedModel) {
410227
+ this.fallbackOverrides.set(source, model);
410228
+ this.modelConfigService.registerRuntimeModelOverride({
410229
+ match: { model: source },
410230
+ modelConfig: { model }
410231
+ });
410232
+ }
410233
+ }
410234
+ this.fallbackOverrides.set(failedModel, model);
410235
+ this.modelConfigService.registerRuntimeModelOverride({
410236
+ match: { model: failedModel },
410237
+ modelConfig: { model }
410238
+ });
410239
+ }
410026
410240
  const authType = this.getContentGeneratorConfig()?.authType;
410027
410241
  if (authType) {
410028
410242
  logFlashFallback(this, new FlashFallbackEvent(authType));
410029
410243
  }
410030
410244
  }
410245
+ getFallbackOverride(model) {
410246
+ return this.fallbackOverrides.get(model);
410247
+ }
410031
410248
  getActiveModel() {
410032
410249
  return this._activeModel ?? this.model;
410033
410250
  }
@@ -410972,6 +411189,10 @@ ${sections.join("\n")}
410972
411189
  * @returns An error message string if the path is disallowed, null otherwise.
410973
411190
  */
410974
411191
  validatePathAccess(absolutePath, checkType = "write") {
411192
+ const pathValidation = validatePath(absolutePath);
411193
+ if (!pathValidation.isValid) {
411194
+ return `Invalid path: ${pathValidation.error}`;
411195
+ }
410975
411196
  if (checkType === "write" && hasScopedAutoMemoryExtractionWriteAccess()) {
410976
411197
  const resolvedPath = resolveToRealPath(absolutePath);
410977
411198
  if (this.isScopedAutoMemoryExtractionWritePathAllowed(absolutePath, resolvedPath)) {
@@ -412881,6 +413102,16 @@ var init_exitCodes = __esm({
412881
413102
  }
412882
413103
  });
412883
413104
 
413105
+ // packages/core/dist/src/utils/atCommandUtils.js
413106
+ var init_atCommandUtils = __esm({
413107
+ "packages/core/dist/src/utils/atCommandUtils.js"() {
413108
+ "use strict";
413109
+ init_path_validator();
413110
+ init_config4();
413111
+ init_errors2();
413112
+ }
413113
+ });
413114
+
412884
413115
  // packages/core/dist/src/utils/tool-visibility.js
412885
413116
  var init_tool_visibility = __esm({
412886
413117
  "packages/core/dist/src/utils/tool-visibility.js"() {
@@ -413867,16 +414098,16 @@ var require_parse11 = __commonJS({
413867
414098
  const analysis = analyzeRepeatedExtglob(body2, opts);
413868
414099
  if ((token2.type === "plus" || token2.type === "star") && analysis.risky) {
413869
414100
  const safeOutput = analysis.safeOutput ? (token2.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0;
413870
- const open4 = tokens[token2.tokensIndex];
413871
- open4.type = "text";
413872
- open4.value = literal3;
413873
- open4.output = safeOutput || utils.escapeRegex(literal3);
414101
+ const open5 = tokens[token2.tokensIndex];
414102
+ open5.type = "text";
414103
+ open5.value = literal3;
414104
+ open5.output = safeOutput || utils.escapeRegex(literal3);
413874
414105
  for (let i4 = token2.tokensIndex + 1; i4 < tokens.length; i4++) {
413875
414106
  tokens[i4].value = "";
413876
414107
  tokens[i4].output = "";
413877
414108
  delete tokens[i4].suffix;
413878
414109
  }
413879
- state.output = token2.output + open4.output;
414110
+ state.output = token2.output + open5.output;
413880
414111
  state.backtrack = true;
413881
414112
  push({ type: "paren", extglob: true, value, output: "" });
413882
414113
  decrement("parens");
@@ -414096,15 +414327,15 @@ var require_parse11 = __commonJS({
414096
414327
  }
414097
414328
  if (value === "{" && opts.nobrace !== true) {
414098
414329
  increment("braces");
414099
- const open4 = {
414330
+ const open5 = {
414100
414331
  type: "brace",
414101
414332
  value,
414102
414333
  output: "(",
414103
414334
  outputIndex: state.output.length,
414104
414335
  tokensIndex: state.tokens.length
414105
414336
  };
414106
- braces.push(open4);
414107
- push(open4);
414337
+ braces.push(open5);
414338
+ push(open5);
414108
414339
  continue;
414109
414340
  }
414110
414341
  if (value === "}") {
@@ -414869,12 +415100,12 @@ var require_resolve_symlink = __commonJS({
414869
415100
  fs_1.default.realpath(path98, (error2, resolvedPath) => {
414870
415101
  if (error2)
414871
415102
  return queue.dequeue(suppressErrors ? null : error2, state);
414872
- fs_1.default.stat(resolvedPath, (error3, stat6) => {
415103
+ fs_1.default.stat(resolvedPath, (error3, stat7) => {
414873
415104
  if (error3)
414874
415105
  return queue.dequeue(suppressErrors ? null : error3, state);
414875
- if (stat6.isDirectory() && isRecursive(path98, resolvedPath, state))
415106
+ if (stat7.isDirectory() && isRecursive(path98, resolvedPath, state))
414876
415107
  return queue.dequeue(null, state);
414877
- callback(stat6, resolvedPath);
415108
+ callback(stat7, resolvedPath);
414878
415109
  queue.dequeue(null, state);
414879
415110
  });
414880
415111
  });
@@ -414884,10 +415115,10 @@ var require_resolve_symlink = __commonJS({
414884
415115
  queue.enqueue();
414885
415116
  try {
414886
415117
  const resolvedPath = fs_1.default.realpathSync(path98);
414887
- const stat6 = fs_1.default.statSync(resolvedPath);
414888
- if (stat6.isDirectory() && isRecursive(path98, resolvedPath, state))
415118
+ const stat7 = fs_1.default.statSync(resolvedPath);
415119
+ if (stat7.isDirectory() && isRecursive(path98, resolvedPath, state))
414889
415120
  return;
414890
- callback(stat6, resolvedPath);
415121
+ callback(stat7, resolvedPath);
414891
415122
  } catch (e3) {
414892
415123
  if (!suppressErrors)
414893
415124
  throw e3;
@@ -415186,8 +415417,8 @@ var require_walker = __commonJS({
415186
415417
  this.walkDirectory(this.state, path98, path98, depth - 1, this.walk);
415187
415418
  } else if (this.resolveSymlink && entry.isSymbolicLink()) {
415188
415419
  let path98 = joinPath.joinPathWithBasePath(entry.name, directoryPath);
415189
- this.resolveSymlink(path98, this.state, (stat6, resolvedPath) => {
415190
- if (stat6.isDirectory()) {
415420
+ this.resolveSymlink(path98, this.state, (stat7, resolvedPath) => {
415421
+ if (stat7.isDirectory()) {
415191
415422
  resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options);
415192
415423
  if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path98 + pathSeparator))
415193
415424
  return;
@@ -415559,17 +415790,6 @@ var init_apiConversionUtils = __esm({
415559
415790
  }
415560
415791
  });
415561
415792
 
415562
- // packages/core/dist/src/utils/sessionUtils.js
415563
- var init_sessionUtils = __esm({
415564
- "packages/core/dist/src/utils/sessionUtils.js"() {
415565
- "use strict";
415566
- init_node();
415567
- init_chatRecordingService();
415568
- init_geminiRequest();
415569
- init_agentChatHistory();
415570
- }
415571
- });
415572
-
415573
415793
  // node_modules/strip-json-comments/index.js
415574
415794
  var require_strip_json_comments = __commonJS({
415575
415795
  "node_modules/strip-json-comments/index.js"(exports2, module2) {
@@ -416360,6 +416580,8 @@ var init_src2 = __esm({
416360
416580
  init_planUtils();
416361
416581
  init_approvalModeUtils();
416362
416582
  init_fileDiffUtils();
416583
+ init_path_validator();
416584
+ init_atCommandUtils();
416363
416585
  init_retry();
416364
416586
  init_shell_utils();
416365
416587
  init_types2();