@aiaiaichain/agent 0.1.5 → 0.1.7

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 (121) hide show
  1. package/dist/api/ExtensionAPI.d.ts +0 -1
  2. package/dist/api/ExtensionAPI.js +3 -7
  3. package/dist/api/Registry.d.ts +0 -1
  4. package/dist/api/Registry.js +54 -57
  5. package/dist/cli.d.ts +0 -1
  6. package/dist/cli.js +684 -685
  7. package/dist/core/AgentDir.d.ts +1 -1
  8. package/dist/core/AgentDir.js +45 -39
  9. package/dist/core/ChainConfig.d.ts +0 -1
  10. package/dist/core/ChainConfig.js +51 -55
  11. package/dist/core/EnvLoader.d.ts +4 -1
  12. package/dist/core/EnvLoader.js +97 -84
  13. package/dist/core/SystemMonitor.d.ts +0 -1
  14. package/dist/core/SystemMonitor.js +72 -85
  15. package/dist/index.d.ts +0 -1
  16. package/dist/index.js +19 -26
  17. package/dist/loader.d.ts +0 -1
  18. package/dist/loader.js +64 -67
  19. package/dist/mcp/entry.d.ts +0 -1
  20. package/dist/mcp/entry.js +3 -6
  21. package/dist/mcp/server.d.ts +0 -1
  22. package/dist/mcp/server.js +152 -156
  23. package/dist/models/CostTracker.d.ts +0 -1
  24. package/dist/models/CostTracker.js +58 -61
  25. package/dist/models/ModelRegistry.d.ts +0 -1
  26. package/dist/models/ModelRegistry.js +195 -155
  27. package/dist/providers/ProviderRegistry.d.ts +0 -1
  28. package/dist/providers/ProviderRegistry.js +33 -36
  29. package/dist/runner/AgentRunner.d.ts +0 -1
  30. package/dist/runner/AgentRunner.js +180 -184
  31. package/dist/runner/ModelClient.d.ts +0 -1
  32. package/dist/runner/ModelClient.js +133 -134
  33. package/dist/runner/SwarmRouter.d.ts +0 -1
  34. package/dist/runner/SwarmRouter.js +18 -22
  35. package/dist/runner/ToolDispatcher.d.ts +0 -1
  36. package/dist/runner/ToolDispatcher.js +30 -33
  37. package/dist/scheduler/AgentScheduler.d.ts +0 -1
  38. package/dist/scheduler/AgentScheduler.js +99 -103
  39. package/dist/session/ContextStore.d.ts +1 -1
  40. package/dist/session/ContextStore.js +76 -78
  41. package/dist/session/GoalManager.d.ts +0 -1
  42. package/dist/session/GoalManager.js +96 -100
  43. package/dist/session/MemoryStore.d.ts +2 -1
  44. package/dist/session/MemoryStore.js +108 -87
  45. package/dist/session/SessionManager.d.ts +5 -4
  46. package/dist/session/SessionManager.js +83 -62
  47. package/dist/session/SessionStore.d.ts +0 -1
  48. package/dist/session/SessionStore.js +112 -116
  49. package/dist/setup/SetupWizard.d.ts +0 -1
  50. package/dist/setup/SetupWizard.js +61 -64
  51. package/dist/tools/CrossTools.d.ts +0 -1
  52. package/dist/tools/CrossTools.js +140 -144
  53. package/dist/tools/GmgnIntegration.d.ts +0 -1
  54. package/dist/tools/GmgnIntegration.js +220 -230
  55. package/dist/tools/MarketSentiment.d.ts +0 -1
  56. package/dist/tools/MarketSentiment.js +213 -195
  57. package/dist/tools/NewsSentiment.d.ts +0 -1
  58. package/dist/tools/NewsSentiment.js +126 -130
  59. package/dist/tools/PriceFeed.d.ts +6 -1
  60. package/dist/tools/PriceFeed.js +201 -133
  61. package/dist/tools/TechnicalAnalysis.d.ts +1 -2
  62. package/dist/tools/TechnicalAnalysis.js +248 -216
  63. package/dist/tools/TechnicalAnalysis.worker.d.ts +25 -0
  64. package/dist/tools/TechnicalAnalysis.worker.js +92 -0
  65. package/dist/tools/TokenCalendar.d.ts +0 -1
  66. package/dist/tools/TokenCalendar.js +63 -68
  67. package/dist/tools/TokenSecurityScanner.d.ts +0 -1
  68. package/dist/tools/TokenSecurityScanner.js +93 -96
  69. package/dist/tools/TransactionSim.d.ts +0 -1
  70. package/dist/tools/TransactionSim.js +65 -71
  71. package/dist/tui/App.d.ts +0 -1
  72. package/dist/tui/App.js +895 -824
  73. package/dist/tui/ModelSelector.d.ts +0 -1
  74. package/dist/tui/ModelSelector.js +46 -49
  75. package/dist/tui/REPL.d.ts +0 -1
  76. package/dist/tui/REPL.js +222 -210
  77. package/dist/tui/Sparkline.d.ts +0 -1
  78. package/dist/tui/Sparkline.js +36 -37
  79. package/dist/tui/StatusBar.d.ts +0 -1
  80. package/dist/tui/StatusBar.js +9 -10
  81. package/dist/tui/ThemePresets.d.ts +0 -1
  82. package/dist/tui/ThemePresets.js +99 -103
  83. package/dist/tui/theme.d.ts +0 -1
  84. package/dist/tui/theme.js +50 -31
  85. package/dist/util/clipboard.d.ts +0 -1
  86. package/dist/util/clipboard.js +16 -20
  87. package/dist/util/commandSuggest.d.ts +0 -1
  88. package/dist/util/commandSuggest.js +34 -38
  89. package/dist/util/confirmation.d.ts +0 -1
  90. package/dist/util/confirmation.js +8 -11
  91. package/dist/util/errorHandler.d.ts +0 -1
  92. package/dist/util/errorHandler.js +20 -23
  93. package/dist/util/errors.d.ts +59 -0
  94. package/dist/util/errors.js +93 -0
  95. package/dist/util/logger.d.ts +0 -1
  96. package/dist/util/logger.js +30 -33
  97. package/dist/util/processManager.d.ts +0 -1
  98. package/dist/util/processManager.js +33 -36
  99. package/dist/util/resilientFetch.d.ts +6 -1
  100. package/dist/util/resilientFetch.js +134 -80
  101. package/dist/util/responseCache.d.ts +0 -1
  102. package/dist/util/responseCache.js +36 -45
  103. package/dist/util/rpc.d.ts +16 -0
  104. package/dist/util/rpc.js +69 -0
  105. package/dist/util/safeLog.d.ts +0 -1
  106. package/dist/util/safeLog.js +52 -53
  107. package/dist/util/scheduler.d.ts +0 -1
  108. package/dist/util/scheduler.js +53 -58
  109. package/dist/util/webhooks.d.ts +0 -1
  110. package/dist/util/webhooks.js +54 -58
  111. package/dist/wallet/ActionFeed.d.ts +3 -3
  112. package/dist/wallet/ActionFeed.js +189 -187
  113. package/dist/wallet/AgentWallet.d.ts +9 -7
  114. package/dist/wallet/AgentWallet.js +121 -141
  115. package/dist/wallet/ProfitTracker.d.ts +0 -1
  116. package/dist/wallet/ProfitTracker.js +71 -74
  117. package/package.json +12 -7
  118. package/scripts/build-esbuild.mjs +40 -0
  119. package/scripts/bundle-dts.mjs +58 -0
  120. package/scripts/minify.mjs +44 -0
  121. package/scripts/postinstall.js +27 -0
@@ -3,8 +3,8 @@
3
3
  * Created on first run. Contains config, memory, sessions, skills.
4
4
  */
5
5
  export declare class AgentDir {
6
+ static getInstance(): typeof AgentDir;
6
7
  static init(): void;
7
8
  static path(...parts: string[]): string;
8
9
  static getHome(): string;
9
10
  }
10
- //# sourceMappingURL=AgentDir.d.ts.map
@@ -1,17 +1,14 @@
1
- /**
2
- * AgentDir — manages the AIAIAI home directory (~/.aiaiai/)
3
- * Created on first run. Contains config, memory, sessions, skills.
4
- */
1
+
5
2
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
6
3
  import { resolve } from 'node:path';
7
4
  import { homedir } from 'node:os';
8
5
  const HOME = process.env.AIAIAI_HOME ?? resolve(homedir(), '.aiaiai');
9
6
  const DIRS = [
10
- 'config',
11
- 'memory',
12
- 'checkpoints',
13
- 'sessions',
14
- 'skills',
7
+ 'config',
8
+ 'memory',
9
+ 'checkpoints',
10
+ 'sessions',
11
+ 'skills',
15
12
  ];
16
13
  const AIAIAI_MD_CONTENT = `# AIAIAI Chain Agent
17
14
 
@@ -40,35 +37,44 @@ aiaiaichain config — show configuration
40
37
  aiaiaichain price — show $AIAIAI token price
41
38
  \`\`\`
42
39
  `;
40
+
41
+ let _initialized = false;
42
+ let _homePath = "";
43
43
  export class AgentDir {
44
- static init() {
45
- if (!existsSync(HOME))
46
- mkdirSync(HOME, { recursive: true });
47
- for (const dir of DIRS) {
48
- const full = resolve(HOME, dir);
49
- if (!existsSync(full))
50
- mkdirSync(full, { recursive: true });
51
- }
52
- const mdPath = resolve(HOME, 'AIAIAI.md');
53
- if (!existsSync(mdPath))
54
- writeFileSync(mdPath, AIAIAI_MD_CONTENT, 'utf-8');
55
- const histPath = resolve(HOME, 'history.jsonl');
56
- if (!existsSync(histPath))
57
- writeFileSync(histPath, '', 'utf-8');
58
- const settingsPath = resolve(HOME, 'settings.json');
59
- if (!existsSync(settingsPath)) {
60
- writeFileSync(settingsPath, JSON.stringify({
61
- theme: 'dark',
62
- autoSave: true,
63
- activeChain: 'solana',
64
- }, null, 2), 'utf-8');
65
- }
66
- }
67
- static path(...parts) {
68
- return resolve(HOME, ...parts);
69
- }
70
- static getHome() {
71
- return HOME;
72
- }
44
+ static getInstance() {
45
+ return AgentDir;
46
+ }
47
+ static init() {
48
+ if (_initialized)
49
+ return;
50
+ if (!existsSync(HOME))
51
+ mkdirSync(HOME, { recursive: true });
52
+ for (const dir of DIRS) {
53
+ const full = resolve(HOME, dir);
54
+ if (!existsSync(full))
55
+ mkdirSync(full, { recursive: true });
56
+ }
57
+ const mdPath = resolve(HOME, 'AIAIAI.md');
58
+ if (!existsSync(mdPath))
59
+ writeFileSync(mdPath, AIAIAI_MD_CONTENT, 'utf-8');
60
+ const histPath = resolve(HOME, 'history.jsonl');
61
+ if (!existsSync(histPath))
62
+ writeFileSync(histPath, '', 'utf-8');
63
+ const settingsPath = resolve(HOME, 'settings.json');
64
+ if (!existsSync(settingsPath)) {
65
+ writeFileSync(settingsPath, JSON.stringify({
66
+ theme: 'dark',
67
+ autoSave: true,
68
+ activeChain: 'solana',
69
+ }, null, 2), 'utf-8');
70
+ }
71
+ _initialized = true;
72
+ _homePath = HOME;
73
+ }
74
+ static path(...parts) {
75
+ return resolve(HOME, ...parts);
76
+ }
77
+ static getHome() {
78
+ return HOME;
79
+ }
73
80
  }
74
- //# sourceMappingURL=AgentDir.js.map
@@ -16,4 +16,3 @@ export declare function getPrimaryChain(): ChainInfo;
16
16
  export declare function getEnabledChains(): ChainInfo[];
17
17
  export declare function getChain(name: string): ChainInfo | undefined;
18
18
  export declare function getSupportedChains(): string[];
19
- //# sourceMappingURL=ChainConfig.d.ts.map
@@ -1,65 +1,61 @@
1
- /**
2
- * ChainConfig — single source of truth for supported chains.
3
- * Solana is the default/primary chain. EVM chains are available but disabled by default.
4
- */
1
+
5
2
  export const CHAINS = {
6
- solana: {
7
- name: 'solana',
8
- symbol: 'SOL',
9
- chainId: 101,
10
- rpcUrl: process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',
11
- explorerUrl: 'https://solscan.io',
12
- enabled: true,
13
- primary: true,
14
- },
15
- ethereum: {
16
- name: 'ethereum',
17
- symbol: 'ETH',
18
- chainId: 1,
19
- rpcUrl: 'https://eth-mainnet.g.alchemy.com/v2/',
20
- explorerUrl: 'https://etherscan.io',
21
- enabled: false,
22
- primary: false,
23
- },
24
- bsc: {
25
- name: 'bsc',
26
- symbol: 'BNB',
27
- chainId: 56,
28
- rpcUrl: 'https://bsc-dataseed.binance.org',
29
- explorerUrl: 'https://bscscan.com',
30
- enabled: false,
31
- primary: false,
32
- },
33
- base: {
34
- name: 'base',
35
- symbol: 'ETH',
36
- chainId: 8453,
37
- rpcUrl: 'https://mainnet.base.org',
38
- explorerUrl: 'https://basescan.org',
39
- enabled: false,
40
- primary: false,
41
- },
42
- arbitrum: {
43
- name: 'arbitrum',
44
- symbol: 'ETH',
45
- chainId: 42161,
46
- rpcUrl: 'https://arb1.arbitrum.io/rpc',
47
- explorerUrl: 'https://arbiscan.io',
48
- enabled: false,
49
- primary: false,
50
- },
3
+ solana: {
4
+ name: 'solana',
5
+ symbol: 'SOL',
6
+ chainId: 101,
7
+ rpcUrl: process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',
8
+ explorerUrl: 'https://solscan.io',
9
+ enabled: true,
10
+ primary: true,
11
+ },
12
+ ethereum: {
13
+ name: 'ethereum',
14
+ symbol: 'ETH',
15
+ chainId: 1,
16
+ rpcUrl: 'https://eth-mainnet.g.alchemy.com/v2/',
17
+ explorerUrl: 'https://etherscan.io',
18
+ enabled: false,
19
+ primary: false,
20
+ },
21
+ bsc: {
22
+ name: 'bsc',
23
+ symbol: 'BNB',
24
+ chainId: 56,
25
+ rpcUrl: 'https://bsc-dataseed.binance.org',
26
+ explorerUrl: 'https://bscscan.com',
27
+ enabled: false,
28
+ primary: false,
29
+ },
30
+ base: {
31
+ name: 'base',
32
+ symbol: 'ETH',
33
+ chainId: 8453,
34
+ rpcUrl: 'https://mainnet.base.org',
35
+ explorerUrl: 'https://basescan.org',
36
+ enabled: false,
37
+ primary: false,
38
+ },
39
+ arbitrum: {
40
+ name: 'arbitrum',
41
+ symbol: 'ETH',
42
+ chainId: 42161,
43
+ rpcUrl: 'https://arb1.arbitrum.io/rpc',
44
+ explorerUrl: 'https://arbiscan.io',
45
+ enabled: false,
46
+ primary: false,
47
+ },
51
48
  };
52
49
  export function getPrimaryChain() {
53
- const primary = Object.values(CHAINS).find(c => c.primary);
54
- return primary ?? CHAINS.solana;
50
+ const primary = Object.values(CHAINS).find(c => c.primary);
51
+ return primary ?? CHAINS.solana;
55
52
  }
56
53
  export function getEnabledChains() {
57
- return Object.values(CHAINS).filter(c => c.enabled);
54
+ return Object.values(CHAINS).filter(c => c.enabled);
58
55
  }
59
56
  export function getChain(name) {
60
- return CHAINS[name];
57
+ return CHAINS[name];
61
58
  }
62
59
  export function getSupportedChains() {
63
- return Object.keys(CHAINS);
60
+ return Object.keys(CHAINS);
64
61
  }
65
- //# sourceMappingURL=ChainConfig.js.map
@@ -5,6 +5,10 @@ export declare class EnvLoader {
5
5
  private cache;
6
6
  private envPath;
7
7
  constructor();
8
+ /**
9
+ * #24: Validate .env file permissions on startup
10
+ */
11
+ private validatePermissions;
8
12
  private load;
9
13
  get(key: string, defaultValue?: string): string | undefined;
10
14
  getRequired(key: string): string;
@@ -15,4 +19,3 @@ export declare class EnvLoader {
15
19
  reload(): void;
16
20
  }
17
21
  export declare const env: EnvLoader;
18
- //# sourceMappingURL=EnvLoader.d.ts.map
@@ -1,90 +1,103 @@
1
- /**
2
- * EnvLoader — loads/writes environment variables from ~/.aiaiai/.env
3
- */
1
+
4
2
  import { existsSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
5
3
  import { resolve } from "node:path";
6
4
  import { homedir } from "node:os";
7
5
  export class EnvLoader {
8
- cache = {};
9
- envPath;
10
- constructor() {
11
- const home = process.env.AIAIAI_HOME ?? resolve(homedir(), '.aiaiai');
12
- this.envPath = resolve(home, ".env");
13
- this.load();
14
- }
15
- load() {
16
- if (existsSync(this.envPath)) {
17
- const content = readFileSync(this.envPath, "utf-8");
18
- for (const line of content.split("\n")) {
19
- const trimmed = line.trim();
20
- if (!trimmed || trimmed.startsWith("#"))
21
- continue;
22
- const eqIdx = trimmed.indexOf("=");
23
- if (eqIdx === -1)
24
- continue;
25
- const key = trimmed.slice(0, eqIdx).trim();
26
- const value = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, "");
27
- if (key)
28
- this.cache[key] = value;
29
- }
30
- }
31
- for (const key of Object.keys(process.env)) {
32
- const value = process.env[key];
33
- if (value !== undefined)
34
- this.cache[key] = value;
35
- }
36
- }
37
- get(key, defaultValue) {
38
- return this.cache[key] ?? defaultValue;
39
- }
40
- getRequired(key) {
41
- const value = this.get(key);
42
- if (!value)
43
- throw new Error(`Required env var ${key} is not set`);
44
- return value;
45
- }
46
- has(key) {
47
- return this.cache[key] !== undefined && this.cache[key].trim() !== "";
48
- }
49
- /** Write a key=value to the .env file and update cache */
50
- set(key, value) {
51
- const content = existsSync(this.envPath) ? readFileSync(this.envPath, "utf-8") : "";
52
- const lines = content.split("\n");
53
- let found = false;
54
- for (let i = 0; i < lines.length; i++) {
55
- const line = lines[i].trim();
56
- if (line.startsWith(`${key}=`)) {
57
- lines[i] = `${key}=${value}`;
58
- found = true;
59
- break;
60
- }
61
- }
62
- if (!found) {
63
- if (content && !content.endsWith("\n"))
64
- lines.push("");
65
- lines.push(`${key}=${value}`);
66
- }
67
- const newContent = lines.join("\n") + "\n";
68
- writeFileSync(this.envPath, newContent, "utf-8");
69
- try {
70
- chmodSync(this.envPath, 0o600);
71
- }
72
- catch { /* non-fatal */ }
73
- this.cache[key] = value;
74
- process.env[key] = value;
75
- }
76
- getAll() {
77
- const result = {};
78
- for (const [key, value] of Object.entries(this.cache)) {
79
- if (value !== undefined)
80
- result[key] = value;
81
- }
82
- return result;
83
- }
84
- reload() {
85
- this.cache = {};
86
- this.load();
87
- }
6
+ cache = {};
7
+ envPath;
8
+ constructor() {
9
+ const home = process.env.AIAIAI_HOME ?? resolve(homedir(), '.aiaiai');
10
+ this.envPath = resolve(home, ".env");
11
+ this.load();
12
+ this.validatePermissions();
13
+ }
14
+
15
+ validatePermissions() {
16
+ try {
17
+ if (!existsSync(this.envPath))
18
+ return;
19
+ const { statSync } = require('node:fs');
20
+ const stats = statSync(this.envPath);
21
+ const mode = stats.mode & 0o777;
22
+
23
+ if (mode & 0o077) {
24
+ console.warn(`⚠️ .env file has overly permissive permissions (${mode.toString(8)}). Run: chmod 600 ${this.envPath}`);
25
+ }
26
+ }
27
+ catch { }
28
+ }
29
+ load() {
30
+ if (existsSync(this.envPath)) {
31
+ const content = readFileSync(this.envPath, "utf-8");
32
+ for (const line of content.split("\n")) {
33
+ const trimmed = line.trim();
34
+ if (!trimmed || trimmed.startsWith("#"))
35
+ continue;
36
+ const eqIdx = trimmed.indexOf("=");
37
+ if (eqIdx === -1)
38
+ continue;
39
+ const key = trimmed.slice(0, eqIdx).trim();
40
+ const value = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, "");
41
+ if (key)
42
+ this.cache[key] = value;
43
+ }
44
+ }
45
+ for (const key of Object.keys(process.env)) {
46
+ const value = process.env[key];
47
+ if (value !== undefined)
48
+ this.cache[key] = value;
49
+ }
50
+ }
51
+ get(key, defaultValue) {
52
+ return this.cache[key] ?? defaultValue;
53
+ }
54
+ getRequired(key) {
55
+ const value = this.get(key);
56
+ if (!value)
57
+ throw new Error(`Required env var ${key} is not set`);
58
+ return value;
59
+ }
60
+ has(key) {
61
+ return this.cache[key] !== undefined && this.cache[key].trim() !== "";
62
+ }
63
+
64
+ set(key, value) {
65
+ const content = existsSync(this.envPath) ? readFileSync(this.envPath, "utf-8") : "";
66
+ const lines = content.split("\n");
67
+ let found = false;
68
+ for (let i = 0; i < lines.length; i++) {
69
+ const line = lines[i].trim();
70
+ if (line.startsWith(`${key}=`)) {
71
+ lines[i] = `${key}=${value}`;
72
+ found = true;
73
+ break;
74
+ }
75
+ }
76
+ if (!found) {
77
+ if (content && !content.endsWith("\n"))
78
+ lines.push("");
79
+ lines.push(`${key}=${value}`);
80
+ }
81
+ const newContent = lines.join("\n") + "\n";
82
+ writeFileSync(this.envPath, newContent, "utf-8");
83
+ try {
84
+ chmodSync(this.envPath, 0o600);
85
+ }
86
+ catch { }
87
+ this.cache[key] = value;
88
+ process.env[key] = value;
89
+ }
90
+ getAll() {
91
+ const result = {};
92
+ for (const [key, value] of Object.entries(this.cache)) {
93
+ if (value !== undefined)
94
+ result[key] = value;
95
+ }
96
+ return result;
97
+ }
98
+ reload() {
99
+ this.cache = {};
100
+ this.load();
101
+ }
88
102
  }
89
103
  export const env = new EnvLoader();
90
- //# sourceMappingURL=EnvLoader.js.map
@@ -29,4 +29,3 @@ export declare class SystemMonitor {
29
29
  resetApiCounter(): number;
30
30
  }
31
31
  export declare const systemMonitor: SystemMonitor;
32
- //# sourceMappingURL=SystemMonitor.d.ts.map
@@ -1,89 +1,76 @@
1
- /**
2
- * SystemMonitor — tracks CPU, RAM, network, and agent stats.
3
- * Uses Node.js built-in modules only (no external deps).
4
- */
5
- import { cpus, totalmem, freemem, uptime } from 'node:os';
1
+
2
+ import { totalmem, freemem, uptime } from 'node:os';
6
3
  import { logger } from '../util/logger.js';
4
+
5
+ let lastCpuUsage = process.cpuUsage();
7
6
  export class SystemMonitor {
8
- apiCallCount = 0;
9
- prevCpuTimes = { idle: 0, total: 0 };
10
- /** Track an API call */
11
- trackApiCall() {
12
- this.apiCallCount++;
13
- }
14
- /** Get current system stats */
15
- getStats(tokenCount = 0) {
16
- return {
17
- cpuPercent: this.getCpuPercent(),
18
- ramPercent: this.getRamPercent(),
19
- ramUsed: this.formatBytes(totalmem() - freemem()),
20
- ramTotal: this.formatBytes(totalmem()),
21
- uptime: this.formatUptime(uptime()),
22
- ...this.getNetStats(),
23
- apiCallsPerMin: this.apiCallCount,
24
- tokensUsed: tokenCount,
25
- };
26
- }
27
- getCpuPercent() {
28
- try {
29
- const cpuInfo = cpus();
30
- let totalIdle = 0, totalTick = 0;
31
- for (const cpu of cpuInfo) {
32
- for (const type in cpu.times) {
33
- totalTick += cpu.times[type];
34
- }
35
- totalIdle += cpu.times.idle;
36
- }
37
- const idle = totalIdle / cpuInfo.length;
38
- const total = totalTick / cpuInfo.length;
39
- // Delta-based: compare against previous sample
40
- const nowIdle = idle, nowTotal = total;
41
- if (this.prevCpuTimes.total > 0) {
42
- const idleDelta = nowIdle - this.prevCpuTimes.idle;
43
- const totalDelta = nowTotal - this.prevCpuTimes.total;
44
- this.prevCpuTimes = { idle: nowIdle, total: nowTotal };
45
- if (totalDelta <= 0)
46
- return 0;
47
- return Math.round((1 - idleDelta / totalDelta) * 100);
48
- }
49
- this.prevCpuTimes = { idle: nowIdle, total: nowTotal };
50
- return 0;
51
- }
52
- catch (error) {
53
- logger.debug('SystemMonitor', 'CPU measurement failed', { error: error.message });
54
- return 0;
55
- }
56
- }
57
- getRamPercent() {
58
- const used = totalmem() - freemem();
59
- return Math.round((used / totalmem()) * 100);
60
- }
61
- getNetStats() {
62
- // Node.js doesn't expose per-interface byte counters without native addons.
63
- // Return N/A rather than pretending zeros are real data.
64
- return { netUp: 'N/A', netDown: 'N/A' };
65
- }
66
- formatBytes(bytes) {
67
- if (bytes === 0)
68
- return '0 B';
69
- const k = 1024;
70
- const sizes = ['B', 'KB', 'MB', 'GB'];
71
- const i = Math.floor(Math.log(bytes) / Math.log(k));
72
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
73
- }
74
- formatUptime(seconds) {
75
- const h = Math.floor(seconds / 3600);
76
- const m = Math.floor((seconds % 3600) / 60);
77
- if (h > 0)
78
- return `${h}h ${m}m`;
79
- return `${m}m`;
80
- }
81
- /** Reset API call counter (call every minute) */
82
- resetApiCounter() {
83
- const count = this.apiCallCount;
84
- this.apiCallCount = 0;
85
- return count;
86
- }
7
+ apiCallCount = 0;
8
+ prevCpuTimes = { idle: 0, total: 0 };
9
+
10
+ trackApiCall() {
11
+ this.apiCallCount++;
12
+ }
13
+
14
+ getStats(tokenCount = 0) {
15
+ return {
16
+ cpuPercent: this.getCpuPercent(),
17
+ ramPercent: this.getRamPercent(),
18
+ ramUsed: this.formatBytes(totalmem() - freemem()),
19
+ ramTotal: this.formatBytes(totalmem()),
20
+ uptime: this.formatUptime(uptime()),
21
+ ...this.getNetStats(),
22
+ apiCallsPerMin: this.apiCallCount,
23
+ tokensUsed: tokenCount,
24
+ };
25
+ }
26
+ getCpuPercent() {
27
+ try {
28
+
29
+ const currentUsage = process.cpuUsage();
30
+ const userDelta = currentUsage.user - lastCpuUsage.user;
31
+ const systemDelta = currentUsage.system - lastCpuUsage.system;
32
+ lastCpuUsage = currentUsage;
33
+
34
+
35
+ const totalDelta = userDelta + systemDelta;
36
+
37
+ const pct = Math.min(100, Math.round((totalDelta / 10_000_000) * 100));
38
+ return pct;
39
+ }
40
+ catch (error) {
41
+ logger.debug('SystemMonitor', 'CPU measurement failed', { error: error.message });
42
+ return 0;
43
+ }
44
+ }
45
+ getRamPercent() {
46
+ const used = totalmem() - freemem();
47
+ return Math.round((used / totalmem()) * 100);
48
+ }
49
+ getNetStats() {
50
+
51
+
52
+ return { netUp: 'N/A', netDown: 'N/A' };
53
+ }
54
+ formatBytes(bytes) {
55
+ if (bytes === 0)
56
+ return '0 B';
57
+ const k = 1024;
58
+ const sizes = ['B', 'KB', 'MB', 'GB'];
59
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
60
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
61
+ }
62
+ formatUptime(seconds) {
63
+ const h = Math.floor(seconds / 3600);
64
+ const m = Math.floor((seconds % 3600) / 60);
65
+ if (h > 0)
66
+ return `${h}h ${m}m`;
67
+ return `${m}m`;
68
+ }
69
+
70
+ resetApiCounter() {
71
+ const count = this.apiCallCount;
72
+ this.apiCallCount = 0;
73
+ return count;
74
+ }
87
75
  }
88
76
  export const systemMonitor = new SystemMonitor();
89
- //# sourceMappingURL=SystemMonitor.js.map
package/dist/index.d.ts CHANGED
@@ -58,4 +58,3 @@ export { recordTrade, getPLSummary, getTradeHistory, exportCSV } from "./wallet/
58
58
  export type { Trade, ProfitState, PLSummary } from "./wallet/ProfitTracker.js";
59
59
  export { scanTokenSecurityTool } from "./tools/TokenSecurityScanner.js";
60
60
  export type { TokenSecurityResult } from "./tools/TokenSecurityScanner.js";
61
- //# sourceMappingURL=index.d.ts.map