@google/gemini-cli 0.68.0-preview.0 → 0.69.0-preview.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/bundle/{chunk-VBHMFLBY.js → chunk-2KKDGWF2.js} +1 -1
  2. package/bundle/{chunk-ODU7Z2RJ.js → chunk-2ONJU4V7.js} +1 -1
  3. package/bundle/chunk-3HEOCQDN.js +65 -0
  4. package/bundle/{chunk-HRM7UWGB.js → chunk-4SOPZCNA.js} +22 -6
  5. package/bundle/{chunk-JMHCFAD6.js → chunk-6KCLIS6W.js} +1 -1
  6. package/bundle/{chunk-CXMHAFLN.js → chunk-BRHBBQC5.js} +2 -2
  7. package/bundle/{chunk-KKKD4FID.js → chunk-C5BED6L6.js} +2 -2
  8. package/bundle/{chunk-OZOUOK43.js → chunk-CGQSFR2I.js} +7 -2
  9. package/bundle/{chunk-RD2EMHV2.js → chunk-CWHEOJXF.js} +7 -2
  10. package/bundle/{chunk-ZZOOHVBL.js → chunk-DWMZSQYG.js} +4479 -1925
  11. package/bundle/{chunk-ZEK4UYYW.js → chunk-GDCMMKZ2.js} +1 -1
  12. package/bundle/{chunk-44PCK4QK.js → chunk-GQ7FZNO2.js} +1 -1
  13. package/bundle/{chunk-XPTXBYQQ.js → chunk-JJWPYMIO.js} +3 -3
  14. package/bundle/{chunk-L57AYV6U.js → chunk-KUXCUQKX.js} +4357 -1897
  15. package/bundle/{chunk-6A5BTTNC.js → chunk-LYKP3S67.js} +22 -6
  16. package/bundle/{chunk-RCF66HCI.js → chunk-MP4TVGOP.js} +4479 -1925
  17. package/bundle/{chunk-XVNEFQR3.js → chunk-PH5XENTH.js} +1 -1
  18. package/bundle/{chunk-B2FKXXUH.js → chunk-RBDD6IBU.js} +617 -228
  19. package/bundle/{chunk-BKVNBJ5C.js → chunk-SYOIMUZI.js} +617 -228
  20. package/bundle/{chunk-VCO4TMD6.js → chunk-U3FFDEKY.js} +22 -6
  21. package/bundle/{chunk-LQDISFTJ.js → chunk-U5FJ6OGB.js} +2 -2
  22. package/bundle/{chunk-WEP47ZZU.js → chunk-UAHZWXSG.js} +7 -2
  23. package/bundle/chunk-UW3ZS3BH.js +65 -0
  24. package/bundle/{chunk-Q76ZDILI.js → chunk-V7L3FMBE.js} +3 -3
  25. package/bundle/chunk-VQTELFV3.js +65 -0
  26. package/bundle/{chunk-YPPJDFYP.js → chunk-YODS6HR2.js} +3 -3
  27. package/bundle/{chunk-G7EMTV2Q.js → chunk-YP5TA33N.js} +617 -228
  28. package/bundle/{cleanup-CCR2EOHA.js → cleanup-3T2KXSP4.js} +2 -2
  29. package/bundle/{cleanup-OQV2G5Y3.js → cleanup-NNQCI4KC.js} +2 -2
  30. package/bundle/{cleanup-T24OFMOA.js → cleanup-TA4VYDXQ.js} +2 -2
  31. package/bundle/{core-NQRKBS47.js → core-6XF5EO7Z.js} +35 -1
  32. package/bundle/{core-UIPNZ5VU.js → core-TUJHM7E7.js} +35 -1
  33. package/bundle/{devtoolsService-3G5ZA3JV.js → devtoolsService-7EMPANTX.js} +2 -2
  34. package/bundle/{devtoolsService-V3OEHE5V.js → devtoolsService-I7WFRUEA.js} +2 -2
  35. package/bundle/{devtoolsService-EWNQDTC7.js → devtoolsService-RCBUZGYD.js} +2 -2
  36. package/bundle/{dist-OYZDNSTI.js → dist-OSQFIX7F.js} +35 -1
  37. package/bundle/docs/changelogs/index.md +18 -0
  38. package/bundle/docs/changelogs/latest.md +89 -84
  39. package/bundle/docs/changelogs/preview.md +106 -92
  40. package/bundle/docs/cli/themes.md +50 -5
  41. package/bundle/docs/cli/trusted-folders.md +13 -0
  42. package/bundle/docs/reference/commands.md +4 -0
  43. package/bundle/docs/reference/configuration.md +8 -0
  44. package/bundle/docs/reference/policy-engine.md +6 -0
  45. package/bundle/formatError-KEQ3HU3Y.js +14 -0
  46. package/bundle/formatError-LJFIC7G3.js +14 -0
  47. package/bundle/formatError-MIUNQEYE.js +14 -0
  48. package/bundle/{gemini-YFCTZ76S.js → gemini-22ON2CZG.js} +493 -132
  49. package/bundle/{gemini-FSHMUCSM.js → gemini-HLS52ZNZ.js} +493 -132
  50. package/bundle/{gemini-2P73372G.js → gemini-ZZZEFPSK.js} +493 -132
  51. package/bundle/gemini.js +14 -13
  52. package/bundle/{interactiveCli-F5RRE2VJ.js → interactiveCli-5HMWVTK2.js} +1641 -1208
  53. package/bundle/{interactiveCli-X54KN2EM.js → interactiveCli-HQBE3C3C.js} +1641 -1208
  54. package/bundle/{interactiveCli-I75IWUIA.js → interactiveCli-NKFQZXB5.js} +1641 -1208
  55. package/bundle/{liteRtServerManager-JTOIS4KU.js → liteRtServerManager-2IOXWO76.js} +4 -4
  56. package/bundle/{liteRtServerManager-UVQ2I6NL.js → liteRtServerManager-AG4Y5JMZ.js} +4 -4
  57. package/bundle/{liteRtServerManager-FLPMMDNM.js → liteRtServerManager-OFNVXXQ4.js} +4 -4
  58. package/bundle/{oauth2-provider-AYO4BU7A.js → oauth2-provider-2DHNJ2S3.js} +1 -1
  59. package/bundle/{oauth2-provider-NCQY7TJE.js → oauth2-provider-OEGXLWIL.js} +1 -1
  60. package/bundle/{oauth2-provider-VMBYZOC7.js → oauth2-provider-YDNSNN32.js} +1 -1
  61. package/bundle/policies/yolo.toml +1 -0
  62. package/bundle/sandbox-macos-permissive-open.sb +8 -0
  63. package/bundle/sandbox-macos-permissive-proxied.sb +8 -0
  64. package/bundle/sandbox-macos-restrictive-open.sb +1 -0
  65. package/bundle/sandbox-macos-restrictive-proxied.sb +1 -0
  66. package/bundle/sandbox-macos-strict-open.sb +1 -0
  67. package/bundle/sandbox-macos-strict-proxied.sb +1 -0
  68. package/bundle/{start-IXQ2E7L6.js → start-7GJH3MKY.js} +6 -6
  69. package/bundle/{start-YEKGRZVH.js → start-JSVKPUTV.js} +6 -6
  70. package/bundle/{start-DFHM4HI4.js → start-N33LF5WK.js} +6 -6
  71. package/package.json +1 -1
@@ -2,7 +2,10 @@ const require = (await import('node:module')).createRequire(import.meta.url); co
2
2
  import {
3
3
  startCommand,
4
4
  startServer
5
- } from "./chunk-YPPJDFYP.js";
5
+ } from "./chunk-YODS6HR2.js";
6
+ import {
7
+ formatCliError
8
+ } from "./chunk-VQTELFV3.js";
6
9
  import {
7
10
  BuiltinCommandLoader,
8
11
  CommandService,
@@ -45,11 +48,11 @@ import {
45
48
  updateExtension,
46
49
  validateAuthMethod,
47
50
  validateContextFilePath
48
- } from "./chunk-G7EMTV2Q.js";
51
+ } from "./chunk-YP5TA33N.js";
49
52
  import {
50
53
  exitCli,
51
54
  require_source
52
- } from "./chunk-ODU7Z2RJ.js";
55
+ } from "./chunk-2ONJU4V7.js";
53
56
  import {
54
57
  appEvents
55
58
  } from "./chunk-5PS3AYFU.js";
@@ -89,12 +92,12 @@ import {
89
92
  saveModelChange,
90
93
  setAmbiguousCharactersWide,
91
94
  stripAnsi
92
- } from "./chunk-VCO4TMD6.js";
95
+ } from "./chunk-U3FFDEKY.js";
93
96
  import {
94
97
  RELAUNCH_EXIT_CODE,
95
98
  require_semver
96
- } from "./chunk-KKKD4FID.js";
97
- import "./chunk-44PCK4QK.js";
99
+ } from "./chunk-C5BED6L6.js";
100
+ import "./chunk-GQ7FZNO2.js";
98
101
  import {
99
102
  cleanupCheckpoints,
100
103
  registerCleanup,
@@ -103,7 +106,7 @@ import {
103
106
  runExitCleanup,
104
107
  runSyncCleanup,
105
108
  setupSignalHandlers
106
- } from "./chunk-WEP47ZZU.js";
109
+ } from "./chunk-CGQSFR2I.js";
107
110
  import {
108
111
  ASK_USER_TOOL_NAME,
109
112
  AjvJsonSchemaValidator,
@@ -139,6 +142,8 @@ import {
139
142
  FatalUntrustedWorkspaceError,
140
143
  FileDiscoveryService,
141
144
  FolderTrustDiscoveryService,
145
+ GEMINI_CLI_IN_SHELL_ENV_VAR,
146
+ GEMINI_CLI_NESTED_SESSION_ENV_VAR,
142
147
  GEMINI_DIR,
143
148
  GEMINI_MODEL_ALIAS_AUTO,
144
149
  GeminiEventType,
@@ -165,6 +170,7 @@ import {
165
170
  MCPServerStatus,
166
171
  McpError,
167
172
  MessageBusType,
173
+ NESTED_INTERACTIVE_SESSION_ERROR,
168
174
  OTHER_BLOCKED_MESSAGE,
169
175
  OutputFormat,
170
176
  PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
@@ -263,6 +269,7 @@ import {
263
269
  logToolCall,
264
270
  logUserPrompt,
265
271
  mergeCapabilities,
272
+ normalizeError,
266
273
  parseAndFormatApiError,
267
274
  partListUnionToString,
268
275
  patchStdio,
@@ -289,7 +296,7 @@ import {
289
296
  updatePolicy,
290
297
  writeToStderr,
291
298
  writeToStdout
292
- } from "./chunk-L57AYV6U.js";
299
+ } from "./chunk-KUXCUQKX.js";
293
300
  import "./chunk-664ZODQF.js";
294
301
  import "./chunk-IUUIT4SU.js";
295
302
  import "./chunk-L6PII3GR.js";
@@ -1574,11 +1581,11 @@ var parser = new YargsParser({
1574
1581
  resolve: resolve2,
1575
1582
  // TODO: figure out a way to combine ESM and CJS coverage, such that
1576
1583
  // we can exercise all the lines below:
1577
- require: (path18) => {
1584
+ require: (path19) => {
1578
1585
  if (typeof __require !== "undefined") {
1579
- return __require(path18);
1580
- } else if (path18.match(/\.json$/)) {
1581
- return JSON.parse(readFileSync(path18, "utf8"));
1586
+ return __require(path19);
1587
+ } else if (path19.match(/\.json$/)) {
1588
+ return JSON.parse(readFileSync(path19, "utf8"));
1582
1589
  } else {
1583
1590
  throw Error("only .json config files are supported in ESM");
1584
1591
  }
@@ -6382,27 +6389,27 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
6382
6389
  var __filename = fileURLToPath2(import.meta.url);
6383
6390
  var __dirname2 = dirname3(__filename);
6384
6391
  var EXAMPLES_PATH = join(__dirname2, "examples");
6385
- async function pathExists(path18) {
6392
+ async function pathExists(path19) {
6386
6393
  try {
6387
- await access(path18);
6394
+ await access(path19);
6388
6395
  return true;
6389
6396
  } catch {
6390
6397
  return false;
6391
6398
  }
6392
6399
  }
6393
- async function createDirectory(path18) {
6394
- if (await pathExists(path18)) {
6395
- throw new Error(`Path already exists: ${path18}`);
6400
+ async function createDirectory(path19) {
6401
+ if (await pathExists(path19)) {
6402
+ throw new Error(`Path already exists: ${path19}`);
6396
6403
  }
6397
- await mkdir(path18, { recursive: true });
6404
+ await mkdir(path19, { recursive: true });
6398
6405
  }
6399
- async function copyDirectory(template, path18) {
6400
- await createDirectory(path18);
6406
+ async function copyDirectory(template, path19) {
6407
+ await createDirectory(path19);
6401
6408
  const examplePath = join(EXAMPLES_PATH, template);
6402
6409
  const entries = await readdir(examplePath, { withFileTypes: true });
6403
6410
  for (const entry of entries) {
6404
6411
  const srcPath = join(examplePath, entry.name);
6405
- const destPath = join(path18, entry.name);
6412
+ const destPath = join(path19, entry.name);
6406
6413
  await cp(srcPath, destPath, { recursive: true });
6407
6414
  }
6408
6415
  }
@@ -6734,7 +6741,7 @@ async function handleEnable3(args) {
6734
6741
  const result = enableSkill(settings, name);
6735
6742
  const feedback = renderSkillActionFeedback(
6736
6743
  result,
6737
- (label, path18) => `${import_chalk5.default.bold(label)} (${import_chalk5.default.dim(path18)})`
6744
+ (label, path19) => `${import_chalk5.default.bold(label)} (${import_chalk5.default.dim(path19)})`
6738
6745
  );
6739
6746
  debugLogger.log(feedback);
6740
6747
  }
@@ -6764,7 +6771,7 @@ async function handleDisable3(args) {
6764
6771
  const result = disableSkill(settings, name, scope);
6765
6772
  const feedback = renderSkillActionFeedback(
6766
6773
  result,
6767
- (label, path18) => `${import_chalk6.default.bold(label)} (${import_chalk6.default.dim(path18)})`
6774
+ (label, path19) => `${import_chalk6.default.bold(label)} (${import_chalk6.default.dim(path19)})`
6768
6775
  );
6769
6776
  debugLogger.log(feedback);
6770
6777
  }
@@ -7894,6 +7901,16 @@ var RequestPermissionResponseSchema = external_exports.object({
7894
7901
  })
7895
7902
  ])
7896
7903
  });
7904
+ function isAnsiOutput(value) {
7905
+ return Array.isArray(value) && value.every(
7906
+ (line) => Array.isArray(line) && line.every(
7907
+ (token) => typeof token === "object" && token !== null && "text" in token && typeof token.text === "string"
7908
+ )
7909
+ );
7910
+ }
7911
+ function ansiOutputToPlainText(ansiOutput) {
7912
+ return ansiOutput.map((line) => line.map((token) => token.text).join("")).join("\n").trim();
7913
+ }
7897
7914
  function toToolCallContent(toolResult) {
7898
7915
  if (toolResult.error?.message) {
7899
7916
  throw new Error(toolResult.error.message);
@@ -7904,6 +7921,12 @@ function toToolCallContent(toolResult) {
7904
7921
  type: "content",
7905
7922
  content: { type: "text", text: toolResult.returnDisplay }
7906
7923
  };
7924
+ } else if (isAnsiOutput(toolResult.returnDisplay)) {
7925
+ const text = ansiOutputToPlainText(toolResult.returnDisplay);
7926
+ if (!text) {
7927
+ return null;
7928
+ }
7929
+ return { type: "content", content: { type: "text", text } };
7907
7930
  } else {
7908
7931
  if ("fileName" in toolResult.returnDisplay) {
7909
7932
  return {
@@ -8380,7 +8403,7 @@ async function loadSandboxConfig(settings, argv) {
8380
8403
  }
8381
8404
  const command2 = getSandboxCommand(sandboxValue);
8382
8405
  const packageJson = await getPackageJson(__dirname3);
8383
- const image = process.env["GEMINI_SANDBOX_IMAGE"] ?? "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.68.0-preview.0" ?? customImage ?? packageJson?.config?.sandboxImageUri;
8406
+ const image = process.env["GEMINI_SANDBOX_IMAGE"] ?? "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.69.0-preview.0" ?? customImage ?? packageJson?.config?.sandboxImageUri;
8384
8407
  const isNative = command2 === "windows-native" || command2 === "sandbox-exec" || command2 === "lxc";
8385
8408
  return command2 && (image || isNative) ? { enabled: true, allowedPaths, networkAccess, command: command2, image } : void 0;
8386
8409
  }
@@ -8783,6 +8806,40 @@ async function parseArguments(settings) {
8783
8806
  } else if (typeof queryArg === "string") {
8784
8807
  q = queryArg;
8785
8808
  }
8809
+ const trimmedQuery = q?.trim() ?? "";
8810
+ const rawQueryTokens = trimmedQuery.length > 0 ? trimmedQuery.split(/\s+/) : [];
8811
+ const firstQueryToken = rawQueryTokens[0]?.toLowerCase();
8812
+ const secondQueryToken = rawQueryTokens[1]?.toLowerCase();
8813
+ const isQuotedPrompt = rawQueryTokens.length > 1 && process3.argv.some((arg) => arg.trim() === trimmedQuery);
8814
+ const isInvalidConfigSubcommand = !result["isCommand"] && (firstQueryToken === "config" && (secondQueryToken === void 0 || secondQueryToken.startsWith("-") || [
8815
+ "set",
8816
+ "get",
8817
+ "list",
8818
+ "delete",
8819
+ "unset",
8820
+ "edit",
8821
+ "show",
8822
+ "default-model",
8823
+ "model"
8824
+ ].includes(secondQueryToken)) || (firstQueryToken === "set" || firstQueryToken === "model") && secondQueryToken !== void 0 && ["set", "get", "list", "default-model", "model"].includes(
8825
+ secondQueryToken
8826
+ )) && !isQuotedPrompt;
8827
+ const isInNestedShell = process3.env[GEMINI_CLI_IN_SHELL_ENV_VAR] === "1" || process3.env[GEMINI_CLI_NESTED_SESSION_ENV_VAR] === "1";
8828
+ if (isInNestedShell) {
8829
+ const isAllowedNonInteractive = Boolean(result["isCommand"]) || Boolean(result["listModels"]) || Boolean(result["list-models"]) || Boolean(result["listExtensions"]) || Boolean(result["list-extensions"]) || Boolean(result["listSessions"]) || Boolean(result["list-sessions"]) || Boolean(result["deleteSession"]) || Boolean(result["delete-session"]) || Boolean(result["prompt"]) && !result["promptInteractive"] && !result["prompt-interactive"] && !isInvalidConfigSubcommand;
8830
+ if (!isAllowedNonInteractive) {
8831
+ debugLogger.error(NESTED_INTERACTIVE_SESSION_ERROR);
8832
+ await runExitCleanup();
8833
+ process3.exit(1);
8834
+ }
8835
+ }
8836
+ if (isInvalidConfigSubcommand) {
8837
+ debugLogger.error(
8838
+ `Error: Unknown command "${rawQueryTokens[0]}". To switch models or update settings, use built-in slash commands (/model, /settings).`
8839
+ );
8840
+ await runExitCleanup();
8841
+ process3.exit(1);
8842
+ }
8786
8843
  if (q && !result["prompt"]) {
8787
8844
  if (!isHeadlessMode()) {
8788
8845
  startupMessages.push(
@@ -9113,12 +9170,13 @@ async function loadCliConfig(settings, sessionId, argv, options = {}) {
9113
9170
  usageStatisticsEnabled: settings.privacy?.usageStatisticsEnabled,
9114
9171
  fileFiltering,
9115
9172
  checkpointing: settings.general?.checkpointing?.enabled,
9116
- proxy: process3.env["HTTPS_PROXY"] || process3.env["https_proxy"] || process3.env["HTTP_PROXY"] || process3.env["http_proxy"],
9173
+ proxy: process3.env["HTTPS_PROXY"] || process3.env["https_proxy"] || process3.env["HTTP_PROXY"] || process3.env["http_proxy"] || process3.env["ALL_PROXY"] || process3.env["all_proxy"],
9117
9174
  cwd,
9118
9175
  fileDiscoveryService: fileService,
9119
9176
  bugCommand: settings.advanced?.bugCommand,
9120
9177
  model: resolvedModel,
9121
9178
  maxSessionTurns: settings.model?.maxSessionTurns,
9179
+ requestTimeoutMs: settings.model?.requestTimeoutMs,
9122
9180
  listExtensions: argv.listExtensions || false,
9123
9181
  listSessions: argv.listSessions || false,
9124
9182
  deleteSession: argv.deleteSession,
@@ -9249,22 +9307,30 @@ async function resolveWorktreeSettings(cwd) {
9249
9307
  }
9250
9308
 
9251
9309
  // packages/cli/src/utils/readStdin.ts
9252
- function truncateUtf8Bytes(str, maxBytes) {
9253
- const buf = Buffer.from(str, "utf8");
9254
- if (buf.length <= maxBytes) return str;
9310
+ function truncateUtf8Buffer(buf, maxBytes) {
9311
+ if (maxBytes <= 0) return "";
9312
+ if (buf.length <= maxBytes) return buf.toString("utf8");
9255
9313
  let end = maxBytes;
9256
9314
  while (end > 0 && (buf[end] & 192) === 128) {
9257
9315
  end--;
9258
9316
  }
9259
9317
  return buf.subarray(0, end).toString("utf8");
9260
9318
  }
9319
+ function truncateUtf8Bytes(str, maxBytes) {
9320
+ if (maxBytes <= 0) return "";
9321
+ return truncateUtf8Buffer(Buffer.from(str, "utf8"), maxBytes);
9322
+ }
9261
9323
  async function readStdin() {
9324
+ if (process.stdin.isTTY || process.stdin.destroyed || process.stdin.readableEnded) {
9325
+ return "";
9326
+ }
9262
9327
  const MAX_STDIN_SIZE = 8 * 1024 * 1024;
9263
9328
  return new Promise((resolve10, reject) => {
9264
9329
  let data = "";
9265
9330
  let totalSize = 0;
9331
+ let settled = false;
9266
9332
  process.stdin.setEncoding("utf8");
9267
- const pipedInputShouldBeAvailableInMs = 500;
9333
+ const pipedInputShouldBeAvailableInMs = 1e3;
9268
9334
  let pipedInputTimerId = setTimeout(() => {
9269
9335
  onEnd();
9270
9336
  }, pipedInputShouldBeAvailableInMs);
@@ -9275,26 +9341,46 @@ async function readStdin() {
9275
9341
  clearTimeout(pipedInputTimerId);
9276
9342
  pipedInputTimerId = null;
9277
9343
  }
9278
- const chunkByteLength = Buffer.byteLength(chunk, "utf8");
9344
+ let chunkByteLength;
9345
+ let chunkBuffer;
9346
+ let chunkStr = "";
9347
+ if (Buffer.isBuffer(chunk)) {
9348
+ chunkBuffer = chunk;
9349
+ chunkByteLength = chunk.length;
9350
+ } else {
9351
+ chunkStr = typeof chunk === "string" ? chunk : String(chunk);
9352
+ chunkByteLength = Buffer.byteLength(chunkStr, "utf8");
9353
+ }
9279
9354
  if (totalSize + chunkByteLength > MAX_STDIN_SIZE) {
9280
9355
  const remainingBytes = MAX_STDIN_SIZE - totalSize;
9281
- data += truncateUtf8Bytes(chunk, remainingBytes);
9356
+ data += chunkBuffer ? truncateUtf8Buffer(chunkBuffer, remainingBytes) : truncateUtf8Bytes(chunkStr, remainingBytes);
9282
9357
  debugLogger.warn(
9283
9358
  `Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`
9284
9359
  );
9285
- process.stdin.destroy();
9286
- onEnd();
9360
+ cleanup();
9361
+ if (typeof process.stdin.unpipe === "function") {
9362
+ process.stdin.unpipe();
9363
+ }
9364
+ if (typeof process.stdin.pause === "function") {
9365
+ process.stdin.pause();
9366
+ }
9367
+ settled = true;
9368
+ resolve10(data);
9287
9369
  break;
9288
9370
  }
9289
- data += chunk;
9371
+ data += chunkBuffer ? chunkBuffer.toString("utf8") : chunkStr;
9290
9372
  totalSize += chunkByteLength;
9291
9373
  }
9292
9374
  };
9293
9375
  const onEnd = () => {
9376
+ if (settled) return;
9377
+ settled = true;
9294
9378
  cleanup();
9295
9379
  resolve10(data);
9296
9380
  };
9297
9381
  const onError = (err) => {
9382
+ if (settled) return;
9383
+ settled = true;
9298
9384
  cleanup();
9299
9385
  reject(err);
9300
9386
  };
@@ -9323,7 +9409,7 @@ import { createHash as createHash2 } from "node:crypto";
9323
9409
  import v8 from "node:v8";
9324
9410
  import os6 from "node:os";
9325
9411
  import dns from "node:dns";
9326
- import * as path17 from "node:path";
9412
+ import * as path18 from "node:path";
9327
9413
  import * as fsPromises from "node:fs/promises";
9328
9414
 
9329
9415
  // packages/cli/src/utils/sandbox.ts
@@ -9662,6 +9748,9 @@ var BUILTIN_SEATBELT_PROFILE_CONTENTS = {
9662
9748
  (global-name "com.apple.SystemConfiguration.DNSConfiguration")
9663
9749
  (global-name "com.apple.SystemConfiguration.configd")
9664
9750
  )
9751
+ (allow mach-lookup
9752
+ (global-name "com.apple.FSEvents")
9753
+ )
9665
9754
  (allow system-socket
9666
9755
  (require-all
9667
9756
  (socket-domain AF_SYSTEM)
@@ -9828,6 +9917,9 @@ var BUILTIN_SEATBELT_PROFILE_CONTENTS = {
9828
9917
  (global-name "com.apple.SystemConfiguration.DNSConfiguration")
9829
9918
  (global-name "com.apple.SystemConfiguration.configd")
9830
9919
  )
9920
+ (allow mach-lookup
9921
+ (global-name "com.apple.FSEvents")
9922
+ )
9831
9923
  (allow system-socket
9832
9924
  (require-all
9833
9925
  (socket-domain AF_SYSTEM)
@@ -9916,6 +10008,7 @@ var BUILTIN_SEATBELT_PROFILE_CONTENTS = {
9916
10008
  (allow file-read*
9917
10009
  (literal (string-append (param "HOME_DIR") "/.gemini/settings.json"))
9918
10010
  (literal (string-append (param "HOME_DIR") "/.gemini/keybindings.json"))
10011
+ (literal (string-append (param "HOME_DIR") "/.gemini/theme.json"))
9919
10012
  )
9920
10013
  (allow process-exec)
9921
10014
  (allow process-fork)
@@ -10063,6 +10156,7 @@ var BUILTIN_SEATBELT_PROFILE_CONTENTS = {
10063
10156
  (allow file-read*
10064
10157
  (literal (string-append (param "HOME_DIR") "/.gemini/settings.json"))
10065
10158
  (literal (string-append (param "HOME_DIR") "/.gemini/keybindings.json"))
10159
+ (literal (string-append (param "HOME_DIR") "/.gemini/theme.json"))
10066
10160
  )
10067
10161
  (allow process-exec)
10068
10162
  (allow process-fork)
@@ -10213,6 +10307,7 @@ var BUILTIN_SEATBELT_PROFILE_CONTENTS = {
10213
10307
  (subpath (param "CACHE_DIR"))
10214
10308
  (literal (string-append (param "HOME_DIR") "/.gemini/settings.json"))
10215
10309
  (literal (string-append (param "HOME_DIR") "/.gemini/keybindings.json"))
10310
+ (literal (string-append (param "HOME_DIR") "/.gemini/theme.json"))
10216
10311
  (subpath (string-append (param "HOME_DIR") "/.npm"))
10217
10312
  (subpath (string-append (param "HOME_DIR") "/.cache"))
10218
10313
  (literal (string-append (param "HOME_DIR") "/.gitconfig"))
@@ -10386,6 +10481,7 @@ var BUILTIN_SEATBELT_PROFILE_CONTENTS = {
10386
10481
  (subpath (param "CACHE_DIR"))
10387
10482
  (literal (string-append (param "HOME_DIR") "/.gemini/settings.json"))
10388
10483
  (literal (string-append (param "HOME_DIR") "/.gemini/keybindings.json"))
10484
+ (literal (string-append (param "HOME_DIR") "/.gemini/theme.json"))
10389
10485
  (subpath (string-append (param "HOME_DIR") "/.npm"))
10390
10486
  (subpath (string-append (param "HOME_DIR") "/.cache"))
10391
10487
  (literal (string-append (param "HOME_DIR") "/.gitconfig"))
@@ -12587,6 +12683,159 @@ async function ensureSandboxImageIsPresent(sandbox, image, cliConfig) {
12587
12683
  return false;
12588
12684
  }
12589
12685
 
12686
+ // packages/cli/src/utils/sandboxFolderTrust.ts
12687
+ import * as path11 from "node:path";
12688
+ import * as readline2 from "node:readline";
12689
+ import { Writable } from "node:stream";
12690
+ var TRUST_WORKSPACE_ENV = "GEMINI_CLI_TRUST_WORKSPACE";
12691
+ function parseTrustChoice(answer) {
12692
+ switch (answer.trim()) {
12693
+ case "1":
12694
+ return TrustLevel.TRUST_FOLDER;
12695
+ case "2":
12696
+ return TrustLevel.TRUST_PARENT;
12697
+ case "3":
12698
+ return TrustLevel.DO_NOT_TRUST;
12699
+ default:
12700
+ return void 0;
12701
+ }
12702
+ }
12703
+ async function resolveFolderTrustForSandbox({
12704
+ sandboxCommand,
12705
+ settings,
12706
+ interactive,
12707
+ workspaceDir = process.cwd(),
12708
+ promptForTrustLevel = promptForFolderTrustLevel
12709
+ }) {
12710
+ if (sandboxCommand !== "sandbox-exec") {
12711
+ return;
12712
+ }
12713
+ if (!isFolderTrustEnabled(settings.merged)) {
12714
+ return;
12715
+ }
12716
+ const trust = isWorkspaceTrusted(settings.merged, workspaceDir);
12717
+ if (trust.source === "env") {
12718
+ return;
12719
+ }
12720
+ let isTrusted = trust.isTrusted;
12721
+ if (isTrusted === void 0) {
12722
+ if (!interactive) {
12723
+ return;
12724
+ }
12725
+ const trustLevel = await promptForTrustLevel(workspaceDir);
12726
+ if (trustLevel === void 0) {
12727
+ throw new FatalCancellationError(
12728
+ "A folder trust level must be selected to continue."
12729
+ );
12730
+ }
12731
+ try {
12732
+ await loadTrustedFolders().setValue(workspaceDir, trustLevel);
12733
+ } catch {
12734
+ throw new FatalConfigError("Failed to save trust settings.");
12735
+ }
12736
+ isTrusted = trustLevel !== TrustLevel.DO_NOT_TRUST;
12737
+ }
12738
+ process.env[TRUST_WORKSPACE_ENV] = isTrusted ? "true" : "false";
12739
+ }
12740
+ function formatFolderTrustPrompt(workspaceDir, discoveryResults) {
12741
+ const folderName = stripAnsi(path11.basename(workspaceDir)).trim() || stripAnsi(workspaceDir);
12742
+ const parentDir = path11.dirname(workspaceDir);
12743
+ const parentFolderName = stripAnsi(path11.basename(parentDir)).trim() || stripAnsi(parentDir);
12744
+ const lines = [
12745
+ "",
12746
+ "Do you trust the files in this folder?",
12747
+ "",
12748
+ "Trusting a folder allows Gemini CLI to load its local configurations, including custom commands, hooks, MCP servers, agent skills, and settings. These configurations could execute code on your behalf or change the behavior of the CLI.",
12749
+ ""
12750
+ ];
12751
+ const appendSection = (title, items) => {
12752
+ if (items.length === 0) {
12753
+ return;
12754
+ }
12755
+ lines.push(title);
12756
+ for (const item of items) {
12757
+ lines.push(` \u2022 ${stripAnsi(item)}`);
12758
+ }
12759
+ lines.push("");
12760
+ };
12761
+ if (discoveryResults) {
12762
+ appendSection("Discovery Errors:", discoveryResults.discoveryErrors ?? []);
12763
+ appendSection(
12764
+ "Security Warnings:",
12765
+ discoveryResults.securityWarnings ?? []
12766
+ );
12767
+ const groups = [
12768
+ ["Commands", discoveryResults.commands ?? []],
12769
+ ["MCP Servers", discoveryResults.mcps ?? []],
12770
+ ["Hooks", discoveryResults.hooks ?? []],
12771
+ ["Skills", discoveryResults.skills ?? []],
12772
+ ["Agents", discoveryResults.agents ?? []],
12773
+ ["Setting overrides", discoveryResults.settings ?? []]
12774
+ ];
12775
+ const nonEmptyGroups = groups.filter(([, items]) => items.length > 0);
12776
+ if (nonEmptyGroups.length > 0) {
12777
+ lines.push("This folder contains:");
12778
+ for (const [label, items] of nonEmptyGroups) {
12779
+ lines.push(` \u2022 ${label} (${items.length}):`);
12780
+ for (const item of items) {
12781
+ lines.push(` - ${stripAnsi(item)}`);
12782
+ }
12783
+ }
12784
+ lines.push("");
12785
+ }
12786
+ }
12787
+ lines.push(
12788
+ ` 1. Trust folder (${folderName})`,
12789
+ ` 2. Trust parent folder (${parentFolderName})`,
12790
+ " 3. Don't trust",
12791
+ "",
12792
+ "This choice is saved before Gemini CLI starts in the macOS Seatbelt sandbox.",
12793
+ ""
12794
+ );
12795
+ return lines.join("\n");
12796
+ }
12797
+ function createTerminalOutput() {
12798
+ return new Writable({
12799
+ decodeStrings: false,
12800
+ write(chunk, _encoding, callback) {
12801
+ writeToStdout(chunk);
12802
+ callback();
12803
+ }
12804
+ });
12805
+ }
12806
+ async function promptForFolderTrustLevel(workspaceDir, input = process.stdin, output = createTerminalOutput()) {
12807
+ let discoveryResults;
12808
+ try {
12809
+ discoveryResults = await FolderTrustDiscoveryService.discover(workspaceDir);
12810
+ } catch {
12811
+ }
12812
+ output.write(formatFolderTrustPrompt(workspaceDir, discoveryResults));
12813
+ return new Promise((resolve10) => {
12814
+ const rl = readline2.createInterface({ input, output, terminal: false });
12815
+ let settled = false;
12816
+ const finish = (trustLevel) => {
12817
+ if (settled) {
12818
+ return;
12819
+ }
12820
+ settled = true;
12821
+ rl.close();
12822
+ resolve10(trustLevel);
12823
+ };
12824
+ rl.on("line", (line) => {
12825
+ const trustLevel = parseTrustChoice(line);
12826
+ if (trustLevel) {
12827
+ finish(trustLevel);
12828
+ return;
12829
+ }
12830
+ output.write("Enter 1, 2, or 3.\n");
12831
+ rl.prompt();
12832
+ });
12833
+ rl.on("close", () => finish(void 0));
12834
+ rl.setPrompt("Select an option [1-3]: ");
12835
+ rl.prompt();
12836
+ });
12837
+ }
12838
+
12590
12839
  // packages/cli/src/utils/startupWarnings.ts
12591
12840
  import fs8 from "node:fs/promises";
12592
12841
  import os4 from "node:os";
@@ -12614,7 +12863,7 @@ async function getStartupWarnings() {
12614
12863
  // packages/cli/src/utils/userStartupWarnings.ts
12615
12864
  import fs9 from "node:fs/promises";
12616
12865
  import { homedir as osHomedir } from "node:os";
12617
- import path11 from "node:path";
12866
+ import path12 from "node:path";
12618
12867
  import process5 from "node:process";
12619
12868
  var homeDirectoryCheck = {
12620
12869
  id: "home-directory",
@@ -12628,7 +12877,7 @@ var homeDirectoryCheck = {
12628
12877
  fs9.realpath(workspaceRoot),
12629
12878
  fs9.realpath(osHomedir())
12630
12879
  ]);
12631
- if (path11.resolve(workspaceRealPath) === path11.resolve(homeRealPath)) {
12880
+ if (path12.resolve(workspaceRealPath) === path12.resolve(homeRealPath)) {
12632
12881
  if (isFolderTrustEnabled(settings) && isWorkspaceTrusted(settings).isTrusted) {
12633
12882
  return null;
12634
12883
  }
@@ -12647,7 +12896,7 @@ var rootDirectoryCheck = {
12647
12896
  try {
12648
12897
  const workspaceRealPath = await fs9.realpath(workspaceRoot);
12649
12898
  const errorMessage = "Warning: You are running Gemini CLI in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.";
12650
- if (path11.dirname(workspaceRealPath) === workspaceRealPath) {
12899
+ if (path12.dirname(workspaceRealPath) === workspaceRealPath) {
12651
12900
  return errorMessage;
12652
12901
  }
12653
12902
  return null;
@@ -12706,7 +12955,7 @@ async function getUserStartupWarnings(settings, workspaceRoot = process5.cwd(),
12706
12955
  }
12707
12956
 
12708
12957
  // packages/cli/src/nonInteractiveCli.ts
12709
- import readline3 from "node:readline";
12958
+ import readline4 from "node:readline";
12710
12959
 
12711
12960
  // packages/cli/src/ui/noninteractive/nonInteractiveUi.ts
12712
12961
  function createNonInteractiveUI() {
@@ -12913,8 +13162,11 @@ function handleToolError(toolName, toolError, config, errorType, resultDisplay)
12913
13162
  }
12914
13163
  debugLogger.warn(errorMessage);
12915
13164
  }
12916
- function handleCancellationError(config) {
12917
- const cancellationError = new FatalCancellationError("Operation cancelled.");
13165
+ function handleCancellationError(config, exitCode = 130) {
13166
+ const cancellationError = new FatalCancellationError(
13167
+ "Operation cancelled.",
13168
+ exitCode
13169
+ );
12918
13170
  if (config.getOutputFormat() === OutputFormat.STREAM_JSON) {
12919
13171
  const streamFormatter = new StreamJsonFormatter();
12920
13172
  const metrics = uiTelemetryService.getMetrics();
@@ -13030,7 +13282,7 @@ var TextOutput = class {
13030
13282
  };
13031
13283
 
13032
13284
  // packages/cli/src/nonInteractiveCliAgentSession.ts
13033
- import readline2 from "node:readline";
13285
+ import readline3 from "node:readline";
13034
13286
  async function runNonInteractive({
13035
13287
  config,
13036
13288
  settings,
@@ -13048,7 +13300,7 @@ async function runNonInteractive({
13048
13300
  }
13049
13301
  });
13050
13302
  if (process.env["GEMINI_CLI_ACTIVITY_LOG_TARGET"]) {
13051
- const { setupInitialActivityLogger } = await import("./devtoolsService-V3OEHE5V.js");
13303
+ const { setupInitialActivityLogger } = await import("./devtoolsService-I7WFRUEA.js");
13052
13304
  setupInitialActivityLogger(config);
13053
13305
  }
13054
13306
  const { stdout: workingStdout } = createWorkingStdio();
@@ -13079,9 +13331,17 @@ async function runNonInteractive({
13079
13331
  }
13080
13332
  throw err;
13081
13333
  };
13082
- const triggerAbort = () => {
13334
+ let abortExitCode = 130;
13335
+ const triggerAbort = (signal) => {
13336
+ if (signal === "SIGTERM") {
13337
+ abortExitCode = 143;
13338
+ } else if (signal === "SIGHUP") {
13339
+ abortExitCode = 129;
13340
+ } else {
13341
+ abortExitCode = 130;
13342
+ }
13083
13343
  if (isAborting) {
13084
- process.exit(130);
13344
+ process.exit(abortExitCode);
13085
13345
  }
13086
13346
  isAborting = true;
13087
13347
  cancelMessageTimer = setTimeout(() => {
@@ -13089,30 +13349,35 @@ async function runNonInteractive({
13089
13349
  }, 200);
13090
13350
  abortController.abort();
13091
13351
  };
13352
+ const onSigint = () => triggerAbort("SIGINT");
13353
+ const onSigterm = () => triggerAbort("SIGTERM");
13354
+ const onSighup = () => triggerAbort("SIGHUP");
13092
13355
  const setupCancellation = () => {
13093
- process.on("SIGINT", triggerAbort);
13094
- process.on("SIGTERM", triggerAbort);
13356
+ process.on("SIGINT", onSigint);
13357
+ process.on("SIGTERM", onSigterm);
13358
+ process.on("SIGHUP", onSighup);
13095
13359
  if (!process.stdin?.isTTY) {
13096
13360
  return;
13097
13361
  }
13098
13362
  stdinWasRaw = process.stdin.isRaw || false;
13099
13363
  process.stdin.setRawMode(true);
13100
13364
  process.stdin.resume();
13101
- rl = readline2.createInterface({
13365
+ rl = readline3.createInterface({
13102
13366
  input: process.stdin,
13103
13367
  escapeCodeTimeout: 0
13104
13368
  });
13105
- readline2.emitKeypressEvents(process.stdin, rl);
13369
+ readline3.emitKeypressEvents(process.stdin, rl);
13106
13370
  keypressHandler = (str, key) => {
13107
13371
  if (key && key.ctrl && key.name === "c" || str === "") {
13108
- triggerAbort();
13372
+ triggerAbort("SIGINT");
13109
13373
  }
13110
13374
  };
13111
13375
  process.stdin.on("keypress", keypressHandler);
13112
13376
  };
13113
13377
  const cleanupCancellation = () => {
13114
- process.off("SIGINT", triggerAbort);
13115
- process.off("SIGTERM", triggerAbort);
13378
+ process.off("SIGINT", onSigint);
13379
+ process.off("SIGTERM", onSigterm);
13380
+ process.off("SIGHUP", onSighup);
13116
13381
  process.stdout.off("error", handleStdoutError);
13117
13382
  if (cancelMessageTimer) {
13118
13383
  clearTimeout(cancelMessageTimer);
@@ -13218,7 +13483,7 @@ async function runNonInteractive({
13218
13483
  };
13219
13484
  abortController.signal.addEventListener("abort", abortSession);
13220
13485
  if (abortController.signal.aborted) {
13221
- throw new FatalCancellationError("Operation cancelled.");
13486
+ throw new FatalCancellationError("Operation cancelled.", abortExitCode);
13222
13487
  }
13223
13488
  const { streamId } = await session.send({
13224
13489
  message: {
@@ -13264,64 +13529,63 @@ async function runNonInteractive({
13264
13529
  const reconstructFatalError = (event) => {
13265
13530
  const errorMeta = event._meta;
13266
13531
  const name = typeof errorMeta?.["errorName"] === "string" ? errorMeta["errorName"] : void 0;
13532
+ const rawError = errorMeta?.["rawError"];
13533
+ const normalized = normalizeError(
13534
+ rawError ?? {
13535
+ message: event.message,
13536
+ status: errorMeta?.["status"],
13537
+ code: errorMeta?.["code"]
13538
+ }
13539
+ );
13540
+ const code = normalized.code ?? (typeof normalized.status === "string" ? normalized.status : void 0);
13267
13541
  let errToThrow;
13268
13542
  switch (name) {
13269
13543
  case "FatalAuthenticationError":
13270
- errToThrow = new FatalAuthenticationError(event.message);
13544
+ errToThrow = new FatalAuthenticationError(normalized.message);
13271
13545
  break;
13272
13546
  case "FatalInputError":
13273
- errToThrow = new FatalInputError(event.message);
13547
+ errToThrow = new FatalInputError(normalized.message);
13274
13548
  break;
13275
13549
  case "FatalSandboxError":
13276
- errToThrow = new FatalSandboxError(event.message);
13550
+ errToThrow = new FatalSandboxError(normalized.message);
13277
13551
  break;
13278
13552
  case "FatalConfigError":
13279
- errToThrow = new FatalConfigError(event.message);
13553
+ errToThrow = new FatalConfigError(normalized.message);
13280
13554
  break;
13281
13555
  case "FatalTurnLimitedError":
13282
- errToThrow = new FatalTurnLimitedError(event.message);
13556
+ errToThrow = new FatalTurnLimitedError(normalized.message);
13283
13557
  break;
13284
13558
  case "FatalToolExecutionError":
13285
- errToThrow = new FatalToolExecutionError(event.message);
13559
+ errToThrow = new FatalToolExecutionError(normalized.message);
13286
13560
  break;
13287
13561
  case "FatalCancellationError":
13288
- errToThrow = new FatalCancellationError(event.message);
13562
+ errToThrow = new FatalCancellationError(
13563
+ normalized.message,
13564
+ abortExitCode
13565
+ );
13289
13566
  break;
13290
13567
  case "FatalError":
13291
13568
  errToThrow = new FatalError(
13292
- event.message,
13569
+ normalized.message,
13293
13570
  typeof errorMeta?.["exitCode"] === "number" ? errorMeta["exitCode"] : 1
13294
13571
  );
13295
13572
  break;
13296
13573
  default:
13297
- errToThrow = new Error(event.message);
13298
- if (name) {
13299
- Object.defineProperty(errToThrow, "name", {
13300
- value: name,
13301
- enumerable: true
13302
- });
13303
- }
13574
+ errToThrow = Object.assign(
13575
+ new Error(
13576
+ normalized.message,
13577
+ rawError !== void 0 ? { cause: rawError } : void 0
13578
+ ),
13579
+ name ? { name } : {}
13580
+ );
13304
13581
  break;
13305
13582
  }
13306
- if (errorMeta?.["exitCode"] !== void 0) {
13307
- Object.defineProperty(errToThrow, "exitCode", {
13308
- value: errorMeta["exitCode"],
13309
- enumerable: true
13310
- });
13311
- }
13312
- if (errorMeta?.["code"] !== void 0) {
13313
- Object.defineProperty(errToThrow, "code", {
13314
- value: errorMeta["code"],
13315
- enumerable: true
13316
- });
13317
- }
13318
- if (errorMeta?.["status"] !== void 0) {
13319
- Object.defineProperty(errToThrow, "status", {
13320
- value: errorMeta["status"],
13321
- enumerable: true
13322
- });
13323
- }
13324
- return errToThrow;
13583
+ return Object.assign(errToThrow, {
13584
+ ...errorMeta?.["exitCode"] !== void 0 ? { exitCode: errorMeta["exitCode"] } : {},
13585
+ ...typeof normalized.status === "number" ? { status: normalized.status } : {},
13586
+ ...code !== void 0 ? { code } : {},
13587
+ ...normalized.details !== void 0 ? { details: normalized.details } : {}
13588
+ });
13325
13589
  };
13326
13590
  let responseText = "";
13327
13591
  let preToolResponseText;
@@ -13548,7 +13812,8 @@ async function runNonInteractive({
13548
13812
  await runExitCleanup();
13549
13813
  }
13550
13814
  if (abortController.signal.aborted || isFatalCancellationError(errorToHandle)) {
13551
- handleCancellationError(config);
13815
+ const exitCode = isFatalCancellationError(errorToHandle) ? errorToHandle.exitCode : abortExitCode;
13816
+ handleCancellationError(config, exitCode);
13552
13817
  }
13553
13818
  if (errorToHandle) {
13554
13819
  handleError(errorToHandle, config);
@@ -13576,7 +13841,7 @@ async function runNonInteractive2(params) {
13576
13841
  }
13577
13842
  });
13578
13843
  if (process.env["GEMINI_CLI_ACTIVITY_LOG_TARGET"]) {
13579
- const { setupInitialActivityLogger } = await import("./devtoolsService-V3OEHE5V.js");
13844
+ const { setupInitialActivityLogger } = await import("./devtoolsService-I7WFRUEA.js");
13580
13845
  setupInitialActivityLogger(config);
13581
13846
  }
13582
13847
  const { stdout: workingStdout } = createWorkingStdio();
@@ -13607,9 +13872,17 @@ async function runNonInteractive2(params) {
13607
13872
  }
13608
13873
  throw err;
13609
13874
  };
13610
- const triggerAbort = () => {
13875
+ let abortExitCode = 130;
13876
+ const triggerAbort = (signal) => {
13877
+ if (signal === "SIGTERM") {
13878
+ abortExitCode = 143;
13879
+ } else if (signal === "SIGHUP") {
13880
+ abortExitCode = 129;
13881
+ } else {
13882
+ abortExitCode = 130;
13883
+ }
13611
13884
  if (isAborting) {
13612
- process.exit(130);
13885
+ process.exit(abortExitCode);
13613
13886
  }
13614
13887
  isAborting = true;
13615
13888
  cancelMessageTimer = setTimeout(() => {
@@ -13617,30 +13890,35 @@ async function runNonInteractive2(params) {
13617
13890
  }, 200);
13618
13891
  abortController.abort();
13619
13892
  };
13893
+ const handleSigInt = () => triggerAbort("SIGINT");
13894
+ const handleSigTerm = () => triggerAbort("SIGTERM");
13895
+ const handleSigHup = () => triggerAbort("SIGHUP");
13620
13896
  const setupCancellation = () => {
13621
- process.on("SIGINT", triggerAbort);
13622
- process.on("SIGTERM", triggerAbort);
13897
+ process.on("SIGINT", handleSigInt);
13898
+ process.on("SIGTERM", handleSigTerm);
13899
+ process.on("SIGHUP", handleSigHup);
13623
13900
  if (!process.stdin?.isTTY) {
13624
13901
  return;
13625
13902
  }
13626
13903
  stdinWasRaw = process.stdin.isRaw || false;
13627
13904
  process.stdin.setRawMode(true);
13628
13905
  process.stdin.resume();
13629
- rl = readline3.createInterface({
13906
+ rl = readline4.createInterface({
13630
13907
  input: process.stdin,
13631
13908
  escapeCodeTimeout: 0
13632
13909
  });
13633
- readline3.emitKeypressEvents(process.stdin, rl);
13910
+ readline4.emitKeypressEvents(process.stdin, rl);
13634
13911
  keypressHandler = (str, key) => {
13635
13912
  if (key && key.ctrl && key.name === "c" || str === "") {
13636
- triggerAbort();
13913
+ triggerAbort("SIGINT");
13637
13914
  }
13638
13915
  };
13639
13916
  process.stdin.on("keypress", keypressHandler);
13640
13917
  };
13641
13918
  const cleanupCancellation = () => {
13642
- process.off("SIGINT", triggerAbort);
13643
- process.off("SIGTERM", triggerAbort);
13919
+ process.off("SIGINT", handleSigInt);
13920
+ process.off("SIGTERM", handleSigTerm);
13921
+ process.off("SIGHUP", handleSigHup);
13644
13922
  process.stdout.off("error", handleStdoutError);
13645
13923
  if (cancelMessageTimer) {
13646
13924
  clearTimeout(cancelMessageTimer);
@@ -13753,7 +14031,7 @@ async function runNonInteractive2(params) {
13753
14031
  let responseText = "";
13754
14032
  for await (const event of responseStream) {
13755
14033
  if (abortController.signal.aborted) {
13756
- handleCancellationError(config);
14034
+ handleCancellationError(config, abortExitCode);
13757
14035
  }
13758
14036
  if (event.type === GeminiEventType.Content) {
13759
14037
  const isRaw = config.getRawOutput() || config.getAcceptRawOutputRisk();
@@ -13807,7 +14085,20 @@ async function runNonInteractive2(params) {
13807
14085
  }
13808
14086
  warnings.push(message);
13809
14087
  } else if (event.type === GeminiEventType.Error) {
13810
- throw event.value.error;
14088
+ const normalized = normalizeError(event.value?.error);
14089
+ const code = normalized.code ?? (typeof normalized.status === "string" ? normalized.status : void 0);
14090
+ const err = Object.assign(
14091
+ new Error(
14092
+ normalized.message,
14093
+ normalized.originalError !== void 0 ? { cause: normalized.originalError } : void 0
14094
+ ),
14095
+ {
14096
+ ...typeof normalized.status === "number" ? { status: normalized.status } : {},
14097
+ ...code !== void 0 ? { code } : {},
14098
+ ...normalized.details !== void 0 ? { details: normalized.details } : {}
14099
+ }
14100
+ );
14101
+ throw err;
13811
14102
  } else if (event.type === GeminiEventType.AgentExecutionStopped) {
13812
14103
  const stopMessage = `Agent execution stopped: ${event.value.systemMessage?.trim() || event.value.reason}`;
13813
14104
  if (config.getOutputFormat() === OutputFormat.TEXT) {
@@ -13896,13 +14187,27 @@ async function runNonInteractive2(params) {
13896
14187
  }
13897
14188
  if (toolCallRequests.length > 0) {
13898
14189
  if (abortController.signal.aborted) {
13899
- throw new FatalCancellationError("Operation cancelled.");
14190
+ throw new FatalCancellationError(
14191
+ "Operation cancelled.",
14192
+ abortExitCode
14193
+ );
13900
14194
  }
13901
14195
  textOutput.ensureTrailingNewline();
13902
- const completedToolCalls = await scheduler.schedule(
13903
- toolCallRequests,
13904
- abortController.signal
13905
- );
14196
+ let completedToolCalls;
14197
+ try {
14198
+ completedToolCalls = await scheduler.schedule(
14199
+ toolCallRequests,
14200
+ abortController.signal
14201
+ );
14202
+ } catch (scheduleError) {
14203
+ if (abortController.signal.aborted) {
14204
+ throw new FatalCancellationError(
14205
+ "Operation cancelled.",
14206
+ abortExitCode
14207
+ );
14208
+ }
14209
+ throw scheduleError;
14210
+ }
13906
14211
  const toolResponseParts = [];
13907
14212
  for (const completedToolCall of completedToolCalls) {
13908
14213
  const toolResponse = completedToolCall.response;
@@ -13980,6 +14285,12 @@ async function runNonInteractive2(params) {
13980
14285
  }
13981
14286
  return;
13982
14287
  }
14288
+ if (abortController.signal.aborted) {
14289
+ throw new FatalCancellationError(
14290
+ "Operation cancelled.",
14291
+ abortExitCode
14292
+ );
14293
+ }
13983
14294
  currentMessages = [{ role: "user", parts: toolResponseParts }];
13984
14295
  } else {
13985
14296
  if (streamFormatter) {
@@ -14019,7 +14330,8 @@ async function runNonInteractive2(params) {
14019
14330
  await runExitCleanup();
14020
14331
  }
14021
14332
  if (abortController.signal.aborted || isFatalCancellationError(errorToHandle)) {
14022
- handleCancellationError(config);
14333
+ const exitCode = isFatalCancellationError(errorToHandle) ? errorToHandle.exitCode : abortExitCode;
14334
+ handleCancellationError(config, exitCode);
14023
14335
  }
14024
14336
  if (errorToHandle) {
14025
14337
  handleError(errorToHandle, config);
@@ -15565,7 +15877,7 @@ var RequestError = class _RequestError extends Error {
15565
15877
  };
15566
15878
 
15567
15879
  // packages/cli/src/acp/acpStdioTransport.ts
15568
- import { Readable, Writable } from "node:stream";
15880
+ import { Readable, Writable as Writable2 } from "node:stream";
15569
15881
 
15570
15882
  // packages/cli/src/acp/acpErrors.ts
15571
15883
  function getAcpErrorMessage(error) {
@@ -15592,7 +15904,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
15592
15904
 
15593
15905
  // packages/cli/src/acp/acpSession.ts
15594
15906
  import * as fs12 from "node:fs/promises";
15595
- import * as path14 from "node:path";
15907
+ import * as path15 from "node:path";
15596
15908
  import { randomUUID } from "node:crypto";
15597
15909
 
15598
15910
  // packages/cli/src/acp/commands/commandRegistry.ts
@@ -16034,7 +16346,7 @@ var UpdateExtensionCommand = class {
16034
16346
 
16035
16347
  // packages/cli/src/acp/commands/init.ts
16036
16348
  import * as fs10 from "node:fs";
16037
- import * as path12 from "node:path";
16349
+ import * as path13 from "node:path";
16038
16350
  var InitCommand = class {
16039
16351
  name = "init";
16040
16352
  description = "Analyzes the project and creates a tailored GEMINI.md file";
@@ -16044,7 +16356,7 @@ var InitCommand = class {
16044
16356
  if (!targetDir) {
16045
16357
  throw new Error("Command requires a workspace.");
16046
16358
  }
16047
- const geminiMdPath = path12.join(targetDir, "GEMINI.md");
16359
+ const geminiMdPath = path13.join(targetDir, "GEMINI.md");
16048
16360
  const result = performInit(fs10.existsSync(geminiMdPath));
16049
16361
  switch (result.type) {
16050
16362
  case "message":
@@ -16077,7 +16389,7 @@ ${result.content}`
16077
16389
 
16078
16390
  // packages/cli/src/acp/commands/restore.ts
16079
16391
  import * as fs11 from "node:fs/promises";
16080
- import * as path13 from "node:path";
16392
+ import * as path14 from "node:path";
16081
16393
  var RestoreCommand = class {
16082
16394
  name = "restore";
16083
16395
  description = "Restore to a previous checkpoint, or list available checkpoints to restore. This will reset the conversation and file history to the state it was in when the checkpoint was created";
@@ -16099,7 +16411,7 @@ var RestoreCommand = class {
16099
16411
  }
16100
16412
  const selectedFile = argsStr.endsWith(".json") ? argsStr : `${argsStr}.json`;
16101
16413
  const checkpointDir = config.storage.getProjectTempCheckpointsDir();
16102
- const filePath = path13.join(checkpointDir, selectedFile);
16414
+ const filePath = path14.join(checkpointDir, selectedFile);
16103
16415
  let data;
16104
16416
  try {
16105
16417
  data = await fs11.readFile(filePath, "utf-8");
@@ -16173,7 +16485,7 @@ var ListCheckpointsCommand = class {
16173
16485
  }
16174
16486
  const checkpointFiles = /* @__PURE__ */ new Map();
16175
16487
  for (const file of jsonFiles) {
16176
- const filePath = path13.join(checkpointDir, file);
16488
+ const filePath = path14.join(checkpointDir, file);
16177
16489
  const data = await fs11.readFile(filePath, "utf-8");
16178
16490
  checkpointFiles.set(file, data);
16179
16491
  }
@@ -16383,6 +16695,7 @@ var Session = class {
16383
16695
  CoreEvent.ApprovalModeChanged,
16384
16696
  this.handleApprovalModeChanged
16385
16697
  );
16698
+ coreEvents.on(CoreEvent.RetryAttempt, this.handleRetryAttempt);
16386
16699
  this.context.config.getMessageBus()?.subscribe(
16387
16700
  MessageBusType.TOOL_CONFIRMATION_REQUEST,
16388
16701
  this.handleToolConfirmationRequest,
@@ -16476,11 +16789,26 @@ var Session = class {
16476
16789
  });
16477
16790
  }
16478
16791
  };
16792
+ handleRetryAttempt = (payload) => {
16793
+ if (payload.sessionId === this.id) {
16794
+ const delaySec = Math.max(1, Math.round(payload.delayMs / 1e3));
16795
+ this.sendUpdate({
16796
+ sessionUpdate: "agent_thought_chunk",
16797
+ content: {
16798
+ type: "text",
16799
+ text: `[Retry ${payload.attempt}/${payload.maxAttempts}] ${payload.error || "Request failed"}. Retrying in ${delaySec}s...`
16800
+ }
16801
+ }).catch((err) => {
16802
+ debugLogger.error(`Failed to send retry session update: ${err}`);
16803
+ });
16804
+ }
16805
+ };
16479
16806
  async dispose() {
16480
16807
  coreEvents.off(
16481
16808
  CoreEvent.ApprovalModeChanged,
16482
16809
  this.handleApprovalModeChanged
16483
16810
  );
16811
+ coreEvents.off(CoreEvent.RetryAttempt, this.handleRetryAttempt);
16484
16812
  this.disposeController.abort();
16485
16813
  if (this.context.config?.dispose) {
16486
16814
  try {
@@ -16657,6 +16985,7 @@ ${thought.description}`;
16657
16985
  let currentParts = parts;
16658
16986
  let turnCount = 0;
16659
16987
  const maxTurns = this.context.config.getMaxSessionTurns();
16988
+ let isFirstChunkAfterRetry = false;
16660
16989
  while (true) {
16661
16990
  turnCount++;
16662
16991
  if (maxTurns >= 0 && turnCount > maxTurns) {
@@ -16688,10 +17017,13 @@ ${thought.description}`;
16688
17017
  type: "text",
16689
17018
  text: event.value
16690
17019
  };
16691
- await this.sendUpdate({
17020
+ const update = {
16692
17021
  sessionUpdate: "agent_message_chunk",
16693
- content
16694
- });
17022
+ content,
17023
+ ...isFirstChunkAfterRetry ? { _meta: { retry: true, reset: true } } : {}
17024
+ };
17025
+ isFirstChunkAfterRetry = false;
17026
+ await this.sendUpdate(update);
16695
17027
  break;
16696
17028
  }
16697
17029
  case GeminiEventType.Thought: {
@@ -16703,6 +17035,22 @@ ${event.value.description}`;
16703
17035
  });
16704
17036
  break;
16705
17037
  }
17038
+ case GeminiEventType.Retry: {
17039
+ toolCallRequests.length = 0;
17040
+ debugLogger.warn(
17041
+ "Model stream interrupted mid-response; retrying prompt..."
17042
+ );
17043
+ await this.sendUpdate({
17044
+ sessionUpdate: "agent_thought_chunk",
17045
+ content: {
17046
+ type: "text",
17047
+ text: "_[Stream interrupted. Retrying response...]_"
17048
+ },
17049
+ _meta: { retry: true }
17050
+ });
17051
+ isFirstChunkAfterRetry = true;
17052
+ break;
17053
+ }
16706
17054
  case GeminiEventType.ToolCallRequest:
16707
17055
  toolCallRequests.push(event.value);
16708
17056
  break;
@@ -17174,7 +17522,7 @@ ${event.value.description}`;
17174
17522
  } else if (result.status === "invalid") {
17175
17523
  continue;
17176
17524
  } else {
17177
- absolutePath = path14.resolve(
17525
+ absolutePath = path15.resolve(
17178
17526
  this.context.config.getTargetDir(),
17179
17527
  pathName
17180
17528
  );
@@ -17248,7 +17596,7 @@ ${event.value.description}`;
17248
17596
  }
17249
17597
  try {
17250
17598
  if (!validationError) {
17251
- if ((path14.isAbsolute(pathName) || !isWithinRoot(
17599
+ if ((path15.isAbsolute(pathName) || !isWithinRoot(
17252
17600
  absolutePath,
17253
17601
  this.context.config.getTargetDir()
17254
17602
  )) && !readDirectly) {
@@ -17346,7 +17694,7 @@ ${contentToPush}`;
17346
17694
  const lines = globResult.llmContent.split("\n");
17347
17695
  if (lines.length > 1 && lines[1]) {
17348
17696
  const firstMatchAbsolute = lines[1].trim();
17349
- currentPathSpec = path14.relative(
17697
+ currentPathSpec = path15.relative(
17350
17698
  this.context.config.getTargetDir(),
17351
17699
  firstMatchAbsolute
17352
17700
  );
@@ -17471,13 +17819,15 @@ ${REFERENCE_CONTENT_START}`
17471
17819
  const match = fileContentRegex.exec(part);
17472
17820
  if (match) {
17473
17821
  const filePathSpecInContent = match[1];
17474
- const fileActualContent = match[2].trim();
17822
+ const fileActualContent = match[2];
17475
17823
  processedQueryParts.push({
17476
17824
  text: `
17477
17825
  Content from @${filePathSpecInContent}:
17478
17826
  `
17479
17827
  });
17480
- processedQueryParts.push({ text: fileActualContent });
17828
+ if (fileActualContent !== "") {
17829
+ processedQueryParts.push({ text: fileActualContent });
17830
+ }
17481
17831
  } else {
17482
17832
  processedQueryParts.push({ text: part });
17483
17833
  }
@@ -17567,7 +17917,7 @@ Content from @${contextPart.uri}:
17567
17917
 
17568
17918
  // packages/cli/src/acp/acpFileSystemService.ts
17569
17919
  import os5 from "node:os";
17570
- import path15 from "node:path";
17920
+ import path16 from "node:path";
17571
17921
  var AcpFileSystemService = class {
17572
17922
  constructor(connection, sessionId, capabilities, fallback, root) {
17573
17923
  this.connection = connection;
@@ -17576,7 +17926,7 @@ var AcpFileSystemService = class {
17576
17926
  this.fallback = fallback;
17577
17927
  this.root = root;
17578
17928
  }
17579
- geminiDir = path15.join(os5.homedir(), ".gemini");
17929
+ geminiDir = path16.join(os5.homedir(), ".gemini");
17580
17930
  shouldUseFallback(filePath) {
17581
17931
  return !isWithinRoot(filePath, this.root) || isWithinRoot(filePath, this.geminiDir);
17582
17932
  }
@@ -18131,7 +18481,7 @@ var GeminiAgent = class {
18131
18481
  // packages/cli/src/acp/acpStdioTransport.ts
18132
18482
  async function runAcpClient(config, settings, argv) {
18133
18483
  const { stdout: workingStdout } = createWorkingStdio();
18134
- const stdout = Writable.toWeb(workingStdout);
18484
+ const stdout = Writable2.toWeb(workingStdout);
18135
18485
  const stdin = Readable.toWeb(process.stdin);
18136
18486
  const stream = ndJsonStream(stdout, stdin);
18137
18487
  const connection = new AgentSideConnection(
@@ -18277,6 +18627,7 @@ async function setupTerminalAndTheme(config, settings) {
18277
18627
  terminalCapabilityManager.areAmbiguousCharactersWide()
18278
18628
  );
18279
18629
  }
18630
+ themeManager.loadUserThemes?.();
18280
18631
  themeManager.loadCustomThemes(settings.merged.ui.customThemes);
18281
18632
  if (settings.merged.ui.theme) {
18282
18633
  if (!themeManager.setActiveTheme(settings.merged.ui.theme)) {
@@ -18310,7 +18661,7 @@ async function setupTerminalAndTheme(config, settings) {
18310
18661
 
18311
18662
  // packages/cli/src/utils/logCleanup.ts
18312
18663
  import { promises as fs13 } from "node:fs";
18313
- import * as path16 from "node:path";
18664
+ import * as path17 from "node:path";
18314
18665
  var RETENTION_PERIOD_MS = 7 * 24 * 60 * 60 * 1e3;
18315
18666
  async function cleanupBackgroundLogs(debugMode = false) {
18316
18667
  try {
@@ -18325,7 +18676,7 @@ async function cleanupBackgroundLogs(debugMode = false) {
18325
18676
  let deletedCount = 0;
18326
18677
  for (const entry of entries) {
18327
18678
  if (entry.isFile() && entry.name.endsWith(".log")) {
18328
- const filePath = path16.join(logDir, entry.name);
18679
+ const filePath = path17.join(logDir, entry.name);
18329
18680
  try {
18330
18681
  const stats = await fs13.stat(filePath);
18331
18682
  if (now - stats.mtime.getTime() > RETENTION_PERIOD_MS) {
@@ -18670,8 +19021,8 @@ async function resolveSessionId(resumeArg, sessionIdArg, sessionFileArg) {
18670
19021
  sessionData.projectHash = getProjectHash(storage.getProjectRoot());
18671
19022
  sessionData.startTime = isoNow;
18672
19023
  sessionData.lastUpdated = isoNow;
18673
- const chatsDir = path17.join(storage.getProjectTempDir(), "chats");
18674
- const newSessionPath = path17.join(
19024
+ const chatsDir = path18.join(storage.getProjectTempDir(), "chats");
19025
+ const newSessionPath = path18.join(
18675
19026
  chatsDir,
18676
19027
  `session-${now}-${newSessionId.slice(0, 8)}.jsonl`
18677
19028
  );
@@ -18739,7 +19090,7 @@ async function resolveSessionId(resumeArg, sessionIdArg, sessionFileArg) {
18739
19090
  }
18740
19091
  }
18741
19092
  async function startInteractiveUI(config, settings, startupWarnings, workspaceRoot = process.cwd(), resumedSessionData, initializationResult) {
18742
- const { startInteractiveUI: doStartUI } = await import("./interactiveCli-F5RRE2VJ.js");
19093
+ const { startInteractiveUI: doStartUI } = await import("./interactiveCli-5HMWVTK2.js");
18743
19094
  await doStartUI(
18744
19095
  config,
18745
19096
  settings,
@@ -18858,6 +19209,7 @@ async function main() {
18858
19209
  });
18859
19210
  adminControlsListner.setConfig(partialConfig);
18860
19211
  let initialAuthFailed = false;
19212
+ let initialAuthError = void 0;
18861
19213
  if (!settings.merged.security.auth.useExternal && !argv.isCommand) {
18862
19214
  try {
18863
19215
  if (partialConfig.isInteractive() && settings.merged.security.auth.selectedType) {
@@ -18885,8 +19237,9 @@ async function main() {
18885
19237
  process.exit(ExitCodes.SUCCESS);
18886
19238
  }
18887
19239
  if (!(err instanceof ValidationRequiredError)) {
18888
- debugLogger.error("Error authenticating:", err);
19240
+ debugLogger.debug("Error authenticating:", err);
18889
19241
  initialAuthFailed = true;
19242
+ initialAuthError = err;
18890
19243
  }
18891
19244
  }
18892
19245
  }
@@ -18922,6 +19275,9 @@ async function main() {
18922
19275
  const sandboxConfig = await loadSandboxConfig(settings.merged, argv);
18923
19276
  if (sandboxConfig) {
18924
19277
  if (initialAuthFailed) {
19278
+ writeToStderr(
19279
+ formatCliError(initialAuthError, { debug: isDebugMode2 }) + "\n"
19280
+ );
18925
19281
  await runExitCleanup();
18926
19282
  process.exit(ExitCodes.FATAL_AUTHENTICATION_ERROR);
18927
19283
  }
@@ -18946,6 +19302,11 @@ ${finalArgs[promptIndex + 1]}`;
18946
19302
  return finalArgs;
18947
19303
  };
18948
19304
  const sandboxArgs = injectStdinIntoArgs(process.argv, stdinData);
19305
+ await resolveFolderTrustForSandbox({
19306
+ sandboxCommand: sandboxConfig.command,
19307
+ settings,
19308
+ interactive: partialConfig.isInteractive() && !!process.stdin?.isTTY && !!process.stdout?.isTTY
19309
+ });
18949
19310
  await relaunchOnExitCode(
18950
19311
  () => start_sandbox(sandboxConfig, memoryArgs, partialConfig, sandboxArgs)
18951
19312
  );
@@ -18964,7 +19325,7 @@ ${finalArgs[promptIndex + 1]}`;
18964
19325
  await config.storage.initialize();
18965
19326
  adminControlsListner.setConfig(config);
18966
19327
  if (config.isInteractive() && settings.merged.general.devtools) {
18967
- const { setupInitialActivityLogger } = await import("./devtoolsService-V3OEHE5V.js");
19328
+ const { setupInitialActivityLogger } = await import("./devtoolsService-I7WFRUEA.js");
18968
19329
  setupInitialActivityLogger(config);
18969
19330
  }
18970
19331
  registerTelemetryConfig(config);
@@ -19023,7 +19384,7 @@ ${finalArgs[promptIndex + 1]}`;
19023
19384
  const initAppHandle = startupProfiler.start("initialize_app");
19024
19385
  const initializationResult = await initializeApp(config, settings);
19025
19386
  initAppHandle?.end();
19026
- import("./liteRtServerManager-JTOIS4KU.js").then(({ LiteRtServerManager }) => {
19387
+ import("./liteRtServerManager-OFNVXXQ4.js").then(({ LiteRtServerManager }) => {
19027
19388
  const mergedGemma = settings.merged.experimental?.gemmaModelRouter;
19028
19389
  if (!mergedGemma) return;
19029
19390
  const userGemma = settings.forScope("User" /* User */).settings.experimental?.gemmaModelRouter;