iubcli 4.2.13 → 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/dist/index.js CHANGED
@@ -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~")) {
@@ -6411,10 +6414,24 @@ var IUBAgent = class {
6411
6414
  if (hasSavedConfig() || this.config.apiKey !== POLLINATIONS_FREE_API_KEY) {
6412
6415
  saveConfig(this.config);
6413
6416
  }
6414
- this.onModelChangeCallback?.(this.config.model, this.config.provider);
6417
+ this.onModelChangeCallback?.(this.config.model, this.config.provider, this.config);
6415
6418
  } catch {
6416
6419
  }
6417
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
+ }
6418
6435
  /**
6419
6436
  * Sync active OpenAI message history into Gemini content format (preserving tool calls/results).
6420
6437
  */
@@ -6579,13 +6596,14 @@ ${String(out).slice(0, 6e3)}`);
6579
6596
  for (const rawModel of GEMINI_CASCADE_CHAIN) {
6580
6597
  const model = normalizeGeminiModel(rawModel);
6581
6598
  if (!this.attemptedModelsInCascade.has(model)) {
6599
+ const prevProvider = this.config.provider;
6582
6600
  renderCascadeNotice(currentModel, model, noticeReason);
6583
6601
  this.config.provider = "gemini";
6584
6602
  this.config.apiKey = geminiKey;
6585
6603
  this.config.model = model;
6586
6604
  delete this.config.baseURL;
6587
6605
  this.initClients();
6588
- this.syncMessagesToGemini();
6606
+ this.syncHistoryForProviderChange(prevProvider, "gemini");
6589
6607
  return model;
6590
6608
  }
6591
6609
  }
@@ -6597,13 +6615,14 @@ ${String(out).slice(0, 6e3)}`);
6597
6615
  if (!openRouterKey) return null;
6598
6616
  for (const model of OPENROUTER_FREE_CASCADE_CHAIN) {
6599
6617
  if (!this.attemptedModelsInCascade.has(model)) {
6618
+ const prevProvider = this.config.provider;
6600
6619
  renderCascadeNotice(currentModel, model, noticeReason);
6601
6620
  this.config.provider = "openrouter";
6602
6621
  this.config.apiKey = openRouterKey;
6603
6622
  this.config.model = model;
6604
6623
  this.config.baseURL = "https://openrouter.ai/api/v1";
6605
6624
  this.initClients();
6606
- this.syncMessagesToOpenAI();
6625
+ this.syncHistoryForProviderChange(prevProvider, "openrouter");
6607
6626
  return model;
6608
6627
  }
6609
6628
  }
@@ -6630,6 +6649,7 @@ ${String(out).slice(0, 6e3)}`);
6630
6649
  for (const targetModel of candidateModels) {
6631
6650
  const dedupeKey = `custom:${targetModel}`;
6632
6651
  if (!this.attemptedModelsInCascade.has(dedupeKey) && !this.attemptedModelsInCascade.has(targetModel)) {
6652
+ const prevProvider = this.config.provider;
6633
6653
  this.attemptedModelsInCascade.add(dedupeKey);
6634
6654
  this.attemptedModelsInCascade.add(targetModel);
6635
6655
  renderCascadeNotice(currentModel, targetModel, noticeReason);
@@ -6638,7 +6658,7 @@ ${String(out).slice(0, 6e3)}`);
6638
6658
  this.config.baseURL = customBaseURL;
6639
6659
  this.config.model = targetModel;
6640
6660
  this.initClients();
6641
- this.syncMessagesToOpenAI();
6661
+ this.syncHistoryForProviderChange(prevProvider, "custom");
6642
6662
  return targetModel;
6643
6663
  }
6644
6664
  }
@@ -6673,16 +6693,13 @@ ${String(out).slice(0, 6e3)}`);
6673
6693
  const nextOR = switchToOpenRouter("Custom provider rate-limited/exhausted; cascading to OpenRouter Free");
6674
6694
  if (nextOR) return nextOR;
6675
6695
  }
6696
+ const prevProviderBeforeExplore = this.config.provider;
6676
6697
  const explored = await exploreAndSelectFreeModel(this.config, this.attemptedModelsInCascade, false, false);
6677
6698
  if (explored) {
6678
6699
  this.attemptedModelsInCascade.add(explored.id);
6679
6700
  this.initClients();
6680
- if (explored.provider === "gemini") {
6681
- this.syncMessagesToGemini();
6682
- } else {
6683
- this.syncMessagesToOpenAI();
6684
- }
6685
- this.onModelChangeCallback?.(explored.id, explored.provider);
6701
+ this.syncHistoryForProviderChange(prevProviderBeforeExplore, this.config.provider);
6702
+ this.onModelChangeCallback?.(explored.id, explored.provider, this.config);
6686
6703
  return explored.id;
6687
6704
  }
6688
6705
  if (this.neverStopAttempts < 10) {
@@ -6698,27 +6715,25 @@ ${String(out).slice(0, 6e3)}`);
6698
6715
  if (signal?.aborted) return null;
6699
6716
  this.attemptedModelsInCascade.clear();
6700
6717
  this.deadProvidersInTurn.clear();
6718
+ const prevProviderBeforeRecovery = this.config.provider;
6701
6719
  const recovered = await exploreAndSelectFreeModel(this.config, /* @__PURE__ */ new Set(), true, false);
6702
6720
  if (recovered) {
6703
6721
  this.initClients();
6704
- if (recovered.provider === "gemini") {
6705
- this.syncMessagesToGemini();
6706
- } else {
6707
- this.syncMessagesToOpenAI();
6708
- }
6709
- this.onModelChangeCallback?.(recovered.id, recovered.provider);
6722
+ this.syncHistoryForProviderChange(prevProviderBeforeRecovery, this.config.provider);
6723
+ this.onModelChangeCallback?.(recovered.id, recovered.provider, this.config);
6710
6724
  return recovered.id;
6711
6725
  }
6712
6726
  }
6713
6727
  if (this.config.baseURL !== POLLINATIONS_BASE_URL || this.config.model !== POLLINATIONS_DEFAULT_MODEL) {
6728
+ const prevProviderBeforeFallback = this.config.provider;
6714
6729
  renderCascadeNotice(currentModel, POLLINATIONS_DEFAULT_MODEL, "Switching to Zero-Key Built-in Free AI");
6715
6730
  this.config.provider = "custom";
6716
6731
  this.config.apiKey = POLLINATIONS_FREE_API_KEY;
6717
6732
  this.config.baseURL = POLLINATIONS_BASE_URL;
6718
6733
  this.config.model = POLLINATIONS_DEFAULT_MODEL;
6719
6734
  this.initClients();
6720
- this.syncMessagesToOpenAI();
6721
- this.onModelChangeCallback?.(this.config.model, this.config.provider);
6735
+ this.syncHistoryForProviderChange(prevProviderBeforeFallback, "custom");
6736
+ this.onModelChangeCallback?.(this.config.model, this.config.provider, this.config);
6722
6737
  return this.config.model;
6723
6738
  }
6724
6739
  renderAllTokensExhaustedReport();
@@ -6728,15 +6743,12 @@ ${String(out).slice(0, 6e3)}`);
6728
6743
  * Run model explorer to find and select an active model with free tokens.
6729
6744
  */
6730
6745
  async exploreFreeModel() {
6746
+ const prevProvider = this.config.provider;
6731
6747
  const explored = await exploreAndSelectFreeModel(this.config);
6732
6748
  if (explored) {
6733
6749
  this.initClients();
6734
- if (explored.provider === "gemini") {
6735
- this.syncMessagesToGemini();
6736
- } else {
6737
- this.syncMessagesToOpenAI();
6738
- }
6739
- this.onModelChangeCallback?.(explored.id, explored.provider);
6750
+ this.syncHistoryForProviderChange(prevProvider, this.config.provider);
6751
+ this.onModelChangeCallback?.(explored.id, explored.provider, this.config);
6740
6752
  return explored.id;
6741
6753
  }
6742
6754
  return null;
@@ -6849,19 +6861,59 @@ ${String(out).slice(0, 6e3)}`);
6849
6861
  * Ensure message history has no dangling tool_calls or unresponded user turns before starting a new turn.
6850
6862
  */
6851
6863
  sanitizeDanglingHistory() {
6852
- const lastOpenAI = this.openAIMessages[this.openAIMessages.length - 1];
6853
- if (lastOpenAI && lastOpenAI.role === "assistant" && Array.isArray(lastOpenAI.tool_calls) && lastOpenAI.tool_calls.length > 0) {
6854
- for (const tc of lastOpenAI.tool_calls) {
6855
- if (tc?.id) {
6856
- this.openAIMessages.push({
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) => ({
6857
6889
  role: "tool",
6858
- tool_call_id: tc.id,
6890
+ tool_call_id: id,
6859
6891
  content: "Action cancelled before completion."
6860
- });
6861
- }
6892
+ }))
6893
+ );
6862
6894
  }
6863
6895
  }
6864
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
+ }
6865
6917
  if (lastGemini && lastGemini.role === "user") {
6866
6918
  this.geminiContents.push({
6867
6919
  role: "model",
@@ -7144,8 +7196,23 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7144
7196
  return directText || "";
7145
7197
  }
7146
7198
  const toolResponseParts = [];
7147
- 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];
7148
7213
  if (options?.signal?.aborted) {
7214
+ pushCancelledFunctionResponses(callIndex);
7215
+ this.geminiContents.push({ role: "user", parts: toolResponseParts });
7149
7216
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7150
7217
  }
7151
7218
  const toolName = call.name;
@@ -7156,9 +7223,6 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7156
7223
  });
7157
7224
  toolsExecutedInChat++;
7158
7225
  const output = await executeTool(toolName, toolArgs, this.mode, options?.signal);
7159
- if (options?.signal?.aborted) {
7160
- return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7161
- }
7162
7226
  toolResponseParts.push({
7163
7227
  functionResponse: {
7164
7228
  name: toolName,
@@ -7166,6 +7230,11 @@ Please run ${chalk8.yellow("/config")} to update your API key.`
7166
7230
  response: { output }
7167
7231
  }
7168
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
+ }
7169
7238
  }
7170
7239
  this.geminiContents.push({
7171
7240
  role: "user",
@@ -7419,8 +7488,23 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7419
7488
  }
7420
7489
  return finalCandidate;
7421
7490
  }
7422
- 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];
7423
7506
  if (options?.signal?.aborted) {
7507
+ pushCancelledToolResponses(callIndex);
7424
7508
  return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7425
7509
  }
7426
7510
  const fnObj = toolCall.function;
@@ -7456,14 +7540,15 @@ Please run ${chalk8.yellow("/provider")} or ${chalk8.yellow("/config")} to confi
7456
7540
  });
7457
7541
  toolsExecutedInChat++;
7458
7542
  const toolResult = await executeTool(fnName, fnArgs, this.mode, options?.signal);
7459
- if (options?.signal?.aborted) {
7460
- return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7461
- }
7462
7543
  this.openAIMessages.push({
7463
7544
  role: "tool",
7464
7545
  tool_call_id: toolCall.id,
7465
7546
  content: toolResult
7466
7547
  });
7548
+ if (options?.signal?.aborted) {
7549
+ pushCancelledToolResponses(callIndex + 1);
7550
+ return chalk8.yellow("\nTask cancelled by user (Escape key pressed).");
7551
+ }
7467
7552
  }
7468
7553
  }
7469
7554
  return "Maximum agent iteration steps reached for this request.";
@@ -8425,12 +8510,10 @@ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 655
8425
8510
  await meshNode.start();
8426
8511
  setActiveMeshNode(meshNode);
8427
8512
  }
8428
- agent.setOnModelChange((newModel, newProvider) => {
8429
- const freshConfig = getConfig();
8430
- if (freshConfig) {
8431
- config = freshConfig;
8432
- }
8433
- if (config) {
8513
+ agent.setOnModelChange((newModel, newProvider, activeConfig) => {
8514
+ if (activeConfig) {
8515
+ config = activeConfig;
8516
+ } else if (config) {
8434
8517
  config.model = newModel;
8435
8518
  if (newProvider) {
8436
8519
  config.provider = newProvider;
@@ -8439,14 +8522,9 @@ Invalid --mesh-port "${options.meshPort}". Expected an integer between 1 and 655
8439
8522
  } else if (config.provider === "openrouter") {
8440
8523
  config.baseURL = "https://openrouter.ai/api/v1";
8441
8524
  }
8442
- const saved = config.savedProviders?.[config.provider];
8443
- if (saved && saved.apiKey) {
8444
- config.apiKey = saved.apiKey;
8445
- if (config.provider !== "gemini") {
8446
- config.baseURL = saved.baseURL || config.baseURL;
8447
- }
8448
- }
8449
8525
  }
8526
+ }
8527
+ if (config) {
8450
8528
  if (hasSavedConfig() || config.apiKey !== POLLINATIONS_FREE_API_KEY) {
8451
8529
  saveConfig(config);
8452
8530
  }