iubcli 4.2.13 → 4.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -194,7 +194,8 @@ function createSpinner(text) {
194
194
  text: chalk.cyan(text),
195
195
  color: "cyan",
196
196
  spinner: "dots",
197
- stream: process.stdout
197
+ stream: process.stdout,
198
+ discardStdin: false
198
199
  });
199
200
  }
200
201
  function renderPriorityTaskBanner(task, model, mode) {
@@ -972,6 +973,9 @@ function parseDirectoryChangeCommand(subCommand, currentCwd) {
972
973
  return null;
973
974
  }
974
975
  async function executeSequentialCommand(command, signal) {
976
+ if (signal?.aborted) {
977
+ return "Action aborted by user (Escape).";
978
+ }
975
979
  if (!safetySession.autoApproveAll) {
976
980
  const summary = `${chalk2.gray("Shell Command:")} ${chalk2.magenta.bold(command)}
977
981
  ${chalk2.gray("Working Directory:")} ${process.cwd()}`;
@@ -2232,7 +2236,10 @@ function renderStatusLine(width, statusText, borderColor) {
2232
2236
  }
2233
2237
  function restoreTerminalViewport() {
2234
2238
  try {
2235
- process.stdout.write("\x1B[r\x1B[?2004l\x1B[?25h");
2239
+ const interactiveStateActive = process.stdin.isRaw || _dockedActive || _dockedPromptActive || _interactiveSelectActive;
2240
+ if (process.stdout.isTTY && interactiveStateActive) {
2241
+ process.stdout.write("\x1B[r\x1B[?2004l\x1B[?25h");
2242
+ }
2236
2243
  if (process.stdin.isTTY && process.stdin.isRaw) {
2237
2244
  process.stdin.setRawMode(false);
2238
2245
  }
@@ -2291,10 +2298,123 @@ function truncateWithAnsi(str, maxWidth) {
2291
2298
  function stripTerminalControlNoise(raw) {
2292
2299
  return raw.replace(/\x1b\[[IO]/g, "").replace(/\x1b\[[0-9;]*R/g, "").replace(/\x1b\[\?[0-9;]*c/g, "").replace(/\x1b\[<[0-9;]*[Mm]/g, "");
2293
2300
  }
2301
+ function isIncompleteEscapePrefix(str) {
2302
+ if (str === "\x1B" || str === "\x1BO") return true;
2303
+ return /^\x1b\[[0-9;?:]*$/.test(str);
2304
+ }
2305
+ function parseTerminalEscape(rest) {
2306
+ const win32Match = rest.match(/^\x1b\[(\d+);(\d+);(\d+);([01]);(\d+);(\d+)_/);
2307
+ if (win32Match) {
2308
+ const length = win32Match[0].length;
2309
+ const vk = Number(win32Match[1]);
2310
+ const uc = Number(win32Match[3]);
2311
+ const isKeyDown = win32Match[4] === "1";
2312
+ const controlState = Number(win32Match[5]);
2313
+ if (!isKeyDown) return { type: "noop", length };
2314
+ if (uc === 3 || vk === 67 && (controlState & 12) !== 0) return { type: "ctrl_c", length };
2315
+ if (vk === 38) return { type: "up", length };
2316
+ if (vk === 40) return { type: "down", length };
2317
+ if (vk === 37) return { type: "left", length };
2318
+ if (vk === 39) return { type: "right", length };
2319
+ if (vk === 33) return { type: "page_up", length };
2320
+ if (vk === 34) return { type: "page_down", length };
2321
+ if (vk === 36) return { type: "home", length };
2322
+ if (vk === 35) return { type: "end", length };
2323
+ if (vk === 13) return { type: "enter", length };
2324
+ if (vk === 27) return { type: "escape", length };
2325
+ if (vk === 9) return { type: "tab", length };
2326
+ if (vk === 8) return { type: "backspace", length };
2327
+ if (vk === 46) return { type: "delete", length };
2328
+ if (uc >= 32) return { type: "char", char: String.fromCodePoint(uc), length };
2329
+ return { type: "noop", length };
2330
+ }
2331
+ if (rest.startsWith("\x1B\r") || rest.startsWith("\x1B\r")) {
2332
+ return { type: "newline", length: 2 };
2333
+ }
2334
+ const kittyEnterMatch = rest.match(/^\x1b\[13(?:;(\d+)(?::\d+)?)?u/);
2335
+ if (kittyEnterMatch) {
2336
+ const mod = kittyEnterMatch[1] ? Number(kittyEnterMatch[1]) : 1;
2337
+ return { type: mod > 1 ? "newline" : "enter", length: kittyEnterMatch[0].length };
2338
+ }
2339
+ const kittyEscMatch = rest.match(/^\x1b\[27(?:;[0-9:]+)?u/);
2340
+ if (kittyEscMatch) {
2341
+ return { type: "escape", length: kittyEscMatch[0].length };
2342
+ }
2343
+ const kittyTabMatch = rest.match(/^\x1b\[9(?:;1(?::\d+)?)?u/);
2344
+ if (kittyTabMatch) {
2345
+ return { type: "tab", length: kittyTabMatch[0].length };
2346
+ }
2347
+ const csiNavMatch = rest.match(/^\x1b\[[0-9;:]*([ABCDHF])/);
2348
+ if (csiNavMatch) {
2349
+ const dirMap = {
2350
+ A: "up",
2351
+ B: "down",
2352
+ C: "right",
2353
+ D: "left",
2354
+ H: "home",
2355
+ F: "end"
2356
+ };
2357
+ return { type: dirMap[csiNavMatch[1]], length: csiNavMatch[0].length };
2358
+ }
2359
+ const rxvtNavMatch = rest.match(/^\x1b\[([abcd])/);
2360
+ if (rxvtNavMatch) {
2361
+ const dirMap = {
2362
+ a: "up",
2363
+ b: "down",
2364
+ c: "right",
2365
+ d: "left"
2366
+ };
2367
+ return { type: dirMap[rxvtNavMatch[1]], length: 3 };
2368
+ }
2369
+ const tildeMatch = rest.match(/^\x1b\[(\d+)(?:;[0-9:]+)?~/);
2370
+ if (tildeMatch) {
2371
+ const code = tildeMatch[1];
2372
+ const length = tildeMatch[0].length;
2373
+ if (code === "5") return { type: "page_up", length };
2374
+ if (code === "6") return { type: "page_down", length };
2375
+ if (code === "1" || code === "7") return { type: "home", length };
2376
+ if (code === "4" || code === "8") return { type: "end", length };
2377
+ if (code === "3") return { type: "delete", length };
2378
+ if (code === "13") return { type: "enter", length };
2379
+ if (code === "12") return { type: "f2", length };
2380
+ return { type: "noop", length };
2381
+ }
2382
+ const ss3Match = rest.match(/^\x1bO([A-Za-z])/);
2383
+ if (ss3Match) {
2384
+ const ch = ss3Match[1];
2385
+ const ss3Map = {
2386
+ A: "up",
2387
+ a: "up",
2388
+ B: "down",
2389
+ b: "down",
2390
+ C: "right",
2391
+ c: "right",
2392
+ D: "left",
2393
+ d: "left",
2394
+ H: "home",
2395
+ F: "end",
2396
+ M: "enter",
2397
+ Q: "f2"
2398
+ };
2399
+ return { type: ss3Map[ch] || "noop", length: 3 };
2400
+ }
2401
+ const genericCsi = rest.match(/^\x1b\[[0-9;?:]*[a-zA-Z~_]/);
2402
+ if (genericCsi) {
2403
+ return { type: "noop", length: genericCsi[0].length };
2404
+ }
2405
+ if (isIncompleteEscapePrefix(rest)) {
2406
+ return null;
2407
+ }
2408
+ return { type: "escape", length: 1 };
2409
+ }
2294
2410
  var _interactiveSelectActive = false;
2411
+ var _lastInteractivePromptEndMs = 0;
2295
2412
  function isInteractivePromptActive() {
2296
2413
  return _interactiveSelectActive;
2297
2414
  }
2415
+ function wasInteractivePromptRecentlyActive(withinMs = 600) {
2416
+ return _interactiveSelectActive || Date.now() - _lastInteractivePromptEndMs < withinMs;
2417
+ }
2298
2418
  function isDockedPromptWaiting() {
2299
2419
  return _dockedPromptActive;
2300
2420
  }
@@ -2352,7 +2472,7 @@ async function interactiveSelect(config) {
2352
2472
  const renderFrame = () => {
2353
2473
  updateScroll();
2354
2474
  const maxVisible = getMaxVisible();
2355
- const safeWidth = Math.max(40, termCols - 4);
2475
+ const safeWidth = Math.max(16, termCols - 2);
2356
2476
  const lines = [];
2357
2477
  lines.push(truncateWithAnsi(chalk4.cyan.bold("\u25C6 ") + chalk4.bold.white(config.message), safeWidth));
2358
2478
  const visibleSlice = config.options.slice(scrollOffset, scrollOffset + maxVisible);
@@ -2404,11 +2524,17 @@ async function interactiveSelect(config) {
2404
2524
  process.stdout.write(frame + "\n");
2405
2525
  lastLineCount = frame.split("\n").length;
2406
2526
  };
2527
+ let numBuffer = "";
2528
+ let numTimeout = null;
2529
+ let escBuffer = "";
2530
+ let escTimeout = null;
2407
2531
  const cleanup = () => {
2408
2532
  _interactiveSelectActive = false;
2533
+ _lastInteractivePromptEndMs = Date.now();
2409
2534
  process.stdin.removeListener("data", onData);
2410
2535
  process.stdout.removeListener("resize", onResize);
2411
2536
  if (numTimeout) clearTimeout(numTimeout);
2537
+ if (escTimeout) clearTimeout(escTimeout);
2412
2538
  try {
2413
2539
  if (!wasRaw && process.stdin.isTTY) {
2414
2540
  process.stdin.setRawMode(false);
@@ -2443,10 +2569,48 @@ async function interactiveSelect(config) {
2443
2569
  termCols = process.stdout.columns || 80;
2444
2570
  draw();
2445
2571
  };
2446
- let numBuffer = "";
2447
- let numTimeout = null;
2572
+ const moveUp = () => {
2573
+ cursor = (cursor - 1 + config.options.length) % config.options.length;
2574
+ };
2575
+ const moveDown = () => {
2576
+ cursor = (cursor + 1) % config.options.length;
2577
+ };
2578
+ const applyChar = (ch) => {
2579
+ if (ch === "q" || ch === "Q") return "cancel";
2580
+ if (ch === "\r" || ch === "\n") return "confirm";
2581
+ if (ch === "k" || ch === "K" || ch === "w" || ch === "W") {
2582
+ moveUp();
2583
+ return "dirty";
2584
+ }
2585
+ if (ch === "j" || ch === "J" || ch === "s" || ch === "S") {
2586
+ moveDown();
2587
+ return "dirty";
2588
+ }
2589
+ if (/^[0-9]$/.test(ch)) {
2590
+ numBuffer += ch;
2591
+ const target = parseInt(numBuffer, 10);
2592
+ let changed = false;
2593
+ if (target >= 1 && target <= config.options.length) {
2594
+ cursor = target - 1;
2595
+ changed = true;
2596
+ }
2597
+ if (numTimeout) clearTimeout(numTimeout);
2598
+ numTimeout = setTimeout(() => {
2599
+ numBuffer = "";
2600
+ }, 700);
2601
+ return changed ? "dirty" : "none";
2602
+ }
2603
+ return "none";
2604
+ };
2448
2605
  const onData = (buf) => {
2449
- const str = stripTerminalControlNoise(buf.toString("utf-8"));
2606
+ if (escTimeout) {
2607
+ clearTimeout(escTimeout);
2608
+ escTimeout = null;
2609
+ }
2610
+ const raw = typeof buf === "string" ? buf : buf.toString("utf-8");
2611
+ const incoming = stripTerminalControlNoise(raw);
2612
+ const str = escBuffer + incoming;
2613
+ escBuffer = "";
2450
2614
  if (!str) return;
2451
2615
  let idx = 0;
2452
2616
  let dirty = false;
@@ -2457,109 +2621,74 @@ async function interactiveSelect(config) {
2457
2621
  process.stdout.write("\r\n" + chalk4.yellow("Exiting IUB CLI...\n"));
2458
2622
  process.exit(0);
2459
2623
  }
2460
- if (rest.startsWith("\x1B[A") || rest.startsWith("\x1BOA")) {
2461
- cursor = (cursor - 1 + config.options.length) % config.options.length;
2462
- idx += 3;
2463
- dirty = true;
2464
- continue;
2465
- }
2466
- if (rest.startsWith("\x1B[B") || rest.startsWith("\x1BOB")) {
2467
- cursor = (cursor + 1) % config.options.length;
2468
- idx += 3;
2469
- dirty = true;
2470
- continue;
2471
- }
2472
- if (rest.startsWith("\x1B[5~")) {
2473
- cursor = Math.max(0, cursor - getMaxVisible());
2474
- idx += 4;
2475
- dirty = true;
2476
- continue;
2477
- }
2478
- if (rest.startsWith("\x1B[6~")) {
2479
- cursor = Math.min(config.options.length - 1, cursor + getMaxVisible());
2480
- idx += 4;
2481
- dirty = true;
2482
- continue;
2483
- }
2484
- if (rest.startsWith("\x1B[H")) {
2485
- cursor = 0;
2486
- idx += 3;
2487
- dirty = true;
2488
- continue;
2489
- }
2490
- if (rest.startsWith("\x1B[1~")) {
2491
- cursor = 0;
2492
- idx += 4;
2493
- dirty = true;
2494
- continue;
2495
- }
2496
- if (rest.startsWith("\x1B[F")) {
2497
- cursor = config.options.length - 1;
2498
- idx += 3;
2499
- dirty = true;
2500
- continue;
2501
- }
2502
- if (rest.startsWith("\x1B[4~")) {
2503
- cursor = config.options.length - 1;
2504
- idx += 4;
2505
- dirty = true;
2506
- continue;
2507
- }
2508
- if (rest.startsWith("\x1BOM")) {
2509
- confirm();
2510
- return;
2511
- }
2512
- if (rest.startsWith("\x1B[13~")) {
2513
- confirm();
2514
- return;
2515
- }
2516
- const ch = str[idx];
2517
- if (ch === "\x1B" && idx === str.length - 1) {
2518
- cancel();
2519
- return;
2520
- }
2521
- if (ch === "\x1B") {
2522
- const csiMatch = rest.match(/^\x1b\[[0-9;]*[a-zA-Z~]/);
2523
- if (csiMatch) {
2524
- idx += csiMatch[0].length;
2525
- continue;
2624
+ if (rest[0] === "\x1B") {
2625
+ const parsed = parseTerminalEscape(rest);
2626
+ if (parsed === null) {
2627
+ escBuffer = rest;
2628
+ escTimeout = setTimeout(() => {
2629
+ escBuffer = "";
2630
+ escTimeout = null;
2631
+ cancel();
2632
+ }, 60);
2633
+ break;
2526
2634
  }
2527
- cancel();
2528
- return;
2635
+ if (parsed.type === "ctrl_c") {
2636
+ cleanup();
2637
+ process.stdout.write("\r\n" + chalk4.yellow("Exiting IUB CLI...\n"));
2638
+ process.exit(0);
2639
+ }
2640
+ if (parsed.type === "escape") {
2641
+ cancel();
2642
+ return;
2643
+ }
2644
+ if (parsed.type === "enter") {
2645
+ confirm();
2646
+ return;
2647
+ }
2648
+ if (parsed.type === "up" || parsed.type === "left") {
2649
+ moveUp();
2650
+ dirty = true;
2651
+ } else if (parsed.type === "down" || parsed.type === "right") {
2652
+ moveDown();
2653
+ dirty = true;
2654
+ } else if (parsed.type === "page_up") {
2655
+ cursor = Math.max(0, cursor - getMaxVisible());
2656
+ dirty = true;
2657
+ } else if (parsed.type === "page_down") {
2658
+ cursor = Math.min(config.options.length - 1, cursor + getMaxVisible());
2659
+ dirty = true;
2660
+ } else if (parsed.type === "home") {
2661
+ cursor = 0;
2662
+ dirty = true;
2663
+ } else if (parsed.type === "end") {
2664
+ cursor = config.options.length - 1;
2665
+ dirty = true;
2666
+ } else if (parsed.type === "char") {
2667
+ const res2 = applyChar(parsed.char);
2668
+ if (res2 === "cancel") {
2669
+ cancel();
2670
+ return;
2671
+ }
2672
+ if (res2 === "confirm") {
2673
+ confirm();
2674
+ return;
2675
+ }
2676
+ if (res2 === "dirty") dirty = true;
2677
+ }
2678
+ idx += parsed.length;
2679
+ continue;
2529
2680
  }
2530
- if (ch === "q" || ch === "Q") {
2681
+ const res = applyChar(str[idx]);
2682
+ if (res === "cancel") {
2531
2683
  cancel();
2532
2684
  return;
2533
2685
  }
2534
- if (ch === "\r" || ch === "\n") {
2686
+ if (res === "confirm") {
2535
2687
  confirm();
2536
2688
  return;
2537
2689
  }
2538
- if (ch === "k" || ch === "K" || ch === "w" || ch === "W") {
2539
- cursor = (cursor - 1 + config.options.length) % config.options.length;
2540
- idx += 1;
2690
+ if (res === "dirty") {
2541
2691
  dirty = true;
2542
- continue;
2543
- }
2544
- if (ch === "j" || ch === "J" || ch === "s" || ch === "S") {
2545
- cursor = (cursor + 1) % config.options.length;
2546
- idx += 1;
2547
- dirty = true;
2548
- continue;
2549
- }
2550
- if (/^[0-9]$/.test(ch)) {
2551
- numBuffer += ch;
2552
- const target = parseInt(numBuffer, 10);
2553
- if (target >= 1 && target <= config.options.length) {
2554
- cursor = target - 1;
2555
- dirty = true;
2556
- }
2557
- if (numTimeout) clearTimeout(numTimeout);
2558
- numTimeout = setTimeout(() => {
2559
- numBuffer = "";
2560
- }, 700);
2561
- idx += 1;
2562
- continue;
2563
2692
  }
2564
2693
  idx += 1;
2565
2694
  }
@@ -2628,6 +2757,7 @@ async function interactiveInput(config) {
2628
2757
  };
2629
2758
  const cleanup = () => {
2630
2759
  _interactiveSelectActive = false;
2760
+ _lastInteractivePromptEndMs = Date.now();
2631
2761
  try {
2632
2762
  process.stdout.write("\x1B[?2004l");
2633
2763
  } catch {
@@ -2967,8 +3097,11 @@ async function readInlinePrompt(options) {
2967
3097
  const linesUp = lines.length - 1 - (cursorLine - startLine);
2968
3098
  process.stdout.write(`\x1B[${linesUp}A\r\x1B[${getActiveCol()}G`);
2969
3099
  };
3100
+ let escBuffer = "";
3101
+ let escTimeout = null;
2970
3102
  const cleanup = () => {
2971
3103
  _dockedPromptActive = false;
3104
+ if (escTimeout) clearTimeout(escTimeout);
2972
3105
  try {
2973
3106
  process.stdout.write("\x1B[?2004l");
2974
3107
  } catch {
@@ -3028,8 +3161,112 @@ async function readInlinePrompt(options) {
3028
3161
  redrawFrom(prevLine);
3029
3162
  }
3030
3163
  };
3164
+ const insertNewline = () => {
3165
+ const cur = bufferLines[cursorLine];
3166
+ const prevLine = cursorLine;
3167
+ bufferLines[cursorLine] = cur.slice(0, cursorCol);
3168
+ bufferLines.splice(cursorLine + 1, 0, cur.slice(cursorCol));
3169
+ cursorLine++;
3170
+ cursorCol = 0;
3171
+ redrawFrom(prevLine);
3172
+ };
3173
+ const moveLeft = () => {
3174
+ if (cursorCol > 0) {
3175
+ cursorCol--;
3176
+ updateActiveLine();
3177
+ } else if (cursorLine > 0) {
3178
+ cursorLine--;
3179
+ cursorCol = bufferLines[cursorLine].length;
3180
+ process.stdout.write("\x1B[1A");
3181
+ updateActiveLine();
3182
+ }
3183
+ };
3184
+ const moveRight = () => {
3185
+ if (cursorCol < bufferLines[cursorLine].length) {
3186
+ cursorCol++;
3187
+ updateActiveLine();
3188
+ } else if (cursorLine < bufferLines.length - 1) {
3189
+ cursorLine++;
3190
+ cursorCol = 0;
3191
+ process.stdout.write("\x1B[1B");
3192
+ updateActiveLine();
3193
+ }
3194
+ };
3195
+ const moveUp = () => {
3196
+ if (cursorLine > 0) {
3197
+ cursorLine--;
3198
+ cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
3199
+ process.stdout.write("\x1B[1A");
3200
+ updateActiveLine();
3201
+ } else if (_commandHistory.length > 0) {
3202
+ if (historyIdx === -1) savedDraft = bufferLines.join("\n");
3203
+ if (historyIdx < _commandHistory.length - 1) {
3204
+ historyIdx++;
3205
+ const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
3206
+ bufferLines = histItem.split("\n");
3207
+ cursorLine = bufferLines.length - 1;
3208
+ cursorCol = bufferLines[cursorLine].length;
3209
+ redrawFrom(0);
3210
+ }
3211
+ }
3212
+ };
3213
+ const moveDown = () => {
3214
+ if (cursorLine < bufferLines.length - 1) {
3215
+ cursorLine++;
3216
+ cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
3217
+ process.stdout.write("\x1B[1B");
3218
+ updateActiveLine();
3219
+ } else if (historyIdx > 0) {
3220
+ historyIdx--;
3221
+ const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
3222
+ bufferLines = histItem.split("\n");
3223
+ cursorLine = 0;
3224
+ cursorCol = bufferLines[0].length;
3225
+ redrawFrom(0);
3226
+ } else if (historyIdx === 0) {
3227
+ historyIdx = -1;
3228
+ bufferLines = savedDraft.split("\n");
3229
+ cursorLine = 0;
3230
+ cursorCol = bufferLines[0].length;
3231
+ redrawFrom(0);
3232
+ }
3233
+ };
3234
+ const deleteForward = () => {
3235
+ const cur = bufferLines[cursorLine];
3236
+ if (cursorCol < cur.length) {
3237
+ bufferLines[cursorLine] = cur.slice(0, cursorCol) + cur.slice(cursorCol + 1);
3238
+ updateActiveLine();
3239
+ } else if (cursorLine < bufferLines.length - 1) {
3240
+ bufferLines[cursorLine] = cur + bufferLines[cursorLine + 1];
3241
+ bufferLines.splice(cursorLine + 1, 1);
3242
+ redrawFrom(cursorLine);
3243
+ }
3244
+ };
3245
+ const deleteBackward = () => {
3246
+ if (cursorCol > 0) {
3247
+ const cur = bufferLines[cursorLine];
3248
+ bufferLines[cursorLine] = cur.slice(0, cursorCol - 1) + cur.slice(cursorCol);
3249
+ cursorCol--;
3250
+ updateActiveLine();
3251
+ } else if (cursorLine > 0) {
3252
+ const cur = bufferLines[cursorLine];
3253
+ const prev = bufferLines[cursorLine - 1];
3254
+ cursorCol = prev.length;
3255
+ bufferLines[cursorLine - 1] = prev + cur;
3256
+ bufferLines.splice(cursorLine, 1);
3257
+ cursorLine--;
3258
+ process.stdout.write("\x1B[1A");
3259
+ redrawFrom(cursorLine);
3260
+ }
3261
+ };
3031
3262
  const onData = (data) => {
3032
- let str = stripTerminalControlNoise(data.toString("utf-8"));
3263
+ if (escTimeout) {
3264
+ clearTimeout(escTimeout);
3265
+ escTimeout = null;
3266
+ }
3267
+ const rawStr = typeof data === "string" ? data : data.toString("utf-8");
3268
+ let str = escBuffer + stripTerminalControlNoise(rawStr);
3269
+ escBuffer = "";
3033
3270
  if (!str) return;
3034
3271
  if (str.includes("\x1B[200~")) {
3035
3272
  inBracketedPaste = true;
@@ -3086,7 +3323,7 @@ async function readInlinePrompt(options) {
3086
3323
  process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
3087
3324
  process.exit(0);
3088
3325
  }
3089
- if (rest.startsWith(" ") || rest.startsWith("\x1BOQ") || rest.startsWith("\x1B[12~")) {
3326
+ if (rest.startsWith(" ")) {
3090
3327
  cleanup();
3091
3328
  const linesUpToTop = cursorLine + 1;
3092
3329
  process.stdout.write(`\x1B[${linesUpToTop}A\r\x1B[J`);
@@ -3105,44 +3342,103 @@ async function readInlinePrompt(options) {
3105
3342
  idx += 1;
3106
3343
  continue;
3107
3344
  }
3108
- if (rest.startsWith("\n") || rest.startsWith("\x1B\r") || rest.startsWith("\x1B[13;2u") || rest.startsWith("\x1B[13;5u")) {
3109
- const seqLen = rest.startsWith("\n") ? 1 : rest.startsWith("\x1B\r") ? 2 : 7;
3110
- const cur2 = bufferLines[cursorLine];
3111
- const prevLine = cursorLine;
3112
- bufferLines[cursorLine] = cur2.slice(0, cursorCol);
3113
- bufferLines.splice(cursorLine + 1, 0, cur2.slice(cursorCol));
3114
- cursorLine++;
3115
- cursorCol = 0;
3116
- redrawFrom(prevLine);
3117
- idx += seqLen;
3118
- continue;
3119
- }
3120
- if (rest.startsWith("\r\n")) {
3121
- if (bufferLines.join("\n").trim().length > 0) {
3122
- submit();
3345
+ if (rest[0] === "\x1B") {
3346
+ const parsed = parseTerminalEscape(rest);
3347
+ if (parsed === null) {
3348
+ escBuffer = rest;
3349
+ escTimeout = setTimeout(() => {
3350
+ escBuffer = "";
3351
+ escTimeout = null;
3352
+ cancel();
3353
+ }, 60);
3354
+ return;
3355
+ }
3356
+ if (parsed.type === "ctrl_c") {
3357
+ cleanup();
3358
+ const down = bufferLines.length - 1 - cursorLine + 2;
3359
+ process.stdout.write(`\x1B[${down}B\r
3360
+ `);
3361
+ process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
3362
+ process.exit(0);
3363
+ }
3364
+ if (parsed.type === "tab" || parsed.type === "f2") {
3365
+ cleanup();
3366
+ const linesUpToTop = cursorLine + 1;
3367
+ process.stdout.write(`\x1B[${linesUpToTop}A\r\x1B[J`);
3368
+ resolve("/model");
3123
3369
  return;
3124
3370
  }
3125
- idx += 2;
3371
+ if (parsed.type === "newline") {
3372
+ insertNewline();
3373
+ } else if (parsed.type === "enter") {
3374
+ if (bufferLines.join("\n").trim().length > 0) {
3375
+ submit();
3376
+ return;
3377
+ }
3378
+ } else if (parsed.type === "escape") {
3379
+ cancel();
3380
+ } else if (parsed.type === "home") {
3381
+ cursorCol = 0;
3382
+ updateActiveLine();
3383
+ } else if (parsed.type === "end") {
3384
+ cursorCol = bufferLines[cursorLine].length;
3385
+ updateActiveLine();
3386
+ } else if (parsed.type === "delete") {
3387
+ deleteForward();
3388
+ } else if (parsed.type === "backspace") {
3389
+ deleteBackward();
3390
+ } else if (parsed.type === "left") {
3391
+ moveLeft();
3392
+ } else if (parsed.type === "right") {
3393
+ moveRight();
3394
+ } else if (parsed.type === "up") {
3395
+ moveUp();
3396
+ } else if (parsed.type === "down") {
3397
+ moveDown();
3398
+ } else if (parsed.type === "page_up") {
3399
+ if (_commandHistory.length > 0) {
3400
+ if (historyIdx === -1) savedDraft = bufferLines.join("\n");
3401
+ historyIdx = _commandHistory.length - 1;
3402
+ bufferLines = _commandHistory[0].split("\n");
3403
+ cursorLine = 0;
3404
+ cursorCol = bufferLines[0].length;
3405
+ redrawFrom(0);
3406
+ }
3407
+ } else if (parsed.type === "page_down") {
3408
+ if (historyIdx !== -1) {
3409
+ historyIdx = -1;
3410
+ bufferLines = savedDraft.split("\n");
3411
+ cursorLine = 0;
3412
+ cursorCol = bufferLines[0].length;
3413
+ redrawFrom(0);
3414
+ }
3415
+ } else if (parsed.type === "char") {
3416
+ const cur2 = bufferLines[cursorLine];
3417
+ bufferLines[cursorLine] = cur2.slice(0, cursorCol) + parsed.char + cur2.slice(cursorCol);
3418
+ cursorCol += parsed.char.length;
3419
+ updateActiveLine();
3420
+ }
3421
+ idx += parsed.length;
3126
3422
  continue;
3127
3423
  }
3128
- if (rest.startsWith("\r") || rest.startsWith("\x1BOM") || rest.startsWith("\x1B[13~")) {
3424
+ if (rest.startsWith("\r\n") || rest.startsWith("\n") || rest.startsWith("\r")) {
3129
3425
  if (bufferLines.join("\n").trim().length > 0) {
3130
3426
  submit();
3131
3427
  return;
3132
3428
  }
3133
- idx += rest.startsWith("\r") ? 1 : rest.startsWith("\x1BOM") ? 3 : 5;
3429
+ idx += rest.startsWith("\r\n") ? 2 : 1;
3134
3430
  continue;
3135
3431
  }
3136
- if (rest.startsWith("") || rest.startsWith("\x1B[H") || rest.startsWith("\x1B[1~") || rest.startsWith("\x1BOH")) {
3432
+ if (rest.startsWith("")) {
3137
3433
  cursorCol = 0;
3138
3434
  updateActiveLine();
3139
- idx += rest.startsWith("") ? 1 : rest.startsWith("\x1B[1~") ? 4 : 3;
3435
+ idx += 1;
3140
3436
  continue;
3141
3437
  }
3142
- if (rest.startsWith("") || rest.startsWith("\x1B[F") || rest.startsWith("\x1B[4~") || rest.startsWith("\x1BOF")) {
3438
+ if (rest.startsWith("")) {
3143
3439
  cursorCol = bufferLines[cursorLine].length;
3144
3440
  updateActiveLine();
3145
- idx += rest.startsWith("") ? 1 : rest.startsWith("\x1B[4~") ? 4 : 3;
3441
+ idx += 1;
3146
3442
  continue;
3147
3443
  }
3148
3444
  if (rest.startsWith("")) {
@@ -3152,142 +3448,18 @@ async function readInlinePrompt(options) {
3152
3448
  idx += 1;
3153
3449
  continue;
3154
3450
  }
3155
- if (rest.startsWith("\x1B[3~")) {
3156
- const cur2 = bufferLines[cursorLine];
3157
- if (cursorCol < cur2.length) {
3158
- bufferLines[cursorLine] = cur2.slice(0, cursorCol) + cur2.slice(cursorCol + 1);
3159
- updateActiveLine();
3160
- } else if (cursorLine < bufferLines.length - 1) {
3161
- bufferLines[cursorLine] = cur2 + bufferLines[cursorLine + 1];
3162
- bufferLines.splice(cursorLine + 1, 1);
3163
- redrawFrom(cursorLine);
3164
- }
3165
- idx += 4;
3166
- continue;
3167
- }
3168
- if (rest.startsWith("\b") || rest.startsWith("\x7F")) {
3169
- if (cursorCol > 0) {
3170
- const cur2 = bufferLines[cursorLine];
3171
- bufferLines[cursorLine] = cur2.slice(0, cursorCol - 1) + cur2.slice(cursorCol);
3172
- cursorCol--;
3173
- updateActiveLine();
3174
- } else if (cursorLine > 0) {
3175
- const cur2 = bufferLines[cursorLine];
3176
- const prev = bufferLines[cursorLine - 1];
3177
- cursorCol = prev.length;
3178
- bufferLines[cursorLine - 1] = prev + cur2;
3179
- bufferLines.splice(cursorLine, 1);
3180
- cursorLine--;
3181
- process.stdout.write("\x1B[1A");
3182
- redrawFrom(cursorLine);
3183
- }
3451
+ if (rest.startsWith("")) {
3452
+ moveUp();
3184
3453
  idx += 1;
3185
3454
  continue;
3186
3455
  }
3187
- if (rest.startsWith("\x1B[D") || rest.startsWith("\x1BOD")) {
3188
- if (cursorCol > 0) {
3189
- cursorCol--;
3190
- updateActiveLine();
3191
- } else if (cursorLine > 0) {
3192
- cursorLine--;
3193
- cursorCol = bufferLines[cursorLine].length;
3194
- process.stdout.write("\x1B[1A");
3195
- updateActiveLine();
3196
- }
3197
- idx += 3;
3198
- continue;
3199
- }
3200
- if (rest.startsWith("\x1B[C") || rest.startsWith("\x1BOC")) {
3201
- if (cursorCol < bufferLines[cursorLine].length) {
3202
- cursorCol++;
3203
- updateActiveLine();
3204
- } else if (cursorLine < bufferLines.length - 1) {
3205
- cursorLine++;
3206
- cursorCol = 0;
3207
- process.stdout.write("\x1B[1B");
3208
- updateActiveLine();
3209
- }
3210
- idx += 3;
3211
- continue;
3212
- }
3213
- if (rest.startsWith("\x1B[A") || rest.startsWith("\x1BOA") || rest.startsWith("")) {
3214
- const seqLen = rest.startsWith("") ? 1 : 3;
3215
- if (cursorLine > 0) {
3216
- cursorLine--;
3217
- cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
3218
- process.stdout.write("\x1B[1A");
3219
- updateActiveLine();
3220
- } else if (_commandHistory.length > 0) {
3221
- if (historyIdx === -1) savedDraft = bufferLines.join("\n");
3222
- if (historyIdx < _commandHistory.length - 1) {
3223
- historyIdx++;
3224
- const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
3225
- bufferLines = histItem.split("\n");
3226
- cursorLine = bufferLines.length - 1;
3227
- cursorCol = bufferLines[cursorLine].length;
3228
- redrawFrom(0);
3229
- }
3230
- }
3231
- idx += seqLen;
3232
- continue;
3233
- }
3234
- if (rest.startsWith("\x1B[B") || rest.startsWith("\x1BOB") || rest.startsWith("")) {
3235
- const seqLen = rest.startsWith("") ? 1 : 3;
3236
- if (cursorLine < bufferLines.length - 1) {
3237
- cursorLine++;
3238
- cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
3239
- process.stdout.write("\x1B[1B");
3240
- updateActiveLine();
3241
- } else if (historyIdx > 0) {
3242
- historyIdx--;
3243
- const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
3244
- bufferLines = histItem.split("\n");
3245
- cursorLine = 0;
3246
- cursorCol = bufferLines[0].length;
3247
- redrawFrom(0);
3248
- } else if (historyIdx === 0) {
3249
- historyIdx = -1;
3250
- bufferLines = savedDraft.split("\n");
3251
- cursorLine = 0;
3252
- cursorCol = bufferLines[0].length;
3253
- redrawFrom(0);
3254
- }
3255
- idx += seqLen;
3256
- continue;
3257
- }
3258
- if (rest.startsWith("\x1B[5~")) {
3259
- if (_commandHistory.length > 0) {
3260
- if (historyIdx === -1) savedDraft = bufferLines.join("\n");
3261
- historyIdx = _commandHistory.length - 1;
3262
- bufferLines = _commandHistory[0].split("\n");
3263
- cursorLine = 0;
3264
- cursorCol = bufferLines[0].length;
3265
- redrawFrom(0);
3266
- }
3267
- idx += 4;
3268
- continue;
3269
- }
3270
- if (rest.startsWith("\x1B[6~")) {
3271
- if (historyIdx !== -1) {
3272
- historyIdx = -1;
3273
- bufferLines = savedDraft.split("\n");
3274
- cursorLine = 0;
3275
- cursorCol = bufferLines[0].length;
3276
- redrawFrom(0);
3277
- }
3278
- idx += 4;
3456
+ if (rest.startsWith("")) {
3457
+ moveDown();
3458
+ idx += 1;
3279
3459
  continue;
3280
3460
  }
3281
- if (rest[0] === "\x1B") {
3282
- if (idx === str.length - 1) {
3283
- cancel();
3284
- return;
3285
- }
3286
- const csiMatch = rest.match(/^\x1b\[[0-9;]*[a-zA-Z~]/);
3287
- if (csiMatch) {
3288
- idx += csiMatch[0].length;
3289
- continue;
3290
- }
3461
+ if (rest.startsWith("\b") || rest.startsWith("\x7F")) {
3462
+ deleteBackward();
3291
3463
  idx += 1;
3292
3464
  continue;
3293
3465
  }
@@ -6411,10 +6583,24 @@ var IUBAgent = class {
6411
6583
  if (hasSavedConfig() || this.config.apiKey !== POLLINATIONS_FREE_API_KEY) {
6412
6584
  saveConfig(this.config);
6413
6585
  }
6414
- this.onModelChangeCallback?.(this.config.model, this.config.provider);
6586
+ this.onModelChangeCallback?.(this.config.model, this.config.provider, this.config);
6415
6587
  } catch {
6416
6588
  }
6417
6589
  }
6590
+ /**
6591
+ * Sync conversation history only when switching between Gemini and OpenAI-compatible
6592
+ * formats. Gemini -> Gemini failover must never rebuild geminiContents from the
6593
+ * (usually empty) OpenAI mirror, and OpenAI -> OpenAI switches must not overwrite
6594
+ * live messages with a stale Gemini transcript.
6595
+ */
6596
+ syncHistoryForProviderChange(prevProvider, nextProvider) {
6597
+ if (prevProvider === nextProvider) return;
6598
+ if (prevProvider !== "gemini" && nextProvider === "gemini") {
6599
+ this.syncMessagesToGemini();
6600
+ } else if (prevProvider === "gemini" && nextProvider !== "gemini") {
6601
+ this.syncMessagesToOpenAI();
6602
+ }
6603
+ }
6418
6604
  /**
6419
6605
  * Sync active OpenAI message history into Gemini content format (preserving tool calls/results).
6420
6606
  */
@@ -6579,13 +6765,14 @@ ${String(out).slice(0, 6e3)}`);
6579
6765
  for (const rawModel of GEMINI_CASCADE_CHAIN) {
6580
6766
  const model = normalizeGeminiModel(rawModel);
6581
6767
  if (!this.attemptedModelsInCascade.has(model)) {
6768
+ const prevProvider = this.config.provider;
6582
6769
  renderCascadeNotice(currentModel, model, noticeReason);
6583
6770
  this.config.provider = "gemini";
6584
6771
  this.config.apiKey = geminiKey;
6585
6772
  this.config.model = model;
6586
6773
  delete this.config.baseURL;
6587
6774
  this.initClients();
6588
- this.syncMessagesToGemini();
6775
+ this.syncHistoryForProviderChange(prevProvider, "gemini");
6589
6776
  return model;
6590
6777
  }
6591
6778
  }
@@ -6597,13 +6784,14 @@ ${String(out).slice(0, 6e3)}`);
6597
6784
  if (!openRouterKey) return null;
6598
6785
  for (const model of OPENROUTER_FREE_CASCADE_CHAIN) {
6599
6786
  if (!this.attemptedModelsInCascade.has(model)) {
6787
+ const prevProvider = this.config.provider;
6600
6788
  renderCascadeNotice(currentModel, model, noticeReason);
6601
6789
  this.config.provider = "openrouter";
6602
6790
  this.config.apiKey = openRouterKey;
6603
6791
  this.config.model = model;
6604
6792
  this.config.baseURL = "https://openrouter.ai/api/v1";
6605
6793
  this.initClients();
6606
- this.syncMessagesToOpenAI();
6794
+ this.syncHistoryForProviderChange(prevProvider, "openrouter");
6607
6795
  return model;
6608
6796
  }
6609
6797
  }
@@ -6630,6 +6818,7 @@ ${String(out).slice(0, 6e3)}`);
6630
6818
  for (const targetModel of candidateModels) {
6631
6819
  const dedupeKey = `custom:${targetModel}`;
6632
6820
  if (!this.attemptedModelsInCascade.has(dedupeKey) && !this.attemptedModelsInCascade.has(targetModel)) {
6821
+ const prevProvider = this.config.provider;
6633
6822
  this.attemptedModelsInCascade.add(dedupeKey);
6634
6823
  this.attemptedModelsInCascade.add(targetModel);
6635
6824
  renderCascadeNotice(currentModel, targetModel, noticeReason);
@@ -6638,7 +6827,7 @@ ${String(out).slice(0, 6e3)}`);
6638
6827
  this.config.baseURL = customBaseURL;
6639
6828
  this.config.model = targetModel;
6640
6829
  this.initClients();
6641
- this.syncMessagesToOpenAI();
6830
+ this.syncHistoryForProviderChange(prevProvider, "custom");
6642
6831
  return targetModel;
6643
6832
  }
6644
6833
  }
@@ -6673,16 +6862,13 @@ ${String(out).slice(0, 6e3)}`);
6673
6862
  const nextOR = switchToOpenRouter("Custom provider rate-limited/exhausted; cascading to OpenRouter Free");
6674
6863
  if (nextOR) return nextOR;
6675
6864
  }
6865
+ const prevProviderBeforeExplore = this.config.provider;
6676
6866
  const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade, false, false);
6677
6867
  if (explored) {
6678
6868
  this.attemptedModelsInCascade.add(explored.id);
6679
6869
  this.initClients();
6680
- if (explored.provider === "gemini") {
6681
- this.syncMessagesToGemini();
6682
- } else {
6683
- this.syncMessagesToOpenAI();
6684
- }
6685
- this.onModelChangeCallback?.(explored.id, explored.provider);
6870
+ this.syncHistoryForProviderChange(prevProviderBeforeExplore, this.config.provider);
6871
+ this.onModelChangeCallback?.(explored.id, explored.provider, this.config);
6686
6872
  return explored.id;
6687
6873
  }
6688
6874
  if (this.neverStopAttempts < 10) {
@@ -6698,27 +6884,25 @@ ${String(out).slice(0, 6e3)}`);
6698
6884
  if (signal?.aborted) return null;
6699
6885
  this.attemptedModelsInCascade.clear();
6700
6886
  this.deadProvidersInTurn.clear();
6887
+ const prevProviderBeforeRecovery = this.config.provider;
6701
6888
  const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true, false);
6702
6889
  if (recovered) {
6703
6890
  this.initClients();
6704
- if (recovered.provider === "gemini") {
6705
- this.syncMessagesToGemini();
6706
- } else {
6707
- this.syncMessagesToOpenAI();
6708
- }
6709
- this.onModelChangeCallback?.(recovered.id, recovered.provider);
6891
+ this.syncHistoryForProviderChange(prevProviderBeforeRecovery, this.config.provider);
6892
+ this.onModelChangeCallback?.(recovered.id, recovered.provider, this.config);
6710
6893
  return recovered.id;
6711
6894
  }
6712
6895
  }
6713
6896
  if (this.config.baseURL !== POLLINATIONS_BASE_URL || this.config.model !== POLLINATIONS_DEFAULT_MODEL) {
6897
+ const prevProviderBeforeFallback = this.config.provider;
6714
6898
  renderCascadeNotice(currentModel, POLLINATIONS_DEFAULT_MODEL, "Switching to Zero-Key Built-in Free AI");
6715
6899
  this.config.provider = "custom";
6716
6900
  this.config.apiKey = POLLINATIONS_FREE_API_KEY;
6717
6901
  this.config.baseURL = POLLINATIONS_BASE_URL;
6718
6902
  this.config.model = POLLINATIONS_DEFAULT_MODEL;
6719
6903
  this.initClients();
6720
- this.syncMessagesToOpenAI();
6721
- this.onModelChangeCallback?.(this.config.model, this.config.provider);
6904
+ this.syncHistoryForProviderChange(prevProviderBeforeFallback, "custom");
6905
+ this.onModelChangeCallback?.(this.config.model, this.config.provider, this.config);
6722
6906
  return this.config.model;
6723
6907
  }
6724
6908
  renderAllTokensExhaustedReport();
@@ -6728,15 +6912,12 @@ ${String(out).slice(0, 6e3)}`);
6728
6912
  * Run model explorer to find and select an active model with free tokens.
6729
6913
  */
6730
6914
  async exploreFreeModel() {
6915
+ const prevProvider = this.config.provider;
6731
6916
  const explored = await exploreAndSelectFreeModel(this.config);
6732
6917
  if (explored) {
6733
6918
  this.initClients();
6734
- if (explored.provider === "gemini") {
6735
- this.syncMessagesToGemini();
6736
- } else {
6737
- this.syncMessagesToOpenAI();
6738
- }
6739
- this.onModelChangeCallback?.(explored.id, explored.provider);
6919
+ this.syncHistoryForProviderChange(prevProvider, this.config.provider);
6920
+ this.onModelChangeCallback?.(explored.id, explored.provider, this.config);
6740
6921
  return explored.id;
6741
6922
  }
6742
6923
  return null;
@@ -6849,19 +7030,59 @@ ${String(out).slice(0, 6e3)}`);
6849
7030
  * Ensure message history has no dangling tool_calls or unresponded user turns before starting a new turn.
6850
7031
  */
6851
7032
  sanitizeDanglingHistory() {
6852
- const lastOpenAI = this.openAIMessages[this.openAIMessages.length - 1];
6853
- if (lastOpenAI && lastOpenAI.role === "assistant" && Array.isArray(lastOpenAI.tool_calls) && lastOpenAI.tool_calls.length > 0) {
6854
- for (const tc of lastOpenAI.tool_calls) {
6855
- if (tc?.id) {
6856
- this.openAIMessages.push({
7033
+ let lastAssistantIdx = -1;
7034
+ for (let i = this.openAIMessages.length - 1; i >= 0; i--) {
7035
+ const msg = this.openAIMessages[i];
7036
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
7037
+ lastAssistantIdx = i;
7038
+ break;
7039
+ }
7040
+ }
7041
+ if (lastAssistantIdx !== -1) {
7042
+ const assistant = this.openAIMessages[lastAssistantIdx];
7043
+ const expectedIds = assistant.tool_calls.map((tc) => tc?.id).filter((id) => typeof id === "string" && id.length > 0);
7044
+ const responded = /* @__PURE__ */ new Set();
7045
+ let insertAt = lastAssistantIdx + 1;
7046
+ for (let i = lastAssistantIdx + 1; i < this.openAIMessages.length; i++) {
7047
+ const msg = this.openAIMessages[i];
7048
+ if (msg.role !== "tool") break;
7049
+ if (msg.tool_call_id) responded.add(msg.tool_call_id);
7050
+ insertAt = i + 1;
7051
+ }
7052
+ const missing = expectedIds.filter((id) => !responded.has(id));
7053
+ if (missing.length > 0) {
7054
+ this.openAIMessages.splice(
7055
+ insertAt,
7056
+ 0,
7057
+ ...missing.map((id) => ({
6857
7058
  role: "tool",
6858
- tool_call_id: tc.id,
7059
+ tool_call_id: id,
6859
7060
  content: "Action cancelled before completion."
6860
- });
6861
- }
7061
+ }))
7062
+ );
6862
7063
  }
6863
7064
  }
6864
7065
  const lastGemini = this.geminiContents[this.geminiContents.length - 1];
7066
+ if (lastGemini && lastGemini.role === "model") {
7067
+ const pendingCalls = (lastGemini.parts || []).filter((p) => p?.functionCall);
7068
+ if (pendingCalls.length > 0) {
7069
+ this.geminiContents.push({
7070
+ role: "user",
7071
+ parts: pendingCalls.map((p) => ({
7072
+ functionResponse: {
7073
+ name: p.functionCall.name,
7074
+ id: p.functionCall.id,
7075
+ response: { output: "Action cancelled before completion." }
7076
+ }
7077
+ }))
7078
+ });
7079
+ this.geminiContents.push({
7080
+ role: "model",
7081
+ parts: [{ text: "[Tool execution was interrupted by the user.]" }]
7082
+ });
7083
+ return;
7084
+ }
7085
+ }
6865
7086
  if (lastGemini && lastGemini.role === "user") {
6866
7087
  this.geminiContents.push({
6867
7088
  role: "model",
@@ -7144,8 +7365,23 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7144
7365
  return directText || "";
7145
7366
  }
7146
7367
  const toolResponseParts = [];
7147
- for (const call of functionCalls) {
7368
+ const pushCancelledFunctionResponses = (fromIndex) => {
7369
+ for (let j = fromIndex; j < functionCalls.length; j++) {
7370
+ const pending = functionCalls[j];
7371
+ toolResponseParts.push({
7372
+ functionResponse: {
7373
+ name: pending.name,
7374
+ id: pending.id,
7375
+ response: { output: "Action cancelled by user (Escape)." }
7376
+ }
7377
+ });
7378
+ }
7379
+ };
7380
+ for (let callIndex = 0; callIndex < functionCalls.length; callIndex++) {
7381
+ const call = functionCalls[callIndex];
7148
7382
  if (options?.signal?.aborted) {
7383
+ pushCancelledFunctionResponses(callIndex);
7384
+ this.geminiContents.push({ role: "user", parts: toolResponseParts });
7149
7385
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7150
7386
  }
7151
7387
  const toolName = call.name;
@@ -7156,9 +7392,6 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7156
7392
  });
7157
7393
  toolsExecutedInChat++;
7158
7394
  const output = await executeTool(toolName, toolArgs, this.mode, options?.signal);
7159
- if (options?.signal?.aborted) {
7160
- return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7161
- }
7162
7395
  toolResponseParts.push({
7163
7396
  functionResponse: {
7164
7397
  name: toolName,
@@ -7166,6 +7399,11 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7166
7399
  response: { output }
7167
7400
  }
7168
7401
  });
7402
+ if (options?.signal?.aborted) {
7403
+ pushCancelledFunctionResponses(callIndex + 1);
7404
+ this.geminiContents.push({ role: "user", parts: toolResponseParts });
7405
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7406
+ }
7169
7407
  }
7170
7408
  this.geminiContents.push({
7171
7409
  role: "user",
@@ -7419,8 +7657,23 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7419
7657
  }
7420
7658
  return finalCandidate;
7421
7659
  }
7422
- for (const toolCall of message.tool_calls) {
7660
+ const toolCalls = message.tool_calls;
7661
+ const pushCancelledToolResponses = (fromIndex) => {
7662
+ for (let j = fromIndex; j < toolCalls.length; j++) {
7663
+ const pending = toolCalls[j];
7664
+ if (pending?.id) {
7665
+ this.openAIMessages.push({
7666
+ role: "tool",
7667
+ tool_call_id: pending.id,
7668
+ content: "Action cancelled by user (Escape)."
7669
+ });
7670
+ }
7671
+ }
7672
+ };
7673
+ for (let callIndex = 0; callIndex < toolCalls.length; callIndex++) {
7674
+ const toolCall = toolCalls[callIndex];
7423
7675
  if (options?.signal?.aborted) {
7676
+ pushCancelledToolResponses(callIndex);
7424
7677
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7425
7678
  }
7426
7679
  const fnObj = toolCall.function;
@@ -7456,14 +7709,15 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7456
7709
  });
7457
7710
  toolsExecutedInChat++;
7458
7711
  const toolResult = await executeTool(fnName, fnArgs, this.mode, options?.signal);
7459
- if (options?.signal?.aborted) {
7460
- return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7461
- }
7462
7712
  this.openAIMessages.push({
7463
7713
  role: "tool",
7464
7714
  tool_call_id: toolCall.id,
7465
7715
  content: toolResult
7466
7716
  });
7717
+ if (options?.signal?.aborted) {
7718
+ pushCancelledToolResponses(callIndex + 1);
7719
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7720
+ }
7467
7721
  }
7468
7722
  }
7469
7723
  return "Maximum agent iteration steps reached for this request.";
@@ -8268,31 +8522,61 @@ function attachEscapeListener(onEscape) {
8268
8522
  } catch {
8269
8523
  }
8270
8524
  let triggered = false;
8525
+ let escTimer = null;
8271
8526
  const triggerEscape = () => {
8272
8527
  if (triggered) return;
8273
8528
  triggered = true;
8529
+ if (escTimer) {
8530
+ clearTimeout(escTimer);
8531
+ escTimer = null;
8532
+ }
8274
8533
  onEscape();
8275
8534
  };
8276
8535
  const onData = (chunk) => {
8277
- if (isInteractivePromptActive()) return;
8536
+ if (isInteractivePromptActive()) {
8537
+ if (escTimer) {
8538
+ clearTimeout(escTimer);
8539
+ escTimer = null;
8540
+ }
8541
+ return;
8542
+ }
8278
8543
  const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
8279
- if (buf.length === 1 && buf[0] === 27) {
8280
- triggerEscape();
8281
- } else if (buf.length === 1 && buf[0] === 3) {
8544
+ if (buf.length === 1 && buf[0] === 3) {
8282
8545
  process.exit(0);
8283
8546
  }
8547
+ if (wasInteractivePromptRecentlyActive(600)) return;
8548
+ if (buf.length === 1 && buf[0] === 27) {
8549
+ if (escTimer) {
8550
+ triggerEscape();
8551
+ return;
8552
+ }
8553
+ escTimer = setTimeout(() => {
8554
+ escTimer = null;
8555
+ if (!isInteractivePromptActive() && !wasInteractivePromptRecentlyActive(600)) {
8556
+ triggerEscape();
8557
+ }
8558
+ }, 60);
8559
+ } else if (escTimer) {
8560
+ clearTimeout(escTimer);
8561
+ escTimer = null;
8562
+ }
8284
8563
  };
8285
8564
  const keypressHandler = (str, key) => {
8286
- if (isInteractivePromptActive()) return;
8565
+ if (key && key.ctrl && key.name === "c") {
8566
+ process.exit(0);
8567
+ }
8568
+ if (isInteractivePromptActive() || wasInteractivePromptRecentlyActive(600)) return;
8287
8569
  if (key && key.name === "escape" || str === "\x1B" || str === "\x1B" || key && key.sequence === "\x1B") {
8288
8570
  triggerEscape();
8289
- } else if (key && key.ctrl && key.name === "c") {
8290
- process.exit(0);
8291
8571
  }
8292
8572
  };
8293
8573
  process.stdin.on("data", onData);
8294
8574
  process.stdin.on("keypress", keypressHandler);
8295
8575
  return () => {
8576
+ if (escTimer) {
8577
+ clearTimeout(escTimer);
8578
+ escTimer = null;
8579
+ }
8296
8580
  process.stdin.removeListener("data", onData);
8297
8581
  process.stdin.removeListener("keypress", keypressHandler);
8298
8582
  try {
@@ -8425,12 +8709,10 @@ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 655
8425
8709
  await meshNode.start();
8426
8710
  setActiveMeshNode(meshNode);
8427
8711
  }
8428
- agent.setOnModelChange((newModel, newProvider) => {
8429
- const freshConfig = getConfig();
8430
- if (freshConfig) {
8431
- config = freshConfig;
8432
- }
8433
- if (config) {
8712
+ agent.setOnModelChange((newModel, newProvider, activeConfig) => {
8713
+ if (activeConfig) {
8714
+ config = activeConfig;
8715
+ } else if (config) {
8434
8716
  config.model = newModel;
8435
8717
  if (newProvider) {
8436
8718
  config.provider = newProvider;
@@ -8439,14 +8721,9 @@ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 655
8439
8721
  } else if (config.provider === "openrouter") {
8440
8722
  config.baseURL = "https://openrouter.ai/api/v1";
8441
8723
  }
8442
- const saved = config.savedProviders?.[config.provider];
8443
- if (saved && saved.apiKey) {
8444
- config.apiKey = saved.apiKey;
8445
- if (config.provider !== "gemini") {
8446
- config.baseURL = saved.baseURL || config.baseURL;
8447
- }
8448
- }
8449
8724
  }
8725
+ }
8726
+ if (config) {
8450
8727
  if (hasSavedConfig() || config.apiKey !== POLLINATIONS_FREE_API_KEY) {
8451
8728
  saveConfig(config);
8452
8729
  }