@google/gemini-cli-a2a-server 0.12.0-nightly.20251023.c4c0c0d1 → 0.12.0-nightly.20251027.cb0947c5

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.
@@ -6344,7 +6344,7 @@ var require_diagnostics = __commonJS({
6344
6344
  function write2() {
6345
6345
  logger6.apply(logger6, arguments);
6346
6346
  }
6347
- function process23(message) {
6347
+ function process25(message) {
6348
6348
  for (var i3 = 0; i3 < modifiers.length; i3++) {
6349
6349
  message = modifiers[i3].apply(modifiers[i3], arguments);
6350
6350
  }
@@ -6371,7 +6371,7 @@ var require_diagnostics = __commonJS({
6371
6371
  function yep(options2) {
6372
6372
  function diagnostics() {
6373
6373
  var args2 = Array.prototype.slice.call(arguments, 0);
6374
- write2.call(write2, options2, process23(args2, options2));
6374
+ write2.call(write2, options2, process25(args2, options2));
6375
6375
  return true;
6376
6376
  }
6377
6377
  options2.enabled = true;
@@ -6383,7 +6383,7 @@ var require_diagnostics = __commonJS({
6383
6383
  module2.exports = function create3(diagnostics) {
6384
6384
  diagnostics.introduce = introduce;
6385
6385
  diagnostics.enabled = enabled;
6386
- diagnostics.process = process23;
6386
+ diagnostics.process = process25;
6387
6387
  diagnostics.modify = modify;
6388
6388
  diagnostics.write = write2;
6389
6389
  diagnostics.nope = nope;
@@ -52323,7 +52323,7 @@ var require_logging_utils = __commonJS({
52323
52323
  exports2.setBackend = setBackend;
52324
52324
  exports2.log = log;
52325
52325
  var node_events_1 = __require("node:events");
52326
- var process23 = __importStar(__require("node:process"));
52326
+ var process25 = __importStar(__require("node:process"));
52327
52327
  var util4 = __importStar(__require("node:util"));
52328
52328
  var colours_1 = require_colours();
52329
52329
  var LogSeverity;
@@ -52374,7 +52374,7 @@ var require_logging_utils = __commonJS({
52374
52374
  this.cached = /* @__PURE__ */ new Map();
52375
52375
  this.filters = [];
52376
52376
  this.filtersSet = false;
52377
- let nodeFlag = (_a3 = process23.env[exports2.env.nodeEnables]) !== null && _a3 !== void 0 ? _a3 : "*";
52377
+ let nodeFlag = (_a3 = process25.env[exports2.env.nodeEnables]) !== null && _a3 !== void 0 ? _a3 : "*";
52378
52378
  if (nodeFlag === "all") {
52379
52379
  nodeFlag = "*";
52380
52380
  }
@@ -52414,7 +52414,7 @@ var require_logging_utils = __commonJS({
52414
52414
  return (fields, ...args2) => {
52415
52415
  var _a3;
52416
52416
  const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
52417
- const pid = `${colours_1.Colours.yellow}${process23.pid}${colours_1.Colours.reset}`;
52417
+ const pid = `${colours_1.Colours.yellow}${process25.pid}${colours_1.Colours.reset}`;
52418
52418
  let level;
52419
52419
  switch (fields.severity) {
52420
52420
  case LogSeverity.ERROR:
@@ -52462,8 +52462,8 @@ var require_logging_utils = __commonJS({
52462
52462
  }
52463
52463
  setFilters() {
52464
52464
  var _a3;
52465
- const existingFilters = (_a3 = process23.env["NODE_DEBUG"]) !== null && _a3 !== void 0 ? _a3 : "";
52466
- process23.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`;
52465
+ const existingFilters = (_a3 = process25.env["NODE_DEBUG"]) !== null && _a3 !== void 0 ? _a3 : "";
52466
+ process25.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`;
52467
52467
  }
52468
52468
  };
52469
52469
  function getDebugBackend(debugPkg) {
@@ -52509,7 +52509,7 @@ var require_logging_utils = __commonJS({
52509
52509
  loggerCache.clear();
52510
52510
  }
52511
52511
  function log(namespace, parent) {
52512
- const enablesFlag = process23.env[exports2.env.nodeEnables];
52512
+ const enablesFlag = process25.env[exports2.env.nodeEnables];
52513
52513
  if (!enablesFlag) {
52514
52514
  return exports2.placeholder;
52515
52515
  }
@@ -57931,7 +57931,7 @@ var require_googleauth = __commonJS({
57931
57931
  NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",
57932
57932
  NO_UNIVERSE_DOMAIN_FOUND: "Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"
57933
57933
  };
57934
- var GoogleAuth7 = class {
57934
+ var GoogleAuth8 = class {
57935
57935
  // Note: this properly is only public to satisfy unit tests.
57936
57936
  // https://github.com/Microsoft/TypeScript/issues/5228
57937
57937
  get isGCE() {
@@ -58580,7 +58580,7 @@ var require_googleauth = __commonJS({
58580
58580
  return res.data.signedBlob;
58581
58581
  }
58582
58582
  };
58583
- exports2.GoogleAuth = GoogleAuth7;
58583
+ exports2.GoogleAuth = GoogleAuth8;
58584
58584
  _GoogleAuth_pendingAuthClient = /* @__PURE__ */ new WeakMap(), _GoogleAuth_instances = /* @__PURE__ */ new WeakSet(), _GoogleAuth_prepareAndCacheClient = async function _GoogleAuth_prepareAndCacheClient2(credential, quotaProjectIdOverride = process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || null) {
58585
58585
  const projectId = await this.getProjectIdOptional();
58586
58586
  if (quotaProjectIdOverride) {
@@ -58605,7 +58605,7 @@ var require_googleauth = __commonJS({
58605
58605
  return credential;
58606
58606
  }
58607
58607
  };
58608
- GoogleAuth7.DefaultTransporter = transporters_1.DefaultTransporter;
58608
+ GoogleAuth8.DefaultTransporter = transporters_1.DefaultTransporter;
58609
58609
  }
58610
58610
  });
58611
58611
 
@@ -65173,11 +65173,11 @@ var require_copy = __commonJS({
65173
65173
  if (!destStat) {
65174
65174
  await fs60.mkdir(dest);
65175
65175
  }
65176
- const promises2 = [];
65176
+ const promises3 = [];
65177
65177
  for await (const item of await fs60.opendir(src)) {
65178
65178
  const srcItem = path64.join(src, item.name);
65179
65179
  const destItem = path64.join(dest, item.name);
65180
- promises2.push(
65180
+ promises3.push(
65181
65181
  runFilter(srcItem, destItem, opts).then((include) => {
65182
65182
  if (include) {
65183
65183
  return stat2.checkPaths(srcItem, destItem, "copy", opts).then(({ destStat: destStat2 }) => {
@@ -65187,7 +65187,7 @@ var require_copy = __commonJS({
65187
65187
  })
65188
65188
  );
65189
65189
  }
65190
- await Promise.all(promises2);
65190
+ await Promise.all(promises3);
65191
65191
  if (!destStat) {
65192
65192
  await fs60.chmod(dest, srcStat.mode);
65193
65193
  }
@@ -70088,6 +70088,62 @@ var init_base_token_storage = __esm({
70088
70088
  }
70089
70089
  });
70090
70090
 
70091
+ // packages/core/dist/src/utils/events.js
70092
+ import { EventEmitter as EventEmitter4 } from "node:events";
70093
+ var CoreEvent, CoreEventEmitter, coreEvents;
70094
+ var init_events = __esm({
70095
+ "packages/core/dist/src/utils/events.js"() {
70096
+ "use strict";
70097
+ (function(CoreEvent2) {
70098
+ CoreEvent2["UserFeedback"] = "user-feedback";
70099
+ })(CoreEvent || (CoreEvent = {}));
70100
+ CoreEventEmitter = class _CoreEventEmitter extends EventEmitter4 {
70101
+ _feedbackBacklog = [];
70102
+ static MAX_BACKLOG_SIZE = 1e4;
70103
+ constructor() {
70104
+ super();
70105
+ }
70106
+ /**
70107
+ * Sends actionable feedback to the user.
70108
+ * Buffers automatically if the UI hasn't subscribed yet.
70109
+ */
70110
+ emitFeedback(severity, message, error) {
70111
+ const payload = { severity, message, error };
70112
+ if (this.listenerCount(CoreEvent.UserFeedback) === 0) {
70113
+ if (this._feedbackBacklog.length >= _CoreEventEmitter.MAX_BACKLOG_SIZE) {
70114
+ this._feedbackBacklog.shift();
70115
+ }
70116
+ this._feedbackBacklog.push(payload);
70117
+ } else {
70118
+ this.emit(CoreEvent.UserFeedback, payload);
70119
+ }
70120
+ }
70121
+ /**
70122
+ * Flushes buffered messages. Call this immediately after primary UI listener
70123
+ * subscribes.
70124
+ */
70125
+ drainFeedbackBacklog() {
70126
+ const backlog = [...this._feedbackBacklog];
70127
+ this._feedbackBacklog.length = 0;
70128
+ for (const payload of backlog) {
70129
+ this.emit(CoreEvent.UserFeedback, payload);
70130
+ }
70131
+ }
70132
+ on(event, listener) {
70133
+ return super.on(event, listener);
70134
+ }
70135
+ off(event, listener) {
70136
+ return super.off(event, listener);
70137
+ }
70138
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
70139
+ emit(event, ...args2) {
70140
+ return super.emit(event, ...args2);
70141
+ }
70142
+ };
70143
+ coreEvents = new CoreEventEmitter();
70144
+ }
70145
+ });
70146
+
70091
70147
  // packages/core/dist/src/mcp/token-storage/keychain-token-storage.js
70092
70148
  var keychain_token_storage_exports = {};
70093
70149
  __export(keychain_token_storage_exports, {
@@ -70099,6 +70155,7 @@ var init_keychain_token_storage = __esm({
70099
70155
  "packages/core/dist/src/mcp/token-storage/keychain-token-storage.js"() {
70100
70156
  "use strict";
70101
70157
  init_base_token_storage();
70158
+ init_events();
70102
70159
  KEYCHAIN_TEST_PREFIX = "__keychain_test__";
70103
70160
  KeychainTokenStorage = class extends BaseTokenStorage {
70104
70161
  keychainAvailable = null;
@@ -70114,7 +70171,7 @@ var init_keychain_token_storage = __esm({
70114
70171
  const module2 = await import(moduleName2);
70115
70172
  this.keytarModule = module2.default || module2;
70116
70173
  } catch (error) {
70117
- console.error(error);
70174
+ coreEvents.emitFeedback("error", "Failed to load 'keytar' module", error);
70118
70175
  }
70119
70176
  return this.keytarModule;
70120
70177
  }
@@ -70187,7 +70244,7 @@ var init_keychain_token_storage = __esm({
70187
70244
  const credentials = await keytar.findCredentials(this.serviceName);
70188
70245
  return credentials.filter((cred) => !cred.account.startsWith(KEYCHAIN_TEST_PREFIX)).map((cred) => cred.account);
70189
70246
  } catch (error) {
70190
- console.error("Failed to list servers from keychain:", error);
70247
+ coreEvents.emitFeedback("error", "Failed to list servers from keychain", error);
70191
70248
  return [];
70192
70249
  }
70193
70250
  }
@@ -70209,11 +70266,11 @@ var init_keychain_token_storage = __esm({
70209
70266
  result.set(cred.account, data);
70210
70267
  }
70211
70268
  } catch (error) {
70212
- console.error(`Failed to parse credentials for ${cred.account}:`, error);
70269
+ coreEvents.emitFeedback("error", `Failed to parse credentials for ${cred.account}`, error);
70213
70270
  }
70214
70271
  }
70215
70272
  } catch (error) {
70216
- console.error("Failed to get all credentials from keychain:", error);
70273
+ coreEvents.emitFeedback("error", "Failed to get all credentials from keychain", error);
70217
70274
  }
70218
70275
  return result;
70219
70276
  }
@@ -95890,7 +95947,7 @@ var require_root = __commonJS({
95890
95947
  }
95891
95948
  return null;
95892
95949
  }
95893
- function process23(filename2, source) {
95950
+ function process25(filename2, source) {
95894
95951
  try {
95895
95952
  if (util4.isString(source) && source.charAt(0) === "{")
95896
95953
  source = JSON.parse(source);
@@ -95925,12 +95982,12 @@ var require_root = __commonJS({
95925
95982
  self2.files.push(filename2);
95926
95983
  if (filename2 in common2) {
95927
95984
  if (sync2) {
95928
- process23(filename2, common2[filename2]);
95985
+ process25(filename2, common2[filename2]);
95929
95986
  } else {
95930
95987
  ++queued;
95931
95988
  setTimeout(function() {
95932
95989
  --queued;
95933
- process23(filename2, common2[filename2]);
95990
+ process25(filename2, common2[filename2]);
95934
95991
  });
95935
95992
  }
95936
95993
  return;
@@ -95944,7 +96001,7 @@ var require_root = __commonJS({
95944
96001
  finish(err2);
95945
96002
  return;
95946
96003
  }
95947
- process23(filename2, source);
96004
+ process25(filename2, source);
95948
96005
  } else {
95949
96006
  ++queued;
95950
96007
  self2.fetch(filename2, function(err2, source2) {
@@ -95959,7 +96016,7 @@ var require_root = __commonJS({
95959
96016
  finish(null, self2);
95960
96017
  return;
95961
96018
  }
95962
- process23(filename2, source2);
96019
+ process25(filename2, source2);
95963
96020
  });
95964
96021
  }
95965
96022
  }
@@ -120331,8 +120388,8 @@ var require_utils12 = __commonJS({
120331
120388
  });
120332
120389
  }
120333
120390
  exports2.callWithTimeout = callWithTimeout;
120334
- async function PromiseAllSettled(promises2) {
120335
- return Promise.all(promises2.map(async (p) => {
120391
+ async function PromiseAllSettled(promises3) {
120392
+ return Promise.all(promises3.map(async (p) => {
120336
120393
  try {
120337
120394
  const ret = await p;
120338
120395
  return {
@@ -122684,13 +122741,13 @@ var require_getMachineId_win = __commonJS({
122684
122741
  "use strict";
122685
122742
  Object.defineProperty(exports2, "__esModule", { value: true });
122686
122743
  exports2.getMachineId = void 0;
122687
- var process23 = __require("process");
122744
+ var process25 = __require("process");
122688
122745
  var execAsync_1 = require_execAsync();
122689
122746
  var api_1 = (init_esm2(), __toCommonJS(esm_exports5));
122690
122747
  async function getMachineId() {
122691
122748
  const args2 = "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid";
122692
122749
  let command = "%windir%\\System32\\REG.exe";
122693
- if (process23.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process23.env) {
122750
+ if (process25.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process25.env) {
122694
122751
  command = "%windir%\\sysnative\\cmd.exe /c " + command;
122695
122752
  }
122696
122753
  try {
@@ -122729,11 +122786,11 @@ var require_getMachineId = __commonJS({
122729
122786
  "use strict";
122730
122787
  Object.defineProperty(exports2, "__esModule", { value: true });
122731
122788
  exports2.getMachineId = void 0;
122732
- var process23 = __require("process");
122789
+ var process25 = __require("process");
122733
122790
  var getMachineIdImpl;
122734
122791
  async function getMachineId() {
122735
122792
  if (!getMachineIdImpl) {
122736
- switch (process23.platform) {
122793
+ switch (process25.platform) {
122737
122794
  case "darwin":
122738
122795
  getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_darwin()))).getMachineId;
122739
122796
  break;
@@ -126224,12 +126281,12 @@ var require_BatchLogRecordProcessorBase = __commonJS({
126224
126281
  * */
126225
126282
  _flushAll() {
126226
126283
  return new Promise((resolve13, reject) => {
126227
- const promises2 = [];
126284
+ const promises3 = [];
126228
126285
  const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
126229
126286
  for (let i3 = 0; i3 < batchCount; i3++) {
126230
- promises2.push(this._flushOneBatch());
126287
+ promises3.push(this._flushOneBatch());
126231
126288
  }
126232
- Promise.all(promises2).then(() => {
126289
+ Promise.all(promises3).then(() => {
126233
126290
  resolve13();
126234
126291
  }).catch(reject);
126235
126292
  });
@@ -127291,12 +127348,12 @@ var require_BatchSpanProcessorBase = __commonJS({
127291
127348
  * */
127292
127349
  _flushAll() {
127293
127350
  return new Promise((resolve13, reject) => {
127294
- const promises2 = [];
127351
+ const promises3 = [];
127295
127352
  const count2 = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
127296
127353
  for (let i3 = 0, j = count2; i3 < j; i3++) {
127297
- promises2.push(this._flushOneBatch());
127354
+ promises3.push(this._flushOneBatch());
127298
127355
  }
127299
- Promise.all(promises2).then(() => {
127356
+ Promise.all(promises3).then(() => {
127300
127357
  resolve13();
127301
127358
  }).catch(reject);
127302
127359
  });
@@ -127607,12 +127664,12 @@ var require_MultiSpanProcessor = __commonJS({
127607
127664
  this._spanProcessors = _spanProcessors;
127608
127665
  }
127609
127666
  forceFlush() {
127610
- const promises2 = [];
127667
+ const promises3 = [];
127611
127668
  for (const spanProcessor of this._spanProcessors) {
127612
- promises2.push(spanProcessor.forceFlush());
127669
+ promises3.push(spanProcessor.forceFlush());
127613
127670
  }
127614
127671
  return new Promise((resolve13) => {
127615
- Promise.all(promises2).then(() => {
127672
+ Promise.all(promises3).then(() => {
127616
127673
  resolve13();
127617
127674
  }).catch((error) => {
127618
127675
  (0, core_1.globalErrorHandler)(error || new Error("MultiSpanProcessor: forceFlush failed"));
@@ -127631,12 +127688,12 @@ var require_MultiSpanProcessor = __commonJS({
127631
127688
  }
127632
127689
  }
127633
127690
  shutdown() {
127634
- const promises2 = [];
127691
+ const promises3 = [];
127635
127692
  for (const spanProcessor of this._spanProcessors) {
127636
- promises2.push(spanProcessor.shutdown());
127693
+ promises3.push(spanProcessor.shutdown());
127637
127694
  }
127638
127695
  return new Promise((resolve13, reject) => {
127639
- Promise.all(promises2).then(() => {
127696
+ Promise.all(promises3).then(() => {
127640
127697
  resolve13();
127641
127698
  }, reject);
127642
127699
  });
@@ -127691,7 +127748,7 @@ var require_BasicTracerProvider = __commonJS({
127691
127748
  }
127692
127749
  forceFlush() {
127693
127750
  const timeout = this._config.forceFlushTimeoutMillis;
127694
- const promises2 = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
127751
+ const promises3 = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
127695
127752
  return new Promise((resolve13) => {
127696
127753
  let state;
127697
127754
  const timeoutInterval = setTimeout(() => {
@@ -127712,7 +127769,7 @@ var require_BasicTracerProvider = __commonJS({
127712
127769
  });
127713
127770
  });
127714
127771
  return new Promise((resolve13, reject) => {
127715
- Promise.all(promises2).then((results) => {
127772
+ Promise.all(promises3).then((results) => {
127716
127773
  const errors = results.filter((result) => result !== ForceFlushState.resolved);
127717
127774
  if (errors.length > 0) {
127718
127775
  reject(errors);
@@ -132658,17 +132715,17 @@ var require_sdk = __commonJS({
132658
132715
  }
132659
132716
  }
132660
132717
  shutdown() {
132661
- const promises2 = [];
132718
+ const promises3 = [];
132662
132719
  if (this._tracerProvider) {
132663
- promises2.push(this._tracerProvider.shutdown());
132720
+ promises3.push(this._tracerProvider.shutdown());
132664
132721
  }
132665
132722
  if (this._loggerProvider) {
132666
- promises2.push(this._loggerProvider.shutdown());
132723
+ promises3.push(this._loggerProvider.shutdown());
132667
132724
  }
132668
132725
  if (this._meterProvider) {
132669
- promises2.push(this._meterProvider.shutdown());
132726
+ promises3.push(this._meterProvider.shutdown());
132670
132727
  }
132671
- return Promise.all(promises2).then(() => {
132728
+ return Promise.all(promises3).then(() => {
132672
132729
  });
132673
132730
  }
132674
132731
  configureLoggerProviderFromEnv() {
@@ -139548,10 +139605,10 @@ var require_http22 = __commonJS({
139548
139605
  var extend = require_extend();
139549
139606
  var stream_1 = __require("stream");
139550
139607
  var util4 = __require("util");
139551
- var process23 = __require("process");
139608
+ var process25 = __require("process");
139552
139609
  var common_1 = require_common3();
139553
139610
  var { HTTP2_HEADER_CONTENT_ENCODING, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http22.constants;
139554
- var DEBUG = !!process23.env.HTTP2_DEBUG;
139611
+ var DEBUG = !!process25.env.HTTP2_DEBUG;
139555
139612
  exports2.sessions = {};
139556
139613
  async function request3(config2) {
139557
139614
  const opts = extend(true, {}, config2);
@@ -212963,9 +213020,9 @@ var require_src56 = __commonJS({
212963
213020
  const isArray2 = Array.isArray(key);
212964
213021
  const keyPrefixed = isArray2 ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);
212965
213022
  if (isArray2 && store.getMany === void 0) {
212966
- const promises2 = [];
213023
+ const promises3 = [];
212967
213024
  for (const key2 of keyPrefixed) {
212968
- promises2.push(
213025
+ promises3.push(
212969
213026
  Promise.resolve().then(() => store.get(key2)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => {
212970
213027
  if (data === void 0 || data === null) {
212971
213028
  return void 0;
@@ -212977,7 +213034,7 @@ var require_src56 = __commonJS({
212977
213034
  })
212978
213035
  );
212979
213036
  }
212980
- return Promise.allSettled(promises2).then((values) => {
213037
+ return Promise.allSettled(promises3).then((values) => {
212981
213038
  const data = [];
212982
213039
  for (const value of values) {
212983
213040
  data.push(value.value);
@@ -213033,11 +213090,11 @@ var require_src56 = __commonJS({
213033
213090
  if (Array.isArray(key)) {
213034
213091
  const keyPrefixed2 = this._getKeyPrefixArray(key);
213035
213092
  if (store.deleteMany === void 0) {
213036
- const promises2 = [];
213093
+ const promises3 = [];
213037
213094
  for (const key2 of keyPrefixed2) {
213038
- promises2.push(store.delete(key2));
213095
+ promises3.push(store.delete(key2));
213039
213096
  }
213040
- return Promise.allSettled(promises2).then((values) => values.every((x) => x.value === true));
213097
+ return Promise.allSettled(promises3).then((values) => values.every((x) => x.value === true));
213041
213098
  }
213042
213099
  return Promise.resolve().then(() => store.deleteMany(keyPrefixed2));
213043
213100
  }
@@ -236837,20 +236894,6 @@ var require_undici = __commonJS({
236837
236894
  }
236838
236895
  });
236839
236896
 
236840
- // node_modules/strip-ansi/node_modules/ansi-regex/index.js
236841
- var require_ansi_regex = __commonJS({
236842
- "node_modules/strip-ansi/node_modules/ansi-regex/index.js"(exports2, module2) {
236843
- "use strict";
236844
- module2.exports = ({ onlyFirst = false } = {}) => {
236845
- const pattern = [
236846
- "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
236847
- "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
236848
- ].join("|");
236849
- return new RegExp(pattern, onlyFirst ? void 0 : "g");
236850
- };
236851
- }
236852
- });
236853
-
236854
236897
  // node_modules/chardet/lib/fs/node.js
236855
236898
  var require_node22 = __commonJS({
236856
236899
  "node_modules/chardet/lib/fs/node.js"(exports2, module2) {
@@ -258218,20 +258261,20 @@ var Bucket = class _Bucket extends ServiceObject {
258218
258261
  };
258219
258262
  (async () => {
258220
258263
  try {
258221
- let promises2 = [];
258264
+ let promises3 = [];
258222
258265
  const limit = (0, import_p_limit.default)(MAX_PARALLEL_LIMIT);
258223
258266
  const filesStream = this.getFilesStream(query);
258224
258267
  for await (const curFile of filesStream) {
258225
- if (promises2.length >= MAX_QUEUE_SIZE) {
258226
- await Promise.all(promises2);
258227
- promises2 = [];
258268
+ if (promises3.length >= MAX_QUEUE_SIZE) {
258269
+ await Promise.all(promises3);
258270
+ promises3 = [];
258228
258271
  }
258229
- promises2.push(limit(() => deleteFile(curFile)).catch((e2) => {
258272
+ promises3.push(limit(() => deleteFile(curFile)).catch((e2) => {
258230
258273
  filesStream.destroy();
258231
258274
  throw e2;
258232
258275
  }));
258233
258276
  }
258234
- await Promise.all(promises2);
258277
+ await Promise.all(promises3);
258235
258278
  callback(errors.length > 0 ? errors : null);
258236
258279
  } catch (e2) {
258237
258280
  callback(e2);
@@ -260143,10 +260186,10 @@ var Bucket = class _Bucket extends ServiceObject {
260143
260186
  };
260144
260187
  this.getFiles(options2).then(([files]) => {
260145
260188
  const limit = (0, import_p_limit.default)(MAX_PARALLEL_LIMIT);
260146
- const promises2 = files.map((file) => {
260189
+ const promises3 = files.map((file) => {
260147
260190
  return limit(() => processFile(file));
260148
260191
  });
260149
- return Promise.all(promises2);
260192
+ return Promise.all(promises3);
260150
260193
  }).then(() => callback(errors.length > 0 ? errors : null, updatedFiles), (err2) => callback(err2, updatedFiles));
260151
260194
  }
260152
260195
  getId() {
@@ -267244,7 +267287,7 @@ var mtimeFilter = (opt) => {
267244
267287
  // packages/a2a-server/src/persistence/gcs.ts
267245
267288
  var fse = __toESM(require_lib8(), 1);
267246
267289
  import { promises as fsPromises4, createReadStream as createReadStream4 } from "node:fs";
267247
- import { tmpdir as tmpdir3 } from "node:os";
267290
+ import { tmpdir as tmpdir4 } from "node:os";
267248
267291
  import { join as join22 } from "node:path";
267249
267292
 
267250
267293
  // packages/a2a-server/src/config/config.ts
@@ -267255,7 +267298,7 @@ import { homedir as homedir5 } from "node:os";
267255
267298
 
267256
267299
  // packages/core/dist/src/config/config.js
267257
267300
  import * as path56 from "node:path";
267258
- import process22 from "node:process";
267301
+ import process24 from "node:process";
267259
267302
 
267260
267303
  // node_modules/@google/genai/dist/node/index.mjs
267261
267304
  var import_google_auth_library6 = __toESM(require_src10(), 1);
@@ -284918,12 +284961,7 @@ function shortenPath(filePath, maxLen = 35) {
284918
284961
  if (filePath.length <= maxLen) {
284919
284962
  return filePath;
284920
284963
  }
284921
- const parsedPath = path10.parse(filePath);
284922
- const root = parsedPath.root;
284923
- const separator = path10.sep;
284924
- const relativePath = filePath.substring(root.length);
284925
- const segments = relativePath.split(separator).filter((s2) => s2 !== "");
284926
- if (segments.length <= 1) {
284964
+ const simpleTruncate = () => {
284927
284965
  const keepLen = Math.floor((maxLen - 3) / 2);
284928
284966
  if (keepLen <= 0) {
284929
284967
  return filePath.substring(0, maxLen - 3) + "...";
@@ -284931,29 +284969,134 @@ function shortenPath(filePath, maxLen = 35) {
284931
284969
  const start2 = filePath.substring(0, keepLen);
284932
284970
  const end = filePath.substring(filePath.length - keepLen);
284933
284971
  return `${start2}...${end}`;
284972
+ };
284973
+ const truncateComponent = (component, targetLength, mode) => {
284974
+ if (component.length <= targetLength) {
284975
+ return component;
284976
+ }
284977
+ if (targetLength <= 0) {
284978
+ return "";
284979
+ }
284980
+ if (targetLength <= 3) {
284981
+ if (mode === "end") {
284982
+ return component.slice(-targetLength);
284983
+ }
284984
+ return component.slice(0, targetLength);
284985
+ }
284986
+ if (mode === "start") {
284987
+ return `${component.slice(0, targetLength - 3)}...`;
284988
+ }
284989
+ if (mode === "end") {
284990
+ return `...${component.slice(component.length - (targetLength - 3))}`;
284991
+ }
284992
+ const front = Math.ceil((targetLength - 3) / 2);
284993
+ const back = targetLength - 3 - front;
284994
+ return `${component.slice(0, front)}...${component.slice(component.length - back)}`;
284995
+ };
284996
+ const parsedPath = path10.parse(filePath);
284997
+ const root = parsedPath.root;
284998
+ const separator = path10.sep;
284999
+ const relativePath = filePath.substring(root.length);
285000
+ const segments = relativePath.split(separator).filter((s2) => s2 !== "");
285001
+ if (segments.length <= 1) {
285002
+ return simpleTruncate();
284934
285003
  }
284935
285004
  const firstDir = segments[0];
284936
285005
  const lastSegment = segments[segments.length - 1];
284937
285006
  const startComponent = root + firstDir;
284938
- const endPartSegments = [];
284939
- let currentLength = separator.length + lastSegment.length;
284940
- for (let i3 = segments.length - 2; i3 >= 0; i3--) {
285007
+ const endPartSegments = [lastSegment];
285008
+ let endPartLength = lastSegment.length;
285009
+ for (let i3 = segments.length - 2; i3 > 0; i3--) {
284941
285010
  const segment = segments[i3];
284942
- const lengthWithSegment = currentLength + separator.length + segment.length;
284943
- if (lengthWithSegment <= maxLen) {
285011
+ const newLength = startComponent.length + separator.length + 3 + // for "..."
285012
+ separator.length + endPartLength + separator.length + segment.length;
285013
+ if (newLength <= maxLen) {
284944
285014
  endPartSegments.unshift(segment);
284945
- currentLength = lengthWithSegment;
285015
+ endPartLength += separator.length + segment.length;
284946
285016
  } else {
284947
285017
  break;
284948
285018
  }
284949
285019
  }
284950
- let result = endPartSegments.join(separator) + separator + lastSegment;
284951
- if (currentLength > maxLen) {
284952
- return result;
285020
+ const components = [firstDir, ...endPartSegments];
285021
+ const componentModes = components.map((_, index) => {
285022
+ if (index === 0) {
285023
+ return "start";
285024
+ }
285025
+ if (index === components.length - 1) {
285026
+ return "end";
285027
+ }
285028
+ return "center";
285029
+ });
285030
+ const separatorsCount = endPartSegments.length + 1;
285031
+ const fixedLen = root.length + separatorsCount * separator.length + 3;
285032
+ const availableForComponents = maxLen - fixedLen;
285033
+ const trailingFallback = () => {
285034
+ const ellipsisTail = `...${separator}${lastSegment}`;
285035
+ if (ellipsisTail.length <= maxLen) {
285036
+ return ellipsisTail;
285037
+ }
285038
+ if (root) {
285039
+ const rootEllipsisTail = `${root}...${separator}${lastSegment}`;
285040
+ if (rootEllipsisTail.length <= maxLen) {
285041
+ return rootEllipsisTail;
285042
+ }
285043
+ }
285044
+ if (root && `${root}${lastSegment}`.length <= maxLen) {
285045
+ return `${root}${lastSegment}`;
285046
+ }
285047
+ if (lastSegment.length <= maxLen) {
285048
+ return lastSegment;
285049
+ }
285050
+ return simpleTruncate();
285051
+ };
285052
+ if (availableForComponents <= 0) {
285053
+ return trailingFallback();
285054
+ }
285055
+ const minLengths = components.map((component, index) => {
285056
+ if (index === 0) {
285057
+ return Math.min(component.length, 1);
285058
+ }
285059
+ if (index === components.length - 1) {
285060
+ return component.length;
285061
+ }
285062
+ return Math.min(component.length, 1);
285063
+ });
285064
+ const minTotal = minLengths.reduce((sum, len) => sum + len, 0);
285065
+ if (availableForComponents < minTotal) {
285066
+ return trailingFallback();
285067
+ }
285068
+ const budgets = components.map((component) => component.length);
285069
+ let currentTotal = budgets.reduce((sum, len) => sum + len, 0);
285070
+ const pickIndexToReduce = () => {
285071
+ let bestIndex = -1;
285072
+ let bestScore = -Infinity;
285073
+ for (let i3 = 0; i3 < budgets.length; i3++) {
285074
+ if (budgets[i3] <= minLengths[i3]) {
285075
+ continue;
285076
+ }
285077
+ const isLast = i3 === budgets.length - 1;
285078
+ const score = (isLast ? 0 : 1e6) + budgets[i3];
285079
+ if (score > bestScore) {
285080
+ bestScore = score;
285081
+ bestIndex = i3;
285082
+ }
285083
+ }
285084
+ return bestIndex;
285085
+ };
285086
+ while (currentTotal > availableForComponents) {
285087
+ const index = pickIndexToReduce();
285088
+ if (index === -1) {
285089
+ return trailingFallback();
285090
+ }
285091
+ budgets[index]--;
285092
+ currentTotal--;
284953
285093
  }
284954
- result = startComponent + separator + result;
285094
+ const truncatedComponents = components.map((component, index) => truncateComponent(component, budgets[index], componentModes[index]));
285095
+ const truncatedFirst = truncatedComponents[0];
285096
+ const truncatedEnd = truncatedComponents.slice(1).join(separator);
285097
+ const result = `${root}${truncatedFirst}${separator}...${separator}${truncatedEnd}`;
284955
285098
  if (result.length > maxLen) {
284956
- return "..." + result.substring(result.length - maxLen - 3);
285099
+ return trailingFallback();
284957
285100
  }
284958
285101
  return result;
284959
285102
  }
@@ -285502,6 +285645,21 @@ function getUseEncryptedStorageFlag() {
285502
285645
  return process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] === "true";
285503
285646
  }
285504
285647
  async function initOauthClient(authType, config2) {
285648
+ const credentials = await fetchCachedCredentials();
285649
+ if (credentials && credentials.type === "external_account_authorized_user") {
285650
+ const auth2 = new import_google_auth_library8.GoogleAuth({
285651
+ scopes: OAUTH_SCOPE
285652
+ });
285653
+ const byoidClient = await auth2.fromJSON({
285654
+ ...credentials,
285655
+ refresh_token: credentials.refresh_token ?? void 0
285656
+ });
285657
+ const token2 = await byoidClient.getAccessToken();
285658
+ if (token2) {
285659
+ debugLogger.debug("Created BYOID auth client.");
285660
+ return byoidClient;
285661
+ }
285662
+ }
285505
285663
  const client = new import_google_auth_library8.OAuth2Client({
285506
285664
  clientId: OAUTH_CLIENT_ID,
285507
285665
  clientSecret: OAUTH_CLIENT_SECRET,
@@ -285524,16 +285682,25 @@ async function initOauthClient(authType, config2) {
285524
285682
  await cacheCredentials(tokens);
285525
285683
  }
285526
285684
  });
285527
- if (await loadCachedCredentials(client)) {
285528
- if (!userAccountManager.getCachedGoogleAccount()) {
285529
- try {
285530
- await fetchAndCacheUserInfo(client);
285531
- } catch (error) {
285532
- debugLogger.warn("Failed to fetch user info:", getErrorMessage(error));
285685
+ if (credentials) {
285686
+ client.setCredentials(credentials);
285687
+ try {
285688
+ const { token: token2 } = await client.getAccessToken();
285689
+ if (token2) {
285690
+ await client.getTokenInfo(token2);
285691
+ if (!userAccountManager.getCachedGoogleAccount()) {
285692
+ try {
285693
+ await fetchAndCacheUserInfo(client);
285694
+ } catch (error) {
285695
+ debugLogger.warn("Failed to fetch user info:", getErrorMessage(error));
285696
+ }
285697
+ }
285698
+ debugLogger.log("Loaded cached credentials.");
285699
+ return client;
285533
285700
  }
285701
+ } catch (error) {
285702
+ debugLogger.debug(`Cached credentials are not valid:`, getErrorMessage(error));
285534
285703
  }
285535
- debugLogger.log("Loaded cached credentials.");
285536
- return client;
285537
285704
  }
285538
285705
  if (authType === AuthType2.CLOUD_SHELL) {
285539
285706
  try {
@@ -285743,15 +285910,10 @@ function getAvailablePort() {
285743
285910
  }
285744
285911
  });
285745
285912
  }
285746
- async function loadCachedCredentials(client) {
285913
+ async function fetchCachedCredentials() {
285747
285914
  const useEncryptedStorage = getUseEncryptedStorageFlag();
285748
285915
  if (useEncryptedStorage) {
285749
- const credentials = await OAuthCredentialStorage.loadCredentials();
285750
- if (credentials) {
285751
- client.setCredentials(credentials);
285752
- return true;
285753
- }
285754
- return false;
285916
+ return await OAuthCredentialStorage.loadCredentials();
285755
285917
  }
285756
285918
  const pathsToTry = [
285757
285919
  Storage2.getOAuthCredsPath(),
@@ -285759,19 +285921,13 @@ async function loadCachedCredentials(client) {
285759
285921
  ].filter((p) => !!p);
285760
285922
  for (const keyFile of pathsToTry) {
285761
285923
  try {
285762
- const creds = await fs22.readFile(keyFile, "utf-8");
285763
- client.setCredentials(JSON.parse(creds));
285764
- const { token: token2 } = await client.getAccessToken();
285765
- if (!token2) {
285766
- continue;
285767
- }
285768
- await client.getTokenInfo(token2);
285769
- return true;
285924
+ const keyFileString = await fs22.readFile(keyFile, "utf-8");
285925
+ return JSON.parse(keyFileString);
285770
285926
  } catch (error) {
285771
285927
  debugLogger.debug(`Failed to load credentials from ${keyFile}:`, getErrorMessage(error));
285772
285928
  }
285773
285929
  }
285774
- return false;
285930
+ return null;
285775
285931
  }
285776
285932
  async function cacheCredentials(credentials) {
285777
285933
  const filePath = Storage2.getOAuthCredsPath();
@@ -286349,24 +286505,18 @@ var BaseToolInvocation = class {
286349
286505
  throw new Error(`Tool execution for "${this._toolDisplayName || this._toolName}" denied by policy.`);
286350
286506
  }
286351
286507
  if (decision === "ASK_USER") {
286352
- const confirmationDetails = {
286353
- type: "info",
286354
- title: `Confirm: ${this._toolDisplayName || this._toolName}`,
286355
- prompt: this.getDescription(),
286356
- onConfirm: async (outcome) => {
286357
- if (outcome === ToolConfirmationOutcome.ProceedAlways) {
286358
- if (this.messageBus && this._toolName) {
286359
- this.messageBus.publish({
286360
- type: MessageBusType.UPDATE_POLICY,
286361
- toolName: this._toolName
286362
- });
286363
- }
286364
- }
286365
- }
286366
- };
286367
- return confirmationDetails;
286508
+ return this.getConfirmationDetails(abortSignal);
286368
286509
  }
286369
286510
  }
286511
+ return this.getConfirmationDetails(abortSignal);
286512
+ }
286513
+ /**
286514
+ * Subclasses should override this method to provide custom confirmation UI
286515
+ * when the policy engine's decision is 'ASK_USER'.
286516
+ * The base implementation returns false (no confirmation needed).
286517
+ * Only tools that need confirmation (e.g., write, execute tools) should override this.
286518
+ */
286519
+ async getConfirmationDetails(_abortSignal) {
286370
286520
  return false;
286371
286521
  }
286372
286522
  getMessageBusDecision(abortSignal) {
@@ -286784,7 +286934,7 @@ var DiscoveredMCPTool = class _DiscoveredMCPTool extends BaseDeclarativeTool {
286784
286934
  asFullyQualifiedTool() {
286785
286935
  return new _DiscoveredMCPTool(this.mcpTool, this.serverName, this.serverToolName, this.description, this.parameterSchema, this.trust, `${this.serverName}__${this.serverToolName}`, this.cliConfig, this.extensionId);
286786
286936
  }
286787
- createInvocation(params) {
286937
+ createInvocation(params, _messageBus, _toolName, _displayName) {
286788
286938
  return new DiscoveredMCPToolInvocation(this.mcpTool, this.serverName, this.serverToolName, this.displayName, this.trust, params, this.cliConfig);
286789
286939
  }
286790
286940
  };
@@ -286968,90 +287118,6 @@ function getCommonAttributes(config2) {
286968
287118
 
286969
287119
  // packages/core/dist/src/telemetry/types.js
286970
287120
  init_esm();
286971
- var EVENT_CLI_CONFIG = "gemini_cli.config";
286972
- var StartSessionEvent = class {
286973
- "event.name";
286974
- "event.timestamp";
286975
- model;
286976
- embedding_model;
286977
- sandbox_enabled;
286978
- core_tools_enabled;
286979
- approval_mode;
286980
- api_key_enabled;
286981
- vertex_ai_enabled;
286982
- debug_enabled;
286983
- mcp_servers;
286984
- telemetry_enabled;
286985
- telemetry_log_user_prompts_enabled;
286986
- file_filtering_respect_git_ignore;
286987
- mcp_servers_count;
286988
- mcp_tools_count;
286989
- mcp_tools;
286990
- output_format;
286991
- extensions_count;
286992
- extension_ids;
286993
- constructor(config2, toolRegistry) {
286994
- const generatorConfig = config2.getContentGeneratorConfig();
286995
- const mcpServers = config2.getMcpServers();
286996
- let useGemini = false;
286997
- let useVertex = false;
286998
- if (generatorConfig && generatorConfig.authType) {
286999
- useGemini = generatorConfig.authType === AuthType2.USE_GEMINI;
287000
- useVertex = generatorConfig.authType === AuthType2.USE_VERTEX_AI;
287001
- }
287002
- this["event.name"] = "cli_config";
287003
- this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
287004
- this.model = config2.getModel();
287005
- this.embedding_model = config2.getEmbeddingModel();
287006
- this.sandbox_enabled = typeof config2.getSandbox() === "string" || !!config2.getSandbox();
287007
- this.core_tools_enabled = (config2.getCoreTools() ?? []).join(",");
287008
- this.approval_mode = config2.getApprovalMode();
287009
- this.api_key_enabled = useGemini || useVertex;
287010
- this.vertex_ai_enabled = useVertex;
287011
- this.debug_enabled = config2.getDebugMode();
287012
- this.mcp_servers = mcpServers ? Object.keys(mcpServers).join(",") : "";
287013
- this.telemetry_enabled = config2.getTelemetryEnabled();
287014
- this.telemetry_log_user_prompts_enabled = config2.getTelemetryLogPromptsEnabled();
287015
- this.file_filtering_respect_git_ignore = config2.getFileFilteringRespectGitIgnore();
287016
- this.mcp_servers_count = mcpServers ? Object.keys(mcpServers).length : 0;
287017
- this.output_format = config2.getOutputFormat();
287018
- const extensions = config2.getExtensions();
287019
- this.extensions_count = extensions.length;
287020
- this.extension_ids = extensions.map((e2) => e2.id).join(",");
287021
- if (toolRegistry) {
287022
- const mcpTools = toolRegistry.getAllTools().filter((tool) => tool instanceof DiscoveredMCPTool);
287023
- this.mcp_tools_count = mcpTools.length;
287024
- this.mcp_tools = mcpTools.map((tool) => tool.name).join(",");
287025
- }
287026
- }
287027
- toOpenTelemetryAttributes(config2) {
287028
- return {
287029
- ...getCommonAttributes(config2),
287030
- "event.name": EVENT_CLI_CONFIG,
287031
- "event.timestamp": this["event.timestamp"],
287032
- model: this.model,
287033
- embedding_model: this.embedding_model,
287034
- sandbox_enabled: this.sandbox_enabled,
287035
- core_tools_enabled: this.core_tools_enabled,
287036
- approval_mode: this.approval_mode,
287037
- api_key_enabled: this.api_key_enabled,
287038
- vertex_ai_enabled: this.vertex_ai_enabled,
287039
- log_user_prompts_enabled: this.telemetry_log_user_prompts_enabled,
287040
- file_filtering_respect_git_ignore: this.file_filtering_respect_git_ignore,
287041
- debug_mode: this.debug_enabled,
287042
- mcp_servers: this.mcp_servers,
287043
- mcp_servers_count: this.mcp_servers_count,
287044
- mcp_tools: this.mcp_tools,
287045
- mcp_tools_count: this.mcp_tools_count,
287046
- output_format: this.output_format,
287047
- extensions_count: this.extensions_count,
287048
- extension_ids: this.extension_ids
287049
- };
287050
- }
287051
- toLogBody() {
287052
- return "CLI configuration loaded.";
287053
- }
287054
- };
287055
287121
  var EVENT_TOOL_CALL = "gemini_cli.tool_call";
287056
287122
  var ToolCallEvent = class {
287057
287123
  "event.name";
@@ -288511,8 +288577,8 @@ var Float64Vector = import_vector.default.Float64Vector;
288511
288577
  var PointerVector = import_vector.default.PointerVector;
288512
288578
 
288513
288579
  // packages/core/dist/src/generated/git-commit.js
288514
- var GIT_COMMIT_INFO = "c4c0c0d1";
288515
- var CLI_VERSION = "0.12.0-nightly.20251023.c4c0c0d1";
288580
+ var GIT_COMMIT_INFO = "cb0947c5";
288581
+ var CLI_VERSION = "0.12.0-nightly.20251027.cb0947c5";
288516
288582
 
288517
288583
  // packages/core/dist/src/ide/detect-ide.js
288518
288584
  var IDE_DEFINITIONS = {
@@ -288697,6 +288763,36 @@ var ClearcutLogger = class _ClearcutLogger {
288697
288763
  }
288698
288764
  }
288699
288765
  }
288766
+ createBasicLogEvent(eventName, data = []) {
288767
+ const surface = determineSurface();
288768
+ return {
288769
+ console_type: "GEMINI_CLI",
288770
+ application: 102,
288771
+ // GEMINI_CLI
288772
+ event_name: eventName,
288773
+ event_metadata: [
288774
+ [
288775
+ ...data,
288776
+ {
288777
+ gemini_cli_key: EventMetadataKey.GEMINI_CLI_SURFACE,
288778
+ value: surface
288779
+ },
288780
+ {
288781
+ gemini_cli_key: EventMetadataKey.GEMINI_CLI_VERSION,
288782
+ value: CLI_VERSION
288783
+ },
288784
+ {
288785
+ gemini_cli_key: EventMetadataKey.GEMINI_CLI_GIT_COMMIT_HASH,
288786
+ value: GIT_COMMIT_INFO
288787
+ },
288788
+ {
288789
+ gemini_cli_key: EventMetadataKey.GEMINI_CLI_OS,
288790
+ value: process.platform
288791
+ }
288792
+ ]
288793
+ ]
288794
+ };
288795
+ }
288700
288796
  createLogEvent(eventName, data = []) {
288701
288797
  const email = this.userAccountManager.getCachedGoogleAccount();
288702
288798
  if (eventName !== EventNames.START_SESSION) {
@@ -288704,13 +288800,7 @@ var ClearcutLogger = class _ClearcutLogger {
288704
288800
  }
288705
288801
  const totalAccounts = this.userAccountManager.getLifetimeGoogleAccounts();
288706
288802
  data = this.addDefaultFields(data, totalAccounts);
288707
- const logEvent = {
288708
- console_type: "GEMINI_CLI",
288709
- application: 102,
288710
- // GEMINI_CLI
288711
- event_name: eventName,
288712
- event_metadata: [data]
288713
- };
288803
+ const logEvent = this.createBasicLogEvent(eventName, data);
288714
288804
  if (email) {
288715
288805
  logEvent.client_email = email;
288716
288806
  } else {
@@ -289251,7 +289341,7 @@ var ClearcutLogger = class _ClearcutLogger {
289251
289341
  value: event.status
289252
289342
  }
289253
289343
  ];
289254
- this.enqueueLogEvent(this.createLogEvent(EventNames.EXTENSION_INSTALL, data));
289344
+ this.enqueueLogEvent(this.createBasicLogEvent(EventNames.EXTENSION_INSTALL, data));
289255
289345
  this.flushToClearcut().catch((error) => {
289256
289346
  debugLogger.debug("Error flushing to Clearcut:", error);
289257
289347
  });
@@ -289271,7 +289361,7 @@ var ClearcutLogger = class _ClearcutLogger {
289271
289361
  value: event.status
289272
289362
  }
289273
289363
  ];
289274
- this.enqueueLogEvent(this.createLogEvent(EventNames.EXTENSION_UNINSTALL, data));
289364
+ this.enqueueLogEvent(this.createBasicLogEvent(EventNames.EXTENSION_UNINSTALL, data));
289275
289365
  this.flushToClearcut().catch((error) => {
289276
289366
  debugLogger.debug("Error flushing to Clearcut:", error);
289277
289367
  });
@@ -289303,7 +289393,7 @@ var ClearcutLogger = class _ClearcutLogger {
289303
289393
  value: event.status
289304
289394
  }
289305
289395
  ];
289306
- this.enqueueLogEvent(this.createLogEvent(EventNames.EXTENSION_UPDATE, data));
289396
+ this.enqueueLogEvent(this.createBasicLogEvent(EventNames.EXTENSION_UPDATE, data));
289307
289397
  this.flushToClearcut().catch((error) => {
289308
289398
  debugLogger.debug("Error flushing to Clearcut:", error);
289309
289399
  });
@@ -289377,7 +289467,7 @@ var ClearcutLogger = class _ClearcutLogger {
289377
289467
  value: event.setting_scope
289378
289468
  }
289379
289469
  ];
289380
- this.enqueueLogEvent(this.createLogEvent(EventNames.EXTENSION_ENABLE, data));
289470
+ this.enqueueLogEvent(this.createBasicLogEvent(EventNames.EXTENSION_ENABLE, data));
289381
289471
  this.flushToClearcut().catch((error) => {
289382
289472
  debugLogger.debug("Error flushing to Clearcut:", error);
289383
289473
  });
@@ -289407,7 +289497,7 @@ var ClearcutLogger = class _ClearcutLogger {
289407
289497
  value: event.setting_scope
289408
289498
  }
289409
289499
  ];
289410
- this.enqueueLogEvent(this.createLogEvent(EventNames.EXTENSION_DISABLE, data));
289500
+ this.enqueueLogEvent(this.createBasicLogEvent(EventNames.EXTENSION_DISABLE, data));
289411
289501
  this.flushToClearcut().catch((error) => {
289412
289502
  debugLogger.debug("Error flushing to Clearcut:", error);
289413
289503
  });
@@ -289487,7 +289577,6 @@ var ClearcutLogger = class _ClearcutLogger {
289487
289577
  * should exist on all log events.
289488
289578
  */
289489
289579
  addDefaultFields(data, totalAccounts) {
289490
- const surface = determineSurface();
289491
289580
  const defaultLogMetadata = [
289492
289581
  {
289493
289582
  gemini_cli_key: EventMetadataKey.GEMINI_CLI_SESSION_ID,
@@ -289501,26 +289590,10 @@ var ClearcutLogger = class _ClearcutLogger {
289501
289590
  gemini_cli_key: EventMetadataKey.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT,
289502
289591
  value: `${totalAccounts}`
289503
289592
  },
289504
- {
289505
- gemini_cli_key: EventMetadataKey.GEMINI_CLI_SURFACE,
289506
- value: surface
289507
- },
289508
- {
289509
- gemini_cli_key: EventMetadataKey.GEMINI_CLI_VERSION,
289510
- value: CLI_VERSION
289511
- },
289512
- {
289513
- gemini_cli_key: EventMetadataKey.GEMINI_CLI_GIT_COMMIT_HASH,
289514
- value: GIT_COMMIT_INFO
289515
- },
289516
289593
  {
289517
289594
  gemini_cli_key: EventMetadataKey.GEMINI_CLI_PROMPT_ID,
289518
289595
  value: this.promptId
289519
289596
  },
289520
- {
289521
- gemini_cli_key: EventMetadataKey.GEMINI_CLI_OS,
289522
- value: process.platform
289523
- },
289524
289597
  {
289525
289598
  gemini_cli_key: EventMetadataKey.GEMINI_CLI_NODE_VERSION,
289526
289599
  value: process.versions.node
@@ -289730,7 +289803,7 @@ var GcpLogExporter = class {
289730
289803
  };
289731
289804
 
289732
289805
  // packages/core/dist/src/telemetry/uiTelemetry.js
289733
- import { EventEmitter as EventEmitter4 } from "node:events";
289806
+ import { EventEmitter as EventEmitter5 } from "node:events";
289734
289807
  var createInitialModelMetrics = () => ({
289735
289808
  api: {
289736
289809
  totalRequests: 0,
@@ -289766,7 +289839,7 @@ var createInitialMetrics = () => ({
289766
289839
  totalLinesRemoved: 0
289767
289840
  }
289768
289841
  });
289769
- var UiTelemetryService = class extends EventEmitter4 {
289842
+ var UiTelemetryService = class extends EventEmitter5 {
289770
289843
  #metrics = createInitialMetrics();
289771
289844
  #lastPromptTokenCount = 0;
289772
289845
  addEvent(event) {
@@ -290530,17 +290603,6 @@ async function shutdownTelemetry(config2) {
290530
290603
  }
290531
290604
 
290532
290605
  // packages/core/dist/src/telemetry/loggers.js
290533
- function logCliConfiguration(config2, event) {
290534
- ClearcutLogger.getInstance(config2)?.logStartSessionEvent(event);
290535
- if (!isTelemetrySdkInitialized())
290536
- return;
290537
- const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
290538
- const logRecord = {
290539
- body: event.toLogBody(),
290540
- attributes: event.toOpenTelemetryAttributes(config2)
290541
- };
290542
- logger6.emit(logRecord);
290543
- }
290544
290606
  function logToolCall(config2, event) {
290545
290607
  const uiEvent = {
290546
290608
  ...event,
@@ -290857,43 +290919,6 @@ function isApiError(error) {
290857
290919
  function isStructuredError(error) {
290858
290920
  return typeof error === "object" && error !== null && "message" in error && typeof error.message === "string";
290859
290921
  }
290860
- function isProQuotaExceededError(error) {
290861
- const checkMessage = (message) => message.includes("Quota exceeded for quota metric 'Gemini") && message.includes("Pro Requests'");
290862
- if (typeof error === "string") {
290863
- return checkMessage(error);
290864
- }
290865
- if (isStructuredError(error)) {
290866
- return checkMessage(error.message);
290867
- }
290868
- if (isApiError(error)) {
290869
- return checkMessage(error.error.message);
290870
- }
290871
- if (error && typeof error === "object" && "response" in error) {
290872
- const gaxiosError = error;
290873
- if (gaxiosError.response && gaxiosError.response.data) {
290874
- if (typeof gaxiosError.response.data === "string") {
290875
- return checkMessage(gaxiosError.response.data);
290876
- }
290877
- if (typeof gaxiosError.response.data === "object" && gaxiosError.response.data !== null && "error" in gaxiosError.response.data) {
290878
- const errorData = gaxiosError.response.data;
290879
- return checkMessage(errorData.error?.message || "");
290880
- }
290881
- }
290882
- }
290883
- return false;
290884
- }
290885
- function isGenericQuotaExceededError(error) {
290886
- if (typeof error === "string") {
290887
- return error.includes("Quota exceeded for quota metric");
290888
- }
290889
- if (isStructuredError(error)) {
290890
- return error.message.includes("Quota exceeded for quota metric");
290891
- }
290892
- if (isApiError(error)) {
290893
- return error.error.message.includes("Quota exceeded for quota metric");
290894
- }
290895
- return false;
290896
- }
290897
290922
 
290898
290923
  // packages/core/dist/src/core/loggingContentGenerator.js
290899
290924
  var LoggingContentGenerator = class {
@@ -290982,6 +291007,58 @@ async function createCodeAssistContentGenerator(httpOptions, authType, config2,
290982
291007
  throw new Error(`Unsupported authType: ${authType}`);
290983
291008
  }
290984
291009
 
291010
+ // packages/core/dist/src/core/fakeContentGenerator.js
291011
+ import { promises } from "node:fs";
291012
+ var FakeContentGenerator = class _FakeContentGenerator {
291013
+ responses;
291014
+ callCounters = {
291015
+ generateContent: 0,
291016
+ generateContentStream: 0,
291017
+ countTokens: 0,
291018
+ embedContent: 0
291019
+ };
291020
+ userTier;
291021
+ constructor(responses) {
291022
+ this.responses = {
291023
+ generateContent: responses.generateContent ?? [],
291024
+ generateContentStream: responses.generateContentStream ?? [],
291025
+ countTokens: responses.countTokens ?? [],
291026
+ embedContent: responses.embedContent ?? []
291027
+ };
291028
+ }
291029
+ static async fromFile(filePath) {
291030
+ const fileContent = await promises.readFile(filePath, "utf-8");
291031
+ const responses = JSON.parse(fileContent);
291032
+ return new _FakeContentGenerator(responses);
291033
+ }
291034
+ getNextResponse(method, request3) {
291035
+ const response = this.responses[method][this.callCounters[method]++];
291036
+ if (!response) {
291037
+ throw new Error(`No more mock responses for ${method}, got request:
291038
+ ` + safeJsonStringify(request3));
291039
+ }
291040
+ return response;
291041
+ }
291042
+ async generateContent(_request, _userPromptId) {
291043
+ return this.getNextResponse("generateContent", _request);
291044
+ }
291045
+ async generateContentStream(_request, _userPromptId) {
291046
+ const responses = this.getNextResponse("generateContentStream", _request);
291047
+ async function* stream3() {
291048
+ for (const response of responses) {
291049
+ yield response;
291050
+ }
291051
+ }
291052
+ return stream3();
291053
+ }
291054
+ async countTokens(_request) {
291055
+ return this.getNextResponse("countTokens", _request);
291056
+ }
291057
+ async embedContent(_request) {
291058
+ return this.getNextResponse("embedContent", _request);
291059
+ }
291060
+ };
291061
+
290985
291062
  // packages/core/dist/src/core/contentGenerator.js
290986
291063
  var AuthType2;
290987
291064
  (function(AuthType3) {
@@ -291015,7 +291092,10 @@ function createContentGeneratorConfig(config2, authType) {
291015
291092
  return contentGeneratorConfig;
291016
291093
  }
291017
291094
  async function createContentGenerator(config2, gcConfig, sessionId2) {
291018
- const version3 = "0.12.0-nightly.20251023.c4c0c0d1";
291095
+ if (gcConfig.fakeResponses) {
291096
+ return FakeContentGenerator.fromFile(gcConfig.fakeResponses);
291097
+ }
291098
+ const version3 = "0.12.0-nightly.20251027.cb0947c5";
291019
291099
  const userAgent = `GeminiCLI/${version3} (${process.platform}; ${process.arch})`;
291020
291100
  const baseHeaders = {
291021
291101
  "User-Agent": userAgent
@@ -298317,10 +298397,242 @@ var import_shell_quote = __toESM(require_shell_quote(), 1);
298317
298397
 
298318
298398
  // packages/core/dist/src/mcp/google-auth-provider.js
298319
298399
  var import_google_auth_library9 = __toESM(require_src10(), 1);
298400
+
298401
+ // packages/core/dist/src/mcp/oauth-utils.js
298402
+ var FIVE_MIN_BUFFER_MS = 5 * 60 * 1e3;
298403
+ var OAuthUtils = class {
298404
+ /**
298405
+ * Construct well-known OAuth endpoint URLs.
298406
+ * By default, uses standard root-based well-known URLs.
298407
+ * If includePathSuffix is true, appends any path from the base URL to the well-known endpoints.
298408
+ */
298409
+ static buildWellKnownUrls(baseUrl, includePathSuffix = false) {
298410
+ const serverUrl = new URL(baseUrl);
298411
+ const base = `${serverUrl.protocol}//${serverUrl.host}`;
298412
+ if (!includePathSuffix) {
298413
+ return {
298414
+ protectedResource: new URL("/.well-known/oauth-protected-resource", base).toString(),
298415
+ authorizationServer: new URL("/.well-known/oauth-authorization-server", base).toString()
298416
+ };
298417
+ }
298418
+ const pathSuffix = serverUrl.pathname.replace(/\/$/, "");
298419
+ return {
298420
+ protectedResource: new URL(`/.well-known/oauth-protected-resource${pathSuffix}`, base).toString(),
298421
+ authorizationServer: new URL(`/.well-known/oauth-authorization-server${pathSuffix}`, base).toString()
298422
+ };
298423
+ }
298424
+ /**
298425
+ * Fetch OAuth protected resource metadata.
298426
+ *
298427
+ * @param resourceMetadataUrl The protected resource metadata URL
298428
+ * @returns The protected resource metadata or null if not available
298429
+ */
298430
+ static async fetchProtectedResourceMetadata(resourceMetadataUrl) {
298431
+ try {
298432
+ const response = await fetch(resourceMetadataUrl);
298433
+ if (!response.ok) {
298434
+ return null;
298435
+ }
298436
+ return await response.json();
298437
+ } catch (error) {
298438
+ debugLogger.debug(`Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error)}`);
298439
+ return null;
298440
+ }
298441
+ }
298442
+ /**
298443
+ * Fetch OAuth authorization server metadata.
298444
+ *
298445
+ * @param authServerMetadataUrl The authorization server metadata URL
298446
+ * @returns The authorization server metadata or null if not available
298447
+ */
298448
+ static async fetchAuthorizationServerMetadata(authServerMetadataUrl) {
298449
+ try {
298450
+ const response = await fetch(authServerMetadataUrl);
298451
+ if (!response.ok) {
298452
+ return null;
298453
+ }
298454
+ return await response.json();
298455
+ } catch (error) {
298456
+ debugLogger.debug(`Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error)}`);
298457
+ return null;
298458
+ }
298459
+ }
298460
+ /**
298461
+ * Convert authorization server metadata to OAuth configuration.
298462
+ *
298463
+ * @param metadata The authorization server metadata
298464
+ * @returns The OAuth configuration
298465
+ */
298466
+ static metadataToOAuthConfig(metadata2) {
298467
+ return {
298468
+ authorizationUrl: metadata2.authorization_endpoint,
298469
+ tokenUrl: metadata2.token_endpoint,
298470
+ scopes: metadata2.scopes_supported || [],
298471
+ registrationUrl: metadata2.registration_endpoint
298472
+ };
298473
+ }
298474
+ /**
298475
+ * Discover Oauth Authorization server metadata given an Auth server URL, by
298476
+ * trying the standard well-known endpoints.
298477
+ *
298478
+ * @param authServerUrl The authorization server URL
298479
+ * @returns The authorization server metadata or null if not found
298480
+ */
298481
+ static async discoverAuthorizationServerMetadata(authServerUrl) {
298482
+ const authServerUrlObj = new URL(authServerUrl);
298483
+ const base = `${authServerUrlObj.protocol}//${authServerUrlObj.host}`;
298484
+ const endpointsToTry = [];
298485
+ if (authServerUrlObj.pathname !== "/") {
298486
+ endpointsToTry.push(new URL(`/.well-known/oauth-authorization-server${authServerUrlObj.pathname}`, base).toString());
298487
+ endpointsToTry.push(new URL(`/.well-known/openid-configuration${authServerUrlObj.pathname}`, base).toString());
298488
+ endpointsToTry.push(new URL(`${authServerUrlObj.pathname}/.well-known/openid-configuration`, base).toString());
298489
+ }
298490
+ endpointsToTry.push(new URL("/.well-known/oauth-authorization-server", base).toString());
298491
+ endpointsToTry.push(new URL("/.well-known/openid-configuration", base).toString());
298492
+ for (const endpoint of endpointsToTry) {
298493
+ const authServerMetadata = await this.fetchAuthorizationServerMetadata(endpoint);
298494
+ if (authServerMetadata) {
298495
+ return authServerMetadata;
298496
+ }
298497
+ }
298498
+ debugLogger.debug(`Metadata discovery failed for authorization server ${authServerUrl}`);
298499
+ return null;
298500
+ }
298501
+ /**
298502
+ * Discover OAuth configuration using the standard well-known endpoints.
298503
+ *
298504
+ * @param serverUrl The base URL of the server
298505
+ * @returns The discovered OAuth configuration or null if not available
298506
+ */
298507
+ static async discoverOAuthConfig(serverUrl) {
298508
+ try {
298509
+ const wellKnownUrls = this.buildWellKnownUrls(serverUrl, false);
298510
+ let resourceMetadata = await this.fetchProtectedResourceMetadata(wellKnownUrls.protectedResource);
298511
+ if (!resourceMetadata) {
298512
+ const url4 = new URL(serverUrl);
298513
+ if (url4.pathname && url4.pathname !== "/") {
298514
+ const pathBasedUrls = this.buildWellKnownUrls(serverUrl, true);
298515
+ resourceMetadata = await this.fetchProtectedResourceMetadata(pathBasedUrls.protectedResource);
298516
+ }
298517
+ }
298518
+ if (resourceMetadata?.authorization_servers?.length) {
298519
+ const authServerUrl = resourceMetadata.authorization_servers[0];
298520
+ const authServerMetadata2 = await this.discoverAuthorizationServerMetadata(authServerUrl);
298521
+ if (authServerMetadata2) {
298522
+ const config2 = this.metadataToOAuthConfig(authServerMetadata2);
298523
+ if (authServerMetadata2.registration_endpoint) {
298524
+ debugLogger.log("Dynamic client registration is supported at:", authServerMetadata2.registration_endpoint);
298525
+ }
298526
+ return config2;
298527
+ }
298528
+ }
298529
+ debugLogger.debug(`Trying OAuth discovery fallback at ${serverUrl}`);
298530
+ const authServerMetadata = await this.discoverAuthorizationServerMetadata(serverUrl);
298531
+ if (authServerMetadata) {
298532
+ const config2 = this.metadataToOAuthConfig(authServerMetadata);
298533
+ if (authServerMetadata.registration_endpoint) {
298534
+ debugLogger.log("Dynamic client registration is supported at:", authServerMetadata.registration_endpoint);
298535
+ }
298536
+ return config2;
298537
+ }
298538
+ return null;
298539
+ } catch (error) {
298540
+ debugLogger.debug(`Failed to discover OAuth configuration: ${getErrorMessage(error)}`);
298541
+ return null;
298542
+ }
298543
+ }
298544
+ /**
298545
+ * Parse WWW-Authenticate header to extract OAuth information.
298546
+ *
298547
+ * @param header The WWW-Authenticate header value
298548
+ * @returns The resource metadata URI if found
298549
+ */
298550
+ static parseWWWAuthenticateHeader(header) {
298551
+ const match2 = header.match(/resource_metadata="([^"]+)"/);
298552
+ if (match2) {
298553
+ return match2[1];
298554
+ }
298555
+ return null;
298556
+ }
298557
+ /**
298558
+ * Discover OAuth configuration from WWW-Authenticate header.
298559
+ *
298560
+ * @param wwwAuthenticate The WWW-Authenticate header value
298561
+ * @returns The discovered OAuth configuration or null if not available
298562
+ */
298563
+ static async discoverOAuthFromWWWAuthenticate(wwwAuthenticate) {
298564
+ const resourceMetadataUri = this.parseWWWAuthenticateHeader(wwwAuthenticate);
298565
+ if (!resourceMetadataUri) {
298566
+ return null;
298567
+ }
298568
+ const resourceMetadata = await this.fetchProtectedResourceMetadata(resourceMetadataUri);
298569
+ if (!resourceMetadata?.authorization_servers?.length) {
298570
+ return null;
298571
+ }
298572
+ const authServerUrl = resourceMetadata.authorization_servers[0];
298573
+ const authServerMetadata = await this.discoverAuthorizationServerMetadata(authServerUrl);
298574
+ if (authServerMetadata) {
298575
+ return this.metadataToOAuthConfig(authServerMetadata);
298576
+ }
298577
+ return null;
298578
+ }
298579
+ /**
298580
+ * Extract base URL from an MCP server URL.
298581
+ *
298582
+ * @param mcpServerUrl The MCP server URL
298583
+ * @returns The base URL
298584
+ */
298585
+ static extractBaseUrl(mcpServerUrl) {
298586
+ const serverUrl = new URL(mcpServerUrl);
298587
+ return `${serverUrl.protocol}//${serverUrl.host}`;
298588
+ }
298589
+ /**
298590
+ * Check if a URL is an SSE endpoint.
298591
+ *
298592
+ * @param url The URL to check
298593
+ * @returns True if the URL appears to be an SSE endpoint
298594
+ */
298595
+ static isSSEEndpoint(url4) {
298596
+ return url4.includes("/sse") || !url4.includes("/mcp");
298597
+ }
298598
+ /**
298599
+ * Build a resource parameter for OAuth requests.
298600
+ *
298601
+ * @param endpointUrl The endpoint URL
298602
+ * @returns The resource parameter value
298603
+ */
298604
+ static buildResourceParameter(endpointUrl) {
298605
+ const url4 = new URL(endpointUrl);
298606
+ return `${url4.protocol}//${url4.host}${url4.pathname}`;
298607
+ }
298608
+ /**
298609
+ * Parses a JWT string to extract its expiry time.
298610
+ * @param idToken The JWT ID token.
298611
+ * @returns The expiry time in **milliseconds**, or undefined if parsing fails.
298612
+ */
298613
+ static parseTokenExpiry(idToken) {
298614
+ try {
298615
+ const payload = JSON.parse(Buffer.from(idToken.split(".")[1], "base64").toString());
298616
+ if (payload && typeof payload.exp === "number") {
298617
+ return payload.exp * 1e3;
298618
+ }
298619
+ } catch (e2) {
298620
+ console.error("Failed to parse ID token for expiry time with error:", e2);
298621
+ }
298622
+ return void 0;
298623
+ }
298624
+ };
298625
+
298626
+ // packages/core/dist/src/mcp/google-auth-provider.js
298627
+ var CLOUD_RUN_HOST_REGEX = /^(.*\.)?run\.app$/;
298320
298628
  var ALLOWED_HOSTS = [/^.+\.googleapis\.com$/, /^(.*\.)?luci\.app$/];
298321
298629
  var GoogleCredentialProvider = class {
298322
298630
  config;
298323
298631
  auth;
298632
+ useIdToken = false;
298633
+ audience;
298634
+ cachedToken;
298635
+ tokenExpiryTime;
298324
298636
  // Properties required by OAuthClientProvider, with no-op values
298325
298637
  redirectUrl = "";
298326
298638
  clientMetadata = {
@@ -298338,15 +298650,22 @@ var GoogleCredentialProvider = class {
298338
298650
  throw new Error("URL must be provided in the config for Google Credentials provider");
298339
298651
  }
298340
298652
  const hostname2 = new URL(url4).hostname;
298341
- if (!ALLOWED_HOSTS.some((pattern) => pattern.test(hostname2))) {
298653
+ const isRunAppHost = CLOUD_RUN_HOST_REGEX.test(hostname2);
298654
+ if (!this.config?.allow_unscoped_id_tokens_cloud_run && isRunAppHost) {
298655
+ throw new Error(`To enable the Cloud Run MCP Server at ${url4} please set allow_unscoped_id_tokens_cloud_run:true in the MCP Server config.`);
298656
+ }
298657
+ if (this.config?.allow_unscoped_id_tokens_cloud_run && isRunAppHost) {
298658
+ this.useIdToken = true;
298659
+ }
298660
+ this.audience = hostname2;
298661
+ if (!this.useIdToken && !ALLOWED_HOSTS.some((pattern) => pattern.test(hostname2))) {
298342
298662
  throw new Error(`Host "${hostname2}" is not an allowed host for Google Credential provider.`);
298343
298663
  }
298344
- const scopes = this.config?.oauth?.scopes;
298345
- if (!scopes || scopes.length === 0) {
298346
- throw new Error("Scopes must be provided in the oauth config for Google Credentials provider");
298664
+ if (!this.useIdToken && !this.config?.oauth?.scopes) {
298665
+ throw new Error("Scopes must be provided in the oauth config for Google Credentials provider (or enable allow_unscoped_id_tokens_for_cloud_run to use ID tokens for Cloud Run endpoints)");
298347
298666
  }
298348
298667
  this.auth = new import_google_auth_library9.GoogleAuth({
298349
- scopes
298668
+ scopes: this.config?.oauth?.scopes
298350
298669
  });
298351
298670
  }
298352
298671
  clientInformation() {
@@ -298356,17 +298675,46 @@ var GoogleCredentialProvider = class {
298356
298675
  this._clientInformation = clientInformation;
298357
298676
  }
298358
298677
  async tokens() {
298678
+ if (this.cachedToken && this.tokenExpiryTime && Date.now() < this.tokenExpiryTime - FIVE_MIN_BUFFER_MS) {
298679
+ return this.cachedToken;
298680
+ }
298681
+ this.cachedToken = void 0;
298682
+ this.tokenExpiryTime = void 0;
298683
+ if (this.useIdToken) {
298684
+ try {
298685
+ const idClient = await this.auth.getIdTokenClient(this.audience);
298686
+ const idToken = await idClient.idTokenProvider.fetchIdToken(this.audience);
298687
+ const newToken2 = {
298688
+ access_token: idToken,
298689
+ token_type: "Bearer"
298690
+ };
298691
+ const expiryTime2 = OAuthUtils.parseTokenExpiry(idToken);
298692
+ if (expiryTime2) {
298693
+ this.tokenExpiryTime = expiryTime2;
298694
+ this.cachedToken = newToken2;
298695
+ }
298696
+ return newToken2;
298697
+ } catch (e2) {
298698
+ console.error("Failed to get ID token from Google ADC", e2);
298699
+ return void 0;
298700
+ }
298701
+ }
298359
298702
  const client = await this.auth.getClient();
298360
298703
  const accessTokenResponse = await client.getAccessToken();
298361
298704
  if (!accessTokenResponse.token) {
298362
298705
  console.error("Failed to get access token from Google ADC");
298363
298706
  return void 0;
298364
298707
  }
298365
- const tokens = {
298708
+ const newToken = {
298366
298709
  access_token: accessTokenResponse.token,
298367
298710
  token_type: "Bearer"
298368
298711
  };
298369
- return tokens;
298712
+ const expiryTime = client.credentials?.expiry_date;
298713
+ if (expiryTime) {
298714
+ this.tokenExpiryTime = expiryTime;
298715
+ this.cachedToken = newToken;
298716
+ }
298717
+ return newToken;
298370
298718
  }
298371
298719
  saveTokens(_tokens) {
298372
298720
  }
@@ -298381,7 +298729,6 @@ var GoogleCredentialProvider = class {
298381
298729
 
298382
298730
  // packages/core/dist/src/mcp/sa-impersonation-provider.js
298383
298731
  var import_google_auth_library10 = __toESM(require_src10(), 1);
298384
- var fiveMinBufferMs = 5 * 60 * 1e3;
298385
298732
  function createIamApiUrl(targetSA) {
298386
298733
  return `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(targetSA)}:generateIdToken`;
298387
298734
  }
@@ -298425,7 +298772,7 @@ var ServiceAccountImpersonationProvider = class {
298425
298772
  this._clientInformation = clientInformation;
298426
298773
  }
298427
298774
  async tokens() {
298428
- if (this.cachedToken && this.tokenExpiryTime && Date.now() < this.tokenExpiryTime - fiveMinBufferMs) {
298775
+ if (this.cachedToken && this.tokenExpiryTime && Date.now() < this.tokenExpiryTime - FIVE_MIN_BUFFER_MS) {
298429
298776
  return this.cachedToken;
298430
298777
  }
298431
298778
  this.cachedToken = void 0;
@@ -298451,7 +298798,7 @@ var ServiceAccountImpersonationProvider = class {
298451
298798
  console.error("Failed to fetch ID token from Google:", e2);
298452
298799
  return void 0;
298453
298800
  }
298454
- const expiryTime = this.parseTokenExpiry(idToken);
298801
+ const expiryTime = OAuthUtils.parseTokenExpiry(idToken);
298455
298802
  const newTokens = {
298456
298803
  access_token: idToken,
298457
298804
  token_type: "Bearer"
@@ -298471,22 +298818,6 @@ var ServiceAccountImpersonationProvider = class {
298471
298818
  codeVerifier() {
298472
298819
  return "";
298473
298820
  }
298474
- /**
298475
- * Parses a JWT string to extract its expiry time.
298476
- * @param idToken The JWT ID token.
298477
- * @returns The expiry time in **milliseconds**, or undefined if parsing fails.
298478
- */
298479
- parseTokenExpiry(idToken) {
298480
- try {
298481
- const payload = JSON.parse(Buffer.from(idToken.split(".")[1], "base64").toString());
298482
- if (payload && typeof payload.exp === "number") {
298483
- return payload.exp * 1e3;
298484
- }
298485
- } catch (e2) {
298486
- console.error("Failed to parse ID token for expiry time with error:", e2);
298487
- }
298488
- return void 0;
298489
- }
298490
298821
  };
298491
298822
 
298492
298823
  // packages/core/dist/src/tools/mcp-client.js
@@ -298623,7 +298954,7 @@ var MCPOAuthTokenStorage = class {
298623
298954
  }
298624
298955
  } catch (error) {
298625
298956
  if (error.code !== "ENOENT") {
298626
- console.error(`Failed to load MCP OAuth tokens: ${getErrorMessage(error)}`);
298957
+ coreEvents.emitFeedback("error", `Failed to load MCP OAuth tokens: ${getErrorMessage(error)}`, error);
298627
298958
  }
298628
298959
  }
298629
298960
  return tokenMap;
@@ -298646,7 +298977,7 @@ var MCPOAuthTokenStorage = class {
298646
298977
  try {
298647
298978
  await fs25.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), { mode: 384 });
298648
298979
  } catch (error) {
298649
- console.error(`Failed to save MCP OAuth token: ${getErrorMessage(error)}`);
298980
+ coreEvents.emitFeedback("error", `Failed to save MCP OAuth token: ${getErrorMessage(error)}`, error);
298650
298981
  throw error;
298651
298982
  }
298652
298983
  }
@@ -298709,7 +299040,7 @@ var MCPOAuthTokenStorage = class {
298709
299040
  });
298710
299041
  }
298711
299042
  } catch (error) {
298712
- console.error(`Failed to remove MCP OAuth token: ${getErrorMessage(error)}`);
299043
+ coreEvents.emitFeedback("error", `Failed to remove MCP OAuth token: ${getErrorMessage(error)}`, error);
298713
299044
  }
298714
299045
  }
298715
299046
  }
@@ -298738,217 +299069,9 @@ var MCPOAuthTokenStorage = class {
298738
299069
  await fs25.unlink(tokenFile);
298739
299070
  } catch (error) {
298740
299071
  if (error.code !== "ENOENT") {
298741
- console.error(`Failed to clear MCP OAuth tokens: ${getErrorMessage(error)}`);
298742
- }
298743
- }
298744
- }
298745
- };
298746
-
298747
- // packages/core/dist/src/mcp/oauth-utils.js
298748
- var OAuthUtils = class {
298749
- /**
298750
- * Construct well-known OAuth endpoint URLs.
298751
- * By default, uses standard root-based well-known URLs.
298752
- * If includePathSuffix is true, appends any path from the base URL to the well-known endpoints.
298753
- */
298754
- static buildWellKnownUrls(baseUrl, includePathSuffix = false) {
298755
- const serverUrl = new URL(baseUrl);
298756
- const base = `${serverUrl.protocol}//${serverUrl.host}`;
298757
- if (!includePathSuffix) {
298758
- return {
298759
- protectedResource: new URL("/.well-known/oauth-protected-resource", base).toString(),
298760
- authorizationServer: new URL("/.well-known/oauth-authorization-server", base).toString()
298761
- };
298762
- }
298763
- const pathSuffix = serverUrl.pathname.replace(/\/$/, "");
298764
- return {
298765
- protectedResource: new URL(`/.well-known/oauth-protected-resource${pathSuffix}`, base).toString(),
298766
- authorizationServer: new URL(`/.well-known/oauth-authorization-server${pathSuffix}`, base).toString()
298767
- };
298768
- }
298769
- /**
298770
- * Fetch OAuth protected resource metadata.
298771
- *
298772
- * @param resourceMetadataUrl The protected resource metadata URL
298773
- * @returns The protected resource metadata or null if not available
298774
- */
298775
- static async fetchProtectedResourceMetadata(resourceMetadataUrl) {
298776
- try {
298777
- const response = await fetch(resourceMetadataUrl);
298778
- if (!response.ok) {
298779
- return null;
298780
- }
298781
- return await response.json();
298782
- } catch (error) {
298783
- debugLogger.debug(`Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error)}`);
298784
- return null;
298785
- }
298786
- }
298787
- /**
298788
- * Fetch OAuth authorization server metadata.
298789
- *
298790
- * @param authServerMetadataUrl The authorization server metadata URL
298791
- * @returns The authorization server metadata or null if not available
298792
- */
298793
- static async fetchAuthorizationServerMetadata(authServerMetadataUrl) {
298794
- try {
298795
- const response = await fetch(authServerMetadataUrl);
298796
- if (!response.ok) {
298797
- return null;
298798
- }
298799
- return await response.json();
298800
- } catch (error) {
298801
- debugLogger.debug(`Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error)}`);
298802
- return null;
298803
- }
298804
- }
298805
- /**
298806
- * Convert authorization server metadata to OAuth configuration.
298807
- *
298808
- * @param metadata The authorization server metadata
298809
- * @returns The OAuth configuration
298810
- */
298811
- static metadataToOAuthConfig(metadata2) {
298812
- return {
298813
- authorizationUrl: metadata2.authorization_endpoint,
298814
- tokenUrl: metadata2.token_endpoint,
298815
- scopes: metadata2.scopes_supported || [],
298816
- registrationUrl: metadata2.registration_endpoint
298817
- };
298818
- }
298819
- /**
298820
- * Discover Oauth Authorization server metadata given an Auth server URL, by
298821
- * trying the standard well-known endpoints.
298822
- *
298823
- * @param authServerUrl The authorization server URL
298824
- * @returns The authorization server metadata or null if not found
298825
- */
298826
- static async discoverAuthorizationServerMetadata(authServerUrl) {
298827
- const authServerUrlObj = new URL(authServerUrl);
298828
- const base = `${authServerUrlObj.protocol}//${authServerUrlObj.host}`;
298829
- const endpointsToTry = [];
298830
- if (authServerUrlObj.pathname !== "/") {
298831
- endpointsToTry.push(new URL(`/.well-known/oauth-authorization-server${authServerUrlObj.pathname}`, base).toString());
298832
- endpointsToTry.push(new URL(`/.well-known/openid-configuration${authServerUrlObj.pathname}`, base).toString());
298833
- endpointsToTry.push(new URL(`${authServerUrlObj.pathname}/.well-known/openid-configuration`, base).toString());
298834
- }
298835
- endpointsToTry.push(new URL("/.well-known/oauth-authorization-server", base).toString());
298836
- endpointsToTry.push(new URL("/.well-known/openid-configuration", base).toString());
298837
- for (const endpoint of endpointsToTry) {
298838
- const authServerMetadata = await this.fetchAuthorizationServerMetadata(endpoint);
298839
- if (authServerMetadata) {
298840
- return authServerMetadata;
298841
- }
298842
- }
298843
- debugLogger.debug(`Metadata discovery failed for authorization server ${authServerUrl}`);
298844
- return null;
298845
- }
298846
- /**
298847
- * Discover OAuth configuration using the standard well-known endpoints.
298848
- *
298849
- * @param serverUrl The base URL of the server
298850
- * @returns The discovered OAuth configuration or null if not available
298851
- */
298852
- static async discoverOAuthConfig(serverUrl) {
298853
- try {
298854
- const wellKnownUrls = this.buildWellKnownUrls(serverUrl, false);
298855
- let resourceMetadata = await this.fetchProtectedResourceMetadata(wellKnownUrls.protectedResource);
298856
- if (!resourceMetadata) {
298857
- const url4 = new URL(serverUrl);
298858
- if (url4.pathname && url4.pathname !== "/") {
298859
- const pathBasedUrls = this.buildWellKnownUrls(serverUrl, true);
298860
- resourceMetadata = await this.fetchProtectedResourceMetadata(pathBasedUrls.protectedResource);
298861
- }
298862
- }
298863
- if (resourceMetadata?.authorization_servers?.length) {
298864
- const authServerUrl = resourceMetadata.authorization_servers[0];
298865
- const authServerMetadata2 = await this.discoverAuthorizationServerMetadata(authServerUrl);
298866
- if (authServerMetadata2) {
298867
- const config2 = this.metadataToOAuthConfig(authServerMetadata2);
298868
- if (authServerMetadata2.registration_endpoint) {
298869
- debugLogger.log("Dynamic client registration is supported at:", authServerMetadata2.registration_endpoint);
298870
- }
298871
- return config2;
298872
- }
298873
- }
298874
- debugLogger.debug(`Trying OAuth discovery fallback at ${serverUrl}`);
298875
- const authServerMetadata = await this.discoverAuthorizationServerMetadata(serverUrl);
298876
- if (authServerMetadata) {
298877
- const config2 = this.metadataToOAuthConfig(authServerMetadata);
298878
- if (authServerMetadata.registration_endpoint) {
298879
- debugLogger.log("Dynamic client registration is supported at:", authServerMetadata.registration_endpoint);
298880
- }
298881
- return config2;
299072
+ coreEvents.emitFeedback("error", `Failed to clear MCP OAuth tokens: ${getErrorMessage(error)}`, error);
298882
299073
  }
298883
- return null;
298884
- } catch (error) {
298885
- debugLogger.debug(`Failed to discover OAuth configuration: ${getErrorMessage(error)}`);
298886
- return null;
298887
- }
298888
- }
298889
- /**
298890
- * Parse WWW-Authenticate header to extract OAuth information.
298891
- *
298892
- * @param header The WWW-Authenticate header value
298893
- * @returns The resource metadata URI if found
298894
- */
298895
- static parseWWWAuthenticateHeader(header) {
298896
- const match2 = header.match(/resource_metadata="([^"]+)"/);
298897
- if (match2) {
298898
- return match2[1];
298899
- }
298900
- return null;
298901
- }
298902
- /**
298903
- * Discover OAuth configuration from WWW-Authenticate header.
298904
- *
298905
- * @param wwwAuthenticate The WWW-Authenticate header value
298906
- * @returns The discovered OAuth configuration or null if not available
298907
- */
298908
- static async discoverOAuthFromWWWAuthenticate(wwwAuthenticate) {
298909
- const resourceMetadataUri = this.parseWWWAuthenticateHeader(wwwAuthenticate);
298910
- if (!resourceMetadataUri) {
298911
- return null;
298912
- }
298913
- const resourceMetadata = await this.fetchProtectedResourceMetadata(resourceMetadataUri);
298914
- if (!resourceMetadata?.authorization_servers?.length) {
298915
- return null;
298916
- }
298917
- const authServerUrl = resourceMetadata.authorization_servers[0];
298918
- const authServerMetadata = await this.discoverAuthorizationServerMetadata(authServerUrl);
298919
- if (authServerMetadata) {
298920
- return this.metadataToOAuthConfig(authServerMetadata);
298921
299074
  }
298922
- return null;
298923
- }
298924
- /**
298925
- * Extract base URL from an MCP server URL.
298926
- *
298927
- * @param mcpServerUrl The MCP server URL
298928
- * @returns The base URL
298929
- */
298930
- static extractBaseUrl(mcpServerUrl) {
298931
- const serverUrl = new URL(mcpServerUrl);
298932
- return `${serverUrl.protocol}//${serverUrl.host}`;
298933
- }
298934
- /**
298935
- * Check if a URL is an SSE endpoint.
298936
- *
298937
- * @param url The URL to check
298938
- * @returns True if the URL appears to be an SSE endpoint
298939
- */
298940
- static isSSEEndpoint(url4) {
298941
- return url4.includes("/sse") || !url4.includes("/mcp");
298942
- }
298943
- /**
298944
- * Build a resource parameter for OAuth requests.
298945
- *
298946
- * @param endpointUrl The endpoint URL
298947
- * @returns The resource parameter value
298948
- */
298949
- static buildResourceParameter(endpointUrl) {
298950
- const url4 = new URL(endpointUrl);
298951
- return `${url4.protocol}//${url4.host}${url4.pathname}`;
298952
299075
  }
298953
299076
  };
298954
299077
 
@@ -299321,7 +299444,7 @@ var MCPOAuthProvider = class {
299321
299444
  ...config2,
299322
299445
  authorizationUrl: discoveredConfig.authorizationUrl,
299323
299446
  tokenUrl: discoveredConfig.tokenUrl,
299324
- scopes: discoveredConfig.scopes || config2.scopes || [],
299447
+ scopes: config2.scopes || discoveredConfig.scopes || [],
299325
299448
  // Preserve existing client credentials
299326
299449
  clientId: config2.clientId,
299327
299450
  clientSecret: config2.clientSecret
@@ -299339,7 +299462,7 @@ var MCPOAuthProvider = class {
299339
299462
  ...config2,
299340
299463
  authorizationUrl: discoveredConfig.authorizationUrl,
299341
299464
  tokenUrl: discoveredConfig.tokenUrl,
299342
- scopes: discoveredConfig.scopes || config2.scopes || [],
299465
+ scopes: config2.scopes || discoveredConfig.scopes || [],
299343
299466
  registrationUrl: discoveredConfig.registrationUrl,
299344
299467
  // Preserve existing client credentials
299345
299468
  clientId: config2.clientId,
@@ -300302,7 +300425,7 @@ Signal: Signal number or \`(none)\` if no signal was received.
300302
300425
  this.description = description;
300303
300426
  this.parameterSchema = parameterSchema;
300304
300427
  }
300305
- createInvocation(params) {
300428
+ createInvocation(params, _messageBus, _toolName, _displayName) {
300306
300429
  return new DiscoveredToolInvocation(this.config, this.name, params);
300307
300430
  }
300308
300431
  };
@@ -300655,7 +300778,7 @@ var LSToolInvocation = class extends BaseToolInvocation {
300655
300778
  modifiedTime: stats2.mtime
300656
300779
  });
300657
300780
  } catch (error) {
300658
- console.error(`Error accessing ${fullPath}: ${error}`);
300781
+ debugLogger.debug(`Error accessing ${fullPath}: ${error}`);
300659
300782
  }
300660
300783
  }
300661
300784
  entries2.sort((a2, b) => {
@@ -300747,6 +300870,7 @@ var LSTool = class _LSTool extends BaseDeclarativeTool {
300747
300870
 
300748
300871
  // packages/core/dist/src/tools/read-file.js
300749
300872
  import path23 from "node:path";
300873
+ import process9 from "node:process";
300750
300874
 
300751
300875
  // packages/core/dist/src/utils/fileUtils.js
300752
300876
  import fs28 from "node:fs";
@@ -302095,8 +302219,7 @@ Do NOT use this tool:
302095
302219
 
302096
302220
  ## Parameters
302097
302221
 
302098
- - \`fact\` (string, required): The specific fact or piece of information to remember. This should be a clear, self-contained statement. For example, if the user says "My favorite color is blue", the fact would be "My favorite color is blue".
302099
- `;
302222
+ - \`fact\` (string, required): The specific fact or piece of information to remember. This should be a clear, self-contained statement. For example, if the user says "My favorite color is blue", the fact would be "My favorite color is blue".`;
302100
302223
  var DEFAULT_CONTEXT_FILENAME = "GEMINI.md";
302101
302224
  var MEMORY_SECTION_HEADER = "## Gemini Added Memories";
302102
302225
  var currentGeminiMdFilename = DEFAULT_CONTEXT_FILENAME;
@@ -302171,11 +302294,14 @@ ${afterSectionMarker}`.trimEnd() + "\n";
302171
302294
  }
302172
302295
  var MemoryToolInvocation = class _MemoryToolInvocation extends BaseToolInvocation {
302173
302296
  static allowlist = /* @__PURE__ */ new Set();
302297
+ constructor(params, messageBus, toolName, displayName) {
302298
+ super(params, messageBus, toolName, displayName);
302299
+ }
302174
302300
  getDescription() {
302175
302301
  const memoryFilePath = getGlobalMemoryFilePath();
302176
302302
  return `in ${tildeifyPath(memoryFilePath)}`;
302177
302303
  }
302178
- async shouldConfirmExecute(_abortSignal) {
302304
+ async getConfirmationDetails(_abortSignal) {
302179
302305
  const memoryFilePath = getGlobalMemoryFilePath();
302180
302306
  const allowlistKey = memoryFilePath;
302181
302307
  if (_MemoryToolInvocation.allowlist.has(allowlistKey)) {
@@ -302251,8 +302377,8 @@ var MemoryToolInvocation = class _MemoryToolInvocation extends BaseToolInvocatio
302251
302377
  };
302252
302378
  var MemoryTool = class _MemoryTool extends BaseDeclarativeTool {
302253
302379
  static Name = MEMORY_TOOL_NAME;
302254
- constructor() {
302255
- super(_MemoryTool.Name, "Save Memory", memoryToolDescription, Kind.Think, memoryToolSchemaData.parametersJsonSchema);
302380
+ constructor(messageBus) {
302381
+ super(_MemoryTool.Name, "Save Memory", memoryToolDescription, Kind.Think, memoryToolSchemaData.parametersJsonSchema, true, false, messageBus);
302256
302382
  }
302257
302383
  validateToolParamValues(params) {
302258
302384
  if (params.fact.trim() === "") {
@@ -302260,8 +302386,8 @@ var MemoryTool = class _MemoryTool extends BaseDeclarativeTool {
302260
302386
  }
302261
302387
  return null;
302262
302388
  }
302263
- createInvocation(params) {
302264
- return new MemoryToolInvocation(params);
302389
+ createInvocation(params, messageBus, toolName, displayName) {
302390
+ return new MemoryToolInvocation(params, messageBus ?? this.messageBus, toolName ?? this.name, displayName ?? this.displayName);
302265
302391
  }
302266
302392
  static async performAddMemoryEntry(text, memoryFilePath, fsAdapter) {
302267
302393
  try {
@@ -302921,7 +303047,7 @@ var ReadFileTool = class _ReadFileTool extends BaseDeclarativeTool {
302921
303047
  super(_ReadFileTool.Name, "ReadFile", `Reads and returns the content of a specified file. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it can read specific line ranges.`, Kind.Read, {
302922
303048
  properties: {
302923
303049
  absolute_path: {
302924
- description: "The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path.",
303050
+ description: process9.platform === "win32" ? "The absolute path to the file to read (e.g., 'C:\\Users\\project\\file.txt'). Relative paths are not supported. You must provide an absolute path." : "The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path.",
302925
303051
  type: "string"
302926
303052
  },
302927
303053
  offset: {
@@ -302962,8 +303088,9 @@ var ReadFileTool = class _ReadFileTool extends BaseDeclarativeTool {
302962
303088
  return "Limit must be a positive number";
302963
303089
  }
302964
303090
  const fileService = this.config.getFileService();
302965
- if (fileService.shouldGeminiIgnoreFile(params.absolute_path)) {
302966
- return `File path '${filePath}' is ignored by .geminiignore pattern(s).`;
303091
+ const fileFilteringOptions = this.config.getFileFilteringOptions();
303092
+ if (fileService.shouldIgnoreFile(params.absolute_path, fileFilteringOptions)) {
303093
+ return `File path '${filePath}' is ignored by configured ignore patterns.`;
302967
303094
  }
302968
303095
  return null;
302969
303096
  }
@@ -307226,7 +307353,7 @@ var PathScurryBase = class {
307226
307353
  const dirs = /* @__PURE__ */ new Set();
307227
307354
  const queue = [entry];
307228
307355
  let processing = 0;
307229
- const process23 = () => {
307356
+ const process25 = () => {
307230
307357
  let paused = false;
307231
307358
  while (!paused) {
307232
307359
  const dir = queue.shift();
@@ -307241,14 +307368,14 @@ var PathScurryBase = class {
307241
307368
  if (er)
307242
307369
  return results.emit("error", er);
307243
307370
  if (follow && !didRealpaths) {
307244
- const promises2 = [];
307371
+ const promises3 = [];
307245
307372
  for (const e2 of entries2) {
307246
307373
  if (e2.isSymbolicLink()) {
307247
- promises2.push(e2.realpath().then((r2) => r2?.isUnknown() ? r2.lstat() : r2));
307374
+ promises3.push(e2.realpath().then((r2) => r2?.isUnknown() ? r2.lstat() : r2));
307248
307375
  }
307249
307376
  }
307250
- if (promises2.length) {
307251
- Promise.all(promises2).then(() => onReaddir(null, entries2, true));
307377
+ if (promises3.length) {
307378
+ Promise.all(promises3).then(() => onReaddir(null, entries2, true));
307252
307379
  return;
307253
307380
  }
307254
307381
  }
@@ -307267,9 +307394,9 @@ var PathScurryBase = class {
307267
307394
  }
307268
307395
  }
307269
307396
  if (paused && !results.flowing) {
307270
- results.once("drain", process23);
307397
+ results.once("drain", process25);
307271
307398
  } else if (!sync2) {
307272
- process23();
307399
+ process25();
307273
307400
  }
307274
307401
  };
307275
307402
  let sync2 = true;
@@ -307277,7 +307404,7 @@ var PathScurryBase = class {
307277
307404
  sync2 = false;
307278
307405
  }
307279
307406
  };
307280
- process23();
307407
+ process25();
307281
307408
  return results;
307282
307409
  }
307283
307410
  streamSync(entry = this.cwd, opts = {}) {
@@ -307295,7 +307422,7 @@ var PathScurryBase = class {
307295
307422
  }
307296
307423
  const queue = [entry];
307297
307424
  let processing = 0;
307298
- const process23 = () => {
307425
+ const process25 = () => {
307299
307426
  let paused = false;
307300
307427
  while (!paused) {
307301
307428
  const dir = queue.shift();
@@ -307329,9 +307456,9 @@ var PathScurryBase = class {
307329
307456
  }
307330
307457
  }
307331
307458
  if (paused && !results.flowing)
307332
- results.once("drain", process23);
307459
+ results.once("drain", process25);
307333
307460
  };
307334
- process23();
307461
+ process25();
307335
307462
  return results;
307336
307463
  }
307337
307464
  chdir(path64 = this.cwd) {
@@ -308598,7 +308725,7 @@ var GrepToolInvocation = class extends BaseToolInvocation {
308598
308725
  returnDisplay: `Found ${matchCount} ${matchTerm}`
308599
308726
  };
308600
308727
  } catch (error) {
308601
- console.error(`Error during GrepLogic execution: ${error}`);
308728
+ debugLogger.warn(`Error during GrepLogic execution: ${error}`);
308602
308729
  const errorMessage = getErrorMessage(error);
308603
308730
  return {
308604
308731
  llmContent: `Error during grep search operation: ${errorMessage}`,
@@ -308865,7 +308992,7 @@ var GrepToolInvocation = class extends BaseToolInvocation {
308865
308992
  }
308866
308993
  return allMatches;
308867
308994
  } catch (error) {
308868
- console.error(`GrepLogic: Error in performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(error)}`);
308995
+ debugLogger.warn(`GrepLogic: Error in performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(error)}`);
308869
308996
  throw error;
308870
308997
  }
308871
308998
  }
@@ -309213,9 +309340,9 @@ import { spawnSync } from "node:child_process";
309213
309340
  import { debuglog } from "node:util";
309214
309341
 
309215
309342
  // node_modules/execa/lib/utils/standard-stream.js
309216
- import process9 from "node:process";
309343
+ import process10 from "node:process";
309217
309344
  var isStandardStream = (stream3) => STANDARD_STREAMS.includes(stream3);
309218
- var STANDARD_STREAMS = [process9.stdin, process9.stdout, process9.stderr];
309345
+ var STANDARD_STREAMS = [process10.stdin, process10.stdout, process10.stderr];
309219
309346
  var STANDARD_STREAMS_ALIASES = ["stdin", "stdout", "stderr"];
309220
309347
  var getStreamName = (fdNumber) => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;
309221
309348
 
@@ -309350,11 +309477,11 @@ var quoteString = (escapedArgument) => {
309350
309477
  var NO_ESCAPE_REGEXP = /^[\w./-]+$/;
309351
309478
 
309352
309479
  // node_modules/is-unicode-supported/index.js
309353
- import process10 from "node:process";
309480
+ import process11 from "node:process";
309354
309481
  function isUnicodeSupported() {
309355
- const { env: env2 } = process10;
309482
+ const { env: env2 } = process11;
309356
309483
  const { TERM, TERM_PROGRAM } = env2;
309357
- if (process10.platform !== "win32") {
309484
+ if (process11.platform !== "win32") {
309358
309485
  return TERM !== "linux";
309359
309486
  }
309360
309487
  return Boolean(env2.WT_SESSION) || Boolean(env2.TERMINUS_SUBLIME) || env2.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env2.TERMINAL_EMULATOR === "JetBrains-JediTerm";
@@ -309857,10 +309984,10 @@ var handleCommand = (filePath, rawArguments, rawOptions) => {
309857
309984
  // node_modules/execa/lib/arguments/options.js
309858
309985
  var import_cross_spawn2 = __toESM(require_cross_spawn(), 1);
309859
309986
  import path31 from "node:path";
309860
- import process13 from "node:process";
309987
+ import process14 from "node:process";
309861
309988
 
309862
309989
  // node_modules/npm-run-path/index.js
309863
- import process11 from "node:process";
309990
+ import process12 from "node:process";
309864
309991
  import path28 from "node:path";
309865
309992
 
309866
309993
  // node_modules/npm-run-path/node_modules/path-key/index.js
@@ -309901,10 +310028,10 @@ var TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024;
309901
310028
 
309902
310029
  // node_modules/npm-run-path/index.js
309903
310030
  var npmRunPath = ({
309904
- cwd: cwd2 = process11.cwd(),
309905
- path: pathOption = process11.env[pathKey()],
310031
+ cwd: cwd2 = process12.cwd(),
310032
+ path: pathOption = process12.env[pathKey()],
309906
310033
  preferLocal = true,
309907
- execPath: execPath2 = process11.execPath,
310034
+ execPath: execPath2 = process12.execPath,
309908
310035
  addExecPath = true
309909
310036
  } = {}) => {
309910
310037
  const cwdPath = path28.resolve(toPath(cwd2));
@@ -309932,7 +310059,7 @@ var applyExecPath = (result, pathParts, execPath2, cwdPath) => {
309932
310059
  result.push(pathPart);
309933
310060
  }
309934
310061
  };
309935
- var npmRunPathEnv = ({ env: env2 = process11.env, ...options2 } = {}) => {
310062
+ var npmRunPathEnv = ({ env: env2 = process12.env, ...options2 } = {}) => {
309936
310063
  env2 = { ...env2 };
309937
310064
  const pathName = pathKey({ env: env2 });
309938
310065
  options2.path = env2[pathName];
@@ -310662,7 +310789,7 @@ var incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {
310662
310789
  };
310663
310790
 
310664
310791
  // node_modules/execa/lib/ipc/forward.js
310665
- import { EventEmitter as EventEmitter5 } from "node:events";
310792
+ import { EventEmitter as EventEmitter6 } from "node:events";
310666
310793
 
310667
310794
  // node_modules/execa/lib/ipc/incoming.js
310668
310795
  import { once as once2 } from "node:events";
@@ -310744,7 +310871,7 @@ var getIpcEmitter = (anyProcess, channel, isSubprocess) => {
310744
310871
  if (IPC_EMITTERS.has(anyProcess)) {
310745
310872
  return IPC_EMITTERS.get(anyProcess);
310746
310873
  }
310747
- const ipcEmitter = new EventEmitter5();
310874
+ const ipcEmitter = new EventEmitter6();
310748
310875
  ipcEmitter.connected = true;
310749
310876
  IPC_EMITTERS.set(anyProcess, ipcEmitter);
310750
310877
  forwardEvents({
@@ -311202,14 +311329,14 @@ var serializeEncoding = (encoding) => typeof encoding === "string" ? `"${encodin
311202
311329
  // node_modules/execa/lib/arguments/cwd.js
311203
311330
  import { statSync } from "node:fs";
311204
311331
  import path30 from "node:path";
311205
- import process12 from "node:process";
311332
+ import process13 from "node:process";
311206
311333
  var normalizeCwd = (cwd2 = getDefaultCwd()) => {
311207
311334
  const cwdString = safeNormalizeFileUrl(cwd2, 'The "cwd" option');
311208
311335
  return path30.resolve(cwdString);
311209
311336
  };
311210
311337
  var getDefaultCwd = () => {
311211
311338
  try {
311212
- return process12.cwd();
311339
+ return process13.cwd();
311213
311340
  } catch (error) {
311214
311341
  error.message = `The current directory does not exist.
311215
311342
  ${error.message}`;
@@ -311252,7 +311379,7 @@ var normalizeOptions = (filePath, rawArguments, rawOptions) => {
311252
311379
  options2.killSignal = normalizeKillSignal(options2.killSignal);
311253
311380
  options2.forceKillAfterDelay = normalizeForceKillAfterDelay(options2.forceKillAfterDelay);
311254
311381
  options2.lines = options2.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options2.encoding) && options2.buffer[fdNumber]);
311255
- if (process13.platform === "win32" && path31.basename(file, ".exe") === "cmd") {
311382
+ if (process14.platform === "win32" && path31.basename(file, ".exe") === "cmd") {
311256
311383
  commandArguments.unshift("/q");
311257
311384
  }
311258
311385
  return { file, commandArguments, options: options2 };
@@ -311293,7 +311420,7 @@ var addDefaultOptions = ({
311293
311420
  serialization
311294
311421
  });
311295
311422
  var getEnv2 = ({ env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath: nodePath2 }) => {
311296
- const env2 = extendEnv ? { ...process13.env, ...envOption } : envOption;
311423
+ const env2 = extendEnv ? { ...process14.env, ...envOption } : envOption;
311297
311424
  if (preferLocal || node) {
311298
311425
  return npmRunPathEnv({
311299
311426
  env: env2,
@@ -312494,7 +312621,7 @@ var normalizeGenerator = ({ stdioItem, stdioItem: { value }, index, newTransform
312494
312621
  var sortTransforms = (newTransforms, direction) => direction === "input" ? newTransforms.reverse() : newTransforms;
312495
312622
 
312496
312623
  // node_modules/execa/lib/stdio/direction.js
312497
- import process14 from "node:process";
312624
+ import process15 from "node:process";
312498
312625
  var getStreamDirection = (stdioItems, fdNumber, optionName) => {
312499
312626
  const directions = stdioItems.map((stdioItem) => getStdioItemDirection(stdioItem, fdNumber));
312500
312627
  if (directions.includes("input") && directions.includes("output")) {
@@ -312534,10 +312661,10 @@ var guessStreamDirection = {
312534
312661
  }
312535
312662
  };
312536
312663
  var getStandardStreamDirection = (value) => {
312537
- if ([0, process14.stdin].includes(value)) {
312664
+ if ([0, process15.stdin].includes(value)) {
312538
312665
  return "input";
312539
312666
  }
312540
- if ([1, 2, process14.stdout, process14.stderr].includes(value)) {
312667
+ if ([1, 2, process15.stdout, process15.stderr].includes(value)) {
312541
312668
  return "output";
312542
312669
  }
312543
312670
  };
@@ -313641,7 +313768,7 @@ import { setMaxListeners } from "node:events";
313641
313768
  import { spawn as spawn4 } from "node:child_process";
313642
313769
 
313643
313770
  // node_modules/execa/lib/ipc/methods.js
313644
- import process15 from "node:process";
313771
+ import process16 from "node:process";
313645
313772
 
313646
313773
  // node_modules/execa/lib/ipc/get-one.js
313647
313774
  import { once as once5, on as on2 } from "node:events";
@@ -313782,9 +313909,9 @@ var addIpcMethods = (subprocess, { ipc }) => {
313782
313909
  Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));
313783
313910
  };
313784
313911
  var getIpcExport = () => {
313785
- const anyProcess = process15;
313912
+ const anyProcess = process16;
313786
313913
  const isSubprocess = true;
313787
- const ipc = process15.channel !== void 0;
313914
+ const ipc = process16.channel !== void 0;
313788
313915
  return {
313789
313916
  ...getIpcMethods(anyProcess, isSubprocess, ipc),
313790
313917
  getCancelSignal: getCancelSignal.bind(void 0, {
@@ -314250,7 +314377,7 @@ if (process.platform === "linux") {
314250
314377
  }
314251
314378
 
314252
314379
  // node_modules/signal-exit/dist/mjs/index.js
314253
- var processOk = (process23) => !!process23 && typeof process23 === "object" && typeof process23.removeListener === "function" && typeof process23.emit === "function" && typeof process23.reallyExit === "function" && typeof process23.listeners === "function" && typeof process23.kill === "function" && typeof process23.pid === "number" && typeof process23.on === "function";
314380
+ var processOk = (process25) => !!process25 && typeof process25 === "object" && typeof process25.removeListener === "function" && typeof process25.emit === "function" && typeof process25.reallyExit === "function" && typeof process25.listeners === "function" && typeof process25.kill === "function" && typeof process25.pid === "number" && typeof process25.on === "function";
314254
314381
  var kExitEmitter = Symbol.for("signal-exit emitter");
314255
314382
  var global2 = globalThis;
314256
314383
  var ObjectDefineProperty = Object.defineProperty.bind(Object);
@@ -314335,7 +314462,7 @@ var SignalExit = class extends SignalExitBase {
314335
314462
  // "SIGHUP" throws an `ENOSYS` error on Windows,
314336
314463
  // so use a supported signal instead
314337
314464
  /* c8 ignore start */
314338
- #hupSig = process16.platform === "win32" ? "SIGINT" : "SIGHUP";
314465
+ #hupSig = process17.platform === "win32" ? "SIGINT" : "SIGHUP";
314339
314466
  /* c8 ignore stop */
314340
314467
  #emitter = new Emitter();
314341
314468
  #process;
@@ -314343,15 +314470,15 @@ var SignalExit = class extends SignalExitBase {
314343
314470
  #originalProcessReallyExit;
314344
314471
  #sigListeners = {};
314345
314472
  #loaded = false;
314346
- constructor(process23) {
314473
+ constructor(process25) {
314347
314474
  super();
314348
- this.#process = process23;
314475
+ this.#process = process25;
314349
314476
  this.#sigListeners = {};
314350
314477
  for (const sig of signals) {
314351
314478
  this.#sigListeners[sig] = () => {
314352
314479
  const listeners = this.#process.listeners(sig);
314353
314480
  let { count: count2 } = this.#emitter;
314354
- const p = process23;
314481
+ const p = process25;
314355
314482
  if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") {
314356
314483
  count2 += p.__signal_exit_emitter__.count;
314357
314484
  }
@@ -314360,12 +314487,12 @@ var SignalExit = class extends SignalExitBase {
314360
314487
  const ret = this.#emitter.emit("exit", null, sig);
314361
314488
  const s2 = sig === "SIGHUP" ? this.#hupSig : sig;
314362
314489
  if (!ret)
314363
- process23.kill(process23.pid, s2);
314490
+ process25.kill(process25.pid, s2);
314364
314491
  }
314365
314492
  };
314366
314493
  }
314367
- this.#originalProcessReallyExit = process23.reallyExit;
314368
- this.#originalProcessEmit = process23.emit;
314494
+ this.#originalProcessReallyExit = process25.reallyExit;
314495
+ this.#originalProcessEmit = process25.emit;
314369
314496
  }
314370
314497
  onExit(cb, opts) {
314371
314498
  if (!processOk(this.#process)) {
@@ -314446,7 +314573,7 @@ var SignalExit = class extends SignalExitBase {
314446
314573
  }
314447
314574
  }
314448
314575
  };
314449
- var process16 = globalThis.process;
314576
+ var process17 = globalThis.process;
314450
314577
  var {
314451
314578
  /**
314452
314579
  * Called when the process is exiting, whether via signal, explicit
@@ -314474,7 +314601,7 @@ var {
314474
314601
  * @internal
314475
314602
  */
314476
314603
  unload
314477
- } = signalExitWrap(processOk(process16) ? new SignalExit(process16) : new SignalExitFallback());
314604
+ } = signalExitWrap(processOk(process17) ? new SignalExit(process17) : new SignalExitFallback());
314478
314605
 
314479
314606
  // node_modules/execa/lib/terminate/cleanup.js
314480
314607
  var cleanupOnExit = (subprocess, { cleanup, detached }, { signal }) => {
@@ -315223,17 +315350,17 @@ var addConcurrentStream = (concurrentStreams, stream3, waitName) => {
315223
315350
  if (!weakMap.has(stream3)) {
315224
315351
  weakMap.set(stream3, []);
315225
315352
  }
315226
- const promises2 = weakMap.get(stream3);
315353
+ const promises3 = weakMap.get(stream3);
315227
315354
  const promise = createDeferred();
315228
- promises2.push(promise);
315355
+ promises3.push(promise);
315229
315356
  const resolve13 = promise.resolve.bind(promise);
315230
- return { resolve: resolve13, promises: promises2 };
315357
+ return { resolve: resolve13, promises: promises3 };
315231
315358
  };
315232
- var waitForConcurrentStreams = async ({ resolve: resolve13, promises: promises2 }, subprocess) => {
315359
+ var waitForConcurrentStreams = async ({ resolve: resolve13, promises: promises3 }, subprocess) => {
315233
315360
  resolve13();
315234
315361
  const [isSubprocessExit] = await Promise.race([
315235
315362
  Promise.allSettled([true, subprocess]),
315236
- Promise.all([false, ...promises2])
315363
+ Promise.all([false, ...promises3])
315237
315364
  ]);
315238
315365
  return !isSubprocessExit;
315239
315366
  };
@@ -317076,7 +317203,7 @@ function assertWhitespaceString(value, message) {
317076
317203
  var distribution_default = is;
317077
317204
 
317078
317205
  // node_modules/got/dist/source/as-promise/index.js
317079
- import { EventEmitter as EventEmitter7 } from "node:events";
317206
+ import { EventEmitter as EventEmitter8 } from "node:events";
317080
317207
 
317081
317208
  // node_modules/p-cancelable/index.js
317082
317209
  var CancelError = class extends Error {
@@ -317281,7 +317408,7 @@ var AbortError = class extends RequestError2 {
317281
317408
  };
317282
317409
 
317283
317410
  // node_modules/got/dist/source/core/index.js
317284
- import process18 from "node:process";
317411
+ import process19 from "node:process";
317285
317412
  import { Buffer as Buffer8 } from "node:buffer";
317286
317413
  import { Duplex as Duplex4 } from "node:stream";
317287
317414
  import http5, { ServerResponse } from "node:http";
@@ -317392,7 +317519,7 @@ var timer = (request3) => {
317392
317519
  var source_default = timer;
317393
317520
 
317394
317521
  // node_modules/cacheable-request/dist/index.js
317395
- import EventEmitter6 from "node:events";
317522
+ import EventEmitter7 from "node:events";
317396
317523
  import urlLib from "node:url";
317397
317524
  import crypto19 from "node:crypto";
317398
317525
  import stream2, { PassThrough as PassThroughStream2 } from "node:stream";
@@ -317740,7 +317867,7 @@ var CacheableRequest = class {
317740
317867
  ...urlObjectToRequestOptions(url4)
317741
317868
  };
317742
317869
  options2.headers = Object.fromEntries(entries(options2.headers).map(([key2, value]) => [key2.toLowerCase(), value]));
317743
- const ee = new EventEmitter6();
317870
+ const ee = new EventEmitter7();
317744
317871
  const normalizedUrlString = normalizeUrl(urlLib.format(url4), {
317745
317872
  stripWWW: false,
317746
317873
  // eslint-disable-line @typescript-eslint/naming-convention
@@ -318559,7 +318686,7 @@ var calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, comp
318559
318686
  var calculate_retry_delay_default = calculateRetryDelay;
318560
318687
 
318561
318688
  // node_modules/got/dist/source/core/options.js
318562
- import process17 from "node:process";
318689
+ import process18 from "node:process";
318563
318690
  import { promisify as promisify11, inspect as inspect3 } from "node:util";
318564
318691
  import { checkServerIdentity } from "node:tls";
318565
318692
  import https2 from "node:https";
@@ -318957,7 +319084,7 @@ function parseLinkHeader(link2) {
318957
319084
  }
318958
319085
 
318959
319086
  // node_modules/got/dist/source/core/options.js
318960
- var [major2, minor] = process17.versions.node.split(".").map(Number);
319087
+ var [major2, minor] = process18.versions.node.split(".").map(Number);
318961
319088
  function validateSearchParameters(searchParameters) {
318962
319089
  for (const key in searchParameters) {
318963
319090
  const value = searchParameters[key];
@@ -320569,7 +320696,7 @@ function isUnixSocketURL(url4) {
320569
320696
  }
320570
320697
 
320571
320698
  // node_modules/got/dist/source/core/index.js
320572
- var supportsBrotli = distribution_default.string(process18.versions.brotli);
320699
+ var supportsBrotli = distribution_default.string(process19.versions.brotli);
320573
320700
  var methodsWithoutBody = /* @__PURE__ */ new Set(["GET", "HEAD"]);
320574
320701
  var cacheableStore = new WeakableMap();
320575
320702
  var redirectCodes = /* @__PURE__ */ new Set([300, 301, 302, 303, 304, 307, 308]);
@@ -320799,7 +320926,7 @@ var Request = class _Request extends Duplex4 {
320799
320926
  this.emit("retry", this.retryCount + 1, error, (updatedOptions) => {
320800
320927
  const request3 = new _Request(options2.url, updatedOptions, options2);
320801
320928
  request3.retryCount = this.retryCount + 1;
320802
- process18.nextTick(() => {
320929
+ process19.nextTick(() => {
320803
320930
  void request3.flush();
320804
320931
  });
320805
320932
  return request3;
@@ -320992,9 +321119,9 @@ var Request = class _Request extends Duplex4 {
320992
321119
  this.emit("downloadProgress", this.downloadProgress);
320993
321120
  const rawCookies = response.headers["set-cookie"];
320994
321121
  if (distribution_default.object(options2.cookieJar) && rawCookies) {
320995
- let promises2 = rawCookies.map(async (rawCookie) => options2.cookieJar.setCookie(rawCookie, url4.toString()));
321122
+ let promises3 = rawCookies.map(async (rawCookie) => options2.cookieJar.setCookie(rawCookie, url4.toString()));
320996
321123
  if (options2.ignoreInvalidCookies) {
320997
- promises2 = promises2.map(async (promise) => {
321124
+ promises3 = promises3.map(async (promise) => {
320998
321125
  try {
320999
321126
  await promise;
321000
321127
  } catch {
@@ -321002,7 +321129,7 @@ var Request = class _Request extends Duplex4 {
321002
321129
  });
321003
321130
  }
321004
321131
  try {
321005
- await Promise.all(promises2);
321132
+ await Promise.all(promises3);
321006
321133
  } catch (error) {
321007
321134
  this._beforeError(error);
321008
321135
  return;
@@ -321471,7 +321598,7 @@ function asPromise(firstRequest) {
321471
321598
  let globalRequest;
321472
321599
  let globalResponse;
321473
321600
  let normalizedOptions;
321474
- const emitter = new EventEmitter7();
321601
+ const emitter = new EventEmitter8();
321475
321602
  const promise = new PCancelable((resolve13, reject, onCancel) => {
321476
321603
  onCancel(() => {
321477
321604
  globalRequest.destroy();
@@ -321862,7 +321989,7 @@ var getTarget = () => {
321862
321989
  var downloadFile2 = async (url4, outFile) => {
321863
321990
  let tmpDir = void 0;
321864
321991
  try {
321865
- tmpDir = await import_fs_extra.default.mkdtemp("download-ripgrep");
321992
+ tmpDir = await import_fs_extra.default.mkdtemp(path33.join(os8.tmpdir(), "download-ripgrep"));
321866
321993
  const tmpFile = path33.join(tmpDir, "tmp-file");
321867
321994
  await pipeline2(source_default2.stream(url4), createWriteStream5(tmpFile));
321868
321995
  await mkdir3(dirname7(outFile), { recursive: true });
@@ -322421,8 +322548,8 @@ ${fileListDescription}`;
322421
322548
  returnDisplay: `Found ${fileCount} matching file(s)`
322422
322549
  };
322423
322550
  } catch (error) {
322424
- const errorMessage = error instanceof Error ? error.message : String(error);
322425
- console.error(`GlobLogic execute Error: ${errorMessage}`, error);
322551
+ debugLogger.warn(`GlobLogic execute Error`, error);
322552
+ const errorMessage = getErrorMessage(error);
322426
322553
  const rawError = `Error during glob search operation: ${errorMessage}`;
322427
322554
  return {
322428
322555
  llmContent: rawError,
@@ -322501,6 +322628,7 @@ var GlobTool = class _GlobTool extends BaseDeclarativeTool {
322501
322628
  // packages/core/dist/src/tools/edit.js
322502
322629
  import * as fs36 from "node:fs";
322503
322630
  import * as path38 from "node:path";
322631
+ import process20 from "node:process";
322504
322632
 
322505
322633
  // packages/core/dist/src/utils/LruCache.js
322506
322634
  var LruCache = class {
@@ -324000,12 +324128,11 @@ function applyReplacement(currentContent, oldString, newString, isNewFile) {
324000
324128
  }
324001
324129
  return safeLiteralReplace(currentContent, oldString, newString);
324002
324130
  }
324003
- var EditToolInvocation = class {
324131
+ var EditToolInvocation = class extends BaseToolInvocation {
324004
324132
  config;
324005
- params;
324006
- constructor(config2, params) {
324133
+ constructor(config2, params, messageBus, toolName, displayName) {
324134
+ super(params, messageBus, toolName, displayName);
324007
324135
  this.config = config2;
324008
- this.params = params;
324009
324136
  }
324010
324137
  toolLocations() {
324011
324138
  return [{ path: this.params.file_path }];
@@ -324101,7 +324228,7 @@ var EditToolInvocation = class {
324101
324228
  * Handles the confirmation prompt for the Edit tool in the CLI.
324102
324229
  * It needs to calculate the diff to show the user.
324103
324230
  */
324104
- async shouldConfirmExecute(abortSignal) {
324231
+ async getConfirmationDetails(abortSignal) {
324105
324232
  if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
324106
324233
  return false;
324107
324234
  }
@@ -324255,8 +324382,11 @@ var EditToolInvocation = class {
324255
324382
  var EditTool = class _EditTool extends BaseDeclarativeTool {
324256
324383
  config;
324257
324384
  static Name = EDIT_TOOL_NAME;
324258
- constructor(config2) {
324259
- super(_EditTool.Name, "Edit", `Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
324385
+ constructor(config2, messageBus) {
324386
+ super(
324387
+ _EditTool.Name,
324388
+ "Edit",
324389
+ `Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
324260
324390
 
324261
324391
  The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
324262
324392
 
@@ -324266,29 +324396,37 @@ Expectation for required parameters:
324266
324396
  3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic.
324267
324397
  4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
324268
324398
  **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
324269
- **Multiple replacements:** Set \`expected_replacements\` to the number of occurrences you want to replace. The tool will replace ALL occurrences that match \`old_string\` exactly. Ensure the number of replacements matches your expectation.`, Kind.Edit, {
324270
- properties: {
324271
- file_path: {
324272
- description: "The absolute path to the file to modify. Must start with '/'.",
324273
- type: "string"
324274
- },
324275
- old_string: {
324276
- description: "The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. For multiple replacements, specify expected_replacements parameter. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.",
324277
- type: "string"
324278
- },
324279
- new_string: {
324280
- description: "The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",
324281
- type: "string"
324399
+ **Multiple replacements:** Set \`expected_replacements\` to the number of occurrences you want to replace. The tool will replace ALL occurrences that match \`old_string\` exactly. Ensure the number of replacements matches your expectation.`,
324400
+ Kind.Edit,
324401
+ {
324402
+ properties: {
324403
+ file_path: {
324404
+ description: process20.platform === "win32" ? "The absolute path to the file to modify (e.g., 'C:\\Users\\project\\file.txt'). Must be an absolute path." : "The absolute path to the file to modify (e.g., '/home/user/project/file.txt'). Must start with '/'.",
324405
+ type: "string"
324406
+ },
324407
+ old_string: {
324408
+ description: "The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. For multiple replacements, specify expected_replacements parameter. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.",
324409
+ type: "string"
324410
+ },
324411
+ new_string: {
324412
+ description: "The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",
324413
+ type: "string"
324414
+ },
324415
+ expected_replacements: {
324416
+ type: "number",
324417
+ description: "Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.",
324418
+ minimum: 1
324419
+ }
324282
324420
  },
324283
- expected_replacements: {
324284
- type: "number",
324285
- description: "Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.",
324286
- minimum: 1
324287
- }
324421
+ required: ["file_path", "old_string", "new_string"],
324422
+ type: "object"
324288
324423
  },
324289
- required: ["file_path", "old_string", "new_string"],
324290
- type: "object"
324291
- });
324424
+ true,
324425
+ // isOutputMarkdown
324426
+ false,
324427
+ // canUpdateOutput
324428
+ messageBus
324429
+ );
324292
324430
  this.config = config2;
324293
324431
  }
324294
324432
  /**
@@ -324310,8 +324448,8 @@ Expectation for required parameters:
324310
324448
  }
324311
324449
  return null;
324312
324450
  }
324313
- createInvocation(params) {
324314
- return new EditToolInvocation(this.config, params);
324451
+ createInvocation(params, messageBus, toolName, displayName) {
324452
+ return new EditToolInvocation(this.config, params, messageBus ?? this.messageBus, toolName ?? this.name, displayName ?? this.displayName);
324315
324453
  }
324316
324454
  getModifyContext(_) {
324317
324455
  return {
@@ -324658,6 +324796,226 @@ async function reportError(error, baseMessage, context2, type = "general", repor
324658
324796
  }
324659
324797
  }
324660
324798
 
324799
+ // packages/core/dist/src/utils/googleErrors.js
324800
+ function parseGoogleApiError(error) {
324801
+ if (!error) {
324802
+ return null;
324803
+ }
324804
+ let errorObj = error;
324805
+ if (typeof errorObj === "string") {
324806
+ try {
324807
+ errorObj = JSON.parse(errorObj);
324808
+ } catch (_) {
324809
+ return null;
324810
+ }
324811
+ }
324812
+ if (Array.isArray(errorObj) && errorObj.length > 0) {
324813
+ errorObj = errorObj[0];
324814
+ }
324815
+ if (typeof errorObj !== "object" || errorObj === null) {
324816
+ return null;
324817
+ }
324818
+ let currentError = fromGaxiosError(errorObj) ?? fromApiError(errorObj);
324819
+ let depth = 0;
324820
+ const maxDepth = 10;
324821
+ while (currentError && typeof currentError.message === "string" && depth < maxDepth) {
324822
+ try {
324823
+ const parsedMessage = JSON.parse(currentError.message.replace(/\u00A0/g, "").replace(/\n/g, " "));
324824
+ if (parsedMessage.error) {
324825
+ currentError = parsedMessage.error;
324826
+ depth++;
324827
+ } else {
324828
+ break;
324829
+ }
324830
+ } catch (_error) {
324831
+ break;
324832
+ }
324833
+ }
324834
+ if (!currentError) {
324835
+ return null;
324836
+ }
324837
+ const code2 = currentError.code;
324838
+ const message = currentError.message;
324839
+ const errorDetails = currentError.details;
324840
+ if (Array.isArray(errorDetails) && code2 && message) {
324841
+ const details = [];
324842
+ for (const detail of errorDetails) {
324843
+ if (detail && typeof detail === "object") {
324844
+ const detailObj = detail;
324845
+ const typeKey = Object.keys(detailObj).find((key) => key.trim() === "@type");
324846
+ if (typeKey) {
324847
+ if (typeKey !== "@type") {
324848
+ detailObj["@type"] = detailObj[typeKey];
324849
+ delete detailObj[typeKey];
324850
+ }
324851
+ details.push(detailObj);
324852
+ }
324853
+ }
324854
+ }
324855
+ if (details.length > 0) {
324856
+ return {
324857
+ code: code2,
324858
+ message,
324859
+ details
324860
+ };
324861
+ }
324862
+ }
324863
+ return null;
324864
+ }
324865
+ function fromGaxiosError(errorObj) {
324866
+ const gaxiosError = errorObj;
324867
+ let outerError;
324868
+ if (gaxiosError.response?.data) {
324869
+ let data = gaxiosError.response.data;
324870
+ if (typeof data === "string") {
324871
+ try {
324872
+ data = JSON.parse(data);
324873
+ } catch (_) {
324874
+ }
324875
+ }
324876
+ if (Array.isArray(data) && data.length > 0) {
324877
+ data = data[0];
324878
+ }
324879
+ if (typeof data === "object" && data !== null) {
324880
+ if ("error" in data) {
324881
+ outerError = data.error;
324882
+ }
324883
+ }
324884
+ }
324885
+ if (!outerError) {
324886
+ if (gaxiosError.error) {
324887
+ outerError = gaxiosError.error;
324888
+ } else {
324889
+ return void 0;
324890
+ }
324891
+ }
324892
+ return outerError;
324893
+ }
324894
+ function fromApiError(errorObj) {
324895
+ const apiError = errorObj;
324896
+ let outerError;
324897
+ if (apiError.message) {
324898
+ let data = apiError.message;
324899
+ if (typeof data === "string") {
324900
+ try {
324901
+ data = JSON.parse(data);
324902
+ } catch (_) {
324903
+ }
324904
+ }
324905
+ if (Array.isArray(data) && data.length > 0) {
324906
+ data = data[0];
324907
+ }
324908
+ if (typeof data === "object" && data !== null) {
324909
+ if ("error" in data) {
324910
+ outerError = data.error;
324911
+ }
324912
+ }
324913
+ }
324914
+ return outerError;
324915
+ }
324916
+
324917
+ // packages/core/dist/src/utils/googleQuotaErrors.js
324918
+ var TerminalQuotaError = class extends Error {
324919
+ cause;
324920
+ constructor(message, cause) {
324921
+ super(message);
324922
+ this.cause = cause;
324923
+ this.name = "TerminalQuotaError";
324924
+ }
324925
+ };
324926
+ var RetryableQuotaError = class extends Error {
324927
+ cause;
324928
+ retryDelayMs;
324929
+ constructor(message, cause, retryDelaySeconds) {
324930
+ super(message);
324931
+ this.cause = cause;
324932
+ this.name = "RetryableQuotaError";
324933
+ this.retryDelayMs = retryDelaySeconds * 1e3;
324934
+ }
324935
+ };
324936
+ function parseDurationInSeconds(duration) {
324937
+ if (!duration.endsWith("s")) {
324938
+ return null;
324939
+ }
324940
+ const seconds = parseFloat(duration.slice(0, -1));
324941
+ return isNaN(seconds) ? null : seconds;
324942
+ }
324943
+ function classifyGoogleError(error) {
324944
+ const googleApiError = parseGoogleApiError(error);
324945
+ if (!googleApiError || googleApiError.code !== 429) {
324946
+ return error;
324947
+ }
324948
+ const quotaFailure = googleApiError.details.find((d) => d["@type"] === "type.googleapis.com/google.rpc.QuotaFailure");
324949
+ const errorInfo = googleApiError.details.find((d) => d["@type"] === "type.googleapis.com/google.rpc.ErrorInfo");
324950
+ const retryInfo = googleApiError.details.find((d) => d["@type"] === "type.googleapis.com/google.rpc.RetryInfo");
324951
+ if (quotaFailure) {
324952
+ for (const violation of quotaFailure.violations) {
324953
+ const quotaId = violation.quotaId ?? "";
324954
+ if (quotaId.includes("PerDay") || quotaId.includes("Daily")) {
324955
+ return new TerminalQuotaError(`${googleApiError.message}
324956
+ Expected quota reset within 24h.`, googleApiError);
324957
+ }
324958
+ }
324959
+ }
324960
+ if (errorInfo) {
324961
+ if (errorInfo.domain) {
324962
+ const validDomains = [
324963
+ "cloudcode-pa.googleapis.com",
324964
+ "staging-cloudcode-pa.googleapis.com",
324965
+ "autopush-cloudcode-pa.googleapis.com"
324966
+ ];
324967
+ if (validDomains.includes(errorInfo.domain)) {
324968
+ if (errorInfo.reason === "RATE_LIMIT_EXCEEDED") {
324969
+ let delaySeconds = 10;
324970
+ if (retryInfo?.retryDelay) {
324971
+ const parsedDelay = parseDurationInSeconds(retryInfo.retryDelay);
324972
+ if (parsedDelay) {
324973
+ delaySeconds = parsedDelay;
324974
+ }
324975
+ }
324976
+ return new RetryableQuotaError(`${googleApiError.message}`, googleApiError, delaySeconds);
324977
+ }
324978
+ if (errorInfo.reason === "QUOTA_EXHAUSTED") {
324979
+ return new TerminalQuotaError(`${googleApiError.message}`, googleApiError);
324980
+ }
324981
+ }
324982
+ }
324983
+ const quotaLimit = errorInfo.metadata?.["quota_limit"] ?? "";
324984
+ if (quotaLimit.includes("PerDay") || quotaLimit.includes("Daily")) {
324985
+ return new TerminalQuotaError(`${googleApiError.message}
324986
+ Expected quota reset within 24h.`, googleApiError);
324987
+ }
324988
+ }
324989
+ if (retryInfo?.retryDelay) {
324990
+ const delaySeconds = parseDurationInSeconds(retryInfo.retryDelay);
324991
+ if (delaySeconds) {
324992
+ if (delaySeconds > 120) {
324993
+ return new TerminalQuotaError(`${googleApiError.message}
324994
+ Suggested retry after ${retryInfo.retryDelay}.`, googleApiError);
324995
+ }
324996
+ return new RetryableQuotaError(`${googleApiError.message}
324997
+ Suggested retry after ${retryInfo.retryDelay}.`, googleApiError, delaySeconds);
324998
+ }
324999
+ }
325000
+ if (quotaFailure) {
325001
+ for (const violation of quotaFailure.violations) {
325002
+ const quotaId = violation.quotaId ?? "";
325003
+ if (quotaId.includes("PerMinute")) {
325004
+ return new RetryableQuotaError(`${googleApiError.message}
325005
+ Suggested retry after 60s.`, googleApiError, 60);
325006
+ }
325007
+ }
325008
+ }
325009
+ if (errorInfo) {
325010
+ const quotaLimit = errorInfo.metadata?.["quota_limit"] ?? "";
325011
+ if (quotaLimit.includes("PerMinute")) {
325012
+ return new RetryableQuotaError(`${errorInfo.reason}
325013
+ Suggested retry after 60s.`, googleApiError, 60);
325014
+ }
325015
+ }
325016
+ return error;
325017
+ }
325018
+
324661
325019
  // packages/core/dist/src/utils/delay.js
324662
325020
  function createAbortError() {
324663
325021
  const abortError = new Error("Aborted");
@@ -324688,7 +325046,7 @@ function delay2(ms, signal) {
324688
325046
  // packages/core/dist/src/utils/retry.js
324689
325047
  var FETCH_FAILED_MESSAGE = "exception TypeError: fetch failed sending request";
324690
325048
  var DEFAULT_RETRY_OPTIONS = {
324691
- maxAttempts: 5,
325049
+ maxAttempts: 3,
324692
325050
  initialDelayMs: 5e3,
324693
325051
  maxDelayMs: 3e4,
324694
325052
  // 30 seconds
@@ -324723,7 +325081,6 @@ async function retryWithBackoff(fn, options2) {
324723
325081
  };
324724
325082
  let attempt = 0;
324725
325083
  let currentDelay = initialDelayMs;
324726
- let consecutive429Count = 0;
324727
325084
  while (attempt < maxAttempts) {
324728
325085
  if (signal?.aborted) {
324729
325086
  throw createAbortError();
@@ -324743,72 +325100,51 @@ async function retryWithBackoff(fn, options2) {
324743
325100
  if (error instanceof Error && error.name === "AbortError") {
324744
325101
  throw error;
324745
325102
  }
324746
- const errorStatus = getErrorStatus(error);
324747
- if (errorStatus === 429 && authType === AuthType2.LOGIN_WITH_GOOGLE && isProQuotaExceededError(error) && onPersistent429) {
324748
- try {
324749
- const fallbackModel = await onPersistent429(authType, error);
324750
- if (fallbackModel !== false && fallbackModel !== null) {
324751
- attempt = 0;
324752
- consecutive429Count = 0;
324753
- currentDelay = initialDelayMs;
324754
- continue;
324755
- } else {
324756
- throw error;
324757
- }
324758
- } catch (fallbackError) {
324759
- debugLogger.warn("Fallback to Flash model failed:", fallbackError);
324760
- }
324761
- }
324762
- if (errorStatus === 429 && authType === AuthType2.LOGIN_WITH_GOOGLE && !isProQuotaExceededError(error) && isGenericQuotaExceededError(error) && onPersistent429) {
324763
- try {
324764
- const fallbackModel = await onPersistent429(authType, error);
324765
- if (fallbackModel !== false && fallbackModel !== null) {
324766
- attempt = 0;
324767
- consecutive429Count = 0;
324768
- currentDelay = initialDelayMs;
324769
- continue;
324770
- } else {
324771
- throw error;
325103
+ const classifiedError = classifyGoogleError(error);
325104
+ if (classifiedError instanceof TerminalQuotaError) {
325105
+ if (onPersistent429 && authType === AuthType2.LOGIN_WITH_GOOGLE) {
325106
+ try {
325107
+ const fallbackModel = await onPersistent429(authType, classifiedError);
325108
+ if (fallbackModel) {
325109
+ attempt = 0;
325110
+ currentDelay = initialDelayMs;
325111
+ continue;
325112
+ }
325113
+ } catch (fallbackError) {
325114
+ debugLogger.warn("Fallback to Flash model failed:", fallbackError);
324772
325115
  }
324773
- } catch (fallbackError) {
324774
- debugLogger.warn("Fallback to Flash model failed:", fallbackError);
324775
325116
  }
325117
+ throw classifiedError;
324776
325118
  }
324777
- if (errorStatus === 429) {
324778
- consecutive429Count++;
324779
- } else {
324780
- consecutive429Count = 0;
324781
- }
324782
- if (consecutive429Count >= 2 && onPersistent429 && authType === AuthType2.LOGIN_WITH_GOOGLE) {
324783
- try {
324784
- const fallbackModel = await onPersistent429(authType, error);
324785
- if (fallbackModel !== false && fallbackModel !== null) {
324786
- attempt = 0;
324787
- consecutive429Count = 0;
324788
- currentDelay = initialDelayMs;
324789
- continue;
324790
- } else {
324791
- throw error;
325119
+ if (classifiedError instanceof RetryableQuotaError) {
325120
+ if (attempt >= maxAttempts) {
325121
+ if (onPersistent429 && authType === AuthType2.LOGIN_WITH_GOOGLE) {
325122
+ try {
325123
+ const fallbackModel = await onPersistent429(authType, classifiedError);
325124
+ if (fallbackModel) {
325125
+ attempt = 0;
325126
+ currentDelay = initialDelayMs;
325127
+ continue;
325128
+ }
325129
+ } catch (fallbackError) {
325130
+ console.warn("Model fallback failed:", fallbackError);
325131
+ }
324792
325132
  }
324793
- } catch (fallbackError) {
324794
- debugLogger.warn("Fallback to Flash model failed:", fallbackError);
325133
+ throw classifiedError;
324795
325134
  }
325135
+ console.warn(`Attempt ${attempt} failed: ${classifiedError.message}. Retrying after ${classifiedError.retryDelayMs}ms...`);
325136
+ await delay2(classifiedError.retryDelayMs, signal);
325137
+ continue;
324796
325138
  }
324797
325139
  if (attempt >= maxAttempts || !shouldRetryOnError(error, retryFetchErrors)) {
324798
325140
  throw error;
324799
325141
  }
324800
- const { delayDurationMs, errorStatus: delayErrorStatus } = getDelayDurationAndStatus(error);
324801
- if (delayDurationMs > 0) {
324802
- debugLogger.warn(`Attempt ${attempt} failed with status ${delayErrorStatus ?? "unknown"}. Retrying after explicit delay of ${delayDurationMs}ms...`, error);
324803
- await delay2(delayDurationMs, signal);
324804
- currentDelay = initialDelayMs;
324805
- } else {
324806
- logRetryAttempt(attempt, error, errorStatus);
324807
- const jitter = currentDelay * 0.3 * (Math.random() * 2 - 1);
324808
- const delayWithJitter = Math.max(0, currentDelay + jitter);
324809
- await delay2(delayWithJitter, signal);
324810
- currentDelay = Math.min(maxDelayMs, currentDelay * 2);
324811
- }
325142
+ const errorStatus = getErrorStatus(error);
325143
+ logRetryAttempt(attempt, error, errorStatus);
325144
+ const jitter = currentDelay * 0.3 * (Math.random() * 2 - 1);
325145
+ const delayWithJitter = Math.max(0, currentDelay + jitter);
325146
+ await delay2(delayWithJitter, signal);
325147
+ currentDelay = Math.min(maxDelayMs, currentDelay * 2);
324812
325148
  }
324813
325149
  }
324814
325150
  throw new Error("Retry attempts exhausted");
@@ -324827,36 +325163,6 @@ function getErrorStatus(error) {
324827
325163
  }
324828
325164
  return void 0;
324829
325165
  }
324830
- function getRetryAfterDelayMs(error) {
324831
- if (typeof error === "object" && error !== null) {
324832
- if ("response" in error && typeof error.response === "object" && error.response !== null) {
324833
- const response = error.response;
324834
- if ("headers" in response && typeof response.headers === "object" && response.headers !== null) {
324835
- const headers = response.headers;
324836
- const retryAfterHeader = headers["retry-after"];
324837
- if (typeof retryAfterHeader === "string") {
324838
- const retryAfterSeconds = parseInt(retryAfterHeader, 10);
324839
- if (!isNaN(retryAfterSeconds)) {
324840
- return retryAfterSeconds * 1e3;
324841
- }
324842
- const retryAfterDate = new Date(retryAfterHeader);
324843
- if (!isNaN(retryAfterDate.getTime())) {
324844
- return Math.max(0, retryAfterDate.getTime() - Date.now());
324845
- }
324846
- }
324847
- }
324848
- }
324849
- }
324850
- return 0;
324851
- }
324852
- function getDelayDurationAndStatus(error) {
324853
- const errorStatus = getErrorStatus(error);
324854
- let delayDurationMs = 0;
324855
- if (errorStatus === 429) {
324856
- delayDurationMs = getRetryAfterDelayMs(error);
324857
- }
324858
- return { delayDurationMs, errorStatus };
324859
- }
324860
325166
  function logRetryAttempt(attempt, error, errorStatus) {
324861
325167
  let message = `Attempt ${attempt} failed. Retrying with backoff...`;
324862
325168
  if (errorStatus) {
@@ -325272,12 +325578,11 @@ function getErrorReplaceResult(params, occurrences, expectedReplacements, finalO
325272
325578
  }
325273
325579
  return error;
325274
325580
  }
325275
- var EditToolInvocation2 = class {
325581
+ var EditToolInvocation2 = class extends BaseToolInvocation {
325276
325582
  config;
325277
- params;
325278
- constructor(config2, params) {
325583
+ constructor(config2, params, messageBus, toolName, displayName) {
325584
+ super(params, messageBus, toolName, displayName);
325279
325585
  this.config = config2;
325280
- this.params = params;
325281
325586
  }
325282
325587
  toolLocations() {
325283
325588
  return [{ path: this.params.file_path }];
@@ -325444,7 +325749,7 @@ var EditToolInvocation2 = class {
325444
325749
  * Handles the confirmation prompt for the Edit tool in the CLI.
325445
325750
  * It needs to calculate the diff to show the user.
325446
325751
  */
325447
- async shouldConfirmExecute(abortSignal) {
325752
+ async getConfirmationDetails(abortSignal) {
325448
325753
  if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
325449
325754
  return false;
325450
325755
  }
@@ -325602,8 +325907,11 @@ var EditToolInvocation2 = class {
325602
325907
  var SmartEditTool = class _SmartEditTool extends BaseDeclarativeTool {
325603
325908
  config;
325604
325909
  static Name = EDIT_TOOL_NAME;
325605
- constructor(config2) {
325606
- super(_SmartEditTool.Name, "Edit", `Replaces text within a file. Replaces a single occurrence. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
325910
+ constructor(config2, messageBus) {
325911
+ super(
325912
+ _SmartEditTool.Name,
325913
+ "Edit",
325914
+ `Replaces text within a file. Replaces a single occurrence. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
325607
325915
 
325608
325916
  The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
325609
325917
 
@@ -325615,14 +325923,16 @@ var SmartEditTool = class _SmartEditTool extends BaseDeclarativeTool {
325615
325923
  5. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
325616
325924
  **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
325617
325925
  6. Prefer to break down complex and long changes into multiple smaller atomic calls to this tool. Always check the content of the file after changes or not finding a string to match.
325618
- **Multiple replacements:** If there are multiple and ambiguous occurences of the \`old_string\` in the file, the tool will also fail.`, Kind.Edit, {
325619
- properties: {
325620
- file_path: {
325621
- description: "The absolute path to the file to modify. Must start with '/'.",
325622
- type: "string"
325623
- },
325624
- instruction: {
325625
- description: `A clear, semantic instruction for the code change, acting as a high-quality prompt for an expert LLM assistant. It must be self-contained and explain the goal of the change.
325926
+ **Multiple replacements:** If there are multiple and ambiguous occurences of the \`old_string\` in the file, the tool will also fail.`,
325927
+ Kind.Edit,
325928
+ {
325929
+ properties: {
325930
+ file_path: {
325931
+ description: "The absolute path to the file to modify. Must start with '/'.",
325932
+ type: "string"
325933
+ },
325934
+ instruction: {
325935
+ description: `A clear, semantic instruction for the code change, acting as a high-quality prompt for an expert LLM assistant. It must be self-contained and explain the goal of the change.
325626
325936
 
325627
325937
  A good instruction should concisely answer:
325628
325938
  1. WHY is the change needed? (e.g., "To fix a bug where users can be null...")
@@ -325637,20 +325947,26 @@ A good instruction should concisely answer:
325637
325947
  - "Fix the bug." (Doesn't explain the bug or the fix)
325638
325948
  - "Replace the line with this new line." (Brittle, just repeats the other parameters)
325639
325949
  `,
325640
- type: "string"
325641
- },
325642
- old_string: {
325643
- description: "The exact literal text to replace, preferably unescaped. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.",
325644
- type: "string"
325950
+ type: "string"
325951
+ },
325952
+ old_string: {
325953
+ description: "The exact literal text to replace, preferably unescaped. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.",
325954
+ type: "string"
325955
+ },
325956
+ new_string: {
325957
+ description: "The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",
325958
+ type: "string"
325959
+ }
325645
325960
  },
325646
- new_string: {
325647
- description: "The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",
325648
- type: "string"
325649
- }
325961
+ required: ["file_path", "instruction", "old_string", "new_string"],
325962
+ type: "object"
325650
325963
  },
325651
- required: ["file_path", "instruction", "old_string", "new_string"],
325652
- type: "object"
325653
- });
325964
+ true,
325965
+ // isOutputMarkdown
325966
+ false,
325967
+ // canUpdateOutput
325968
+ messageBus
325969
+ );
325654
325970
  this.config = config2;
325655
325971
  }
325656
325972
  /**
@@ -325680,7 +325996,7 @@ A good instruction should concisely answer:
325680
325996
  return null;
325681
325997
  }
325682
325998
  createInvocation(params) {
325683
- return new EditToolInvocation2(this.config, params);
325999
+ return new EditToolInvocation2(this.config, params, this.messageBus, this.name, this.displayName);
325684
326000
  }
325685
326001
  getModifyContext(_) {
325686
326002
  return {
@@ -325756,9 +326072,17 @@ async function summarizeToolOutput(textToSummarize, geminiClient, abortSignal, m
325756
326072
  }
325757
326073
  }
325758
326074
 
326075
+ // node_modules/ansi-regex/index.js
326076
+ function ansiRegex({ onlyFirst = false } = {}) {
326077
+ const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
326078
+ const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
326079
+ const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
326080
+ const pattern = `${osc}|${csi}`;
326081
+ return new RegExp(pattern, onlyFirst ? void 0 : "g");
326082
+ }
326083
+
325759
326084
  // node_modules/strip-ansi/index.js
325760
- var import_ansi_regex = __toESM(require_ansi_regex(), 1);
325761
- var regex = (0, import_ansi_regex.default)();
326085
+ var regex = ansiRegex();
325762
326086
  function stripAnsi(string) {
325763
326087
  if (typeof string !== "string") {
325764
326088
  throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
@@ -331296,8 +331620,8 @@ var OUTPUT_UPDATE_INTERVAL_MS = 1e3;
331296
331620
  var ShellToolInvocation = class extends BaseToolInvocation {
331297
331621
  config;
331298
331622
  allowlist;
331299
- constructor(config2, params, allowlist) {
331300
- super(params);
331623
+ constructor(config2, params, allowlist, messageBus) {
331624
+ super(params, messageBus);
331301
331625
  this.config = config2;
331302
331626
  this.allowlist = allowlist;
331303
331627
  }
@@ -331311,13 +331635,11 @@ var ShellToolInvocation = class extends BaseToolInvocation {
331311
331635
  }
331312
331636
  return description;
331313
331637
  }
331314
- async shouldConfirmExecute(_abortSignal) {
331638
+ async getConfirmationDetails(_abortSignal) {
331315
331639
  const command = stripShellWrapper(this.params.command);
331316
331640
  const rootCommands = [...new Set(getCommandRoots(command))];
331317
331641
  if (!this.config.isInteractive() && this.config.getApprovalMode() !== ApprovalMode.YOLO) {
331318
- const allowedTools = this.config.getAllowedTools() || [];
331319
- const [SHELL_TOOL_NAME2] = SHELL_TOOL_NAMES;
331320
- if (doesToolInvocationMatch(SHELL_TOOL_NAME2, command, allowedTools)) {
331642
+ if (this.isInvocationAllowlisted(command)) {
331321
331643
  return false;
331322
331644
  }
331323
331645
  throw new Error(`Command "${command}" is not in the list of allowed tools for non-interactive mode.`);
@@ -331484,6 +331806,14 @@ ${result.output}`;
331484
331806
  }
331485
331807
  }
331486
331808
  }
331809
+ isInvocationAllowlisted(command) {
331810
+ const allowedTools = this.config.getAllowedTools() || [];
331811
+ if (allowedTools.length === 0) {
331812
+ return false;
331813
+ }
331814
+ const invocation = { params: { command } };
331815
+ return isShellInvocationAllowlisted(invocation, allowedTools);
331816
+ }
331487
331817
  };
331488
331818
  function getShellToolDescription() {
331489
331819
  const returnedInfo = `
@@ -331516,7 +331846,7 @@ var ShellTool = class _ShellTool extends BaseDeclarativeTool {
331516
331846
  config;
331517
331847
  static Name = SHELL_TOOL_NAME;
331518
331848
  allowlist = /* @__PURE__ */ new Set();
331519
- constructor(config2) {
331849
+ constructor(config2, messageBus) {
331520
331850
  void initializeShellParsers().catch(() => {
331521
331851
  });
331522
331852
  super(
@@ -331544,7 +331874,9 @@ var ShellTool = class _ShellTool extends BaseDeclarativeTool {
331544
331874
  },
331545
331875
  false,
331546
331876
  // output is not markdown
331547
- true
331877
+ true,
331878
+ // output can be updated
331879
+ messageBus
331548
331880
  );
331549
331881
  this.config = config2;
331550
331882
  }
@@ -331575,8 +331907,8 @@ var ShellTool = class _ShellTool extends BaseDeclarativeTool {
331575
331907
  }
331576
331908
  return null;
331577
331909
  }
331578
- createInvocation(params) {
331579
- return new ShellToolInvocation(this.config, params, this.allowlist);
331910
+ createInvocation(params, messageBus) {
331911
+ return new ShellToolInvocation(this.config, params, this.allowlist, messageBus);
331580
331912
  }
331581
331913
  };
331582
331914
 
@@ -331619,8 +331951,8 @@ async function getCorrectedFileContent(config2, filePath, proposedContent, abort
331619
331951
  }
331620
331952
  var WriteFileToolInvocation = class extends BaseToolInvocation {
331621
331953
  config;
331622
- constructor(config2, params) {
331623
- super(params);
331954
+ constructor(config2, params, messageBus, toolName, displayName) {
331955
+ super(params, messageBus, toolName, displayName);
331624
331956
  this.config = config2;
331625
331957
  }
331626
331958
  toolLocations() {
@@ -331630,7 +331962,7 @@ var WriteFileToolInvocation = class extends BaseToolInvocation {
331630
331962
  const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
331631
331963
  return `Writing to ${shortenPath(relativePath)}`;
331632
331964
  }
331633
- async shouldConfirmExecute(abortSignal) {
331965
+ async getConfirmationDetails(abortSignal) {
331634
331966
  if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
331635
331967
  return false;
331636
331968
  }
@@ -331763,7 +332095,7 @@ var WriteFileToolInvocation = class extends BaseToolInvocation {
331763
332095
  var WriteFileTool = class _WriteFileTool extends BaseDeclarativeTool {
331764
332096
  config;
331765
332097
  static Name = WRITE_FILE_TOOL_NAME;
331766
- constructor(config2) {
332098
+ constructor(config2, messageBus) {
331767
332099
  super(_WriteFileTool.Name, "WriteFile", `Writes content to a specified file in the local filesystem.
331768
332100
 
331769
332101
  The user has the ability to modify \`content\`. If modified, this will be stated in the response.`, Kind.Edit, {
@@ -331779,7 +332111,7 @@ var WriteFileTool = class _WriteFileTool extends BaseDeclarativeTool {
331779
332111
  },
331780
332112
  required: ["file_path", "content"],
331781
332113
  type: "object"
331782
- });
332114
+ }, true, false, messageBus);
331783
332115
  this.config = config2;
331784
332116
  }
331785
332117
  validateToolParamValues(params) {
@@ -331808,7 +332140,7 @@ var WriteFileTool = class _WriteFileTool extends BaseDeclarativeTool {
331808
332140
  return null;
331809
332141
  }
331810
332142
  createInvocation(params) {
331811
- return new WriteFileToolInvocation(this.config, params);
332143
+ return new WriteFileToolInvocation(this.config, params, this.messageBus, this.name, this.displayName);
331812
332144
  }
331813
332145
  getModifyContext(abortSignal) {
331814
332146
  return {
@@ -336144,10 +336476,10 @@ function compile$1(options2 = {}) {
336144
336476
  }
336145
336477
  );
336146
336478
  return function(html2, metadata2 = void 0) {
336147
- return process19(html2, metadata2, options2, picker, findBaseElements, limitedWalk);
336479
+ return process21(html2, metadata2, options2, picker, findBaseElements, limitedWalk);
336148
336480
  };
336149
336481
  }
336150
- function process19(html2, metadata2, options2, picker, findBaseElements, walk) {
336482
+ function process21(html2, metadata2, options2, picker, findBaseElements, walk) {
336151
336483
  const maxInputLength = options2.limits.maxInputLength;
336152
336484
  if (maxInputLength && html2 && html2.length > maxInputLength) {
336153
336485
  console.warn(
@@ -336912,16 +337244,7 @@ ${textContent2}
336912
337244
  const displayPrompt = this.params.prompt.length > 100 ? this.params.prompt.substring(0, 97) + "..." : this.params.prompt;
336913
337245
  return `Processing URLs and instructions from prompt: "${displayPrompt}"`;
336914
337246
  }
336915
- async shouldConfirmExecute(abortSignal) {
336916
- if (this.messageBus) {
336917
- const decision = await this.getMessageBusDecision(abortSignal);
336918
- if (decision === "ALLOW") {
336919
- return false;
336920
- }
336921
- if (decision === "DENY") {
336922
- throw new Error("Tool execution denied by policy.");
336923
- }
336924
- }
337247
+ async getConfirmationDetails(_abortSignal) {
336925
337248
  if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
336926
337249
  return false;
336927
337250
  }
@@ -337600,6 +337923,10 @@ async function readFullStructure(rootPath, options2) {
337600
337923
  }
337601
337924
  const filesInCurrentDir = [];
337602
337925
  const subFoldersInCurrentDir = [];
337926
+ const filterFileOptions = {
337927
+ respectGitIgnore: options2.fileFilteringOptions?.respectGitIgnore,
337928
+ respectGeminiIgnore: options2.fileFilteringOptions?.respectGeminiIgnore
337929
+ };
337603
337930
  for (const entry of entries2) {
337604
337931
  if (entry.isFile()) {
337605
337932
  if (currentItemCount >= options2.maxItems) {
@@ -337608,11 +337935,8 @@ async function readFullStructure(rootPath, options2) {
337608
337935
  }
337609
337936
  const fileName = entry.name;
337610
337937
  const filePath = path46.join(currentPath, fileName);
337611
- if (options2.fileService) {
337612
- const shouldIgnore = options2.fileFilteringOptions.respectGitIgnore && options2.fileService.shouldGitIgnoreFile(filePath) || options2.fileFilteringOptions.respectGeminiIgnore && options2.fileService.shouldGeminiIgnoreFile(filePath);
337613
- if (shouldIgnore) {
337614
- continue;
337615
- }
337938
+ if (options2.fileService?.shouldIgnoreFile(filePath, filterFileOptions)) {
337939
+ continue;
337616
337940
  }
337617
337941
  if (!options2.fileIncludePattern || options2.fileIncludePattern.test(fileName)) {
337618
337942
  filesInCurrentDir.push(fileName);
@@ -337631,10 +337955,7 @@ async function readFullStructure(rootPath, options2) {
337631
337955
  }
337632
337956
  const subFolderName = entry.name;
337633
337957
  const subFolderPath = path46.join(currentPath, subFolderName);
337634
- let isIgnored = false;
337635
- if (options2.fileService) {
337636
- isIgnored = options2.fileFilteringOptions.respectGitIgnore && options2.fileService.shouldGitIgnoreFile(subFolderPath) || options2.fileFilteringOptions.respectGeminiIgnore && options2.fileService.shouldGeminiIgnoreFile(subFolderPath);
337637
- }
337958
+ const isIgnored = options2.fileService?.shouldIgnoreFile(subFolderPath, filterFileOptions) ?? false;
337638
337959
  if (options2.ignoredFolders.has(subFolderName) || isIgnored) {
337639
337960
  const ignoredSubFolder = {
337640
337961
  name: subFolderName,
@@ -337775,6 +338096,24 @@ ${directoryContext}
337775
338096
  const initialParts = [{ text: context2 }];
337776
338097
  return initialParts;
337777
338098
  }
338099
+ async function getInitialChatHistory(config2, extraHistory) {
338100
+ const envParts = await getEnvironmentContext(config2);
338101
+ const envContextString = envParts.map((part) => part.text || "").join("\n\n");
338102
+ const allSetupText = `
338103
+ ${envContextString}
338104
+
338105
+ Reminder: Do not return an empty response when a tool call is required.
338106
+
338107
+ My setup is complete. I will provide my first command in the next turn.
338108
+ `.trim();
338109
+ return [
338110
+ {
338111
+ role: "user",
338112
+ parts: [{ text: allSetupText }]
338113
+ },
338114
+ ...extraHistory ?? []
338115
+ ];
338116
+ }
337778
338117
 
337779
338118
  // packages/core/dist/src/utils/generateContentResponseUtilities.js
337780
338119
  function getResponseTextFromParts(parts2) {
@@ -337907,7 +338246,10 @@ ${truncatedContent}`,
337907
338246
  };
337908
338247
  }
337909
338248
  }
337910
- var CoreToolScheduler = class {
338249
+ var CoreToolScheduler = class _CoreToolScheduler {
338250
+ // Static WeakMap to track which MessageBus instances already have a handler subscribed
338251
+ // This prevents duplicate subscriptions when multiple CoreToolScheduler instances are created
338252
+ static subscribedMessageBuses = /* @__PURE__ */ new WeakMap();
337911
338253
  toolCalls = [];
337912
338254
  outputUpdateHandler;
337913
338255
  onAllToolCallsComplete;
@@ -337917,7 +338259,10 @@ var CoreToolScheduler = class {
337917
338259
  onEditorClose;
337918
338260
  isFinalizingToolCalls = false;
337919
338261
  isScheduling = false;
338262
+ isCancelling = false;
337920
338263
  requestQueue = [];
338264
+ toolCallQueue = [];
338265
+ completedToolCallsForBatch = [];
337921
338266
  constructor(options2) {
337922
338267
  this.config = options2.config;
337923
338268
  this.outputUpdateHandler = options2.outputUpdateHandler;
@@ -337927,10 +338272,21 @@ var CoreToolScheduler = class {
337927
338272
  this.onEditorClose = options2.onEditorClose;
337928
338273
  if (this.config.getEnableMessageBusIntegration()) {
337929
338274
  const messageBus = this.config.getMessageBus();
337930
- messageBus.subscribe(MessageBusType.TOOL_CONFIRMATION_REQUEST, this.handleToolConfirmationRequest.bind(this));
338275
+ if (!_CoreToolScheduler.subscribedMessageBuses.has(messageBus)) {
338276
+ const sharedHandler = (request3) => {
338277
+ messageBus.publish({
338278
+ type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
338279
+ correlationId: request3.correlationId,
338280
+ confirmed: false,
338281
+ requiresUserConfirmation: true
338282
+ });
338283
+ };
338284
+ messageBus.subscribe(MessageBusType.TOOL_CONFIRMATION_REQUEST, sharedHandler);
338285
+ _CoreToolScheduler.subscribedMessageBuses.set(messageBus, sharedHandler);
338286
+ }
337931
338287
  }
337932
338288
  }
337933
- setStatusInternal(targetCallId, newStatus, auxiliaryData) {
338289
+ setStatusInternal(targetCallId, newStatus, signal, auxiliaryData) {
337934
338290
  this.toolCalls = this.toolCalls.map((currentCall) => {
337935
338291
  if (currentCall.request.callId !== targetCallId || currentCall.status === "success" || currentCall.status === "error" || currentCall.status === "cancelled") {
337936
338292
  return currentCall;
@@ -338049,7 +338405,6 @@ var CoreToolScheduler = class {
338049
338405
  }
338050
338406
  });
338051
338407
  this.notifyToolCallsUpdate();
338052
- this.checkAndNotifyCompletion();
338053
338408
  }
338054
338409
  setArgsInternal(targetCallId, args2) {
338055
338410
  this.toolCalls = this.toolCalls.map((call) => {
@@ -338138,13 +338493,29 @@ var CoreToolScheduler = class {
338138
338493
  }
338139
338494
  return this._schedule(request3, signal);
338140
338495
  }
338496
+ cancelAll(signal) {
338497
+ if (this.isCancelling) {
338498
+ return;
338499
+ }
338500
+ this.isCancelling = true;
338501
+ if (this.toolCalls.length > 0) {
338502
+ const activeCall = this.toolCalls[0];
338503
+ if (activeCall.status === "awaiting_approval" || activeCall.status === "executing" || activeCall.status === "scheduled" || activeCall.status === "validating") {
338504
+ this.setStatusInternal(activeCall.request.callId, "cancelled", signal, "User cancelled the operation.");
338505
+ }
338506
+ }
338507
+ this._cancelAllQueuedCalls();
338508
+ void this.checkAndNotifyCompletion(signal);
338509
+ }
338141
338510
  async _schedule(request3, signal) {
338142
338511
  this.isScheduling = true;
338512
+ this.isCancelling = false;
338143
338513
  try {
338144
338514
  if (this.isRunning()) {
338145
338515
  throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).");
338146
338516
  }
338147
338517
  const requestsToProcess = Array.isArray(request3) ? request3 : [request3];
338518
+ this.completedToolCallsForBatch = [];
338148
338519
  const newToolCalls = requestsToProcess.map((reqInfo) => {
338149
338520
  const toolInstance = this.config.getToolRegistry().getTool(reqInfo.name);
338150
338521
  if (!toolInstance) {
@@ -338175,28 +338546,44 @@ var CoreToolScheduler = class {
338175
338546
  startTime: Date.now()
338176
338547
  };
338177
338548
  });
338178
- this.toolCalls = this.toolCalls.concat(newToolCalls);
338179
- this.notifyToolCallsUpdate();
338180
- for (const toolCall of newToolCalls) {
338181
- if (toolCall.status !== "validating") {
338182
- continue;
338549
+ this.toolCallQueue.push(...newToolCalls);
338550
+ await this._processNextInQueue(signal);
338551
+ } finally {
338552
+ this.isScheduling = false;
338553
+ }
338554
+ }
338555
+ async _processNextInQueue(signal) {
338556
+ if (this.toolCalls.length > 0 || this.toolCallQueue.length === 0) {
338557
+ return;
338558
+ }
338559
+ if (signal.aborted) {
338560
+ this._cancelAllQueuedCalls();
338561
+ await this.checkAndNotifyCompletion(signal);
338562
+ return;
338563
+ }
338564
+ const toolCall = this.toolCallQueue.shift();
338565
+ this.toolCalls = [toolCall];
338566
+ this.notifyToolCallsUpdate();
338567
+ if (toolCall.status === "error") {
338568
+ await this.checkAndNotifyCompletion(signal);
338569
+ return;
338570
+ }
338571
+ if (toolCall.status === "validating") {
338572
+ const { request: reqInfo, invocation } = toolCall;
338573
+ try {
338574
+ if (signal.aborted) {
338575
+ this.setStatusInternal(reqInfo.callId, "cancelled", signal, "Tool call cancelled by user.");
338576
+ await this.checkAndNotifyCompletion(signal);
338577
+ return;
338183
338578
  }
338184
- const validatingCall = toolCall;
338185
- const { request: reqInfo, invocation } = validatingCall;
338186
- try {
338187
- if (signal.aborted) {
338188
- this.setStatusInternal(reqInfo.callId, "cancelled", "Tool call cancelled by user.");
338189
- continue;
338190
- }
338191
- const confirmationDetails = await invocation.shouldConfirmExecute(signal);
338192
- if (!confirmationDetails) {
338193
- this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
338194
- this.setStatusInternal(reqInfo.callId, "scheduled");
338195
- continue;
338196
- }
338197
- if (this.isAutoApproved(validatingCall)) {
338579
+ const confirmationDetails = await invocation.shouldConfirmExecute(signal);
338580
+ if (!confirmationDetails) {
338581
+ this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
338582
+ this.setStatusInternal(reqInfo.callId, "scheduled", signal);
338583
+ } else {
338584
+ if (this.isAutoApproved(toolCall)) {
338198
338585
  this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
338199
- this.setStatusInternal(reqInfo.callId, "scheduled");
338586
+ this.setStatusInternal(reqInfo.callId, "scheduled", signal);
338200
338587
  } else {
338201
338588
  if (confirmationDetails.type === "edit" && confirmationDetails.ideConfirmation) {
338202
338589
  confirmationDetails.ideConfirmation.then((resolution) => {
@@ -338212,33 +338599,30 @@ var CoreToolScheduler = class {
338212
338599
  ...confirmationDetails,
338213
338600
  onConfirm: (outcome, payload) => this.handleConfirmationResponse(reqInfo.callId, originalOnConfirm, outcome, signal, payload)
338214
338601
  };
338215
- this.setStatusInternal(reqInfo.callId, "awaiting_approval", wrappedConfirmationDetails);
338216
- }
338217
- } catch (error) {
338218
- if (signal.aborted) {
338219
- this.setStatusInternal(reqInfo.callId, "cancelled", "Tool call cancelled by user.");
338220
- continue;
338602
+ this.setStatusInternal(reqInfo.callId, "awaiting_approval", signal, wrappedConfirmationDetails);
338221
338603
  }
338222
- this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, error instanceof Error ? error : new Error(String(error)), ToolErrorType.UNHANDLED_EXCEPTION));
338604
+ }
338605
+ } catch (error) {
338606
+ if (signal.aborted) {
338607
+ this.setStatusInternal(reqInfo.callId, "cancelled", signal, "Tool call cancelled by user.");
338608
+ await this.checkAndNotifyCompletion(signal);
338609
+ } else {
338610
+ this.setStatusInternal(reqInfo.callId, "error", signal, createErrorResponse(reqInfo, error instanceof Error ? error : new Error(String(error)), ToolErrorType.UNHANDLED_EXCEPTION));
338611
+ await this.checkAndNotifyCompletion(signal);
338223
338612
  }
338224
338613
  }
338225
- await this.attemptExecutionOfScheduledCalls(signal);
338226
- void this.checkAndNotifyCompletion();
338227
- } finally {
338228
- this.isScheduling = false;
338229
338614
  }
338615
+ await this.attemptExecutionOfScheduledCalls(signal);
338230
338616
  }
338231
338617
  async handleConfirmationResponse(callId, originalOnConfirm, outcome, signal, payload) {
338232
338618
  const toolCall = this.toolCalls.find((c4) => c4.request.callId === callId && c4.status === "awaiting_approval");
338233
338619
  if (toolCall && toolCall.status === "awaiting_approval") {
338234
338620
  await originalOnConfirm(outcome);
338235
338621
  }
338236
- if (outcome === ToolConfirmationOutcome.ProceedAlways) {
338237
- await this.autoApproveCompatiblePendingTools(signal, callId);
338238
- }
338239
338622
  this.setToolCallOutcome(callId, outcome);
338240
338623
  if (outcome === ToolConfirmationOutcome.Cancel || signal.aborted) {
338241
- this.setStatusInternal(callId, "cancelled", "User did not allow tool call");
338624
+ this.cancelAll(signal);
338625
+ return;
338242
338626
  } else if (outcome === ToolConfirmationOutcome.ModifyWithEditor) {
338243
338627
  const waitingToolCall = toolCall;
338244
338628
  if (isModifiableDeclarativeTool(waitingToolCall.tool)) {
@@ -338247,13 +338631,13 @@ var CoreToolScheduler = class {
338247
338631
  if (!editorType) {
338248
338632
  return;
338249
338633
  }
338250
- this.setStatusInternal(callId, "awaiting_approval", {
338634
+ this.setStatusInternal(callId, "awaiting_approval", signal, {
338251
338635
  ...waitingToolCall.confirmationDetails,
338252
338636
  isModifying: true
338253
338637
  });
338254
338638
  const { updatedParams, updatedDiff } = await modifyWithEditor(waitingToolCall.request.args, modifyContext, editorType, signal, this.onEditorClose);
338255
338639
  this.setArgsInternal(callId, updatedParams);
338256
- this.setStatusInternal(callId, "awaiting_approval", {
338640
+ this.setStatusInternal(callId, "awaiting_approval", signal, {
338257
338641
  ...waitingToolCall.confirmationDetails,
338258
338642
  fileDiff: updatedDiff,
338259
338643
  isModifying: false
@@ -338263,7 +338647,7 @@ var CoreToolScheduler = class {
338263
338647
  if (payload?.newContent && toolCall) {
338264
338648
  await this._applyInlineModify(toolCall, payload, signal);
338265
338649
  }
338266
- this.setStatusInternal(callId, "scheduled");
338650
+ this.setStatusInternal(callId, "scheduled", signal);
338267
338651
  }
338268
338652
  await this.attemptExecutionOfScheduledCalls(signal);
338269
338653
  }
@@ -338282,7 +338666,7 @@ var CoreToolScheduler = class {
338282
338666
  const updatedParams = modifyContext.createUpdatedParams(currentContent, payload.newContent, toolCall.request.args);
338283
338667
  const updatedDiff = createPatch(modifyContext.getFilePath(toolCall.request.args), currentContent, payload.newContent, "Current", "Proposed");
338284
338668
  this.setArgsInternal(toolCall.request.callId, updatedParams);
338285
- this.setStatusInternal(toolCall.request.callId, "awaiting_approval", {
338669
+ this.setStatusInternal(toolCall.request.callId, "awaiting_approval", signal, {
338286
338670
  ...toolCall.confirmationDetails,
338287
338671
  fileDiff: updatedDiff
338288
338672
  });
@@ -338297,7 +338681,7 @@ var CoreToolScheduler = class {
338297
338681
  const scheduledCall = toolCall;
338298
338682
  const { callId, name: toolName } = scheduledCall.request;
338299
338683
  const invocation = scheduledCall.invocation;
338300
- this.setStatusInternal(callId, "executing");
338684
+ this.setStatusInternal(callId, "executing", signal);
338301
338685
  const liveOutputCallback = scheduledCall.tool.canUpdateOutput && this.outputUpdateHandler ? (outputChunk) => {
338302
338686
  if (this.outputUpdateHandler) {
338303
338687
  this.outputUpdateHandler(callId, outputChunk);
@@ -338319,10 +338703,8 @@ var CoreToolScheduler = class {
338319
338703
  try {
338320
338704
  const toolResult = await promise;
338321
338705
  if (signal.aborted) {
338322
- this.setStatusInternal(callId, "cancelled", "User cancelled tool execution.");
338323
- continue;
338324
- }
338325
- if (toolResult.error === void 0) {
338706
+ this.setStatusInternal(callId, "cancelled", signal, "User cancelled tool execution.");
338707
+ } else if (toolResult.error === void 0) {
338326
338708
  let content = toolResult.llmContent;
338327
338709
  let outputFile = void 0;
338328
338710
  const contentLength = typeof content === "string" ? content.length : void 0;
@@ -338353,45 +338735,106 @@ var CoreToolScheduler = class {
338353
338735
  outputFile,
338354
338736
  contentLength
338355
338737
  };
338356
- this.setStatusInternal(callId, "success", successResponse);
338738
+ this.setStatusInternal(callId, "success", signal, successResponse);
338357
338739
  } else {
338358
338740
  const error = new Error(toolResult.error.message);
338359
338741
  const errorResponse = createErrorResponse(scheduledCall.request, error, toolResult.error.type);
338360
- this.setStatusInternal(callId, "error", errorResponse);
338742
+ this.setStatusInternal(callId, "error", signal, errorResponse);
338361
338743
  }
338362
338744
  } catch (executionError) {
338363
338745
  if (signal.aborted) {
338364
- this.setStatusInternal(callId, "cancelled", "User cancelled tool execution.");
338746
+ this.setStatusInternal(callId, "cancelled", signal, "User cancelled tool execution.");
338365
338747
  } else {
338366
- this.setStatusInternal(callId, "error", createErrorResponse(scheduledCall.request, executionError instanceof Error ? executionError : new Error(String(executionError)), ToolErrorType.UNHANDLED_EXCEPTION));
338748
+ this.setStatusInternal(callId, "error", signal, createErrorResponse(scheduledCall.request, executionError instanceof Error ? executionError : new Error(String(executionError)), ToolErrorType.UNHANDLED_EXCEPTION));
338367
338749
  }
338368
338750
  }
338751
+ await this.checkAndNotifyCompletion(signal);
338369
338752
  }
338370
338753
  }
338371
338754
  }
338372
- async checkAndNotifyCompletion() {
338373
- const allCallsAreTerminal = this.toolCalls.every((call) => call.status === "success" || call.status === "error" || call.status === "cancelled");
338374
- if (this.toolCalls.length > 0 && allCallsAreTerminal) {
338375
- const completedCalls = [...this.toolCalls];
338755
+ async checkAndNotifyCompletion(signal) {
338756
+ if (this.toolCalls.length === 0) {
338757
+ if (signal.aborted && this.toolCallQueue.length > 0) {
338758
+ this._cancelAllQueuedCalls();
338759
+ }
338760
+ } else {
338761
+ const activeCall = this.toolCalls[0];
338762
+ const isTerminal = activeCall.status === "success" || activeCall.status === "error" || activeCall.status === "cancelled";
338763
+ if (!isTerminal) {
338764
+ return;
338765
+ }
338766
+ const completedCall = activeCall;
338767
+ this.completedToolCallsForBatch.push(completedCall);
338768
+ logToolCall(this.config, new ToolCallEvent(completedCall));
338376
338769
  this.toolCalls = [];
338377
- for (const call of completedCalls) {
338378
- logToolCall(this.config, new ToolCallEvent(call));
338770
+ }
338771
+ if (this.toolCallQueue.length === 0 || signal.aborted) {
338772
+ if (signal.aborted) {
338773
+ this._cancelAllQueuedCalls();
338774
+ }
338775
+ if (this.completedToolCallsForBatch.length === 0 && !signal.aborted) {
338776
+ return;
338379
338777
  }
338380
338778
  if (this.onAllToolCallsComplete) {
338381
338779
  this.isFinalizingToolCalls = true;
338382
- await this.onAllToolCallsComplete(completedCalls);
338780
+ await this.onAllToolCallsComplete(this.completedToolCallsForBatch);
338781
+ this.completedToolCallsForBatch = [];
338383
338782
  this.isFinalizingToolCalls = false;
338384
338783
  }
338784
+ this.isCancelling = false;
338385
338785
  this.notifyToolCallsUpdate();
338386
338786
  if (this.requestQueue.length > 0) {
338387
338787
  const next = this.requestQueue.shift();
338388
338788
  this._schedule(next.request, next.signal).then(next.resolve).catch(next.reject);
338389
338789
  }
338790
+ } else {
338791
+ await this._processNextInQueue(signal);
338792
+ }
338793
+ }
338794
+ _cancelAllQueuedCalls() {
338795
+ while (this.toolCallQueue.length > 0) {
338796
+ const queuedCall = this.toolCallQueue.shift();
338797
+ if (queuedCall.status === "error") {
338798
+ this.completedToolCallsForBatch.push(queuedCall);
338799
+ continue;
338800
+ }
338801
+ const durationMs = "startTime" in queuedCall && queuedCall.startTime ? Date.now() - queuedCall.startTime : void 0;
338802
+ const errorMessage = "[Operation Cancelled] User cancelled the operation.";
338803
+ this.completedToolCallsForBatch.push({
338804
+ request: queuedCall.request,
338805
+ tool: queuedCall.tool,
338806
+ invocation: queuedCall.invocation,
338807
+ status: "cancelled",
338808
+ response: {
338809
+ callId: queuedCall.request.callId,
338810
+ responseParts: [
338811
+ {
338812
+ functionResponse: {
338813
+ id: queuedCall.request.callId,
338814
+ name: queuedCall.request.name,
338815
+ response: {
338816
+ error: errorMessage
338817
+ }
338818
+ }
338819
+ }
338820
+ ],
338821
+ resultDisplay: void 0,
338822
+ error: void 0,
338823
+ errorType: void 0,
338824
+ contentLength: errorMessage.length
338825
+ },
338826
+ durationMs,
338827
+ outcome: ToolConfirmationOutcome.Cancel
338828
+ });
338390
338829
  }
338391
338830
  }
338392
338831
  notifyToolCallsUpdate() {
338393
338832
  if (this.onToolCallsUpdate) {
338394
- this.onToolCallsUpdate([...this.toolCalls]);
338833
+ this.onToolCallsUpdate([
338834
+ ...this.completedToolCallsForBatch,
338835
+ ...this.toolCalls,
338836
+ ...this.toolCallQueue
338837
+ ]);
338395
338838
  }
338396
338839
  }
338397
338840
  setToolCallOutcome(callId, outcome) {
@@ -338404,22 +338847,6 @@ var CoreToolScheduler = class {
338404
338847
  };
338405
338848
  });
338406
338849
  }
338407
- /**
338408
- * Handle tool confirmation requests from the message bus when policy decision is ASK_USER.
338409
- * This publishes a response with requiresUserConfirmation=true to signal the tool
338410
- * that it should fall back to its legacy confirmation UI.
338411
- */
338412
- handleToolConfirmationRequest(request3) {
338413
- const messageBus = this.config.getMessageBus();
338414
- messageBus.publish({
338415
- type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
338416
- correlationId: request3.correlationId,
338417
- confirmed: false,
338418
- // Not auto-approved
338419
- requiresUserConfirmation: true
338420
- // Use legacy UI confirmation
338421
- });
338422
- }
338423
338850
  isAutoApproved(toolCall) {
338424
338851
  if (this.config.getApprovalMode() === ApprovalMode.YOLO) {
338425
338852
  return true;
@@ -338432,20 +338859,6 @@ var CoreToolScheduler = class {
338432
338859
  }
338433
338860
  return doesToolInvocationMatch(tool, invocation, allowedTools);
338434
338861
  }
338435
- async autoApproveCompatiblePendingTools(signal, triggeringCallId) {
338436
- const pendingTools = this.toolCalls.filter((call) => call.status === "awaiting_approval" && call.request.callId !== triggeringCallId);
338437
- for (const pendingTool of pendingTools) {
338438
- try {
338439
- const stillNeedsConfirmation = await pendingTool.invocation.shouldConfirmExecute(signal);
338440
- if (!stillNeedsConfirmation) {
338441
- this.setToolCallOutcome(pendingTool.request.callId, ToolConfirmationOutcome.ProceedAlways);
338442
- this.setStatusInternal(pendingTool.request.callId, "scheduled");
338443
- }
338444
- } catch (error) {
338445
- console.error(`Error checking confirmation for tool ${pendingTool.request.callId}:`, error);
338446
- }
338447
- }
338448
- }
338449
338862
  };
338450
338863
 
338451
338864
  // packages/core/dist/src/utils/thoughtUtils.js
@@ -339338,7 +339751,7 @@ function getCitations(resp) {
339338
339751
  import path49 from "node:path";
339339
339752
  import fs47 from "node:fs";
339340
339753
  import os17 from "node:os";
339341
- import process20 from "node:process";
339754
+ import process22 from "node:process";
339342
339755
 
339343
339756
  // packages/core/dist/src/agents/codebase-investigator.js
339344
339757
  var CodebaseInvestigationReportSchema = external_exports.object({
@@ -339488,7 +339901,7 @@ function resolvePathFromEnv(envVar) {
339488
339901
  function getCoreSystemPrompt(config2, userMemory) {
339489
339902
  let systemMdEnabled = false;
339490
339903
  let systemMdPath = path49.resolve(path49.join(GEMINI_DIR, "system.md"));
339491
- const systemMdResolution = resolvePathFromEnv(process20.env["GEMINI_SYSTEM_MD"]);
339904
+ const systemMdResolution = resolvePathFromEnv(process22.env["GEMINI_SYSTEM_MD"]);
339492
339905
  if (systemMdResolution.value && !systemMdResolution.isDisabled) {
339493
339906
  systemMdEnabled = true;
339494
339907
  if (!systemMdResolution.isSwitch) {
@@ -339606,8 +340019,8 @@ ${function() {
339606
340019
  - **Feedback:** To report a bug or provide feedback, please use the /bug command.
339607
340020
 
339608
340021
  ${function() {
339609
- const isSandboxExec = process20.env["SANDBOX"] === "sandbox-exec";
339610
- const isGenericSandbox = !!process20.env["SANDBOX"];
340022
+ const isSandboxExec = process22.env["SANDBOX"] === "sandbox-exec";
340023
+ const isGenericSandbox = !!process22.env["SANDBOX"];
339611
340024
  if (isSandboxExec) {
339612
340025
  return `
339613
340026
  # macOS Seatbelt
@@ -339627,7 +340040,7 @@ You are running outside of a sandbox container, directly on the user's system. F
339627
340040
  }()}
339628
340041
 
339629
340042
  ${function() {
339630
- if (isGitRepository(process20.cwd())) {
340043
+ if (isGitRepository(process22.cwd())) {
339631
340044
  return `
339632
340045
  # Git Repository
339633
340046
  - The current working (project) directory is being managed by a git repository.
@@ -339651,7 +340064,7 @@ ${function() {
339651
340064
  # Final Reminder
339652
340065
  Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use '${READ_FILE_TOOL_NAME}' or '${READ_MANY_FILES_TOOL_NAME}' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
339653
340066
  `.trim();
339654
- const writeSystemMdResolution = resolvePathFromEnv(process20.env["GEMINI_WRITE_SYSTEM_MD"]);
340067
+ const writeSystemMdResolution = resolvePathFromEnv(process22.env["GEMINI_WRITE_SYSTEM_MD"]);
339655
340068
  if (writeSystemMdResolution.value && !writeSystemMdResolution.isDisabled) {
339656
340069
  const writePath = writeSystemMdResolution.isSwitch ? systemMdPath : writeSystemMdResolution.value;
339657
340070
  fs47.mkdirSync(path49.dirname(writePath), { recursive: true });
@@ -340058,19 +340471,28 @@ var LoopDetectionService = class {
340058
340471
  ...trimmedHistory,
340059
340472
  { role: "user", parts: [{ text: taskPrompt }] }
340060
340473
  ];
340474
+ if (contents.length > 0 && isFunctionCall(contents[0])) {
340475
+ contents.unshift({
340476
+ role: "user",
340477
+ parts: [{ text: "Recent conversation history:" }]
340478
+ });
340479
+ }
340061
340480
  const schema = {
340062
340481
  type: "object",
340063
340482
  properties: {
340064
- reasoning: {
340483
+ unproductive_state_analysis: {
340065
340484
  type: "string",
340066
340485
  description: "Your reasoning on if the conversation is looping without forward progress."
340067
340486
  },
340068
- confidence: {
340487
+ unproductive_state_confidence: {
340069
340488
  type: "number",
340070
340489
  description: "A number between 0.0 and 1.0 representing your confidence that the conversation is in an unproductive state."
340071
340490
  }
340072
340491
  },
340073
- required: ["reasoning", "confidence"]
340492
+ required: [
340493
+ "unproductive_state_analysis",
340494
+ "unproductive_state_confidence"
340495
+ ]
340074
340496
  };
340075
340497
  let result;
340076
340498
  try {
@@ -340083,18 +340505,18 @@ var LoopDetectionService = class {
340083
340505
  promptId: this.promptId
340084
340506
  });
340085
340507
  } catch (e2) {
340086
- this.config.getDebugMode() ? console.error(e2) : debugLogger.debug(e2);
340508
+ this.config.getDebugMode() ? debugLogger.warn(e2) : debugLogger.debug(e2);
340087
340509
  return false;
340088
340510
  }
340089
- if (typeof result["confidence"] === "number") {
340090
- if (result["confidence"] > 0.9) {
340091
- if (typeof result["reasoning"] === "string" && result["reasoning"]) {
340092
- debugLogger.warn(result["reasoning"]);
340511
+ if (typeof result["unproductive_state_confidence"] === "number") {
340512
+ if (result["unproductive_state_confidence"] > 0.9) {
340513
+ if (typeof result["unproductive_state_analysis"] === "string" && result["unproductive_state_analysis"]) {
340514
+ debugLogger.warn(result["unproductive_state_analysis"]);
340093
340515
  }
340094
340516
  logLoopDetected(this.config, new LoopDetectedEvent(LoopType.LLM_DETECTED_LOOP, this.promptId));
340095
340517
  return true;
340096
340518
  } else {
340097
- this.llmCheckInterval = Math.round(MIN_LLM_CHECK_INTERVAL + (MAX_LLM_CHECK_INTERVAL - MIN_LLM_CHECK_INTERVAL) * (1 - result["confidence"]));
340519
+ this.llmCheckInterval = Math.round(MIN_LLM_CHECK_INTERVAL + (MAX_LLM_CHECK_INTERVAL - MIN_LLM_CHECK_INTERVAL) * (1 - result["unproductive_state_confidence"]));
340098
340520
  }
340099
340521
  }
340100
340522
  return false;
@@ -340127,10 +340549,9 @@ var LoopDetectionService = class {
340127
340549
  }
340128
340550
  };
340129
340551
 
340130
- // packages/core/dist/src/core/client.js
340131
- function isThinkingSupported(model) {
340132
- return model.startsWith("gemini-2.5") || model === DEFAULT_GEMINI_MODEL_AUTO;
340133
- }
340552
+ // packages/core/dist/src/services/chatCompressionService.js
340553
+ var COMPRESSION_TOKEN_THRESHOLD = 0.7;
340554
+ var COMPRESSION_PRESERVE_THRESHOLD = 0.3;
340134
340555
  function findCompressSplitPoint(contents, fraction) {
340135
340556
  if (fraction <= 0 || fraction >= 1) {
340136
340557
  throw new Error("Fraction must be between 0 and 1");
@@ -340156,9 +340577,110 @@ function findCompressSplitPoint(contents, fraction) {
340156
340577
  }
340157
340578
  return lastSplitPoint;
340158
340579
  }
340580
+ var ChatCompressionService = class {
340581
+ async compress(chat, promptId, force, model, config2, hasFailedCompressionAttempt) {
340582
+ const curatedHistory = chat.getHistory(true);
340583
+ if (curatedHistory.length === 0 || hasFailedCompressionAttempt && !force) {
340584
+ return {
340585
+ newHistory: null,
340586
+ info: {
340587
+ originalTokenCount: 0,
340588
+ newTokenCount: 0,
340589
+ compressionStatus: CompressionStatus.NOOP
340590
+ }
340591
+ };
340592
+ }
340593
+ const originalTokenCount = uiTelemetryService.getLastPromptTokenCount();
340594
+ const contextPercentageThreshold = config2.getChatCompression()?.contextPercentageThreshold;
340595
+ if (!force) {
340596
+ const threshold = contextPercentageThreshold ?? COMPRESSION_TOKEN_THRESHOLD;
340597
+ if (originalTokenCount < threshold * tokenLimit(model)) {
340598
+ return {
340599
+ newHistory: null,
340600
+ info: {
340601
+ originalTokenCount,
340602
+ newTokenCount: originalTokenCount,
340603
+ compressionStatus: CompressionStatus.NOOP
340604
+ }
340605
+ };
340606
+ }
340607
+ }
340608
+ const splitPoint = findCompressSplitPoint(curatedHistory, 1 - COMPRESSION_PRESERVE_THRESHOLD);
340609
+ const historyToCompress = curatedHistory.slice(0, splitPoint);
340610
+ const historyToKeep = curatedHistory.slice(splitPoint);
340611
+ if (historyToCompress.length === 0) {
340612
+ return {
340613
+ newHistory: null,
340614
+ info: {
340615
+ originalTokenCount,
340616
+ newTokenCount: originalTokenCount,
340617
+ compressionStatus: CompressionStatus.NOOP
340618
+ }
340619
+ };
340620
+ }
340621
+ const summaryResponse = await config2.getContentGenerator().generateContent({
340622
+ model,
340623
+ contents: [
340624
+ ...historyToCompress,
340625
+ {
340626
+ role: "user",
340627
+ parts: [
340628
+ {
340629
+ text: "First, reason in your scratchpad. Then, generate the <state_snapshot>."
340630
+ }
340631
+ ]
340632
+ }
340633
+ ],
340634
+ config: {
340635
+ systemInstruction: { text: getCompressionPrompt() }
340636
+ }
340637
+ }, promptId);
340638
+ const summary = getResponseText(summaryResponse) ?? "";
340639
+ const extraHistory = [
340640
+ {
340641
+ role: "user",
340642
+ parts: [{ text: summary }]
340643
+ },
340644
+ {
340645
+ role: "model",
340646
+ parts: [{ text: "Got it. Thanks for the additional context!" }]
340647
+ },
340648
+ ...historyToKeep
340649
+ ];
340650
+ const fullNewHistory = await getInitialChatHistory(config2, extraHistory);
340651
+ const newTokenCount = Math.floor(fullNewHistory.reduce((total, content) => total + JSON.stringify(content).length, 0) / 4);
340652
+ logChatCompression(config2, makeChatCompressionEvent({
340653
+ tokens_before: originalTokenCount,
340654
+ tokens_after: newTokenCount
340655
+ }));
340656
+ if (newTokenCount > originalTokenCount) {
340657
+ return {
340658
+ newHistory: null,
340659
+ info: {
340660
+ originalTokenCount,
340661
+ newTokenCount,
340662
+ compressionStatus: CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT
340663
+ }
340664
+ };
340665
+ } else {
340666
+ uiTelemetryService.setLastPromptTokenCount(newTokenCount);
340667
+ return {
340668
+ newHistory: extraHistory,
340669
+ info: {
340670
+ originalTokenCount,
340671
+ newTokenCount,
340672
+ compressionStatus: CompressionStatus.COMPRESSED
340673
+ }
340674
+ };
340675
+ }
340676
+ }
340677
+ };
340678
+
340679
+ // packages/core/dist/src/core/client.js
340680
+ function isThinkingSupported(model) {
340681
+ return model.startsWith("gemini-2.5") || model === DEFAULT_GEMINI_MODEL_AUTO;
340682
+ }
340159
340683
  var MAX_TURNS = 100;
340160
- var COMPRESSION_TOKEN_THRESHOLD = 0.7;
340161
- var COMPRESSION_PRESERVE_THRESHOLD = 0.3;
340162
340684
  var GeminiClient = class {
340163
340685
  config;
340164
340686
  chat;
@@ -340168,6 +340690,7 @@ var GeminiClient = class {
340168
340690
  };
340169
340691
  sessionTurnCount = 0;
340170
340692
  loopDetector;
340693
+ compressionService;
340171
340694
  lastPromptId;
340172
340695
  currentSequenceModel = null;
340173
340696
  lastSentIdeContext;
@@ -340180,6 +340703,7 @@ var GeminiClient = class {
340180
340703
  constructor(config2) {
340181
340704
  this.config = config2;
340182
340705
  this.loopDetector = new LoopDetectionService(config2);
340706
+ this.compressionService = new ChatCompressionService();
340183
340707
  this.lastPromptId = this.config.getSessionId();
340184
340708
  }
340185
340709
  async initialize() {
@@ -340246,22 +340770,7 @@ var GeminiClient = class {
340246
340770
  const toolRegistry = this.config.getToolRegistry();
340247
340771
  const toolDeclarations = toolRegistry.getFunctionDeclarations();
340248
340772
  const tools = [{ functionDeclarations: toolDeclarations }];
340249
- const envParts = await getEnvironmentContext(this.config);
340250
- const envContextString = envParts.map((part) => part.text || "").join("\n\n");
340251
- const allSetupText = `
340252
- ${envContextString}
340253
-
340254
- Reminder: Do not return an empty response when a tool call is required.
340255
-
340256
- My setup is complete. I will provide my first command in the next turn.
340257
- `.trim();
340258
- const history = [
340259
- {
340260
- role: "user",
340261
- parts: [{ text: allSetupText }]
340262
- },
340263
- ...extraHistory ?? []
340264
- ];
340773
+ const history = await getInitialChatHistory(this.config, extraHistory);
340265
340774
  try {
340266
340775
  const userMemory = this.config.getUserMemory();
340267
340776
  const systemInstruction = getCoreSystemPrompt(this.config, userMemory);
@@ -340573,87 +341082,16 @@ My setup is complete. I will provide my first command in the next turn.
340573
341082
  }
340574
341083
  async tryCompressChat(prompt_id, force = false) {
340575
341084
  const model = this._getEffectiveModelForCurrentTurn();
340576
- const curatedHistory = this.getChat().getHistory(true);
340577
- if (curatedHistory.length === 0 || this.hasFailedCompressionAttempt && !force) {
340578
- return {
340579
- originalTokenCount: 0,
340580
- newTokenCount: 0,
340581
- compressionStatus: CompressionStatus.NOOP
340582
- };
340583
- }
340584
- const originalTokenCount = uiTelemetryService.getLastPromptTokenCount();
340585
- const contextPercentageThreshold = this.config.getChatCompression()?.contextPercentageThreshold;
340586
- if (!force) {
340587
- const threshold = contextPercentageThreshold ?? COMPRESSION_TOKEN_THRESHOLD;
340588
- if (originalTokenCount < threshold * tokenLimit(model)) {
340589
- return {
340590
- originalTokenCount,
340591
- newTokenCount: originalTokenCount,
340592
- compressionStatus: CompressionStatus.NOOP
340593
- };
340594
- }
340595
- }
340596
- const splitPoint = findCompressSplitPoint(curatedHistory, 1 - COMPRESSION_PRESERVE_THRESHOLD);
340597
- const historyToCompress = curatedHistory.slice(0, splitPoint);
340598
- const historyToKeep = curatedHistory.slice(splitPoint);
340599
- if (historyToCompress.length === 0) {
340600
- return {
340601
- originalTokenCount,
340602
- newTokenCount: originalTokenCount,
340603
- compressionStatus: CompressionStatus.NOOP
340604
- };
340605
- }
340606
- const summaryResponse = await this.config.getContentGenerator().generateContent({
340607
- model,
340608
- contents: [
340609
- ...historyToCompress,
340610
- {
340611
- role: "user",
340612
- parts: [
340613
- {
340614
- text: "First, reason in your scratchpad. Then, generate the <state_snapshot>."
340615
- }
340616
- ]
340617
- }
340618
- ],
340619
- config: {
340620
- systemInstruction: { text: getCompressionPrompt() }
340621
- }
340622
- }, prompt_id);
340623
- const summary = getResponseText(summaryResponse) ?? "";
340624
- const chat = await this.startChat([
340625
- {
340626
- role: "user",
340627
- parts: [{ text: summary }]
340628
- },
340629
- {
340630
- role: "model",
340631
- parts: [{ text: "Got it. Thanks for the additional context!" }]
340632
- },
340633
- ...historyToKeep
340634
- ]);
340635
- this.forceFullIdeContext = true;
340636
- const newTokenCount = Math.floor(chat.getHistory().reduce((total, content) => total + JSON.stringify(content).length, 0) / 4);
340637
- logChatCompression(this.config, makeChatCompressionEvent({
340638
- tokens_before: originalTokenCount,
340639
- tokens_after: newTokenCount
340640
- }));
340641
- if (newTokenCount > originalTokenCount) {
341085
+ const { newHistory, info: info2 } = await this.compressionService.compress(this.getChat(), prompt_id, force, model, this.config, this.hasFailedCompressionAttempt);
341086
+ if (info2.compressionStatus === CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT) {
340642
341087
  this.hasFailedCompressionAttempt = !force && true;
340643
- return {
340644
- originalTokenCount,
340645
- newTokenCount,
340646
- compressionStatus: CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT
340647
- };
340648
- } else {
340649
- this.chat = chat;
340650
- uiTelemetryService.setLastPromptTokenCount(newTokenCount);
341088
+ } else if (info2.compressionStatus === CompressionStatus.COMPRESSED) {
341089
+ if (newHistory) {
341090
+ this.chat = await this.startChat(newHistory);
341091
+ this.forceFullIdeContext = true;
341092
+ }
340651
341093
  }
340652
- return {
340653
- originalTokenCount,
340654
- newTokenCount,
340655
- compressionStatus: CompressionStatus.COMPRESSED
340656
- };
341094
+ return info2;
340657
341095
  }
340658
341096
  };
340659
341097
 
@@ -340836,15 +341274,13 @@ var FileDiscoveryService = class {
340836
341274
  /**
340837
341275
  * Filters a list of file paths based on git ignore rules
340838
341276
  */
340839
- filterFiles(filePaths, options2 = {
340840
- respectGitIgnore: true,
340841
- respectGeminiIgnore: true
340842
- }) {
341277
+ filterFiles(filePaths, options2 = {}) {
341278
+ const { respectGitIgnore = true, respectGeminiIgnore = true } = options2;
340843
341279
  return filePaths.filter((filePath) => {
340844
- if (options2.respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
341280
+ if (respectGitIgnore && this.gitIgnoreFilter?.isIgnored(filePath)) {
340845
341281
  return false;
340846
341282
  }
340847
- if (options2.respectGeminiIgnore && this.shouldGeminiIgnoreFile(filePath)) {
341283
+ if (respectGeminiIgnore && this.geminiIgnoreFilter?.isIgnored(filePath)) {
340848
341284
  return false;
340849
341285
  }
340850
341286
  return true;
@@ -340865,36 +341301,11 @@ var FileDiscoveryService = class {
340865
341301
  ignoredCount
340866
341302
  };
340867
341303
  }
340868
- /**
340869
- * Checks if a single file should be git-ignored
340870
- */
340871
- shouldGitIgnoreFile(filePath) {
340872
- if (this.gitIgnoreFilter) {
340873
- return this.gitIgnoreFilter.isIgnored(filePath);
340874
- }
340875
- return false;
340876
- }
340877
- /**
340878
- * Checks if a single file should be gemini-ignored
340879
- */
340880
- shouldGeminiIgnoreFile(filePath) {
340881
- if (this.geminiIgnoreFilter) {
340882
- return this.geminiIgnoreFilter.isIgnored(filePath);
340883
- }
340884
- return false;
340885
- }
340886
341304
  /**
340887
341305
  * Unified method to check if a file should be ignored based on filtering options
340888
341306
  */
340889
341307
  shouldIgnoreFile(filePath, options2 = {}) {
340890
- const { respectGitIgnore = true, respectGeminiIgnore = true } = options2;
340891
- if (respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
340892
- return true;
340893
- }
340894
- if (respectGeminiIgnore && this.shouldGeminiIgnoreFile(filePath)) {
340895
- return true;
340896
- }
340897
- return false;
341308
+ return this.filterFiles([filePath], options2).length === 0;
340898
341309
  }
340899
341310
  };
340900
341311
 
@@ -340909,7 +341320,7 @@ var import_promise_deferred = __toESM(require_dist9(), 1);
340909
341320
  var import_promise_deferred2 = __toESM(require_dist9(), 1);
340910
341321
  import { Buffer as Buffer22 } from "node:buffer";
340911
341322
  import { spawn as spawn8 } from "child_process";
340912
- import { EventEmitter as EventEmitter8 } from "node:events";
341323
+ import { EventEmitter as EventEmitter9 } from "node:events";
340913
341324
  var __defProp3 = Object.defineProperty;
340914
341325
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
340915
341326
  var __getOwnPropNames2 = Object.getOwnPropertyNames;
@@ -345250,7 +345661,7 @@ init_utils4();
345250
345661
  var PluginStore = class {
345251
345662
  constructor() {
345252
345663
  this.plugins = /* @__PURE__ */ new Set();
345253
- this.events = new EventEmitter8();
345664
+ this.events = new EventEmitter9();
345254
345665
  }
345255
345666
  on(type, listener) {
345256
345667
  this.events.on(type, listener);
@@ -345680,7 +346091,7 @@ var WriteTodosTool = class _WriteTodosTool extends BaseDeclarativeTool {
345680
346091
  }
345681
346092
  return null;
345682
346093
  }
345683
- createInvocation(params) {
346094
+ createInvocation(params, _messageBus, _toolName, _displayName) {
345684
346095
  return new WriteTodosToolInvocation(params);
345685
346096
  }
345686
346097
  };
@@ -346045,7 +346456,7 @@ var JsonStreamEventType;
346045
346456
  // packages/core/dist/src/utils/workspaceContext.js
346046
346457
  import * as fs52 from "node:fs";
346047
346458
  import * as path55 from "node:path";
346048
- import * as process21 from "node:process";
346459
+ import * as process23 from "node:process";
346049
346460
  var WorkspaceContext = class {
346050
346461
  directories = /* @__PURE__ */ new Set();
346051
346462
  initialDirectories;
@@ -346087,7 +346498,7 @@ var WorkspaceContext = class {
346087
346498
  * @param directory The directory path to add (can be relative or absolute)
346088
346499
  * @param basePath Optional base path for resolving relative paths (defaults to cwd)
346089
346500
  */
346090
- addDirectory(directory, basePath = process21.cwd()) {
346501
+ addDirectory(directory, basePath = process23.cwd()) {
346091
346502
  try {
346092
346503
  const resolved = this.resolveAndValidateDir(directory, basePath);
346093
346504
  if (this.directories.has(resolved)) {
@@ -346099,7 +346510,7 @@ var WorkspaceContext = class {
346099
346510
  debugLogger.warn(`[WARN] Skipping unreadable directory: ${directory} (${err2 instanceof Error ? err2.message : String(err2)})`);
346100
346511
  }
346101
346512
  }
346102
- resolveAndValidateDir(directory, basePath = process21.cwd()) {
346513
+ resolveAndValidateDir(directory, basePath = process23.cwd()) {
346103
346514
  const absolutePath = path55.isAbsolute(directory) ? directory : path55.resolve(basePath, directory);
346104
346515
  if (!fs52.existsSync(absolutePath)) {
346105
346516
  throw new Error(`Directory does not exist: ${absolutePath}`);
@@ -346188,7 +346599,7 @@ var WorkspaceContext = class {
346188
346599
  };
346189
346600
 
346190
346601
  // packages/core/dist/src/confirmation-bus/message-bus.js
346191
- import { EventEmitter as EventEmitter9 } from "node:events";
346602
+ import { EventEmitter as EventEmitter10 } from "node:events";
346192
346603
 
346193
346604
  // packages/core/dist/src/policy/types.js
346194
346605
  var PolicyDecision;
@@ -346199,7 +346610,7 @@ var PolicyDecision;
346199
346610
  })(PolicyDecision || (PolicyDecision = {}));
346200
346611
 
346201
346612
  // packages/core/dist/src/confirmation-bus/message-bus.js
346202
- var MessageBus = class extends EventEmitter9 {
346613
+ var MessageBus = class extends EventEmitter10 {
346203
346614
  policyEngine;
346204
346615
  debug;
346205
346616
  constructor(policyEngine, debug2 = false) {
@@ -346507,7 +346918,7 @@ function convertInputConfigToJsonSchema(inputConfig) {
346507
346918
  // packages/core/dist/src/core/nonInteractiveToolExecutor.js
346508
346919
  async function executeToolCall(config2, toolCallRequest, abortSignal) {
346509
346920
  return new Promise((resolve13, reject) => {
346510
- new CoreToolScheduler({
346921
+ const scheduler3 = new CoreToolScheduler({
346511
346922
  config: config2,
346512
346923
  getPreferredEditor: () => void 0,
346513
346924
  onEditorClose: () => {
@@ -346515,7 +346926,10 @@ async function executeToolCall(config2, toolCallRequest, abortSignal) {
346515
346926
  onAllToolCallsComplete: async (completedToolCalls) => {
346516
346927
  resolve13(completedToolCalls[0]);
346517
346928
  }
346518
- }).schedule(toolCallRequest, abortSignal).catch(reject);
346929
+ });
346930
+ scheduler3.schedule(toolCallRequest, abortSignal).catch((error) => {
346931
+ reject(error);
346932
+ });
346519
346933
  });
346520
346934
  }
346521
346935
 
@@ -348530,6 +348944,7 @@ var Config = class {
348530
348944
  continueOnFailedApiCall;
348531
348945
  retryFetchErrors;
348532
348946
  enableShellOutputEfficiency;
348947
+ fakeResponses;
348533
348948
  disableYoloMode;
348534
348949
  constructor(params) {
348535
348950
  this.sessionId = params.sessionId;
@@ -348571,7 +348986,7 @@ var Config = class {
348571
348986
  };
348572
348987
  this.checkpointing = params.checkpointing ?? false;
348573
348988
  this.proxy = params.proxy;
348574
- this.cwd = params.cwd ?? process22.cwd();
348989
+ this.cwd = params.cwd ?? process24.cwd();
348575
348990
  this.fileDiscoveryService = params.fileDiscoveryService ?? null;
348576
348991
  this.bugCommand = params.bugCommand;
348577
348992
  this.model = params.model;
@@ -348617,6 +349032,7 @@ var Config = class {
348617
349032
  this.enableShellOutputEfficiency = params.enableShellOutputEfficiency ?? true;
348618
349033
  this.extensionManagement = params.extensionManagement ?? true;
348619
349034
  this.storage = new Storage2(this.targetDir);
349035
+ this.fakeResponses = params.fakeResponses;
348620
349036
  this.enablePromptCompletion = params.enablePromptCompletion ?? false;
348621
349037
  this.fileExclusions = new FileExclusions(this);
348622
349038
  this.eventEmitter = params.eventEmitter;
@@ -348669,7 +349085,6 @@ var Config = class {
348669
349085
  this.contentGeneratorConfig = newContentGeneratorConfig;
348670
349086
  this.baseLlmClient = new BaseLlmClient(this.contentGenerator, this);
348671
349087
  this.inFallbackMode = false;
348672
- logCliConfiguration(this, new StartSessionEvent(this, this.toolRegistry));
348673
349088
  }
348674
349089
  getUserTier() {
348675
349090
  return this.contentGenerator?.userTier;
@@ -348731,7 +349146,7 @@ var Config = class {
348731
349146
  }
348732
349147
  isRestrictiveSandbox() {
348733
349148
  const sandboxConfig = this.getSandbox();
348734
- const seatbeltProfile = process22.env["SEATBELT_PROFILE"];
349149
+ const seatbeltProfile = process24.env["SEATBELT_PROFILE"];
348735
349150
  return !!sandboxConfig && sandboxConfig.command === "sandbox-exec" && !!seatbeltProfile && seatbeltProfile.startsWith("restrictive-");
348736
349151
  }
348737
349152
  getTargetDir() {
@@ -351783,34 +352198,12 @@ var hasFileExtension = (0, import_picomatch.default)("**/*[*.]*");
351783
352198
  var import_fdir = __toESM(require_dist10(), 1);
351784
352199
 
351785
352200
  // packages/core/dist/src/utils/errorParsing.js
351786
- var getRateLimitErrorMessageGoogleFree = (fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
351787
- Possible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session.`;
351788
- var getRateLimitErrorMessageGoogleProQuotaFree = (currentModel = DEFAULT_GEMINI_MODEL, fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
351789
- You have reached your daily ${currentModel} quota limit. You will be switched to the ${fallbackModel} model for the rest of this session. To increase your limits, upgrade to get higher limits at https://goo.gle/set-up-gemini-code-assist, or use /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
351790
- var getRateLimitErrorMessageGoogleGenericQuotaFree = () => `
351791
- You have reached your daily quota limit. To increase your limits, upgrade to get higher limits at https://goo.gle/set-up-gemini-code-assist, or use /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
351792
- var getRateLimitErrorMessageGooglePaid = (fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
351793
- Possible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session. We appreciate you for choosing Gemini Code Assist and the Gemini CLI.`;
351794
- var getRateLimitErrorMessageGoogleProQuotaPaid = (currentModel = DEFAULT_GEMINI_MODEL, fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
351795
- You have reached your daily ${currentModel} quota limit. You will be switched to the ${fallbackModel} model for the rest of this session. We appreciate you for choosing Gemini Code Assist and the Gemini CLI. To continue accessing the ${currentModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
351796
- var getRateLimitErrorMessageGoogleGenericQuotaPaid = (currentModel = DEFAULT_GEMINI_MODEL) => `
351797
- You have reached your daily quota limit. We appreciate you for choosing Gemini Code Assist and the Gemini CLI. To continue accessing the ${currentModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
351798
352201
  var RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI = "\nPlease wait and try again later. To increase your limits, request a quota increase through AI Studio, or switch to another /auth method";
351799
352202
  var RATE_LIMIT_ERROR_MESSAGE_VERTEX = "\nPlease wait and try again later. To increase your limits, request a quota increase through Vertex, or switch to another /auth method";
351800
352203
  var getRateLimitErrorMessageDefault = (fallbackModel = DEFAULT_GEMINI_FLASH_MODEL) => `
351801
352204
  Possible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session.`;
351802
- function getRateLimitMessage(authType, error, userTier, currentModel, fallbackModel) {
352205
+ function getRateLimitMessage(authType, fallbackModel) {
351803
352206
  switch (authType) {
351804
- case AuthType2.LOGIN_WITH_GOOGLE: {
351805
- const isPaidTier = userTier === UserTierId.LEGACY || userTier === UserTierId.STANDARD;
351806
- if (isProQuotaExceededError(error)) {
351807
- return isPaidTier ? getRateLimitErrorMessageGoogleProQuotaPaid(currentModel || DEFAULT_GEMINI_MODEL, fallbackModel) : getRateLimitErrorMessageGoogleProQuotaFree(currentModel || DEFAULT_GEMINI_MODEL, fallbackModel);
351808
- } else if (isGenericQuotaExceededError(error)) {
351809
- return isPaidTier ? getRateLimitErrorMessageGoogleGenericQuotaPaid(currentModel || DEFAULT_GEMINI_MODEL) : getRateLimitErrorMessageGoogleGenericQuotaFree();
351810
- } else {
351811
- return isPaidTier ? getRateLimitErrorMessageGooglePaid(fallbackModel) : getRateLimitErrorMessageGoogleFree(fallbackModel);
351812
- }
351813
- }
351814
352207
  case AuthType2.USE_GEMINI:
351815
352208
  return RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI;
351816
352209
  case AuthType2.USE_VERTEX_AI:
@@ -351823,7 +352216,7 @@ function parseAndFormatApiError(error, authType, userTier, currentModel, fallbac
351823
352216
  if (isStructuredError(error)) {
351824
352217
  let text = `[API Error: ${error.message}]`;
351825
352218
  if (error.status === 429) {
351826
- text += getRateLimitMessage(authType, error, userTier, currentModel, fallbackModel);
352219
+ text += getRateLimitMessage(authType, fallbackModel);
351827
352220
  }
351828
352221
  return text;
351829
352222
  }
@@ -351846,7 +352239,7 @@ function parseAndFormatApiError(error, authType, userTier, currentModel, fallbac
351846
352239
  }
351847
352240
  let text = `[API Error: ${finalMessage} (Status: ${parsedError.error.status})]`;
351848
352241
  if (parsedError.error.code === 429) {
351849
- text += getRateLimitMessage(authType, parsedError, userTier, currentModel, fallbackModel);
352242
+ text += getRateLimitMessage(authType, fallbackModel);
351850
352243
  }
351851
352244
  return text;
351852
352245
  }
@@ -351857,56 +352250,8 @@ function parseAndFormatApiError(error, authType, userTier, currentModel, fallbac
351857
352250
  return "[API Error: An unknown error occurred.]";
351858
352251
  }
351859
352252
 
351860
- // packages/core/dist/src/utils/events.js
351861
- import { EventEmitter as EventEmitter10 } from "node:events";
351862
- var CoreEvent;
351863
- (function(CoreEvent2) {
351864
- CoreEvent2["UserFeedback"] = "user-feedback";
351865
- })(CoreEvent || (CoreEvent = {}));
351866
- var CoreEventEmitter = class _CoreEventEmitter extends EventEmitter10 {
351867
- _feedbackBacklog = [];
351868
- static MAX_BACKLOG_SIZE = 1e4;
351869
- constructor() {
351870
- super();
351871
- }
351872
- /**
351873
- * Sends actionable feedback to the user.
351874
- * Buffers automatically if the UI hasn't subscribed yet.
351875
- */
351876
- emitFeedback(severity, message, error) {
351877
- const payload = { severity, message, error };
351878
- if (this.listenerCount(CoreEvent.UserFeedback) === 0) {
351879
- if (this._feedbackBacklog.length >= _CoreEventEmitter.MAX_BACKLOG_SIZE) {
351880
- this._feedbackBacklog.shift();
351881
- }
351882
- this._feedbackBacklog.push(payload);
351883
- } else {
351884
- this.emit(CoreEvent.UserFeedback, payload);
351885
- }
351886
- }
351887
- /**
351888
- * Flushes buffered messages. Call this immediately after primary UI listener
351889
- * subscribes.
351890
- */
351891
- drainFeedbackBacklog() {
351892
- const backlog = [...this._feedbackBacklog];
351893
- this._feedbackBacklog.length = 0;
351894
- for (const payload of backlog) {
351895
- this.emit(CoreEvent.UserFeedback, payload);
351896
- }
351897
- }
351898
- on(event, listener) {
351899
- return super.on(event, listener);
351900
- }
351901
- off(event, listener) {
351902
- return super.off(event, listener);
351903
- }
351904
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
351905
- emit(event, ...args2) {
351906
- return super.emit(event, ...args2);
351907
- }
351908
- };
351909
- var coreEvents = new CoreEventEmitter();
352253
+ // packages/core/dist/src/index.js
352254
+ init_events();
351910
352255
 
351911
352256
  // packages/core/dist/src/utils/session.js
351912
352257
  import { randomUUID as randomUUID6 } from "node:crypto";
@@ -352154,7 +352499,7 @@ var GCSTaskStore = class {
352154
352499
  if (await fse.pathExists(workDir)) {
352155
352500
  const entries2 = await fsPromises4.readdir(workDir);
352156
352501
  if (entries2.length > 0) {
352157
- const tmpArchiveFile = join22(tmpdir3(), getTmpArchiveFilename(taskId));
352502
+ const tmpArchiveFile = join22(tmpdir4(), getTmpArchiveFilename(taskId));
352158
352503
  try {
352159
352504
  await create(
352160
352505
  {
@@ -352276,7 +352621,7 @@ var GCSTaskStore = class {
352276
352621
  const workspaceFile = this.storage.bucket(this.bucketName).file(workspaceObjectPath);
352277
352622
  const [workspaceExists] = await workspaceFile.exists();
352278
352623
  if (workspaceExists) {
352279
- const tmpArchiveFile = join22(tmpdir3(), getTmpArchiveFilename(taskId));
352624
+ const tmpArchiveFile = join22(tmpdir4(), getTmpArchiveFilename(taskId));
352280
352625
  try {
352281
352626
  await workspaceFile.download({ destination: tmpArchiveFile });
352282
352627
  await extract({ file: tmpArchiveFile, cwd: workDir });
@@ -352759,8 +353104,8 @@ var Task = class _Task {
352759
353104
  );
352760
353105
  }
352761
353106
  if (hasChanged) {
352762
- const message = this.toolStatusMessage(tc, this.id, this.contextId);
352763
353107
  const coderAgentMessage = tc.status === "awaiting_approval" ? { kind: "tool-call-confirmation" /* ToolCallConfirmationEvent */ } : { kind: "tool-call-update" /* ToolCallUpdateEvent */ };
353108
+ const message = this.toolStatusMessage(tc, this.id, this.contextId);
352764
353109
  const event = this._createStatusUpdateEvent(
352765
353110
  this.taskState,
352766
353111
  coderAgentMessage,
@@ -352785,10 +353130,10 @@ var Task = class _Task {
352785
353130
  const isAwaitingApproval = allPendingStatuses.some(
352786
353131
  (status) => status === "awaiting_approval"
352787
353132
  );
352788
- const allPendingAreStable = allPendingStatuses.every(
352789
- (status) => status === "awaiting_approval" || status === "success" || status === "error" || status === "cancelled"
353133
+ const isExecuting = allPendingStatuses.some(
353134
+ (status) => status === "executing"
352790
353135
  );
352791
- if (isAwaitingApproval && allPendingAreStable && !this.skipFinalTrueAfterInlineEdit) {
353136
+ if (isAwaitingApproval && !isExecuting && !this.skipFinalTrueAfterInlineEdit) {
352792
353137
  this.skipFinalTrueAfterInlineEdit = false;
352793
353138
  this.setTaskStateAndPublishUpdate(
352794
353139
  "input-required",
@@ -352957,6 +353302,10 @@ var Task = class _Task {
352957
353302
  logger.info("[Task] Sending agent thought...");
352958
353303
  this._sendThought(event.value, traceId);
352959
353304
  break;
353305
+ case GeminiEventType.Citation:
353306
+ logger.info("[Task] Received citation from LLM stream.");
353307
+ this._sendCitation(event.value);
353308
+ break;
352960
353309
  case GeminiEventType.ChatCompressed:
352961
353310
  break;
352962
353311
  case GeminiEventType.Finished:
@@ -353233,6 +353582,19 @@ var Task = class _Task {
353233
353582
  )
353234
353583
  );
353235
353584
  }
353585
+ _sendCitation(citation) {
353586
+ if (!citation || citation.trim() === "") {
353587
+ return;
353588
+ }
353589
+ logger.info("[Task] Sending citation to event bus.");
353590
+ const message = this._createTextMessage(citation);
353591
+ const citationEvent = {
353592
+ kind: "citation" /* CitationEvent */
353593
+ };
353594
+ this.eventBus?.publish(
353595
+ this._createStatusUpdateEvent(this.taskState, citationEvent, message)
353596
+ );
353597
+ }
353236
353598
  };
353237
353599
 
353238
353600
  // packages/a2a-server/src/http/requestStorage.ts