@bike4mind/cli 0.2.1-feat-cli-usage-command.17001 → 0.2.1-feat-cli-file-reference.17023

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,9 +4,9 @@ import {
4
4
  getEffectiveApiKey,
5
5
  getOpenWeatherKey,
6
6
  getSerperKey
7
- } from "./chunk-QXGU6KYI.js";
8
- import "./chunk-7R5QIZU3.js";
9
- import "./chunk-F3ETXO5N.js";
7
+ } from "./chunk-GZTILMGE.js";
8
+ import "./chunk-CJRAEEKV.js";
9
+ import "./chunk-5N4PG5EH.js";
10
10
  import {
11
11
  BFLImageService,
12
12
  BaseStorage,
@@ -15,7 +15,7 @@ import {
15
15
  OpenAIBackend,
16
16
  OpenAIImageService,
17
17
  XAIImageService
18
- } from "./chunk-U3GPYBTD.js";
18
+ } from "./chunk-NZADYDFG.js";
19
19
  import {
20
20
  Logger
21
21
  } from "./chunk-AMDXHL6S.js";
@@ -29,7 +29,6 @@ import {
29
29
  AuthEvents,
30
30
  BFL_IMAGE_MODELS,
31
31
  BFL_SAFETY_TOLERANCE,
32
- CREDIT_DEDUCT_TRANSACTION_TYPES,
33
32
  ChatCompletionCreateInputSchema,
34
33
  ChatModels,
35
34
  CollectionType,
@@ -79,13 +78,13 @@ import {
79
78
  } from "./chunk-PDX44BCA.js";
80
79
 
81
80
  // src/index.tsx
82
- import React10, { useState as useState3, useEffect as useEffect3, useCallback } from "react";
83
- import { render, Box as Box10, Text as Text9, useApp, useInput as useInput2 } from "ink";
81
+ import React11, { useState as useState3, useEffect as useEffect3, useCallback } from "react";
82
+ import { render, Box as Box11, Text as Text10, useApp, useInput as useInput2 } from "ink";
84
83
  import { v4 as uuidv49 } from "uuid";
85
84
 
86
85
  // src/components/App.tsx
87
- import React7 from "react";
88
- import { Box as Box7, Text as Text6, Static } from "ink";
86
+ import React8 from "react";
87
+ import { Box as Box8, Text as Text7, Static } from "ink";
89
88
 
90
89
  // src/components/StatusBar.tsx
91
90
  import React from "react";
@@ -95,8 +94,8 @@ var StatusBar = React.memo(function StatusBar2({ sessionName, model, tokenUsage
95
94
  });
96
95
 
97
96
  // src/components/InputPrompt.tsx
98
- import React3, { useState, useMemo, useEffect } from "react";
99
- import { Box as Box3, Text as Text3, useInput } from "ink";
97
+ import React4, { useState, useMemo, useEffect } from "react";
98
+ import { Box as Box4, Text as Text4, useInput } from "ink";
100
99
  import TextInput from "ink-text-input";
101
100
 
102
101
  // src/components/CommandAutocomplete.tsx
@@ -113,8 +112,210 @@ function CommandAutocomplete({ commands, selectedIndex }) {
113
112
  }));
114
113
  }
115
114
 
116
- // src/utils/fuzzySearch.ts
115
+ // src/components/FileAutocomplete.tsx
116
+ import React3 from "react";
117
+ import { Box as Box3, Text as Text3 } from "ink";
118
+
119
+ // src/utils/fileSearch.ts
120
+ import * as fs from "fs";
121
+ import * as path from "path";
117
122
  import Fuse from "fuse.js";
123
+ var DEFAULT_IGNORE_PATTERNS = [
124
+ "node_modules",
125
+ ".git",
126
+ ".next",
127
+ ".turbo",
128
+ "dist",
129
+ "build",
130
+ ".cache",
131
+ "coverage",
132
+ ".DS_Store",
133
+ ".env",
134
+ ".env.local",
135
+ ".env.secrets"
136
+ ];
137
+ function walkDirectory(basePath = process.cwd(), maxDepth = 5, ignorePatterns = DEFAULT_IGNORE_PATTERNS) {
138
+ const results = [];
139
+ const normalizedBase = path.resolve(basePath);
140
+ function walk(currentPath, depth) {
141
+ if (depth > maxDepth) return;
142
+ try {
143
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
144
+ for (const entry of entries) {
145
+ if (ignorePatterns.some((pattern) => entry.name === pattern || entry.name.startsWith(pattern))) {
146
+ continue;
147
+ }
148
+ const fullPath = path.join(currentPath, entry.name);
149
+ const relativePath = path.relative(normalizedBase, fullPath);
150
+ if (entry.isDirectory()) {
151
+ results.push({
152
+ path: relativePath,
153
+ isDirectory: true
154
+ });
155
+ walk(fullPath, depth + 1);
156
+ } else if (entry.isFile()) {
157
+ try {
158
+ const stats = fs.statSync(fullPath);
159
+ results.push({
160
+ path: relativePath,
161
+ isDirectory: false,
162
+ size: stats.size
163
+ });
164
+ } catch {
165
+ results.push({
166
+ path: relativePath,
167
+ isDirectory: false
168
+ });
169
+ }
170
+ }
171
+ }
172
+ } catch {
173
+ }
174
+ }
175
+ walk(normalizedBase, 0);
176
+ return results;
177
+ }
178
+ function formatFileSize(bytes) {
179
+ if (bytes < 1024) return `${bytes} B`;
180
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
181
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
182
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
183
+ }
184
+ var cachedFiles = null;
185
+ var cacheTimestamp = 0;
186
+ var CACHE_TTL_MS = 3e4;
187
+ function getCachedFiles() {
188
+ const now = Date.now();
189
+ if (!cachedFiles || now - cacheTimestamp > CACHE_TTL_MS) {
190
+ cachedFiles = walkDirectory();
191
+ cacheTimestamp = now;
192
+ }
193
+ return cachedFiles;
194
+ }
195
+ function searchFiles(query) {
196
+ const files = getCachedFiles();
197
+ if (!query || query.trim() === "") {
198
+ return files.filter((f) => !f.path.includes(path.sep)).slice(0, 20);
199
+ }
200
+ const queryDir = path.dirname(query);
201
+ let searchPool = files;
202
+ if (queryDir && queryDir !== ".") {
203
+ const normalizedDir = queryDir.replace(/\\/g, "/");
204
+ searchPool = files.filter((f) => {
205
+ const normalizedPath = f.path.replace(/\\/g, "/");
206
+ return normalizedPath.startsWith(normalizedDir + "/") || normalizedPath === normalizedDir;
207
+ });
208
+ if (searchPool.length === 0) {
209
+ searchPool = files;
210
+ }
211
+ }
212
+ const fuse2 = new Fuse(searchPool, {
213
+ keys: [{ name: "path", weight: 1 }],
214
+ threshold: 0.4,
215
+ // Allow some fuzzy matching
216
+ includeScore: true,
217
+ minMatchCharLength: 1,
218
+ // Use extended search for better path matching
219
+ useExtendedSearch: false
220
+ });
221
+ const results = fuse2.search(query);
222
+ return results.slice(0, 20).map((result) => result.item);
223
+ }
224
+ function isPathWithinCwd(filePath) {
225
+ const cwd = path.resolve(process.cwd());
226
+ const absolutePath = path.resolve(cwd, filePath);
227
+ let resolvedCwd = cwd;
228
+ let resolvedPath = absolutePath;
229
+ try {
230
+ const realCwd = fs.realpathSync.native(cwd);
231
+ if (realCwd) {
232
+ resolvedCwd = realCwd;
233
+ }
234
+ } catch {
235
+ }
236
+ try {
237
+ const realPath = fs.realpathSync.native(absolutePath);
238
+ if (realPath) {
239
+ resolvedPath = realPath;
240
+ }
241
+ } catch {
242
+ const relativePath2 = path.relative(cwd, absolutePath);
243
+ resolvedPath = path.resolve(resolvedCwd, relativePath2);
244
+ }
245
+ const normalizedCwd = resolvedCwd.toLowerCase();
246
+ const normalizedPath = resolvedPath.toLowerCase();
247
+ const isWithin = normalizedPath === normalizedCwd || normalizedPath.startsWith(normalizedCwd + path.sep);
248
+ if (!isWithin) {
249
+ return false;
250
+ }
251
+ const relativePath = path.relative(resolvedCwd, resolvedPath);
252
+ return !relativePath.startsWith("..") && !path.isAbsolute(relativePath);
253
+ }
254
+ function isBinaryFile(filePath) {
255
+ const binaryExtensions = [
256
+ ".png",
257
+ ".jpg",
258
+ ".jpeg",
259
+ ".gif",
260
+ ".bmp",
261
+ ".ico",
262
+ ".webp",
263
+ // Note: .svg is NOT included because SVG is XML text format that can be safely read
264
+ ".pdf",
265
+ ".doc",
266
+ ".docx",
267
+ ".xls",
268
+ ".xlsx",
269
+ ".ppt",
270
+ ".pptx",
271
+ ".zip",
272
+ ".tar",
273
+ ".gz",
274
+ ".rar",
275
+ ".7z",
276
+ ".exe",
277
+ ".dll",
278
+ ".so",
279
+ ".dylib",
280
+ ".bin",
281
+ ".dat",
282
+ ".mp3",
283
+ ".mp4",
284
+ ".wav",
285
+ ".avi",
286
+ ".mov",
287
+ ".mkv",
288
+ ".ttf",
289
+ ".otf",
290
+ ".woff",
291
+ ".woff2",
292
+ ".eot",
293
+ ".class",
294
+ ".pyc",
295
+ ".o",
296
+ ".obj"
297
+ ];
298
+ const ext = path.extname(filePath).toLowerCase();
299
+ return binaryExtensions.includes(ext);
300
+ }
301
+ var MAX_FILE_SIZE = 10 * 1024 * 1024;
302
+
303
+ // src/components/FileAutocomplete.tsx
304
+ function FileAutocomplete({ files, selectedIndex, query }) {
305
+ if (files.length === 0) {
306
+ return /* @__PURE__ */ React3.createElement(Box3, { marginLeft: 2, marginTop: 1 }, /* @__PURE__ */ React3.createElement(Text3, { dimColor: true }, "No matching files", query ? ` for "${query}"` : ""));
307
+ }
308
+ return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", marginLeft: 2, marginTop: 1 }, /* @__PURE__ */ React3.createElement(Box3, { marginBottom: 1 }, /* @__PURE__ */ React3.createElement(Text3, { dimColor: true }, files.length === 1 ? "1 match" : `${files.length} matches`, " - Use up/down to navigate, Tab to select")), files.map((file, index) => {
309
+ const isSelected = index === selectedIndex;
310
+ const icon = file.isDirectory ? "[folder]" : "[file] ";
311
+ const sizeDisplay = file.isDirectory ? "" : file.size !== void 0 ? ` (${formatFileSize(file.size)})` : "";
312
+ const pathDisplay = file.isDirectory ? `${file.path}/` : file.path;
313
+ return /* @__PURE__ */ React3.createElement(Box3, { key: file.path, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: isSelected ? "cyan" : void 0, bold: isSelected }, isSelected ? "> " : " "), /* @__PURE__ */ React3.createElement(Text3, { color: file.isDirectory ? "yellow" : isSelected ? "cyan" : void 0, bold: isSelected }, icon), /* @__PURE__ */ React3.createElement(Text3, { color: isSelected ? "cyan" : void 0, bold: isSelected }, " ", pathDisplay), /* @__PURE__ */ React3.createElement(Text3, { dimColor: true }, sizeDisplay));
314
+ }));
315
+ }
316
+
317
+ // src/utils/fuzzySearch.ts
318
+ import Fuse2 from "fuse.js";
118
319
 
119
320
  // src/config/commands.ts
120
321
  var COMMANDS = [
@@ -178,15 +379,11 @@ var COMMANDS = [
178
379
  {
179
380
  name: "trusted",
180
381
  description: "List all trusted tools"
181
- },
182
- {
183
- name: "usage",
184
- description: "Show credit usage and balance"
185
382
  }
186
383
  ];
187
384
 
188
385
  // src/utils/fuzzySearch.ts
189
- var fuse = new Fuse(COMMANDS, {
386
+ var fuse = new Fuse2(COMMANDS, {
190
387
  keys: [
191
388
  { name: "name", weight: 0.7 },
192
389
  // Prioritize command name
@@ -207,23 +404,71 @@ function searchCommands(query) {
207
404
  }
208
405
 
209
406
  // src/components/InputPrompt.tsx
407
+ function shouldShowFileAutocomplete(_query) {
408
+ return true;
409
+ }
410
+ function findAtTrigger(value) {
411
+ for (let i = value.length - 1; i >= 0; i--) {
412
+ if (value[i] === "@") {
413
+ const isValid = i === 0 || value[i - 1] === " ";
414
+ if (isValid) {
415
+ const query = value.slice(i + 1);
416
+ if (query.includes(" ")) {
417
+ return null;
418
+ }
419
+ if (!shouldShowFileAutocomplete(query)) {
420
+ return null;
421
+ }
422
+ return { startIndex: i, query };
423
+ }
424
+ }
425
+ }
426
+ return null;
427
+ }
210
428
  function InputPrompt({ onSubmit, disabled = false, history = [] }) {
211
429
  const [value, setValue] = useState("");
212
430
  const [selectedIndex, setSelectedIndex] = useState(0);
213
431
  const [historyIndex, setHistoryIndex] = useState(-1);
214
432
  const [tempInput, setTempInput] = useState("");
215
433
  const [inputKey, setInputKey] = useState(0);
216
- const shouldShowAutocomplete = value.startsWith("/") && !disabled;
217
- const query = shouldShowAutocomplete ? value.slice(1) : "";
434
+ const [fileAutocomplete, setFileAutocomplete] = useState(null);
435
+ const [fileSelectedIndex, setFileSelectedIndex] = useState(0);
436
+ const shouldShowCommandAutocomplete = value.startsWith("/") && !disabled && !fileAutocomplete?.active;
437
+ const commandQuery = shouldShowCommandAutocomplete ? value.slice(1) : "";
218
438
  const filteredCommands = useMemo(() => {
219
- if (!shouldShowAutocomplete) return [];
220
- return searchCommands(query);
221
- }, [shouldShowAutocomplete, query]);
439
+ if (!shouldShowCommandAutocomplete) return [];
440
+ return searchCommands(commandQuery);
441
+ }, [shouldShowCommandAutocomplete, commandQuery]);
442
+ const filteredFiles = useMemo(() => {
443
+ if (!fileAutocomplete?.active) return [];
444
+ return searchFiles(fileAutocomplete.query);
445
+ }, [fileAutocomplete?.active, fileAutocomplete?.query]);
222
446
  useEffect(() => {
223
447
  setSelectedIndex(0);
224
448
  }, [filteredCommands]);
449
+ useEffect(() => {
450
+ setFileSelectedIndex(0);
451
+ }, [filteredFiles]);
225
452
  useInput((input, key) => {
226
- if (shouldShowAutocomplete && filteredCommands.length > 0) {
453
+ if (fileAutocomplete?.active && filteredFiles.length > 0) {
454
+ if (key.upArrow) {
455
+ setFileSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredFiles.length - 1);
456
+ return;
457
+ } else if (key.downArrow) {
458
+ setFileSelectedIndex((prev) => prev < filteredFiles.length - 1 ? prev + 1 : 0);
459
+ return;
460
+ } else if (key.tab) {
461
+ const selectedFile = filteredFiles[fileSelectedIndex];
462
+ if (selectedFile) {
463
+ insertSelectedFile(selectedFile);
464
+ }
465
+ return;
466
+ } else if (key.escape) {
467
+ setFileAutocomplete(null);
468
+ return;
469
+ }
470
+ }
471
+ if (shouldShowCommandAutocomplete && filteredCommands.length > 0) {
227
472
  if (key.upArrow) {
228
473
  setSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredCommands.length - 1);
229
474
  } else if (key.downArrow) {
@@ -231,7 +476,7 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
231
476
  }
232
477
  return;
233
478
  }
234
- if (!shouldShowAutocomplete && history.length > 0) {
479
+ if (!shouldShowCommandAutocomplete && !fileAutocomplete?.active && history.length > 0) {
235
480
  if (key.upArrow) {
236
481
  if (historyIndex === -1) {
237
482
  setTempInput(value);
@@ -254,9 +499,35 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
254
499
  }
255
500
  }
256
501
  });
502
+ const insertSelectedFile = (file) => {
503
+ if (!fileAutocomplete) return;
504
+ const beforeAt = value.slice(0, fileAutocomplete.startIndex);
505
+ const afterQuery = value.slice(fileAutocomplete.startIndex + 1 + fileAutocomplete.query.length);
506
+ const pathToInsert = file.isDirectory ? `@${file.path}/` : `@${file.path}`;
507
+ const newValue = beforeAt + pathToInsert + afterQuery;
508
+ setValue(newValue);
509
+ setInputKey((prev) => prev + 1);
510
+ if (file.isDirectory) {
511
+ setFileAutocomplete({
512
+ active: true,
513
+ startIndex: fileAutocomplete.startIndex,
514
+ query: file.path + "/"
515
+ });
516
+ setFileSelectedIndex(0);
517
+ } else {
518
+ setFileAutocomplete(null);
519
+ }
520
+ };
257
521
  const handleSubmit = (input) => {
258
522
  if (disabled || !input.trim()) return;
259
- if (shouldShowAutocomplete && filteredCommands.length > 0) {
523
+ if (fileAutocomplete?.active && filteredFiles.length > 0) {
524
+ const selectedFile = filteredFiles[fileSelectedIndex];
525
+ if (selectedFile) {
526
+ insertSelectedFile(selectedFile);
527
+ }
528
+ return;
529
+ }
530
+ if (shouldShowCommandAutocomplete && filteredCommands.length > 0) {
260
531
  const selectedCommand = filteredCommands[selectedIndex];
261
532
  const commandText = `/${selectedCommand.name}`;
262
533
  if (selectedCommand.args) {
@@ -273,6 +544,7 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
273
544
  onSubmit(input);
274
545
  setValue("");
275
546
  setHistoryIndex(-1);
547
+ setFileAutocomplete(null);
276
548
  };
277
549
  const handleChange = (newValue) => {
278
550
  setValue(newValue);
@@ -280,30 +552,40 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
280
552
  setHistoryIndex(-1);
281
553
  setTempInput("");
282
554
  }
555
+ const atTrigger = findAtTrigger(newValue);
556
+ if (atTrigger) {
557
+ setFileAutocomplete({
558
+ active: true,
559
+ startIndex: atTrigger.startIndex,
560
+ query: atTrigger.query
561
+ });
562
+ } else {
563
+ setFileAutocomplete(null);
564
+ }
283
565
  };
284
- return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column" }, /* @__PURE__ */ React3.createElement(Box3, null, /* @__PURE__ */ React3.createElement(Text3, { bold: true, color: "cyan" }, "> "), /* @__PURE__ */ React3.createElement(
566
+ return /* @__PURE__ */ React4.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { bold: true, color: "cyan" }, "> "), /* @__PURE__ */ React4.createElement(
285
567
  TextInput,
286
568
  {
287
569
  key: inputKey,
288
570
  value,
289
571
  onChange: handleChange,
290
572
  onSubmit: handleSubmit,
291
- placeholder: disabled ? "Thinking..." : "Type your message or /help for commands",
573
+ placeholder: disabled ? "Thinking..." : "Type your message, /help for commands, or @file to reference",
292
574
  showCursor: !disabled
293
575
  }
294
- )), shouldShowAutocomplete && /* @__PURE__ */ React3.createElement(CommandAutocomplete, { commands: filteredCommands, selectedIndex }));
576
+ )), shouldShowCommandAutocomplete && /* @__PURE__ */ React4.createElement(CommandAutocomplete, { commands: filteredCommands, selectedIndex }), fileAutocomplete?.active && /* @__PURE__ */ React4.createElement(FileAutocomplete, { files: filteredFiles, selectedIndex: fileSelectedIndex, query: fileAutocomplete.query }));
295
577
  }
296
578
 
297
579
  // src/components/AgentThinking.tsx
298
- import React5 from "react";
299
- import { Box as Box5 } from "ink";
580
+ import React6 from "react";
581
+ import { Box as Box6 } from "ink";
300
582
 
301
583
  // src/components/ThoughtStream.tsx
302
- import React4 from "react";
303
- import { Box as Box4, Text as Text4 } from "ink";
584
+ import React5 from "react";
585
+ import { Box as Box5, Text as Text5 } from "ink";
304
586
  import Spinner from "ink-spinner";
305
- var ThoughtStream = React4.memo(function ThoughtStream2({ steps }) {
306
- return /* @__PURE__ */ React4.createElement(Box4, { flexDirection: "column", gap: 1 }, steps.map((step, index) => /* @__PURE__ */ React4.createElement(Box4, { key: index, flexDirection: "column" }, step.type === "thought" && /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { color: "magenta" }, "\u{1F914} Thought: "), /* @__PURE__ */ React4.createElement(Text4, null, step.content)), step.type === "action" && /* @__PURE__ */ React4.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { color: "yellow" }, "\u26A1 Action: "), /* @__PURE__ */ React4.createElement(Text4, { bold: true }, step.metadata?.toolName || "unknown")), step.metadata?.toolInput && /* @__PURE__ */ React4.createElement(Box4, { paddingLeft: 2 }, /* @__PURE__ */ React4.createElement(Text4, { dimColor: true }, JSON.stringify(step.metadata.toolInput, null, 2)))), step.type === "observation" && /* @__PURE__ */ React4.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { color: "blue" }, "\u{1F4CA} Observation: ")), /* @__PURE__ */ React4.createElement(Box4, { paddingLeft: 2 }, /* @__PURE__ */ React4.createElement(Text4, null, step.content))), step.type === "final_answer" && /* @__PURE__ */ React4.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { color: "green", bold: true }, "\u2705 Final Answer:", " ")), /* @__PURE__ */ React4.createElement(Box4, { paddingLeft: 2 }, /* @__PURE__ */ React4.createElement(Text4, null, step.content)), step.metadata?.tokenUsage && /* @__PURE__ */ React4.createElement(Box4, { paddingLeft: 2 }, /* @__PURE__ */ React4.createElement(Text4, { dimColor: true }, "(", step.metadata.tokenUsage.total, " tokens)"))))), !steps.some((s) => s.type === "final_answer") && /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { color: "yellow" }, /* @__PURE__ */ React4.createElement(Spinner, { type: "dots" })), /* @__PURE__ */ React4.createElement(Text4, null, " ", steps.length === 0 ? "Thinking..." : "Processing...")));
587
+ var ThoughtStream = React5.memo(function ThoughtStream2({ steps }) {
588
+ return /* @__PURE__ */ React5.createElement(Box5, { flexDirection: "column", gap: 1 }, steps.map((step, index) => /* @__PURE__ */ React5.createElement(Box5, { key: index, flexDirection: "column" }, step.type === "thought" && /* @__PURE__ */ React5.createElement(Box5, null, /* @__PURE__ */ React5.createElement(Text5, { color: "magenta" }, "\u{1F914} Thought: "), /* @__PURE__ */ React5.createElement(Text5, null, step.content)), step.type === "action" && /* @__PURE__ */ React5.createElement(Box5, { flexDirection: "column" }, /* @__PURE__ */ React5.createElement(Box5, null, /* @__PURE__ */ React5.createElement(Text5, { color: "yellow" }, "\u26A1 Action: "), /* @__PURE__ */ React5.createElement(Text5, { bold: true }, step.metadata?.toolName || "unknown")), step.metadata?.toolInput && /* @__PURE__ */ React5.createElement(Box5, { paddingLeft: 2 }, /* @__PURE__ */ React5.createElement(Text5, { dimColor: true }, JSON.stringify(step.metadata.toolInput, null, 2)))), step.type === "observation" && /* @__PURE__ */ React5.createElement(Box5, { flexDirection: "column" }, /* @__PURE__ */ React5.createElement(Box5, null, /* @__PURE__ */ React5.createElement(Text5, { color: "blue" }, "\u{1F4CA} Observation: ")), /* @__PURE__ */ React5.createElement(Box5, { paddingLeft: 2 }, /* @__PURE__ */ React5.createElement(Text5, null, step.content))), step.type === "final_answer" && /* @__PURE__ */ React5.createElement(Box5, { flexDirection: "column" }, /* @__PURE__ */ React5.createElement(Box5, null, /* @__PURE__ */ React5.createElement(Text5, { color: "green", bold: true }, "\u2705 Final Answer:", " ")), /* @__PURE__ */ React5.createElement(Box5, { paddingLeft: 2 }, /* @__PURE__ */ React5.createElement(Text5, null, step.content)), step.metadata?.tokenUsage && /* @__PURE__ */ React5.createElement(Box5, { paddingLeft: 2 }, /* @__PURE__ */ React5.createElement(Text5, { dimColor: true }, "(", step.metadata.tokenUsage.total, " tokens)"))))), !steps.some((s) => s.type === "final_answer") && /* @__PURE__ */ React5.createElement(Box5, null, /* @__PURE__ */ React5.createElement(Text5, { color: "yellow" }, /* @__PURE__ */ React5.createElement(Spinner, { type: "dots" })), /* @__PURE__ */ React5.createElement(Text5, null, " ", steps.length === 0 ? "Thinking..." : "Processing...")));
307
589
  });
308
590
 
309
591
  // src/store/index.ts
@@ -329,32 +611,32 @@ var useCliStore = create((set) => ({
329
611
  }));
330
612
 
331
613
  // src/components/AgentThinking.tsx
332
- var AgentThinking = React5.memo(function AgentThinking2() {
614
+ var AgentThinking = React6.memo(function AgentThinking2() {
333
615
  const isThinking = useCliStore((state) => state.isThinking);
334
616
  const agentSteps = useCliStore((state) => state.agentSteps);
335
617
  if (!isThinking) {
336
618
  return null;
337
619
  }
338
- return /* @__PURE__ */ React5.createElement(Box5, { borderStyle: "single", borderColor: "yellow", paddingX: 1, marginY: 1 }, /* @__PURE__ */ React5.createElement(ThoughtStream, { steps: agentSteps }));
620
+ return /* @__PURE__ */ React6.createElement(Box6, { borderStyle: "single", borderColor: "yellow", paddingX: 1, marginY: 1 }, /* @__PURE__ */ React6.createElement(ThoughtStream, { steps: agentSteps }));
339
621
  });
340
622
 
341
623
  // src/components/PermissionPrompt.tsx
342
- import React6 from "react";
343
- import { Box as Box6, Text as Text5 } from "ink";
624
+ import React7 from "react";
625
+ import { Box as Box7, Text as Text6 } from "ink";
344
626
  import SelectInput from "ink-select-input";
345
627
  function renderDiffPreview(preview) {
346
628
  const lines = preview.split("\n");
347
629
  return lines.map((line, index) => {
348
630
  if (line.startsWith("+")) {
349
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, color: "green" }, line);
631
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, color: "green" }, line);
350
632
  }
351
633
  if (line.startsWith("-")) {
352
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, color: "red" }, line);
634
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, color: "red" }, line);
353
635
  }
354
636
  if (line.startsWith("@@")) {
355
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, color: "cyan" }, line);
637
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, color: "cyan" }, line);
356
638
  }
357
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, dimColor: true }, line);
639
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, dimColor: true }, line);
358
640
  });
359
641
  }
360
642
  function PermissionPrompt({
@@ -374,7 +656,121 @@ function PermissionPrompt({
374
656
  { label: "\u2717 Deny", value: "deny" }
375
657
  ];
376
658
  const argsString = typeof args === "string" ? args : JSON.stringify(args, null, 2);
377
- return /* @__PURE__ */ React6.createElement(Box6, { flexDirection: "column", borderStyle: "bold", borderColor: "yellow", padding: 1, marginY: 1 }, /* @__PURE__ */ React6.createElement(Box6, null, /* @__PURE__ */ React6.createElement(Text5, { bold: true, color: "yellow" }, "\u26A0\uFE0F Permission Required")), /* @__PURE__ */ React6.createElement(Box6, { marginTop: 1 }, /* @__PURE__ */ React6.createElement(Text5, { dimColor: true }, "Tool: "), /* @__PURE__ */ React6.createElement(Text5, { bold: true, color: "cyan" }, toolName)), toolDescription && /* @__PURE__ */ React6.createElement(Box6, null, /* @__PURE__ */ React6.createElement(Text5, { dimColor: true }, "Action: "), /* @__PURE__ */ React6.createElement(Text5, null, toolDescription)), /* @__PURE__ */ React6.createElement(Box6, { marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React6.createElement(Text5, { bold: true }, "Arguments:"), /* @__PURE__ */ React6.createElement(Box6, { paddingLeft: 2, flexDirection: "column" }, /* @__PURE__ */ React6.createElement(Text5, { dimColor: true }, argsString))), preview && /* @__PURE__ */ React6.createElement(Box6, { marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React6.createElement(Text5, { bold: true }, "Preview:"), /* @__PURE__ */ React6.createElement(Box6, { borderStyle: "single", borderColor: "gray", paddingX: 1, flexDirection: "column" }, renderDiffPreview(preview))), !canBeTrusted && /* @__PURE__ */ React6.createElement(Box6, { marginTop: 1 }, /* @__PURE__ */ React6.createElement(Text5, { color: "red", dimColor: true }, "Note: This tool cannot be trusted due to its dangerous nature.")), /* @__PURE__ */ React6.createElement(Box6, { marginTop: 1 }, /* @__PURE__ */ React6.createElement(SelectInput, { items, onSelect: (item) => onResponse(item.value) })));
659
+ return /* @__PURE__ */ React7.createElement(Box7, { flexDirection: "column", borderStyle: "bold", borderColor: "yellow", padding: 1, marginY: 1 }, /* @__PURE__ */ React7.createElement(Box7, null, /* @__PURE__ */ React7.createElement(Text6, { bold: true, color: "yellow" }, "\u26A0\uFE0F Permission Required")), /* @__PURE__ */ React7.createElement(Box7, { marginTop: 1 }, /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, "Tool: "), /* @__PURE__ */ React7.createElement(Text6, { bold: true, color: "cyan" }, toolName)), toolDescription && /* @__PURE__ */ React7.createElement(Box7, null, /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, "Action: "), /* @__PURE__ */ React7.createElement(Text6, null, toolDescription)), /* @__PURE__ */ React7.createElement(Box7, { marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React7.createElement(Text6, { bold: true }, "Arguments:"), /* @__PURE__ */ React7.createElement(Box7, { paddingLeft: 2, flexDirection: "column" }, /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, argsString))), preview && /* @__PURE__ */ React7.createElement(Box7, { marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React7.createElement(Text6, { bold: true }, "Preview:"), /* @__PURE__ */ React7.createElement(Box7, { borderStyle: "single", borderColor: "gray", paddingX: 1, flexDirection: "column" }, renderDiffPreview(preview))), !canBeTrusted && /* @__PURE__ */ React7.createElement(Box7, { marginTop: 1 }, /* @__PURE__ */ React7.createElement(Text6, { color: "red", dimColor: true }, "Note: This tool cannot be trusted due to its dangerous nature.")), /* @__PURE__ */ React7.createElement(Box7, { marginTop: 1 }, /* @__PURE__ */ React7.createElement(SelectInput, { items, onSelect: (item) => onResponse(item.value) })));
660
+ }
661
+
662
+ // src/utils/processFileReferences.ts
663
+ import * as fs2 from "fs";
664
+ import * as path2 from "path";
665
+
666
+ // src/utils/constants.ts
667
+ var NAME_SUFFIXES = ["jr", "sr", "ii", "iii", "iv", "v", "phd", "md", "esq"];
668
+ function isNameSuffix(value) {
669
+ return NAME_SUFFIXES.includes(value);
670
+ }
671
+
672
+ // src/utils/processFileReferences.ts
673
+ var FILE_REFERENCE_REGEX = /(?:^|\s)@([^\s@]+)/g;
674
+ function looksLikeFilePath(ref) {
675
+ if (ref.includes("/") || ref.includes(path2.sep)) {
676
+ return true;
677
+ }
678
+ const extensionMatch = /\.(\w+)$/.exec(ref);
679
+ if (extensionMatch) {
680
+ const ext = extensionMatch[1].toLowerCase();
681
+ if (isNameSuffix(ext)) {
682
+ return false;
683
+ }
684
+ if (ext.length > 10) {
685
+ return false;
686
+ }
687
+ return true;
688
+ }
689
+ return false;
690
+ }
691
+ function extractFileReferences(message) {
692
+ const references = [];
693
+ const regex = /(?:^|\s)@([^\s@]+)/g;
694
+ let match;
695
+ while ((match = regex.exec(message)) !== null) {
696
+ const ref = match[1];
697
+ if (looksLikeFilePath(ref)) {
698
+ references.push(ref);
699
+ }
700
+ }
701
+ return references;
702
+ }
703
+ function readFileContents(filePath) {
704
+ const cwd = process.cwd();
705
+ const absolutePath = path2.resolve(cwd, filePath);
706
+ if (!isPathWithinCwd(filePath)) {
707
+ return { error: `Security: Path "${filePath}" is outside the current working directory` };
708
+ }
709
+ if (!fs2.existsSync(absolutePath)) {
710
+ return { error: `File not found: "${filePath}"` };
711
+ }
712
+ const stats = fs2.statSync(absolutePath);
713
+ if (stats.isDirectory()) {
714
+ try {
715
+ const entries = fs2.readdirSync(absolutePath);
716
+ const fileCount = entries.length;
717
+ return {
718
+ content: `(Directory with ${fileCount} items. Use file tools to explore if needed.)`,
719
+ size: 0
720
+ };
721
+ } catch (err) {
722
+ return { error: `Cannot read directory "${filePath}": ${err instanceof Error ? err.message : "Unknown error"}` };
723
+ }
724
+ }
725
+ if (stats.size > MAX_FILE_SIZE) {
726
+ return {
727
+ error: `File too large: "${filePath}" is ${formatFileSize(stats.size)} (max ${formatFileSize(MAX_FILE_SIZE)})`
728
+ };
729
+ }
730
+ if (isBinaryFile(filePath)) {
731
+ return { error: `Binary file: "${filePath}" cannot be included as text content` };
732
+ }
733
+ try {
734
+ const content = fs2.readFileSync(absolutePath, "utf-8");
735
+ return { content, size: stats.size };
736
+ } catch (err) {
737
+ return { error: `Cannot read file "${filePath}": ${err instanceof Error ? err.message : "Unknown error"}` };
738
+ }
739
+ }
740
+ function formatFileBlock(filePath, content, size, isDirectory) {
741
+ if (isDirectory) {
742
+ return `
743
+ --- Directory Reference: ${filePath} ---
744
+ ${content}
745
+ --- End of ${filePath} ---`;
746
+ }
747
+ return `
748
+ --- Referenced File: ${filePath} (${formatFileSize(size)}) ---
749
+ ${content}
750
+ --- End of ${filePath} ---`;
751
+ }
752
+ async function processFileReferences(message) {
753
+ const references = extractFileReferences(message);
754
+ const errors = [];
755
+ const fileBlocks = [];
756
+ for (const ref of references) {
757
+ const result = readFileContents(ref);
758
+ if ("error" in result) {
759
+ errors.push(result.error);
760
+ continue;
761
+ }
762
+ const isDirectory = result.size === 0 && result.content.startsWith("(Directory");
763
+ fileBlocks.push(formatFileBlock(ref, result.content, result.size, isDirectory));
764
+ }
765
+ if (fileBlocks.length === 0) {
766
+ return { content: message, errors };
767
+ }
768
+ const processedContent = message + "\n" + fileBlocks.join("\n");
769
+ return { content: processedContent, errors };
770
+ }
771
+ function hasFileReferences(message) {
772
+ FILE_REFERENCE_REGEX.lastIndex = 0;
773
+ return FILE_REFERENCE_REGEX.test(message);
378
774
  }
379
775
 
380
776
  // src/components/App.tsx
@@ -387,7 +783,7 @@ function App({ onMessage, onCommand, onPermissionResponse, commandHistory = [] }
387
783
  const permissionPrompt = useCliStore((state) => state.permissionPrompt);
388
784
  const exitRequested = useCliStore((state) => state.exitRequested);
389
785
  const setIsThinking = useCliStore((state) => state.setIsThinking);
390
- const handleSubmit = React7.useCallback(
786
+ const handleSubmit = React8.useCallback(
391
787
  async (input) => {
392
788
  const trimmed = input.trim();
393
789
  if (!trimmed) return;
@@ -398,14 +794,25 @@ function App({ onMessage, onCommand, onPermissionResponse, commandHistory = [] }
398
794
  }
399
795
  setIsThinking(true);
400
796
  try {
401
- await onMessage(trimmed);
797
+ let messageToSend = trimmed;
798
+ if (hasFileReferences(trimmed)) {
799
+ const processed = await processFileReferences(trimmed);
800
+ messageToSend = processed.content;
801
+ if (processed.errors.length > 0) {
802
+ const errorBlock = processed.errors.map((e) => `[Warning: ${e}]`).join("\n");
803
+ messageToSend = `${messageToSend}
804
+
805
+ ${errorBlock}`;
806
+ }
807
+ }
808
+ await onMessage(messageToSend);
402
809
  } finally {
403
810
  setIsThinking(false);
404
811
  }
405
812
  },
406
813
  [onMessage, onCommand, setIsThinking]
407
814
  );
408
- return /* @__PURE__ */ React7.createElement(Box7, { flexDirection: "column" }, /* @__PURE__ */ React7.createElement(StatusBar, { sessionName, model: currentModel, tokenUsage: totalTokens }), permissionPrompt ? /* @__PURE__ */ React7.createElement(Box7, { flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React7.createElement(
815
+ return /* @__PURE__ */ React8.createElement(Box8, { flexDirection: "column" }, /* @__PURE__ */ React8.createElement(StatusBar, { sessionName, model: currentModel, tokenUsage: totalTokens }), permissionPrompt ? /* @__PURE__ */ React8.createElement(Box8, { flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React8.createElement(
409
816
  PermissionPrompt,
410
817
  {
411
818
  toolName: permissionPrompt.toolName,
@@ -414,39 +821,39 @@ function App({ onMessage, onCommand, onPermissionResponse, commandHistory = [] }
414
821
  canBeTrusted: permissionPrompt.canBeTrusted,
415
822
  onResponse: onPermissionResponse
416
823
  }
417
- )) : /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(Static, { items: messages }, (message, index) => /* @__PURE__ */ React7.createElement(Box7, { key: index, flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React7.createElement(MessageItem, { message }))), /* @__PURE__ */ React7.createElement(AgentThinking, null), exitRequested && /* @__PURE__ */ React7.createElement(Box7, { paddingX: 1, marginBottom: 1 }, /* @__PURE__ */ React7.createElement(Text6, { color: "yellow", bold: true }, "\u26A0\uFE0F Press Ctrl+C again to exit")), /* @__PURE__ */ React7.createElement(Box7, { borderStyle: "single", borderColor: "cyan", paddingX: 1 }, /* @__PURE__ */ React7.createElement(InputPrompt, { onSubmit: handleSubmit, disabled: isThinking, history: commandHistory }))));
824
+ )) : /* @__PURE__ */ React8.createElement(React8.Fragment, null, /* @__PURE__ */ React8.createElement(Static, { items: messages }, (message, index) => /* @__PURE__ */ React8.createElement(Box8, { key: index, flexDirection: "column", paddingX: 1 }, /* @__PURE__ */ React8.createElement(MessageItem, { message }))), /* @__PURE__ */ React8.createElement(AgentThinking, null), exitRequested && /* @__PURE__ */ React8.createElement(Box8, { paddingX: 1, marginBottom: 1 }, /* @__PURE__ */ React8.createElement(Text7, { color: "yellow", bold: true }, "\u26A0\uFE0F Press Ctrl+C again to exit")), /* @__PURE__ */ React8.createElement(Box8, { borderStyle: "single", borderColor: "cyan", paddingX: 1 }, /* @__PURE__ */ React8.createElement(InputPrompt, { onSubmit: handleSubmit, disabled: isThinking, history: commandHistory }))));
418
825
  }
419
826
  function MessageItem({ message }) {
420
- return /* @__PURE__ */ React7.createElement(Box7, { flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ React7.createElement(Box7, null, /* @__PURE__ */ React7.createElement(Text6, { bold: true, color: message.role === "user" ? "cyan" : "green" }, message.role === "user" ? "\u{1F464} You" : "\u{1F916} Assistant"), /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, " \u2022 ", new Date(message.timestamp).toLocaleTimeString())), /* @__PURE__ */ React7.createElement(Box7, { paddingLeft: 2 }, message.metadata?.permissionDenied ? /* @__PURE__ */ React7.createElement(Text6, { color: "yellow" }, "\u26A0\uFE0F ", message.content) : /* @__PURE__ */ React7.createElement(Text6, null, message.content)), message.metadata?.steps && message.metadata.steps.length > 0 && /* @__PURE__ */ React7.createElement(Box7, { paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React7.createElement(Text6, { dimColor: true, bold: true }, "\u{1F527} Agent Reasoning Trace (", message.metadata.steps.filter((s) => s.type === "action").length, " ", "tools used, ", message.metadata.steps.length, " total steps)", message.metadata.tokenUsage && ` \u2022 ${message.metadata.tokenUsage.total} tokens`), /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, "Step types: ", message.metadata.steps.map((s) => s.type).join(", ")), message.metadata.steps.map((step, idx) => {
827
+ return /* @__PURE__ */ React8.createElement(Box8, { flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ React8.createElement(Box8, null, /* @__PURE__ */ React8.createElement(Text7, { bold: true, color: message.role === "user" ? "cyan" : "green" }, message.role === "user" ? "\u{1F464} You" : "\u{1F916} Assistant"), /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, " \u2022 ", new Date(message.timestamp).toLocaleTimeString())), /* @__PURE__ */ React8.createElement(Box8, { paddingLeft: 2 }, message.metadata?.permissionDenied ? /* @__PURE__ */ React8.createElement(Text7, { color: "yellow" }, "\u26A0\uFE0F ", message.content) : /* @__PURE__ */ React8.createElement(Text7, null, message.content)), message.metadata?.steps && message.metadata.steps.length > 0 && /* @__PURE__ */ React8.createElement(Box8, { paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React8.createElement(Text7, { dimColor: true, bold: true }, "\u{1F527} Agent Reasoning Trace (", message.metadata.steps.filter((s) => s.type === "action").length, " ", "tools used, ", message.metadata.steps.length, " total steps)", message.metadata.tokenUsage && ` \u2022 ${message.metadata.tokenUsage.total} tokens`), /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, "Step types: ", message.metadata.steps.map((s) => s.type).join(", ")), message.metadata.steps.map((step, idx) => {
421
828
  if (step.type === "thought") {
422
- return /* @__PURE__ */ React7.createElement(Box7, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React7.createElement(Text6, { color: "blue" }, "\u{1F4AD} Thought:"), /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, ` ${step.content.slice(0, 200)}${step.content.length > 200 ? "..." : ""}`));
829
+ return /* @__PURE__ */ React8.createElement(Box8, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React8.createElement(Text7, { color: "blue" }, "\u{1F4AD} Thought:"), /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, ` ${step.content.slice(0, 200)}${step.content.length > 200 ? "..." : ""}`));
423
830
  }
424
831
  if (step.type === "action") {
425
832
  const toolName = step.metadata?.toolName || "unknown";
426
833
  const toolInput = step.metadata?.toolInput;
427
834
  const observationStep = message.metadata.steps[idx + 1];
428
835
  const result = observationStep?.type === "observation" ? observationStep.content : null;
429
- return /* @__PURE__ */ React7.createElement(Box7, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React7.createElement(Text6, { color: "yellow" }, "\u{1F527} Action: ", toolName), toolInput && /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, ` Input: ${typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput).slice(0, 100)}`), result && /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, ` Result: ${typeof result === "string" ? result.slice(0, 200) : JSON.stringify(result).slice(0, 200)}${(typeof result === "string" ? result.length : JSON.stringify(result).length) > 200 ? "..." : ""}`));
836
+ return /* @__PURE__ */ React8.createElement(Box8, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React8.createElement(Text7, { color: "yellow" }, "\u{1F527} Action: ", toolName), toolInput && /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, ` Input: ${typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput).slice(0, 100)}`), result && /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, ` Result: ${typeof result === "string" ? result.slice(0, 200) : JSON.stringify(result).slice(0, 200)}${(typeof result === "string" ? result.length : JSON.stringify(result).length) > 200 ? "..." : ""}`));
430
837
  }
431
838
  return null;
432
- }).filter(Boolean)), message.metadata?.tokenUsage && (!message.metadata.steps || message.metadata.steps.length === 0) && /* @__PURE__ */ React7.createElement(Box7, { paddingLeft: 2 }, /* @__PURE__ */ React7.createElement(Text6, { dimColor: true }, `${message.metadata.tokenUsage.total} tokens`)));
839
+ }).filter(Boolean)), message.metadata?.tokenUsage && (!message.metadata.steps || message.metadata.steps.length === 0) && /* @__PURE__ */ React8.createElement(Box8, { paddingLeft: 2 }, /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, `${message.metadata.tokenUsage.total} tokens`)));
433
840
  }
434
841
 
435
842
  // src/components/MessageList.tsx
436
- import React8 from "react";
437
- import { Box as Box8, Text as Text7 } from "ink";
843
+ import React9 from "react";
844
+ import { Box as Box9, Text as Text8 } from "ink";
438
845
  function stripThinkingTags(content) {
439
846
  return content.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
440
847
  }
441
- var MessageList = React8.memo(
848
+ var MessageList = React9.memo(
442
849
  function MessageList2({ messages }) {
443
850
  if (messages.length === 0) {
444
- return /* @__PURE__ */ React8.createElement(Box8, { paddingY: 1 }, /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, "No messages yet. Type a message to start!"));
851
+ return /* @__PURE__ */ React9.createElement(Box9, { paddingY: 1 }, /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, "No messages yet. Type a message to start!"));
445
852
  }
446
- return /* @__PURE__ */ React8.createElement(Box8, { flexDirection: "column", gap: 1, paddingY: 1 }, messages.map((message, index) => /* @__PURE__ */ React8.createElement(Box8, { key: index, flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ React8.createElement(Box8, null, /* @__PURE__ */ React8.createElement(Text7, { bold: true, color: message.role === "user" ? "cyan" : "green" }, message.role === "user" ? "\u{1F464} You" : "\u{1F916} Assistant"), /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, " \u2022 ", new Date(message.timestamp).toLocaleTimeString())), /* @__PURE__ */ React8.createElement(Box8, { paddingLeft: 2 }, message.metadata?.permissionDenied ? /* @__PURE__ */ React8.createElement(Text7, { color: "yellow" }, "\u26A0\uFE0F ", stripThinkingTags(message.content)) : /* @__PURE__ */ React8.createElement(Text7, null, stripThinkingTags(message.content))), message.metadata?.steps && message.metadata.steps.length > 0 && /* @__PURE__ */ React8.createElement(Box8, { paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React8.createElement(Text7, { dimColor: true, bold: true }, "\u{1F527} Agent Reasoning Trace (", message.metadata.steps.filter((s) => s.type === "action").length, " tools used,", " ", message.metadata.steps.length, " total steps)", message.metadata.tokenUsage && ` \u2022 ${message.metadata.tokenUsage.total} tokens`), /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, "Step types: ", message.metadata.steps.map((s) => s.type).join(", ")), message.metadata.steps.map((step, idx) => {
853
+ return /* @__PURE__ */ React9.createElement(Box9, { flexDirection: "column", gap: 1, paddingY: 1 }, messages.map((message, index) => /* @__PURE__ */ React9.createElement(Box9, { key: index, flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ React9.createElement(Box9, null, /* @__PURE__ */ React9.createElement(Text8, { bold: true, color: message.role === "user" ? "cyan" : "green" }, message.role === "user" ? "\u{1F464} You" : "\u{1F916} Assistant"), /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, " \u2022 ", new Date(message.timestamp).toLocaleTimeString())), /* @__PURE__ */ React9.createElement(Box9, { paddingLeft: 2 }, message.metadata?.permissionDenied ? /* @__PURE__ */ React9.createElement(Text8, { color: "yellow" }, "\u26A0\uFE0F ", stripThinkingTags(message.content)) : /* @__PURE__ */ React9.createElement(Text8, null, stripThinkingTags(message.content))), message.metadata?.steps && message.metadata.steps.length > 0 && /* @__PURE__ */ React9.createElement(Box9, { paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React9.createElement(Text8, { dimColor: true, bold: true }, "\u{1F527} Agent Reasoning Trace (", message.metadata.steps.filter((s) => s.type === "action").length, " tools used,", " ", message.metadata.steps.length, " total steps)", message.metadata.tokenUsage && ` \u2022 ${message.metadata.tokenUsage.total} tokens`), /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, "Step types: ", message.metadata.steps.map((s) => s.type).join(", ")), message.metadata.steps.map((step, idx) => {
447
854
  if (step.type === "thought") {
448
- return /* @__PURE__ */ React8.createElement(Box8, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React8.createElement(Text7, { color: "blue" }, "\u{1F4AD} Thought:"), /* @__PURE__ */ React8.createElement(
449
- Text7,
855
+ return /* @__PURE__ */ React9.createElement(Box9, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React9.createElement(Text8, { color: "blue" }, "\u{1F4AD} Thought:"), /* @__PURE__ */ React9.createElement(
856
+ Text8,
450
857
  {
451
858
  dimColor: true
452
859
  },
@@ -458,10 +865,10 @@ var MessageList = React8.memo(
458
865
  const toolInput = step.metadata?.toolInput;
459
866
  const observationStep = message.metadata.steps[idx + 1];
460
867
  const result = observationStep?.type === "observation" ? observationStep.content : null;
461
- return /* @__PURE__ */ React8.createElement(Box8, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React8.createElement(Text7, { color: "yellow" }, "\u{1F527} Action: ", toolName), toolInput && /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, ` Input: ${typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput).slice(0, 100)}`), result && /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, ` Result: ${typeof result === "string" ? result.slice(0, 200) : JSON.stringify(result).slice(0, 200)}${(typeof result === "string" ? result.length : JSON.stringify(result).length) > 200 ? "..." : ""}`));
868
+ return /* @__PURE__ */ React9.createElement(Box9, { key: idx, paddingLeft: 2, marginTop: 1, flexDirection: "column" }, /* @__PURE__ */ React9.createElement(Text8, { color: "yellow" }, "\u{1F527} Action: ", toolName), toolInput && /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, ` Input: ${typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput).slice(0, 100)}`), result && /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, ` Result: ${typeof result === "string" ? result.slice(0, 200) : JSON.stringify(result).slice(0, 200)}${(typeof result === "string" ? result.length : JSON.stringify(result).length) > 200 ? "..." : ""}`));
462
869
  }
463
870
  return null;
464
- }).filter(Boolean)), message.metadata?.tokenUsage && (!message.metadata.steps || message.metadata.steps.length === 0) && /* @__PURE__ */ React8.createElement(Box8, { paddingLeft: 2 }, /* @__PURE__ */ React8.createElement(Text7, { dimColor: true }, `${message.metadata.tokenUsage.total} tokens`)))));
871
+ }).filter(Boolean)), message.metadata?.tokenUsage && (!message.metadata.steps || message.metadata.steps.length === 0) && /* @__PURE__ */ React9.createElement(Box9, { paddingLeft: 2 }, /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, `${message.metadata.tokenUsage.total} tokens`)))));
465
872
  },
466
873
  (prevProps, nextProps) => {
467
874
  if (prevProps.messages.length !== nextProps.messages.length) {
@@ -472,8 +879,8 @@ var MessageList = React8.memo(
472
879
  );
473
880
 
474
881
  // src/components/LoginFlow.tsx
475
- import React9, { useState as useState2, useEffect as useEffect2 } from "react";
476
- import { Box as Box9, Text as Text8 } from "ink";
882
+ import React10, { useState as useState2, useEffect as useEffect2 } from "react";
883
+ import { Box as Box10, Text as Text9 } from "ink";
477
884
  import Spinner2 from "ink-spinner";
478
885
  import jwt from "jsonwebtoken";
479
886
  import open from "open";
@@ -583,7 +990,7 @@ var OAuthClient = class {
583
990
  * Sleep for specified milliseconds
584
991
  */
585
992
  sleep(ms) {
586
- return new Promise((resolve) => setTimeout(resolve, ms));
993
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
587
994
  }
588
995
  };
589
996
 
@@ -636,31 +1043,31 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
636
1043
  }
637
1044
  }, [deviceFlow, status]);
638
1045
  if (status === "initiating") {
639
- return /* @__PURE__ */ React9.createElement(Box9, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React9.createElement(Box9, null, /* @__PURE__ */ React9.createElement(Text8, { color: "cyan" }, /* @__PURE__ */ React9.createElement(Spinner2, { type: "dots" }), " Initiating device authorization...")));
1046
+ return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React10.createElement(Box10, null, /* @__PURE__ */ React10.createElement(Text9, { color: "cyan" }, /* @__PURE__ */ React10.createElement(Spinner2, { type: "dots" }), " Initiating device authorization...")));
640
1047
  }
641
1048
  if (status === "error") {
642
- return /* @__PURE__ */ React9.createElement(Box9, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1 }, /* @__PURE__ */ React9.createElement(Text8, { color: "red", bold: true }, "\u2716 Authentication Failed")), /* @__PURE__ */ React9.createElement(Box9, null, /* @__PURE__ */ React9.createElement(Text8, { color: "red" }, error)));
1049
+ return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1 }, /* @__PURE__ */ React10.createElement(Text9, { color: "red", bold: true }, "\u2716 Authentication Failed")), /* @__PURE__ */ React10.createElement(Box10, null, /* @__PURE__ */ React10.createElement(Text9, { color: "red" }, error)));
643
1050
  }
644
1051
  if (status === "success") {
645
- return /* @__PURE__ */ React9.createElement(Box9, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1 }, /* @__PURE__ */ React9.createElement(Text8, { color: "green", bold: true }, "\u2714 Successfully authenticated!")), /* @__PURE__ */ React9.createElement(Box9, null, /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, "You can now use B4M CLI with your account.")));
1052
+ return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1 }, /* @__PURE__ */ React10.createElement(Text9, { color: "green", bold: true }, "\u2714 Successfully authenticated!")), /* @__PURE__ */ React10.createElement(Box10, null, /* @__PURE__ */ React10.createElement(Text9, { dimColor: true }, "You can now use B4M CLI with your account.")));
646
1053
  }
647
- return /* @__PURE__ */ React9.createElement(Box9, { flexDirection: "column", padding: 1, borderStyle: "round", borderColor: "cyan" }, /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1 }, /* @__PURE__ */ React9.createElement(Text8, { color: "cyan", bold: true }, "\u{1F510} Device Authorization")), /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1 }, /* @__PURE__ */ React9.createElement(Text8, null, "Opening browser automatically... If it doesn't open, please visit:")), /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1, paddingLeft: 2 }, /* @__PURE__ */ React9.createElement(Text8, { color: "blue", bold: true }, deviceFlow?.verification_uri)), /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1 }, /* @__PURE__ */ React9.createElement(Text8, null, "And enter this code when prompted:")), /* @__PURE__ */ React9.createElement(Box9, { marginBottom: 1, paddingLeft: 2 }, /* @__PURE__ */ React9.createElement(Text8, { color: "yellow", bold: true }, deviceFlow?.user_code)), /* @__PURE__ */ React9.createElement(Box9, { marginTop: 1 }, /* @__PURE__ */ React9.createElement(Text8, { color: "cyan" }, /* @__PURE__ */ React9.createElement(Spinner2, { type: "dots" }), " ", statusMessage)), /* @__PURE__ */ React9.createElement(Box9, { marginTop: 1 }, /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, "Expires in ", deviceFlow ? Math.floor(deviceFlow.expires_in / 60) : 0, " minutes")));
1054
+ return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1, borderStyle: "round", borderColor: "cyan" }, /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1 }, /* @__PURE__ */ React10.createElement(Text9, { color: "cyan", bold: true }, "\u{1F510} Device Authorization")), /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1 }, /* @__PURE__ */ React10.createElement(Text9, null, "Opening browser automatically... If it doesn't open, please visit:")), /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1, paddingLeft: 2 }, /* @__PURE__ */ React10.createElement(Text9, { color: "blue", bold: true }, deviceFlow?.verification_uri)), /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1 }, /* @__PURE__ */ React10.createElement(Text9, null, "And enter this code when prompted:")), /* @__PURE__ */ React10.createElement(Box10, { marginBottom: 1, paddingLeft: 2 }, /* @__PURE__ */ React10.createElement(Text9, { color: "yellow", bold: true }, deviceFlow?.user_code)), /* @__PURE__ */ React10.createElement(Box10, { marginTop: 1 }, /* @__PURE__ */ React10.createElement(Text9, { color: "cyan" }, /* @__PURE__ */ React10.createElement(Spinner2, { type: "dots" }), " ", statusMessage)), /* @__PURE__ */ React10.createElement(Box10, { marginTop: 1 }, /* @__PURE__ */ React10.createElement(Text9, { dimColor: true }, "Expires in ", deviceFlow ? Math.floor(deviceFlow.expires_in / 60) : 0, " minutes")));
648
1055
  }
649
1056
 
650
1057
  // src/storage/SessionStore.ts
651
- import { promises as fs } from "fs";
652
- import path from "path";
1058
+ import { promises as fs3 } from "fs";
1059
+ import path3 from "path";
653
1060
  import { homedir } from "os";
654
1061
  var SessionStore = class {
655
1062
  constructor(basePath) {
656
- this.basePath = basePath || path.join(homedir(), ".bike4mind", "sessions");
1063
+ this.basePath = basePath || path3.join(homedir(), ".bike4mind", "sessions");
657
1064
  }
658
1065
  /**
659
1066
  * Initialize storage directory
660
1067
  */
661
1068
  async init() {
662
1069
  try {
663
- await fs.mkdir(this.basePath, { recursive: true });
1070
+ await fs3.mkdir(this.basePath, { recursive: true });
664
1071
  } catch (error) {
665
1072
  console.error("Failed to initialize session storage:", error);
666
1073
  throw error;
@@ -671,9 +1078,9 @@ var SessionStore = class {
671
1078
  */
672
1079
  async save(session) {
673
1080
  await this.init();
674
- const filePath = path.join(this.basePath, `${session.id}.json`);
1081
+ const filePath = path3.join(this.basePath, `${session.id}.json`);
675
1082
  try {
676
- await fs.writeFile(filePath, JSON.stringify(session, null, 2), "utf-8");
1083
+ await fs3.writeFile(filePath, JSON.stringify(session, null, 2), "utf-8");
677
1084
  } catch (error) {
678
1085
  console.error("Failed to save session:", error);
679
1086
  throw error;
@@ -683,9 +1090,9 @@ var SessionStore = class {
683
1090
  * Load a session from disk by ID
684
1091
  */
685
1092
  async load(id) {
686
- const filePath = path.join(this.basePath, `${id}.json`);
1093
+ const filePath = path3.join(this.basePath, `${id}.json`);
687
1094
  try {
688
- const data = await fs.readFile(filePath, "utf-8");
1095
+ const data = await fs3.readFile(filePath, "utf-8");
689
1096
  return JSON.parse(data);
690
1097
  } catch (error) {
691
1098
  if (error.code === "ENOENT") {
@@ -709,12 +1116,12 @@ var SessionStore = class {
709
1116
  async list() {
710
1117
  await this.init();
711
1118
  try {
712
- const files = await fs.readdir(this.basePath);
1119
+ const files = await fs3.readdir(this.basePath);
713
1120
  const jsonFiles = files.filter((f) => f.endsWith(".json"));
714
1121
  const sessions = await Promise.all(
715
1122
  jsonFiles.map(async (file) => {
716
- const filePath = path.join(this.basePath, file);
717
- const data = await fs.readFile(filePath, "utf-8");
1123
+ const filePath = path3.join(this.basePath, file);
1124
+ const data = await fs3.readFile(filePath, "utf-8");
718
1125
  return JSON.parse(data);
719
1126
  })
720
1127
  );
@@ -728,9 +1135,9 @@ var SessionStore = class {
728
1135
  * Delete a session
729
1136
  */
730
1137
  async delete(id) {
731
- const filePath = path.join(this.basePath, `${id}.json`);
1138
+ const filePath = path3.join(this.basePath, `${id}.json`);
732
1139
  try {
733
- await fs.unlink(filePath);
1140
+ await fs3.unlink(filePath);
734
1141
  return true;
735
1142
  } catch (error) {
736
1143
  if (error.code === "ENOENT") {
@@ -766,8 +1173,8 @@ var SessionStore = class {
766
1173
  };
767
1174
 
768
1175
  // src/storage/ConfigStore.ts
769
- import { promises as fs2 } from "fs";
770
- import path2 from "path";
1176
+ import { promises as fs4 } from "fs";
1177
+ import path4 from "path";
771
1178
  import { homedir as homedir2 } from "os";
772
1179
  import { v4 as uuidv4 } from "uuid";
773
1180
  import { z } from "zod";
@@ -841,15 +1248,15 @@ var DEFAULT_CONFIG = {
841
1248
  var ConfigStore = class {
842
1249
  constructor(configPath) {
843
1250
  this.config = null;
844
- this.configPath = configPath || path2.join(homedir2(), ".bike4mind", "config.json");
1251
+ this.configPath = configPath || path4.join(homedir2(), ".bike4mind", "config.json");
845
1252
  }
846
1253
  /**
847
1254
  * Initialize config directory
848
1255
  */
849
1256
  async init() {
850
- const dir = path2.dirname(this.configPath);
1257
+ const dir = path4.dirname(this.configPath);
851
1258
  try {
852
- await fs2.mkdir(dir, { recursive: true });
1259
+ await fs4.mkdir(dir, { recursive: true });
853
1260
  } catch (error) {
854
1261
  console.error("Failed to initialize config directory:", error);
855
1262
  throw error;
@@ -864,15 +1271,15 @@ var ConfigStore = class {
864
1271
  }
865
1272
  try {
866
1273
  try {
867
- const stats = await fs2.stat(this.configPath);
1274
+ const stats = await fs4.stat(this.configPath);
868
1275
  const mode = stats.mode & 511;
869
1276
  if (mode !== 384) {
870
1277
  console.warn(`\u26A0\uFE0F Config file has insecure permissions (${mode.toString(8)}). Setting to 0600...`);
871
- await fs2.chmod(this.configPath, 384);
1278
+ await fs4.chmod(this.configPath, 384);
872
1279
  }
873
1280
  } catch (statError) {
874
1281
  }
875
- const data = await fs2.readFile(this.configPath, "utf-8");
1282
+ const data = await fs4.readFile(this.configPath, "utf-8");
876
1283
  const rawConfig = JSON.parse(data);
877
1284
  if (rawConfig.apiConfig && "environment" in rawConfig.apiConfig) {
878
1285
  const oldApiConfig = rawConfig.apiConfig;
@@ -945,8 +1352,8 @@ var ConfigStore = class {
945
1352
  throw new Error("No configuration to save");
946
1353
  }
947
1354
  try {
948
- await fs2.writeFile(this.configPath, JSON.stringify(this.config, null, 2), "utf-8");
949
- await fs2.chmod(this.configPath, 384);
1355
+ await fs4.writeFile(this.configPath, JSON.stringify(this.config, null, 2), "utf-8");
1356
+ await fs4.chmod(this.configPath, 384);
950
1357
  } catch (error) {
951
1358
  console.error("Failed to save config:", error);
952
1359
  throw error;
@@ -1093,22 +1500,22 @@ var ConfigStore = class {
1093
1500
  };
1094
1501
 
1095
1502
  // src/storage/CommandHistoryStore.ts
1096
- import { promises as fs3 } from "fs";
1097
- import path3 from "path";
1503
+ import { promises as fs5 } from "fs";
1504
+ import path5 from "path";
1098
1505
  import { homedir as homedir3 } from "os";
1099
1506
  var MAX_HISTORY_ENTRIES = 1e3;
1100
1507
  var CommandHistoryStore = class {
1101
1508
  constructor(historyPath) {
1102
1509
  this.history = null;
1103
- this.historyPath = historyPath || path3.join(homedir3(), ".bike4mind", "history.jsonl");
1510
+ this.historyPath = historyPath || path5.join(homedir3(), ".bike4mind", "history.jsonl");
1104
1511
  }
1105
1512
  /**
1106
1513
  * Initialize history directory
1107
1514
  */
1108
1515
  async init() {
1109
- const dir = path3.dirname(this.historyPath);
1516
+ const dir = path5.dirname(this.historyPath);
1110
1517
  try {
1111
- await fs3.mkdir(dir, { recursive: true });
1518
+ await fs5.mkdir(dir, { recursive: true });
1112
1519
  } catch (error) {
1113
1520
  console.error("Failed to initialize history directory:", error);
1114
1521
  throw error;
@@ -1123,7 +1530,7 @@ var CommandHistoryStore = class {
1123
1530
  return this.history;
1124
1531
  }
1125
1532
  try {
1126
- const data = await fs3.readFile(this.historyPath, "utf-8");
1533
+ const data = await fs5.readFile(this.historyPath, "utf-8");
1127
1534
  const lines = data.trim().split("\n").filter((line) => line.length > 0);
1128
1535
  const entries = lines.map((line) => {
1129
1536
  try {
@@ -1160,7 +1567,7 @@ var CommandHistoryStore = class {
1160
1567
  };
1161
1568
  await this.init();
1162
1569
  const line = JSON.stringify(entry) + "\n";
1163
- await fs3.appendFile(this.historyPath, line, "utf-8");
1570
+ await fs5.appendFile(this.historyPath, line, "utf-8");
1164
1571
  this.history = [command, ...this.history || []];
1165
1572
  if (this.history.length > MAX_HISTORY_ENTRIES) {
1166
1573
  await this.trim();
@@ -1183,7 +1590,7 @@ var CommandHistoryStore = class {
1183
1590
  };
1184
1591
  return JSON.stringify(entry);
1185
1592
  }).join("\n");
1186
- await fs3.writeFile(this.historyPath, lines + "\n", "utf-8");
1593
+ await fs5.writeFile(this.historyPath, lines + "\n", "utf-8");
1187
1594
  this.history = trimmedCommands;
1188
1595
  }
1189
1596
  /**
@@ -1191,7 +1598,7 @@ var CommandHistoryStore = class {
1191
1598
  */
1192
1599
  async clear() {
1193
1600
  try {
1194
- await fs3.unlink(this.historyPath);
1601
+ await fs5.unlink(this.historyPath);
1195
1602
  } catch (error) {
1196
1603
  if (error.code !== "ENOENT") {
1197
1604
  throw error;
@@ -1965,7 +2372,7 @@ import { GoogleGenerativeAI } from "@google/generative-ai";
1965
2372
  import OpenAI2 from "openai";
1966
2373
 
1967
2374
  // ../../b4m-core/packages/services/dist/src/importHistoryService/index.js
1968
- import fs4, { unlinkSync } from "fs";
2375
+ import fs6, { unlinkSync } from "fs";
1969
2376
  import yauzl from "yauzl";
1970
2377
  import axios3 from "axios";
1971
2378
 
@@ -2572,190 +2979,196 @@ var listFabFilesBySessionSchema = z90.object({
2572
2979
  sessionId: z90.string()
2573
2980
  });
2574
2981
 
2575
- // ../../b4m-core/packages/services/dist/src/fabFileService/createByUrl.js
2982
+ // ../../b4m-core/packages/services/dist/src/fabFileService/listByQuest.js
2576
2983
  import { z as z91 } from "zod";
2577
- var createFabFileByUrlSchema = z91.object({
2578
- url: z91.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,})).+/)
2984
+ var listFabFilesByQuestSchema = z91.object({
2985
+ questId: z91.string()
2579
2986
  });
2580
2987
 
2581
- // ../../b4m-core/packages/services/dist/src/fabFileService/search.js
2988
+ // ../../b4m-core/packages/services/dist/src/fabFileService/createByUrl.js
2582
2989
  import { z as z92 } from "zod";
2583
- var searchFabFilesSchema = z92.object({
2584
- search: z92.string().optional(),
2585
- filters: z92.object({
2586
- tags: z92.array(z92.string()).optional(),
2587
- type: z92.enum(["text", "pdf", "url", "image", "excel", "word", "json", "csv", "markdown", "code"]).optional(),
2588
- shared: z92.coerce.boolean().optional(),
2990
+ var createFabFileByUrlSchema = z92.object({
2991
+ 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,})).+/)
2992
+ });
2993
+
2994
+ // ../../b4m-core/packages/services/dist/src/fabFileService/search.js
2995
+ import { z as z93 } from "zod";
2996
+ var searchFabFilesSchema = z93.object({
2997
+ search: z93.string().optional(),
2998
+ filters: z93.object({
2999
+ tags: z93.array(z93.string()).optional(),
3000
+ type: z93.enum(["text", "pdf", "url", "image", "excel", "word", "json", "csv", "markdown", "code"]).optional(),
3001
+ shared: z93.coerce.boolean().optional(),
2589
3002
  // Indicates if the user is searching for shared files
2590
- curated: z92.coerce.boolean().optional(),
3003
+ curated: z93.coerce.boolean().optional(),
2591
3004
  // Indicates if the user is searching for curated notebook files
2592
- projectId: z92.string().optional(),
2593
- ids: z92.array(z92.string()).optional()
3005
+ projectId: z93.string().optional(),
3006
+ ids: z93.array(z93.string()).optional()
2594
3007
  // Add support for filtering by IDs
2595
3008
  }).optional(),
2596
- pagination: z92.object({
2597
- page: z92.coerce.number(),
2598
- limit: z92.coerce.number()
3009
+ pagination: z93.object({
3010
+ page: z93.coerce.number(),
3011
+ limit: z93.coerce.number()
2599
3012
  }).optional(),
2600
- order: z92.object({
2601
- by: z92.enum(["createdAt", "fileName", "fileSize"]),
2602
- direction: z92.enum(["asc", "desc"])
3013
+ order: z93.object({
3014
+ by: z93.enum(["createdAt", "fileName", "fileSize"]),
3015
+ direction: z93.enum(["asc", "desc"])
2603
3016
  }).optional(),
2604
- options: z92.object({
2605
- includeShared: z92.coerce.boolean().optional()
3017
+ options: z93.object({
3018
+ includeShared: z93.coerce.boolean().optional()
2606
3019
  }).optional()
2607
3020
  });
2608
3021
 
2609
3022
  // ../../b4m-core/packages/services/dist/src/fabFileService/addFavorite.js
2610
- import { z as z93 } from "zod";
2611
- var addFavoriteParametersSchema3 = z93.object({
2612
- fileId: z93.string()
3023
+ import { z as z94 } from "zod";
3024
+ var addFavoriteParametersSchema3 = z94.object({
3025
+ fileId: z94.string()
2613
3026
  });
2614
3027
 
2615
3028
  // ../../b4m-core/packages/services/dist/src/fabFileService/deleteFavorite.js
2616
- import { z as z94 } from "zod";
2617
- var deleteFavoriteParametersSchema4 = z94.object({
2618
- fileId: z94.string()
3029
+ import { z as z95 } from "zod";
3030
+ var deleteFavoriteParametersSchema4 = z95.object({
3031
+ fileId: z95.string()
2619
3032
  });
2620
3033
 
2621
3034
  // ../../b4m-core/packages/services/dist/src/fabFileService/toggleTags.js
2622
- import { z as z95 } from "zod";
2623
- var fabFileToggleTagsSchema = z95.object({
2624
- ids: z95.array(z95.string()),
2625
- tags: z95.array(z95.string())
3035
+ import { z as z96 } from "zod";
3036
+ var fabFileToggleTagsSchema = z96.object({
3037
+ ids: z96.array(z96.string()),
3038
+ tags: z96.array(z96.string())
2626
3039
  });
2627
3040
 
2628
3041
  // ../../b4m-core/packages/services/dist/src/fabFileService/edit.js
2629
- import { z as z96 } from "zod";
3042
+ import { z as z97 } from "zod";
2630
3043
  import { diffLines } from "diff";
2631
- var editFabFileSchema = z96.object({
2632
- id: z96.string(),
2633
- instruction: z96.string(),
2634
- selection: z96.object({
2635
- start: z96.number(),
2636
- end: z96.number()
3044
+ var editFabFileSchema = z97.object({
3045
+ id: z97.string(),
3046
+ instruction: z97.string(),
3047
+ selection: z97.object({
3048
+ start: z97.number(),
3049
+ end: z97.number()
2637
3050
  }).optional(),
2638
- preserveFormatting: z96.boolean().optional().default(true),
2639
- applyImmediately: z96.boolean().optional().default(false)
3051
+ preserveFormatting: z97.boolean().optional().default(true),
3052
+ applyImmediately: z97.boolean().optional().default(false)
2640
3053
  });
2641
3054
 
2642
3055
  // ../../b4m-core/packages/services/dist/src/fabFileService/applyEdit.js
2643
3056
  import mime2 from "mime-types";
2644
3057
  import { v4 as uuidv43 } from "uuid";
2645
- import { z as z97 } from "zod";
2646
- var applyEditSchema = z97.object({
2647
- id: z97.string(),
2648
- modifiedContent: z97.string(),
2649
- createBackup: z97.boolean().optional().default(true)
3058
+ import { z as z98 } from "zod";
3059
+ var applyEditSchema = z98.object({
3060
+ id: z98.string(),
3061
+ modifiedContent: z98.string(),
3062
+ createBackup: z98.boolean().optional().default(true)
2650
3063
  });
2651
3064
 
2652
3065
  // ../../b4m-core/packages/services/dist/src/friendshipService/respondToFriendRequest.js
2653
- import { z as z98 } from "zod";
2654
- var respondToFriendRequestSchema = z98.object({
2655
- id: z98.string(),
3066
+ import { z as z99 } from "zod";
3067
+ var respondToFriendRequestSchema = z99.object({
3068
+ id: z99.string(),
2656
3069
  /** The user ID of the recipient of the friend request */
2657
- userId: z98.string(),
2658
- accept: z98.boolean()
3070
+ userId: z99.string(),
3071
+ accept: z99.boolean()
2659
3072
  });
2660
3073
 
2661
3074
  // ../../b4m-core/packages/services/dist/src/friendshipService/unfriend.js
2662
- import { z as z99 } from "zod";
2663
- var unfriendSchema = z99.object({
2664
- friendshipId: z99.string(),
3075
+ import { z as z100 } from "zod";
3076
+ var unfriendSchema = z100.object({
3077
+ friendshipId: z100.string(),
2665
3078
  /** The user ID of the user who wants to unfriend the other user */
2666
- userId: z99.string()
3079
+ userId: z100.string()
2667
3080
  });
2668
3081
 
2669
3082
  // ../../b4m-core/packages/services/dist/src/friendshipService/list.js
2670
- import { z as z100 } from "zod";
2671
- var listFriendsSchema = z100.object({
2672
- userId: z100.string()
3083
+ import { z as z101 } from "zod";
3084
+ var listFriendsSchema = z101.object({
3085
+ userId: z101.string()
2673
3086
  });
2674
- var listPendingFriendRequestsSchema = z100.object({
2675
- userId: z100.string()
3087
+ var listPendingFriendRequestsSchema = z101.object({
3088
+ userId: z101.string()
2676
3089
  });
2677
3090
 
2678
3091
  // ../../b4m-core/packages/services/dist/src/adminService/loginAs.js
2679
- import { z as z101 } from "zod";
2680
- var loginAsSchema = z101.object({
2681
- targetUserId: z101.string()
3092
+ import { z as z102 } from "zod";
3093
+ var loginAsSchema = z102.object({
3094
+ targetUserId: z102.string()
2682
3095
  });
2683
3096
 
2684
3097
  // ../../b4m-core/packages/services/dist/src/cacheService/get.js
2685
- import { z as z102 } from "zod";
2686
- var getParamsSchema = z102.object({
2687
- key: z102.string()
3098
+ import { z as z103 } from "zod";
3099
+ var getParamsSchema = z103.object({
3100
+ key: z103.string()
2688
3101
  });
2689
3102
 
2690
3103
  // ../../b4m-core/packages/services/dist/src/cacheService/set.js
2691
- import { z as z103 } from "zod";
2692
- var setParamsSchema = z103.object({
2693
- key: z103.string(),
2694
- value: z103.any(),
3104
+ import { z as z104 } from "zod";
3105
+ var setParamsSchema = z104.object({
3106
+ key: z104.string(),
3107
+ value: z104.any(),
2695
3108
  /**
2696
3109
  * Time to live in milliseconds
2697
3110
  */
2698
- ttl: z103.number(),
2699
- recache: z103.boolean().optional()
3111
+ ttl: z104.number(),
3112
+ recache: z104.boolean().optional()
2700
3113
  });
2701
3114
 
2702
3115
  // ../../b4m-core/packages/services/dist/src/cacheService/ttl.js
2703
- import { z as z104 } from "zod";
2704
- var ttlParamsSchema = z104.object({
2705
- key: z104.string()
3116
+ import { z as z105 } from "zod";
3117
+ var ttlParamsSchema = z105.object({
3118
+ key: z105.string()
2706
3119
  });
2707
3120
 
2708
3121
  // ../../b4m-core/packages/services/dist/src/cacheService/weeklyReports.js
2709
- import { z as z105 } from "zod";
3122
+ import { z as z106 } from "zod";
2710
3123
  import dayjs3 from "dayjs";
2711
- var weeklyReportSchema = z105.object({
2712
- startDate: z105.string(),
2713
- endDate: z105.string(),
2714
- report: z105.string(),
2715
- aiInsights: z105.string().nullable()
3124
+ var weeklyReportSchema = z106.object({
3125
+ startDate: z106.string(),
3126
+ endDate: z106.string(),
3127
+ report: z106.string(),
3128
+ aiInsights: z106.string().nullable()
2716
3129
  });
2717
3130
 
2718
3131
  // ../../b4m-core/packages/services/dist/src/embeddingCacheService/generateCacheKey.js
2719
3132
  import crypto2 from "crypto";
2720
3133
 
2721
3134
  // ../../b4m-core/packages/services/dist/src/researchAgentService/create.js
2722
- import { z as z106 } from "zod";
2723
- var researchAgentCreateSchema = z106.object({
2724
- name: z106.string().min(1),
2725
- description: z106.string().min(1)
2726
- });
2727
-
2728
- // ../../b4m-core/packages/services/dist/src/researchAgentService/update.js
2729
3135
  import { z as z107 } from "zod";
2730
- var researchAgentUpdateSchema = z107.object({
2731
- id: z107.string(),
3136
+ var researchAgentCreateSchema = z107.object({
2732
3137
  name: z107.string().min(1),
2733
3138
  description: z107.string().min(1)
2734
3139
  });
2735
3140
 
2736
- // ../../b4m-core/packages/services/dist/src/researchAgentService/remove.js
3141
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/update.js
2737
3142
  import { z as z108 } from "zod";
2738
- var researchAgentRemoveSchema = z108.object({
2739
- id: z108.string()
3143
+ var researchAgentUpdateSchema = z108.object({
3144
+ id: z108.string(),
3145
+ name: z108.string().min(1),
3146
+ description: z108.string().min(1)
2740
3147
  });
2741
3148
 
2742
- // ../../b4m-core/packages/services/dist/src/researchAgentService/get.js
3149
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/remove.js
2743
3150
  import { z as z109 } from "zod";
2744
- var researchAgentGetSchema = z109.object({
3151
+ var researchAgentRemoveSchema = z109.object({
2745
3152
  id: z109.string()
2746
3153
  });
2747
3154
 
2748
- // ../../b4m-core/packages/services/dist/src/researchAgentService/listFiles.js
3155
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/get.js
2749
3156
  import { z as z110 } from "zod";
2750
- var researchAgentListFilesSchema = z110.object({
3157
+ var researchAgentGetSchema = z110.object({
3158
+ id: z110.string()
3159
+ });
3160
+
3161
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/listFiles.js
3162
+ import { z as z111 } from "zod";
3163
+ var researchAgentListFilesSchema = z111.object({
2751
3164
  /**
2752
3165
  * The ID of the research agent
2753
3166
  */
2754
- id: z110.string()
3167
+ id: z111.string()
2755
3168
  });
2756
3169
 
2757
3170
  // ../../b4m-core/packages/services/dist/src/researchTaskService/process.js
2758
- import { z as z111 } from "zod";
3171
+ import { z as z112 } from "zod";
2759
3172
 
2760
3173
  // ../../b4m-core/packages/services/dist/src/lib/turndown.js
2761
3174
  import turndown from "turndown";
@@ -3146,316 +3559,316 @@ var deepResearchTool = {
3146
3559
  };
3147
3560
 
3148
3561
  // ../../b4m-core/packages/services/dist/src/researchTaskService/process.js
3149
- var ResearchTaskProcessSchema = z111.object({
3150
- id: z111.string()
3562
+ var ResearchTaskProcessSchema = z112.object({
3563
+ id: z112.string()
3151
3564
  });
3152
3565
 
3153
3566
  // ../../b4m-core/packages/services/dist/src/researchTaskService/create.js
3154
- import { z as z112 } from "zod";
3155
- var researchTaskCreateSchema = z112.object({
3156
- researchAgentId: z112.string(),
3157
- title: z112.string().max(100),
3158
- description: z112.string().max(500),
3159
- prompt: z112.string().max(500).optional(),
3160
- type: z112.nativeEnum(ResearchTaskType),
3161
- executionType: z112.nativeEnum(ResearchTaskExecutionType).default(ResearchTaskExecutionType.ON_DEMAND),
3162
- fileTagId: z112.string().optional(),
3163
- autoGeneratedTag: z112.object({
3164
- name: z112.string(),
3165
- icon: z112.string(),
3166
- color: z112.string()
3567
+ import { z as z113 } from "zod";
3568
+ var researchTaskCreateSchema = z113.object({
3569
+ researchAgentId: z113.string(),
3570
+ title: z113.string().max(100),
3571
+ description: z113.string().max(500),
3572
+ prompt: z113.string().max(500).optional(),
3573
+ type: z113.nativeEnum(ResearchTaskType),
3574
+ executionType: z113.nativeEnum(ResearchTaskExecutionType).default(ResearchTaskExecutionType.ON_DEMAND),
3575
+ fileTagId: z113.string().optional(),
3576
+ autoGeneratedTag: z113.object({
3577
+ name: z113.string(),
3578
+ icon: z113.string(),
3579
+ color: z113.string()
3167
3580
  }).optional()
3168
3581
  });
3169
3582
  var researchTaskScrapeCreateSchema = researchTaskCreateSchema.extend({
3170
- urls: z112.array(z112.string().url()).min(1),
3171
- canDiscoverLinks: z112.boolean()
3583
+ urls: z113.array(z113.string().url()).min(1),
3584
+ canDiscoverLinks: z113.boolean()
3172
3585
  });
3173
3586
  var researchTaskPeriodicCreateSchema = researchTaskCreateSchema.extend({
3174
- executionPeriodicStartAt: z112.coerce.date(),
3175
- executionPeriodicEndAt: z112.coerce.date(),
3176
- executionPeriodicFrequency: z112.nativeEnum(ResearchTaskPeriodicFrequencyType)
3587
+ executionPeriodicStartAt: z113.coerce.date(),
3588
+ executionPeriodicEndAt: z113.coerce.date(),
3589
+ executionPeriodicFrequency: z113.nativeEnum(ResearchTaskPeriodicFrequencyType)
3177
3590
  });
3178
3591
  var researchTaskScheduledCreateSchema = researchTaskCreateSchema.extend({
3179
- executionScheduledAt: z112.coerce.date()
3592
+ executionScheduledAt: z113.coerce.date()
3180
3593
  });
3181
3594
  var researchTaskDeepResearchCreateSchema = researchTaskCreateSchema.extend({
3182
- maxDepth: z112.number().min(1).max(10).optional()
3595
+ maxDepth: z113.number().min(1).max(10).optional()
3183
3596
  });
3184
3597
 
3185
3598
  // ../../b4m-core/packages/services/dist/src/researchTaskService/search.js
3186
- import { z as z113 } from "zod";
3187
- var searchResearchTasksSchema = z113.object({
3188
- search: z113.string().optional(),
3599
+ import { z as z114 } from "zod";
3600
+ var searchResearchTasksSchema = z114.object({
3601
+ search: z114.string().optional(),
3189
3602
  // ADD FILTERS SCHEMA HERE
3190
3603
  // filters: z
3191
3604
  // .object({
3192
3605
  // userId: z.string().optional(),
3193
3606
  // })
3194
3607
  // .optional(),
3195
- pagination: z113.object({
3196
- page: z113.coerce.number().optional(),
3197
- limit: z113.coerce.number().optional()
3608
+ pagination: z114.object({
3609
+ page: z114.coerce.number().optional(),
3610
+ limit: z114.coerce.number().optional()
3198
3611
  }).optional(),
3199
- orderBy: z113.object({
3200
- by: z113.enum(["createdAt", "updatedAt"]).optional(),
3201
- direction: z113.enum(["asc", "desc"]).optional()
3612
+ orderBy: z114.object({
3613
+ by: z114.enum(["createdAt", "updatedAt"]).optional(),
3614
+ direction: z114.enum(["asc", "desc"]).optional()
3202
3615
  }).optional()
3203
3616
  });
3204
3617
 
3205
3618
  // ../../b4m-core/packages/services/dist/src/researchTaskService/get.js
3206
- import { z as z114 } from "zod";
3207
- var getResearchTaskSchema = z114.object({
3208
- id: z114.string().min(1)
3619
+ import { z as z115 } from "zod";
3620
+ var getResearchTaskSchema = z115.object({
3621
+ id: z115.string().min(1)
3209
3622
  });
3210
3623
 
3211
3624
  // ../../b4m-core/packages/services/dist/src/researchTaskService/update.js
3212
- import { z as z115 } from "zod";
3213
- var updateResearchTaskSchema = z115.object({
3214
- id: z115.string(),
3215
- title: z115.string(),
3216
- description: z115.string(),
3217
- type: z115.nativeEnum(ResearchTaskType)
3625
+ import { z as z116 } from "zod";
3626
+ var updateResearchTaskSchema = z116.object({
3627
+ id: z116.string(),
3628
+ title: z116.string(),
3629
+ description: z116.string(),
3630
+ type: z116.nativeEnum(ResearchTaskType)
3218
3631
  });
3219
3632
  var researchTaskScrapeUpdateSchema = updateResearchTaskSchema.extend({
3220
- urls: z115.array(z115.string().url()).min(1),
3221
- canDiscoverLinks: z115.boolean()
3633
+ urls: z116.array(z116.string().url()).min(1),
3634
+ canDiscoverLinks: z116.boolean()
3222
3635
  });
3223
3636
 
3224
3637
  // ../../b4m-core/packages/services/dist/src/researchTaskService/listByAgentId.js
3225
- import { z as z116 } from "zod";
3226
- var listByAgentIdSchema = z116.object({
3227
- researchAgentId: z116.string()
3638
+ import { z as z117 } from "zod";
3639
+ var listByAgentIdSchema = z117.object({
3640
+ researchAgentId: z117.string()
3228
3641
  });
3229
3642
 
3230
3643
  // ../../b4m-core/packages/services/dist/src/researchTaskService/remove.js
3231
- import { z as z117 } from "zod";
3232
- var researchTaskRemoveSchema = z117.object({
3233
- id: z117.string().min(1)
3644
+ import { z as z118 } from "zod";
3645
+ var researchTaskRemoveSchema = z118.object({
3646
+ id: z118.string().min(1)
3234
3647
  });
3235
3648
 
3236
3649
  // ../../b4m-core/packages/services/dist/src/researchTaskService/retry.js
3237
- import { z as z118 } from "zod";
3238
- var researchTaskRetrySchema = z118.object({
3239
- id: z118.string(),
3240
- userId: z118.string()
3650
+ import { z as z119 } from "zod";
3651
+ var researchTaskRetrySchema = z119.object({
3652
+ id: z119.string(),
3653
+ userId: z119.string()
3241
3654
  });
3242
3655
 
3243
3656
  // ../../b4m-core/packages/services/dist/src/researchTaskService/processDiscoveredLinks.js
3244
3657
  import axios4 from "axios";
3245
- import { z as z119 } from "zod";
3658
+ import { z as z120 } from "zod";
3246
3659
  import plimit from "p-limit";
3247
3660
  import pLimit2 from "p-limit";
3248
- var researchTaskProcessDiscoveredLinksSchema = z119.object({
3249
- id: z119.string()
3661
+ var researchTaskProcessDiscoveredLinksSchema = z120.object({
3662
+ id: z120.string()
3250
3663
  });
3251
3664
 
3252
3665
  // ../../b4m-core/packages/services/dist/src/researchTaskService/downloadRelevantLinks.js
3253
- import { z as z120 } from "zod";
3666
+ import { z as z121 } from "zod";
3254
3667
  import plimit2 from "p-limit";
3255
3668
  import axios5 from "axios";
3256
3669
  import { fileTypeFromBuffer } from "file-type";
3257
- var researchTaskDownloadRelevantLinksSchema = z120.object({
3258
- id: z120.string()
3670
+ var researchTaskDownloadRelevantLinksSchema = z121.object({
3671
+ id: z121.string()
3259
3672
  });
3260
3673
 
3261
3674
  // ../../b4m-core/packages/services/dist/src/researchData/remove.js
3262
- import { z as z121 } from "zod";
3263
- var researchDataRemoveSchema = z121.object({
3264
- id: z121.string(),
3265
- researchAgentId: z121.string()
3675
+ import { z as z122 } from "zod";
3676
+ var researchDataRemoveSchema = z122.object({
3677
+ id: z122.string(),
3678
+ researchAgentId: z122.string()
3266
3679
  });
3267
3680
 
3268
3681
  // ../../b4m-core/packages/services/dist/src/taskSchedulerService/create.js
3269
- import { z as z122 } from "zod";
3270
- var researchTaskPayload = z122.object({
3271
- id: z122.string(),
3272
- userId: z122.string()
3682
+ import { z as z123 } from "zod";
3683
+ var researchTaskPayload = z123.object({
3684
+ id: z123.string(),
3685
+ userId: z123.string()
3273
3686
  });
3274
- var customTaskPayload = z122.object({
3275
- test: z122.string()
3687
+ var customTaskPayload = z123.object({
3688
+ test: z123.string()
3276
3689
  });
3277
- var taskSchedulerCreate = z122.discriminatedUnion("handler", [
3278
- z122.object({
3279
- handler: z122.literal(TaskScheduleHandler.RESEARCH_TASK_PROCESS),
3690
+ var taskSchedulerCreate = z123.discriminatedUnion("handler", [
3691
+ z123.object({
3692
+ handler: z123.literal(TaskScheduleHandler.RESEARCH_TASK_PROCESS),
3280
3693
  payload: researchTaskPayload,
3281
- processDate: z122.date()
3694
+ processDate: z123.date()
3282
3695
  }),
3283
- z122.object({
3284
- handler: z122.literal(TaskScheduleHandler.CUSTOM_TASK_PROCESS),
3696
+ z123.object({
3697
+ handler: z123.literal(TaskScheduleHandler.CUSTOM_TASK_PROCESS),
3285
3698
  payload: customTaskPayload,
3286
- processDate: z122.date()
3699
+ processDate: z123.date()
3287
3700
  })
3288
3701
  ]);
3289
3702
 
3290
3703
  // ../../b4m-core/packages/services/dist/src/tagService/createFileTag.js
3291
- import { z as z123 } from "zod";
3292
- var tagCreateFileTagSchema = z123.object({
3293
- name: z123.string(),
3294
- icon: z123.string().optional(),
3295
- color: z123.string().optional(),
3296
- description: z123.string().optional()
3297
- });
3298
-
3299
- // ../../b4m-core/packages/services/dist/src/tagService/create.js
3300
3704
  import { z as z124 } from "zod";
3301
- var tagCreateSchema = z124.object({
3705
+ var tagCreateFileTagSchema = z124.object({
3302
3706
  name: z124.string(),
3303
3707
  icon: z124.string().optional(),
3304
- description: z124.string().optional(),
3305
3708
  color: z124.string().optional(),
3306
- type: z124.nativeEnum(TagType)
3709
+ description: z124.string().optional()
3307
3710
  });
3308
3711
 
3309
- // ../../b4m-core/packages/services/dist/src/tagService/update.js
3712
+ // ../../b4m-core/packages/services/dist/src/tagService/create.js
3310
3713
  import { z as z125 } from "zod";
3311
- var tagUpdateSchema = z125.object({
3312
- id: z125.string(),
3313
- name: z125.string().optional(),
3714
+ var tagCreateSchema = z125.object({
3715
+ name: z125.string(),
3314
3716
  icon: z125.string().optional(),
3315
3717
  description: z125.string().optional(),
3316
- color: z125.string().optional()
3718
+ color: z125.string().optional(),
3719
+ type: z125.nativeEnum(TagType)
3317
3720
  });
3318
3721
 
3319
- // ../../b4m-core/packages/services/dist/src/tagService/remove.js
3722
+ // ../../b4m-core/packages/services/dist/src/tagService/update.js
3320
3723
  import { z as z126 } from "zod";
3321
- var tagRemoveSchema = z126.object({
3322
- id: z126.string()
3724
+ var tagUpdateSchema = z126.object({
3725
+ id: z126.string(),
3726
+ name: z126.string().optional(),
3727
+ icon: z126.string().optional(),
3728
+ description: z126.string().optional(),
3729
+ color: z126.string().optional()
3323
3730
  });
3324
3731
 
3325
- // ../../b4m-core/packages/services/dist/src/artifactService/create.js
3732
+ // ../../b4m-core/packages/services/dist/src/tagService/remove.js
3326
3733
  import { z as z127 } from "zod";
3327
- var createArtifactSchema = z127.object({
3328
- id: z127.string().optional(),
3734
+ var tagRemoveSchema = z127.object({
3735
+ id: z127.string()
3736
+ });
3737
+
3738
+ // ../../b4m-core/packages/services/dist/src/artifactService/create.js
3739
+ import { z as z128 } from "zod";
3740
+ var createArtifactSchema = z128.object({
3741
+ id: z128.string().optional(),
3329
3742
  // Allow custom ID for AI-generated artifacts
3330
- type: z127.enum(["mermaid", "recharts", "python", "react", "html", "svg", "code", "quest", "file", "questmaster"]),
3331
- title: z127.string().min(1).max(255),
3332
- description: z127.string().max(1e3).optional(),
3333
- content: z127.string().min(1),
3334
- projectId: z127.string().optional(),
3335
- organizationId: z127.string().optional(),
3336
- visibility: z127.enum(["private", "project", "organization", "public"]).default("private"),
3337
- tags: z127.array(z127.string().max(50)).max(20).default([]),
3338
- versionTag: z127.string().max(100).optional(),
3339
- sourceQuestId: z127.string().optional(),
3340
- sessionId: z127.string().optional(),
3341
- parentArtifactId: z127.string().optional(),
3342
- permissions: z127.object({
3343
- canRead: z127.array(z127.string()).default([]),
3344
- canWrite: z127.array(z127.string()).default([]),
3345
- canDelete: z127.array(z127.string()).default([]),
3346
- isPublic: z127.boolean().default(false),
3347
- inheritFromProject: z127.boolean().default(true)
3743
+ type: z128.enum(["mermaid", "recharts", "python", "react", "html", "svg", "code", "quest", "file", "questmaster"]),
3744
+ title: z128.string().min(1).max(255),
3745
+ description: z128.string().max(1e3).optional(),
3746
+ content: z128.string().min(1),
3747
+ projectId: z128.string().optional(),
3748
+ organizationId: z128.string().optional(),
3749
+ visibility: z128.enum(["private", "project", "organization", "public"]).default("private"),
3750
+ tags: z128.array(z128.string().max(50)).max(20).default([]),
3751
+ versionTag: z128.string().max(100).optional(),
3752
+ sourceQuestId: z128.string().optional(),
3753
+ sessionId: z128.string().optional(),
3754
+ parentArtifactId: z128.string().optional(),
3755
+ permissions: z128.object({
3756
+ canRead: z128.array(z128.string()).default([]),
3757
+ canWrite: z128.array(z128.string()).default([]),
3758
+ canDelete: z128.array(z128.string()).default([]),
3759
+ isPublic: z128.boolean().default(false),
3760
+ inheritFromProject: z128.boolean().default(true)
3348
3761
  }).optional(),
3349
- metadata: z127.record(z127.unknown()).default({})
3762
+ metadata: z128.record(z128.unknown()).default({})
3350
3763
  });
3351
3764
 
3352
3765
  // ../../b4m-core/packages/services/dist/src/artifactService/get.js
3353
- import { z as z128 } from "zod";
3354
- var getArtifactSchema = z128.object({
3355
- id: z128.string(),
3356
- includeContent: z128.boolean().default(false),
3357
- includeVersions: z128.boolean().default(false),
3358
- version: z128.number().optional()
3766
+ import { z as z129 } from "zod";
3767
+ var getArtifactSchema = z129.object({
3768
+ id: z129.string(),
3769
+ includeContent: z129.boolean().default(false),
3770
+ includeVersions: z129.boolean().default(false),
3771
+ version: z129.number().optional()
3359
3772
  });
3360
3773
 
3361
3774
  // ../../b4m-core/packages/services/dist/src/artifactService/list.js
3362
- import { z as z129 } from "zod";
3363
- var listArtifactsSchema = z129.object({
3364
- type: z129.string().optional(),
3365
- status: z129.enum(["draft", "review", "published", "archived"]).optional(),
3366
- visibility: z129.enum(["private", "project", "organization", "public"]).optional(),
3367
- projectId: z129.string().optional(),
3368
- sessionId: z129.string().optional(),
3369
- tags: z129.array(z129.string()).optional(),
3370
- search: z129.string().optional(),
3371
- limit: z129.number().min(1).max(100).default(20),
3372
- offset: z129.number().min(0).default(0),
3373
- sortBy: z129.enum(["createdAt", "updatedAt", "title", "type"]).default("updatedAt"),
3374
- sortOrder: z129.enum(["asc", "desc"]).default("desc"),
3375
- includeDeleted: z129.boolean().default(false)
3775
+ import { z as z130 } from "zod";
3776
+ var listArtifactsSchema = z130.object({
3777
+ type: z130.string().optional(),
3778
+ status: z130.enum(["draft", "review", "published", "archived"]).optional(),
3779
+ visibility: z130.enum(["private", "project", "organization", "public"]).optional(),
3780
+ projectId: z130.string().optional(),
3781
+ sessionId: z130.string().optional(),
3782
+ tags: z130.array(z130.string()).optional(),
3783
+ search: z130.string().optional(),
3784
+ limit: z130.number().min(1).max(100).default(20),
3785
+ offset: z130.number().min(0).default(0),
3786
+ sortBy: z130.enum(["createdAt", "updatedAt", "title", "type"]).default("updatedAt"),
3787
+ sortOrder: z130.enum(["asc", "desc"]).default("desc"),
3788
+ includeDeleted: z130.boolean().default(false)
3376
3789
  });
3377
3790
 
3378
3791
  // ../../b4m-core/packages/services/dist/src/artifactService/update.js
3379
- import { z as z130 } from "zod";
3380
- var updateArtifactSchema = z130.object({
3381
- id: z130.string(),
3382
- title: z130.string().min(1).max(255).optional(),
3383
- description: z130.string().max(1e3).optional(),
3384
- content: z130.string().optional(),
3385
- visibility: z130.enum(["private", "project", "organization", "public"]).optional(),
3386
- status: z130.enum(["draft", "review", "published", "archived"]).optional(),
3387
- tags: z130.array(z130.string().max(50)).max(20).optional(),
3388
- versionTag: z130.string().max(100).optional(),
3389
- permissions: z130.object({
3390
- canRead: z130.array(z130.string()).optional(),
3391
- canWrite: z130.array(z130.string()).optional(),
3392
- canDelete: z130.array(z130.string()).optional(),
3393
- isPublic: z130.boolean().optional(),
3394
- inheritFromProject: z130.boolean().optional()
3792
+ import { z as z131 } from "zod";
3793
+ var updateArtifactSchema = z131.object({
3794
+ id: z131.string(),
3795
+ title: z131.string().min(1).max(255).optional(),
3796
+ description: z131.string().max(1e3).optional(),
3797
+ content: z131.string().optional(),
3798
+ visibility: z131.enum(["private", "project", "organization", "public"]).optional(),
3799
+ status: z131.enum(["draft", "review", "published", "archived"]).optional(),
3800
+ tags: z131.array(z131.string().max(50)).max(20).optional(),
3801
+ versionTag: z131.string().max(100).optional(),
3802
+ permissions: z131.object({
3803
+ canRead: z131.array(z131.string()).optional(),
3804
+ canWrite: z131.array(z131.string()).optional(),
3805
+ canDelete: z131.array(z131.string()).optional(),
3806
+ isPublic: z131.boolean().optional(),
3807
+ inheritFromProject: z131.boolean().optional()
3395
3808
  }).optional(),
3396
- metadata: z130.record(z130.unknown()).optional(),
3397
- changes: z130.array(z130.string()).optional(),
3398
- changeDescription: z130.string().max(1e3).optional(),
3399
- createNewVersion: z130.boolean().optional(),
3400
- versionMessage: z130.string().max(500).optional()
3809
+ metadata: z131.record(z131.unknown()).optional(),
3810
+ changes: z131.array(z131.string()).optional(),
3811
+ changeDescription: z131.string().max(1e3).optional(),
3812
+ createNewVersion: z131.boolean().optional(),
3813
+ versionMessage: z131.string().max(500).optional()
3401
3814
  });
3402
3815
 
3403
3816
  // ../../b4m-core/packages/services/dist/src/artifactService/delete.js
3404
- import { z as z131 } from "zod";
3405
- var deleteArtifactSchema = z131.object({
3406
- id: z131.string(),
3407
- hardDelete: z131.boolean().default(false)
3817
+ import { z as z132 } from "zod";
3818
+ var deleteArtifactSchema = z132.object({
3819
+ id: z132.string(),
3820
+ hardDelete: z132.boolean().default(false)
3408
3821
  // For future implementation
3409
3822
  });
3410
3823
 
3411
3824
  // ../../b4m-core/packages/services/dist/src/questMasterService/create.js
3412
- import { z as z132 } from "zod";
3413
- var questSchema = z132.object({
3414
- id: z132.string(),
3415
- title: z132.string().min(1).max(255),
3416
- description: z132.string().max(1e3),
3417
- status: z132.enum(["not_started", "in_progress", "completed", "blocked"]).default("not_started"),
3418
- order: z132.number().min(0),
3419
- dependencies: z132.array(z132.string()).default([]),
3420
- estimatedTime: z132.string().optional()
3421
- });
3422
- var questResourceSchema = z132.object({
3423
- title: z132.string().min(1).max(255),
3424
- url: z132.string().url(),
3425
- type: z132.enum(["documentation", "tutorial", "reference", "example"])
3426
- });
3427
- var createQuestMasterSchema = z132.object({
3428
- title: z132.string().min(1).max(255),
3429
- description: z132.string().max(1e3).optional(),
3430
- goal: z132.string().min(1).max(1e3),
3431
- complexity: z132.enum(["beginner", "intermediate", "advanced", "expert"]),
3432
- estimatedTotalTime: z132.string().optional(),
3433
- prerequisites: z132.array(z132.string().max(200)).default([]),
3434
- quests: z132.array(questSchema).min(1),
3435
- resources: z132.array(questResourceSchema).default([]),
3436
- projectId: z132.string().optional(),
3437
- organizationId: z132.string().optional(),
3438
- visibility: z132.enum(["private", "project", "organization", "public"]).default("private"),
3439
- tags: z132.array(z132.string().max(50)).max(20).default([]),
3440
- permissions: z132.object({
3441
- canRead: z132.array(z132.string()).default([]),
3442
- canWrite: z132.array(z132.string()).default([]),
3443
- canDelete: z132.array(z132.string()).default([]),
3444
- isPublic: z132.boolean().default(false),
3445
- inheritFromProject: z132.boolean().default(true)
3825
+ import { z as z133 } from "zod";
3826
+ var questSchema = z133.object({
3827
+ id: z133.string(),
3828
+ title: z133.string().min(1).max(255),
3829
+ description: z133.string().max(1e3),
3830
+ status: z133.enum(["not_started", "in_progress", "completed", "blocked"]).default("not_started"),
3831
+ order: z133.number().min(0),
3832
+ dependencies: z133.array(z133.string()).default([]),
3833
+ estimatedTime: z133.string().optional()
3834
+ });
3835
+ var questResourceSchema = z133.object({
3836
+ title: z133.string().min(1).max(255),
3837
+ url: z133.string().url(),
3838
+ type: z133.enum(["documentation", "tutorial", "reference", "example"])
3839
+ });
3840
+ var createQuestMasterSchema = z133.object({
3841
+ title: z133.string().min(1).max(255),
3842
+ description: z133.string().max(1e3).optional(),
3843
+ goal: z133.string().min(1).max(1e3),
3844
+ complexity: z133.enum(["beginner", "intermediate", "advanced", "expert"]),
3845
+ estimatedTotalTime: z133.string().optional(),
3846
+ prerequisites: z133.array(z133.string().max(200)).default([]),
3847
+ quests: z133.array(questSchema).min(1),
3848
+ resources: z133.array(questResourceSchema).default([]),
3849
+ projectId: z133.string().optional(),
3850
+ organizationId: z133.string().optional(),
3851
+ visibility: z133.enum(["private", "project", "organization", "public"]).default("private"),
3852
+ tags: z133.array(z133.string().max(50)).max(20).default([]),
3853
+ permissions: z133.object({
3854
+ canRead: z133.array(z133.string()).default([]),
3855
+ canWrite: z133.array(z133.string()).default([]),
3856
+ canDelete: z133.array(z133.string()).default([]),
3857
+ isPublic: z133.boolean().default(false),
3858
+ inheritFromProject: z133.boolean().default(true)
3446
3859
  }).optional(),
3447
- sourceQuestId: z132.string().optional(),
3448
- sessionId: z132.string().optional(),
3449
- metadata: z132.record(z132.unknown()).default({})
3860
+ sourceQuestId: z133.string().optional(),
3861
+ sessionId: z133.string().optional(),
3862
+ metadata: z133.record(z133.unknown()).default({})
3450
3863
  });
3451
3864
 
3452
3865
  // ../../b4m-core/packages/services/dist/src/questMasterService/updateQuestStatus.js
3453
- import { z as z133 } from "zod";
3454
- var updateQuestStatusSchema = z133.object({
3455
- artifactId: z133.string(),
3456
- questId: z133.string(),
3457
- status: z133.enum(["not_started", "in_progress", "completed", "blocked"]),
3458
- completionNote: z133.string().max(500).optional()
3866
+ import { z as z134 } from "zod";
3867
+ var updateQuestStatusSchema = z134.object({
3868
+ artifactId: z134.string(),
3869
+ questId: z134.string(),
3870
+ status: z134.enum(["not_started", "in_progress", "completed", "blocked"]),
3871
+ completionNote: z134.string().max(500).optional()
3459
3872
  });
3460
3873
 
3461
3874
  // ../../b4m-core/packages/services/dist/src/dataLakeService/opensearchClient.js
@@ -3475,63 +3888,63 @@ import { v4 as uuidv44 } from "uuid";
3475
3888
  import { randomUUID as randomUUID5 } from "crypto";
3476
3889
 
3477
3890
  // ../../b4m-core/packages/services/dist/src/emailIngestionService/types.js
3478
- import { z as z134 } from "zod";
3479
- var processIngestedEmailOptionsSchema = z134.object({
3480
- platformDomain: z134.string().optional(),
3481
- isNewsletter: z134.boolean().optional()
3891
+ import { z as z135 } from "zod";
3892
+ var processIngestedEmailOptionsSchema = z135.object({
3893
+ platformDomain: z135.string().optional(),
3894
+ isNewsletter: z135.boolean().optional()
3482
3895
  }).optional();
3483
- var emailAttachmentSchema = z134.object({
3484
- filename: z134.string().optional(),
3485
- contentType: z134.string().optional(),
3486
- contentDisposition: z134.string().optional(),
3487
- size: z134.number().min(0),
3488
- content: z134.instanceof(Buffer),
3489
- related: z134.boolean().optional()
3490
- });
3491
- var parsedEmailObjectSchema = z134.object({
3492
- messageId: z134.string().optional(),
3493
- inReplyTo: z134.string().optional(),
3494
- references: z134.union([z134.string(), z134.array(z134.string())]).optional(),
3495
- from: z134.any().optional(),
3896
+ var emailAttachmentSchema = z135.object({
3897
+ filename: z135.string().optional(),
3898
+ contentType: z135.string().optional(),
3899
+ contentDisposition: z135.string().optional(),
3900
+ size: z135.number().min(0),
3901
+ content: z135.instanceof(Buffer),
3902
+ related: z135.boolean().optional()
3903
+ });
3904
+ var parsedEmailObjectSchema = z135.object({
3905
+ messageId: z135.string().optional(),
3906
+ inReplyTo: z135.string().optional(),
3907
+ references: z135.union([z135.string(), z135.array(z135.string())]).optional(),
3908
+ from: z135.any().optional(),
3496
3909
  // Complex email address object
3497
- to: z134.any().optional(),
3498
- cc: z134.any().optional(),
3499
- bcc: z134.any().optional(),
3500
- subject: z134.string().optional(),
3501
- date: z134.date().optional(),
3502
- text: z134.string().optional(),
3503
- html: z134.string().optional(),
3504
- attachments: z134.array(emailAttachmentSchema).optional()
3505
- });
3506
- var processIngestedEmailSchema = z134.object({
3910
+ to: z135.any().optional(),
3911
+ cc: z135.any().optional(),
3912
+ bcc: z135.any().optional(),
3913
+ subject: z135.string().optional(),
3914
+ date: z135.date().optional(),
3915
+ text: z135.string().optional(),
3916
+ html: z135.string().optional(),
3917
+ attachments: z135.array(emailAttachmentSchema).optional()
3918
+ });
3919
+ var processIngestedEmailSchema = z135.object({
3507
3920
  parsedEmail: parsedEmailObjectSchema,
3508
- rawEmailS3Key: z134.string().min(1, "rawEmailS3Key cannot be empty"),
3921
+ rawEmailS3Key: z135.string().min(1, "rawEmailS3Key cannot be empty"),
3509
3922
  options: processIngestedEmailOptionsSchema
3510
3923
  });
3511
3924
 
3512
3925
  // ../../b4m-core/packages/services/dist/src/emailAnalysisService/types.js
3513
- import { z as z135 } from "zod";
3514
- var llmAnalysisResponseSchema = z135.object({
3515
- summary: z135.string().min(1, "Summary cannot be empty"),
3516
- entities: z135.object({
3517
- companies: z135.array(z135.string()).default([]),
3518
- people: z135.array(z135.string()).default([]),
3519
- products: z135.array(z135.string()).default([]),
3520
- technologies: z135.array(z135.string()).default([])
3926
+ import { z as z136 } from "zod";
3927
+ var llmAnalysisResponseSchema = z136.object({
3928
+ summary: z136.string().min(1, "Summary cannot be empty"),
3929
+ entities: z136.object({
3930
+ companies: z136.array(z136.string()).default([]),
3931
+ people: z136.array(z136.string()).default([]),
3932
+ products: z136.array(z136.string()).default([]),
3933
+ technologies: z136.array(z136.string()).default([])
3521
3934
  }),
3522
- sentiment: z135.enum(["positive", "neutral", "negative", "urgent"]),
3523
- actionItems: z135.array(z135.object({
3524
- description: z135.string(),
3525
- deadline: z135.string().optional()
3935
+ sentiment: z136.enum(["positive", "neutral", "negative", "urgent"]),
3936
+ actionItems: z136.array(z136.object({
3937
+ description: z136.string(),
3938
+ deadline: z136.string().optional()
3526
3939
  // ISO date string from LLM
3527
3940
  })).default([]),
3528
- privacyRecommendation: z135.enum(["public", "team", "private"]),
3529
- embargoDetected: z135.boolean().default(false),
3530
- suggestedTags: z135.array(z135.string()).default([])
3941
+ privacyRecommendation: z136.enum(["public", "team", "private"]),
3942
+ embargoDetected: z136.boolean().default(false),
3943
+ suggestedTags: z136.array(z136.string()).default([])
3531
3944
  });
3532
3945
 
3533
3946
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletion.js
3534
- import { z as z137 } from "zod";
3947
+ import { z as z138 } from "zod";
3535
3948
 
3536
3949
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletionInvoke.js
3537
3950
  import { fromZodError } from "zod-validation-error";
@@ -3645,8 +4058,8 @@ async function processAndStoreImages(images, context) {
3645
4058
  const buffer = await downloadImage(image);
3646
4059
  const fileType = await fileTypeFromBuffer2(buffer);
3647
4060
  const filename = `${uuidv45()}.${fileType?.ext}`;
3648
- const path11 = await context.imageGenerateStorage.upload(buffer, filename, {});
3649
- return path11;
4061
+ const path13 = await context.imageGenerateStorage.upload(buffer, filename, {});
4062
+ return path13;
3650
4063
  }));
3651
4064
  }
3652
4065
  async function updateQuestAndReturnMarkdown(storedImageUrls, context) {
@@ -4591,17 +5004,17 @@ var rechartsTool = {
4591
5004
  };
4592
5005
 
4593
5006
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/editFile/index.js
4594
- import { z as z136 } from "zod";
5007
+ import { z as z137 } from "zod";
4595
5008
  import { diffLines as diffLines2 } from "diff";
4596
- var editFileSchema = z136.object({
4597
- fileId: z136.string().describe("The ID of the file to edit"),
4598
- instruction: z136.string().describe("Natural language instruction describing the changes to make"),
4599
- selection: z136.object({
4600
- start: z136.number().describe("Starting character position of the selection"),
4601
- end: z136.number().describe("Ending character position of the selection")
5009
+ var editFileSchema = z137.object({
5010
+ fileId: z137.string().describe("The ID of the file to edit"),
5011
+ instruction: z137.string().describe("Natural language instruction describing the changes to make"),
5012
+ selection: z137.object({
5013
+ start: z137.number().describe("Starting character position of the selection"),
5014
+ end: z137.number().describe("Ending character position of the selection")
4602
5015
  }).optional().describe("Optional selection range to edit within the file"),
4603
- preserveFormatting: z136.boolean().optional().default(true).describe("Whether to preserve the original formatting style"),
4604
- returnDiff: z136.boolean().optional().default(true).describe("Whether to return a diff of the changes")
5016
+ preserveFormatting: z137.boolean().optional().default(true).describe("Whether to preserve the original formatting style"),
5017
+ returnDiff: z137.boolean().optional().default(true).describe("Whether to return a diff of the changes")
4605
5018
  });
4606
5019
  function generateSimpleDiff(original, modified) {
4607
5020
  const differences = diffLines2(original, modified);
@@ -4830,8 +5243,8 @@ async function processAndStoreImage(imageUrl, context) {
4830
5243
  const buffer = await downloadImage2(imageUrl);
4831
5244
  const fileType = await fileTypeFromBuffer3(buffer);
4832
5245
  const filename = `${uuidv46()}.${fileType?.ext}`;
4833
- const path11 = await context.imageGenerateStorage.upload(buffer, filename, {});
4834
- return path11;
5246
+ const path13 = await context.imageGenerateStorage.upload(buffer, filename, {});
5247
+ return path13;
4835
5248
  }
4836
5249
  async function updateQuestAndReturnMarkdown2(storedImagePath, context) {
4837
5250
  await context.onFinish?.("edit_image", storedImagePath);
@@ -6360,8 +6773,8 @@ var getHeliocentricCoords = (planet, T) => {
6360
6773
  const sinNode = Math.sin(longNode);
6361
6774
  const x = r * (cosNode * cosOmega - sinNode * sinOmega * cosI);
6362
6775
  const y = r * (sinNode * cosOmega + cosNode * sinOmega * cosI);
6363
- const z143 = r * sinOmega * sinI;
6364
- return { x, y, z: z143, r };
6776
+ const z144 = r * sinOmega * sinI;
6777
+ return { x, y, z: z144, r };
6365
6778
  };
6366
6779
  var getGeocentricEcliptic = (planet, earth) => {
6367
6780
  const dx = planet.x - earth.x;
@@ -6668,33 +7081,33 @@ var planetVisibilityTool = {
6668
7081
  };
6669
7082
 
6670
7083
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/fileRead/index.js
6671
- import { promises as fs5 } from "fs";
6672
- import { existsSync, statSync } from "fs";
6673
- import path4 from "path";
6674
- var MAX_FILE_SIZE = 10 * 1024 * 1024;
7084
+ import { promises as fs7 } from "fs";
7085
+ import { existsSync as existsSync2, statSync as statSync3 } from "fs";
7086
+ import path6 from "path";
7087
+ var MAX_FILE_SIZE2 = 10 * 1024 * 1024;
6675
7088
  async function readFileContent(params) {
6676
7089
  const { path: filePath, encoding = "utf-8", maxLines } = params;
6677
- const normalizedPath = path4.normalize(filePath);
6678
- const resolvedPath = path4.resolve(process.cwd(), normalizedPath);
6679
- const cwd = path4.resolve(process.cwd());
7090
+ const normalizedPath = path6.normalize(filePath);
7091
+ const resolvedPath = path6.resolve(process.cwd(), normalizedPath);
7092
+ const cwd = path6.resolve(process.cwd());
6680
7093
  if (!resolvedPath.startsWith(cwd)) {
6681
7094
  throw new Error(`Access denied: Cannot read files outside of current working directory`);
6682
7095
  }
6683
- if (!existsSync(resolvedPath)) {
7096
+ if (!existsSync2(resolvedPath)) {
6684
7097
  throw new Error(`File not found: ${filePath}`);
6685
7098
  }
6686
- const stats = statSync(resolvedPath);
7099
+ const stats = statSync3(resolvedPath);
6687
7100
  if (stats.isDirectory()) {
6688
7101
  throw new Error(`Path is a directory, not a file: ${filePath}`);
6689
7102
  }
6690
- if (stats.size > MAX_FILE_SIZE) {
6691
- throw new Error(`File too large: ${(stats.size / 1024 / 1024).toFixed(2)}MB (max ${MAX_FILE_SIZE / 1024 / 1024}MB)`);
7103
+ if (stats.size > MAX_FILE_SIZE2) {
7104
+ throw new Error(`File too large: ${(stats.size / 1024 / 1024).toFixed(2)}MB (max ${MAX_FILE_SIZE2 / 1024 / 1024}MB)`);
6692
7105
  }
6693
7106
  const isBinary = await checkIfBinary(resolvedPath);
6694
7107
  if (isBinary && encoding === "utf-8") {
6695
7108
  throw new Error(`File appears to be binary. Use encoding 'base64' to read binary files, or specify a different encoding.`);
6696
7109
  }
6697
- const content = await fs5.readFile(resolvedPath, encoding);
7110
+ const content = await fs7.readFile(resolvedPath, encoding);
6698
7111
  if (maxLines && typeof content === "string") {
6699
7112
  const lines = content.split("\n");
6700
7113
  if (lines.length > maxLines) {
@@ -6709,7 +7122,7 @@ ${content}`;
6709
7122
  }
6710
7123
  async function checkIfBinary(filePath) {
6711
7124
  const buffer = Buffer.alloc(8192);
6712
- const fd = await fs5.open(filePath, "r");
7125
+ const fd = await fs7.open(filePath, "r");
6713
7126
  try {
6714
7127
  const { bytesRead } = await fd.read(buffer, 0, 8192, 0);
6715
7128
  const chunk = buffer.slice(0, bytesRead);
@@ -6726,7 +7139,7 @@ var fileReadTool = {
6726
7139
  context.logger.info("\u{1F4C4} FileRead: Reading file", { path: params.path });
6727
7140
  try {
6728
7141
  const content = await readFileContent(params);
6729
- const stats = statSync(path4.resolve(process.cwd(), path4.normalize(params.path)));
7142
+ const stats = statSync3(path6.resolve(process.cwd(), path6.normalize(params.path)));
6730
7143
  context.logger.info("\u2705 FileRead: Success", {
6731
7144
  path: params.path,
6732
7145
  size: stats.size,
@@ -6765,25 +7178,25 @@ var fileReadTool = {
6765
7178
  };
6766
7179
 
6767
7180
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/createFile/index.js
6768
- import { promises as fs6 } from "fs";
6769
- import { existsSync as existsSync2 } from "fs";
6770
- import path5 from "path";
7181
+ import { promises as fs8 } from "fs";
7182
+ import { existsSync as existsSync3 } from "fs";
7183
+ import path7 from "path";
6771
7184
  async function createFile(params) {
6772
7185
  const { path: filePath, content, createDirectories = true } = params;
6773
- const normalizedPath = path5.normalize(filePath);
6774
- const resolvedPath = path5.resolve(process.cwd(), normalizedPath);
6775
- const cwd = path5.resolve(process.cwd());
7186
+ const normalizedPath = path7.normalize(filePath);
7187
+ const resolvedPath = path7.resolve(process.cwd(), normalizedPath);
7188
+ const cwd = path7.resolve(process.cwd());
6776
7189
  if (!resolvedPath.startsWith(cwd)) {
6777
7190
  throw new Error(`Access denied: Cannot create files outside of current working directory`);
6778
7191
  }
6779
- const fileExists = existsSync2(resolvedPath);
7192
+ const fileExists = existsSync3(resolvedPath);
6780
7193
  const action = fileExists ? "overwritten" : "created";
6781
7194
  if (createDirectories) {
6782
- const dir = path5.dirname(resolvedPath);
6783
- await fs6.mkdir(dir, { recursive: true });
7195
+ const dir = path7.dirname(resolvedPath);
7196
+ await fs8.mkdir(dir, { recursive: true });
6784
7197
  }
6785
- await fs6.writeFile(resolvedPath, content, "utf-8");
6786
- const stats = await fs6.stat(resolvedPath);
7198
+ await fs8.writeFile(resolvedPath, content, "utf-8");
7199
+ const stats = await fs8.stat(resolvedPath);
6787
7200
  const lines = content.split("\n").length;
6788
7201
  return `File ${action} successfully: ${filePath}
6789
7202
  Size: ${stats.size} bytes
@@ -6794,7 +7207,7 @@ var createFileTool = {
6794
7207
  implementation: (context) => ({
6795
7208
  toolFn: async (value) => {
6796
7209
  const params = value;
6797
- const fileExists = existsSync2(path5.resolve(process.cwd(), path5.normalize(params.path)));
7210
+ const fileExists = existsSync3(path7.resolve(process.cwd(), path7.normalize(params.path)));
6798
7211
  context.logger.info(`\u{1F4DD} CreateFile: ${fileExists ? "Overwriting" : "Creating"} file`, {
6799
7212
  path: params.path,
6800
7213
  size: params.content.length
@@ -6835,8 +7248,8 @@ var createFileTool = {
6835
7248
 
6836
7249
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/globFiles/index.js
6837
7250
  import { readdir } from "fs/promises";
6838
- import { statSync as statSync2 } from "fs";
6839
- import path6 from "path";
7251
+ import { statSync as statSync4 } from "fs";
7252
+ import path8 from "path";
6840
7253
  function matchGlob(filePath, pattern) {
6841
7254
  let regexPattern = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\?/g, ".").replace(/\{([^}]+)\}/g, (_, options) => `(${options.split(",").join("|")})`).replace(/\[([^\]]+)\]/g, "[$1]");
6842
7255
  regexPattern = regexPattern.replace(/\{\{GLOBSTAR\}\}\//g, "(.*/)?").replace(/\/\{\{GLOBSTAR\}\}/g, "(/.*)?").replace(/\{\{GLOBSTAR\}\}/g, ".*");
@@ -6854,8 +7267,8 @@ async function walkDir(dir, pattern, includeHidden, maxResults, basePath = "") {
6854
7267
  if (!includeHidden && entry.name.startsWith(".")) {
6855
7268
  continue;
6856
7269
  }
6857
- const relativePath = basePath ? path6.join(basePath, entry.name) : entry.name;
6858
- const fullPath = path6.join(dir, entry.name);
7270
+ const relativePath = basePath ? path8.join(basePath, entry.name) : entry.name;
7271
+ const fullPath = path8.join(dir, entry.name);
6859
7272
  if (matchGlob(relativePath, pattern)) {
6860
7273
  matches.push(relativePath);
6861
7274
  }
@@ -6871,7 +7284,7 @@ async function walkDir(dir, pattern, includeHidden, maxResults, basePath = "") {
6871
7284
  async function listFiles(params) {
6872
7285
  const { pattern, cwd: relativeCwd, includeHidden = false, maxResults = 1e3 } = params;
6873
7286
  const baseCwd = process.cwd();
6874
- const targetCwd = relativeCwd ? path6.resolve(baseCwd, path6.normalize(relativeCwd)) : baseCwd;
7287
+ const targetCwd = relativeCwd ? path8.resolve(baseCwd, path8.normalize(relativeCwd)) : baseCwd;
6875
7288
  if (!targetCwd.startsWith(baseCwd)) {
6876
7289
  throw new Error(`Access denied: Cannot list files outside of current working directory`);
6877
7290
  }
@@ -6882,8 +7295,8 @@ async function listFiles(params) {
6882
7295
  const filesInfo = [];
6883
7296
  for (const match of matches) {
6884
7297
  try {
6885
- const fullPath = path6.join(targetCwd, match);
6886
- const stats = statSync2(fullPath);
7298
+ const fullPath = path8.join(targetCwd, match);
7299
+ const stats = statSync4(fullPath);
6887
7300
  filesInfo.push({
6888
7301
  path: match,
6889
7302
  size: stats.size,
@@ -6964,9 +7377,9 @@ var globFilesTool = {
6964
7377
 
6965
7378
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/grepSearch/index.js
6966
7379
  import { readdir as readdir2 } from "fs/promises";
6967
- import { readFileSync, statSync as statSync3 } from "fs";
6968
- import path7 from "path";
6969
- var MAX_FILE_SIZE2 = 10 * 1024 * 1024;
7380
+ import { readFileSync as readFileSync2, statSync as statSync5 } from "fs";
7381
+ import path9 from "path";
7382
+ var MAX_FILE_SIZE3 = 10 * 1024 * 1024;
6970
7383
  function matchGlob2(filePath, pattern) {
6971
7384
  const regexPattern = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\{\{GLOBSTAR\}\}/g, ".*").replace(/\?/g, ".").replace(/\{([^}]+)\}/g, (_, options) => `(${options.split(",").join("|")})`).replace(/\[([^\]]+)\]/g, "[$1]");
6972
7385
  const regex = new RegExp(`^${regexPattern}$`);
@@ -6983,8 +7396,8 @@ async function walkDir2(dir, pattern, maxResults, basePath = "") {
6983
7396
  if (entry.name.startsWith(".")) {
6984
7397
  continue;
6985
7398
  }
6986
- const relativePath = basePath ? path7.join(basePath, entry.name) : entry.name;
6987
- const fullPath = path7.join(dir, entry.name);
7399
+ const relativePath = basePath ? path9.join(basePath, entry.name) : entry.name;
7400
+ const fullPath = path9.join(dir, entry.name);
6988
7401
  if (matchGlob2(relativePath, pattern)) {
6989
7402
  matches.push(relativePath);
6990
7403
  }
@@ -6997,10 +7410,10 @@ async function walkDir2(dir, pattern, maxResults, basePath = "") {
6997
7410
  }
6998
7411
  return matches;
6999
7412
  }
7000
- async function searchFiles(params) {
7413
+ async function searchFiles2(params) {
7001
7414
  const { pattern, filePattern = "**/*", cwd: relativeCwd, caseSensitive = false, maxResults = 100, contextLines = 0 } = params;
7002
7415
  const baseCwd = process.cwd();
7003
- const targetCwd = relativeCwd ? path7.resolve(baseCwd, path7.normalize(relativeCwd)) : baseCwd;
7416
+ const targetCwd = relativeCwd ? path9.resolve(baseCwd, path9.normalize(relativeCwd)) : baseCwd;
7004
7417
  if (!targetCwd.startsWith(baseCwd)) {
7005
7418
  throw new Error(`Access denied: Cannot search files outside of current working directory`);
7006
7419
  }
@@ -7014,13 +7427,13 @@ async function searchFiles(params) {
7014
7427
  const filesToSearch = await walkDir2(targetCwd, filePattern, 1e4);
7015
7428
  const filteredFiles = [];
7016
7429
  for (const match of filesToSearch) {
7017
- const fullPath = path7.join(targetCwd, match);
7430
+ const fullPath = path9.join(targetCwd, match);
7018
7431
  try {
7019
- const stats = statSync3(fullPath);
7020
- if (stats.isDirectory() || stats.size > MAX_FILE_SIZE2) {
7432
+ const stats = statSync5(fullPath);
7433
+ if (stats.isDirectory() || stats.size > MAX_FILE_SIZE3) {
7021
7434
  continue;
7022
7435
  }
7023
- if (isBinaryFile(fullPath)) {
7436
+ if (isBinaryFile2(fullPath)) {
7024
7437
  continue;
7025
7438
  }
7026
7439
  filteredFiles.push(match);
@@ -7038,9 +7451,9 @@ async function searchFiles(params) {
7038
7451
  break;
7039
7452
  }
7040
7453
  filesSearched++;
7041
- const fullPath = path7.join(targetCwd, file);
7454
+ const fullPath = path9.join(targetCwd, file);
7042
7455
  try {
7043
- const content = readFileSync(fullPath, "utf-8");
7456
+ const content = readFileSync2(fullPath, "utf-8");
7044
7457
  const lines = content.split("\n");
7045
7458
  for (let i = 0; i < lines.length; i++) {
7046
7459
  if (matches.length >= maxResults) {
@@ -7104,7 +7517,7 @@ ${match.context.after.map((l) => ` ${l}`).join("\n")}`;
7104
7517
  }).join("\n");
7105
7518
  return `${summary}${patternInfo}${cwdInfo}${matchesList}`;
7106
7519
  }
7107
- function isBinaryFile(filePath) {
7520
+ function isBinaryFile2(filePath) {
7108
7521
  try {
7109
7522
  const buffer = Buffer.alloc(8192);
7110
7523
  const fd = __require("fs").openSync(filePath, "r");
@@ -7127,7 +7540,7 @@ var grepSearchTool = {
7127
7540
  cwd: params.cwd || "."
7128
7541
  });
7129
7542
  try {
7130
- const result = await searchFiles(params);
7543
+ const result = await searchFiles2(params);
7131
7544
  context.logger.info("\u2705 GrepSearch: Success");
7132
7545
  return result;
7133
7546
  } catch (error) {
@@ -7173,31 +7586,31 @@ var grepSearchTool = {
7173
7586
  };
7174
7587
 
7175
7588
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/deleteFile/index.js
7176
- import { promises as fs7 } from "fs";
7177
- import { existsSync as existsSync3, statSync as statSync4 } from "fs";
7178
- import path8 from "path";
7589
+ import { promises as fs9 } from "fs";
7590
+ import { existsSync as existsSync4, statSync as statSync6 } from "fs";
7591
+ import path10 from "path";
7179
7592
  async function deleteFile(params) {
7180
7593
  const { path: filePath, recursive = false } = params;
7181
- const normalizedPath = path8.normalize(filePath);
7182
- const resolvedPath = path8.resolve(process.cwd(), normalizedPath);
7183
- const cwd = path8.resolve(process.cwd());
7594
+ const normalizedPath = path10.normalize(filePath);
7595
+ const resolvedPath = path10.resolve(process.cwd(), normalizedPath);
7596
+ const cwd = path10.resolve(process.cwd());
7184
7597
  if (!resolvedPath.startsWith(cwd)) {
7185
7598
  throw new Error(`Access denied: Cannot delete files outside of current working directory`);
7186
7599
  }
7187
- if (!existsSync3(resolvedPath)) {
7600
+ if (!existsSync4(resolvedPath)) {
7188
7601
  throw new Error(`File or directory not found: ${filePath}`);
7189
7602
  }
7190
- const stats = statSync4(resolvedPath);
7603
+ const stats = statSync6(resolvedPath);
7191
7604
  const isDirectory = stats.isDirectory();
7192
7605
  const size = stats.size;
7193
7606
  if (isDirectory && !recursive) {
7194
7607
  throw new Error(`Path is a directory: ${filePath}. Use recursive=true to delete directories and their contents.`);
7195
7608
  }
7196
7609
  if (isDirectory) {
7197
- await fs7.rm(resolvedPath, { recursive: true, force: true });
7610
+ await fs9.rm(resolvedPath, { recursive: true, force: true });
7198
7611
  return `Directory deleted successfully: ${filePath}`;
7199
7612
  } else {
7200
- await fs7.unlink(resolvedPath);
7613
+ await fs9.unlink(resolvedPath);
7201
7614
  return `File deleted successfully: ${filePath}
7202
7615
  Size: ${size} bytes`;
7203
7616
  }
@@ -7207,8 +7620,8 @@ var deleteFileTool = {
7207
7620
  implementation: (context) => ({
7208
7621
  toolFn: async (value) => {
7209
7622
  const params = value;
7210
- const resolvedPath = path8.resolve(process.cwd(), path8.normalize(params.path));
7211
- const isDirectory = existsSync3(resolvedPath) && statSync4(resolvedPath).isDirectory();
7623
+ const resolvedPath = path10.resolve(process.cwd(), path10.normalize(params.path));
7624
+ const isDirectory = existsSync4(resolvedPath) && statSync6(resolvedPath).isDirectory();
7212
7625
  context.logger.info(`\u{1F5D1}\uFE0F DeleteFile: Deleting ${isDirectory ? "directory" : "file"}`, {
7213
7626
  path: params.path,
7214
7627
  recursive: params.recursive
@@ -7386,42 +7799,42 @@ var DISABLE_SERVER_THROTTLING = process.env.DISABLE_SERVER_THROTTLING === "true"
7386
7799
  var questSaveMutex = new Mutex();
7387
7800
 
7388
7801
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletion.js
7389
- var QuestStartBodySchema = z137.object({
7390
- userId: z137.string(),
7391
- sessionId: z137.string(),
7392
- questId: z137.string(),
7393
- message: z137.string(),
7394
- messageFileIds: z137.array(z137.string()),
7395
- historyCount: z137.number(),
7396
- fabFileIds: z137.array(z137.string()),
7802
+ var QuestStartBodySchema = z138.object({
7803
+ userId: z138.string(),
7804
+ sessionId: z138.string(),
7805
+ questId: z138.string(),
7806
+ message: z138.string(),
7807
+ messageFileIds: z138.array(z138.string()),
7808
+ historyCount: z138.number(),
7809
+ fabFileIds: z138.array(z138.string()),
7397
7810
  params: ChatCompletionCreateInputSchema,
7398
7811
  dashboardParams: DashboardParamsSchema.optional(),
7399
- enableQuestMaster: z137.boolean().optional(),
7400
- enableMementos: z137.boolean().optional(),
7401
- enableArtifacts: z137.boolean().optional(),
7402
- enableAgents: z137.boolean().optional(),
7812
+ enableQuestMaster: z138.boolean().optional(),
7813
+ enableMementos: z138.boolean().optional(),
7814
+ enableArtifacts: z138.boolean().optional(),
7815
+ enableAgents: z138.boolean().optional(),
7403
7816
  promptMeta: PromptMetaZodSchema,
7404
- tools: z137.array(z137.union([b4mLLMTools, z137.string()])).optional(),
7405
- mcpServers: z137.array(z137.string()).optional(),
7406
- projectId: z137.string().optional(),
7407
- organizationId: z137.string().nullable().optional(),
7817
+ tools: z138.array(z138.union([b4mLLMTools, z138.string()])).optional(),
7818
+ mcpServers: z138.array(z138.string()).optional(),
7819
+ projectId: z138.string().optional(),
7820
+ organizationId: z138.string().nullable().optional(),
7408
7821
  questMaster: QuestMasterParamsSchema.optional(),
7409
- toolPromptId: z137.string().optional(),
7822
+ toolPromptId: z138.string().optional(),
7410
7823
  researchMode: ResearchModeParamsSchema.optional(),
7411
- fallbackModel: z137.string().optional(),
7412
- embeddingModel: z137.string().optional(),
7413
- queryComplexity: z137.string(),
7824
+ fallbackModel: z138.string().optional(),
7825
+ embeddingModel: z138.string().optional(),
7826
+ queryComplexity: z138.string(),
7414
7827
  imageConfig: GenerateImageToolCallSchema.optional(),
7415
- deepResearchConfig: z137.object({
7416
- maxDepth: z137.number().optional(),
7417
- duration: z137.number().optional(),
7828
+ deepResearchConfig: z138.object({
7829
+ maxDepth: z138.number().optional(),
7830
+ duration: z138.number().optional(),
7418
7831
  // Note: searchers are passed via ToolContext and not through this API schema
7419
- searchers: z137.array(z137.any()).optional()
7832
+ searchers: z138.array(z138.any()).optional()
7420
7833
  }).optional(),
7421
- extraContextMessages: z137.array(z137.object({
7422
- role: z137.enum(["user", "assistant", "system", "function", "tool"]),
7423
- content: z137.union([z137.string(), z137.array(z137.any())]),
7424
- fabFileIds: z137.array(z137.string()).optional()
7834
+ extraContextMessages: z138.array(z138.object({
7835
+ role: z138.enum(["user", "assistant", "system", "function", "tool"]),
7836
+ content: z138.union([z138.string(), z138.array(z138.any())]),
7837
+ fabFileIds: z138.array(z138.string()).optional()
7425
7838
  })).optional()
7426
7839
  });
7427
7840
 
@@ -7429,30 +7842,9 @@ var QuestStartBodySchema = z137.object({
7429
7842
  import axios8 from "axios";
7430
7843
  import { fileTypeFromBuffer as fileTypeFromBuffer4 } from "file-type";
7431
7844
  import { v4 as uuidv47 } from "uuid";
7432
- import { z as z138 } from "zod";
7845
+ import { z as z139 } from "zod";
7433
7846
  import { fromZodError as fromZodError2 } from "zod-validation-error";
7434
7847
  var ImageGenerationBodySchema = OpenAIImageGenerationInput.extend({
7435
- sessionId: z138.string(),
7436
- questId: z138.string(),
7437
- userId: z138.string(),
7438
- prompt: z138.string(),
7439
- safety_tolerance: z138.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
7440
- prompt_upsampling: z138.boolean().optional().default(false),
7441
- seed: z138.number().nullable().optional(),
7442
- output_format: z138.enum(["jpeg", "png"]).nullable().optional().default("png"),
7443
- width: z138.number().optional(),
7444
- height: z138.number().optional(),
7445
- aspect_ratio: z138.string().optional(),
7446
- fabFileIds: z138.array(z138.string()).optional()
7447
- });
7448
-
7449
- // ../../b4m-core/packages/services/dist/src/llm/ImageEdit.js
7450
- import axios9 from "axios";
7451
- import { fileTypeFromBuffer as fileTypeFromBuffer5 } from "file-type";
7452
- import { v4 as uuidv48 } from "uuid";
7453
- import { z as z139 } from "zod";
7454
- import { fromZodError as fromZodError3 } from "zod-validation-error";
7455
- var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
7456
7848
  sessionId: z139.string(),
7457
7849
  questId: z139.string(),
7458
7850
  userId: z139.string(),
@@ -7460,35 +7852,56 @@ var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
7460
7852
  safety_tolerance: z139.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
7461
7853
  prompt_upsampling: z139.boolean().optional().default(false),
7462
7854
  seed: z139.number().nullable().optional(),
7463
- output_format: z139.enum(["jpeg", "png"]).optional().default("png"),
7855
+ output_format: z139.enum(["jpeg", "png"]).nullable().optional().default("png"),
7464
7856
  width: z139.number().optional(),
7465
7857
  height: z139.number().optional(),
7466
7858
  aspect_ratio: z139.string().optional(),
7467
- size: z139.string().optional(),
7468
- fabFileIds: z139.array(z139.string()).optional(),
7469
- image: z139.string()
7859
+ fabFileIds: z139.array(z139.string()).optional()
7470
7860
  });
7471
7861
 
7472
- // ../../b4m-core/packages/services/dist/src/llm/refineText.js
7862
+ // ../../b4m-core/packages/services/dist/src/llm/ImageEdit.js
7863
+ import axios9 from "axios";
7864
+ import { fileTypeFromBuffer as fileTypeFromBuffer5 } from "file-type";
7865
+ import { v4 as uuidv48 } from "uuid";
7473
7866
  import { z as z140 } from "zod";
7474
- var refineTextLLMSchema = z140.object({
7475
- text: z140.string(),
7476
- context: z140.string().optional()
7867
+ import { fromZodError as fromZodError3 } from "zod-validation-error";
7868
+ var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
7869
+ sessionId: z140.string(),
7870
+ questId: z140.string(),
7871
+ userId: z140.string(),
7872
+ prompt: z140.string(),
7873
+ safety_tolerance: z140.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
7874
+ prompt_upsampling: z140.boolean().optional().default(false),
7875
+ seed: z140.number().nullable().optional(),
7876
+ output_format: z140.enum(["jpeg", "png"]).optional().default("png"),
7877
+ width: z140.number().optional(),
7878
+ height: z140.number().optional(),
7879
+ aspect_ratio: z140.string().optional(),
7880
+ size: z140.string().optional(),
7881
+ fabFileIds: z140.array(z140.string()).optional(),
7882
+ image: z140.string()
7883
+ });
7884
+
7885
+ // ../../b4m-core/packages/services/dist/src/llm/refineText.js
7886
+ import { z as z141 } from "zod";
7887
+ var refineTextLLMSchema = z141.object({
7888
+ text: z141.string(),
7889
+ context: z141.string().optional()
7477
7890
  // tone: z.enum(['formal', 'informal', 'neutral']).optional(),
7478
7891
  // style: z.enum(['technical', 'creative', 'academic', 'business', 'narrative']).optional(),
7479
7892
  });
7480
7893
 
7481
7894
  // ../../b4m-core/packages/services/dist/src/llm/MementoEvaluationService.js
7482
- import { z as z141 } from "zod";
7483
- var SingleMementoEvalSchema = z141.object({
7484
- importance: z141.number().min(1).max(10),
7895
+ import { z as z142 } from "zod";
7896
+ var SingleMementoEvalSchema = z142.object({
7897
+ importance: z142.number().min(1).max(10),
7485
7898
  // 1-10 scale for personal info importance
7486
- summary: z141.string(),
7487
- tags: z141.array(z141.string()).optional()
7899
+ summary: z142.string(),
7900
+ tags: z142.array(z142.string()).optional()
7488
7901
  });
7489
- var MementoEvalResponseSchema = z141.object({
7490
- isPersonal: z141.boolean(),
7491
- mementos: z141.array(SingleMementoEvalSchema).optional()
7902
+ var MementoEvalResponseSchema = z142.object({
7903
+ isPersonal: z142.boolean(),
7904
+ mementos: z142.array(SingleMementoEvalSchema).optional()
7492
7905
  // Array of distinct personal information
7493
7906
  });
7494
7907
 
@@ -7498,10 +7911,10 @@ import jwt2 from "jsonwebtoken";
7498
7911
  // src/utils/diffPreview.ts
7499
7912
  import * as Diff from "diff";
7500
7913
  import { readFile } from "fs/promises";
7501
- import { existsSync as existsSync4 } from "fs";
7914
+ import { existsSync as existsSync5 } from "fs";
7502
7915
  async function generateFileDiffPreview(args) {
7503
7916
  try {
7504
- if (!existsSync4(args.path)) {
7917
+ if (!existsSync5(args.path)) {
7505
7918
  const lines2 = args.content.split("\n");
7506
7919
  const preview = lines2.slice(0, 20).join("\n");
7507
7920
  const hasMore = lines2.length > 20;
@@ -7531,10 +7944,10 @@ ${preview}${hasMore ? `
7531
7944
  }
7532
7945
  async function generateFileDeletePreview(args) {
7533
7946
  try {
7534
- if (!existsSync4(args.path)) {
7947
+ if (!existsSync5(args.path)) {
7535
7948
  return `[File does not exist: ${args.path}]`;
7536
7949
  }
7537
- const stats = await import("fs/promises").then((fs9) => fs9.stat(args.path));
7950
+ const stats = await import("fs/promises").then((fs11) => fs11.stat(args.path));
7538
7951
  return `[File will be deleted]
7539
7952
 
7540
7953
  Path: ${args.path}
@@ -7550,21 +7963,21 @@ var NoOpStorage = class extends BaseStorage {
7550
7963
  async upload(input, destination, options) {
7551
7964
  return `/tmp/${destination}`;
7552
7965
  }
7553
- async download(path11) {
7966
+ async download(path13) {
7554
7967
  throw new Error("Download not supported in CLI");
7555
7968
  }
7556
- async delete(path11) {
7969
+ async delete(path13) {
7557
7970
  }
7558
- async getSignedUrl(path11) {
7559
- return `/tmp/${path11}`;
7971
+ async getSignedUrl(path13) {
7972
+ return `/tmp/${path13}`;
7560
7973
  }
7561
- getPublicUrl(path11) {
7562
- return `/tmp/${path11}`;
7974
+ getPublicUrl(path13) {
7975
+ return `/tmp/${path13}`;
7563
7976
  }
7564
- async getPreview(path11) {
7565
- return `/tmp/${path11}`;
7977
+ async getPreview(path13) {
7978
+ return `/tmp/${path13}`;
7566
7979
  }
7567
- async getMetadata(path11) {
7980
+ async getMetadata(path13) {
7568
7981
  return { size: 0, contentType: "application/octet-stream" };
7569
7982
  }
7570
7983
  };
@@ -7725,8 +8138,8 @@ function generateCliTools(userId, llm, model, permissionManager, showPermissionP
7725
8138
  }
7726
8139
 
7727
8140
  // src/config/toolSafety.ts
7728
- import { z as z142 } from "zod";
7729
- var ToolCategorySchema = z142.enum([
8141
+ import { z as z143 } from "zod";
8142
+ var ToolCategorySchema = z143.enum([
7730
8143
  "auto_approve",
7731
8144
  // Safe tools that run automatically without permission
7732
8145
  "prompt_always",
@@ -7734,9 +8147,9 @@ var ToolCategorySchema = z142.enum([
7734
8147
  "prompt_default"
7735
8148
  // Tools that prompt by default but can be trusted
7736
8149
  ]);
7737
- var ToolSafetyConfigSchema = z142.object({
7738
- categories: z142.record(z142.string(), ToolCategorySchema),
7739
- trustedTools: z142.array(z142.string())
8150
+ var ToolSafetyConfigSchema = z143.object({
8151
+ categories: z143.record(z143.string(), ToolCategorySchema),
8152
+ trustedTools: z143.array(z143.string())
7740
8153
  });
7741
8154
  var DEFAULT_TOOL_CATEGORIES = {
7742
8155
  // ===== AUTO APPROVE (Safe tools) =====
@@ -7890,8 +8303,8 @@ function getEnvironmentName(configApiConfig) {
7890
8303
  }
7891
8304
 
7892
8305
  // src/utils/Logger.ts
7893
- import fs8 from "fs/promises";
7894
- import path9 from "path";
8306
+ import fs10 from "fs/promises";
8307
+ import path11 from "path";
7895
8308
  import os from "os";
7896
8309
  var Logger2 = class _Logger {
7897
8310
  constructor() {
@@ -7914,9 +8327,9 @@ var Logger2 = class _Logger {
7914
8327
  */
7915
8328
  async initialize(sessionId) {
7916
8329
  this.sessionId = sessionId;
7917
- const debugDir = path9.join(os.homedir(), ".bike4mind", "debug");
7918
- await fs8.mkdir(debugDir, { recursive: true });
7919
- this.logFilePath = path9.join(debugDir, `${sessionId}.txt`);
8330
+ const debugDir = path11.join(os.homedir(), ".bike4mind", "debug");
8331
+ await fs10.mkdir(debugDir, { recursive: true });
8332
+ this.logFilePath = path11.join(debugDir, `${sessionId}.txt`);
7920
8333
  await this.writeToFile("INFO", "=== CLI SESSION START ===");
7921
8334
  }
7922
8335
  /**
@@ -7980,7 +8393,7 @@ var Logger2 = class _Logger {
7980
8393
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
7981
8394
  const logEntry = `[${timestamp}] [${level}] ${message}
7982
8395
  `;
7983
- await fs8.appendFile(this.logFilePath, logEntry, "utf-8");
8396
+ await fs10.appendFile(this.logFilePath, logEntry, "utf-8");
7984
8397
  } catch (error) {
7985
8398
  console.error("File logging failed:", error);
7986
8399
  }
@@ -8126,15 +8539,15 @@ var Logger2 = class _Logger {
8126
8539
  async cleanupOldLogs() {
8127
8540
  if (!this.fileLoggingEnabled) return;
8128
8541
  try {
8129
- const debugDir = path9.join(os.homedir(), ".bike4mind", "debug");
8130
- const files = await fs8.readdir(debugDir);
8542
+ const debugDir = path11.join(os.homedir(), ".bike4mind", "debug");
8543
+ const files = await fs10.readdir(debugDir);
8131
8544
  const now = Date.now();
8132
8545
  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1e3;
8133
8546
  for (const file of files) {
8134
- const filePath = path9.join(debugDir, file);
8135
- const stats = await fs8.stat(filePath);
8547
+ const filePath = path11.join(debugDir, file);
8548
+ const stats = await fs10.stat(filePath);
8136
8549
  if (stats.mtime.getTime() < thirtyDaysAgo) {
8137
- await fs8.unlink(filePath);
8550
+ await fs10.unlink(filePath);
8138
8551
  }
8139
8552
  }
8140
8553
  } catch (error) {
@@ -8147,8 +8560,8 @@ var logger = Logger2.getInstance();
8147
8560
  // ../../b4m-core/packages/mcp/dist/src/client.js
8148
8561
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
8149
8562
  import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
8150
- import path10 from "path";
8151
- import { existsSync as existsSync5, readdirSync } from "fs";
8563
+ import path12 from "path";
8564
+ import { existsSync as existsSync6, readdirSync as readdirSync3 } from "fs";
8152
8565
  var MCPClient = class {
8153
8566
  // Note: This class handles MCP server communication with repository filtering
8154
8567
  mcp;
@@ -8173,20 +8586,20 @@ var MCPClient = class {
8173
8586
  const root = process.env.INIT_CWD || process.cwd();
8174
8587
  const candidatePaths = [
8175
8588
  // When running from SST Lambda with node_modules structure (copyFiles)
8176
- path10.join(root, `node_modules/@bike4mind/mcp/dist/src/${this.serverName}/index.js`),
8589
+ path12.join(root, `node_modules/@bike4mind/mcp/dist/src/${this.serverName}/index.js`),
8177
8590
  // When running from SST Lambda deployed environment (/var/task)
8178
- path10.join(root, `b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8591
+ path12.join(root, `b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8179
8592
  // When running from SST Lambda (.sst/artifacts/mcpHandler-dev), navigate to monorepo root (3 levels up)
8180
- path10.join(root, `../../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8593
+ path12.join(root, `../../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8181
8594
  // When running from packages/client (Next.js app), navigate to monorepo root (2 levels up)
8182
- path10.join(root, `../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8595
+ path12.join(root, `../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8183
8596
  // Original paths (backward compatibility)
8184
- path10.join(root, `/b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8185
- path10.join(root, "core", "mcp", "servers", this.serverName, "dist", "index.js")
8597
+ path12.join(root, `/b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8598
+ path12.join(root, "core", "mcp", "servers", this.serverName, "dist", "index.js")
8186
8599
  ];
8187
- const serverScriptPath = candidatePaths.find((p) => existsSync5(p));
8600
+ const serverScriptPath = candidatePaths.find((p) => existsSync6(p));
8188
8601
  if (!serverScriptPath) {
8189
- const getDirectories = (source) => readdirSync(source, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
8602
+ const getDirectories = (source) => readdirSync3(source, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
8190
8603
  console.error(`[MCP] Server script not found. Tried paths:`, candidatePaths);
8191
8604
  console.error(`[MCP] Available directories in ${root}:`, getDirectories(root));
8192
8605
  throw new Error(`MCP Server script path not found for ${this.serverName}. Root: ${root}, Available dirs: ${getDirectories(root).join(", ")}`);
@@ -8215,7 +8628,7 @@ var MCPClient = class {
8215
8628
  }
8216
8629
  };
8217
8630
  await this.mcp.connect(this.transport);
8218
- await new Promise((resolve) => setTimeout(resolve, 100));
8631
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
8219
8632
  const toolsResult = await this.mcp.listTools();
8220
8633
  this.tools = toolsResult.tools.map((tool) => {
8221
8634
  return {
@@ -8398,7 +8811,7 @@ var ServerLlmBackend = class {
8398
8811
  */
8399
8812
  async complete(model, messages, options, callback) {
8400
8813
  logger.debug(`[ServerLlmBackend] Starting complete() with model: ${model}`);
8401
- return new Promise(async (resolve, reject) => {
8814
+ return new Promise(async (resolve3, reject) => {
8402
8815
  try {
8403
8816
  logger.debug("[ServerLlmBackend] Making streaming request...");
8404
8817
  const response = await this.makeStreamingRequest(model, messages, options);
@@ -8428,15 +8841,15 @@ var ServerLlmBackend = class {
8428
8841
  reject(err);
8429
8842
  }).then(() => {
8430
8843
  logger.debug("[ServerLlmBackend] Callback completed, resolving");
8431
- resolve();
8844
+ resolve3();
8432
8845
  });
8433
8846
  } else if (cleanedText) {
8434
8847
  callback([cleanedText], lastUsageInfo).catch((err) => {
8435
8848
  logger.error("[ServerLlmBackend] Callback error:", err);
8436
8849
  reject(err);
8437
- }).then(() => resolve());
8850
+ }).then(() => resolve3());
8438
8851
  } else {
8439
- resolve();
8852
+ resolve3();
8440
8853
  }
8441
8854
  return;
8442
8855
  }
@@ -8496,7 +8909,7 @@ var ServerLlmBackend = class {
8496
8909
  response.data.on("end", () => {
8497
8910
  if (!receivedDone) {
8498
8911
  logger.debug("[ServerLlmBackend] Stream ended without [DONE], resolving anyway");
8499
- resolve();
8912
+ resolve3();
8500
8913
  } else {
8501
8914
  logger.debug("[ServerLlmBackend] Stream ended, [DONE] handler will resolve");
8502
8915
  }
@@ -8760,13 +9173,10 @@ var ApiClient = class {
8760
9173
  }
8761
9174
  };
8762
9175
 
8763
- // src/index.tsx
8764
- import { isAxiosError as isAxiosError2 } from "axios";
8765
-
8766
9176
  // package.json
8767
9177
  var package_default = {
8768
9178
  name: "@bike4mind/cli",
8769
- version: "0.2.1-feat-cli-usage-command.17001+2f4ebd097",
9179
+ version: "0.2.1-feat-cli-file-reference.17023+cf6767ead",
8770
9180
  type: "module",
8771
9181
  description: "Interactive CLI tool for Bike4Mind with ReAct agents",
8772
9182
  license: "UNLICENSED",
@@ -8777,6 +9187,9 @@ var package_default = {
8777
9187
  },
8778
9188
  homepage: "https://github.com/bike4mind/lumina5#readme",
8779
9189
  bugs: "https://github.com/bike4mind/lumina5/issues",
9190
+ publishConfig: {
9191
+ access: "public"
9192
+ },
8780
9193
  keywords: [
8781
9194
  "cli",
8782
9195
  "ai",
@@ -8797,6 +9210,8 @@ var package_default = {
8797
9210
  dev: "tsx src/index.tsx",
8798
9211
  build: "tsup",
8799
9212
  typecheck: "tsc --noEmit",
9213
+ test: "vitest run",
9214
+ "test:watch": "vitest",
8800
9215
  start: "node dist/index.js",
8801
9216
  prepublishOnly: "pnpm build"
8802
9217
  },
@@ -8863,10 +9278,10 @@ var package_default = {
8863
9278
  },
8864
9279
  devDependencies: {
8865
9280
  "@bike4mind/agents": "0.1.0",
8866
- "@bike4mind/common": "2.36.1-feat-cli-usage-command.17001+2f4ebd097",
8867
- "@bike4mind/mcp": "1.19.4-feat-cli-usage-command.17001+2f4ebd097",
8868
- "@bike4mind/services": "2.29.1-feat-cli-usage-command.17001+2f4ebd097",
8869
- "@bike4mind/utils": "2.0.3-feat-cli-usage-command.17001+2f4ebd097",
9281
+ "@bike4mind/common": "2.36.1-feat-cli-file-reference.17023+cf6767ead",
9282
+ "@bike4mind/mcp": "1.19.4-feat-cli-file-reference.17023+cf6767ead",
9283
+ "@bike4mind/services": "2.29.1-feat-cli-file-reference.17023+cf6767ead",
9284
+ "@bike4mind/utils": "2.0.3-feat-cli-file-reference.17023+cf6767ead",
8870
9285
  "@types/diff": "^5.0.9",
8871
9286
  "@types/jsonwebtoken": "^9.0.4",
8872
9287
  "@types/node": "^22.9.0",
@@ -8875,16 +9290,12 @@ var package_default = {
8875
9290
  "@types/yargs": "^17.0.32",
8876
9291
  tsup: "^8.5.1",
8877
9292
  tsx: "^4.21.0",
8878
- typescript: "^5.9.3"
9293
+ typescript: "^5.9.3",
9294
+ vitest: "^3.2.4"
8879
9295
  },
8880
- gitHead: "2f4ebd097a871fe1588b568df8b89cf2e4706379"
9296
+ gitHead: "cf6767ead9e1a222e56d4b8114dfe9f9a8c2229b"
8881
9297
  };
8882
9298
 
8883
- // src/config/constants.ts
8884
- var USAGE_DAYS = 30;
8885
- var MODEL_NAME_COLUMN_WIDTH = 18;
8886
- var USAGE_CACHE_TTL = 5 * 60 * 1e3;
8887
-
8888
9299
  // src/index.tsx
8889
9300
  process.removeAllListeners("warning");
8890
9301
  process.on("warning", (warning) => {
@@ -8895,7 +9306,6 @@ process.on("warning", (warning) => {
8895
9306
  });
8896
9307
  var exitTimestamp = null;
8897
9308
  var EXIT_TIMEOUT_MS = 2e3;
8898
- var usageCache = null;
8899
9309
  function CliApp() {
8900
9310
  const { exit } = useApp();
8901
9311
  const [state, setState] = useState3({
@@ -8935,7 +9345,7 @@ function CliApp() {
8935
9345
  }
8936
9346
  await Promise.race([
8937
9347
  Promise.all(cleanupTasks),
8938
- new Promise((resolve) => setTimeout(resolve, 500))
9348
+ new Promise((resolve3) => setTimeout(resolve3, 500))
8939
9349
  // 500ms timeout
8940
9350
  ]);
8941
9351
  setTimeout(() => {
@@ -9069,9 +9479,9 @@ function CliApp() {
9069
9479
  };
9070
9480
  const permissionManager = new PermissionManager(config.trustedTools || []);
9071
9481
  const promptFn = (toolName, args, preview) => {
9072
- return new Promise((resolve) => {
9482
+ return new Promise((resolve3) => {
9073
9483
  const canBeTrusted = permissionManager.canBeTrusted(toolName);
9074
- const prompt = { toolName, args, preview, canBeTrusted, resolve };
9484
+ const prompt = { toolName, args, preview, canBeTrusted, resolve: resolve3 };
9075
9485
  setState((prev) => ({
9076
9486
  ...prev,
9077
9487
  permissionManager,
@@ -9260,7 +9670,6 @@ Available commands:
9260
9670
  /login - Authenticate with your B4M account
9261
9671
  /logout - Clear authentication and sign out
9262
9672
  /whoami - Show current authenticated user
9263
- /usage - Show credit usage and balance
9264
9673
  /save <name> - Save current session
9265
9674
  /sessions - List saved sessions
9266
9675
  /config - Show configuration
@@ -9431,114 +9840,17 @@ Tool Permissions:
9431
9840
  console.log(`Expires: ${new Date(authTokens.expiresAt).toLocaleString()}`);
9432
9841
  console.log("");
9433
9842
  break;
9434
- case "usage": {
9435
- const usageAuthTokens = await state.configStore.getAuthTokens();
9436
- if (!usageAuthTokens || new Date(usageAuthTokens.expiresAt) <= /* @__PURE__ */ new Date()) {
9437
- console.log("\nNot authenticated. Run /login to authenticate.\n");
9438
- return;
9439
- }
9440
- console.log("\nFetching usage data...");
9441
- const now = Date.now();
9442
- let currentCredits;
9443
- let transactions;
9444
- if (usageCache && now - usageCache.timestamp < USAGE_CACHE_TTL) {
9445
- currentCredits = usageCache.data.currentCredits;
9446
- transactions = usageCache.data.transactions;
9447
- console.log("(using cached data)\n");
9448
- } else {
9449
- try {
9450
- const config = await state.configStore.get();
9451
- const apiBaseURL = getApiUrl(config.apiConfig);
9452
- const apiClient = new ApiClient(apiBaseURL, state.configStore);
9453
- const [identifyResponse, transactionsResponse] = await Promise.all([
9454
- apiClient.get("/api/identify"),
9455
- apiClient.get(`/api/credits/transactions?days=${USAGE_DAYS}`)
9456
- ]);
9457
- currentCredits = identifyResponse.user.currentCredits;
9458
- transactions = transactionsResponse || [];
9459
- usageCache = {
9460
- data: { currentCredits, transactions },
9461
- timestamp: now
9462
- };
9463
- } catch (error) {
9464
- if (isAxiosError2(error)) {
9465
- if (error.response?.status === 401) {
9466
- console.log("\n\u274C Authentication failed. Run /login to re-authenticate.\n");
9467
- } else if (error.response?.status === 403) {
9468
- console.log("\n\u274C Access denied. You may not have permission to view usage data.\n");
9469
- } else if (error.response?.status === 404) {
9470
- console.log("\n\u274C Usage endpoint not available on this server.\n");
9471
- } else if (error.code === "ECONNREFUSED" || error.code === "ENOTFOUND") {
9472
- console.log("\n\u274C Cannot connect to server. Check your API configuration with /api-info\n");
9473
- } else {
9474
- console.log(`
9475
- \u274C Error fetching usage data: ${error.message}
9476
- `);
9477
- }
9478
- } else if (error instanceof Error) {
9479
- console.log(`
9480
- \u274C Error: ${error.message}
9481
- `);
9482
- } else {
9483
- console.log("\n\u274C Unexpected error fetching usage data. Please try again.\n");
9484
- }
9485
- break;
9486
- }
9487
- }
9488
- const deductTransactions = transactions.filter(
9489
- (t) => CREDIT_DEDUCT_TRANSACTION_TYPES.includes(t.type)
9490
- );
9491
- const totalCreditsUsed = deductTransactions.reduce((sum2, t) => sum2 + Math.abs(t.credits), 0);
9492
- const dailyBurnRate = Math.round(totalCreditsUsed / USAGE_DAYS);
9493
- let daysRemainingStr;
9494
- if (dailyBurnRate === 0) {
9495
- daysRemainingStr = "N/A (no usage)";
9496
- } else {
9497
- const daysRemaining = Math.floor(currentCredits / dailyBurnRate);
9498
- daysRemainingStr = `~${daysRemaining.toLocaleString()} days`;
9499
- }
9500
- const usageByModel = {};
9501
- for (const t of deductTransactions) {
9502
- const modelName = t.metadata?.modelName || ("model" in t ? t.model : null) || "Unknown";
9503
- usageByModel[modelName] = (usageByModel[modelName] || 0) + Math.abs(t.credits);
9504
- }
9505
- const sortedModels = Object.entries(usageByModel).sort((a, b) => b[1] - a[1]);
9506
- console.log("\n Credit Usage Summary");
9507
- console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n");
9508
- console.log(`Credits Balance: ${currentCredits.toLocaleString()}`);
9509
- console.log(`Daily Burn Rate: ${dailyBurnRate.toLocaleString()} credits/day`);
9510
- console.log(`Days Remaining: ${daysRemainingStr}`);
9511
- if (currentCredits === 0) {
9512
- console.log("\n\u26A0\uFE0F You have no credits remaining.");
9513
- console.log("\u{1F4A1} Visit bike4mind.io to purchase more credits.\n");
9514
- break;
9515
- }
9516
- if (sortedModels.length > 0) {
9517
- console.log(`
9518
- Usage by Model (Last ${USAGE_DAYS} days):`);
9519
- for (const [model, credits] of sortedModels) {
9520
- const percentage = totalCreditsUsed > 0 ? Math.round(credits / totalCreditsUsed * 100) : 0;
9521
- const paddedModel = model.padEnd(MODEL_NAME_COLUMN_WIDTH);
9522
- console.log(` ${paddedModel}${credits.toLocaleString()} credits (${percentage}%)`);
9523
- }
9524
- } else {
9525
- console.log(`
9526
- No usage data available for the last ${USAGE_DAYS} days.`);
9527
- }
9528
- console.log("");
9529
- break;
9530
- }
9531
9843
  default:
9532
9844
  console.log(`Unknown command: /${command}`);
9533
9845
  console.log("Type /help for available commands");
9534
9846
  }
9535
9847
  };
9536
9848
  if (initError) {
9537
- return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React10.createElement(Text9, { color: "red", bold: true }, "\u274C Initialization Error"), /* @__PURE__ */ React10.createElement(Text9, null, initError), /* @__PURE__ */ React10.createElement(Text9, { dimColor: true }, "\n", "Tip: Run /config to set up your API keys"));
9849
+ return /* @__PURE__ */ React11.createElement(Box11, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React11.createElement(Text10, { color: "red", bold: true }, "\u274C Initialization Error"), /* @__PURE__ */ React11.createElement(Text10, null, initError), /* @__PURE__ */ React11.createElement(Text10, { dimColor: true }, "\n", "Tip: Run /config to set up your API keys"));
9538
9850
  }
9539
9851
  if (state.showLoginFlow) {
9540
9852
  const loginApiUrl = getApiUrl(state.config?.apiConfig);
9541
- return /* @__PURE__ */ React10.createElement(
9853
+ return /* @__PURE__ */ React11.createElement(
9542
9854
  LoginFlow,
9543
9855
  {
9544
9856
  apiUrl: loginApiUrl,
@@ -9561,9 +9873,9 @@ No usage data available for the last ${USAGE_DAYS} days.`);
9561
9873
  );
9562
9874
  }
9563
9875
  if (!isInitialized) {
9564
- return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React10.createElement(Text9, null, "\u{1F680} Initializing..."));
9876
+ return /* @__PURE__ */ React11.createElement(Box11, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React11.createElement(Text10, null, "\u{1F680} Initializing..."));
9565
9877
  }
9566
- return /* @__PURE__ */ React10.createElement(
9878
+ return /* @__PURE__ */ React11.createElement(
9567
9879
  App,
9568
9880
  {
9569
9881
  onMessage: handleMessage,
@@ -9594,6 +9906,6 @@ var isDevMode = import.meta.url.includes("/src/") || process.env.NODE_ENV === "d
9594
9906
  if (isDevMode) {
9595
9907
  console.log("\u{1F527} Running in development mode (using TypeScript source)\n");
9596
9908
  }
9597
- render(/* @__PURE__ */ React10.createElement(CliApp, null), {
9909
+ render(/* @__PURE__ */ React11.createElement(CliApp, null), {
9598
9910
  exitOnCtrlC: false
9599
9911
  });