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

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,9 @@ 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 path2 from "path";
99
+ import { Box as Box4, Text as Text4, useInput } from "ink";
100
100
  import TextInput from "ink-text-input";
101
101
 
102
102
  // src/components/CommandAutocomplete.tsx
@@ -113,8 +113,210 @@ function CommandAutocomplete({ commands, selectedIndex }) {
113
113
  }));
114
114
  }
115
115
 
116
- // src/utils/fuzzySearch.ts
116
+ // src/components/FileAutocomplete.tsx
117
+ import React3 from "react";
118
+ import { Box as Box3, Text as Text3 } from "ink";
119
+
120
+ // src/utils/fileSearch.ts
121
+ import * as fs from "fs";
122
+ import * as path from "path";
117
123
  import Fuse from "fuse.js";
124
+ var DEFAULT_IGNORE_PATTERNS = [
125
+ "node_modules",
126
+ ".git",
127
+ ".next",
128
+ ".turbo",
129
+ "dist",
130
+ "build",
131
+ ".cache",
132
+ "coverage",
133
+ ".DS_Store",
134
+ ".env",
135
+ ".env.local",
136
+ ".env.secrets"
137
+ ];
138
+ function walkDirectory(basePath = process.cwd(), maxDepth = 5, ignorePatterns = DEFAULT_IGNORE_PATTERNS) {
139
+ const results = [];
140
+ const normalizedBase = path.resolve(basePath);
141
+ function walk(currentPath, depth) {
142
+ if (depth > maxDepth) return;
143
+ try {
144
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
145
+ for (const entry of entries) {
146
+ if (ignorePatterns.some((pattern) => entry.name === pattern || entry.name.startsWith(pattern))) {
147
+ continue;
148
+ }
149
+ const fullPath = path.join(currentPath, entry.name);
150
+ const relativePath = path.relative(normalizedBase, fullPath);
151
+ if (entry.isDirectory()) {
152
+ results.push({
153
+ path: relativePath,
154
+ isDirectory: true
155
+ });
156
+ walk(fullPath, depth + 1);
157
+ } else if (entry.isFile()) {
158
+ try {
159
+ const stats = fs.statSync(fullPath);
160
+ results.push({
161
+ path: relativePath,
162
+ isDirectory: false,
163
+ size: stats.size
164
+ });
165
+ } catch {
166
+ results.push({
167
+ path: relativePath,
168
+ isDirectory: false
169
+ });
170
+ }
171
+ }
172
+ }
173
+ } catch {
174
+ }
175
+ }
176
+ walk(normalizedBase, 0);
177
+ return results;
178
+ }
179
+ function formatFileSize(bytes) {
180
+ if (bytes < 1024) return `${bytes} B`;
181
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
182
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
183
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
184
+ }
185
+ var cachedFiles = null;
186
+ var cacheTimestamp = 0;
187
+ var CACHE_TTL_MS = 3e4;
188
+ function getCachedFiles() {
189
+ const now = Date.now();
190
+ if (!cachedFiles || now - cacheTimestamp > CACHE_TTL_MS) {
191
+ cachedFiles = walkDirectory();
192
+ cacheTimestamp = now;
193
+ }
194
+ return cachedFiles;
195
+ }
196
+ function searchFiles(query) {
197
+ const files = getCachedFiles();
198
+ if (!query || query.trim() === "") {
199
+ return files.filter((f) => !f.path.includes(path.sep)).slice(0, 20);
200
+ }
201
+ const queryDir = path.dirname(query);
202
+ let searchPool = files;
203
+ if (queryDir && queryDir !== ".") {
204
+ const normalizedDir = queryDir.replace(/\\/g, "/");
205
+ searchPool = files.filter((f) => {
206
+ const normalizedPath = f.path.replace(/\\/g, "/");
207
+ return normalizedPath.startsWith(normalizedDir + "/") || normalizedPath === normalizedDir;
208
+ });
209
+ if (searchPool.length === 0) {
210
+ searchPool = files;
211
+ }
212
+ }
213
+ const fuse2 = new Fuse(searchPool, {
214
+ keys: [{ name: "path", weight: 1 }],
215
+ threshold: 0.4,
216
+ // Allow some fuzzy matching
217
+ includeScore: true,
218
+ minMatchCharLength: 1,
219
+ // Use extended search for better path matching
220
+ useExtendedSearch: false
221
+ });
222
+ const results = fuse2.search(query);
223
+ return results.slice(0, 20).map((result) => result.item);
224
+ }
225
+ function isPathWithinCwd(filePath) {
226
+ const cwd = path.resolve(process.cwd());
227
+ const absolutePath = path.resolve(cwd, filePath);
228
+ let resolvedCwd = cwd;
229
+ let resolvedPath = absolutePath;
230
+ try {
231
+ const realCwd = fs.realpathSync.native(cwd);
232
+ if (realCwd) {
233
+ resolvedCwd = realCwd;
234
+ }
235
+ } catch {
236
+ }
237
+ try {
238
+ const realPath = fs.realpathSync.native(absolutePath);
239
+ if (realPath) {
240
+ resolvedPath = realPath;
241
+ }
242
+ } catch {
243
+ const relativePath2 = path.relative(cwd, absolutePath);
244
+ resolvedPath = path.resolve(resolvedCwd, relativePath2);
245
+ }
246
+ const normalizedCwd = resolvedCwd.toLowerCase();
247
+ const normalizedPath = resolvedPath.toLowerCase();
248
+ const isWithin = normalizedPath === normalizedCwd || normalizedPath.startsWith(normalizedCwd + path.sep);
249
+ if (!isWithin) {
250
+ return false;
251
+ }
252
+ const relativePath = path.relative(resolvedCwd, resolvedPath);
253
+ return !relativePath.startsWith("..") && !path.isAbsolute(relativePath);
254
+ }
255
+ function isBinaryFile(filePath) {
256
+ const binaryExtensions = [
257
+ ".png",
258
+ ".jpg",
259
+ ".jpeg",
260
+ ".gif",
261
+ ".bmp",
262
+ ".ico",
263
+ ".webp",
264
+ // Note: .svg is NOT included because SVG is XML text format that can be safely read
265
+ ".pdf",
266
+ ".doc",
267
+ ".docx",
268
+ ".xls",
269
+ ".xlsx",
270
+ ".ppt",
271
+ ".pptx",
272
+ ".zip",
273
+ ".tar",
274
+ ".gz",
275
+ ".rar",
276
+ ".7z",
277
+ ".exe",
278
+ ".dll",
279
+ ".so",
280
+ ".dylib",
281
+ ".bin",
282
+ ".dat",
283
+ ".mp3",
284
+ ".mp4",
285
+ ".wav",
286
+ ".avi",
287
+ ".mov",
288
+ ".mkv",
289
+ ".ttf",
290
+ ".otf",
291
+ ".woff",
292
+ ".woff2",
293
+ ".eot",
294
+ ".class",
295
+ ".pyc",
296
+ ".o",
297
+ ".obj"
298
+ ];
299
+ const ext = path.extname(filePath).toLowerCase();
300
+ return binaryExtensions.includes(ext);
301
+ }
302
+ var MAX_FILE_SIZE = 10 * 1024 * 1024;
303
+
304
+ // src/components/FileAutocomplete.tsx
305
+ function FileAutocomplete({ files, selectedIndex, query }) {
306
+ if (files.length === 0) {
307
+ return /* @__PURE__ */ React3.createElement(Box3, { marginLeft: 2, marginTop: 1 }, /* @__PURE__ */ React3.createElement(Text3, { dimColor: true }, "No matching files", query ? ` for "${query}"` : ""));
308
+ }
309
+ 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) => {
310
+ const isSelected = index === selectedIndex;
311
+ const icon = file.isDirectory ? "[folder]" : "[file] ";
312
+ const sizeDisplay = file.isDirectory ? "" : file.size !== void 0 ? ` (${formatFileSize(file.size)})` : "";
313
+ const pathDisplay = file.isDirectory ? `${file.path}/` : file.path;
314
+ 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));
315
+ }));
316
+ }
317
+
318
+ // src/utils/fuzzySearch.ts
319
+ import Fuse2 from "fuse.js";
118
320
 
119
321
  // src/config/commands.ts
120
322
  var COMMANDS = [
@@ -178,15 +380,11 @@ var COMMANDS = [
178
380
  {
179
381
  name: "trusted",
180
382
  description: "List all trusted tools"
181
- },
182
- {
183
- name: "usage",
184
- description: "Show credit usage and balance"
185
383
  }
186
384
  ];
187
385
 
188
386
  // src/utils/fuzzySearch.ts
189
- var fuse = new Fuse(COMMANDS, {
387
+ var fuse = new Fuse2(COMMANDS, {
190
388
  keys: [
191
389
  { name: "name", weight: 0.7 },
192
390
  // Prioritize command name
@@ -206,24 +404,101 @@ function searchCommands(query) {
206
404
  return results.map((result) => result.item);
207
405
  }
208
406
 
407
+ // src/utils/constants.ts
408
+ var NAME_SUFFIXES = ["jr", "sr", "ii", "iii", "iv", "v", "phd", "md", "esq"];
409
+ function isNameSuffix(value) {
410
+ return NAME_SUFFIXES.includes(value);
411
+ }
412
+
209
413
  // src/components/InputPrompt.tsx
414
+ function looksLikeFilePath(query) {
415
+ if (query === "") {
416
+ return true;
417
+ }
418
+ if (query.includes("/") || query.includes(path2.sep)) {
419
+ return true;
420
+ }
421
+ const extensionMatch = /\.(\w*)$/.exec(query);
422
+ if (extensionMatch) {
423
+ const ext = extensionMatch[1].toLowerCase();
424
+ if (ext === "") {
425
+ return true;
426
+ }
427
+ if (isNameSuffix(ext)) {
428
+ return false;
429
+ }
430
+ if (ext.length > 10) {
431
+ return false;
432
+ }
433
+ return true;
434
+ }
435
+ if (query.startsWith(".")) {
436
+ return true;
437
+ }
438
+ return false;
439
+ }
440
+ function findAtTrigger(value) {
441
+ for (let i = value.length - 1; i >= 0; i--) {
442
+ if (value[i] === "@") {
443
+ const isValid = i === 0 || value[i - 1] === " ";
444
+ if (isValid) {
445
+ const query = value.slice(i + 1);
446
+ if (query.includes(" ")) {
447
+ return null;
448
+ }
449
+ if (!looksLikeFilePath(query)) {
450
+ return null;
451
+ }
452
+ return { startIndex: i, query };
453
+ }
454
+ }
455
+ }
456
+ return null;
457
+ }
210
458
  function InputPrompt({ onSubmit, disabled = false, history = [] }) {
211
459
  const [value, setValue] = useState("");
212
460
  const [selectedIndex, setSelectedIndex] = useState(0);
213
461
  const [historyIndex, setHistoryIndex] = useState(-1);
214
462
  const [tempInput, setTempInput] = useState("");
215
463
  const [inputKey, setInputKey] = useState(0);
216
- const shouldShowAutocomplete = value.startsWith("/") && !disabled;
217
- const query = shouldShowAutocomplete ? value.slice(1) : "";
464
+ const [fileAutocomplete, setFileAutocomplete] = useState(null);
465
+ const [fileSelectedIndex, setFileSelectedIndex] = useState(0);
466
+ const shouldShowCommandAutocomplete = value.startsWith("/") && !disabled && !fileAutocomplete?.active;
467
+ const commandQuery = shouldShowCommandAutocomplete ? value.slice(1) : "";
218
468
  const filteredCommands = useMemo(() => {
219
- if (!shouldShowAutocomplete) return [];
220
- return searchCommands(query);
221
- }, [shouldShowAutocomplete, query]);
469
+ if (!shouldShowCommandAutocomplete) return [];
470
+ return searchCommands(commandQuery);
471
+ }, [shouldShowCommandAutocomplete, commandQuery]);
472
+ const filteredFiles = useMemo(() => {
473
+ if (!fileAutocomplete?.active) return [];
474
+ return searchFiles(fileAutocomplete.query);
475
+ }, [fileAutocomplete?.active, fileAutocomplete?.query]);
222
476
  useEffect(() => {
223
477
  setSelectedIndex(0);
224
478
  }, [filteredCommands]);
479
+ useEffect(() => {
480
+ setFileSelectedIndex(0);
481
+ }, [filteredFiles]);
225
482
  useInput((input, key) => {
226
- if (shouldShowAutocomplete && filteredCommands.length > 0) {
483
+ if (fileAutocomplete?.active && filteredFiles.length > 0) {
484
+ if (key.upArrow) {
485
+ setFileSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredFiles.length - 1);
486
+ return;
487
+ } else if (key.downArrow) {
488
+ setFileSelectedIndex((prev) => prev < filteredFiles.length - 1 ? prev + 1 : 0);
489
+ return;
490
+ } else if (key.tab) {
491
+ const selectedFile = filteredFiles[fileSelectedIndex];
492
+ if (selectedFile) {
493
+ insertSelectedFile(selectedFile);
494
+ }
495
+ return;
496
+ } else if (key.escape) {
497
+ setFileAutocomplete(null);
498
+ return;
499
+ }
500
+ }
501
+ if (shouldShowCommandAutocomplete && filteredCommands.length > 0) {
227
502
  if (key.upArrow) {
228
503
  setSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredCommands.length - 1);
229
504
  } else if (key.downArrow) {
@@ -231,7 +506,7 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
231
506
  }
232
507
  return;
233
508
  }
234
- if (!shouldShowAutocomplete && history.length > 0) {
509
+ if (!shouldShowCommandAutocomplete && !fileAutocomplete?.active && history.length > 0) {
235
510
  if (key.upArrow) {
236
511
  if (historyIndex === -1) {
237
512
  setTempInput(value);
@@ -254,9 +529,35 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
254
529
  }
255
530
  }
256
531
  });
532
+ const insertSelectedFile = (file) => {
533
+ if (!fileAutocomplete) return;
534
+ const beforeAt = value.slice(0, fileAutocomplete.startIndex);
535
+ const afterQuery = value.slice(fileAutocomplete.startIndex + 1 + fileAutocomplete.query.length);
536
+ const pathToInsert = file.isDirectory ? `@${file.path}/` : `@${file.path}`;
537
+ const newValue = beforeAt + pathToInsert + afterQuery;
538
+ setValue(newValue);
539
+ setInputKey((prev) => prev + 1);
540
+ if (file.isDirectory) {
541
+ setFileAutocomplete({
542
+ active: true,
543
+ startIndex: fileAutocomplete.startIndex,
544
+ query: file.path + "/"
545
+ });
546
+ setFileSelectedIndex(0);
547
+ } else {
548
+ setFileAutocomplete(null);
549
+ }
550
+ };
257
551
  const handleSubmit = (input) => {
258
552
  if (disabled || !input.trim()) return;
259
- if (shouldShowAutocomplete && filteredCommands.length > 0) {
553
+ if (fileAutocomplete?.active && filteredFiles.length > 0) {
554
+ const selectedFile = filteredFiles[fileSelectedIndex];
555
+ if (selectedFile) {
556
+ insertSelectedFile(selectedFile);
557
+ }
558
+ return;
559
+ }
560
+ if (shouldShowCommandAutocomplete && filteredCommands.length > 0) {
260
561
  const selectedCommand = filteredCommands[selectedIndex];
261
562
  const commandText = `/${selectedCommand.name}`;
262
563
  if (selectedCommand.args) {
@@ -273,6 +574,7 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
273
574
  onSubmit(input);
274
575
  setValue("");
275
576
  setHistoryIndex(-1);
577
+ setFileAutocomplete(null);
276
578
  };
277
579
  const handleChange = (newValue) => {
278
580
  setValue(newValue);
@@ -280,30 +582,40 @@ function InputPrompt({ onSubmit, disabled = false, history = [] }) {
280
582
  setHistoryIndex(-1);
281
583
  setTempInput("");
282
584
  }
585
+ const atTrigger = findAtTrigger(newValue);
586
+ if (atTrigger) {
587
+ setFileAutocomplete({
588
+ active: true,
589
+ startIndex: atTrigger.startIndex,
590
+ query: atTrigger.query
591
+ });
592
+ } else {
593
+ setFileAutocomplete(null);
594
+ }
283
595
  };
284
- return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column" }, /* @__PURE__ */ React3.createElement(Box3, null, /* @__PURE__ */ React3.createElement(Text3, { bold: true, color: "cyan" }, "> "), /* @__PURE__ */ React3.createElement(
596
+ return /* @__PURE__ */ React4.createElement(Box4, { flexDirection: "column" }, /* @__PURE__ */ React4.createElement(Box4, null, /* @__PURE__ */ React4.createElement(Text4, { bold: true, color: "cyan" }, "> "), /* @__PURE__ */ React4.createElement(
285
597
  TextInput,
286
598
  {
287
599
  key: inputKey,
288
600
  value,
289
601
  onChange: handleChange,
290
602
  onSubmit: handleSubmit,
291
- placeholder: disabled ? "Thinking..." : "Type your message or /help for commands",
603
+ placeholder: disabled ? "Thinking..." : "Type your message, /help for commands, or @file to reference",
292
604
  showCursor: !disabled
293
605
  }
294
- )), shouldShowAutocomplete && /* @__PURE__ */ React3.createElement(CommandAutocomplete, { commands: filteredCommands, selectedIndex }));
606
+ )), shouldShowCommandAutocomplete && /* @__PURE__ */ React4.createElement(CommandAutocomplete, { commands: filteredCommands, selectedIndex }), fileAutocomplete?.active && /* @__PURE__ */ React4.createElement(FileAutocomplete, { files: filteredFiles, selectedIndex: fileSelectedIndex, query: fileAutocomplete.query }));
295
607
  }
296
608
 
297
609
  // src/components/AgentThinking.tsx
298
- import React5 from "react";
299
- import { Box as Box5 } from "ink";
610
+ import React6 from "react";
611
+ import { Box as Box6 } from "ink";
300
612
 
301
613
  // src/components/ThoughtStream.tsx
302
- import React4 from "react";
303
- import { Box as Box4, Text as Text4 } from "ink";
614
+ import React5 from "react";
615
+ import { Box as Box5, Text as Text5 } from "ink";
304
616
  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...")));
617
+ var ThoughtStream = React5.memo(function ThoughtStream2({ steps }) {
618
+ 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
619
  });
308
620
 
309
621
  // src/store/index.ts
@@ -329,32 +641,32 @@ var useCliStore = create((set) => ({
329
641
  }));
330
642
 
331
643
  // src/components/AgentThinking.tsx
332
- var AgentThinking = React5.memo(function AgentThinking2() {
644
+ var AgentThinking = React6.memo(function AgentThinking2() {
333
645
  const isThinking = useCliStore((state) => state.isThinking);
334
646
  const agentSteps = useCliStore((state) => state.agentSteps);
335
647
  if (!isThinking) {
336
648
  return null;
337
649
  }
338
- return /* @__PURE__ */ React5.createElement(Box5, { borderStyle: "single", borderColor: "yellow", paddingX: 1, marginY: 1 }, /* @__PURE__ */ React5.createElement(ThoughtStream, { steps: agentSteps }));
650
+ return /* @__PURE__ */ React6.createElement(Box6, { borderStyle: "single", borderColor: "yellow", paddingX: 1, marginY: 1 }, /* @__PURE__ */ React6.createElement(ThoughtStream, { steps: agentSteps }));
339
651
  });
340
652
 
341
653
  // src/components/PermissionPrompt.tsx
342
- import React6 from "react";
343
- import { Box as Box6, Text as Text5 } from "ink";
654
+ import React7 from "react";
655
+ import { Box as Box7, Text as Text6 } from "ink";
344
656
  import SelectInput from "ink-select-input";
345
657
  function renderDiffPreview(preview) {
346
658
  const lines = preview.split("\n");
347
659
  return lines.map((line, index) => {
348
660
  if (line.startsWith("+")) {
349
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, color: "green" }, line);
661
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, color: "green" }, line);
350
662
  }
351
663
  if (line.startsWith("-")) {
352
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, color: "red" }, line);
664
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, color: "red" }, line);
353
665
  }
354
666
  if (line.startsWith("@@")) {
355
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, color: "cyan" }, line);
667
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, color: "cyan" }, line);
356
668
  }
357
- return /* @__PURE__ */ React6.createElement(Text5, { key: index, dimColor: true }, line);
669
+ return /* @__PURE__ */ React7.createElement(Text6, { key: index, dimColor: true }, line);
358
670
  });
359
671
  }
360
672
  function PermissionPrompt({
@@ -374,7 +686,113 @@ function PermissionPrompt({
374
686
  { label: "\u2717 Deny", value: "deny" }
375
687
  ];
376
688
  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) })));
689
+ 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) })));
690
+ }
691
+
692
+ // src/utils/processFileReferences.ts
693
+ import * as fs2 from "fs";
694
+ import * as path3 from "path";
695
+ var FILE_REFERENCE_REGEX = /(?:^|\s)@([^\s@]+)/g;
696
+ function looksLikeFilePath2(ref) {
697
+ if (ref.includes("/") || ref.includes(path3.sep)) {
698
+ return true;
699
+ }
700
+ const extensionMatch = /\.(\w+)$/.exec(ref);
701
+ if (extensionMatch) {
702
+ const ext = extensionMatch[1].toLowerCase();
703
+ if (isNameSuffix(ext)) {
704
+ return false;
705
+ }
706
+ if (ext.length > 10) {
707
+ return false;
708
+ }
709
+ return true;
710
+ }
711
+ return false;
712
+ }
713
+ function extractFileReferences(message) {
714
+ const references = [];
715
+ const regex = /(?:^|\s)@([^\s@]+)/g;
716
+ let match;
717
+ while ((match = regex.exec(message)) !== null) {
718
+ const ref = match[1];
719
+ if (looksLikeFilePath2(ref)) {
720
+ references.push(ref);
721
+ }
722
+ }
723
+ return references;
724
+ }
725
+ function readFileContents(filePath) {
726
+ const cwd = process.cwd();
727
+ const absolutePath = path3.resolve(cwd, filePath);
728
+ if (!isPathWithinCwd(filePath)) {
729
+ return { error: `Security: Path "${filePath}" is outside the current working directory` };
730
+ }
731
+ if (!fs2.existsSync(absolutePath)) {
732
+ return { error: `File not found: "${filePath}"` };
733
+ }
734
+ const stats = fs2.statSync(absolutePath);
735
+ if (stats.isDirectory()) {
736
+ try {
737
+ const entries = fs2.readdirSync(absolutePath);
738
+ const fileCount = entries.length;
739
+ return {
740
+ content: `(Directory with ${fileCount} items. Use file tools to explore if needed.)`,
741
+ size: 0
742
+ };
743
+ } catch (err) {
744
+ return { error: `Cannot read directory "${filePath}": ${err instanceof Error ? err.message : "Unknown error"}` };
745
+ }
746
+ }
747
+ if (stats.size > MAX_FILE_SIZE) {
748
+ return {
749
+ error: `File too large: "${filePath}" is ${formatFileSize(stats.size)} (max ${formatFileSize(MAX_FILE_SIZE)})`
750
+ };
751
+ }
752
+ if (isBinaryFile(filePath)) {
753
+ return { error: `Binary file: "${filePath}" cannot be included as text content` };
754
+ }
755
+ try {
756
+ const content = fs2.readFileSync(absolutePath, "utf-8");
757
+ return { content, size: stats.size };
758
+ } catch (err) {
759
+ return { error: `Cannot read file "${filePath}": ${err instanceof Error ? err.message : "Unknown error"}` };
760
+ }
761
+ }
762
+ function formatFileBlock(filePath, content, size, isDirectory) {
763
+ if (isDirectory) {
764
+ return `
765
+ --- Directory Reference: ${filePath} ---
766
+ ${content}
767
+ --- End of ${filePath} ---`;
768
+ }
769
+ return `
770
+ --- Referenced File: ${filePath} (${formatFileSize(size)}) ---
771
+ ${content}
772
+ --- End of ${filePath} ---`;
773
+ }
774
+ async function processFileReferences(message) {
775
+ const references = extractFileReferences(message);
776
+ const errors = [];
777
+ const fileBlocks = [];
778
+ for (const ref of references) {
779
+ const result = readFileContents(ref);
780
+ if ("error" in result) {
781
+ errors.push(result.error);
782
+ continue;
783
+ }
784
+ const isDirectory = result.size === 0 && result.content.startsWith("(Directory");
785
+ fileBlocks.push(formatFileBlock(ref, result.content, result.size, isDirectory));
786
+ }
787
+ if (fileBlocks.length === 0) {
788
+ return { content: message, errors };
789
+ }
790
+ const processedContent = message + "\n" + fileBlocks.join("\n");
791
+ return { content: processedContent, errors };
792
+ }
793
+ function hasFileReferences(message) {
794
+ FILE_REFERENCE_REGEX.lastIndex = 0;
795
+ return FILE_REFERENCE_REGEX.test(message);
378
796
  }
379
797
 
380
798
  // src/components/App.tsx
@@ -387,7 +805,7 @@ function App({ onMessage, onCommand, onPermissionResponse, commandHistory = [] }
387
805
  const permissionPrompt = useCliStore((state) => state.permissionPrompt);
388
806
  const exitRequested = useCliStore((state) => state.exitRequested);
389
807
  const setIsThinking = useCliStore((state) => state.setIsThinking);
390
- const handleSubmit = React7.useCallback(
808
+ const handleSubmit = React8.useCallback(
391
809
  async (input) => {
392
810
  const trimmed = input.trim();
393
811
  if (!trimmed) return;
@@ -398,14 +816,25 @@ function App({ onMessage, onCommand, onPermissionResponse, commandHistory = [] }
398
816
  }
399
817
  setIsThinking(true);
400
818
  try {
401
- await onMessage(trimmed);
819
+ let messageToSend = trimmed;
820
+ if (hasFileReferences(trimmed)) {
821
+ const processed = await processFileReferences(trimmed);
822
+ messageToSend = processed.content;
823
+ if (processed.errors.length > 0) {
824
+ const errorBlock = processed.errors.map((e) => `[Warning: ${e}]`).join("\n");
825
+ messageToSend = `${messageToSend}
826
+
827
+ ${errorBlock}`;
828
+ }
829
+ }
830
+ await onMessage(messageToSend);
402
831
  } finally {
403
832
  setIsThinking(false);
404
833
  }
405
834
  },
406
835
  [onMessage, onCommand, setIsThinking]
407
836
  );
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(
837
+ 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
838
  PermissionPrompt,
410
839
  {
411
840
  toolName: permissionPrompt.toolName,
@@ -414,39 +843,39 @@ function App({ onMessage, onCommand, onPermissionResponse, commandHistory = [] }
414
843
  canBeTrusted: permissionPrompt.canBeTrusted,
415
844
  onResponse: onPermissionResponse
416
845
  }
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 }))));
846
+ )) : /* @__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
847
  }
419
848
  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) => {
849
+ 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
850
  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 ? "..." : ""}`));
851
+ 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
852
  }
424
853
  if (step.type === "action") {
425
854
  const toolName = step.metadata?.toolName || "unknown";
426
855
  const toolInput = step.metadata?.toolInput;
427
856
  const observationStep = message.metadata.steps[idx + 1];
428
857
  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 ? "..." : ""}`));
858
+ 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
859
  }
431
860
  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`)));
861
+ }).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
862
  }
434
863
 
435
864
  // src/components/MessageList.tsx
436
- import React8 from "react";
437
- import { Box as Box8, Text as Text7 } from "ink";
865
+ import React9 from "react";
866
+ import { Box as Box9, Text as Text8 } from "ink";
438
867
  function stripThinkingTags(content) {
439
868
  return content.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
440
869
  }
441
- var MessageList = React8.memo(
870
+ var MessageList = React9.memo(
442
871
  function MessageList2({ messages }) {
443
872
  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!"));
873
+ return /* @__PURE__ */ React9.createElement(Box9, { paddingY: 1 }, /* @__PURE__ */ React9.createElement(Text8, { dimColor: true }, "No messages yet. Type a message to start!"));
445
874
  }
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) => {
875
+ 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
876
  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,
877
+ 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(
878
+ Text8,
450
879
  {
451
880
  dimColor: true
452
881
  },
@@ -458,10 +887,10 @@ var MessageList = React8.memo(
458
887
  const toolInput = step.metadata?.toolInput;
459
888
  const observationStep = message.metadata.steps[idx + 1];
460
889
  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 ? "..." : ""}`));
890
+ 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
891
  }
463
892
  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`)))));
893
+ }).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
894
  },
466
895
  (prevProps, nextProps) => {
467
896
  if (prevProps.messages.length !== nextProps.messages.length) {
@@ -472,8 +901,8 @@ var MessageList = React8.memo(
472
901
  );
473
902
 
474
903
  // 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";
904
+ import React10, { useState as useState2, useEffect as useEffect2 } from "react";
905
+ import { Box as Box10, Text as Text9 } from "ink";
477
906
  import Spinner2 from "ink-spinner";
478
907
  import jwt from "jsonwebtoken";
479
908
  import open from "open";
@@ -583,7 +1012,7 @@ var OAuthClient = class {
583
1012
  * Sleep for specified milliseconds
584
1013
  */
585
1014
  sleep(ms) {
586
- return new Promise((resolve) => setTimeout(resolve, ms));
1015
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
587
1016
  }
588
1017
  };
589
1018
 
@@ -636,31 +1065,31 @@ function LoginFlow({ apiUrl = "http://localhost:3000", configStore, onSuccess, o
636
1065
  }
637
1066
  }, [deviceFlow, status]);
638
1067
  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...")));
1068
+ 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
1069
  }
641
1070
  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)));
1071
+ 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
1072
  }
644
1073
  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.")));
1074
+ 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
1075
  }
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")));
1076
+ 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
1077
  }
649
1078
 
650
1079
  // src/storage/SessionStore.ts
651
- import { promises as fs } from "fs";
652
- import path from "path";
1080
+ import { promises as fs3 } from "fs";
1081
+ import path4 from "path";
653
1082
  import { homedir } from "os";
654
1083
  var SessionStore = class {
655
1084
  constructor(basePath) {
656
- this.basePath = basePath || path.join(homedir(), ".bike4mind", "sessions");
1085
+ this.basePath = basePath || path4.join(homedir(), ".bike4mind", "sessions");
657
1086
  }
658
1087
  /**
659
1088
  * Initialize storage directory
660
1089
  */
661
1090
  async init() {
662
1091
  try {
663
- await fs.mkdir(this.basePath, { recursive: true });
1092
+ await fs3.mkdir(this.basePath, { recursive: true });
664
1093
  } catch (error) {
665
1094
  console.error("Failed to initialize session storage:", error);
666
1095
  throw error;
@@ -671,9 +1100,9 @@ var SessionStore = class {
671
1100
  */
672
1101
  async save(session) {
673
1102
  await this.init();
674
- const filePath = path.join(this.basePath, `${session.id}.json`);
1103
+ const filePath = path4.join(this.basePath, `${session.id}.json`);
675
1104
  try {
676
- await fs.writeFile(filePath, JSON.stringify(session, null, 2), "utf-8");
1105
+ await fs3.writeFile(filePath, JSON.stringify(session, null, 2), "utf-8");
677
1106
  } catch (error) {
678
1107
  console.error("Failed to save session:", error);
679
1108
  throw error;
@@ -683,9 +1112,9 @@ var SessionStore = class {
683
1112
  * Load a session from disk by ID
684
1113
  */
685
1114
  async load(id) {
686
- const filePath = path.join(this.basePath, `${id}.json`);
1115
+ const filePath = path4.join(this.basePath, `${id}.json`);
687
1116
  try {
688
- const data = await fs.readFile(filePath, "utf-8");
1117
+ const data = await fs3.readFile(filePath, "utf-8");
689
1118
  return JSON.parse(data);
690
1119
  } catch (error) {
691
1120
  if (error.code === "ENOENT") {
@@ -709,12 +1138,12 @@ var SessionStore = class {
709
1138
  async list() {
710
1139
  await this.init();
711
1140
  try {
712
- const files = await fs.readdir(this.basePath);
1141
+ const files = await fs3.readdir(this.basePath);
713
1142
  const jsonFiles = files.filter((f) => f.endsWith(".json"));
714
1143
  const sessions = await Promise.all(
715
1144
  jsonFiles.map(async (file) => {
716
- const filePath = path.join(this.basePath, file);
717
- const data = await fs.readFile(filePath, "utf-8");
1145
+ const filePath = path4.join(this.basePath, file);
1146
+ const data = await fs3.readFile(filePath, "utf-8");
718
1147
  return JSON.parse(data);
719
1148
  })
720
1149
  );
@@ -728,9 +1157,9 @@ var SessionStore = class {
728
1157
  * Delete a session
729
1158
  */
730
1159
  async delete(id) {
731
- const filePath = path.join(this.basePath, `${id}.json`);
1160
+ const filePath = path4.join(this.basePath, `${id}.json`);
732
1161
  try {
733
- await fs.unlink(filePath);
1162
+ await fs3.unlink(filePath);
734
1163
  return true;
735
1164
  } catch (error) {
736
1165
  if (error.code === "ENOENT") {
@@ -766,8 +1195,8 @@ var SessionStore = class {
766
1195
  };
767
1196
 
768
1197
  // src/storage/ConfigStore.ts
769
- import { promises as fs2 } from "fs";
770
- import path2 from "path";
1198
+ import { promises as fs4 } from "fs";
1199
+ import path5 from "path";
771
1200
  import { homedir as homedir2 } from "os";
772
1201
  import { v4 as uuidv4 } from "uuid";
773
1202
  import { z } from "zod";
@@ -841,15 +1270,15 @@ var DEFAULT_CONFIG = {
841
1270
  var ConfigStore = class {
842
1271
  constructor(configPath) {
843
1272
  this.config = null;
844
- this.configPath = configPath || path2.join(homedir2(), ".bike4mind", "config.json");
1273
+ this.configPath = configPath || path5.join(homedir2(), ".bike4mind", "config.json");
845
1274
  }
846
1275
  /**
847
1276
  * Initialize config directory
848
1277
  */
849
1278
  async init() {
850
- const dir = path2.dirname(this.configPath);
1279
+ const dir = path5.dirname(this.configPath);
851
1280
  try {
852
- await fs2.mkdir(dir, { recursive: true });
1281
+ await fs4.mkdir(dir, { recursive: true });
853
1282
  } catch (error) {
854
1283
  console.error("Failed to initialize config directory:", error);
855
1284
  throw error;
@@ -864,15 +1293,15 @@ var ConfigStore = class {
864
1293
  }
865
1294
  try {
866
1295
  try {
867
- const stats = await fs2.stat(this.configPath);
1296
+ const stats = await fs4.stat(this.configPath);
868
1297
  const mode = stats.mode & 511;
869
1298
  if (mode !== 384) {
870
1299
  console.warn(`\u26A0\uFE0F Config file has insecure permissions (${mode.toString(8)}). Setting to 0600...`);
871
- await fs2.chmod(this.configPath, 384);
1300
+ await fs4.chmod(this.configPath, 384);
872
1301
  }
873
1302
  } catch (statError) {
874
1303
  }
875
- const data = await fs2.readFile(this.configPath, "utf-8");
1304
+ const data = await fs4.readFile(this.configPath, "utf-8");
876
1305
  const rawConfig = JSON.parse(data);
877
1306
  if (rawConfig.apiConfig && "environment" in rawConfig.apiConfig) {
878
1307
  const oldApiConfig = rawConfig.apiConfig;
@@ -945,8 +1374,8 @@ var ConfigStore = class {
945
1374
  throw new Error("No configuration to save");
946
1375
  }
947
1376
  try {
948
- await fs2.writeFile(this.configPath, JSON.stringify(this.config, null, 2), "utf-8");
949
- await fs2.chmod(this.configPath, 384);
1377
+ await fs4.writeFile(this.configPath, JSON.stringify(this.config, null, 2), "utf-8");
1378
+ await fs4.chmod(this.configPath, 384);
950
1379
  } catch (error) {
951
1380
  console.error("Failed to save config:", error);
952
1381
  throw error;
@@ -1093,22 +1522,22 @@ var ConfigStore = class {
1093
1522
  };
1094
1523
 
1095
1524
  // src/storage/CommandHistoryStore.ts
1096
- import { promises as fs3 } from "fs";
1097
- import path3 from "path";
1525
+ import { promises as fs5 } from "fs";
1526
+ import path6 from "path";
1098
1527
  import { homedir as homedir3 } from "os";
1099
1528
  var MAX_HISTORY_ENTRIES = 1e3;
1100
1529
  var CommandHistoryStore = class {
1101
1530
  constructor(historyPath) {
1102
1531
  this.history = null;
1103
- this.historyPath = historyPath || path3.join(homedir3(), ".bike4mind", "history.jsonl");
1532
+ this.historyPath = historyPath || path6.join(homedir3(), ".bike4mind", "history.jsonl");
1104
1533
  }
1105
1534
  /**
1106
1535
  * Initialize history directory
1107
1536
  */
1108
1537
  async init() {
1109
- const dir = path3.dirname(this.historyPath);
1538
+ const dir = path6.dirname(this.historyPath);
1110
1539
  try {
1111
- await fs3.mkdir(dir, { recursive: true });
1540
+ await fs5.mkdir(dir, { recursive: true });
1112
1541
  } catch (error) {
1113
1542
  console.error("Failed to initialize history directory:", error);
1114
1543
  throw error;
@@ -1123,7 +1552,7 @@ var CommandHistoryStore = class {
1123
1552
  return this.history;
1124
1553
  }
1125
1554
  try {
1126
- const data = await fs3.readFile(this.historyPath, "utf-8");
1555
+ const data = await fs5.readFile(this.historyPath, "utf-8");
1127
1556
  const lines = data.trim().split("\n").filter((line) => line.length > 0);
1128
1557
  const entries = lines.map((line) => {
1129
1558
  try {
@@ -1160,7 +1589,7 @@ var CommandHistoryStore = class {
1160
1589
  };
1161
1590
  await this.init();
1162
1591
  const line = JSON.stringify(entry) + "\n";
1163
- await fs3.appendFile(this.historyPath, line, "utf-8");
1592
+ await fs5.appendFile(this.historyPath, line, "utf-8");
1164
1593
  this.history = [command, ...this.history || []];
1165
1594
  if (this.history.length > MAX_HISTORY_ENTRIES) {
1166
1595
  await this.trim();
@@ -1183,7 +1612,7 @@ var CommandHistoryStore = class {
1183
1612
  };
1184
1613
  return JSON.stringify(entry);
1185
1614
  }).join("\n");
1186
- await fs3.writeFile(this.historyPath, lines + "\n", "utf-8");
1615
+ await fs5.writeFile(this.historyPath, lines + "\n", "utf-8");
1187
1616
  this.history = trimmedCommands;
1188
1617
  }
1189
1618
  /**
@@ -1191,7 +1620,7 @@ var CommandHistoryStore = class {
1191
1620
  */
1192
1621
  async clear() {
1193
1622
  try {
1194
- await fs3.unlink(this.historyPath);
1623
+ await fs5.unlink(this.historyPath);
1195
1624
  } catch (error) {
1196
1625
  if (error.code !== "ENOENT") {
1197
1626
  throw error;
@@ -1965,7 +2394,7 @@ import { GoogleGenerativeAI } from "@google/generative-ai";
1965
2394
  import OpenAI2 from "openai";
1966
2395
 
1967
2396
  // ../../b4m-core/packages/services/dist/src/importHistoryService/index.js
1968
- import fs4, { unlinkSync } from "fs";
2397
+ import fs6, { unlinkSync } from "fs";
1969
2398
  import yauzl from "yauzl";
1970
2399
  import axios3 from "axios";
1971
2400
 
@@ -2572,190 +3001,196 @@ var listFabFilesBySessionSchema = z90.object({
2572
3001
  sessionId: z90.string()
2573
3002
  });
2574
3003
 
2575
- // ../../b4m-core/packages/services/dist/src/fabFileService/createByUrl.js
3004
+ // ../../b4m-core/packages/services/dist/src/fabFileService/listByQuest.js
2576
3005
  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,})).+/)
3006
+ var listFabFilesByQuestSchema = z91.object({
3007
+ questId: z91.string()
2579
3008
  });
2580
3009
 
2581
- // ../../b4m-core/packages/services/dist/src/fabFileService/search.js
3010
+ // ../../b4m-core/packages/services/dist/src/fabFileService/createByUrl.js
2582
3011
  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(),
3012
+ var createFabFileByUrlSchema = z92.object({
3013
+ 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,})).+/)
3014
+ });
3015
+
3016
+ // ../../b4m-core/packages/services/dist/src/fabFileService/search.js
3017
+ import { z as z93 } from "zod";
3018
+ var searchFabFilesSchema = z93.object({
3019
+ search: z93.string().optional(),
3020
+ filters: z93.object({
3021
+ tags: z93.array(z93.string()).optional(),
3022
+ type: z93.enum(["text", "pdf", "url", "image", "excel", "word", "json", "csv", "markdown", "code"]).optional(),
3023
+ shared: z93.coerce.boolean().optional(),
2589
3024
  // Indicates if the user is searching for shared files
2590
- curated: z92.coerce.boolean().optional(),
3025
+ curated: z93.coerce.boolean().optional(),
2591
3026
  // Indicates if the user is searching for curated notebook files
2592
- projectId: z92.string().optional(),
2593
- ids: z92.array(z92.string()).optional()
3027
+ projectId: z93.string().optional(),
3028
+ ids: z93.array(z93.string()).optional()
2594
3029
  // Add support for filtering by IDs
2595
3030
  }).optional(),
2596
- pagination: z92.object({
2597
- page: z92.coerce.number(),
2598
- limit: z92.coerce.number()
3031
+ pagination: z93.object({
3032
+ page: z93.coerce.number(),
3033
+ limit: z93.coerce.number()
2599
3034
  }).optional(),
2600
- order: z92.object({
2601
- by: z92.enum(["createdAt", "fileName", "fileSize"]),
2602
- direction: z92.enum(["asc", "desc"])
3035
+ order: z93.object({
3036
+ by: z93.enum(["createdAt", "fileName", "fileSize"]),
3037
+ direction: z93.enum(["asc", "desc"])
2603
3038
  }).optional(),
2604
- options: z92.object({
2605
- includeShared: z92.coerce.boolean().optional()
3039
+ options: z93.object({
3040
+ includeShared: z93.coerce.boolean().optional()
2606
3041
  }).optional()
2607
3042
  });
2608
3043
 
2609
3044
  // ../../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()
3045
+ import { z as z94 } from "zod";
3046
+ var addFavoriteParametersSchema3 = z94.object({
3047
+ fileId: z94.string()
2613
3048
  });
2614
3049
 
2615
3050
  // ../../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()
3051
+ import { z as z95 } from "zod";
3052
+ var deleteFavoriteParametersSchema4 = z95.object({
3053
+ fileId: z95.string()
2619
3054
  });
2620
3055
 
2621
3056
  // ../../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())
3057
+ import { z as z96 } from "zod";
3058
+ var fabFileToggleTagsSchema = z96.object({
3059
+ ids: z96.array(z96.string()),
3060
+ tags: z96.array(z96.string())
2626
3061
  });
2627
3062
 
2628
3063
  // ../../b4m-core/packages/services/dist/src/fabFileService/edit.js
2629
- import { z as z96 } from "zod";
3064
+ import { z as z97 } from "zod";
2630
3065
  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()
3066
+ var editFabFileSchema = z97.object({
3067
+ id: z97.string(),
3068
+ instruction: z97.string(),
3069
+ selection: z97.object({
3070
+ start: z97.number(),
3071
+ end: z97.number()
2637
3072
  }).optional(),
2638
- preserveFormatting: z96.boolean().optional().default(true),
2639
- applyImmediately: z96.boolean().optional().default(false)
3073
+ preserveFormatting: z97.boolean().optional().default(true),
3074
+ applyImmediately: z97.boolean().optional().default(false)
2640
3075
  });
2641
3076
 
2642
3077
  // ../../b4m-core/packages/services/dist/src/fabFileService/applyEdit.js
2643
3078
  import mime2 from "mime-types";
2644
3079
  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)
3080
+ import { z as z98 } from "zod";
3081
+ var applyEditSchema = z98.object({
3082
+ id: z98.string(),
3083
+ modifiedContent: z98.string(),
3084
+ createBackup: z98.boolean().optional().default(true)
2650
3085
  });
2651
3086
 
2652
3087
  // ../../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(),
3088
+ import { z as z99 } from "zod";
3089
+ var respondToFriendRequestSchema = z99.object({
3090
+ id: z99.string(),
2656
3091
  /** The user ID of the recipient of the friend request */
2657
- userId: z98.string(),
2658
- accept: z98.boolean()
3092
+ userId: z99.string(),
3093
+ accept: z99.boolean()
2659
3094
  });
2660
3095
 
2661
3096
  // ../../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(),
3097
+ import { z as z100 } from "zod";
3098
+ var unfriendSchema = z100.object({
3099
+ friendshipId: z100.string(),
2665
3100
  /** The user ID of the user who wants to unfriend the other user */
2666
- userId: z99.string()
3101
+ userId: z100.string()
2667
3102
  });
2668
3103
 
2669
3104
  // ../../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()
3105
+ import { z as z101 } from "zod";
3106
+ var listFriendsSchema = z101.object({
3107
+ userId: z101.string()
2673
3108
  });
2674
- var listPendingFriendRequestsSchema = z100.object({
2675
- userId: z100.string()
3109
+ var listPendingFriendRequestsSchema = z101.object({
3110
+ userId: z101.string()
2676
3111
  });
2677
3112
 
2678
3113
  // ../../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()
3114
+ import { z as z102 } from "zod";
3115
+ var loginAsSchema = z102.object({
3116
+ targetUserId: z102.string()
2682
3117
  });
2683
3118
 
2684
3119
  // ../../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()
3120
+ import { z as z103 } from "zod";
3121
+ var getParamsSchema = z103.object({
3122
+ key: z103.string()
2688
3123
  });
2689
3124
 
2690
3125
  // ../../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(),
3126
+ import { z as z104 } from "zod";
3127
+ var setParamsSchema = z104.object({
3128
+ key: z104.string(),
3129
+ value: z104.any(),
2695
3130
  /**
2696
3131
  * Time to live in milliseconds
2697
3132
  */
2698
- ttl: z103.number(),
2699
- recache: z103.boolean().optional()
3133
+ ttl: z104.number(),
3134
+ recache: z104.boolean().optional()
2700
3135
  });
2701
3136
 
2702
3137
  // ../../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()
3138
+ import { z as z105 } from "zod";
3139
+ var ttlParamsSchema = z105.object({
3140
+ key: z105.string()
2706
3141
  });
2707
3142
 
2708
3143
  // ../../b4m-core/packages/services/dist/src/cacheService/weeklyReports.js
2709
- import { z as z105 } from "zod";
3144
+ import { z as z106 } from "zod";
2710
3145
  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()
3146
+ var weeklyReportSchema = z106.object({
3147
+ startDate: z106.string(),
3148
+ endDate: z106.string(),
3149
+ report: z106.string(),
3150
+ aiInsights: z106.string().nullable()
2716
3151
  });
2717
3152
 
2718
3153
  // ../../b4m-core/packages/services/dist/src/embeddingCacheService/generateCacheKey.js
2719
3154
  import crypto2 from "crypto";
2720
3155
 
2721
3156
  // ../../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
3157
  import { z as z107 } from "zod";
2730
- var researchAgentUpdateSchema = z107.object({
2731
- id: z107.string(),
3158
+ var researchAgentCreateSchema = z107.object({
2732
3159
  name: z107.string().min(1),
2733
3160
  description: z107.string().min(1)
2734
3161
  });
2735
3162
 
2736
- // ../../b4m-core/packages/services/dist/src/researchAgentService/remove.js
3163
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/update.js
2737
3164
  import { z as z108 } from "zod";
2738
- var researchAgentRemoveSchema = z108.object({
2739
- id: z108.string()
3165
+ var researchAgentUpdateSchema = z108.object({
3166
+ id: z108.string(),
3167
+ name: z108.string().min(1),
3168
+ description: z108.string().min(1)
2740
3169
  });
2741
3170
 
2742
- // ../../b4m-core/packages/services/dist/src/researchAgentService/get.js
3171
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/remove.js
2743
3172
  import { z as z109 } from "zod";
2744
- var researchAgentGetSchema = z109.object({
3173
+ var researchAgentRemoveSchema = z109.object({
2745
3174
  id: z109.string()
2746
3175
  });
2747
3176
 
2748
- // ../../b4m-core/packages/services/dist/src/researchAgentService/listFiles.js
3177
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/get.js
2749
3178
  import { z as z110 } from "zod";
2750
- var researchAgentListFilesSchema = z110.object({
3179
+ var researchAgentGetSchema = z110.object({
3180
+ id: z110.string()
3181
+ });
3182
+
3183
+ // ../../b4m-core/packages/services/dist/src/researchAgentService/listFiles.js
3184
+ import { z as z111 } from "zod";
3185
+ var researchAgentListFilesSchema = z111.object({
2751
3186
  /**
2752
3187
  * The ID of the research agent
2753
3188
  */
2754
- id: z110.string()
3189
+ id: z111.string()
2755
3190
  });
2756
3191
 
2757
3192
  // ../../b4m-core/packages/services/dist/src/researchTaskService/process.js
2758
- import { z as z111 } from "zod";
3193
+ import { z as z112 } from "zod";
2759
3194
 
2760
3195
  // ../../b4m-core/packages/services/dist/src/lib/turndown.js
2761
3196
  import turndown from "turndown";
@@ -3146,316 +3581,316 @@ var deepResearchTool = {
3146
3581
  };
3147
3582
 
3148
3583
  // ../../b4m-core/packages/services/dist/src/researchTaskService/process.js
3149
- var ResearchTaskProcessSchema = z111.object({
3150
- id: z111.string()
3584
+ var ResearchTaskProcessSchema = z112.object({
3585
+ id: z112.string()
3151
3586
  });
3152
3587
 
3153
3588
  // ../../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()
3589
+ import { z as z113 } from "zod";
3590
+ var researchTaskCreateSchema = z113.object({
3591
+ researchAgentId: z113.string(),
3592
+ title: z113.string().max(100),
3593
+ description: z113.string().max(500),
3594
+ prompt: z113.string().max(500).optional(),
3595
+ type: z113.nativeEnum(ResearchTaskType),
3596
+ executionType: z113.nativeEnum(ResearchTaskExecutionType).default(ResearchTaskExecutionType.ON_DEMAND),
3597
+ fileTagId: z113.string().optional(),
3598
+ autoGeneratedTag: z113.object({
3599
+ name: z113.string(),
3600
+ icon: z113.string(),
3601
+ color: z113.string()
3167
3602
  }).optional()
3168
3603
  });
3169
3604
  var researchTaskScrapeCreateSchema = researchTaskCreateSchema.extend({
3170
- urls: z112.array(z112.string().url()).min(1),
3171
- canDiscoverLinks: z112.boolean()
3605
+ urls: z113.array(z113.string().url()).min(1),
3606
+ canDiscoverLinks: z113.boolean()
3172
3607
  });
3173
3608
  var researchTaskPeriodicCreateSchema = researchTaskCreateSchema.extend({
3174
- executionPeriodicStartAt: z112.coerce.date(),
3175
- executionPeriodicEndAt: z112.coerce.date(),
3176
- executionPeriodicFrequency: z112.nativeEnum(ResearchTaskPeriodicFrequencyType)
3609
+ executionPeriodicStartAt: z113.coerce.date(),
3610
+ executionPeriodicEndAt: z113.coerce.date(),
3611
+ executionPeriodicFrequency: z113.nativeEnum(ResearchTaskPeriodicFrequencyType)
3177
3612
  });
3178
3613
  var researchTaskScheduledCreateSchema = researchTaskCreateSchema.extend({
3179
- executionScheduledAt: z112.coerce.date()
3614
+ executionScheduledAt: z113.coerce.date()
3180
3615
  });
3181
3616
  var researchTaskDeepResearchCreateSchema = researchTaskCreateSchema.extend({
3182
- maxDepth: z112.number().min(1).max(10).optional()
3617
+ maxDepth: z113.number().min(1).max(10).optional()
3183
3618
  });
3184
3619
 
3185
3620
  // ../../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(),
3621
+ import { z as z114 } from "zod";
3622
+ var searchResearchTasksSchema = z114.object({
3623
+ search: z114.string().optional(),
3189
3624
  // ADD FILTERS SCHEMA HERE
3190
3625
  // filters: z
3191
3626
  // .object({
3192
3627
  // userId: z.string().optional(),
3193
3628
  // })
3194
3629
  // .optional(),
3195
- pagination: z113.object({
3196
- page: z113.coerce.number().optional(),
3197
- limit: z113.coerce.number().optional()
3630
+ pagination: z114.object({
3631
+ page: z114.coerce.number().optional(),
3632
+ limit: z114.coerce.number().optional()
3198
3633
  }).optional(),
3199
- orderBy: z113.object({
3200
- by: z113.enum(["createdAt", "updatedAt"]).optional(),
3201
- direction: z113.enum(["asc", "desc"]).optional()
3634
+ orderBy: z114.object({
3635
+ by: z114.enum(["createdAt", "updatedAt"]).optional(),
3636
+ direction: z114.enum(["asc", "desc"]).optional()
3202
3637
  }).optional()
3203
3638
  });
3204
3639
 
3205
3640
  // ../../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)
3641
+ import { z as z115 } from "zod";
3642
+ var getResearchTaskSchema = z115.object({
3643
+ id: z115.string().min(1)
3209
3644
  });
3210
3645
 
3211
3646
  // ../../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)
3647
+ import { z as z116 } from "zod";
3648
+ var updateResearchTaskSchema = z116.object({
3649
+ id: z116.string(),
3650
+ title: z116.string(),
3651
+ description: z116.string(),
3652
+ type: z116.nativeEnum(ResearchTaskType)
3218
3653
  });
3219
3654
  var researchTaskScrapeUpdateSchema = updateResearchTaskSchema.extend({
3220
- urls: z115.array(z115.string().url()).min(1),
3221
- canDiscoverLinks: z115.boolean()
3655
+ urls: z116.array(z116.string().url()).min(1),
3656
+ canDiscoverLinks: z116.boolean()
3222
3657
  });
3223
3658
 
3224
3659
  // ../../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()
3660
+ import { z as z117 } from "zod";
3661
+ var listByAgentIdSchema = z117.object({
3662
+ researchAgentId: z117.string()
3228
3663
  });
3229
3664
 
3230
3665
  // ../../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)
3666
+ import { z as z118 } from "zod";
3667
+ var researchTaskRemoveSchema = z118.object({
3668
+ id: z118.string().min(1)
3234
3669
  });
3235
3670
 
3236
3671
  // ../../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()
3672
+ import { z as z119 } from "zod";
3673
+ var researchTaskRetrySchema = z119.object({
3674
+ id: z119.string(),
3675
+ userId: z119.string()
3241
3676
  });
3242
3677
 
3243
3678
  // ../../b4m-core/packages/services/dist/src/researchTaskService/processDiscoveredLinks.js
3244
3679
  import axios4 from "axios";
3245
- import { z as z119 } from "zod";
3680
+ import { z as z120 } from "zod";
3246
3681
  import plimit from "p-limit";
3247
3682
  import pLimit2 from "p-limit";
3248
- var researchTaskProcessDiscoveredLinksSchema = z119.object({
3249
- id: z119.string()
3683
+ var researchTaskProcessDiscoveredLinksSchema = z120.object({
3684
+ id: z120.string()
3250
3685
  });
3251
3686
 
3252
3687
  // ../../b4m-core/packages/services/dist/src/researchTaskService/downloadRelevantLinks.js
3253
- import { z as z120 } from "zod";
3688
+ import { z as z121 } from "zod";
3254
3689
  import plimit2 from "p-limit";
3255
3690
  import axios5 from "axios";
3256
3691
  import { fileTypeFromBuffer } from "file-type";
3257
- var researchTaskDownloadRelevantLinksSchema = z120.object({
3258
- id: z120.string()
3692
+ var researchTaskDownloadRelevantLinksSchema = z121.object({
3693
+ id: z121.string()
3259
3694
  });
3260
3695
 
3261
3696
  // ../../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()
3697
+ import { z as z122 } from "zod";
3698
+ var researchDataRemoveSchema = z122.object({
3699
+ id: z122.string(),
3700
+ researchAgentId: z122.string()
3266
3701
  });
3267
3702
 
3268
3703
  // ../../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()
3704
+ import { z as z123 } from "zod";
3705
+ var researchTaskPayload = z123.object({
3706
+ id: z123.string(),
3707
+ userId: z123.string()
3273
3708
  });
3274
- var customTaskPayload = z122.object({
3275
- test: z122.string()
3709
+ var customTaskPayload = z123.object({
3710
+ test: z123.string()
3276
3711
  });
3277
- var taskSchedulerCreate = z122.discriminatedUnion("handler", [
3278
- z122.object({
3279
- handler: z122.literal(TaskScheduleHandler.RESEARCH_TASK_PROCESS),
3712
+ var taskSchedulerCreate = z123.discriminatedUnion("handler", [
3713
+ z123.object({
3714
+ handler: z123.literal(TaskScheduleHandler.RESEARCH_TASK_PROCESS),
3280
3715
  payload: researchTaskPayload,
3281
- processDate: z122.date()
3716
+ processDate: z123.date()
3282
3717
  }),
3283
- z122.object({
3284
- handler: z122.literal(TaskScheduleHandler.CUSTOM_TASK_PROCESS),
3718
+ z123.object({
3719
+ handler: z123.literal(TaskScheduleHandler.CUSTOM_TASK_PROCESS),
3285
3720
  payload: customTaskPayload,
3286
- processDate: z122.date()
3721
+ processDate: z123.date()
3287
3722
  })
3288
3723
  ]);
3289
3724
 
3290
3725
  // ../../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
3726
  import { z as z124 } from "zod";
3301
- var tagCreateSchema = z124.object({
3727
+ var tagCreateFileTagSchema = z124.object({
3302
3728
  name: z124.string(),
3303
3729
  icon: z124.string().optional(),
3304
- description: z124.string().optional(),
3305
3730
  color: z124.string().optional(),
3306
- type: z124.nativeEnum(TagType)
3731
+ description: z124.string().optional()
3307
3732
  });
3308
3733
 
3309
- // ../../b4m-core/packages/services/dist/src/tagService/update.js
3734
+ // ../../b4m-core/packages/services/dist/src/tagService/create.js
3310
3735
  import { z as z125 } from "zod";
3311
- var tagUpdateSchema = z125.object({
3312
- id: z125.string(),
3313
- name: z125.string().optional(),
3736
+ var tagCreateSchema = z125.object({
3737
+ name: z125.string(),
3314
3738
  icon: z125.string().optional(),
3315
3739
  description: z125.string().optional(),
3316
- color: z125.string().optional()
3740
+ color: z125.string().optional(),
3741
+ type: z125.nativeEnum(TagType)
3317
3742
  });
3318
3743
 
3319
- // ../../b4m-core/packages/services/dist/src/tagService/remove.js
3744
+ // ../../b4m-core/packages/services/dist/src/tagService/update.js
3320
3745
  import { z as z126 } from "zod";
3321
- var tagRemoveSchema = z126.object({
3322
- id: z126.string()
3746
+ var tagUpdateSchema = z126.object({
3747
+ id: z126.string(),
3748
+ name: z126.string().optional(),
3749
+ icon: z126.string().optional(),
3750
+ description: z126.string().optional(),
3751
+ color: z126.string().optional()
3323
3752
  });
3324
3753
 
3325
- // ../../b4m-core/packages/services/dist/src/artifactService/create.js
3754
+ // ../../b4m-core/packages/services/dist/src/tagService/remove.js
3326
3755
  import { z as z127 } from "zod";
3327
- var createArtifactSchema = z127.object({
3328
- id: z127.string().optional(),
3756
+ var tagRemoveSchema = z127.object({
3757
+ id: z127.string()
3758
+ });
3759
+
3760
+ // ../../b4m-core/packages/services/dist/src/artifactService/create.js
3761
+ import { z as z128 } from "zod";
3762
+ var createArtifactSchema = z128.object({
3763
+ id: z128.string().optional(),
3329
3764
  // 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)
3765
+ type: z128.enum(["mermaid", "recharts", "python", "react", "html", "svg", "code", "quest", "file", "questmaster"]),
3766
+ title: z128.string().min(1).max(255),
3767
+ description: z128.string().max(1e3).optional(),
3768
+ content: z128.string().min(1),
3769
+ projectId: z128.string().optional(),
3770
+ organizationId: z128.string().optional(),
3771
+ visibility: z128.enum(["private", "project", "organization", "public"]).default("private"),
3772
+ tags: z128.array(z128.string().max(50)).max(20).default([]),
3773
+ versionTag: z128.string().max(100).optional(),
3774
+ sourceQuestId: z128.string().optional(),
3775
+ sessionId: z128.string().optional(),
3776
+ parentArtifactId: z128.string().optional(),
3777
+ permissions: z128.object({
3778
+ canRead: z128.array(z128.string()).default([]),
3779
+ canWrite: z128.array(z128.string()).default([]),
3780
+ canDelete: z128.array(z128.string()).default([]),
3781
+ isPublic: z128.boolean().default(false),
3782
+ inheritFromProject: z128.boolean().default(true)
3348
3783
  }).optional(),
3349
- metadata: z127.record(z127.unknown()).default({})
3784
+ metadata: z128.record(z128.unknown()).default({})
3350
3785
  });
3351
3786
 
3352
3787
  // ../../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()
3788
+ import { z as z129 } from "zod";
3789
+ var getArtifactSchema = z129.object({
3790
+ id: z129.string(),
3791
+ includeContent: z129.boolean().default(false),
3792
+ includeVersions: z129.boolean().default(false),
3793
+ version: z129.number().optional()
3359
3794
  });
3360
3795
 
3361
3796
  // ../../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)
3797
+ import { z as z130 } from "zod";
3798
+ var listArtifactsSchema = z130.object({
3799
+ type: z130.string().optional(),
3800
+ status: z130.enum(["draft", "review", "published", "archived"]).optional(),
3801
+ visibility: z130.enum(["private", "project", "organization", "public"]).optional(),
3802
+ projectId: z130.string().optional(),
3803
+ sessionId: z130.string().optional(),
3804
+ tags: z130.array(z130.string()).optional(),
3805
+ search: z130.string().optional(),
3806
+ limit: z130.number().min(1).max(100).default(20),
3807
+ offset: z130.number().min(0).default(0),
3808
+ sortBy: z130.enum(["createdAt", "updatedAt", "title", "type"]).default("updatedAt"),
3809
+ sortOrder: z130.enum(["asc", "desc"]).default("desc"),
3810
+ includeDeleted: z130.boolean().default(false)
3376
3811
  });
3377
3812
 
3378
3813
  // ../../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()
3814
+ import { z as z131 } from "zod";
3815
+ var updateArtifactSchema = z131.object({
3816
+ id: z131.string(),
3817
+ title: z131.string().min(1).max(255).optional(),
3818
+ description: z131.string().max(1e3).optional(),
3819
+ content: z131.string().optional(),
3820
+ visibility: z131.enum(["private", "project", "organization", "public"]).optional(),
3821
+ status: z131.enum(["draft", "review", "published", "archived"]).optional(),
3822
+ tags: z131.array(z131.string().max(50)).max(20).optional(),
3823
+ versionTag: z131.string().max(100).optional(),
3824
+ permissions: z131.object({
3825
+ canRead: z131.array(z131.string()).optional(),
3826
+ canWrite: z131.array(z131.string()).optional(),
3827
+ canDelete: z131.array(z131.string()).optional(),
3828
+ isPublic: z131.boolean().optional(),
3829
+ inheritFromProject: z131.boolean().optional()
3395
3830
  }).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()
3831
+ metadata: z131.record(z131.unknown()).optional(),
3832
+ changes: z131.array(z131.string()).optional(),
3833
+ changeDescription: z131.string().max(1e3).optional(),
3834
+ createNewVersion: z131.boolean().optional(),
3835
+ versionMessage: z131.string().max(500).optional()
3401
3836
  });
3402
3837
 
3403
3838
  // ../../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)
3839
+ import { z as z132 } from "zod";
3840
+ var deleteArtifactSchema = z132.object({
3841
+ id: z132.string(),
3842
+ hardDelete: z132.boolean().default(false)
3408
3843
  // For future implementation
3409
3844
  });
3410
3845
 
3411
3846
  // ../../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)
3847
+ import { z as z133 } from "zod";
3848
+ var questSchema = z133.object({
3849
+ id: z133.string(),
3850
+ title: z133.string().min(1).max(255),
3851
+ description: z133.string().max(1e3),
3852
+ status: z133.enum(["not_started", "in_progress", "completed", "blocked"]).default("not_started"),
3853
+ order: z133.number().min(0),
3854
+ dependencies: z133.array(z133.string()).default([]),
3855
+ estimatedTime: z133.string().optional()
3856
+ });
3857
+ var questResourceSchema = z133.object({
3858
+ title: z133.string().min(1).max(255),
3859
+ url: z133.string().url(),
3860
+ type: z133.enum(["documentation", "tutorial", "reference", "example"])
3861
+ });
3862
+ var createQuestMasterSchema = z133.object({
3863
+ title: z133.string().min(1).max(255),
3864
+ description: z133.string().max(1e3).optional(),
3865
+ goal: z133.string().min(1).max(1e3),
3866
+ complexity: z133.enum(["beginner", "intermediate", "advanced", "expert"]),
3867
+ estimatedTotalTime: z133.string().optional(),
3868
+ prerequisites: z133.array(z133.string().max(200)).default([]),
3869
+ quests: z133.array(questSchema).min(1),
3870
+ resources: z133.array(questResourceSchema).default([]),
3871
+ projectId: z133.string().optional(),
3872
+ organizationId: z133.string().optional(),
3873
+ visibility: z133.enum(["private", "project", "organization", "public"]).default("private"),
3874
+ tags: z133.array(z133.string().max(50)).max(20).default([]),
3875
+ permissions: z133.object({
3876
+ canRead: z133.array(z133.string()).default([]),
3877
+ canWrite: z133.array(z133.string()).default([]),
3878
+ canDelete: z133.array(z133.string()).default([]),
3879
+ isPublic: z133.boolean().default(false),
3880
+ inheritFromProject: z133.boolean().default(true)
3446
3881
  }).optional(),
3447
- sourceQuestId: z132.string().optional(),
3448
- sessionId: z132.string().optional(),
3449
- metadata: z132.record(z132.unknown()).default({})
3882
+ sourceQuestId: z133.string().optional(),
3883
+ sessionId: z133.string().optional(),
3884
+ metadata: z133.record(z133.unknown()).default({})
3450
3885
  });
3451
3886
 
3452
3887
  // ../../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()
3888
+ import { z as z134 } from "zod";
3889
+ var updateQuestStatusSchema = z134.object({
3890
+ artifactId: z134.string(),
3891
+ questId: z134.string(),
3892
+ status: z134.enum(["not_started", "in_progress", "completed", "blocked"]),
3893
+ completionNote: z134.string().max(500).optional()
3459
3894
  });
3460
3895
 
3461
3896
  // ../../b4m-core/packages/services/dist/src/dataLakeService/opensearchClient.js
@@ -3475,63 +3910,63 @@ import { v4 as uuidv44 } from "uuid";
3475
3910
  import { randomUUID as randomUUID5 } from "crypto";
3476
3911
 
3477
3912
  // ../../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()
3913
+ import { z as z135 } from "zod";
3914
+ var processIngestedEmailOptionsSchema = z135.object({
3915
+ platformDomain: z135.string().optional(),
3916
+ isNewsletter: z135.boolean().optional()
3482
3917
  }).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(),
3918
+ var emailAttachmentSchema = z135.object({
3919
+ filename: z135.string().optional(),
3920
+ contentType: z135.string().optional(),
3921
+ contentDisposition: z135.string().optional(),
3922
+ size: z135.number().min(0),
3923
+ content: z135.instanceof(Buffer),
3924
+ related: z135.boolean().optional()
3925
+ });
3926
+ var parsedEmailObjectSchema = z135.object({
3927
+ messageId: z135.string().optional(),
3928
+ inReplyTo: z135.string().optional(),
3929
+ references: z135.union([z135.string(), z135.array(z135.string())]).optional(),
3930
+ from: z135.any().optional(),
3496
3931
  // 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({
3932
+ to: z135.any().optional(),
3933
+ cc: z135.any().optional(),
3934
+ bcc: z135.any().optional(),
3935
+ subject: z135.string().optional(),
3936
+ date: z135.date().optional(),
3937
+ text: z135.string().optional(),
3938
+ html: z135.string().optional(),
3939
+ attachments: z135.array(emailAttachmentSchema).optional()
3940
+ });
3941
+ var processIngestedEmailSchema = z135.object({
3507
3942
  parsedEmail: parsedEmailObjectSchema,
3508
- rawEmailS3Key: z134.string().min(1, "rawEmailS3Key cannot be empty"),
3943
+ rawEmailS3Key: z135.string().min(1, "rawEmailS3Key cannot be empty"),
3509
3944
  options: processIngestedEmailOptionsSchema
3510
3945
  });
3511
3946
 
3512
3947
  // ../../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([])
3948
+ import { z as z136 } from "zod";
3949
+ var llmAnalysisResponseSchema = z136.object({
3950
+ summary: z136.string().min(1, "Summary cannot be empty"),
3951
+ entities: z136.object({
3952
+ companies: z136.array(z136.string()).default([]),
3953
+ people: z136.array(z136.string()).default([]),
3954
+ products: z136.array(z136.string()).default([]),
3955
+ technologies: z136.array(z136.string()).default([])
3521
3956
  }),
3522
- sentiment: z135.enum(["positive", "neutral", "negative", "urgent"]),
3523
- actionItems: z135.array(z135.object({
3524
- description: z135.string(),
3525
- deadline: z135.string().optional()
3957
+ sentiment: z136.enum(["positive", "neutral", "negative", "urgent"]),
3958
+ actionItems: z136.array(z136.object({
3959
+ description: z136.string(),
3960
+ deadline: z136.string().optional()
3526
3961
  // ISO date string from LLM
3527
3962
  })).default([]),
3528
- privacyRecommendation: z135.enum(["public", "team", "private"]),
3529
- embargoDetected: z135.boolean().default(false),
3530
- suggestedTags: z135.array(z135.string()).default([])
3963
+ privacyRecommendation: z136.enum(["public", "team", "private"]),
3964
+ embargoDetected: z136.boolean().default(false),
3965
+ suggestedTags: z136.array(z136.string()).default([])
3531
3966
  });
3532
3967
 
3533
3968
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletion.js
3534
- import { z as z137 } from "zod";
3969
+ import { z as z138 } from "zod";
3535
3970
 
3536
3971
  // ../../b4m-core/packages/services/dist/src/llm/ChatCompletionInvoke.js
3537
3972
  import { fromZodError } from "zod-validation-error";
@@ -3645,8 +4080,8 @@ async function processAndStoreImages(images, context) {
3645
4080
  const buffer = await downloadImage(image);
3646
4081
  const fileType = await fileTypeFromBuffer2(buffer);
3647
4082
  const filename = `${uuidv45()}.${fileType?.ext}`;
3648
- const path11 = await context.imageGenerateStorage.upload(buffer, filename, {});
3649
- return path11;
4083
+ const path14 = await context.imageGenerateStorage.upload(buffer, filename, {});
4084
+ return path14;
3650
4085
  }));
3651
4086
  }
3652
4087
  async function updateQuestAndReturnMarkdown(storedImageUrls, context) {
@@ -4591,17 +5026,17 @@ var rechartsTool = {
4591
5026
  };
4592
5027
 
4593
5028
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/editFile/index.js
4594
- import { z as z136 } from "zod";
5029
+ import { z as z137 } from "zod";
4595
5030
  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")
5031
+ var editFileSchema = z137.object({
5032
+ fileId: z137.string().describe("The ID of the file to edit"),
5033
+ instruction: z137.string().describe("Natural language instruction describing the changes to make"),
5034
+ selection: z137.object({
5035
+ start: z137.number().describe("Starting character position of the selection"),
5036
+ end: z137.number().describe("Ending character position of the selection")
4602
5037
  }).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")
5038
+ preserveFormatting: z137.boolean().optional().default(true).describe("Whether to preserve the original formatting style"),
5039
+ returnDiff: z137.boolean().optional().default(true).describe("Whether to return a diff of the changes")
4605
5040
  });
4606
5041
  function generateSimpleDiff(original, modified) {
4607
5042
  const differences = diffLines2(original, modified);
@@ -4830,8 +5265,8 @@ async function processAndStoreImage(imageUrl, context) {
4830
5265
  const buffer = await downloadImage2(imageUrl);
4831
5266
  const fileType = await fileTypeFromBuffer3(buffer);
4832
5267
  const filename = `${uuidv46()}.${fileType?.ext}`;
4833
- const path11 = await context.imageGenerateStorage.upload(buffer, filename, {});
4834
- return path11;
5268
+ const path14 = await context.imageGenerateStorage.upload(buffer, filename, {});
5269
+ return path14;
4835
5270
  }
4836
5271
  async function updateQuestAndReturnMarkdown2(storedImagePath, context) {
4837
5272
  await context.onFinish?.("edit_image", storedImagePath);
@@ -6360,8 +6795,8 @@ var getHeliocentricCoords = (planet, T) => {
6360
6795
  const sinNode = Math.sin(longNode);
6361
6796
  const x = r * (cosNode * cosOmega - sinNode * sinOmega * cosI);
6362
6797
  const y = r * (sinNode * cosOmega + cosNode * sinOmega * cosI);
6363
- const z143 = r * sinOmega * sinI;
6364
- return { x, y, z: z143, r };
6798
+ const z144 = r * sinOmega * sinI;
6799
+ return { x, y, z: z144, r };
6365
6800
  };
6366
6801
  var getGeocentricEcliptic = (planet, earth) => {
6367
6802
  const dx = planet.x - earth.x;
@@ -6668,33 +7103,33 @@ var planetVisibilityTool = {
6668
7103
  };
6669
7104
 
6670
7105
  // ../../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;
7106
+ import { promises as fs7 } from "fs";
7107
+ import { existsSync as existsSync2, statSync as statSync3 } from "fs";
7108
+ import path7 from "path";
7109
+ var MAX_FILE_SIZE2 = 10 * 1024 * 1024;
6675
7110
  async function readFileContent(params) {
6676
7111
  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());
7112
+ const normalizedPath = path7.normalize(filePath);
7113
+ const resolvedPath = path7.resolve(process.cwd(), normalizedPath);
7114
+ const cwd = path7.resolve(process.cwd());
6680
7115
  if (!resolvedPath.startsWith(cwd)) {
6681
7116
  throw new Error(`Access denied: Cannot read files outside of current working directory`);
6682
7117
  }
6683
- if (!existsSync(resolvedPath)) {
7118
+ if (!existsSync2(resolvedPath)) {
6684
7119
  throw new Error(`File not found: ${filePath}`);
6685
7120
  }
6686
- const stats = statSync(resolvedPath);
7121
+ const stats = statSync3(resolvedPath);
6687
7122
  if (stats.isDirectory()) {
6688
7123
  throw new Error(`Path is a directory, not a file: ${filePath}`);
6689
7124
  }
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)`);
7125
+ if (stats.size > MAX_FILE_SIZE2) {
7126
+ throw new Error(`File too large: ${(stats.size / 1024 / 1024).toFixed(2)}MB (max ${MAX_FILE_SIZE2 / 1024 / 1024}MB)`);
6692
7127
  }
6693
7128
  const isBinary = await checkIfBinary(resolvedPath);
6694
7129
  if (isBinary && encoding === "utf-8") {
6695
7130
  throw new Error(`File appears to be binary. Use encoding 'base64' to read binary files, or specify a different encoding.`);
6696
7131
  }
6697
- const content = await fs5.readFile(resolvedPath, encoding);
7132
+ const content = await fs7.readFile(resolvedPath, encoding);
6698
7133
  if (maxLines && typeof content === "string") {
6699
7134
  const lines = content.split("\n");
6700
7135
  if (lines.length > maxLines) {
@@ -6709,7 +7144,7 @@ ${content}`;
6709
7144
  }
6710
7145
  async function checkIfBinary(filePath) {
6711
7146
  const buffer = Buffer.alloc(8192);
6712
- const fd = await fs5.open(filePath, "r");
7147
+ const fd = await fs7.open(filePath, "r");
6713
7148
  try {
6714
7149
  const { bytesRead } = await fd.read(buffer, 0, 8192, 0);
6715
7150
  const chunk = buffer.slice(0, bytesRead);
@@ -6726,7 +7161,7 @@ var fileReadTool = {
6726
7161
  context.logger.info("\u{1F4C4} FileRead: Reading file", { path: params.path });
6727
7162
  try {
6728
7163
  const content = await readFileContent(params);
6729
- const stats = statSync(path4.resolve(process.cwd(), path4.normalize(params.path)));
7164
+ const stats = statSync3(path7.resolve(process.cwd(), path7.normalize(params.path)));
6730
7165
  context.logger.info("\u2705 FileRead: Success", {
6731
7166
  path: params.path,
6732
7167
  size: stats.size,
@@ -6765,25 +7200,25 @@ var fileReadTool = {
6765
7200
  };
6766
7201
 
6767
7202
  // ../../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";
7203
+ import { promises as fs8 } from "fs";
7204
+ import { existsSync as existsSync3 } from "fs";
7205
+ import path8 from "path";
6771
7206
  async function createFile(params) {
6772
7207
  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());
7208
+ const normalizedPath = path8.normalize(filePath);
7209
+ const resolvedPath = path8.resolve(process.cwd(), normalizedPath);
7210
+ const cwd = path8.resolve(process.cwd());
6776
7211
  if (!resolvedPath.startsWith(cwd)) {
6777
7212
  throw new Error(`Access denied: Cannot create files outside of current working directory`);
6778
7213
  }
6779
- const fileExists = existsSync2(resolvedPath);
7214
+ const fileExists = existsSync3(resolvedPath);
6780
7215
  const action = fileExists ? "overwritten" : "created";
6781
7216
  if (createDirectories) {
6782
- const dir = path5.dirname(resolvedPath);
6783
- await fs6.mkdir(dir, { recursive: true });
7217
+ const dir = path8.dirname(resolvedPath);
7218
+ await fs8.mkdir(dir, { recursive: true });
6784
7219
  }
6785
- await fs6.writeFile(resolvedPath, content, "utf-8");
6786
- const stats = await fs6.stat(resolvedPath);
7220
+ await fs8.writeFile(resolvedPath, content, "utf-8");
7221
+ const stats = await fs8.stat(resolvedPath);
6787
7222
  const lines = content.split("\n").length;
6788
7223
  return `File ${action} successfully: ${filePath}
6789
7224
  Size: ${stats.size} bytes
@@ -6794,7 +7229,7 @@ var createFileTool = {
6794
7229
  implementation: (context) => ({
6795
7230
  toolFn: async (value) => {
6796
7231
  const params = value;
6797
- const fileExists = existsSync2(path5.resolve(process.cwd(), path5.normalize(params.path)));
7232
+ const fileExists = existsSync3(path8.resolve(process.cwd(), path8.normalize(params.path)));
6798
7233
  context.logger.info(`\u{1F4DD} CreateFile: ${fileExists ? "Overwriting" : "Creating"} file`, {
6799
7234
  path: params.path,
6800
7235
  size: params.content.length
@@ -6835,8 +7270,8 @@ var createFileTool = {
6835
7270
 
6836
7271
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/globFiles/index.js
6837
7272
  import { readdir } from "fs/promises";
6838
- import { statSync as statSync2 } from "fs";
6839
- import path6 from "path";
7273
+ import { statSync as statSync4 } from "fs";
7274
+ import path9 from "path";
6840
7275
  function matchGlob(filePath, pattern) {
6841
7276
  let regexPattern = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\?/g, ".").replace(/\{([^}]+)\}/g, (_, options) => `(${options.split(",").join("|")})`).replace(/\[([^\]]+)\]/g, "[$1]");
6842
7277
  regexPattern = regexPattern.replace(/\{\{GLOBSTAR\}\}\//g, "(.*/)?").replace(/\/\{\{GLOBSTAR\}\}/g, "(/.*)?").replace(/\{\{GLOBSTAR\}\}/g, ".*");
@@ -6854,8 +7289,8 @@ async function walkDir(dir, pattern, includeHidden, maxResults, basePath = "") {
6854
7289
  if (!includeHidden && entry.name.startsWith(".")) {
6855
7290
  continue;
6856
7291
  }
6857
- const relativePath = basePath ? path6.join(basePath, entry.name) : entry.name;
6858
- const fullPath = path6.join(dir, entry.name);
7292
+ const relativePath = basePath ? path9.join(basePath, entry.name) : entry.name;
7293
+ const fullPath = path9.join(dir, entry.name);
6859
7294
  if (matchGlob(relativePath, pattern)) {
6860
7295
  matches.push(relativePath);
6861
7296
  }
@@ -6871,7 +7306,7 @@ async function walkDir(dir, pattern, includeHidden, maxResults, basePath = "") {
6871
7306
  async function listFiles(params) {
6872
7307
  const { pattern, cwd: relativeCwd, includeHidden = false, maxResults = 1e3 } = params;
6873
7308
  const baseCwd = process.cwd();
6874
- const targetCwd = relativeCwd ? path6.resolve(baseCwd, path6.normalize(relativeCwd)) : baseCwd;
7309
+ const targetCwd = relativeCwd ? path9.resolve(baseCwd, path9.normalize(relativeCwd)) : baseCwd;
6875
7310
  if (!targetCwd.startsWith(baseCwd)) {
6876
7311
  throw new Error(`Access denied: Cannot list files outside of current working directory`);
6877
7312
  }
@@ -6882,8 +7317,8 @@ async function listFiles(params) {
6882
7317
  const filesInfo = [];
6883
7318
  for (const match of matches) {
6884
7319
  try {
6885
- const fullPath = path6.join(targetCwd, match);
6886
- const stats = statSync2(fullPath);
7320
+ const fullPath = path9.join(targetCwd, match);
7321
+ const stats = statSync4(fullPath);
6887
7322
  filesInfo.push({
6888
7323
  path: match,
6889
7324
  size: stats.size,
@@ -6964,9 +7399,9 @@ var globFilesTool = {
6964
7399
 
6965
7400
  // ../../b4m-core/packages/services/dist/src/llm/tools/implementation/grepSearch/index.js
6966
7401
  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;
7402
+ import { readFileSync as readFileSync2, statSync as statSync5 } from "fs";
7403
+ import path10 from "path";
7404
+ var MAX_FILE_SIZE3 = 10 * 1024 * 1024;
6970
7405
  function matchGlob2(filePath, pattern) {
6971
7406
  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
7407
  const regex = new RegExp(`^${regexPattern}$`);
@@ -6983,8 +7418,8 @@ async function walkDir2(dir, pattern, maxResults, basePath = "") {
6983
7418
  if (entry.name.startsWith(".")) {
6984
7419
  continue;
6985
7420
  }
6986
- const relativePath = basePath ? path7.join(basePath, entry.name) : entry.name;
6987
- const fullPath = path7.join(dir, entry.name);
7421
+ const relativePath = basePath ? path10.join(basePath, entry.name) : entry.name;
7422
+ const fullPath = path10.join(dir, entry.name);
6988
7423
  if (matchGlob2(relativePath, pattern)) {
6989
7424
  matches.push(relativePath);
6990
7425
  }
@@ -6997,10 +7432,10 @@ async function walkDir2(dir, pattern, maxResults, basePath = "") {
6997
7432
  }
6998
7433
  return matches;
6999
7434
  }
7000
- async function searchFiles(params) {
7435
+ async function searchFiles2(params) {
7001
7436
  const { pattern, filePattern = "**/*", cwd: relativeCwd, caseSensitive = false, maxResults = 100, contextLines = 0 } = params;
7002
7437
  const baseCwd = process.cwd();
7003
- const targetCwd = relativeCwd ? path7.resolve(baseCwd, path7.normalize(relativeCwd)) : baseCwd;
7438
+ const targetCwd = relativeCwd ? path10.resolve(baseCwd, path10.normalize(relativeCwd)) : baseCwd;
7004
7439
  if (!targetCwd.startsWith(baseCwd)) {
7005
7440
  throw new Error(`Access denied: Cannot search files outside of current working directory`);
7006
7441
  }
@@ -7014,13 +7449,13 @@ async function searchFiles(params) {
7014
7449
  const filesToSearch = await walkDir2(targetCwd, filePattern, 1e4);
7015
7450
  const filteredFiles = [];
7016
7451
  for (const match of filesToSearch) {
7017
- const fullPath = path7.join(targetCwd, match);
7452
+ const fullPath = path10.join(targetCwd, match);
7018
7453
  try {
7019
- const stats = statSync3(fullPath);
7020
- if (stats.isDirectory() || stats.size > MAX_FILE_SIZE2) {
7454
+ const stats = statSync5(fullPath);
7455
+ if (stats.isDirectory() || stats.size > MAX_FILE_SIZE3) {
7021
7456
  continue;
7022
7457
  }
7023
- if (isBinaryFile(fullPath)) {
7458
+ if (isBinaryFile2(fullPath)) {
7024
7459
  continue;
7025
7460
  }
7026
7461
  filteredFiles.push(match);
@@ -7038,9 +7473,9 @@ async function searchFiles(params) {
7038
7473
  break;
7039
7474
  }
7040
7475
  filesSearched++;
7041
- const fullPath = path7.join(targetCwd, file);
7476
+ const fullPath = path10.join(targetCwd, file);
7042
7477
  try {
7043
- const content = readFileSync(fullPath, "utf-8");
7478
+ const content = readFileSync2(fullPath, "utf-8");
7044
7479
  const lines = content.split("\n");
7045
7480
  for (let i = 0; i < lines.length; i++) {
7046
7481
  if (matches.length >= maxResults) {
@@ -7104,7 +7539,7 @@ ${match.context.after.map((l) => ` ${l}`).join("\n")}`;
7104
7539
  }).join("\n");
7105
7540
  return `${summary}${patternInfo}${cwdInfo}${matchesList}`;
7106
7541
  }
7107
- function isBinaryFile(filePath) {
7542
+ function isBinaryFile2(filePath) {
7108
7543
  try {
7109
7544
  const buffer = Buffer.alloc(8192);
7110
7545
  const fd = __require("fs").openSync(filePath, "r");
@@ -7127,7 +7562,7 @@ var grepSearchTool = {
7127
7562
  cwd: params.cwd || "."
7128
7563
  });
7129
7564
  try {
7130
- const result = await searchFiles(params);
7565
+ const result = await searchFiles2(params);
7131
7566
  context.logger.info("\u2705 GrepSearch: Success");
7132
7567
  return result;
7133
7568
  } catch (error) {
@@ -7173,31 +7608,31 @@ var grepSearchTool = {
7173
7608
  };
7174
7609
 
7175
7610
  // ../../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";
7611
+ import { promises as fs9 } from "fs";
7612
+ import { existsSync as existsSync4, statSync as statSync6 } from "fs";
7613
+ import path11 from "path";
7179
7614
  async function deleteFile(params) {
7180
7615
  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());
7616
+ const normalizedPath = path11.normalize(filePath);
7617
+ const resolvedPath = path11.resolve(process.cwd(), normalizedPath);
7618
+ const cwd = path11.resolve(process.cwd());
7184
7619
  if (!resolvedPath.startsWith(cwd)) {
7185
7620
  throw new Error(`Access denied: Cannot delete files outside of current working directory`);
7186
7621
  }
7187
- if (!existsSync3(resolvedPath)) {
7622
+ if (!existsSync4(resolvedPath)) {
7188
7623
  throw new Error(`File or directory not found: ${filePath}`);
7189
7624
  }
7190
- const stats = statSync4(resolvedPath);
7625
+ const stats = statSync6(resolvedPath);
7191
7626
  const isDirectory = stats.isDirectory();
7192
7627
  const size = stats.size;
7193
7628
  if (isDirectory && !recursive) {
7194
7629
  throw new Error(`Path is a directory: ${filePath}. Use recursive=true to delete directories and their contents.`);
7195
7630
  }
7196
7631
  if (isDirectory) {
7197
- await fs7.rm(resolvedPath, { recursive: true, force: true });
7632
+ await fs9.rm(resolvedPath, { recursive: true, force: true });
7198
7633
  return `Directory deleted successfully: ${filePath}`;
7199
7634
  } else {
7200
- await fs7.unlink(resolvedPath);
7635
+ await fs9.unlink(resolvedPath);
7201
7636
  return `File deleted successfully: ${filePath}
7202
7637
  Size: ${size} bytes`;
7203
7638
  }
@@ -7207,8 +7642,8 @@ var deleteFileTool = {
7207
7642
  implementation: (context) => ({
7208
7643
  toolFn: async (value) => {
7209
7644
  const params = value;
7210
- const resolvedPath = path8.resolve(process.cwd(), path8.normalize(params.path));
7211
- const isDirectory = existsSync3(resolvedPath) && statSync4(resolvedPath).isDirectory();
7645
+ const resolvedPath = path11.resolve(process.cwd(), path11.normalize(params.path));
7646
+ const isDirectory = existsSync4(resolvedPath) && statSync6(resolvedPath).isDirectory();
7212
7647
  context.logger.info(`\u{1F5D1}\uFE0F DeleteFile: Deleting ${isDirectory ? "directory" : "file"}`, {
7213
7648
  path: params.path,
7214
7649
  recursive: params.recursive
@@ -7386,42 +7821,42 @@ var DISABLE_SERVER_THROTTLING = process.env.DISABLE_SERVER_THROTTLING === "true"
7386
7821
  var questSaveMutex = new Mutex();
7387
7822
 
7388
7823
  // ../../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()),
7824
+ var QuestStartBodySchema = z138.object({
7825
+ userId: z138.string(),
7826
+ sessionId: z138.string(),
7827
+ questId: z138.string(),
7828
+ message: z138.string(),
7829
+ messageFileIds: z138.array(z138.string()),
7830
+ historyCount: z138.number(),
7831
+ fabFileIds: z138.array(z138.string()),
7397
7832
  params: ChatCompletionCreateInputSchema,
7398
7833
  dashboardParams: DashboardParamsSchema.optional(),
7399
- enableQuestMaster: z137.boolean().optional(),
7400
- enableMementos: z137.boolean().optional(),
7401
- enableArtifacts: z137.boolean().optional(),
7402
- enableAgents: z137.boolean().optional(),
7834
+ enableQuestMaster: z138.boolean().optional(),
7835
+ enableMementos: z138.boolean().optional(),
7836
+ enableArtifacts: z138.boolean().optional(),
7837
+ enableAgents: z138.boolean().optional(),
7403
7838
  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(),
7839
+ tools: z138.array(z138.union([b4mLLMTools, z138.string()])).optional(),
7840
+ mcpServers: z138.array(z138.string()).optional(),
7841
+ projectId: z138.string().optional(),
7842
+ organizationId: z138.string().nullable().optional(),
7408
7843
  questMaster: QuestMasterParamsSchema.optional(),
7409
- toolPromptId: z137.string().optional(),
7844
+ toolPromptId: z138.string().optional(),
7410
7845
  researchMode: ResearchModeParamsSchema.optional(),
7411
- fallbackModel: z137.string().optional(),
7412
- embeddingModel: z137.string().optional(),
7413
- queryComplexity: z137.string(),
7846
+ fallbackModel: z138.string().optional(),
7847
+ embeddingModel: z138.string().optional(),
7848
+ queryComplexity: z138.string(),
7414
7849
  imageConfig: GenerateImageToolCallSchema.optional(),
7415
- deepResearchConfig: z137.object({
7416
- maxDepth: z137.number().optional(),
7417
- duration: z137.number().optional(),
7850
+ deepResearchConfig: z138.object({
7851
+ maxDepth: z138.number().optional(),
7852
+ duration: z138.number().optional(),
7418
7853
  // Note: searchers are passed via ToolContext and not through this API schema
7419
- searchers: z137.array(z137.any()).optional()
7854
+ searchers: z138.array(z138.any()).optional()
7420
7855
  }).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()
7856
+ extraContextMessages: z138.array(z138.object({
7857
+ role: z138.enum(["user", "assistant", "system", "function", "tool"]),
7858
+ content: z138.union([z138.string(), z138.array(z138.any())]),
7859
+ fabFileIds: z138.array(z138.string()).optional()
7425
7860
  })).optional()
7426
7861
  });
7427
7862
 
@@ -7429,30 +7864,9 @@ var QuestStartBodySchema = z137.object({
7429
7864
  import axios8 from "axios";
7430
7865
  import { fileTypeFromBuffer as fileTypeFromBuffer4 } from "file-type";
7431
7866
  import { v4 as uuidv47 } from "uuid";
7432
- import { z as z138 } from "zod";
7867
+ import { z as z139 } from "zod";
7433
7868
  import { fromZodError as fromZodError2 } from "zod-validation-error";
7434
7869
  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
7870
  sessionId: z139.string(),
7457
7871
  questId: z139.string(),
7458
7872
  userId: z139.string(),
@@ -7460,35 +7874,56 @@ var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
7460
7874
  safety_tolerance: z139.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
7461
7875
  prompt_upsampling: z139.boolean().optional().default(false),
7462
7876
  seed: z139.number().nullable().optional(),
7463
- output_format: z139.enum(["jpeg", "png"]).optional().default("png"),
7877
+ output_format: z139.enum(["jpeg", "png"]).nullable().optional().default("png"),
7464
7878
  width: z139.number().optional(),
7465
7879
  height: z139.number().optional(),
7466
7880
  aspect_ratio: z139.string().optional(),
7467
- size: z139.string().optional(),
7468
- fabFileIds: z139.array(z139.string()).optional(),
7469
- image: z139.string()
7881
+ fabFileIds: z139.array(z139.string()).optional()
7470
7882
  });
7471
7883
 
7472
- // ../../b4m-core/packages/services/dist/src/llm/refineText.js
7884
+ // ../../b4m-core/packages/services/dist/src/llm/ImageEdit.js
7885
+ import axios9 from "axios";
7886
+ import { fileTypeFromBuffer as fileTypeFromBuffer5 } from "file-type";
7887
+ import { v4 as uuidv48 } from "uuid";
7473
7888
  import { z as z140 } from "zod";
7474
- var refineTextLLMSchema = z140.object({
7475
- text: z140.string(),
7476
- context: z140.string().optional()
7889
+ import { fromZodError as fromZodError3 } from "zod-validation-error";
7890
+ var ImageEditBodySchema = OpenAIImageGenerationInput.extend({
7891
+ sessionId: z140.string(),
7892
+ questId: z140.string(),
7893
+ userId: z140.string(),
7894
+ prompt: z140.string(),
7895
+ safety_tolerance: z140.number().min(BFL_SAFETY_TOLERANCE.MIN).max(BFL_SAFETY_TOLERANCE.MAX).optional().default(BFL_SAFETY_TOLERANCE.DEFAULT),
7896
+ prompt_upsampling: z140.boolean().optional().default(false),
7897
+ seed: z140.number().nullable().optional(),
7898
+ output_format: z140.enum(["jpeg", "png"]).optional().default("png"),
7899
+ width: z140.number().optional(),
7900
+ height: z140.number().optional(),
7901
+ aspect_ratio: z140.string().optional(),
7902
+ size: z140.string().optional(),
7903
+ fabFileIds: z140.array(z140.string()).optional(),
7904
+ image: z140.string()
7905
+ });
7906
+
7907
+ // ../../b4m-core/packages/services/dist/src/llm/refineText.js
7908
+ import { z as z141 } from "zod";
7909
+ var refineTextLLMSchema = z141.object({
7910
+ text: z141.string(),
7911
+ context: z141.string().optional()
7477
7912
  // tone: z.enum(['formal', 'informal', 'neutral']).optional(),
7478
7913
  // style: z.enum(['technical', 'creative', 'academic', 'business', 'narrative']).optional(),
7479
7914
  });
7480
7915
 
7481
7916
  // ../../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),
7917
+ import { z as z142 } from "zod";
7918
+ var SingleMementoEvalSchema = z142.object({
7919
+ importance: z142.number().min(1).max(10),
7485
7920
  // 1-10 scale for personal info importance
7486
- summary: z141.string(),
7487
- tags: z141.array(z141.string()).optional()
7921
+ summary: z142.string(),
7922
+ tags: z142.array(z142.string()).optional()
7488
7923
  });
7489
- var MementoEvalResponseSchema = z141.object({
7490
- isPersonal: z141.boolean(),
7491
- mementos: z141.array(SingleMementoEvalSchema).optional()
7924
+ var MementoEvalResponseSchema = z142.object({
7925
+ isPersonal: z142.boolean(),
7926
+ mementos: z142.array(SingleMementoEvalSchema).optional()
7492
7927
  // Array of distinct personal information
7493
7928
  });
7494
7929
 
@@ -7498,10 +7933,10 @@ import jwt2 from "jsonwebtoken";
7498
7933
  // src/utils/diffPreview.ts
7499
7934
  import * as Diff from "diff";
7500
7935
  import { readFile } from "fs/promises";
7501
- import { existsSync as existsSync4 } from "fs";
7936
+ import { existsSync as existsSync5 } from "fs";
7502
7937
  async function generateFileDiffPreview(args) {
7503
7938
  try {
7504
- if (!existsSync4(args.path)) {
7939
+ if (!existsSync5(args.path)) {
7505
7940
  const lines2 = args.content.split("\n");
7506
7941
  const preview = lines2.slice(0, 20).join("\n");
7507
7942
  const hasMore = lines2.length > 20;
@@ -7531,10 +7966,10 @@ ${preview}${hasMore ? `
7531
7966
  }
7532
7967
  async function generateFileDeletePreview(args) {
7533
7968
  try {
7534
- if (!existsSync4(args.path)) {
7969
+ if (!existsSync5(args.path)) {
7535
7970
  return `[File does not exist: ${args.path}]`;
7536
7971
  }
7537
- const stats = await import("fs/promises").then((fs9) => fs9.stat(args.path));
7972
+ const stats = await import("fs/promises").then((fs11) => fs11.stat(args.path));
7538
7973
  return `[File will be deleted]
7539
7974
 
7540
7975
  Path: ${args.path}
@@ -7550,21 +7985,21 @@ var NoOpStorage = class extends BaseStorage {
7550
7985
  async upload(input, destination, options) {
7551
7986
  return `/tmp/${destination}`;
7552
7987
  }
7553
- async download(path11) {
7988
+ async download(path14) {
7554
7989
  throw new Error("Download not supported in CLI");
7555
7990
  }
7556
- async delete(path11) {
7991
+ async delete(path14) {
7557
7992
  }
7558
- async getSignedUrl(path11) {
7559
- return `/tmp/${path11}`;
7993
+ async getSignedUrl(path14) {
7994
+ return `/tmp/${path14}`;
7560
7995
  }
7561
- getPublicUrl(path11) {
7562
- return `/tmp/${path11}`;
7996
+ getPublicUrl(path14) {
7997
+ return `/tmp/${path14}`;
7563
7998
  }
7564
- async getPreview(path11) {
7565
- return `/tmp/${path11}`;
7999
+ async getPreview(path14) {
8000
+ return `/tmp/${path14}`;
7566
8001
  }
7567
- async getMetadata(path11) {
8002
+ async getMetadata(path14) {
7568
8003
  return { size: 0, contentType: "application/octet-stream" };
7569
8004
  }
7570
8005
  };
@@ -7725,8 +8160,8 @@ function generateCliTools(userId, llm, model, permissionManager, showPermissionP
7725
8160
  }
7726
8161
 
7727
8162
  // src/config/toolSafety.ts
7728
- import { z as z142 } from "zod";
7729
- var ToolCategorySchema = z142.enum([
8163
+ import { z as z143 } from "zod";
8164
+ var ToolCategorySchema = z143.enum([
7730
8165
  "auto_approve",
7731
8166
  // Safe tools that run automatically without permission
7732
8167
  "prompt_always",
@@ -7734,9 +8169,9 @@ var ToolCategorySchema = z142.enum([
7734
8169
  "prompt_default"
7735
8170
  // Tools that prompt by default but can be trusted
7736
8171
  ]);
7737
- var ToolSafetyConfigSchema = z142.object({
7738
- categories: z142.record(z142.string(), ToolCategorySchema),
7739
- trustedTools: z142.array(z142.string())
8172
+ var ToolSafetyConfigSchema = z143.object({
8173
+ categories: z143.record(z143.string(), ToolCategorySchema),
8174
+ trustedTools: z143.array(z143.string())
7740
8175
  });
7741
8176
  var DEFAULT_TOOL_CATEGORIES = {
7742
8177
  // ===== AUTO APPROVE (Safe tools) =====
@@ -7890,8 +8325,8 @@ function getEnvironmentName(configApiConfig) {
7890
8325
  }
7891
8326
 
7892
8327
  // src/utils/Logger.ts
7893
- import fs8 from "fs/promises";
7894
- import path9 from "path";
8328
+ import fs10 from "fs/promises";
8329
+ import path12 from "path";
7895
8330
  import os from "os";
7896
8331
  var Logger2 = class _Logger {
7897
8332
  constructor() {
@@ -7914,9 +8349,9 @@ var Logger2 = class _Logger {
7914
8349
  */
7915
8350
  async initialize(sessionId) {
7916
8351
  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`);
8352
+ const debugDir = path12.join(os.homedir(), ".bike4mind", "debug");
8353
+ await fs10.mkdir(debugDir, { recursive: true });
8354
+ this.logFilePath = path12.join(debugDir, `${sessionId}.txt`);
7920
8355
  await this.writeToFile("INFO", "=== CLI SESSION START ===");
7921
8356
  }
7922
8357
  /**
@@ -7980,7 +8415,7 @@ var Logger2 = class _Logger {
7980
8415
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
7981
8416
  const logEntry = `[${timestamp}] [${level}] ${message}
7982
8417
  `;
7983
- await fs8.appendFile(this.logFilePath, logEntry, "utf-8");
8418
+ await fs10.appendFile(this.logFilePath, logEntry, "utf-8");
7984
8419
  } catch (error) {
7985
8420
  console.error("File logging failed:", error);
7986
8421
  }
@@ -8126,15 +8561,15 @@ var Logger2 = class _Logger {
8126
8561
  async cleanupOldLogs() {
8127
8562
  if (!this.fileLoggingEnabled) return;
8128
8563
  try {
8129
- const debugDir = path9.join(os.homedir(), ".bike4mind", "debug");
8130
- const files = await fs8.readdir(debugDir);
8564
+ const debugDir = path12.join(os.homedir(), ".bike4mind", "debug");
8565
+ const files = await fs10.readdir(debugDir);
8131
8566
  const now = Date.now();
8132
8567
  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1e3;
8133
8568
  for (const file of files) {
8134
- const filePath = path9.join(debugDir, file);
8135
- const stats = await fs8.stat(filePath);
8569
+ const filePath = path12.join(debugDir, file);
8570
+ const stats = await fs10.stat(filePath);
8136
8571
  if (stats.mtime.getTime() < thirtyDaysAgo) {
8137
- await fs8.unlink(filePath);
8572
+ await fs10.unlink(filePath);
8138
8573
  }
8139
8574
  }
8140
8575
  } catch (error) {
@@ -8147,8 +8582,8 @@ var logger = Logger2.getInstance();
8147
8582
  // ../../b4m-core/packages/mcp/dist/src/client.js
8148
8583
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
8149
8584
  import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
8150
- import path10 from "path";
8151
- import { existsSync as existsSync5, readdirSync } from "fs";
8585
+ import path13 from "path";
8586
+ import { existsSync as existsSync6, readdirSync as readdirSync3 } from "fs";
8152
8587
  var MCPClient = class {
8153
8588
  // Note: This class handles MCP server communication with repository filtering
8154
8589
  mcp;
@@ -8173,20 +8608,20 @@ var MCPClient = class {
8173
8608
  const root = process.env.INIT_CWD || process.cwd();
8174
8609
  const candidatePaths = [
8175
8610
  // When running from SST Lambda with node_modules structure (copyFiles)
8176
- path10.join(root, `node_modules/@bike4mind/mcp/dist/src/${this.serverName}/index.js`),
8611
+ path13.join(root, `node_modules/@bike4mind/mcp/dist/src/${this.serverName}/index.js`),
8177
8612
  // When running from SST Lambda deployed environment (/var/task)
8178
- path10.join(root, `b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8613
+ path13.join(root, `b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8179
8614
  // 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`),
8615
+ path13.join(root, `../../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8181
8616
  // 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`),
8617
+ path13.join(root, `../../b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8183
8618
  // 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")
8619
+ path13.join(root, `/b4m-core/packages/mcp/dist/src/${this.serverName}/index.js`),
8620
+ path13.join(root, "core", "mcp", "servers", this.serverName, "dist", "index.js")
8186
8621
  ];
8187
- const serverScriptPath = candidatePaths.find((p) => existsSync5(p));
8622
+ const serverScriptPath = candidatePaths.find((p) => existsSync6(p));
8188
8623
  if (!serverScriptPath) {
8189
- const getDirectories = (source) => readdirSync(source, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
8624
+ const getDirectories = (source) => readdirSync3(source, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
8190
8625
  console.error(`[MCP] Server script not found. Tried paths:`, candidatePaths);
8191
8626
  console.error(`[MCP] Available directories in ${root}:`, getDirectories(root));
8192
8627
  throw new Error(`MCP Server script path not found for ${this.serverName}. Root: ${root}, Available dirs: ${getDirectories(root).join(", ")}`);
@@ -8215,7 +8650,7 @@ var MCPClient = class {
8215
8650
  }
8216
8651
  };
8217
8652
  await this.mcp.connect(this.transport);
8218
- await new Promise((resolve) => setTimeout(resolve, 100));
8653
+ await new Promise((resolve3) => setTimeout(resolve3, 100));
8219
8654
  const toolsResult = await this.mcp.listTools();
8220
8655
  this.tools = toolsResult.tools.map((tool) => {
8221
8656
  return {
@@ -8398,7 +8833,7 @@ var ServerLlmBackend = class {
8398
8833
  */
8399
8834
  async complete(model, messages, options, callback) {
8400
8835
  logger.debug(`[ServerLlmBackend] Starting complete() with model: ${model}`);
8401
- return new Promise(async (resolve, reject) => {
8836
+ return new Promise(async (resolve3, reject) => {
8402
8837
  try {
8403
8838
  logger.debug("[ServerLlmBackend] Making streaming request...");
8404
8839
  const response = await this.makeStreamingRequest(model, messages, options);
@@ -8428,15 +8863,15 @@ var ServerLlmBackend = class {
8428
8863
  reject(err);
8429
8864
  }).then(() => {
8430
8865
  logger.debug("[ServerLlmBackend] Callback completed, resolving");
8431
- resolve();
8866
+ resolve3();
8432
8867
  });
8433
8868
  } else if (cleanedText) {
8434
8869
  callback([cleanedText], lastUsageInfo).catch((err) => {
8435
8870
  logger.error("[ServerLlmBackend] Callback error:", err);
8436
8871
  reject(err);
8437
- }).then(() => resolve());
8872
+ }).then(() => resolve3());
8438
8873
  } else {
8439
- resolve();
8874
+ resolve3();
8440
8875
  }
8441
8876
  return;
8442
8877
  }
@@ -8496,7 +8931,7 @@ var ServerLlmBackend = class {
8496
8931
  response.data.on("end", () => {
8497
8932
  if (!receivedDone) {
8498
8933
  logger.debug("[ServerLlmBackend] Stream ended without [DONE], resolving anyway");
8499
- resolve();
8934
+ resolve3();
8500
8935
  } else {
8501
8936
  logger.debug("[ServerLlmBackend] Stream ended, [DONE] handler will resolve");
8502
8937
  }
@@ -8760,13 +9195,10 @@ var ApiClient = class {
8760
9195
  }
8761
9196
  };
8762
9197
 
8763
- // src/index.tsx
8764
- import { isAxiosError as isAxiosError2 } from "axios";
8765
-
8766
9198
  // package.json
8767
9199
  var package_default = {
8768
9200
  name: "@bike4mind/cli",
8769
- version: "0.2.1-feat-cli-usage-command.17001+2f4ebd097",
9201
+ version: "0.2.1-feat-cli-file-reference.17022+ce90278a8",
8770
9202
  type: "module",
8771
9203
  description: "Interactive CLI tool for Bike4Mind with ReAct agents",
8772
9204
  license: "UNLICENSED",
@@ -8777,6 +9209,9 @@ var package_default = {
8777
9209
  },
8778
9210
  homepage: "https://github.com/bike4mind/lumina5#readme",
8779
9211
  bugs: "https://github.com/bike4mind/lumina5/issues",
9212
+ publishConfig: {
9213
+ access: "public"
9214
+ },
8780
9215
  keywords: [
8781
9216
  "cli",
8782
9217
  "ai",
@@ -8797,6 +9232,8 @@ var package_default = {
8797
9232
  dev: "tsx src/index.tsx",
8798
9233
  build: "tsup",
8799
9234
  typecheck: "tsc --noEmit",
9235
+ test: "vitest run",
9236
+ "test:watch": "vitest",
8800
9237
  start: "node dist/index.js",
8801
9238
  prepublishOnly: "pnpm build"
8802
9239
  },
@@ -8863,10 +9300,10 @@ var package_default = {
8863
9300
  },
8864
9301
  devDependencies: {
8865
9302
  "@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",
9303
+ "@bike4mind/common": "2.36.1-feat-cli-file-reference.17022+ce90278a8",
9304
+ "@bike4mind/mcp": "1.19.4-feat-cli-file-reference.17022+ce90278a8",
9305
+ "@bike4mind/services": "2.29.1-feat-cli-file-reference.17022+ce90278a8",
9306
+ "@bike4mind/utils": "2.0.3-feat-cli-file-reference.17022+ce90278a8",
8870
9307
  "@types/diff": "^5.0.9",
8871
9308
  "@types/jsonwebtoken": "^9.0.4",
8872
9309
  "@types/node": "^22.9.0",
@@ -8875,16 +9312,12 @@ var package_default = {
8875
9312
  "@types/yargs": "^17.0.32",
8876
9313
  tsup: "^8.5.1",
8877
9314
  tsx: "^4.21.0",
8878
- typescript: "^5.9.3"
9315
+ typescript: "^5.9.3",
9316
+ vitest: "^3.2.4"
8879
9317
  },
8880
- gitHead: "2f4ebd097a871fe1588b568df8b89cf2e4706379"
9318
+ gitHead: "ce90278a814f46eea49075c82f23b97e3356c1d2"
8881
9319
  };
8882
9320
 
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
9321
  // src/index.tsx
8889
9322
  process.removeAllListeners("warning");
8890
9323
  process.on("warning", (warning) => {
@@ -8895,7 +9328,6 @@ process.on("warning", (warning) => {
8895
9328
  });
8896
9329
  var exitTimestamp = null;
8897
9330
  var EXIT_TIMEOUT_MS = 2e3;
8898
- var usageCache = null;
8899
9331
  function CliApp() {
8900
9332
  const { exit } = useApp();
8901
9333
  const [state, setState] = useState3({
@@ -8935,7 +9367,7 @@ function CliApp() {
8935
9367
  }
8936
9368
  await Promise.race([
8937
9369
  Promise.all(cleanupTasks),
8938
- new Promise((resolve) => setTimeout(resolve, 500))
9370
+ new Promise((resolve3) => setTimeout(resolve3, 500))
8939
9371
  // 500ms timeout
8940
9372
  ]);
8941
9373
  setTimeout(() => {
@@ -9069,9 +9501,9 @@ function CliApp() {
9069
9501
  };
9070
9502
  const permissionManager = new PermissionManager(config.trustedTools || []);
9071
9503
  const promptFn = (toolName, args, preview) => {
9072
- return new Promise((resolve) => {
9504
+ return new Promise((resolve3) => {
9073
9505
  const canBeTrusted = permissionManager.canBeTrusted(toolName);
9074
- const prompt = { toolName, args, preview, canBeTrusted, resolve };
9506
+ const prompt = { toolName, args, preview, canBeTrusted, resolve: resolve3 };
9075
9507
  setState((prev) => ({
9076
9508
  ...prev,
9077
9509
  permissionManager,
@@ -9260,7 +9692,6 @@ Available commands:
9260
9692
  /login - Authenticate with your B4M account
9261
9693
  /logout - Clear authentication and sign out
9262
9694
  /whoami - Show current authenticated user
9263
- /usage - Show credit usage and balance
9264
9695
  /save <name> - Save current session
9265
9696
  /sessions - List saved sessions
9266
9697
  /config - Show configuration
@@ -9431,114 +9862,17 @@ Tool Permissions:
9431
9862
  console.log(`Expires: ${new Date(authTokens.expiresAt).toLocaleString()}`);
9432
9863
  console.log("");
9433
9864
  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
9865
  default:
9532
9866
  console.log(`Unknown command: /${command}`);
9533
9867
  console.log("Type /help for available commands");
9534
9868
  }
9535
9869
  };
9536
9870
  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"));
9871
+ 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
9872
  }
9539
9873
  if (state.showLoginFlow) {
9540
9874
  const loginApiUrl = getApiUrl(state.config?.apiConfig);
9541
- return /* @__PURE__ */ React10.createElement(
9875
+ return /* @__PURE__ */ React11.createElement(
9542
9876
  LoginFlow,
9543
9877
  {
9544
9878
  apiUrl: loginApiUrl,
@@ -9561,9 +9895,9 @@ No usage data available for the last ${USAGE_DAYS} days.`);
9561
9895
  );
9562
9896
  }
9563
9897
  if (!isInitialized) {
9564
- return /* @__PURE__ */ React10.createElement(Box10, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React10.createElement(Text9, null, "\u{1F680} Initializing..."));
9898
+ return /* @__PURE__ */ React11.createElement(Box11, { flexDirection: "column", padding: 1 }, /* @__PURE__ */ React11.createElement(Text10, null, "\u{1F680} Initializing..."));
9565
9899
  }
9566
- return /* @__PURE__ */ React10.createElement(
9900
+ return /* @__PURE__ */ React11.createElement(
9567
9901
  App,
9568
9902
  {
9569
9903
  onMessage: handleMessage,
@@ -9594,6 +9928,6 @@ var isDevMode = import.meta.url.includes("/src/") || process.env.NODE_ENV === "d
9594
9928
  if (isDevMode) {
9595
9929
  console.log("\u{1F527} Running in development mode (using TypeScript source)\n");
9596
9930
  }
9597
- render(/* @__PURE__ */ React10.createElement(CliApp, null), {
9931
+ render(/* @__PURE__ */ React11.createElement(CliApp, null), {
9598
9932
  exitOnCtrlC: false
9599
9933
  });