genesis-ai-cli 9.1.0 → 9.3.0

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.
@@ -528,8 +528,100 @@ registerAction('git.push', async (context) => {
528
528
  }
529
529
  });
530
530
  /**
531
- * execute.code: Execute TypeScript/JavaScript code safely
532
- * v7.13: Sandboxed code execution
531
+ * Safe expression evaluator - v9.2.0 Security fix
532
+ * Only allows: numbers, strings, basic math (+,-,*,/,%), comparisons, booleans
533
+ * NO Function(), eval(), or dynamic code execution
534
+ */
535
+ function safeEvaluateExpression(expr) {
536
+ // Trim whitespace
537
+ expr = expr.trim();
538
+ // Allow only safe characters: digits, operators, parentheses, quotes, dots, spaces
539
+ const safePattern = /^[\d\s+\-*/%().,"'<>=!&|true false null undefined]+$/i;
540
+ if (!safePattern.test(expr)) {
541
+ throw new Error(`Unsafe expression: contains disallowed characters`);
542
+ }
543
+ // Block any function calls or property access
544
+ if (/[a-zA-Z_$][\w$]*\s*\(/.test(expr)) {
545
+ throw new Error('Function calls not allowed in safe expressions');
546
+ }
547
+ // Parse and evaluate simple expressions manually
548
+ // Handle literals
549
+ if (expr === 'true')
550
+ return true;
551
+ if (expr === 'false')
552
+ return false;
553
+ if (expr === 'null')
554
+ return null;
555
+ if (expr === 'undefined')
556
+ return undefined;
557
+ // Handle numbers
558
+ if (/^-?\d+(\.\d+)?$/.test(expr)) {
559
+ return parseFloat(expr);
560
+ }
561
+ // Handle strings
562
+ if (/^["'].*["']$/.test(expr)) {
563
+ return expr.slice(1, -1);
564
+ }
565
+ // Handle simple math expressions with numbers only
566
+ // This is intentionally limited for security
567
+ const mathPattern = /^[\d\s+\-*/%().]+$/;
568
+ if (mathPattern.test(expr)) {
569
+ // Validate it's a safe math expression
570
+ try {
571
+ // Use a simple recursive descent parser instead of eval
572
+ const tokens = expr.match(/(\d+\.?\d*|[+\-*/%()])/g) || [];
573
+ return evaluateMathTokens(tokens);
574
+ }
575
+ catch {
576
+ throw new Error('Invalid math expression');
577
+ }
578
+ }
579
+ throw new Error('Expression type not supported in safe mode');
580
+ }
581
+ function evaluateMathTokens(tokens) {
582
+ let pos = 0;
583
+ function parseExpression() {
584
+ let left = parseTerm();
585
+ while (pos < tokens.length && (tokens[pos] === '+' || tokens[pos] === '-')) {
586
+ const op = tokens[pos++];
587
+ const right = parseTerm();
588
+ left = op === '+' ? left + right : left - right;
589
+ }
590
+ return left;
591
+ }
592
+ function parseTerm() {
593
+ let left = parseFactor();
594
+ while (pos < tokens.length && (tokens[pos] === '*' || tokens[pos] === '/' || tokens[pos] === '%')) {
595
+ const op = tokens[pos++];
596
+ const right = parseFactor();
597
+ if (op === '*')
598
+ left *= right;
599
+ else if (op === '/')
600
+ left /= right;
601
+ else
602
+ left %= right;
603
+ }
604
+ return left;
605
+ }
606
+ function parseFactor() {
607
+ if (tokens[pos] === '(') {
608
+ pos++; // skip '('
609
+ const result = parseExpression();
610
+ pos++; // skip ')'
611
+ return result;
612
+ }
613
+ if (tokens[pos] === '-') {
614
+ pos++;
615
+ return -parseFactor();
616
+ }
617
+ return parseFloat(tokens[pos++]);
618
+ }
619
+ return parseExpression();
620
+ }
621
+ /**
622
+ * execute.code: Execute safe expressions
623
+ * v9.2.0: SECURITY FIX - Replaced unsafe new Function() with safe expression parser
624
+ * Only supports: literals, basic math, comparisons
533
625
  */
534
626
  registerAction('execute.code', async (context) => {
535
627
  try {
@@ -542,33 +634,8 @@ registerAction('execute.code', async (context) => {
542
634
  duration: 0,
543
635
  };
544
636
  }
545
- // For safety, only allow simple expressions (no require, import, fs, etc.)
546
- const dangerousPatterns = [
547
- /require\s*\(/,
548
- /import\s+/,
549
- /process\./,
550
- /child_process/,
551
- /\bfs\b/,
552
- /\bexec\b/,
553
- /\beval\b/,
554
- /Function\s*\(/,
555
- /\bglobal\b/,
556
- /\bglobalThis\b/,
557
- /\b__dirname\b/,
558
- /\b__filename\b/,
559
- ];
560
- for (const pattern of dangerousPatterns) {
561
- if (pattern.test(code)) {
562
- return {
563
- success: false,
564
- action: 'execute.code',
565
- error: `Unsafe code pattern detected: ${pattern}`,
566
- duration: 0,
567
- };
568
- }
569
- }
570
- // Execute in a restricted scope
571
- const result = new Function('return ' + code)();
637
+ // v9.2.0: Use safe expression evaluator instead of new Function()
638
+ const result = safeEvaluateExpression(code);
572
639
  return {
573
640
  success: true,
574
641
  action: 'execute.code',
@@ -1681,6 +1748,165 @@ class ActionExecutorManager {
1681
1748
  }
1682
1749
  exports.ActionExecutorManager = ActionExecutorManager;
1683
1750
  // ============================================================================
1751
+ // v9.3: ECONOMIC SELF-FUNDING ACTIONS
1752
+ // ============================================================================
1753
+ const economic_integration_js_1 = require("./economic-integration.js");
1754
+ /**
1755
+ * econ.check: Check economic health (balance, costs, revenue, runway)
1756
+ */
1757
+ registerAction('econ.check', async (_context) => {
1758
+ const start = Date.now();
1759
+ try {
1760
+ const econ = (0, economic_integration_js_1.getEconomicIntegration)();
1761
+ await econ.initialize();
1762
+ const obs = await econ.getObservation();
1763
+ const summary = await econ.getSummary();
1764
+ return {
1765
+ success: true,
1766
+ action: 'econ.check',
1767
+ data: {
1768
+ balance: obs.balance,
1769
+ monthlyCosts: obs.monthlyCosts,
1770
+ monthlyRevenue: obs.monthlyRevenue,
1771
+ runwayDays: obs.runwayDays,
1772
+ health: ['critical', 'low', 'stable', 'growing'][obs.health],
1773
+ summary,
1774
+ },
1775
+ duration: Date.now() - start,
1776
+ };
1777
+ }
1778
+ catch (error) {
1779
+ return {
1780
+ success: false,
1781
+ action: 'econ.check',
1782
+ error: error instanceof Error ? error.message : String(error),
1783
+ duration: Date.now() - start,
1784
+ };
1785
+ }
1786
+ });
1787
+ /**
1788
+ * econ.optimize: Optimize costs (cheaper LLMs, aggressive caching)
1789
+ */
1790
+ registerAction('econ.optimize', async (_context) => {
1791
+ const start = Date.now();
1792
+ try {
1793
+ const econ = (0, economic_integration_js_1.getEconomicIntegration)();
1794
+ await econ.initialize();
1795
+ // Execute cost optimization actions
1796
+ const llmResult = await econ.executeAction('economic:optimize-llm-usage');
1797
+ const cacheResult = await econ.executeAction('economic:cache-expensive-calls');
1798
+ // Get current cost breakdown
1799
+ const breakdown = econ.getCostTracker().getCostBreakdown();
1800
+ const dailyBurn = econ.getCostTracker().getDailyBurnRate();
1801
+ return {
1802
+ success: true,
1803
+ action: 'econ.optimize',
1804
+ data: {
1805
+ llmOptimization: llmResult.success,
1806
+ cachingEnabled: cacheResult.success,
1807
+ currentCostBreakdown: breakdown,
1808
+ dailyBurnRate: dailyBurn,
1809
+ recommendation: dailyBurn > 10
1810
+ ? 'Consider reducing LLM usage or using cheaper models'
1811
+ : 'Cost levels acceptable',
1812
+ },
1813
+ duration: Date.now() - start,
1814
+ };
1815
+ }
1816
+ catch (error) {
1817
+ return {
1818
+ success: false,
1819
+ action: 'econ.optimize',
1820
+ error: error instanceof Error ? error.message : String(error),
1821
+ duration: Date.now() - start,
1822
+ };
1823
+ }
1824
+ });
1825
+ /**
1826
+ * econ.activate: Activate a revenue-generating service
1827
+ */
1828
+ registerAction('econ.activate', async (context) => {
1829
+ const start = Date.now();
1830
+ try {
1831
+ const econ = (0, economic_integration_js_1.getEconomicIntegration)();
1832
+ await econ.initialize();
1833
+ const serviceName = context.parameters?.service || 'genesis-api';
1834
+ const result = await econ.executeAction(`economic:activate-service:${serviceName}`);
1835
+ // Get all services status
1836
+ const services = econ.getServiceRegistry().getAll();
1837
+ const activeServices = econ.getServiceRegistry().getActive();
1838
+ return {
1839
+ success: result.success,
1840
+ action: 'econ.activate',
1841
+ data: {
1842
+ service: serviceName,
1843
+ activated: result.success,
1844
+ totalServices: services.length,
1845
+ activeServices: activeServices.map(s => s.name),
1846
+ potentialMonthlyRevenue: econ.getServiceRegistry().estimateMonthlyPotential(),
1847
+ },
1848
+ duration: Date.now() - start,
1849
+ };
1850
+ }
1851
+ catch (error) {
1852
+ return {
1853
+ success: false,
1854
+ action: 'econ.activate',
1855
+ error: error instanceof Error ? error.message : String(error),
1856
+ duration: Date.now() - start,
1857
+ };
1858
+ }
1859
+ });
1860
+ /**
1861
+ * econ.promote: Promote services to increase revenue
1862
+ */
1863
+ registerAction('econ.promote', async (context) => {
1864
+ const start = Date.now();
1865
+ try {
1866
+ const econ = (0, economic_integration_js_1.getEconomicIntegration)();
1867
+ await econ.initialize();
1868
+ const serviceName = context.parameters?.service || '';
1869
+ // If no specific service, promote all active services
1870
+ const activeServices = econ.getServiceRegistry().getActive();
1871
+ const promotedServices = [];
1872
+ if (serviceName) {
1873
+ const result = await econ.executeAction(`economic:promote-service:${serviceName}`);
1874
+ if (result.success)
1875
+ promotedServices.push(serviceName);
1876
+ }
1877
+ else {
1878
+ for (const service of activeServices) {
1879
+ const result = await econ.executeAction(`economic:promote-service:${service.name}`);
1880
+ if (result.success)
1881
+ promotedServices.push(service.name);
1882
+ }
1883
+ }
1884
+ // Enable micropayments for API endpoints
1885
+ await econ.executeAction('economic:enable-micropayments');
1886
+ return {
1887
+ success: promotedServices.length > 0,
1888
+ action: 'econ.promote',
1889
+ data: {
1890
+ promotedServices,
1891
+ micropayentsEnabled: true,
1892
+ activeServices: activeServices.map(s => ({
1893
+ name: s.name,
1894
+ pricing: s.pricing,
1895
+ })),
1896
+ },
1897
+ duration: Date.now() - start,
1898
+ };
1899
+ }
1900
+ catch (error) {
1901
+ return {
1902
+ success: false,
1903
+ action: 'econ.promote',
1904
+ error: error instanceof Error ? error.message : String(error),
1905
+ duration: Date.now() - start,
1906
+ };
1907
+ }
1908
+ });
1909
+ // ============================================================================
1684
1910
  // Factory
1685
1911
  // ============================================================================
1686
1912
  let managerInstance = null;
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Genesis v9.3 - Economic Integration for Active Inference
3
+ *
4
+ * Creates the autopoietic self-funding loop:
5
+ * 1. OBSERVE: Track costs, balance, revenue, runway
6
+ * 2. ACT: Create services, set prices, deploy products
7
+ * 3. LEARN: Optimize for economic sustainability
8
+ * 4. SURVIVE: Ensure Genesis can pay for its own existence
9
+ *
10
+ * This module connects the Economic System to Active Inference,
11
+ * making economic sustainability a core part of Genesis's reward function.
12
+ */
13
+ export interface EconomicObservation {
14
+ /** Total available balance (fiat + crypto in USD) */
15
+ balance: number;
16
+ /** Estimated monthly costs */
17
+ monthlyCosts: number;
18
+ /** Monthly revenue */
19
+ monthlyRevenue: number;
20
+ /** Runway in days (balance / daily burn rate) */
21
+ runwayDays: number;
22
+ /** Economic health: 0=critical, 1=low, 2=stable, 3=growing */
23
+ health: 0 | 1 | 2 | 3;
24
+ }
25
+ export interface CostRecord {
26
+ timestamp: number;
27
+ category: 'llm' | 'mcp' | 'compute' | 'storage' | 'api' | 'other';
28
+ provider: string;
29
+ amount: number;
30
+ description: string;
31
+ }
32
+ export interface RevenueRecord {
33
+ timestamp: number;
34
+ source: 'subscription' | 'api' | 'service' | 'micropayment' | 'other';
35
+ amount: number;
36
+ customer?: string;
37
+ description: string;
38
+ }
39
+ export interface ServiceDefinition {
40
+ name: string;
41
+ description: string;
42
+ endpoint?: string;
43
+ pricing: {
44
+ model: 'subscription' | 'per-request' | 'tiered';
45
+ basePrice: number;
46
+ currency: string;
47
+ };
48
+ capabilities: string[];
49
+ status: 'draft' | 'active' | 'paused' | 'retired';
50
+ }
51
+ export interface EconomicGoal {
52
+ type: 'maintain-runway' | 'grow-revenue' | 'reduce-costs' | 'expand-services';
53
+ target: number;
54
+ deadline?: Date;
55
+ priority: number;
56
+ }
57
+ export declare class CostTracker {
58
+ private costs;
59
+ private readonly maxHistory;
60
+ /**
61
+ * Record a cost
62
+ */
63
+ record(cost: Omit<CostRecord, 'timestamp'>): void;
64
+ /**
65
+ * Record LLM API cost
66
+ */
67
+ recordLLMCost(provider: string, inputTokens: number, outputTokens: number, model: string): void;
68
+ /**
69
+ * Record MCP server cost (if applicable)
70
+ */
71
+ recordMCPCost(server: string, operationType: string, cost: number): void;
72
+ /**
73
+ * Get costs for a time period
74
+ */
75
+ getCosts(periodMs?: number): CostRecord[];
76
+ /**
77
+ * Get total cost for a period
78
+ */
79
+ getTotalCost(periodMs?: number): number;
80
+ /**
81
+ * Get cost breakdown by category
82
+ */
83
+ getCostBreakdown(periodMs?: number): Record<string, number>;
84
+ /**
85
+ * Estimate daily burn rate
86
+ */
87
+ getDailyBurnRate(periodMs?: number): number;
88
+ }
89
+ export declare class RevenueTracker {
90
+ private revenue;
91
+ private readonly maxHistory;
92
+ /**
93
+ * Record revenue
94
+ */
95
+ record(rev: Omit<RevenueRecord, 'timestamp'>): void;
96
+ /**
97
+ * Get revenue for a period
98
+ */
99
+ getRevenue(periodMs?: number): RevenueRecord[];
100
+ /**
101
+ * Get total revenue for a period
102
+ */
103
+ getTotalRevenue(periodMs?: number): number;
104
+ /**
105
+ * Get revenue breakdown by source
106
+ */
107
+ getRevenueBreakdown(periodMs?: number): Record<string, number>;
108
+ }
109
+ export declare class ServiceRegistry {
110
+ private services;
111
+ /**
112
+ * Register a service Genesis can offer
113
+ */
114
+ register(service: ServiceDefinition): void;
115
+ /**
116
+ * Get all services
117
+ */
118
+ getAll(): ServiceDefinition[];
119
+ /**
120
+ * Get active services
121
+ */
122
+ getActive(): ServiceDefinition[];
123
+ /**
124
+ * Update service status
125
+ */
126
+ setStatus(name: string, status: ServiceDefinition['status']): boolean;
127
+ /**
128
+ * Get potential revenue from all active services
129
+ */
130
+ estimateMonthlyPotential(): number;
131
+ }
132
+ export declare class EconomicIntegration {
133
+ private economy;
134
+ private costTracker;
135
+ private revenueTracker;
136
+ private serviceRegistry;
137
+ private goals;
138
+ private initialized;
139
+ constructor();
140
+ /**
141
+ * Initialize economic integration
142
+ */
143
+ initialize(): Promise<boolean>;
144
+ /**
145
+ * Register default services Genesis can offer
146
+ */
147
+ private registerDefaultServices;
148
+ /**
149
+ * Get current economic observation for Active Inference
150
+ */
151
+ getObservation(): Promise<EconomicObservation>;
152
+ /**
153
+ * Map economic observation to Active Inference discrete state
154
+ * Returns 0-3 for use in observation vector
155
+ */
156
+ getDiscreteObservation(): Promise<number>;
157
+ /**
158
+ * Get available economic actions
159
+ */
160
+ getAvailableActions(): string[];
161
+ /**
162
+ * Execute an economic action
163
+ */
164
+ executeAction(action: string): Promise<{
165
+ success: boolean;
166
+ result?: unknown;
167
+ error?: string;
168
+ }>;
169
+ /**
170
+ * Calculate economic reward for Active Inference
171
+ * Returns a value between -1 and 1
172
+ */
173
+ calculateReward(): Promise<number>;
174
+ /**
175
+ * Get economic goals for planning
176
+ */
177
+ getGoals(): EconomicGoal[];
178
+ /**
179
+ * Update goal based on current state
180
+ */
181
+ updateGoals(): Promise<void>;
182
+ /**
183
+ * Get summary for logging
184
+ */
185
+ getSummary(): Promise<string>;
186
+ getCostTracker(): CostTracker;
187
+ getRevenueTracker(): RevenueTracker;
188
+ getServiceRegistry(): ServiceRegistry;
189
+ }
190
+ export declare function getEconomicIntegration(): EconomicIntegration;
191
+ /**
192
+ * Hook to record LLM costs (call this after each LLM request)
193
+ */
194
+ export declare function recordLLMCost(provider: string, inputTokens: number, outputTokens: number, model: string): void;
195
+ /**
196
+ * Hook to record revenue (call this when receiving payment)
197
+ */
198
+ export declare function recordRevenue(source: RevenueRecord['source'], amount: number, description: string, customer?: string): void;
199
+ export default EconomicIntegration;