httpcat-cli 0.2.11-rc.1 → 0.2.11-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +346 -13
  2. package/Screenshot 2025-12-21 at 8.56.02/342/200/257PM.png +0 -0
  3. package/bun.lock +5 -0
  4. package/cat-spin.sh +417 -0
  5. package/dist/agent/ax-agent.d.ts.map +1 -0
  6. package/dist/agent/ax-agent.js +459 -0
  7. package/dist/agent/ax-agent.js.map +1 -0
  8. package/dist/agent/llm-factory.d.ts.map +1 -0
  9. package/dist/agent/llm-factory.js +82 -0
  10. package/dist/agent/llm-factory.js.map +1 -0
  11. package/dist/agent/setup-wizard.d.ts.map +1 -0
  12. package/dist/agent/setup-wizard.js +114 -0
  13. package/dist/agent/setup-wizard.js.map +1 -0
  14. package/dist/agent/tools.d.ts.map +1 -0
  15. package/dist/agent/tools.js +312 -0
  16. package/dist/agent/tools.js.map +1 -0
  17. package/dist/commands/chat.d.ts.map +1 -1
  18. package/dist/commands/chat.js +56 -46
  19. package/dist/commands/chat.js.map +1 -1
  20. package/dist/commands/create.d.ts.map +1 -1
  21. package/dist/commands/create.js +133 -5
  22. package/dist/commands/create.js.map +1 -1
  23. package/dist/commands/positions.d.ts.map +1 -1
  24. package/dist/commands/positions.js +51 -54
  25. package/dist/commands/positions.js.map +1 -1
  26. package/dist/config.d.ts.map +1 -1
  27. package/dist/config.js +83 -0
  28. package/dist/config.js.map +1 -1
  29. package/dist/index.js +301 -13
  30. package/dist/index.js.map +1 -1
  31. package/dist/interactive/cat-spin.d.ts.map +1 -0
  32. package/dist/interactive/cat-spin.js +448 -0
  33. package/dist/interactive/cat-spin.js.map +1 -0
  34. package/dist/interactive/shell.d.ts.map +1 -1
  35. package/dist/interactive/shell.js +1244 -149
  36. package/dist/interactive/shell.js.map +1 -1
  37. package/dist/mcp/tools.d.ts.map +1 -1
  38. package/dist/mcp/tools.js +1 -6
  39. package/dist/mcp/tools.js.map +1 -1
  40. package/dist/mcp/types.d.ts.map +1 -1
  41. package/dist/utils/loading.d.ts.map +1 -1
  42. package/dist/utils/loading.js +30 -0
  43. package/dist/utils/loading.js.map +1 -1
  44. package/dist/utils/token-resolver.d.ts.map +1 -1
  45. package/dist/utils/token-resolver.js +32 -0
  46. package/dist/utils/token-resolver.js.map +1 -1
  47. package/package.json +2 -1
@@ -5,21 +5,25 @@ import { config } from "../config.js";
5
5
  import { printCat } from "./art.js";
6
6
  import { validateAmount } from "../utils/validation.js";
7
7
  // Import commands
8
- import { createToken } from "../commands/create.js";
9
- import { buyToken, TEST_AMOUNTS, PROD_AMOUNTS } from "../commands/buy.js";
8
+ import { createToken, processPhotoUrl, isFilePath, } from "../commands/create.js";
9
+ import { buyToken, TEST_AMOUNTS, PROD_AMOUNTS, } from "../commands/buy.js";
10
10
  import { sellToken, parseTokenAmount } from "../commands/sell.js";
11
11
  import { getTokenInfo } from "../commands/info.js";
12
12
  import { listTokens } from "../commands/list.js";
13
- import { formatCurrency } from "../utils/formatting.js";
13
+ import { formatCurrency, formatTokenAmount, formatAddress, } from "../utils/formatting.js";
14
14
  import { getPositions } from "../commands/positions.js";
15
15
  import { privateKeyToAccount } from "viem/accounts";
16
16
  import { checkHealth } from "../commands/health.js";
17
- import { startChatStream } from "../commands/chat.js";
17
+ import { joinChat, sendChatMessage, renewLease, normalizeWebSocketUrl, } from "../commands/chat.js";
18
+ import WebSocket from "ws";
18
19
  import { checkBalance } from "../commands/balances.js";
19
20
  import { viewFees, claimFees } from "../commands/claim.js";
20
21
  import { getTransactions } from "../commands/transactions.js";
21
- import { getAccountInfo, switchAccount, addAccount } from "../commands/account.js";
22
+ import { getAccountInfo, switchAccount, addAccount, } from "../commands/account.js";
22
23
  import { HttpcatError } from "../client.js";
24
+ import { createHttpcatAgent, chatWithAgent } from "../agent/ax-agent.js";
25
+ import { createLLM } from "../agent/llm-factory.js";
26
+ import { setupAIAgentWizard } from "../agent/setup-wizard.js";
23
27
  // Detect terminal background color
24
28
  function detectTerminalBackground() {
25
29
  // Check COLORFGBG (format: "foreground;background")
@@ -56,15 +60,19 @@ function detectTerminalBackground() {
56
60
  // Default to dark (safer assumption for modern terminals)
57
61
  return "dark";
58
62
  }
59
- export async function startInteractiveShell(client) {
63
+ export async function startInteractiveShell(client, autoChatToken) {
60
64
  // Auto-detect terminal background and set default theme
61
65
  const detectedBg = detectTerminalBackground();
62
66
  let currentTheme = detectedBg === "dark" ? "dark" : "win95";
67
+ // Helper function to get theme-appropriate cyan/blue color for blessed tags
68
+ // For dark theme, use lighter colors (light-cyan-fg) for better visibility on black
69
+ const getCyanColor = (theme) => theme === "dark" ? "light-cyan-fg" : "cyan-fg";
70
+ const getBlueColor = (theme) => theme === "dark" ? "light-blue-fg" : "blue-fg";
63
71
  // Create blessed screen with optimized settings
64
72
  const screen = blessed.screen({
65
73
  smartCSR: true,
66
74
  title: "httpcat Interactive Shell",
67
- fullUnicode: true,
75
+ fullUnicode: true, // Support double-width/surrogate/combining chars (emojis)
68
76
  fastCSR: false, // Disable fast CSR to prevent rendering issues
69
77
  cursor: {
70
78
  artificial: true,
@@ -72,8 +80,8 @@ export async function startInteractiveShell(client) {
72
80
  blink: true,
73
81
  color: "green",
74
82
  },
75
- // Ensure cursor is always visible
76
- forceUnicode: false,
83
+ // Force Unicode support for emojis
84
+ forceUnicode: true,
77
85
  });
78
86
  const network = client.getNetwork();
79
87
  // Theme colors - no backgrounds, just borders
@@ -112,12 +120,12 @@ export async function startInteractiveShell(client) {
112
120
  }
113
121
  };
114
122
  let themeColors = getThemeColors(currentTheme);
115
- // Create header box with thick borders, transparent background
123
+ // Create header box with thick borders, transparent background - more compact
116
124
  const headerBox = blessed.box({
117
125
  top: 0,
118
126
  left: 0,
119
127
  width: "100%",
120
- height: 16,
128
+ height: 6, // Reduced to save vertical space
121
129
  content: "",
122
130
  tags: true,
123
131
  style: {
@@ -130,10 +138,10 @@ export async function startInteractiveShell(client) {
130
138
  },
131
139
  },
132
140
  padding: {
133
- left: 0,
141
+ left: 1,
134
142
  right: 1,
135
- top: 1,
136
- bottom: 1,
143
+ top: 0,
144
+ bottom: 0,
137
145
  },
138
146
  border: {
139
147
  type: "line",
@@ -141,19 +149,29 @@ export async function startInteractiveShell(client) {
141
149
  ch: "═", // Double line for thicker border
142
150
  },
143
151
  });
144
- // Helper function to build welcome content with account info
145
- const buildWelcomeContent = async (theme) => {
152
+ // Cat face variants for animation
153
+ const catFaces = [
154
+ { name: "Sleepy", face: "[=^ -.- ^=]" },
155
+ { name: "Smug", face: "[=^‿^=]" },
156
+ { name: "Unhinged", face: "[=^◉_◉^=]" },
157
+ { name: "Judgy", face: "[=^ಠ‿ಠ^=]" },
158
+ { name: "Cute", face: "[=^。^=]" },
159
+ { name: "Menacing", face: "[=^>_<^=]" },
160
+ { name: "Loaf Mode", face: "[=^___^=]" },
161
+ { name: "Cosmic", face: "[=^✧_✧^=]" },
162
+ ];
163
+ let currentCatIndex = 0;
164
+ let catAnimationInterval = null;
165
+ // Helper function to build welcome content with account info - more compact
166
+ const buildWelcomeContent = async (theme, catFace) => {
146
167
  const welcomeLines = [];
147
168
  const colorTag = theme === "dark" ? "green-fg" : "black-fg";
148
- // Old-school pattern in top bar
149
- const pattern = "═" + "─".repeat(78) + "═";
150
- welcomeLines.push(`{${colorTag}}${pattern}{/${colorTag}}`);
151
- // Single cat ASCII art
152
- welcomeLines.push(`{${colorTag}} /\\_/\\{/${colorTag}}`);
153
- welcomeLines.push(`{${colorTag}} ( ^.^ ){/${colorTag}}`);
154
- welcomeLines.push(`{${colorTag}} > ^ <{/${colorTag}}`);
155
- welcomeLines.push(`{${colorTag}} / \\{/${colorTag}}`);
156
- welcomeLines.push("");
169
+ const cyanColor = getCyanColor(theme);
170
+ // Use provided cat face or current one
171
+ const displayCatFace = catFace || catFaces[currentCatIndex].face;
172
+ // Cat face with breathing room, compact info below
173
+ welcomeLines.push(`{${colorTag}}${displayCatFace}{/${colorTag}}`);
174
+ welcomeLines.push(`{green-fg}🐱 Welcome to httpcat!{/green-fg} | {green-fg}🌐 {${cyanColor}}${network}{/${cyanColor}}{/green-fg}`);
157
175
  // Get account info
158
176
  let accountInfo = null;
159
177
  try {
@@ -179,39 +197,46 @@ export async function startInteractiveShell(client) {
179
197
  catch (error) {
180
198
  // If account info fails, continue without it
181
199
  }
182
- // Playful cat-like greetings with account info
183
- const greetings = [
184
- `{green-fg}Meow! Welcome to httpcat!{/green-fg}`,
185
- `{green-fg}*purrs* Ready to play with some tokens?{/green-fg}`,
186
- `{green-fg}Connected to: {cyan-fg}${network}{/cyan-fg}{/green-fg}`,
187
- ];
188
- // Add account information
200
+ // Compact account info - combined on fewer lines
189
201
  if (accountInfo) {
190
202
  const { account, balance } = accountInfo;
191
203
  const accountType = account.type === "custom" ? "Custom" : "Seed-Derived";
192
204
  const accountLabel = account.label ? ` (${account.label})` : "";
193
- greetings.push("");
194
- greetings.push(`{cyan-fg}Account #{green-fg}${account.index}{/green-fg} | {green-fg}${accountType}${accountLabel}{/green-fg}{/cyan-fg}`);
195
205
  if (balance) {
196
206
  const ethDisplay = balance.ethFormatted || balance.ethBalance || "0 ETH";
197
207
  const usdcDisplay = balance.usdcFormatted || balance.usdcBalance || "$0.00";
198
- greetings.push(`{cyan-fg}Balance: {yellow-fg}${ethDisplay}{/yellow-fg} | {green-fg}${usdcDisplay}{/green-fg}{/cyan-fg}`);
208
+ // Combine account and balance on one line to save space
209
+ welcomeLines.push(`{${cyanColor}}👤 Account #{green-fg}${account.index}{/green-fg} | {green-fg}${accountType}${accountLabel}{/green-fg} | 💰 {yellow-fg}${ethDisplay}{/yellow-fg} | {green-fg}${usdcDisplay}{/green-fg}{/${cyanColor}}`);
210
+ }
211
+ else {
212
+ welcomeLines.push(`{${cyanColor}}👤 Account #{green-fg}${account.index}{/green-fg} | {green-fg}${accountType}${accountLabel}{/green-fg}{/${cyanColor}}`);
199
213
  }
200
214
  }
201
- greetings.push("");
202
- greetings.push(`{yellow-fg}Pssst... type {bold}help{/bold} if you want to see what I can do!{/yellow-fg}`);
203
- greetings.push(`{yellow-fg}Or just start playing - I'm curious like a cat!{/yellow-fg}`);
204
- welcomeLines.push(...greetings);
205
215
  return welcomeLines.join("\n");
206
216
  };
207
217
  // Set initial header content
208
- buildWelcomeContent(currentTheme).then((content) => {
218
+ buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face).then((content) => {
209
219
  headerBox.setContent(content);
210
220
  screen.render();
211
221
  });
222
+ // Start cat face animation (cycle through every minute)
223
+ const startCatAnimation = () => {
224
+ if (catAnimationInterval) {
225
+ clearInterval(catAnimationInterval);
226
+ }
227
+ catAnimationInterval = setInterval(() => {
228
+ currentCatIndex = (currentCatIndex + 1) % catFaces.length;
229
+ buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face).then((content) => {
230
+ headerBox.setContent(content);
231
+ screen.render();
232
+ });
233
+ }, 60000); // Change every minute (60 seconds)
234
+ };
235
+ // Start animation
236
+ startCatAnimation();
212
237
  // Create output log box (scrollable) with thick borders, transparent background
213
238
  const outputBox = blessed.log({
214
- top: 16,
239
+ top: 6, // Adjusted to match new header height
215
240
  left: 0,
216
241
  width: "100%",
217
242
  bottom: 4, // Leave space for input box at bottom
@@ -269,6 +294,7 @@ export async function startInteractiveShell(client) {
269
294
  height: 3,
270
295
  inputOnFocus: true,
271
296
  keys: true,
297
+ vi: false, // Disabled to prevent double input issues in agent mode
272
298
  secret: false,
273
299
  tags: true,
274
300
  alwaysScroll: false,
@@ -312,9 +338,10 @@ export async function startInteractiveShell(client) {
312
338
  currentTheme = newTheme;
313
339
  themeColors = getThemeColors(currentTheme);
314
340
  // Update screen cursor color
315
- screen.cursor.color = currentTheme === "dark" ? "green" : "black";
316
- // Update header content with new theme colors
317
- buildWelcomeContent(currentTheme).then((content) => {
341
+ screen.cursor.color =
342
+ currentTheme === "dark" ? "green" : "black";
343
+ // Update header content with new theme colors (keep current cat face)
344
+ buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face).then((content) => {
318
345
  headerBox.setContent(content);
319
346
  screen.render();
320
347
  });
@@ -339,9 +366,11 @@ export async function startInteractiveShell(client) {
339
366
  inputBox.style.focus.border.fg = themeColors.border;
340
367
  inputBox.border = { type: "line", fg: themeColors.border, ch: "─" };
341
368
  if (inputBox.cursor) {
342
- inputBox.cursor.color = currentTheme === "dark" ? "green" : "black";
369
+ inputBox.cursor.color =
370
+ currentTheme === "dark" ? "green" : "black";
343
371
  }
344
- screen.cursor.color = currentTheme === "dark" ? "green" : "black";
372
+ screen.cursor.color =
373
+ currentTheme === "dark" ? "green" : "black";
345
374
  screen.render();
346
375
  };
347
376
  // Helper to log output (define before use)
@@ -356,6 +385,42 @@ export async function startInteractiveShell(client) {
356
385
  outputBox.setScrollPerc(100);
357
386
  screen.render();
358
387
  };
388
+ // Helper to log multiple lines with smooth scrolling (for tables/lists)
389
+ const logLinesSmooth = async (lines, scrollToTop = false) => {
390
+ // Disable auto-scroll temporarily to batch output (prevents rapid scrolling)
391
+ const originalAlwaysScroll = outputBox.alwaysScroll;
392
+ outputBox.alwaysScroll = false;
393
+ // Get line count before adding new lines
394
+ const linesBefore = outputBox.lines?.length || 0;
395
+ // Add all lines at once (no rendering between lines = smooth, no rapid scrolling)
396
+ lines.forEach((line) => outputBox.log(line));
397
+ // Calculate scroll position after adding lines
398
+ const linesAfter = outputBox.lines?.length || 0;
399
+ const visibleHeight = outputBox.height || 20;
400
+ if (scrollToTop && linesAfter > visibleHeight) {
401
+ // Scroll to show the beginning of the new content
402
+ // Calculate which line the new content starts at
403
+ const newContentStartLine = linesBefore;
404
+ // Calculate percentage to show that line near the top
405
+ // We want to show the new content starting from the top of visible area
406
+ const totalScrollable = Math.max(1, linesAfter - visibleHeight);
407
+ const scrollPerc = Math.max(0, Math.min(100, (newContentStartLine / totalScrollable) * 100));
408
+ try {
409
+ outputBox.setScrollPerc(scrollPerc);
410
+ }
411
+ catch (e) {
412
+ // Fallback if method doesn't exist
413
+ outputBox.setScrollPerc(0);
414
+ }
415
+ }
416
+ else {
417
+ // Scroll to bottom
418
+ outputBox.setScrollPerc(100);
419
+ }
420
+ // Re-enable auto-scroll
421
+ outputBox.alwaysScroll = originalAlwaysScroll;
422
+ screen.render();
423
+ };
359
424
  // Wrap toggleTheme to also log
360
425
  const toggleThemeWithLog = () => {
361
426
  const themes = ["win95", "dark", "light"];
@@ -376,21 +441,110 @@ export async function startInteractiveShell(client) {
376
441
  // Store toggle function for command handler
377
442
  screen.toggleTheme = toggleThemeWithLog;
378
443
  screen.updateTheme = updateTheme;
444
+ // Command history
445
+ const commandHistory = [];
446
+ let historyIndex = -1; // -1 means not navigating history (showing current input)
447
+ let currentInputBeforeHistory = ""; // Store current input when starting to navigate history
448
+ // Handle up arrow - navigate to previous command in history
449
+ inputBox.key(["up"], () => {
450
+ if (commandHistory.length === 0) {
451
+ return;
452
+ }
453
+ // If we're not currently navigating history, save the current input
454
+ if (historyIndex === -1) {
455
+ currentInputBeforeHistory = inputBox.getValue();
456
+ historyIndex = commandHistory.length - 1; // Start at the most recent command
457
+ }
458
+ else {
459
+ // Move to previous command (earlier in history)
460
+ if (historyIndex > 0) {
461
+ historyIndex--;
462
+ }
463
+ }
464
+ // Set the input to the command at current history index
465
+ inputBox.setValue(commandHistory[historyIndex]);
466
+ screen.render();
467
+ });
468
+ // Handle down arrow - navigate to next command in history (or back to current input)
469
+ inputBox.key(["down"], () => {
470
+ if (commandHistory.length === 0 || historyIndex === -1) {
471
+ return;
472
+ }
473
+ // Move to next command (more recent in history)
474
+ if (historyIndex < commandHistory.length - 1) {
475
+ historyIndex++;
476
+ inputBox.setValue(commandHistory[historyIndex]);
477
+ }
478
+ else {
479
+ // We're at the most recent command, go back to the input that was there before
480
+ historyIndex = -1;
481
+ inputBox.setValue(currentInputBeforeHistory);
482
+ currentInputBeforeHistory = "";
483
+ }
484
+ screen.render();
485
+ });
486
+ // Handle left arrow - move cursor left within input
487
+ // Only intercept if we're not navigating history (blessed handles cursor movement automatically with vi: true)
488
+ inputBox.key(["left"], () => {
489
+ // Reset history navigation when user starts editing with arrow keys
490
+ if (historyIndex !== -1) {
491
+ historyIndex = -1;
492
+ currentInputBeforeHistory = "";
493
+ }
494
+ // Blessed will handle cursor movement automatically with vi: true
495
+ screen.render();
496
+ });
497
+ // Handle right arrow - move cursor right within input
498
+ inputBox.key(["right"], () => {
499
+ // Reset history navigation when user starts editing with arrow keys
500
+ if (historyIndex !== -1) {
501
+ historyIndex = -1;
502
+ currentInputBeforeHistory = "";
503
+ }
504
+ // Blessed will handle cursor movement automatically with vi: true
505
+ screen.render();
506
+ });
507
+ // Handle Home key - move cursor to beginning of line
508
+ inputBox.key(["home"], () => {
509
+ if (historyIndex === -1) {
510
+ // Blessed handles this automatically with vi: true
511
+ screen.render();
512
+ }
513
+ });
514
+ // Handle End key - move cursor to end of line
515
+ inputBox.key(["end"], () => {
516
+ if (historyIndex === -1) {
517
+ // Blessed handles this automatically with vi: true
518
+ screen.render();
519
+ }
520
+ });
379
521
  // Handle input submission
380
522
  inputBox.on("submit", async (value) => {
381
523
  const trimmed = value.trim();
382
524
  inputBox.clearValue();
383
525
  screen.render(); // Clear input immediately
526
+ // Reset history navigation
527
+ historyIndex = -1;
528
+ currentInputBeforeHistory = "";
384
529
  if (!trimmed) {
385
530
  inputBox.focus();
386
531
  screen.render();
387
532
  return;
388
533
  }
534
+ // Add to history (avoid duplicates - don't add if same as last command)
535
+ if (commandHistory.length === 0 ||
536
+ commandHistory[commandHistory.length - 1] !== trimmed) {
537
+ commandHistory.push(trimmed);
538
+ // Limit history size to prevent memory issues (keep last 100 commands)
539
+ if (commandHistory.length > 100) {
540
+ commandHistory.shift();
541
+ }
542
+ }
389
543
  // Log the command with prompt
390
544
  log(`{green-fg}httpcat>{/green-fg} ${trimmed}`);
391
545
  const [command, ...args] = trimmed.split(/\s+/);
392
546
  try {
393
- await handleCommand(client, command.toLowerCase(), args, log, logLines, screen, inputBox, currentTheme, buildWelcomeContent, headerBox);
547
+ await handleCommand(client, command.toLowerCase(), args, log, logLines, logLinesSmooth, screen, inputBox, currentTheme, buildWelcomeContent, headerBox, catFaces, currentCatIndex);
394
548
  }
395
549
  catch (error) {
396
550
  log(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
@@ -399,52 +553,86 @@ export async function startInteractiveShell(client) {
399
553
  inputBox.focus();
400
554
  screen.render();
401
555
  });
402
- // Handle Ctrl+C
403
- screen.key(["C-c"], () => {
404
- screen.destroy();
405
- printCat("sleeping");
406
- console.log(chalk.cyan("Goodbye! 👋"));
407
- process.exit(0);
408
- });
409
556
  // Handle escape to clear input
410
557
  inputBox.key(["escape"], () => {
411
558
  inputBox.clearValue();
412
559
  screen.render();
413
560
  });
414
- // Handle Ctrl+C to quit (also works from input box)
415
- inputBox.key(["C-c"], () => {
561
+ // Handle Ctrl+C - two-stage: first clears input if text exists, second quits
562
+ const handleCtrlC = () => {
563
+ const currentValue = inputBox.getValue();
564
+ // If there's text in the input, clear it instead of quitting
565
+ if (currentValue && currentValue.trim().length > 0) {
566
+ inputBox.clearValue();
567
+ screen.render();
568
+ return;
569
+ }
570
+ // No text in input, so quit
571
+ if (catAnimationInterval) {
572
+ clearInterval(catAnimationInterval);
573
+ catAnimationInterval = null;
574
+ }
416
575
  screen.destroy();
417
576
  printCat("sleeping");
418
577
  console.log(chalk.cyan("Goodbye! 👋"));
419
578
  process.exit(0);
420
- });
579
+ };
580
+ // Handle Ctrl+C on screen level
581
+ screen.key(["C-c"], handleCtrlC);
582
+ // Handle Ctrl+C on input box level
583
+ inputBox.key(["C-c"], handleCtrlC);
421
584
  // Focus input and render
422
585
  inputBox.focus();
423
586
  screen.render();
424
- // Show available commands on load
425
- displayHelp(log, logLines);
587
+ // Show welcome message with key commands on load
588
+ displayWelcomeMessage(log, logLines, outputBox, screen, currentTheme);
589
+ // Auto-enter chat mode if token identifier provided
590
+ if (autoChatToken !== undefined) {
591
+ // Store original submit handler
592
+ const originalHandlers = inputBox.listeners("submit");
593
+ const originalSubmitHandler = originalHandlers[0];
594
+ // Remove original handler temporarily
595
+ inputBox.removeAllListeners("submit");
596
+ // Enter chat mode automatically
597
+ await startChatInShell(client, autoChatToken, log, logLines, screen, inputBox, originalSubmitHandler, headerBox, buildWelcomeContent, currentTheme, catFaces, currentCatIndex);
598
+ }
426
599
  }
427
- async function handleCommand(client, command, args, log, logLines, screen, inputBox, currentTheme, buildWelcomeContent, headerBox) {
600
+ async function handleCommand(client, command, args, log, logLines, logLinesSmooth, screen, inputBox, currentTheme, buildWelcomeContent, headerBox, catFaces, currentCatIndex) {
428
601
  switch (command) {
429
602
  case "help":
430
- displayHelp(log, logLines);
603
+ // Get outputBox from screen children (it's the second child after headerBox)
604
+ const outputBox = screen.children.find((child) => child.type === "log");
605
+ displayHelp(log, logLines, outputBox, screen, currentTheme);
431
606
  break;
432
607
  case "create": {
433
608
  if (args.length < 2) {
434
- log(chalk.red("Usage: create <name> <symbol> [--photo URL] [--banner URL] [--website URL]"));
609
+ log(chalk.red("Usage: create <name> <symbol> [--photo URL|path] [--website URL]"));
435
610
  return;
436
611
  }
437
612
  const [name, symbol] = args;
438
- const photoUrl = extractFlag(args, "--photo");
439
- const bannerUrl = extractFlag(args, "--banner");
613
+ let photoUrl = extractFlag(args, "--photo");
440
614
  const websiteUrl = extractFlag(args, "--website");
615
+ // Process photo if it's a file path (show loading state)
616
+ if (photoUrl && isFilePath(photoUrl)) {
617
+ log(chalk.blue("Uploading image..."));
618
+ screen.render();
619
+ try {
620
+ photoUrl = processPhotoUrl(photoUrl);
621
+ log(chalk.green("✓ Image uploaded"));
622
+ screen.render();
623
+ }
624
+ catch (error) {
625
+ log(chalk.red(`Failed to upload image: ${error instanceof Error ? error.message : String(error)}`));
626
+ screen.render();
627
+ return;
628
+ }
629
+ }
441
630
  log(chalk.blue("Creating token..."));
442
631
  screen.render();
443
632
  const result = await createToken(client, {
444
633
  name,
445
634
  symbol,
446
635
  photoUrl,
447
- bannerUrl,
448
636
  websiteUrl,
449
637
  });
450
638
  displayCreateResultToLog(result, log, logLines);
@@ -489,7 +677,7 @@ async function handleCommand(client, command, args, log, logLines, screen, input
489
677
  try {
490
678
  log(chalk.blue(`Buy ${i}/${repeatCount}...`));
491
679
  screen.render();
492
- const result = await buyToken(client, identifier, amount, isTestMode, i > 1, // Silent after first buy
680
+ const result = await buyToken(client, identifier, amount, isTestMode, true, // silent=true to avoid console.log interference
493
681
  privateKey);
494
682
  results.push(result);
495
683
  totalSpent += parseFloat(result.amountSpent);
@@ -513,6 +701,38 @@ async function handleCommand(client, command, args, log, logLines, screen, input
513
701
  stoppedEarly = true;
514
702
  stopReason = "Insufficient funds";
515
703
  log(chalk.yellow("💡 Insufficient funds. Stopping buy loop."));
704
+ log("");
705
+ // Show current balance to help diagnose the issue
706
+ try {
707
+ const balance = await checkBalance(privateKey, true);
708
+ log(chalk.cyan("💰 Current Wallet Balances:"));
709
+ log(chalk.dim(` ETH: ${balance.ethFormatted}`));
710
+ log(chalk.dim(` USDC: ${balance.usdcFormatted}`));
711
+ if (balance.cat402Formatted) {
712
+ log(chalk.dim(` CAT: ${balance.cat402Formatted}`));
713
+ }
714
+ log("");
715
+ // Provide guidance based on what might be insufficient
716
+ const usdcBalance = parseFloat(balance.usdcFormatted.replace("$", "").replace(",", ""));
717
+ const ethBalance = parseFloat(balance.ethFormatted.replace(" ETH", "").replace(",", ""));
718
+ const buyAmount = parseFloat(amount);
719
+ log(chalk.yellow("💡 Possible issues:"));
720
+ if (usdcBalance < buyAmount) {
721
+ log(chalk.dim(` • Insufficient USDC for purchase: Need $${buyAmount.toFixed(6)}, have $${usdcBalance.toFixed(6)}`));
722
+ }
723
+ if (usdcBalance < 0.01) {
724
+ log(chalk.dim(` • Low USDC for API payments: x402 protocol requires USDC for API calls`));
725
+ }
726
+ if (ethBalance < 0.001) {
727
+ log(chalk.dim(` • Low ETH for gas: Need ETH to pay for transaction fees`));
728
+ }
729
+ log("");
730
+ log(chalk.dim(" Check your balance with: balances"));
731
+ }
732
+ catch (balanceError) {
733
+ // If we can't fetch balance, just show generic message
734
+ log(chalk.dim(" Check your balance with: balances"));
735
+ }
516
736
  break;
517
737
  }
518
738
  // For other errors, re-throw to be handled by outer catch
@@ -541,7 +761,8 @@ async function handleCommand(client, command, args, log, logLines, screen, input
541
761
  // Normal single buy execution
542
762
  log(chalk.blue("Buying tokens..."));
543
763
  screen.render();
544
- const result = await buyToken(client, identifier, amount, isTestMode, false, privateKey);
764
+ const result = await buyToken(client, identifier, amount, isTestMode, true, // silent=true to avoid console.log interference
765
+ privateKey);
545
766
  displayBuyResultToLog(result, log, logLines);
546
767
  }
547
768
  break;
@@ -553,9 +774,13 @@ async function handleCommand(client, command, args, log, logLines, screen, input
553
774
  return;
554
775
  }
555
776
  const [identifier, amountInput] = args;
777
+ // Get user address from private key for position checking
778
+ const privateKey = config.getPrivateKey();
779
+ const account = privateKeyToAccount(privateKey);
780
+ const userAddress = account.address;
556
781
  log(chalk.blue("Checking token info..."));
557
782
  screen.render();
558
- const info = await getTokenInfo(client, identifier);
783
+ const info = await getTokenInfo(client, identifier, userAddress, true); // silent=true to avoid console.log interference
559
784
  if (!info.userPosition || info.userPosition.tokensOwned === "0") {
560
785
  log(chalk.yellow("You do not own any of this token."));
561
786
  return;
@@ -563,7 +788,7 @@ async function handleCommand(client, command, args, log, logLines, screen, input
563
788
  const tokenAmount = parseTokenAmount(amountInput, info.userPosition.tokensOwned);
564
789
  log(chalk.blue("Selling tokens..."));
565
790
  screen.render();
566
- const result = await sellToken(client, identifier, tokenAmount, false);
791
+ const result = await sellToken(client, identifier, tokenAmount, true, privateKey); // silent=true to avoid console.log interference
567
792
  displaySellResultToLog(result, log, logLines);
568
793
  break;
569
794
  }
@@ -580,7 +805,7 @@ async function handleCommand(client, command, args, log, logLines, screen, input
580
805
  const userAddress = account.address;
581
806
  log(chalk.blue("Fetching token info..."));
582
807
  screen.render();
583
- const info = await getTokenInfo(client, identifier, userAddress);
808
+ const info = await getTokenInfo(client, identifier, userAddress, true); // silent=true to avoid console.log interference
584
809
  displayTokenInfoToLog(info, log, logLines);
585
810
  break;
586
811
  }
@@ -591,7 +816,7 @@ async function handleCommand(client, command, args, log, logLines, screen, input
591
816
  log(chalk.blue("Fetching token list..."));
592
817
  screen.render();
593
818
  const result = await listTokens(client, page, limit, sortBy);
594
- displayTokenListToLog(result, log, logLines);
819
+ displayTokenListToLog(result, log, logLines, logLinesSmooth);
595
820
  break;
596
821
  }
597
822
  case "positions": {
@@ -664,14 +889,17 @@ async function handleCommand(client, command, args, log, logLines, screen, input
664
889
  break;
665
890
  }
666
891
  case "chat": {
667
- // For chat, we need to exit the blessed shell and start chat stream
668
- log(chalk.yellow("Starting chat mode..."));
669
- screen.destroy();
670
892
  const tokenIdentifier = args.length > 0 && !args[0].startsWith("--") ? args[0] : undefined;
671
- const inputFormatRaw = extractFlag(args, "--input-format") || "text";
672
- const inputFormat = (inputFormatRaw === "stream-json" ? "stream-json" : "text");
673
- await startChatStream(client, false, tokenIdentifier, inputFormat);
674
- process.exit(0);
893
+ log(chalk.yellow("💬 Entering chat mode..."));
894
+ log(chalk.dim("Type /exit to return to shell, or /help for chat commands"));
895
+ log("");
896
+ // Start chat mode within the shell
897
+ // Store original submit handler
898
+ const originalHandlers = inputBox.listeners("submit");
899
+ const originalSubmitHandler = originalHandlers[0];
900
+ // Remove original handler temporarily
901
+ inputBox.removeAllListeners("submit");
902
+ await startChatInShell(client, tokenIdentifier, log, logLines, screen, inputBox, originalSubmitHandler, headerBox, buildWelcomeContent, currentTheme, catFaces, currentCatIndex);
675
903
  break;
676
904
  }
677
905
  case "exit":
@@ -713,13 +941,13 @@ async function handleCommand(client, command, args, log, logLines, screen, input
713
941
  const address = callerAddress || account.address;
714
942
  log(chalk.blue("Claiming fees..."));
715
943
  screen.render();
716
- const result = await claimFees(client, identifier, address, false);
944
+ const result = await claimFees(client, identifier, address, true); // silent=true to avoid console.log interference
717
945
  displayClaimResultToLog(result, log, logLines);
718
946
  }
719
947
  else {
720
948
  log(chalk.blue("Fetching fee information..."));
721
949
  screen.render();
722
- const result = await viewFees(client, identifier, false);
950
+ const result = await viewFees(client, identifier, true); // silent=true to avoid console.log interference
723
951
  displayFeesToLog(result, log, logLines);
724
952
  }
725
953
  break;
@@ -786,7 +1014,9 @@ async function handleCommand(client, command, args, log, logLines, screen, input
786
1014
  }
787
1015
  for (const account of accounts) {
788
1016
  const isActive = account.index === activeIndex;
789
- const status = isActive ? chalk.green("● Active") : chalk.blue("○ Inactive");
1017
+ const status = isActive
1018
+ ? chalk.green("● Active")
1019
+ : chalk.blue("○ Inactive");
790
1020
  const type = account.type === "custom" ? "Custom" : "Seed-Derived";
791
1021
  const address = account.address.slice(0, 6) + "..." + account.address.slice(-4);
792
1022
  log(` ${chalk.green(account.index.toString().padEnd(5))} ${chalk.blue(type.padEnd(12))} ${chalk.green(address.padEnd(15))} ${status}`);
@@ -812,7 +1042,7 @@ async function handleCommand(client, command, args, log, logLines, screen, input
812
1042
  log(chalk.blue(` Address: ${account.address.slice(0, 6)}...${account.address.slice(-4)}`));
813
1043
  }
814
1044
  // Refresh header with new account info
815
- buildWelcomeContent(currentTheme).then((content) => {
1045
+ buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face).then((content) => {
816
1046
  headerBox.setContent(content);
817
1047
  screen.render();
818
1048
  });
@@ -823,7 +1053,7 @@ async function handleCommand(client, command, args, log, logLines, screen, input
823
1053
  await addAccount();
824
1054
  log(chalk.green("✅ Account added"));
825
1055
  // Refresh header with new account info
826
- buildWelcomeContent(currentTheme).then((content) => {
1056
+ buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face).then((content) => {
827
1057
  headerBox.setContent(content);
828
1058
  screen.render();
829
1059
  });
@@ -857,7 +1087,9 @@ async function handleCommand(client, command, args, log, logLines, screen, input
857
1087
  for (const [name, env] of Object.entries(envs)) {
858
1088
  const isCurrent = name === current;
859
1089
  const prefix = isCurrent ? chalk.green("→ ") : " ";
860
- const nameDisplay = isCurrent ? chalk.green.bold(name) : chalk.bold(name);
1090
+ const nameDisplay = isCurrent
1091
+ ? chalk.green.bold(name)
1092
+ : chalk.bold(name);
861
1093
  log(`${prefix}${nameDisplay}`);
862
1094
  log(chalk.dim(` Agent URL: ${env.agentUrl}`));
863
1095
  log(chalk.dim(` Network: ${env.network}`));
@@ -907,35 +1139,299 @@ async function handleCommand(client, command, args, log, logLines, screen, input
907
1139
  }
908
1140
  break;
909
1141
  }
1142
+ case "agent":
1143
+ case "ai":
1144
+ case "cat": {
1145
+ // Check if --chat flag is provided (for future chat mode)
1146
+ if (args[0] === "--chat") {
1147
+ log(chalk.yellow("⚠️ Agent chat mode is currently disabled"));
1148
+ log(chalk.dim("Use 'agent <query>' or 'cat <query>' to ask the cat directly."));
1149
+ log("");
1150
+ break;
1151
+ }
1152
+ // Check if --setup flag is provided
1153
+ if (args[0] === "--setup") {
1154
+ try {
1155
+ await setupAIAgentWizard();
1156
+ log(chalk.green("✅ Agent configuration updated!"));
1157
+ log("");
1158
+ }
1159
+ catch (error) {
1160
+ log(chalk.red(`❌ Setup failed: ${error.message || String(error)}`));
1161
+ log("");
1162
+ }
1163
+ break;
1164
+ }
1165
+ // Get the query text (everything after the command)
1166
+ const query = args.join(" ").trim();
1167
+ if (!query) {
1168
+ log(chalk.yellow("Usage: agent <query>"));
1169
+ log(chalk.dim("Example: agent 'buy 0.1 USDC worth of WHALE'"));
1170
+ log(chalk.dim("Example: cat 'check my balance'"));
1171
+ log("");
1172
+ break;
1173
+ }
1174
+ // Check if agent is configured
1175
+ const agentConfig = config.getAIAgentConfig();
1176
+ if (!agentConfig) {
1177
+ log(chalk.yellow("⚠️ Agent not configured"));
1178
+ log(chalk.dim("Run 'agent --setup' to configure the AI agent."));
1179
+ log("");
1180
+ break;
1181
+ }
1182
+ const apiKey = config.getAIAgentApiKey();
1183
+ if (!apiKey) {
1184
+ log(chalk.red("❌ Failed to get API key"));
1185
+ log(chalk.dim("Run 'agent --setup' to configure the API key."));
1186
+ log("");
1187
+ break;
1188
+ }
1189
+ try {
1190
+ // Get account address for session ID
1191
+ const privateKey = config.getPrivateKey();
1192
+ const account = privateKeyToAccount(privateKey);
1193
+ const sessionId = account.address;
1194
+ // Show thinking indicator
1195
+ log(chalk.blue("🐱 Cat thinking..."));
1196
+ screen.render();
1197
+ // Create LLM and agent
1198
+ const llm = createLLM(agentConfig, apiKey);
1199
+ const agent = createHttpcatAgent(client, llm);
1200
+ // Chat with agent (pass session ID so it remembers)
1201
+ const response = await chatWithAgent(agent, llm, query, sessionId);
1202
+ // Display response
1203
+ log("");
1204
+ log(chalk.green("🐱 Cat:"));
1205
+ log(chalk.white(response));
1206
+ log("");
1207
+ }
1208
+ catch (error) {
1209
+ // Enhanced error logging
1210
+ if (process.env.HTTPCAT_DEBUG) {
1211
+ log(chalk.red(`❌ Error details: ${JSON.stringify(error, null, 2)}`));
1212
+ if (error.stack) {
1213
+ log(chalk.dim(error.stack));
1214
+ }
1215
+ }
1216
+ // Check for authentication errors
1217
+ const errorMessage = error?.message || String(error);
1218
+ if (errorMessage.includes("Authentication failed") ||
1219
+ errorMessage.includes("API key") ||
1220
+ errorMessage.includes("401") ||
1221
+ errorMessage.includes("403") ||
1222
+ errorMessage.includes("Unauthorized") ||
1223
+ errorMessage.includes("Invalid API key")) {
1224
+ log(chalk.red("❌ Authentication failed"));
1225
+ log(chalk.dim("Your API key may be invalid or expired."));
1226
+ log(chalk.dim("Run 'agent --setup' to reconfigure."));
1227
+ }
1228
+ else {
1229
+ log(chalk.red(`❌ Error: ${errorMessage}`));
1230
+ }
1231
+ log("");
1232
+ }
1233
+ break;
1234
+ }
910
1235
  default:
911
1236
  log(chalk.red(`Unknown command: ${command}`));
912
1237
  log(chalk.dim('Type "help" for available commands'));
913
1238
  }
914
1239
  }
915
- function displayHelp(log, logLines) {
916
- log("");
917
- log(chalk.green.bold("Available Commands:"));
918
- log("");
919
- log(chalk.green(" create <name> <symbol>"));
920
- log(chalk.green(" buy <id> <amount> [--repeat N] [--delay MS]"));
921
- log(chalk.green(" sell <id> <amount|all>"));
922
- log(chalk.green(" info <id>"));
923
- log(chalk.green(" list [--sort mcap|created|name] [--page N] [--limit N]"));
924
- log(chalk.green(" positions [--active|--graduated]"));
925
- log(chalk.green(" balances"));
926
- log(chalk.green(" claim <id> [--execute] [--address ADDR]"));
927
- log(chalk.green(" transactions [--user ADDR] [--token ID] [--type TYPE] [--limit N] [--offset N]"));
928
- log(chalk.green(" account [list|switch <index>|add]"));
929
- log(chalk.green(" env [list|use <name>|show|add|update]"));
930
- log(chalk.green(" chat [token] [--input-format FORMAT]"));
931
- log(chalk.green(" health"));
932
- log(chalk.green(" config [--show|--set|--reset]"));
933
- log(chalk.green(" network"));
934
- log(chalk.green(" clear"));
935
- log(chalk.green(" help"));
936
- log(chalk.green(" exit"));
937
- log("");
938
- log(chalk.blue("Tip: Run any command without arguments to see detailed help"));
1240
+ function displayWelcomeMessage(log, logLines, outputBox, screen, theme = "dark") {
1241
+ // Helper to get theme-appropriate colors
1242
+ const getCyanColor = (t) => t === "dark" ? "light-cyan-fg" : "cyan-fg";
1243
+ const getBlueColor = (t) => t === "dark" ? "light-blue-fg" : "blue-fg";
1244
+ const cyanColor = getCyanColor(theme);
1245
+ const blueColor = getBlueColor(theme);
1246
+ // If we have outputBox, use blessed tags instead of chalk to avoid question marks
1247
+ // Otherwise fall back to the log function with chalk
1248
+ if (outputBox && screen) {
1249
+ const welcomeLines = [
1250
+ "",
1251
+ `{bold}{${cyanColor}}🐱 Welcome to httpcat!{/${cyanColor}}{/bold}`,
1252
+ "",
1253
+ "{yellow-fg}✨ Here are some commands to get you started:{/yellow-fg}",
1254
+ "",
1255
+ "{green-fg} 📋 list{/green-fg} - Browse all available tokens",
1256
+ "{green-fg} ℹ️ info <token>{/green-fg} - Get detailed info about a token",
1257
+ "{green-fg} 💰 buy <token> <amount>{/green-fg} - Buy tokens (e.g., buy MTK 0.10)",
1258
+ "{green-fg} 💼 positions{/green-fg} - View your portfolio",
1259
+ "{green-fg} 💵 balances{/green-fg} - Check your wallet balance",
1260
+ "",
1261
+ `{${blueColor}}💡 Type {bold}help{/bold} to see all available commands!{/${blueColor}}`,
1262
+ "",
1263
+ ];
1264
+ // Log all welcome lines at once
1265
+ welcomeLines.forEach((line) => outputBox.log(line));
1266
+ // Scroll to top so welcome message is visible
1267
+ outputBox.setScrollPerc(0);
1268
+ screen.render();
1269
+ }
1270
+ else {
1271
+ // Fallback to regular log function if outputBox not available
1272
+ log("");
1273
+ log(chalk.cyan.bold("🐱 Welcome to httpcat!"));
1274
+ log("");
1275
+ log(chalk.yellow("✨ Here are some commands to get you started:"));
1276
+ log("");
1277
+ log(chalk.green(" 📋 list") +
1278
+ chalk.dim(" - Browse all available tokens"));
1279
+ log(chalk.green(" ℹ️ info <token>") +
1280
+ chalk.dim(" - Get detailed info about a token"));
1281
+ log(chalk.green(" 💰 buy <token> <amount>") +
1282
+ chalk.dim(" - Buy tokens (e.g., buy MTK 0.10)"));
1283
+ log(chalk.green(" 💼 positions") +
1284
+ chalk.dim(" - View your portfolio"));
1285
+ log(chalk.green(" 💵 balances") +
1286
+ chalk.dim(" - Check your wallet balance"));
1287
+ log("");
1288
+ log(chalk.blue("💡 Type ") +
1289
+ chalk.bold("help") +
1290
+ chalk.blue(" to see all available commands!"));
1291
+ log("");
1292
+ }
1293
+ }
1294
+ function displayHelp(log, logLines, outputBox, screen, theme = "dark") {
1295
+ // Helper to get theme-appropriate colors
1296
+ const getCyanColor = (t) => t === "dark" ? "light-cyan-fg" : "cyan-fg";
1297
+ const getBlueColor = (t) => t === "dark" ? "light-blue-fg" : "blue-fg";
1298
+ const cyanColor = getCyanColor(theme);
1299
+ const blueColor = getBlueColor(theme);
1300
+ // If we have outputBox, use blessed tags instead of chalk to avoid question marks
1301
+ // Otherwise fall back to the log function
1302
+ if (outputBox && screen) {
1303
+ // Get the line number where help will start (before logging)
1304
+ const linesBeforeHelp = outputBox.lines?.length || 0;
1305
+ // Collect all help lines using blessed tags
1306
+ const helpLines = [
1307
+ "",
1308
+ `{${cyanColor}}{bold}Available Commands:{/bold}{/${cyanColor}}`,
1309
+ "",
1310
+ // Token Operations
1311
+ `{${cyanColor}}{bold}Token Operations:{/bold}{/${cyanColor}}`,
1312
+ "{green-fg} create <name> <symbol>{/green-fg}",
1313
+ "{green-fg} buy <id> <amount> [--repeat N] [--delay MS]{/green-fg}",
1314
+ "{green-fg} sell <id> <amount|all>{/green-fg}",
1315
+ "{green-fg} claim <id> [--execute] [--address ADDR]{/green-fg}",
1316
+ "",
1317
+ // Token Information
1318
+ `{${cyanColor}}{bold}Token Information:{/bold}{/${cyanColor}}`,
1319
+ "{green-fg} info <id>{/green-fg}",
1320
+ "{green-fg} list [--sort mcap|created|name] [--page N] [--limit N]{/green-fg}",
1321
+ "",
1322
+ // Portfolio
1323
+ `{${cyanColor}}{bold}Portfolio:{/bold}{/${cyanColor}}`,
1324
+ "{green-fg} positions [--active|--graduated]{/green-fg}",
1325
+ "{green-fg} transactions [--user ADDR] [--token ID] [--type TYPE] [--limit N] [--offset N]{/green-fg}",
1326
+ "{green-fg} balances{/green-fg}",
1327
+ "",
1328
+ // Account Management
1329
+ `{${cyanColor}}{bold}Account Management:{/bold}{/${cyanColor}}`,
1330
+ "{green-fg} account [list|switch <index>|add]{/green-fg}",
1331
+ "{green-fg} env [list|use <name>|show|add|update]{/green-fg}",
1332
+ "",
1333
+ // Social
1334
+ `{${cyanColor}}{bold}Social:{/bold}{/${cyanColor}}`,
1335
+ "{green-fg} chat [token] [--input-format FORMAT]{/green-fg}",
1336
+ "",
1337
+ // Cat (agent and cat are synonyms)
1338
+ `{${cyanColor}}{bold}Cat (or 'agent'):{/bold}{/${cyanColor}}`,
1339
+ "{green-fg} agent <query>{/green-fg} - Ask the cat to do something (or use 'cat')",
1340
+ "{green-fg} agent --chat{/green-fg} - Enter interactive chat mode (or 'cat --chat')",
1341
+ "{green-fg} agent --setup{/green-fg} - Configure API key/provider (or 'cat --setup')",
1342
+ "",
1343
+ // System
1344
+ `{${cyanColor}}{bold}System:{/bold}{/${cyanColor}}`,
1345
+ "{green-fg} health{/green-fg}",
1346
+ "{green-fg} config [--show|--set|--reset]{/green-fg}",
1347
+ "{green-fg} network{/green-fg}",
1348
+ "",
1349
+ // Shell Commands
1350
+ `{${cyanColor}}{bold}Shell Commands:{/bold}{/${cyanColor}}`,
1351
+ "{green-fg} clear{/green-fg}",
1352
+ "{green-fg} help{/green-fg}",
1353
+ "{green-fg} exit{/green-fg}",
1354
+ "",
1355
+ `{${blueColor}}Tip: Run any command without arguments to see detailed help{/${blueColor}}`,
1356
+ ];
1357
+ // Log all help lines at once
1358
+ helpLines.forEach((line) => outputBox.log(line));
1359
+ // Scroll to show "Available Commands" at the top of the visible area
1360
+ // Get total lines after logging
1361
+ const totalLines = outputBox.lines?.length || 0;
1362
+ const visibleHeight = outputBox.height || 20;
1363
+ if (totalLines > visibleHeight && linesBeforeHelp >= 0) {
1364
+ // Calculate which line "Available Commands" is on (after the empty line)
1365
+ const availableCommandsLine = linesBeforeHelp + 1;
1366
+ // Calculate scroll percentage to show that line at the top
1367
+ // Percentage = (line number / total lines) * 100
1368
+ // But we want the line to be at the top, so we need to account for visible height
1369
+ const scrollPerc = Math.max(0, Math.min(100, ((availableCommandsLine - 1) /
1370
+ Math.max(1, totalLines - visibleHeight)) *
1371
+ 100));
1372
+ outputBox.setScrollPerc(scrollPerc);
1373
+ }
1374
+ else {
1375
+ // If all content fits in visible area or no previous content, scroll to top
1376
+ outputBox.setScrollPerc(0);
1377
+ }
1378
+ screen.render();
1379
+ }
1380
+ else {
1381
+ // Fallback to regular log function if outputBox not available
1382
+ log("");
1383
+ log(chalk.cyan.bold("Available Commands:"));
1384
+ log("");
1385
+ // Token Operations
1386
+ log(chalk.bold(chalk.cyan("Token Operations:")));
1387
+ log(chalk.green(" create <name> <symbol>"));
1388
+ log(chalk.green(" buy <id> <amount> [--repeat N] [--delay MS]"));
1389
+ log(chalk.green(" sell <id> <amount|all>"));
1390
+ log(chalk.green(" claim <id> [--execute] [--address ADDR]"));
1391
+ log("");
1392
+ // Token Information
1393
+ log(chalk.bold(chalk.cyan("Token Information:")));
1394
+ log(chalk.green(" info <id>"));
1395
+ log(chalk.green(" list [--sort mcap|created|name] [--page N] [--limit N]"));
1396
+ log("");
1397
+ // Portfolio
1398
+ log(chalk.bold(chalk.cyan("Portfolio:")));
1399
+ log(chalk.green(" positions [--active|--graduated]"));
1400
+ log(chalk.green(" transactions [--user ADDR] [--token ID] [--type TYPE] [--limit N] [--offset N]"));
1401
+ log(chalk.green(" balances"));
1402
+ log("");
1403
+ // Account Management
1404
+ log(chalk.bold(chalk.cyan("Account Management:")));
1405
+ log(chalk.green(" account [list|switch <index>|add]"));
1406
+ log(chalk.green(" env [list|use <name>|show|add|update]"));
1407
+ log("");
1408
+ // Social
1409
+ log(chalk.bold(chalk.cyan("Social:")));
1410
+ log(chalk.green(" chat [token] [--input-format FORMAT]"));
1411
+ log("");
1412
+ // Cat (agent and cat are synonyms)
1413
+ log(chalk.bold(chalk.cyan("Cat (or 'agent'):")));
1414
+ log(chalk.green(" agent <query>") +
1415
+ chalk.dim(" - Ask the cat to do something (or use 'cat')"));
1416
+ log(chalk.green(" agent --chat") +
1417
+ chalk.dim(" - Enter interactive chat mode (or 'cat --chat')"));
1418
+ log(chalk.green(" agent --setup") +
1419
+ chalk.dim(" - Configure API key/provider (or 'cat --setup')"));
1420
+ log("");
1421
+ // System
1422
+ log(chalk.bold(chalk.cyan("System:")));
1423
+ log(chalk.green(" health"));
1424
+ log(chalk.green(" config [--show|--set|--reset]"));
1425
+ log(chalk.green(" network"));
1426
+ log("");
1427
+ // Shell Commands
1428
+ log(chalk.bold(chalk.cyan("Shell Commands:")));
1429
+ log(chalk.green(" clear"));
1430
+ log(chalk.green(" help"));
1431
+ log(chalk.green(" exit"));
1432
+ log("");
1433
+ log(chalk.blue("Tip: Run any command without arguments to see detailed help"));
1434
+ }
939
1435
  }
940
1436
  function displayConfigToLog(log, logLines) {
941
1437
  const cfg = config.getAll();
@@ -972,43 +1468,141 @@ function displayBuyResultToLog(result, log, logLines) {
972
1468
  }
973
1469
  function displaySellResultToLog(result, log, logLines) {
974
1470
  log(chalk.green("Sale successful!"));
975
- log(chalk.blue("Tokens sold: ") + chalk.green(result.tokensSold));
976
- log(chalk.blue("USDC received: ") + chalk.yellow(result.usdcReceived));
977
- log(chalk.blue("New price: ") + chalk.green(result.newPrice));
978
- log(chalk.blue("Graduation: ") +
979
- chalk.magenta(result.graduationProgress.toFixed(2) + "%"));
1471
+ log(chalk.blue("Tokens sold: ") +
1472
+ chalk.green(formatTokenAmount(result.tokensSold || "0")));
1473
+ log(chalk.blue("USDC received: ") +
1474
+ chalk.yellow(formatCurrency(result.usdcReceived || "0", 6)));
1475
+ if (result.fee) {
1476
+ log(chalk.blue("Fee (1%): ") + chalk.yellow(formatCurrency(result.fee, 6)));
1477
+ }
1478
+ if (result.newPrice) {
1479
+ log(chalk.blue("New price: ") + chalk.green(formatCurrency(result.newPrice)));
1480
+ }
1481
+ if (result.newMcap) {
1482
+ log(chalk.blue("New market cap: ") +
1483
+ chalk.yellow(formatCurrency(result.newMcap)));
1484
+ }
1485
+ if (result.graduationProgress !== undefined) {
1486
+ log(chalk.blue("Graduation: ") +
1487
+ chalk.magenta(result.graduationProgress.toFixed(2) + "%"));
1488
+ }
1489
+ if (result.txHash) {
1490
+ log(chalk.blue("Transaction: ") + chalk.green(result.txHash));
1491
+ }
1492
+ else if (result.usdcTransferTx) {
1493
+ log(chalk.blue("Transaction: ") + chalk.green(result.usdcTransferTx));
1494
+ }
1495
+ // Graduation progress bar
1496
+ if (result.graduationProgress !== undefined) {
1497
+ const barLength = 20;
1498
+ const filled = Math.floor((result.graduationProgress / 100) * barLength);
1499
+ const empty = barLength - filled;
1500
+ const bar = "🐱" + "=".repeat(filled) + ">" + " ".repeat(empty);
1501
+ log(chalk.yellow(`[${bar}] ${chalk.bold(result.graduationProgress.toFixed(2) + "%")} to moon!`));
1502
+ }
1503
+ // Display price impact warning for Uniswap swaps
1504
+ if (result.source === "uniswap_v2" && result.priceImpact !== undefined) {
1505
+ if (result.priceImpact < 0.5) {
1506
+ log(chalk.green(`Price Impact: ${result.priceImpact.toFixed(2)}%`));
1507
+ }
1508
+ else if (result.priceImpact < 1) {
1509
+ log(chalk.yellow(`Price Impact: ${result.priceImpact.toFixed(2)}%`));
1510
+ }
1511
+ else if (result.priceImpact < 3) {
1512
+ log(chalk.red(`⚠️ HIGH Price Impact: ${result.priceImpact.toFixed(2)}%`));
1513
+ }
1514
+ else {
1515
+ log(chalk.red(`🚨 VERY HIGH Price Impact: ${result.priceImpact.toFixed(2)}%`));
1516
+ }
1517
+ }
1518
+ // Display route info for Uniswap swaps
1519
+ if (result.source === "uniswap_v2" && result.route) {
1520
+ const feePercent = result.routeFee
1521
+ ? (result.routeFee / 10000).toFixed(2)
1522
+ : "N/A";
1523
+ log(chalk.cyan(`Route: ${result.route} (${feePercent}% fee)`));
1524
+ }
980
1525
  }
981
1526
  function displayTokenInfoToLog(info, log, logLines) {
982
- log(chalk.green.bold(info.name) + ` (${info.symbol})`);
983
- if (info.tokenAddress) {
984
- log(chalk.blue("Address: ") + chalk.green(info.tokenAddress));
985
- }
986
- log(chalk.blue("Price: ") + chalk.green(info.currentPrice));
987
- log(chalk.blue("Market Cap: ") + chalk.yellow(info.marketCap));
988
- log(chalk.blue("Supply: ") + chalk.green(info.totalSupply));
1527
+ log("");
1528
+ // Token header box
1529
+ const priceDisplay = info.status === "graduated"
1530
+ ? chalk.dim("--")
1531
+ : info.price
1532
+ ? formatCurrency(info.price)
1533
+ : chalk.dim("N/A");
1534
+ const mcapDisplay = info.status === "graduated"
1535
+ ? chalk.dim("--")
1536
+ : info.mcap
1537
+ ? formatCurrency(info.mcap)
1538
+ : chalk.dim("N/A");
1539
+ // Create box-like display
1540
+ log(chalk.green.bold(`📊 ${info.name} (${info.symbol})`));
1541
+ log(chalk.dim("─".repeat(60)));
1542
+ log(chalk.blue("Address: ") + chalk.green(formatAddress(info.address || "")));
1543
+ log(chalk.blue("Status: ") + chalk.green(info.status || "unknown"));
1544
+ log(chalk.blue("Price: ") + chalk.green(priceDisplay));
1545
+ log(chalk.blue("Market Cap: ") + chalk.yellow(mcapDisplay));
1546
+ log(chalk.blue("Total Supply: ") +
1547
+ chalk.green(formatTokenAmount(info.totalSupply || "0")));
1548
+ log(chalk.blue("Created: ") +
1549
+ chalk.green(new Date(info.createdAt || Date.now()).toLocaleString()));
1550
+ log("");
1551
+ // Graduation progress
989
1552
  if (info.graduationProgress !== undefined) {
990
- log(chalk.blue("Graduation: ") +
991
- chalk.magenta(info.graduationProgress.toFixed(2) + "%"));
1553
+ const barLength = 20;
1554
+ const filled = Math.floor((info.graduationProgress / 100) * barLength);
1555
+ const empty = barLength - filled;
1556
+ const bar = "🐱" + "=".repeat(filled) + ">" + " ".repeat(empty);
1557
+ log(chalk.yellow(`[${bar}] ${chalk.bold(info.graduationProgress.toFixed(2) + "%")} to moon!`));
1558
+ log("");
992
1559
  }
1560
+ // Position display
993
1561
  if (info.userPosition && info.userPosition.tokensOwned !== "0") {
994
- log(chalk.blue("Your position: ") +
995
- chalk.green(info.userPosition.tokensOwned + " tokens"));
1562
+ log(chalk.green.bold("💼 Your Position"));
1563
+ log(chalk.dim("".repeat(60)));
1564
+ log(chalk.blue("Tokens Owned: ") +
1565
+ chalk.green(formatTokenAmount(info.userPosition.tokensOwned)));
1566
+ log(chalk.blue("Invested: ") +
1567
+ chalk.green(formatCurrency(info.userPosition.usdcInvested || "0")));
1568
+ if (info.userPosition.currentValue) {
1569
+ log(chalk.blue("Current Value: ") +
1570
+ chalk.green(formatCurrency(info.userPosition.currentValue)));
1571
+ }
1572
+ if (info.userPosition.pnl) {
1573
+ const pnl = parseFloat(info.userPosition.pnl);
1574
+ const pnlColor = pnl >= 0 ? chalk.green : chalk.red;
1575
+ const pnlSign = pnl >= 0 ? "+" : "";
1576
+ const pnlIcon = pnl >= 0 ? "🟢" : "🔴";
1577
+ log(chalk.blue("P&L: ") +
1578
+ `${pnlIcon} ${pnlColor(pnlSign + formatCurrency(info.userPosition.pnl))}`);
1579
+ }
1580
+ log("");
996
1581
  }
997
1582
  }
998
- function displayTokenListToLog(result, log, logLines) {
999
- log("");
1000
- log(chalk.green.bold(`Tokens (${result.total || result.tokens.length} total):`));
1583
+ function displayTokenListToLog(result, log, logLines, logLinesSmooth) {
1584
+ // Collect all lines first for smooth scrolling
1585
+ const allLines = [];
1586
+ allLines.push("");
1587
+ allLines.push(chalk.green.bold(`Tokens (${result.total || result.tokens.length} total):`));
1001
1588
  if (result.page && result.pages) {
1002
- log(chalk.dim(`Page ${result.page} of ${result.pages}`));
1589
+ allLines.push(chalk.dim(`Page ${result.page} of ${result.pages}`));
1003
1590
  }
1004
- log("");
1591
+ allLines.push("");
1005
1592
  if (result.tokens.length === 0) {
1006
- log(chalk.yellow("No tokens found."));
1593
+ allLines.push(chalk.yellow("No tokens found."));
1594
+ // Use smooth scrolling if available, otherwise regular logLines
1595
+ if (logLinesSmooth) {
1596
+ logLinesSmooth(allLines, false);
1597
+ }
1598
+ else {
1599
+ logLines(allLines);
1600
+ }
1007
1601
  return;
1008
1602
  }
1009
1603
  // Show header
1010
- log(` ${chalk.cyan.bold("Name".padEnd(20))} ${chalk.cyan.bold("Symbol".padEnd(10))} ${chalk.cyan.bold("Market Cap".padEnd(15))} ${chalk.cyan.bold("Price".padEnd(12))} ${chalk.cyan.bold("Graduation".padEnd(12))} ${chalk.cyan.bold("Status")}`);
1011
- log(chalk.dim(" " + "─".repeat(90)));
1604
+ allLines.push(` ${chalk.cyan.bold("Name".padEnd(20))} ${chalk.cyan.bold("Symbol".padEnd(10))} ${chalk.cyan.bold("Market Cap".padEnd(15))} ${chalk.cyan.bold("Price".padEnd(12))} ${chalk.cyan.bold("Graduation".padEnd(12))} ${chalk.cyan.bold("Status")}`);
1605
+ allLines.push(chalk.dim(" " + "─".repeat(90)));
1012
1606
  // Show tokens
1013
1607
  for (const token of result.tokens) {
1014
1608
  const graduationIcon = token.status === "graduated"
@@ -1028,21 +1622,28 @@ function displayTokenListToLog(result, log, logLines) {
1028
1622
  const statusDisplay = token.status === "graduated"
1029
1623
  ? chalk.green("✓ Graduated")
1030
1624
  : chalk.yellow("Active");
1031
- log(` ${chalk.bold(token.name.padEnd(20))} ${chalk.green(token.symbol.padEnd(10))} ${mcapDisplay.padEnd(15)} ${priceDisplay.padEnd(12)} ${graduationDisplay.padEnd(12)} ${statusDisplay}`);
1625
+ allLines.push(` ${chalk.bold(token.name.padEnd(20))} ${chalk.green(token.symbol.padEnd(10))} ${mcapDisplay.padEnd(15)} ${priceDisplay.padEnd(12)} ${graduationDisplay.padEnd(12)} ${statusDisplay}`);
1032
1626
  }
1033
- log("");
1627
+ allLines.push("");
1034
1628
  if (result.page && result.pages && result.page < result.pages) {
1035
- log(chalk.dim(`Use --page ${result.page + 1} to see more tokens`));
1036
- log("");
1629
+ allLines.push(chalk.dim(`Use --page ${result.page + 1} to see more tokens`));
1630
+ allLines.push("");
1037
1631
  }
1038
1632
  // Show example commands
1039
1633
  if (result.tokens.length > 0) {
1040
1634
  const firstToken = result.tokens[0];
1041
- log(chalk.dim("Example commands:"));
1042
- log(chalk.dim(` buy ${firstToken.symbol}`));
1043
- log(chalk.dim(` sell ${firstToken.symbol}`));
1044
- log(chalk.dim(` info ${firstToken.symbol}`));
1045
- log("");
1635
+ allLines.push(chalk.dim("Example commands:"));
1636
+ allLines.push(chalk.dim(` buy ${firstToken.symbol}`));
1637
+ allLines.push(chalk.dim(` sell ${firstToken.symbol}`));
1638
+ allLines.push(chalk.dim(` info ${firstToken.symbol}`));
1639
+ allLines.push("");
1640
+ }
1641
+ // Use smooth scrolling if available (scrolls to show the list header), otherwise regular logLines
1642
+ if (logLinesSmooth) {
1643
+ logLinesSmooth(allLines, true); // scrollToTop=true to show the list header
1644
+ }
1645
+ else {
1646
+ logLines(allLines);
1046
1647
  }
1047
1648
  }
1048
1649
  function displayPositionsToLog(result, log, logLines) {
@@ -1053,11 +1654,19 @@ function displayPositionsToLog(result, log, logLines) {
1053
1654
  log(chalk.green.bold(`Your Positions (${result.positions.length}):`));
1054
1655
  log("");
1055
1656
  for (const pos of result.positions) {
1056
- log(` ${chalk.green(pos.symbol || "???")} - ${chalk.green(pos.tokensOwned + " tokens")} @ ${chalk.yellow(pos.currentValue || "N/A")}`);
1657
+ const tokenName = pos.token?.name || "???";
1658
+ const tokenSymbol = pos.token?.symbol || "???";
1659
+ const tokensDisplay = formatTokenAmount(pos.tokensOwned || "0");
1660
+ const valueDisplay = pos.currentValue
1661
+ ? formatCurrency(pos.currentValue)
1662
+ : "N/A";
1663
+ log(` ${chalk.green.bold(`${tokenName} (${tokenSymbol})`)} - ${chalk.green(`${tokensDisplay} tokens`)} @ ${chalk.yellow(valueDisplay)}`);
1057
1664
  }
1058
1665
  }
1059
1666
  function displayHealthStatusToLog(health, log, logLines) {
1060
- const statusColor = health.status === "ok" || health.status === "healthy" ? chalk.green : chalk.red;
1667
+ const statusColor = health.status === "ok" || health.status === "healthy"
1668
+ ? chalk.green
1669
+ : chalk.red;
1061
1670
  log(statusColor(`Agent Status: ${health.status}`));
1062
1671
  if (health.version) {
1063
1672
  log(chalk.blue("Version: ") + chalk.green(health.version));
@@ -1070,15 +1679,19 @@ function displayBalanceToLog(balance, log, logLines) {
1070
1679
  log("");
1071
1680
  log(chalk.green.bold("Wallet Balance:"));
1072
1681
  log(chalk.blue("Address: ") + chalk.green(balance.address));
1073
- log(chalk.blue("ETH: ") + chalk.yellow(balance.ethFormatted || balance.ethBalance));
1074
- log(chalk.blue("USDC: ") + chalk.green(balance.usdcFormatted || balance.usdcBalance));
1682
+ log(chalk.blue("ETH: ") +
1683
+ chalk.yellow(balance.ethFormatted || balance.ethBalance));
1684
+ log(chalk.blue("USDC: ") +
1685
+ chalk.green(balance.usdcFormatted || balance.usdcBalance));
1075
1686
  if (balance.cat402Formatted) {
1076
1687
  log(chalk.blue("CAT: ") + chalk.cyan(balance.cat402Formatted));
1077
1688
  }
1078
1689
  log("");
1079
1690
  // Show warnings if balances are low
1080
1691
  const ethNum = Number(balance.ethFormatted || balance.ethBalance);
1081
- const usdcNum = Number((balance.usdcFormatted || balance.usdcBalance).replace("$", "").replace(",", ""));
1692
+ const usdcNum = Number((balance.usdcFormatted || balance.usdcBalance)
1693
+ .replace("$", "")
1694
+ .replace(",", ""));
1082
1695
  if (ethNum < 0.001 && usdcNum < 1) {
1083
1696
  log(chalk.yellow("⚠️ Low balances detected!"));
1084
1697
  log(chalk.dim(" You need Base Sepolia ETH for gas fees"));
@@ -1109,7 +1722,8 @@ function displayFeesToLog(fees, log, logLines) {
1109
1722
  log(chalk.green.bold(`💰 Accumulated Fees: ${fees.tokenName} (${fees.tokenSymbol})`));
1110
1723
  log(chalk.blue("━".repeat(50)));
1111
1724
  log(chalk.blue("Contract: ") + chalk.green(fees.tokenAddress));
1112
- log(chalk.blue("LP Status: ") + chalk.green(fees.isLocked ? "🔒 Locked" : "❌ Not Locked"));
1725
+ log(chalk.blue("LP Status: ") +
1726
+ chalk.green(fees.isLocked ? "🔒 Locked" : "❌ Not Locked"));
1113
1727
  if (typeof fees.v4TickLower === "number" &&
1114
1728
  typeof fees.v4TickUpper === "number" &&
1115
1729
  typeof fees.v4TickCurrent === "number" &&
@@ -1120,7 +1734,8 @@ function displayFeesToLog(fees, log, logLines) {
1120
1734
  log("");
1121
1735
  log(chalk.green("Total Fees:"));
1122
1736
  log(chalk.blue(" Tokens: ") + chalk.green(hasFeesToken ? fees.feeToken : "0"));
1123
- log(chalk.blue(" USDC: ") + chalk.green(hasFeesPaired ? fees.feePaired : "$0.00"));
1737
+ log(chalk.blue(" USDC: ") +
1738
+ chalk.green(hasFeesPaired ? fees.feePaired : "$0.00"));
1124
1739
  log("");
1125
1740
  log(chalk.green("Creator Share (80%):"));
1126
1741
  log(chalk.blue(" Tokens: ") + chalk.green(fees.creatorToken || "0"));
@@ -1185,7 +1800,8 @@ function displayAccountInfoToLog(data, log, logLines) {
1185
1800
  log(chalk.blue("=".repeat(50)));
1186
1801
  log("");
1187
1802
  log(chalk.blue("Account Index: ") + chalk.green(account.index.toString()));
1188
- log(chalk.blue("Type: ") + chalk.green(account.type === "custom" ? "Custom" : "Seed-Derived"));
1803
+ log(chalk.blue("Type: ") +
1804
+ chalk.green(account.type === "custom" ? "Custom" : "Seed-Derived"));
1189
1805
  log(chalk.blue("Address: ") + chalk.green(account.address));
1190
1806
  if (account.label) {
1191
1807
  log(chalk.blue("Label: ") + chalk.green(account.label));
@@ -1204,4 +1820,483 @@ function displayAccountInfoToLog(data, log, logLines) {
1204
1820
  displayPositionsToLog(data.positions, log, logLines);
1205
1821
  }
1206
1822
  }
1823
+ // Helper function to format time remaining for lease
1824
+ function formatTimeRemaining(expiresAt) {
1825
+ const now = new Date();
1826
+ const diffMs = expiresAt.getTime() - now.getTime();
1827
+ if (diffMs <= 0) {
1828
+ return "expired";
1829
+ }
1830
+ const minutes = Math.floor(diffMs / 60000);
1831
+ const seconds = Math.floor((diffMs % 60000) / 1000);
1832
+ if (minutes > 0) {
1833
+ return `${minutes}m ${seconds}s`;
1834
+ }
1835
+ return `${seconds}s`;
1836
+ }
1837
+ // Helper function to build chat header content
1838
+ async function buildChatHeaderContent(theme, tokenInfo, tokenIdentifier, isConnected, leaseInfo, getCyanColor) {
1839
+ const colorTag = theme === "dark" ? "green-fg" : "black-fg";
1840
+ const cyanColor = getCyanColor(theme);
1841
+ const lines = [];
1842
+ // Title line
1843
+ if (tokenInfo) {
1844
+ lines.push(`{${colorTag}}💬 httpcat Chat: {${cyanColor}}${tokenInfo.name} (${tokenInfo.symbol}){/${cyanColor}}{/${colorTag}}`);
1845
+ }
1846
+ else if (tokenIdentifier) {
1847
+ // Fallback to identifier if token lookup failed
1848
+ const displayId = tokenIdentifier.length > 20
1849
+ ? `${tokenIdentifier.slice(0, 10)}...${tokenIdentifier.slice(-6)}`
1850
+ : tokenIdentifier;
1851
+ lines.push(`{${colorTag}}💬 httpcat Chat: {${cyanColor}}${displayId}{/${cyanColor}}{/${colorTag}}`);
1852
+ }
1853
+ else {
1854
+ lines.push(`{${colorTag}}💬 httpcat Chat: General{/${colorTag}}`);
1855
+ }
1856
+ lines.push(`{${colorTag}}${"═".repeat(60)}{/${colorTag}}`);
1857
+ lines.push("");
1858
+ // Connection status
1859
+ if (isConnected) {
1860
+ lines.push(`{green-fg}✅ Connected to chat stream{/green-fg}`);
1861
+ lines.push("");
1862
+ }
1863
+ // Lease info
1864
+ if (leaseInfo) {
1865
+ const timeRemaining = formatTimeRemaining(leaseInfo.leaseExpiresAt);
1866
+ const isExpired = leaseInfo.leaseExpiresAt.getTime() <= Date.now();
1867
+ const timePrefix = isExpired ? "⚠️ " : "⏱️ ";
1868
+ lines.push(`{yellow-fg}${timePrefix}Lease expires in: ${timeRemaining}{/yellow-fg}`);
1869
+ }
1870
+ lines.push("");
1871
+ lines.push(`{${cyanColor}}💡 Type your message and press Enter to send{/${cyanColor}}`);
1872
+ lines.push(`{${cyanColor}}💡 Type /exit to return to shell{/${cyanColor}}`);
1873
+ lines.push(`{${cyanColor}}💡 Type /renew to renew your lease{/${cyanColor}}`);
1874
+ if (tokenIdentifier) {
1875
+ lines.push(`{${cyanColor}}💡 Type /buy <amount> to buy tokens{/${cyanColor}}`);
1876
+ lines.push(`{${cyanColor}}💡 Type /sell <amount> to sell tokens{/${cyanColor}}`);
1877
+ }
1878
+ return lines.join("\n");
1879
+ }
1880
+ // Simplified chat mode that works within the shell
1881
+ async function startChatInShell(client, tokenIdentifier, log, logLines, screen, inputBox, originalSubmitHandler, headerBox, buildWelcomeContent, currentTheme, catFaces, currentCatIndex) {
1882
+ const privateKey = config.getPrivateKey();
1883
+ const account = privateKeyToAccount(privateKey);
1884
+ const userAddress = account.address;
1885
+ let leaseInfo = null;
1886
+ let ws = null;
1887
+ let isInChatMode = true;
1888
+ let isProcessing = false; // Flag to prevent duplicate processing
1889
+ const displayedMessageIds = new Set();
1890
+ // Helper to format chat messages
1891
+ const formatChatMessage = (msg, isOwn = false) => {
1892
+ const date = new Date(msg.timestamp);
1893
+ const now = new Date();
1894
+ const diffMs = now.getTime() - date.getTime();
1895
+ const diffSec = Math.floor(diffMs / 1000);
1896
+ const diffMin = Math.floor(diffSec / 60);
1897
+ let timeStr = "just now";
1898
+ if (diffSec >= 60) {
1899
+ timeStr =
1900
+ diffMin < 60
1901
+ ? `${diffMin}m ago`
1902
+ : date.toLocaleTimeString("en-US", {
1903
+ hour: "2-digit",
1904
+ minute: "2-digit",
1905
+ });
1906
+ }
1907
+ const authorColor = isOwn ? chalk.green : chalk.cyan;
1908
+ const authorShort = msg.authorShort || formatAddress(msg.author, 6);
1909
+ return `${chalk.dim(`[${timeStr}]`)} ${authorColor(authorShort)}: ${msg.message}`;
1910
+ };
1911
+ // Get token information if it's a token chat
1912
+ let tokenInfo = null;
1913
+ if (tokenIdentifier) {
1914
+ try {
1915
+ const info = await getTokenInfo(client, tokenIdentifier, userAddress, true);
1916
+ tokenInfo = { name: info.name, symbol: info.symbol };
1917
+ }
1918
+ catch (error) {
1919
+ // Token lookup failed - will use identifier in header
1920
+ tokenInfo = null;
1921
+ }
1922
+ }
1923
+ // Helper to get cyan color based on theme
1924
+ const getCyanColor = (theme) => theme === "dark" ? "light-cyan-fg" : "cyan-fg";
1925
+ // Helper to update header
1926
+ const updateChatHeader = async (isConnected = false) => {
1927
+ const content = await buildChatHeaderContent(currentTheme, tokenInfo, tokenIdentifier, isConnected, leaseInfo, getCyanColor);
1928
+ headerBox.setContent(content);
1929
+ screen.render();
1930
+ };
1931
+ // Update header to show chat mode
1932
+ await updateChatHeader(false);
1933
+ // Set up header update interval for lease countdown
1934
+ let headerUpdateInterval = null;
1935
+ try {
1936
+ // Join chat
1937
+ log(chalk.blue("Joining chat..."));
1938
+ screen.render();
1939
+ const joinResult = await joinChat(client, userAddress, tokenIdentifier, true);
1940
+ leaseInfo = {
1941
+ leaseId: joinResult.leaseId,
1942
+ leaseExpiresAt: new Date(joinResult.leaseExpiresAt),
1943
+ };
1944
+ // Update header with lease info
1945
+ await updateChatHeader(false);
1946
+ // Display last messages
1947
+ if (joinResult.lastMessages.length > 0) {
1948
+ log(chalk.dim("─".repeat(60)));
1949
+ log(chalk.cyan.bold("Recent messages:"));
1950
+ for (const msg of joinResult.lastMessages) {
1951
+ displayedMessageIds.add(msg.messageId);
1952
+ const isOwn = msg.author.toLowerCase() === userAddress.toLowerCase();
1953
+ log(formatChatMessage(msg, isOwn));
1954
+ }
1955
+ log(chalk.dim("─".repeat(60)));
1956
+ }
1957
+ // Connect to WebSocket
1958
+ const agentUrl = client.getAgentUrl();
1959
+ const normalizedWsUrl = normalizeWebSocketUrl(joinResult.wsUrl, agentUrl);
1960
+ const wsUrlObj = new URL(normalizedWsUrl);
1961
+ wsUrlObj.searchParams.set("leaseId", joinResult.leaseId);
1962
+ await new Promise((resolve) => setTimeout(resolve, 500));
1963
+ ws = new WebSocket(wsUrlObj.toString());
1964
+ ws.on("open", () => {
1965
+ log(chalk.green("✅ Connected to chat stream"));
1966
+ updateChatHeader(true);
1967
+ screen.render();
1968
+ });
1969
+ ws.on("message", (data) => {
1970
+ try {
1971
+ const event = JSON.parse(data.toString());
1972
+ if (event.type === "message" && event.data) {
1973
+ const msg = {
1974
+ ...event.data,
1975
+ authorShort: formatAddress(event.data.author, 6),
1976
+ };
1977
+ if (!displayedMessageIds.has(msg.messageId)) {
1978
+ displayedMessageIds.add(msg.messageId);
1979
+ const isOwn = msg.author.toLowerCase() === userAddress.toLowerCase();
1980
+ log(formatChatMessage(msg, isOwn));
1981
+ screen.render();
1982
+ }
1983
+ }
1984
+ else if (event.type === "lease_expired") {
1985
+ log(chalk.yellow("⏱️ Your lease has expired. Type /renew to continue."));
1986
+ leaseInfo = null;
1987
+ updateChatHeader(true);
1988
+ screen.render();
1989
+ }
1990
+ }
1991
+ catch (error) {
1992
+ // Ignore parse errors
1993
+ }
1994
+ });
1995
+ ws.on("error", (error) => {
1996
+ log(chalk.red(`❌ WebSocket error: ${error.message}`));
1997
+ screen.render();
1998
+ });
1999
+ ws.on("close", () => {
2000
+ if (isInChatMode) {
2001
+ log(chalk.yellow("⚠️ WebSocket connection closed"));
2002
+ updateChatHeader(false);
2003
+ screen.render();
2004
+ }
2005
+ });
2006
+ // Start header update interval
2007
+ headerUpdateInterval = setInterval(async () => {
2008
+ if (leaseInfo && isInChatMode) {
2009
+ await updateChatHeader(true);
2010
+ }
2011
+ }, 1000);
2012
+ // Wait for connection
2013
+ await new Promise((resolve, reject) => {
2014
+ const timeout = setTimeout(() => reject(new Error("Connection timeout")), 10000);
2015
+ ws.once("open", () => {
2016
+ clearTimeout(timeout);
2017
+ resolve();
2018
+ });
2019
+ ws.once("error", (err) => {
2020
+ clearTimeout(timeout);
2021
+ reject(err);
2022
+ });
2023
+ });
2024
+ // Set up chat input handler
2025
+ const chatInputHandler = async (value) => {
2026
+ const trimmed = value.trim();
2027
+ // Clear input immediately
2028
+ inputBox.clearValue();
2029
+ screen.render();
2030
+ if (!trimmed) {
2031
+ isProcessing = false;
2032
+ inputBox.focus();
2033
+ screen.render();
2034
+ return;
2035
+ }
2036
+ // Handle commands
2037
+ if (trimmed.startsWith("/")) {
2038
+ const [cmd, ...cmdArgs] = trimmed.split(" ");
2039
+ switch (cmd) {
2040
+ case "/exit":
2041
+ case "/quit":
2042
+ isInChatMode = false;
2043
+ if (headerUpdateInterval) {
2044
+ clearInterval(headerUpdateInterval);
2045
+ headerUpdateInterval = null;
2046
+ }
2047
+ if (ws) {
2048
+ ws.close();
2049
+ ws = null;
2050
+ }
2051
+ log(chalk.yellow("Exited chat mode. Back to shell."));
2052
+ log("");
2053
+ // Restore original header
2054
+ const originalContent = await buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face);
2055
+ headerBox.setContent(originalContent);
2056
+ // Restore original input handler
2057
+ inputBox.removeAllListeners("submit");
2058
+ inputBox.on("submit", originalSubmitHandler);
2059
+ isProcessing = false;
2060
+ inputBox.focus();
2061
+ screen.render();
2062
+ return;
2063
+ case "/renew":
2064
+ try {
2065
+ log(chalk.blue("Renewing lease..."));
2066
+ screen.render();
2067
+ const renewal = await renewLease(client, userAddress, leaseInfo?.leaseId);
2068
+ leaseInfo = {
2069
+ leaseId: renewal.leaseId,
2070
+ leaseExpiresAt: new Date(renewal.leaseExpiresAt),
2071
+ };
2072
+ await updateChatHeader(true);
2073
+ log(chalk.green("✅ Lease renewed!"));
2074
+ screen.render();
2075
+ }
2076
+ catch (error) {
2077
+ log(chalk.red(`❌ Renew failed: ${error instanceof Error ? error.message : String(error)}`));
2078
+ screen.render();
2079
+ }
2080
+ isProcessing = false;
2081
+ inputBox.focus();
2082
+ screen.render();
2083
+ return;
2084
+ case "/help":
2085
+ log(chalk.cyan("Chat commands: /exit, /quit, /renew, /help"));
2086
+ screen.render();
2087
+ isProcessing = false;
2088
+ inputBox.focus();
2089
+ screen.render();
2090
+ return;
2091
+ default:
2092
+ log(chalk.yellow(`Unknown command: ${cmd}. Type /help for commands.`));
2093
+ screen.render();
2094
+ isProcessing = false;
2095
+ inputBox.focus();
2096
+ screen.render();
2097
+ return;
2098
+ }
2099
+ }
2100
+ // Send message
2101
+ if (!leaseInfo || leaseInfo.leaseExpiresAt.getTime() <= Date.now()) {
2102
+ log(chalk.yellow("⏱️ Your lease has expired. Type /renew to continue."));
2103
+ screen.render();
2104
+ isProcessing = false;
2105
+ inputBox.focus();
2106
+ screen.render();
2107
+ return;
2108
+ }
2109
+ try {
2110
+ // Send message - it will appear via WebSocket when received
2111
+ await sendChatMessage(client, trimmed, leaseInfo.leaseId, userAddress);
2112
+ // Re-attach handler for next message
2113
+ inputBox.removeAllListeners("submit");
2114
+ inputBox.once("submit", chatInputHandler);
2115
+ isProcessing = false;
2116
+ inputBox.focus();
2117
+ screen.render();
2118
+ }
2119
+ catch (error) {
2120
+ log(chalk.red(`❌ Send failed: ${error instanceof Error ? error.message : String(error)}`));
2121
+ screen.render();
2122
+ // Re-attach handler for next message
2123
+ inputBox.removeAllListeners("submit");
2124
+ inputBox.once("submit", chatInputHandler);
2125
+ isProcessing = false;
2126
+ inputBox.focus();
2127
+ screen.render();
2128
+ }
2129
+ };
2130
+ // Temporarily replace input handler
2131
+ // Remove all listeners first to ensure clean state
2132
+ inputBox.removeAllListeners("submit");
2133
+ // Clear any existing input value to prevent state issues
2134
+ inputBox.clearValue();
2135
+ // Add the chat handler - only one handler should be active
2136
+ inputBox.once("submit", chatInputHandler);
2137
+ // Ensure input box has focus and is ready
2138
+ inputBox.focus();
2139
+ screen.render();
2140
+ }
2141
+ catch (error) {
2142
+ log(chalk.red(`❌ Chat error: ${error instanceof Error ? error.message : String(error)}`));
2143
+ if (headerUpdateInterval) {
2144
+ clearInterval(headerUpdateInterval);
2145
+ headerUpdateInterval = null;
2146
+ }
2147
+ if (ws)
2148
+ ws.close();
2149
+ // Restore original header on error
2150
+ const originalContent = await buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face);
2151
+ headerBox.setContent(originalContent);
2152
+ // Restore original handler on error
2153
+ inputBox.removeAllListeners("submit");
2154
+ inputBox.on("submit", originalSubmitHandler);
2155
+ screen.render();
2156
+ inputBox.focus();
2157
+ screen.render();
2158
+ }
2159
+ }
2160
+ /**
2161
+ * Start agent chat mode (similar to startChatInShell)
2162
+ */
2163
+ async function startAgentChatMode(client, log, logLines, screen, inputBox, headerBox, buildWelcomeContent, currentTheme, catFaces, currentCatIndex) {
2164
+ let isProcessing = false;
2165
+ // Get agent config
2166
+ const agentConfig = config.getAIAgentConfig();
2167
+ if (!agentConfig) {
2168
+ throw new Error("Cat not configured");
2169
+ }
2170
+ const apiKey = config.getAIAgentApiKey();
2171
+ if (!apiKey) {
2172
+ throw new Error("Failed to get API key");
2173
+ }
2174
+ // Create LLM and agent
2175
+ const llm = createLLM(agentConfig, apiKey);
2176
+ const agent = createHttpcatAgent(client, llm);
2177
+ // Helper to update header
2178
+ const updateAgentHeader = async () => {
2179
+ const colorTag = currentTheme === "dark" ? "green-fg" : "black-fg";
2180
+ const cyanColor = currentTheme === "dark" ? "light-cyan-fg" : "cyan-fg";
2181
+ const lines = [];
2182
+ lines.push(`{${colorTag}}🐱 Cat Chat Mode{/${colorTag}}`);
2183
+ lines.push(`{${colorTag}}${"═".repeat(60)}{/${colorTag}}`);
2184
+ lines.push("");
2185
+ lines.push(`{${cyanColor}}💡 Ask me to buy tokens, check balances, list tokens, and more!{/${cyanColor}}`);
2186
+ lines.push(`{${cyanColor}}💡 Type /exit to return to shell{/${cyanColor}}`);
2187
+ lines.push("");
2188
+ const content = lines.join("\n");
2189
+ headerBox.setContent(content);
2190
+ screen.render();
2191
+ };
2192
+ // Update header to show agent mode
2193
+ await updateAgentHeader();
2194
+ // Store original submit handler
2195
+ const originalHandlers = inputBox.listeners("submit");
2196
+ const originalSubmitHandler = originalHandlers[0];
2197
+ // Set up agent input handler (similar to chat mode)
2198
+ const agentInputHandler = async (value) => {
2199
+ // Guard against double processing
2200
+ if (isProcessing) {
2201
+ return;
2202
+ }
2203
+ isProcessing = true;
2204
+ const trimmed = value.trim();
2205
+ // Clear input immediately
2206
+ inputBox.clearValue();
2207
+ screen.render();
2208
+ if (!trimmed) {
2209
+ isProcessing = false;
2210
+ inputBox.focus();
2211
+ screen.render();
2212
+ return;
2213
+ }
2214
+ // Handle commands
2215
+ if (trimmed.startsWith("/")) {
2216
+ const [cmd] = trimmed.split(" ");
2217
+ switch (cmd) {
2218
+ case "/exit":
2219
+ case "/quit":
2220
+ log(chalk.yellow("Exited cat mode. Back to shell."));
2221
+ log("");
2222
+ // Restore original header
2223
+ const originalContent = await buildWelcomeContent(currentTheme, catFaces[currentCatIndex].face);
2224
+ headerBox.setContent(originalContent);
2225
+ // Restore original input handler
2226
+ inputBox.removeAllListeners("submit");
2227
+ inputBox.on("submit", originalSubmitHandler);
2228
+ isProcessing = false;
2229
+ inputBox.focus();
2230
+ screen.render();
2231
+ return;
2232
+ case "/help":
2233
+ log(chalk.cyan("Cat commands: /exit, /quit, /help"));
2234
+ isProcessing = false;
2235
+ inputBox.focus();
2236
+ screen.render();
2237
+ return;
2238
+ default:
2239
+ log(chalk.yellow(`Unknown command: ${cmd}. Type /help for commands.`));
2240
+ isProcessing = false;
2241
+ inputBox.focus();
2242
+ screen.render();
2243
+ return;
2244
+ }
2245
+ }
2246
+ // Send to agent
2247
+ try {
2248
+ log(chalk.blue("🐱 Cat thinking..."));
2249
+ screen.render();
2250
+ const response = await chatWithAgent(agent, llm, trimmed);
2251
+ log(chalk.green("🐱 Cat:"));
2252
+ log(response);
2253
+ log("");
2254
+ }
2255
+ catch (error) {
2256
+ const errorMsg = error.message || String(error);
2257
+ const errorStack = error.stack || "";
2258
+ // Log full error details for debugging
2259
+ if (process.env.HTTPCAT_DEBUG) {
2260
+ log(chalk.dim(`Debug: Full error: ${JSON.stringify(error, null, 2)}`));
2261
+ if (errorStack) {
2262
+ log(chalk.dim(`Debug: Stack trace: ${errorStack}`));
2263
+ }
2264
+ }
2265
+ log(chalk.red(`❌ Agent error: ${errorMsg}`));
2266
+ // Check for authentication errors
2267
+ const isAuthError = errorMsg.includes("Authentication failed") ||
2268
+ errorMsg.includes("API key") ||
2269
+ errorMsg.includes("401") ||
2270
+ errorMsg.includes("403") ||
2271
+ errorMsg.includes("Unauthorized") ||
2272
+ errorMsg.includes("Invalid API key") ||
2273
+ errorMsg.includes("authentication") ||
2274
+ errorMsg.includes("Invalid API Key") ||
2275
+ errorStack.includes("401") ||
2276
+ errorStack.includes("403");
2277
+ if (isAuthError) {
2278
+ log("");
2279
+ log(chalk.yellow("🔑 Authentication Error Detected"));
2280
+ log(chalk.dim("Your API key may be invalid, expired, or incorrectly configured."));
2281
+ log(chalk.dim("Exit cat mode and run 'agent' (or 'cat') again to re-run the setup wizard."));
2282
+ }
2283
+ log("");
2284
+ }
2285
+ isProcessing = false;
2286
+ inputBox.focus();
2287
+ screen.render();
2288
+ };
2289
+ // Remove original handler and add agent handler
2290
+ inputBox.removeAllListeners("submit");
2291
+ inputBox.on("submit", agentInputHandler);
2292
+ // Clear and focus input
2293
+ inputBox.clearValue();
2294
+ inputBox.focus();
2295
+ screen.render();
2296
+ // Show welcome message
2297
+ log(chalk.green("🐱 Cat chat mode activated!"));
2298
+ log(chalk.dim("Ask me anything about tokens, trading, or your portfolio."));
2299
+ log(chalk.dim("Type /exit to return to shell."));
2300
+ log("");
2301
+ }
1207
2302
  //# sourceMappingURL=shell.js.map