iubcli 4.2.10 → 4.2.11

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
@@ -4,12 +4,14 @@
4
4
  import fs8 from "fs";
5
5
  import path8 from "path";
6
6
  import readline from "readline";
7
+ import { execSync as execSync3 } from "child_process";
7
8
  import { Command } from "commander";
8
9
  import chalk9 from "chalk";
9
10
 
10
11
  // src/config.ts
11
12
  import fs5 from "fs";
12
13
  import path5 from "path";
14
+ import { fileURLToPath } from "url";
13
15
  import Conf2 from "conf";
14
16
 
15
17
  // src/prompt.ts
@@ -62,7 +64,7 @@ function printBanner(provider, model, workspace) {
62
64
  `;
63
65
  console.log(asciiArt);
64
66
  console.log(
65
- ` ${chalk.bgHex("#003087").white.bold(" IUB CLI v2.0 ")} ${chalk.hex("#00A3FF")(
67
+ ` ${chalk.bgHex("#003087").white.bold(` IUB CLI v${getAppVersion()} `)} ${chalk.hex("#00A3FF")(
66
68
  "Next-Gen Autonomous BYOK Terminal Coding Agent"
67
69
  )}`
68
70
  );
@@ -156,6 +158,8 @@ ${badge}`);
156
158
  console.log(chalk.gray(`Path: `) + chalk.cyan(args.filePath));
157
159
  const lines = typeof args.content === "string" ? args.content.split("\n").length : 0;
158
160
  console.log(chalk.gray(`Lines: `) + chalk.yellow(`${lines} lines`));
161
+ } else if (toolName === "edit_file") {
162
+ console.log(chalk.gray(`Editing: `) + chalk.cyan(args.filePath));
159
163
  } else if (toolName === "run_command") {
160
164
  console.log(chalk.gray(`Command: `) + chalk.magenta.bold(args.command));
161
165
  } else if (toolName === "read_file") {
@@ -168,6 +172,12 @@ ${badge}`);
168
172
  console.log(chalk.gray(`Pattern: `) + chalk.cyan.bold(args.pattern));
169
173
  } else if (toolName === "fetch_url") {
170
174
  console.log(chalk.gray(`Fetching URL: `) + chalk.cyan.bold(args.url));
175
+ } else if (toolName === "web_search") {
176
+ console.log(chalk.gray(`Searching web: `) + chalk.cyan.bold(args.query));
177
+ } else if (toolName === "peer_call_tool") {
178
+ console.log(chalk.gray(`Peer: `) + chalk.cyan.bold(args.peer) + chalk.gray(` \u2022 Tool: `) + chalk.yellow(args.tool));
179
+ } else if (toolName === "peer_send_message") {
180
+ console.log(chalk.gray(`Peer: `) + chalk.cyan.bold(args.peer));
171
181
  }
172
182
  }
173
183
  function renderToolResult(toolName, result, isError = false) {
@@ -306,8 +316,8 @@ function showFreeApiKeyGuide() {
306
316
  console.log(chalk.bold.hex("#00A3FF")("1. Google Gemini (Google AI Studio) - RECOMMENDED"));
307
317
  console.log(` ${chalk.gray("Direct Link:")} ${chalk.bold.underline.cyan("https://aistudio.google.com/apikey")}`);
308
318
  console.log(` ${chalk.gray("Steps:")} Sign in with Google -> Click "${chalk.white("Create API Key")}" -> Copy key.`);
309
- console.log(` ${chalk.gray("Best Free Model:")} ${chalk.bold.yellow("gemini-2.0-flash")} (100% Free, flagship speed & 1,500 RPD)`);
310
- console.log(` ${chalk.gray("Alternative Free Models:")} ${chalk.white("gemini-2.0-flash-lite, gemini-2.5-flash, gemini-1.5-flash")}`);
319
+ console.log(` ${chalk.gray("Best Free Model:")} ${chalk.bold.yellow("gemini-3.5-flash-lite")} (100% Free, flagship speed & 1,500 RPD)`);
320
+ console.log(` ${chalk.gray("Alternative Free Models:")} ${chalk.white("gemini-3.1-flash-lite, gemma-4-31b-it, gemini-3.5-flash")}`);
311
321
  console.log(` ${chalk.gray("Quota:")} Free tier gives 15 Requests/min & 1,500 Requests/day for free!
312
322
  `);
313
323
  console.log(chalk.bold.hex("#00A3FF")("2. OpenRouter (Access 14+ 100% Free Frontier Models)"));
@@ -419,7 +429,7 @@ function showTokenLimitsGuide() {
419
429
  console.log(` \u2022 ${chalk.white("mistralai/codestral-2501")} : ${chalk.cyan("256,000 tokens")} context | Dedicated 256K software engineering model`);
420
430
  console.log(` \u2022 ${chalk.white("google/gemini-2.5-pro")} : ${chalk.cyan("2,097,152 tokens")} context | Massive 2 Million token long-context frontier
421
431
  `);
422
- console.log(chalk.bold.hex("#00A3FF")("9. Local Offline Models (Ollama - localhost:11434)"));
432
+ console.log(chalk.bold.hex("#00A3FF")("6. Local Offline Models (Ollama - localhost:11434)"));
423
433
  console.log(` \u2022 ${chalk.white("deepseek-r1")} & ${chalk.white("qwen2.5-coder")} : ${chalk.green.bold("100% UNLIMITED TOKENS, ZERO RATE LIMITS")}`);
424
434
  console.log(` Runs 100% private and offline on your local CPU/GPU with no internet required!
425
435
  `);
@@ -437,27 +447,40 @@ function renderGitStatus() {
437
447
  console.log(chalk.bgHex("#003087").white.bold(" GIT REPOSITORY STATUS "));
438
448
  console.log(chalk.dim("\u2500".repeat(70)));
439
449
  try {
440
- const branch = execSync("git rev-parse --abbrev-ref HEAD 2>/dev/null || git branch --show-current", {
441
- encoding: "utf8",
442
- stdio: ["ignore", "pipe", "ignore"]
443
- }).trim();
450
+ let branch = "";
451
+ try {
452
+ branch = execSync("git rev-parse --abbrev-ref HEAD", {
453
+ encoding: "utf8",
454
+ stdio: ["ignore", "pipe", "ignore"]
455
+ }).trim();
456
+ } catch {
457
+ branch = execSync("git branch --show-current", {
458
+ encoding: "utf8",
459
+ stdio: ["ignore", "pipe", "ignore"]
460
+ }).trim();
461
+ }
444
462
  const status = execSync("git status --short", {
445
463
  encoding: "utf8",
446
464
  stdio: ["ignore", "pipe", "ignore"]
447
- }).trim();
448
- const log = execSync("git log -3 --oneline 2>/dev/null", {
449
- encoding: "utf8",
450
- stdio: ["ignore", "pipe", "ignore"]
451
- }).trim();
465
+ }).trimEnd();
466
+ let log = "";
467
+ try {
468
+ log = execSync("git log -3 --oneline", {
469
+ encoding: "utf8",
470
+ stdio: ["ignore", "pipe", "ignore"]
471
+ }).trim();
472
+ } catch {
473
+ }
452
474
  console.log(` ${chalk.gray("Current Branch:")} ${chalk.cyan.bold(branch || "Detached / Unknown")}`);
453
475
  if (status.length === 0) {
454
476
  console.log(` ${chalk.gray("Working Tree:")} ${chalk.green("Working directory is clean")}`);
455
477
  } else {
456
- const statusLines = status.split("\n");
478
+ const statusLines = status.split(/\r?\n/).filter(Boolean);
457
479
  console.log(` ${chalk.gray("Modified Files:")} ${chalk.yellow(statusLines.length)} file(s):`);
458
480
  for (const line of statusLines.slice(0, 10)) {
459
- const flag = line.slice(0, 2).trim();
460
- const file = line.slice(3).trim();
481
+ const match = line.match(/^(.{2})\s+(.*)$/);
482
+ const flag = match ? match[1].trim() : "?";
483
+ const file = match ? match[2].trim() : line.trim();
461
484
  const coloredFlag = flag === "M" ? chalk.yellow("M") : flag === "??" ? chalk.green("?") : chalk.cyan(flag);
462
485
  console.log(` ${coloredFlag} ${file}`);
463
486
  }
@@ -479,10 +502,16 @@ function renderGitStatus() {
479
502
  console.log(border + "\n");
480
503
  }
481
504
  function renderDirectoryTree(dirPath = ".", maxDepth = 2) {
505
+ const resolvedRoot = path.resolve(dirPath);
482
506
  const border = chalk.hex("#00A3FF")("\u2500".repeat(70));
483
507
  console.log("\n" + border);
484
- console.log(chalk.bgHex("#1A237E").white.bold(` WORKSPACE TREE: ${path.resolve(dirPath)} `));
508
+ console.log(chalk.bgHex("#1A237E").white.bold(` WORKSPACE TREE: ${resolvedRoot} `));
485
509
  console.log(chalk.dim("\u2500".repeat(70)));
510
+ if (!fs.existsSync(resolvedRoot) || !fs.statSync(resolvedRoot).isDirectory()) {
511
+ console.log(chalk.red(` Directory not found: ${dirPath}`));
512
+ console.log(border + "\n");
513
+ return;
514
+ }
486
515
  const IGNORED = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".cache", "coverage"]);
487
516
  function printTree(currentDir, prefix = "", depth = 0) {
488
517
  if (depth >= maxDepth) return;
@@ -510,7 +539,7 @@ function renderDirectoryTree(dirPath = ".", maxDepth = 2) {
510
539
  }
511
540
  }
512
541
  }
513
- printTree(process.cwd());
542
+ printTree(resolvedRoot);
514
543
  console.log(border + "\n");
515
544
  }
516
545
  function showAbout() {
@@ -522,7 +551,7 @@ function showAbout() {
522
551
  brand(" \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\n") + brand(" \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\n") + brand(" \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\n") + accentGold(" \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\n") + accentGold(" \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\n") + dim(" \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D")
523
552
  );
524
553
  console.log("\n" + chalk.dim("\u2500".repeat(74)));
525
- console.log(` ${chalk.bold.white("Project:")} ${brand("IUB CLI v2.0.0")}`);
554
+ console.log(` ${chalk.bold.white("Project:")} ${brand(`IUB CLI v${getAppVersion()}`)}`);
526
555
  console.log(` ${chalk.bold.white("Description:")} Next-Gen Autonomous AI Terminal Coding Agent`);
527
556
  console.log(` ${chalk.bold.white("Architecture:")} Dual-Engine (BUILD & PLAN Modes) with Workspace Mesh RPC`);
528
557
  console.log(chalk.dim("\u2500".repeat(74)));
@@ -841,13 +870,16 @@ With: ${effectiveReplacement.split("\n").length} line(s) (${effectiveReplacement
841
870
  console.log(chalk2.cyan("Auto-approve enabled for this session."));
842
871
  }
843
872
  }
873
+ if (!normalizedMode && usesCRLF && effectiveReplacement.includes("\n")) {
874
+ effectiveReplacement = effectiveReplacement.replace(/\r?\n/g, "\r\n");
875
+ }
844
876
  const idx = workingContent.indexOf(effectiveTarget);
845
877
  let updatedContent = workingContent.slice(0, idx) + effectiveReplacement + workingContent.slice(idx + effectiveTarget.length);
846
878
  if (normalizedMode && usesCRLF) {
847
879
  updatedContent = updatedContent.replace(/\n/g, "\r\n");
848
880
  }
849
881
  sessionFileHistory.push({
850
- filePath,
882
+ filePath: path2.relative(rootDir, targetFile).replace(/\\/g, "/"),
851
883
  isNew: false,
852
884
  previousContent: content,
853
885
  newContent: updatedContent,
@@ -881,9 +913,16 @@ function splitShellCommands(command) {
881
913
  let current = "";
882
914
  let inDoubleQuote = false;
883
915
  let inSingleQuote = false;
916
+ let parenDepth = 0;
917
+ let braceDepth = 0;
884
918
  for (let i = 0; i < command.length; i++) {
885
919
  const char = command[i];
886
920
  const nextChar = command[i + 1];
921
+ if (char === "\\" && (inDoubleQuote || inSingleQuote) && nextChar !== void 0) {
922
+ current += char + nextChar;
923
+ i++;
924
+ continue;
925
+ }
887
926
  if (char === '"' && !inSingleQuote) {
888
927
  inDoubleQuote = !inDoubleQuote;
889
928
  current += char;
@@ -891,16 +930,24 @@ function splitShellCommands(command) {
891
930
  inSingleQuote = !inSingleQuote;
892
931
  current += char;
893
932
  } else if (!inDoubleQuote && !inSingleQuote) {
894
- if (char === "&" && nextChar === "&") {
895
- if (current.trim()) commands.push(current.trim());
896
- current = "";
897
- i++;
898
- } else if (char === ";" || char === "\n") {
899
- if (current.trim()) commands.push(current.trim());
900
- current = "";
901
- } else {
902
- current += char;
933
+ if (char === "(") parenDepth++;
934
+ else if (char === ")" && parenDepth > 0) parenDepth--;
935
+ else if (char === "{") braceDepth++;
936
+ else if (char === "}" && braceDepth > 0) braceDepth--;
937
+ if (parenDepth === 0 && braceDepth === 0) {
938
+ if (char === "&" && nextChar === "&") {
939
+ if (current.trim()) commands.push(current.trim());
940
+ current = "";
941
+ i++;
942
+ continue;
943
+ }
944
+ if (char === ";" || char === "\n") {
945
+ if (current.trim()) commands.push(current.trim());
946
+ current = "";
947
+ continue;
948
+ }
903
949
  }
950
+ current += char;
904
951
  } else {
905
952
  current += char;
906
953
  }
@@ -910,6 +957,20 @@ function splitShellCommands(command) {
910
957
  }
911
958
  return commands;
912
959
  }
960
+ function parseDirectoryChangeCommand(subCommand, currentCwd) {
961
+ const match = subCommand.trim().match(/^(?:cd|chdir|pushd|Set-Location|sl)\s+(.+)$/i);
962
+ if (!match) return null;
963
+ let target = match[1].trim();
964
+ if (target.startsWith('"') && target.endsWith('"') || target.startsWith("'") && target.endsWith("'")) {
965
+ target = target.slice(1, -1).trim();
966
+ }
967
+ if (!target || target.startsWith("-")) return null;
968
+ const resolved = path2.resolve(currentCwd, target);
969
+ if (fs2.existsSync(resolved) && fs2.statSync(resolved).isDirectory()) {
970
+ return resolved;
971
+ }
972
+ return null;
973
+ }
913
974
  async function executeSequentialCommand(command, signal) {
914
975
  if (!safetySession.autoApproveAll) {
915
976
  const summary = `${chalk2.gray("Shell Command:")} ${chalk2.magenta.bold(command)}
@@ -934,6 +995,7 @@ Continuous Execution: Running ${chalk2.bold(subCommands.length)} commands strict
934
995
  )
935
996
  );
936
997
  const stepResults = [];
998
+ let effectiveCwd = process.cwd();
937
999
  for (let i = 0; i < subCommands.length; i++) {
938
1000
  if (signal?.aborted) {
939
1001
  return "Action aborted by user (Escape).";
@@ -941,7 +1003,14 @@ Continuous Execution: Running ${chalk2.bold(subCommands.length)} commands strict
941
1003
  const sub = subCommands[i];
942
1004
  console.log(chalk2.cyan(`
943
1005
  Step ${i + 1}/${subCommands.length}: ${chalk2.bold(sub)}`));
944
- const res = await runActualProcess(sub, signal);
1006
+ const nextDir = parseDirectoryChangeCommand(sub, effectiveCwd);
1007
+ if (nextDir) {
1008
+ effectiveCwd = nextDir;
1009
+ stepResults.push(`[Step ${i + 1}/${subCommands.length}: ${sub}]
1010
+ Changed working directory to "${effectiveCwd}".`);
1011
+ continue;
1012
+ }
1013
+ const res = await runActualProcess(sub, signal, effectiveCwd);
945
1014
  stepResults.push(`[Step ${i + 1}/${subCommands.length}: ${sub}]
946
1015
  ${res}`);
947
1016
  if (res.includes("Command exited with status code") || res.includes("Command timed out") || res.includes("failed to start")) {
@@ -954,7 +1023,7 @@ Step ${i + 1} exited with error. Stopping subsequent steps immediately.`));
954
1023
  }
955
1024
  console.log(chalk2.cyan(`
956
1025
  Running command: ${chalk2.bold(command)}...`));
957
- return await runActualProcess(command, signal);
1026
+ return await runActualProcess(command, signal, process.cwd());
958
1027
  }
959
1028
  function diagnoseCommandFailure(command, stdout, stderr, code) {
960
1029
  const combined = stdout + "\n" + stderr;
@@ -982,7 +1051,29 @@ function diagnoseCommandFailure(command, stdout, stderr, code) {
982
1051
  }
983
1052
  return null;
984
1053
  }
985
- function runActualProcess(command, signal) {
1054
+ function terminateChildTree(child) {
1055
+ try {
1056
+ if (process.platform === "win32" && child.pid) {
1057
+ const killer = spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
1058
+ stdio: "ignore",
1059
+ windowsHide: true
1060
+ });
1061
+ killer.on("error", () => {
1062
+ });
1063
+ } else {
1064
+ child.kill("SIGTERM");
1065
+ }
1066
+ } catch {
1067
+ try {
1068
+ child.kill();
1069
+ } catch {
1070
+ }
1071
+ }
1072
+ }
1073
+ function runActualProcess(command, signal, cwd = process.cwd()) {
1074
+ if (signal?.aborted) {
1075
+ return Promise.resolve("Command aborted by user (Escape).");
1076
+ }
986
1077
  return new Promise((resolve) => {
987
1078
  const isWindows = process.platform === "win32";
988
1079
  let sanitizedCommand = command;
@@ -1000,7 +1091,7 @@ function runActualProcess(command, signal) {
1000
1091
  shellArgs = ["-c", sanitizedCommand];
1001
1092
  }
1002
1093
  const child = spawn(shellProgram, shellArgs, {
1003
- cwd: process.cwd(),
1094
+ cwd,
1004
1095
  stdio: ["ignore", "pipe", "pipe"],
1005
1096
  env: {
1006
1097
  ...process.env,
@@ -1011,25 +1102,33 @@ function runActualProcess(command, signal) {
1011
1102
  DEBIAN_FRONTEND: "noninteractive"
1012
1103
  }
1013
1104
  });
1014
- if (signal) {
1015
- signal.addEventListener("abort", () => {
1016
- try {
1017
- child.kill("SIGTERM");
1018
- } catch {
1019
- }
1020
- resolve("Command aborted by user (Escape).");
1021
- });
1022
- }
1105
+ let settled = false;
1023
1106
  let stdout = "";
1024
1107
  let stderr = "";
1025
1108
  let isTimedOut = false;
1109
+ const cleanup = () => {
1110
+ clearTimeout(timer);
1111
+ if (signal) {
1112
+ signal.removeEventListener("abort", onAbort);
1113
+ }
1114
+ };
1115
+ const finish = (output) => {
1116
+ if (settled) return;
1117
+ settled = true;
1118
+ cleanup();
1119
+ resolve(output);
1120
+ };
1121
+ const onAbort = () => {
1122
+ terminateChildTree(child);
1123
+ finish("Command aborted by user (Escape).");
1124
+ };
1125
+ if (signal) {
1126
+ signal.addEventListener("abort", onAbort, { once: true });
1127
+ }
1026
1128
  const timeoutMs = 18e4;
1027
1129
  const timer = setTimeout(() => {
1028
1130
  isTimedOut = true;
1029
- try {
1030
- child.kill("SIGTERM");
1031
- } catch {
1032
- }
1131
+ terminateChildTree(child);
1033
1132
  }, timeoutMs);
1034
1133
  child.stdout.on("data", (data) => {
1035
1134
  if (stdout.length < 20 * 1024 * 1024) {
@@ -1042,13 +1141,11 @@ function runActualProcess(command, signal) {
1042
1141
  }
1043
1142
  });
1044
1143
  child.on("error", (err) => {
1045
- clearTimeout(timer);
1046
- resolve(`Command failed to start: ${err.message}`);
1144
+ finish(`Command failed to start: ${err.message}`);
1047
1145
  });
1048
1146
  child.on("close", (code) => {
1049
- clearTimeout(timer);
1050
1147
  if (isTimedOut) {
1051
- resolve(`Command timed out after ${timeoutMs / 1e3} seconds.`);
1148
+ finish(`Command timed out after ${timeoutMs / 1e3} seconds.`);
1052
1149
  return;
1053
1150
  }
1054
1151
  const capOutput = (raw, maxChars = 15e3) => {
@@ -1079,13 +1176,43 @@ ${capOutput(stderr)}`);
1079
1176
  }
1080
1177
  }
1081
1178
  if (outputParts.length === 0) {
1082
- resolve(`Command executed successfully with no output (exit code 0).`);
1179
+ finish(`Command executed successfully with no output (exit code 0).`);
1083
1180
  return;
1084
1181
  }
1085
- resolve(outputParts.join("\n\n"));
1182
+ finish(outputParts.join("\n\n"));
1086
1183
  });
1087
1184
  });
1088
1185
  }
1186
+ function globToRegExp(pattern) {
1187
+ const normalized = pattern.replace(/\\/g, "/").trim();
1188
+ let regexStr = "^";
1189
+ let i = 0;
1190
+ while (i < normalized.length) {
1191
+ const ch = normalized[i];
1192
+ if (ch === "*") {
1193
+ if (normalized[i + 1] === "*") {
1194
+ if (normalized[i + 2] === "/") {
1195
+ regexStr += "(?:.*/)?";
1196
+ i += 3;
1197
+ } else {
1198
+ regexStr += ".*";
1199
+ i += 2;
1200
+ }
1201
+ } else {
1202
+ regexStr += normalized.includes("/") ? "[^/]*" : ".*";
1203
+ i++;
1204
+ }
1205
+ } else if (ch === "?") {
1206
+ regexStr += "[^/]";
1207
+ i++;
1208
+ } else {
1209
+ regexStr += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1210
+ i++;
1211
+ }
1212
+ }
1213
+ regexStr += "$";
1214
+ return new RegExp(regexStr, "i");
1215
+ }
1089
1216
  async function grepSearch(query, filePattern, maxMatches = 50) {
1090
1217
  const rootDir = process.cwd();
1091
1218
  const matches = [];
@@ -1095,7 +1222,7 @@ async function grepSearch(query, filePattern, maxMatches = 50) {
1095
1222
  } catch {
1096
1223
  re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
1097
1224
  }
1098
- const patternFilter = filePattern ? new RegExp(filePattern.replace(/\./g, "\\.").replace(/\*/g, ".*"), "i") : null;
1225
+ const patternFilter = filePattern ? globToRegExp(filePattern) : null;
1099
1226
  function walk(dir) {
1100
1227
  if (matches.length >= maxMatches) return;
1101
1228
  let entries = [];
@@ -1112,7 +1239,7 @@ async function grepSearch(query, filePattern, maxMatches = 50) {
1112
1239
  if (entry.isDirectory()) {
1113
1240
  walk(fullPath);
1114
1241
  } else if (entry.isFile()) {
1115
- if (patternFilter && !patternFilter.test(relPath)) continue;
1242
+ if (patternFilter && !patternFilter.test(relPath) && !patternFilter.test(entry.name)) continue;
1116
1243
  const ext = path2.extname(entry.name).toLowerCase();
1117
1244
  if ([".png", ".jpg", ".jpeg", ".gif", ".zip", ".tar", ".gz", ".ico", ".pdf", ".exe", ".dll", ".bin"].includes(ext)) {
1118
1245
  continue;
@@ -1144,7 +1271,7 @@ async function grepSearch(query, filePattern, maxMatches = 50) {
1144
1271
  async function findFiles(pattern, maxResults = 50) {
1145
1272
  const rootDir = process.cwd();
1146
1273
  const results = [];
1147
- const regex = new RegExp(pattern.replace(/\./g, "\\.").replace(/\*/g, ".*"), "i");
1274
+ const regex = globToRegExp(pattern);
1148
1275
  function walk(dir) {
1149
1276
  if (results.length >= maxResults) return;
1150
1277
  let entries = [];
@@ -1175,17 +1302,19 @@ async function findFiles(pattern, maxResults = 50) {
1175
1302
  ` + results.join("\n");
1176
1303
  }
1177
1304
  async function fetchUrl(targetUrl) {
1305
+ if (typeof targetUrl !== "string" || !/^https?:\/\//i.test(targetUrl.trim())) {
1306
+ return `Error: Invalid URL "${targetUrl}". URL must start with http:// or https://.`;
1307
+ }
1308
+ const controller = new AbortController();
1309
+ const timeout = setTimeout(() => controller.abort(), 8e3);
1178
1310
  try {
1179
- const controller = new AbortController();
1180
- const timeout = setTimeout(() => controller.abort(), 8e3);
1181
- const res = await fetch(targetUrl, {
1311
+ const res = await fetch(targetUrl.trim(), {
1182
1312
  signal: controller.signal,
1183
1313
  headers: {
1184
1314
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) iubcli/2.0",
1185
1315
  "Accept": "text/html,application/xhtml+xml,application/json,text/plain;q=0.9"
1186
1316
  }
1187
1317
  });
1188
- clearTimeout(timeout);
1189
1318
  if (!res.ok) {
1190
1319
  return `HTTP error ${res.status}: ${res.statusText}`;
1191
1320
  }
@@ -1194,19 +1323,21 @@ async function fetchUrl(targetUrl) {
1194
1323
  if (contentType.includes("application/json")) {
1195
1324
  return rawText.slice(0, 3e4);
1196
1325
  }
1197
- const cleanText = rawText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1326
+ const cleanText = rawText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'").replace(/\s+/g, " ").trim();
1198
1327
  const truncated = cleanText.slice(0, 25e3);
1199
1328
  return `[Fetched Content from ${targetUrl} (${truncated.length} chars)]:
1200
1329
 
1201
1330
  ${truncated}`;
1202
1331
  } catch (err) {
1203
1332
  return `Failed to fetch URL "${targetUrl}": ${err.message}`;
1333
+ } finally {
1334
+ clearTimeout(timeout);
1204
1335
  }
1205
1336
  }
1206
1337
  async function webSearch(query) {
1338
+ const controller = new AbortController();
1339
+ const timeout = setTimeout(() => controller.abort(), 8e3);
1207
1340
  try {
1208
- const controller = new AbortController();
1209
- const timeout = setTimeout(() => controller.abort(), 8e3);
1210
1341
  const apiUrl = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`;
1211
1342
  const res = await fetch(apiUrl, {
1212
1343
  signal: controller.signal,
@@ -1252,13 +1383,16 @@ async function webSearch(query) {
1252
1383
  return await fetchUrl(ddgHtmlUrl);
1253
1384
  } catch (err) {
1254
1385
  return `Failed to perform web search for "${query}": ${err.message}`;
1386
+ } finally {
1387
+ clearTimeout(timeout);
1255
1388
  }
1256
1389
  }
1257
1390
  async function executeTool(name, args, mode = "build", signal) {
1258
1391
  if (signal?.aborted) {
1259
1392
  return "Action aborted by user (Escape).";
1260
1393
  }
1261
- if (mode === "plan" && (name === "write_file" || name === "edit_file" || name === "run_command")) {
1394
+ const isMutatingPeerCall = name === "peer_call_tool" && ["write_file", "edit_file", "run_command"].includes(String(args?.tool || ""));
1395
+ if (mode === "plan" && (name === "write_file" || name === "edit_file" || name === "run_command" || isMutatingPeerCall)) {
1262
1396
  const errorMsg = `Action blocked: IUB CLI is currently in PLAN MODE. File modifications and terminal commands are disabled. Switch to BUILD mode (/build or /mode) to execute changes.`;
1263
1397
  renderToolCall(name, args);
1264
1398
  renderToolResult(name, errorMsg, true);
@@ -1322,7 +1456,18 @@ async function executeTool(name, args, mode = "build", signal) {
1322
1456
  } else {
1323
1457
  const targetPeer = args.peer;
1324
1458
  const targetTool = args.tool;
1325
- const targetArgs = typeof args.args === "string" ? JSON.parse(args.args) : args.args || {};
1459
+ let targetArgs = {};
1460
+ if (typeof args.args === "string") {
1461
+ try {
1462
+ targetArgs = JSON.parse(args.args);
1463
+ } catch (parseErr) {
1464
+ result = `Error: Invalid JSON in peer_call_tool "args": ${parseErr.message}`;
1465
+ isError = true;
1466
+ break;
1467
+ }
1468
+ } else {
1469
+ targetArgs = args.args || {};
1470
+ }
1326
1471
  result = await activeMeshNode.callRemoteTool(targetPeer, targetTool, targetArgs);
1327
1472
  }
1328
1473
  break;
@@ -2034,7 +2179,7 @@ function renderBottomBorder(width, borderColor, customHint) {
2034
2179
  const dashesCount = Math.max(1, width - prefixWidth - hintWidth - suffixWidth);
2035
2180
  return borderColor("\u2570\u2500\u2500 ") + (hintText ? chalk4.gray(hintText) : "") + borderColor("\u2500".repeat(dashesCount)) + borderColor("\u2500\u2500\u256F");
2036
2181
  }
2037
- function renderContentLine(width, lineText, isFirst, isBuild, borderColor) {
2182
+ function renderContentLine(width, lineText, isFirst, isBuild, borderColor, cursorCol) {
2038
2183
  const promptArrow = isFirst ? isBuild ? chalk4.hex("#00A3FF").bold("\u276F ") : chalk4.hex("#FFB300").bold("\u276F ") : chalk4.dim("\xB7 ");
2039
2184
  const prefix = borderColor("\u2502 ") + promptArrow;
2040
2185
  const prefixWidth = 4;
@@ -2042,8 +2187,22 @@ function renderContentLine(width, lineText, isFirst, isBuild, borderColor) {
2042
2187
  const suffixWidth = 2;
2043
2188
  const textCapacity = Math.max(1, width - prefixWidth - suffixWidth);
2044
2189
  let visibleText = lineText;
2045
- while (stringWidth(visibleText) > textCapacity && visibleText.length > 0) {
2046
- visibleText = visibleText.slice(1);
2190
+ if (stringWidth(visibleText) > textCapacity) {
2191
+ if (cursorCol !== void 0 && cursorCol < lineText.length) {
2192
+ let start = 0;
2193
+ while (start < cursorCol && stringWidth(lineText.slice(start, cursorCol)) > textCapacity - 2) {
2194
+ start++;
2195
+ }
2196
+ let end = lineText.length;
2197
+ while (end > cursorCol && stringWidth(lineText.slice(start, end)) > textCapacity) {
2198
+ end--;
2199
+ }
2200
+ visibleText = lineText.slice(start, end);
2201
+ } else {
2202
+ while (stringWidth(visibleText) > textCapacity && visibleText.length > 0) {
2203
+ visibleText = visibleText.slice(1);
2204
+ }
2205
+ }
2047
2206
  }
2048
2207
  const textWidth = stringWidth(visibleText);
2049
2208
  const paddingSpaces = Math.max(0, width - prefixWidth - suffixWidth - textWidth);
@@ -2073,7 +2232,10 @@ function renderStatusLine(width, statusText, borderColor) {
2073
2232
  }
2074
2233
  function restoreTerminalViewport() {
2075
2234
  try {
2076
- process.stdout.write("\x1B[r\x1B[?25h");
2235
+ process.stdout.write("\x1B[r\x1B[?2004l\x1B[?25h");
2236
+ if (process.stdin.isTTY && process.stdin.isRaw) {
2237
+ process.stdin.setRawMode(false);
2238
+ }
2077
2239
  } catch {
2078
2240
  }
2079
2241
  }
@@ -2177,9 +2339,10 @@ async function interactiveSelect(config) {
2177
2339
  process.stdout.write("\x1B[?25l");
2178
2340
  let termRows = process.stdout.rows || 24;
2179
2341
  let termCols = process.stdout.columns || 80;
2180
- const maxVisible = Math.max(3, Math.min(config.maxItems || 8, config.options.length, termRows - 10));
2342
+ const getMaxVisible = () => Math.max(3, Math.min(config.maxItems || 8, config.options.length, termRows - 10));
2181
2343
  let scrollOffset = 0;
2182
2344
  const updateScroll = () => {
2345
+ const maxVisible = getMaxVisible();
2183
2346
  if (cursor < scrollOffset) {
2184
2347
  scrollOffset = cursor;
2185
2348
  } else if (cursor >= scrollOffset + maxVisible) {
@@ -2188,6 +2351,7 @@ async function interactiveSelect(config) {
2188
2351
  };
2189
2352
  const renderFrame = () => {
2190
2353
  updateScroll();
2354
+ const maxVisible = getMaxVisible();
2191
2355
  const safeWidth = Math.max(40, termCols - 4);
2192
2356
  const lines = [];
2193
2357
  lines.push(truncateWithAnsi(chalk4.cyan.bold("\u25C6 ") + chalk4.bold.white(config.message), safeWidth));
@@ -2306,13 +2470,13 @@ async function interactiveSelect(config) {
2306
2470
  continue;
2307
2471
  }
2308
2472
  if (rest.startsWith("\x1B[5~")) {
2309
- cursor = Math.max(0, cursor - maxVisible);
2473
+ cursor = Math.max(0, cursor - getMaxVisible());
2310
2474
  idx += 4;
2311
2475
  dirty = true;
2312
2476
  continue;
2313
2477
  }
2314
2478
  if (rest.startsWith("\x1B[6~")) {
2315
- cursor = Math.min(config.options.length - 1, cursor + maxVisible);
2479
+ cursor = Math.min(config.options.length - 1, cursor + getMaxVisible());
2316
2480
  idx += 4;
2317
2481
  dirty = true;
2318
2482
  continue;
@@ -2755,7 +2919,14 @@ async function readInlinePrompt(options) {
2755
2919
  let historyIdx = -1;
2756
2920
  let savedDraft = "";
2757
2921
  const boxWidth = getSafeBoxWidth();
2922
+ const textCapacity = Math.max(1, boxWidth - 6);
2758
2923
  const hintText = "\xB7 Shift+Enter: newline \u2022 /help for commands \u2022 \u2191/\u2193: history";
2924
+ const getActiveCol = () => {
2925
+ const line = bufferLines[cursorLine] || "";
2926
+ const beforeCursor = line.slice(0, cursorCol);
2927
+ const beforeWidth = stringWidth(beforeCursor);
2928
+ return 5 + Math.min(beforeWidth, textCapacity);
2929
+ };
2759
2930
  process.stdout.write(renderTopBorder(boxWidth, isBuildMode, options.model, borderColor) + "\n");
2760
2931
  process.stdout.write(renderContentLine(boxWidth, "", true, isBuildMode, borderColor) + "\n");
2761
2932
  process.stdout.write(renderHintLine(boxWidth, hintText, borderColor) + "\n");
@@ -2767,10 +2938,10 @@ async function readInlinePrompt(options) {
2767
2938
  bufferLines[cursorLine],
2768
2939
  cursorLine === 0,
2769
2940
  isBuildMode,
2770
- borderColor
2941
+ borderColor,
2942
+ cursorCol
2771
2943
  );
2772
- const activeCol = 5 + Math.min(cursorCol, boxWidth - 8);
2773
- process.stdout.write(`\r${lineStr}\r\x1B[${activeCol}G`);
2944
+ process.stdout.write(`\r${lineStr}\r\x1B[${getActiveCol()}G`);
2774
2945
  };
2775
2946
  const redrawFrom = (startLine) => {
2776
2947
  if (cursorLine > startLine) {
@@ -2778,15 +2949,23 @@ async function readInlinePrompt(options) {
2778
2949
  }
2779
2950
  const lines = [];
2780
2951
  for (let i = startLine; i < bufferLines.length; i++) {
2781
- lines.push(renderContentLine(boxWidth, bufferLines[i], i === 0, isBuildMode, borderColor));
2952
+ lines.push(
2953
+ renderContentLine(
2954
+ boxWidth,
2955
+ bufferLines[i],
2956
+ i === 0,
2957
+ isBuildMode,
2958
+ borderColor,
2959
+ i === cursorLine ? cursorCol : void 0
2960
+ )
2961
+ );
2782
2962
  }
2783
2963
  lines.push(renderHintLine(boxWidth, hintText, borderColor));
2784
2964
  lines.push(renderBottomBorder(boxWidth, borderColor));
2785
2965
  process.stdout.write("\r\x1B[J");
2786
2966
  process.stdout.write(lines.join("\n"));
2787
2967
  const linesUp = lines.length - 1 - (cursorLine - startLine);
2788
- const activeCol = 5 + Math.min(cursorCol, boxWidth - 8);
2789
- process.stdout.write(`\x1B[${linesUp}A\r\x1B[${activeCol}G`);
2968
+ process.stdout.write(`\x1B[${linesUp}A\r\x1B[${getActiveCol()}G`);
2790
2969
  };
2791
2970
  const cleanup = () => {
2792
2971
  _dockedPromptActive = false;
@@ -2896,165 +3075,239 @@ async function readInlinePrompt(options) {
2896
3075
  handlePastedText(str);
2897
3076
  return;
2898
3077
  }
2899
- if (str === "") {
2900
- cleanup();
2901
- const down = bufferLines.length - cursorLine;
2902
- process.stdout.write(`\x1B[${down}B\r
2903
- `);
2904
- process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
2905
- process.exit(0);
2906
- }
2907
- if (str === " " || str === " " || str === "\x1BOQ" || str === "\x1B[12~") {
2908
- cleanup();
2909
- const linesUpToTop = cursorLine + 1;
2910
- process.stdout.write(`\x1B[${linesUpToTop}A\r\x1B[J`);
2911
- resolve("/model");
2912
- return;
2913
- }
2914
- if (str === "") {
2915
- if (bufferLines.join("").length === 0) {
3078
+ let idx = 0;
3079
+ while (idx < str.length) {
3080
+ const rest = str.slice(idx);
3081
+ if (rest.startsWith("")) {
2916
3082
  cleanup();
3083
+ const down = bufferLines.length - 1 - cursorLine + 2;
3084
+ process.stdout.write(`\x1B[${down}B\r
3085
+ `);
2917
3086
  process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
2918
3087
  process.exit(0);
2919
3088
  }
2920
- }
2921
- if (str === "\x1B") {
2922
- cancel();
2923
- return;
2924
- }
2925
- if (str === "\n" || str === "\x1B\r" || str === "\x1B\r" || str === "\x1B[13;2u" || str === "\x1B[13;5u") {
2926
- const cur = bufferLines[cursorLine];
2927
- const prevLine = cursorLine;
2928
- bufferLines[cursorLine] = cur.slice(0, cursorCol);
2929
- bufferLines.splice(cursorLine + 1, 0, cur.slice(cursorCol));
2930
- cursorLine++;
2931
- cursorCol = 0;
2932
- redrawFrom(prevLine);
2933
- return;
2934
- }
2935
- if (str === "\r" || str === "\n" || str === "\r\n" || str === "\x1BOM" || str === "\x1B[13~") {
2936
- if (bufferLines.join("\n").trim().length === 0) return;
2937
- submit();
2938
- return;
2939
- }
2940
- if (str === "\b" || str === "\x7F") {
2941
- if (cursorCol > 0) {
2942
- const cur = bufferLines[cursorLine];
2943
- bufferLines[cursorLine] = cur.slice(0, cursorCol - 1) + cur.slice(cursorCol);
2944
- cursorCol--;
3089
+ if (rest.startsWith(" ") || rest.startsWith("\x1BOQ") || rest.startsWith("\x1B[12~")) {
3090
+ cleanup();
3091
+ const linesUpToTop = cursorLine + 1;
3092
+ process.stdout.write(`\x1B[${linesUpToTop}A\r\x1B[J`);
3093
+ resolve("/model");
3094
+ return;
3095
+ }
3096
+ if (rest.startsWith("")) {
3097
+ if (bufferLines.join("").length === 0) {
3098
+ cleanup();
3099
+ const down = bufferLines.length - 1 - cursorLine + 2;
3100
+ process.stdout.write(`\x1B[${down}B\r
3101
+ `);
3102
+ process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
3103
+ process.exit(0);
3104
+ }
3105
+ idx += 1;
3106
+ continue;
3107
+ }
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();
3123
+ return;
3124
+ }
3125
+ idx += 2;
3126
+ continue;
3127
+ }
3128
+ if (rest.startsWith("\r") || rest.startsWith("\x1BOM") || rest.startsWith("\x1B[13~")) {
3129
+ if (bufferLines.join("\n").trim().length > 0) {
3130
+ submit();
3131
+ return;
3132
+ }
3133
+ idx += rest.startsWith("\r") ? 1 : rest.startsWith("\x1BOM") ? 3 : 5;
3134
+ continue;
3135
+ }
3136
+ if (rest.startsWith("") || rest.startsWith("\x1B[H") || rest.startsWith("\x1B[1~") || rest.startsWith("\x1BOH")) {
3137
+ cursorCol = 0;
2945
3138
  updateActiveLine();
2946
- } else if (cursorLine > 0) {
2947
- const cur = bufferLines[cursorLine];
2948
- const prev = bufferLines[cursorLine - 1];
2949
- cursorCol = prev.length;
2950
- bufferLines[cursorLine - 1] = prev + cur;
2951
- bufferLines.splice(cursorLine, 1);
2952
- cursorLine--;
2953
- process.stdout.write("\x1B[1A");
2954
- redrawFrom(cursorLine);
3139
+ idx += rest.startsWith("") ? 1 : rest.startsWith("\x1B[1~") ? 4 : 3;
3140
+ continue;
2955
3141
  }
2956
- return;
2957
- }
2958
- if (str === "\x1B[D" || str === "\x1BOD") {
2959
- if (cursorCol > 0) {
2960
- cursorCol--;
2961
- process.stdout.write(`\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
2962
- } else if (cursorLine > 0) {
2963
- cursorLine--;
3142
+ if (rest.startsWith("") || rest.startsWith("\x1B[F") || rest.startsWith("\x1B[4~") || rest.startsWith("\x1BOF")) {
2964
3143
  cursorCol = bufferLines[cursorLine].length;
2965
- process.stdout.write(`\x1B[1A\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
3144
+ updateActiveLine();
3145
+ idx += rest.startsWith("") ? 1 : rest.startsWith("\x1B[4~") ? 4 : 3;
3146
+ continue;
2966
3147
  }
2967
- return;
2968
- }
2969
- if (str === "\x1B[C" || str === "\x1BOC") {
2970
- if (cursorCol < bufferLines[cursorLine].length) {
2971
- cursorCol++;
2972
- process.stdout.write(`\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
2973
- } else if (cursorLine < bufferLines.length - 1) {
2974
- cursorLine++;
3148
+ if (rest.startsWith("")) {
3149
+ bufferLines[cursorLine] = "";
2975
3150
  cursorCol = 0;
2976
- process.stdout.write("\x1B[1B\x1B[5G");
3151
+ updateActiveLine();
3152
+ idx += 1;
3153
+ continue;
2977
3154
  }
2978
- return;
2979
- }
2980
- if (str === "\x1B[A" || str === "\x1BOA" || str === "") {
2981
- if (cursorLine > 0) {
2982
- cursorLine--;
2983
- cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
2984
- process.stdout.write(`\x1B[1A\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
2985
- return;
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
+ }
3184
+ idx += 1;
3185
+ continue;
3186
+ }
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;
2986
3233
  }
2987
- if (_commandHistory.length > 0) {
2988
- if (historyIdx === -1) savedDraft = bufferLines.join("\n");
2989
- if (historyIdx < _commandHistory.length - 1) {
2990
- historyIdx++;
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--;
2991
3243
  const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
2992
3244
  bufferLines = histItem.split("\n");
2993
- cursorLine = bufferLines.length - 1;
2994
- cursorCol = bufferLines[cursorLine].length;
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;
2995
3253
  redrawFrom(0);
2996
3254
  }
3255
+ idx += seqLen;
3256
+ continue;
2997
3257
  }
2998
- return;
2999
- }
3000
- if (str === "\x1B[B" || str === "\x1BOB" || str === "") {
3001
- if (cursorLine < bufferLines.length - 1) {
3002
- cursorLine++;
3003
- cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
3004
- process.stdout.write(`\x1B[1B\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
3005
- return;
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;
3006
3269
  }
3007
- if (historyIdx > 0) {
3008
- historyIdx--;
3009
- const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
3010
- bufferLines = histItem.split("\n");
3011
- cursorLine = 0;
3012
- cursorCol = bufferLines[0].length;
3013
- redrawFrom(0);
3014
- } else if (historyIdx === 0) {
3015
- historyIdx = -1;
3016
- bufferLines = savedDraft.split("\n");
3017
- cursorLine = 0;
3018
- cursorCol = bufferLines[0].length;
3019
- redrawFrom(0);
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;
3279
+ continue;
3020
3280
  }
3021
- return;
3022
- }
3023
- if (str === "\x1B[5~") {
3024
- if (_commandHistory.length > 0) {
3025
- if (historyIdx === -1) savedDraft = bufferLines.join("\n");
3026
- historyIdx = _commandHistory.length - 1;
3027
- bufferLines = _commandHistory[0].split("\n");
3028
- cursorLine = 0;
3029
- cursorCol = bufferLines[0].length;
3030
- redrawFrom(0);
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
+ }
3291
+ idx += 1;
3292
+ continue;
3031
3293
  }
3032
- return;
3033
- }
3034
- if (str === "\x1B[6~") {
3035
- if (historyIdx !== -1) {
3036
- historyIdx = -1;
3037
- bufferLines = savedDraft.split("\n");
3038
- cursorLine = 0;
3039
- cursorCol = bufferLines[0].length;
3040
- redrawFrom(0);
3294
+ const code = rest.charCodeAt(0);
3295
+ if (code < 32 || code === 127) {
3296
+ idx += 1;
3297
+ continue;
3041
3298
  }
3042
- return;
3043
- }
3044
- if (str.startsWith("\x1B[")) return;
3045
- if (str.length === 1 && str.charCodeAt(0) >= 32) {
3046
- const cur = bufferLines[cursorLine];
3047
- bufferLines[cursorLine] = cur.slice(0, cursorCol) + str + cur.slice(cursorCol);
3048
- cursorCol++;
3049
- updateActiveLine();
3050
- return;
3051
- }
3052
- if (str.length > 0 && !str.includes("\x1B")) {
3299
+ let printableEnd = idx + 1;
3300
+ while (printableEnd < str.length) {
3301
+ const c = str.charCodeAt(printableEnd);
3302
+ if (c < 32 || c === 127) break;
3303
+ printableEnd++;
3304
+ }
3305
+ const chunk = str.slice(idx, printableEnd);
3053
3306
  const cur = bufferLines[cursorLine];
3054
- bufferLines[cursorLine] = cur.slice(0, cursorCol) + str + cur.slice(cursorCol);
3055
- cursorCol += str.length;
3307
+ bufferLines[cursorLine] = cur.slice(0, cursorCol) + chunk + cur.slice(cursorCol);
3308
+ cursorCol += chunk.length;
3056
3309
  updateActiveLine();
3057
- return;
3310
+ idx = printableEnd;
3058
3311
  }
3059
3312
  };
3060
3313
  process.stdin.on("data", onData);
@@ -3069,11 +3322,14 @@ async function expandOpenCodeMentions(rawPrompt) {
3069
3322
  const contexts = [];
3070
3323
  const urlRegex = /(?:@)?(https?:\/\/[^\s"'<>]+)/g;
3071
3324
  const urlMatches = Array.from(rawPrompt.matchAll(urlRegex));
3325
+ const seenUrls = /* @__PURE__ */ new Set();
3072
3326
  for (const match of urlMatches) {
3073
- const targetUrl = match[1];
3327
+ const targetUrl = match[1].replace(/[.,;:!?)]+$/, "");
3328
+ if (!targetUrl || seenUrls.has(targetUrl)) continue;
3329
+ seenUrls.add(targetUrl);
3330
+ const controller = new AbortController();
3331
+ const timeout = setTimeout(() => controller.abort(), 6e3);
3074
3332
  try {
3075
- const controller = new AbortController();
3076
- const timeout = setTimeout(() => controller.abort(), 6e3);
3077
3333
  const res = await fetch(targetUrl, {
3078
3334
  signal: controller.signal,
3079
3335
  headers: {
@@ -3081,7 +3337,6 @@ async function expandOpenCodeMentions(rawPrompt) {
3081
3337
  Accept: "text/html,application/xhtml+xml,application/json,text/plain;q=0.9"
3082
3338
  }
3083
3339
  });
3084
- clearTimeout(timeout);
3085
3340
  if (res.ok) {
3086
3341
  const contentType = res.headers.get("content-type") || "";
3087
3342
  const rawBody = await res.text();
@@ -3098,15 +3353,20 @@ async function expandOpenCodeMentions(rawPrompt) {
3098
3353
  attachedFiles.push(`web:${targetUrl.slice(0, 45)}...`);
3099
3354
  }
3100
3355
  } catch {
3356
+ } finally {
3357
+ clearTimeout(timeout);
3101
3358
  }
3102
3359
  }
3103
- const fileRegex = /@([a-zA-Z0-9_\-\.\/\\]+)/g;
3360
+ const fileRegex = /(?:^|\s)@([a-zA-Z0-9_\-\.\/\\]+)/g;
3104
3361
  const fileMatches = Array.from(rawPrompt.matchAll(fileRegex));
3362
+ const seenPaths = /* @__PURE__ */ new Set();
3105
3363
  for (const match of fileMatches) {
3106
3364
  const rawPath = match[1];
3107
3365
  if (rawPath.startsWith("http://") || rawPath.startsWith("https://")) continue;
3108
3366
  const resolvedPath = path4.resolve(process.cwd(), rawPath);
3367
+ if (seenPaths.has(resolvedPath)) continue;
3109
3368
  if (fs4.existsSync(resolvedPath)) {
3369
+ seenPaths.add(resolvedPath);
3110
3370
  const stat = fs4.statSync(resolvedPath);
3111
3371
  if (stat.isFile()) {
3112
3372
  if (isImageFile(resolvedPath)) {
@@ -3181,6 +3441,27 @@ async function expandOpenCodeMentions(rawPrompt) {
3181
3441
 
3182
3442
  // src/config.ts
3183
3443
  import chalk5 from "chalk";
3444
+ var _cachedAppVersion = null;
3445
+ function getAppVersion() {
3446
+ if (_cachedAppVersion) return _cachedAppVersion;
3447
+ try {
3448
+ const here = path5.dirname(fileURLToPath(import.meta.url));
3449
+ for (const rel of ["../package.json", "../../package.json"]) {
3450
+ const candidate = path5.resolve(here, rel);
3451
+ if (fs5.existsSync(candidate)) {
3452
+ const pkg = JSON.parse(fs5.readFileSync(candidate, "utf8"));
3453
+ if (typeof pkg?.version === "string" && pkg.version.trim()) {
3454
+ const ver = pkg.version.trim();
3455
+ _cachedAppVersion = ver;
3456
+ return ver;
3457
+ }
3458
+ }
3459
+ }
3460
+ } catch {
3461
+ }
3462
+ _cachedAppVersion = "4.2.10";
3463
+ return _cachedAppVersion;
3464
+ }
3184
3465
  var configStore = new Conf2({
3185
3466
  projectName: "iubcli"
3186
3467
  });
@@ -3275,14 +3556,14 @@ async function detectLocalOllamaModels(timeoutMs = 700) {
3275
3556
  const timer = setTimeout(() => controller.abort(), timeoutMs);
3276
3557
  try {
3277
3558
  const res = await fetch("http://127.0.0.1:11434/api/tags", { signal: controller.signal });
3278
- clearTimeout(timer);
3279
3559
  if (!res.ok) return [];
3280
3560
  const data = await res.json();
3281
3561
  const models = Array.isArray(data?.models) ? data.models.map((m) => String(m?.name || m?.model || "").trim()).filter(Boolean) : [];
3282
3562
  return models;
3283
3563
  } catch {
3284
- clearTimeout(timer);
3285
3564
  return [];
3565
+ } finally {
3566
+ clearTimeout(timer);
3286
3567
  }
3287
3568
  }
3288
3569
  function sanitizeApiKeyInput(raw) {
@@ -3458,11 +3739,20 @@ function saveConfig(config) {
3458
3739
  if (config.provider === "gemini") {
3459
3740
  delete config.baseURL;
3460
3741
  }
3461
- config.savedProviders[config.provider] = {
3462
- apiKey: config.apiKey,
3463
- model: config.model,
3464
- ...config.baseURL ? { baseURL: config.baseURL } : {}
3465
- };
3742
+ const existingCustom = config.savedProviders.custom;
3743
+ const incomingIsKeylessCustom = config.provider === "custom" && Boolean(
3744
+ config.baseURL && (config.baseURL.includes("pollinations.ai") || config.baseURL.includes("localhost") || config.baseURL.includes("127.0.0.1"))
3745
+ );
3746
+ const existingCustomIsRealKey = Boolean(
3747
+ existingCustom?.apiKey && existingCustom.apiKey !== POLLINATIONS_FREE_API_KEY && existingCustom.apiKey !== "ollama" && !existingCustom.baseURL?.includes("pollinations.ai")
3748
+ );
3749
+ if (!(incomingIsKeylessCustom && existingCustomIsRealKey)) {
3750
+ config.savedProviders[config.provider] = {
3751
+ apiKey: config.apiKey,
3752
+ model: config.model,
3753
+ ...config.baseURL ? { baseURL: config.baseURL } : {}
3754
+ };
3755
+ }
3466
3756
  configStore.set("config", config);
3467
3757
  }
3468
3758
  function printSetupHeader(title, subtitle) {
@@ -4036,7 +4326,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4036
4326
  console.log(chalk5.yellow("Setup cancelled.\n"));
4037
4327
  process.exit(0);
4038
4328
  }
4039
- return existingConfig;
4329
+ return existingConfig ?? null;
4040
4330
  }
4041
4331
  if (choice === "free_starter") {
4042
4332
  const zeroConfig = createZeroKeyConfig(existingConfig);
@@ -4056,7 +4346,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4056
4346
  console.log(chalk5.yellow("Setup cancelled.\n"));
4057
4347
  process.exit(0);
4058
4348
  }
4059
- return existingConfig;
4349
+ return existingConfig ?? null;
4060
4350
  }
4061
4351
  const ollamaConfig = {
4062
4352
  provider: "custom",
@@ -4092,7 +4382,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4092
4382
  ]
4093
4383
  });
4094
4384
  if (!keyChoice) {
4095
- return existingConfig;
4385
+ return existingConfig ?? null;
4096
4386
  }
4097
4387
  if (keyChoice === "saved") {
4098
4388
  resolvedApiKey = savedForProvider.apiKey;
@@ -4106,7 +4396,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4106
4396
  console.log(chalk5.yellow("Setup cancelled.\n"));
4107
4397
  process.exit(0);
4108
4398
  }
4109
- return existingConfig;
4399
+ return existingConfig ?? null;
4110
4400
  }
4111
4401
  baseURL = preset.baseURL;
4112
4402
  defaultModelHint = preset.defaultModel;
@@ -4127,7 +4417,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4127
4417
  console.log(chalk5.yellow("Setup cancelled.\n"));
4128
4418
  process.exit(0);
4129
4419
  }
4130
- return existingConfig;
4420
+ return existingConfig ?? null;
4131
4421
  }
4132
4422
  provider = verified.provider;
4133
4423
  resolvedApiKey = verified.apiKey;
@@ -4152,7 +4442,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4152
4442
  console.log(chalk5.yellow("Setup cancelled.\n"));
4153
4443
  process.exit(0);
4154
4444
  }
4155
- return existingConfig;
4445
+ return existingConfig ?? null;
4156
4446
  }
4157
4447
  const finalConfig = {
4158
4448
  provider,
@@ -5125,8 +5415,11 @@ var POLLINATIONS_CASCADE_CHAIN = [
5125
5415
  "qwen-coder"
5126
5416
  ];
5127
5417
  async function fetchLiveOpenRouterFreeModels() {
5418
+ const controller = new AbortController();
5419
+ const timer = setTimeout(() => controller.abort(), 6e3);
5128
5420
  try {
5129
5421
  const res = await fetch("https://openrouter.ai/api/v1/models", {
5422
+ signal: controller.signal,
5130
5423
  headers: { "User-Agent": "IUB CLI" }
5131
5424
  });
5132
5425
  if (!res.ok) return [];
@@ -5153,6 +5446,8 @@ async function fetchLiveOpenRouterFreeModels() {
5153
5446
  return freeModels;
5154
5447
  } catch {
5155
5448
  return [];
5449
+ } finally {
5450
+ clearTimeout(timer);
5156
5451
  }
5157
5452
  }
5158
5453
  async function selectAgentModelInteractive(currentConfig, mode = "build", initialCategory) {
@@ -5295,7 +5590,12 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5295
5590
  ...AGENT_MODELS.filter((m) => m.category === "local" && !existingIds.has(m.id))
5296
5591
  ];
5297
5592
  } else if (categoryChoice === "all") {
5298
- modelsToShow = AGENT_MODELS;
5593
+ const seenIds = /* @__PURE__ */ new Set();
5594
+ modelsToShow = AGENT_MODELS.filter((m) => {
5595
+ if (seenIds.has(m.id)) return false;
5596
+ seenIds.add(m.id);
5597
+ return true;
5598
+ });
5299
5599
  } else {
5300
5600
  modelsToShow = AGENT_MODELS.filter((m) => m.category === categoryChoice);
5301
5601
  }
@@ -5378,7 +5678,7 @@ async function resolveAndSavePreset(preset, currentConfig) {
5378
5678
  validate: (v) => !v || v.trim().length === 0 ? "Key cannot be empty!" : void 0
5379
5679
  });
5380
5680
  if (!enteredKey) return null;
5381
- targetApiKey = enteredKey.trim();
5681
+ targetApiKey = sanitizeApiKeyInput(enteredKey);
5382
5682
  targetBaseURL = targetProvider === "gemini" ? void 0 : preset.baseURL;
5383
5683
  }
5384
5684
  } else if (targetProvider === "openrouter") {
@@ -5519,11 +5819,20 @@ function detectProjectContext(rootDir = process.cwd()) {
5519
5819
  }
5520
5820
  }
5521
5821
  try {
5522
- const branch = execSync2("git rev-parse --abbrev-ref HEAD 2>/dev/null || git branch --show-current", {
5523
- cwd: rootDir,
5524
- encoding: "utf8",
5525
- stdio: ["ignore", "pipe", "ignore"]
5526
- }).trim();
5822
+ let branch = "";
5823
+ try {
5824
+ branch = execSync2("git rev-parse --abbrev-ref HEAD", {
5825
+ cwd: rootDir,
5826
+ encoding: "utf8",
5827
+ stdio: ["ignore", "pipe", "ignore"]
5828
+ }).trim();
5829
+ } catch {
5830
+ branch = execSync2("git branch --show-current", {
5831
+ cwd: rootDir,
5832
+ encoding: "utf8",
5833
+ stdio: ["ignore", "pipe", "ignore"]
5834
+ }).trim();
5835
+ }
5527
5836
  if (branch) gitBranch = branch;
5528
5837
  const status = execSync2("git status --porcelain", {
5529
5838
  cwd: rootDir,
@@ -5533,9 +5842,12 @@ function detectProjectContext(rootDir = process.cwd()) {
5533
5842
  gitDirty = status.length > 0;
5534
5843
  } catch {
5535
5844
  }
5845
+ const stackDetails = [language];
5846
+ if (hasTypeScript && language !== "TypeScript") stackDetails.push("TypeScript");
5847
+ if (hasTailwind) stackDetails.push("Tailwind CSS");
5536
5848
  const summaryLines = [
5537
5849
  `### DETECTED WORKSPACE ENVIRONMENT:`,
5538
- `- Framework / Stack: ${framework} (${language}${hasTypeScript ? ", TypeScript" : ""}${hasTailwind ? ", Tailwind CSS" : ""})`,
5850
+ `- Framework / Stack: ${framework} (${stackDetails.join(", ")})`,
5539
5851
  `- Package Manager: ${packageManager}`
5540
5852
  ];
5541
5853
  if (Object.keys(scripts).length > 0) {
@@ -5645,7 +5957,7 @@ async function probeCandidate(candidate) {
5645
5957
  return false;
5646
5958
  }
5647
5959
  }
5648
- async function exploreAndSelectFreeModel(config, excludedModels = /* @__PURE__ */ new Set(), silent = false) {
5960
+ async function exploreAndSelectFreeModel(config, excludedModels = /* @__PURE__ */ new Set(), silent = false, persist = true) {
5649
5961
  if (!silent) {
5650
5962
  process.stdout.write(
5651
5963
  chalk7.cyan("\nExploring all available models across providers to find active free tokens...\n")
@@ -5791,7 +6103,9 @@ async function exploreAndSelectFreeModel(config, excludedModels = /* @__PURE__ *
5791
6103
  } else {
5792
6104
  delete config.baseURL;
5793
6105
  }
5794
- saveConfig(config);
6106
+ if (persist) {
6107
+ saveConfig(config);
6108
+ }
5795
6109
  if (!silent) {
5796
6110
  renderModelExplorationNotice(winner.id, winner.provider, testedCount);
5797
6111
  }
@@ -5992,11 +6306,7 @@ var IUBAgent = class {
5992
6306
  }
5993
6307
  if (this.config.provider === "gemini") {
5994
6308
  const normalized = normalizeGeminiModel(this.config.model);
5995
- if (!normalized || !GEMINI_CASCADE_CHAIN.includes(normalized)) {
5996
- this.config.model = "gemini-3.5-flash-lite";
5997
- } else {
5998
- this.config.model = normalized;
5999
- }
6309
+ this.config.model = normalized || "gemini-3.5-flash-lite";
6000
6310
  delete this.config.baseURL;
6001
6311
  this.geminiClient = new GoogleGenAI2({ apiKey: this.config.apiKey });
6002
6312
  this.openAIClient = void 0;
@@ -6014,6 +6324,7 @@ var IUBAgent = class {
6014
6324
  * Set agent mode (build or plan) and update prompt instructions.
6015
6325
  */
6016
6326
  setMode(mode) {
6327
+ if (this.mode === mode) return;
6017
6328
  this.mode = mode;
6018
6329
  this.updateSystemPrompt();
6019
6330
  }
@@ -6075,12 +6386,23 @@ var IUBAgent = class {
6075
6386
  }
6076
6387
  }
6077
6388
  /**
6078
- * Update configuration and recreate clients.
6389
+ * Update configuration and recreate clients while preserving conversation history by default.
6079
6390
  */
6080
- updateConfig(newConfig) {
6391
+ updateConfig(newConfig, resetHistory = false) {
6392
+ const prevProvider = this.config.provider;
6081
6393
  this.config = newConfig;
6082
6394
  this.initClients();
6083
- this.resetHistory();
6395
+ if (resetHistory) {
6396
+ this.resetHistory();
6397
+ return;
6398
+ }
6399
+ if (prevProvider !== "gemini" && newConfig.provider === "gemini") {
6400
+ this.syncMessagesToGemini();
6401
+ } else if (prevProvider === "gemini" && newConfig.provider !== "gemini") {
6402
+ this.syncMessagesToOpenAI();
6403
+ } else if (newConfig.provider !== "gemini" && this.openAIMessages[0]?.role === "system") {
6404
+ this.openAIMessages[0].content = getSystemPrompt(this.mode);
6405
+ }
6084
6406
  }
6085
6407
  onModelChangeCallback;
6086
6408
  setOnModelChange(cb) {
@@ -6177,6 +6499,9 @@ var IUBAgent = class {
6177
6499
  merged.push({ role: item.role, parts: [...item.parts] });
6178
6500
  }
6179
6501
  }
6502
+ while (merged.length > 0 && merged[0].role !== "user") {
6503
+ merged.shift();
6504
+ }
6180
6505
  this.geminiContents = merged;
6181
6506
  }
6182
6507
  /**
@@ -6247,7 +6572,8 @@ ${String(out).slice(0, 6e3)}`);
6247
6572
  * Intelligently cascade to the next available model when token quota, auth error, or rate limit is reached.
6248
6573
  * Cycles cleanly across providers without looping back into dead providers or persisting broken models.
6249
6574
  */
6250
- async cascadeModel(currentModel, reason) {
6575
+ async cascadeModel(currentModel, reason, signal) {
6576
+ if (signal?.aborted) return null;
6251
6577
  this.cascadeStepsCount++;
6252
6578
  this.attemptedModelsInCascade.add(currentModel);
6253
6579
  if (this.config.provider === "gemini") {
@@ -6363,7 +6689,7 @@ ${String(out).slice(0, 6e3)}`);
6363
6689
  const nextOR = switchToOpenRouter("Custom provider rate-limited/exhausted; cascading to OpenRouter Free");
6364
6690
  if (nextOR) return nextOR;
6365
6691
  }
6366
- const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade);
6692
+ const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade, false, false);
6367
6693
  if (explored) {
6368
6694
  this.attemptedModelsInCascade.add(explored.id);
6369
6695
  this.initClients();
@@ -6380,13 +6706,15 @@ ${String(out).slice(0, 6e3)}`);
6380
6706
  const cooldownSec = 10;
6381
6707
  renderRollingRateLimitNotice(currentModel, cooldownSec, "All free models in rolling rate limit");
6382
6708
  for (let rem = cooldownSec; rem > 0; rem--) {
6709
+ if (signal?.aborted) return null;
6383
6710
  const msg = `Free rate limits active \u2022 Auto-cooling down (${rem}s) [Never-Stop Mode]... (Esc to cancel)`;
6384
6711
  updateFixedBottomStatus(msg, { mode: this.mode, model: this.config.model });
6385
6712
  await new Promise((r) => setTimeout(r, 1e3));
6386
6713
  }
6714
+ if (signal?.aborted) return null;
6387
6715
  this.attemptedModelsInCascade.clear();
6388
6716
  this.deadProvidersInTurn.clear();
6389
- const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true);
6717
+ const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true, false);
6390
6718
  if (recovered) {
6391
6719
  this.initClients();
6392
6720
  if (recovered.provider === "gemini") {
@@ -6455,9 +6783,13 @@ ${String(out).slice(0, 6e3)}`);
6455
6783
  const turnsBefore = this.openAIMessages.length + this.geminiContents.length;
6456
6784
  if (this.openAIMessages.length > 5) {
6457
6785
  const systemMsg = this.openAIMessages[0];
6458
- const recent = this.openAIMessages.slice(-4);
6786
+ let sliceStart = Math.max(1, this.openAIMessages.length - 4);
6787
+ while (sliceStart < this.openAIMessages.length && this.openAIMessages[sliceStart].role === "tool") {
6788
+ sliceStart++;
6789
+ }
6790
+ const recent = this.openAIMessages.slice(sliceStart);
6459
6791
  const intermediateUserQueries = [];
6460
- for (let i = 1; i < this.openAIMessages.length - 4; i++) {
6792
+ for (let i = 1; i < sliceStart; i++) {
6461
6793
  const msg = this.openAIMessages[i];
6462
6794
  if (msg.role === "user" && typeof msg.content === "string") {
6463
6795
  intermediateUserQueries.push(msg.content.slice(0, 100));
@@ -6470,7 +6802,11 @@ ${String(out).slice(0, 6e3)}`);
6470
6802
  this.openAIMessages = [systemMsg, summaryNote, ...recent];
6471
6803
  }
6472
6804
  if (this.geminiContents.length > 4) {
6473
- this.geminiContents = this.geminiContents.slice(-4);
6805
+ let trimmed = this.geminiContents.slice(-4);
6806
+ while (trimmed.length > 0 && (trimmed[0].role !== "user" || trimmed[0].parts?.some((p) => p.functionResponse))) {
6807
+ trimmed.shift();
6808
+ }
6809
+ this.geminiContents = trimmed;
6474
6810
  }
6475
6811
  const turnsAfter = this.openAIMessages.length + this.geminiContents.length;
6476
6812
  return { turnsBefore, turnsAfter };
@@ -6494,6 +6830,61 @@ ${String(out).slice(0, 6e3)}`);
6494
6830
  estimatedCostSavedUsd: Math.round(costSaved * 1e3) / 1e3
6495
6831
  };
6496
6832
  }
6833
+ getRequestTimeoutMs() {
6834
+ const url = (this.config.baseURL || "").toLowerCase();
6835
+ if (url.includes("localhost") || url.includes("127.0.0.1")) {
6836
+ return 12e4;
6837
+ }
6838
+ return 6e4;
6839
+ }
6840
+ async raceWithTimeoutAndAbort(operation, timeoutMessage, signal) {
6841
+ if (signal?.aborted) {
6842
+ throw new Error("ABORTED_BY_USER");
6843
+ }
6844
+ let timeoutId;
6845
+ let onAbort;
6846
+ const timeoutPromise = new Promise((_, reject) => {
6847
+ timeoutId = setTimeout(() => reject(new Error(timeoutMessage)), this.getRequestTimeoutMs());
6848
+ });
6849
+ const abortPromise = new Promise((_, reject) => {
6850
+ if (signal) {
6851
+ onAbort = () => reject(new Error("ABORTED_BY_USER"));
6852
+ signal.addEventListener("abort", onAbort, { once: true });
6853
+ }
6854
+ });
6855
+ try {
6856
+ return await Promise.race([operation, timeoutPromise, abortPromise]);
6857
+ } finally {
6858
+ if (timeoutId) clearTimeout(timeoutId);
6859
+ if (signal && onAbort) {
6860
+ signal.removeEventListener("abort", onAbort);
6861
+ }
6862
+ }
6863
+ }
6864
+ /**
6865
+ * Ensure message history has no dangling tool_calls or unresponded user turns before starting a new turn.
6866
+ */
6867
+ sanitizeDanglingHistory() {
6868
+ const lastOpenAI = this.openAIMessages[this.openAIMessages.length - 1];
6869
+ if (lastOpenAI && lastOpenAI.role === "assistant" && Array.isArray(lastOpenAI.tool_calls) && lastOpenAI.tool_calls.length > 0) {
6870
+ for (const tc of lastOpenAI.tool_calls) {
6871
+ if (tc?.id) {
6872
+ this.openAIMessages.push({
6873
+ role: "tool",
6874
+ tool_call_id: tc.id,
6875
+ content: "Action cancelled before completion."
6876
+ });
6877
+ }
6878
+ }
6879
+ }
6880
+ const lastGemini = this.geminiContents[this.geminiContents.length - 1];
6881
+ if (lastGemini && lastGemini.role === "user") {
6882
+ this.geminiContents.push({
6883
+ role: "model",
6884
+ parts: [{ text: "[Previous request interrupted by user before completion.]" }]
6885
+ });
6886
+ }
6887
+ }
6497
6888
  /**
6498
6889
  * Main chat turn loop with automatic tool execution and cross-provider failover.
6499
6890
  */
@@ -6502,6 +6893,9 @@ ${String(out).slice(0, 6e3)}`);
6502
6893
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6503
6894
  }
6504
6895
  this.resetCascadeAttempts();
6896
+ if (!options?.isCascadeRetry) {
6897
+ this.sanitizeDanglingHistory();
6898
+ }
6505
6899
  const modeDirective = this.mode === "build" ? `[SYSTEM STATUS: ACTIVE MODE = BUILD MODE. All coding tools (write_file, edit_file, run_command) are FULLY UNLOCKED AND ACTIVE. You MUST NOT claim you are in PLAN mode or ask the user to type /build. You are ALREADY in BUILD mode. Immediately call your tools to implement, create, or edit code.]` : `[SYSTEM STATUS: ACTIVE MODE = PLAN MODE. You are in read-only planning mode. Formulate comprehensive step-by-step plans without modifying files.]`;
6506
6900
  const englishEnforcedInput = `[CRITICAL: You must provide all explanations, responses, and terminal output strictly in clear ENGLISH. Do not use Bengali script under any circumstances.]
6507
6901
  ${modeDirective}
@@ -6517,12 +6911,17 @@ ${userInput}`;
6517
6911
  if (options?.signal?.aborted) {
6518
6912
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6519
6913
  }
6520
- const nextModel = await this.cascadeModel(this.config.model, "Provider failure auto-recovery");
6914
+ const nextModel = await this.cascadeModel(
6915
+ this.config.model,
6916
+ "Provider failure auto-recovery",
6917
+ options?.signal
6918
+ );
6521
6919
  if (nextModel) {
6920
+ const retryOpts = { ...options, isCascadeRetry: true };
6522
6921
  if (this.config.provider === "gemini") {
6523
- return await this.chatGemini(englishEnforcedInput, options);
6922
+ return await this.chatGemini(englishEnforcedInput, retryOpts);
6524
6923
  } else {
6525
- return await this.chatOpenAI(englishEnforcedInput, options);
6924
+ return await this.chatOpenAI(englishEnforcedInput, retryOpts);
6526
6925
  }
6527
6926
  }
6528
6927
  return chalk8.yellow("\nAll free model tokens are currently exhausted across all providers. Check the renewal countdown above.");
@@ -6551,8 +6950,7 @@ ${userInput}`;
6551
6950
  if (!this.geminiClient) {
6552
6951
  throw new Error("Gemini client is not initialized.");
6553
6952
  }
6554
- const lastContent = this.geminiContents[this.geminiContents.length - 1];
6555
- if (!lastContent || lastContent.role !== "user") {
6953
+ if (!options?.isCascadeRetry) {
6556
6954
  const parts = [{ text: userInput }];
6557
6955
  if (options?.images && options.images.length > 0) {
6558
6956
  for (const img of options.images) {
@@ -6564,15 +6962,21 @@ ${userInput}`;
6564
6962
  });
6565
6963
  }
6566
6964
  }
6567
- this.geminiContents.push({
6568
- role: "user",
6569
- parts
6570
- });
6965
+ const lastContent = this.geminiContents[this.geminiContents.length - 1];
6966
+ if (lastContent && lastContent.role === "user") {
6967
+ lastContent.parts.push(...parts);
6968
+ } else {
6969
+ this.geminiContents.push({
6970
+ role: "user",
6971
+ parts
6972
+ });
6973
+ }
6571
6974
  }
6572
6975
  const maxTurns = 40;
6573
6976
  let turnCount = 0;
6574
6977
  let toolsExecutedInChat = 0;
6575
6978
  let nudgedBuildExecution = false;
6979
+ let emptyNudges = 0;
6576
6980
  while (turnCount < maxTurns) {
6577
6981
  if (options?.signal?.aborted) {
6578
6982
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
@@ -6608,19 +7012,8 @@ ${userInput}`;
6608
7012
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6609
7013
  }
6610
7014
  attempts++;
6611
- let timeoutId;
6612
7015
  try {
6613
- const abortPromise = new Promise((_, reject) => {
6614
- if (options?.signal?.aborted) {
6615
- reject(new Error("ABORTED_BY_USER"));
6616
- return;
6617
- }
6618
- options?.signal?.addEventListener("abort", () => reject(new Error("ABORTED_BY_USER")), { once: true });
6619
- });
6620
- const timeoutPromise = new Promise((_, reject) => {
6621
- timeoutId = setTimeout(() => reject(new Error("Gemini API request timed out (18s)")), 18e3);
6622
- });
6623
- response = await Promise.race([
7016
+ response = await this.raceWithTimeoutAndAbort(
6624
7017
  this.geminiClient.models.generateContent({
6625
7018
  model: candidateModel,
6626
7019
  contents: this.geminiContents,
@@ -6629,10 +7022,9 @@ ${userInput}`;
6629
7022
  tools: this.mode === "plan" ? PLAN_GEMINI_TOOLS : BUILD_GEMINI_TOOLS
6630
7023
  }
6631
7024
  }),
6632
- timeoutPromise,
6633
- abortPromise
6634
- ]);
6635
- if (timeoutId) clearTimeout(timeoutId);
7025
+ `Gemini API request timed out (${Math.round(this.getRequestTimeoutMs() / 1e3)}s)`,
7026
+ options?.signal
7027
+ );
6636
7028
  usedGeminiModel = candidateModel;
6637
7029
  if (candidateModel !== this.config.model) {
6638
7030
  spinner.stop();
@@ -6644,7 +7036,6 @@ ${userInput}`;
6644
7036
  lastError = null;
6645
7037
  break;
6646
7038
  } catch (err) {
6647
- if (timeoutId) clearTimeout(timeoutId);
6648
7039
  if (options?.signal?.aborted || err?.message === "ABORTED_BY_USER") {
6649
7040
  spinner.stop();
6650
7041
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
@@ -6678,16 +7069,18 @@ ${userInput}`;
6678
7069
  spinner.stop();
6679
7070
  if (!response) {
6680
7071
  const errMsg = lastError ? lastError?.message || String(lastError) : "All Gemini candidates exhausted";
7072
+ const retryOpts = { ...options, isCascadeRetry: true };
6681
7073
  if (errMsg.includes("API_KEY_INVALID") || errMsg.includes("403") || errMsg.includes("401")) {
6682
7074
  const nextModel = await this.cascadeModel(
6683
7075
  this.config.model,
6684
- "Gemini auth error (401/403), cascading to OpenRouter/Custom"
7076
+ "Gemini auth error (401/403), cascading to OpenRouter/Custom",
7077
+ options?.signal
6685
7078
  );
6686
7079
  if (nextModel) {
6687
7080
  if (this.config.provider === "gemini") {
6688
- return await this.chatGemini(userInput, options);
7081
+ return await this.chatGemini(userInput, retryOpts);
6689
7082
  } else {
6690
- return await this.chatOpenAI(userInput, options);
7083
+ return await this.chatOpenAI(userInput, retryOpts);
6691
7084
  }
6692
7085
  }
6693
7086
  return chalk8.red(
@@ -6698,13 +7091,14 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6698
7091
  } else {
6699
7092
  const nextModel = await this.cascadeModel(
6700
7093
  usedGeminiModel,
6701
- errMsg.includes("429") || errMsg.includes("RESOURCE_EXHAUSTED") ? "Gemini Rate Limit / Token Quota Exceeded (429)" : "Gemini Server High Demand / Provider Error"
7094
+ errMsg.includes("429") || errMsg.includes("RESOURCE_EXHAUSTED") ? "Gemini Rate Limit / Token Quota Exceeded (429)" : "Gemini Server High Demand / Provider Error",
7095
+ options?.signal
6702
7096
  );
6703
7097
  if (nextModel) {
6704
7098
  if (this.config.provider === "gemini") {
6705
- return await this.chatGemini(userInput, options);
7099
+ return await this.chatGemini(userInput, retryOpts);
6706
7100
  } else {
6707
- return await this.chatOpenAI(userInput, options);
7101
+ return await this.chatOpenAI(userInput, retryOpts);
6708
7102
  }
6709
7103
  }
6710
7104
  return chalk8.yellow(
@@ -6721,6 +7115,10 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6721
7115
  this.metrics.totalTokens += response.usageMetadata.totalTokenCount || 0;
6722
7116
  }
6723
7117
  if (candidate?.finishReason === "MALFORMED_FUNCTION_CALL" && functionCalls.length === 0) {
7118
+ emptyNudges++;
7119
+ if (emptyNudges > 2) {
7120
+ return "Model returned repeated malformed tool calls. Please try rephrasing or switching models with /model.";
7121
+ }
6724
7122
  this.geminiContents.push({
6725
7123
  role: "user",
6726
7124
  parts: [
@@ -6736,13 +7134,18 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6736
7134
  }
6737
7135
  const directText = (candidate?.content?.parts || []).map((p) => typeof p.text === "string" ? p.text : "").join("").trim();
6738
7136
  if (!functionCalls || functionCalls.length === 0) {
6739
- if (!directText && turnCount < maxTurns) {
7137
+ if (!directText && turnCount < maxTurns && emptyNudges < 2) {
7138
+ emptyNudges++;
6740
7139
  this.geminiContents.push({
6741
7140
  role: "user",
6742
7141
  parts: [{ text: "Please continue and provide your response or call the needed tool." }]
6743
7142
  });
6744
7143
  continue;
6745
7144
  }
7145
+ if (!directText) {
7146
+ const reason = candidate?.finishReason ? ` (${candidate.finishReason})` : "";
7147
+ return `Model returned an empty response${reason}.`;
7148
+ }
6746
7149
  if (this.shouldNudgePassiveBuildReply(userInput, directText, toolsExecutedInChat, nudgedBuildExecution) && turnCount < maxTurns) {
6747
7150
  nudgedBuildExecution = true;
6748
7151
  this.geminiContents.push({
@@ -6798,18 +7201,19 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6798
7201
  if (!this.openAIClient || !this.config.apiKey) {
6799
7202
  const nextModel = await this.cascadeModel(
6800
7203
  this.config.model,
6801
- `Auth error / Missing API key for ${this.config.provider}`
7204
+ `Auth error / Missing API key for ${this.config.provider}`,
7205
+ options?.signal
6802
7206
  );
6803
7207
  if (nextModel) {
7208
+ const retryOpts = { ...options, isCascadeRetry: true };
6804
7209
  if (this.config.provider === "gemini") {
6805
- return await this.chatGemini(userInput, options);
7210
+ return await this.chatGemini(userInput, retryOpts);
6806
7211
  }
6807
7212
  } else {
6808
7213
  throw new Error("OpenAI client is not initialized.");
6809
7214
  }
6810
7215
  }
6811
- const lastMsg = this.openAIMessages[this.openAIMessages.length - 1];
6812
- if (!lastMsg || lastMsg.role !== "user") {
7216
+ if (!options?.isCascadeRetry) {
6813
7217
  if (options?.images && options.images.length > 0) {
6814
7218
  const contentParts = [{ type: "text", text: userInput }];
6815
7219
  for (const img of options.images) {
@@ -6835,6 +7239,7 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6835
7239
  let turnCount = 0;
6836
7240
  let toolsExecutedInChat = 0;
6837
7241
  let nudgedBuildExecution = false;
7242
+ let emptyNudges = 0;
6838
7243
  while (turnCount < maxTurns) {
6839
7244
  if (options?.signal?.aborted) {
6840
7245
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
@@ -6859,19 +7264,9 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6859
7264
  if (!this.openAIClient) {
6860
7265
  break;
6861
7266
  }
6862
- let timeoutId;
7267
+ const timeoutMs = this.getRequestTimeoutMs();
6863
7268
  try {
6864
- const abortPromise = new Promise((_, reject) => {
6865
- if (options?.signal?.aborted) {
6866
- reject(new Error("ABORTED_BY_USER"));
6867
- return;
6868
- }
6869
- options?.signal?.addEventListener("abort", () => reject(new Error("ABORTED_BY_USER")), { once: true });
6870
- });
6871
- const timeoutPromise = new Promise((_, reject) => {
6872
- timeoutId = setTimeout(() => reject(new Error("Provider API request timed out (18s)")), 18e3);
6873
- });
6874
- completion = await Promise.race([
7269
+ completion = await this.raceWithTimeoutAndAbort(
6875
7270
  this.openAIClient.chat.completions.create(
6876
7271
  {
6877
7272
  model: this.config.model,
@@ -6881,17 +7276,15 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6881
7276
  },
6882
7277
  {
6883
7278
  signal: options?.signal,
6884
- timeout: 18e3
7279
+ timeout: timeoutMs
6885
7280
  }
6886
7281
  ),
6887
- timeoutPromise,
6888
- abortPromise
6889
- ]);
6890
- if (timeoutId) clearTimeout(timeoutId);
7282
+ `Provider API request timed out (${Math.round(timeoutMs / 1e3)}s)`,
7283
+ options?.signal
7284
+ );
6891
7285
  this.persistVerifiedActiveModel();
6892
7286
  break;
6893
7287
  } catch (err) {
6894
- if (timeoutId) clearTimeout(timeoutId);
6895
7288
  if (options?.signal?.aborted || err?.message === "ABORTED_BY_USER") {
6896
7289
  spinner.stop();
6897
7290
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
@@ -6955,10 +7348,10 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6955
7348
  }
6956
7349
  cascadeAttempts++;
6957
7350
  spinner.stop();
6958
- const nextModel = await this.cascadeModel(this.config.model, cascadeReason);
7351
+ const nextModel = await this.cascadeModel(this.config.model, cascadeReason, options?.signal);
6959
7352
  if (nextModel) {
6960
7353
  if (this.config.provider === "gemini") {
6961
- return await this.chatGemini(userInput, options);
7354
+ return await this.chatGemini(userInput, { ...options, isCascadeRetry: true });
6962
7355
  }
6963
7356
  spinner.text = chalk8.cyan(`IUB CLI continuing with [${nextModel}]...`);
6964
7357
  spinner.start();
@@ -6981,12 +7374,13 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
6981
7374
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6982
7375
  }
6983
7376
  if (!completion) {
6984
- const nextModel = await this.cascadeModel(this.config.model, "Cascade auto-recovery");
7377
+ const nextModel = await this.cascadeModel(this.config.model, "Cascade auto-recovery", options?.signal);
6985
7378
  if (nextModel) {
7379
+ const retryOpts = { ...options, isCascadeRetry: true };
6986
7380
  if (this.config.provider === "gemini") {
6987
- return await this.chatGemini(userInput, options);
7381
+ return await this.chatGemini(userInput, retryOpts);
6988
7382
  } else {
6989
- return await this.chatOpenAI(userInput, options);
7383
+ return await this.chatOpenAI(userInput, retryOpts);
6990
7384
  }
6991
7385
  }
6992
7386
  return chalk8.yellow(
@@ -6995,10 +7389,14 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
6995
7389
  }
6996
7390
  const choice = completion.choices?.[0];
6997
7391
  if (!choice || !choice.message) {
6998
- const nextModel = await this.cascadeModel(this.config.model, "Empty choices returned from model");
7392
+ const nextModel = await this.cascadeModel(
7393
+ this.config.model,
7394
+ "Empty choices returned from model",
7395
+ options?.signal
7396
+ );
6999
7397
  if (nextModel) {
7000
7398
  if (this.config.provider === "gemini") {
7001
- return await this.chatGemini(userInput, options);
7399
+ return await this.chatGemini(userInput, { ...options, isCascadeRetry: true });
7002
7400
  }
7003
7401
  continue;
7004
7402
  }
@@ -7019,7 +7417,8 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7019
7417
  if (!message.tool_calls || message.tool_calls.length === 0) {
7020
7418
  const rawText = message.content?.trim() || "";
7021
7419
  const reasoningText = (message.reasoning || "").trim();
7022
- if (!rawText && reasoningText && turnCount < maxTurns) {
7420
+ if (!rawText && reasoningText && turnCount < maxTurns && emptyNudges < 2) {
7421
+ emptyNudges++;
7023
7422
  this.openAIMessages.push({
7024
7423
  role: "user",
7025
7424
  content: "Please proceed directly with your final answer or call the required tool now."
@@ -7041,12 +7440,22 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7041
7440
  if (options?.signal?.aborted) {
7042
7441
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7043
7442
  }
7044
- if (toolCall.type !== "function") continue;
7045
- const fnName = toolCall.function.name;
7443
+ const fnObj = toolCall.function;
7444
+ if (!fnObj || typeof fnObj.name !== "string") {
7445
+ if (toolCall.id) {
7446
+ this.openAIMessages.push({
7447
+ role: "tool",
7448
+ tool_call_id: toolCall.id,
7449
+ content: "Error: Unsupported or malformed tool call payload."
7450
+ });
7451
+ }
7452
+ continue;
7453
+ }
7454
+ const fnName = fnObj.name;
7046
7455
  let fnArgs = null;
7047
7456
  let parseError = null;
7048
7457
  try {
7049
- fnArgs = JSON.parse(toolCall.function.arguments || "{}");
7458
+ fnArgs = JSON.parse(fnObj.arguments || "{}");
7050
7459
  } catch (e) {
7051
7460
  parseError = e?.message || "Invalid JSON";
7052
7461
  }
@@ -7215,6 +7624,8 @@ var MeshNode = class extends EventEmitter {
7215
7624
  }
7216
7625
  });
7217
7626
  server.once("listening", () => {
7627
+ server.on("error", () => {
7628
+ });
7218
7629
  this.wss = server;
7219
7630
  this.isHost = true;
7220
7631
  this.setupHostServer();
@@ -7229,6 +7640,8 @@ var MeshNode = class extends EventEmitter {
7229
7640
  if (!this.wss) return;
7230
7641
  this.wss.on("connection", (ws) => {
7231
7642
  let authedPeer = null;
7643
+ ws.on("error", () => {
7644
+ });
7232
7645
  const authTimeout = setTimeout(() => {
7233
7646
  if (!authedPeer) {
7234
7647
  try {
@@ -7315,6 +7728,20 @@ var MeshNode = class extends EventEmitter {
7315
7728
  const ws = new WebSocket(url);
7316
7729
  this.clientWs = ws;
7317
7730
  this.isHost = false;
7731
+ let settled = false;
7732
+ const done = () => {
7733
+ if (settled) return;
7734
+ settled = true;
7735
+ clearTimeout(connectTimer);
7736
+ resolve();
7737
+ };
7738
+ const connectTimer = setTimeout(() => {
7739
+ try {
7740
+ ws.terminate();
7741
+ } catch {
7742
+ }
7743
+ done();
7744
+ }, 2500);
7318
7745
  ws.on("open", () => {
7319
7746
  const authMsg = {
7320
7747
  type: "AUTH",
@@ -7333,7 +7760,7 @@ var MeshNode = class extends EventEmitter {
7333
7760
  this.peers.set(p.nodeId, p);
7334
7761
  }
7335
7762
  }
7336
- resolve();
7763
+ done();
7337
7764
  return;
7338
7765
  }
7339
7766
  if (msg.type === "AUTH_FAIL") {
@@ -7342,7 +7769,7 @@ var MeshNode = class extends EventEmitter {
7342
7769
  ws.close();
7343
7770
  } catch {
7344
7771
  }
7345
- resolve();
7772
+ done();
7346
7773
  return;
7347
7774
  }
7348
7775
  if (msg.type === "PEER_JOINED") {
@@ -7381,12 +7808,12 @@ var MeshNode = class extends EventEmitter {
7381
7808
  }
7382
7809
  });
7383
7810
  ws.on("error", () => {
7384
- resolve();
7811
+ done();
7385
7812
  });
7386
7813
  ws.on("close", () => {
7387
7814
  this.peers.clear();
7388
7815
  this.clientWs = null;
7389
- resolve();
7816
+ done();
7390
7817
  if (this.running) {
7391
7818
  this.scheduleReconnect();
7392
7819
  }
@@ -7553,29 +7980,47 @@ var MeshNode = class extends EventEmitter {
7553
7980
  }
7554
7981
  /**
7555
7982
  * Find a peer by role name (e.g. "backend", "frontend") or exact nodeId.
7983
+ * Prefers remote peers over self when multiple instances share a role.
7556
7984
  */
7557
7985
  findPeer(roleOrId) {
7558
7986
  const query = roleOrId.toLowerCase().trim();
7559
- if (this.nodeId.toLowerCase() === query || this.role.toLowerCase() === query) {
7560
- return this.getMyPeerInfo();
7561
- }
7562
7987
  for (const p of this.peers.values()) {
7563
7988
  if (p.nodeId.toLowerCase() === query || p.role.toLowerCase() === query) {
7564
7989
  return p;
7565
7990
  }
7566
7991
  }
7992
+ if (this.nodeId.toLowerCase() === query || this.role.toLowerCase() === query) {
7993
+ return this.getMyPeerInfo();
7994
+ }
7567
7995
  return null;
7568
7996
  }
7569
7997
  /**
7570
7998
  * Execute a tool on a remote peer instance over the WebSocket mesh RPC.
7571
7999
  */
7572
8000
  async callRemoteTool(targetRoleOrId, toolName, args = {}, timeoutMs = 45e3) {
8001
+ if (targetRoleOrId === "all" || targetRoleOrId === "*") {
8002
+ const remotePeers = this.listPeers().filter((p) => p.nodeId !== this.nodeId);
8003
+ if (remotePeers.length === 0) {
8004
+ return "Error: No other IUB CLI peer instances are currently connected in the mesh.";
8005
+ }
8006
+ const results = await Promise.all(
8007
+ remotePeers.map(async (p) => {
8008
+ const out = await this.callRemoteTool(p.nodeId, toolName, args, timeoutMs);
8009
+ return `[Peer ${p.role} (${p.nodeId})]:
8010
+ ${out}`;
8011
+ })
8012
+ );
8013
+ return results.join("\n\n");
8014
+ }
7573
8015
  const peer = this.findPeer(targetRoleOrId);
7574
- if (!peer && targetRoleOrId !== "all") {
8016
+ if (!peer) {
7575
8017
  const activePeers = this.listPeers().filter((p) => p.nodeId !== this.nodeId);
7576
8018
  const peerSummary = activePeers.length > 0 ? `Connected peers: ${activePeers.map((p) => `"${p.role}" (${p.workspace})`).join(", ")}` : "No other IUB CLI instances are currently connected.";
7577
8019
  return `Error: Peer instance "${targetRoleOrId}" not found in mesh. ${peerSummary}`;
7578
8020
  }
8021
+ if (peer.nodeId === this.nodeId) {
8022
+ return `Error: Target "${targetRoleOrId}" resolves to this local instance. Use local tools directly instead of peer_call_tool.`;
8023
+ }
7579
8024
  const reqId = `rpc-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`;
7580
8025
  const req = {
7581
8026
  type: "RPC_REQUEST",
@@ -7632,6 +8077,9 @@ var MeshNode = class extends EventEmitter {
7632
8077
  if (!peer) {
7633
8078
  return `Error: Peer "${targetRoleOrId}" is not connected to the mesh.`;
7634
8079
  }
8080
+ if (peer.nodeId === this.nodeId) {
8081
+ return `Error: Target "${targetRoleOrId}" resolves to this local instance.`;
8082
+ }
7635
8083
  const reqId = `msg-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`;
7636
8084
  const req = {
7637
8085
  type: "RPC_REQUEST",
@@ -7747,7 +8195,65 @@ function gracefulExit(code = 0) {
7747
8195
  process.stdin.unref?.();
7748
8196
  } catch {
7749
8197
  }
7750
- setTimeout(() => process.exit(code), 80).unref();
8198
+ setTimeout(() => process.exit(code), 40);
8199
+ }
8200
+ async function runDoctorDiagnostics(config) {
8201
+ const checks = [];
8202
+ const nodeVer = process.version;
8203
+ const major = parseInt(nodeVer.replace("v", "").split(".")[0], 10);
8204
+ checks.push({
8205
+ name: "Node.js Runtime",
8206
+ status: major >= 18 ? "ok" : "error",
8207
+ detail: `${nodeVer} (Node 18+ required for modern async streams)`
8208
+ });
8209
+ const hasKey = isKeylessConfig(config) || Boolean(config.apiKey && config.apiKey.trim().length > 5);
8210
+ checks.push({
8211
+ name: "AI Provider & Key",
8212
+ status: hasKey ? "ok" : "error",
8213
+ detail: `${formatProviderLabel(config)} with model "${config.model}" (${isKeylessConfig(config) ? "Zero-Key Active" : hasKey ? "Configured" : "Missing API Key"})`
8214
+ });
8215
+ try {
8216
+ const testFile = path8.resolve(process.cwd(), ".iubcli_check.tmp");
8217
+ fs8.writeFileSync(testFile, "ok", "utf8");
8218
+ fs8.unlinkSync(testFile);
8219
+ checks.push({
8220
+ name: "Workspace Read/Write",
8221
+ status: "ok",
8222
+ detail: `${process.cwd()} (Read/Write verified)`
8223
+ });
8224
+ } catch (e) {
8225
+ checks.push({
8226
+ name: "Workspace Read/Write",
8227
+ status: "error",
8228
+ detail: `Cannot write to ${process.cwd()}: ${e.message}`
8229
+ });
8230
+ }
8231
+ try {
8232
+ const gitVer = execSync3("git --version", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
8233
+ checks.push({
8234
+ name: "Git CLI",
8235
+ status: "ok",
8236
+ detail: gitVer || "Available"
8237
+ });
8238
+ } catch {
8239
+ checks.push({
8240
+ name: "Git CLI",
8241
+ status: "warn",
8242
+ detail: "git not found in PATH (/git command disabled)"
8243
+ });
8244
+ }
8245
+ const ollamaModels = await detectLocalOllamaModels(400);
8246
+ checks.push({
8247
+ name: "Local Ollama",
8248
+ status: ollamaModels.length > 0 ? "ok" : "warn",
8249
+ detail: ollamaModels.length > 0 ? `Running on localhost:11434 (${ollamaModels.length} model(s): ${ollamaModels.slice(0, 3).join(", ")})` : "Not detected on localhost:11434 (optional offline fallback)"
8250
+ });
8251
+ checks.push({
8252
+ name: "OS & Execution Shell",
8253
+ status: "ok",
8254
+ detail: `${process.platform} (${process.arch}) with non-interactive child process safety`
8255
+ });
8256
+ renderDoctorReport(checks);
7751
8257
  }
7752
8258
  process.on("exit", () => {
7753
8259
  getActiveMeshNode()?.stop();
@@ -7815,7 +8321,25 @@ function attachEscapeListener(onEscape) {
7815
8321
  };
7816
8322
  }
7817
8323
  var program = new Command();
7818
- program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK terminal coding agent that speaks Bangla, Banglish & English.").version("4.2.9", "-v, --version", "Output the current version").option("-m, --model <model>", "Override model for this session").option("-M, --mode <mode>", 'Execution mode: "build" (default) or "plan"', "build").option("-p, --prompt <prompt>", "Run a single prompt and exit").option("-y, --yes", "Auto-approve all file writes and shell commands").option("-r, --role <role>", 'Instance role for cross-instance mesh (e.g. "frontend", "backend")').option("--mesh-port <port>", "Local port for mesh broker", "49152").option("--mesh-token <token>", "Shared authentication token for mesh").option("--no-mesh", "Disable cross-instance mesh networking").action(async (options) => {
8324
+ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK terminal coding agent that speaks Bangla, Banglish & English.").version(getAppVersion(), "-v, --version", "Output the current version").option("-m, --model <model>", "Override model for this session").option("-M, --mode <mode>", 'Execution mode: "build" (default) or "plan"', "build").option("-p, --prompt <prompt>", "Run a single prompt and exit").option("-y, --yes", "Auto-approve all file writes and shell commands").option("-r, --role <role>", 'Instance role for cross-instance mesh (e.g. "frontend", "backend")').option("--mesh-port <port>", "Local port for mesh broker", "49152").option("--mesh-token <token>", "Shared authentication token for mesh").option("--no-mesh", "Disable cross-instance mesh networking").action(async (options) => {
8325
+ const rawMode = String(options.mode || "build").toLowerCase().trim();
8326
+ if (rawMode !== "build" && rawMode !== "plan") {
8327
+ console.error(chalk9.red(`
8328
+ Invalid --mode "${options.mode}". Expected "build" or "plan".
8329
+ `));
8330
+ process.exit(1);
8331
+ }
8332
+ let parsedMeshPort;
8333
+ if (options.meshPort !== void 0) {
8334
+ const p = Number(options.meshPort);
8335
+ if (!Number.isInteger(p) || p < 1 || p > 65535) {
8336
+ console.error(chalk9.red(`
8337
+ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 65535.
8338
+ `));
8339
+ process.exit(1);
8340
+ }
8341
+ parsedMeshPort = p;
8342
+ }
7819
8343
  if (options.yes) {
7820
8344
  safetySession.autoApproveAll = true;
7821
8345
  }
@@ -7851,13 +8375,13 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7851
8375
  if (options.model) {
7852
8376
  config.model = options.model;
7853
8377
  }
7854
- const initialMode = options.mode === "plan" ? "plan" : "build";
8378
+ const initialMode = rawMode === "plan" ? "plan" : "build";
7855
8379
  const agent = new IUBAgent(config, initialMode);
7856
8380
  let meshNode = null;
7857
- if (!options.noMesh) {
8381
+ if (options.mesh !== false) {
7858
8382
  meshNode = new MeshNode({
7859
8383
  role: options.role,
7860
- port: options.meshPort ? parseInt(options.meshPort, 10) : void 0,
8384
+ port: parsedMeshPort,
7861
8385
  token: options.meshToken,
7862
8386
  mode: initialMode,
7863
8387
  model: config.model,
@@ -8030,8 +8554,9 @@ Error: ${err.message}
8030
8554
  const found = await exploreAndSelectFreeModel(config);
8031
8555
  if (found) {
8032
8556
  agent.updateConfig(config);
8557
+ meshNode?.updateState({ model: config.model });
8033
8558
  updateDockedModel(
8034
- PROVIDER_LABELS[config.provider] || config.provider,
8559
+ formatProviderLabel(config),
8035
8560
  config.model,
8036
8561
  agent.getMode()
8037
8562
  );
@@ -8095,7 +8620,7 @@ Could not find image file at: ${cleanArg}
8095
8620
  }
8096
8621
  if (lowerCmd === "/mode") {
8097
8622
  prepareInteractiveArea(
8098
- PROVIDER_LABELS[config.provider] || config.provider,
8623
+ formatProviderLabel(config),
8099
8624
  config.model,
8100
8625
  agent.getMode()
8101
8626
  );
@@ -8118,6 +8643,7 @@ Could not find image file at: ${cleanArg}
8118
8643
  if (modeChoice) {
8119
8644
  agent.setMode(modeChoice);
8120
8645
  meshNode?.updateState({ mode: modeChoice });
8646
+ updateDockedModel(formatProviderLabel(config), config.model, modeChoice);
8121
8647
  console.log(chalk9.green(`
8122
8648
  Agent mode switched to: ${modeChoice === "build" ? "BUILD Mode" : "PLAN Mode"}
8123
8649
  `));
@@ -8181,42 +8707,7 @@ Agent mode switched to: ${modeChoice === "build" ? "BUILD Mode" : "PLAN Mode"}
8181
8707
  continue;
8182
8708
  }
8183
8709
  if (lowerCmd === "/doctor" || lowerCmd === "/check") {
8184
- const checks = [];
8185
- const nodeVer = process.version;
8186
- const major = parseInt(nodeVer.replace("v", "").split(".")[0], 10);
8187
- checks.push({
8188
- name: "Node.js Runtime",
8189
- status: major >= 18 ? "ok" : "error",
8190
- detail: `${nodeVer} (Node 18+ required for modern async streams)`
8191
- });
8192
- const hasKey = isKeylessConfig(config) || Boolean(config.apiKey && config.apiKey.trim().length > 5);
8193
- checks.push({
8194
- name: "AI Provider & Key",
8195
- status: hasKey ? "ok" : "error",
8196
- detail: `${formatProviderLabel(config)} with model "${config.model}" (${isKeylessConfig(config) ? "Zero-Key Active" : hasKey ? "Configured" : "Missing API Key"})`
8197
- });
8198
- try {
8199
- const testFile = path8.resolve(process.cwd(), ".iubcli_check.tmp");
8200
- fs8.writeFileSync(testFile, "ok", "utf8");
8201
- fs8.unlinkSync(testFile);
8202
- checks.push({
8203
- name: "Workspace Read/Write",
8204
- status: "ok",
8205
- detail: `${process.cwd()} (Read/Write verified)`
8206
- });
8207
- } catch (e) {
8208
- checks.push({
8209
- name: "Workspace Read/Write",
8210
- status: "error",
8211
- detail: `Cannot write to ${process.cwd()}: ${e.message}`
8212
- });
8213
- }
8214
- checks.push({
8215
- name: "OS & Execution Shell",
8216
- status: "ok",
8217
- detail: `${process.platform} (${process.arch}) with non-interactive child process safety`
8218
- });
8219
- renderDoctorReport(checks);
8710
+ await runDoctorDiagnostics(config);
8220
8711
  continue;
8221
8712
  }
8222
8713
  if (lowerCmd === "/diff" || lowerCmd === "/changes") {
@@ -8252,8 +8743,21 @@ ${result.message}
8252
8743
  renderGitStatus();
8253
8744
  continue;
8254
8745
  }
8255
- if (lowerCmd === "/tree") {
8256
- renderDirectoryTree();
8746
+ if (lowerCmd === "/tree" || lowerCmd.startsWith("/tree ")) {
8747
+ const treeArgs = trimmed.slice(5).trim();
8748
+ if (!treeArgs) {
8749
+ renderDirectoryTree();
8750
+ } else {
8751
+ const parts = treeArgs.split(/\s+/);
8752
+ const maybeDepth = Number(parts[0]);
8753
+ if (parts.length === 1 && Number.isInteger(maybeDepth) && maybeDepth > 0 && maybeDepth <= 6) {
8754
+ renderDirectoryTree(".", maybeDepth);
8755
+ } else {
8756
+ const targetDir = parts[0];
8757
+ const depth = parts[1] && Number.isInteger(Number(parts[1])) ? Math.min(6, Math.max(1, Number(parts[1]))) : 2;
8758
+ renderDirectoryTree(targetDir, depth);
8759
+ }
8760
+ }
8257
8761
  continue;
8258
8762
  }
8259
8763
  if (lowerCmd === "/detect" || lowerCmd === "/stack") {
@@ -8282,7 +8786,7 @@ Context window optimized for faster responses and lower token load.
8282
8786
  const mem = agent.getHistoryStats();
8283
8787
  console.log("\n" + chalk9.bold.hex("#00A3FF")("Active Session Status (OpenCode Style)"));
8284
8788
  console.log(chalk9.dim("\u2500".repeat(60)));
8285
- console.log(` ${chalk9.gray("Provider:")} ${chalk9.bold(PROVIDER_LABELS[config.provider])}`);
8789
+ console.log(` ${chalk9.gray("Provider:")} ${chalk9.bold(formatProviderLabel(config))}`);
8286
8790
  console.log(` ${chalk9.gray("Active Model:")} ${chalk9.cyan.bold(config.model)}`);
8287
8791
  console.log(` ${chalk9.gray("Active Mode:")} ${agent.getMode() === "build" ? chalk9.green.bold("BUILD") : chalk9.yellow.bold("PLAN")}`);
8288
8792
  console.log(` ${chalk9.gray("Working Dir:")} ${chalk9.white(process.cwd())}`);
@@ -8344,7 +8848,7 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8344
8848
  }
8345
8849
  continue;
8346
8850
  }
8347
- if (lowerCmd.startsWith("/send ") || lowerCmd.startsWith("/msg ")) {
8851
+ if (lowerCmd === "/send" || lowerCmd === "/msg" || lowerCmd.startsWith("/send ") || lowerCmd.startsWith("/msg ")) {
8348
8852
  const parts = trimmed.split(/\s+/);
8349
8853
  if (parts.length < 3) {
8350
8854
  console.log(chalk9.yellow("\nUsage: /send <role|nodeId> <message>\nExample: /send backend Please implement /api/users route.\n"));
@@ -8368,7 +8872,7 @@ ${result}
8368
8872
  console.log(chalk9.green("Conversation history cleared! Session memory reset.\n"));
8369
8873
  continue;
8370
8874
  }
8371
- if (lowerCmd === "/provider") {
8875
+ if (lowerCmd === "/provider" || lowerCmd === "/providers") {
8372
8876
  prepareInteractiveArea(
8373
8877
  formatProviderLabel(config),
8374
8878
  config.model,
@@ -8378,6 +8882,8 @@ ${result}
8378
8882
  if (newConfig) {
8379
8883
  config = newConfig;
8380
8884
  agent.updateConfig(newConfig);
8885
+ meshNode?.updateState({ model: config.model });
8886
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8381
8887
  console.log(chalk9.green(`
8382
8888
  Provider updated to: ${formatProviderLabel(config)} (${config.model})
8383
8889
  `));
@@ -8391,11 +8897,15 @@ Provider updated to: ${formatProviderLabel(config)} (${config.model})
8391
8897
  agent.getMode()
8392
8898
  );
8393
8899
  const newConfig = await promptConfig(false, config);
8394
- config = newConfig;
8395
- agent.updateConfig(newConfig);
8396
- console.log(chalk9.green(`
8900
+ if (newConfig) {
8901
+ config = newConfig;
8902
+ agent.updateConfig(newConfig);
8903
+ meshNode?.updateState({ model: config.model });
8904
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8905
+ console.log(chalk9.green(`
8397
8906
  Configuration updated: ${formatProviderLabel(config)} (${config.model})
8398
8907
  `));
8908
+ }
8399
8909
  continue;
8400
8910
  }
8401
8911
  const directCategoryShortcuts = {
@@ -8414,6 +8924,8 @@ Configuration updated: ${formatProviderLabel(config)} (${config.model})
8414
8924
  if (newConfig) {
8415
8925
  config = newConfig;
8416
8926
  agent.updateConfig(newConfig);
8927
+ meshNode?.updateState({ model: config.model });
8928
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8417
8929
  console.log(chalk9.green(`
8418
8930
  Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8419
8931
  `));
@@ -8431,11 +8943,15 @@ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8431
8943
  if (directConfig) {
8432
8944
  config = directConfig;
8433
8945
  agent.updateConfig(directConfig);
8946
+ meshNode?.updateState({ model: config.model });
8434
8947
  updateDockedModel(
8435
8948
  formatProviderLabel(config),
8436
8949
  config.model,
8437
8950
  agent.getMode()
8438
8951
  );
8952
+ console.log(chalk9.green(`
8953
+ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8954
+ `));
8439
8955
  }
8440
8956
  continue;
8441
8957
  } else if (query.includes("/") || query.startsWith("gemini-") || query.startsWith("gemma-") || query.startsWith("gpt-")) {
@@ -8455,11 +8971,15 @@ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8455
8971
  if (inferredConfig) {
8456
8972
  config = inferredConfig;
8457
8973
  agent.updateConfig(inferredConfig);
8974
+ meshNode?.updateState({ model: config.model });
8458
8975
  updateDockedModel(
8459
8976
  formatProviderLabel(config),
8460
8977
  config.model,
8461
8978
  agent.getMode()
8462
8979
  );
8980
+ console.log(chalk9.green(`
8981
+ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8982
+ `));
8463
8983
  }
8464
8984
  continue;
8465
8985
  }
@@ -8468,6 +8988,8 @@ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8468
8988
  if (newConfig) {
8469
8989
  config = newConfig;
8470
8990
  agent.updateConfig(newConfig);
8991
+ meshNode?.updateState({ model: config.model });
8992
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8471
8993
  console.log(chalk9.green(`
8472
8994
  Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8473
8995
  `));
@@ -8476,12 +8998,22 @@ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8476
8998
  }
8477
8999
  let isPriorityTask = false;
8478
9000
  let taskPrompt = trimmed;
8479
- if (trimmed.startsWith("/task ") || trimmed.startsWith("/urgent ") || trimmed.startsWith("/priority ")) {
9001
+ if (lowerCmd === "/task" || lowerCmd === "/urgent" || lowerCmd === "/priority") {
9002
+ console.log(chalk9.yellow("\nUsage: /task <description>\nExample: /task Fix login form validation\n"));
9003
+ continue;
9004
+ }
9005
+ if (lowerCmd.startsWith("/task ") || lowerCmd.startsWith("/urgent ") || lowerCmd.startsWith("/priority ")) {
8480
9006
  isPriorityTask = true;
8481
9007
  taskPrompt = trimmed.replace(/^\/(task|urgent|priority)\s+/i, "").trim();
8482
9008
  } else if (/^(urgent|priority|task):\s*/i.test(trimmed)) {
8483
9009
  isPriorityTask = true;
8484
9010
  taskPrompt = trimmed.replace(/^(urgent|priority|task):\s*/i, "").trim();
9011
+ } else if (trimmed.startsWith("/") && !trimmed.startsWith("//") && !/^\/[^\s]+\//.test(trimmed)) {
9012
+ const cmdWord = trimmed.split(/\s+/)[0];
9013
+ console.log(chalk9.yellow(`
9014
+ Unknown command "${cmdWord}". Type ${chalk9.cyan("/help")} to see all available commands.
9015
+ `));
9016
+ continue;
8485
9017
  }
8486
9018
  if (isPriorityTask) {
8487
9019
  renderPriorityTaskBanner(taskPrompt, config.model, agent.getMode());
@@ -8538,6 +9070,7 @@ program.command("agent").alias("model").description("OpenCode-style AI agent & m
8538
9070
  if (!config) {
8539
9071
  config = await promptConfig(true);
8540
9072
  }
9073
+ if (!config) return;
8541
9074
  await selectAgentModelInteractive(config, "build");
8542
9075
  });
8543
9076
  program.command("mode").description("Switch agent mode between BUILD (autonomous coder) and PLAN (architect)").action(async () => {
@@ -8553,51 +9086,16 @@ program.command("about").alias("developer").alias("author").description("Display
8553
9086
  program.command("renewal").alias("countdown").alias("renew").description("Display live token quota renewal countdown and provider reset schedules").action(() => {
8554
9087
  renderAllTokensExhaustedReport();
8555
9088
  });
8556
- program.command("doctor").alias("check").description("Run automated diagnostic check of Node.js runtime, workspace, shell, and provider").action(() => {
8557
- let config = getConfig() || {
9089
+ program.command("doctor").alias("check").description("Run automated diagnostic check of Node.js runtime, workspace, shell, and provider").action(async () => {
9090
+ const config = getConfig() || {
8558
9091
  provider: "gemini",
8559
9092
  apiKey: "",
8560
9093
  model: "gemini-3.5-flash-lite"
8561
9094
  };
8562
- const checks = [];
8563
- const nodeVer = process.version;
8564
- const major = parseInt(nodeVer.replace("v", "").split(".")[0], 10);
8565
- checks.push({
8566
- name: "Node.js Runtime",
8567
- status: major >= 18 ? "ok" : "error",
8568
- detail: `${nodeVer} (Node 18+ required for modern async streams)`
8569
- });
8570
- const hasKey = isKeylessConfig(config) || Boolean(config.apiKey && config.apiKey.trim().length > 5);
8571
- checks.push({
8572
- name: "AI Provider & Key",
8573
- status: hasKey ? "ok" : "error",
8574
- detail: `${formatProviderLabel(config)} with model "${config.model}" (${isKeylessConfig(config) ? "Zero-Key Active" : hasKey ? "Configured" : "Missing API Key"})`
8575
- });
8576
- try {
8577
- const testFile = path8.resolve(process.cwd(), ".iubcli_check.tmp");
8578
- fs8.writeFileSync(testFile, "ok", "utf8");
8579
- fs8.unlinkSync(testFile);
8580
- checks.push({
8581
- name: "Workspace Read/Write",
8582
- status: "ok",
8583
- detail: `${process.cwd()} (Read/Write verified)`
8584
- });
8585
- } catch (e) {
8586
- checks.push({
8587
- name: "Workspace Read/Write",
8588
- status: "error",
8589
- detail: `Cannot write to ${process.cwd()}: ${e.message}`
8590
- });
8591
- }
8592
- checks.push({
8593
- name: "OS & Execution Shell",
8594
- status: "ok",
8595
- detail: `${process.platform} (${process.arch}) with non-interactive child process safety`
8596
- });
8597
- renderDoctorReport(checks);
9095
+ await runDoctorDiagnostics(config);
8598
9096
  });
8599
9097
  program.command("stats").alias("cost").description("Display token limits, pricing, and live cost calculation").action(() => {
8600
- let config = getConfig() || {
9098
+ const config = getConfig() || {
8601
9099
  provider: "gemini",
8602
9100
  apiKey: "",
8603
9101
  model: "gemini-3.5-flash-lite"
@@ -8633,6 +9131,7 @@ program.command("peers").alias("mesh").description("Discover and display connect
8633
9131
  console.log(chalk9.dim("\u2500".repeat(70)) + "\n");
8634
9132
  }
8635
9133
  node.stop();
9134
+ gracefulExit(0);
8636
9135
  });
8637
9136
  program.parse(process.argv);
8638
9137
  //# sourceMappingURL=index.js.map