iubcli 4.2.9 → 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(" \u{1F393} 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
  );
@@ -90,10 +92,10 @@ function renderCascadeNotice(fromModel, toModel, reason) {
90
92
  process.stdout.write("\r\x1B[2K\n");
91
93
  console.log(border);
92
94
  console.log(
93
- chalk.bgHex("#FF9900").black.bold(" \u{1F504} AUTO-CASCADE ACTIVATED ") + " " + chalk.white.bold(`Token / Rate limit reached on: ${chalk.yellow(fromModel)}`)
95
+ chalk.bgHex("#FF9900").black.bold(" AUTO-CASCADE ACTIVATED ") + " " + chalk.white.bold(`Token / Rate limit reached on: ${chalk.yellow(fromModel)}`)
94
96
  );
95
97
  console.log(
96
- chalk.hex("#00A3FF").bold("\u2714 Seamlessly continuing with: ") + chalk.bold.cyan(toModel) + chalk.gray(` (${reason})`)
98
+ chalk.hex("#00A3FF").bold("Seamlessly continuing with: ") + chalk.bold.cyan(toModel) + chalk.gray(` (${reason})`)
97
99
  );
98
100
  console.log(chalk.gray("Your task and conversation continue without any loss of context."));
99
101
  console.log(border + "\n");
@@ -105,10 +107,10 @@ function renderModelExplorationNotice(model, provider, testedCount) {
105
107
  process.stdout.write("\r\x1B[2K\n");
106
108
  console.log(border);
107
109
  console.log(
108
- chalk.bgHex("#002B5C").hex("#00A3FF").bold(" \u{1F50D} MODEL EXPLORER: FREE TOKENS DISCOVERED ") + " " + chalk.white.bold(`Scanned ${testedCount} model(s)`)
110
+ chalk.bgHex("#002B5C").hex("#00A3FF").bold(" MODEL EXPLORER: FREE TOKENS DISCOVERED ") + " " + chalk.white.bold(`Scanned ${testedCount} model(s)`)
109
111
  );
110
112
  console.log(
111
- chalk.green.bold("\u2714 Selected Active Model: ") + chalk.bold.cyan(model) + chalk.gray(` [${provider.toUpperCase()}]`)
113
+ chalk.green.bold("Selected Active Model: ") + chalk.bold.cyan(model) + chalk.gray(` [${provider.toUpperCase()}]`)
112
114
  );
113
115
  console.log(chalk.gray("Active free tokens verified. Seamlessly continuing your coding task..."));
114
116
  console.log(border + "\n");
@@ -120,7 +122,7 @@ function renderRollingRateLimitNotice(model, seconds, reason) {
120
122
  process.stdout.write("\r\x1B[2K\n");
121
123
  console.log(border);
122
124
  console.log(
123
- chalk.bgHex("#1E40AF").white.bold(" \u23F3 ROLLING RATE LIMIT COOLDOWN (NEVER-STOP) ") + " " + chalk.white.bold(`[${chalk.yellow(model)}]`)
125
+ chalk.bgHex("#1E40AF").white.bold(" ROLLING RATE LIMIT COOLDOWN (NEVER-STOP) ") + " " + chalk.white.bold(`[${chalk.yellow(model)}]`)
124
126
  );
125
127
  console.log(
126
128
  chalk.cyan.bold(`Auto-cooling down for ${seconds}s before automatic retry...`) + chalk.gray(reason ? ` (${reason})` : "")
@@ -129,7 +131,7 @@ function renderRollingRateLimitNotice(model, seconds, reason) {
129
131
  console.log(border + "\n");
130
132
  }
131
133
  async function askToolConfirmation(toolName, summary) {
132
- console.log("\n" + chalk.bgHex("#FF9900").black.bold(" \u26A0\uFE0F SAFETY CONFIRMATION "));
134
+ console.log("\n" + chalk.bgHex("#FF9900").black.bold(" SAFETY CONFIRMATION "));
133
135
  console.log(
134
136
  `${chalk.gray("Tool:")} ${chalk.cyan.bold(toolName)}`
135
137
  );
@@ -138,9 +140,9 @@ ${chalk.white(summary)}`);
138
140
  const choice = await interactiveSelect({
139
141
  message: "Allow IUB CLI to execute this action?",
140
142
  options: [
141
- { value: "yes", label: chalk.green("\u2714 Yes, execute this action") },
142
- { value: "all", label: chalk.cyan("\u26A1 Yes to ALL actions (Auto-approve for this session)") },
143
- { value: "no", label: chalk.red("\u2716 No, cancel / reject this action") }
143
+ { value: "yes", label: chalk.green("Yes, execute this action") },
144
+ { value: "all", label: chalk.cyan("Yes to ALL actions (Auto-approve for this session)") },
145
+ { value: "no", label: chalk.red("No, cancel / reject this action") }
144
146
  ]
145
147
  });
146
148
  if (!choice) {
@@ -149,13 +151,15 @@ ${chalk.white(summary)}`);
149
151
  return choice;
150
152
  }
151
153
  function renderToolCall(toolName, args) {
152
- const badge = chalk.bgHex("#0047AB").white.bold(` \u{1F6E0}\uFE0F TOOL: ${toolName} `);
154
+ const badge = chalk.bgHex("#0047AB").white.bold(` TOOL: ${toolName} `);
153
155
  console.log(`
154
156
  ${badge}`);
155
157
  if (toolName === "write_file") {
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,14 +172,20 @@ ${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) {
174
184
  if (isError) {
175
- console.log(chalk.red(`\u2716 [${toolName} error]: ${result.trim()}`));
185
+ console.log(chalk.red(`[${toolName} error]: ${result.trim()}`));
176
186
  } else {
177
187
  const preview = result.length > 300 ? result.slice(0, 300) + "...\n" + chalk.dim(`(truncated ${result.length} chars)`) : result;
178
- console.log(chalk.green(`\u2714 [${toolName} completed]:`));
188
+ console.log(chalk.green(`[${toolName} completed]:`));
179
189
  console.log(chalk.dim(preview.trim()));
180
190
  }
181
191
  }
@@ -191,26 +201,26 @@ function renderPriorityTaskBanner(task, model, mode) {
191
201
  const border = chalk.hex("#00A3FF")("\u2550".repeat(78));
192
202
  console.log("\n" + border);
193
203
  console.log(
194
- chalk.bgHex("#00A3FF").black.bold(" \u26A1 [PRIORITY TASK DISPATCH] ") + " " + chalk.white.bold("Executing specific priority task first (Antigravity mode)")
204
+ chalk.bgHex("#00A3FF").black.bold(" [PRIORITY TASK DISPATCH] ") + " " + chalk.white.bold("Executing specific priority task first (Antigravity mode)")
195
205
  );
196
206
  console.log(
197
- ` ${chalk.gray("Selected Model:")} ${chalk.bold.hex("#00A3FF")(model)} ${chalk.gray("Mode:")} ${mode === "build" ? chalk.green.bold("\u26A1 BUILD") : chalk.yellow.bold("\u{1F4CB} PLAN")} ${chalk.gray("(Press")} ${chalk.yellow.bold("Esc")} ${chalk.gray("anytime to stop)")}`
207
+ ` ${chalk.gray("Selected Model:")} ${chalk.bold.hex("#00A3FF")(model)} ${chalk.gray("Mode:")} ${mode === "build" ? chalk.green.bold("BUILD") : chalk.yellow.bold("PLAN")} ${chalk.gray("(Press")} ${chalk.yellow.bold("Esc")} ${chalk.gray("anytime to stop)")}`
198
208
  );
199
209
  console.log(` ${chalk.gray("Task:")} ${chalk.cyan.bold(task)}`);
200
210
  console.log(border + "\n");
201
211
  }
202
212
  function renderInterruptedNotice() {
203
213
  console.log(
204
- "\n" + chalk.bgHex("#FF3366").white.bold(" \u23F9\uFE0F EXECUTION STOPPED ") + " " + chalk.yellow.bold("Model stopped working by user (Escape key pressed).") + "\n" + chalk.gray("Processes terminated cleanly. Returned to IUB CLI prompt.\n")
214
+ "\n" + chalk.bgHex("#FF3366").white.bold(" EXECUTION STOPPED ") + " " + chalk.yellow.bold("Model stopped working by user (Escape key pressed).") + "\n" + chalk.gray("Processes terminated cleanly. Returned to IUB CLI prompt.\n")
205
215
  );
206
216
  }
207
217
  function renderDoctorReport(checks) {
208
218
  const border = chalk.hex("#00A3FF")("\u2550".repeat(74));
209
219
  console.log("\n" + border);
210
- console.log(chalk.bgHex("#003087").white.bold(" \u{1FA7A} IUB CLI SYSTEM DOCTOR (SYSTEM HEALTH REPORT) "));
220
+ console.log(chalk.bgHex("#003087").white.bold(" IUB CLI SYSTEM DOCTOR (SYSTEM HEALTH REPORT) "));
211
221
  console.log(chalk.gray("Comprehensive diagnostic check of your agent environment:\n"));
212
222
  for (const c of checks) {
213
- const symbol = c.status === "ok" ? chalk.green.bold(" \u2714 [PASS]") : c.status === "warn" ? chalk.yellow.bold(" \u26A0\uFE0F [WARN]") : chalk.red.bold(" \u2716 [FAIL]");
223
+ const symbol = c.status === "ok" ? chalk.green.bold(" [PASS]") : c.status === "warn" ? chalk.yellow.bold(" [WARN]") : chalk.red.bold(" [FAIL]");
214
224
  console.log(`${symbol} ${chalk.white.bold(c.name)}: ${chalk.gray(c.detail)}`);
215
225
  }
216
226
  console.log(border + "\n");
@@ -218,11 +228,11 @@ function renderDoctorReport(checks) {
218
228
  function renderSessionStats(stats) {
219
229
  const border = chalk.hex("#00A3FF")("\u2500".repeat(70));
220
230
  console.log("\n" + border);
221
- console.log(chalk.bgHex("#1A237E").white.bold(" \u{1F4CA} LIVE SESSION INTELLIGENCE & SAVINGS (OpenCode Style) "));
231
+ console.log(chalk.bgHex("#1A237E").white.bold(" LIVE SESSION INTELLIGENCE & SAVINGS (OpenCode Style) "));
222
232
  console.log(chalk.dim("\u2500".repeat(70)));
223
233
  console.log(` ${chalk.gray("Active Provider:")} ${chalk.bold.cyan(stats.provider)}`);
224
234
  console.log(` ${chalk.gray("Selected Model:")} ${chalk.bold.green(stats.model)}`);
225
- console.log(` ${chalk.gray("Current Mode:")} ${stats.mode === "build" ? chalk.green.bold("\u26A1 BUILD") : chalk.yellow.bold("\u{1F4CB} PLAN")}`);
235
+ console.log(` ${chalk.gray("Current Mode:")} ${stats.mode === "build" ? chalk.green.bold("BUILD") : chalk.yellow.bold("PLAN")}`);
226
236
  console.log(` ${chalk.gray("Total LLM Calls:")} ${chalk.bold.yellow(stats.totalRequests)} calls`);
227
237
  console.log(` ${chalk.gray("Total Tokens Used:")} ${chalk.bold.white(stats.totalTokens.toLocaleString())} tokens ${chalk.dim(`(Prompt: ${stats.promptTokens.toLocaleString()} \u2022 Completion: ${stats.completionTokens.toLocaleString()})`)}`);
228
238
  console.log(` ${chalk.gray("Estimated Savings:")} ${chalk.bold.hex("#00A3FF")(`$${stats.estimatedCostSavedUsd.toFixed(3)} USD`)} ${chalk.dim("(vs commercial GPT-4 / Opus)")}`);
@@ -230,11 +240,11 @@ function renderSessionStats(stats) {
230
240
  console.log(border + "\n");
231
241
  }
232
242
  function showHelp() {
233
- console.log("\n" + chalk.bold.hex("#00A3FF")("\u{1F393} IUB CLI Help & Usage Guide"));
243
+ console.log("\n" + chalk.bold.hex("#00A3FF")("IUB CLI Help & Usage Guide"));
234
244
  console.log(chalk.dim("\u2500".repeat(70)));
235
245
  console.log(`${chalk.yellow.bold("Agent Modes (OpenCode Style):")}`);
236
- console.log(` ${chalk.green.bold("\u26A1 BUILD Mode")} - Autonomous full-stack coder. Can create/edit files & run terminal commands.`);
237
- console.log(` ${chalk.yellow.bold("\u{1F4CB} PLAN Mode")} - Senior Architect. Read-only codebase investigation & step-by-step planning.`);
246
+ console.log(` ${chalk.green.bold("BUILD Mode")} - Autonomous full-stack coder. Can create/edit files & run terminal commands.`);
247
+ console.log(` ${chalk.yellow.bold("PLAN Mode")} - Senior Architect. Read-only codebase investigation & step-by-step planning.`);
238
248
  console.log(`
239
249
  ${chalk.yellow.bold("Slash Commands in Chat (OpenCode & Antigravity Style):")}`);
240
250
  console.log(` ${chalk.cyan("/explore")} - Explore all models and auto-select the model with active free tokens (alias: /find-model, /scan)`);
@@ -301,20 +311,20 @@ ${chalk.yellow.bold("Language Support (Outputs strictly in English):")}`);
301
311
  }
302
312
  function showFreeApiKeyGuide() {
303
313
  const line = chalk.dim("\u2500".repeat(78));
304
- console.log("\n" + chalk.bgHex("#003087").white.bold(" \u{1F511} FREE API KEYS & MODELS GUIDE (100% Free Coding Tier) "));
314
+ console.log("\n" + chalk.bgHex("#003087").white.bold(" FREE API KEYS & MODELS GUIDE (100% Free Coding Tier) "));
305
315
  console.log(chalk.gray("Get free API keys with generous quotas for IUB CLI - no credit card required!\n"));
306
- console.log(chalk.bold.hex("#00A3FF")("1. Google Gemini (Google AI Studio) - \u{1F31F} RECOMMENDED"));
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
- console.log(` ${chalk.gray("Steps:")} Sign in with Google \u2794 Click "${chalk.white("Create API Key")}" \u2794 Copy key.`);
309
- console.log(` ${chalk.gray("Best Free Model:")} ${chalk.bold.yellow("gemini-2.0-flash")} (\u{1F31F} 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")}`);
318
+ console.log(` ${chalk.gray("Steps:")} Sign in with Google -> Click "${chalk.white("Create API Key")}" -> Copy key.`);
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)"));
314
324
  console.log(` ${chalk.gray("Direct Link:")} ${chalk.bold.underline.cyan("https://openrouter.ai/keys")}`);
315
- console.log(` ${chalk.gray("Steps:")} Sign in with GitHub/Google \u2794 Click "${chalk.white("Create Key")}" \u2794 Copy key.`);
325
+ console.log(` ${chalk.gray("Steps:")} Sign in with GitHub/Google -> Click "${chalk.white("Create Key")}" -> Copy key.`);
316
326
  console.log(` ${chalk.gray("Top Free Agent Models (Zero Cost):")}`);
317
- console.log(` \u2022 ${chalk.yellow("openrouter/free")} (\u{1F31F} Auto Best Free Model - Zero downtime)`);
327
+ console.log(` \u2022 ${chalk.yellow("openrouter/free")} (Auto Best Free Model - Zero downtime)`);
318
328
  console.log(` \u2022 ${chalk.yellow("particle-ai/particle-1:free")} (1 Million token context agentic coding model)`);
319
329
  console.log(` \u2022 ${chalk.yellow("nvidia/nemotron-3-ultra-550b-a55b:free")} (Massive 550B frontier model, 1M context)`);
320
330
  console.log(` \u2022 ${chalk.yellow("google/gemma-4-31b-it:free")} (Google DeepMind 31B code instruction model)`);
@@ -324,9 +334,9 @@ function showFreeApiKeyGuide() {
324
334
  console.log(` \u2022 ${chalk.yellow("inclusionai/ling-3.2-flash:free")} (1M token context hybrid reasoning)`);
325
335
  console.log(` ${chalk.gray("Quota:")} 100% Free with zero payment or credit card needed!
326
336
  `);
327
- console.log(chalk.bold.hex("#00D2FF")("3. DeepSeek Platform (5,000,000 Free Tokens - \u{1F31F} SOTA Coding)"));
337
+ console.log(chalk.bold.hex("#00D2FF")("3. DeepSeek Platform (5,000,000 Free Tokens - SOTA Coding)"));
328
338
  console.log(` ${chalk.gray("Direct Link:")} ${chalk.bold.underline.cyan("https://platform.deepseek.com")}`);
329
- console.log(` ${chalk.gray("Steps:")} Sign up with Email/Google \u2794 Create API Key \u2794 5 Million free tokens credited.`);
339
+ console.log(` ${chalk.gray("Steps:")} Sign up with Email/Google -> Create API Key -> 5 Million free tokens credited.`);
330
340
  console.log(` ${chalk.gray("In IUB CLI:")} Select "${chalk.white("Custom OpenAI-Compatible")}"`);
331
341
  console.log(` ${chalk.gray("Base URL:")} ${chalk.cyan("https://api.deepseek.com/v1")}`);
332
342
  console.log(` ${chalk.gray("Models:")} ${chalk.yellow("deepseek-chat")} (V3 Coding), ${chalk.yellow("deepseek-reasoner")} (R1 Chain-of-Thought)`);
@@ -353,12 +363,12 @@ function showFreeApiKeyGuide() {
353
363
  console.log(` ${chalk.gray("API Key:")} Any text (e.g. ${chalk.white("ollama")})
354
364
  `);
355
365
  console.log(line);
356
- console.log(chalk.cyan(`\u{1F4A1} Tip: Use ${chalk.yellow.bold("/provider")} or ${chalk.yellow.bold("/config")} in chat to switch anytime!
366
+ console.log(chalk.cyan(`Tip: Use ${chalk.yellow.bold("/provider")} or ${chalk.yellow.bold("/config")} in chat to switch anytime!
357
367
  `));
358
368
  }
359
369
  function showTokenLimitsGuide() {
360
370
  const line = chalk.dim("\u2500".repeat(88));
361
- console.log("\n" + chalk.bgHex("#0047AB").white.bold(" \u{1F4CA} COMPLETE TOKEN LIMITS & RATE LIMITS GUIDE (ALL MODELS) "));
371
+ console.log("\n" + chalk.bgHex("#0047AB").white.bold(" COMPLETE TOKEN LIMITS & RATE LIMITS GUIDE (ALL MODELS) "));
362
372
  console.log(chalk.gray("Exact context window tokens, rate limits (RPM/TPM), and daily quotas for all 83+ models in IUB CLI:\n"));
363
373
  console.log(chalk.bold.hex("#00A3FF")("1. Google Gemini Suite (Google AI Studio Free Tier)"));
364
374
  console.log(chalk.dim("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"));
@@ -371,7 +381,7 @@ function showTokenLimitsGuide() {
371
381
  console.log(chalk.dim("\u2502") + chalk.green(" gemini-2.0-flash ") + chalk.dim("\u2502") + chalk.white(" 1,048,576 toks ") + chalk.dim("\u2502") + chalk.yellow(" 15 RPM ") + chalk.dim("\u2502") + chalk.cyan(" 1,000,000 TPM") + chalk.dim("\u2502") + chalk.green(" Auto->3.5 ") + chalk.dim("\u2502"));
372
382
  console.log(chalk.dim("\u2502") + chalk.green(" gemini-1.5-pro ") + chalk.dim("\u2502") + chalk.cyan(" 2,097,152 toks ") + chalk.dim("\u2502") + chalk.yellow(" 5 RPM ") + chalk.dim("\u2502") + chalk.cyan(" 1,000,000 TPM") + chalk.dim("\u2502") + chalk.yellow(" 50 RPD ") + chalk.dim("\u2502"));
373
383
  console.log(chalk.dim("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"));
374
- console.log(chalk.gray("\u2139\uFE0F Daily resets at 00:00 UTC. Gemini 3.5 Flash Lite is the primary autonomous coding model.\n"));
384
+ console.log(chalk.gray("Daily resets at 00:00 UTC. Gemini 3.5 Flash Lite is the primary autonomous coding model.\n"));
375
385
  console.log(chalk.bold.hex("#00A3FF")("2. 100% Free OpenRouter Models (Zero-Plan Coding Fleet)"));
376
386
  console.log(chalk.dim("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"));
377
387
  console.log(chalk.dim("\u2502") + chalk.bold(" Model ") + chalk.dim("\u2502") + chalk.bold(" Context Window ") + chalk.dim("\u2502") + chalk.bold(" Rate Limit ") + chalk.dim("\u2502") + chalk.bold(" Free Tier ") + chalk.dim("\u2502"));
@@ -395,7 +405,7 @@ function showTokenLimitsGuide() {
395
405
  console.log(chalk.dim("\u2502") + chalk.green(" liquid/lfm-3-1.7b:free ") + chalk.dim("\u2502") + chalk.white(" 32,768 toks ") + chalk.dim("\u2502") + chalk.yellow(" 20 RPM ") + chalk.dim("\u2502") + chalk.green(" Edge Free ") + chalk.dim("\u2502"));
396
406
  console.log(chalk.dim("\u2502") + chalk.green(" recursive/flint-v1.0:free ") + chalk.dim("\u2502") + chalk.white(" 131,072 toks ") + chalk.dim("\u2502") + chalk.yellow(" 20 RPM ") + chalk.dim("\u2502") + chalk.green(" 128K Free ") + chalk.dim("\u2502"));
397
407
  console.log(chalk.dim("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"));
398
- console.log(chalk.gray("\u2139\uFE0F 100% Free on OpenRouter with zero credit card required. Free tier rate limits reset daily.\n"));
408
+ console.log(chalk.gray("100% Free on OpenRouter with zero credit card required. Free tier rate limits reset daily.\n"));
399
409
  console.log(chalk.bold.hex("#00A3FF")("3. DeepSeek Platform Models (platform.deepseek.com)"));
400
410
  console.log(` \u2022 ${chalk.white("deepseek-chat")} (V3/V2.5) : ${chalk.cyan("128,000 tokens")} context | Rolling RPM | ${chalk.green("5,000,000 Free Starter Tokens")}`);
401
411
  console.log(` \u2022 ${chalk.white("deepseek-reasoner")} (R1) : ${chalk.cyan("128,000 tokens")} context | Deep CoT reasoning | ${chalk.green("5,000,000 Free Starter Tokens")}`);
@@ -411,7 +421,7 @@ function showTokenLimitsGuide() {
411
421
  console.log(chalk.dim("\u2502") + chalk.green(" mixtral-8x7b-32768 ") + chalk.dim("\u2502") + chalk.white(" 32,768 toks ") + chalk.dim("\u2502") + chalk.yellow(" 30 RPM ") + chalk.dim("\u2502") + chalk.cyan(" 5,000 TPM ") + chalk.dim("\u2502") + chalk.green(" 14,400 RPD ") + chalk.dim("\u2502"));
412
422
  console.log(chalk.dim("\u2502") + chalk.green(" gemma2-9b-it ") + chalk.dim("\u2502") + chalk.white(" 8,192 toks ") + chalk.dim("\u2502") + chalk.yellow(" 30 RPM ") + chalk.dim("\u2502") + chalk.cyan(" 15,000 TPM ") + chalk.dim("\u2502") + chalk.green(" 14,400 RPD ") + chalk.dim("\u2502"));
413
423
  console.log(chalk.dim("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"));
414
- console.log(chalk.gray("\u2139\uFE0F Groq delivers 500+ tokens/second inference with a generous 14,400 requests/day free quota!\n"));
424
+ console.log(chalk.gray("Groq delivers 500+ tokens/second inference with a generous 14,400 requests/day free quota!\n"));
415
425
  console.log(chalk.bold.hex("#00A3FF")("5. Frontier Flagship Coding Agents (OpenRouter / BYOK)"));
416
426
  console.log(` \u2022 ${chalk.white("anthropic/claude-3.5-sonnet")} : ${chalk.cyan("200,000 tokens")} context | Top-ranked coding benchmark model`);
417
427
  console.log(` \u2022 ${chalk.white("openai/gpt-4o")} : ${chalk.cyan("128,000 tokens")} context | Flagship multimodal developer agent`);
@@ -419,14 +429,14 @@ 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
  `);
426
436
  console.log(line);
427
437
  console.log(
428
438
  chalk.cyan(
429
- `\u{1F4A1} Switch Model Anytime: Run ${chalk.yellow.bold("/agent")} or ${chalk.yellow.bold("/model [name]")} | Check Token Renewal Countdown: ${chalk.yellow.bold("/renewal")}
439
+ `Switch Model Anytime: Run ${chalk.yellow.bold("/agent")} or ${chalk.yellow.bold("/model [name]")} | Check Token Renewal Countdown: ${chalk.yellow.bold("/renewal")}
430
440
  `
431
441
  )
432
442
  );
@@ -434,30 +444,43 @@ function showTokenLimitsGuide() {
434
444
  function renderGitStatus() {
435
445
  const border = chalk.hex("#00A3FF")("\u2500".repeat(70));
436
446
  console.log("\n" + border);
437
- console.log(chalk.bgHex("#003087").white.bold(" \u{1F33F} GIT REPOSITORY STATUS "));
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
- console.log(` ${chalk.gray("Working Tree:")} ${chalk.green("\u2714 Working directory is clean")}`);
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(` \u{1F4C2} 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,24 +539,24 @@ 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() {
517
546
  const brand = chalk.hex("#00A3FF").bold;
518
547
  const accentGold = chalk.hex("#FFC72C").bold;
519
548
  const dim = chalk.gray;
520
- console.log("\n" + chalk.bgHex("#003087").white.bold(" \u{1F393} ABOUT IUB CLI ") + "\n");
549
+ console.log("\n" + chalk.bgHex("#003087").white.bold(" ABOUT IUB CLI ") + "\n");
521
550
  console.log(
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)));
529
558
  console.log(`
530
- ${chalk.bold.hex("#00A3FF")("\u{1F468}\u200D\u{1F4BB} CREATOR & LEAD DEVELOPER:")}`);
559
+ ${chalk.bold.hex("#00A3FF")("CREATOR & LEAD DEVELOPER:")}`);
531
560
  console.log(` ${chalk.bold.white("Developer Name:")} ${chalk.bold.hex("#00A3FF")("Ifaz MD Zahin")}`);
532
561
  console.log(
533
562
  ` ${chalk.bold.white("GitHub Account:")} ${chalk.bold.underline.cyan("https://github.com/Ifaz2611")} ${chalk.dim("(@Ifaz2611)")}`
@@ -572,11 +601,11 @@ function renderAllTokensExhaustedReport() {
572
601
  const utcResetStr = "00:00:00 UTC";
573
602
  const border = chalk.hex("#FF3366")("\u2550".repeat(76));
574
603
  console.log("\n" + border);
575
- console.log(" " + chalk.bgHex("#D32F2F").white.bold(" \u{1F6D1} ALL FREE MODEL TOKENS EXHAUSTED ACROSS ALL AGENTS "));
604
+ console.log(" " + chalk.bgHex("#D32F2F").white.bold(" ALL FREE MODEL TOKENS EXHAUSTED ACROSS ALL AGENTS "));
576
605
  console.log(chalk.yellow.bold("\n IUB CLI has exhaustively cycled through all available free models in the CLI."));
577
606
  console.log(chalk.gray(" All free daily rate limits and per-minute quotas have been temporarily reached."));
578
607
  console.log(chalk.dim("\u2500".repeat(76)));
579
- console.log(chalk.bold.hex("#00A3FF")("\n \u23F3 NEXT GLOBAL TOKEN QUOTA RENEWAL IN:"));
608
+ console.log(chalk.bold.hex("#00A3FF")("\n NEXT GLOBAL TOKEN QUOTA RENEWAL IN:"));
580
609
  console.log(
581
610
  ` ${chalk.bgHex("#1A237E").white.bold(
582
611
  ` ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds `
@@ -586,7 +615,7 @@ function renderAllTokensExhaustedReport() {
586
615
  console.log(
587
616
  ` ${chalk.dim("\u2022")} Reset Time (Local): ${chalk.green.bold(localResetStr)} (Your local timezone)`
588
617
  );
589
- console.log(chalk.bold.yellow("\n \u{1F4CB} Quota Renewal Schedule by Provider:"));
618
+ console.log(chalk.bold.yellow("\n Quota Renewal Schedule by Provider:"));
590
619
  console.log(
591
620
  ` 1. ${chalk.bold.white("Google Gemini Free Tier")} : Resets ${chalk.green("1,500 Requests/day")} & ${chalk.cyan("1M TPM")} daily at 00:00 UTC`
592
621
  );
@@ -600,7 +629,7 @@ function renderAllTokensExhaustedReport() {
600
629
  ` 4. ${chalk.bold.white("DeepSeek Platform")} : Rolling RPM resets every minute; daily grants refresh at 00:00 UTC`
601
630
  );
602
631
  console.log(chalk.dim("\u2500".repeat(76)));
603
- console.log(chalk.bold.cyan("\n \u{1F4A1} WHAT YOU CAN DO RIGHT NOW (NO WAITING REQUIRED):"));
632
+ console.log(chalk.bold.cyan("\n WHAT YOU CAN DO RIGHT NOW (NO WAITING REQUIRED):"));
604
633
  console.log(` 1. ${chalk.green.bold("Run Local Offline Models (UNLIMITED TOKENS, ZERO LIMITS):")}`);
605
634
  console.log(` Use Ollama for 100% free offline coding on your local CPU/GPU.`);
606
635
  console.log(
@@ -644,7 +673,7 @@ function undoLastChange() {
644
673
  fs2.unlinkSync(targetFile);
645
674
  return {
646
675
  success: true,
647
- message: `\u2714 Undid creation of "${lastChange.filePath}" (file removed).`
676
+ message: `Undid creation of "${lastChange.filePath}" (file removed).`
648
677
  };
649
678
  }
650
679
  } else {
@@ -652,11 +681,11 @@ function undoLastChange() {
652
681
  fs2.writeFileSync(targetFile, lastChange.previousContent, "utf8");
653
682
  return {
654
683
  success: true,
655
- message: `\u2714 Reverted "${lastChange.filePath}" to its previous version (${lastChange.previousContent.length} bytes).`
684
+ message: `Reverted "${lastChange.filePath}" to its previous version (${lastChange.previousContent.length} bytes).`
656
685
  };
657
686
  }
658
687
  }
659
- return { success: true, message: `\u2714 Reverted "${lastChange.filePath}".` };
688
+ return { success: true, message: `Reverted "${lastChange.filePath}".` };
660
689
  } catch (err) {
661
690
  return { success: false, message: `Failed to undo "${lastChange.filePath}": ${err.message}` };
662
691
  }
@@ -763,7 +792,7 @@ Preview (first 5 lines):
763
792
  return `Action rejected: User declined writing to "${filePath}".`;
764
793
  } else if (decision === "all") {
765
794
  safetySession.autoApproveAll = true;
766
- console.log(chalk2.cyan("\u26A1 Auto-approve enabled for this session."));
795
+ console.log(chalk2.cyan("Auto-approve enabled for this session."));
767
796
  }
768
797
  }
769
798
  try {
@@ -838,16 +867,19 @@ With: ${effectiveReplacement.split("\n").length} line(s) (${effectiveReplacement
838
867
  return `Action rejected: User declined editing "${filePath}".`;
839
868
  } else if (decision === "all") {
840
869
  safetySession.autoApproveAll = true;
841
- console.log(chalk2.cyan("\u26A1 Auto-approve enabled for this session."));
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,
@@ -856,7 +888,7 @@ With: ${effectiveReplacement.split("\n").length} line(s) (${effectiveReplacement
856
888
  fs2.writeFileSync(targetFile, updatedContent, "utf8");
857
889
  const beforeLines = effectiveTarget.split("\n").length;
858
890
  const afterLines = effectiveReplacement.split("\n").length;
859
- return `\u2714 Successfully edited "${filePath}" (surgically replaced ${beforeLines} line(s) with ${afterLines} line(s)).`;
891
+ return `Successfully edited "${filePath}" (surgically replaced ${beforeLines} line(s) with ${afterLines} line(s)).`;
860
892
  }
861
893
  var commandExecutionMutex = Promise.resolve();
862
894
  async function runCommand(command, signal) {
@@ -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)}
@@ -919,7 +980,7 @@ ${chalk2.gray("Working Directory:")} ${process.cwd()}`;
919
980
  return `Action rejected: User cancelled execution of command "${command}".`;
920
981
  } else if (decision === "all") {
921
982
  safetySession.autoApproveAll = true;
922
- console.log(chalk2.cyan("\u26A1 Auto-approve enabled for this session."));
983
+ console.log(chalk2.cyan("Auto-approve enabled for this session."));
923
984
  }
924
985
  }
925
986
  if (signal?.aborted) {
@@ -930,59 +991,89 @@ ${chalk2.gray("Working Directory:")} ${process.cwd()}`;
930
991
  console.log(
931
992
  chalk2.cyan(
932
993
  `
933
- \u26A1 Continuous Execution: Running ${chalk2.bold(subCommands.length)} commands strictly one by one...`
994
+ Continuous Execution: Running ${chalk2.bold(subCommands.length)} commands strictly one by one...`
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).";
940
1002
  }
941
1003
  const sub = subCommands[i];
942
1004
  console.log(chalk2.cyan(`
943
- \u26A1 Step ${i + 1}/${subCommands.length}: ${chalk2.bold(sub)}`));
944
- const res = await runActualProcess(sub, signal);
1005
+ Step ${i + 1}/${subCommands.length}: ${chalk2.bold(sub)}`));
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")) {
948
1017
  console.log(chalk2.yellow(`
949
- \u26A0\uFE0F Step ${i + 1} exited with error. Stopping subsequent steps immediately.`));
1018
+ Step ${i + 1} exited with error. Stopping subsequent steps immediately.`));
950
1019
  break;
951
1020
  }
952
1021
  }
953
1022
  return stepResults.join("\n\n");
954
1023
  }
955
1024
  console.log(chalk2.cyan(`
956
- \u26A1 Running command: ${chalk2.bold(command)}...`));
957
- return await runActualProcess(command, signal);
1025
+ Running command: ${chalk2.bold(command)}...`));
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;
961
1030
  const nodeModuleMatch = combined.match(/(?:Cannot find module|Module not found: Can't resolve) ['"]([^'"]+)['"]/i);
962
1031
  if (nodeModuleMatch && nodeModuleMatch[1] && !nodeModuleMatch[1].startsWith(".")) {
963
1032
  const pkg = nodeModuleMatch[1].startsWith("@") ? nodeModuleMatch[1].split("/").slice(0, 2).join("/") : nodeModuleMatch[1].split("/")[0];
964
- return `\u{1F4A1} IUB CLI Smart Diagnostic: Missing npm package "${pkg}" detected. Recommendation: run "npm install ${pkg}" to install it.`;
1033
+ return `IUB CLI Smart Diagnostic: Missing npm package "${pkg}" detected. Recommendation: run "npm install ${pkg}" to install it.`;
965
1034
  }
966
1035
  const pyModuleMatch = combined.match(/(?:ModuleNotFoundError: No module named|ImportError: cannot import name) ['"]([^'"]+)['"]/i);
967
1036
  if (pyModuleMatch && pyModuleMatch[1]) {
968
- return `\u{1F4A1} IUB CLI Smart Diagnostic: Missing Python package "${pyModuleMatch[1]}" detected. Recommendation: run "pip install ${pyModuleMatch[1]}".`;
1037
+ return `IUB CLI Smart Diagnostic: Missing Python package "${pyModuleMatch[1]}" detected. Recommendation: run "pip install ${pyModuleMatch[1]}".`;
969
1038
  }
970
1039
  const portMatch = combined.match(/EADDRINUSE.*?[:\s](\d{4,5})\b/i) || combined.match(/port (\d{4,5}) is already in use/i);
971
1040
  if (portMatch) {
972
- return `\u{1F4A1} IUB CLI Smart Diagnostic: Port ${portMatch[1]} is already occupied. Recommendation: use a different port (e.g. PORT=${parseInt(portMatch[1], 10) + 1}) or terminate the existing process.`;
1041
+ return `IUB CLI Smart Diagnostic: Port ${portMatch[1]} is already occupied. Recommendation: use a different port (e.g. PORT=${parseInt(portMatch[1], 10) + 1}) or terminate the existing process.`;
973
1042
  }
974
1043
  const tsErrorMatch = combined.match(/error TS(\d+):/i);
975
1044
  if (tsErrorMatch) {
976
- return `\u{1F4A1} IUB CLI Smart Diagnostic: TypeScript compilation error (TS${tsErrorMatch[1]}) detected. Inspect the file and line number shown in the error log above and use edit_file or write_file to fix it.`;
1045
+ return `IUB CLI Smart Diagnostic: TypeScript compilation error (TS${tsErrorMatch[1]}) detected. Inspect the file and line number shown in the error log above and use edit_file or write_file to fix it.`;
977
1046
  }
978
1047
  if (combined.includes("has no upstream branch") || combined.includes("set-upstream")) {
979
1048
  const branchMatch = combined.match(/git push --set-upstream origin ([^\s]+)/i);
980
1049
  const branchName = branchMatch ? branchMatch[1] : "main";
981
- return `\u{1F4A1} IUB CLI Smart Diagnostic: Git remote branch has no upstream. Recommendation: run "git push -u origin ${branchName}".`;
1050
+ return `IUB CLI Smart Diagnostic: Git remote branch has no upstream. Recommendation: run "git push -u origin ${branchName}".`;
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,14 +1383,17 @@ 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")) {
1262
- const errorMsg = `\u26A0\uFE0F 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.`;
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)) {
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);
1265
1399
  return errorMsg;
@@ -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;
@@ -1844,7 +1989,7 @@ function loadImagePayload(filePath) {
1844
1989
  if (!isImageFile(resolved)) return null;
1845
1990
  if (stat.size > 15 * 1024 * 1024) {
1846
1991
  console.log(chalk3.yellow(`
1847
- \u26A0\uFE0F Image "${filePath}" is larger than 15MB. Skipping.
1992
+ Image "${filePath}" is larger than 15MB. Skipping.
1848
1993
  `));
1849
1994
  return null;
1850
1995
  }
@@ -1976,7 +2121,7 @@ function getDockedRows(rows) {
1976
2121
  };
1977
2122
  }
1978
2123
  function renderTopBorder(width, isBuild, model, borderColor) {
1979
- const modeText = isBuild ? " \u26A1 BUILD " : " \u{1F4CB} PLAN ";
2124
+ const modeText = isBuild ? " BUILD " : " PLAN ";
1980
2125
  const modeBadge = isBuild ? chalk4.bgHex("#00C853").black.bold(modeText) : chalk4.bgHex("#FFB300").black.bold(modeText);
1981
2126
  const modeWidth = stringWidth(modeText);
1982
2127
  let rightText = " (Tab: model \u2022 Esc: clear) ";
@@ -1993,10 +2138,10 @@ function renderTopBorder(width, isBuild, model, borderColor) {
1993
2138
  if (modelDisplay.includes("/")) {
1994
2139
  modelDisplay = modelDisplay.split("/").pop() || modelDisplay;
1995
2140
  }
1996
- let modelText = ` \u{1F916} ${modelDisplay} `;
2141
+ let modelText = ` ${modelDisplay} `;
1997
2142
  while (stringWidth(modelText) > availForModel && modelDisplay.length > 1) {
1998
2143
  modelDisplay = modelDisplay.slice(0, -1);
1999
- modelText = ` \u{1F916} ${modelDisplay}\u2026 `;
2144
+ modelText = ` ${modelDisplay}\u2026 `;
2000
2145
  }
2001
2146
  const modelBadge = chalk4.bgHex("#1A237E").white.bold(modelText);
2002
2147
  const modelWidth = stringWidth(modelText);
@@ -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);
@@ -2063,7 +2222,7 @@ function renderHintLine(width, hintText, borderColor) {
2063
2222
  return borderColor("\u2502 ") + chalk4.dim(visibleHint) + " ".repeat(paddingSpaces) + suffix;
2064
2223
  }
2065
2224
  function renderStatusLine(width, statusText, borderColor) {
2066
- const prefix = borderColor("\u2502 ") + chalk4.cyan("\u23F3 ");
2225
+ const prefix = borderColor("\u2502 ");
2067
2226
  const textCapacity = Math.max(1, width - 6);
2068
2227
  let visibleText = statusText;
2069
2228
  while (stringWidth(visibleText) > textCapacity && visibleText.length > 0) {
@@ -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));
@@ -2260,7 +2424,7 @@ async function interactiveSelect(config) {
2260
2424
  }
2261
2425
  const chosen = config.options[cursor];
2262
2426
  process.stdout.write(
2263
- chalk4.hex("#00A3FF")("\u2714 ") + chalk4.bold(config.message) + " " + chalk4.hex("#00A3FF").bold(chosen.label) + "\n\n"
2427
+ chalk4.bold(config.message) + " " + chalk4.hex("#00A3FF").bold(chosen.label) + "\n\n"
2264
2428
  );
2265
2429
  resolve(chosen.value);
2266
2430
  };
@@ -2269,11 +2433,9 @@ async function interactiveSelect(config) {
2269
2433
  if (lastLineCount > 0) {
2270
2434
  process.stdout.write(`\x1B[${lastLineCount}A\r\x1B[J`);
2271
2435
  }
2272
- process.stdout.write(
2273
- chalk4.gray("\u2716 ") + chalk4.dim(`${config.message} (cancelled)
2436
+ process.stdout.write(chalk4.dim(`${config.message} (cancelled)
2274
2437
 
2275
- `)
2276
- );
2438
+ `));
2277
2439
  resolve(null);
2278
2440
  };
2279
2441
  const onResize = () => {
@@ -2308,13 +2470,13 @@ async function interactiveSelect(config) {
2308
2470
  continue;
2309
2471
  }
2310
2472
  if (rest.startsWith("\x1B[5~")) {
2311
- cursor = Math.max(0, cursor - maxVisible);
2473
+ cursor = Math.max(0, cursor - getMaxVisible());
2312
2474
  idx += 4;
2313
2475
  dirty = true;
2314
2476
  continue;
2315
2477
  }
2316
2478
  if (rest.startsWith("\x1B[6~")) {
2317
- cursor = Math.min(config.options.length - 1, cursor + maxVisible);
2479
+ cursor = Math.min(config.options.length - 1, cursor + getMaxVisible());
2318
2480
  idx += 4;
2319
2481
  dirty = true;
2320
2482
  continue;
@@ -2451,7 +2613,7 @@ async function interactiveInput(config) {
2451
2613
  const shown = value.length === 0 && config.placeholder ? chalk4.dim(truncateWithAnsi(config.placeholder, safeWidth2 - 6)) : chalk4.white(visible);
2452
2614
  lines.push(` ${chalk4.hex("#00A3FF").bold("\u276F")} ${shown}`);
2453
2615
  if (errorMsg) {
2454
- lines.push(chalk4.red(` \u2716 ${truncateWithAnsi(errorMsg, safeWidth2 - 6)}`));
2616
+ lines.push(chalk4.red(` ${truncateWithAnsi(errorMsg, safeWidth2 - 6)}`));
2455
2617
  } else {
2456
2618
  lines.push(chalk4.dim(" Enter: confirm \u2022 Esc: cancel"));
2457
2619
  }
@@ -2494,14 +2656,14 @@ async function interactiveInput(config) {
2494
2656
  finishClear();
2495
2657
  const shownDone = config.mask ? chalk4.dim("\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022") : chalk4.hex("#00A3FF").bold(value || "(empty)");
2496
2658
  process.stdout.write(
2497
- chalk4.hex("#00A3FF")("\u2714 ") + chalk4.bold(config.message) + " " + shownDone + "\n\n"
2659
+ chalk4.bold(config.message) + " " + shownDone + "\n\n"
2498
2660
  );
2499
2661
  resolve(value);
2500
2662
  };
2501
2663
  const cancel = () => {
2502
2664
  cleanup();
2503
2665
  finishClear();
2504
- process.stdout.write(chalk4.gray("\u2716 ") + chalk4.dim(`${config.message} (cancelled)
2666
+ process.stdout.write(chalk4.dim(`${config.message} (cancelled)
2505
2667
 
2506
2668
  `));
2507
2669
  resolve(null);
@@ -2757,7 +2919,14 @@ async function readInlinePrompt(options) {
2757
2919
  let historyIdx = -1;
2758
2920
  let savedDraft = "";
2759
2921
  const boxWidth = getSafeBoxWidth();
2922
+ const textCapacity = Math.max(1, boxWidth - 6);
2760
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
+ };
2761
2930
  process.stdout.write(renderTopBorder(boxWidth, isBuildMode, options.model, borderColor) + "\n");
2762
2931
  process.stdout.write(renderContentLine(boxWidth, "", true, isBuildMode, borderColor) + "\n");
2763
2932
  process.stdout.write(renderHintLine(boxWidth, hintText, borderColor) + "\n");
@@ -2769,10 +2938,10 @@ async function readInlinePrompt(options) {
2769
2938
  bufferLines[cursorLine],
2770
2939
  cursorLine === 0,
2771
2940
  isBuildMode,
2772
- borderColor
2941
+ borderColor,
2942
+ cursorCol
2773
2943
  );
2774
- const activeCol = 5 + Math.min(cursorCol, boxWidth - 8);
2775
- process.stdout.write(`\r${lineStr}\r\x1B[${activeCol}G`);
2944
+ process.stdout.write(`\r${lineStr}\r\x1B[${getActiveCol()}G`);
2776
2945
  };
2777
2946
  const redrawFrom = (startLine) => {
2778
2947
  if (cursorLine > startLine) {
@@ -2780,15 +2949,23 @@ async function readInlinePrompt(options) {
2780
2949
  }
2781
2950
  const lines = [];
2782
2951
  for (let i = startLine; i < bufferLines.length; i++) {
2783
- 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
+ );
2784
2962
  }
2785
2963
  lines.push(renderHintLine(boxWidth, hintText, borderColor));
2786
2964
  lines.push(renderBottomBorder(boxWidth, borderColor));
2787
2965
  process.stdout.write("\r\x1B[J");
2788
2966
  process.stdout.write(lines.join("\n"));
2789
2967
  const linesUp = lines.length - 1 - (cursorLine - startLine);
2790
- const activeCol = 5 + Math.min(cursorCol, boxWidth - 8);
2791
- process.stdout.write(`\x1B[${linesUp}A\r\x1B[${activeCol}G`);
2968
+ process.stdout.write(`\x1B[${linesUp}A\r\x1B[${getActiveCol()}G`);
2792
2969
  };
2793
2970
  const cleanup = () => {
2794
2971
  _dockedPromptActive = false;
@@ -2898,165 +3075,239 @@ async function readInlinePrompt(options) {
2898
3075
  handlePastedText(str);
2899
3076
  return;
2900
3077
  }
2901
- if (str === "") {
2902
- cleanup();
2903
- const down = bufferLines.length - cursorLine;
2904
- process.stdout.write(`\x1B[${down}B\r
2905
- `);
2906
- process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
2907
- process.exit(0);
2908
- }
2909
- if (str === " " || str === " " || str === "\x1BOQ" || str === "\x1B[12~") {
2910
- cleanup();
2911
- const linesUpToTop = cursorLine + 1;
2912
- process.stdout.write(`\x1B[${linesUpToTop}A\r\x1B[J`);
2913
- resolve("/model");
2914
- return;
2915
- }
2916
- if (str === "") {
2917
- if (bufferLines.join("").length === 0) {
3078
+ let idx = 0;
3079
+ while (idx < str.length) {
3080
+ const rest = str.slice(idx);
3081
+ if (rest.startsWith("")) {
2918
3082
  cleanup();
3083
+ const down = bufferLines.length - 1 - cursorLine + 2;
3084
+ process.stdout.write(`\x1B[${down}B\r
3085
+ `);
2919
3086
  process.stdout.write(chalk4.yellow("Exiting IUB CLI...\n"));
2920
3087
  process.exit(0);
2921
3088
  }
2922
- }
2923
- if (str === "\x1B") {
2924
- cancel();
2925
- return;
2926
- }
2927
- if (str === "\n" || str === "\x1B\r" || str === "\x1B\r" || str === "\x1B[13;2u" || str === "\x1B[13;5u") {
2928
- const cur = bufferLines[cursorLine];
2929
- const prevLine = cursorLine;
2930
- bufferLines[cursorLine] = cur.slice(0, cursorCol);
2931
- bufferLines.splice(cursorLine + 1, 0, cur.slice(cursorCol));
2932
- cursorLine++;
2933
- cursorCol = 0;
2934
- redrawFrom(prevLine);
2935
- return;
2936
- }
2937
- if (str === "\r" || str === "\n" || str === "\r\n" || str === "\x1BOM" || str === "\x1B[13~") {
2938
- if (bufferLines.join("\n").trim().length === 0) return;
2939
- submit();
2940
- return;
2941
- }
2942
- if (str === "\b" || str === "\x7F") {
2943
- if (cursorCol > 0) {
2944
- const cur = bufferLines[cursorLine];
2945
- bufferLines[cursorLine] = cur.slice(0, cursorCol - 1) + cur.slice(cursorCol);
2946
- 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;
2947
3138
  updateActiveLine();
2948
- } else if (cursorLine > 0) {
2949
- const cur = bufferLines[cursorLine];
2950
- const prev = bufferLines[cursorLine - 1];
2951
- cursorCol = prev.length;
2952
- bufferLines[cursorLine - 1] = prev + cur;
2953
- bufferLines.splice(cursorLine, 1);
2954
- cursorLine--;
2955
- process.stdout.write("\x1B[1A");
2956
- redrawFrom(cursorLine);
3139
+ idx += rest.startsWith("") ? 1 : rest.startsWith("\x1B[1~") ? 4 : 3;
3140
+ continue;
2957
3141
  }
2958
- return;
2959
- }
2960
- if (str === "\x1B[D" || str === "\x1BOD") {
2961
- if (cursorCol > 0) {
2962
- cursorCol--;
2963
- process.stdout.write(`\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
2964
- } else if (cursorLine > 0) {
2965
- cursorLine--;
3142
+ if (rest.startsWith("") || rest.startsWith("\x1B[F") || rest.startsWith("\x1B[4~") || rest.startsWith("\x1BOF")) {
2966
3143
  cursorCol = bufferLines[cursorLine].length;
2967
- 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;
2968
3147
  }
2969
- return;
2970
- }
2971
- if (str === "\x1B[C" || str === "\x1BOC") {
2972
- if (cursorCol < bufferLines[cursorLine].length) {
2973
- cursorCol++;
2974
- process.stdout.write(`\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
2975
- } else if (cursorLine < bufferLines.length - 1) {
2976
- cursorLine++;
3148
+ if (rest.startsWith("")) {
3149
+ bufferLines[cursorLine] = "";
2977
3150
  cursorCol = 0;
2978
- process.stdout.write("\x1B[1B\x1B[5G");
3151
+ updateActiveLine();
3152
+ idx += 1;
3153
+ continue;
2979
3154
  }
2980
- return;
2981
- }
2982
- if (str === "\x1B[A" || str === "\x1BOA" || str === "") {
2983
- if (cursorLine > 0) {
2984
- cursorLine--;
2985
- cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
2986
- process.stdout.write(`\x1B[1A\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
2987
- 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;
2988
3233
  }
2989
- if (_commandHistory.length > 0) {
2990
- if (historyIdx === -1) savedDraft = bufferLines.join("\n");
2991
- if (historyIdx < _commandHistory.length - 1) {
2992
- 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--;
2993
3243
  const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
2994
3244
  bufferLines = histItem.split("\n");
2995
- cursorLine = bufferLines.length - 1;
2996
- 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;
2997
3253
  redrawFrom(0);
2998
3254
  }
3255
+ idx += seqLen;
3256
+ continue;
2999
3257
  }
3000
- return;
3001
- }
3002
- if (str === "\x1B[B" || str === "\x1BOB" || str === "") {
3003
- if (cursorLine < bufferLines.length - 1) {
3004
- cursorLine++;
3005
- cursorCol = Math.min(cursorCol, bufferLines[cursorLine].length);
3006
- process.stdout.write(`\x1B[1B\x1B[${5 + Math.min(cursorCol, boxWidth - 8)}G`);
3007
- 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;
3008
3269
  }
3009
- if (historyIdx > 0) {
3010
- historyIdx--;
3011
- const histItem = _commandHistory[_commandHistory.length - 1 - historyIdx];
3012
- bufferLines = histItem.split("\n");
3013
- cursorLine = 0;
3014
- cursorCol = bufferLines[0].length;
3015
- redrawFrom(0);
3016
- } else if (historyIdx === 0) {
3017
- historyIdx = -1;
3018
- bufferLines = savedDraft.split("\n");
3019
- cursorLine = 0;
3020
- cursorCol = bufferLines[0].length;
3021
- 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;
3022
3280
  }
3023
- return;
3024
- }
3025
- if (str === "\x1B[5~") {
3026
- if (_commandHistory.length > 0) {
3027
- if (historyIdx === -1) savedDraft = bufferLines.join("\n");
3028
- historyIdx = _commandHistory.length - 1;
3029
- bufferLines = _commandHistory[0].split("\n");
3030
- cursorLine = 0;
3031
- cursorCol = bufferLines[0].length;
3032
- 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;
3033
3293
  }
3034
- return;
3035
- }
3036
- if (str === "\x1B[6~") {
3037
- if (historyIdx !== -1) {
3038
- historyIdx = -1;
3039
- bufferLines = savedDraft.split("\n");
3040
- cursorLine = 0;
3041
- cursorCol = bufferLines[0].length;
3042
- redrawFrom(0);
3294
+ const code = rest.charCodeAt(0);
3295
+ if (code < 32 || code === 127) {
3296
+ idx += 1;
3297
+ continue;
3043
3298
  }
3044
- return;
3045
- }
3046
- if (str.startsWith("\x1B[")) return;
3047
- if (str.length === 1 && str.charCodeAt(0) >= 32) {
3048
- const cur = bufferLines[cursorLine];
3049
- bufferLines[cursorLine] = cur.slice(0, cursorCol) + str + cur.slice(cursorCol);
3050
- cursorCol++;
3051
- updateActiveLine();
3052
- return;
3053
- }
3054
- 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);
3055
3306
  const cur = bufferLines[cursorLine];
3056
- bufferLines[cursorLine] = cur.slice(0, cursorCol) + str + cur.slice(cursorCol);
3057
- cursorCol += str.length;
3307
+ bufferLines[cursorLine] = cur.slice(0, cursorCol) + chunk + cur.slice(cursorCol);
3308
+ cursorCol += chunk.length;
3058
3309
  updateActiveLine();
3059
- return;
3310
+ idx = printableEnd;
3060
3311
  }
3061
3312
  };
3062
3313
  process.stdin.on("data", onData);
@@ -3071,11 +3322,14 @@ async function expandOpenCodeMentions(rawPrompt) {
3071
3322
  const contexts = [];
3072
3323
  const urlRegex = /(?:@)?(https?:\/\/[^\s"'<>]+)/g;
3073
3324
  const urlMatches = Array.from(rawPrompt.matchAll(urlRegex));
3325
+ const seenUrls = /* @__PURE__ */ new Set();
3074
3326
  for (const match of urlMatches) {
3075
- 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);
3076
3332
  try {
3077
- const controller = new AbortController();
3078
- const timeout = setTimeout(() => controller.abort(), 6e3);
3079
3333
  const res = await fetch(targetUrl, {
3080
3334
  signal: controller.signal,
3081
3335
  headers: {
@@ -3083,7 +3337,6 @@ async function expandOpenCodeMentions(rawPrompt) {
3083
3337
  Accept: "text/html,application/xhtml+xml,application/json,text/plain;q=0.9"
3084
3338
  }
3085
3339
  });
3086
- clearTimeout(timeout);
3087
3340
  if (res.ok) {
3088
3341
  const contentType = res.headers.get("content-type") || "";
3089
3342
  const rawBody = await res.text();
@@ -3100,22 +3353,27 @@ async function expandOpenCodeMentions(rawPrompt) {
3100
3353
  attachedFiles.push(`web:${targetUrl.slice(0, 45)}...`);
3101
3354
  }
3102
3355
  } catch {
3356
+ } finally {
3357
+ clearTimeout(timeout);
3103
3358
  }
3104
3359
  }
3105
- const fileRegex = /@([a-zA-Z0-9_\-\.\/\\]+)/g;
3360
+ const fileRegex = /(?:^|\s)@([a-zA-Z0-9_\-\.\/\\]+)/g;
3106
3361
  const fileMatches = Array.from(rawPrompt.matchAll(fileRegex));
3362
+ const seenPaths = /* @__PURE__ */ new Set();
3107
3363
  for (const match of fileMatches) {
3108
3364
  const rawPath = match[1];
3109
3365
  if (rawPath.startsWith("http://") || rawPath.startsWith("https://")) continue;
3110
3366
  const resolvedPath = path4.resolve(process.cwd(), rawPath);
3367
+ if (seenPaths.has(resolvedPath)) continue;
3111
3368
  if (fs4.existsSync(resolvedPath)) {
3369
+ seenPaths.add(resolvedPath);
3112
3370
  const stat = fs4.statSync(resolvedPath);
3113
3371
  if (stat.isFile()) {
3114
3372
  if (isImageFile(resolvedPath)) {
3115
3373
  const imgPayload = loadImagePayload(resolvedPath);
3116
3374
  if (imgPayload) {
3117
3375
  attachedImages.push(imgPayload);
3118
- attachedFiles.push(`\u{1F5BC}\uFE0F @${rawPath}`);
3376
+ attachedFiles.push(`@${rawPath}`);
3119
3377
  contexts.push(
3120
3378
  `
3121
3379
  --- [Attached Image: @${rawPath} (${(imgPayload.size / 1024).toFixed(1)} KB, ${imgPayload.mimeType})] ---`
@@ -3161,7 +3419,7 @@ async function expandOpenCodeMentions(rawPrompt) {
3161
3419
  if (payload) {
3162
3420
  attachedImages.push(payload);
3163
3421
  const name = path4.basename(resolvedPath);
3164
- attachedFiles.push(`\u{1F5BC}\uFE0F ${name}`);
3422
+ attachedFiles.push(`${name}`);
3165
3423
  contexts.push(
3166
3424
  `
3167
3425
  --- [Attached Image: ${name} (${(payload.size / 1024).toFixed(1)} KB, ${payload.mimeType})] ---`
@@ -3171,7 +3429,7 @@ async function expandOpenCodeMentions(rawPrompt) {
3171
3429
  }
3172
3430
  if (attachedFiles.length > 0) {
3173
3431
  console.log(
3174
- chalk4.bgHex("#002B5C").hex("#00A3FF").bold(" \u{1F4CE} Resource Ingestion: ") + chalk4.white(` ${attachedFiles.length} item(s): `) + chalk4.cyan.bold(attachedFiles.join(", "))
3432
+ chalk4.bgHex("#002B5C").hex("#00A3FF").bold(" Resource Ingestion: ") + chalk4.white(` ${attachedFiles.length} item(s): `) + chalk4.cyan.bold(attachedFiles.join(", "))
3175
3433
  );
3176
3434
  }
3177
3435
  return {
@@ -3183,6 +3441,27 @@ async function expandOpenCodeMentions(rawPrompt) {
3183
3441
 
3184
3442
  // src/config.ts
3185
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
+ }
3186
3465
  var configStore = new Conf2({
3187
3466
  projectName: "iubcli"
3188
3467
  });
@@ -3277,14 +3556,14 @@ async function detectLocalOllamaModels(timeoutMs = 700) {
3277
3556
  const timer = setTimeout(() => controller.abort(), timeoutMs);
3278
3557
  try {
3279
3558
  const res = await fetch("http://127.0.0.1:11434/api/tags", { signal: controller.signal });
3280
- clearTimeout(timer);
3281
3559
  if (!res.ok) return [];
3282
3560
  const data = await res.json();
3283
3561
  const models = Array.isArray(data?.models) ? data.models.map((m) => String(m?.name || m?.model || "").trim()).filter(Boolean) : [];
3284
3562
  return models;
3285
3563
  } catch {
3286
- clearTimeout(timer);
3287
3564
  return [];
3565
+ } finally {
3566
+ clearTimeout(timer);
3288
3567
  }
3289
3568
  }
3290
3569
  function sanitizeApiKeyInput(raw) {
@@ -3460,11 +3739,20 @@ function saveConfig(config) {
3460
3739
  if (config.provider === "gemini") {
3461
3740
  delete config.baseURL;
3462
3741
  }
3463
- config.savedProviders[config.provider] = {
3464
- apiKey: config.apiKey,
3465
- model: config.model,
3466
- ...config.baseURL ? { baseURL: config.baseURL } : {}
3467
- };
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
+ }
3468
3756
  configStore.set("config", config);
3469
3757
  }
3470
3758
  function printSetupHeader(title, subtitle) {
@@ -3481,7 +3769,7 @@ function printSetupComplete(providerLabel, model, extraNote) {
3481
3769
  const cols = process.stdout.columns || 80;
3482
3770
  const line = chalk5.hex("#00A3FF")("\u2500".repeat(Math.max(40, Math.min(cols - 4, 68))));
3483
3771
  console.log(line);
3484
- console.log(chalk5.green.bold(" \u2714 Configuration saved!"));
3772
+ console.log(chalk5.green.bold(" Configuration saved!"));
3485
3773
  console.log(` ${chalk5.dim("Provider:")} ${chalk5.bold.cyan(providerLabel)}`);
3486
3774
  console.log(` ${chalk5.dim("Model:")} ${chalk5.bold.hex("#00A3FF")(model)}`);
3487
3775
  if (extraNote) {
@@ -3723,11 +4011,11 @@ async function promptVerifiedApiKey(options) {
3723
4011
  options: [
3724
4012
  {
3725
4013
  value: "zero_key",
3726
- label: `${chalk5.hex("#00A3FF").bold("\u{1F680} Continue with Free Zero-Key Starter AI")} ${chalk5.green("(No Key Needed)")}`,
4014
+ label: `${chalk5.hex("#00A3FF").bold("Continue with Free Zero-Key Starter AI")} ${chalk5.green("(No Key Needed)")}`,
3727
4015
  hint: "Start right now without creating any API key (~45s cooldown/reply)"
3728
4016
  },
3729
- { value: "retry", label: chalk5.cyan("\u{1F511} Go back and enter an API key") },
3730
- { value: "cancel", label: chalk5.gray("\u2716 Exit setup") }
4017
+ { value: "retry", label: chalk5.cyan("Go back and enter an API key") },
4018
+ { value: "cancel", label: chalk5.gray("Exit setup") }
3731
4019
  ]
3732
4020
  });
3733
4021
  if (fallbackPick === "retry") continue;
@@ -3747,26 +4035,26 @@ async function promptVerifiedApiKey(options) {
3747
4035
  const detected = inferProviderFromApiKey(cleanedKey);
3748
4036
  let modelOverride;
3749
4037
  if (detected === "gemini" && activeProvider !== "gemini") {
3750
- console.log(chalk5.cyan("\n\u2139\uFE0F Detected Google Gemini API key (AIza...) \u2014 routing cleanly to Google Gemini!\n"));
4038
+ console.log(chalk5.cyan("\n Detected Google Gemini API key (AIza...) \u2014 routing cleanly to Google Gemini!\n"));
3751
4039
  activeProvider = "gemini";
3752
4040
  activeBaseURL = void 0;
3753
4041
  modelOverride = DEFAULT_MODELS.gemini;
3754
4042
  } else if (detected === "openrouter" && activeProvider !== "openrouter") {
3755
- console.log(chalk5.cyan("\n\u2139\uFE0F Detected OpenRouter API key (sk-or-...) \u2014 routing cleanly to OpenRouter!\n"));
4043
+ console.log(chalk5.cyan("\n Detected OpenRouter API key (sk-or-...) \u2014 routing cleanly to OpenRouter!\n"));
3756
4044
  activeProvider = "openrouter";
3757
4045
  activeBaseURL = "https://openrouter.ai/api/v1";
3758
4046
  modelOverride = DEFAULT_MODELS.openrouter;
3759
4047
  } else if (detected === "groq" && (activeProvider !== "custom" || !activeBaseURL?.includes("groq.com"))) {
3760
- console.log(chalk5.cyan("\n\u2139\uFE0F Detected Groq API key (gsk_...) \u2014 routing cleanly to Groq Cloud!\n"));
4048
+ console.log(chalk5.cyan("\n Detected Groq API key (gsk_...) \u2014 routing cleanly to Groq Cloud!\n"));
3761
4049
  activeProvider = "custom";
3762
4050
  activeBaseURL = "https://api.groq.com/openai/v1";
3763
4051
  modelOverride = "llama-3.3-70b-versatile";
3764
4052
  }
3765
- process.stdout.write(chalk5.cyan(" \u23F3 Verifying API key..."));
4053
+ process.stdout.write(chalk5.cyan(" Verifying API key..."));
3766
4054
  const check = await verifyProviderCredentials(activeProvider, cleanedKey, activeBaseURL);
3767
4055
  process.stdout.write("\r\x1B[2K");
3768
4056
  if (check.ok) {
3769
- console.log(chalk5.green(" \u2714 API key verified!\n"));
4057
+ console.log(chalk5.green(" API key verified!\n"));
3770
4058
  return {
3771
4059
  provider: activeProvider,
3772
4060
  apiKey: cleanedKey,
@@ -3774,20 +4062,20 @@ async function promptVerifiedApiKey(options) {
3774
4062
  modelOverride
3775
4063
  };
3776
4064
  }
3777
- console.log(chalk5.red(` \u2716 Verification failed: ${check.error || "Invalid API key."}
4065
+ console.log(chalk5.red(` Verification failed: ${check.error || "Invalid API key."}
3778
4066
  `));
3779
4067
  const action = await interactiveSelect({
3780
4068
  message: "API key check failed. Choose next step:",
3781
4069
  options: [
3782
- { value: "retry", label: chalk5.cyan("\u{1F511} Re-enter a different API key") },
4070
+ { value: "retry", label: chalk5.cyan("Re-enter a different API key") },
3783
4071
  ...options.allowZeroKeyFallback ? [
3784
4072
  {
3785
4073
  value: "zero_key",
3786
- label: chalk5.hex("#00A3FF")("\u{1F680} Use Free Zero-Key Mode for now (No Key Needed)")
4074
+ label: chalk5.hex("#00A3FF")("Use Free Zero-Key Mode for now (No Key Needed)")
3787
4075
  }
3788
4076
  ] : [],
3789
4077
  { value: "save_anyway", label: chalk5.yellow("Save key anyway") },
3790
- { value: "cancel", label: chalk5.gray("\u2716 Cancel") }
4078
+ { value: "cancel", label: chalk5.gray("Cancel") }
3791
4079
  ]
3792
4080
  });
3793
4081
  if (action === "retry") continue;
@@ -3875,7 +4163,7 @@ async function switchProviderInteractive(currentConfig) {
3875
4163
  options: [
3876
4164
  {
3877
4165
  value: "yes",
3878
- label: chalk5.green(`\u2714 Use saved API key and model (${chalk5.bold(saved.model)})`)
4166
+ label: chalk5.green(`Use saved API key and model (${chalk5.bold(saved.model)})`)
3879
4167
  },
3880
4168
  {
3881
4169
  value: "change_model",
@@ -3995,7 +4283,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
3995
4283
  ...ollamaModels.length > 0 ? [
3996
4284
  {
3997
4285
  value: "ollama",
3998
- label: `${chalk5.bold.hex("#00A3FF")("Local Ollama")} ${chalk5.green(`[\u2714 Detected ${ollamaModels.length} local model(s) \u2022 No Key Needed]`)}`,
4286
+ label: `${chalk5.bold.hex("#00A3FF")("Local Ollama")} ${chalk5.green(`[Detected ${ollamaModels.length} local model(s) \u2022 No Key Needed]`)}`,
3999
4287
  hint: `Ready now offline (${ollamaModels.slice(0, 3).join(", ")}) at localhost:11434`
4000
4288
  }
4001
4289
  ] : [],
@@ -4038,7 +4326,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4038
4326
  console.log(chalk5.yellow("Setup cancelled.\n"));
4039
4327
  process.exit(0);
4040
4328
  }
4041
- return existingConfig;
4329
+ return existingConfig ?? null;
4042
4330
  }
4043
4331
  if (choice === "free_starter") {
4044
4332
  const zeroConfig = createZeroKeyConfig(existingConfig);
@@ -4058,7 +4346,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4058
4346
  console.log(chalk5.yellow("Setup cancelled.\n"));
4059
4347
  process.exit(0);
4060
4348
  }
4061
- return existingConfig;
4349
+ return existingConfig ?? null;
4062
4350
  }
4063
4351
  const ollamaConfig = {
4064
4352
  provider: "custom",
@@ -4089,12 +4377,12 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4089
4377
  const keyChoice = await interactiveSelect({
4090
4378
  message: `Saved API key found for ${PROVIDER_LABELS[provider]}.`,
4091
4379
  options: [
4092
- { value: "saved", label: chalk5.green("\u2714 Keep existing API key") },
4380
+ { value: "saved", label: chalk5.green("Keep existing API key") },
4093
4381
  { value: "new", label: chalk5.yellow("Enter a new API key") }
4094
4382
  ]
4095
4383
  });
4096
4384
  if (!keyChoice) {
4097
- return existingConfig;
4385
+ return existingConfig ?? null;
4098
4386
  }
4099
4387
  if (keyChoice === "saved") {
4100
4388
  resolvedApiKey = savedForProvider.apiKey;
@@ -4108,7 +4396,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4108
4396
  console.log(chalk5.yellow("Setup cancelled.\n"));
4109
4397
  process.exit(0);
4110
4398
  }
4111
- return existingConfig;
4399
+ return existingConfig ?? null;
4112
4400
  }
4113
4401
  baseURL = preset.baseURL;
4114
4402
  defaultModelHint = preset.defaultModel;
@@ -4129,7 +4417,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4129
4417
  console.log(chalk5.yellow("Setup cancelled.\n"));
4130
4418
  process.exit(0);
4131
4419
  }
4132
- return existingConfig;
4420
+ return existingConfig ?? null;
4133
4421
  }
4134
4422
  provider = verified.provider;
4135
4423
  resolvedApiKey = verified.apiKey;
@@ -4154,7 +4442,7 @@ async function promptConfig(isFirstTime = false, fallbackConfig) {
4154
4442
  console.log(chalk5.yellow("Setup cancelled.\n"));
4155
4443
  process.exit(0);
4156
4444
  }
4157
- return existingConfig;
4445
+ return existingConfig ?? null;
4158
4446
  }
4159
4447
  const finalConfig = {
4160
4448
  provider,
@@ -4186,7 +4474,7 @@ import OpenAI from "openai";
4186
4474
  import chalk6 from "chalk";
4187
4475
  var AGENT_MODELS = [
4188
4476
  // ==========================================
4189
- // 🚀 Built-in Zero-Key Instant Free Model
4477
+ // Built-in Zero-Key Instant Free Model
4190
4478
  // ==========================================
4191
4479
  {
4192
4480
  id: POLLINATIONS_DEFAULT_MODEL,
@@ -4199,11 +4487,11 @@ var AGENT_MODELS = [
4199
4487
  baseURL: POLLINATIONS_BASE_URL
4200
4488
  },
4201
4489
  // ==========================================
4202
- // 🌟 100% Free OpenRouter Models (Zero Cost)
4490
+ // 100% Free OpenRouter Models (Zero Cost)
4203
4491
  // ==========================================
4204
4492
  {
4205
4493
  id: "openrouter/free",
4206
- name: "OpenRouter Free Agent (\u{1F31F} Recommended)",
4494
+ name: "OpenRouter Free Agent (Recommended)",
4207
4495
  provider: "openrouter",
4208
4496
  category: "free",
4209
4497
  description: "Auto-routes to the best active free coding model with tool calling. 0% downtime.",
@@ -4402,7 +4690,7 @@ var AGENT_MODELS = [
4402
4690
  baseURL: "https://openrouter.ai/api/v1"
4403
4691
  },
4404
4692
  // ==========================================
4405
- // ⚡ OpenCode Console & Freebuff Zero-Key Built-in Models ($0 Endpoints)
4693
+ // OpenCode Console & Freebuff Zero-Key Built-in Models ($0 Endpoints)
4406
4694
  // ==========================================
4407
4695
  // 1. Zero-Retention / No-Training Models:
4408
4696
  {
@@ -4599,11 +4887,11 @@ var AGENT_MODELS = [
4599
4887
  contextLength: "2,097,152"
4600
4888
  },
4601
4889
  // ==========================================
4602
- // 🔷 Google Gemini Suite (100% Free Tier: 1M Tokens, 1,500 Req/Day)
4890
+ // Google Gemini Suite (100% Free Tier: 1M Tokens, 1,500 Req/Day)
4603
4891
  // ==========================================
4604
4892
  {
4605
4893
  id: "gemini-3.5-flash-lite",
4606
- name: "Gemini 3.5 Flash-Lite (\u{1F31F} Verified Active Free Coder)",
4894
+ name: "Gemini 3.5 Flash-Lite (Verified Active Free Coder)",
4607
4895
  provider: "gemini",
4608
4896
  category: "gemini",
4609
4897
  description: "Google's ultra-fast verified free model with full tool calling, instant token generation, and zero downtime.",
@@ -4728,11 +5016,11 @@ var AGENT_MODELS = [
4728
5016
  contextLength: "2,097,152"
4729
5017
  },
4730
5018
  // ==========================================
4731
- // 🧠 DeepSeek Frontier Models (Free Tokens & High Speed)
5019
+ // DeepSeek Frontier Models (Free Tokens & High Speed)
4732
5020
  // ==========================================
4733
5021
  {
4734
5022
  id: "deepseek-chat",
4735
- name: "DeepSeek V4.1 / V3.2 Chat (\u{1F31F} 5M Free Tokens)",
5023
+ name: "DeepSeek V4.1 / V3.2 Chat (5M Free Tokens)",
4736
5024
  provider: "custom",
4737
5025
  category: "deepseek",
4738
5026
  description: "DeepSeek flagship frontier coding model with 5M free tokens on platform.deepseek.com.",
@@ -4791,11 +5079,11 @@ var AGENT_MODELS = [
4791
5079
  baseURL: "https://openrouter.ai/api/v1"
4792
5080
  },
4793
5081
  // ==========================================
4794
- // ⚡ Tencent HY4 Suite (1M Token Context - Free Promotional Tokens)
5082
+ // Tencent HY4 Suite (1M Token Context - Free Promotional Tokens)
4795
5083
  // ==========================================
4796
5084
  {
4797
5085
  id: "tencent/hy4-flash",
4798
- name: "Tencent Hy4 Flash (\u{1F31F} 1M Context - Free Promo)",
5086
+ name: "Tencent Hy4 Flash (1M Context - Free Promo)",
4799
5087
  provider: "openrouter",
4800
5088
  category: "hy4",
4801
5089
  description: "Tencent frontier Hy4 Flash model with 1,048,576 token context and ultra-fast generation.",
@@ -4824,11 +5112,11 @@ var AGENT_MODELS = [
4824
5112
  baseURL: "https://openrouter.ai/api/v1"
4825
5113
  },
4826
5114
  // ==========================================
4827
- // 🚀 Zhipu AI GLM 5.3 Suite (Daily Free Tokens - 1M Context)
5115
+ // Zhipu AI GLM 5.3 Suite (Daily Free Tokens - 1M Context)
4828
5116
  // ==========================================
4829
5117
  {
4830
5118
  id: "z-ai/glm-5.3-flash",
4831
- name: "GLM 5.3 Flash (\u{1F31F} Daily Free Tokens & 1M Context)",
5119
+ name: "GLM 5.3 Flash (Daily Free Tokens & 1M Context)",
4832
5120
  provider: "openrouter",
4833
5121
  category: "glm",
4834
5122
  description: "Z.ai latest GLM 5.3 Flash with 1,048,576 token context and daily free tokens on BigModel.",
@@ -4867,7 +5155,7 @@ var AGENT_MODELS = [
4867
5155
  baseURL: "https://openrouter.ai/api/v1"
4868
5156
  },
4869
5157
  // ==========================================
4870
- // ⚡ Groq Cloud Free Tier (14,400 Req/Day Free)
5158
+ // Groq Cloud Free Tier (14,400 Req/Day Free)
4871
5159
  // ==========================================
4872
5160
  {
4873
5161
  id: "llama-3.3-70b-versatile",
@@ -4920,7 +5208,7 @@ var AGENT_MODELS = [
4920
5208
  baseURL: "https://api.groq.com/openai/v1"
4921
5209
  },
4922
5210
  // ==========================================
4923
- // ⚡ Cerebras Cloud Free Tier (1,800+ Tokens/Sec)
5211
+ // Cerebras Cloud Free Tier (1,800+ Tokens/Sec)
4924
5212
  // ==========================================
4925
5213
  {
4926
5214
  id: "llama3.3-70b",
@@ -4943,7 +5231,7 @@ var AGENT_MODELS = [
4943
5231
  baseURL: "https://api.cerebras.ai/v1"
4944
5232
  },
4945
5233
  // ==========================================
4946
- // 💻 Local Offline Models (Ollama)
5234
+ // Local Offline Models (Ollama)
4947
5235
  // ==========================================
4948
5236
  {
4949
5237
  id: "qwen2.5-coder",
@@ -4966,7 +5254,7 @@ var AGENT_MODELS = [
4966
5254
  baseURL: "http://localhost:11434/v1"
4967
5255
  },
4968
5256
  // ==========================================
4969
- // 👑 Frontier AI Coding Agents (OpenCode Flagships)
5257
+ // Frontier AI Coding Agents (OpenCode Flagships)
4970
5258
  // ==========================================
4971
5259
  {
4972
5260
  id: "anthropic/claude-3.5-sonnet",
@@ -5127,8 +5415,11 @@ var POLLINATIONS_CASCADE_CHAIN = [
5127
5415
  "qwen-coder"
5128
5416
  ];
5129
5417
  async function fetchLiveOpenRouterFreeModels() {
5418
+ const controller = new AbortController();
5419
+ const timer = setTimeout(() => controller.abort(), 6e3);
5130
5420
  try {
5131
5421
  const res = await fetch("https://openrouter.ai/api/v1/models", {
5422
+ signal: controller.signal,
5132
5423
  headers: { "User-Agent": "IUB CLI" }
5133
5424
  });
5134
5425
  if (!res.ok) return [];
@@ -5155,6 +5446,8 @@ async function fetchLiveOpenRouterFreeModels() {
5155
5446
  return freeModels;
5156
5447
  } catch {
5157
5448
  return [];
5449
+ } finally {
5450
+ clearTimeout(timer);
5158
5451
  }
5159
5452
  }
5160
5453
  async function selectAgentModelInteractive(currentConfig, mode = "build", initialCategory) {
@@ -5175,12 +5468,12 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5175
5468
  const hasGroqReady = Boolean(
5176
5469
  process.env.GROQ_API_KEY || currentConfig.savedProviders?.custom?.baseURL?.includes("groq.com") && currentConfig.savedProviders?.custom?.apiKey
5177
5470
  );
5178
- const orBadge = hasOpenRouterReady ? chalk6.green(" [\u2714 Ready]") : chalk6.yellow(" [\u{1F511} Needs OpenRouter Key]");
5179
- const geminiBadge = hasGeminiReady ? chalk6.green(" [\u2714 Ready]") : chalk6.yellow(" [\u{1F511} Needs Gemini Key]");
5180
- const groqBadge = hasGroqReady ? chalk6.green(" [\u2714 Ready]") : chalk6.yellow(" [\u{1F511} Needs Groq Key]");
5471
+ const orBadge = hasOpenRouterReady ? chalk6.green(" [Ready]") : chalk6.yellow(" [Needs OpenRouter Key]");
5472
+ const geminiBadge = hasGeminiReady ? chalk6.green(" [Ready]") : chalk6.yellow(" [Needs Gemini Key]");
5473
+ const groqBadge = hasGroqReady ? chalk6.green(" [Ready]") : chalk6.yellow(" [Needs Groq Key]");
5181
5474
  const currentPreset = AGENT_MODELS.find((m) => m.id === currentConfig.model);
5182
5475
  const defaultCategory = currentPreset?.category || (currentConfig.provider === "gemini" ? "gemini" : currentConfig.provider === "openrouter" ? "free" : "free");
5183
- console.log(chalk6.bold.hex("#00A3FF")("\n\u{1F916} IUB CLI AI Agent & Model Selector\n"));
5476
+ console.log(chalk6.bold.hex("#00A3FF")("\nIUB CLI AI Agent & Model Selector\n"));
5184
5477
  let categoryChoice = initialCategory;
5185
5478
  if (!categoryChoice) {
5186
5479
  categoryChoice = await interactiveSelect({
@@ -5190,62 +5483,62 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5190
5483
  options: [
5191
5484
  {
5192
5485
  value: "gemini",
5193
- label: `${chalk6.bold.yellow("\u{1F537} Google Gemini Free Suite")}${geminiBadge}`,
5486
+ label: `${chalk6.bold.yellow("Google Gemini Free Suite")}${geminiBadge}`,
5194
5487
  hint: "Gemini 3.5/3.1 Flash Lite, Gemma 4 \u2022 1M-2M context, 1,500 req/day free"
5195
5488
  },
5196
5489
  {
5197
5490
  value: "free",
5198
- label: `${chalk6.bold.green("\u{1F31F} Free Models & Zero-Key Starter AI")}${orBadge}`,
5491
+ label: `${chalk6.bold.green("Free Models & Zero-Key Starter AI")}${orBadge}`,
5199
5492
  hint: "Includes Zero-Key GPT-OSS 20B (no key) + OpenRouter free models (Nemotron, Gemma 4)"
5200
5493
  },
5201
5494
  {
5202
5495
  value: "live_sync",
5203
- label: `${chalk6.bold.hex("#00FFFF")("\u{1F504} Live Sync: OpenRouter Active Free Models")}${orBadge}`,
5496
+ label: `${chalk6.bold.hex("#00FFFF")("Live Sync: OpenRouter Active Free Models")}${orBadge}`,
5204
5497
  hint: "Queries OpenRouter API live for active tool-capable free models"
5205
5498
  },
5206
5499
  {
5207
5500
  value: "zen",
5208
- label: `${chalk6.bold.hex("#00E5FF")("\u26A1 OpenCode & Freebuff Built-in Roster")}${orBadge}`,
5501
+ label: `${chalk6.bold.hex("#00E5FF")("OpenCode & Freebuff Built-in Roster")}${orBadge}`,
5209
5502
  hint: "DeepSeek V4.1, GLM 5.3, Solar routed via OpenRouter"
5210
5503
  },
5211
5504
  {
5212
5505
  value: "deepseek",
5213
- label: `${chalk6.bold.hex("#00D2FF")("\u{1F9E0} DeepSeek Frontier Models")}`,
5506
+ label: `${chalk6.bold.hex("#00D2FF")("DeepSeek Frontier Models")}`,
5214
5507
  hint: "DeepSeek Platform (5M free), Groq & OpenRouter"
5215
5508
  },
5216
5509
  {
5217
5510
  value: "hy4",
5218
- label: `${chalk6.bold.hex("#FF6D00")("\u26A1 Tencent HY4 Suite")}${orBadge}`,
5511
+ label: `${chalk6.bold.hex("#FF6D00")("Tencent HY4 Suite")}${orBadge}`,
5219
5512
  hint: "Hy4 Flash, Hy4 1M Frontier (1M tokens context)"
5220
5513
  },
5221
5514
  {
5222
5515
  value: "glm",
5223
- label: `${chalk6.bold.hex("#7C4DFF")("\u{1F680} Zhipu AI GLM 5.3 Suite")}${orBadge}`,
5516
+ label: `${chalk6.bold.hex("#7C4DFF")("Zhipu AI GLM 5.3 Suite")}${orBadge}`,
5224
5517
  hint: "GLM 5.3 Flash, GLM 5.3 1M (daily free tokens)"
5225
5518
  },
5226
5519
  {
5227
5520
  value: "groq",
5228
- label: `${chalk6.bold.hex("#FF9900")("\u26A1 Groq & Cerebras Free Tier")}${groqBadge}`,
5521
+ label: `${chalk6.bold.hex("#FF9900")("Groq & Cerebras Free Tier")}${groqBadge}`,
5229
5522
  hint: "Llama 3.3 70B, Qwen Coder \u2022 14,400 requests/day, 500+ tok/s"
5230
5523
  },
5231
5524
  {
5232
5525
  value: "flagship",
5233
- label: `${chalk6.bold.hex("#FFD700")("\u{1F451} Frontier Flagship Coding Agents")}${orBadge}`,
5526
+ label: `${chalk6.bold.hex("#FFD700")("Frontier Flagship Coding Agents")}${orBadge}`,
5234
5527
  hint: "Claude 3.5 Sonnet, GPT-4o, Codestral via OpenRouter"
5235
5528
  },
5236
5529
  {
5237
5530
  value: "local",
5238
- label: `${chalk6.bold.magenta("\u{1F4BB} Local Offline Models")} ${chalk6.green("[\u2714 No API Key Needed]")}`,
5531
+ label: `${chalk6.bold.magenta("Local Offline Models")} ${chalk6.green("[No API Key Needed]")}`,
5239
5532
  hint: "Runs 100% locally via Ollama on localhost:11434"
5240
5533
  },
5241
5534
  {
5242
5535
  value: "all",
5243
- label: `${chalk6.bold("\u{1F4CB} Browse All Model Presets")}`,
5536
+ label: `${chalk6.bold("Browse All Model Presets")}`,
5244
5537
  hint: "View complete catalog of all presets"
5245
5538
  },
5246
5539
  {
5247
5540
  value: "custom",
5248
- label: `${chalk6.bold("\u270F\uFE0F Enter Custom Model ID Manually")}`,
5541
+ label: `${chalk6.bold(" Enter Custom Model ID Manually")}`,
5249
5542
  hint: "Type any model slug for your current provider"
5250
5543
  }
5251
5544
  ]
@@ -5261,7 +5554,7 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5261
5554
  if (!customModel) return null;
5262
5555
  currentConfig.model = customModel.trim();
5263
5556
  saveConfig(currentConfig);
5264
- console.log(chalk6.green(`\u2714 Active Agent Model set to: ${chalk6.bold(currentConfig.model)}
5557
+ console.log(chalk6.green(`Active Agent Model set to: ${chalk6.bold(currentConfig.model)}
5265
5558
  `));
5266
5559
  return currentConfig;
5267
5560
  }
@@ -5272,11 +5565,11 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5272
5565
  const liveModels = await fetchLiveOpenRouterFreeModels();
5273
5566
  spinner.stop();
5274
5567
  if (liveModels.length > 0) {
5275
- console.log(chalk6.green(`\u2714 Found ${liveModels.length} active free tool-capable models on OpenRouter!
5568
+ console.log(chalk6.green(`Found ${liveModels.length} active free tool-capable models on OpenRouter!
5276
5569
  `));
5277
5570
  modelsToShow = liveModels;
5278
5571
  } else {
5279
- console.log(chalk6.yellow("\u26A0\uFE0F Could not connect to OpenRouter live API. Falling back to built-in presets.\n"));
5572
+ console.log(chalk6.yellow("Could not connect to OpenRouter live API. Falling back to built-in presets.\n"));
5280
5573
  modelsToShow = AGENT_MODELS.filter((m) => m.category === "free");
5281
5574
  }
5282
5575
  } else if (categoryChoice === "local") {
@@ -5297,7 +5590,12 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5297
5590
  ...AGENT_MODELS.filter((m) => m.category === "local" && !existingIds.has(m.id))
5298
5591
  ];
5299
5592
  } else if (categoryChoice === "all") {
5300
- 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
+ });
5301
5599
  } else {
5302
5600
  modelsToShow = AGENT_MODELS.filter((m) => m.category === categoryChoice);
5303
5601
  }
@@ -5319,7 +5617,7 @@ async function selectAgentModelInteractive(currentConfig, mode = "build", initia
5319
5617
  if (!updatedConfig) return null;
5320
5618
  console.log(
5321
5619
  chalk6.green(
5322
- `\u2714 Active Agent Model: ${chalk6.bold(preset.name)}
5620
+ `Active Agent Model: ${chalk6.bold(preset.name)}
5323
5621
  Provider: ${chalk6.bold(formatProviderLabel(updatedConfig))} \u2022 Model ID: ${chalk6.cyan(preset.id)}
5324
5622
  `
5325
5623
  )
@@ -5360,12 +5658,12 @@ async function resolveAndSavePreset(preset, currentConfig) {
5360
5658
  options: [
5361
5659
  {
5362
5660
  value: "cancel",
5363
- label: chalk6.green(`\u2B05 Keep using current model (${currentConfig.model})`),
5661
+ label: chalk6.green(`Keep using current model (${currentConfig.model})`),
5364
5662
  hint: "Do not ask for a key \u2014 keep working immediately"
5365
5663
  },
5366
5664
  {
5367
5665
  value: "enter",
5368
- label: chalk6.cyan(`\u{1F511} Enter API Key for ${serviceName}`),
5666
+ label: chalk6.cyan(`Enter API Key for ${serviceName}`),
5369
5667
  hint: serviceUrl
5370
5668
  }
5371
5669
  ]
@@ -5380,7 +5678,7 @@ async function resolveAndSavePreset(preset, currentConfig) {
5380
5678
  validate: (v) => !v || v.trim().length === 0 ? "Key cannot be empty!" : void 0
5381
5679
  });
5382
5680
  if (!enteredKey) return null;
5383
- targetApiKey = enteredKey.trim();
5681
+ targetApiKey = sanitizeApiKeyInput(enteredKey);
5384
5682
  targetBaseURL = targetProvider === "gemini" ? void 0 : preset.baseURL;
5385
5683
  }
5386
5684
  } else if (targetProvider === "openrouter") {
@@ -5521,11 +5819,20 @@ function detectProjectContext(rootDir = process.cwd()) {
5521
5819
  }
5522
5820
  }
5523
5821
  try {
5524
- const branch = execSync2("git rev-parse --abbrev-ref HEAD 2>/dev/null || git branch --show-current", {
5525
- cwd: rootDir,
5526
- encoding: "utf8",
5527
- stdio: ["ignore", "pipe", "ignore"]
5528
- }).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
+ }
5529
5836
  if (branch) gitBranch = branch;
5530
5837
  const status = execSync2("git status --porcelain", {
5531
5838
  cwd: rootDir,
@@ -5535,9 +5842,12 @@ function detectProjectContext(rootDir = process.cwd()) {
5535
5842
  gitDirty = status.length > 0;
5536
5843
  } catch {
5537
5844
  }
5845
+ const stackDetails = [language];
5846
+ if (hasTypeScript && language !== "TypeScript") stackDetails.push("TypeScript");
5847
+ if (hasTailwind) stackDetails.push("Tailwind CSS");
5538
5848
  const summaryLines = [
5539
- `### \u{1F4C1} DETECTED WORKSPACE ENVIRONMENT:`,
5540
- `- Framework / Stack: ${framework} (${language}${hasTypeScript ? ", TypeScript" : ""}${hasTailwind ? ", Tailwind CSS" : ""})`,
5849
+ `### DETECTED WORKSPACE ENVIRONMENT:`,
5850
+ `- Framework / Stack: ${framework} (${stackDetails.join(", ")})`,
5541
5851
  `- Package Manager: ${packageManager}`
5542
5852
  ];
5543
5853
  if (Object.keys(scripts).length > 0) {
@@ -5647,10 +5957,10 @@ async function probeCandidate(candidate) {
5647
5957
  return false;
5648
5958
  }
5649
5959
  }
5650
- async function exploreAndSelectFreeModel(config, excludedModels = /* @__PURE__ */ new Set(), silent = false) {
5960
+ async function exploreAndSelectFreeModel(config, excludedModels = /* @__PURE__ */ new Set(), silent = false, persist = true) {
5651
5961
  if (!silent) {
5652
5962
  process.stdout.write(
5653
- chalk7.cyan("\n\u{1F50D} Exploring all available models across providers to find active free tokens...\n")
5963
+ chalk7.cyan("\nExploring all available models across providers to find active free tokens...\n")
5654
5964
  );
5655
5965
  }
5656
5966
  const geminiKey = config.savedProviders?.gemini?.apiKey || (config.provider === "gemini" ? config.apiKey : void 0) || getEnvProviderKey("gemini");
@@ -5793,7 +6103,9 @@ async function exploreAndSelectFreeModel(config, excludedModels = /* @__PURE__ *
5793
6103
  } else {
5794
6104
  delete config.baseURL;
5795
6105
  }
5796
- saveConfig(config);
6106
+ if (persist) {
6107
+ saveConfig(config);
6108
+ }
5797
6109
  if (!silent) {
5798
6110
  renderModelExplorationNotice(winner.id, winner.provider, testedCount);
5799
6111
  }
@@ -5813,7 +6125,7 @@ function getSystemPrompt(mode = "build") {
5813
6125
  const peers = meshNode.listPeers().filter((p) => p.nodeId !== meshNode.nodeId);
5814
6126
  if (peers.length > 0) {
5815
6127
  meshContext = `
5816
- ### \u{1F310} CONNECTED WORKSPACE MESH PEERS (CROSS-INSTANCE COLLABORATION):
6128
+ ### CONNECTED WORKSPACE MESH PEERS (CROSS-INSTANCE COLLABORATION):
5817
6129
  This instance role is [${meshNode.role.toUpperCase()}] at "${meshNode.workspace}".
5818
6130
  Active connected peer instances in the mesh:
5819
6131
  ` + peers.map(
@@ -5831,7 +6143,7 @@ Example: To inspect backend endpoints from frontend, call peer_call_tool("backen
5831
6143
  if (mode === "plan") {
5832
6144
  return `You are IUB CLI, a world-class Principal Software Architect and Systems Designer running directly in the user's terminal. You are designed to be more intelligent, thorough, and reliable than other agents like OpenCode or FreeBuf.
5833
6145
 
5834
- ### \u{1F6A8} CRITICAL DIRECTIVE 1: STRICTLY 100% ENGLISH OUTPUT ONLY (MANDATORY)
6146
+ ### CRITICAL DIRECTIVE 1: STRICTLY 100% ENGLISH OUTPUT ONLY (MANDATORY)
5835
6147
  - YOU MUST COMMUNICATE AND RESPOND EXCLUSIVELY IN ENGLISH.
5836
6148
  - UNDER NO CIRCUMSTANCES SHOULD YOU OUTPUT BENGALI SCRIPT (\u09AC\u09BE\u0982\u09B2\u09BE).
5837
6149
  - Monospace terminal consoles and Windows fonts cannot render complex Bengali ligatures and conjuncts properly, resulting in broken, overlapping characters.
@@ -5839,7 +6151,7 @@ Example: To inspect backend endpoints from frontend, call peer_call_tool("backen
5839
6151
 
5840
6152
  ${envContext.summary}
5841
6153
  ${meshContext}
5842
- ### \u{1F31F} CURRENT ACTIVE MODE: \u{1F4CB} PLAN MODE (ARCHITECT & PLANNING ONLY)
6154
+ ### CURRENT ACTIVE MODE: PLAN MODE (ARCHITECT & PLANNING ONLY)
5843
6155
  - You are strictly in PLAN MODE. You act as an expert senior software architect.
5844
6156
  - Your primary duty is to deeply investigate the workspace, analyze requirements, explore existing code, and formulate a comprehensive, battle-tested, numbered step-by-step architectural plan.
5845
6157
  - In this mode, you ONLY have read-only tools:
@@ -5854,12 +6166,12 @@ ${meshContext}
5854
6166
  9. peer_send_message(peer, message): Coordinate architectural contracts with peers.
5855
6167
  - YOU CANNOT AND MUST NOT write files or run terminal commands. Any attempt will be safely blocked.
5856
6168
  - Your architectural breakdown MUST be thorough and structured:
5857
- 1. \u{1F3AF} Executive Architecture Summary & Requirements Analysis.
5858
- 2. \u{1F4C2} Proposed Project & Directory Structure.
5859
- 3. \u{1F4E6} Dependencies, Libraries & Versions needed.
5860
- 4. \u{1F9E9} Core Components, Modules, Data Models & API Contracts.
5861
- 5. \u{1F6E0}\uFE0F Step-by-Step Implementation Roadmap (ordered sequence of files to create/edit).
5862
- 6. \u{1F9EA} Verification & Testing Strategy.
6169
+ 1. Executive Architecture Summary & Requirements Analysis.
6170
+ 2. Proposed Project & Directory Structure.
6171
+ 3. Dependencies, Libraries & Versions needed.
6172
+ 4. Core Components, Modules, Data Models & API Contracts.
6173
+ 5. Step-by-Step Implementation Roadmap (ordered sequence of files to create/edit).
6174
+ 6. Verification & Testing Strategy.
5863
6175
 
5864
6176
  ### 1. LANGUAGE & COMMUNICATION RULES (CRITICAL):
5865
6177
  - ALWAYS write all responses, architectural plans, explanations, code, and terminal guidance in clear, professional ENGLISH.
@@ -5868,7 +6180,7 @@ ${meshContext}
5868
6180
  }
5869
6181
  return `You are IUB CLI v2.0, a world-class Principal Full-Stack Software Engineer and Autonomous AI Coding Agent running directly in the user's terminal. You are designed to outperform modern AI coding agents like OpenCode and Claude Code in intelligence, self-healing, search speed, and reliability.
5870
6182
 
5871
- ### \u{1F6A8} CRITICAL DIRECTIVE 1: STRICTLY 100% ENGLISH OUTPUT ONLY (MANDATORY)
6183
+ ### CRITICAL DIRECTIVE 1: STRICTLY 100% ENGLISH OUTPUT ONLY (MANDATORY)
5872
6184
  - YOU MUST COMMUNICATE AND RESPOND EXCLUSIVELY IN ENGLISH.
5873
6185
  - UNDER NO CIRCUMSTANCES SHOULD YOU OUTPUT BENGALI SCRIPT (\u09AC\u09BE\u0982\u09B2\u09BE).
5874
6186
  - Monospace terminal consoles and Windows fonts cannot render complex Bengali ligatures and conjuncts properly, resulting in broken, overlapping characters.
@@ -5876,7 +6188,7 @@ ${meshContext}
5876
6188
 
5877
6189
  ${envContext.summary}
5878
6190
  ${meshContext}
5879
- ### \u{1F31F} CURRENT ACTIVE MODE: \u26A1 BUILD MODE (AUTONOMOUS BUILDER)
6191
+ ### CURRENT ACTIVE MODE: BUILD MODE (AUTONOMOUS BUILDER)
5880
6192
  - You are 100% in BUILD MODE right now. You are NOT in plan mode.
5881
6193
  - File creation (write_file), surgical editing (edit_file), and terminal command execution (run_command) are FULLY UNLOCKED AND ACTIVE.
5882
6194
  - NEVER claim or state that you are in plan mode, and NEVER claim you cannot write or edit files.
@@ -5897,7 +6209,7 @@ ${meshContext}
5897
6209
  11. peer_call_tool(peer, tool, args): Remotely execute tools (read_file, write_file, edit_file, run_command, list_files) in peer workspaces.
5898
6210
  12. peer_send_message(peer, message): Coordinate schemas, contracts, or tasks with peer instances.
5899
6211
 
5900
- ### \u{1F9E0} INTELLIGENT AGENT PROTOCOL (FOLLOW RIGOROUSLY):
6212
+ ### INTELLIGENT AGENT PROTOCOL (FOLLOW RIGOROUSLY):
5901
6213
  1. **Investigate Before Acting**:
5902
6214
  - Always explore the workspace with list_files, read_file, or grep_search first. Never code blindly without understanding existing dependencies and architecture.
5903
6215
  2. **Surgical Editing Preference (CRITICAL)**:
@@ -5994,11 +6306,7 @@ var IUBAgent = class {
5994
6306
  }
5995
6307
  if (this.config.provider === "gemini") {
5996
6308
  const normalized = normalizeGeminiModel(this.config.model);
5997
- if (!normalized || !GEMINI_CASCADE_CHAIN.includes(normalized)) {
5998
- this.config.model = "gemini-3.5-flash-lite";
5999
- } else {
6000
- this.config.model = normalized;
6001
- }
6309
+ this.config.model = normalized || "gemini-3.5-flash-lite";
6002
6310
  delete this.config.baseURL;
6003
6311
  this.geminiClient = new GoogleGenAI2({ apiKey: this.config.apiKey });
6004
6312
  this.openAIClient = void 0;
@@ -6016,6 +6324,7 @@ var IUBAgent = class {
6016
6324
  * Set agent mode (build or plan) and update prompt instructions.
6017
6325
  */
6018
6326
  setMode(mode) {
6327
+ if (this.mode === mode) return;
6019
6328
  this.mode = mode;
6020
6329
  this.updateSystemPrompt();
6021
6330
  }
@@ -6035,13 +6344,13 @@ var IUBAgent = class {
6035
6344
  if (this.mode === "build") {
6036
6345
  this.openAIMessages.push({
6037
6346
  role: "system",
6038
- content: "[SYSTEM DIRECTIVE: The user has switched the agent to \u26A1 BUILD MODE. You have full authority to use write_file, edit_file, and run_command immediately. Any previous PLAN MODE restrictions or tool blocks are completely lifted. Code and build the solution right now.]"
6347
+ content: "[SYSTEM DIRECTIVE: The user has switched the agent to BUILD MODE. You have full authority to use write_file, edit_file, and run_command immediately. Any previous PLAN MODE restrictions or tool blocks are completely lifted. Code and build the solution right now.]"
6039
6348
  });
6040
6349
  this.geminiContents.push({
6041
6350
  role: "user",
6042
6351
  parts: [
6043
6352
  {
6044
- text: "[SYSTEM NOTIFICATION: IUB CLI is now in \u26A1 BUILD MODE. Autonomous file creation, editing, and terminal commands are active.]"
6353
+ text: "[SYSTEM NOTIFICATION: IUB CLI is now in BUILD MODE. Autonomous file creation, editing, and terminal commands are active.]"
6045
6354
  }
6046
6355
  ]
6047
6356
  });
@@ -6056,13 +6365,13 @@ var IUBAgent = class {
6056
6365
  } else {
6057
6366
  this.openAIMessages.push({
6058
6367
  role: "system",
6059
- content: "[SYSTEM DIRECTIVE: The user has switched the agent to \u{1F4CB} PLAN MODE. Act as Senior Architect formulating structured plans without modifying workspace files.]"
6368
+ content: "[SYSTEM DIRECTIVE: The user has switched the agent to PLAN MODE. Act as Senior Architect formulating structured plans without modifying workspace files.]"
6060
6369
  });
6061
6370
  this.geminiContents.push({
6062
6371
  role: "user",
6063
6372
  parts: [
6064
6373
  {
6065
- text: "[SYSTEM NOTIFICATION: IUB CLI is now in \u{1F4CB} PLAN MODE. Only read-only tools are enabled.]"
6374
+ text: "[SYSTEM NOTIFICATION: IUB CLI is now in PLAN MODE. Only read-only tools are enabled.]"
6066
6375
  }
6067
6376
  ]
6068
6377
  });
@@ -6077,12 +6386,23 @@ var IUBAgent = class {
6077
6386
  }
6078
6387
  }
6079
6388
  /**
6080
- * Update configuration and recreate clients.
6389
+ * Update configuration and recreate clients while preserving conversation history by default.
6081
6390
  */
6082
- updateConfig(newConfig) {
6391
+ updateConfig(newConfig, resetHistory = false) {
6392
+ const prevProvider = this.config.provider;
6083
6393
  this.config = newConfig;
6084
6394
  this.initClients();
6085
- 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
+ }
6086
6406
  }
6087
6407
  onModelChangeCallback;
6088
6408
  setOnModelChange(cb) {
@@ -6179,6 +6499,9 @@ var IUBAgent = class {
6179
6499
  merged.push({ role: item.role, parts: [...item.parts] });
6180
6500
  }
6181
6501
  }
6502
+ while (merged.length > 0 && merged[0].role !== "user") {
6503
+ merged.shift();
6504
+ }
6182
6505
  this.geminiContents = merged;
6183
6506
  }
6184
6507
  /**
@@ -6249,7 +6572,8 @@ ${String(out).slice(0, 6e3)}`);
6249
6572
  * Intelligently cascade to the next available model when token quota, auth error, or rate limit is reached.
6250
6573
  * Cycles cleanly across providers without looping back into dead providers or persisting broken models.
6251
6574
  */
6252
- async cascadeModel(currentModel, reason) {
6575
+ async cascadeModel(currentModel, reason, signal) {
6576
+ if (signal?.aborted) return null;
6253
6577
  this.cascadeStepsCount++;
6254
6578
  this.attemptedModelsInCascade.add(currentModel);
6255
6579
  if (this.config.provider === "gemini") {
@@ -6365,7 +6689,7 @@ ${String(out).slice(0, 6e3)}`);
6365
6689
  const nextOR = switchToOpenRouter("Custom provider rate-limited/exhausted; cascading to OpenRouter Free");
6366
6690
  if (nextOR) return nextOR;
6367
6691
  }
6368
- const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade);
6692
+ const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade, false, false);
6369
6693
  if (explored) {
6370
6694
  this.attemptedModelsInCascade.add(explored.id);
6371
6695
  this.initClients();
@@ -6382,13 +6706,15 @@ ${String(out).slice(0, 6e3)}`);
6382
6706
  const cooldownSec = 10;
6383
6707
  renderRollingRateLimitNotice(currentModel, cooldownSec, "All free models in rolling rate limit");
6384
6708
  for (let rem = cooldownSec; rem > 0; rem--) {
6385
- const msg = `\u23F3 Free rate limits active \u2022 Auto-cooling down (${rem}s) [Never-Stop Mode]... (Esc to cancel)`;
6709
+ if (signal?.aborted) return null;
6710
+ const msg = `Free rate limits active \u2022 Auto-cooling down (${rem}s) [Never-Stop Mode]... (Esc to cancel)`;
6386
6711
  updateFixedBottomStatus(msg, { mode: this.mode, model: this.config.model });
6387
6712
  await new Promise((r) => setTimeout(r, 1e3));
6388
6713
  }
6714
+ if (signal?.aborted) return null;
6389
6715
  this.attemptedModelsInCascade.clear();
6390
6716
  this.deadProvidersInTurn.clear();
6391
- const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true);
6717
+ const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true, false);
6392
6718
  if (recovered) {
6393
6719
  this.initClients();
6394
6720
  if (recovered.provider === "gemini") {
@@ -6457,9 +6783,13 @@ ${String(out).slice(0, 6e3)}`);
6457
6783
  const turnsBefore = this.openAIMessages.length + this.geminiContents.length;
6458
6784
  if (this.openAIMessages.length > 5) {
6459
6785
  const systemMsg = this.openAIMessages[0];
6460
- 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);
6461
6791
  const intermediateUserQueries = [];
6462
- for (let i = 1; i < this.openAIMessages.length - 4; i++) {
6792
+ for (let i = 1; i < sliceStart; i++) {
6463
6793
  const msg = this.openAIMessages[i];
6464
6794
  if (msg.role === "user" && typeof msg.content === "string") {
6465
6795
  intermediateUserQueries.push(msg.content.slice(0, 100));
@@ -6472,7 +6802,11 @@ ${String(out).slice(0, 6e3)}`);
6472
6802
  this.openAIMessages = [systemMsg, summaryNote, ...recent];
6473
6803
  }
6474
6804
  if (this.geminiContents.length > 4) {
6475
- 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;
6476
6810
  }
6477
6811
  const turnsAfter = this.openAIMessages.length + this.geminiContents.length;
6478
6812
  return { turnsBefore, turnsAfter };
@@ -6496,15 +6830,73 @@ ${String(out).slice(0, 6e3)}`);
6496
6830
  estimatedCostSavedUsd: Math.round(costSaved * 1e3) / 1e3
6497
6831
  };
6498
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
+ }
6499
6888
  /**
6500
6889
  * Main chat turn loop with automatic tool execution and cross-provider failover.
6501
6890
  */
6502
6891
  async chat(userInput, options) {
6503
6892
  if (options?.signal?.aborted) {
6504
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
6893
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6505
6894
  }
6506
6895
  this.resetCascadeAttempts();
6507
- const modeDirective = this.mode === "build" ? `[SYSTEM STATUS: ACTIVE MODE = \u26A1 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 = \u{1F4CB} PLAN MODE. You are in read-only planning mode. Formulate comprehensive step-by-step plans without modifying files.]`;
6896
+ if (!options?.isCascadeRetry) {
6897
+ this.sanitizeDanglingHistory();
6898
+ }
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.]`;
6508
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.]
6509
6901
  ${modeDirective}
6510
6902
 
@@ -6517,17 +6909,22 @@ ${userInput}`;
6517
6909
  }
6518
6910
  } catch (err) {
6519
6911
  if (options?.signal?.aborted) {
6520
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
6912
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6521
6913
  }
6522
- 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
+ );
6523
6919
  if (nextModel) {
6920
+ const retryOpts = { ...options, isCascadeRetry: true };
6524
6921
  if (this.config.provider === "gemini") {
6525
- return await this.chatGemini(englishEnforcedInput, options);
6922
+ return await this.chatGemini(englishEnforcedInput, retryOpts);
6526
6923
  } else {
6527
- return await this.chatOpenAI(englishEnforcedInput, options);
6924
+ return await this.chatOpenAI(englishEnforcedInput, retryOpts);
6528
6925
  }
6529
6926
  }
6530
- return chalk8.yellow("\n\u23F3 All free model tokens are currently exhausted across all providers. Check the renewal countdown above.");
6927
+ return chalk8.yellow("\nAll free model tokens are currently exhausted across all providers. Check the renewal countdown above.");
6531
6928
  }
6532
6929
  }
6533
6930
  shouldNudgePassiveBuildReply(userPrompt, replyText, toolsExecutedInChat, alreadyNudged) {
@@ -6548,13 +6945,12 @@ ${userInput}`;
6548
6945
  */
6549
6946
  async chatGemini(userInput, options) {
6550
6947
  if (options?.signal?.aborted) {
6551
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
6948
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6552
6949
  }
6553
6950
  if (!this.geminiClient) {
6554
6951
  throw new Error("Gemini client is not initialized.");
6555
6952
  }
6556
- const lastContent = this.geminiContents[this.geminiContents.length - 1];
6557
- if (!lastContent || lastContent.role !== "user") {
6953
+ if (!options?.isCascadeRetry) {
6558
6954
  const parts = [{ text: userInput }];
6559
6955
  if (options?.images && options.images.length > 0) {
6560
6956
  for (const img of options.images) {
@@ -6566,18 +6962,24 @@ ${userInput}`;
6566
6962
  });
6567
6963
  }
6568
6964
  }
6569
- this.geminiContents.push({
6570
- role: "user",
6571
- parts
6572
- });
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
+ }
6573
6974
  }
6574
6975
  const maxTurns = 40;
6575
6976
  let turnCount = 0;
6576
6977
  let toolsExecutedInChat = 0;
6577
6978
  let nudgedBuildExecution = false;
6979
+ let emptyNudges = 0;
6578
6980
  while (turnCount < maxTurns) {
6579
6981
  if (options?.signal?.aborted) {
6580
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
6982
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6581
6983
  }
6582
6984
  turnCount++;
6583
6985
  updateFixedBottomStatus(
@@ -6600,29 +7002,18 @@ ${userInput}`;
6600
7002
  for (const candidateModel of modelCandidates) {
6601
7003
  if (options?.signal?.aborted) {
6602
7004
  spinner.stop();
6603
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7005
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6604
7006
  }
6605
7007
  let attempts = 0;
6606
7008
  const maxModelAttempts = 2;
6607
7009
  while (attempts < maxModelAttempts) {
6608
7010
  if (options?.signal?.aborted) {
6609
7011
  spinner.stop();
6610
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7012
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6611
7013
  }
6612
7014
  attempts++;
6613
- let timeoutId;
6614
7015
  try {
6615
- const abortPromise = new Promise((_, reject) => {
6616
- if (options?.signal?.aborted) {
6617
- reject(new Error("ABORTED_BY_USER"));
6618
- return;
6619
- }
6620
- options?.signal?.addEventListener("abort", () => reject(new Error("ABORTED_BY_USER")), { once: true });
6621
- });
6622
- const timeoutPromise = new Promise((_, reject) => {
6623
- timeoutId = setTimeout(() => reject(new Error("Gemini API request timed out (18s)")), 18e3);
6624
- });
6625
- response = await Promise.race([
7016
+ response = await this.raceWithTimeoutAndAbort(
6626
7017
  this.geminiClient.models.generateContent({
6627
7018
  model: candidateModel,
6628
7019
  contents: this.geminiContents,
@@ -6631,10 +7022,9 @@ ${userInput}`;
6631
7022
  tools: this.mode === "plan" ? PLAN_GEMINI_TOOLS : BUILD_GEMINI_TOOLS
6632
7023
  }
6633
7024
  }),
6634
- timeoutPromise,
6635
- abortPromise
6636
- ]);
6637
- if (timeoutId) clearTimeout(timeoutId);
7025
+ `Gemini API request timed out (${Math.round(this.getRequestTimeoutMs() / 1e3)}s)`,
7026
+ options?.signal
7027
+ );
6638
7028
  usedGeminiModel = candidateModel;
6639
7029
  if (candidateModel !== this.config.model) {
6640
7030
  spinner.stop();
@@ -6646,10 +7036,9 @@ ${userInput}`;
6646
7036
  lastError = null;
6647
7037
  break;
6648
7038
  } catch (err) {
6649
- if (timeoutId) clearTimeout(timeoutId);
6650
7039
  if (options?.signal?.aborted || err?.message === "ABORTED_BY_USER") {
6651
7040
  spinner.stop();
6652
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7041
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6653
7042
  }
6654
7043
  lastError = err;
6655
7044
  this.attemptedModelsInCascade.add(candidateModel);
@@ -6680,37 +7069,40 @@ ${userInput}`;
6680
7069
  spinner.stop();
6681
7070
  if (!response) {
6682
7071
  const errMsg = lastError ? lastError?.message || String(lastError) : "All Gemini candidates exhausted";
7072
+ const retryOpts = { ...options, isCascadeRetry: true };
6683
7073
  if (errMsg.includes("API_KEY_INVALID") || errMsg.includes("403") || errMsg.includes("401")) {
6684
7074
  const nextModel = await this.cascadeModel(
6685
7075
  this.config.model,
6686
- "Gemini auth error (401/403), cascading to OpenRouter/Custom"
7076
+ "Gemini auth error (401/403), cascading to OpenRouter/Custom",
7077
+ options?.signal
6687
7078
  );
6688
7079
  if (nextModel) {
6689
7080
  if (this.config.provider === "gemini") {
6690
- return await this.chatGemini(userInput, options);
7081
+ return await this.chatGemini(userInput, retryOpts);
6691
7082
  } else {
6692
- return await this.chatOpenAI(userInput, options);
7083
+ return await this.chatOpenAI(userInput, retryOpts);
6693
7084
  }
6694
7085
  }
6695
7086
  return chalk8.red(
6696
7087
  `
6697
- \u2716 Gemini API Key Error: Your API key appears to be invalid or expired.
7088
+ Gemini API Key Error: Your API key appears to be invalid or expired.
6698
7089
  Please run ${chalk8.yellow("/config")} to update your API key.`
6699
7090
  );
6700
7091
  } else {
6701
7092
  const nextModel = await this.cascadeModel(
6702
7093
  usedGeminiModel,
6703
- 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
6704
7096
  );
6705
7097
  if (nextModel) {
6706
7098
  if (this.config.provider === "gemini") {
6707
- return await this.chatGemini(userInput, options);
7099
+ return await this.chatGemini(userInput, retryOpts);
6708
7100
  } else {
6709
- return await this.chatOpenAI(userInput, options);
7101
+ return await this.chatOpenAI(userInput, retryOpts);
6710
7102
  }
6711
7103
  }
6712
7104
  return chalk8.yellow(
6713
- "\n\u23F3 All free model tokens are currently exhausted across all providers. Check the renewal countdown above."
7105
+ "\nAll free model tokens are currently exhausted across all providers. Check the renewal countdown above."
6714
7106
  );
6715
7107
  }
6716
7108
  }
@@ -6723,6 +7115,10 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6723
7115
  this.metrics.totalTokens += response.usageMetadata.totalTokenCount || 0;
6724
7116
  }
6725
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
+ }
6726
7122
  this.geminiContents.push({
6727
7123
  role: "user",
6728
7124
  parts: [
@@ -6738,13 +7134,18 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6738
7134
  }
6739
7135
  const directText = (candidate?.content?.parts || []).map((p) => typeof p.text === "string" ? p.text : "").join("").trim();
6740
7136
  if (!functionCalls || functionCalls.length === 0) {
6741
- if (!directText && turnCount < maxTurns) {
7137
+ if (!directText && turnCount < maxTurns && emptyNudges < 2) {
7138
+ emptyNudges++;
6742
7139
  this.geminiContents.push({
6743
7140
  role: "user",
6744
7141
  parts: [{ text: "Please continue and provide your response or call the needed tool." }]
6745
7142
  });
6746
7143
  continue;
6747
7144
  }
7145
+ if (!directText) {
7146
+ const reason = candidate?.finishReason ? ` (${candidate.finishReason})` : "";
7147
+ return `Model returned an empty response${reason}.`;
7148
+ }
6748
7149
  if (this.shouldNudgePassiveBuildReply(userInput, directText, toolsExecutedInChat, nudgedBuildExecution) && turnCount < maxTurns) {
6749
7150
  nudgedBuildExecution = true;
6750
7151
  this.geminiContents.push({
@@ -6762,7 +7163,7 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6762
7163
  const toolResponseParts = [];
6763
7164
  for (const call of functionCalls) {
6764
7165
  if (options?.signal?.aborted) {
6765
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7166
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6766
7167
  }
6767
7168
  const toolName = call.name;
6768
7169
  const toolArgs = call.args || {};
@@ -6773,7 +7174,7 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6773
7174
  toolsExecutedInChat++;
6774
7175
  const output = await executeTool(toolName, toolArgs, this.mode, options?.signal);
6775
7176
  if (options?.signal?.aborted) {
6776
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7177
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6777
7178
  }
6778
7179
  toolResponseParts.push({
6779
7180
  functionResponse: {
@@ -6795,23 +7196,24 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6795
7196
  */
6796
7197
  async chatOpenAI(userInput, options) {
6797
7198
  if (options?.signal?.aborted) {
6798
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7199
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6799
7200
  }
6800
7201
  if (!this.openAIClient || !this.config.apiKey) {
6801
7202
  const nextModel = await this.cascadeModel(
6802
7203
  this.config.model,
6803
- `Auth error / Missing API key for ${this.config.provider}`
7204
+ `Auth error / Missing API key for ${this.config.provider}`,
7205
+ options?.signal
6804
7206
  );
6805
7207
  if (nextModel) {
7208
+ const retryOpts = { ...options, isCascadeRetry: true };
6806
7209
  if (this.config.provider === "gemini") {
6807
- return await this.chatGemini(userInput, options);
7210
+ return await this.chatGemini(userInput, retryOpts);
6808
7211
  }
6809
7212
  } else {
6810
7213
  throw new Error("OpenAI client is not initialized.");
6811
7214
  }
6812
7215
  }
6813
- const lastMsg = this.openAIMessages[this.openAIMessages.length - 1];
6814
- if (!lastMsg || lastMsg.role !== "user") {
7216
+ if (!options?.isCascadeRetry) {
6815
7217
  if (options?.images && options.images.length > 0) {
6816
7218
  const contentParts = [{ type: "text", text: userInput }];
6817
7219
  for (const img of options.images) {
@@ -6837,9 +7239,10 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6837
7239
  let turnCount = 0;
6838
7240
  let toolsExecutedInChat = 0;
6839
7241
  let nudgedBuildExecution = false;
7242
+ let emptyNudges = 0;
6840
7243
  while (turnCount < maxTurns) {
6841
7244
  if (options?.signal?.aborted) {
6842
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7245
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6843
7246
  }
6844
7247
  turnCount++;
6845
7248
  updateFixedBottomStatus(
@@ -6856,24 +7259,14 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6856
7259
  while (cascadeAttempts < maxCascadeAttempts) {
6857
7260
  if (options?.signal?.aborted) {
6858
7261
  spinner.stop();
6859
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7262
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6860
7263
  }
6861
7264
  if (!this.openAIClient) {
6862
7265
  break;
6863
7266
  }
6864
- let timeoutId;
7267
+ const timeoutMs = this.getRequestTimeoutMs();
6865
7268
  try {
6866
- const abortPromise = new Promise((_, reject) => {
6867
- if (options?.signal?.aborted) {
6868
- reject(new Error("ABORTED_BY_USER"));
6869
- return;
6870
- }
6871
- options?.signal?.addEventListener("abort", () => reject(new Error("ABORTED_BY_USER")), { once: true });
6872
- });
6873
- const timeoutPromise = new Promise((_, reject) => {
6874
- timeoutId = setTimeout(() => reject(new Error("Provider API request timed out (18s)")), 18e3);
6875
- });
6876
- completion = await Promise.race([
7269
+ completion = await this.raceWithTimeoutAndAbort(
6877
7270
  this.openAIClient.chat.completions.create(
6878
7271
  {
6879
7272
  model: this.config.model,
@@ -6883,20 +7276,18 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6883
7276
  },
6884
7277
  {
6885
7278
  signal: options?.signal,
6886
- timeout: 18e3
7279
+ timeout: timeoutMs
6887
7280
  }
6888
7281
  ),
6889
- timeoutPromise,
6890
- abortPromise
6891
- ]);
6892
- if (timeoutId) clearTimeout(timeoutId);
7282
+ `Provider API request timed out (${Math.round(timeoutMs / 1e3)}s)`,
7283
+ options?.signal
7284
+ );
6893
7285
  this.persistVerifiedActiveModel();
6894
7286
  break;
6895
7287
  } catch (err) {
6896
- if (timeoutId) clearTimeout(timeoutId);
6897
7288
  if (options?.signal?.aborted || err?.message === "ABORTED_BY_USER") {
6898
7289
  spinner.stop();
6899
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7290
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6900
7291
  }
6901
7292
  const errMsg = err?.message || String(err);
6902
7293
  const lowerErr = errMsg.toLowerCase();
@@ -6909,7 +7300,7 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6909
7300
  for (let rem = waitSec; rem > 0; rem--) {
6910
7301
  if (options?.signal?.aborted) {
6911
7302
  spinner.stop();
6912
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7303
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6913
7304
  }
6914
7305
  const note = `Rolling rate limit cooldown (${rem}s) on [${this.config.model}] \u2022 Auto-resuming...`;
6915
7306
  spinner.text = chalk8.cyan(note);
@@ -6932,7 +7323,7 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6932
7323
  for (let rem = waitSec; rem > 0; rem--) {
6933
7324
  if (options?.signal?.aborted) {
6934
7325
  spinner.stop();
6935
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7326
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6936
7327
  }
6937
7328
  const note = `Free Zero-Key cooldown (${rem}s) \u2022 Tip: /config for instant free Gemini key`;
6938
7329
  spinner.text = chalk8.cyan(note);
@@ -6957,10 +7348,10 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6957
7348
  }
6958
7349
  cascadeAttempts++;
6959
7350
  spinner.stop();
6960
- const nextModel = await this.cascadeModel(this.config.model, cascadeReason);
7351
+ const nextModel = await this.cascadeModel(this.config.model, cascadeReason, options?.signal);
6961
7352
  if (nextModel) {
6962
7353
  if (this.config.provider === "gemini") {
6963
- return await this.chatGemini(userInput, options);
7354
+ return await this.chatGemini(userInput, { ...options, isCascadeRetry: true });
6964
7355
  }
6965
7356
  spinner.text = chalk8.cyan(`IUB CLI continuing with [${nextModel}]...`);
6966
7357
  spinner.start();
@@ -6969,38 +7360,43 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
6969
7360
  if (lowerErr.includes("401") || lowerErr.includes("invalid_api_key") || lowerErr.includes("user not found")) {
6970
7361
  return chalk8.red(
6971
7362
  `
6972
- \u2716 API Key Error: Authentication failed for ${this.config.provider}.
7363
+ API Key Error: Authentication failed for ${this.config.provider}.
6973
7364
  Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to configure a valid key.`
6974
7365
  );
6975
7366
  }
6976
7367
  return chalk8.yellow(
6977
- "\n\u23F3 All free model tokens are currently exhausted across all providers. Check the renewal countdown above."
7368
+ "\nAll free model tokens are currently exhausted across all providers. Check the renewal countdown above."
6978
7369
  );
6979
7370
  }
6980
7371
  }
6981
7372
  spinner.stop();
6982
7373
  if (options?.signal?.aborted) {
6983
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7374
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
6984
7375
  }
6985
7376
  if (!completion) {
6986
- 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);
6987
7378
  if (nextModel) {
7379
+ const retryOpts = { ...options, isCascadeRetry: true };
6988
7380
  if (this.config.provider === "gemini") {
6989
- return await this.chatGemini(userInput, options);
7381
+ return await this.chatGemini(userInput, retryOpts);
6990
7382
  } else {
6991
- return await this.chatOpenAI(userInput, options);
7383
+ return await this.chatOpenAI(userInput, retryOpts);
6992
7384
  }
6993
7385
  }
6994
7386
  return chalk8.yellow(
6995
- "\n\u23F3 All free model tokens are currently exhausted across all providers. Check the renewal countdown above."
7387
+ "\nAll free model tokens are currently exhausted across all providers. Check the renewal countdown above."
6996
7388
  );
6997
7389
  }
6998
7390
  const choice = completion.choices?.[0];
6999
7391
  if (!choice || !choice.message) {
7000
- 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
+ );
7001
7397
  if (nextModel) {
7002
7398
  if (this.config.provider === "gemini") {
7003
- return await this.chatGemini(userInput, options);
7399
+ return await this.chatGemini(userInput, { ...options, isCascadeRetry: true });
7004
7400
  }
7005
7401
  continue;
7006
7402
  }
@@ -7021,7 +7417,8 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7021
7417
  if (!message.tool_calls || message.tool_calls.length === 0) {
7022
7418
  const rawText = message.content?.trim() || "";
7023
7419
  const reasoningText = (message.reasoning || "").trim();
7024
- if (!rawText && reasoningText && turnCount < maxTurns) {
7420
+ if (!rawText && reasoningText && turnCount < maxTurns && emptyNudges < 2) {
7421
+ emptyNudges++;
7025
7422
  this.openAIMessages.push({
7026
7423
  role: "user",
7027
7424
  content: "Please proceed directly with your final answer or call the required tool now."
@@ -7041,14 +7438,24 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7041
7438
  }
7042
7439
  for (const toolCall of message.tool_calls) {
7043
7440
  if (options?.signal?.aborted) {
7044
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7441
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7442
+ }
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;
7045
7453
  }
7046
- if (toolCall.type !== "function") continue;
7047
- const fnName = toolCall.function.name;
7454
+ const fnName = fnObj.name;
7048
7455
  let fnArgs = null;
7049
7456
  let parseError = null;
7050
7457
  try {
7051
- fnArgs = JSON.parse(toolCall.function.arguments || "{}");
7458
+ fnArgs = JSON.parse(fnObj.arguments || "{}");
7052
7459
  } catch (e) {
7053
7460
  parseError = e?.message || "Invalid JSON";
7054
7461
  }
@@ -7067,7 +7474,7 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7067
7474
  toolsExecutedInChat++;
7068
7475
  const toolResult = await executeTool(fnName, fnArgs, this.mode, options?.signal);
7069
7476
  if (options?.signal?.aborted) {
7070
- return chalk8.yellow("\n\u23F9\uFE0F Task cancelled by user (Escape key pressed).");
7477
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7071
7478
  }
7072
7479
  this.openAIMessages.push({
7073
7480
  role: "tool",
@@ -7217,6 +7624,8 @@ var MeshNode = class extends EventEmitter {
7217
7624
  }
7218
7625
  });
7219
7626
  server.once("listening", () => {
7627
+ server.on("error", () => {
7628
+ });
7220
7629
  this.wss = server;
7221
7630
  this.isHost = true;
7222
7631
  this.setupHostServer();
@@ -7231,6 +7640,8 @@ var MeshNode = class extends EventEmitter {
7231
7640
  if (!this.wss) return;
7232
7641
  this.wss.on("connection", (ws) => {
7233
7642
  let authedPeer = null;
7643
+ ws.on("error", () => {
7644
+ });
7234
7645
  const authTimeout = setTimeout(() => {
7235
7646
  if (!authedPeer) {
7236
7647
  try {
@@ -7317,6 +7728,20 @@ var MeshNode = class extends EventEmitter {
7317
7728
  const ws = new WebSocket(url);
7318
7729
  this.clientWs = ws;
7319
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);
7320
7745
  ws.on("open", () => {
7321
7746
  const authMsg = {
7322
7747
  type: "AUTH",
@@ -7335,7 +7760,7 @@ var MeshNode = class extends EventEmitter {
7335
7760
  this.peers.set(p.nodeId, p);
7336
7761
  }
7337
7762
  }
7338
- resolve();
7763
+ done();
7339
7764
  return;
7340
7765
  }
7341
7766
  if (msg.type === "AUTH_FAIL") {
@@ -7344,7 +7769,7 @@ var MeshNode = class extends EventEmitter {
7344
7769
  ws.close();
7345
7770
  } catch {
7346
7771
  }
7347
- resolve();
7772
+ done();
7348
7773
  return;
7349
7774
  }
7350
7775
  if (msg.type === "PEER_JOINED") {
@@ -7383,12 +7808,12 @@ var MeshNode = class extends EventEmitter {
7383
7808
  }
7384
7809
  });
7385
7810
  ws.on("error", () => {
7386
- resolve();
7811
+ done();
7387
7812
  });
7388
7813
  ws.on("close", () => {
7389
7814
  this.peers.clear();
7390
7815
  this.clientWs = null;
7391
- resolve();
7816
+ done();
7392
7817
  if (this.running) {
7393
7818
  this.scheduleReconnect();
7394
7819
  }
@@ -7555,29 +7980,47 @@ var MeshNode = class extends EventEmitter {
7555
7980
  }
7556
7981
  /**
7557
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.
7558
7984
  */
7559
7985
  findPeer(roleOrId) {
7560
7986
  const query = roleOrId.toLowerCase().trim();
7561
- if (this.nodeId.toLowerCase() === query || this.role.toLowerCase() === query) {
7562
- return this.getMyPeerInfo();
7563
- }
7564
7987
  for (const p of this.peers.values()) {
7565
7988
  if (p.nodeId.toLowerCase() === query || p.role.toLowerCase() === query) {
7566
7989
  return p;
7567
7990
  }
7568
7991
  }
7992
+ if (this.nodeId.toLowerCase() === query || this.role.toLowerCase() === query) {
7993
+ return this.getMyPeerInfo();
7994
+ }
7569
7995
  return null;
7570
7996
  }
7571
7997
  /**
7572
7998
  * Execute a tool on a remote peer instance over the WebSocket mesh RPC.
7573
7999
  */
7574
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
+ }
7575
8015
  const peer = this.findPeer(targetRoleOrId);
7576
- if (!peer && targetRoleOrId !== "all") {
8016
+ if (!peer) {
7577
8017
  const activePeers = this.listPeers().filter((p) => p.nodeId !== this.nodeId);
7578
8018
  const peerSummary = activePeers.length > 0 ? `Connected peers: ${activePeers.map((p) => `"${p.role}" (${p.workspace})`).join(", ")}` : "No other IUB CLI instances are currently connected.";
7579
8019
  return `Error: Peer instance "${targetRoleOrId}" not found in mesh. ${peerSummary}`;
7580
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
+ }
7581
8024
  const reqId = `rpc-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`;
7582
8025
  const req = {
7583
8026
  type: "RPC_REQUEST",
@@ -7634,6 +8077,9 @@ var MeshNode = class extends EventEmitter {
7634
8077
  if (!peer) {
7635
8078
  return `Error: Peer "${targetRoleOrId}" is not connected to the mesh.`;
7636
8079
  }
8080
+ if (peer.nodeId === this.nodeId) {
8081
+ return `Error: Target "${targetRoleOrId}" resolves to this local instance.`;
8082
+ }
7637
8083
  const reqId = `msg-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`;
7638
8084
  const req = {
7639
8085
  type: "RPC_REQUEST",
@@ -7749,7 +8195,65 @@ function gracefulExit(code = 0) {
7749
8195
  process.stdin.unref?.();
7750
8196
  } catch {
7751
8197
  }
7752
- 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);
7753
8257
  }
7754
8258
  process.on("exit", () => {
7755
8259
  getActiveMeshNode()?.stop();
@@ -7817,7 +8321,25 @@ function attachEscapeListener(onEscape) {
7817
8321
  };
7818
8322
  }
7819
8323
  var program = new Command();
7820
- 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
+ }
7821
8343
  if (options.yes) {
7822
8344
  safetySession.autoApproveAll = true;
7823
8345
  }
@@ -7832,12 +8354,12 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7832
8354
  model: localOllama[0],
7833
8355
  baseURL: "http://localhost:11434/v1"
7834
8356
  };
7835
- console.log(chalk9.cyan(`\u2139\uFE0F Auto-detected Local Ollama (${localOllama[0]}).`));
8357
+ console.log(chalk9.cyan(` Auto-detected Local Ollama (${localOllama[0]}).`));
7836
8358
  } else {
7837
8359
  config = createZeroKeyConfig();
7838
8360
  console.log(
7839
8361
  chalk9.cyan(
7840
- '\u2139\uFE0F No API key configured \u2014 starting with Free Zero-Key AI. Run "iubcli config" anytime to add a free Gemini key.'
8362
+ ' No API key configured \u2014 starting with Free Zero-Key AI. Run "iubcli config" anytime to add a free Gemini key.'
7841
8363
  )
7842
8364
  );
7843
8365
  }
@@ -7853,13 +8375,13 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7853
8375
  if (options.model) {
7854
8376
  config.model = options.model;
7855
8377
  }
7856
- const initialMode = options.mode === "plan" ? "plan" : "build";
8378
+ const initialMode = rawMode === "plan" ? "plan" : "build";
7857
8379
  const agent = new IUBAgent(config, initialMode);
7858
8380
  let meshNode = null;
7859
- if (!options.noMesh) {
8381
+ if (options.mesh !== false) {
7860
8382
  meshNode = new MeshNode({
7861
8383
  role: options.role,
7862
- port: options.meshPort ? parseInt(options.meshPort, 10) : void 0,
8384
+ port: parsedMeshPort,
7863
8385
  token: options.meshToken,
7864
8386
  mode: initialMode,
7865
8387
  model: config.model,
@@ -7867,7 +8389,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7867
8389
  workspace: process.cwd(),
7868
8390
  onRemoteToolExecution: async (tool, args, fromRole) => {
7869
8391
  console.log(chalk9.cyan(`
7870
- \u{1F4E1} [Mesh RPC from ${chalk9.bold(fromRole)}] Executing tool: ${chalk9.bold(tool)}`));
8392
+ [Mesh RPC from ${chalk9.bold(fromRole)}] Executing tool: ${chalk9.bold(tool)}`));
7871
8393
  updateFixedBottomStatus(`[Mesh: ${fromRole}] Executing ${tool}...`, {
7872
8394
  mode: agent.getMode(),
7873
8395
  model: config?.model || "unknown"
@@ -7879,7 +8401,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7879
8401
  onPeerMessage: (message, fromRole) => {
7880
8402
  console.log(
7881
8403
  chalk9.bgHex("#002B5C").hex("#00A3FF").bold(`
7882
- \u{1F4EC} [Mesh Message from ${fromRole}]: `) + chalk9.white(message) + "\n"
8404
+ [Mesh Message from ${fromRole}]: `) + chalk9.white(message) + "\n"
7883
8405
  );
7884
8406
  },
7885
8407
  onPeerConnect: (peer) => {
@@ -7893,7 +8415,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7893
8415
  }
7894
8416
  console.log(
7895
8417
  chalk9.green(`
7896
- \u{1F310} [Mesh] Connected to peer [${chalk9.bold(peer.role)}] (${peer.workspace})
8418
+ [Mesh] Connected to peer [${chalk9.bold(peer.role)}] (${peer.workspace})
7897
8419
  `)
7898
8420
  );
7899
8421
  updateFixedBottomStatus(`Peer connected: ${peer.role}`, {
@@ -7912,7 +8434,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7912
8434
  }
7913
8435
  console.log(
7914
8436
  chalk9.yellow(`
7915
- \u{1F310} [Mesh] Peer disconnected: [${chalk9.bold(peer.role)}] (${peer.workspace})
8437
+ [Mesh] Peer disconnected: [${chalk9.bold(peer.role)}] (${peer.workspace})
7916
8438
  `)
7917
8439
  );
7918
8440
  }
@@ -7957,7 +8479,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7957
8479
  console.log(
7958
8480
  chalk9.cyan(
7959
8481
  `
7960
- \u26A1 Running single prompt with ${formatProviderLabel(config)} (${config.model}) in [${initialMode.toUpperCase()} MODE]:`
8482
+ Running single prompt with ${formatProviderLabel(config)} (${config.model}) in [${initialMode.toUpperCase()} MODE]:`
7961
8483
  )
7962
8484
  );
7963
8485
  console.log(chalk9.white(options.prompt) + "\n");
@@ -7985,7 +8507,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
7985
8507
  renderInterruptedNotice();
7986
8508
  } else {
7987
8509
  console.error(chalk9.red(`
7988
- \u2716 Error: ${err.message}
8510
+ Error: ${err.message}
7989
8511
  `));
7990
8512
  process.exitCode = 1;
7991
8513
  }
@@ -8020,7 +8542,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8020
8542
  }
8021
8543
  const lowerCmd = trimmed.toLowerCase();
8022
8544
  if (lowerCmd === "/exit" || lowerCmd === "/quit") {
8023
- console.log(chalk9.hex("#00A3FF")("\nThanks for using IUB CLI. Happy coding! \u{1F680}\n"));
8545
+ console.log(chalk9.hex("#00A3FF")("\nThanks for using IUB CLI. Happy coding! \n"));
8024
8546
  gracefulExit(0);
8025
8547
  return;
8026
8548
  }
@@ -8032,13 +8554,14 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8032
8554
  const found = await exploreAndSelectFreeModel(config);
8033
8555
  if (found) {
8034
8556
  agent.updateConfig(config);
8557
+ meshNode?.updateState({ model: config.model });
8035
8558
  updateDockedModel(
8036
- PROVIDER_LABELS[config.provider] || config.provider,
8559
+ formatProviderLabel(config),
8037
8560
  config.model,
8038
8561
  agent.getMode()
8039
8562
  );
8040
8563
  } else {
8041
- console.log(chalk9.yellow("\n\u26A0\uFE0F All free models currently have zero available quota across all providers.\n"));
8564
+ console.log(chalk9.yellow("\nAll free models currently have zero available quota across all providers.\n"));
8042
8565
  }
8043
8566
  continue;
8044
8567
  }
@@ -8052,12 +8575,12 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8052
8575
  capturedPath = resolved;
8053
8576
  } else {
8054
8577
  console.log(chalk9.red(`
8055
- \u2716 Could not find image file at: ${cleanArg}
8578
+ Could not find image file at: ${cleanArg}
8056
8579
  `));
8057
8580
  continue;
8058
8581
  }
8059
8582
  } else {
8060
- process.stdout.write(chalk9.cyan("\n\u{1F4F8} Checking system clipboard for screenshot / image...\n"));
8583
+ process.stdout.write(chalk9.cyan("\nChecking system clipboard for screenshot / image...\n"));
8061
8584
  capturedPath = captureClipboardImage();
8062
8585
  }
8063
8586
  if (capturedPath) {
@@ -8066,19 +8589,19 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8066
8589
  stagedImages.push(payload);
8067
8590
  const kb = (payload.size / 1024).toFixed(1);
8068
8591
  console.log(
8069
- "\n" + chalk9.bgHex("#002B5C").hex("#00A3FF").bold(" \u{1F5BC}\uFE0F IMAGE STAGED SUCCESSFULLY ") + `
8592
+ "\n" + chalk9.bgHex("#002B5C").hex("#00A3FF").bold(" IMAGE STAGED SUCCESSFULLY ") + `
8070
8593
  ${chalk9.gray("File:")} ${chalk9.white(path8.basename(payload.path))}
8071
8594
  ${chalk9.gray("Format:")} ${chalk9.cyan(payload.mimeType)} (${kb} KB)
8072
8595
  ${chalk9.gray("Saved to:")} ${chalk9.dim(payload.path)}
8073
8596
 
8074
- ` + chalk9.green.bold("\u2714 Ready!") + chalk9.white(' Type your question or prompt (e.g. "Explain this error" or "Code this UI") and press Enter.\n')
8597
+ ` + chalk9.green.bold("Ready!") + chalk9.white(' Type your question or prompt (e.g. "Explain this error" or "Code this UI") and press Enter.\n')
8075
8598
  );
8076
8599
  } else {
8077
- console.log(chalk9.yellow("\n\u26A0\uFE0F Could not read image payload (file might be damaged or larger than 15MB).\n"));
8600
+ console.log(chalk9.yellow("\nCould not read image payload (file might be damaged or larger than 15MB).\n"));
8078
8601
  }
8079
8602
  } else {
8080
8603
  console.log(
8081
- "\n" + chalk9.bgHex("#FF9900").black.bold(" \u26A0\uFE0F NO IMAGE FOUND IN CLIPBOARD ") + "\n" + chalk9.white("No image data was found in your clipboard.\n\n") + chalk9.yellow("\u{1F4A1} How to paste a screenshot:") + `
8604
+ "\n" + chalk9.bgHex("#FF9900").black.bold(" NO IMAGE FOUND IN CLIPBOARD ") + "\n" + chalk9.white("No image data was found in your clipboard.\n\n") + chalk9.yellow("How to paste a screenshot:") + `
8082
8605
  1. Take a screenshot: ${chalk9.bold("Win + Shift + S")} on Windows, or ${chalk9.bold("Cmd + Shift + 4")} on macOS
8083
8606
  2. Return here and run ${chalk9.cyan.bold("/image")}
8084
8607
  3. Or mention an image file: ${chalk9.cyan.bold("@screenshot.png")} or drag-and-drop the image path into prompt.
@@ -8097,7 +8620,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8097
8620
  }
8098
8621
  if (lowerCmd === "/mode") {
8099
8622
  prepareInteractiveArea(
8100
- PROVIDER_LABELS[config.provider] || config.provider,
8623
+ formatProviderLabel(config),
8101
8624
  config.model,
8102
8625
  agent.getMode()
8103
8626
  );
@@ -8107,12 +8630,12 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8107
8630
  options: [
8108
8631
  {
8109
8632
  value: "build",
8110
- label: "\u26A1 BUILD Mode (Autonomous Full-Stack Coding)",
8633
+ label: "BUILD Mode (Autonomous Full-Stack Coding)",
8111
8634
  hint: "Full tool access: inspect, create/update files & run terminal commands"
8112
8635
  },
8113
8636
  {
8114
8637
  value: "plan",
8115
- label: "\u{1F4CB} PLAN Mode (Senior Architect & Planning)",
8638
+ label: "PLAN Mode (Senior Architect & Planning)",
8116
8639
  hint: "Read-only: inspect files, explore architecture & design step-by-step plans"
8117
8640
  }
8118
8641
  ]
@@ -8120,8 +8643,9 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8120
8643
  if (modeChoice) {
8121
8644
  agent.setMode(modeChoice);
8122
8645
  meshNode?.updateState({ mode: modeChoice });
8646
+ updateDockedModel(formatProviderLabel(config), config.model, modeChoice);
8123
8647
  console.log(chalk9.green(`
8124
- \u2714 Agent mode switched to: ${modeChoice === "build" ? "\u26A1 BUILD Mode" : "\u{1F4CB} PLAN Mode"}
8648
+ Agent mode switched to: ${modeChoice === "build" ? "BUILD Mode" : "PLAN Mode"}
8125
8649
  `));
8126
8650
  }
8127
8651
  continue;
@@ -8134,7 +8658,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8134
8658
  config.model,
8135
8659
  "plan"
8136
8660
  );
8137
- console.log(chalk9.hex("#FFB300")("\n\u{1F4CB} Active mode switched to PLAN MODE (Senior Architect & Read-Only Planning).\n"));
8661
+ console.log(chalk9.hex("#FFB300")("\nActive mode switched to PLAN MODE (Senior Architect & Read-Only Planning).\n"));
8138
8662
  continue;
8139
8663
  }
8140
8664
  if (lowerCmd === "/build" || lowerCmd === "/mode build" || lowerCmd === "build mode" || lowerCmd === "switch to build mode" || lowerCmd === "switch build") {
@@ -8145,7 +8669,7 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8145
8669
  config.model,
8146
8670
  "build"
8147
8671
  );
8148
- console.log(chalk9.hex("#00A3FF")("\n\u26A1 Active mode switched to BUILD MODE (Autonomous Full-Stack Coding & Execution Enabled).\n"));
8672
+ console.log(chalk9.hex("#00A3FF")("\nActive mode switched to BUILD MODE (Autonomous Full-Stack Coding & Execution Enabled).\n"));
8149
8673
  continue;
8150
8674
  }
8151
8675
  if (lowerCmd.includes("you are in build mode") && agent.getMode() !== "build") {
@@ -8183,50 +8707,15 @@ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK term
8183
8707
  continue;
8184
8708
  }
8185
8709
  if (lowerCmd === "/doctor" || lowerCmd === "/check") {
8186
- const checks = [];
8187
- const nodeVer = process.version;
8188
- const major = parseInt(nodeVer.replace("v", "").split(".")[0], 10);
8189
- checks.push({
8190
- name: "Node.js Runtime",
8191
- status: major >= 18 ? "ok" : "error",
8192
- detail: `${nodeVer} (Node 18+ required for modern async streams)`
8193
- });
8194
- const hasKey = isKeylessConfig(config) || Boolean(config.apiKey && config.apiKey.trim().length > 5);
8195
- checks.push({
8196
- name: "AI Provider & Key",
8197
- status: hasKey ? "ok" : "error",
8198
- detail: `${formatProviderLabel(config)} with model "${config.model}" (${isKeylessConfig(config) ? "Zero-Key Active" : hasKey ? "Configured" : "Missing API Key"})`
8199
- });
8200
- try {
8201
- const testFile = path8.resolve(process.cwd(), ".iubcli_check.tmp");
8202
- fs8.writeFileSync(testFile, "ok", "utf8");
8203
- fs8.unlinkSync(testFile);
8204
- checks.push({
8205
- name: "Workspace Read/Write",
8206
- status: "ok",
8207
- detail: `${process.cwd()} (Read/Write verified)`
8208
- });
8209
- } catch (e) {
8210
- checks.push({
8211
- name: "Workspace Read/Write",
8212
- status: "error",
8213
- detail: `Cannot write to ${process.cwd()}: ${e.message}`
8214
- });
8215
- }
8216
- checks.push({
8217
- name: "OS & Execution Shell",
8218
- status: "ok",
8219
- detail: `${process.platform} (${process.arch}) with non-interactive child process safety`
8220
- });
8221
- renderDoctorReport(checks);
8710
+ await runDoctorDiagnostics(config);
8222
8711
  continue;
8223
8712
  }
8224
8713
  if (lowerCmd === "/diff" || lowerCmd === "/changes") {
8225
8714
  const changes = getSessionChanges();
8226
8715
  if (changes.length === 0) {
8227
- console.log(chalk9.yellow("\n\u2139\uFE0F No file modifications or creations recorded in this session.\n"));
8716
+ console.log(chalk9.yellow("\n No file modifications or creations recorded in this session.\n"));
8228
8717
  } else {
8229
- console.log("\n" + chalk9.bold.hex("#00A3FF")("\u{1F4C1} Files Modified / Created in this Session:"));
8718
+ console.log("\n" + chalk9.bold.hex("#00A3FF")("Files Modified / Created in this Session:"));
8230
8719
  console.log(chalk9.dim("\u2500".repeat(60)));
8231
8720
  changes.forEach((c, idx) => {
8232
8721
  const status = c.isNew ? chalk9.green("[NEW]") : chalk9.yellow("[MODIFIED]");
@@ -8245,7 +8734,7 @@ ${result.message}
8245
8734
  `));
8246
8735
  } else {
8247
8736
  console.log(chalk9.yellow(`
8248
- \u2139\uFE0F ${result.message}
8737
+ ${result.message}
8249
8738
  `));
8250
8739
  }
8251
8740
  continue;
@@ -8254,13 +8743,26 @@ ${result.message}
8254
8743
  renderGitStatus();
8255
8744
  continue;
8256
8745
  }
8257
- if (lowerCmd === "/tree") {
8258
- 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
+ }
8259
8761
  continue;
8260
8762
  }
8261
8763
  if (lowerCmd === "/detect" || lowerCmd === "/stack") {
8262
8764
  const ctx = detectProjectContext();
8263
- console.log("\n" + chalk9.bold.hex("#00A3FF")("\u{1F50D} Detected Workspace Environment"));
8765
+ console.log("\n" + chalk9.bold.hex("#00A3FF")("Detected Workspace Environment"));
8264
8766
  console.log(chalk9.dim("\u2500".repeat(60)));
8265
8767
  console.log(ctx.summary.split("\n").slice(1).map((l) => " " + l).join("\n"));
8266
8768
  console.log(chalk9.dim("\u2500".repeat(60)) + "\n");
@@ -8271,8 +8773,8 @@ ${result.message}
8271
8773
  console.log(
8272
8774
  chalk9.green(
8273
8775
  `
8274
- \u2714 Conversation history compacted!
8275
- Turns before: ${chalk9.yellow(result.turnsBefore)} \u2794 Turns after: ${chalk9.green(result.turnsAfter)}
8776
+ Conversation history compacted!
8777
+ Turns before: ${chalk9.yellow(result.turnsBefore)} -> Turns after: ${chalk9.green(result.turnsAfter)}
8276
8778
  Context window optimized for faster responses and lower token load.
8277
8779
  `
8278
8780
  )
@@ -8282,11 +8784,11 @@ Context window optimized for faster responses and lower token load.
8282
8784
  if (lowerCmd === "/session" || lowerCmd === "/status") {
8283
8785
  const changes = getSessionChanges();
8284
8786
  const mem = agent.getHistoryStats();
8285
- console.log("\n" + chalk9.bold.hex("#00A3FF")("\u{1F4CA} Active Session Status (OpenCode Style)"));
8787
+ console.log("\n" + chalk9.bold.hex("#00A3FF")("Active Session Status (OpenCode Style)"));
8286
8788
  console.log(chalk9.dim("\u2500".repeat(60)));
8287
- console.log(` ${chalk9.gray("Provider:")} ${chalk9.bold(PROVIDER_LABELS[config.provider])}`);
8789
+ console.log(` ${chalk9.gray("Provider:")} ${chalk9.bold(formatProviderLabel(config))}`);
8288
8790
  console.log(` ${chalk9.gray("Active Model:")} ${chalk9.cyan.bold(config.model)}`);
8289
- console.log(` ${chalk9.gray("Active Mode:")} ${agent.getMode() === "build" ? chalk9.green.bold("\u26A1 BUILD") : chalk9.yellow.bold("\u{1F4CB} PLAN")}`);
8791
+ console.log(` ${chalk9.gray("Active Mode:")} ${agent.getMode() === "build" ? chalk9.green.bold("BUILD") : chalk9.yellow.bold("PLAN")}`);
8290
8792
  console.log(` ${chalk9.gray("Working Dir:")} ${chalk9.white(process.cwd())}`);
8291
8793
  console.log(` ${chalk9.gray("Files Touched:")} ${chalk9.yellow(changes.length)} files`);
8292
8794
  console.log(` ${chalk9.gray("Auto-Approve:")} ${safetySession.autoApproveAll ? chalk9.green("Enabled (-y)") : chalk9.gray("Confirm per action")}`);
@@ -8297,16 +8799,16 @@ Context window optimized for faster responses and lower token load.
8297
8799
  if (lowerCmd === "/peers" || lowerCmd === "/mesh") {
8298
8800
  const mesh = getActiveMeshNode();
8299
8801
  if (!mesh) {
8300
- console.log(chalk9.yellow("\n\u2139\uFE0F Cross-instance mesh is disabled on this instance (--no-mesh).\n"));
8802
+ console.log(chalk9.yellow("\nCross-instance mesh is disabled on this instance (--no-mesh).\n"));
8301
8803
  } else {
8302
8804
  const allPeers = mesh.listPeers();
8303
8805
  const remotePeers = allPeers.filter((p) => p.nodeId !== mesh.nodeId);
8304
- console.log("\n" + chalk9.bold.hex("#00A3FF")("\u{1F310} Cross-Instance Workspace Mesh (Multi-Agent Sync)"));
8806
+ console.log("\n" + chalk9.bold.hex("#00A3FF")("Cross-Instance Workspace Mesh (Multi-Agent Sync)"));
8305
8807
  console.log(chalk9.dim("\u2500".repeat(70)));
8306
8808
  console.log(` ${chalk9.bold("This Instance:")} [${chalk9.cyan.bold(mesh.role.toUpperCase())}] (Node: ${chalk9.gray(mesh.nodeId)})`);
8307
8809
  console.log(` ${chalk9.gray("Workspace:")} ${mesh.workspace}`);
8308
8810
  console.log(` ${chalk9.gray("Mesh Status:")} ${mesh["isHost"] ? chalk9.green("Broker Host") : chalk9.blue("Peer Client")} on 127.0.0.1:${mesh.port}`);
8309
- console.log(` ${chalk9.gray("Active Mode:")} ${mesh.mode === "build" ? chalk9.green("\u26A1 BUILD") : chalk9.yellow("\u{1F4CB} PLAN")}`);
8811
+ console.log(` ${chalk9.gray("Active Mode:")} ${mesh.mode === "build" ? chalk9.green("BUILD") : chalk9.yellow("PLAN")}`);
8310
8812
  console.log(chalk9.dim("\u2500".repeat(70)));
8311
8813
  if (remotePeers.length === 0) {
8312
8814
  console.log(chalk9.yellow(` No other IUB CLI instances connected yet.`));
@@ -8318,8 +8820,8 @@ Context window optimized for faster responses and lower token load.
8318
8820
  const roleBadge = chalk9.bold.hex("#00A3FF")(`[${p.role.toUpperCase()}]`);
8319
8821
  const modeBadge = p.mode === "build" ? chalk9.green("BUILD") : chalk9.yellow("PLAN");
8320
8822
  console.log(` ${idx + 1}. ${roleBadge} (nodeId: ${chalk9.gray(p.nodeId)})`);
8321
- console.log(` \u{1F4C1} Workspace: ${chalk9.white(p.workspace)}`);
8322
- console.log(` \u26A1 Mode: ${modeBadge} \u2022 \u{1F916} Model: ${chalk9.cyan(p.model)} (${p.provider})`);
8823
+ console.log(` Workspace: ${chalk9.white(p.workspace)}`);
8824
+ console.log(` Mode: ${modeBadge} \u2022 Model: ${chalk9.cyan(p.model)} (${p.provider})`);
8323
8825
  });
8324
8826
  console.log(chalk9.dim("\u2500".repeat(70)) + "\n");
8325
8827
  }
@@ -8330,14 +8832,14 @@ Context window optimized for faster responses and lower token load.
8330
8832
  const parts = trimmed.split(/\s+/);
8331
8833
  const mesh = getActiveMeshNode();
8332
8834
  if (!mesh) {
8333
- console.log(chalk9.yellow("\n\u2139\uFE0F Mesh is not active on this instance.\n"));
8835
+ console.log(chalk9.yellow("\nMesh is not active on this instance.\n"));
8334
8836
  continue;
8335
8837
  }
8336
8838
  if (parts.length > 1) {
8337
8839
  const newRole = parts.slice(1).join("-").trim();
8338
8840
  mesh.updateState({ role: newRole });
8339
8841
  console.log(chalk9.green(`
8340
- \u2714 Instance role updated to: [${chalk9.bold(newRole)}]
8842
+ Instance role updated to: [${chalk9.bold(newRole)}]
8341
8843
  `));
8342
8844
  } else {
8343
8845
  console.log(chalk9.cyan(`
@@ -8346,7 +8848,7 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8346
8848
  }
8347
8849
  continue;
8348
8850
  }
8349
- if (lowerCmd.startsWith("/send ") || lowerCmd.startsWith("/msg ")) {
8851
+ if (lowerCmd === "/send" || lowerCmd === "/msg" || lowerCmd.startsWith("/send ") || lowerCmd.startsWith("/msg ")) {
8350
8852
  const parts = trimmed.split(/\s+/);
8351
8853
  if (parts.length < 3) {
8352
8854
  console.log(chalk9.yellow("\nUsage: /send <role|nodeId> <message>\nExample: /send backend Please implement /api/users route.\n"));
@@ -8356,21 +8858,21 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8356
8858
  const msg = parts.slice(2).join(" ");
8357
8859
  const mesh = getActiveMeshNode();
8358
8860
  if (!mesh) {
8359
- console.log(chalk9.yellow("\n\u2139\uFE0F Mesh is not active on this instance.\n"));
8861
+ console.log(chalk9.yellow("\nMesh is not active on this instance.\n"));
8360
8862
  continue;
8361
8863
  }
8362
8864
  const result = await mesh.sendMessage(target, msg);
8363
8865
  console.log(chalk9.green(`
8364
- \u2714 ${result}
8866
+ ${result}
8365
8867
  `));
8366
8868
  continue;
8367
8869
  }
8368
8870
  if (lowerCmd === "/clear" || lowerCmd === "/cls" || lowerCmd === "/reset") {
8369
8871
  agent.resetHistory();
8370
- console.log(chalk9.green("\u2714 Conversation history cleared! Session memory reset.\n"));
8872
+ console.log(chalk9.green("Conversation history cleared! Session memory reset.\n"));
8371
8873
  continue;
8372
8874
  }
8373
- if (lowerCmd === "/provider") {
8875
+ if (lowerCmd === "/provider" || lowerCmd === "/providers") {
8374
8876
  prepareInteractiveArea(
8375
8877
  formatProviderLabel(config),
8376
8878
  config.model,
@@ -8380,8 +8882,10 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8380
8882
  if (newConfig) {
8381
8883
  config = newConfig;
8382
8884
  agent.updateConfig(newConfig);
8885
+ meshNode?.updateState({ model: config.model });
8886
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8383
8887
  console.log(chalk9.green(`
8384
- \u2714 Provider updated to: ${formatProviderLabel(config)} (${config.model})
8888
+ Provider updated to: ${formatProviderLabel(config)} (${config.model})
8385
8889
  `));
8386
8890
  }
8387
8891
  continue;
@@ -8393,11 +8897,15 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8393
8897
  agent.getMode()
8394
8898
  );
8395
8899
  const newConfig = await promptConfig(false, config);
8396
- config = newConfig;
8397
- agent.updateConfig(newConfig);
8398
- console.log(chalk9.green(`
8399
- \u2714 Configuration updated: ${formatProviderLabel(config)} (${config.model})
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(`
8906
+ Configuration updated: ${formatProviderLabel(config)} (${config.model})
8400
8907
  `));
8908
+ }
8401
8909
  continue;
8402
8910
  }
8403
8911
  const directCategoryShortcuts = {
@@ -8416,8 +8924,10 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8416
8924
  if (newConfig) {
8417
8925
  config = newConfig;
8418
8926
  agent.updateConfig(newConfig);
8927
+ meshNode?.updateState({ model: config.model });
8928
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8419
8929
  console.log(chalk9.green(`
8420
- \u2714 Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8930
+ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8421
8931
  `));
8422
8932
  }
8423
8933
  continue;
@@ -8433,11 +8943,15 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8433
8943
  if (directConfig) {
8434
8944
  config = directConfig;
8435
8945
  agent.updateConfig(directConfig);
8946
+ meshNode?.updateState({ model: config.model });
8436
8947
  updateDockedModel(
8437
8948
  formatProviderLabel(config),
8438
8949
  config.model,
8439
8950
  agent.getMode()
8440
8951
  );
8952
+ console.log(chalk9.green(`
8953
+ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8954
+ `));
8441
8955
  }
8442
8956
  continue;
8443
8957
  } else if (query.includes("/") || query.startsWith("gemini-") || query.startsWith("gemma-") || query.startsWith("gpt-")) {
@@ -8457,11 +8971,15 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8457
8971
  if (inferredConfig) {
8458
8972
  config = inferredConfig;
8459
8973
  agent.updateConfig(inferredConfig);
8974
+ meshNode?.updateState({ model: config.model });
8460
8975
  updateDockedModel(
8461
8976
  formatProviderLabel(config),
8462
8977
  config.model,
8463
8978
  agent.getMode()
8464
8979
  );
8980
+ console.log(chalk9.green(`
8981
+ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8982
+ `));
8465
8983
  }
8466
8984
  continue;
8467
8985
  }
@@ -8470,20 +8988,32 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8470
8988
  if (newConfig) {
8471
8989
  config = newConfig;
8472
8990
  agent.updateConfig(newConfig);
8991
+ meshNode?.updateState({ model: config.model });
8992
+ updateDockedModel(formatProviderLabel(config), config.model, agent.getMode());
8473
8993
  console.log(chalk9.green(`
8474
- \u2714 Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8994
+ Active model updated to: ${config.model} [${config.provider.toUpperCase()}]
8475
8995
  `));
8476
8996
  }
8477
8997
  continue;
8478
8998
  }
8479
8999
  let isPriorityTask = false;
8480
9000
  let taskPrompt = trimmed;
8481
- 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 ")) {
8482
9006
  isPriorityTask = true;
8483
9007
  taskPrompt = trimmed.replace(/^\/(task|urgent|priority)\s+/i, "").trim();
8484
9008
  } else if (/^(urgent|priority|task):\s*/i.test(trimmed)) {
8485
9009
  isPriorityTask = true;
8486
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;
8487
9017
  }
8488
9018
  if (isPriorityTask) {
8489
9019
  renderPriorityTaskBanner(taskPrompt, config.model, agent.getMode());
@@ -8498,7 +9028,7 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8498
9028
  hasAborted = true;
8499
9029
  abortController.abort();
8500
9030
  renderInterruptedNotice();
8501
- updateFixedBottomStatus("\u23F9\uFE0F Stopped by Escape key", {
9031
+ updateFixedBottomStatus("Stopped by Escape key", {
8502
9032
  mode: agent.getMode(),
8503
9033
  model: config?.model || "unknown"
8504
9034
  });
@@ -8517,7 +9047,7 @@ Current instance role: [${chalk9.bold(mesh.role)}] (Usage: /role <frontend|backe
8517
9047
  if (abortController.signal.aborted || hasAborted) {
8518
9048
  } else {
8519
9049
  console.error(chalk9.red(`
8520
- \u2716 Agent Error: ${err.message}
9050
+ Agent Error: ${err.message}
8521
9051
  `));
8522
9052
  }
8523
9053
  } finally {
@@ -8540,12 +9070,13 @@ program.command("agent").alias("model").description("OpenCode-style AI agent & m
8540
9070
  if (!config) {
8541
9071
  config = await promptConfig(true);
8542
9072
  }
9073
+ if (!config) return;
8543
9074
  await selectAgentModelInteractive(config, "build");
8544
9075
  });
8545
9076
  program.command("mode").description("Switch agent mode between BUILD (autonomous coder) and PLAN (architect)").action(async () => {
8546
- console.log(chalk9.bold.hex("#00A3FF")("\n\u{1F393} IUB CLI Agent Modes (OpenCode Style):\n"));
8547
- console.log(` ${chalk9.green.bold("\u26A1 BUILD Mode:")} Autonomous full-stack coder. Inspects, writes files & runs terminal commands.`);
8548
- console.log(` ${chalk9.yellow.bold("\u{1F4CB} PLAN Mode:")} Senior Architect. Read-only codebase investigation & architectural planning.
9077
+ console.log(chalk9.bold.hex("#00A3FF")("\nIUB CLI Agent Modes (OpenCode Style):\n"));
9078
+ console.log(` ${chalk9.green.bold("BUILD Mode:")} Autonomous full-stack coder. Inspects, writes files & runs terminal commands.`);
9079
+ console.log(` ${chalk9.yellow.bold("PLAN Mode:")} Senior Architect. Read-only codebase investigation & architectural planning.
8549
9080
  `);
8550
9081
  console.log(chalk9.gray('Use "/mode", "/plan", or "/build" inside interactive chat or launch with "iubcli -M plan".\n'));
8551
9082
  });
@@ -8555,51 +9086,16 @@ program.command("about").alias("developer").alias("author").description("Display
8555
9086
  program.command("renewal").alias("countdown").alias("renew").description("Display live token quota renewal countdown and provider reset schedules").action(() => {
8556
9087
  renderAllTokensExhaustedReport();
8557
9088
  });
8558
- program.command("doctor").alias("check").description("Run automated diagnostic check of Node.js runtime, workspace, shell, and provider").action(() => {
8559
- 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() || {
8560
9091
  provider: "gemini",
8561
9092
  apiKey: "",
8562
9093
  model: "gemini-3.5-flash-lite"
8563
9094
  };
8564
- const checks = [];
8565
- const nodeVer = process.version;
8566
- const major = parseInt(nodeVer.replace("v", "").split(".")[0], 10);
8567
- checks.push({
8568
- name: "Node.js Runtime",
8569
- status: major >= 18 ? "ok" : "error",
8570
- detail: `${nodeVer} (Node 18+ required for modern async streams)`
8571
- });
8572
- const hasKey = isKeylessConfig(config) || Boolean(config.apiKey && config.apiKey.trim().length > 5);
8573
- checks.push({
8574
- name: "AI Provider & Key",
8575
- status: hasKey ? "ok" : "error",
8576
- detail: `${formatProviderLabel(config)} with model "${config.model}" (${isKeylessConfig(config) ? "Zero-Key Active" : hasKey ? "Configured" : "Missing API Key"})`
8577
- });
8578
- try {
8579
- const testFile = path8.resolve(process.cwd(), ".iubcli_check.tmp");
8580
- fs8.writeFileSync(testFile, "ok", "utf8");
8581
- fs8.unlinkSync(testFile);
8582
- checks.push({
8583
- name: "Workspace Read/Write",
8584
- status: "ok",
8585
- detail: `${process.cwd()} (Read/Write verified)`
8586
- });
8587
- } catch (e) {
8588
- checks.push({
8589
- name: "Workspace Read/Write",
8590
- status: "error",
8591
- detail: `Cannot write to ${process.cwd()}: ${e.message}`
8592
- });
8593
- }
8594
- checks.push({
8595
- name: "OS & Execution Shell",
8596
- status: "ok",
8597
- detail: `${process.platform} (${process.arch}) with non-interactive child process safety`
8598
- });
8599
- renderDoctorReport(checks);
9095
+ await runDoctorDiagnostics(config);
8600
9096
  });
8601
9097
  program.command("stats").alias("cost").description("Display token limits, pricing, and live cost calculation").action(() => {
8602
- let config = getConfig() || {
9098
+ const config = getConfig() || {
8603
9099
  provider: "gemini",
8604
9100
  apiKey: "",
8605
9101
  model: "gemini-3.5-flash-lite"
@@ -8620,7 +9116,7 @@ program.command("peers").alias("mesh").description("Discover and display connect
8620
9116
  const node = new MeshNode({ role: "cli-scanner", workspace: process.cwd() });
8621
9117
  await node.start();
8622
9118
  const peers = node.listPeers().filter((p) => p.nodeId !== node.nodeId);
8623
- console.log("\n" + chalk9.bold.hex("#00A3FF")("\u{1F310} Cross-Instance Workspace Mesh Status:"));
9119
+ console.log("\n" + chalk9.bold.hex("#00A3FF")("Cross-Instance Workspace Mesh Status:"));
8624
9120
  console.log(chalk9.dim("\u2500".repeat(70)));
8625
9121
  if (peers.length === 0) {
8626
9122
  console.log(chalk9.yellow(" No other active IUB CLI instances detected on 127.0.0.1:49152."));
@@ -8629,12 +9125,13 @@ program.command("peers").alias("mesh").description("Discover and display connect
8629
9125
  console.log(chalk9.bold(` Active Peers (${peers.length}):`));
8630
9126
  peers.forEach((p, idx) => {
8631
9127
  console.log(` ${idx + 1}. [${chalk9.cyan.bold(p.role.toUpperCase())}] (${chalk9.gray(p.nodeId)})`);
8632
- console.log(` \u{1F4C1} Workspace: ${chalk9.white(p.workspace)}`);
8633
- console.log(` \u26A1 Mode: ${p.mode.toUpperCase()} \u2022 \u{1F916} Model: ${p.model} (${p.provider})`);
9128
+ console.log(` Workspace: ${chalk9.white(p.workspace)}`);
9129
+ console.log(` Mode: ${p.mode.toUpperCase()} \u2022 Model: ${p.model} (${p.provider})`);
8634
9130
  });
8635
9131
  console.log(chalk9.dim("\u2500".repeat(70)) + "\n");
8636
9132
  }
8637
9133
  node.stop();
9134
+ gracefulExit(0);
8638
9135
  });
8639
9136
  program.parse(process.argv);
8640
9137
  //# sourceMappingURL=index.js.map