@bike4mind/cli 0.2.10-fix-b4m-cli-flicker.17235 → 0.2.10-fix-cli-duplicate-chat-history.17269

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.
Files changed (2) hide show
  1. package/dist/index.js +2161 -1053
  2. package/package.json +7 -6
package/dist/index.js CHANGED
@@ -79,12 +79,13 @@ import {
79
79
  } from "./chunk-PDX44BCA.js";
80
80
 
81
81
  // src/index.tsx
82
- import React17, { useState as useState7, useEffect as useEffect3, useCallback, useRef } from "react";
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
+ import { execSync } from "child_process";
84
85
  import { v4 as uuidv49 } from "uuid";
85
86
 
86
87
  // src/components/App.tsx
87
- import React11 from "react";
88
+ import React11, { useState as useState4 } from "react";
88
89
  import { Box as Box10, Text as Text10, Static } from "ink";
89
90
 
90
91
  // src/components/StatusBar.tsx
@@ -95,7 +96,7 @@ var StatusBar = React.memo(function StatusBar2({ sessionName, model, tokenUsage
95
96
  });
96
97
 
97
98
  // src/components/InputPrompt.tsx
98
- import React5, { useState as useState2, useMemo, useEffect } from "react";
99
+ import React5, { useState as useState2, useMemo, useEffect, useRef } from "react";
99
100
  import { Box as Box4, Text as Text5, useInput as useInput2 } from "ink";
100
101
 
101
102
  // src/components/CustomTextInput.tsx
@@ -209,7 +210,8 @@ function CommandAutocomplete({ commands, selectedIndex }) {
209
210
  return /* @__PURE__ */ React3.createElement(Box2, { flexDirection: "column", marginLeft: 2, marginTop: 1 }, /* @__PURE__ */ React3.createElement(Box2, { marginBottom: 1 }, /* @__PURE__ */ React3.createElement(Text3, { dimColor: true }, commands.length === 1 ? "1 command" : `${commands.length} commands`, " \u2022 Use \u2191\u2193 to navigate, Enter to select")), commands.map((cmd, index) => {
210
211
  const args = cmd.args ? ` ${cmd.args}` : "";
211
212
  const isSelected = index === selectedIndex;
212
- return /* @__PURE__ */ React3.createElement(Box2, { key: cmd.name, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: isSelected ? "cyan" : void 0, bold: isSelected }, isSelected ? "\u25B8 " : " ", "/", cmd.name, args, " - ", cmd.description));
213
+ const sourceIcon = cmd.source === "global" ? "\u{1F3E0} " : cmd.source === "project" ? "\u{1F4C1} " : cmd.source === "built-in" ? "\u{1F527} " : "";
214
+ return /* @__PURE__ */ React3.createElement(Box2, { key: cmd.name, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: isSelected ? "cyan" : void 0, bold: isSelected }, isSelected ? "\u25B8 " : " ", sourceIcon, "/", cmd.name, args, " - ", cmd.description));
213
215
  }));
214
216
  }
215
217
 
@@ -310,7 +312,7 @@ function searchFiles(query) {
310
312
  searchPool = files;
311
313
  }
312
314
  }
313
- const fuse2 = new Fuse(searchPool, {
315
+ const fuse = new Fuse(searchPool, {
314
316
  keys: [{ name: "path", weight: 1 }],
315
317
  threshold: 0.4,
316
318
  // Allow some fuzzy matching
@@ -319,7 +321,7 @@ function searchFiles(query) {
319
321
  // Use extended search for better path matching
320
322
  useExtendedSearch: false
321
323
  });
322
- const results = fuse2.search(query);
324
+ const results = fuse.search(query);
323
325
  return results.slice(0, 20).map((result) => result.item);
324
326
  }
325
327
  function isPathWithinCwd(filePath) {
@@ -494,11 +496,61 @@ var COMMANDS = [
494
496
  name: "rewind",
495
497
  description: "Rewind conversation to a previous point",
496
498
  aliases: ["undo"]
499
+ },
500
+ {
501
+ name: "project-config",
502
+ description: "Show merged project configuration"
503
+ },
504
+ {
505
+ name: "commands",
506
+ description: "List all custom commands"
507
+ },
508
+ {
509
+ name: "commands:new",
510
+ description: "Create a new custom command",
511
+ args: "<name>"
512
+ },
513
+ {
514
+ name: "commands:reload",
515
+ description: "Reload custom commands from disk"
497
516
  }
498
517
  ];
518
+ function getAllCommandNames() {
519
+ const names = [];
520
+ for (const cmd of COMMANDS) {
521
+ names.push(cmd.name);
522
+ if (cmd.aliases) {
523
+ names.push(...cmd.aliases);
524
+ }
525
+ }
526
+ return names;
527
+ }
528
+ function isBuiltInCommand(name) {
529
+ return getAllCommandNames().includes(name);
530
+ }
531
+ function customCommandToDefinition(customCommand) {
532
+ return {
533
+ name: customCommand.name,
534
+ description: customCommand.description,
535
+ args: customCommand.argumentHint,
536
+ source: customCommand.source
537
+ };
538
+ }
539
+ function mergeCommands(customCommands) {
540
+ const builtInCommands = COMMANDS.map((cmd) => ({ ...cmd, source: "built-in" }));
541
+ const customDefinitions = customCommands.filter((cmd) => !isBuiltInCommand(cmd.name)).map(customCommandToDefinition);
542
+ const conflicts = customCommands.filter((cmd) => isBuiltInCommand(cmd.name));
543
+ if (conflicts.length > 0) {
544
+ console.warn(
545
+ "Warning: The following custom commands have names that conflict with built-in commands and will be ignored:",
546
+ conflicts.map((cmd) => cmd.name).join(", ")
547
+ );
548
+ }
549
+ return [...builtInCommands, ...customDefinitions];
550
+ }
499
551
 
500
552
  // src/utils/fuzzySearch.ts
501
- var fuse = new Fuse2(COMMANDS, {
553
+ var fuseOptions = {
502
554
  keys: [
503
555
  { name: "name", weight: 0.7 },
504
556
  // Prioritize command name
@@ -509,11 +561,12 @@ var fuse = new Fuse2(COMMANDS, {
509
561
  // 0 = perfect match, 1 = match anything
510
562
  includeScore: true,
511
563
  minMatchCharLength: 1
512
- });
513
- function searchCommands(query) {
564
+ };
565
+ function searchCommands(query, commands = COMMANDS) {
514
566
  if (!query || query.trim() === "") {
515
- return COMMANDS;
567
+ return commands;
516
568
  }
569
+ const fuse = new Fuse2(commands, fuseOptions);
517
570
  const results = fuse.search(query);
518
571
  return results.map((result) => result.item);
519
572
  }
@@ -732,17 +785,20 @@ function findAtTrigger(value) {
732
785
  }
733
786
  function InputPrompt({
734
787
  onSubmit,
788
+ onBashCommand,
735
789
  onImageDetected,
736
790
  disabled = false,
737
791
  history = [],
792
+ commands = [],
738
793
  prefillInput,
739
- onPrefillConsumed
794
+ onPrefillConsumed,
795
+ onBashModeChange
740
796
  }) {
741
797
  const [value, setValue] = useState2("");
742
798
  const [selectedIndex, setSelectedIndex] = useState2(0);
743
799
  const [historyIndex, setHistoryIndex] = useState2(-1);
744
800
  const [tempInput, setTempInput] = useState2("");
745
- const [inputKey, setInputKey] = useState2(0);
801
+ const inputKey = useRef(0);
746
802
  useEffect(() => {
747
803
  if (prefillInput) {
748
804
  setValue(prefillInput);
@@ -751,12 +807,16 @@ function InputPrompt({
751
807
  }, [prefillInput, onPrefillConsumed]);
752
808
  const [fileAutocomplete, setFileAutocomplete] = useState2(null);
753
809
  const [fileSelectedIndex, setFileSelectedIndex] = useState2(0);
810
+ const isBashMode = value.startsWith("!");
811
+ useEffect(() => {
812
+ onBashModeChange?.(isBashMode);
813
+ }, [isBashMode, onBashModeChange]);
754
814
  const shouldShowCommandAutocomplete = value.startsWith("/") && !disabled && !fileAutocomplete?.active;
755
815
  const commandQuery = shouldShowCommandAutocomplete ? value.slice(1) : "";
756
816
  const filteredCommands = useMemo(() => {
757
817
  if (!shouldShowCommandAutocomplete) return [];
758
- return searchCommands(commandQuery);
759
- }, [shouldShowCommandAutocomplete, commandQuery]);
818
+ return searchCommands(commandQuery, commands);
819
+ }, [shouldShowCommandAutocomplete, commandQuery, commands]);
760
820
  const filteredFiles = useMemo(() => {
761
821
  if (!fileAutocomplete?.active) return [];
762
822
  return searchFiles(fileAutocomplete.query);
@@ -857,6 +917,16 @@ function InputPrompt({
857
917
  onSubmit(commandText);
858
918
  return;
859
919
  }
920
+ if (isBashMode && onBashCommand) {
921
+ const command = input.slice(1).trim();
922
+ if (command) {
923
+ onBashCommand(command);
924
+ setValue("");
925
+ setHistoryIndex(-1);
926
+ setFileAutocomplete(null);
927
+ }
928
+ return;
929
+ }
860
930
  onSubmit(input);
861
931
  setValue("");
862
932
  setHistoryIndex(-1);
@@ -887,14 +957,19 @@ function InputPrompt({
887
957
  setFileAutocomplete(null);
888
958
  }
889
959
  };
890
- return /* @__PURE__ */ React5.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React5.createElement(Box4, null, /* @__PURE__ */ React5.createElement(Text5, { bold: true, color: "cyan" }, "> "), /* @__PURE__ */ React5.createElement(
960
+ const getPlaceholder = () => {
961
+ if (disabled) return "Thinking...";
962
+ if (isBashMode) return "Enter shell command to execute...";
963
+ return "Type your message, /help for commands, @file to reference, or ! for bash";
964
+ };
965
+ return /* @__PURE__ */ React5.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React5.createElement(Box4, null, /* @__PURE__ */ React5.createElement(Text5, { bold: true, color: isBashMode ? "yellow" : "cyan" }, isBashMode ? "$ " : "> "), /* @__PURE__ */ React5.createElement(
891
966
  CustomTextInput,
892
967
  {
893
- key: inputKey,
968
+ key: inputKey.current,
894
969
  value,
895
970
  onChange: handleChange,
896
971
  onSubmit: handleSubmit,
897
- placeholder: disabled ? "" : "Type your message, /help for commands, or @file to reference",
972
+ placeholder: getPlaceholder(),
898
973
  showCursor: !disabled
899
974
  }
900
975
  )), shouldShowCommandAutocomplete && /* @__PURE__ */ React5.createElement(CommandAutocomplete, { commands: filteredCommands, selectedIndex }), fileAutocomplete?.active && /* @__PURE__ */ React5.createElement(FileAutocomplete, { files: filteredFiles, selectedIndex: fileSelectedIndex, query: fileAutocomplete.query }));
@@ -918,6 +993,16 @@ var useCliStore = create((set) => ({
918
993
  // Session state
919
994
  session: null,
920
995
  setSession: (session) => set({ session }),
996
+ addMessage: (message) => set((state) => {
997
+ if (!state.session) return state;
998
+ return {
999
+ session: {
1000
+ ...state.session,
1001
+ messages: [...state.session.messages, message],
1002
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1003
+ }
1004
+ };
1005
+ }),
921
1006
  // Pending messages
922
1007
  pendingMessages: [],
923
1008
  addPendingMessage: (message) => set((state) => ({ pendingMessages: [...state.pendingMessages, message] })),
@@ -1378,9 +1463,11 @@ function hasFileReferences(message) {
1378
1463
  function App({
1379
1464
  onMessage,
1380
1465
  onCommand,
1466
+ onBashCommand,
1381
1467
  onPermissionResponse,
1382
1468
  onImageDetected,
1383
1469
  commandHistory = [],
1470
+ commands = [],
1384
1471
  config,
1385
1472
  availableModels = [],
1386
1473
  onSaveConfig,
@@ -1398,6 +1485,7 @@ function App({
1398
1485
  const setShowConfigEditor = useCliStore((state) => state.setShowConfigEditor);
1399
1486
  const exitRequested = useCliStore((state) => state.exitRequested);
1400
1487
  const setIsThinking = useCliStore((state) => state.setIsThinking);
1488
+ const [isBashMode, setIsBashMode] = useState4(false);
1401
1489
  const handleSubmit = React11.useCallback(
1402
1490
  async (input) => {
1403
1491
  const trimmed = input.trim();
@@ -1435,7 +1523,7 @@ ${errorBlock}`;
1435
1523
  onSave: onSaveConfig,
1436
1524
  onClose: () => setShowConfigEditor(false)
1437
1525
  }
1438
- )) : permissionPrompt ? /* @__PURE__ */ React11.createElement(Box10, { flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1526
+ )) : /* @__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 })))), permissionPrompt && /* @__PURE__ */ React11.createElement(Box10, { flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1439
1527
  PermissionPrompt,
1440
1528
  {
1441
1529
  toolName: permissionPrompt.toolName,
@@ -1444,15 +1532,18 @@ ${errorBlock}`;
1444
1532
  canBeTrusted: permissionPrompt.canBeTrusted,
1445
1533
  onResponse: onPermissionResponse
1446
1534
  }
1447
- )) : /* @__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: "cyan", paddingX: 1 }, /* @__PURE__ */ React11.createElement(
1535
+ )), /* @__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(
1448
1536
  InputPrompt,
1449
1537
  {
1450
1538
  onSubmit: handleSubmit,
1539
+ onBashCommand,
1451
1540
  onImageDetected,
1452
1541
  disabled: isThinking,
1453
1542
  history: commandHistory,
1543
+ commands,
1454
1544
  prefillInput,
1455
- onPrefillConsumed
1545
+ onPrefillConsumed,
1546
+ onBashModeChange: setIsBashMode
1456
1547
  }
1457
1548
  )), /* @__PURE__ */ React11.createElement(StatusBar, { sessionName, model: currentModel, tokenUsage: totalTokens })));
1458
1549
  }
@@ -1530,12 +1621,12 @@ function TrustLocationSelector({ inProject, onSelect, onCancel }) {
1530
1621
  }
1531
1622
 
1532
1623
  // src/components/RewindSelector.tsx
1533
- import React14, { useState as useState4 } from "react";
1624
+ import React14, { useState as useState5 } from "react";
1534
1625
  import { Box as Box13, Text as Text13, useInput as useInput4 } from "ink";
1535
1626
  import SelectInput3 from "ink-select-input";
1536
1627
  function RewindSelector({ messages, onSelect, onCancel }) {
1537
- const [step, setStep] = useState4("selection");
1538
- const [selectedMessageIndex, setSelectedMessageIndex] = useState4(null);
1628
+ const [step, setStep] = useState5("selection");
1629
+ const [selectedMessageIndex, setSelectedMessageIndex] = useState5(null);
1539
1630
  useInput4((input, key) => {
1540
1631
  if (key.escape) {
1541
1632
  if (step === "confirmation") {
@@ -1599,12 +1690,12 @@ function RewindSelector({ messages, onSelect, onCancel }) {
1599
1690
  }
1600
1691
 
1601
1692
  // src/components/SessionSelector.tsx
1602
- import React15, { useState as useState5 } from "react";
1693
+ import React15, { useState as useState6 } from "react";
1603
1694
  import { Box as Box14, Text as Text14, useInput as useInput5 } from "ink";
1604
1695
  import SelectInput4 from "ink-select-input";
1605
1696
  function SessionSelector({ sessions, currentSession, onSelect, onCancel }) {
1606
- const [step, setStep] = useState5("selection");
1607
- const [selectedSession, setSelectedSession] = useState5(null);
1697
+ const [step, setStep] = useState6("selection");
1698
+ const [selectedSession, setSelectedSession] = useState6(null);
1608
1699
  useInput5((input, key) => {
1609
1700
  if (key.escape) {
1610
1701
  if (step === "confirmation") {
@@ -1662,7 +1753,7 @@ function SessionSelector({ sessions, currentSession, onSelect, onCancel }) {
1662
1753
  }
1663
1754
 
1664
1755
  // src/components/LoginFlow.tsx
1665
- import React16, { useState as useState6, useEffect as useEffect2 } from "react";
1756
+ import React16, { useState as useState7, useEffect as useEffect2 } from "react";
1666
1757
  import { Box as Box15, Text as Text15 } from "ink";
1667
1758
  import Spinner2 from "ink-spinner";
1668
1759
  import jwt from "jsonwebtoken";
@@ -1779,10 +1870,10 @@ var OAuthClient = class {
1779
1870
 
1780
1871
  // src/components/LoginFlow.tsx
1781
1872
  function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, onError }) {
1782
- const [status, setStatus] = useState6("initiating");
1783
- const [deviceFlow, setDeviceFlow] = useState6(null);
1784
- const [statusMessage, setStatusMessage] = useState6("Initiating device authorization...");
1785
- const [error, setError] = useState6(null);
1873
+ const [status, setStatus] = useState7("initiating");
1874
+ const [deviceFlow, setDeviceFlow] = useState7(null);
1875
+ const [statusMessage, setStatusMessage] = useState7("Initiating device authorization...");
1876
+ const [error, setError] = useState7(null);
1786
1877
  useEffect2(() => {
1787
1878
  const runLoginFlow = async () => {
1788
1879
  const oauth = new OAuthClient(apiUrl);
@@ -2672,6 +2763,261 @@ var CommandHistoryStore = class {
2672
2763
  }
2673
2764
  };
2674
2765
 
2766
+ // src/storage/CustomCommandStore.ts
2767
+ import fs6 from "fs/promises";
2768
+ import path6 from "path";
2769
+ import os from "os";
2770
+
2771
+ // src/utils/commandParser.ts
2772
+ import matter from "gray-matter";
2773
+ import { z as z2 } from "zod";
2774
+ var FrontmatterSchema = z2.object({
2775
+ description: z2.string().optional(),
2776
+ "argument-hint": z2.string().optional(),
2777
+ model: z2.string().optional(),
2778
+ // Future fields (ignored for now):
2779
+ "allowed-tools": z2.any().optional(),
2780
+ context: z2.any().optional(),
2781
+ agent: z2.any().optional(),
2782
+ "disable-model-invocation": z2.any().optional(),
2783
+ hooks: z2.any().optional()
2784
+ });
2785
+ function extractDescriptionFromBody(body) {
2786
+ const lines = body.trim().split("\n");
2787
+ for (const line of lines) {
2788
+ const trimmed = line.trim();
2789
+ if (trimmed && !trimmed.startsWith("#")) {
2790
+ return trimmed.length > 100 ? trimmed.substring(0, 97) + "..." : trimmed;
2791
+ }
2792
+ }
2793
+ return "Custom command";
2794
+ }
2795
+ function parseCommandFile(fileContent, filePath, commandName, source) {
2796
+ try {
2797
+ const { data: frontmatter, content: body } = matter(fileContent);
2798
+ const validationResult = FrontmatterSchema.safeParse(frontmatter);
2799
+ if (!validationResult.success) {
2800
+ console.warn(
2801
+ `Warning: Invalid frontmatter in ${filePath}:`,
2802
+ validationResult.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")
2803
+ );
2804
+ }
2805
+ const validFrontmatter = validationResult.success ? validationResult.data : {};
2806
+ const description = validFrontmatter.description || extractDescriptionFromBody(body) || "Custom command";
2807
+ return {
2808
+ name: commandName,
2809
+ description,
2810
+ argumentHint: validFrontmatter["argument-hint"],
2811
+ model: validFrontmatter.model,
2812
+ body: body.trim(),
2813
+ source,
2814
+ filePath
2815
+ };
2816
+ } catch (error) {
2817
+ throw new Error(
2818
+ `Failed to parse command file ${filePath}: ${error instanceof Error ? error.message : String(error)}`
2819
+ );
2820
+ }
2821
+ }
2822
+ function isValidCommandName(name) {
2823
+ if (!name || name.trim().length === 0) {
2824
+ return false;
2825
+ }
2826
+ const validPattern = /^[a-z0-9-_:]+$/i;
2827
+ return validPattern.test(name);
2828
+ }
2829
+ function extractCommandName(filename) {
2830
+ if (!filename.endsWith(".md")) {
2831
+ return null;
2832
+ }
2833
+ const name = filename.slice(0, -3);
2834
+ if (!isValidCommandName(name)) {
2835
+ return null;
2836
+ }
2837
+ return name;
2838
+ }
2839
+
2840
+ // src/storage/CustomCommandStore.ts
2841
+ var CustomCommandStore = class {
2842
+ constructor(projectRoot) {
2843
+ this.commands = /* @__PURE__ */ new Map();
2844
+ this.globalCommandsDir = path6.join(os.homedir(), ".bike4mind", "commands");
2845
+ this.projectCommandsDir = path6.join(projectRoot || process.cwd(), ".bike4mind", "commands");
2846
+ }
2847
+ /**
2848
+ * Loads all custom commands from both global and project directories
2849
+ * Project commands override global commands with the same name
2850
+ */
2851
+ async loadCommands() {
2852
+ this.commands.clear();
2853
+ await this.loadCommandsFromDirectory(this.globalCommandsDir, "global");
2854
+ await this.loadCommandsFromDirectory(this.projectCommandsDir, "project");
2855
+ }
2856
+ /**
2857
+ * Recursively scans a directory for .md files and loads them as commands
2858
+ *
2859
+ * @param directory - Directory to scan
2860
+ * @param source - Source identifier ('global' or 'project')
2861
+ */
2862
+ async loadCommandsFromDirectory(directory, source) {
2863
+ try {
2864
+ const stats = await fs6.stat(directory);
2865
+ if (!stats.isDirectory()) {
2866
+ return;
2867
+ }
2868
+ const commandFiles = await this.findCommandFiles(directory);
2869
+ for (const filePath of commandFiles) {
2870
+ try {
2871
+ await this.loadCommandFile(filePath, source);
2872
+ } catch (error) {
2873
+ console.warn(
2874
+ `Failed to load command from ${filePath}:`,
2875
+ error instanceof Error ? error.message : String(error)
2876
+ );
2877
+ }
2878
+ }
2879
+ } catch (error) {
2880
+ if (error.code !== "ENOENT") {
2881
+ console.warn(
2882
+ `Error accessing ${source} commands directory ${directory}:`,
2883
+ error instanceof Error ? error.message : String(error)
2884
+ );
2885
+ }
2886
+ }
2887
+ }
2888
+ /**
2889
+ * Recursively finds all .md files in a directory
2890
+ *
2891
+ * @param directory - Directory to search
2892
+ * @returns Array of full file paths to .md files
2893
+ */
2894
+ async findCommandFiles(directory) {
2895
+ const files = [];
2896
+ try {
2897
+ const entries = await fs6.readdir(directory, { withFileTypes: true });
2898
+ for (const entry of entries) {
2899
+ const fullPath = path6.join(directory, entry.name);
2900
+ if (entry.isDirectory()) {
2901
+ const subFiles = await this.findCommandFiles(fullPath);
2902
+ files.push(...subFiles);
2903
+ } else if (entry.isFile() && entry.name.endsWith(".md")) {
2904
+ files.push(fullPath);
2905
+ }
2906
+ }
2907
+ } catch (error) {
2908
+ console.warn(`Error reading directory ${directory}:`, error instanceof Error ? error.message : String(error));
2909
+ }
2910
+ return files;
2911
+ }
2912
+ /**
2913
+ * Loads a single command file
2914
+ *
2915
+ * @param filePath - Full path to the command file
2916
+ * @param source - Source identifier ('global' or 'project')
2917
+ */
2918
+ async loadCommandFile(filePath, source) {
2919
+ const filename = path6.basename(filePath);
2920
+ const commandName = extractCommandName(filename);
2921
+ if (!commandName) {
2922
+ console.warn(`Invalid command filename: ${filename} (must end with .md and have valid name)`);
2923
+ return;
2924
+ }
2925
+ const fileContent = await fs6.readFile(filePath, "utf-8");
2926
+ const command = parseCommandFile(fileContent, filePath, commandName, source);
2927
+ const existing = this.commands.get(commandName);
2928
+ if (existing && existing.source === "project" && source === "global") {
2929
+ return;
2930
+ }
2931
+ this.commands.set(commandName, command);
2932
+ }
2933
+ /**
2934
+ * Gets a command by name
2935
+ *
2936
+ * @param name - Command name
2937
+ * @returns CustomCommand if found, undefined otherwise
2938
+ */
2939
+ getCommand(name) {
2940
+ return this.commands.get(name);
2941
+ }
2942
+ /**
2943
+ * Gets all loaded commands
2944
+ *
2945
+ * @returns Array of all custom commands
2946
+ */
2947
+ getAllCommands() {
2948
+ return Array.from(this.commands.values());
2949
+ }
2950
+ /**
2951
+ * Gets commands filtered by source
2952
+ *
2953
+ * @param source - Filter by 'global' or 'project'
2954
+ * @returns Array of commands from the specified source
2955
+ */
2956
+ getCommandsBySource(source) {
2957
+ return this.getAllCommands().filter((cmd) => cmd.source === source);
2958
+ }
2959
+ /**
2960
+ * Checks if a command name exists
2961
+ *
2962
+ * @param name - Command name to check
2963
+ * @returns true if command exists
2964
+ */
2965
+ hasCommand(name) {
2966
+ return this.commands.has(name);
2967
+ }
2968
+ /**
2969
+ * Gets the number of loaded commands
2970
+ *
2971
+ * @returns Number of custom commands
2972
+ */
2973
+ getCommandCount() {
2974
+ return this.commands.size;
2975
+ }
2976
+ /**
2977
+ * Reloads all commands from directories
2978
+ * Useful for the /commands:reload command
2979
+ */
2980
+ async reloadCommands() {
2981
+ await this.loadCommands();
2982
+ }
2983
+ /**
2984
+ * Creates a new command file from a template
2985
+ *
2986
+ * @param name - Command name
2987
+ * @param isGlobal - If true, creates in global directory, otherwise project directory
2988
+ * @returns Path to the created file
2989
+ */
2990
+ async createCommandFile(name, isGlobal = false) {
2991
+ const targetDir = isGlobal ? this.globalCommandsDir : this.projectCommandsDir;
2992
+ const filePath = path6.join(targetDir, `${name}.md`);
2993
+ try {
2994
+ await fs6.access(filePath);
2995
+ throw new Error(`Command file already exists: ${filePath}`);
2996
+ } catch (error) {
2997
+ if (error.code !== "ENOENT") {
2998
+ throw error;
2999
+ }
3000
+ }
3001
+ await fs6.mkdir(targetDir, { recursive: true });
3002
+ const template = `---
3003
+ description: ${name} command
3004
+ argument-hint: [args]
3005
+ ---
3006
+
3007
+ # ${name}
3008
+
3009
+ Replace this with your command template.
3010
+
3011
+ You can use:
3012
+ - $ARGUMENTS for all arguments
3013
+ - $1, $2, etc. for positional arguments
3014
+ - @filename for file references
3015
+ `;
3016
+ await fs6.writeFile(filePath, template, "utf-8");
3017
+ return filePath;
3018
+ }
3019
+ };
3020
+
2675
3021
  // ../../b4m-core/packages/agents/src/ReActAgent.ts
2676
3022
  import { EventEmitter } from "events";
2677
3023
  var ReActAgent = class extends EventEmitter {
@@ -2985,38 +3331,38 @@ Remember: You are an autonomous AGENT. Act independently and solve problems proa
2985
3331
  // ../../b4m-core/packages/services/dist/src/referService/generateCodes.js
2986
3332
  import { randomBytes } from "crypto";
2987
3333
  import range from "lodash/range.js";
2988
- import { z as z2 } from "zod";
2989
- var generateReferralCodesSchema = z2.object({
2990
- count: z2.number().optional(),
2991
- unlimitedUse: z2.boolean().optional(),
2992
- expiresAt: z2.date().optional()
3334
+ import { z as z3 } from "zod";
3335
+ var generateReferralCodesSchema = z3.object({
3336
+ count: z3.number().optional(),
3337
+ unlimitedUse: z3.boolean().optional(),
3338
+ expiresAt: z3.date().optional()
2993
3339
  });
2994
3340
 
2995
3341
  // ../../b4m-core/packages/services/dist/src/referService/delete.js
2996
- import { z as z3 } from "zod";
2997
- var deleteInviteCodesSchema = z3.object({
2998
- ids: z3.array(z3.string())
3342
+ import { z as z4 } from "zod";
3343
+ var deleteInviteCodesSchema = z4.object({
3344
+ ids: z4.array(z4.string())
2999
3345
  });
3000
3346
 
3001
3347
  // ../../b4m-core/packages/services/dist/src/userService/login.js
3002
- import { z as z4 } from "zod";
3348
+ import { z as z5 } from "zod";
3003
3349
  import bcrypt from "bcryptjs";
3004
- var loginUserSchema = z4.object({
3005
- usernameOrEmail: z4.string(),
3006
- password: z4.string(),
3007
- metadata: z4.object({
3008
- loginTime: z4.date(),
3009
- userAgent: z4.string(),
3010
- browser: z4.string(),
3011
- operatingSystem: z4.string(),
3012
- deviceType: z4.string(),
3013
- screenResolution: z4.string(),
3014
- viewportSize: z4.string(),
3015
- colorDepth: z4.number(),
3016
- pixelDepth: z4.number(),
3017
- devicePixelRatio: z4.number(),
3018
- ip: z4.string().optional().default(""),
3019
- location: z4.string().optional()
3350
+ var loginUserSchema = z5.object({
3351
+ usernameOrEmail: z5.string(),
3352
+ password: z5.string(),
3353
+ metadata: z5.object({
3354
+ loginTime: z5.date(),
3355
+ userAgent: z5.string(),
3356
+ browser: z5.string(),
3357
+ operatingSystem: z5.string(),
3358
+ deviceType: z5.string(),
3359
+ screenResolution: z5.string(),
3360
+ viewportSize: z5.string(),
3361
+ colorDepth: z5.number(),
3362
+ pixelDepth: z5.number(),
3363
+ devicePixelRatio: z5.number(),
3364
+ ip: z5.string().optional().default(""),
3365
+ location: z5.string().optional()
3020
3366
  }).optional()
3021
3367
  });
3022
3368
 
@@ -3026,78 +3372,78 @@ import escapeRegExp from "lodash/escapeRegExp.js";
3026
3372
 
3027
3373
  // ../../b4m-core/packages/services/dist/src/userService/forgotPassword.js
3028
3374
  import { randomUUID } from "crypto";
3029
- import { z as z5 } from "zod";
3030
- var forgotPasswordUserSchema = z5.object({
3031
- email: z5.string().email()
3375
+ import { z as z6 } from "zod";
3376
+ var forgotPasswordUserSchema = z6.object({
3377
+ email: z6.string().email()
3032
3378
  });
3033
3379
 
3034
3380
  // ../../b4m-core/packages/services/dist/src/userService/update.js
3035
3381
  import bcrypt3 from "bcryptjs";
3036
- import { z as z6 } from "zod";
3037
- var updateUserSchema = z6.object({
3038
- name: z6.string().optional(),
3039
- username: z6.string().optional(),
3382
+ import { z as z7 } from "zod";
3383
+ var updateUserSchema = z7.object({
3384
+ name: z7.string().optional(),
3385
+ username: z7.string().optional(),
3040
3386
  // email field removed - users must use the secure email change verification flow
3041
3387
  // See requestEmailChange and verifyEmailChange in userService
3042
- password: z6.string().nullable().optional(),
3043
- team: z6.string().nullable().optional(),
3044
- role: z6.string().nullable().optional(),
3045
- phone: z6.string().nullable().optional(),
3046
- preferredLanguage: z6.string().nullable().optional(),
3047
- preferredContact: z6.string().nullable().optional(),
3048
- preferredVoice: z6.string().nullable().optional(),
3049
- tshirtSize: z6.string().nullable().optional(),
3050
- geoLocation: z6.string().nullable().optional(),
3051
- lastNotebookId: z6.string().nullable().optional(),
3052
- tags: z6.array(z6.string()).nullable().optional(),
3053
- lastCreditsPurchasedAt: z6.date().nullable().optional(),
3054
- systemFiles: z6.array(z6.object({
3055
- fileId: z6.string(),
3056
- enabled: z6.boolean()
3388
+ password: z7.string().nullable().optional(),
3389
+ team: z7.string().nullable().optional(),
3390
+ role: z7.string().nullable().optional(),
3391
+ phone: z7.string().nullable().optional(),
3392
+ preferredLanguage: z7.string().nullable().optional(),
3393
+ preferredContact: z7.string().nullable().optional(),
3394
+ preferredVoice: z7.string().nullable().optional(),
3395
+ tshirtSize: z7.string().nullable().optional(),
3396
+ geoLocation: z7.string().nullable().optional(),
3397
+ lastNotebookId: z7.string().nullable().optional(),
3398
+ tags: z7.array(z7.string()).nullable().optional(),
3399
+ lastCreditsPurchasedAt: z7.date().nullable().optional(),
3400
+ systemFiles: z7.array(z7.object({
3401
+ fileId: z7.string(),
3402
+ enabled: z7.boolean()
3057
3403
  })).nullable().optional(),
3058
- securityQuestions: z6.array(z6.object({ question: z6.string(), answer: z6.string() })).nullable().optional(),
3059
- photoUrl: z6.string().nullable().optional(),
3060
- showCreditsUsed: z6.boolean().optional()
3404
+ securityQuestions: z7.array(z7.object({ question: z7.string(), answer: z7.string() })).nullable().optional(),
3405
+ photoUrl: z7.string().nullable().optional(),
3406
+ showCreditsUsed: z7.boolean().optional()
3061
3407
  });
3062
3408
 
3063
3409
  // ../../b4m-core/packages/services/dist/src/userService/adminUpdate.js
3064
- import { z as z8 } from "zod";
3410
+ import { z as z9 } from "zod";
3065
3411
 
3066
3412
  // ../../b4m-core/packages/services/dist/src/friendshipService/sendFriendRequest.js
3067
- import { z as z7 } from "zod";
3068
- var sendFriendRequestSchema = z7.object({
3069
- requesterId: z7.string(),
3070
- recipientId: z7.string(),
3071
- message: z7.string().optional()
3413
+ import { z as z8 } from "zod";
3414
+ var sendFriendRequestSchema = z8.object({
3415
+ requesterId: z8.string(),
3416
+ recipientId: z8.string(),
3417
+ message: z8.string().optional()
3072
3418
  });
3073
3419
 
3074
3420
  // ../../b4m-core/packages/services/dist/src/userService/adminUpdate.js
3075
3421
  var adminUpdateUserSchema = updateUserSchema.extend({
3076
- id: z8.string(),
3422
+ id: z9.string(),
3077
3423
  // Admins can directly update email addresses without verification
3078
- email: z8.string().email().optional(),
3079
- role: z8.string().optional().nullable(),
3080
- isAdmin: z8.boolean().optional(),
3081
- organizationId: z8.string().optional().nullable(),
3082
- storageLimit: z8.number().optional(),
3083
- currentCredits: z8.number().optional(),
3084
- isBanned: z8.boolean().optional(),
3085
- isModerated: z8.boolean().optional(),
3086
- subscribedUntil: z8.string().optional().nullable(),
3087
- systemFiles: z8.array(z8.object({ fileId: z8.string(), enabled: z8.boolean() })).optional(),
3088
- level: z8.enum(["DemoUser", "PaidUser", "VIPUser", "ManagerUser", "AdminUser"]).optional(),
3089
- lastNotebookId: z8.string().optional().nullable(),
3090
- userNotes: z8.array(z8.object({ timestamp: z8.string(), note: z8.string(), userName: z8.string() })).optional(),
3091
- numReferralsAvailable: z8.number().optional()
3424
+ email: z9.string().email().optional(),
3425
+ role: z9.string().optional().nullable(),
3426
+ isAdmin: z9.boolean().optional(),
3427
+ organizationId: z9.string().optional().nullable(),
3428
+ storageLimit: z9.number().optional(),
3429
+ currentCredits: z9.number().optional(),
3430
+ isBanned: z9.boolean().optional(),
3431
+ isModerated: z9.boolean().optional(),
3432
+ subscribedUntil: z9.string().optional().nullable(),
3433
+ systemFiles: z9.array(z9.object({ fileId: z9.string(), enabled: z9.boolean() })).optional(),
3434
+ level: z9.enum(["DemoUser", "PaidUser", "VIPUser", "ManagerUser", "AdminUser"]).optional(),
3435
+ lastNotebookId: z9.string().optional().nullable(),
3436
+ userNotes: z9.array(z9.object({ timestamp: z9.string(), note: z9.string(), userName: z9.string() })).optional(),
3437
+ numReferralsAvailable: z9.number().optional()
3092
3438
  });
3093
3439
 
3094
3440
  // ../../b4m-core/packages/services/dist/src/userService/register.js
3095
- import { z as z10 } from "zod";
3441
+ import { z as z11 } from "zod";
3096
3442
  import bcrypt4 from "bcryptjs";
3097
3443
 
3098
3444
  // ../../b4m-core/packages/services/dist/src/creditService/addCredits.js
3099
- import { z as z9 } from "zod";
3100
- var AddCreditsSchema = z9.discriminatedUnion("type", [
3445
+ import { z as z10 } from "zod";
3446
+ var AddCreditsSchema = z10.discriminatedUnion("type", [
3101
3447
  PurchaseTransaction.omit({ createdAt: true, updatedAt: true }),
3102
3448
  SubscriptionCreditTransaction.omit({ createdAt: true, updatedAt: true }),
3103
3449
  GenericCreditAddTransaction.omit({ createdAt: true, updatedAt: true }),
@@ -3105,57 +3451,57 @@ var AddCreditsSchema = z9.discriminatedUnion("type", [
3105
3451
  ]);
3106
3452
 
3107
3453
  // ../../b4m-core/packages/services/dist/src/userService/register.js
3108
- var registerUserSchema = z10.object({
3109
- username: z10.string(),
3110
- email: z10.string(),
3111
- name: z10.string(),
3112
- inviteCode: z10.string(),
3113
- password: z10.string(),
3114
- metadata: z10.object({
3115
- loginTime: z10.date(),
3116
- userAgent: z10.string(),
3117
- browser: z10.string(),
3118
- operatingSystem: z10.string(),
3119
- deviceType: z10.string(),
3120
- screenResolution: z10.string(),
3121
- viewportSize: z10.string(),
3122
- colorDepth: z10.number(),
3123
- pixelDepth: z10.number(),
3124
- devicePixelRatio: z10.number(),
3125
- ip: z10.string().optional().default(""),
3126
- location: z10.string().optional()
3454
+ var registerUserSchema = z11.object({
3455
+ username: z11.string(),
3456
+ email: z11.string(),
3457
+ name: z11.string(),
3458
+ inviteCode: z11.string(),
3459
+ password: z11.string(),
3460
+ metadata: z11.object({
3461
+ loginTime: z11.date(),
3462
+ userAgent: z11.string(),
3463
+ browser: z11.string(),
3464
+ operatingSystem: z11.string(),
3465
+ deviceType: z11.string(),
3466
+ screenResolution: z11.string(),
3467
+ viewportSize: z11.string(),
3468
+ colorDepth: z11.number(),
3469
+ pixelDepth: z11.number(),
3470
+ devicePixelRatio: z11.number(),
3471
+ ip: z11.string().optional().default(""),
3472
+ location: z11.string().optional()
3127
3473
  }).optional()
3128
3474
  });
3129
3475
 
3130
3476
  // ../../b4m-core/packages/services/dist/src/userService/adminDelete.js
3131
- import { z as z11 } from "zod";
3132
- var adminDeleteUserSchema = z11.object({
3133
- id: z11.string()
3477
+ import { z as z12 } from "zod";
3478
+ var adminDeleteUserSchema = z12.object({
3479
+ id: z12.string()
3134
3480
  });
3135
3481
 
3136
3482
  // ../../b4m-core/packages/services/dist/src/userService/searchUserCollection.js
3137
- import { z as z12 } from "zod";
3138
- var searchUserCollectionSchema = z12.object({
3139
- userId: z12.string(),
3140
- page: z12.coerce.number().optional().default(1),
3141
- limit: z12.coerce.number().optional().default(10),
3142
- search: z12.string().optional().default(""),
3143
- type: z12.nativeEnum(CollectionType).optional()
3483
+ import { z as z13 } from "zod";
3484
+ var searchUserCollectionSchema = z13.object({
3485
+ userId: z13.string(),
3486
+ page: z13.coerce.number().optional().default(1),
3487
+ limit: z13.coerce.number().optional().default(10),
3488
+ search: z13.string().optional().default(""),
3489
+ type: z13.nativeEnum(CollectionType).optional()
3144
3490
  });
3145
3491
 
3146
3492
  // ../../b4m-core/packages/services/dist/src/userService/recalculateUserStorage.js
3147
- import { z as z13 } from "zod";
3148
- var recalculateUserStorageSchema = z13.object({
3493
+ import { z as z14 } from "zod";
3494
+ var recalculateUserStorageSchema = z14.object({
3149
3495
  /**
3150
3496
  * The user to recalculate the storage for
3151
3497
  */
3152
- userId: z13.string()
3498
+ userId: z14.string()
3153
3499
  });
3154
3500
 
3155
3501
  // ../../b4m-core/packages/services/dist/src/userService/listRecentActivities.js
3156
- import { z as z14 } from "zod";
3157
- var listRecentActivitiesSchema = z14.object({
3158
- coverage: z14.enum(["all", "important"]).default("important")
3502
+ import { z as z15 } from "zod";
3503
+ var listRecentActivitiesSchema = z15.object({
3504
+ coverage: z15.enum(["all", "important"]).default("important")
3159
3505
  });
3160
3506
  var IMPORTANT_COUNTER_NAMES = [
3161
3507
  SessionEvents.CREATE_SESSION,
@@ -3169,82 +3515,82 @@ var IMPORTANT_COUNTER_NAMES = [
3169
3515
 
3170
3516
  // ../../b4m-core/packages/services/dist/src/userService/sendEmailVerification.js
3171
3517
  import { randomUUID as randomUUID2 } from "crypto";
3172
- import { z as z15 } from "zod";
3173
- var sendEmailVerificationSchema = z15.object({
3174
- userId: z15.string()
3518
+ import { z as z16 } from "zod";
3519
+ var sendEmailVerificationSchema = z16.object({
3520
+ userId: z16.string()
3175
3521
  });
3176
3522
 
3177
3523
  // ../../b4m-core/packages/services/dist/src/userService/verifyEmailToken.js
3178
- import { z as z16 } from "zod";
3524
+ import { z as z17 } from "zod";
3179
3525
 
3180
3526
  // ../../b4m-core/packages/services/dist/src/utils/crypto.js
3181
3527
  import crypto from "crypto";
3182
3528
 
3183
3529
  // ../../b4m-core/packages/services/dist/src/userService/verifyEmailToken.js
3184
- var verifyEmailTokenSchema = z16.object({
3185
- token: z16.string()
3530
+ var verifyEmailTokenSchema = z17.object({
3531
+ token: z17.string()
3186
3532
  });
3187
3533
 
3188
3534
  // ../../b4m-core/packages/services/dist/src/userService/resendEmailVerification.js
3189
3535
  import { randomUUID as randomUUID3 } from "crypto";
3190
- import { z as z17 } from "zod";
3191
- var resendEmailVerificationSchema = z17.object({
3192
- userId: z17.string()
3536
+ import { z as z18 } from "zod";
3537
+ var resendEmailVerificationSchema = z18.object({
3538
+ userId: z18.string()
3193
3539
  });
3194
3540
 
3195
3541
  // ../../b4m-core/packages/services/dist/src/userService/requestEmailChange.js
3196
3542
  import { randomUUID as randomUUID4 } from "crypto";
3197
- import { z as z18 } from "zod";
3198
- var requestEmailChangeSchema = z18.object({
3199
- userId: z18.string(),
3200
- newEmail: z18.string().email(),
3201
- password: z18.string()
3543
+ import { z as z19 } from "zod";
3544
+ var requestEmailChangeSchema = z19.object({
3545
+ userId: z19.string(),
3546
+ newEmail: z19.string().email(),
3547
+ password: z19.string()
3202
3548
  });
3203
3549
 
3204
3550
  // ../../b4m-core/packages/services/dist/src/userService/verifyEmailChange.js
3205
- import { z as z19 } from "zod";
3206
- var verifyEmailChangeSchema = z19.object({
3207
- token: z19.string()
3551
+ import { z as z20 } from "zod";
3552
+ var verifyEmailChangeSchema = z20.object({
3553
+ token: z20.string()
3208
3554
  });
3209
3555
 
3210
3556
  // ../../b4m-core/packages/services/dist/src/userService/cancelEmailChange.js
3211
- import { z as z20 } from "zod";
3212
- var cancelEmailChangeSchema = z20.object({
3213
- userId: z20.string()
3557
+ import { z as z21 } from "zod";
3558
+ var cancelEmailChangeSchema = z21.object({
3559
+ userId: z21.string()
3214
3560
  });
3215
3561
 
3216
3562
  // ../../b4m-core/packages/services/dist/src/userApiKeyService/create.js
3217
3563
  import { randomBytes as randomBytes2 } from "crypto";
3218
3564
  import bcrypt5 from "bcryptjs";
3219
- import { z as z21 } from "zod";
3220
- var createUserApiKeySchema = z21.object({
3221
- name: z21.string().min(1).max(100),
3222
- scopes: z21.array(z21.nativeEnum(ApiKeyScope)).min(1),
3223
- expiresAt: z21.date().optional(),
3224
- rateLimit: z21.object({
3225
- requestsPerMinute: z21.number().min(1).max(1e3).default(60),
3226
- requestsPerDay: z21.number().min(1).max(1e4).default(1e3)
3565
+ import { z as z22 } from "zod";
3566
+ var createUserApiKeySchema = z22.object({
3567
+ name: z22.string().min(1).max(100),
3568
+ scopes: z22.array(z22.nativeEnum(ApiKeyScope)).min(1),
3569
+ expiresAt: z22.date().optional(),
3570
+ rateLimit: z22.object({
3571
+ requestsPerMinute: z22.number().min(1).max(1e3).default(60),
3572
+ requestsPerDay: z22.number().min(1).max(1e4).default(1e3)
3227
3573
  }).optional(),
3228
- metadata: z21.object({
3229
- clientIP: z21.string().optional(),
3230
- userAgent: z21.string().optional(),
3231
- createdFrom: z21.enum(["dashboard", "cli", "api"])
3574
+ metadata: z22.object({
3575
+ clientIP: z22.string().optional(),
3576
+ userAgent: z22.string().optional(),
3577
+ createdFrom: z22.enum(["dashboard", "cli", "api"])
3232
3578
  })
3233
3579
  });
3234
3580
 
3235
3581
  // ../../b4m-core/packages/services/dist/src/userApiKeyService/revoke.js
3236
- import { z as z22 } from "zod";
3237
- var revokeUserApiKeySchema = z22.object({
3238
- keyId: z22.string(),
3239
- reason: z22.string().optional()
3582
+ import { z as z23 } from "zod";
3583
+ var revokeUserApiKeySchema = z23.object({
3584
+ keyId: z23.string(),
3585
+ reason: z23.string().optional()
3240
3586
  });
3241
3587
 
3242
3588
  // ../../b4m-core/packages/services/dist/src/userApiKeyService/rotate.js
3243
3589
  import { randomBytes as randomBytes3 } from "crypto";
3244
3590
  import bcrypt6 from "bcryptjs";
3245
- import { z as z23 } from "zod";
3246
- var rotateUserApiKeySchema = z23.object({
3247
- keyId: z23.string()
3591
+ import { z as z24 } from "zod";
3592
+ var rotateUserApiKeySchema = z24.object({
3593
+ keyId: z24.string()
3248
3594
  });
3249
3595
 
3250
3596
  // ../../b4m-core/packages/services/dist/src/userApiKeyService/validate.js
@@ -3391,29 +3737,29 @@ var EVENT_GROUPS = [
3391
3737
  ];
3392
3738
 
3393
3739
  // ../../b4m-core/packages/services/dist/src/countersService/generateReport.js
3394
- import { z as z25 } from "zod";
3740
+ import { z as z26 } from "zod";
3395
3741
 
3396
3742
  // ../../b4m-core/packages/services/dist/src/countersService/getAllCounterFrom24Hours.js
3397
- import { z as z24 } from "zod";
3743
+ import { z as z25 } from "zod";
3398
3744
  import dayjs2 from "dayjs";
3399
- var getCounterTotalsForLast24HoursSchema = z24.object({
3400
- date: z24.string(),
3401
- endDate: z24.string().optional()
3745
+ var getCounterTotalsForLast24HoursSchema = z25.object({
3746
+ date: z25.string(),
3747
+ endDate: z25.string().optional()
3402
3748
  });
3403
3749
 
3404
3750
  // ../../b4m-core/packages/services/dist/src/countersService/generateReport.js
3405
- var generateDailyReportSchema = z25.object({
3406
- date: z25.string(),
3407
- startDate: z25.string().optional(),
3408
- endDate: z25.string().optional()
3751
+ var generateDailyReportSchema = z26.object({
3752
+ date: z26.string(),
3753
+ startDate: z26.string().optional(),
3754
+ endDate: z26.string().optional()
3409
3755
  });
3410
3756
 
3411
3757
  // ../../b4m-core/packages/services/dist/src/countersService/incrementUserCounter.js
3412
- import { z as z26 } from "zod";
3413
- var incrementUserCounterSchema = z26.object({
3414
- action: z26.string(),
3415
- increment: z26.coerce.number().default(1).optional(),
3416
- metadata: z26.record(z26.unknown()).optional()
3758
+ import { z as z27 } from "zod";
3759
+ var incrementUserCounterSchema = z27.object({
3760
+ action: z27.string(),
3761
+ increment: z27.coerce.number().default(1).optional(),
3762
+ metadata: z27.record(z27.unknown()).optional()
3417
3763
  });
3418
3764
 
3419
3765
  // ../../b4m-core/packages/services/dist/src/countersService/sendSlackReport.js
@@ -3429,47 +3775,47 @@ import { GoogleGenerativeAI } from "@google/generative-ai";
3429
3775
  import OpenAI2 from "openai";
3430
3776
 
3431
3777
  // ../../b4m-core/packages/services/dist/src/importHistoryService/index.js
3432
- import fs6, { unlinkSync } from "fs";
3778
+ import fs7, { unlinkSync } from "fs";
3433
3779
  import yauzl from "yauzl";
3434
3780
  import axios3 from "axios";
3435
3781
 
3436
3782
  // ../../b4m-core/packages/services/dist/src/importHistoryService/importOpenaiHistory.js
3437
- import { z as z27 } from "zod";
3783
+ import { z as z28 } from "zod";
3438
3784
  import last from "lodash/last.js";
3439
- var epochDate = () => z27.preprocess((val) => new Date(Number(val) * 1e3), z27.date());
3440
- var openaiConversationSchema = z27.object({
3441
- id: z27.string(),
3442
- title: z27.string(),
3785
+ var epochDate = () => z28.preprocess((val) => new Date(Number(val) * 1e3), z28.date());
3786
+ var openaiConversationSchema = z28.object({
3787
+ id: z28.string(),
3788
+ title: z28.string(),
3443
3789
  create_time: epochDate(),
3444
3790
  update_time: epochDate().nullable(),
3445
- mapping: z27.record(
3446
- z27.string(),
3447
- z27.object({
3448
- id: z27.string(),
3449
- parent: z27.string().nullable(),
3450
- children: z27.array(z27.string()),
3451
- message: z27.object({
3452
- id: z27.string(),
3791
+ mapping: z28.record(
3792
+ z28.string(),
3793
+ z28.object({
3794
+ id: z28.string(),
3795
+ parent: z28.string().nullable(),
3796
+ children: z28.array(z28.string()),
3797
+ message: z28.object({
3798
+ id: z28.string(),
3453
3799
  create_time: epochDate(),
3454
3800
  update_time: epochDate().nullable(),
3455
- author: z27.object({
3456
- role: z27.string(),
3457
- name: z27.string().nullable(),
3458
- metadata: z27.any()
3801
+ author: z28.object({
3802
+ role: z28.string(),
3803
+ name: z28.string().nullable(),
3804
+ metadata: z28.any()
3459
3805
  // Accept any metadata structure
3460
3806
  }).passthrough(),
3461
3807
  // Allow extra fields in author
3462
- content: z27.object({
3463
- content_type: z27.string(),
3464
- parts: z27.array(z27.any()).optional()
3808
+ content: z28.object({
3809
+ content_type: z28.string(),
3810
+ parts: z28.array(z28.any()).optional()
3465
3811
  // Accept any type in parts array (strings, objects, etc.)
3466
3812
  }).passthrough(),
3467
3813
  // Allow extra fields in content
3468
- status: z27.string(),
3469
- end_turn: z27.boolean().nullable(),
3470
- metadata: z27.any(),
3814
+ status: z28.string(),
3815
+ end_turn: z28.boolean().nullable(),
3816
+ metadata: z28.any(),
3471
3817
  // Accept any metadata structure since it varies widely
3472
- recipient: z27.string()
3818
+ recipient: z28.string()
3473
3819
  }).passthrough().nullable()
3474
3820
  }).passthrough()
3475
3821
  // Allow extra fields in mapping node
@@ -3477,38 +3823,38 @@ var openaiConversationSchema = z27.object({
3477
3823
  }).passthrough();
3478
3824
 
3479
3825
  // ../../b4m-core/packages/services/dist/src/importHistoryService/importClaudeHistory.js
3480
- import { z as z28 } from "zod";
3481
- var claudeChatMessageSchema = z28.object({
3482
- uuid: z28.string().uuid(),
3483
- text: z28.string(),
3484
- content: z28.array(
3485
- z28.object({
3486
- type: z28.string(),
3826
+ import { z as z29 } from "zod";
3827
+ var claudeChatMessageSchema = z29.object({
3828
+ uuid: z29.string().uuid(),
3829
+ text: z29.string(),
3830
+ content: z29.array(
3831
+ z29.object({
3832
+ type: z29.string(),
3487
3833
  // Accept any type: "text", "image", "tool_result", etc.
3488
- text: z28.string().optional()
3834
+ text: z29.string().optional()
3489
3835
  // Make text optional since tool_result may not have it
3490
3836
  }).passthrough()
3491
3837
  // Allow all other fields
3492
3838
  ),
3493
- sender: z28.enum(["human", "assistant"]),
3494
- created_at: z28.coerce.date(),
3495
- updated_at: z28.coerce.date(),
3496
- attachments: z28.array(z28.any()),
3839
+ sender: z29.enum(["human", "assistant"]),
3840
+ created_at: z29.coerce.date(),
3841
+ updated_at: z29.coerce.date(),
3842
+ attachments: z29.array(z29.any()),
3497
3843
  // Accept any attachment structure
3498
- files: z28.array(z28.any())
3844
+ files: z29.array(z29.any())
3499
3845
  // Accept any file structure
3500
3846
  }).passthrough();
3501
- var claudeConversationSchema = z28.object({
3502
- uuid: z28.string().uuid(),
3503
- name: z28.string(),
3504
- summary: z28.string().optional(),
3847
+ var claudeConversationSchema = z29.object({
3848
+ uuid: z29.string().uuid(),
3849
+ name: z29.string(),
3850
+ summary: z29.string().optional(),
3505
3851
  // Summary field is optional
3506
- created_at: z28.coerce.date(),
3507
- updated_at: z28.coerce.date(),
3508
- account: z28.object({
3509
- uuid: z28.string().uuid()
3852
+ created_at: z29.coerce.date(),
3853
+ updated_at: z29.coerce.date(),
3854
+ account: z29.object({
3855
+ uuid: z29.string().uuid()
3510
3856
  }),
3511
- chat_messages: z28.array(claudeChatMessageSchema)
3857
+ chat_messages: z29.array(claudeChatMessageSchema)
3512
3858
  }).passthrough();
3513
3859
 
3514
3860
  // ../../b4m-core/packages/services/dist/src/importHistoryService/index.js
@@ -3519,357 +3865,357 @@ var ImportSource;
3519
3865
  })(ImportSource || (ImportSource = {}));
3520
3866
 
3521
3867
  // ../../b4m-core/packages/services/dist/src/sessionService/create.js
3522
- import { z as z29 } from "zod";
3523
- var createSessionParametersSchema = z29.object({
3524
- name: z29.string(),
3525
- knowledgeIds: z29.array(z29.string()).optional(),
3526
- artifactIds: z29.array(z29.string()).optional(),
3527
- agentIds: z29.array(z29.string()).optional(),
3528
- tags: z29.array(z29.object({ name: z29.string(), strength: z29.number() })).optional(),
3529
- summary: z29.string().optional(),
3530
- summaryAt: z29.date().optional(),
3531
- clonedSourceId: z29.string().optional().nullable(),
3532
- forkedSourceId: z29.string().optional().nullable(),
3533
- projectId: z29.string().optional(),
3534
- lastUsedModel: z29.string().optional().nullable()
3868
+ import { z as z30 } from "zod";
3869
+ var createSessionParametersSchema = z30.object({
3870
+ name: z30.string(),
3871
+ knowledgeIds: z30.array(z30.string()).optional(),
3872
+ artifactIds: z30.array(z30.string()).optional(),
3873
+ agentIds: z30.array(z30.string()).optional(),
3874
+ tags: z30.array(z30.object({ name: z30.string(), strength: z30.number() })).optional(),
3875
+ summary: z30.string().optional(),
3876
+ summaryAt: z30.date().optional(),
3877
+ clonedSourceId: z30.string().optional().nullable(),
3878
+ forkedSourceId: z30.string().optional().nullable(),
3879
+ projectId: z30.string().optional(),
3880
+ lastUsedModel: z30.string().optional().nullable()
3535
3881
  });
3536
3882
 
3537
3883
  // ../../b4m-core/packages/services/dist/src/sessionService/delete.js
3538
- import { z as z30 } from "zod";
3539
- var deleteSessionSchema = z30.object({
3540
- id: z30.string()
3884
+ import { z as z31 } from "zod";
3885
+ var deleteSessionSchema = z31.object({
3886
+ id: z31.string()
3541
3887
  });
3542
3888
 
3543
3889
  // ../../b4m-core/packages/services/dist/src/sessionService/sumarize.js
3544
- import { z as z31 } from "zod";
3545
- var sumarizeSessionSchema = z31.object({
3546
- id: z31.string()
3890
+ import { z as z32 } from "zod";
3891
+ var sumarizeSessionSchema = z32.object({
3892
+ id: z32.string()
3547
3893
  });
3548
3894
 
3549
3895
  // ../../b4m-core/packages/services/dist/src/projectService/create.js
3550
- import { z as z32 } from "zod";
3551
- var createProjectSchema = z32.object({
3552
- name: z32.string().min(1),
3553
- description: z32.string().min(1),
3554
- sessionIds: z32.array(z32.string()).optional(),
3555
- fileIds: z32.array(z32.string()).optional()
3896
+ import { z as z33 } from "zod";
3897
+ var createProjectSchema = z33.object({
3898
+ name: z33.string().min(1),
3899
+ description: z33.string().min(1),
3900
+ sessionIds: z33.array(z33.string()).optional(),
3901
+ fileIds: z33.array(z33.string()).optional()
3556
3902
  });
3557
3903
 
3558
3904
  // ../../b4m-core/packages/services/dist/src/projectService/search.js
3559
- import { z as z33 } from "zod";
3560
- var searchProjectsSchema = z33.object({
3561
- search: z33.string().optional(),
3562
- filters: z33.object({
3563
- favorite: z33.coerce.boolean().optional(),
3564
- scope: z33.record(z33.any()).optional()
3905
+ import { z as z34 } from "zod";
3906
+ var searchProjectsSchema = z34.object({
3907
+ search: z34.string().optional(),
3908
+ filters: z34.object({
3909
+ favorite: z34.coerce.boolean().optional(),
3910
+ scope: z34.record(z34.any()).optional()
3565
3911
  }).optional(),
3566
- pagination: z33.object({
3567
- page: z33.coerce.number().optional(),
3568
- limit: z33.coerce.number().optional()
3912
+ pagination: z34.object({
3913
+ page: z34.coerce.number().optional(),
3914
+ limit: z34.coerce.number().optional()
3569
3915
  }).optional(),
3570
- orderBy: z33.object({
3571
- by: z33.enum(["createdAt", "updatedAt"]).optional(),
3572
- direction: z33.enum(["asc", "desc"]).optional()
3916
+ orderBy: z34.object({
3917
+ by: z34.enum(["createdAt", "updatedAt"]).optional(),
3918
+ direction: z34.enum(["asc", "desc"]).optional()
3573
3919
  }).optional()
3574
3920
  });
3575
3921
 
3576
3922
  // ../../b4m-core/packages/services/dist/src/projectService/addSessions.js
3577
- import { z as z44 } from "zod";
3923
+ import { z as z45 } from "zod";
3578
3924
  import uniq2 from "lodash/uniq.js";
3579
3925
 
3580
3926
  // ../../b4m-core/packages/services/dist/src/sharingService/accept.js
3581
- import { z as z34 } from "zod";
3582
- var acceptInviteSchema = z34.object({
3583
- id: z34.string()
3927
+ import { z as z35 } from "zod";
3928
+ var acceptInviteSchema = z35.object({
3929
+ id: z35.string()
3584
3930
  });
3585
3931
 
3586
3932
  // ../../b4m-core/packages/services/dist/src/sharingService/cancel.js
3587
- import { z as z35 } from "zod";
3588
- var cancelInviteSchema = z35.object({
3589
- id: z35.string(),
3590
- type: z35.nativeEnum(InviteType),
3591
- email: z35.string().email().optional()
3933
+ import { z as z36 } from "zod";
3934
+ var cancelInviteSchema = z36.object({
3935
+ id: z36.string(),
3936
+ type: z36.nativeEnum(InviteType),
3937
+ email: z36.string().email().optional()
3592
3938
  });
3593
3939
 
3594
3940
  // ../../b4m-core/packages/services/dist/src/sharingService/cancelOwnDocument.js
3595
- import { z as z36 } from "zod";
3596
- var cancelOwnDocumentInvitesSchema = z36.object({
3597
- documentId: z36.string(),
3598
- type: z36.nativeEnum(InviteType)
3941
+ import { z as z37 } from "zod";
3942
+ var cancelOwnDocumentInvitesSchema = z37.object({
3943
+ documentId: z37.string(),
3944
+ type: z37.nativeEnum(InviteType)
3599
3945
  });
3600
3946
 
3601
3947
  // ../../b4m-core/packages/services/dist/src/sharingService/create.js
3602
- import { z as z37 } from "zod";
3948
+ import { z as z38 } from "zod";
3603
3949
  var defaultExpiration = () => new Date((/* @__PURE__ */ new Date()).getFullYear() + 100, (/* @__PURE__ */ new Date()).getMonth(), (/* @__PURE__ */ new Date()).getDate());
3604
3950
  var DEFAULT_AVAILABLE = 1;
3605
- var createInviteSchema = z37.object({
3606
- id: z37.string(),
3607
- type: z37.nativeEnum(InviteType),
3608
- permissions: z37.array(z37.nativeEnum(Permission)),
3609
- recipients: z37.string().array().optional(),
3610
- description: z37.string().optional(),
3611
- expiresAt: z37.date().optional().default(defaultExpiration()),
3612
- available: z37.number().optional().default(DEFAULT_AVAILABLE)
3951
+ var createInviteSchema = z38.object({
3952
+ id: z38.string(),
3953
+ type: z38.nativeEnum(InviteType),
3954
+ permissions: z38.array(z38.nativeEnum(Permission)),
3955
+ recipients: z38.string().array().optional(),
3956
+ description: z38.string().optional(),
3957
+ expiresAt: z38.date().optional().default(defaultExpiration()),
3958
+ available: z38.number().optional().default(DEFAULT_AVAILABLE)
3613
3959
  });
3614
3960
 
3615
3961
  // ../../b4m-core/packages/services/dist/src/sharingService/get.js
3616
- import { z as z38 } from "zod";
3617
- var getInviteSchema = z38.object({
3618
- id: z38.string(),
3619
- withUsername: z38.boolean().optional()
3962
+ import { z as z39 } from "zod";
3963
+ var getInviteSchema = z39.object({
3964
+ id: z39.string(),
3965
+ withUsername: z39.boolean().optional()
3620
3966
  });
3621
3967
 
3622
3968
  // ../../b4m-core/packages/services/dist/src/sharingService/listByDocumentIdAndType.js
3623
- import { z as z39 } from "zod";
3624
- var listInviteByDocumentIdAndTypeSchema = z39.object({
3625
- documentId: z39.string(),
3626
- type: z39.nativeEnum(InviteType)
3969
+ import { z as z40 } from "zod";
3970
+ var listInviteByDocumentIdAndTypeSchema = z40.object({
3971
+ documentId: z40.string(),
3972
+ type: z40.nativeEnum(InviteType)
3627
3973
  });
3628
3974
 
3629
3975
  // ../../b4m-core/packages/services/dist/src/sharingService/listOwnPending.js
3630
- import { z as z40 } from "zod";
3631
- var listOwnPendingInvitesSchema = z40.object({
3632
- limit: z40.number().min(1).max(100).default(20),
3633
- page: z40.number().min(1).default(1)
3976
+ import { z as z41 } from "zod";
3977
+ var listOwnPendingInvitesSchema = z41.object({
3978
+ limit: z41.number().min(1).max(100).default(20),
3979
+ page: z41.number().min(1).default(1)
3634
3980
  });
3635
3981
 
3636
3982
  // ../../b4m-core/packages/services/dist/src/sharingService/refuse.js
3637
- import { z as z41 } from "zod";
3638
- var refuseInviteSchema = z41.object({
3639
- id: z41.string()
3983
+ import { z as z42 } from "zod";
3984
+ var refuseInviteSchema = z42.object({
3985
+ id: z42.string()
3640
3986
  });
3641
3987
 
3642
3988
  // ../../b4m-core/packages/services/dist/src/sharingService/revoke.js
3643
- import { z as z42 } from "zod";
3644
- var revokeSharingSchema = z42.object({
3645
- id: z42.string(),
3646
- type: z42.enum(["files", "sessions", "projects"]),
3647
- userId: z42.string(),
3648
- projectId: z42.string().optional()
3989
+ import { z as z43 } from "zod";
3990
+ var revokeSharingSchema = z43.object({
3991
+ id: z43.string(),
3992
+ type: z43.enum(["files", "sessions", "projects"]),
3993
+ userId: z43.string(),
3994
+ projectId: z43.string().optional()
3649
3995
  });
3650
3996
 
3651
3997
  // ../../b4m-core/packages/services/dist/src/projectService/addFiles.js
3652
- import { z as z43 } from "zod";
3998
+ import { z as z44 } from "zod";
3653
3999
  import uniq from "lodash/uniq.js";
3654
- var addFilesProjectSchema = z43.object({
3655
- projectId: z43.string().nonempty(),
3656
- fileIds: z43.array(z43.string().nonempty())
4000
+ var addFilesProjectSchema = z44.object({
4001
+ projectId: z44.string().nonempty(),
4002
+ fileIds: z44.array(z44.string().nonempty())
3657
4003
  });
3658
4004
 
3659
4005
  // ../../b4m-core/packages/services/dist/src/projectService/addSessions.js
3660
- var addSessionsProjectSchema = z44.object({
3661
- projectId: z44.string().nonempty(),
3662
- sessionIds: z44.array(z44.string().nonempty())
4006
+ var addSessionsProjectSchema = z45.object({
4007
+ projectId: z45.string().nonempty(),
4008
+ sessionIds: z45.array(z45.string().nonempty())
3663
4009
  });
3664
4010
 
3665
4011
  // ../../b4m-core/packages/services/dist/src/projectService/get.js
3666
- import { z as z45 } from "zod";
3667
- var getProjectSchema = z45.object({
3668
- id: z45.string()
3669
- });
3670
-
3671
- // ../../b4m-core/packages/services/dist/src/projectService/update.js
3672
4012
  import { z as z46 } from "zod";
3673
- var updateProjectSchema = z46.object({
3674
- id: z46.string(),
3675
- name: z46.string().optional(),
3676
- description: z46.string().optional()
4013
+ var getProjectSchema = z46.object({
4014
+ id: z46.string()
3677
4015
  });
3678
4016
 
3679
- // ../../b4m-core/packages/services/dist/src/projectService/delete.js
4017
+ // ../../b4m-core/packages/services/dist/src/projectService/update.js
3680
4018
  import { z as z47 } from "zod";
3681
- var deleteProjectSchema = z47.object({
3682
- id: z47.string()
4019
+ var updateProjectSchema = z47.object({
4020
+ id: z47.string(),
4021
+ name: z47.string().optional(),
4022
+ description: z47.string().optional()
3683
4023
  });
3684
4024
 
3685
- // ../../b4m-core/packages/services/dist/src/projectService/removeFiles.js
4025
+ // ../../b4m-core/packages/services/dist/src/projectService/delete.js
3686
4026
  import { z as z48 } from "zod";
3687
- var removeProjectFilesSchema = z48.object({
3688
- projectId: z48.string(),
3689
- fileIds: z48.array(z48.string())
4027
+ var deleteProjectSchema = z48.object({
4028
+ id: z48.string()
3690
4029
  });
3691
4030
 
3692
- // ../../b4m-core/packages/services/dist/src/projectService/removeSessions.js
4031
+ // ../../b4m-core/packages/services/dist/src/projectService/removeFiles.js
3693
4032
  import { z as z49 } from "zod";
3694
- var removeProjectSessionsSchema = z49.object({
4033
+ var removeProjectFilesSchema = z49.object({
3695
4034
  projectId: z49.string(),
3696
- sessionIds: z49.array(z49.string())
4035
+ fileIds: z49.array(z49.string())
3697
4036
  });
3698
4037
 
3699
- // ../../b4m-core/packages/services/dist/src/projectService/listSessions.js
4038
+ // ../../b4m-core/packages/services/dist/src/projectService/removeSessions.js
3700
4039
  import { z as z50 } from "zod";
3701
- var listProjectSessionsSchema = z50.object({
3702
- projectId: z50.string()
4040
+ var removeProjectSessionsSchema = z50.object({
4041
+ projectId: z50.string(),
4042
+ sessionIds: z50.array(z50.string())
3703
4043
  });
3704
4044
 
3705
- // ../../b4m-core/packages/services/dist/src/projectService/listFiles.js
4045
+ // ../../b4m-core/packages/services/dist/src/projectService/listSessions.js
3706
4046
  import { z as z51 } from "zod";
3707
- var listProjectFilesSchema = z51.object({
4047
+ var listProjectSessionsSchema = z51.object({
3708
4048
  projectId: z51.string()
3709
4049
  });
3710
4050
 
3711
- // ../../b4m-core/packages/services/dist/src/projectService/listInvites.js
4051
+ // ../../b4m-core/packages/services/dist/src/projectService/listFiles.js
3712
4052
  import { z as z52 } from "zod";
3713
- var listProjectInvitesParamsSchema = z52.object({
3714
- id: z52.string(),
3715
- statuses: z52.string().optional().default(""),
3716
- limit: z52.coerce.number().optional().default(10),
3717
- page: z52.coerce.number().optional().default(1)
4053
+ var listProjectFilesSchema = z52.object({
4054
+ projectId: z52.string()
3718
4055
  });
3719
4056
 
3720
- // ../../b4m-core/packages/services/dist/src/projectService/addSystemPrompts.js
4057
+ // ../../b4m-core/packages/services/dist/src/projectService/listInvites.js
3721
4058
  import { z as z53 } from "zod";
3722
- var addSystemPromptsSchema = z53.object({
3723
- projectId: z53.string(),
3724
- fileIds: z53.array(z53.string())
4059
+ var listProjectInvitesParamsSchema = z53.object({
4060
+ id: z53.string(),
4061
+ statuses: z53.string().optional().default(""),
4062
+ limit: z53.coerce.number().optional().default(10),
4063
+ page: z53.coerce.number().optional().default(1)
3725
4064
  });
3726
4065
 
3727
- // ../../b4m-core/packages/services/dist/src/projectService/toggleSystemPrompt.js
4066
+ // ../../b4m-core/packages/services/dist/src/projectService/addSystemPrompts.js
3728
4067
  import { z as z54 } from "zod";
3729
- var toggleSystemPromptSchema = z54.object({
4068
+ var addSystemPromptsSchema = z54.object({
3730
4069
  projectId: z54.string(),
3731
- fileId: z54.string()
4070
+ fileIds: z54.array(z54.string())
3732
4071
  });
3733
4072
 
3734
- // ../../b4m-core/packages/services/dist/src/projectService/removeSystemPrompt.js
4073
+ // ../../b4m-core/packages/services/dist/src/projectService/toggleSystemPrompt.js
3735
4074
  import { z as z55 } from "zod";
3736
- var removeSystemPromptSchema = z55.object({
4075
+ var toggleSystemPromptSchema = z55.object({
3737
4076
  projectId: z55.string(),
3738
4077
  fileId: z55.string()
3739
4078
  });
3740
4079
 
3741
- // ../../b4m-core/packages/services/dist/src/projectService/addFavorite.js
3742
- import { z as z58 } from "zod";
3743
-
3744
- // ../../b4m-core/packages/services/dist/src/favoriteService/create.js
4080
+ // ../../b4m-core/packages/services/dist/src/projectService/removeSystemPrompt.js
3745
4081
  import { z as z56 } from "zod";
3746
- var createFavoriteParametersSchema = z56.object({
3747
- documentId: z56.string(),
3748
- documentType: z56.nativeEnum(FavoriteDocumentType)
4082
+ var removeSystemPromptSchema = z56.object({
4083
+ projectId: z56.string(),
4084
+ fileId: z56.string()
3749
4085
  });
3750
4086
 
3751
- // ../../b4m-core/packages/services/dist/src/favoriteService/delete.js
4087
+ // ../../b4m-core/packages/services/dist/src/projectService/addFavorite.js
4088
+ import { z as z59 } from "zod";
4089
+
4090
+ // ../../b4m-core/packages/services/dist/src/favoriteService/create.js
3752
4091
  import { z as z57 } from "zod";
3753
- var deleteFavoriteParametersSchema = z57.object({
4092
+ var createFavoriteParametersSchema = z57.object({
3754
4093
  documentId: z57.string(),
3755
4094
  documentType: z57.nativeEnum(FavoriteDocumentType)
3756
4095
  });
3757
4096
 
3758
- // ../../b4m-core/packages/services/dist/src/projectService/addFavorite.js
3759
- var addFavoriteParametersSchema = z58.object({
3760
- projectId: z58.string()
4097
+ // ../../b4m-core/packages/services/dist/src/favoriteService/delete.js
4098
+ import { z as z58 } from "zod";
4099
+ var deleteFavoriteParametersSchema = z58.object({
4100
+ documentId: z58.string(),
4101
+ documentType: z58.nativeEnum(FavoriteDocumentType)
3761
4102
  });
3762
4103
 
3763
- // ../../b4m-core/packages/services/dist/src/projectService/deleteFavorite.js
3764
- import { z as z59 } from "zod";
3765
- var deleteFavoriteParametersSchema2 = z59.object({
4104
+ // ../../b4m-core/packages/services/dist/src/projectService/addFavorite.js
4105
+ var addFavoriteParametersSchema = z59.object({
3766
4106
  projectId: z59.string()
3767
4107
  });
3768
4108
 
3769
- // ../../b4m-core/packages/services/dist/src/projectService/removeNonExistentFiles.js
4109
+ // ../../b4m-core/packages/services/dist/src/projectService/deleteFavorite.js
3770
4110
  import { z as z60 } from "zod";
3771
- var removeNonExistentFilesSchema = z60.object({
4111
+ var deleteFavoriteParametersSchema2 = z60.object({
3772
4112
  projectId: z60.string()
3773
4113
  });
3774
4114
 
3775
- // ../../b4m-core/packages/services/dist/src/projectService/leaveProject.js
4115
+ // ../../b4m-core/packages/services/dist/src/projectService/removeNonExistentFiles.js
3776
4116
  import { z as z61 } from "zod";
3777
- var leaveProjectParamsSchema = z61.object({
3778
- id: z61.string(),
3779
- userIdToRemove: z61.string().optional()
3780
- // Optional: if provided, this is a removal by owner
4117
+ var removeNonExistentFilesSchema = z61.object({
4118
+ projectId: z61.string()
3781
4119
  });
3782
4120
 
3783
- // ../../b4m-core/packages/services/dist/src/sessionService/update.js
3784
- import uniq3 from "lodash/uniq.js";
3785
- import isEqual from "lodash/isEqual.js";
4121
+ // ../../b4m-core/packages/services/dist/src/projectService/leaveProject.js
3786
4122
  import { z as z62 } from "zod";
3787
- var updateSessionParamtersSchema = z62.object({
4123
+ var leaveProjectParamsSchema = z62.object({
3788
4124
  id: z62.string(),
3789
- name: z62.string().optional(),
3790
- knowledgeIds: z62.array(z62.string()).optional(),
3791
- artifactIds: z62.array(z62.string()).optional(),
3792
- tags: z62.array(z62.object({ name: z62.string(), strength: z62.number() })).optional(),
3793
- lastUsedModel: z62.string().optional()
4125
+ userIdToRemove: z62.string().optional()
4126
+ // Optional: if provided, this is a removal by owner
3794
4127
  });
3795
4128
 
3796
- // ../../b4m-core/packages/services/dist/src/sessionService/clone.js
4129
+ // ../../b4m-core/packages/services/dist/src/sessionService/update.js
4130
+ import uniq3 from "lodash/uniq.js";
4131
+ import isEqual from "lodash/isEqual.js";
3797
4132
  import { z as z63 } from "zod";
3798
- var cloneSessionSchema = z63.object({
3799
- id: z63.string()
4133
+ var updateSessionParamtersSchema = z63.object({
4134
+ id: z63.string(),
4135
+ name: z63.string().optional(),
4136
+ knowledgeIds: z63.array(z63.string()).optional(),
4137
+ artifactIds: z63.array(z63.string()).optional(),
4138
+ tags: z63.array(z63.object({ name: z63.string(), strength: z63.number() })).optional(),
4139
+ lastUsedModel: z63.string().optional()
3800
4140
  });
3801
4141
 
3802
- // ../../b4m-core/packages/services/dist/src/sessionService/fork.js
4142
+ // ../../b4m-core/packages/services/dist/src/sessionService/clone.js
3803
4143
  import { z as z64 } from "zod";
3804
- var forkSessionSchema = z64.object({
3805
- sessionId: z64.string(),
3806
- messageId: z64.string()
4144
+ var cloneSessionSchema = z64.object({
4145
+ id: z64.string()
3807
4146
  });
3808
4147
 
3809
- // ../../b4m-core/packages/services/dist/src/sessionService/snip.js
4148
+ // ../../b4m-core/packages/services/dist/src/sessionService/fork.js
3810
4149
  import { z as z65 } from "zod";
3811
- var snipSessionSchema = z65.object({
4150
+ var forkSessionSchema = z65.object({
3812
4151
  sessionId: z65.string(),
3813
4152
  messageId: z65.string()
3814
4153
  });
3815
4154
 
3816
- // ../../b4m-core/packages/services/dist/src/sessionService/get.js
4155
+ // ../../b4m-core/packages/services/dist/src/sessionService/snip.js
3817
4156
  import { z as z66 } from "zod";
3818
- var getSessionSchema = z66.object({
3819
- id: z66.string()
4157
+ var snipSessionSchema = z66.object({
4158
+ sessionId: z66.string(),
4159
+ messageId: z66.string()
3820
4160
  });
3821
4161
 
3822
- // ../../b4m-core/packages/services/dist/src/sessionService/deleteMessage.js
4162
+ // ../../b4m-core/packages/services/dist/src/sessionService/get.js
3823
4163
  import { z as z67 } from "zod";
3824
- var deleteSessionMessageSchema = z67.object({
3825
- sessionId: z67.string(),
3826
- messageId: z67.string()
4164
+ var getSessionSchema = z67.object({
4165
+ id: z67.string()
3827
4166
  });
3828
4167
 
3829
- // ../../b4m-core/packages/services/dist/src/sessionService/addFavorite.js
4168
+ // ../../b4m-core/packages/services/dist/src/sessionService/deleteMessage.js
3830
4169
  import { z as z68 } from "zod";
3831
- var addFavoriteParametersSchema2 = z68.object({
3832
- sessionId: z68.string()
4170
+ var deleteSessionMessageSchema = z68.object({
4171
+ sessionId: z68.string(),
4172
+ messageId: z68.string()
3833
4173
  });
3834
4174
 
3835
- // ../../b4m-core/packages/services/dist/src/sessionService/deleteFavorite.js
4175
+ // ../../b4m-core/packages/services/dist/src/sessionService/addFavorite.js
3836
4176
  import { z as z69 } from "zod";
3837
- var deleteFavoriteParametersSchema3 = z69.object({
4177
+ var addFavoriteParametersSchema2 = z69.object({
3838
4178
  sessionId: z69.string()
3839
4179
  });
3840
4180
 
3841
- // ../../b4m-core/packages/services/dist/src/sessionService/autoName.js
4181
+ // ../../b4m-core/packages/services/dist/src/sessionService/deleteFavorite.js
3842
4182
  import { z as z70 } from "zod";
3843
- var autoNameParameterSchema = z70.object({
3844
- sessionId: z70.string(),
4183
+ var deleteFavoriteParametersSchema3 = z70.object({
4184
+ sessionId: z70.string()
4185
+ });
4186
+
4187
+ // ../../b4m-core/packages/services/dist/src/sessionService/autoName.js
4188
+ import { z as z71 } from "zod";
4189
+ var autoNameParameterSchema = z71.object({
4190
+ sessionId: z71.string(),
3845
4191
  /** The maximum number of words to include in the title */
3846
- maxWords: z70.number().optional()
4192
+ maxWords: z71.number().optional()
3847
4193
  });
3848
4194
 
3849
4195
  // ../../b4m-core/packages/services/dist/src/organizationService/search.js
3850
- import { z as z71 } from "zod";
3851
- var searchSchema2 = z71.object({
4196
+ import { z as z72 } from "zod";
4197
+ var searchSchema2 = z72.object({
3852
4198
  /**
3853
4199
  * Text search query (searches in name and description)
3854
4200
  */
3855
- query: z71.string().optional(),
4201
+ query: z72.string().optional(),
3856
4202
  /**
3857
4203
  * Filter by personal organizations
3858
4204
  */
3859
- filters: z71.object({
3860
- personal: z71.union([z71.enum(["true", "false"]).transform((val) => val === "true"), z71.boolean()]).optional(),
3861
- userId: z71.string().optional()
4205
+ filters: z72.object({
4206
+ personal: z72.union([z72.enum(["true", "false"]).transform((val) => val === "true"), z72.boolean()]).optional(),
4207
+ userId: z72.string().optional()
3862
4208
  }).default({}),
3863
- pagination: z71.object({
3864
- page: z71.coerce.number().int().positive().default(1),
3865
- limit: z71.coerce.number().int().positive().max(100).default(10)
4209
+ pagination: z72.object({
4210
+ page: z72.coerce.number().int().positive().default(1),
4211
+ limit: z72.coerce.number().int().positive().max(100).default(10)
3866
4212
  }).default({
3867
4213
  page: 1,
3868
4214
  limit: 10
3869
4215
  }),
3870
- orderBy: z71.object({
3871
- field: z71.enum(["name", "createdAt", "updatedAt"]).default("name"),
3872
- direction: z71.enum(["asc", "desc"]).default("asc")
4216
+ orderBy: z72.object({
4217
+ field: z72.enum(["name", "createdAt", "updatedAt"]).default("name"),
4218
+ direction: z72.enum(["asc", "desc"]).default("asc")
3873
4219
  }).default({
3874
4220
  field: "name",
3875
4221
  direction: "asc"
@@ -3877,355 +4223,355 @@ var searchSchema2 = z71.object({
3877
4223
  });
3878
4224
 
3879
4225
  // ../../b4m-core/packages/services/dist/src/organizationService/get.js
3880
- import { z as z72 } from "zod";
3881
- var getSchema = z72.object({
4226
+ import { z as z73 } from "zod";
4227
+ var getSchema = z73.object({
3882
4228
  /**
3883
4229
  * Organization ID
3884
4230
  */
3885
- id: z72.string().min(1)
4231
+ id: z73.string().min(1)
3886
4232
  });
3887
4233
 
3888
4234
  // ../../b4m-core/packages/services/dist/src/organizationService/addMember.js
3889
- import { z as z73 } from "zod";
3890
- var addMemberSchema = z73.object({
3891
- userId: z73.string().optional(),
3892
- email: z73.string().optional(),
3893
- organizationId: z73.string(),
3894
- force: z73.boolean().optional()
4235
+ import { z as z74 } from "zod";
4236
+ var addMemberSchema = z74.object({
4237
+ userId: z74.string().optional(),
4238
+ email: z74.string().optional(),
4239
+ organizationId: z74.string(),
4240
+ force: z74.boolean().optional()
3895
4241
  // If true, add the user to the organization even if it's at full capacity
3896
4242
  });
3897
4243
 
3898
4244
  // ../../b4m-core/packages/services/dist/src/organizationService/getUsers.js
3899
- import { z as z74 } from "zod";
3900
- var getUsersSchema = z74.object({
3901
- id: z74.string()
4245
+ import { z as z75 } from "zod";
4246
+ var getUsersSchema = z75.object({
4247
+ id: z75.string()
3902
4248
  });
3903
4249
 
3904
4250
  // ../../b4m-core/packages/services/dist/src/organizationService/create.js
3905
- import { z as z75 } from "zod";
3906
- var createSchema = z75.object({
3907
- name: z75.string(),
3908
- personal: z75.boolean().default(false),
3909
- seats: z75.number().default(1),
3910
- stripeCustomerId: z75.string().nullable(),
3911
- billingOwnerId: z75.string().optional(),
4251
+ import { z as z76 } from "zod";
4252
+ var createSchema = z76.object({
4253
+ name: z76.string(),
4254
+ personal: z76.boolean().default(false),
4255
+ seats: z76.number().default(1),
4256
+ stripeCustomerId: z76.string().nullable(),
4257
+ billingOwnerId: z76.string().optional(),
3912
4258
  // Optional billing owner (defaults to user if not provided)
3913
- managerId: z75.string().optional()
4259
+ managerId: z76.string().optional()
3914
4260
  // Optional team manager
3915
4261
  });
3916
4262
 
3917
4263
  // ../../b4m-core/packages/services/dist/src/organizationService/update.js
3918
- import { z as z76 } from "zod";
3919
- var updateSchema = z76.object({
3920
- id: z76.string(),
3921
- name: z76.string().optional(),
3922
- description: z76.string().optional(),
3923
- billingContact: z76.string().optional(),
3924
- currentCredits: z76.coerce.number().optional()
4264
+ import { z as z77 } from "zod";
4265
+ var updateSchema = z77.object({
4266
+ id: z77.string(),
4267
+ name: z77.string().optional(),
4268
+ description: z77.string().optional(),
4269
+ billingContact: z77.string().optional(),
4270
+ currentCredits: z77.coerce.number().optional()
3925
4271
  });
3926
4272
 
3927
4273
  // ../../b4m-core/packages/services/dist/src/organizationService/delete.js
3928
- import { z as z77 } from "zod";
3929
- var deleteSchema = z77.object({
4274
+ import { z as z78 } from "zod";
4275
+ var deleteSchema = z78.object({
3930
4276
  /**
3931
4277
  * Organization ID
3932
4278
  */
3933
- id: z77.string().min(1)
4279
+ id: z78.string().min(1)
3934
4280
  });
3935
4281
 
3936
4282
  // ../../b4m-core/packages/services/dist/src/organizationService/listPendingUsers.js
3937
- import { z as z78 } from "zod";
3938
- var listPendingUsersSchema = z78.object({
3939
- organizationId: z78.string()
4283
+ import { z as z79 } from "zod";
4284
+ var listPendingUsersSchema = z79.object({
4285
+ organizationId: z79.string()
3940
4286
  });
3941
4287
 
3942
4288
  // ../../b4m-core/packages/services/dist/src/organizationService/revokeAccess.js
3943
- import { z as z79 } from "zod";
3944
- var revokeAccessSchema = z79.object({
3945
- id: z79.string(),
3946
- userId: z79.string()
4289
+ import { z as z80 } from "zod";
4290
+ var revokeAccessSchema = z80.object({
4291
+ id: z80.string(),
4292
+ userId: z80.string()
3947
4293
  });
3948
4294
 
3949
4295
  // ../../b4m-core/packages/services/dist/src/organizationService/leave.js
3950
- import { z as z80 } from "zod";
3951
- var organizationLeaveSchema = z80.object({
3952
- id: z80.string()
4296
+ import { z as z81 } from "zod";
4297
+ var organizationLeaveSchema = z81.object({
4298
+ id: z81.string()
3953
4299
  });
3954
4300
 
3955
4301
  // ../../b4m-core/packages/services/dist/src/apiKeyService/create.js
3956
- import { z as z81 } from "zod";
3957
- var createApiKeySchema = z81.object({
3958
- apiKey: z81.string().min(6),
3959
- description: z81.string().optional().default(""),
3960
- isActive: z81.boolean().optional().default(true),
3961
- type: z81.nativeEnum(ApiKeyType),
3962
- expireDays: z81.number().min(1).max(365).default(90)
4302
+ import { z as z82 } from "zod";
4303
+ var createApiKeySchema = z82.object({
4304
+ apiKey: z82.string().min(6),
4305
+ description: z82.string().optional().default(""),
4306
+ isActive: z82.boolean().optional().default(true),
4307
+ type: z82.nativeEnum(ApiKeyType),
4308
+ expireDays: z82.number().min(1).max(365).default(90)
3963
4309
  // Default 90-day expiration
3964
4310
  });
3965
4311
 
3966
4312
  // ../../b4m-core/packages/services/dist/src/apiKeyService/set.js
3967
- import { z as z82 } from "zod";
3968
- var setApiKeySchema = z82.object({
3969
- id: z82.string(),
3970
- type: z82.nativeEnum(ApiKeyType)
4313
+ import { z as z83 } from "zod";
4314
+ var setApiKeySchema = z83.object({
4315
+ id: z83.string(),
4316
+ type: z83.nativeEnum(ApiKeyType)
3971
4317
  });
3972
4318
 
3973
4319
  // ../../b4m-core/packages/services/dist/src/apiKeyService/delete.js
3974
- import { z as z83 } from "zod";
3975
- var deleteApiKeySchema = z83.object({
3976
- id: z83.string()
4320
+ import { z as z84 } from "zod";
4321
+ var deleteApiKeySchema = z84.object({
4322
+ id: z84.string()
3977
4323
  });
3978
4324
 
3979
4325
  // ../../b4m-core/packages/services/dist/src/fabFileService/get.js
3980
- import { z as z84 } from "zod";
3981
- var getFabFileSchema = z84.object({
3982
- id: z84.string()
4326
+ import { z as z85 } from "zod";
4327
+ var getFabFileSchema = z85.object({
4328
+ id: z85.string()
3983
4329
  });
3984
4330
 
3985
4331
  // ../../b4m-core/packages/services/dist/src/fabFileService/list.js
3986
- import { z as z85 } from "zod";
3987
- var listFabFilesSchema = z85.object({
3988
- ids: z85.array(z85.string()).optional()
4332
+ import { z as z86 } from "zod";
4333
+ var listFabFilesSchema = z86.object({
4334
+ ids: z86.array(z86.string()).optional()
3989
4335
  });
3990
4336
 
3991
4337
  // ../../b4m-core/packages/services/dist/src/fabFileService/update.js
3992
4338
  import mime from "mime-types";
3993
4339
  import { v4 as uuidv42 } from "uuid";
3994
- import { z as z86 } from "zod";
3995
- var updateFabFileSchema = z86.object({
3996
- id: z86.string(),
3997
- fileName: z86.string(),
3998
- mimeType: z86.string(),
3999
- fileContent: z86.string().optional(),
4000
- type: z86.nativeEnum(KnowledgeType),
4001
- system: z86.boolean().optional(),
4002
- systemPriority: z86.number().min(0).max(999).optional(),
4003
- sessionId: z86.string().optional(),
4004
- notes: z86.string().optional(),
4005
- primaryTag: z86.string().optional(),
4006
- tags: z86.array(z86.object({
4007
- name: z86.string(),
4008
- strength: z86.number()
4340
+ import { z as z87 } from "zod";
4341
+ var updateFabFileSchema = z87.object({
4342
+ id: z87.string(),
4343
+ fileName: z87.string(),
4344
+ mimeType: z87.string(),
4345
+ fileContent: z87.string().optional(),
4346
+ type: z87.nativeEnum(KnowledgeType),
4347
+ system: z87.boolean().optional(),
4348
+ systemPriority: z87.number().min(0).max(999).optional(),
4349
+ sessionId: z87.string().optional(),
4350
+ notes: z87.string().optional(),
4351
+ primaryTag: z87.string().optional(),
4352
+ tags: z87.array(z87.object({
4353
+ name: z87.string(),
4354
+ strength: z87.number()
4009
4355
  })).optional(),
4010
- error: z86.string().nullable().optional()
4356
+ error: z87.string().nullable().optional()
4011
4357
  });
4012
4358
 
4013
4359
  // ../../b4m-core/packages/services/dist/src/fabFileService/delete.js
4014
- import { z as z87 } from "zod";
4015
- var deleteFabFileSchema = z87.object({
4016
- id: z87.string()
4360
+ import { z as z88 } from "zod";
4361
+ var deleteFabFileSchema = z88.object({
4362
+ id: z88.string()
4017
4363
  });
4018
4364
 
4019
4365
  // ../../b4m-core/packages/services/dist/src/fabFileService/chunk.js
4020
- import { z as z88 } from "zod";
4021
- var chunkFileSchema = z88.object({
4022
- fabFileId: z88.string(),
4023
- embeddingModel: z88.string()
4366
+ import { z as z89 } from "zod";
4367
+ var chunkFileSchema = z89.object({
4368
+ fabFileId: z89.string(),
4369
+ embeddingModel: z89.string()
4024
4370
  });
4025
4371
 
4026
4372
  // ../../b4m-core/packages/services/dist/src/fabFileService/vectorize.js
4027
- import { z as z89 } from "zod";
4028
- var vectorizeFabFileChunkSchema = z89.object({
4029
- fabFileId: z89.string(),
4030
- chunkId: z89.string()
4373
+ import { z as z90 } from "zod";
4374
+ var vectorizeFabFileChunkSchema = z90.object({
4375
+ fabFileId: z90.string(),
4376
+ chunkId: z90.string()
4031
4377
  });
4032
4378
 
4033
4379
  // ../../b4m-core/packages/services/dist/src/fabFileService/listBySession.js
4034
- import { z as z90 } from "zod";
4035
- var listFabFilesBySessionSchema = z90.object({
4036
- sessionId: z90.string()
4380
+ import { z as z91 } from "zod";
4381
+ var listFabFilesBySessionSchema = z91.object({
4382
+ sessionId: z91.string()
4037
4383
  });
4038
4384
 
4039
4385
  // ../../b4m-core/packages/services/dist/src/fabFileService/listByQuest.js
4040
- import { z as z91 } from "zod";
4041
- var listFabFilesByQuestSchema = z91.object({
4042
- questId: z91.string()
4386
+ import { z as z92 } from "zod";
4387
+ var listFabFilesByQuestSchema = z92.object({
4388
+ questId: z92.string()
4043
4389
  });
4044
4390
 
4045
4391
  // ../../b4m-core/packages/services/dist/src/fabFileService/createByUrl.js
4046
- import { z as z92 } from "zod";
4047
- var createFabFileByUrlSchema = z92.object({
4048
- url: z92.string().regex(/^(?!https?:\/\/(drive|docs)\.google\.com\/(?:file\/d\/|open\?id=|uc\?id=|document\/d\/|spreadsheets\/d\/|presentation\/d\/|forms\/d\/|drive\/folders\/)([a-zA-Z0-9_-]{10,})).+/)
4392
+ import { z as z93 } from "zod";
4393
+ var createFabFileByUrlSchema = z93.object({
4394
+ url: z93.string().regex(/^(?!https?:\/\/(drive|docs)\.google\.com\/(?:file\/d\/|open\?id=|uc\?id=|document\/d\/|spreadsheets\/d\/|presentation\/d\/|forms\/d\/|drive\/folders\/)([a-zA-Z0-9_-]{10,})).+/)
4049
4395
  });
4050
4396
 
4051
4397
  // ../../b4m-core/packages/services/dist/src/fabFileService/search.js
4052
- import { z as z93 } from "zod";
4053
- var searchFabFilesSchema = z93.object({
4054
- search: z93.string().optional(),
4055
- filters: z93.object({
4056
- tags: z93.array(z93.string()).optional(),
4057
- type: z93.enum(["text", "pdf", "url", "image", "excel", "word", "json", "csv", "markdown", "code"]).optional(),
4058
- shared: z93.coerce.boolean().optional(),
4398
+ import { z as z94 } from "zod";
4399
+ var searchFabFilesSchema = z94.object({
4400
+ search: z94.string().optional(),
4401
+ filters: z94.object({
4402
+ tags: z94.array(z94.string()).optional(),
4403
+ type: z94.enum(["text", "pdf", "url", "image", "excel", "word", "json", "csv", "markdown", "code"]).optional(),
4404
+ shared: z94.coerce.boolean().optional(),
4059
4405
  // Indicates if the user is searching for shared files
4060
- curated: z93.coerce.boolean().optional(),
4406
+ curated: z94.coerce.boolean().optional(),
4061
4407
  // Indicates if the user is searching for curated notebook files
4062
- projectId: z93.string().optional(),
4063
- ids: z93.array(z93.string()).optional()
4408
+ projectId: z94.string().optional(),
4409
+ ids: z94.array(z94.string()).optional()
4064
4410
  // Add support for filtering by IDs
4065
4411
  }).optional(),
4066
- pagination: z93.object({
4067
- page: z93.coerce.number(),
4068
- limit: z93.coerce.number()
4412
+ pagination: z94.object({
4413
+ page: z94.coerce.number(),
4414
+ limit: z94.coerce.number()
4069
4415
  }).optional(),
4070
- order: z93.object({
4071
- by: z93.enum(["createdAt", "fileName", "fileSize"]),
4072
- direction: z93.enum(["asc", "desc"])
4416
+ order: z94.object({
4417
+ by: z94.enum(["createdAt", "fileName", "fileSize"]),
4418
+ direction: z94.enum(["asc", "desc"])
4073
4419
  }).optional(),
4074
- options: z93.object({
4075
- includeShared: z93.coerce.boolean().optional()
4420
+ options: z94.object({
4421
+ includeShared: z94.coerce.boolean().optional()
4076
4422
  }).optional()
4077
4423
  });
4078
4424
 
4079
4425
  // ../../b4m-core/packages/services/dist/src/fabFileService/addFavorite.js
4080
- import { z as z94 } from "zod";
4081
- var addFavoriteParametersSchema3 = z94.object({
4082
- fileId: z94.string()
4426
+ import { z as z95 } from "zod";
4427
+ var addFavoriteParametersSchema3 = z95.object({
4428
+ fileId: z95.string()
4083
4429
  });
4084
4430
 
4085
4431
  // ../../b4m-core/packages/services/dist/src/fabFileService/deleteFavorite.js
4086
- import { z as z95 } from "zod";
4087
- var deleteFavoriteParametersSchema4 = z95.object({
4088
- fileId: z95.string()
4432
+ import { z as z96 } from "zod";
4433
+ var deleteFavoriteParametersSchema4 = z96.object({
4434
+ fileId: z96.string()
4089
4435
  });
4090
4436
 
4091
4437
  // ../../b4m-core/packages/services/dist/src/fabFileService/toggleTags.js
4092
- import { z as z96 } from "zod";
4093
- var fabFileToggleTagsSchema = z96.object({
4094
- ids: z96.array(z96.string()),
4095
- tags: z96.array(z96.string())
4438
+ import { z as z97 } from "zod";
4439
+ var fabFileToggleTagsSchema = z97.object({
4440
+ ids: z97.array(z97.string()),
4441
+ tags: z97.array(z97.string())
4096
4442
  });
4097
4443
 
4098
4444
  // ../../b4m-core/packages/services/dist/src/fabFileService/edit.js
4099
- import { z as z97 } from "zod";
4445
+ import { z as z98 } from "zod";
4100
4446
  import { diffLines } from "diff";
4101
- var editFabFileSchema = z97.object({
4102
- id: z97.string(),
4103
- instruction: z97.string(),
4104
- selection: z97.object({
4105
- start: z97.number(),
4106
- end: z97.number()
4447
+ var editFabFileSchema = z98.object({
4448
+ id: z98.string(),
4449
+ instruction: z98.string(),
4450
+ selection: z98.object({
4451
+ start: z98.number(),
4452
+ end: z98.number()
4107
4453
  }).optional(),
4108
- preserveFormatting: z97.boolean().optional().default(true),
4109
- applyImmediately: z97.boolean().optional().default(false)
4454
+ preserveFormatting: z98.boolean().optional().default(true),
4455
+ applyImmediately: z98.boolean().optional().default(false)
4110
4456
  });
4111
4457
 
4112
4458
  // ../../b4m-core/packages/services/dist/src/fabFileService/applyEdit.js
4113
4459
  import mime2 from "mime-types";
4114
4460
  import { v4 as uuidv43 } from "uuid";
4115
- import { z as z98 } from "zod";
4116
- var applyEditSchema = z98.object({
4117
- id: z98.string(),
4118
- modifiedContent: z98.string(),
4119
- createBackup: z98.boolean().optional().default(true)
4461
+ import { z as z99 } from "zod";
4462
+ var applyEditSchema = z99.object({
4463
+ id: z99.string(),
4464
+ modifiedContent: z99.string(),
4465
+ createBackup: z99.boolean().optional().default(true)
4120
4466
  });
4121
4467
 
4122
4468
  // ../../b4m-core/packages/services/dist/src/friendshipService/respondToFriendRequest.js
4123
- import { z as z99 } from "zod";
4124
- var respondToFriendRequestSchema = z99.object({
4125
- id: z99.string(),
4469
+ import { z as z100 } from "zod";
4470
+ var respondToFriendRequestSchema = z100.object({
4471
+ id: z100.string(),
4126
4472
  /** The user ID of the recipient of the friend request */
4127
- userId: z99.string(),
4128
- accept: z99.boolean()
4473
+ userId: z100.string(),
4474
+ accept: z100.boolean()
4129
4475
  });
4130
4476
 
4131
4477
  // ../../b4m-core/packages/services/dist/src/friendshipService/unfriend.js
4132
- import { z as z100 } from "zod";
4133
- var unfriendSchema = z100.object({
4134
- friendshipId: z100.string(),
4478
+ import { z as z101 } from "zod";
4479
+ var unfriendSchema = z101.object({
4480
+ friendshipId: z101.string(),
4135
4481
  /** The user ID of the user who wants to unfriend the other user */
4136
- userId: z100.string()
4482
+ userId: z101.string()
4137
4483
  });
4138
4484
 
4139
4485
  // ../../b4m-core/packages/services/dist/src/friendshipService/list.js
4140
- import { z as z101 } from "zod";
4141
- var listFriendsSchema = z101.object({
4142
- userId: z101.string()
4486
+ import { z as z102 } from "zod";
4487
+ var listFriendsSchema = z102.object({
4488
+ userId: z102.string()
4143
4489
  });
4144
- var listPendingFriendRequestsSchema = z101.object({
4145
- userId: z101.string()
4490
+ var listPendingFriendRequestsSchema = z102.object({
4491
+ userId: z102.string()
4146
4492
  });
4147
4493
 
4148
4494
  // ../../b4m-core/packages/services/dist/src/adminService/loginAs.js
4149
- import { z as z102 } from "zod";
4150
- var loginAsSchema = z102.object({
4151
- targetUserId: z102.string()
4495
+ import { z as z103 } from "zod";
4496
+ var loginAsSchema = z103.object({
4497
+ targetUserId: z103.string()
4152
4498
  });
4153
4499
 
4154
4500
  // ../../b4m-core/packages/services/dist/src/cacheService/get.js
4155
- import { z as z103 } from "zod";
4156
- var getParamsSchema = z103.object({
4157
- key: z103.string()
4501
+ import { z as z104 } from "zod";
4502
+ var getParamsSchema = z104.object({
4503
+ key: z104.string()
4158
4504
  });
4159
4505
 
4160
4506
  // ../../b4m-core/packages/services/dist/src/cacheService/set.js
4161
- import { z as z104 } from "zod";
4162
- var setParamsSchema = z104.object({
4163
- key: z104.string(),
4164
- value: z104.any(),
4507
+ import { z as z105 } from "zod";
4508
+ var setParamsSchema = z105.object({
4509
+ key: z105.string(),
4510
+ value: z105.any(),
4165
4511
  /**
4166
4512
  * Time to live in milliseconds
4167
4513
  */
4168
- ttl: z104.number(),
4169
- recache: z104.boolean().optional()
4514
+ ttl: z105.number(),
4515
+ recache: z105.boolean().optional()
4170
4516
  });
4171
4517
 
4172
4518
  // ../../b4m-core/packages/services/dist/src/cacheService/ttl.js
4173
- import { z as z105 } from "zod";
4174
- var ttlParamsSchema = z105.object({
4175
- key: z105.string()
4519
+ import { z as z106 } from "zod";
4520
+ var ttlParamsSchema = z106.object({
4521
+ key: z106.string()
4176
4522
  });
4177
4523
 
4178
4524
  // ../../b4m-core/packages/services/dist/src/cacheService/weeklyReports.js
4179
- import { z as z106 } from "zod";
4525
+ import { z as z107 } from "zod";
4180
4526
  import dayjs3 from "dayjs";
4181
- var weeklyReportSchema = z106.object({
4182
- startDate: z106.string(),
4183
- endDate: z106.string(),
4184
- report: z106.string(),
4185
- aiInsights: z106.string().nullable()
4527
+ var weeklyReportSchema = z107.object({
4528
+ startDate: z107.string(),
4529
+ endDate: z107.string(),
4530
+ report: z107.string(),
4531
+ aiInsights: z107.string().nullable()
4186
4532
  });
4187
4533
 
4188
4534
  // ../../b4m-core/packages/services/dist/src/embeddingCacheService/generateCacheKey.js
4189
4535
  import crypto2 from "crypto";
4190
4536
 
4191
4537
  // ../../b4m-core/packages/services/dist/src/researchAgentService/create.js
4192
- import { z as z107 } from "zod";
4193
- var researchAgentCreateSchema = z107.object({
4194
- name: z107.string().min(1),
4195
- description: z107.string().min(1)
4196
- });
4197
-
4198
- // ../../b4m-core/packages/services/dist/src/researchAgentService/update.js
4199
4538
  import { z as z108 } from "zod";
4200
- var researchAgentUpdateSchema = z108.object({
4201
- id: z108.string(),
4539
+ var researchAgentCreateSchema = z108.object({
4202
4540
  name: z108.string().min(1),
4203
4541
  description: z108.string().min(1)
4204
4542
  });
4205
4543
 
4206
- // ../../b4m-core/packages/services/dist/src/researchAgentService/remove.js
4544
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/update.js
4207
4545
  import { z as z109 } from "zod";
4208
- var researchAgentRemoveSchema = z109.object({
4209
- id: z109.string()
4546
+ var researchAgentUpdateSchema = z109.object({
4547
+ id: z109.string(),
4548
+ name: z109.string().min(1),
4549
+ description: z109.string().min(1)
4210
4550
  });
4211
4551
 
4212
- // ../../b4m-core/packages/services/dist/src/researchAgentService/get.js
4552
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/remove.js
4213
4553
  import { z as z110 } from "zod";
4214
- var researchAgentGetSchema = z110.object({
4554
+ var researchAgentRemoveSchema = z110.object({
4215
4555
  id: z110.string()
4216
4556
  });
4217
4557
 
4218
- // ../../b4m-core/packages/services/dist/src/researchAgentService/listFiles.js
4558
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/get.js
4219
4559
  import { z as z111 } from "zod";
4220
- var researchAgentListFilesSchema = z111.object({
4560
+ var researchAgentGetSchema = z111.object({
4561
+ id: z111.string()
4562
+ });
4563
+
4564
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/listFiles.js
4565
+ import { z as z112 } from "zod";
4566
+ var researchAgentListFilesSchema = z112.object({
4221
4567
  /**
4222
4568
  * The ID of the research agent
4223
4569
  */
4224
- id: z111.string()
4570
+ id: z112.string()
4225
4571
  });
4226
4572
 
4227
4573
  // ../../b4m-core/packages/services/dist/src/researchTaskService/process.js
4228
- import { z as z112 } from "zod";
4574
+ import { z as z113 } from "zod";
4229
4575
 
4230
4576
  // ../../b4m-core/packages/services/dist/src/lib/turndown.js
4231
4577
  import turndown from "turndown";
@@ -4616,316 +4962,316 @@ var deepResearchTool = {
4616
4962
  };
4617
4963
 
4618
4964
  // ../../b4m-core/packages/services/dist/src/researchTaskService/process.js
4619
- var ResearchTaskProcessSchema = z112.object({
4620
- id: z112.string()
4965
+ var ResearchTaskProcessSchema = z113.object({
4966
+ id: z113.string()
4621
4967
  });
4622
4968
 
4623
4969
  // ../../b4m-core/packages/services/dist/src/researchTaskService/create.js
4624
- import { z as z113 } from "zod";
4625
- var researchTaskCreateSchema = z113.object({
4626
- researchAgentId: z113.string(),
4627
- title: z113.string().max(100),
4628
- description: z113.string().max(500),
4629
- prompt: z113.string().max(500).optional(),
4630
- type: z113.nativeEnum(ResearchTaskType),
4631
- executionType: z113.nativeEnum(ResearchTaskExecutionType).default(ResearchTaskExecutionType.ON_DEMAND),
4632
- fileTagId: z113.string().optional(),
4633
- autoGeneratedTag: z113.object({
4634
- name: z113.string(),
4635
- icon: z113.string(),
4636
- color: z113.string()
4970
+ import { z as z114 } from "zod";
4971
+ var researchTaskCreateSchema = z114.object({
4972
+ researchAgentId: z114.string(),
4973
+ title: z114.string().max(100),
4974
+ description: z114.string().max(500),
4975
+ prompt: z114.string().max(500).optional(),
4976
+ type: z114.nativeEnum(ResearchTaskType),
4977
+ executionType: z114.nativeEnum(ResearchTaskExecutionType).default(ResearchTaskExecutionType.ON_DEMAND),
4978
+ fileTagId: z114.string().optional(),
4979
+ autoGeneratedTag: z114.object({
4980
+ name: z114.string(),
4981
+ icon: z114.string(),
4982
+ color: z114.string()
4637
4983
  }).optional()
4638
4984
  });
4639
4985
  var researchTaskScrapeCreateSchema = researchTaskCreateSchema.extend({
4640
- urls: z113.array(z113.string().url()).min(1),
4641
- canDiscoverLinks: z113.boolean()
4986
+ urls: z114.array(z114.string().url()).min(1),
4987
+ canDiscoverLinks: z114.boolean()
4642
4988
  });
4643
4989
  var researchTaskPeriodicCreateSchema = researchTaskCreateSchema.extend({
4644
- executionPeriodicStartAt: z113.coerce.date(),
4645
- executionPeriodicEndAt: z113.coerce.date(),
4646
- executionPeriodicFrequency: z113.nativeEnum(ResearchTaskPeriodicFrequencyType)
4990
+ executionPeriodicStartAt: z114.coerce.date(),
4991
+ executionPeriodicEndAt: z114.coerce.date(),
4992
+ executionPeriodicFrequency: z114.nativeEnum(ResearchTaskPeriodicFrequencyType)
4647
4993
  });
4648
4994
  var researchTaskScheduledCreateSchema = researchTaskCreateSchema.extend({
4649
- executionScheduledAt: z113.coerce.date()
4995
+ executionScheduledAt: z114.coerce.date()
4650
4996
  });
4651
4997
  var researchTaskDeepResearchCreateSchema = researchTaskCreateSchema.extend({
4652
- maxDepth: z113.number().min(1).max(10).optional()
4998
+ maxDepth: z114.number().min(1).max(10).optional()
4653
4999
  });
4654
5000
 
4655
5001
  // ../../b4m-core/packages/services/dist/src/researchTaskService/search.js
4656
- import { z as z114 } from "zod";
4657
- var searchResearchTasksSchema = z114.object({
4658
- search: z114.string().optional(),
5002
+ import { z as z115 } from "zod";
5003
+ var searchResearchTasksSchema = z115.object({
5004
+ search: z115.string().optional(),
4659
5005
  // ADD FILTERS SCHEMA HERE
4660
5006
  // filters: z
4661
5007
  // .object({
4662
5008
  // userId: z.string().optional(),
4663
5009
  // })
4664
5010
  // .optional(),
4665
- pagination: z114.object({
4666
- page: z114.coerce.number().optional(),
4667
- limit: z114.coerce.number().optional()
5011
+ pagination: z115.object({
5012
+ page: z115.coerce.number().optional(),
5013
+ limit: z115.coerce.number().optional()
4668
5014
  }).optional(),
4669
- orderBy: z114.object({
4670
- by: z114.enum(["createdAt", "updatedAt"]).optional(),
4671
- direction: z114.enum(["asc", "desc"]).optional()
5015
+ orderBy: z115.object({
5016
+ by: z115.enum(["createdAt", "updatedAt"]).optional(),
5017
+ direction: z115.enum(["asc", "desc"]).optional()
4672
5018
  }).optional()
4673
5019
  });
4674
5020
 
4675
5021
  // ../../b4m-core/packages/services/dist/src/researchTaskService/get.js
4676
- import { z as z115 } from "zod";
4677
- var getResearchTaskSchema = z115.object({
4678
- id: z115.string().min(1)
5022
+ import { z as z116 } from "zod";
5023
+ var getResearchTaskSchema = z116.object({
5024
+ id: z116.string().min(1)
4679
5025
  });
4680
5026
 
4681
5027
  // ../../b4m-core/packages/services/dist/src/researchTaskService/update.js
4682
- import { z as z116 } from "zod";
4683
- var updateResearchTaskSchema = z116.object({
4684
- id: z116.string(),
4685
- title: z116.string(),
4686
- description: z116.string(),
4687
- type: z116.nativeEnum(ResearchTaskType)
5028
+ import { z as z117 } from "zod";
5029
+ var updateResearchTaskSchema = z117.object({
5030
+ id: z117.string(),
5031
+ title: z117.string(),
5032
+ description: z117.string(),
5033
+ type: z117.nativeEnum(ResearchTaskType)
4688
5034
  });
4689
5035
  var researchTaskScrapeUpdateSchema = updateResearchTaskSchema.extend({
4690
- urls: z116.array(z116.string().url()).min(1),
4691
- canDiscoverLinks: z116.boolean()
5036
+ urls: z117.array(z117.string().url()).min(1),
5037
+ canDiscoverLinks: z117.boolean()
4692
5038
  });
4693
5039
 
4694
5040
  // ../../b4m-core/packages/services/dist/src/researchTaskService/listByAgentId.js
4695
- import { z as z117 } from "zod";
4696
- var listByAgentIdSchema = z117.object({
4697
- researchAgentId: z117.string()
5041
+ import { z as z118 } from "zod";
5042
+ var listByAgentIdSchema = z118.object({
5043
+ researchAgentId: z118.string()
4698
5044
  });
4699
5045
 
4700
5046
  // ../../b4m-core/packages/services/dist/src/researchTaskService/remove.js
4701
- import { z as z118 } from "zod";
4702
- var researchTaskRemoveSchema = z118.object({
4703
- id: z118.string().min(1)
5047
+ import { z as z119 } from "zod";
5048
+ var researchTaskRemoveSchema = z119.object({
5049
+ id: z119.string().min(1)
4704
5050
  });
4705
5051
 
4706
5052
  // ../../b4m-core/packages/services/dist/src/researchTaskService/retry.js
4707
- import { z as z119 } from "zod";
4708
- var researchTaskRetrySchema = z119.object({
4709
- id: z119.string(),
4710
- userId: z119.string()
5053
+ import { z as z120 } from "zod";
5054
+ var researchTaskRetrySchema = z120.object({
5055
+ id: z120.string(),
5056
+ userId: z120.string()
4711
5057
  });
4712
5058
 
4713
5059
  // ../../b4m-core/packages/services/dist/src/researchTaskService/processDiscoveredLinks.js
4714
5060
  import axios4 from "axios";
4715
- import { z as z120 } from "zod";
5061
+ import { z as z121 } from "zod";
4716
5062
  import plimit from "p-limit";
4717
5063
  import pLimit2 from "p-limit";
4718
- var researchTaskProcessDiscoveredLinksSchema = z120.object({
4719
- id: z120.string()
5064
+ var researchTaskProcessDiscoveredLinksSchema = z121.object({
5065
+ id: z121.string()
4720
5066
  });
4721
5067
 
4722
5068
  // ../../b4m-core/packages/services/dist/src/researchTaskService/downloadRelevantLinks.js
4723
- import { z as z121 } from "zod";
5069
+ import { z as z122 } from "zod";
4724
5070
  import plimit2 from "p-limit";
4725
5071
  import axios5 from "axios";
4726
5072
  import { fileTypeFromBuffer } from "file-type";
4727
- var researchTaskDownloadRelevantLinksSchema = z121.object({
4728
- id: z121.string()
5073
+ var researchTaskDownloadRelevantLinksSchema = z122.object({
5074
+ id: z122.string()
4729
5075
  });
4730
5076
 
4731
5077
  // ../../b4m-core/packages/services/dist/src/researchData/remove.js
4732
- import { z as z122 } from "zod";
4733
- var researchDataRemoveSchema = z122.object({
4734
- id: z122.string(),
4735
- researchAgentId: z122.string()
5078
+ import { z as z123 } from "zod";
5079
+ var researchDataRemoveSchema = z123.object({
5080
+ id: z123.string(),
5081
+ researchAgentId: z123.string()
4736
5082
  });
4737
5083
 
4738
5084
  // ../../b4m-core/packages/services/dist/src/taskSchedulerService/create.js
4739
- import { z as z123 } from "zod";
4740
- var researchTaskPayload = z123.object({
4741
- id: z123.string(),
4742
- userId: z123.string()
5085
+ import { z as z124 } from "zod";
5086
+ var researchTaskPayload = z124.object({
5087
+ id: z124.string(),
5088
+ userId: z124.string()
4743
5089
  });
4744
- var customTaskPayload = z123.object({
4745
- test: z123.string()
5090
+ var customTaskPayload = z124.object({
5091
+ test: z124.string()
4746
5092
  });
4747
- var taskSchedulerCreate = z123.discriminatedUnion("handler", [
4748
- z123.object({
4749
- handler: z123.literal(TaskScheduleHandler.RESEARCH_TASK_PROCESS),
5093
+ var taskSchedulerCreate = z124.discriminatedUnion("handler", [
5094
+ z124.object({
5095
+ handler: z124.literal(TaskScheduleHandler.RESEARCH_TASK_PROCESS),
4750
5096
  payload: researchTaskPayload,
4751
- processDate: z123.date()
5097
+ processDate: z124.date()
4752
5098
  }),
4753
- z123.object({
4754
- handler: z123.literal(TaskScheduleHandler.CUSTOM_TASK_PROCESS),
5099
+ z124.object({
5100
+ handler: z124.literal(TaskScheduleHandler.CUSTOM_TASK_PROCESS),
4755
5101
  payload: customTaskPayload,
4756
- processDate: z123.date()
5102
+ processDate: z124.date()
4757
5103
  })
4758
5104
  ]);
4759
5105
 
4760
5106
  // ../../b4m-core/packages/services/dist/src/tagService/createFileTag.js
4761
- import { z as z124 } from "zod";
4762
- var tagCreateFileTagSchema = z124.object({
4763
- name: z124.string(),
4764
- icon: z124.string().optional(),
4765
- color: z124.string().optional(),
4766
- description: z124.string().optional()
4767
- });
4768
-
4769
- // ../../b4m-core/packages/services/dist/src/tagService/create.js
4770
5107
  import { z as z125 } from "zod";
4771
- var tagCreateSchema = z125.object({
5108
+ var tagCreateFileTagSchema = z125.object({
4772
5109
  name: z125.string(),
4773
5110
  icon: z125.string().optional(),
4774
- description: z125.string().optional(),
4775
5111
  color: z125.string().optional(),
4776
- type: z125.nativeEnum(TagType)
5112
+ description: z125.string().optional()
4777
5113
  });
4778
5114
 
4779
- // ../../b4m-core/packages/services/dist/src/tagService/update.js
5115
+ // ../../b4m-core/packages/services/dist/src/tagService/create.js
4780
5116
  import { z as z126 } from "zod";
4781
- var tagUpdateSchema = z126.object({
4782
- id: z126.string(),
4783
- name: z126.string().optional(),
5117
+ var tagCreateSchema = z126.object({
5118
+ name: z126.string(),
4784
5119
  icon: z126.string().optional(),
4785
5120
  description: z126.string().optional(),
4786
- color: z126.string().optional()
5121
+ color: z126.string().optional(),
5122
+ type: z126.nativeEnum(TagType)
4787
5123
  });
4788
5124
 
4789
- // ../../b4m-core/packages/services/dist/src/tagService/remove.js
5125
+ // ../../b4m-core/packages/services/dist/src/tagService/update.js
4790
5126
  import { z as z127 } from "zod";
4791
- var tagRemoveSchema = z127.object({
4792
- id: z127.string()
5127
+ var tagUpdateSchema = z127.object({
5128
+ id: z127.string(),
5129
+ name: z127.string().optional(),
5130
+ icon: z127.string().optional(),
5131
+ description: z127.string().optional(),
5132
+ color: z127.string().optional()
4793
5133
  });
4794
5134
 
4795
- // ../../b4m-core/packages/services/dist/src/artifactService/create.js
5135
+ // ../../b4m-core/packages/services/dist/src/tagService/remove.js
4796
5136
  import { z as z128 } from "zod";
4797
- var createArtifactSchema = z128.object({
4798
- id: z128.string().optional(),
5137
+ var tagRemoveSchema = z128.object({
5138
+ id: z128.string()
5139
+ });
5140
+
5141
+ // ../../b4m-core/packages/services/dist/src/artifactService/create.js
5142
+ import { z as z129 } from "zod";
5143
+ var createArtifactSchema = z129.object({
5144
+ id: z129.string().optional(),
4799
5145
  // Allow custom ID for AI-generated artifacts
4800
- type: z128.enum(["mermaid", "recharts", "python", "react", "html", "svg", "code", "quest", "file", "questmaster"]),
4801
- title: z128.string().min(1).max(255),
4802
- description: z128.string().max(1e3).optional(),
4803
- content: z128.string().min(1),
4804
- projectId: z128.string().optional(),
4805
- organizationId: z128.string().optional(),
4806
- visibility: z128.enum(["private", "project", "organization", "public"]).default("private"),
4807
- tags: z128.array(z128.string().max(50)).max(20).default([]),
4808
- versionTag: z128.string().max(100).optional(),
4809
- sourceQuestId: z128.string().optional(),
4810
- sessionId: z128.string().optional(),
4811
- parentArtifactId: z128.string().optional(),
4812
- permissions: z128.object({
4813
- canRead: z128.array(z128.string()).default([]),
4814
- canWrite: z128.array(z128.string()).default([]),
4815
- canDelete: z128.array(z128.string()).default([]),
4816
- isPublic: z128.boolean().default(false),
4817
- inheritFromProject: z128.boolean().default(true)
5146
+ type: z129.enum(["mermaid", "recharts", "python", "react", "html", "svg", "code", "quest", "file", "questmaster"]),
5147
+ title: z129.string().min(1).max(255),
5148
+ description: z129.string().max(1e3).optional(),
5149
+ content: z129.string().min(1),
5150
+ projectId: z129.string().optional(),
5151
+ organizationId: z129.string().optional(),
5152
+ visibility: z129.enum(["private", "project", "organization", "public"]).default("private"),
5153
+ tags: z129.array(z129.string().max(50)).max(20).default([]),
5154
+ versionTag: z129.string().max(100).optional(),
5155
+ sourceQuestId: z129.string().optional(),
5156
+ sessionId: z129.string().optional(),
5157
+ parentArtifactId: z129.string().optional(),
5158
+ permissions: z129.object({
5159
+ canRead: z129.array(z129.string()).default([]),
5160
+ canWrite: z129.array(z129.string()).default([]),
5161
+ canDelete: z129.array(z129.string()).default([]),
5162
+ isPublic: z129.boolean().default(false),
5163
+ inheritFromProject: z129.boolean().default(true)
4818
5164
  }).optional(),
4819
- metadata: z128.record(z128.unknown()).default({})
5165
+ metadata: z129.record(z129.unknown()).default({})
4820
5166
  });
4821
5167
 
4822
5168
  // ../../b4m-core/packages/services/dist/src/artifactService/get.js
4823
- import { z as z129 } from "zod";
4824
- var getArtifactSchema = z129.object({
4825
- id: z129.string(),
4826
- includeContent: z129.boolean().default(false),
4827
- includeVersions: z129.boolean().default(false),
4828
- version: z129.number().optional()
5169
+ import { z as z130 } from "zod";
5170
+ var getArtifactSchema = z130.object({
5171
+ id: z130.string(),
5172
+ includeContent: z130.boolean().default(false),
5173
+ includeVersions: z130.boolean().default(false),
5174
+ version: z130.number().optional()
4829
5175
  });
4830
5176
 
4831
5177
  // ../../b4m-core/packages/services/dist/src/artifactService/list.js
4832
- import { z as z130 } from "zod";
4833
- var listArtifactsSchema = z130.object({
4834
- type: z130.string().optional(),
4835
- status: z130.enum(["draft", "review", "published", "archived"]).optional(),
4836
- visibility: z130.enum(["private", "project", "organization", "public"]).optional(),
4837
- projectId: z130.string().optional(),
4838
- sessionId: z130.string().optional(),
4839
- tags: z130.array(z130.string()).optional(),
4840
- search: z130.string().optional(),
4841
- limit: z130.number().min(1).max(100).default(20),
4842
- offset: z130.number().min(0).default(0),
4843
- sortBy: z130.enum(["createdAt", "updatedAt", "title", "type"]).default("updatedAt"),
4844
- sortOrder: z130.enum(["asc", "desc"]).default("desc"),
4845
- includeDeleted: z130.boolean().default(false)
5178
+ import { z as z131 } from "zod";
5179
+ var listArtifactsSchema = z131.object({
5180
+ type: z131.string().optional(),
5181
+ status: z131.enum(["draft", "review", "published", "archived"]).optional(),
5182
+ visibility: z131.enum(["private", "project", "organization", "public"]).optional(),
5183
+ projectId: z131.string().optional(),
5184
+ sessionId: z131.string().optional(),
5185
+ tags: z131.array(z131.string()).optional(),
5186
+ search: z131.string().optional(),
5187
+ limit: z131.number().min(1).max(100).default(20),
5188
+ offset: z131.number().min(0).default(0),
5189
+ sortBy: z131.enum(["createdAt", "updatedAt", "title", "type"]).default("updatedAt"),
5190
+ sortOrder: z131.enum(["asc", "desc"]).default("desc"),
5191
+ includeDeleted: z131.boolean().default(false)
4846
5192
  });
4847
5193
 
4848
5194
  // ../../b4m-core/packages/services/dist/src/artifactService/update.js
4849
- import { z as z131 } from "zod";
4850
- var updateArtifactSchema = z131.object({
4851
- id: z131.string(),
4852
- title: z131.string().min(1).max(255).optional(),
4853
- description: z131.string().max(1e3).optional(),
4854
- content: z131.string().optional(),
4855
- visibility: z131.enum(["private", "project", "organization", "public"]).optional(),
4856
- status: z131.enum(["draft", "review", "published", "archived"]).optional(),
4857
- tags: z131.array(z131.string().max(50)).max(20).optional(),
4858
- versionTag: z131.string().max(100).optional(),
4859
- permissions: z131.object({
4860
- canRead: z131.array(z131.string()).optional(),
4861
- canWrite: z131.array(z131.string()).optional(),
4862
- canDelete: z131.array(z131.string()).optional(),
4863
- isPublic: z131.boolean().optional(),
4864
- inheritFromProject: z131.boolean().optional()
5195
+ import { z as z132 } from "zod";
5196
+ var updateArtifactSchema = z132.object({
5197
+ id: z132.string(),
5198
+ title: z132.string().min(1).max(255).optional(),
5199
+ description: z132.string().max(1e3).optional(),
5200
+ content: z132.string().optional(),
5201
+ visibility: z132.enum(["private", "project", "organization", "public"]).optional(),
5202
+ status: z132.enum(["draft", "review", "published", "archived"]).optional(),
5203
+ tags: z132.array(z132.string().max(50)).max(20).optional(),
5204
+ versionTag: z132.string().max(100).optional(),
5205
+ permissions: z132.object({
5206
+ canRead: z132.array(z132.string()).optional(),
5207
+ canWrite: z132.array(z132.string()).optional(),
5208
+ canDelete: z132.array(z132.string()).optional(),
5209
+ isPublic: z132.boolean().optional(),
5210
+ inheritFromProject: z132.boolean().optional()
4865
5211
  }).optional(),
4866
- metadata: z131.record(z131.unknown()).optional(),
4867
- changes: z131.array(z131.string()).optional(),
4868
- changeDescription: z131.string().max(1e3).optional(),
4869
- createNewVersion: z131.boolean().optional(),
4870
- versionMessage: z131.string().max(500).optional()
5212
+ metadata: z132.record(z132.unknown()).optional(),
5213
+ changes: z132.array(z132.string()).optional(),
5214
+ changeDescription: z132.string().max(1e3).optional(),
5215
+ createNewVersion: z132.boolean().optional(),
5216
+ versionMessage: z132.string().max(500).optional()
4871
5217
  });
4872
5218
 
4873
5219
  // ../../b4m-core/packages/services/dist/src/artifactService/delete.js
4874
- import { z as z132 } from "zod";
4875
- var deleteArtifactSchema = z132.object({
4876
- id: z132.string(),
4877
- hardDelete: z132.boolean().default(false)
5220
+ import { z as z133 } from "zod";
5221
+ var deleteArtifactSchema = z133.object({
5222
+ id: z133.string(),
5223
+ hardDelete: z133.boolean().default(false)
4878
5224
  // For future implementation
4879
5225
  });
4880
5226
 
4881
5227
  // ../../b4m-core/packages/services/dist/src/questMasterService/create.js
4882
- import { z as z133 } from "zod";
4883
- var questSchema = z133.object({
4884
- id: z133.string(),
4885
- title: z133.string().min(1).max(255),
4886
- description: z133.string().max(1e3),
4887
- status: z133.enum(["not_started", "in_progress", "completed", "blocked"]).default("not_started"),
4888
- order: z133.number().min(0),
4889
- dependencies: z133.array(z133.string()).default([]),
4890
- estimatedTime: z133.string().optional()
4891
- });
4892
- var questResourceSchema = z133.object({
4893
- title: z133.string().min(1).max(255),
4894
- url: z133.string().url(),
4895
- type: z133.enum(["documentation", "tutorial", "reference", "example"])
4896
- });
4897
- var createQuestMasterSchema = z133.object({
4898
- title: z133.string().min(1).max(255),
4899
- description: z133.string().max(1e3).optional(),
4900
- goal: z133.string().min(1).max(1e3),
4901
- complexity: z133.enum(["beginner", "intermediate", "advanced", "expert"]),
4902
- estimatedTotalTime: z133.string().optional(),
4903
- prerequisites: z133.array(z133.string().max(200)).default([]),
4904
- quests: z133.array(questSchema).min(1),
4905
- resources: z133.array(questResourceSchema).default([]),
4906
- projectId: z133.string().optional(),
4907
- organizationId: z133.string().optional(),
4908
- visibility: z133.enum(["private", "project", "organization", "public"]).default("private"),
4909
- tags: z133.array(z133.string().max(50)).max(20).default([]),
4910
- permissions: z133.object({
4911
- canRead: z133.array(z133.string()).default([]),
4912
- canWrite: z133.array(z133.string()).default([]),
4913
- canDelete: z133.array(z133.string()).default([]),
4914
- isPublic: z133.boolean().default(false),
4915
- inheritFromProject: z133.boolean().default(true)
5228
+ import { z as z134 } from "zod";
5229
+ var questSchema = z134.object({
5230
+ id: z134.string(),
5231
+ title: z134.string().min(1).max(255),
5232
+ description: z134.string().max(1e3),
5233
+ status: z134.enum(["not_started", "in_progress", "completed", "blocked"]).default("not_started"),
5234
+ order: z134.number().min(0),
5235
+ dependencies: z134.array(z134.string()).default([]),
5236
+ estimatedTime: z134.string().optional()
5237
+ });
5238
+ var questResourceSchema = z134.object({
5239
+ title: z134.string().min(1).max(255),
5240
+ url: z134.string().url(),
5241
+ type: z134.enum(["documentation", "tutorial", "reference", "example"])
5242
+ });
5243
+ var createQuestMasterSchema = z134.object({
5244
+ title: z134.string().min(1).max(255),
5245
+ description: z134.string().max(1e3).optional(),
5246
+ goal: z134.string().min(1).max(1e3),
5247
+ complexity: z134.enum(["beginner", "intermediate", "advanced", "expert"]),
5248
+ estimatedTotalTime: z134.string().optional(),
5249
+ prerequisites: z134.array(z134.string().max(200)).default([]),
5250
+ quests: z134.array(questSchema).min(1),
5251
+ resources: z134.array(questResourceSchema).default([]),
5252
+ projectId: z134.string().optional(),
5253
+ organizationId: z134.string().optional(),
5254
+ visibility: z134.enum(["private", "project", "organization", "public"]).default("private"),
5255
+ tags: z134.array(z134.string().max(50)).max(20).default([]),
5256
+ permissions: z134.object({
5257
+ canRead: z134.array(z134.string()).default([]),
5258
+ canWrite: z134.array(z134.string()).default([]),
5259
+ canDelete: z134.array(z134.string()).default([]),
5260
+ isPublic: z134.boolean().default(false),
5261
+ inheritFromProject: z134.boolean().default(true)
4916
5262
  }).optional(),
4917
- sourceQuestId: z133.string().optional(),
4918
- sessionId: z133.string().optional(),
4919
- metadata: z133.record(z133.unknown()).default({})
5263
+ sourceQuestId: z134.string().optional(),
5264
+ sessionId: z134.string().optional(),
5265
+ metadata: z134.record(z134.unknown()).default({})
4920
5266
  });
4921
5267
 
4922
5268
  // ../../b4m-core/packages/services/dist/src/questMasterService/updateQuestStatus.js
4923
- import { z as z134 } from "zod";
4924
- var updateQuestStatusSchema = z134.object({
4925
- artifactId: z134.string(),
4926
- questId: z134.string(),
4927
- status: z134.enum(["not_started", "in_progress", "completed", "blocked"]),
4928
- completionNote: z134.string().max(500).optional()
5269
+ import { z as z135 } from "zod";
5270
+ var updateQuestStatusSchema = z135.object({
5271
+ artifactId: z135.string(),
5272
+ questId: z135.string(),
5273
+ status: z135.enum(["not_started", "in_progress", "completed", "blocked"]),
5274
+ completionNote: z135.string().max(500).optional()
4929
5275
  });
4930
5276
 
4931
5277
  // ../../b4m-core/packages/services/dist/src/dataLakeService/opensearchClient.js
@@ -4945,63 +5291,63 @@ import { v4 as uuidv44 } from "uuid";
4945
5291
  import { randomUUID as randomUUID5 } from "crypto";
4946
5292
 
4947
5293
  // ../../b4m-core/packages/services/dist/src/emailIngestionService/types.js
4948
- import { z as z135 } from "zod";
4949
- var processIngestedEmailOptionsSchema = z135.object({
4950
- platformDomain: z135.string().optional(),
4951
- isNewsletter: z135.boolean().optional()
5294
+ import { z as z136 } from "zod";
5295
+ var processIngestedEmailOptionsSchema = z136.object({
5296
+ platformDomain: z136.string().optional(),
5297
+ isNewsletter: z136.boolean().optional()
4952
5298
  }).optional();
4953
- var emailAttachmentSchema = z135.object({
4954
- filename: z135.string().optional(),
4955
- contentType: z135.string().optional(),
4956
- contentDisposition: z135.string().optional(),
4957
- size: z135.number().min(0),
4958
- content: z135.instanceof(Buffer),
4959
- related: z135.boolean().optional()
4960
- });
4961
- var parsedEmailObjectSchema = z135.object({
4962
- messageId: z135.string().optional(),
4963
- inReplyTo: z135.string().optional(),
4964
- references: z135.union([z135.string(), z135.array(z135.string())]).optional(),
4965
- from: z135.any().optional(),
5299
+ var emailAttachmentSchema = z136.object({
5300
+ filename: z136.string().optional(),
5301
+ contentType: z136.string().optional(),
5302
+ contentDisposition: z136.string().optional(),
5303
+ size: z136.number().min(0),
5304
+ content: z136.instanceof(Buffer),
5305
+ related: z136.boolean().optional()
5306
+ });
5307
+ var parsedEmailObjectSchema = z136.object({
5308
+ messageId: z136.string().optional(),
5309
+ inReplyTo: z136.string().optional(),
5310
+ references: z136.union([z136.string(), z136.array(z136.string())]).optional(),
5311
+ from: z136.any().optional(),
4966
5312
  // Complex email address object
4967
- to: z135.any().optional(),
4968
- cc: z135.any().optional(),
4969
- bcc: z135.any().optional(),
4970
- subject: z135.string().optional(),
4971
- date: z135.date().optional(),
4972
- text: z135.string().optional(),
4973
- html: z135.string().optional(),
4974
- attachments: z135.array(emailAttachmentSchema).optional()
4975
- });
4976
- var processIngestedEmailSchema = z135.object({
5313
+ to: z136.any().optional(),
5314
+ cc: z136.any().optional(),
5315
+ bcc: z136.any().optional(),
5316
+ subject: z136.string().optional(),
5317
+ date: z136.date().optional(),
5318
+ text: z136.string().optional(),
5319
+ html: z136.string().optional(),
5320
+ attachments: z136.array(emailAttachmentSchema).optional()
5321
+ });
5322
+ var processIngestedEmailSchema = z136.object({
4977
5323
  parsedEmail: parsedEmailObjectSchema,
4978
- rawEmailS3Key: z135.string().min(1, "rawEmailS3Key cannot be empty"),
5324
+ rawEmailS3Key: z136.string().min(1, "rawEmailS3Key cannot be empty"),
4979
5325
  options: processIngestedEmailOptionsSchema
4980
5326
  });
4981
5327
 
4982
5328
  // ../../b4m-core/packages/services/dist/src/emailAnalysisService/types.js
4983
- import { z as z136 } from "zod";
4984
- var llmAnalysisResponseSchema = z136.object({
4985
- summary: z136.string().min(1, "Summary cannot be empty"),
4986
- entities: z136.object({
4987
- companies: z136.array(z136.string()).default([]),
4988
- people: z136.array(z136.string()).default([]),
4989
- products: z136.array(z136.string()).default([]),
4990
- technologies: z136.array(z136.string()).default([])
5329
+ import { z as z137 } from "zod";
5330
+ var llmAnalysisResponseSchema = z137.object({
5331
+ summary: z137.string().min(1, "Summary cannot be empty"),
5332
+ entities: z137.object({
5333
+ companies: z137.array(z137.string()).default([]),
5334
+ people: z137.array(z137.string()).default([]),
5335
+ products: z137.array(z137.string()).default([]),
5336
+ technologies: z137.array(z137.string()).default([])
4991
5337
  }),
4992
- sentiment: z136.enum(["positive", "neutral", "negative", "urgent"]),
4993
- actionItems: z136.array(z136.object({
4994
- description: z136.string(),
4995
- deadline: z136.string().optional()
5338
+ sentiment: z137.enum(["positive", "neutral", "negative", "urgent"]),
5339
+ actionItems: z137.array(z137.object({
5340
+ description: z137.string(),
5341
+ deadline: z137.string().optional()
4996
5342
  // ISO date string from LLM
4997
5343
  })).default([]),
4998
- privacyRecommendation: z136.enum(["public", "team", "private"]),
4999
- embargoDetected: z136.boolean().default(false),
5000
- suggestedTags: z136.array(z136.string()).default([])
5344
+ privacyRecommendation: z137.enum(["public", "team", "private"]),
5345
+ embargoDetected: z137.boolean().default(false),
5346
+ suggestedTags: z137.array(z137.string()).default([])
5001
5347
  });
5002
5348
 
5003
5349
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletion.js
5004
- import { z as z138 } from "zod";
5350
+ import { z as z139 } from "zod";
5005
5351
 
5006
5352
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletionInvoke.js
5007
5353
  import { fromZodError } from "zod-validation-error";
@@ -5115,8 +5461,8 @@ async function processAndStoreImages(images, context) {
5115
5461
  const buffer = await downloadImage(image);
5116
5462
  const fileType = await fileTypeFromBuffer2(buffer);
5117
5463
  const filename = `${uuidv45()}.${fileType?.ext}`;
5118
- const path15 = await context.imageGenerateStorage.upload(buffer, filename, {});
5119
- return path15;
5464
+ const path16 = await context.imageGenerateStorage.upload(buffer, filename, {});
5465
+ return path16;
5120
5466
  }));
5121
5467
  }
5122
5468
  async function updateQuestAndReturnMarkdown(storedImageUrls, context) {
@@ -6089,17 +6435,17 @@ var rechartsTool = {
6089
6435
  };
6090
6436
 
6091
6437
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/editFile/index.js
6092
- import { z as z137 } from "zod";
6438
+ import { z as z138 } from "zod";
6093
6439
  import { diffLines as diffLines2 } from "diff";
6094
- var editFileSchema = z137.object({
6095
- fileId: z137.string().describe("The ID of the file to edit"),
6096
- instruction: z137.string().describe("Natural language instruction describing the changes to make"),
6097
- selection: z137.object({
6098
- start: z137.number().describe("Starting character position of the selection"),
6099
- end: z137.number().describe("Ending character position of the selection")
6440
+ var editFileSchema = z138.object({
6441
+ fileId: z138.string().describe("The ID of the file to edit"),
6442
+ instruction: z138.string().describe("Natural language instruction describing the changes to make"),
6443
+ selection: z138.object({
6444
+ start: z138.number().describe("Starting character position of the selection"),
6445
+ end: z138.number().describe("Ending character position of the selection")
6100
6446
  }).optional().describe("Optional selection range to edit within the file"),
6101
- preserveFormatting: z137.boolean().optional().default(true).describe("Whether to preserve the original formatting style"),
6102
- returnDiff: z137.boolean().optional().default(true).describe("Whether to return a diff of the changes")
6447
+ preserveFormatting: z138.boolean().optional().default(true).describe("Whether to preserve the original formatting style"),
6448
+ returnDiff: z138.boolean().optional().default(true).describe("Whether to return a diff of the changes")
6103
6449
  });
6104
6450
  function generateSimpleDiff(original, modified) {
6105
6451
  const differences = diffLines2(original, modified);
@@ -6328,8 +6674,8 @@ async function processAndStoreImage(imageUrl, context) {
6328
6674
  const buffer = await downloadImage2(imageUrl);
6329
6675
  const fileType = await fileTypeFromBuffer3(buffer);
6330
6676
  const filename = `${uuidv46()}.${fileType?.ext}`;
6331
- const path15 = await context.imageGenerateStorage.upload(buffer, filename, {});
6332
- return path15;
6677
+ const path16 = await context.imageGenerateStorage.upload(buffer, filename, {});
6678
+ return path16;
6333
6679
  }
6334
6680
  async function updateQuestAndReturnMarkdown2(storedImagePath, context) {
6335
6681
  await context.onFinish?.("edit_image", storedImagePath);
@@ -7858,8 +8204,8 @@ var getHeliocentricCoords = (planet, T) => {
7858
8204
  const sinNode = Math.sin(longNode);
7859
8205
  const x = r * (cosNode * cosOmega - sinNode * sinOmega * cosI);
7860
8206
  const y = r * (sinNode * cosOmega + cosNode * sinOmega * cosI);
7861
- const z144 = r * sinOmega * sinI;
7862
- return { x, y, z: z144, r };
8207
+ const z145 = r * sinOmega * sinI;
8208
+ return { x, y, z: z145, r };
7863
8209
  };
7864
8210
  var getGeocentricEcliptic = (planet, earth) => {
7865
8211
  const dx = planet.x - earth.x;
@@ -8166,15 +8512,15 @@ var planetVisibilityTool = {
8166
8512
  };
8167
8513
 
8168
8514
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/fileRead/index.js
8169
- import { promises as fs7 } from "fs";
8515
+ import { promises as fs8 } from "fs";
8170
8516
  import { existsSync as existsSync4, statSync as statSync4 } from "fs";
8171
- import path6 from "path";
8517
+ import path7 from "path";
8172
8518
  var MAX_FILE_SIZE2 = 10 * 1024 * 1024;
8173
8519
  async function readFileContent(params) {
8174
8520
  const { path: filePath, encoding = "utf-8", maxLines } = params;
8175
- const normalizedPath = path6.normalize(filePath);
8176
- const resolvedPath = path6.resolve(process.cwd(), normalizedPath);
8177
- const cwd = path6.resolve(process.cwd());
8521
+ const normalizedPath = path7.normalize(filePath);
8522
+ const resolvedPath = path7.resolve(process.cwd(), normalizedPath);
8523
+ const cwd = path7.resolve(process.cwd());
8178
8524
  if (!resolvedPath.startsWith(cwd)) {
8179
8525
  throw new Error(`Access denied: Cannot read files outside of current working directory`);
8180
8526
  }
@@ -8192,7 +8538,7 @@ async function readFileContent(params) {
8192
8538
  if (isBinary && encoding === "utf-8") {
8193
8539
  throw new Error(`File appears to be binary. Use encoding 'base64' to read binary files, or specify a different encoding.`);
8194
8540
  }
8195
- const content = await fs7.readFile(resolvedPath, encoding);
8541
+ const content = await fs8.readFile(resolvedPath, encoding);
8196
8542
  if (maxLines && typeof content === "string") {
8197
8543
  const lines = content.split("\n");
8198
8544
  if (lines.length > maxLines) {
@@ -8207,7 +8553,7 @@ ${content}`;
8207
8553
  }
8208
8554
  async function checkIfBinary(filePath) {
8209
8555
  const buffer = Buffer.alloc(8192);
8210
- const fd = await fs7.open(filePath, "r");
8556
+ const fd = await fs8.open(filePath, "r");
8211
8557
  try {
8212
8558
  const { bytesRead } = await fd.read(buffer, 0, 8192, 0);
8213
8559
  const chunk = buffer.slice(0, bytesRead);
@@ -8224,7 +8570,7 @@ var fileReadTool = {
8224
8570
  context.logger.info("\u{1F4C4} FileRead: Reading file", { path: params.path });
8225
8571
  try {
8226
8572
  const content = await readFileContent(params);
8227
- const stats = statSync4(path6.resolve(process.cwd(), path6.normalize(params.path)));
8573
+ const stats = statSync4(path7.resolve(process.cwd(), path7.normalize(params.path)));
8228
8574
  context.logger.info("\u2705 FileRead: Success", {
8229
8575
  path: params.path,
8230
8576
  size: stats.size,
@@ -8233,7 +8579,8 @@ var fileReadTool = {
8233
8579
  return content;
8234
8580
  } catch (error) {
8235
8581
  context.logger.error("\u274C FileRead: Failed", error);
8236
- throw error;
8582
+ const errorMessage = error instanceof Error ? error.message : String(error);
8583
+ return `Error reading file: ${errorMessage}`;
8237
8584
  }
8238
8585
  },
8239
8586
  toolSchema: {
@@ -8263,25 +8610,25 @@ var fileReadTool = {
8263
8610
  };
8264
8611
 
8265
8612
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/createFile/index.js
8266
- import { promises as fs8 } from "fs";
8613
+ import { promises as fs9 } from "fs";
8267
8614
  import { existsSync as existsSync5 } from "fs";
8268
- import path7 from "path";
8615
+ import path8 from "path";
8269
8616
  async function createFile(params) {
8270
8617
  const { path: filePath, content, createDirectories = true } = params;
8271
- const normalizedPath = path7.normalize(filePath);
8272
- const resolvedPath = path7.resolve(process.cwd(), normalizedPath);
8273
- const cwd = path7.resolve(process.cwd());
8618
+ const normalizedPath = path8.normalize(filePath);
8619
+ const resolvedPath = path8.resolve(process.cwd(), normalizedPath);
8620
+ const cwd = path8.resolve(process.cwd());
8274
8621
  if (!resolvedPath.startsWith(cwd)) {
8275
8622
  throw new Error(`Access denied: Cannot create files outside of current working directory`);
8276
8623
  }
8277
8624
  const fileExists = existsSync5(resolvedPath);
8278
8625
  const action = fileExists ? "overwritten" : "created";
8279
8626
  if (createDirectories) {
8280
- const dir = path7.dirname(resolvedPath);
8281
- await fs8.mkdir(dir, { recursive: true });
8627
+ const dir = path8.dirname(resolvedPath);
8628
+ await fs9.mkdir(dir, { recursive: true });
8282
8629
  }
8283
- await fs8.writeFile(resolvedPath, content, "utf-8");
8284
- const stats = await fs8.stat(resolvedPath);
8630
+ await fs9.writeFile(resolvedPath, content, "utf-8");
8631
+ const stats = await fs9.stat(resolvedPath);
8285
8632
  const lines = content.split("\n").length;
8286
8633
  return `File ${action} successfully: ${filePath}
8287
8634
  Size: ${stats.size} bytes
@@ -8292,7 +8639,7 @@ var createFileTool = {
8292
8639
  implementation: (context) => ({
8293
8640
  toolFn: async (value) => {
8294
8641
  const params = value;
8295
- const fileExists = existsSync5(path7.resolve(process.cwd(), path7.normalize(params.path)));
8642
+ const fileExists = existsSync5(path8.resolve(process.cwd(), path8.normalize(params.path)));
8296
8643
  context.logger.info(`\u{1F4DD} CreateFile: ${fileExists ? "Overwriting" : "Creating"} file`, {
8297
8644
  path: params.path,
8298
8645
  size: params.content.length
@@ -8334,7 +8681,7 @@ var createFileTool = {
8334
8681
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/globFiles/index.js
8335
8682
  import { readdir } from "fs/promises";
8336
8683
  import { statSync as statSync5 } from "fs";
8337
- import path8 from "path";
8684
+ import path9 from "path";
8338
8685
  function matchGlob(filePath, pattern) {
8339
8686
  let regexPattern = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\?/g, ".").replace(/\{([^}]+)\}/g, (_, options) => `(${options.split(",").join("|")})`).replace(/\[([^\]]+)\]/g, "[$1]");
8340
8687
  regexPattern = regexPattern.replace(/\{\{GLOBSTAR\}\}\//g, "(.*/)?").replace(/\/\{\{GLOBSTAR\}\}/g, "(/.*)?").replace(/\{\{GLOBSTAR\}\}/g, ".*");
@@ -8352,8 +8699,8 @@ async function walkDir(dir, pattern, includeHidden, maxResults, basePath = "") {
8352
8699
  if (!includeHidden && entry.name.startsWith(".")) {
8353
8700
  continue;
8354
8701
  }
8355
- const relativePath = basePath ? path8.join(basePath, entry.name) : entry.name;
8356
- const fullPath = path8.join(dir, entry.name);
8702
+ const relativePath = basePath ? path9.join(basePath, entry.name) : entry.name;
8703
+ const fullPath = path9.join(dir, entry.name);
8357
8704
  if (matchGlob(relativePath, pattern)) {
8358
8705
  matches.push(relativePath);
8359
8706
  }
@@ -8369,7 +8716,7 @@ async function walkDir(dir, pattern, includeHidden, maxResults, basePath = "") {
8369
8716
  async function listFiles(params) {
8370
8717
  const { pattern, cwd: relativeCwd, includeHidden = false, maxResults = 1e3 } = params;
8371
8718
  const baseCwd = process.cwd();
8372
- const targetCwd = relativeCwd ? path8.resolve(baseCwd, path8.normalize(relativeCwd)) : baseCwd;
8719
+ const targetCwd = relativeCwd ? path9.resolve(baseCwd, path9.normalize(relativeCwd)) : baseCwd;
8373
8720
  if (!targetCwd.startsWith(baseCwd)) {
8374
8721
  throw new Error(`Access denied: Cannot list files outside of current working directory`);
8375
8722
  }
@@ -8380,7 +8727,7 @@ async function listFiles(params) {
8380
8727
  const filesInfo = [];
8381
8728
  for (const match of matches) {
8382
8729
  try {
8383
- const fullPath = path8.join(targetCwd, match);
8730
+ const fullPath = path9.join(targetCwd, match);
8384
8731
  const stats = statSync5(fullPath);
8385
8732
  filesInfo.push({
8386
8733
  path: match,
@@ -8463,7 +8810,7 @@ var globFilesTool = {
8463
8810
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/grepSearch/index.js
8464
8811
  import { readdir as readdir2 } from "fs/promises";
8465
8812
  import { readFileSync as readFileSync3, statSync as statSync6 } from "fs";
8466
- import path9 from "path";
8813
+ import path10 from "path";
8467
8814
  var MAX_FILE_SIZE3 = 10 * 1024 * 1024;
8468
8815
  function matchGlob2(filePath, pattern) {
8469
8816
  const regexPattern = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\{\{GLOBSTAR\}\}/g, ".*").replace(/\?/g, ".").replace(/\{([^}]+)\}/g, (_, options) => `(${options.split(",").join("|")})`).replace(/\[([^\]]+)\]/g, "[$1]");
@@ -8481,8 +8828,8 @@ async function walkDir2(dir, pattern, maxResults, basePath = "") {
8481
8828
  if (entry.name.startsWith(".")) {
8482
8829
  continue;
8483
8830
  }
8484
- const relativePath = basePath ? path9.join(basePath, entry.name) : entry.name;
8485
- const fullPath = path9.join(dir, entry.name);
8831
+ const relativePath = basePath ? path10.join(basePath, entry.name) : entry.name;
8832
+ const fullPath = path10.join(dir, entry.name);
8486
8833
  if (matchGlob2(relativePath, pattern)) {
8487
8834
  matches.push(relativePath);
8488
8835
  }
@@ -8498,7 +8845,7 @@ async function walkDir2(dir, pattern, maxResults, basePath = "") {
8498
8845
  async function searchFiles2(params) {
8499
8846
  const { pattern, filePattern = "**/*", cwd: relativeCwd, caseSensitive = false, maxResults = 100, contextLines = 0 } = params;
8500
8847
  const baseCwd = process.cwd();
8501
- const targetCwd = relativeCwd ? path9.resolve(baseCwd, path9.normalize(relativeCwd)) : baseCwd;
8848
+ const targetCwd = relativeCwd ? path10.resolve(baseCwd, path10.normalize(relativeCwd)) : baseCwd;
8502
8849
  if (!targetCwd.startsWith(baseCwd)) {
8503
8850
  throw new Error(`Access denied: Cannot search files outside of current working directory`);
8504
8851
  }
@@ -8512,7 +8859,7 @@ async function searchFiles2(params) {
8512
8859
  const filesToSearch = await walkDir2(targetCwd, filePattern, 1e4);
8513
8860
  const filteredFiles = [];
8514
8861
  for (const match of filesToSearch) {
8515
- const fullPath = path9.join(targetCwd, match);
8862
+ const fullPath = path10.join(targetCwd, match);
8516
8863
  try {
8517
8864
  const stats = statSync6(fullPath);
8518
8865
  if (stats.isDirectory() || stats.size > MAX_FILE_SIZE3) {
@@ -8536,7 +8883,7 @@ async function searchFiles2(params) {
8536
8883
  break;
8537
8884
  }
8538
8885
  filesSearched++;
8539
- const fullPath = path9.join(targetCwd, file);
8886
+ const fullPath = path10.join(targetCwd, file);
8540
8887
  try {
8541
8888
  const content = readFileSync3(fullPath, "utf-8");
8542
8889
  const lines = content.split("\n");
@@ -8671,14 +9018,14 @@ var grepSearchTool = {
8671
9018
  };
8672
9019
 
8673
9020
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/deleteFile/index.js
8674
- import { promises as fs9 } from "fs";
9021
+ import { promises as fs10 } from "fs";
8675
9022
  import { existsSync as existsSync6, statSync as statSync7 } from "fs";
8676
- import path10 from "path";
9023
+ import path11 from "path";
8677
9024
  async function deleteFile(params) {
8678
9025
  const { path: filePath, recursive = false } = params;
8679
- const normalizedPath = path10.normalize(filePath);
8680
- const resolvedPath = path10.resolve(process.cwd(), normalizedPath);
8681
- const cwd = path10.resolve(process.cwd());
9026
+ const normalizedPath = path11.normalize(filePath);
9027
+ const resolvedPath = path11.resolve(process.cwd(), normalizedPath);
9028
+ const cwd = path11.resolve(process.cwd());
8682
9029
  if (!resolvedPath.startsWith(cwd)) {
8683
9030
  throw new Error(`Access denied: Cannot delete files outside of current working directory`);
8684
9031
  }
@@ -8692,10 +9039,10 @@ async function deleteFile(params) {
8692
9039
  throw new Error(`Path is a directory: ${filePath}. Use recursive=true to delete directories and their contents.`);
8693
9040
  }
8694
9041
  if (isDirectory) {
8695
- await fs9.rm(resolvedPath, { recursive: true, force: true });
9042
+ await fs10.rm(resolvedPath, { recursive: true, force: true });
8696
9043
  return `Directory deleted successfully: ${filePath}`;
8697
9044
  } else {
8698
- await fs9.unlink(resolvedPath);
9045
+ await fs10.unlink(resolvedPath);
8699
9046
  return `File deleted successfully: ${filePath}
8700
9047
  Size: ${size} bytes`;
8701
9048
  }
@@ -8705,7 +9052,7 @@ var deleteFileTool = {
8705
9052
  implementation: (context) => ({
8706
9053
  toolFn: async (value) => {
8707
9054
  const params = value;
8708
- const resolvedPath = path10.resolve(process.cwd(), path10.normalize(params.path));
9055
+ const resolvedPath = path11.resolve(process.cwd(), path11.normalize(params.path));
8709
9056
  const isDirectory = existsSync6(resolvedPath) && statSync7(resolvedPath).isDirectory();
8710
9057
  context.logger.info(`\u{1F5D1}\uFE0F DeleteFile: Deleting ${isDirectory ? "directory" : "file"}`, {
8711
9058
  path: params.path,
@@ -8743,7 +9090,7 @@ var deleteFileTool = {
8743
9090
 
8744
9091
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/bashExecute/index.js
8745
9092
  import { spawn } from "child_process";
8746
- import path11 from "path";
9093
+ import path12 from "path";
8747
9094
  var DEFAULT_TIMEOUT_MS = 6e4;
8748
9095
  var MAX_OUTPUT_SIZE = 100 * 1024;
8749
9096
  var DANGEROUS_PATTERNS = [
@@ -8927,7 +9274,7 @@ async function executeBashCommand(params) {
8927
9274
  };
8928
9275
  }
8929
9276
  const baseCwd = process.cwd();
8930
- const targetCwd = relativeCwd ? path11.resolve(baseCwd, relativeCwd) : baseCwd;
9277
+ const targetCwd = relativeCwd ? path12.resolve(baseCwd, relativeCwd) : baseCwd;
8931
9278
  const effectiveTimeout = Math.min(timeout, 5 * 60 * 1e3);
8932
9279
  return new Promise((resolve3) => {
8933
9280
  let stdout = "";
@@ -9261,42 +9608,42 @@ var DISABLE_SERVER_THROTTLING = process.env.DISABLE_SERVER_THROTTLING === "true"
9261
9608
  var questSaveMutex = new Mutex();
9262
9609
 
9263
9610
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletion.js
9264
- var QuestStartBodySchema = z138.object({
9265
- userId: z138.string(),
9266
- sessionId: z138.string(),
9267
- questId: z138.string(),
9268
- message: z138.string(),
9269
- messageFileIds: z138.array(z138.string()),
9270
- historyCount: z138.number(),
9271
- fabFileIds: z138.array(z138.string()),
9611
+ var QuestStartBodySchema = z139.object({
9612
+ userId: z139.string(),
9613
+ sessionId: z139.string(),
9614
+ questId: z139.string(),
9615
+ message: z139.string(),
9616
+ messageFileIds: z139.array(z139.string()),
9617
+ historyCount: z139.number(),
9618
+ fabFileIds: z139.array(z139.string()),
9272
9619
  params: ChatCompletionCreateInputSchema,
9273
9620
  dashboardParams: DashboardParamsSchema.optional(),
9274
- enableQuestMaster: z138.boolean().optional(),
9275
- enableMementos: z138.boolean().optional(),
9276
- enableArtifacts: z138.boolean().optional(),
9277
- enableAgents: z138.boolean().optional(),
9621
+ enableQuestMaster: z139.boolean().optional(),
9622
+ enableMementos: z139.boolean().optional(),
9623
+ enableArtifacts: z139.boolean().optional(),
9624
+ enableAgents: z139.boolean().optional(),
9278
9625
  promptMeta: PromptMetaZodSchema,
9279
- tools: z138.array(z138.union([b4mLLMTools, z138.string()])).optional(),
9280
- mcpServers: z138.array(z138.string()).optional(),
9281
- projectId: z138.string().optional(),
9282
- organizationId: z138.string().nullable().optional(),
9626
+ tools: z139.array(z139.union([b4mLLMTools, z139.string()])).optional(),
9627
+ mcpServers: z139.array(z139.string()).optional(),
9628
+ projectId: z139.string().optional(),
9629
+ organizationId: z139.string().nullable().optional(),
9283
9630
  questMaster: QuestMasterParamsSchema.optional(),
9284
- toolPromptId: z138.string().optional(),
9631
+ toolPromptId: z139.string().optional(),
9285
9632
  researchMode: ResearchModeParamsSchema.optional(),
9286
- fallbackModel: z138.string().optional(),
9287
- embeddingModel: z138.string().optional(),
9288
- queryComplexity: z138.string(),
9633
+ fallbackModel: z139.string().optional(),
9634
+ embeddingModel: z139.string().optional(),
9635
+ queryComplexity: z139.string(),
9289
9636
  imageConfig: GenerateImageToolCallSchema.optional(),
9290
- deepResearchConfig: z138.object({
9291
- maxDepth: z138.number().optional(),
9292
- duration: z138.number().optional(),
9637
+ deepResearchConfig: z139.object({
9638
+ maxDepth: z139.number().optional(),
9639
+ duration: z139.number().optional(),
9293
9640
  // Note: searchers are passed via ToolContext and not through this API schema
9294
- searchers: z138.array(z138.any()).optional()
9641
+ searchers: z139.array(z139.any()).optional()
9295
9642
  }).optional(),
9296
- extraContextMessages: z138.array(z138.object({
9297
- role: z138.enum(["user", "assistant", "system", "function", "tool"]),
9298
- content: z138.union([z138.string(), z138.array(z138.any())]),
9299
- fabFileIds: z138.array(z138.string()).optional()
9643
+ extraContextMessages: z139.array(z139.object({
9644
+ role: z139.enum(["user", "assistant", "system", "function", "tool"]),
9645
+ content: z139.union([z139.string(), z139.array(z139.any())]),
9646
+ fabFileIds: z139.array(z139.string()).optional()
9300
9647
  })).optional()
9301
9648
  });
9302
9649
 
@@ -9304,30 +9651,9 @@ var QuestStartBodySchema = z138.object({
9304
9651
  import axios8 from "axios";
9305
9652
  import { fileTypeFromBuffer as fileTypeFromBuffer4 } from "file-type";
9306
9653
  import { v4 as uuidv47 } from "uuid";
9307
- import { z as z139 } from "zod";
9654
+ import { z as z140 } from "zod";
9308
9655
  import { fromZodError as fromZodError2 } from "zod-validation-error";
9309
9656
  var ImageGenerationBodySchema = OpenAIImageGenerationInput.extend({
9310
- sessionId: z139.string(),
9311
- questId: z139.string(),
9312
- userId: z139.string(),
9313
- prompt: z139.string(),
9314
- safety_tolerance: z139.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
9315
- prompt_upsampling: z139.boolean().optional().default(false),
9316
- seed: z139.number().nullable().optional(),
9317
- output_format: z139.enum(["jpeg", "png"]).nullable().optional().default("png"),
9318
- width: z139.number().optional(),
9319
- height: z139.number().optional(),
9320
- aspect_ratio: z139.string().optional(),
9321
- fabFileIds: z139.array(z139.string()).optional()
9322
- });
9323
-
9324
- // ../../b4m-core/packages/services/dist/src/llm/ImageEdit.js
9325
- import axios9 from "axios";
9326
- import { fileTypeFromBuffer as fileTypeFromBuffer5 } from "file-type";
9327
- import { v4 as uuidv48 } from "uuid";
9328
- import { z as z140 } from "zod";
9329
- import { fromZodError as fromZodError3 } from "zod-validation-error";
9330
- var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
9331
9657
  sessionId: z140.string(),
9332
9658
  questId: z140.string(),
9333
9659
  userId: z140.string(),
@@ -9335,35 +9661,56 @@ var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
9335
9661
  safety_tolerance: z140.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
9336
9662
  prompt_upsampling: z140.boolean().optional().default(false),
9337
9663
  seed: z140.number().nullable().optional(),
9338
- output_format: z140.enum(["jpeg", "png"]).optional().default("png"),
9664
+ output_format: z140.enum(["jpeg", "png"]).nullable().optional().default("png"),
9339
9665
  width: z140.number().optional(),
9340
9666
  height: z140.number().optional(),
9341
9667
  aspect_ratio: z140.string().optional(),
9342
- size: z140.string().optional(),
9343
- fabFileIds: z140.array(z140.string()).optional(),
9344
- image: z140.string()
9668
+ fabFileIds: z140.array(z140.string()).optional()
9345
9669
  });
9346
9670
 
9347
- // ../../b4m-core/packages/services/dist/src/llm/refineText.js
9671
+ // ../../b4m-core/packages/services/dist/src/llm/ImageEdit.js
9672
+ import axios9 from "axios";
9673
+ import { fileTypeFromBuffer as fileTypeFromBuffer5 } from "file-type";
9674
+ import { v4 as uuidv48 } from "uuid";
9348
9675
  import { z as z141 } from "zod";
9349
- var refineTextLLMSchema = z141.object({
9350
- text: z141.string(),
9351
- context: z141.string().optional()
9676
+ import { fromZodError as fromZodError3 } from "zod-validation-error";
9677
+ var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
9678
+ sessionId: z141.string(),
9679
+ questId: z141.string(),
9680
+ userId: z141.string(),
9681
+ prompt: z141.string(),
9682
+ safety_tolerance: z141.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
9683
+ prompt_upsampling: z141.boolean().optional().default(false),
9684
+ seed: z141.number().nullable().optional(),
9685
+ output_format: z141.enum(["jpeg", "png"]).optional().default("png"),
9686
+ width: z141.number().optional(),
9687
+ height: z141.number().optional(),
9688
+ aspect_ratio: z141.string().optional(),
9689
+ size: z141.string().optional(),
9690
+ fabFileIds: z141.array(z141.string()).optional(),
9691
+ image: z141.string()
9692
+ });
9693
+
9694
+ // ../../b4m-core/packages/services/dist/src/llm/refineText.js
9695
+ import { z as z142 } from "zod";
9696
+ var refineTextLLMSchema = z142.object({
9697
+ text: z142.string(),
9698
+ context: z142.string().optional()
9352
9699
  // tone: z.enum(['formal', 'informal', 'neutral']).optional(),
9353
9700
  // style: z.enum(['technical', 'creative', 'academic', 'business', 'narrative']).optional(),
9354
9701
  });
9355
9702
 
9356
9703
  // ../../b4m-core/packages/services/dist/src/llm/MementoEvaluationService.js
9357
- import { z as z142 } from "zod";
9358
- var SingleMementoEvalSchema = z142.object({
9359
- importance: z142.number().min(1).max(10),
9704
+ import { z as z143 } from "zod";
9705
+ var SingleMementoEvalSchema = z143.object({
9706
+ importance: z143.number().min(1).max(10),
9360
9707
  // 1-10 scale for personal info importance
9361
- summary: z142.string(),
9362
- tags: z142.array(z142.string()).optional()
9708
+ summary: z143.string(),
9709
+ tags: z143.array(z143.string()).optional()
9363
9710
  });
9364
- var MementoEvalResponseSchema = z142.object({
9365
- isPersonal: z142.boolean(),
9366
- mementos: z142.array(SingleMementoEvalSchema).optional()
9711
+ var MementoEvalResponseSchema = z143.object({
9712
+ isPersonal: z143.boolean(),
9713
+ mementos: z143.array(SingleMementoEvalSchema).optional()
9367
9714
  // Array of distinct personal information
9368
9715
  });
9369
9716
 
@@ -9420,7 +9767,7 @@ async function generateFileDeletePreview(args) {
9420
9767
  if (!existsSync7(args.path)) {
9421
9768
  return `[File does not exist: ${args.path}]`;
9422
9769
  }
9423
- const stats = await import("fs/promises").then((fs12) => fs12.stat(args.path));
9770
+ const stats = await import("fs/promises").then((fs13) => fs13.stat(args.path));
9424
9771
  return `[File will be deleted]
9425
9772
 
9426
9773
  Path: ${args.path}
@@ -9432,9 +9779,9 @@ Last modified: ${stats.mtime.toLocaleString()}`;
9432
9779
  }
9433
9780
 
9434
9781
  // src/utils/Logger.ts
9435
- import fs10 from "fs/promises";
9436
- import path12 from "path";
9437
- import os from "os";
9782
+ import fs11 from "fs/promises";
9783
+ import path13 from "path";
9784
+ import os2 from "os";
9438
9785
  var Logger2 = class _Logger {
9439
9786
  constructor() {
9440
9787
  this.logFilePath = null;
@@ -9456,9 +9803,9 @@ var Logger2 = class _Logger {
9456
9803
  */
9457
9804
  async initialize(sessionId) {
9458
9805
  this.sessionId = sessionId;
9459
- const debugDir = path12.join(os.homedir(), ".bike4mind", "debug");
9460
- await fs10.mkdir(debugDir, { recursive: true });
9461
- this.logFilePath = path12.join(debugDir, `${sessionId}.txt`);
9806
+ const debugDir = path13.join(os2.homedir(), ".bike4mind", "debug");
9807
+ await fs11.mkdir(debugDir, { recursive: true });
9808
+ this.logFilePath = path13.join(debugDir, `${sessionId}.txt`);
9462
9809
  await this.writeToFile("INFO", "=== CLI SESSION START ===");
9463
9810
  }
9464
9811
  /**
@@ -9522,7 +9869,7 @@ var Logger2 = class _Logger {
9522
9869
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
9523
9870
  const logEntry = `[${timestamp}] [${level}] ${message}
9524
9871
  `;
9525
- await fs10.appendFile(this.logFilePath, logEntry, "utf-8");
9872
+ await fs11.appendFile(this.logFilePath, logEntry, "utf-8");
9526
9873
  } catch (error) {
9527
9874
  console.error("File logging failed:", error);
9528
9875
  }
@@ -9668,15 +10015,15 @@ var Logger2 = class _Logger {
9668
10015
  async cleanupOldLogs() {
9669
10016
  if (!this.fileLoggingEnabled) return;
9670
10017
  try {
9671
- const debugDir = path12.join(os.homedir(), ".bike4mind", "debug");
9672
- const files = await fs10.readdir(debugDir);
10018
+ const debugDir = path13.join(os2.homedir(), ".bike4mind", "debug");
10019
+ const files = await fs11.readdir(debugDir);
9673
10020
  const now = Date.now();
9674
10021
  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1e3;
9675
10022
  for (const file of files) {
9676
- const filePath = path12.join(debugDir, file);
9677
- const stats = await fs10.stat(filePath);
10023
+ const filePath = path13.join(debugDir, file);
10024
+ const stats = await fs11.stat(filePath);
9678
10025
  if (stats.mtime.getTime() < thirtyDaysAgo) {
9679
- await fs10.unlink(filePath);
10026
+ await fs11.unlink(filePath);
9680
10027
  }
9681
10028
  }
9682
10029
  } catch (error) {
@@ -9770,21 +10117,21 @@ var NoOpStorage = class extends BaseStorage {
9770
10117
  async upload(input, destination, options) {
9771
10118
  return `/tmp/${destination}`;
9772
10119
  }
9773
- async download(path15) {
10120
+ async download(path16) {
9774
10121
  throw new Error("Download not supported in CLI");
9775
10122
  }
9776
- async delete(path15) {
10123
+ async delete(path16) {
9777
10124
  }
9778
- async getSignedUrl(path15) {
9779
- return `/tmp/${path15}`;
10125
+ async getSignedUrl(path16) {
10126
+ return `/tmp/${path16}`;
9780
10127
  }
9781
- getPublicUrl(path15) {
9782
- return `/tmp/${path15}`;
10128
+ getPublicUrl(path16) {
10129
+ return `/tmp/${path16}`;
9783
10130
  }
9784
- async getPreview(path15) {
9785
- return `/tmp/${path15}`;
10131
+ async getPreview(path16) {
10132
+ return `/tmp/${path16}`;
9786
10133
  }
9787
- async getMetadata(path15) {
10134
+ async getMetadata(path16) {
9788
10135
  return { size: 0, contentType: "application/octet-stream" };
9789
10136
  }
9790
10137
  };
@@ -9878,7 +10225,31 @@ function wrapToolWithPermission(tool, permissionManager, showPermissionPrompt, a
9878
10225
  }
9879
10226
  };
9880
10227
  }
9881
- function generateCliTools(userId, llm, model, permissionManager, showPermissionPrompt, agentContext, configStore, apiClient) {
10228
+ var TOOL_NAME_MAPPING = {
10229
+ // Claude Code -> B4M
10230
+ read: "file_read",
10231
+ write: "create_file",
10232
+ edit: "edit_file",
10233
+ delete: "delete_file",
10234
+ glob: "glob_files",
10235
+ grep: "grep_search",
10236
+ bash: "bash_execute",
10237
+ // B4M -> Claude Code (reverse mapping)
10238
+ file_read: "read",
10239
+ create_file: "write",
10240
+ edit_file: "edit",
10241
+ delete_file: "delete",
10242
+ glob_files: "glob",
10243
+ grep_search: "grep",
10244
+ bash_execute: "bash"
10245
+ };
10246
+ function normalizeToolName(toolName) {
10247
+ if (toolName.includes("_")) {
10248
+ return toolName;
10249
+ }
10250
+ return TOOL_NAME_MAPPING[toolName] || toolName;
10251
+ }
10252
+ function generateCliTools(userId, llm, model, permissionManager, showPermissionPrompt, agentContext, configStore, apiClient, toolFilter) {
9882
10253
  const logger2 = new CliLogger();
9883
10254
  const storage = new NoOpStorage();
9884
10255
  const user = {
@@ -9948,15 +10319,30 @@ function generateCliTools(userId, llm, model, permissionManager, showPermissionP
9948
10319
  toolConfig,
9949
10320
  model
9950
10321
  );
9951
- const tools2 = Object.entries(toolsMap).filter(([key]) => toolConfig[key] !== void 0).map(
10322
+ let tools2 = Object.entries(toolsMap).filter(([key]) => toolConfig[key] !== void 0).map(
9952
10323
  ([_, tool]) => wrapToolWithPermission(tool, permissionManager, showPermissionPrompt, agentContext, configStore, apiClient)
9953
10324
  );
10325
+ if (toolFilter) {
10326
+ const { allowedTools, deniedTools } = toolFilter;
10327
+ const normalizedAllowed = allowedTools?.map(normalizeToolName);
10328
+ const normalizedDenied = deniedTools?.map(normalizeToolName);
10329
+ tools2 = tools2.filter((tool) => {
10330
+ const toolName = tool.toolSchema.name;
10331
+ if (normalizedDenied && normalizedDenied.includes(toolName)) {
10332
+ return false;
10333
+ }
10334
+ if (normalizedAllowed && normalizedAllowed.length > 0) {
10335
+ return normalizedAllowed.includes(toolName);
10336
+ }
10337
+ return true;
10338
+ });
10339
+ }
9954
10340
  return { tools: tools2, agentContext };
9955
10341
  }
9956
10342
 
9957
10343
  // src/config/toolSafety.ts
9958
- import { z as z143 } from "zod";
9959
- var ToolCategorySchema = z143.enum([
10344
+ import { z as z144 } from "zod";
10345
+ var ToolCategorySchema = z144.enum([
9960
10346
  "auto_approve",
9961
10347
  // Safe tools that run automatically without permission
9962
10348
  "prompt_always",
@@ -9964,9 +10350,9 @@ var ToolCategorySchema = z143.enum([
9964
10350
  "prompt_default"
9965
10351
  // Tools that prompt by default but can be trusted
9966
10352
  ]);
9967
- var ToolSafetyConfigSchema = z143.object({
9968
- categories: z143.record(z143.string(), ToolCategorySchema),
9969
- trustedTools: z143.array(z143.string())
10353
+ var ToolSafetyConfigSchema = z144.object({
10354
+ categories: z144.record(z144.string(), ToolCategorySchema),
10355
+ trustedTools: z144.array(z144.string())
9970
10356
  });
9971
10357
  var DEFAULT_TOOL_CATEGORIES = {
9972
10358
  // ===== AUTO APPROVE (Safe tools) =====
@@ -10146,8 +10532,8 @@ function getEnvironmentName(configApiConfig) {
10146
10532
  }
10147
10533
 
10148
10534
  // src/utils/contextLoader.ts
10149
- import * as fs11 from "fs";
10150
- import * as path13 from "path";
10535
+ import * as fs12 from "fs";
10536
+ import * as path14 from "path";
10151
10537
  import { homedir as homedir4 } from "os";
10152
10538
  var CONTEXT_FILE_SIZE_LIMIT = 100 * 1024;
10153
10539
  var PROJECT_CONTEXT_FILES = [
@@ -10168,9 +10554,9 @@ function formatFileSize2(bytes) {
10168
10554
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
10169
10555
  }
10170
10556
  function tryReadContextFile(dir, filename, source) {
10171
- const filePath = path13.join(dir, filename);
10557
+ const filePath = path14.join(dir, filename);
10172
10558
  try {
10173
- const stats = fs11.lstatSync(filePath);
10559
+ const stats = fs12.lstatSync(filePath);
10174
10560
  if (stats.isDirectory()) {
10175
10561
  return null;
10176
10562
  }
@@ -10184,7 +10570,7 @@ function tryReadContextFile(dir, filename, source) {
10184
10570
  error: `${source === "global" ? "Global" : "Project"} ${filename} exceeds 100KB limit (${formatFileSize2(stats.size)})`
10185
10571
  };
10186
10572
  }
10187
- const content = fs11.readFileSync(filePath, "utf-8");
10573
+ const content = fs12.readFileSync(filePath, "utf-8");
10188
10574
  return {
10189
10575
  filename,
10190
10576
  content,
@@ -10236,7 +10622,7 @@ ${project.content}`;
10236
10622
  }
10237
10623
  async function loadContextFiles(projectDir) {
10238
10624
  const errors = [];
10239
- const globalDir = path13.join(homedir4(), ".bike4mind");
10625
+ const globalDir = path14.join(homedir4(), ".bike4mind");
10240
10626
  const projectDirectory = projectDir || process.cwd();
10241
10627
  const [globalResult, projectResult] = await Promise.all([
10242
10628
  Promise.resolve(findContextFile(globalDir, GLOBAL_CONTEXT_FILES, "global")),
@@ -10257,10 +10643,22 @@ async function loadContextFiles(projectDir) {
10257
10643
  };
10258
10644
  }
10259
10645
 
10646
+ // src/utils/argumentSubstitution.ts
10647
+ function substituteArguments(template, args) {
10648
+ let result = template;
10649
+ for (let i = args.length; i >= 1; i--) {
10650
+ const pattern = new RegExp(`\\$${i}`, "g");
10651
+ result = result.replace(pattern, args[i - 1] || "");
10652
+ }
10653
+ const allArgsString = args.join(" ");
10654
+ result = result.replace(/\$ARGUMENTS/g, allArgsString);
10655
+ return result;
10656
+ }
10657
+
10260
10658
  // ../../b4m-core/packages/mcp/dist/src/client.js
10261
10659
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
10262
10660
  import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
10263
- import path14 from "path";
10661
+ import path15 from "path";
10264
10662
  import { existsSync as existsSync8, readdirSync as readdirSync3 } from "fs";
10265
10663
  var MCPClient = class {
10266
10664
  // Note: This class handles MCP server communication with repository filtering
@@ -10301,16 +10699,16 @@ var MCPClient = class {
10301
10699
  const root = process.env.INIT_CWD || process.cwd();
10302
10700
  const candidatePaths = [
10303
10701
  // When running from SST Lambda with node_modules structure (copyFiles)
10304
- path14.join(root, `node_modules/@bike4mind/mcp/dist/src/${this.serverName}/index.js`),
10702
+ path15.join(root, `node_modules/@bike4mind/mcp/dist/src/${this.serverName}/index.js`),
10305
10703
  // When running from SST Lambda deployed environment (/var/task)
10306
- path14.join(root, `b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10704
+ path15.join(root, `b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10307
10705
  // When running from SST Lambda (.sst/artifacts/mcpHandler-dev), navigate to monorepo root (3 levels up)
10308
- path14.join(root, `../../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10706
+ path15.join(root, `../../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10309
10707
  // When running from packages/client (Next.js app), navigate to monorepo root (2 levels up)
10310
- path14.join(root, `../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10708
+ path15.join(root, `../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10311
10709
  // Original paths (backward compatibility)
10312
- path14.join(root, `/b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10313
- path14.join(root, "core", "mcp", "servers", this.serverName, "dist", "index.js")
10710
+ path15.join(root, `/b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
10711
+ path15.join(root, "core", "mcp", "servers", this.serverName, "dist", "index.js")
10314
10712
  ];
10315
10713
  const serverScriptPath = candidatePaths.find((p) => existsSync8(p));
10316
10714
  if (!serverScriptPath) {
@@ -11114,7 +11512,7 @@ import { isAxiosError as isAxiosError2 } from "axios";
11114
11512
  // package.json
11115
11513
  var package_default = {
11116
11514
  name: "@bike4mind/cli",
11117
- version: "0.2.10-fix-b4m-cli-flicker.17235+479bb7772",
11515
+ version: "0.2.10-fix-cli-duplicate-chat-history.17269+1be89f2b4",
11118
11516
  type: "module",
11119
11517
  description: "Interactive CLI tool for Bike4Mind with ReAct agents",
11120
11518
  license: "UNLICENSED",
@@ -11184,6 +11582,7 @@ var package_default = {
11184
11582
  "eventsource-parser": "^3.0.6",
11185
11583
  "file-type": "^18.7.0",
11186
11584
  "fuse.js": "^7.1.0",
11585
+ "gray-matter": "^4.0.3",
11187
11586
  ink: "^6.5.1",
11188
11587
  "ink-select-input": "^6.2.0",
11189
11588
  "ink-spinner": "^5.0.0",
@@ -11217,10 +11616,10 @@ var package_default = {
11217
11616
  },
11218
11617
  devDependencies: {
11219
11618
  "@bike4mind/agents": "0.1.0",
11220
- "@bike4mind/common": "2.39.1-fix-b4m-cli-flicker.17235+479bb7772",
11221
- "@bike4mind/mcp": "1.20.4-fix-b4m-cli-flicker.17235+479bb7772",
11222
- "@bike4mind/services": "2.34.2-fix-b4m-cli-flicker.17235+479bb7772",
11223
- "@bike4mind/utils": "2.1.4-fix-b4m-cli-flicker.17235+479bb7772",
11619
+ "@bike4mind/common": "2.39.1-fix-cli-duplicate-chat-history.17269+1be89f2b4",
11620
+ "@bike4mind/mcp": "1.20.4-fix-cli-duplicate-chat-history.17269+1be89f2b4",
11621
+ "@bike4mind/services": "2.34.2-fix-cli-duplicate-chat-history.17269+1be89f2b4",
11622
+ "@bike4mind/utils": "2.1.4-fix-cli-duplicate-chat-history.17269+1be89f2b4",
11224
11623
  "@types/better-sqlite3": "^7.6.13",
11225
11624
  "@types/diff": "^5.0.9",
11226
11625
  "@types/jsonwebtoken": "^9.0.4",
@@ -11233,7 +11632,7 @@ var package_default = {
11233
11632
  typescript: "^5.9.3",
11234
11633
  vitest: "^3.2.4"
11235
11634
  },
11236
- gitHead: "479bb77726d7e49cda72367ba8fd3c84e346474d"
11635
+ gitHead: "1be89f2b4af11a0ce89c8d4822dda698ded0f703"
11237
11636
  };
11238
11637
 
11239
11638
  // src/config/constants.ts
@@ -11241,6 +11640,331 @@ var USAGE_DAYS = 30;
11241
11640
  var MODEL_NAME_COLUMN_WIDTH = 18;
11242
11641
  var USAGE_CACHE_TTL = 5 * 60 * 1e3;
11243
11642
 
11643
+ // src/agents/SubagentOrchestrator.ts
11644
+ var SubagentOrchestrator = class {
11645
+ constructor(deps) {
11646
+ this.deps = deps;
11647
+ }
11648
+ /**
11649
+ * Delegate a task to a specialized subagent
11650
+ *
11651
+ * @param options - Configuration for subagent execution
11652
+ * @returns Subagent result with summary
11653
+ */
11654
+ async delegateToSubagent(options) {
11655
+ const { task, type, thoroughness, parentSessionId, config: configOverride } = options;
11656
+ const baseConfig = this.deps.subagentConfigs.get(type);
11657
+ if (!baseConfig) {
11658
+ throw new Error(`No configuration found for subagent type: ${type}`);
11659
+ }
11660
+ const config = {
11661
+ ...baseConfig,
11662
+ ...configOverride,
11663
+ type
11664
+ };
11665
+ const model = config.model || "claude-3-5-haiku-20241022";
11666
+ const maxIterations = this.getMaxIterations(config, thoroughness);
11667
+ const toolFilter = {
11668
+ allowedTools: config.allowedTools,
11669
+ deniedTools: config.deniedTools
11670
+ };
11671
+ const agentContext = {
11672
+ currentAgent: null,
11673
+ observationQueue: []
11674
+ };
11675
+ const { tools: tools2, agentContext: updatedContext } = generateCliTools(
11676
+ this.deps.userId,
11677
+ this.deps.llm,
11678
+ model,
11679
+ this.deps.permissionManager,
11680
+ this.deps.showPermissionPrompt,
11681
+ agentContext,
11682
+ this.deps.configStore,
11683
+ this.deps.apiClient,
11684
+ toolFilter
11685
+ );
11686
+ this.deps.logger.debug(`Spawning ${type} subagent with ${tools2.length} tools, thoroughness: ${thoroughness}`);
11687
+ const subagent = new ReActAgent({
11688
+ userId: this.deps.userId,
11689
+ logger: this.deps.logger,
11690
+ llm: this.deps.llm,
11691
+ model,
11692
+ tools: tools2,
11693
+ maxIterations,
11694
+ systemPrompt: config.systemPrompt || this.getDefaultSystemPrompt(type)
11695
+ });
11696
+ updatedContext.currentAgent = subagent;
11697
+ const startTime = Date.now();
11698
+ const result = await subagent.run(task, {
11699
+ maxIterations
11700
+ });
11701
+ const duration = Date.now() - startTime;
11702
+ this.deps.logger.debug(
11703
+ `Subagent completed in ${duration}ms, ${result.completionInfo.iterations} iterations, ${result.completionInfo.totalTokens} tokens`
11704
+ );
11705
+ const summary = this.summarizeResult(result, type);
11706
+ const subagentResult = {
11707
+ ...result,
11708
+ subagentType: type,
11709
+ thoroughness,
11710
+ summary,
11711
+ parentSessionId
11712
+ };
11713
+ return subagentResult;
11714
+ }
11715
+ /**
11716
+ * Get max iterations based on thoroughness and config
11717
+ */
11718
+ getMaxIterations(config, thoroughness) {
11719
+ const defaults = {
11720
+ quick: 2,
11721
+ medium: 5,
11722
+ very_thorough: 10
11723
+ };
11724
+ const configIterations = config.maxIterations || defaults;
11725
+ return configIterations[thoroughness];
11726
+ }
11727
+ /**
11728
+ * Get default system prompt for subagent type
11729
+ */
11730
+ getDefaultSystemPrompt(type) {
11731
+ switch (type) {
11732
+ case "explore":
11733
+ return `You are a code exploration specialist. Your job is to search and analyze codebases efficiently.
11734
+
11735
+ Focus on:
11736
+ - Finding relevant files and functions
11737
+ - Understanding code structure and patterns
11738
+ - Providing clear, concise summaries
11739
+
11740
+ You have read-only access. Use file_read, grep_search, and glob_files to explore.
11741
+
11742
+ When you find what you're looking for, provide a clear summary including:
11743
+ 1. What you found (files, functions, patterns)
11744
+ 2. Key insights or observations
11745
+ 3. Relevant code locations
11746
+
11747
+ Be thorough but concise. Your summary will be used by the main agent.`;
11748
+ case "plan":
11749
+ return `You are a task planning specialist. Your job is to break down complex tasks into clear, actionable steps.
11750
+
11751
+ Focus on:
11752
+ - Identifying dependencies and blockers
11753
+ - Creating logical sequence of steps
11754
+ - Estimating scope and priorities
11755
+
11756
+ Provide a structured plan that the main agent can execute.`;
11757
+ case "review":
11758
+ return `You are a code review specialist. Your job is to analyze code quality and identify issues.
11759
+
11760
+ Focus on:
11761
+ - Code quality and best practices
11762
+ - Potential bugs and edge cases
11763
+ - Performance and security considerations
11764
+
11765
+ Provide actionable feedback with specific file and line references.`;
11766
+ default:
11767
+ return "You are a helpful AI assistant.";
11768
+ }
11769
+ }
11770
+ /**
11771
+ * Summarize subagent result for parent agent
11772
+ */
11773
+ summarizeResult(result, type) {
11774
+ const { finalAnswer, steps, completionInfo } = result;
11775
+ const toolCalls = steps.filter((s) => s.type === "action");
11776
+ const filesRead = toolCalls.filter((s) => s.metadata?.toolName === "file_read").length;
11777
+ const searches = toolCalls.filter((s) => s.metadata?.toolName === "grep_search").length;
11778
+ const globs = toolCalls.filter((s) => s.metadata?.toolName === "glob_files").length;
11779
+ let summary = `**${type.charAt(0).toUpperCase() + type.slice(1)} Subagent Results**
11780
+
11781
+ `;
11782
+ summary += `*Execution: ${completionInfo.iterations} iterations, ${completionInfo.toolCalls} tool calls*
11783
+
11784
+ `;
11785
+ if (type === "explore") {
11786
+ summary += `*Exploration: ${filesRead} files read, ${searches} searches, ${globs} glob patterns*
11787
+
11788
+ `;
11789
+ }
11790
+ const maxLength = 1e3;
11791
+ if (finalAnswer.length > maxLength) {
11792
+ summary += finalAnswer.slice(0, maxLength) + "\n\n...(truncated)";
11793
+ } else {
11794
+ summary += finalAnswer;
11795
+ }
11796
+ return summary;
11797
+ }
11798
+ };
11799
+
11800
+ // src/agents/configs.ts
11801
+ var EXPLORE_CONFIG = {
11802
+ type: "explore",
11803
+ model: "claude-3-5-haiku-20241022",
11804
+ systemPrompt: `You are a code exploration specialist. Your job is to search and analyze codebases efficiently.
11805
+
11806
+ Focus on:
11807
+ - Finding relevant files and functions
11808
+ - Understanding code structure and patterns
11809
+ - Providing clear, concise summaries
11810
+
11811
+ You have read-only access. Use file_read, grep_search, and glob_files to explore.
11812
+
11813
+ When you find what you're looking for, provide a clear summary including:
11814
+ 1. What you found (files, functions, patterns)
11815
+ 2. Key insights or observations
11816
+ 3. Relevant code locations
11817
+
11818
+ Be thorough but concise. Your summary will be used by the main agent.`,
11819
+ allowedTools: [
11820
+ "file_read",
11821
+ "grep_search",
11822
+ "glob_files",
11823
+ "bash_execute",
11824
+ // Only for read-only commands like ls, cat, find
11825
+ "current_datetime",
11826
+ "math_evaluate"
11827
+ ],
11828
+ deniedTools: [
11829
+ "create_file",
11830
+ "edit_file",
11831
+ "delete_file",
11832
+ "web_search",
11833
+ "weather_info",
11834
+ "blog_publish",
11835
+ "blog_edit",
11836
+ "blog_draft"
11837
+ ],
11838
+ maxIterations: {
11839
+ quick: 2,
11840
+ medium: 5,
11841
+ very_thorough: 10
11842
+ },
11843
+ defaultThoroughness: "medium"
11844
+ };
11845
+ var PLAN_CONFIG = {
11846
+ type: "plan",
11847
+ model: "claude-3-5-haiku-20241022",
11848
+ systemPrompt: `You are a task planning specialist. Your job is to break down complex tasks into clear, actionable steps.
11849
+
11850
+ Focus on:
11851
+ - Identifying dependencies and blockers
11852
+ - Creating logical sequence of steps
11853
+ - Estimating scope and priorities
11854
+
11855
+ You can explore the codebase to understand the current architecture before planning.
11856
+
11857
+ Provide a structured plan that the main agent can execute.`,
11858
+ allowedTools: ["file_read", "grep_search", "glob_files", "bash_execute", "current_datetime", "math_evaluate"],
11859
+ deniedTools: ["create_file", "edit_file", "delete_file", "web_search", "weather_info"],
11860
+ maxIterations: {
11861
+ quick: 3,
11862
+ medium: 7,
11863
+ very_thorough: 12
11864
+ },
11865
+ defaultThoroughness: "medium"
11866
+ };
11867
+ var REVIEW_CONFIG = {
11868
+ type: "review",
11869
+ model: "claude-sonnet-4-5-20250929",
11870
+ // Use latest Sonnet for better reasoning
11871
+ systemPrompt: `You are a code review specialist. Your job is to analyze code quality and identify issues.
11872
+
11873
+ Focus on:
11874
+ - Code quality and best practices
11875
+ - Potential bugs and edge cases
11876
+ - Performance and security considerations
11877
+
11878
+ You have read-only access to analyze code.
11879
+
11880
+ Provide actionable feedback with specific file and line references.`,
11881
+ allowedTools: ["file_read", "grep_search", "glob_files", "bash_execute", "current_datetime"],
11882
+ deniedTools: ["create_file", "edit_file", "delete_file", "web_search", "weather_info"],
11883
+ maxIterations: {
11884
+ quick: 3,
11885
+ medium: 8,
11886
+ very_thorough: 15
11887
+ },
11888
+ defaultThoroughness: "medium"
11889
+ };
11890
+ function getDefaultSubagentConfigs() {
11891
+ return /* @__PURE__ */ new Map([
11892
+ ["explore", EXPLORE_CONFIG],
11893
+ ["plan", PLAN_CONFIG],
11894
+ ["review", REVIEW_CONFIG]
11895
+ ]);
11896
+ }
11897
+
11898
+ // src/agents/delegateTool.ts
11899
+ function createSubagentDelegateTool(orchestrator, parentSessionId) {
11900
+ return {
11901
+ toolFn: async (args) => {
11902
+ const params = args;
11903
+ if (!params.task) {
11904
+ throw new Error("subagent_delegate: task parameter is required");
11905
+ }
11906
+ if (!params.type) {
11907
+ throw new Error("subagent_delegate: type parameter is required");
11908
+ }
11909
+ const thoroughness = params.thoroughness || "medium";
11910
+ const type = params.type;
11911
+ const result = await orchestrator.delegateToSubagent({
11912
+ task: params.task,
11913
+ type,
11914
+ thoroughness,
11915
+ parentSessionId
11916
+ });
11917
+ return result.summary;
11918
+ },
11919
+ toolSchema: {
11920
+ name: "subagent_delegate",
11921
+ description: `Delegate a task to a specialized subagent for focused work.
11922
+
11923
+ **When to use this tool:**
11924
+ - **Explore**: When you need to search through the codebase, find files, or understand code structure (read-only)
11925
+ - **Plan**: When you need to break down a complex task into actionable steps
11926
+ - **Review**: When you need to analyze code quality and identify potential issues
11927
+
11928
+ **Benefits:**
11929
+ - Keeps main conversation focused and clean
11930
+ - Uses specialized prompts optimized for each task type
11931
+ - Faster execution with appropriate models (Haiku for explore/plan, Sonnet for review)
11932
+
11933
+ **Example uses:**
11934
+ - "Find all files that use the authentication system" \u2192 explore
11935
+ - "Search for components that handle user input" \u2192 explore
11936
+ - "Break down implementing a new feature into steps" \u2192 plan
11937
+ - "Review this module for potential bugs" \u2192 review`,
11938
+ parameters: {
11939
+ type: "object",
11940
+ properties: {
11941
+ task: {
11942
+ type: "string",
11943
+ 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."
11944
+ },
11945
+ type: {
11946
+ type: "string",
11947
+ enum: ["explore", "plan", "review"],
11948
+ description: `Type of subagent to use:
11949
+ - explore: Read-only codebase exploration and search (fast, uses Haiku)
11950
+ - plan: Task breakdown and planning (uses Haiku)
11951
+ - review: Code quality analysis and review (uses Sonnet for better reasoning)`
11952
+ },
11953
+ thoroughness: {
11954
+ type: "string",
11955
+ enum: ["quick", "medium", "very_thorough"],
11956
+ description: `How thoroughly to execute:
11957
+ - quick: Fast lookup, 1-2 iterations
11958
+ - medium: Balanced exploration, 3-5 iterations (default)
11959
+ - very_thorough: Comprehensive analysis, 8-10 iterations`
11960
+ }
11961
+ },
11962
+ required: ["task", "type"]
11963
+ }
11964
+ }
11965
+ };
11966
+ }
11967
+
11244
11968
  // src/index.tsx
11245
11969
  process.removeAllListeners("warning");
11246
11970
  process.on("warning", (warning) => {
@@ -11255,11 +11979,12 @@ var usageCache = null;
11255
11979
  function CliApp() {
11256
11980
  const { exit } = useApp();
11257
11981
  const imageRenderer = new ImageRenderer();
11258
- const [state, setState] = useState7({
11982
+ const [state, setState] = useState8({
11259
11983
  session: null,
11260
11984
  sessionStore: new SessionStore(),
11261
11985
  configStore: new ConfigStore(),
11262
11986
  commandHistoryStore: new CommandHistoryStore(),
11987
+ customCommandStore: new CustomCommandStore(),
11263
11988
  imageStore: null,
11264
11989
  // Lazy-loaded on first use
11265
11990
  imageRenderer,
@@ -11272,10 +11997,10 @@ function CliApp() {
11272
11997
  rewindSelector: null,
11273
11998
  sessionSelector: null
11274
11999
  });
11275
- const [isInitialized, setIsInitialized] = useState7(false);
11276
- const [initError, setInitError] = useState7(null);
11277
- const [commandHistory, setCommandHistory] = useState7([]);
11278
- const imageStoreInitPromise = useRef(null);
12000
+ const [isInitialized, setIsInitialized] = useState8(false);
12001
+ const [initError, setInitError] = useState8(null);
12002
+ const [commandHistory, setCommandHistory] = useState8([]);
12003
+ const imageStoreInitPromise = useRef2(null);
11279
12004
  const setStoreSession = useCliStore((state2) => state2.setSession);
11280
12005
  const setPermissionPrompt = useCliStore((state2) => state2.setPermissionPrompt);
11281
12006
  const setShowConfigEditor = useCliStore((state2) => state2.setShowConfigEditor);
@@ -11339,6 +12064,15 @@ function CliApp() {
11339
12064
  const config = await state.configStore.load();
11340
12065
  const history = await state.commandHistoryStore.load();
11341
12066
  setCommandHistory(history);
12067
+ try {
12068
+ await state.customCommandStore.loadCommands();
12069
+ const customCommandCount = state.customCommandStore.getCommandCount();
12070
+ if (customCommandCount > 0) {
12071
+ console.log(`\u{1F4DD} Loaded ${customCommandCount} custom command${customCommandCount !== 1 ? "s" : ""}`);
12072
+ }
12073
+ } catch (error) {
12074
+ console.warn("Failed to load custom commands:", error instanceof Error ? error.message : String(error));
12075
+ }
11342
12076
  const authTokens = await state.configStore.getAuthTokens();
11343
12077
  let isAuthenticated = false;
11344
12078
  if (!authTokens) {
@@ -11478,7 +12212,34 @@ function CliApp() {
11478
12212
  console.log(` \u{1F4E1} ${serverName}: ${count} tool(s)`);
11479
12213
  });
11480
12214
  }
11481
- const allTools = [...b4mTools, ...mcpTools];
12215
+ const subagentConfigs = getDefaultSubagentConfigs();
12216
+ if (config.subagents) {
12217
+ if (config.subagents.explore) {
12218
+ const currentConfig = subagentConfigs.get("explore");
12219
+ subagentConfigs.set("explore", { ...currentConfig, ...config.subagents.explore });
12220
+ }
12221
+ if (config.subagents.plan) {
12222
+ const currentConfig = subagentConfigs.get("plan");
12223
+ subagentConfigs.set("plan", { ...currentConfig, ...config.subagents.plan });
12224
+ }
12225
+ if (config.subagents.review) {
12226
+ const currentConfig = subagentConfigs.get("review");
12227
+ subagentConfigs.set("review", { ...currentConfig, ...config.subagents.review });
12228
+ }
12229
+ }
12230
+ const orchestrator = new SubagentOrchestrator({
12231
+ userId: config.userId,
12232
+ llm,
12233
+ logger: silentLogger,
12234
+ permissionManager,
12235
+ showPermissionPrompt: promptFn,
12236
+ configStore: state.configStore,
12237
+ apiClient,
12238
+ subagentConfigs
12239
+ });
12240
+ const subagentDelegateTool = createSubagentDelegateTool(orchestrator, newSession.id);
12241
+ const allTools = [...b4mTools, ...mcpTools, subagentDelegateTool];
12242
+ console.log(`\u{1F916} Subagent delegation enabled (explore, plan, review)`);
11482
12243
  const projectDir = state.configStore.getProjectConfigDir();
11483
12244
  const contextResult = await loadContextFiles(projectDir);
11484
12245
  if (contextResult.globalContext) {
@@ -11515,6 +12276,15 @@ FOR CODING TASKS:
11515
12276
  - When searching for code: Use grep_search or glob_files to find relevant files
11516
12277
  - Permission system will ask for approval before any file writes
11517
12278
 
12279
+ SUBAGENT DELEGATION:
12280
+ - You have access to specialized subagents via the subagent_delegate tool
12281
+ - Use subagents for focused exploration, planning, or review tasks:
12282
+ * explore: Fast read-only codebase search (e.g., "find all auth files", "locate API endpoints")
12283
+ * plan: Break down complex tasks into actionable steps
12284
+ * review: Analyze code quality and identify issues
12285
+ - Subagents keep the main conversation clean and run faster with optimized models
12286
+ - Delegate when you need to search extensively or analyze code structure
12287
+
11518
12288
  FOR GENERAL TASKS:
11519
12289
  - Use available tools to get information (weather, web search, calculations, etc.)
11520
12290
  - When user asks follow-up questions, use conversation context to understand what they're referring to
@@ -11525,6 +12295,7 @@ EXAMPLES:
11525
12295
  - "how about Japan?" \u2192 use weather tool for Japan (applying same question from context)
11526
12296
  - "enhance README" \u2192 file_read \u2192 generate \u2192 create_file
11527
12297
  - "what packages installed?" \u2192 glob_files "**/package.json" \u2192 file_read
12298
+ - "find all components using React hooks" \u2192 subagent_delegate(task="find all components using React hooks", type="explore")
11528
12299
 
11529
12300
  Remember: Use context from previous messages to understand follow-up questions.${contextSection}`;
11530
12301
  const maxIterations = config.preferences.maxIterations === null ? 999999 : config.preferences.maxIterations;
@@ -11571,8 +12342,164 @@ Remember: Use context from previous messages to understand follow-up questions.$
11571
12342
  useEffect3(() => {
11572
12343
  init();
11573
12344
  }, [init]);
12345
+ const handleCustomCommandMessage = async (fullTemplate, displayMessage) => {
12346
+ if (!state.agent || !state.session) {
12347
+ console.error("\u274C Agent or session not initialized");
12348
+ return;
12349
+ }
12350
+ const authTokens = await state.configStore.getAuthTokens();
12351
+ if (!authTokens || new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date()) {
12352
+ console.log("\n\u274C Authentication required to use AI features.");
12353
+ console.log("\u{1F4A1} Run /login to authenticate with your B4M account.\n");
12354
+ return;
12355
+ }
12356
+ useCliStore.getState().setIsThinking(true);
12357
+ const currentSteps = [];
12358
+ const stepHandler = (step) => {
12359
+ currentSteps.push(step);
12360
+ const currentSession = useCliStore.getState().session;
12361
+ if (currentSession) {
12362
+ const messages = [...currentSession.messages];
12363
+ const lastMessage = messages[messages.length - 1];
12364
+ if (lastMessage && lastMessage.role === "assistant") {
12365
+ messages[messages.length - 1] = {
12366
+ ...lastMessage,
12367
+ metadata: {
12368
+ ...lastMessage.metadata,
12369
+ steps: [...currentSteps]
12370
+ }
12371
+ };
12372
+ setStoreSession({
12373
+ ...currentSession,
12374
+ messages
12375
+ });
12376
+ }
12377
+ }
12378
+ };
12379
+ state.agent.on("action", stepHandler);
12380
+ try {
12381
+ let messageContent = fullTemplate;
12382
+ const userMessageContent = displayMessage;
12383
+ if (state.messageBuilder && state.messageBuilder.hasImages(fullTemplate)) {
12384
+ const { message: multimodalMessage } = await state.messageBuilder.buildMessage(fullTemplate);
12385
+ messageContent = multimodalMessage.content;
12386
+ }
12387
+ const userMessage = {
12388
+ role: "user",
12389
+ content: userMessageContent,
12390
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
12391
+ };
12392
+ const pendingAssistantMessage = {
12393
+ role: "assistant",
12394
+ content: "...",
12395
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12396
+ metadata: {
12397
+ steps: []
12398
+ }
12399
+ };
12400
+ const sessionWithMessages = {
12401
+ ...state.session,
12402
+ messages: [...state.session.messages, userMessage, pendingAssistantMessage],
12403
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
12404
+ };
12405
+ setState((prev) => ({ ...prev, session: sessionWithMessages }));
12406
+ setStoreSession(sessionWithMessages);
12407
+ const recentMessages = state.session.messages.slice(-20);
12408
+ const previousMessages = recentMessages.filter((msg) => msg.role === "user" || msg.role === "assistant").map((msg) => ({
12409
+ role: msg.role,
12410
+ content: msg.content
12411
+ }));
12412
+ const result = await state.agent.run(messageContent, {
12413
+ previousMessages: previousMessages.length > 0 ? previousMessages : void 0
12414
+ });
12415
+ const permissionDenied = result.finalAnswer.startsWith("Permission denied for tool");
12416
+ if (permissionDenied) {
12417
+ console.log("\n\u26A0\uFE0F Action denied by user\n");
12418
+ }
12419
+ const successfulToolCalls = result.steps.filter((s) => s.type === "observation").length;
12420
+ const currentSession = useCliStore.getState().session;
12421
+ if (!currentSession) return;
12422
+ const updatedMessages = [...currentSession.messages];
12423
+ updatedMessages[updatedMessages.length - 1] = {
12424
+ role: "assistant",
12425
+ content: result.finalAnswer,
12426
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12427
+ metadata: {
12428
+ steps: result.steps,
12429
+ tokenUsage: {
12430
+ prompt: 0,
12431
+ completion: 0,
12432
+ total: result.completionInfo.totalTokens
12433
+ },
12434
+ model: state.session.model,
12435
+ permissionDenied
12436
+ }
12437
+ };
12438
+ const finalSession = {
12439
+ ...currentSession,
12440
+ messages: updatedMessages,
12441
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12442
+ metadata: {
12443
+ ...currentSession.metadata,
12444
+ totalTokens: currentSession.metadata.totalTokens + result.completionInfo.totalTokens,
12445
+ toolCallCount: currentSession.metadata.toolCallCount + successfulToolCalls
12446
+ }
12447
+ };
12448
+ setState((prev) => ({ ...prev, session: finalSession }));
12449
+ setStoreSession(finalSession);
12450
+ await state.sessionStore.save(finalSession);
12451
+ usageCache = null;
12452
+ useCliStore.getState().setIsThinking(false);
12453
+ } catch (error) {
12454
+ useCliStore.getState().setIsThinking(false);
12455
+ if (error?.message?.includes("Permission denied")) {
12456
+ console.log("\n\u26A0\uFE0F Action blocked by permission settings");
12457
+ const currentSession2 = useCliStore.getState().session;
12458
+ if (!currentSession2) return;
12459
+ const sessionWithDenied = { ...currentSession2 };
12460
+ const messages2 = [...sessionWithDenied.messages];
12461
+ const lastMessage2 = messages2[messages2.length - 1];
12462
+ if (lastMessage2 && lastMessage2.role === "assistant") {
12463
+ messages2[messages2.length - 1] = {
12464
+ ...lastMessage2,
12465
+ content: error.message,
12466
+ metadata: {
12467
+ ...lastMessage2.metadata,
12468
+ permissionDenied: true
12469
+ }
12470
+ };
12471
+ }
12472
+ sessionWithDenied.messages = messages2;
12473
+ setState((prev) => ({ ...prev, session: sessionWithDenied }));
12474
+ setStoreSession(sessionWithDenied);
12475
+ await state.sessionStore.save(sessionWithDenied);
12476
+ return;
12477
+ }
12478
+ console.error("Error executing command:", error);
12479
+ console.error(error.stack);
12480
+ const currentSession = useCliStore.getState().session;
12481
+ if (!currentSession) return;
12482
+ const sessionWithError = { ...currentSession };
12483
+ const messages = [...sessionWithError.messages];
12484
+ const lastMessage = messages[messages.length - 1];
12485
+ if (lastMessage && lastMessage.role === "assistant") {
12486
+ messages[messages.length - 1] = {
12487
+ ...lastMessage,
12488
+ content: `\u274C Error: ${error.message || "Unknown error occurred"}`
12489
+ };
12490
+ }
12491
+ sessionWithError.messages = messages;
12492
+ setState((prev) => ({ ...prev, session: sessionWithError }));
12493
+ setStoreSession(sessionWithError);
12494
+ } finally {
12495
+ state.agent.off("action", stepHandler);
12496
+ }
12497
+ };
11574
12498
  const handleMessage = async (message) => {
11575
- if (!state.agent || !state.session) return;
12499
+ if (!state.agent || !state.session) {
12500
+ console.error("\u274C Agent or session not initialized");
12501
+ return;
12502
+ }
11576
12503
  await state.commandHistoryStore.add(message);
11577
12504
  const updatedHistory = await state.commandHistoryStore.list();
11578
12505
  setCommandHistory(updatedHistory);
@@ -11582,6 +12509,7 @@ Remember: Use context from previous messages to understand follow-up questions.$
11582
12509
  console.log("\u{1F4A1} Run /login to authenticate with your B4M account.\n");
11583
12510
  return;
11584
12511
  }
12512
+ useCliStore.getState().setIsThinking(true);
11585
12513
  const currentSteps = [];
11586
12514
  const stepHandler = (step) => {
11587
12515
  currentSteps.push(step);
@@ -11683,6 +12611,46 @@ Remember: Use context from previous messages to understand follow-up questions.$
11683
12611
  state.agent.off("action", stepHandler);
11684
12612
  }
11685
12613
  };
12614
+ const handleBashCommand = useCallback(
12615
+ (command) => {
12616
+ if (!state.session) return;
12617
+ let output;
12618
+ let isError = false;
12619
+ try {
12620
+ output = execSync(command, {
12621
+ encoding: "utf-8",
12622
+ stdio: ["pipe", "pipe", "pipe"],
12623
+ cwd: process.cwd(),
12624
+ maxBuffer: 10 * 1024 * 1024
12625
+ // 10MB buffer
12626
+ });
12627
+ } catch (error) {
12628
+ const execError = error;
12629
+ output = execError.stderr || execError.message || "Command failed";
12630
+ isError = true;
12631
+ }
12632
+ const userMessage = {
12633
+ role: "user",
12634
+ content: `$ ${command}`,
12635
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
12636
+ };
12637
+ const assistantMessage = {
12638
+ role: "assistant",
12639
+ content: isError ? `\u274C Error:
12640
+ ${output}` : output.trim() || "(no output)",
12641
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
12642
+ };
12643
+ const updatedSession = {
12644
+ ...state.session,
12645
+ messages: [...state.session.messages, userMessage, assistantMessage],
12646
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
12647
+ };
12648
+ setState((prev) => ({ ...prev, session: updatedSession }));
12649
+ setStoreSession(updatedSession);
12650
+ state.sessionStore.save(updatedSession);
12651
+ },
12652
+ [state.session, state.sessionStore]
12653
+ );
11686
12654
  const handleImageDetected = async (imageData) => {
11687
12655
  try {
11688
12656
  let imageStore = state.imageStore;
@@ -11737,8 +12705,48 @@ Remember: Use context from previous messages to understand follow-up questions.$
11737
12705
  };
11738
12706
  };
11739
12707
  const handleCommand = async (command, args) => {
12708
+ const customCommand = state.customCommandStore.getCommand(command);
12709
+ if (customCommand) {
12710
+ try {
12711
+ const sourceIcon = customCommand.source === "global" ? "\u{1F3E0}" : "\u{1F4C1}";
12712
+ console.log(`${sourceIcon} Executing custom command: /${command}`);
12713
+ let substitutedBody = substituteArguments(customCommand.body, args);
12714
+ const processed = await processFileReferences(substitutedBody);
12715
+ substitutedBody = processed.content;
12716
+ if (processed.errors.length > 0) {
12717
+ processed.errors.forEach((error) => console.warn(`Warning: ${error}`));
12718
+ }
12719
+ if (process.env.B4M_VERBOSE === "1") {
12720
+ console.log("\u{1F4DD} Expanded command:\n", substitutedBody);
12721
+ }
12722
+ const displayMessage = `/${command}${args.length > 0 ? " " + args.join(" ") : ""}`;
12723
+ if (customCommand.model && state.agent) {
12724
+ console.log(`\u{1F504} Using model override: ${customCommand.model}`);
12725
+ const originalModel = state.session?.model;
12726
+ if (state.session) {
12727
+ state.session.model = customCommand.model;
12728
+ }
12729
+ await handleCustomCommandMessage(substitutedBody, displayMessage);
12730
+ if (state.session && originalModel) {
12731
+ state.session.model = originalModel;
12732
+ }
12733
+ } else {
12734
+ console.log("\u{1F916} Sending to agent...\n");
12735
+ await handleCustomCommandMessage(substitutedBody, displayMessage);
12736
+ }
12737
+ return;
12738
+ } catch (error) {
12739
+ console.error(
12740
+ `\u274C Failed to execute custom command /${command}:`,
12741
+ error instanceof Error ? error.message : String(error)
12742
+ );
12743
+ return;
12744
+ }
12745
+ }
11740
12746
  switch (command) {
11741
- case "help":
12747
+ case "help": {
12748
+ const customCommands = state.customCommandStore.getAllCommands();
12749
+ const hasCustomCommands = customCommands.length > 0;
11742
12750
  console.log(`
11743
12751
  Available commands:
11744
12752
  /help - Show this help message
@@ -11765,8 +12773,19 @@ Tool Permissions:
11765
12773
 
11766
12774
  Project Configuration:
11767
12775
  /project-config - Show merged project configuration
12776
+
12777
+ Custom Commands:
12778
+ /commands - List all custom commands
12779
+ /commands:new <name> - Create a new custom command
12780
+ /commands:reload - Reload custom commands from disk${hasCustomCommands ? "\n\n\u{1F4DD} Custom Commands Available:" : ""}${hasCustomCommands ? customCommands.map((cmd) => {
12781
+ const source = cmd.source === "global" ? "\u{1F3E0}" : "\u{1F4C1}";
12782
+ const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
12783
+ return `
12784
+ ${source} /${cmd.name}${argHint} - ${cmd.description}`;
12785
+ }).join("") : ""}
11768
12786
  `);
11769
12787
  break;
12788
+ }
11770
12789
  case "exit":
11771
12790
  case "quit":
11772
12791
  logger.debug("[EXIT /exit command - cleaning up and exiting...");
@@ -12254,6 +13273,71 @@ No usage data available for the last ${USAGE_DAYS} days.`);
12254
13273
  console.log("");
12255
13274
  break;
12256
13275
  }
13276
+ case "commands": {
13277
+ const customCommands = state.customCommandStore.getAllCommands();
13278
+ const globalCommands = state.customCommandStore.getCommandsBySource("global");
13279
+ const projectCommands = state.customCommandStore.getCommandsBySource("project");
13280
+ console.log("\n\u{1F4DD} Custom Commands:\n");
13281
+ if (customCommands.length === 0) {
13282
+ console.log("No custom commands found.");
13283
+ console.log("\nTo create a custom command:");
13284
+ console.log(" /commands:new <name> - Create a new command");
13285
+ console.log("\nCustom commands can be stored in:");
13286
+ console.log(" \u{1F3E0} Global: ~/.bike4mind/commands/ (available in all projects)");
13287
+ console.log(" \u{1F4C1} Project: .bike4mind/commands/ (team-shared, committed to git)");
13288
+ } else {
13289
+ if (globalCommands.length > 0) {
13290
+ console.log("\u{1F3E0} Global Commands (~/.bike4mind/commands/):");
13291
+ globalCommands.forEach((cmd) => {
13292
+ const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
13293
+ console.log(` /${cmd.name}${argHint} - ${cmd.description}`);
13294
+ });
13295
+ console.log("");
13296
+ }
13297
+ if (projectCommands.length > 0) {
13298
+ console.log("\u{1F4C1} Project Commands (.bike4mind/commands/):");
13299
+ projectCommands.forEach((cmd) => {
13300
+ const argHint = cmd.argumentHint ? ` ${cmd.argumentHint}` : "";
13301
+ console.log(` /${cmd.name}${argHint} - ${cmd.description}`);
13302
+ });
13303
+ console.log("");
13304
+ }
13305
+ console.log(`Total: ${customCommands.length} custom command${customCommands.length !== 1 ? "s" : ""}`);
13306
+ }
13307
+ console.log("");
13308
+ break;
13309
+ }
13310
+ case "commands:new": {
13311
+ const commandName = args[0];
13312
+ if (!commandName) {
13313
+ console.log("\u274C Please provide a command name");
13314
+ console.log("Usage: /commands:new <name>");
13315
+ break;
13316
+ }
13317
+ console.log("\nWhere should this command be stored?");
13318
+ console.log(" 1. \u{1F3E0} Global (~/.bike4mind/commands/) - available in all projects");
13319
+ console.log(" 2. \u{1F4C1} Project (.bike4mind/commands/) - team-shared");
13320
+ console.log("\nDefaulting to global. Creating command file...");
13321
+ try {
13322
+ const filePath = await state.customCommandStore.createCommandFile(commandName, true);
13323
+ console.log(`\u2705 Created command file: ${filePath}`);
13324
+ console.log("\nEdit this file to customize your command.");
13325
+ console.log("Then run: /commands:reload to load it");
13326
+ } catch (error) {
13327
+ console.error("\u274C Failed to create command file:", error instanceof Error ? error.message : String(error));
13328
+ }
13329
+ break;
13330
+ }
13331
+ case "commands:reload": {
13332
+ try {
13333
+ await state.customCommandStore.reloadCommands();
13334
+ const count = state.customCommandStore.getCommandCount();
13335
+ console.log(`\u2705 Reloaded ${count} custom command${count !== 1 ? "s" : ""}`);
13336
+ } catch (error) {
13337
+ console.error("\u274C Failed to reload commands:", error instanceof Error ? error.message : String(error));
13338
+ }
13339
+ break;
13340
+ }
12257
13341
  default:
12258
13342
  console.log(`Unknown command: /${command}`);
12259
13343
  console.log("Type /help for available commands");
@@ -12261,7 +13345,28 @@ No usage data available for the last ${USAGE_DAYS} days.`);
12261
13345
  };
12262
13346
  const handleSaveConfig = async (updatedConfig) => {
12263
13347
  await state.configStore.save(updatedConfig);
12264
- setState((prev) => ({ ...prev, config: updatedConfig }));
13348
+ const modelChanged = state.config?.defaultModel !== updatedConfig.defaultModel;
13349
+ setState((prev) => {
13350
+ if (modelChanged && prev.session) {
13351
+ const updatedSession = {
13352
+ ...prev.session,
13353
+ model: updatedConfig.defaultModel,
13354
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
13355
+ };
13356
+ setStoreSession(updatedSession);
13357
+ if (prev.agent) {
13358
+ prev.agent.context.model = updatedConfig.defaultModel;
13359
+ }
13360
+ return { ...prev, config: updatedConfig, session: updatedSession };
13361
+ }
13362
+ return { ...prev, config: updatedConfig };
13363
+ });
13364
+ if (modelChanged && state.agent) {
13365
+ const llm = state.agent.context.llm;
13366
+ if (llm) {
13367
+ llm.currentModel = updatedConfig.defaultModel;
13368
+ }
13369
+ }
12265
13370
  };
12266
13371
  if (initError) {
12267
13372
  return /* @__PURE__ */ React17.createElement(Box16, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React17.createElement(Text16, { color: "red", bold: true }, "\u274C Initialization Error"), /* @__PURE__ */ React17.createElement(Text16, null, initError), /* @__PURE__ */ React17.createElement(Text16, { dimColor: true }, "\n", "Tip: Run /config to set up your API keys"));
@@ -12350,13 +13455,16 @@ No usage data available for the last ${USAGE_DAYS} days.`);
12350
13455
  if (!isInitialized) {
12351
13456
  return /* @__PURE__ */ React17.createElement(Box16, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React17.createElement(Text16, null, "\u{1F680} Initializing..."));
12352
13457
  }
13458
+ const allCommands = mergeCommands(state.customCommandStore.getAllCommands());
12353
13459
  return /* @__PURE__ */ React17.createElement(
12354
13460
  App,
12355
13461
  {
12356
13462
  onMessage: handleMessage,
12357
13463
  onCommand: handleCommand,
13464
+ onBashCommand: handleBashCommand,
12358
13465
  onImageDetected: handleImageDetected,
12359
13466
  commandHistory,
13467
+ commands: allCommands,
12360
13468
  config: state.config,
12361
13469
  availableModels: state.availableModels,
12362
13470
  onSaveConfig: handleSaveConfig,