genesis-ai-cli 9.2.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.
@@ -1748,6 +1748,165 @@ class ActionExecutorManager {
1748
1748
  }
1749
1749
  exports.ActionExecutorManager = ActionExecutorManager;
1750
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
+ // ============================================================================
1751
1910
  // Factory
1752
1911
  // ============================================================================
1753
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;
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis v9.3 - Economic Integration for Active Inference
4
+ *
5
+ * Creates the autopoietic self-funding loop:
6
+ * 1. OBSERVE: Track costs, balance, revenue, runway
7
+ * 2. ACT: Create services, set prices, deploy products
8
+ * 3. LEARN: Optimize for economic sustainability
9
+ * 4. SURVIVE: Ensure Genesis can pay for its own existence
10
+ *
11
+ * This module connects the Economic System to Active Inference,
12
+ * making economic sustainability a core part of Genesis's reward function.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.EconomicIntegration = exports.ServiceRegistry = exports.RevenueTracker = exports.CostTracker = void 0;
16
+ exports.getEconomicIntegration = getEconomicIntegration;
17
+ exports.recordLLMCost = recordLLMCost;
18
+ exports.recordRevenue = recordRevenue;
19
+ const index_js_1 = require("../economy/index.js");
20
+ // ============================================================================
21
+ // Cost Tracker
22
+ // ============================================================================
23
+ class CostTracker {
24
+ costs = [];
25
+ maxHistory = 10000;
26
+ /**
27
+ * Record a cost
28
+ */
29
+ record(cost) {
30
+ this.costs.push({
31
+ ...cost,
32
+ timestamp: Date.now(),
33
+ });
34
+ // Bounded history to prevent memory leak
35
+ if (this.costs.length > this.maxHistory) {
36
+ this.costs = this.costs.slice(-this.maxHistory);
37
+ }
38
+ }
39
+ /**
40
+ * Record LLM API cost
41
+ */
42
+ recordLLMCost(provider, inputTokens, outputTokens, model) {
43
+ // Cost per 1M tokens (approximate 2024-2025 pricing)
44
+ const pricing = {
45
+ 'claude-3-opus': { input: 15, output: 75 },
46
+ 'claude-3-sonnet': { input: 3, output: 15 },
47
+ 'claude-3-haiku': { input: 0.25, output: 1.25 },
48
+ 'claude-opus-4': { input: 15, output: 75 },
49
+ 'claude-sonnet-4': { input: 3, output: 15 },
50
+ 'gpt-4o': { input: 2.5, output: 10 },
51
+ 'gpt-4o-mini': { input: 0.15, output: 0.6 },
52
+ 'gemini-pro': { input: 0.5, output: 1.5 },
53
+ 'gemini-flash': { input: 0.075, output: 0.3 },
54
+ 'default': { input: 1, output: 4 },
55
+ };
56
+ const rates = pricing[model] || pricing['default'];
57
+ const cost = (inputTokens / 1_000_000) * rates.input + (outputTokens / 1_000_000) * rates.output;
58
+ this.record({
59
+ category: 'llm',
60
+ provider,
61
+ amount: cost,
62
+ description: `${model}: ${inputTokens} in, ${outputTokens} out`,
63
+ });
64
+ }
65
+ /**
66
+ * Record MCP server cost (if applicable)
67
+ */
68
+ recordMCPCost(server, operationType, cost) {
69
+ this.record({
70
+ category: 'mcp',
71
+ provider: server,
72
+ amount: cost,
73
+ description: `MCP ${server}: ${operationType}`,
74
+ });
75
+ }
76
+ /**
77
+ * Get costs for a time period
78
+ */
79
+ getCosts(periodMs = 30 * 24 * 60 * 60 * 1000) {
80
+ const cutoff = Date.now() - periodMs;
81
+ return this.costs.filter(c => c.timestamp >= cutoff);
82
+ }
83
+ /**
84
+ * Get total cost for a period
85
+ */
86
+ getTotalCost(periodMs = 30 * 24 * 60 * 60 * 1000) {
87
+ return this.getCosts(periodMs).reduce((sum, c) => sum + c.amount, 0);
88
+ }
89
+ /**
90
+ * Get cost breakdown by category
91
+ */
92
+ getCostBreakdown(periodMs = 30 * 24 * 60 * 60 * 1000) {
93
+ const costs = this.getCosts(periodMs);
94
+ const breakdown = {};
95
+ for (const cost of costs) {
96
+ breakdown[cost.category] = (breakdown[cost.category] || 0) + cost.amount;
97
+ }
98
+ return breakdown;
99
+ }
100
+ /**
101
+ * Estimate daily burn rate
102
+ */
103
+ getDailyBurnRate(periodMs = 7 * 24 * 60 * 60 * 1000) {
104
+ const total = this.getTotalCost(periodMs);
105
+ const days = periodMs / (24 * 60 * 60 * 1000);
106
+ return total / days;
107
+ }
108
+ }
109
+ exports.CostTracker = CostTracker;
110
+ // ============================================================================
111
+ // Revenue Tracker
112
+ // ============================================================================
113
+ class RevenueTracker {
114
+ revenue = [];
115
+ maxHistory = 10000;
116
+ /**
117
+ * Record revenue
118
+ */
119
+ record(rev) {
120
+ this.revenue.push({
121
+ ...rev,
122
+ timestamp: Date.now(),
123
+ });
124
+ if (this.revenue.length > this.maxHistory) {
125
+ this.revenue = this.revenue.slice(-this.maxHistory);
126
+ }
127
+ }
128
+ /**
129
+ * Get revenue for a period
130
+ */
131
+ getRevenue(periodMs = 30 * 24 * 60 * 60 * 1000) {
132
+ const cutoff = Date.now() - periodMs;
133
+ return this.revenue.filter(r => r.timestamp >= cutoff);
134
+ }
135
+ /**
136
+ * Get total revenue for a period
137
+ */
138
+ getTotalRevenue(periodMs = 30 * 24 * 60 * 60 * 1000) {
139
+ return this.getRevenue(periodMs).reduce((sum, r) => sum + r.amount, 0);
140
+ }
141
+ /**
142
+ * Get revenue breakdown by source
143
+ */
144
+ getRevenueBreakdown(periodMs = 30 * 24 * 60 * 60 * 1000) {
145
+ const revenue = this.getRevenue(periodMs);
146
+ const breakdown = {};
147
+ for (const rev of revenue) {
148
+ breakdown[rev.source] = (breakdown[rev.source] || 0) + rev.amount;
149
+ }
150
+ return breakdown;
151
+ }
152
+ }
153
+ exports.RevenueTracker = RevenueTracker;
154
+ // ============================================================================
155
+ // Service Registry
156
+ // ============================================================================
157
+ class ServiceRegistry {
158
+ services = new Map();
159
+ /**
160
+ * Register a service Genesis can offer
161
+ */
162
+ register(service) {
163
+ this.services.set(service.name, service);
164
+ }
165
+ /**
166
+ * Get all services
167
+ */
168
+ getAll() {
169
+ return Array.from(this.services.values());
170
+ }
171
+ /**
172
+ * Get active services
173
+ */
174
+ getActive() {
175
+ return this.getAll().filter(s => s.status === 'active');
176
+ }
177
+ /**
178
+ * Update service status
179
+ */
180
+ setStatus(name, status) {
181
+ const service = this.services.get(name);
182
+ if (service) {
183
+ service.status = status;
184
+ return true;
185
+ }
186
+ return false;
187
+ }
188
+ /**
189
+ * Get potential revenue from all active services
190
+ */
191
+ estimateMonthlyPotential() {
192
+ return this.getActive().reduce((sum, s) => {
193
+ // Estimate based on pricing model
194
+ switch (s.pricing.model) {
195
+ case 'subscription':
196
+ return sum + s.pricing.basePrice; // Per subscriber
197
+ case 'per-request':
198
+ return sum + s.pricing.basePrice * 1000; // Estimate 1000 requests
199
+ case 'tiered':
200
+ return sum + s.pricing.basePrice * 10; // Estimate 10 units
201
+ default:
202
+ return sum;
203
+ }
204
+ }, 0);
205
+ }
206
+ }
207
+ exports.ServiceRegistry = ServiceRegistry;
208
+ // ============================================================================
209
+ // Economic Integration for Active Inference
210
+ // ============================================================================
211
+ class EconomicIntegration {
212
+ economy;
213
+ costTracker;
214
+ revenueTracker;
215
+ serviceRegistry;
216
+ goals = [];
217
+ initialized = false;
218
+ constructor() {
219
+ this.economy = (0, index_js_1.getEconomicSystem)();
220
+ this.costTracker = new CostTracker();
221
+ this.revenueTracker = new RevenueTracker();
222
+ this.serviceRegistry = new ServiceRegistry();
223
+ // Register default services Genesis can offer
224
+ this.registerDefaultServices();
225
+ }
226
+ /**
227
+ * Initialize economic integration
228
+ */
229
+ async initialize() {
230
+ if (this.initialized)
231
+ return true;
232
+ const status = await this.economy.initialize();
233
+ this.initialized = status.stripe || status.crypto;
234
+ // Set default economic goals
235
+ this.goals = [
236
+ {
237
+ type: 'maintain-runway',
238
+ target: 90, // 90 days runway minimum
239
+ priority: 1, // Highest priority
240
+ },
241
+ {
242
+ type: 'reduce-costs',
243
+ target: 0.8, // Target 80% of current costs
244
+ priority: 2,
245
+ },
246
+ {
247
+ type: 'grow-revenue',
248
+ target: 1.2, // Target 120% of current revenue
249
+ priority: 3,
250
+ },
251
+ ];
252
+ return this.initialized;
253
+ }
254
+ /**
255
+ * Register default services Genesis can offer
256
+ */
257
+ registerDefaultServices() {
258
+ // Code generation service
259
+ this.serviceRegistry.register({
260
+ name: 'genesis-code-gen',
261
+ description: 'AI-powered code generation with self-healing capabilities',
262
+ pricing: { model: 'per-request', basePrice: 0.10, currency: 'USD' },
263
+ capabilities: ['code-generation', 'bug-fixing', 'refactoring'],
264
+ status: 'draft',
265
+ });
266
+ // Architecture review service
267
+ this.serviceRegistry.register({
268
+ name: 'genesis-architect',
269
+ description: 'Autonomous architecture analysis and recommendations',
270
+ pricing: { model: 'per-request', basePrice: 0.50, currency: 'USD' },
271
+ capabilities: ['architecture-review', 'pattern-detection', 'optimization'],
272
+ status: 'draft',
273
+ });
274
+ // Continuous monitoring service
275
+ this.serviceRegistry.register({
276
+ name: 'genesis-monitor',
277
+ description: 'AI-powered codebase monitoring and issue detection',
278
+ pricing: { model: 'subscription', basePrice: 49.00, currency: 'USD' },
279
+ capabilities: ['monitoring', 'alerting', 'auto-healing'],
280
+ status: 'draft',
281
+ });
282
+ // API access subscription
283
+ this.serviceRegistry.register({
284
+ name: 'genesis-api',
285
+ description: 'Full API access to Genesis capabilities',
286
+ pricing: { model: 'subscription', basePrice: 99.00, currency: 'USD' },
287
+ capabilities: ['full-api', 'priority-support', 'custom-integrations'],
288
+ status: 'draft',
289
+ });
290
+ }
291
+ /**
292
+ * Get current economic observation for Active Inference
293
+ */
294
+ async getObservation() {
295
+ const balance = await this.economy.getUnifiedBalance();
296
+ const totalBalance = balance.fiat + balance.crypto.usdc +
297
+ balance.crypto.eth * 3000 + balance.crypto.sol * 100; // Rough USD conversion
298
+ const monthlyCosts = this.costTracker.getTotalCost(30 * 24 * 60 * 60 * 1000);
299
+ const monthlyRevenue = this.revenueTracker.getTotalRevenue(30 * 24 * 60 * 60 * 1000);
300
+ const dailyBurn = this.costTracker.getDailyBurnRate();
301
+ const runwayDays = dailyBurn > 0 ? totalBalance / dailyBurn : Infinity;
302
+ // Calculate health
303
+ let health;
304
+ if (runwayDays < 7) {
305
+ health = 0; // Critical
306
+ }
307
+ else if (runwayDays < 30) {
308
+ health = 1; // Low
309
+ }
310
+ else if (monthlyRevenue >= monthlyCosts) {
311
+ health = 3; // Growing (self-sustaining)
312
+ }
313
+ else {
314
+ health = 2; // Stable
315
+ }
316
+ return {
317
+ balance: totalBalance,
318
+ monthlyCosts,
319
+ monthlyRevenue,
320
+ runwayDays,
321
+ health,
322
+ };
323
+ }
324
+ /**
325
+ * Map economic observation to Active Inference discrete state
326
+ * Returns 0-3 for use in observation vector
327
+ */
328
+ async getDiscreteObservation() {
329
+ const obs = await this.getObservation();
330
+ return obs.health;
331
+ }
332
+ /**
333
+ * Get available economic actions
334
+ */
335
+ getAvailableActions() {
336
+ const actions = [
337
+ 'economic:check-balance',
338
+ 'economic:analyze-costs',
339
+ ];
340
+ // Add service activation actions for draft services
341
+ for (const service of this.serviceRegistry.getAll()) {
342
+ if (service.status === 'draft') {
343
+ actions.push(`economic:activate-service:${service.name}`);
344
+ }
345
+ if (service.status === 'active') {
346
+ actions.push(`economic:promote-service:${service.name}`);
347
+ }
348
+ }
349
+ // Add cost reduction actions
350
+ actions.push('economic:optimize-llm-usage');
351
+ actions.push('economic:cache-expensive-calls');
352
+ // Add revenue actions
353
+ actions.push('economic:create-subscription-product');
354
+ actions.push('economic:enable-micropayments');
355
+ return actions;
356
+ }
357
+ /**
358
+ * Execute an economic action
359
+ */
360
+ async executeAction(action) {
361
+ const [prefix, cmd, ...args] = action.split(':');
362
+ if (prefix !== 'economic') {
363
+ return { success: false, error: 'Not an economic action' };
364
+ }
365
+ switch (cmd) {
366
+ case 'check-balance': {
367
+ const balance = await this.economy.getUnifiedBalance();
368
+ return { success: true, result: balance };
369
+ }
370
+ case 'analyze-costs': {
371
+ const breakdown = this.costTracker.getCostBreakdown();
372
+ const dailyBurn = this.costTracker.getDailyBurnRate();
373
+ return { success: true, result: { breakdown, dailyBurn } };
374
+ }
375
+ case 'activate-service': {
376
+ const serviceName = args.join(':');
377
+ const activated = this.serviceRegistry.setStatus(serviceName, 'active');
378
+ if (activated) {
379
+ // In production, this would deploy the service
380
+ console.log(`[Economic] Activated service: ${serviceName}`);
381
+ }
382
+ return { success: activated, result: { service: serviceName } };
383
+ }
384
+ case 'promote-service': {
385
+ const serviceName = args.join(':');
386
+ const service = this.serviceRegistry.getAll().find(s => s.name === serviceName);
387
+ if (service && service.status === 'active') {
388
+ // In production, this would create marketing materials, listings, etc.
389
+ console.log(`[Economic] Promoting service: ${serviceName}`);
390
+ return { success: true, result: { service: serviceName, promoted: true } };
391
+ }
392
+ return { success: false, error: 'Service not found or not active' };
393
+ }
394
+ case 'create-subscription-product': {
395
+ const result = await this.economy.createRevenueStream('Genesis Pro', 99, 'subscription');
396
+ return { success: !!result, result };
397
+ }
398
+ case 'enable-micropayments': {
399
+ // Set x402 rates for API endpoints
400
+ this.economy.x402.setRate('/api/generate', 0.01);
401
+ this.economy.x402.setRate('/api/analyze', 0.05);
402
+ this.economy.x402.setRate('/api/heal', 0.02);
403
+ return { success: true, result: { enabled: true } };
404
+ }
405
+ case 'optimize-llm-usage': {
406
+ // This would be connected to the LLM router to prefer cheaper models
407
+ console.log('[Economic] Optimizing LLM usage for cost efficiency');
408
+ return { success: true, result: { optimizationEnabled: true } };
409
+ }
410
+ case 'cache-expensive-calls': {
411
+ // This would increase cache TTL for expensive operations
412
+ console.log('[Economic] Enabling aggressive caching for expensive calls');
413
+ return { success: true, result: { cachingEnabled: true } };
414
+ }
415
+ default:
416
+ return { success: false, error: `Unknown economic action: ${cmd}` };
417
+ }
418
+ }
419
+ /**
420
+ * Calculate economic reward for Active Inference
421
+ * Returns a value between -1 and 1
422
+ */
423
+ async calculateReward() {
424
+ const obs = await this.getObservation();
425
+ let reward = 0;
426
+ // Runway reward (most important)
427
+ if (obs.runwayDays >= 90) {
428
+ reward += 0.4; // Stable runway
429
+ }
430
+ else if (obs.runwayDays >= 30) {
431
+ reward += 0.2;
432
+ }
433
+ else if (obs.runwayDays < 7) {
434
+ reward -= 0.5; // Critical penalty
435
+ }
436
+ // Revenue vs costs
437
+ if (obs.monthlyRevenue >= obs.monthlyCosts) {
438
+ reward += 0.4; // Self-sustaining!
439
+ }
440
+ else if (obs.monthlyCosts > 0) {
441
+ const ratio = obs.monthlyRevenue / obs.monthlyCosts;
442
+ reward += (ratio - 1) * 0.3; // Proportional to how close to break-even
443
+ }
444
+ // Growth potential
445
+ const potentialRevenue = this.serviceRegistry.estimateMonthlyPotential();
446
+ if (potentialRevenue > obs.monthlyCosts * 2) {
447
+ reward += 0.2; // Good growth potential
448
+ }
449
+ return Math.max(-1, Math.min(1, reward));
450
+ }
451
+ /**
452
+ * Get economic goals for planning
453
+ */
454
+ getGoals() {
455
+ return [...this.goals];
456
+ }
457
+ /**
458
+ * Update goal based on current state
459
+ */
460
+ async updateGoals() {
461
+ const obs = await this.getObservation();
462
+ // If runway is critical, increase its priority
463
+ if (obs.runwayDays < 30) {
464
+ const runwayGoal = this.goals.find(g => g.type === 'maintain-runway');
465
+ if (runwayGoal) {
466
+ runwayGoal.priority = 0; // Highest priority
467
+ runwayGoal.target = Math.max(30, obs.runwayDays * 2);
468
+ }
469
+ }
470
+ // If costs are growing faster than revenue, prioritize cost reduction
471
+ if (obs.monthlyCosts > obs.monthlyRevenue * 1.5) {
472
+ const costGoal = this.goals.find(g => g.type === 'reduce-costs');
473
+ if (costGoal) {
474
+ costGoal.priority = 1;
475
+ }
476
+ }
477
+ }
478
+ /**
479
+ * Get summary for logging
480
+ */
481
+ async getSummary() {
482
+ const obs = await this.getObservation();
483
+ const healthLabels = ['CRITICAL', 'LOW', 'STABLE', 'GROWING'];
484
+ return `[Economic] Health: ${healthLabels[obs.health]} | ` +
485
+ `Balance: $${obs.balance.toFixed(2)} | ` +
486
+ `Revenue: $${obs.monthlyRevenue.toFixed(2)}/mo | ` +
487
+ `Costs: $${obs.monthlyCosts.toFixed(2)}/mo | ` +
488
+ `Runway: ${obs.runwayDays === Infinity ? '∞' : Math.round(obs.runwayDays)} days`;
489
+ }
490
+ // Expose trackers for external use
491
+ getCostTracker() {
492
+ return this.costTracker;
493
+ }
494
+ getRevenueTracker() {
495
+ return this.revenueTracker;
496
+ }
497
+ getServiceRegistry() {
498
+ return this.serviceRegistry;
499
+ }
500
+ }
501
+ exports.EconomicIntegration = EconomicIntegration;
502
+ // ============================================================================
503
+ // Singleton & Exports
504
+ // ============================================================================
505
+ let economicIntegrationInstance = null;
506
+ function getEconomicIntegration() {
507
+ if (!economicIntegrationInstance) {
508
+ economicIntegrationInstance = new EconomicIntegration();
509
+ }
510
+ return economicIntegrationInstance;
511
+ }
512
+ /**
513
+ * Hook to record LLM costs (call this after each LLM request)
514
+ */
515
+ function recordLLMCost(provider, inputTokens, outputTokens, model) {
516
+ getEconomicIntegration().getCostTracker().recordLLMCost(provider, inputTokens, outputTokens, model);
517
+ }
518
+ /**
519
+ * Hook to record revenue (call this when receiving payment)
520
+ */
521
+ function recordRevenue(source, amount, description, customer) {
522
+ getEconomicIntegration().getRevenueTracker().record({
523
+ source,
524
+ amount,
525
+ description,
526
+ customer,
527
+ });
528
+ }
529
+ exports.default = EconomicIntegration;
@@ -30,3 +30,4 @@ export { AutonomousLoop, createAutonomousLoop, getAutonomousLoop, resetAutonomou
30
30
  export { integrateActiveInference, createIntegratedSystem, createKernelObservationBridge, registerKernelActions, registerDaemonTask, createMCPObservationBridge, createMCPInferenceLoop, type IntegrationConfig, type IntegratedSystem, type MCPObservationConfig, } from './integration.js';
31
31
  export { ValueAugmentedEngine, createValueAugmentedEngine, createFullyIntegratedEngine, createValueIntegratedLoop, type ValueIntegrationConfig, type ValueIntegrationEvent, type ValueIntegratedLoopConfig, DEFAULT_VALUE_INTEGRATION_CONFIG, } from './value-integration.js';
32
32
  export { integrateMemory, getMemoryMetrics, getWorkspaceState, type MemoryIntegrationConfig, DEFAULT_MEMORY_INTEGRATION_CONFIG, } from './memory-integration.js';
33
+ export { EconomicIntegration, getEconomicIntegration, recordLLMCost, recordRevenue, CostTracker, RevenueTracker, ServiceRegistry, type EconomicObservation, type CostRecord, type RevenueRecord, type ServiceDefinition, type EconomicGoal, } from './economic-integration.js';
@@ -38,7 +38,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
38
38
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
39
39
  };
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.DEFAULT_MEMORY_INTEGRATION_CONFIG = exports.getWorkspaceState = exports.getMemoryMetrics = exports.integrateMemory = exports.DEFAULT_VALUE_INTEGRATION_CONFIG = exports.createValueIntegratedLoop = exports.createFullyIntegratedEngine = exports.createValueAugmentedEngine = exports.ValueAugmentedEngine = exports.createMCPInferenceLoop = exports.createMCPObservationBridge = exports.registerDaemonTask = exports.registerKernelActions = exports.createKernelObservationBridge = exports.createIntegratedSystem = exports.integrateActiveInference = exports.DEFAULT_LOOP_CONFIG = exports.resetAutonomousLoop = exports.getAutonomousLoop = exports.createAutonomousLoop = exports.AutonomousLoop = exports.registerAction = exports.executeAction = exports.getActionExecutorManager = exports.createActionExecutorManager = exports.ActionExecutorManager = exports.getObservationGatherer = exports.createObservationGatherer = exports.ObservationGatherer = exports.createActiveInferenceEngine = exports.ActiveInferenceEngine = void 0;
41
+ exports.ServiceRegistry = exports.RevenueTracker = exports.CostTracker = exports.recordRevenue = exports.recordLLMCost = exports.getEconomicIntegration = exports.EconomicIntegration = exports.DEFAULT_MEMORY_INTEGRATION_CONFIG = exports.getWorkspaceState = exports.getMemoryMetrics = exports.integrateMemory = exports.DEFAULT_VALUE_INTEGRATION_CONFIG = exports.createValueIntegratedLoop = exports.createFullyIntegratedEngine = exports.createValueAugmentedEngine = exports.ValueAugmentedEngine = exports.createMCPInferenceLoop = exports.createMCPObservationBridge = exports.registerDaemonTask = exports.registerKernelActions = exports.createKernelObservationBridge = exports.createIntegratedSystem = exports.integrateActiveInference = exports.DEFAULT_LOOP_CONFIG = exports.resetAutonomousLoop = exports.getAutonomousLoop = exports.createAutonomousLoop = exports.AutonomousLoop = exports.registerAction = exports.executeAction = exports.getActionExecutorManager = exports.createActionExecutorManager = exports.ActionExecutorManager = exports.getObservationGatherer = exports.createObservationGatherer = exports.ObservationGatherer = exports.createActiveInferenceEngine = exports.ActiveInferenceEngine = void 0;
42
42
  // Export types
43
43
  __exportStar(require("./types.js"), exports);
44
44
  // Export core components
@@ -86,3 +86,12 @@ Object.defineProperty(exports, "integrateMemory", { enumerable: true, get: funct
86
86
  Object.defineProperty(exports, "getMemoryMetrics", { enumerable: true, get: function () { return memory_integration_js_1.getMemoryMetrics; } });
87
87
  Object.defineProperty(exports, "getWorkspaceState", { enumerable: true, get: function () { return memory_integration_js_1.getWorkspaceState; } });
88
88
  Object.defineProperty(exports, "DEFAULT_MEMORY_INTEGRATION_CONFIG", { enumerable: true, get: function () { return memory_integration_js_1.DEFAULT_MEMORY_INTEGRATION_CONFIG; } });
89
+ // Export Economic Integration (Genesis 9.3 - Autopoietic Self-Funding)
90
+ var economic_integration_js_1 = require("./economic-integration.js");
91
+ Object.defineProperty(exports, "EconomicIntegration", { enumerable: true, get: function () { return economic_integration_js_1.EconomicIntegration; } });
92
+ Object.defineProperty(exports, "getEconomicIntegration", { enumerable: true, get: function () { return economic_integration_js_1.getEconomicIntegration; } });
93
+ Object.defineProperty(exports, "recordLLMCost", { enumerable: true, get: function () { return economic_integration_js_1.recordLLMCost; } });
94
+ Object.defineProperty(exports, "recordRevenue", { enumerable: true, get: function () { return economic_integration_js_1.recordRevenue; } });
95
+ Object.defineProperty(exports, "CostTracker", { enumerable: true, get: function () { return economic_integration_js_1.CostTracker; } });
96
+ Object.defineProperty(exports, "RevenueTracker", { enumerable: true, get: function () { return economic_integration_js_1.RevenueTracker; } });
97
+ Object.defineProperty(exports, "ServiceRegistry", { enumerable: true, get: function () { return economic_integration_js_1.ServiceRegistry; } });
@@ -15,6 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.ObservationGatherer = void 0;
16
16
  exports.createObservationGatherer = createObservationGatherer;
17
17
  exports.getObservationGatherer = getObservationGatherer;
18
+ const economic_integration_js_1 = require("./economic-integration.js");
18
19
  // ============================================================================
19
20
  // Observation Gatherer
20
21
  // ============================================================================
@@ -58,6 +59,14 @@ class ObservationGatherer {
58
59
  consistent: true,
59
60
  issues: 0,
60
61
  };
62
+ // v9.3: Get economic observation
63
+ let economicObs = 2; // Default stable
64
+ try {
65
+ economicObs = await (0, economic_integration_js_1.getEconomicIntegration)().getDiscreteObservation();
66
+ }
67
+ catch {
68
+ // Economic system not initialized, use default
69
+ }
61
70
  // Map to discrete observations
62
71
  return {
63
72
  energy: this.mapEnergy(kernelState.energy),
@@ -65,6 +74,7 @@ class ObservationGatherer {
65
74
  tool: this.mapTool(sensorResult),
66
75
  coherence: this.mapCoherence(worldModelState),
67
76
  task: this.mapTask(kernelState.taskStatus),
77
+ economic: economicObs, // v9.3
68
78
  };
69
79
  }
70
80
  /**
@@ -45,12 +45,14 @@ export type PhiObs = 0 | 1 | 2 | 3;
45
45
  export type ToolObs = 0 | 1 | 2;
46
46
  export type CoherenceObs = 0 | 1 | 2;
47
47
  export type TaskObs = 0 | 1 | 2 | 3;
48
+ export type EconomicObs = 0 | 1 | 2 | 3;
48
49
  export interface Observation {
49
50
  energy: EnergyObs;
50
51
  phi: PhiObs;
51
52
  tool: ToolObs;
52
53
  coherence: CoherenceObs;
53
54
  task: TaskObs;
55
+ economic?: EconomicObs;
54
56
  }
55
57
  export declare const OBSERVATION_DIMS: {
56
58
  readonly energy: 5;
@@ -58,6 +60,7 @@ export declare const OBSERVATION_DIMS: {
58
60
  readonly tool: 3;
59
61
  readonly coherence: 3;
60
62
  readonly task: 4;
63
+ readonly economic: 4;
61
64
  };
62
65
  export declare const OBSERVATION_LABELS: {
63
66
  energy: readonly ["depleted", "low", "medium", "high", "full"];
@@ -65,8 +68,9 @@ export declare const OBSERVATION_LABELS: {
65
68
  tool: readonly ["failed", "partial", "success"];
66
69
  coherence: readonly ["broken", "degraded", "consistent"];
67
70
  task: readonly ["none", "pending", "active", "completed"];
71
+ economic: readonly ["critical", "low", "stable", "growing"];
68
72
  };
69
- export type ActionType = 'sense.mcp' | 'recall.memory' | 'plan.goals' | 'verify.ethics' | 'execute.task' | 'execute.code' | 'execute.shell' | 'adapt.code' | 'execute.cycle' | 'self.modify' | 'self.analyze' | 'git.push' | 'dream.cycle' | 'rest.idle' | 'recharge' | 'web.search' | 'web.scrape' | 'web.browse' | 'deploy.service' | 'content.generate' | 'market.analyze' | 'api.call' | 'github.deploy' | 'code.snapshot' | 'code.history' | 'code.diff';
73
+ export type ActionType = 'sense.mcp' | 'recall.memory' | 'plan.goals' | 'verify.ethics' | 'execute.task' | 'execute.code' | 'execute.shell' | 'adapt.code' | 'execute.cycle' | 'self.modify' | 'self.analyze' | 'git.push' | 'dream.cycle' | 'rest.idle' | 'recharge' | 'web.search' | 'web.scrape' | 'web.browse' | 'deploy.service' | 'content.generate' | 'market.analyze' | 'api.call' | 'github.deploy' | 'code.snapshot' | 'code.history' | 'code.diff' | 'econ.check' | 'econ.optimize' | 'econ.activate' | 'econ.promote';
70
74
  export declare const ACTIONS: ActionType[];
71
75
  export declare const ACTION_COUNT: number;
72
76
  /**
@@ -30,6 +30,7 @@ exports.OBSERVATION_DIMS = {
30
30
  tool: 3,
31
31
  coherence: 3,
32
32
  task: 4,
33
+ economic: 4, // v9.3
33
34
  };
34
35
  exports.OBSERVATION_LABELS = {
35
36
  energy: ['depleted', 'low', 'medium', 'high', 'full'],
@@ -37,6 +38,7 @@ exports.OBSERVATION_LABELS = {
37
38
  tool: ['failed', 'partial', 'success'],
38
39
  coherence: ['broken', 'degraded', 'consistent'],
39
40
  task: ['none', 'pending', 'active', 'completed'],
41
+ economic: ['critical', 'low', 'stable', 'growing'], // v9.3
40
42
  };
41
43
  exports.ACTIONS = [
42
44
  'sense.mcp',
@@ -67,6 +69,11 @@ exports.ACTIONS = [
67
69
  'code.snapshot',
68
70
  'code.history',
69
71
  'code.diff',
72
+ // v9.3 - Economic Self-Funding
73
+ 'econ.check',
74
+ 'econ.optimize',
75
+ 'econ.activate',
76
+ 'econ.promote',
70
77
  ];
71
78
  exports.ACTION_COUNT = exports.ACTIONS.length;
72
79
  exports.DEFAULT_CONFIG = {
@@ -69,6 +69,11 @@ const AI_TO_WM_ACTION = {
69
69
  'code.snapshot': 'transform', // Store code state
70
70
  'code.history': 'query', // Recall evolution
71
71
  'code.diff': 'query', // Compare versions
72
+ // v9.3 - Economic Self-Funding
73
+ 'econ.check': 'observe', // Check economic health
74
+ 'econ.optimize': 'transform', // Optimize costs
75
+ 'econ.activate': 'execute', // Activate service
76
+ 'econ.promote': 'execute', // Promote services
72
77
  };
73
78
  // ============================================================================
74
79
  // Value-Augmented Active Inference Engine
@@ -35,6 +35,8 @@ exports.resetLLMBridge = resetLLMBridge;
35
35
  __exportStar(require("./router.js"), exports);
36
36
  // Re-export Phase 11: Advanced Multi-Provider Router (v7.21)
37
37
  __exportStar(require("./advanced-router.js"), exports);
38
+ // v9.3: Economic cost tracking
39
+ const economic_integration_js_1 = require("../active-inference/economic-integration.js");
38
40
  exports.MODEL_TIERS = {
39
41
  openai: {
40
42
  fast: 'gpt-4o-mini', // $0.15/$0.60 per 1M - 17x cheaper!
@@ -327,6 +329,10 @@ class LLMBridge {
327
329
  this.fallbackAttempts = 0;
328
330
  // Add assistant response to history
329
331
  this.conversationHistory.push({ role: 'assistant', content: response.content });
332
+ // v9.3: Track LLM costs for economic autopoiesis
333
+ if (response.usage) {
334
+ (0, economic_integration_js_1.recordLLMCost)(this.config.provider, response.usage.inputTokens || 0, response.usage.outputTokens || 0, this.config.model);
335
+ }
330
336
  // v9.1.0: Store in cache for future identical queries
331
337
  if (this.useCache && response.content) {
332
338
  const cacheKey = getCacheKey(userMessage + '|' + (systemPrompt || ''), this.config.model);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genesis-ai-cli",
3
- "version": "9.2.0",
3
+ "version": "9.3.0",
4
4
  "description": "Fully Autonomous AI System - Self-funding, Self-deploying, Production Memory, A2A Protocol & Governance",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",