@bike4mind/cli 0.2.10-slack-metrics-admin-dashboard.17277 → 0.2.11-feat-api-key-rate-limiting.17321

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,9 +4,9 @@ import {
4
4
  getEffectiveApiKey,
5
5
  getOpenWeatherKey,
6
6
  getSerperKey
7
- } from "./chunk-TFXE7AI6.js";
8
- import "./chunk-VOOM6DLV.js";
9
- import "./chunk-E2VXQGEM.js";
7
+ } from "./chunk-PCZVBQPE.js";
8
+ import "./chunk-R3OGMLPO.js";
9
+ import "./chunk-OX6W5SJ7.js";
10
10
  import {
11
11
  BFLImageService,
12
12
  BaseStorage,
@@ -15,7 +15,7 @@ import {
15
15
  OpenAIBackend,
16
16
  OpenAIImageService,
17
17
  XAIImageService
18
- } from "./chunk-23GLLYOT.js";
18
+ } from "./chunk-4RN2B56U.js";
19
19
  import {
20
20
  Logger
21
21
  } from "./chunk-AMDXHL6S.js";
@@ -73,7 +73,7 @@ import {
73
73
  XAI_IMAGE_MODELS,
74
74
  b4mLLMTools,
75
75
  getMcpProviderMetadata
76
- } from "./chunk-6EQ62KRQ.js";
76
+ } from "./chunk-JS23EPWX.js";
77
77
  import {
78
78
  __require
79
79
  } from "./chunk-PDX44BCA.js";
@@ -82,7 +82,7 @@ import {
82
82
  import React17, { useState as useState8, useEffect as useEffect3, useCallback, useRef as useRef2 } from "react";
83
83
  import { render, Box as Box16, Text as Text16, useApp, useInput as useInput6 } from "ink";
84
84
  import { execSync } from "child_process";
85
- import { v4 as uuidv49 } from "uuid";
85
+ import { v4 as uuidv410 } from "uuid";
86
86
 
87
87
  // src/components/App.tsx
88
88
  import React11, { useState as useState4 } from "react";
@@ -107,7 +107,8 @@ function CustomTextInput({
107
107
  onChange,
108
108
  onSubmit,
109
109
  placeholder = "",
110
- showCursor = true
110
+ showCursor = true,
111
+ disabled = false
111
112
  }) {
112
113
  const [cursorOffset, setCursorOffset] = useState(value.length);
113
114
  useInput(
@@ -188,7 +189,7 @@ function CustomTextInput({
188
189
  setCursorOffset(cursorOffset + 1);
189
190
  }
190
191
  },
191
- { isActive: true }
192
+ { isActive: !disabled }
192
193
  );
193
194
  const hasValue = value.length > 0;
194
195
  if (!hasValue) {
@@ -827,56 +828,59 @@ function InputPrompt({
827
828
  useEffect(() => {
828
829
  setFileSelectedIndex(0);
829
830
  }, [filteredFiles]);
830
- useInput2((_input, key) => {
831
- if (fileAutocomplete?.active && filteredFiles.length > 0) {
832
- if (key.upArrow) {
833
- setFileSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredFiles.length - 1);
834
- return;
835
- } else if (key.downArrow) {
836
- setFileSelectedIndex((prev) => prev < filteredFiles.length - 1 ? prev + 1 : 0);
837
- return;
838
- } else if (key.tab) {
839
- const selectedFile = filteredFiles[fileSelectedIndex];
840
- if (selectedFile) {
841
- insertSelectedFile(selectedFile);
831
+ useInput2(
832
+ (_input, key) => {
833
+ if (fileAutocomplete?.active && filteredFiles.length > 0) {
834
+ if (key.upArrow) {
835
+ setFileSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredFiles.length - 1);
836
+ return;
837
+ } else if (key.downArrow) {
838
+ setFileSelectedIndex((prev) => prev < filteredFiles.length - 1 ? prev + 1 : 0);
839
+ return;
840
+ } else if (key.tab) {
841
+ const selectedFile = filteredFiles[fileSelectedIndex];
842
+ if (selectedFile) {
843
+ insertSelectedFile(selectedFile);
844
+ }
845
+ return;
846
+ } else if (key.escape) {
847
+ setFileAutocomplete(null);
848
+ return;
842
849
  }
843
- return;
844
- } else if (key.escape) {
845
- setFileAutocomplete(null);
846
- return;
847
- }
848
- }
849
- if (shouldShowCommandAutocomplete && filteredCommands.length > 0) {
850
- if (key.upArrow) {
851
- setSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredCommands.length - 1);
852
- } else if (key.downArrow) {
853
- setSelectedIndex((prev) => prev < filteredCommands.length - 1 ? prev + 1 : 0);
854
850
  }
855
- return;
856
- }
857
- if (!shouldShowCommandAutocomplete && !fileAutocomplete?.active && history.length > 0) {
858
- if (key.upArrow) {
859
- if (historyIndex === -1) {
860
- setTempInput(value);
861
- setHistoryIndex(0);
862
- setValue(history[0]);
863
- } else if (historyIndex < history.length - 1) {
864
- const newIndex = historyIndex + 1;
865
- setHistoryIndex(newIndex);
866
- setValue(history[newIndex]);
851
+ if (shouldShowCommandAutocomplete && filteredCommands.length > 0) {
852
+ if (key.upArrow) {
853
+ setSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredCommands.length - 1);
854
+ } else if (key.downArrow) {
855
+ setSelectedIndex((prev) => prev < filteredCommands.length - 1 ? prev + 1 : 0);
867
856
  }
868
- } else if (key.downArrow) {
869
- if (historyIndex > 0) {
870
- const newIndex = historyIndex - 1;
871
- setHistoryIndex(newIndex);
872
- setValue(history[newIndex]);
873
- } else if (historyIndex === 0) {
874
- setHistoryIndex(-1);
875
- setValue(tempInput);
857
+ return;
858
+ }
859
+ if (!shouldShowCommandAutocomplete && !fileAutocomplete?.active && history.length > 0) {
860
+ if (key.upArrow) {
861
+ if (historyIndex === -1) {
862
+ setTempInput(value);
863
+ setHistoryIndex(0);
864
+ setValue(history[0]);
865
+ } else if (historyIndex < history.length - 1) {
866
+ const newIndex = historyIndex + 1;
867
+ setHistoryIndex(newIndex);
868
+ setValue(history[newIndex]);
869
+ }
870
+ } else if (key.downArrow) {
871
+ if (historyIndex > 0) {
872
+ const newIndex = historyIndex - 1;
873
+ setHistoryIndex(newIndex);
874
+ setValue(history[newIndex]);
875
+ } else if (historyIndex === 0) {
876
+ setHistoryIndex(-1);
877
+ setValue(tempInput);
878
+ }
876
879
  }
877
880
  }
878
- }
879
- });
881
+ },
882
+ { isActive: !disabled }
883
+ );
880
884
  const insertSelectedFile = (file) => {
881
885
  if (!fileAutocomplete) return;
882
886
  const beforeAt = value.slice(0, fileAutocomplete.startIndex);
@@ -970,7 +974,8 @@ function InputPrompt({
970
974
  onChange: handleChange,
971
975
  onSubmit: handleSubmit,
972
976
  placeholder: getPlaceholder(),
973
- showCursor: !disabled
977
+ showCursor: !disabled,
978
+ disabled
974
979
  }
975
980
  )), shouldShowCommandAutocomplete && /* @__PURE__ */ React5.createElement(CommandAutocomplete, { commands: filteredCommands, selectedIndex }), fileAutocomplete?.active && /* @__PURE__ */ React5.createElement(FileAutocomplete, { files: filteredFiles, selectedIndex: fileSelectedIndex, query: fileAutocomplete.query }));
976
981
  }
@@ -1523,7 +1528,7 @@ ${errorBlock}`;
1523
1528
  onSave: onSaveConfig,
1524
1529
  onClose: () => setShowConfigEditor(false)
1525
1530
  }
1526
- )) : permissionPrompt ? /* @__PURE__ */ React11.createElement(Box10, { flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1531
+ )) : /* @__PURE__ */ React11.createElement(React11.Fragment, null, /* @__PURE__ */ React11.createElement(Static, { items: messages }, (message) => /* @__PURE__ */ React11.createElement(Box10, { key: message.id, flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(MessageItem, { message }))), /* @__PURE__ */ React11.createElement(Box10, { flexDirection: "column" }, pendingMessages.map((message) => /* @__PURE__ */ React11.createElement(Box10, { key: message.id, flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(MessageItem, { message })))), permissionPrompt && /* @__PURE__ */ React11.createElement(Box10, { flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1527
1532
  PermissionPrompt,
1528
1533
  {
1529
1534
  toolName: permissionPrompt.toolName,
@@ -1532,13 +1537,13 @@ ${errorBlock}`;
1532
1537
  canBeTrusted: permissionPrompt.canBeTrusted,
1533
1538
  onResponse: onPermissionResponse
1534
1539
  }
1535
- )) : /* @__PURE__ */ React11.createElement(React11.Fragment, null, /* @__PURE__ */ React11.createElement(Static, { items: messages }, (message, index) => /* @__PURE__ */ React11.createElement(Box10, { key: `${message.timestamp}-${message.role}-${index}`, flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(MessageItem, { message }))), /* @__PURE__ */ React11.createElement(Box10, { flexDirection: "column" }, pendingMessages.map((message, index) => /* @__PURE__ */ React11.createElement(Box10, { key: `pending-${message.timestamp}-${index}`, flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(MessageItem, { message })))), /* @__PURE__ */ React11.createElement(AgentThinking, null), exitRequested && /* @__PURE__ */ React11.createElement(Box10, { paddingX: 1, marginBottom: 1 }, /* @__PURE__ */ React11.createElement(Text10, { color: "yellow", bold: true }, "Press Ctrl+C again to exit")), /* @__PURE__ */ React11.createElement(Box10, { borderStyle: "single", borderColor: isBashMode ? "yellow" : "cyan", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1540
+ )), !permissionPrompt && /* @__PURE__ */ React11.createElement(AgentThinking, null), exitRequested && /* @__PURE__ */ React11.createElement(Box10, { paddingX: 1, marginBottom: 1 }, /* @__PURE__ */ React11.createElement(Text10, { color: "yellow", bold: true }, "Press Ctrl+C again to exit")), /* @__PURE__ */ React11.createElement(Box10, { borderStyle: "single", borderColor: isBashMode ? "yellow" : "cyan", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1536
1541
  InputPrompt,
1537
1542
  {
1538
1543
  onSubmit: handleSubmit,
1539
1544
  onBashCommand,
1540
1545
  onImageDetected,
1541
- disabled: isThinking,
1546
+ disabled: isThinking || !!permissionPrompt,
1542
1547
  history: commandHistory,
1543
1548
  commands,
1544
1549
  prefillInput,
@@ -1932,6 +1937,7 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
1932
1937
  import { promises as fs3 } from "fs";
1933
1938
  import path3 from "path";
1934
1939
  import { homedir } from "os";
1940
+ import { v4 as uuidv4 } from "uuid";
1935
1941
  var SessionStore = class {
1936
1942
  constructor(basePath) {
1937
1943
  this.basePath = basePath || path3.join(homedir(), ".bike4mind", "sessions");
@@ -1967,7 +1973,14 @@ var SessionStore = class {
1967
1973
  const filePath = path3.join(this.basePath, `${id}.json`);
1968
1974
  try {
1969
1975
  const data = await fs3.readFile(filePath, "utf-8");
1970
- return JSON.parse(data);
1976
+ const session = JSON.parse(data);
1977
+ session.messages = session.messages.map((msg) => {
1978
+ if (!msg.id) {
1979
+ return { ...msg, id: uuidv4() };
1980
+ }
1981
+ return msg;
1982
+ });
1983
+ return session;
1971
1984
  } catch (error) {
1972
1985
  if (error.code === "ENOENT") {
1973
1986
  return null;
@@ -1996,7 +2009,14 @@ var SessionStore = class {
1996
2009
  jsonFiles.map(async (file) => {
1997
2010
  const filePath = path3.join(this.basePath, file);
1998
2011
  const data = await fs3.readFile(filePath, "utf-8");
1999
- return JSON.parse(data);
2012
+ const session = JSON.parse(data);
2013
+ session.messages = session.messages.map((msg) => {
2014
+ if (!msg.id) {
2015
+ return { ...msg, id: uuidv4() };
2016
+ }
2017
+ return msg;
2018
+ });
2019
+ return session;
2000
2020
  })
2001
2021
  );
2002
2022
  return sessions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
@@ -2050,7 +2070,7 @@ var SessionStore = class {
2050
2070
  import { promises as fs4, existsSync as existsSync3 } from "fs";
2051
2071
  import path4 from "path";
2052
2072
  import { homedir as homedir2 } from "os";
2053
- import { v4 as uuidv4 } from "uuid";
2073
+ import { v4 as uuidv42 } from "uuid";
2054
2074
  import { z } from "zod";
2055
2075
  var AuthTokensSchema = z.object({
2056
2076
  accessToken: z.string(),
@@ -2144,7 +2164,7 @@ var ProjectLocalConfigSchema = z.object({
2144
2164
  });
2145
2165
  var DEFAULT_CONFIG = {
2146
2166
  version: "0.1.0",
2147
- userId: uuidv4(),
2167
+ userId: uuidv42(),
2148
2168
  defaultModel: "claude-sonnet-4-5-20250929",
2149
2169
  toolApiKeys: {
2150
2170
  openweather: void 0,
@@ -2426,7 +2446,7 @@ var ConfigStore = class {
2426
2446
  * Reset configuration to defaults
2427
2447
  */
2428
2448
  async reset() {
2429
- this.config = { ...DEFAULT_CONFIG, userId: uuidv4() };
2449
+ this.config = { ...DEFAULT_CONFIG, userId: uuidv42() };
2430
2450
  await this.save();
2431
2451
  return this.config;
2432
2452
  }
@@ -3129,6 +3149,7 @@ ${options.context}` : this.getSystemPrompt()
3129
3149
  }
3130
3150
  if (completionInfo.toolsUsed && completionInfo.toolsUsed.length > 0) {
3131
3151
  hadToolCalls = true;
3152
+ const thinkingBlocks = completionInfo.thinking || [];
3132
3153
  for (const toolUse of completionInfo.toolsUsed) {
3133
3154
  const toolCallId = `${toolUse.name}_${JSON.stringify(toolUse.arguments)}`;
3134
3155
  if (processedToolIds.has(toolCallId)) {
@@ -3161,16 +3182,23 @@ ${options.context}` : this.getSystemPrompt()
3161
3182
  const params = typeof toolUse.arguments === "string" ? JSON.parse(toolUse.arguments) : toolUse.arguments;
3162
3183
  observation = await tool.toolFn(params);
3163
3184
  const toolCallId2 = `${toolUse.name}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
3185
+ const assistantContent = [
3186
+ // Include thinking blocks first (required by Anthropic when thinking is enabled)
3187
+ ...thinkingBlocks,
3188
+ // Then the tool use
3189
+ {
3190
+ type: "tool_use",
3191
+ id: toolCallId2,
3192
+ name: toolUse.name,
3193
+ input: params
3194
+ }
3195
+ ];
3196
+ this.context.logger.debug(
3197
+ `[assistantContent] ${assistantContent.length} blocks (${thinkingBlocks.length} thinking, 1 tool_use)`
3198
+ );
3164
3199
  messages.push({
3165
3200
  role: "assistant",
3166
- content: [
3167
- {
3168
- type: "tool_use",
3169
- id: toolCallId2,
3170
- name: toolUse.name,
3171
- input: params
3172
- }
3173
- ]
3201
+ content: assistantContent
3174
3202
  });
3175
3203
  messages.push({
3176
3204
  role: "user",
@@ -4336,7 +4364,7 @@ var listFabFilesSchema = z86.object({
4336
4364
 
4337
4365
  // ../../b4m-core/packages/services/dist/src/fabFileService/update.js
4338
4366
  import mime from "mime-types";
4339
- import { v4 as uuidv42 } from "uuid";
4367
+ import { v4 as uuidv43 } from "uuid";
4340
4368
  import { z as z87 } from "zod";
4341
4369
  var updateFabFileSchema = z87.object({
4342
4370
  id: z87.string(),
@@ -4457,7 +4485,7 @@ var editFabFileSchema = z98.object({
4457
4485
 
4458
4486
  // ../../b4m-core/packages/services/dist/src/fabFileService/applyEdit.js
4459
4487
  import mime2 from "mime-types";
4460
- import { v4 as uuidv43 } from "uuid";
4488
+ import { v4 as uuidv44 } from "uuid";
4461
4489
  import { z as z99 } from "zod";
4462
4490
  var applyEditSchema = z99.object({
4463
4491
  id: z99.string(),
@@ -5285,7 +5313,7 @@ import { toFile } from "openai/uploads";
5285
5313
  import { Readable } from "stream";
5286
5314
  import { TranscribeClient, StartTranscriptionJobCommand, GetTranscriptionJobCommand, LanguageCode, MediaFormat } from "@aws-sdk/client-transcribe";
5287
5315
  import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
5288
- import { v4 as uuidv44 } from "uuid";
5316
+ import { v4 as uuidv45 } from "uuid";
5289
5317
 
5290
5318
  // ../../b4m-core/packages/services/dist/src/emailIngestionService/processIngestedEmail.js
5291
5319
  import { randomUUID as randomUUID5 } from "crypto";
@@ -5446,7 +5474,7 @@ var weatherTool = {
5446
5474
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/imageGeneration/index.js
5447
5475
  import axios6 from "axios";
5448
5476
  import { fileTypeFromBuffer as fileTypeFromBuffer2 } from "file-type";
5449
- import { v4 as uuidv45 } from "uuid";
5477
+ import { v4 as uuidv46 } from "uuid";
5450
5478
  async function downloadImage(url) {
5451
5479
  if (url.startsWith("data:image/")) {
5452
5480
  const base64Data = url.split(",")[1];
@@ -5460,7 +5488,7 @@ async function processAndStoreImages(images, context) {
5460
5488
  return Promise.all(images.map(async (image) => {
5461
5489
  const buffer = await downloadImage(image);
5462
5490
  const fileType = await fileTypeFromBuffer2(buffer);
5463
- const filename = `${uuidv45()}.${fileType?.ext}`;
5491
+ const filename = `${uuidv46()}.${fileType?.ext}`;
5464
5492
  const path16 = await context.imageGenerateStorage.upload(buffer, filename, {});
5465
5493
  return path16;
5466
5494
  }));
@@ -6629,7 +6657,7 @@ Return only the edited content without any markdown code blocks or explanations.
6629
6657
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/imageEdit/index.js
6630
6658
  import axios7 from "axios";
6631
6659
  import { fileTypeFromBuffer as fileTypeFromBuffer3 } from "file-type";
6632
- import { v4 as uuidv46 } from "uuid";
6660
+ import { v4 as uuidv47 } from "uuid";
6633
6661
  async function downloadImage2(url) {
6634
6662
  if (url.startsWith("data:image/")) {
6635
6663
  const base64Data = url.split(",")[1];
@@ -6673,7 +6701,7 @@ async function getImageFromFileId(fileId, context) {
6673
6701
  async function processAndStoreImage(imageUrl, context) {
6674
6702
  const buffer = await downloadImage2(imageUrl);
6675
6703
  const fileType = await fileTypeFromBuffer3(buffer);
6676
- const filename = `${uuidv46()}.${fileType?.ext}`;
6704
+ const filename = `${uuidv47()}.${fileType?.ext}`;
6677
6705
  const path16 = await context.imageGenerateStorage.upload(buffer, filename, {});
6678
6706
  return path16;
6679
6707
  }
@@ -8579,7 +8607,8 @@ var fileReadTool = {
8579
8607
  return content;
8580
8608
  } catch (error) {
8581
8609
  context.logger.error("\u274C FileRead: Failed", error);
8582
- throw error;
8610
+ const errorMessage = error instanceof Error ? error.message : String(error);
8611
+ return `Error reading file: ${errorMessage}`;
8583
8612
  }
8584
8613
  },
8585
8614
  toolSchema: {
@@ -9649,7 +9678,7 @@ var QuestStartBodySchema = z139.object({
9649
9678
  // ../../b4m-core/packages/services/dist/src/llm/ImageGeneration.js
9650
9679
  import axios8 from "axios";
9651
9680
  import { fileTypeFromBuffer as fileTypeFromBuffer4 } from "file-type";
9652
- import { v4 as uuidv47 } from "uuid";
9681
+ import { v4 as uuidv48 } from "uuid";
9653
9682
  import { z as z140 } from "zod";
9654
9683
  import { fromZodError as fromZodError2 } from "zod-validation-error";
9655
9684
  var ImageGenerationBodySchema = OpenAIImageGenerationInput.extend({
@@ -9670,7 +9699,7 @@ var ImageGenerationBodySchema = OpenAIImageGenerationInput.extend({
9670
9699
  // ../../b4m-core/packages/services/dist/src/llm/ImageEdit.js
9671
9700
  import axios9 from "axios";
9672
9701
  import { fileTypeFromBuffer as fileTypeFromBuffer5 } from "file-type";
9673
- import { v4 as uuidv48 } from "uuid";
9702
+ import { v4 as uuidv49 } from "uuid";
9674
9703
  import { z as z141 } from "zod";
9675
9704
  import { fromZodError as fromZodError3 } from "zod-validation-error";
9676
9705
  var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
@@ -10224,7 +10253,31 @@ function wrapToolWithPermission(tool, permissionManager, showPermissionPrompt, a
10224
10253
  }
10225
10254
  };
10226
10255
  }
10227
- function generateCliTools(userId, llm, model, permissionManager, showPermissionPrompt, agentContext, configStore, apiClient) {
10256
+ var TOOL_NAME_MAPPING = {
10257
+ // Claude Code -> B4M
10258
+ read: "file_read",
10259
+ write: "create_file",
10260
+ edit: "edit_file",
10261
+ delete: "delete_file",
10262
+ glob: "glob_files",
10263
+ grep: "grep_search",
10264
+ bash: "bash_execute",
10265
+ // B4M -> Claude Code (reverse mapping)
10266
+ file_read: "read",
10267
+ create_file: "write",
10268
+ edit_file: "edit",
10269
+ delete_file: "delete",
10270
+ glob_files: "glob",
10271
+ grep_search: "grep",
10272
+ bash_execute: "bash"
10273
+ };
10274
+ function normalizeToolName(toolName) {
10275
+ if (toolName.includes("_")) {
10276
+ return toolName;
10277
+ }
10278
+ return TOOL_NAME_MAPPING[toolName] || toolName;
10279
+ }
10280
+ function generateCliTools(userId, llm, model, permissionManager, showPermissionPrompt, agentContext, configStore, apiClient, toolFilter) {
10228
10281
  const logger2 = new CliLogger();
10229
10282
  const storage = new NoOpStorage();
10230
10283
  const user = {
@@ -10294,9 +10347,24 @@ function generateCliTools(userId, llm, model, permissionManager, showPermissionP
10294
10347
  toolConfig,
10295
10348
  model
10296
10349
  );
10297
- const tools2 = Object.entries(toolsMap).filter(([key]) => toolConfig[key] !== void 0).map(
10350
+ let tools2 = Object.entries(toolsMap).filter(([key]) => toolConfig[key] !== void 0).map(
10298
10351
  ([_, tool]) => wrapToolWithPermission(tool, permissionManager, showPermissionPrompt, agentContext, configStore, apiClient)
10299
10352
  );
10353
+ if (toolFilter) {
10354
+ const { allowedTools, deniedTools } = toolFilter;
10355
+ const normalizedAllowed = allowedTools?.map(normalizeToolName);
10356
+ const normalizedDenied = deniedTools?.map(normalizeToolName);
10357
+ tools2 = tools2.filter((tool) => {
10358
+ const toolName = tool.toolSchema.name;
10359
+ if (normalizedDenied && normalizedDenied.includes(toolName)) {
10360
+ return false;
10361
+ }
10362
+ if (normalizedAllowed && normalizedAllowed.length > 0) {
10363
+ return normalizedAllowed.includes(toolName);
10364
+ }
10365
+ return true;
10366
+ });
10367
+ }
10300
10368
  return { tools: tools2, agentContext };
10301
10369
  }
10302
10370
 
@@ -11079,6 +11147,7 @@ var ServerLlmBackend = class {
11079
11147
  let accumulatedText = "";
11080
11148
  let lastUsageInfo = {};
11081
11149
  let toolsUsed = [];
11150
+ let thinkingBlocks = [];
11082
11151
  let receivedDone = false;
11083
11152
  const parser = createParser({
11084
11153
  onEvent: (event) => {
@@ -11092,9 +11161,12 @@ var ServerLlmBackend = class {
11092
11161
  if (toolsUsed.length > 0) {
11093
11162
  const info = {
11094
11163
  toolsUsed,
11164
+ thinking: thinkingBlocks.length > 0 ? thinkingBlocks : void 0,
11095
11165
  ...lastUsageInfo
11096
11166
  };
11097
- logger.debug("[ServerLlmBackend] Calling callback with tools, will wait for completion");
11167
+ logger.debug(
11168
+ `[ServerLlmBackend] Calling callback with tools, thinking blocks: ${thinkingBlocks.length}`
11169
+ );
11098
11170
  callback([cleanedText], info).catch((err) => {
11099
11171
  logger.error("[ServerLlmBackend] Callback error:", err);
11100
11172
  reject(err);
@@ -11150,6 +11222,10 @@ var ServerLlmBackend = class {
11150
11222
  if (parsed.tools && parsed.tools.length > 0) {
11151
11223
  toolsUsed = parsed.tools;
11152
11224
  }
11225
+ if (parsed.thinking && parsed.thinking.length > 0) {
11226
+ thinkingBlocks = parsed.thinking;
11227
+ logger.debug(`[ServerLlmBackend] Received ${thinkingBlocks.length} thinking blocks`);
11228
+ }
11153
11229
  if (parsed.usage) {
11154
11230
  lastUsageInfo = {
11155
11231
  inputTokens: parsed.usage.inputTokens,
@@ -11472,7 +11548,7 @@ import { isAxiosError as isAxiosError2 } from "axios";
11472
11548
  // package.json
11473
11549
  var package_default = {
11474
11550
  name: "@bike4mind/cli",
11475
- version: "0.2.10-slack-metrics-admin-dashboard.17277+8887342ab",
11551
+ version: "0.2.11-feat-api-key-rate-limiting.17321+5d0057357",
11476
11552
  type: "module",
11477
11553
  description: "Interactive CLI tool for Bike4Mind with ReAct agents",
11478
11554
  license: "UNLICENSED",
@@ -11576,10 +11652,10 @@ var package_default = {
11576
11652
  },
11577
11653
  devDependencies: {
11578
11654
  "@bike4mind/agents": "0.1.0",
11579
- "@bike4mind/common": "2.39.1-slack-metrics-admin-dashboard.17277+8887342ab",
11580
- "@bike4mind/mcp": "1.20.4-slack-metrics-admin-dashboard.17277+8887342ab",
11581
- "@bike4mind/services": "2.34.2-slack-metrics-admin-dashboard.17277+8887342ab",
11582
- "@bike4mind/utils": "2.1.4-slack-metrics-admin-dashboard.17277+8887342ab",
11655
+ "@bike4mind/common": "2.40.1-feat-api-key-rate-limiting.17321+5d0057357",
11656
+ "@bike4mind/mcp": "1.20.5-feat-api-key-rate-limiting.17321+5d0057357",
11657
+ "@bike4mind/services": "2.35.1-feat-api-key-rate-limiting.17321+5d0057357",
11658
+ "@bike4mind/utils": "2.1.5-feat-api-key-rate-limiting.17321+5d0057357",
11583
11659
  "@types/better-sqlite3": "^7.6.13",
11584
11660
  "@types/diff": "^5.0.9",
11585
11661
  "@types/jsonwebtoken": "^9.0.4",
@@ -11592,7 +11668,7 @@ var package_default = {
11592
11668
  typescript: "^5.9.3",
11593
11669
  vitest: "^3.2.4"
11594
11670
  },
11595
- gitHead: "8887342ab75fec0c6122cc7ddae61f5da01dc164"
11671
+ gitHead: "5d0057357536a200c8b1806ccb7f2b47e6868036"
11596
11672
  };
11597
11673
 
11598
11674
  // src/config/constants.ts
@@ -11600,6 +11676,353 @@ var USAGE_DAYS = 30;
11600
11676
  var MODEL_NAME_COLUMN_WIDTH = 18;
11601
11677
  var USAGE_CACHE_TTL = 5 * 60 * 1e3;
11602
11678
 
11679
+ // src/agents/SubagentOrchestrator.ts
11680
+ var SubagentOrchestrator = class {
11681
+ constructor(deps) {
11682
+ this.beforeRunCallback = null;
11683
+ this.afterRunCallback = null;
11684
+ this.deps = deps;
11685
+ }
11686
+ /**
11687
+ * Set a callback to be invoked before each subagent.run()
11688
+ * Use this to subscribe to agent events (e.g., subagent.on('action', handler))
11689
+ */
11690
+ setBeforeRunCallback(callback) {
11691
+ this.beforeRunCallback = callback;
11692
+ }
11693
+ /**
11694
+ * Set a callback to be invoked after each subagent.run()
11695
+ * Use this to unsubscribe from agent events (e.g., subagent.off('action', handler))
11696
+ */
11697
+ setAfterRunCallback(callback) {
11698
+ this.afterRunCallback = callback;
11699
+ }
11700
+ /**
11701
+ * Delegate a task to a specialized subagent
11702
+ *
11703
+ * @param options - Configuration for subagent execution
11704
+ * @returns Subagent result with summary
11705
+ */
11706
+ async delegateToSubagent(options) {
11707
+ const { task, type, thoroughness, parentSessionId, config: configOverride } = options;
11708
+ const baseConfig = this.deps.subagentConfigs.get(type);
11709
+ if (!baseConfig) {
11710
+ throw new Error(`No configuration found for subagent type: ${type}`);
11711
+ }
11712
+ const config = {
11713
+ ...baseConfig,
11714
+ ...configOverride,
11715
+ type
11716
+ };
11717
+ const model = config.model || "claude-3-5-haiku-20241022";
11718
+ const maxIterations = this.getMaxIterations(config, thoroughness);
11719
+ const toolFilter = {
11720
+ allowedTools: config.allowedTools,
11721
+ deniedTools: config.deniedTools
11722
+ };
11723
+ const agentContext = {
11724
+ currentAgent: null,
11725
+ observationQueue: []
11726
+ };
11727
+ const { tools: tools2, agentContext: updatedContext } = generateCliTools(
11728
+ this.deps.userId,
11729
+ this.deps.llm,
11730
+ model,
11731
+ this.deps.permissionManager,
11732
+ this.deps.showPermissionPrompt,
11733
+ agentContext,
11734
+ this.deps.configStore,
11735
+ this.deps.apiClient,
11736
+ toolFilter
11737
+ );
11738
+ this.deps.logger.debug(`Spawning ${type} subagent with ${tools2.length} tools, thoroughness: ${thoroughness}`);
11739
+ const subagent = new ReActAgent({
11740
+ userId: this.deps.userId,
11741
+ logger: this.deps.logger,
11742
+ llm: this.deps.llm,
11743
+ model,
11744
+ tools: tools2,
11745
+ maxIterations,
11746
+ systemPrompt: config.systemPrompt || this.getDefaultSystemPrompt(type)
11747
+ });
11748
+ updatedContext.currentAgent = subagent;
11749
+ if (this.beforeRunCallback) {
11750
+ this.beforeRunCallback(subagent, type);
11751
+ }
11752
+ const startTime = Date.now();
11753
+ const result = await subagent.run(task, {
11754
+ maxIterations
11755
+ });
11756
+ const duration = Date.now() - startTime;
11757
+ if (this.afterRunCallback) {
11758
+ this.afterRunCallback(subagent, type);
11759
+ }
11760
+ this.deps.logger.debug(
11761
+ `Subagent completed in ${duration}ms, ${result.completionInfo.iterations} iterations, ${result.completionInfo.totalTokens} tokens`
11762
+ );
11763
+ const summary = this.summarizeResult(result, type);
11764
+ const subagentResult = {
11765
+ ...result,
11766
+ subagentType: type,
11767
+ thoroughness,
11768
+ summary,
11769
+ parentSessionId
11770
+ };
11771
+ return subagentResult;
11772
+ }
11773
+ /**
11774
+ * Get max iterations based on thoroughness and config
11775
+ */
11776
+ getMaxIterations(config, thoroughness) {
11777
+ const defaults = {
11778
+ quick: 2,
11779
+ medium: 5,
11780
+ very_thorough: 10
11781
+ };
11782
+ const configIterations = config.maxIterations || defaults;
11783
+ return configIterations[thoroughness];
11784
+ }
11785
+ /**
11786
+ * Get default system prompt for subagent type
11787
+ */
11788
+ getDefaultSystemPrompt(type) {
11789
+ switch (type) {
11790
+ case "explore":
11791
+ return `You are a code exploration specialist. Your job is to search and analyze codebases efficiently.
11792
+
11793
+ Focus on:
11794
+ - Finding relevant files and functions
11795
+ - Understanding code structure and patterns
11796
+ - Providing clear, concise summaries
11797
+
11798
+ You have read-only access. Use file_read, grep_search, and glob_files to explore.
11799
+
11800
+ When you find what you're looking for, provide a clear summary including:
11801
+ 1. What you found (files, functions, patterns)
11802
+ 2. Key insights or observations
11803
+ 3. Relevant code locations
11804
+
11805
+ Be thorough but concise. Your summary will be used by the main agent.`;
11806
+ case "plan":
11807
+ return `You are a task planning specialist. Your job is to break down complex tasks into clear, actionable steps.
11808
+
11809
+ Focus on:
11810
+ - Identifying dependencies and blockers
11811
+ - Creating logical sequence of steps
11812
+ - Estimating scope and priorities
11813
+
11814
+ Provide a structured plan that the main agent can execute.`;
11815
+ case "review":
11816
+ return `You are a code review specialist. Your job is to analyze code quality and identify issues.
11817
+
11818
+ Focus on:
11819
+ - Code quality and best practices
11820
+ - Potential bugs and edge cases
11821
+ - Performance and security considerations
11822
+
11823
+ Provide actionable feedback with specific file and line references.`;
11824
+ default:
11825
+ return "You are a helpful AI assistant.";
11826
+ }
11827
+ }
11828
+ /**
11829
+ * Summarize subagent result for parent agent
11830
+ */
11831
+ summarizeResult(result, type) {
11832
+ const { finalAnswer, steps, completionInfo } = result;
11833
+ const toolCalls = steps.filter((s) => s.type === "action");
11834
+ const filesRead = toolCalls.filter((s) => s.metadata?.toolName === "file_read").length;
11835
+ const searches = toolCalls.filter((s) => s.metadata?.toolName === "grep_search").length;
11836
+ const globs = toolCalls.filter((s) => s.metadata?.toolName === "glob_files").length;
11837
+ let summary = `**${type.charAt(0).toUpperCase() + type.slice(1)} Subagent Results**
11838
+
11839
+ `;
11840
+ summary += `*Execution: ${completionInfo.iterations} iterations, ${completionInfo.toolCalls} tool calls*
11841
+
11842
+ `;
11843
+ if (type === "explore") {
11844
+ summary += `*Exploration: ${filesRead} files read, ${searches} searches, ${globs} glob patterns*
11845
+
11846
+ `;
11847
+ }
11848
+ const maxLength = 1e3;
11849
+ if (finalAnswer.length > maxLength) {
11850
+ summary += finalAnswer.slice(0, maxLength) + "\n\n...(truncated)";
11851
+ } else {
11852
+ summary += finalAnswer;
11853
+ }
11854
+ return summary;
11855
+ }
11856
+ };
11857
+
11858
+ // src/agents/configs.ts
11859
+ var EXPLORE_CONFIG = {
11860
+ type: "explore",
11861
+ model: "claude-3-5-haiku-20241022",
11862
+ systemPrompt: `You are a code exploration specialist. Your job is to search and analyze codebases efficiently.
11863
+
11864
+ Focus on:
11865
+ - Finding relevant files and functions
11866
+ - Understanding code structure and patterns
11867
+ - Providing clear, concise summaries
11868
+
11869
+ You have read-only access. Use file_read, grep_search, and glob_files to explore.
11870
+
11871
+ When you find what you're looking for, provide a clear summary including:
11872
+ 1. What you found (files, functions, patterns)
11873
+ 2. Key insights or observations
11874
+ 3. Relevant code locations
11875
+
11876
+ Be thorough but concise. Your summary will be used by the main agent.`,
11877
+ allowedTools: [
11878
+ "file_read",
11879
+ "grep_search",
11880
+ "glob_files",
11881
+ "bash_execute",
11882
+ // Only for read-only commands like ls, cat, find
11883
+ "current_datetime",
11884
+ "math_evaluate"
11885
+ ],
11886
+ deniedTools: [
11887
+ "create_file",
11888
+ "edit_file",
11889
+ "delete_file",
11890
+ "web_search",
11891
+ "weather_info",
11892
+ "blog_publish",
11893
+ "blog_edit",
11894
+ "blog_draft"
11895
+ ],
11896
+ maxIterations: {
11897
+ quick: 2,
11898
+ medium: 5,
11899
+ very_thorough: 10
11900
+ },
11901
+ defaultThoroughness: "medium"
11902
+ };
11903
+ var PLAN_CONFIG = {
11904
+ type: "plan",
11905
+ model: "claude-3-5-haiku-20241022",
11906
+ systemPrompt: `You are a task planning specialist. Your job is to break down complex tasks into clear, actionable steps.
11907
+
11908
+ Focus on:
11909
+ - Identifying dependencies and blockers
11910
+ - Creating logical sequence of steps
11911
+ - Estimating scope and priorities
11912
+
11913
+ You can explore the codebase to understand the current architecture before planning.
11914
+
11915
+ Provide a structured plan that the main agent can execute.`,
11916
+ allowedTools: ["file_read", "grep_search", "glob_files", "bash_execute", "current_datetime", "math_evaluate"],
11917
+ deniedTools: ["create_file", "edit_file", "delete_file", "web_search", "weather_info"],
11918
+ maxIterations: {
11919
+ quick: 3,
11920
+ medium: 7,
11921
+ very_thorough: 12
11922
+ },
11923
+ defaultThoroughness: "medium"
11924
+ };
11925
+ var REVIEW_CONFIG = {
11926
+ type: "review",
11927
+ model: "claude-sonnet-4-5-20250929",
11928
+ // Use latest Sonnet for better reasoning
11929
+ systemPrompt: `You are a code review specialist. Your job is to analyze code quality and identify issues.
11930
+
11931
+ Focus on:
11932
+ - Code quality and best practices
11933
+ - Potential bugs and edge cases
11934
+ - Performance and security considerations
11935
+
11936
+ You have read-only access to analyze code.
11937
+
11938
+ Provide actionable feedback with specific file and line references.`,
11939
+ allowedTools: ["file_read", "grep_search", "glob_files", "bash_execute", "current_datetime"],
11940
+ deniedTools: ["create_file", "edit_file", "delete_file", "web_search", "weather_info"],
11941
+ maxIterations: {
11942
+ quick: 3,
11943
+ medium: 8,
11944
+ very_thorough: 15
11945
+ },
11946
+ defaultThoroughness: "medium"
11947
+ };
11948
+ function getDefaultSubagentConfigs() {
11949
+ return /* @__PURE__ */ new Map([
11950
+ ["explore", EXPLORE_CONFIG],
11951
+ ["plan", PLAN_CONFIG],
11952
+ ["review", REVIEW_CONFIG]
11953
+ ]);
11954
+ }
11955
+
11956
+ // src/agents/delegateTool.ts
11957
+ function createSubagentDelegateTool(orchestrator, parentSessionId) {
11958
+ return {
11959
+ toolFn: async (args) => {
11960
+ const params = args;
11961
+ if (!params.task) {
11962
+ throw new Error("subagent_delegate: task parameter is required");
11963
+ }
11964
+ if (!params.type) {
11965
+ throw new Error("subagent_delegate: type parameter is required");
11966
+ }
11967
+ const thoroughness = params.thoroughness || "medium";
11968
+ const type = params.type;
11969
+ const result = await orchestrator.delegateToSubagent({
11970
+ task: params.task,
11971
+ type,
11972
+ thoroughness,
11973
+ parentSessionId
11974
+ });
11975
+ return result.summary;
11976
+ },
11977
+ toolSchema: {
11978
+ name: "subagent_delegate",
11979
+ description: `Delegate a task to a specialized subagent for focused work.
11980
+
11981
+ **When to use this tool:**
11982
+ - **Explore**: When you need to search through the codebase, find files, or understand code structure (read-only)
11983
+ - **Plan**: When you need to break down a complex task into actionable steps
11984
+ - **Review**: When you need to analyze code quality and identify potential issues
11985
+
11986
+ **Benefits:**
11987
+ - Keeps main conversation focused and clean
11988
+ - Uses specialized prompts optimized for each task type
11989
+ - Faster execution with appropriate models (Haiku for explore/plan, Sonnet for review)
11990
+
11991
+ **Example uses:**
11992
+ - "Find all files that use the authentication system" \u2192 explore
11993
+ - "Search for components that handle user input" \u2192 explore
11994
+ - "Break down implementing a new feature into steps" \u2192 plan
11995
+ - "Review this module for potential bugs" \u2192 review`,
11996
+ parameters: {
11997
+ type: "object",
11998
+ properties: {
11999
+ task: {
12000
+ type: "string",
12001
+ description: "Clear description of what you want the subagent to do. Be specific about what you're looking for or what needs to be accomplished."
12002
+ },
12003
+ type: {
12004
+ type: "string",
12005
+ enum: ["explore", "plan", "review"],
12006
+ description: `Type of subagent to use:
12007
+ - explore: Read-only codebase exploration and search (fast, uses Haiku)
12008
+ - plan: Task breakdown and planning (uses Haiku)
12009
+ - review: Code quality analysis and review (uses Sonnet for better reasoning)`
12010
+ },
12011
+ thoroughness: {
12012
+ type: "string",
12013
+ enum: ["quick", "medium", "very_thorough"],
12014
+ description: `How thoroughly to execute:
12015
+ - quick: Fast lookup, 1-2 iterations
12016
+ - medium: Balanced exploration, 3-5 iterations (default)
12017
+ - very_thorough: Comprehensive analysis, 8-10 iterations`
12018
+ }
12019
+ },
12020
+ required: ["task", "type"]
12021
+ }
12022
+ }
12023
+ };
12024
+ }
12025
+
11603
12026
  // src/index.tsx
11604
12027
  process.removeAllListeners("warning");
11605
12028
  process.on("warning", (warning) => {
@@ -11630,7 +12053,8 @@ function CliApp() {
11630
12053
  permissionPrompt: null,
11631
12054
  trustLocationSelector: null,
11632
12055
  rewindSelector: null,
11633
- sessionSelector: null
12056
+ sessionSelector: null,
12057
+ orchestrator: null
11634
12058
  });
11635
12059
  const [isInitialized, setIsInitialized] = useState8(false);
11636
12060
  const [initError, setInitError] = useState8(null);
@@ -11730,7 +12154,7 @@ function CliApp() {
11730
12154
  if (!isAuthenticated) {
11731
12155
  console.log("\u2139\uFE0F AI features disabled. Available commands: /login, /help, /config\n");
11732
12156
  const minimalSession = {
11733
- id: uuidv49(),
12157
+ id: uuidv410(),
11734
12158
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
11735
12159
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11736
12160
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11774,7 +12198,7 @@ function CliApp() {
11774
12198
  }
11775
12199
  llm.currentModel = modelInfo.id;
11776
12200
  const newSession = {
11777
- id: uuidv49(),
12201
+ id: uuidv410(),
11778
12202
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
11779
12203
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
11780
12204
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11847,7 +12271,34 @@ function CliApp() {
11847
12271
  console.log(` \u{1F4E1} ${serverName}: ${count} tool(s)`);
11848
12272
  });
11849
12273
  }
11850
- const allTools = [...b4mTools, ...mcpTools];
12274
+ const subagentConfigs = getDefaultSubagentConfigs();
12275
+ if (config.subagents) {
12276
+ if (config.subagents.explore) {
12277
+ const currentConfig = subagentConfigs.get("explore");
12278
+ subagentConfigs.set("explore", { ...currentConfig, ...config.subagents.explore });
12279
+ }
12280
+ if (config.subagents.plan) {
12281
+ const currentConfig = subagentConfigs.get("plan");
12282
+ subagentConfigs.set("plan", { ...currentConfig, ...config.subagents.plan });
12283
+ }
12284
+ if (config.subagents.review) {
12285
+ const currentConfig = subagentConfigs.get("review");
12286
+ subagentConfigs.set("review", { ...currentConfig, ...config.subagents.review });
12287
+ }
12288
+ }
12289
+ const orchestrator = new SubagentOrchestrator({
12290
+ userId: config.userId,
12291
+ llm,
12292
+ logger: silentLogger,
12293
+ permissionManager,
12294
+ showPermissionPrompt: promptFn,
12295
+ configStore: state.configStore,
12296
+ apiClient,
12297
+ subagentConfigs
12298
+ });
12299
+ const subagentDelegateTool = createSubagentDelegateTool(orchestrator, newSession.id);
12300
+ const allTools = [...b4mTools, ...mcpTools, subagentDelegateTool];
12301
+ console.log(`\u{1F916} Subagent delegation enabled (explore, plan, review)`);
11851
12302
  const projectDir = state.configStore.getProjectConfigDir();
11852
12303
  const contextResult = await loadContextFiles(projectDir);
11853
12304
  if (contextResult.globalContext) {
@@ -11884,6 +12335,15 @@ FOR CODING TASKS:
11884
12335
  - When searching for code: Use grep_search or glob_files to find relevant files
11885
12336
  - Permission system will ask for approval before any file writes
11886
12337
 
12338
+ SUBAGENT DELEGATION:
12339
+ - You have access to specialized subagents via the subagent_delegate tool
12340
+ - Use subagents for focused exploration, planning, or review tasks:
12341
+ * explore: Fast read-only codebase search (e.g., "find all auth files", "locate API endpoints")
12342
+ * plan: Break down complex tasks into actionable steps
12343
+ * review: Analyze code quality and identify issues
12344
+ - Subagents keep the main conversation clean and run faster with optimized models
12345
+ - Delegate when you need to search extensively or analyze code structure
12346
+
11887
12347
  FOR GENERAL TASKS:
11888
12348
  - Use available tools to get information (weather, web search, calculations, etc.)
11889
12349
  - When user asks follow-up questions, use conversation context to understand what they're referring to
@@ -11894,6 +12354,7 @@ EXAMPLES:
11894
12354
  - "how about Japan?" \u2192 use weather tool for Japan (applying same question from context)
11895
12355
  - "enhance README" \u2192 file_read \u2192 generate \u2192 create_file
11896
12356
  - "what packages installed?" \u2192 glob_files "**/package.json" \u2192 file_read
12357
+ - "find all components using React hooks" \u2192 subagent_delegate(task="find all components using React hooks", type="explore")
11897
12358
 
11898
12359
  Remember: Use context from previous messages to understand follow-up questions.${contextSection}`;
11899
12360
  const maxIterations = config.preferences.maxIterations === null ? 999999 : config.preferences.maxIterations;
@@ -11910,6 +12371,27 @@ Remember: Use context from previous messages to understand follow-up questions.$
11910
12371
  });
11911
12372
  agentContext.currentAgent = agent;
11912
12373
  agent.observationQueue = agentContext.observationQueue;
12374
+ const stepHandler = (step) => {
12375
+ const { pendingMessages, updatePendingMessage } = useCliStore.getState();
12376
+ const lastIdx = pendingMessages.length - 1;
12377
+ if (lastIdx >= 0 && pendingMessages[lastIdx].role === "assistant") {
12378
+ const existingSteps = pendingMessages[lastIdx].metadata?.steps || [];
12379
+ updatePendingMessage(lastIdx, {
12380
+ ...pendingMessages[lastIdx],
12381
+ metadata: {
12382
+ ...pendingMessages[lastIdx].metadata,
12383
+ steps: [...existingSteps, step]
12384
+ }
12385
+ });
12386
+ }
12387
+ };
12388
+ agent.on("action", stepHandler);
12389
+ orchestrator.setBeforeRunCallback((subagent, _subagentType) => {
12390
+ subagent.on("action", stepHandler);
12391
+ });
12392
+ orchestrator.setAfterRunCallback((subagent, _subagentType) => {
12393
+ subagent.off("action", stepHandler);
12394
+ });
11913
12395
  setState((prev) => ({
11914
12396
  ...prev,
11915
12397
  session: newSession,
@@ -11918,8 +12400,10 @@ Remember: Use context from previous messages to understand follow-up questions.$
11918
12400
  permissionManager,
11919
12401
  config,
11920
12402
  // Store config for synchronous access
11921
- availableModels: models
12403
+ availableModels: models,
11922
12404
  // Store models for ConfigEditor
12405
+ orchestrator
12406
+ // Store orchestrator for step handler updates
11923
12407
  }));
11924
12408
  setStoreSession(newSession);
11925
12409
  setIsInitialized(true);
@@ -11983,11 +12467,13 @@ Remember: Use context from previous messages to understand follow-up questions.$
11983
12467
  messageContent = multimodalMessage.content;
11984
12468
  }
11985
12469
  const userMessage = {
12470
+ id: uuidv410(),
11986
12471
  role: "user",
11987
12472
  content: userMessageContent,
11988
12473
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
11989
12474
  };
11990
12475
  const pendingAssistantMessage = {
12476
+ id: uuidv410(),
11991
12477
  role: "assistant",
11992
12478
  content: "...",
11993
12479
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12018,7 +12504,10 @@ Remember: Use context from previous messages to understand follow-up questions.$
12018
12504
  const currentSession = useCliStore.getState().session;
12019
12505
  if (!currentSession) return;
12020
12506
  const updatedMessages = [...currentSession.messages];
12507
+ const lastMessage = updatedMessages[updatedMessages.length - 1];
12021
12508
  updatedMessages[updatedMessages.length - 1] = {
12509
+ id: lastMessage.id,
12510
+ // Preserve the original message ID
12022
12511
  role: "assistant",
12023
12512
  content: result.finalAnswer,
12024
12513
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12108,22 +12597,6 @@ Remember: Use context from previous messages to understand follow-up questions.$
12108
12597
  return;
12109
12598
  }
12110
12599
  useCliStore.getState().setIsThinking(true);
12111
- const currentSteps = [];
12112
- const stepHandler = (step) => {
12113
- currentSteps.push(step);
12114
- const { pendingMessages, updatePendingMessage } = useCliStore.getState();
12115
- const lastIdx = pendingMessages.length - 1;
12116
- if (lastIdx >= 0 && pendingMessages[lastIdx].role === "assistant") {
12117
- updatePendingMessage(lastIdx, {
12118
- ...pendingMessages[lastIdx],
12119
- metadata: {
12120
- ...pendingMessages[lastIdx].metadata,
12121
- steps: [...currentSteps]
12122
- }
12123
- });
12124
- }
12125
- };
12126
- state.agent.on("action", stepHandler);
12127
12600
  try {
12128
12601
  let messageContent = message;
12129
12602
  let userMessageContent = message;
@@ -12133,11 +12606,13 @@ Remember: Use context from previous messages to understand follow-up questions.$
12133
12606
  userMessageContent = message;
12134
12607
  }
12135
12608
  const userMessage = {
12609
+ id: uuidv410(),
12136
12610
  role: "user",
12137
12611
  content: userMessageContent,
12138
12612
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12139
12613
  };
12140
12614
  const pendingAssistantMessage = {
12615
+ id: uuidv410(),
12141
12616
  role: "assistant",
12142
12617
  content: "...",
12143
12618
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -12167,6 +12642,8 @@ Remember: Use context from previous messages to understand follow-up questions.$
12167
12642
  }
12168
12643
  const successfulToolCalls = result.steps.filter((s) => s.type === "observation").length;
12169
12644
  const finalAssistantMessage = {
12645
+ id: pendingAssistantMessage.id,
12646
+ // Preserve the original message ID
12170
12647
  role: "assistant",
12171
12648
  content: result.finalAnswer,
12172
12649
  timestamp: pendingAssistantMessage.timestamp,
@@ -12205,8 +12682,6 @@ Remember: Use context from previous messages to understand follow-up questions.$
12205
12682
  }
12206
12683
  }
12207
12684
  console.error("Error processing message:", error);
12208
- } finally {
12209
- state.agent.off("action", stepHandler);
12210
12685
  }
12211
12686
  };
12212
12687
  const handleBashCommand = useCallback(
@@ -12228,11 +12703,13 @@ Remember: Use context from previous messages to understand follow-up questions.$
12228
12703
  isError = true;
12229
12704
  }
12230
12705
  const userMessage = {
12706
+ id: uuidv410(),
12231
12707
  role: "user",
12232
12708
  content: `$ ${command}`,
12233
12709
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
12234
12710
  };
12235
12711
  const assistantMessage = {
12712
+ id: uuidv410(),
12236
12713
  role: "assistant",
12237
12714
  content: isError ? `\u274C Error:
12238
12715
  ${output}` : output.trim() || "(no output)",
@@ -12643,7 +13120,7 @@ Custom Commands:
12643
13120
  console.clear();
12644
13121
  const model = state.session?.model || state.config?.defaultModel || "claude-sonnet";
12645
13122
  const newSession = {
12646
- id: uuidv49(),
13123
+ id: uuidv410(),
12647
13124
  name: `Session ${(/* @__PURE__ */ new Date()).toLocaleString()}`,
12648
13125
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
12649
13126
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),