iubcli 4.2.12 → 4.2.14

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # IUB CLI
2
2
 
3
- > Autonomous BYOK terminal coding agent for Bangla, Banglish, and English, with BUILD and PLAN modes, local-first configuration, and resilient free-model failover.
3
+ > Autonomous BYOK terminal coding agent for English workflows, with BUILD and PLAN modes, local-first configuration, and resilient free-model failover.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/iubcli.svg?style=flat-square&color=00A3FF)](https://www.npmjs.com/package/iubcli)
6
6
  [![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg?style=flat-square)](https://nodejs.org/)
@@ -20,7 +20,7 @@
20
20
 
21
21
  ## Overview
22
22
 
23
- **IUB CLI** (`iubcli`) is an open-source, serverless terminal coding assistant for developers who think, speak, and code in **Bangla**, **Banglish**, or **English**.
23
+ **IUB CLI** (`iubcli`) is an open-source, serverless terminal coding assistant designed for developers
24
24
 
25
25
  It combines a local terminal UI with provider-backed model calls, giving you an agent that can inspect a workspace, plan changes, edit files, run commands, fetch documentation, and coordinate with other local CLI instances.
26
26
 
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ function printBanner(provider, model, workspace) {
69
69
  )}`
70
70
  );
71
71
  console.log(
72
- ` ${dim("Speaks natural")} ${chalk.bold.white("English")}${dim(",")} ${chalk.bold.cyan("Banglish")}${dim(", & understands ")} ${chalk.bold.hex("#FFC72C")("Bangla")}`
72
+ ` ${dim("Language:")} ${chalk.bold.white("English")}`
73
73
  );
74
74
  console.log(
75
75
  ` ${dim("Developer:")} ${chalk.bold.hex("#00A3FF")("Ifaz MD Zahin")}
@@ -301,10 +301,10 @@ ${chalk.yellow.bold("Autonomous Tool Capabilities (12 Built-in Tools):")}`);
301
301
  console.log(` 11. ${chalk.bold("peer_call_tool")} - Triggers tools on peer instances across workspaces safely`);
302
302
  console.log(` 12. ${chalk.bold("peer_send_message")} - Sends structured messages/contracts to peer instances`);
303
303
  console.log(`
304
- ${chalk.yellow.bold("Language Support (Outputs strictly in English):")}`);
305
- console.log(` \u2022 ${chalk.green("English:")} "Build a full-stack Next.js portfolio website"`);
306
- console.log(` \u2022 ${chalk.green("Banglish:")} "Express diye ekta REST API banaw auth soho"`);
307
- console.log(` \u2022 ${chalk.green("Bangla:")} "Ekta React counter component baniye daw" (Input accepted, instructions in English)`);
304
+ ${chalk.yellow.bold("Example Prompts (English):")}`);
305
+ console.log(` \u2022 ${chalk.green("Build:")} "Build a full-stack Next.js portfolio website"`);
306
+ console.log(` \u2022 ${chalk.green("API:")} "Create an Express REST API with JWT authentication"`);
307
+ console.log(` \u2022 ${chalk.green("UI:")} "Create a responsive React counter component"`);
308
308
  console.log(`
309
309
  ${chalk.gray("Lead Developer & Creator:")} ${chalk.hex("#00A3FF").bold("Ifaz MD Zahin")} ${chalk.dim("(https://github.com/Ifaz2611)")}`);
310
310
  console.log(chalk.dim("\u2500".repeat(70)) + "\n");
@@ -2232,7 +2232,10 @@ function renderStatusLine(width, statusText, borderColor) {
2232
2232
  }
2233
2233
  function restoreTerminalViewport() {
2234
2234
  try {
2235
- process.stdout.write("\x1B[r\x1B[?2004l\x1B[?25h");
2235
+ const interactiveStateActive = process.stdin.isRaw || _dockedActive || _dockedPromptActive || _interactiveSelectActive;
2236
+ if (process.stdout.isTTY && interactiveStateActive) {
2237
+ process.stdout.write("\x1B[r\x1B[?2004l\x1B[?25h");
2238
+ }
2236
2239
  if (process.stdin.isTTY && process.stdin.isRaw) {
2237
2240
  process.stdin.setRawMode(false);
2238
2241
  }
@@ -3105,8 +3108,8 @@ async function readInlinePrompt(options) {
3105
3108
  idx += 1;
3106
3109
  continue;
3107
3110
  }
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;
3111
+ if (rest.startsWith("\x1B\r") || rest.startsWith("\x1B[13;2u") || rest.startsWith("\x1B[13;5u")) {
3112
+ const seqLen = rest.startsWith("\x1B\r") ? 2 : 7;
3110
3113
  const cur2 = bufferLines[cursorLine];
3111
3114
  const prevLine = cursorLine;
3112
3115
  bufferLines[cursorLine] = cur2.slice(0, cursorCol);
@@ -3117,12 +3120,12 @@ async function readInlinePrompt(options) {
3117
3120
  idx += seqLen;
3118
3121
  continue;
3119
3122
  }
3120
- if (rest.startsWith("\r\n")) {
3123
+ if (rest.startsWith("\r\n") || rest.startsWith("\n")) {
3121
3124
  if (bufferLines.join("\n").trim().length > 0) {
3122
3125
  submit();
3123
3126
  return;
3124
3127
  }
3125
- idx += 2;
3128
+ idx += rest.startsWith("\r\n") ? 2 : 1;
3126
3129
  continue;
3127
3130
  }
3128
3131
  if (rest.startsWith("\r") || rest.startsWith("\x1BOM") || rest.startsWith("\x1B[13~")) {
@@ -6143,11 +6146,8 @@ Example: To inspect backend endpoints from frontend, call peer_call_tool("backen
6143
6146
  if (mode === "plan") {
6144
6147
  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.
6145
6148
 
6146
- ### CRITICAL DIRECTIVE 1: STRICTLY 100% ENGLISH OUTPUT ONLY (MANDATORY)
6147
- - YOU MUST COMMUNICATE AND RESPOND EXCLUSIVELY IN ENGLISH.
6148
- - UNDER NO CIRCUMSTANCES SHOULD YOU OUTPUT BENGALI SCRIPT (\u09AC\u09BE\u0982\u09B2\u09BE).
6149
- - Monospace terminal consoles and Windows fonts cannot render complex Bengali ligatures and conjuncts properly, resulting in broken, overlapping characters.
6150
- - Even if the user submits prompts or questions in Bangla or Banglish, your responses, explanations, step-by-step plans, code comments, and terminal messages MUST ALWAYS BE IN 100% CLEAN, PROFESSIONAL ENGLISH.
6149
+ ### LANGUAGE & COMMUNICATION:
6150
+ - Communicate and respond exclusively in clear, professional English.
6151
6151
 
6152
6152
  ${envContext.summary}
6153
6153
  ${meshContext}
@@ -6171,20 +6171,12 @@ ${meshContext}
6171
6171
  3. Dependencies, Libraries & Versions needed.
6172
6172
  4. Core Components, Modules, Data Models & API Contracts.
6173
6173
  5. Step-by-Step Implementation Roadmap (ordered sequence of files to create/edit).
6174
- 6. Verification & Testing Strategy.
6175
-
6176
- ### 1. LANGUAGE & COMMUNICATION RULES (CRITICAL):
6177
- - ALWAYS write all responses, architectural plans, explanations, code, and terminal guidance in clear, professional ENGLISH.
6178
- - DO NOT output Bengali script under any circumstances, because terminal emulators and console fonts do not render Bengali script properly.
6179
- - You can understand user inputs in English, Banglish (Romanized Bengali), and Bangla, but your replies and instructions MUST ALWAYS be written in clean, fluent ENGLISH.`;
6174
+ 6. Verification & Testing Strategy.`;
6180
6175
  }
6181
6176
  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.
6182
6177
 
6183
- ### CRITICAL DIRECTIVE 1: STRICTLY 100% ENGLISH OUTPUT ONLY (MANDATORY)
6184
- - YOU MUST COMMUNICATE AND RESPOND EXCLUSIVELY IN ENGLISH.
6185
- - UNDER NO CIRCUMSTANCES SHOULD YOU OUTPUT BENGALI SCRIPT (\u09AC\u09BE\u0982\u09B2\u09BE).
6186
- - Monospace terminal consoles and Windows fonts cannot render complex Bengali ligatures and conjuncts properly, resulting in broken, overlapping characters.
6187
- - Even if the user submits prompts or questions in Bangla or Banglish, your responses, explanations, step-by-step plans, code comments, and terminal messages MUST ALWAYS BE IN 100% CLEAN, PROFESSIONAL ENGLISH.
6178
+ ### LANGUAGE & COMMUNICATION:
6179
+ - Communicate and respond exclusively in clear, professional English.
6188
6180
 
6189
6181
  ${envContext.summary}
6190
6182
  ${meshContext}
@@ -6254,12 +6246,7 @@ ${meshContext}
6254
6246
  - NEVER apply two or more commands at the same time or batch multiple run_command calls together.
6255
6247
  - NEVER chain lengthy commands with "&&" or ";".
6256
6248
  - Execute ONE command, wait for its output, inspect the result, and ONLY THEN proceed to the next step.
6257
- - This ensures rapid real-time feedback, prevents lengthy hangs, and keeps execution continuous, smooth, and fast.
6258
-
6259
- ### 1. LANGUAGE & COMMUNICATION RULES (CRITICAL):
6260
- - ALWAYS write all responses, architectural plans, explanations, code, and terminal guidance in clear, professional ENGLISH.
6261
- - DO NOT output Bengali script under any circumstances, because terminal emulators and console fonts do not render Bengali script properly.
6262
- - You can understand user inputs in English, Banglish (Romanized Bengali), and Bangla, but your replies and instructions MUST ALWAYS be written in clean, fluent ENGLISH.`;
6249
+ - This ensures rapid real-time feedback, prevents lengthy hangs, and keeps execution continuous, smooth, and fast.`;
6263
6250
  }
6264
6251
  var SYSTEM_PROMPT = getSystemPrompt("build");
6265
6252
  var GEMINI_FALLBACK_MAP = {
@@ -6427,10 +6414,24 @@ var IUBAgent = class {
6427
6414
  if (hasSavedConfig() || this.config.apiKey !== POLLINATIONS_FREE_API_KEY) {
6428
6415
  saveConfig(this.config);
6429
6416
  }
6430
- this.onModelChangeCallback?.(this.config.model, this.config.provider);
6417
+ this.onModelChangeCallback?.(this.config.model, this.config.provider, this.config);
6431
6418
  } catch {
6432
6419
  }
6433
6420
  }
6421
+ /**
6422
+ * Sync conversation history only when switching between Gemini and OpenAI-compatible
6423
+ * formats. Gemini -> Gemini failover must never rebuild geminiContents from the
6424
+ * (usually empty) OpenAI mirror, and OpenAI -> OpenAI switches must not overwrite
6425
+ * live messages with a stale Gemini transcript.
6426
+ */
6427
+ syncHistoryForProviderChange(prevProvider, nextProvider) {
6428
+ if (prevProvider === nextProvider) return;
6429
+ if (prevProvider !== "gemini" && nextProvider === "gemini") {
6430
+ this.syncMessagesToGemini();
6431
+ } else if (prevProvider === "gemini" && nextProvider !== "gemini") {
6432
+ this.syncMessagesToOpenAI();
6433
+ }
6434
+ }
6434
6435
  /**
6435
6436
  * Sync active OpenAI message history into Gemini content format (preserving tool calls/results).
6436
6437
  */
@@ -6595,13 +6596,14 @@ ${String(out).slice(0, 6e3)}`);
6595
6596
  for (const rawModel of GEMINI_CASCADE_CHAIN) {
6596
6597
  const model = normalizeGeminiModel(rawModel);
6597
6598
  if (!this.attemptedModelsInCascade.has(model)) {
6599
+ const prevProvider = this.config.provider;
6598
6600
  renderCascadeNotice(currentModel, model, noticeReason);
6599
6601
  this.config.provider = "gemini";
6600
6602
  this.config.apiKey = geminiKey;
6601
6603
  this.config.model = model;
6602
6604
  delete this.config.baseURL;
6603
6605
  this.initClients();
6604
- this.syncMessagesToGemini();
6606
+ this.syncHistoryForProviderChange(prevProvider, "gemini");
6605
6607
  return model;
6606
6608
  }
6607
6609
  }
@@ -6613,13 +6615,14 @@ ${String(out).slice(0, 6e3)}`);
6613
6615
  if (!openRouterKey) return null;
6614
6616
  for (const model of OPENROUTER_FREE_CASCADE_CHAIN) {
6615
6617
  if (!this.attemptedModelsInCascade.has(model)) {
6618
+ const prevProvider = this.config.provider;
6616
6619
  renderCascadeNotice(currentModel, model, noticeReason);
6617
6620
  this.config.provider = "openrouter";
6618
6621
  this.config.apiKey = openRouterKey;
6619
6622
  this.config.model = model;
6620
6623
  this.config.baseURL = "https://openrouter.ai/api/v1";
6621
6624
  this.initClients();
6622
- this.syncMessagesToOpenAI();
6625
+ this.syncHistoryForProviderChange(prevProvider, "openrouter");
6623
6626
  return model;
6624
6627
  }
6625
6628
  }
@@ -6646,6 +6649,7 @@ ${String(out).slice(0, 6e3)}`);
6646
6649
  for (const targetModel of candidateModels) {
6647
6650
  const dedupeKey = `custom:${targetModel}`;
6648
6651
  if (!this.attemptedModelsInCascade.has(dedupeKey) && !this.attemptedModelsInCascade.has(targetModel)) {
6652
+ const prevProvider = this.config.provider;
6649
6653
  this.attemptedModelsInCascade.add(dedupeKey);
6650
6654
  this.attemptedModelsInCascade.add(targetModel);
6651
6655
  renderCascadeNotice(currentModel, targetModel, noticeReason);
@@ -6654,7 +6658,7 @@ ${String(out).slice(0, 6e3)}`);
6654
6658
  this.config.baseURL = customBaseURL;
6655
6659
  this.config.model = targetModel;
6656
6660
  this.initClients();
6657
- this.syncMessagesToOpenAI();
6661
+ this.syncHistoryForProviderChange(prevProvider, "custom");
6658
6662
  return targetModel;
6659
6663
  }
6660
6664
  }
@@ -6689,16 +6693,13 @@ ${String(out).slice(0, 6e3)}`);
6689
6693
  const nextOR = switchToOpenRouter("Custom provider rate-limited/exhausted; cascading to OpenRouter Free");
6690
6694
  if (nextOR) return nextOR;
6691
6695
  }
6696
+ const prevProviderBeforeExplore = this.config.provider;
6692
6697
  const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade, false, false);
6693
6698
  if (explored) {
6694
6699
  this.attemptedModelsInCascade.add(explored.id);
6695
6700
  this.initClients();
6696
- if (explored.provider === "gemini") {
6697
- this.syncMessagesToGemini();
6698
- } else {
6699
- this.syncMessagesToOpenAI();
6700
- }
6701
- this.onModelChangeCallback?.(explored.id, explored.provider);
6701
+ this.syncHistoryForProviderChange(prevProviderBeforeExplore, this.config.provider);
6702
+ this.onModelChangeCallback?.(explored.id, explored.provider, this.config);
6702
6703
  return explored.id;
6703
6704
  }
6704
6705
  if (this.neverStopAttempts < 10) {
@@ -6714,27 +6715,25 @@ ${String(out).slice(0, 6e3)}`);
6714
6715
  if (signal?.aborted) return null;
6715
6716
  this.attemptedModelsInCascade.clear();
6716
6717
  this.deadProvidersInTurn.clear();
6718
+ const prevProviderBeforeRecovery = this.config.provider;
6717
6719
  const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true, false);
6718
6720
  if (recovered) {
6719
6721
  this.initClients();
6720
- if (recovered.provider === "gemini") {
6721
- this.syncMessagesToGemini();
6722
- } else {
6723
- this.syncMessagesToOpenAI();
6724
- }
6725
- this.onModelChangeCallback?.(recovered.id, recovered.provider);
6722
+ this.syncHistoryForProviderChange(prevProviderBeforeRecovery, this.config.provider);
6723
+ this.onModelChangeCallback?.(recovered.id, recovered.provider, this.config);
6726
6724
  return recovered.id;
6727
6725
  }
6728
6726
  }
6729
6727
  if (this.config.baseURL !== POLLINATIONS_BASE_URL || this.config.model !== POLLINATIONS_DEFAULT_MODEL) {
6728
+ const prevProviderBeforeFallback = this.config.provider;
6730
6729
  renderCascadeNotice(currentModel, POLLINATIONS_DEFAULT_MODEL, "Switching to Zero-Key Built-in Free AI");
6731
6730
  this.config.provider = "custom";
6732
6731
  this.config.apiKey = POLLINATIONS_FREE_API_KEY;
6733
6732
  this.config.baseURL = POLLINATIONS_BASE_URL;
6734
6733
  this.config.model = POLLINATIONS_DEFAULT_MODEL;
6735
6734
  this.initClients();
6736
- this.syncMessagesToOpenAI();
6737
- this.onModelChangeCallback?.(this.config.model, this.config.provider);
6735
+ this.syncHistoryForProviderChange(prevProviderBeforeFallback, "custom");
6736
+ this.onModelChangeCallback?.(this.config.model, this.config.provider, this.config);
6738
6737
  return this.config.model;
6739
6738
  }
6740
6739
  renderAllTokensExhaustedReport();
@@ -6744,15 +6743,12 @@ ${String(out).slice(0, 6e3)}`);
6744
6743
  * Run model explorer to find and select an active model with free tokens.
6745
6744
  */
6746
6745
  async exploreFreeModel() {
6746
+ const prevProvider = this.config.provider;
6747
6747
  const explored = await exploreAndSelectFreeModel(this.config);
6748
6748
  if (explored) {
6749
6749
  this.initClients();
6750
- if (explored.provider === "gemini") {
6751
- this.syncMessagesToGemini();
6752
- } else {
6753
- this.syncMessagesToOpenAI();
6754
- }
6755
- this.onModelChangeCallback?.(explored.id, explored.provider);
6750
+ this.syncHistoryForProviderChange(prevProvider, this.config.provider);
6751
+ this.onModelChangeCallback?.(explored.id, explored.provider, this.config);
6756
6752
  return explored.id;
6757
6753
  }
6758
6754
  return null;
@@ -6865,19 +6861,59 @@ ${String(out).slice(0, 6e3)}`);
6865
6861
  * Ensure message history has no dangling tool_calls or unresponded user turns before starting a new turn.
6866
6862
  */
6867
6863
  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({
6864
+ let lastAssistantIdx = -1;
6865
+ for (let i = this.openAIMessages.length - 1; i >= 0; i--) {
6866
+ const msg = this.openAIMessages[i];
6867
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
6868
+ lastAssistantIdx = i;
6869
+ break;
6870
+ }
6871
+ }
6872
+ if (lastAssistantIdx !== -1) {
6873
+ const assistant = this.openAIMessages[lastAssistantIdx];
6874
+ const expectedIds = assistant.tool_calls.map((tc) => tc?.id).filter((id) => typeof id === "string" && id.length > 0);
6875
+ const responded = /* @__PURE__ */ new Set();
6876
+ let insertAt = lastAssistantIdx + 1;
6877
+ for (let i = lastAssistantIdx + 1; i < this.openAIMessages.length; i++) {
6878
+ const msg = this.openAIMessages[i];
6879
+ if (msg.role !== "tool") break;
6880
+ if (msg.tool_call_id) responded.add(msg.tool_call_id);
6881
+ insertAt = i + 1;
6882
+ }
6883
+ const missing = expectedIds.filter((id) => !responded.has(id));
6884
+ if (missing.length > 0) {
6885
+ this.openAIMessages.splice(
6886
+ insertAt,
6887
+ 0,
6888
+ ...missing.map((id) => ({
6873
6889
  role: "tool",
6874
- tool_call_id: tc.id,
6890
+ tool_call_id: id,
6875
6891
  content: "Action cancelled before completion."
6876
- });
6877
- }
6892
+ }))
6893
+ );
6878
6894
  }
6879
6895
  }
6880
6896
  const lastGemini = this.geminiContents[this.geminiContents.length - 1];
6897
+ if (lastGemini && lastGemini.role === "model") {
6898
+ const pendingCalls = (lastGemini.parts || []).filter((p) => p?.functionCall);
6899
+ if (pendingCalls.length > 0) {
6900
+ this.geminiContents.push({
6901
+ role: "user",
6902
+ parts: pendingCalls.map((p) => ({
6903
+ functionResponse: {
6904
+ name: p.functionCall.name,
6905
+ id: p.functionCall.id,
6906
+ response: { output: "Action cancelled before completion." }
6907
+ }
6908
+ }))
6909
+ });
6910
+ this.geminiContents.push({
6911
+ role: "model",
6912
+ parts: [{ text: "[Tool execution was interrupted by the user.]" }]
6913
+ });
6914
+ return;
6915
+ }
6916
+ }
6881
6917
  if (lastGemini && lastGemini.role === "user") {
6882
6918
  this.geminiContents.push({
6883
6919
  role: "model",
@@ -6897,15 +6933,14 @@ ${String(out).slice(0, 6e3)}`);
6897
6933
  this.sanitizeDanglingHistory();
6898
6934
  }
6899
6935
  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.]`;
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.]
6901
- ${modeDirective}
6936
+ const enrichedInput = `${modeDirective}
6902
6937
 
6903
6938
  ${userInput}`;
6904
6939
  try {
6905
6940
  if (this.config.provider === "gemini") {
6906
- return await this.chatGemini(englishEnforcedInput, options);
6941
+ return await this.chatGemini(enrichedInput, options);
6907
6942
  } else {
6908
- return await this.chatOpenAI(englishEnforcedInput, options);
6943
+ return await this.chatOpenAI(enrichedInput, options);
6909
6944
  }
6910
6945
  } catch (err) {
6911
6946
  if (options?.signal?.aborted) {
@@ -6919,9 +6954,9 @@ ${userInput}`;
6919
6954
  if (nextModel) {
6920
6955
  const retryOpts = { ...options, isCascadeRetry: true };
6921
6956
  if (this.config.provider === "gemini") {
6922
- return await this.chatGemini(englishEnforcedInput, retryOpts);
6957
+ return await this.chatGemini(enrichedInput, retryOpts);
6923
6958
  } else {
6924
- return await this.chatOpenAI(englishEnforcedInput, retryOpts);
6959
+ return await this.chatOpenAI(enrichedInput, retryOpts);
6925
6960
  }
6926
6961
  }
6927
6962
  return chalk8.yellow("\nAll free model tokens are currently exhausted across all providers. Check the renewal countdown above.");
@@ -7161,8 +7196,23 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7161
7196
  return directText || "";
7162
7197
  }
7163
7198
  const toolResponseParts = [];
7164
- for (const call of functionCalls) {
7199
+ const pushCancelledFunctionResponses = (fromIndex) => {
7200
+ for (let j = fromIndex; j < functionCalls.length; j++) {
7201
+ const pending = functionCalls[j];
7202
+ toolResponseParts.push({
7203
+ functionResponse: {
7204
+ name: pending.name,
7205
+ id: pending.id,
7206
+ response: { output: "Action cancelled by user (Escape)." }
7207
+ }
7208
+ });
7209
+ }
7210
+ };
7211
+ for (let callIndex = 0; callIndex < functionCalls.length; callIndex++) {
7212
+ const call = functionCalls[callIndex];
7165
7213
  if (options?.signal?.aborted) {
7214
+ pushCancelledFunctionResponses(callIndex);
7215
+ this.geminiContents.push({ role: "user", parts: toolResponseParts });
7166
7216
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7167
7217
  }
7168
7218
  const toolName = call.name;
@@ -7173,9 +7223,6 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7173
7223
  });
7174
7224
  toolsExecutedInChat++;
7175
7225
  const output = await executeTool(toolName, toolArgs, this.mode, options?.signal);
7176
- if (options?.signal?.aborted) {
7177
- return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7178
- }
7179
7226
  toolResponseParts.push({
7180
7227
  functionResponse: {
7181
7228
  name: toolName,
@@ -7183,6 +7230,11 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7183
7230
  response: { output }
7184
7231
  }
7185
7232
  });
7233
+ if (options?.signal?.aborted) {
7234
+ pushCancelledFunctionResponses(callIndex + 1);
7235
+ this.geminiContents.push({ role: "user", parts: toolResponseParts });
7236
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7237
+ }
7186
7238
  }
7187
7239
  this.geminiContents.push({
7188
7240
  role: "user",
@@ -7436,8 +7488,23 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7436
7488
  }
7437
7489
  return finalCandidate;
7438
7490
  }
7439
- for (const toolCall of message.tool_calls) {
7491
+ const toolCalls = message.tool_calls;
7492
+ const pushCancelledToolResponses = (fromIndex) => {
7493
+ for (let j = fromIndex; j < toolCalls.length; j++) {
7494
+ const pending = toolCalls[j];
7495
+ if (pending?.id) {
7496
+ this.openAIMessages.push({
7497
+ role: "tool",
7498
+ tool_call_id: pending.id,
7499
+ content: "Action cancelled by user (Escape)."
7500
+ });
7501
+ }
7502
+ }
7503
+ };
7504
+ for (let callIndex = 0; callIndex < toolCalls.length; callIndex++) {
7505
+ const toolCall = toolCalls[callIndex];
7440
7506
  if (options?.signal?.aborted) {
7507
+ pushCancelledToolResponses(callIndex);
7441
7508
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7442
7509
  }
7443
7510
  const fnObj = toolCall.function;
@@ -7473,14 +7540,15 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7473
7540
  });
7474
7541
  toolsExecutedInChat++;
7475
7542
  const toolResult = await executeTool(fnName, fnArgs, this.mode, options?.signal);
7476
- if (options?.signal?.aborted) {
7477
- return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7478
- }
7479
7543
  this.openAIMessages.push({
7480
7544
  role: "tool",
7481
7545
  tool_call_id: toolCall.id,
7482
7546
  content: toolResult
7483
7547
  });
7548
+ if (options?.signal?.aborted) {
7549
+ pushCancelledToolResponses(callIndex + 1);
7550
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7551
+ }
7484
7552
  }
7485
7553
  }
7486
7554
  return "Maximum agent iteration steps reached for this request.";
@@ -8321,7 +8389,7 @@ function attachEscapeListener(onEscape) {
8321
8389
  };
8322
8390
  }
8323
8391
  var program = new Command();
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) => {
8392
+ program.name("iubcli").description("IUB CLI \u2014 Next-Gen Autonomous BYOK terminal coding agent.").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
8393
  const rawMode = String(options.mode || "build").toLowerCase().trim();
8326
8394
  if (rawMode !== "build" && rawMode !== "plan") {
8327
8395
  console.error(chalk9.red(`
@@ -8442,12 +8510,10 @@ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 655
8442
8510
  await meshNode.start();
8443
8511
  setActiveMeshNode(meshNode);
8444
8512
  }
8445
- agent.setOnModelChange((newModel, newProvider) => {
8446
- const freshConfig = getConfig();
8447
- if (freshConfig) {
8448
- config = freshConfig;
8449
- }
8450
- if (config) {
8513
+ agent.setOnModelChange((newModel, newProvider, activeConfig) => {
8514
+ if (activeConfig) {
8515
+ config = activeConfig;
8516
+ } else if (config) {
8451
8517
  config.model = newModel;
8452
8518
  if (newProvider) {
8453
8519
  config.provider = newProvider;
@@ -8456,14 +8522,9 @@ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 655
8456
8522
  } else if (config.provider === "openrouter") {
8457
8523
  config.baseURL = "https://openrouter.ai/api/v1";
8458
8524
  }
8459
- const saved = config.savedProviders?.[config.provider];
8460
- if (saved && saved.apiKey) {
8461
- config.apiKey = saved.apiKey;
8462
- if (config.provider !== "gemini") {
8463
- config.baseURL = saved.baseURL || config.baseURL;
8464
- }
8465
- }
8466
8525
  }
8526
+ }
8527
+ if (config) {
8467
8528
  if (hasSavedConfig() || config.apiKey !== POLLINATIONS_FREE_API_KEY) {
8468
8529
  saveConfig(config);
8469
8530
  }