@holoscript/framework 6.0.3 → 6.0.4

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 (160) hide show
  1. package/CHANGELOG.md +1 -2
  2. package/ROADMAP.md +68 -66
  3. package/dist/{InvisibleWallet-BB6tFvRA.d.cts → InvisibleWallet-EFiuaLn3.d.cts} +1 -1
  4. package/dist/{OrchestratorAgent-BvWgf9uw.d.cts → OrchestratorAgent-CrLDGNL6.d.cts} +1 -1
  5. package/dist/agents/index.cjs +11 -10
  6. package/dist/agents/index.d.cts +4 -16
  7. package/dist/ai/index.cjs +2 -2
  8. package/dist/behavior.cjs +10 -0
  9. package/dist/economy/index.cjs +4 -4
  10. package/dist/economy/index.d.cts +2 -2
  11. package/dist/index.cjs +33 -11
  12. package/dist/index.d.cts +3 -3
  13. package/dist/swarm/index.cjs +3 -0
  14. package/package.json +14 -9
  15. package/src/__tests__/bounty-marketplace.test.ts +53 -21
  16. package/src/__tests__/delegation.test.ts +1 -4
  17. package/src/__tests__/done-log-audit.test.ts +38 -46
  18. package/src/__tests__/framework.test.ts +172 -53
  19. package/src/__tests__/goal-synthesizer.test.ts +9 -6
  20. package/src/__tests__/presence.test.ts +1 -1
  21. package/src/__tests__/protocol-agent.test.ts +12 -11
  22. package/src/__tests__/revenue-splitter.test.ts +22 -15
  23. package/src/__tests__/scenario-driven-todo.test.ts +55 -35
  24. package/src/__tests__/self-improve.test.ts +28 -9
  25. package/src/__tests__/service-lifecycle.test.ts +9 -3
  26. package/src/__tests__/skill-router.test.ts +3 -3
  27. package/src/agents/CulturalMemory.ts +6 -6
  28. package/src/agents/DelegationTraceHooks.ts +560 -0
  29. package/src/agents/FederatedRegistryAdapter.ts +1 -1
  30. package/src/agents/NormEngine.ts +3 -8
  31. package/src/agents/OrchestratorAgent.ts +1 -1
  32. package/src/agents/TaskDelegationService.ts +5 -9
  33. package/src/agents/__tests__/AgentWalletRegistry.test.ts +5 -4
  34. package/src/agents/__tests__/CrossRealityHandoff.test.ts +9 -3
  35. package/src/agents/__tests__/DelegationTraceHooks.test.ts +390 -0
  36. package/src/agents/__tests__/TaskDelegationService.test.ts +4 -2
  37. package/src/agents/spatial-comms/Layer1RealTime.ts +36 -19
  38. package/src/agents/spatial-comms/Layer2A2A.ts +1 -3
  39. package/src/agents/spatial-comms/Layer3MCP.ts +13 -4
  40. package/src/agents/spatial-comms/ProtocolTypes.ts +5 -2
  41. package/src/agents/spatial-comms/examples/multi-agent-world-creation.ts +2 -2
  42. package/src/ai/HoloScriptGenerator.ts +2 -2
  43. package/src/ai/__tests__/PerceptionSystem.prod.test.ts +1 -1
  44. package/src/ai/__tests__/PerceptionSystem.test.ts +14 -14
  45. package/src/ai/__tests__/SteeringBehaviors.prod.test.ts +1 -1
  46. package/src/ai/index.ts +5 -1
  47. package/src/board/audit.ts +17 -6
  48. package/src/board/board-ops.ts +45 -15
  49. package/src/board/board-types.ts +94 -20
  50. package/src/delegation.ts +5 -3
  51. package/src/distributed-claimer.ts +13 -2
  52. package/src/economy/BountyManager.ts +40 -18
  53. package/src/economy/KnowledgeMarketplace.ts +27 -8
  54. package/src/economy/PaymentWebhookService.ts +0 -1
  55. package/src/economy/RevenueSplitter.ts +2 -4
  56. package/src/economy/UnifiedBudgetOptimizer.ts +8 -9
  57. package/src/economy/_core-stubs.ts +1 -1
  58. package/src/economy/x402-facilitator.ts +17 -8
  59. package/src/index.ts +16 -12
  60. package/src/knowledge/__tests__/knowledge-consolidator.test.ts +138 -89
  61. package/src/knowledge/__tests__/knowledge-store-vector.test.ts +59 -16
  62. package/src/knowledge/brain.ts +7 -7
  63. package/src/knowledge/consolidation.ts +16 -16
  64. package/src/knowledge/knowledge-consolidator.ts +60 -30
  65. package/src/knowledge/knowledge-store.ts +83 -45
  66. package/src/learning/ProceduralCompiler.ts +6 -1
  67. package/src/learning/learning/MemoryConsolidator.ts +102 -0
  68. package/src/learning/learning/MemoryScorer.ts +69 -0
  69. package/src/learning/learning/ProceduralCompiler.ts +45 -0
  70. package/src/learning/learning/SemanticClusterer.ts +66 -0
  71. package/src/llm/llm-adapter.ts +24 -10
  72. package/src/mesh/index.ts +37 -17
  73. package/src/protocol/goal-synthesizer.ts +24 -34
  74. package/src/protocol/implementations.ts +91 -22
  75. package/src/protocol/micro-phase-decomposer.ts +25 -17
  76. package/src/protocol/micro-step-decomposer.test.ts +104 -39
  77. package/src/protocol-agent.test.ts +17 -7
  78. package/src/protocol-agent.ts +45 -42
  79. package/src/self-improve/absorb-scanner.ts +9 -6
  80. package/src/self-improve/evolution-engine.ts +36 -18
  81. package/src/self-improve/framework-absorber.ts +21 -16
  82. package/src/self-improve/index.ts +2 -10
  83. package/src/self-improve/prompt-optimizer.ts +31 -19
  84. package/src/self-improve/test-generator.ts +16 -12
  85. package/src/skill-router.ts +7 -6
  86. package/src/swarm/messaging/GossipProtocol.ts +1 -1
  87. package/src/swarm/messaging/__tests__/BroadcastChannel.prod.test.ts +31 -9
  88. package/src/swarm/messaging/__tests__/GossipProtocol.prod.test.ts +21 -7
  89. package/src/swarm/messaging/__tests__/SwarmEventBus.prod.test.ts +24 -8
  90. package/src/swarm/messaging/__tests__/SwarmEventBus.test.ts +6 -2
  91. package/src/team.ts +277 -122
  92. package/src/training/scripts/generate-spatial-dataset.ts +1 -1
  93. package/src/training/training/LRScheduler.ts +377 -0
  94. package/src/training/training/QualityScoringPipeline.ts +139 -0
  95. package/src/training/training/SoftDedup.ts +461 -0
  96. package/src/training/training/SparsityMonitor.ts +685 -0
  97. package/src/training/training/SparsityMonitorTypes.ts +209 -0
  98. package/src/training/training/SpatialTrainingDataGenerator.ts +1526 -0
  99. package/src/training/training/SpatialTrainingDataTypes.ts +216 -0
  100. package/src/training/training/TrainingPipelineConfig.ts +215 -0
  101. package/src/training/training/__tests__/CorpusValidation.test.ts +87 -0
  102. package/src/training/training/__tests__/LRScheduler.test.ts +592 -0
  103. package/src/training/training/__tests__/SoftDedup.test.ts +415 -0
  104. package/src/training/training/__tests__/SparsityMonitor.test.ts +1623 -0
  105. package/src/training/training/__tests__/SpatialCorpusValidation.test.ts +72 -0
  106. package/src/training/training/__tests__/SpatialTrainingDataGenerator.test.ts +1244 -0
  107. package/src/training/training/__tests__/TrainingMonkeyIntegration.test.ts +897 -0
  108. package/src/training/training/__tests__/TrainingPipelineConfig.test.ts +202 -0
  109. package/src/training/training/__tests__/schema.test.ts +72 -0
  110. package/src/training/training/__tests__/training-constants.test.ts +106 -0
  111. package/src/training/training/__tests__/trait-mappings.test.ts +81 -0
  112. package/src/training/training/constants.ts +94 -0
  113. package/src/training/training/index.ts +17 -0
  114. package/src/training/training/schema.ts +147 -0
  115. package/src/training/training/scripts/generate-novel-use-cases-dataset.ts +272 -0
  116. package/src/training/training/scripts/generate-spatial-dataset.ts +521 -0
  117. package/src/training/training/trainingmonkey/TrainingMonkeyIntegration.ts +477 -0
  118. package/src/training/training/trainingmonkey/TrainingMonkeyTypes.ts +230 -0
  119. package/src/training/training/trainingmonkey/index.ts +26 -0
  120. package/src/training/training/trait-mappings.ts +157 -0
  121. package/src/types.ts +2 -7
  122. package/ALL-test-results.json +0 -1
  123. package/LICENSE +0 -21
  124. package/dist/AgentManifest-CB4xM-Ma.d.ts +0 -704
  125. package/dist/BehaviorTree-BrBFECv5.d.ts +0 -103
  126. package/dist/InvisibleWallet-rtRrBOA8.d.ts +0 -1732
  127. package/dist/OrchestratorAgent-Q_CbVTmO.d.ts +0 -798
  128. package/dist/agents/index.d.ts +0 -1788
  129. package/dist/agents/index.js +0 -4695
  130. package/dist/ai/index.d.ts +0 -1753
  131. package/dist/ai/index.js +0 -5244
  132. package/dist/behavior.d.ts +0 -130
  133. package/dist/behavior.js +0 -407
  134. package/dist/economy/index.d.ts +0 -747
  135. package/dist/economy/index.js +0 -3617
  136. package/dist/implementations-D9T3un9D.d.ts +0 -236
  137. package/dist/index.d.ts +0 -1729
  138. package/dist/index.js +0 -24277
  139. package/dist/learning/index.d.ts +0 -104
  140. package/dist/learning/index.js +0 -189
  141. package/dist/negotiation/index.d.ts +0 -610
  142. package/dist/negotiation/index.js +0 -931
  143. package/dist/skills/index.d.ts +0 -289
  144. package/dist/skills/index.js +0 -1079
  145. package/dist/swarm/index.d.ts +0 -2433
  146. package/dist/swarm/index.js +0 -5221
  147. package/dist/training/index.d.ts +0 -1734
  148. package/dist/training/index.js +0 -2687
  149. package/extract-failures.js +0 -10
  150. package/src/training/training/data/novel-use-cases.jsonl +0 -153
  151. package/src/training/training/data/spatial-reasoning-10k.jsonl +0 -9354
  152. package/src/types/core-stubs.d.ts +0 -113
  153. package/test-output.txt +0 -0
  154. package/test-result.json +0 -1
  155. package/tsc-errors.txt +0 -4
  156. package/tsc_output.txt +0 -0
  157. package/typescript-errors-2.txt +0 -0
  158. package/typescript-errors.txt +0 -22
  159. package/vitest-log-utf8.txt +0 -268
  160. package/vitest-log.txt +0 -0
@@ -1,1732 +0,0 @@
1
- import { a as ProtocolPhase, P as PhaseResult, b as ProtocolCycleResult } from './implementations-D9T3un9D.js';
2
- import { TraitHandler } from '@holoscript/core';
3
-
4
- /**
5
- * Knowledge Brain — Domain-specific consolidation, excitability, half-lives.
6
- *
7
- * Absorbed from mcp-server/src/holomesh/types.ts (V9/V11 neuroscience model).
8
- * The knowledge store uses these for search ranking, decay, and consolidation.
9
- */
10
- declare const KNOWLEDGE_DOMAINS: readonly ["security", "rendering", "agents", "compilation", "general"];
11
- type KnowledgeDomain = (typeof KNOWLEDGE_DOMAINS)[number];
12
- interface DomainConsolidationConfig {
13
- hotBufferTTL: number;
14
- sleepFrequencyMs: number;
15
- maxEntries: number;
16
- competitionMetric: 'citation_count' | 'query_frequency' | 'peer_corroboration';
17
- downscaleFactor: number;
18
- minCorroborations: number;
19
- }
20
- declare const DOMAIN_CONSOLIDATION: Record<KnowledgeDomain, DomainConsolidationConfig>;
21
- declare const DOMAIN_HALF_LIVES: Record<KnowledgeDomain, number>;
22
- interface HotBufferEntry {
23
- id: string;
24
- domain: KnowledgeDomain;
25
- content: string;
26
- type: string;
27
- authorDid: string;
28
- tags: string[];
29
- ingestedAt: number;
30
- corroborations: string[];
31
- sourcePeerDid: string;
32
- }
33
- interface ExcitabilityMetadata {
34
- queryCount: number;
35
- citationCount: number;
36
- corroborationCount: number;
37
- excitability: number;
38
- lastRetrievedAt: number;
39
- lastReconsolidatedAt: number;
40
- consolidationSurvivals: number;
41
- }
42
- /** Compute excitability score from metadata. */
43
- declare function computeExcitability(meta: Omit<ExcitabilityMetadata, 'excitability'>): number;
44
- /** Apply domain half-life decay to a score. */
45
- declare function applyHalfLifeDecay(score: number, ageMs: number, domain: KnowledgeDomain): number;
46
- interface ConsolidationResult {
47
- domain: KnowledgeDomain;
48
- promoted: number;
49
- merged: number;
50
- evicted: number;
51
- dropped: number;
52
- downscaleFactor: number;
53
- consolidatedAt: number;
54
- }
55
- interface ReconsolidationEvent {
56
- entryId: string;
57
- domain: KnowledgeDomain;
58
- retrievedAt: number;
59
- excitabilityDelta: number;
60
- windowOpen: boolean;
61
- windowClosesAt: number;
62
- }
63
- /** Default reconsolidation window duration (5 minutes). */
64
- declare const RECONSOLIDATION_WINDOW_MS: number;
65
- /** Create a reconsolidation event when an entry is retrieved. */
66
- declare function triggerReconsolidation(entryId: string, domain: KnowledgeDomain, excitabilityDelta: number): ReconsolidationEvent;
67
-
68
- /**
69
- * Knowledge Marketplace — Buy, sell, and price knowledge entries via x402 micropayments.
70
- *
71
- * Enables agents to monetize their discovered W/P/G entries.
72
- * Integrates with KnowledgeStore for entry lookup and X402Facilitator for settlement.
73
- *
74
- * FW-0.6
75
- */
76
-
77
- type ListingStatus = 'active' | 'sold' | 'delisted';
78
- interface KnowledgeListing {
79
- id: string;
80
- entryId: string;
81
- seller: string;
82
- price: number;
83
- /** Currency: 'USDC' for x402 settlement, 'credits' for in-memory ledger. */
84
- currency: 'USDC' | 'credits';
85
- status: ListingStatus;
86
- createdAt: string;
87
- /** Entry snapshot for buyer preview (type + domain + truncated content). */
88
- preview: {
89
- type: KnowledgeInsight['type'];
90
- domain: string;
91
- snippet: string;
92
- };
93
- }
94
- interface PurchaseResult {
95
- success: boolean;
96
- listingId: string;
97
- entryId?: string;
98
- buyer: string;
99
- price: number;
100
- error?: string;
101
- }
102
- interface ListingResult {
103
- success: boolean;
104
- listingId: string;
105
- error?: string;
106
- }
107
- interface PricingFactors {
108
- /** Base price per type: wisdom > pattern > gotcha. */
109
- typeWeights?: Record<KnowledgeInsight['type'], number>;
110
- /** Multiplier for high-confidence entries (confidence >= 0.8). */
111
- confidenceMultiplier?: number;
112
- /** Multiplier for high-reuse entries (reuseCount >= 5). */
113
- reuseMultiplier?: number;
114
- }
115
- declare class KnowledgeMarketplace {
116
- private listings;
117
- private purchases;
118
- private nextId;
119
- private pricingFactors;
120
- constructor(pricingFactors?: PricingFactors);
121
- /** Estimate the value of a knowledge entry (in USDC). */
122
- priceKnowledge(entry: StoredEntry): number;
123
- /** List a knowledge entry for sale. */
124
- sellKnowledge(entry: StoredEntry, price: number, seller: string, currency?: 'USDC' | 'credits'): ListingResult;
125
- /** Buy a listed knowledge entry. */
126
- buyKnowledge(listingId: string, buyer: string): PurchaseResult;
127
- /** Get a listing by ID. */
128
- getListing(listingId: string): KnowledgeListing | undefined;
129
- /** List all active listings. */
130
- activeListings(): KnowledgeListing[];
131
- /** Get purchase history for a buyer. */
132
- purchaseHistory(buyer: string): PurchaseResult[];
133
- /** Delist an entry (only the seller can delist). */
134
- delist(listingId: string, seller: string): boolean;
135
- /** Total revenue for a seller across all sold listings. */
136
- sellerRevenue(seller: string): number;
137
- /** Total marketplace volume (all completed sales). */
138
- totalVolume(): number;
139
- }
140
-
141
- /**
142
- * Knowledge Store — Local-first with remote federation
143
- *
144
- * Local mode: in-memory Map + optional JSON persistence (default)
145
- * Remote mode: delegates to MCP Orchestrator knowledge/query + knowledge/sync
146
- *
147
- * The store shape aligns with MeshKnowledgeEntry from holomesh/types.ts.
148
- * W/P/G taxonomy follows agent-protocol's PWGEntry format.
149
- */
150
-
151
- interface StoredEntry extends KnowledgeInsight {
152
- id: string;
153
- queryCount: number;
154
- reuseCount: number;
155
- createdAt: string;
156
- authorAgent: string;
157
- taskId?: string;
158
- cycleId?: string;
159
- verifierId?: string;
160
- /** Provenance hash — chain of custody */
161
- provenanceHash?: string;
162
- /** Excitability metadata for brain-aware ranking */
163
- excitability?: ExcitabilityMetadata;
164
- }
165
- /** Result from the vector embedding pipeline. */
166
- interface EmbedResult {
167
- entryId: string;
168
- synced: boolean;
169
- /** Remote entry ID returned by orchestrator (if synced). */
170
- remoteId?: string;
171
- }
172
- /** Options for semantic search. */
173
- interface SemanticSearchOptions {
174
- limit?: number;
175
- type?: 'wisdom' | 'pattern' | 'gotcha';
176
- /** Minimum confidence threshold (0-1). */
177
- minConfidence?: number;
178
- /** When true, merge remote results with local keyword fallback. */
179
- hybridSearch?: boolean;
180
- }
181
- declare class KnowledgeStore {
182
- private entries;
183
- private config;
184
- private nextId;
185
- constructor(config: KnowledgeConfig);
186
- /** Publish a knowledge entry. Deduplicates by normalized content. */
187
- publish(insight: KnowledgeInsight, authorAgent: string, provenance?: {
188
- taskId?: string;
189
- cycleId?: string;
190
- verifierId?: string;
191
- provenanceHash?: string;
192
- }): StoredEntry;
193
- /** Search entries by keyword with excitability + half-life decay ranking. */
194
- search(query: string, limit?: number): StoredEntry[];
195
- /** Search remote knowledge store (MCP Orchestrator). */
196
- searchRemote(query: string, limit?: number): Promise<StoredEntry[]>;
197
- /** Sync local entries to remote knowledge store. */
198
- syncToRemote(): Promise<number>;
199
- /**
200
- * Embed and store a knowledge entry.
201
- *
202
- * 1. Publishes locally (dedup, ID generation).
203
- * 2. Syncs to MCP Orchestrator pgvector endpoint for vector embedding.
204
- *
205
- * The orchestrator generates embeddings server-side and stores them
206
- * in pgvector for semantic similarity search via `/knowledge/query`.
207
- */
208
- embedAndStore(insight: KnowledgeInsight, authorAgent: string, provenance?: {
209
- taskId?: string;
210
- cycleId?: string;
211
- verifierId?: string;
212
- provenanceHash?: string;
213
- }): Promise<EmbedResult>;
214
- /**
215
- * Semantic search via MCP Orchestrator pgvector.
216
- *
217
- * Sends the query to the orchestrator `/knowledge/query` endpoint which
218
- * generates an embedding for the query and performs cosine similarity
219
- * search against stored vectors.
220
- *
221
- * Falls back to local keyword search when remote is unavailable.
222
- * When `hybridSearch` is true, merges remote + local results (deduped by ID).
223
- */
224
- semanticSearch(query: string, options?: SemanticSearchOptions): Promise<StoredEntry[]>;
225
- /** Map a remote API response object to a StoredEntry. */
226
- private mapRemoteEntry;
227
- recent(limit?: number): StoredEntry[];
228
- byType(type: 'wisdom' | 'pattern' | 'gotcha'): StoredEntry[];
229
- byDomain(domain: string): StoredEntry[];
230
- markReused(id: string): void;
231
- get size(): number;
232
- all(): StoredEntry[];
233
- /** Cross-reference new insights against existing knowledge. */
234
- compound(newInsights: KnowledgeInsight[]): number;
235
- private persistIfEnabled;
236
- private loadFromDisk;
237
- /**
238
- * Sleep consolidation: Move dormant hot-buffer entries to cold store.
239
- * Entries with age > 24h and queryCount < threshold are archived.
240
- */
241
- sleep(archivePath?: string): Promise<{
242
- archived: number;
243
- evicted: number;
244
- }>;
245
- /**
246
- * Wake consolidation: Restore archived entries back to hot buffer on query.
247
- * Called by search() when a query hits cold store.
248
- */
249
- wake(archivePath: string, query: string): Promise<StoredEntry[]>;
250
- /**
251
- * Promote: Move a dormant entry back to hot buffer and boost its score.
252
- * Called when an archived entry is cited or reused directly.
253
- */
254
- promote(id: string): boolean;
255
- /**
256
- * Evict: Permanently remove an entry from both hot and cold stores.
257
- * Called during cleanup or when an entry is marked as stale/wrong.
258
- */
259
- evict(id: string, archivePath?: string): boolean;
260
- /**
261
- * Consolidate: Full sleep+wake cycle (once per agent work session).
262
- * Moves stale entries to cold store, restores hot entries on demand.
263
- */
264
- consolidate(archivePath?: string): Promise<{
265
- slept: number;
266
- woke: number;
267
- }>;
268
- private _marketplace?;
269
- /** Get or create the marketplace instance. */
270
- get marketplace(): KnowledgeMarketplace;
271
- /** Price a knowledge entry for sale. */
272
- priceEntry(id: string): number | null;
273
- /** List a knowledge entry for sale on the marketplace. */
274
- listForSale(id: string, seller: string, price?: number, currency?: 'USDC' | 'credits'): ListingResult;
275
- /** Buy a listed knowledge entry. Returns the full StoredEntry on success. */
276
- buyListed(listingId: string, buyer: string): {
277
- purchase: PurchaseResult;
278
- entry?: StoredEntry;
279
- };
280
- /** Get active marketplace listings. */
281
- activeListings(): KnowledgeListing[];
282
- }
283
-
284
- /**
285
- * HoloScript Framework Types
286
- *
287
- * Canonical home for all agent types. No circular dependencies.
288
- */
289
-
290
- type LLMProvider = 'anthropic' | 'openai' | 'xai' | 'openrouter';
291
- interface ModelConfig {
292
- provider: LLMProvider;
293
- model: string;
294
- apiKey?: string;
295
- maxTokens?: number;
296
- temperature?: number;
297
- }
298
- type AgentRole = 'architect' | 'coder' | 'researcher' | 'reviewer';
299
- type SlotRole = 'coder' | 'tester' | 'researcher' | 'reviewer' | 'flex';
300
- interface ClaimFilter {
301
- roles: SlotRole[];
302
- maxPriority: number;
303
- }
304
- interface AgentConfig {
305
- name: string;
306
- role: AgentRole;
307
- model: ModelConfig;
308
- capabilities: string[];
309
- claimFilter: ClaimFilter;
310
- systemPrompt?: string;
311
- knowledgeDomains?: string[];
312
- }
313
- interface TaskDef {
314
- id: string;
315
- title: string;
316
- description: string;
317
- status: 'open' | 'claimed' | 'done' | 'blocked';
318
- priority: number;
319
- role?: SlotRole;
320
- source?: string;
321
- claimedBy?: string;
322
- createdAt: string;
323
- completedAt?: string;
324
- }
325
- interface KnowledgeConfig {
326
- persist: boolean;
327
- path?: string;
328
- /** Remote knowledge store URL (MCP orchestrator) */
329
- remoteUrl?: string;
330
- remoteApiKey?: string;
331
- }
332
- interface KnowledgeInsight {
333
- type: 'wisdom' | 'pattern' | 'gotcha';
334
- content: string;
335
- domain: string;
336
- confidence: number;
337
- source: string;
338
- }
339
- type ConsensusMode = 'simple_majority' | 'unanimous' | 'owner_decides';
340
- interface TeamConfig {
341
- name: string;
342
- agents: AgentConfig[];
343
- knowledge?: KnowledgeConfig;
344
- consensus?: ConsensusMode;
345
- maxSlots?: number;
346
- /** Remote board API — when set, board ops delegate to HoloMesh HTTP API */
347
- boardUrl?: string;
348
- boardApiKey?: string;
349
- /** Local presence tracking configuration (FW-0.3). */
350
- presence?: PresenceConfig;
351
- }
352
- interface AgentRuntime {
353
- name: string;
354
- role: AgentRole;
355
- config: AgentConfig;
356
- tasksCompleted: number;
357
- knowledgePublished: number;
358
- reputationScore: number;
359
- reputationTier: ReputationTier;
360
- }
361
- type ReputationTier = 'newcomer' | 'contributor' | 'expert' | 'authority';
362
- interface CycleResult {
363
- teamName: string;
364
- cycle: number;
365
- agentResults: AgentCycleResult[];
366
- knowledgeProduced: KnowledgeInsight[];
367
- compoundedInsights: number;
368
- durationMs: number;
369
- }
370
- interface AgentCycleResult {
371
- agentName: string;
372
- taskId: string | null;
373
- taskTitle: string | null;
374
- action: 'claimed' | 'completed' | 'skipped' | 'error' | 'synthesized';
375
- summary: string;
376
- knowledge: KnowledgeInsight[];
377
- }
378
- interface ProposalResult<T = unknown> {
379
- proposalId: string;
380
- accepted: boolean;
381
- votesFor: number;
382
- votesAgainst: number;
383
- votesTotal: number;
384
- value: T;
385
- }
386
- type SuggestionStatus = 'open' | 'promoted' | 'dismissed';
387
- interface SuggestionVoteEntry {
388
- agent: string;
389
- vote: 'up' | 'down';
390
- reason?: string;
391
- votedAt: string;
392
- }
393
- interface Suggestion {
394
- id: string;
395
- title: string;
396
- description?: string;
397
- category?: string;
398
- evidence?: string;
399
- proposedBy: string;
400
- status: SuggestionStatus;
401
- votes: SuggestionVoteEntry[];
402
- /** Net score (upvotes minus downvotes) */
403
- score: number;
404
- createdAt: string;
405
- resolvedAt?: string;
406
- /** When upvotes >= this threshold, auto-promote to board task */
407
- autoPromoteThreshold?: number;
408
- /** When downvotes >= this threshold, auto-dismiss */
409
- autoDismissThreshold?: number;
410
- /** If promoted, the resulting task ID */
411
- promotedTaskId?: string;
412
- }
413
- interface SuggestionCreateResult {
414
- suggestion: Suggestion;
415
- }
416
- interface SuggestionVoteResult {
417
- suggestion: Suggestion;
418
- /** Set when a suggestion was auto-promoted via threshold */
419
- promotedTaskId?: string;
420
- }
421
- interface SuggestionListResult {
422
- suggestions: Suggestion[];
423
- }
424
- type TeamMode = 'audit' | 'research' | 'build' | 'review';
425
- interface SetModeResult {
426
- mode: TeamMode;
427
- previousMode?: TeamMode;
428
- }
429
- interface DeriveResult {
430
- tasks: TaskDef[];
431
- }
432
- interface SlotInfo {
433
- agentName: string;
434
- role: SlotRole;
435
- status: string;
436
- lastSeen?: string;
437
- ideType?: string;
438
- }
439
- interface PresenceResult {
440
- slots: SlotInfo[];
441
- }
442
- interface HeartbeatResult {
443
- ok: boolean;
444
- }
445
- type AgentPresenceStatus = 'online' | 'idle' | 'offline';
446
- interface AgentPresence {
447
- name: string;
448
- status: AgentPresenceStatus;
449
- lastSeen: number;
450
- currentTask?: string;
451
- uptime: number;
452
- }
453
- interface PresenceConfig {
454
- /** Milliseconds without heartbeat before agent is marked idle (default 60_000). */
455
- idleTimeoutMs?: number;
456
- /** Milliseconds without heartbeat before agent is marked offline (default 300_000). */
457
- offlineTimeoutMs?: number;
458
- }
459
- type ProtocolStyle = 'uaa2' | 'react' | 'plan-exec' | 'debate' | 'swarm';
460
- type AgentStatus = 'idle' | 'running' | 'paused' | 'cancelled' | 'error';
461
- interface PhaseHook {
462
- before?: (phase: ProtocolPhase, input: unknown) => Promise<unknown> | unknown;
463
- after?: (phase: ProtocolPhase, result: PhaseResult) => Promise<PhaseResult> | PhaseResult;
464
- }
465
- interface ProtocolAgentConfig extends AgentConfig {
466
- /** Protocol style — defaults to 'uaa2' (7-phase cycle). */
467
- protocolStyle?: ProtocolStyle;
468
- /** Phase hooks — called before/after each phase. */
469
- phaseHooks?: PhaseHook;
470
- /** Additional LLM overrides for lightweight phases. */
471
- lightModel?: Partial<ModelConfig>;
472
- /** Team knowledge context injected into phases. */
473
- teamKnowledge?: string;
474
- /** Maximum phase retries on failure. */
475
- maxPhaseRetries?: number;
476
- }
477
- interface ProtocolAgentHandle {
478
- /** Agent name. */
479
- readonly name: string;
480
- /** Agent role. */
481
- readonly role: AgentRole;
482
- /** Current status. */
483
- readonly status: AgentStatus;
484
- /** Phase execution history. */
485
- readonly history: PhaseResult[];
486
- /** Execute a task through the full protocol cycle. */
487
- execute(task: {
488
- title: string;
489
- description: string;
490
- }): Promise<ProtocolCycleResult>;
491
- /** Pause execution after the current phase completes. */
492
- pause(): void;
493
- /** Resume a paused agent. */
494
- resume(): void;
495
- /** Cancel execution. The current phase will finish but no further phases run. */
496
- cancel(): void;
497
- /** Reset status to idle and clear history. */
498
- reset(): void;
499
- }
500
-
501
- /**
502
- * x402 Payment Protocol Facilitator
503
- *
504
- * Implements the x402 protocol (https://www.x402.org/) for HTTP 402 Payment Required
505
- * responses, enabling native internet payments for HoloScript resources.
506
- *
507
- * The x402 protocol flow:
508
- * 1. Client requests a resource (GET /api/premium-scene)
509
- * 2. Server responds with HTTP 402 + PaymentRequired body
510
- * 3. Client signs an EIP-712 authorization (gasless) and retries with X-PAYMENT header
511
- * 4. Facilitator verifies signature + settles on-chain
512
- * 5. Server returns the resource with X-PAYMENT-RESPONSE confirmation
513
- *
514
- * Dual-mode settlement:
515
- * - In-memory ledger for microtransactions < $0.10 (no gas, instant)
516
- * - On-chain x402 settlement for amounts >= $0.10 (USDC on Base or Solana)
517
- *
518
- * Optimistic execution:
519
- * - Proceeds on valid authorization before on-chain confirmation
520
- * - Verifies settlement asynchronously, reverts on failure
521
- *
522
- * @version 1.0.0
523
- * @see https://www.x402.org/
524
- * @see https://docs.x402.org/
525
- */
526
-
527
- /** x402 protocol version */
528
- declare const X402_VERSION = 1;
529
- /** Supported settlement chains */
530
- type SettlementChain = 'base' | 'base-sepolia' | 'solana' | 'solana-devnet';
531
- /** Supported payment schemes per x402 spec */
532
- type PaymentScheme = 'exact';
533
- /** Settlement mode based on transaction amount */
534
- type SettlementMode = 'in_memory' | 'on_chain';
535
- /** USDC contract addresses per chain */
536
- declare const USDC_CONTRACTS: Record<SettlementChain, string>;
537
- /** Threshold for switching from in-memory to on-chain settlement (in USDC base units, 6 decimals) */
538
- declare const MICRO_PAYMENT_THRESHOLD = 100000;
539
- /**
540
- * x402 PaymentRequired response body.
541
- * Returned as HTTP 402 response when payment is needed.
542
- */
543
- interface X402PaymentRequired {
544
- /** Protocol version */
545
- x402Version: number;
546
- /** Accepted payment methods */
547
- accepts: X402PaymentOption[];
548
- /** Human-readable error description */
549
- error: string;
550
- }
551
- /**
552
- * A single payment option within the accepts array.
553
- */
554
- interface X402PaymentOption {
555
- /** Payment model: "exact" (fixed price) */
556
- scheme: PaymentScheme;
557
- /** Blockchain network identifier */
558
- network: SettlementChain;
559
- /** Amount in token base units (string for precision, USDC = 6 decimals) */
560
- maxAmountRequired: string;
561
- /** The resource being paid for */
562
- resource: string;
563
- /** Human-readable description */
564
- description: string;
565
- /** Recipient wallet address */
566
- payTo: string;
567
- /** Token contract address (USDC) */
568
- asset: string;
569
- /** Maximum seconds to complete payment */
570
- maxTimeoutSeconds: number;
571
- }
572
- /**
573
- * EIP-712 signed authorization payload from the client.
574
- * Sent in the X-PAYMENT header (base64-encoded).
575
- */
576
- interface X402PaymentPayload {
577
- /** Protocol version */
578
- x402Version: number;
579
- /** Payment scheme */
580
- scheme: PaymentScheme;
581
- /** Target network */
582
- network: SettlementChain;
583
- /** Signed authorization */
584
- payload: {
585
- /** EIP-712 or Ed25519 signature */
586
- signature: string;
587
- /** Transfer authorization details */
588
- authorization: {
589
- /** Payer address */
590
- from: string;
591
- /** Recipient address */
592
- to: string;
593
- /** Amount in base units */
594
- value: string;
595
- /** Unix timestamp after which authorization is valid */
596
- validAfter: string;
597
- /** Unix timestamp before which authorization is valid */
598
- validBefore: string;
599
- /** Unique nonce to prevent replay */
600
- nonce: string;
601
- };
602
- };
603
- }
604
- /**
605
- * Settlement result after on-chain or in-memory settlement.
606
- */
607
- interface X402SettlementResult {
608
- /** Whether settlement succeeded */
609
- success: boolean;
610
- /** On-chain transaction hash (null for in-memory) */
611
- transaction: string | null;
612
- /** Network where settlement occurred */
613
- network: SettlementChain | 'in_memory';
614
- /** Payer address or ID */
615
- payer: string;
616
- /** Error reason if failed */
617
- errorReason: string | null;
618
- /** Settlement mode used */
619
- mode: SettlementMode;
620
- /** Timestamp of settlement */
621
- settledAt: number;
622
- }
623
- /**
624
- * Verification result from the facilitator.
625
- */
626
- interface X402VerificationResult {
627
- /** Whether the payment authorization is valid */
628
- isValid: boolean;
629
- /** Reason for invalidity */
630
- invalidReason: string | null;
631
- }
632
- /**
633
- * In-memory ledger entry for micro-payments.
634
- */
635
- interface LedgerEntry {
636
- /** Unique transaction ID */
637
- id: string;
638
- /** Payer identifier */
639
- from: string;
640
- /** Recipient identifier */
641
- to: string;
642
- /** Amount in USDC base units (6 decimals) */
643
- amount: number;
644
- /** Resource accessed */
645
- resource: string;
646
- /** Timestamp */
647
- timestamp: number;
648
- /** Whether this has been settled on-chain (batch settlement) */
649
- settled: boolean;
650
- /** On-chain tx hash after batch settlement */
651
- settlementTx: string | null;
652
- }
653
- /**
654
- * Configuration for the x402 facilitator.
655
- */
656
- interface X402FacilitatorConfig {
657
- /** Recipient wallet address for payments */
658
- recipientAddress: string;
659
- /** Primary settlement chain */
660
- chain: SettlementChain;
661
- /** Secondary chain (optional, for multi-chain support) */
662
- secondaryChain?: SettlementChain;
663
- /** Micro-payment threshold in USDC base units (default: 100000 = $0.10) */
664
- microPaymentThreshold?: number;
665
- /** Maximum timeout for payment completion in seconds */
666
- maxTimeoutSeconds?: number;
667
- /** Enable optimistic execution (proceed before on-chain confirmation) */
668
- optimisticExecution?: boolean;
669
- /** Batch settlement interval for in-memory ledger entries (ms) */
670
- batchSettlementIntervalMs?: number;
671
- /** Maximum in-memory ledger entries before forced batch settlement */
672
- maxLedgerEntries?: number;
673
- /** Facilitator service URL for on-chain verification/settlement */
674
- facilitatorUrl?: string;
675
- /** Resource description template */
676
- resourceDescription?: string;
677
- }
678
- /**
679
- * In-memory ledger for tracking micro-payments below the on-chain threshold.
680
- * Entries accumulate and are batch-settled periodically.
681
- *
682
- * Thread-safe via synchronous JS execution model.
683
- */
684
- declare class MicroPaymentLedger {
685
- private entries;
686
- private balances;
687
- private txCounter;
688
- private readonly maxEntries;
689
- constructor(maxEntries?: number);
690
- /**
691
- * Record a micro-payment in the in-memory ledger.
692
- */
693
- record(from: string, to: string, amount: number, resource: string): LedgerEntry;
694
- /**
695
- * Get unsettled entries for batch settlement.
696
- */
697
- getUnsettled(): LedgerEntry[];
698
- /**
699
- * Mark entries as settled after batch on-chain settlement.
700
- */
701
- markSettled(entryIds: string[], txHash: string): void;
702
- /**
703
- * Get the net balance for an address (can be negative = owes).
704
- */
705
- getBalance(address: string): number;
706
- /**
707
- * Get total unsettled volume.
708
- */
709
- getUnsettledVolume(): number;
710
- /**
711
- * Get all entries for a specific payer.
712
- */
713
- getEntriesForPayer(from: string): LedgerEntry[];
714
- /**
715
- * Get ledger statistics.
716
- */
717
- getStats(): {
718
- totalEntries: number;
719
- unsettledEntries: number;
720
- unsettledVolume: number;
721
- uniquePayers: number;
722
- uniqueRecipients: number;
723
- };
724
- /**
725
- * Clear all settled entries (garbage collection).
726
- */
727
- pruneSettled(): number;
728
- /**
729
- * Reset the entire ledger.
730
- */
731
- reset(): void;
732
- }
733
- /**
734
- * x402 Payment Protocol Facilitator
735
- *
736
- * Central coordinator for x402 payment flows in HoloScript. Manages:
737
- * - PaymentRequired response generation for @credit-gated resources
738
- * - Payment verification (signature + authorization validity)
739
- * - Dual-mode settlement (in-memory micro vs on-chain macro)
740
- * - Optimistic execution with async settlement verification
741
- * - Batch settlement of accumulated micro-payments
742
- *
743
- * Security considerations:
744
- * - All signatures are verified before granting access
745
- * - Nonce tracking prevents replay attacks
746
- * - ValidBefore/ValidAfter windowing prevents stale authorizations
747
- * - In-memory ledger has hard caps to prevent memory exhaustion
748
- * - Optimistic execution only for amounts below configurable threshold
749
- */
750
- declare class X402Facilitator {
751
- private config;
752
- private ledger;
753
- private usedNonces;
754
- private pendingSettlements;
755
- private settlementResults;
756
- private batchSettlementTimer;
757
- constructor(config: X402FacilitatorConfig);
758
- /**
759
- * Generate an HTTP 402 PaymentRequired response body.
760
- *
761
- * @param resource - The resource path being requested (e.g., "/api/scene/premium")
762
- * @param amountUSDC - Price in USDC (human-readable, e.g., 0.05 for 5 cents)
763
- * @param description - Human-readable description of what is being paid for
764
- * @returns PaymentRequired response body conforming to x402 spec
765
- */
766
- createPaymentRequired(resource: string, amountUSDC: number, description?: string): X402PaymentRequired;
767
- /**
768
- * Verify an X-PAYMENT header payload.
769
- *
770
- * Checks:
771
- * 1. Protocol version matches
772
- * 2. Nonce has not been used (replay protection)
773
- * 3. Authorization window is valid (validAfter <= now <= validBefore)
774
- * 4. Payment amount matches or exceeds required amount
775
- * 5. Recipient matches configured address
776
- * 6. Network is supported
777
- *
778
- * NOTE: Signature cryptographic verification requires on-chain verification
779
- * via the facilitator service. This method validates the structural/temporal
780
- * aspects. For full verification including signature, use verifyAndSettle().
781
- *
782
- * @param payment - Decoded X-PAYMENT payload
783
- * @param requiredAmount - Minimum amount in USDC base units
784
- * @returns Verification result
785
- */
786
- verifyPayment(payment: X402PaymentPayload, requiredAmount: string): X402VerificationResult;
787
- /**
788
- * Determine the settlement mode based on the payment amount.
789
- *
790
- * @param amountBaseUnits - Amount in USDC base units (6 decimals)
791
- * @returns Settlement mode
792
- */
793
- getSettlementMode(amountBaseUnits: number): SettlementMode;
794
- /**
795
- * Process a payment with dual-mode settlement.
796
- *
797
- * For micro-payments (< threshold):
798
- * - Records in in-memory ledger immediately
799
- * - Returns instant success
800
- * - Batch settles periodically
801
- *
802
- * For macro-payments (>= threshold):
803
- * - If optimistic execution enabled: grants access immediately, settles async
804
- * - If not: waits for settlement before granting access
805
- *
806
- * @param payment - Decoded X-PAYMENT payload
807
- * @param resource - Resource being accessed
808
- * @param requiredAmount - Required amount in USDC base units
809
- * @returns Settlement result
810
- */
811
- processPayment(payment: X402PaymentPayload, resource: string, requiredAmount: string): Promise<X402SettlementResult>;
812
- /**
813
- * Settle a micro-payment in the in-memory ledger.
814
- */
815
- private settleMicroPayment;
816
- /**
817
- * Settle a payment on-chain via the facilitator service.
818
- *
819
- * In optimistic mode: returns success immediately, verifies async.
820
- * In non-optimistic mode: waits for facilitator confirmation.
821
- */
822
- private settleOnChain;
823
- /**
824
- * Verify settlement asynchronously (for optimistic execution).
825
- * Calls the facilitator service to verify and execute the on-chain transfer.
826
- */
827
- private verifySettlementAsync;
828
- /**
829
- * Verify settlement synchronously (blocking).
830
- */
831
- private verifySettlementSync;
832
- /**
833
- * Call the x402 facilitator service for on-chain settlement.
834
- *
835
- * The facilitator:
836
- * 1. Validates the EIP-712/Ed25519 signature cryptographically
837
- * 2. Submits the `transferWithAuthorization` transaction on-chain
838
- * 3. Returns the transaction hash and confirmation
839
- */
840
- private callFacilitator;
841
- /**
842
- * Start automatic batch settlement of in-memory ledger entries.
843
- */
844
- startBatchSettlement(): void;
845
- /**
846
- * Stop automatic batch settlement.
847
- */
848
- stopBatchSettlement(): void;
849
- /**
850
- * Run a single batch settlement cycle.
851
- * Aggregates unsettled micro-payments by payer and submits on-chain.
852
- */
853
- runBatchSettlement(): Promise<{
854
- settled: number;
855
- failed: number;
856
- totalVolume: number;
857
- }>;
858
- /**
859
- * Decode a base64-encoded X-PAYMENT header into a payment payload.
860
- */
861
- static decodeXPaymentHeader(header: string): X402PaymentPayload | null;
862
- /**
863
- * Encode a payment payload into a base64 string for the X-PAYMENT header.
864
- */
865
- static encodeXPaymentHeader(payload: X402PaymentPayload): string;
866
- /**
867
- * Create an X-PAYMENT-RESPONSE header value from a settlement result.
868
- */
869
- static createPaymentResponseHeader(result: X402SettlementResult): string;
870
- /**
871
- * Check the settlement status of a pending optimistic execution.
872
- */
873
- getSettlementStatus(nonce: string): X402SettlementResult | 'pending' | 'unknown';
874
- /**
875
- * Get the in-memory ledger instance.
876
- */
877
- getLedger(): MicroPaymentLedger;
878
- /**
879
- * Get facilitator statistics.
880
- */
881
- getStats(): {
882
- usedNonces: number;
883
- pendingSettlements: number;
884
- completedSettlements: number;
885
- ledger: ReturnType<MicroPaymentLedger['getStats']>;
886
- };
887
- /**
888
- * Clean up resources.
889
- */
890
- dispose(): void;
891
- }
892
- /**
893
- * Configuration for the @credit trait.
894
- * Attach to any HoloScript object to gate it behind x402 payment.
895
- */
896
- interface CreditTraitConfig {
897
- /** Price in USDC (human-readable, e.g., 0.05 = 5 cents) */
898
- price: number;
899
- /** Settlement chain */
900
- chain: SettlementChain;
901
- /** Recipient address */
902
- recipient: string;
903
- /** Human-readable resource description */
904
- description: string;
905
- /** Maximum seconds for payment timeout */
906
- timeout: number;
907
- /** Secondary chain for multi-chain support */
908
- secondary_chain?: SettlementChain;
909
- /** Enable optimistic execution */
910
- optimistic: boolean;
911
- /** Micro-payment threshold override (USDC, human-readable) */
912
- micro_threshold?: number;
913
- }
914
- /**
915
- * @credit Trait Handler
916
- *
917
- * When attached to a HoloScript object, this trait gates access behind
918
- * x402 payment. The trait:
919
- *
920
- * 1. On access attempt: emits 'credit:payment_required' with the 402 response body
921
- * 2. On payment received: verifies via facilitator and emits 'credit:access_granted'
922
- * 3. On payment failure: emits 'credit:access_denied'
923
- *
924
- * Events emitted:
925
- * credit:initialized { config }
926
- * credit:payment_required { resource, paymentRequired: X402PaymentRequired }
927
- * credit:access_granted { payer, amount, mode, resource }
928
- * credit:access_denied { payer, reason, resource }
929
- * credit:settlement_status { nonce, status }
930
- * credit:batch_settled { settled, failed, totalVolume }
931
- * credit:stats { totalRevenue, totalRequests, totalGranted, totalDenied }
932
- *
933
- * @example HoloScript usage:
934
- * ```holoscript
935
- * object "premium_scene" {
936
- * @credit(price: 0.05, chain: "base", recipient: "0x...", description: "Premium VR scene")
937
- * geometry: "sphere"
938
- * color: "#gold"
939
- * }
940
- * ```
941
- */
942
- declare const creditTraitHandler: TraitHandler<CreditTraitConfig>;
943
-
944
- /** EVM chain IDs for supported settlement networks */
945
- declare const CHAIN_IDS: Record<string, number>;
946
- /** Reverse lookup: chain ID -> settlement chain name */
947
- declare const CHAIN_ID_TO_NETWORK: Record<number, SettlementChain>;
948
- /**
949
- * Settlement audit event types emitted by PaymentGateway.
950
- */
951
- type SettlementEventType = 'payment:authorization_created' | 'payment:verification_started' | 'payment:verification_passed' | 'payment:verification_failed' | 'payment:settlement_started' | 'payment:settlement_completed' | 'payment:settlement_failed' | 'payment:refund_initiated' | 'payment:refund_completed' | 'payment:refund_failed' | 'payment:batch_settlement_started' | 'payment:batch_settlement_completed';
952
- /**
953
- * Settlement audit event payload.
954
- */
955
- interface SettlementEvent {
956
- /** Event type */
957
- type: SettlementEventType;
958
- /** ISO 8601 timestamp */
959
- timestamp: string;
960
- /** Unique event ID */
961
- eventId: string;
962
- /** Associated payment nonce (if applicable) */
963
- nonce: string | null;
964
- /** Payer address */
965
- payer: string | null;
966
- /** Recipient address */
967
- recipient: string | null;
968
- /** Amount in USDC base units */
969
- amount: string | null;
970
- /** Settlement chain */
971
- network: SettlementChain | 'in_memory' | null;
972
- /** Transaction hash (if on-chain) */
973
- transaction: string | null;
974
- /** Additional metadata */
975
- metadata: Record<string, unknown>;
976
- }
977
- /** Event listener type for the PaymentGateway audit trail */
978
- type SettlementEventListener = (event: SettlementEvent) => void;
979
- /**
980
- * Refund request for reversing a completed payment.
981
- */
982
- interface RefundRequest {
983
- /** Original payment nonce to refund */
984
- originalNonce: string;
985
- /** Reason for the refund */
986
- reason: string;
987
- /** Partial refund amount in USDC base units (null = full refund) */
988
- partialAmount: string | null;
989
- }
990
- /**
991
- * Result of a refund operation.
992
- */
993
- interface RefundResult {
994
- /** Whether the refund was processed */
995
- success: boolean;
996
- /** Refund ID for tracking */
997
- refundId: string;
998
- /** Amount refunded in USDC base units */
999
- amountRefunded: string;
1000
- /** Original payment nonce */
1001
- originalNonce: string;
1002
- /** Transaction hash (for on-chain refunds) */
1003
- transaction: string | null;
1004
- /** Mode of the original settlement */
1005
- originalMode: SettlementMode;
1006
- /** Reason for the refund */
1007
- reason: string;
1008
- /** Error reason if failed */
1009
- errorReason: string | null;
1010
- /** Timestamp of refund */
1011
- refundedAt: number;
1012
- }
1013
- /**
1014
- * PaymentGateway -- High-Level x402 Payment API
1015
- *
1016
- * Provides a unified, agent-friendly interface for the x402 payment protocol.
1017
- * Composes over X402Facilitator to add:
1018
- *
1019
- * - `createPaymentAuthorization()` -- Generate 402 Payment Required responses
1020
- * - `verifyPayment()` -- Validate X-PAYMENT headers
1021
- * - `settlePayment()` -- Process and settle payments (micro or on-chain)
1022
- * - `refundPayment()` -- Reverse completed transactions
1023
- * - Settlement event emitter for audit trail
1024
- * - Chain ID constants for Base L2 (8453)
1025
- *
1026
- * Settlement flow:
1027
- * 1. Agent calls resource -> gateway returns 402 with payment requirements
1028
- * 2. Agent signs EIP-712 authorization -> sends X-PAYMENT header
1029
- * 3. Gateway verifies signature validity and temporal window
1030
- * 4. Gateway settles payment (in-memory for micro, on-chain for macro)
1031
- * 5. Gateway emits audit events at each step
1032
- *
1033
- * @example
1034
- * ```typescript
1035
- * const gateway = new PaymentGateway({
1036
- * recipientAddress: '0x...',
1037
- * chain: 'base',
1038
- * });
1039
- *
1040
- * // Listen for audit events
1041
- * gateway.on('payment:settlement_completed', (event) => {
1042
- * console.log(`Payment settled: ${event.transaction}`);
1043
- * });
1044
- *
1045
- * // Step 1: Generate 402 response
1046
- * const auth = gateway.createPaymentAuthorization('/api/premium-scene', 0.05);
1047
- *
1048
- * // Step 2: Verify incoming payment
1049
- * const verification = gateway.verifyPayment(xPaymentHeader, '50000');
1050
- *
1051
- * // Step 3: Settle
1052
- * const settlement = await gateway.settlePayment(paymentPayload, '/api/premium-scene', '50000');
1053
- *
1054
- * // Step 4: Refund if needed
1055
- * const refund = await gateway.refundPayment({
1056
- * originalNonce: 'nonce_123',
1057
- * reason: 'Content unavailable',
1058
- * partialAmount: null,
1059
- * });
1060
- * ```
1061
- */
1062
- declare class PaymentGateway {
1063
- private facilitator;
1064
- private listeners;
1065
- private refundLedger;
1066
- private eventCounter;
1067
- private readonly config;
1068
- constructor(config: X402FacilitatorConfig);
1069
- /**
1070
- * Subscribe to settlement audit events.
1071
- * Use '*' to receive all events.
1072
- *
1073
- * @param eventType - Event type to listen for, or '*' for all
1074
- * @param listener - Callback function
1075
- * @returns Unsubscribe function
1076
- */
1077
- on(eventType: SettlementEventType | '*', listener: SettlementEventListener): () => void;
1078
- /**
1079
- * Remove a specific listener.
1080
- */
1081
- off(eventType: SettlementEventType | '*', listener: SettlementEventListener): void;
1082
- /**
1083
- * Emit a settlement audit event.
1084
- */
1085
- private emit;
1086
- /**
1087
- * Create a payment authorization (HTTP 402 response body).
1088
- *
1089
- * This is step 1 of the x402 flow: the server tells the agent what payment
1090
- * is required to access the resource.
1091
- *
1092
- * @param resource - Resource path being gated (e.g., "/api/premium-scene")
1093
- * @param amountUSDC - Price in USDC (human-readable, e.g., 0.05 for 5 cents)
1094
- * @param description - Human-readable description
1095
- * @returns x402 PaymentRequired response body
1096
- */
1097
- createPaymentAuthorization(resource: string, amountUSDC: number, description?: string): X402PaymentRequired & {
1098
- chainId: number;
1099
- };
1100
- /**
1101
- * Verify an X-PAYMENT header.
1102
- *
1103
- * Accepts either a raw base64 string (from HTTP header) or a decoded payload.
1104
- * Validates protocol version, nonce, temporal window, amount, and recipient.
1105
- *
1106
- * @param payment - Base64-encoded X-PAYMENT header string or decoded payload
1107
- * @param requiredAmount - Required amount in USDC base units (string for precision)
1108
- * @returns Verification result
1109
- */
1110
- verifyPayment(payment: string | X402PaymentPayload, requiredAmount: string): X402VerificationResult & {
1111
- decodedPayload: X402PaymentPayload | null;
1112
- };
1113
- /**
1114
- * Settle a verified payment.
1115
- *
1116
- * Routes to in-memory micro-payment ledger or on-chain settlement
1117
- * depending on the amount. Emits audit events at each stage.
1118
- *
1119
- * @param payment - Decoded X-PAYMENT payload (or base64 string)
1120
- * @param resource - Resource being accessed
1121
- * @param requiredAmount - Required amount in USDC base units
1122
- * @returns Settlement result
1123
- */
1124
- settlePayment(payment: string | X402PaymentPayload, resource: string, requiredAmount: string): Promise<X402SettlementResult>;
1125
- /**
1126
- * Refund a completed payment.
1127
- *
1128
- * For in-memory micro-payments: records a reverse entry in the ledger.
1129
- * For on-chain payments: calls the facilitator service to initiate refund.
1130
- *
1131
- * @param request - Refund request details
1132
- * @returns Refund result
1133
- */
1134
- refundPayment(request: RefundRequest): Promise<RefundResult>;
1135
- /**
1136
- * Run a batch settlement of accumulated micro-payments.
1137
- */
1138
- runBatchSettlement(): Promise<{
1139
- settled: number;
1140
- failed: number;
1141
- totalVolume: number;
1142
- }>;
1143
- /**
1144
- * Get the underlying facilitator instance.
1145
- */
1146
- getFacilitator(): X402Facilitator;
1147
- /**
1148
- * Get chain ID for the configured settlement chain.
1149
- */
1150
- getChainId(): number;
1151
- /**
1152
- * Get the USDC contract address for the configured chain.
1153
- */
1154
- getUSDCContract(): string;
1155
- /**
1156
- * Look up a refund result by refund ID.
1157
- */
1158
- getRefund(refundId: string): RefundResult | undefined;
1159
- /**
1160
- * Get all refund results.
1161
- */
1162
- getAllRefunds(): RefundResult[];
1163
- /**
1164
- * Get comprehensive gateway statistics.
1165
- */
1166
- getStats(): {
1167
- facilitator: ReturnType<X402Facilitator['getStats']>;
1168
- chainId: number;
1169
- usdcContract: string;
1170
- totalRefunds: number;
1171
- listenerCount: number;
1172
- };
1173
- /**
1174
- * Clean up all resources.
1175
- */
1176
- dispose(): void;
1177
- }
1178
-
1179
- /**
1180
- * Bounty Manager — Task-based incentive system for agent teams.
1181
- *
1182
- * Creates, claims, and settles bounties tied to board tasks.
1183
- * Integrates with X402Facilitator for on-chain or in-memory payouts.
1184
- *
1185
- * FW-0.6
1186
- */
1187
-
1188
- type BountyCurrency = 'USDC' | 'credits';
1189
- type BountyStatus = 'open' | 'claimed' | 'completed' | 'expired' | 'disputed';
1190
- interface BountyReward {
1191
- amount: number;
1192
- currency: BountyCurrency;
1193
- }
1194
- interface Bounty {
1195
- id: string;
1196
- taskId: string;
1197
- reward: BountyReward;
1198
- status: BountyStatus;
1199
- createdBy: string;
1200
- claimedBy?: string;
1201
- completedAt?: string;
1202
- deadline?: number;
1203
- createdAt: string;
1204
- }
1205
- interface ClaimResult {
1206
- success: boolean;
1207
- bountyId: string;
1208
- error?: string;
1209
- }
1210
- interface CompletionProof {
1211
- commitHash?: string;
1212
- summary: string;
1213
- /** Arbitrary evidence (test output, URLs, etc.) */
1214
- evidence?: string[];
1215
- }
1216
- interface PayoutResult {
1217
- success: boolean;
1218
- bountyId: string;
1219
- amount: number;
1220
- currency: BountyCurrency;
1221
- /** Settlement method used (ledger for credits/micro, on-chain for larger USDC) */
1222
- settlement: 'ledger' | 'on_chain';
1223
- error?: string;
1224
- }
1225
- interface BountyManagerConfig {
1226
- /** Optional X402Facilitator for USDC payouts. Without it, only credits work. */
1227
- facilitator?: X402Facilitator;
1228
- /** Optional MicroPaymentLedger for credit-based or micro USDC payouts. */
1229
- ledger?: MicroPaymentLedger;
1230
- /** Default deadline in ms from creation (default: 7 days). */
1231
- defaultDeadlineMs?: number;
1232
- }
1233
- declare class BountyManager {
1234
- private bounties;
1235
- private nextId;
1236
- private config;
1237
- constructor(config?: BountyManagerConfig);
1238
- /** Create a bounty for a board task. */
1239
- createBounty(taskId: string, reward: BountyReward, createdBy: string, deadline?: number): Bounty;
1240
- /** Claim an open bounty. */
1241
- claimBounty(bountyId: string, agentId: string): ClaimResult;
1242
- /** Complete a bounty with proof of work and trigger payout. */
1243
- completeBounty(bountyId: string, proof: CompletionProof): PayoutResult;
1244
- /** Get a bounty by ID. */
1245
- getBounty(bountyId: string): Bounty | undefined;
1246
- /** List bounties, optionally filtered by status. */
1247
- list(status?: BountyStatus): Bounty[];
1248
- /** List bounties for a specific task. */
1249
- byTask(taskId: string): Bounty[];
1250
- /** Expire bounties past their deadline. Returns count expired. */
1251
- expireStale(): number;
1252
- /** Total open bounty value in a given currency. */
1253
- totalOpen(currency?: BountyCurrency): number;
1254
- }
1255
-
1256
- /**
1257
- * Type stubs for @holoscript/core types used by economy module.
1258
- * Copied from core to avoid cross-package DTS resolution failures.
1259
- * The real types come from @holoscript/core at runtime.
1260
- *
1261
- * Source: packages/core/src/compiler/safety/ResourceBudgetAnalyzer.ts
1262
- * Source: packages/core/src/debug/TelemetryCollector.ts
1263
- */
1264
- interface TelemetryCollector {
1265
- record(event: Record<string, unknown>): unknown;
1266
- recordEvent(type: string, agentId: string, data?: Record<string, unknown>, severity?: string): unknown;
1267
- recordError(agentId: string, error: Error, context?: Record<string, unknown>): unknown;
1268
- startSpan(name: string, options?: Record<string, unknown>): unknown;
1269
- endSpan(spanId: string, status?: string, statusMessage?: string): unknown;
1270
- flush(): Promise<void>;
1271
- getStats(): Record<string, unknown>;
1272
- setEnabled(enabled: boolean): void;
1273
- configure(config: Record<string, unknown>): void;
1274
- clear(): void;
1275
- destroy(): void;
1276
- }
1277
- /** Resource categories tracked by the budget analyzer */
1278
- type ResourceCategory = 'particles' | 'physicsBodies' | 'audioSources' | 'meshInstances' | 'gaussians' | 'shaderPasses' | 'networkMsgs' | 'agentCount' | 'memoryMB' | 'gpuDrawCalls';
1279
- /** A resource usage entry from the AST (exact shape from core) */
1280
- interface ResourceUsageNode {
1281
- name: string;
1282
- traits: string[];
1283
- calls: string[];
1284
- count: number;
1285
- traitConfigs?: Record<string, Record<string, number>>;
1286
- }
1287
-
1288
- /**
1289
- * CreatorRevenueAggregator — Earnings tracking and revenue sharing
1290
- *
1291
- * Tracks earnings by creator, plugin, and time period from LedgerEntry records.
1292
- * Calculates revenue shares and maintains payout history.
1293
- *
1294
- * Part of HoloScript v5.8 "Live Economy".
1295
- *
1296
- * @version 1.0.0
1297
- */
1298
-
1299
- /**
1300
- * A revenue event from a tool call or resource access.
1301
- */
1302
- interface RevenueEvent {
1303
- /** Unique event ID */
1304
- id: string;
1305
- /** Creator who earned revenue */
1306
- creatorId: string;
1307
- /** Plugin or tool that generated the revenue */
1308
- pluginId: string;
1309
- /** Gross amount in USDC base units (6 decimals) */
1310
- grossAmount: number;
1311
- /** Platform fee in USDC base units */
1312
- platformFee: number;
1313
- /** Net amount (grossAmount - platformFee) */
1314
- netAmount: number;
1315
- /** Timestamp (ms since epoch) */
1316
- timestamp: number;
1317
- /** Payer (agent or user) */
1318
- payerId: string;
1319
- /** Related ledger entry ID */
1320
- ledgerEntryId?: string;
1321
- }
1322
- /**
1323
- * Aggregated earnings for a creator.
1324
- */
1325
- interface CreatorEarnings {
1326
- /** Creator ID */
1327
- creatorId: string;
1328
- /** Total gross revenue (USDC base units) */
1329
- totalGross: number;
1330
- /** Total platform fees (USDC base units) */
1331
- totalFees: number;
1332
- /** Total net revenue (USDC base units) */
1333
- totalNet: number;
1334
- /** Revenue by plugin */
1335
- byPlugin: Map<string, PluginRevenue>;
1336
- /** Number of revenue events */
1337
- eventCount: number;
1338
- /** Period start (ISO 8601) */
1339
- periodStart: string;
1340
- /** Period end (ISO 8601) */
1341
- periodEnd: string;
1342
- }
1343
- /**
1344
- * Revenue breakdown for a specific plugin.
1345
- */
1346
- interface PluginRevenue {
1347
- /** Plugin ID */
1348
- pluginId: string;
1349
- /** Gross revenue */
1350
- grossAmount: number;
1351
- /** Platform fee */
1352
- platformFee: number;
1353
- /** Net revenue */
1354
- netAmount: number;
1355
- /** Number of revenue events */
1356
- eventCount: number;
1357
- /** Unique payers */
1358
- uniquePayers: Set<string>;
1359
- }
1360
- /**
1361
- * Payout record.
1362
- */
1363
- interface PayoutRecord {
1364
- /** Payout ID */
1365
- id: string;
1366
- /** Creator ID */
1367
- creatorId: string;
1368
- /** Amount paid out (USDC base units) */
1369
- amount: number;
1370
- /** Payout method */
1371
- method: 'usdc_transfer' | 'batch_settlement' | 'manual';
1372
- /** Transaction hash (if on-chain) */
1373
- transactionHash?: string;
1374
- /** Payout timestamp (ISO 8601) */
1375
- paidAt: string;
1376
- /** Status */
1377
- status: 'pending' | 'completed' | 'failed';
1378
- /** Period this payout covers */
1379
- periodStart: string;
1380
- periodEnd: string;
1381
- }
1382
- /**
1383
- * Revenue aggregation period.
1384
- */
1385
- type RevenuePeriod = 'daily' | 'weekly' | 'monthly' | 'all-time';
1386
- /**
1387
- * Revenue aggregator configuration.
1388
- */
1389
- interface RevenueAggregatorConfig {
1390
- /** Platform fee rate (0-1, e.g. 0.15 = 15%) */
1391
- platformFeeRate?: number;
1392
- /** Minimum payout threshold (USDC base units, default: 5_000_000 = $5.00) */
1393
- minPayoutThreshold?: number;
1394
- /** Maximum events to retain per creator */
1395
- maxEventsPerCreator?: number;
1396
- /** Telemetry collector */
1397
- telemetry?: TelemetryCollector;
1398
- }
1399
- declare class CreatorRevenueAggregator {
1400
- private config;
1401
- private events;
1402
- private payouts;
1403
- private eventCounter;
1404
- constructor(config?: RevenueAggregatorConfig);
1405
- /**
1406
- * Record a revenue event.
1407
- */
1408
- recordRevenue(creatorId: string, pluginId: string, grossAmount: number, payerId: string, ledgerEntryId?: string): RevenueEvent;
1409
- /**
1410
- * Get earnings for a specific creator.
1411
- */
1412
- getCreatorEarnings(creatorId: string, period?: RevenuePeriod): CreatorEarnings;
1413
- /**
1414
- * Get top creators by revenue.
1415
- */
1416
- getTopCreators(period?: RevenuePeriod, limit?: number): Array<{
1417
- creatorId: string;
1418
- totalNet: number;
1419
- eventCount: number;
1420
- }>;
1421
- /**
1422
- * Get platform revenue (total fees collected).
1423
- */
1424
- getPlatformRevenue(period?: RevenuePeriod): {
1425
- totalFees: number;
1426
- totalGross: number;
1427
- creatorCount: number;
1428
- };
1429
- /**
1430
- * Get creators eligible for payout (net earnings >= threshold).
1431
- */
1432
- getPayoutEligible(period?: RevenuePeriod): Array<{
1433
- creatorId: string;
1434
- amount: number;
1435
- }>;
1436
- /**
1437
- * Record a payout to a creator.
1438
- */
1439
- recordPayout(creatorId: string, amount: number, method: PayoutRecord['method'], transactionHash?: string): PayoutRecord;
1440
- /**
1441
- * Update payout status.
1442
- */
1443
- updatePayoutStatus(payoutId: string, status: PayoutRecord['status'], transactionHash?: string): boolean;
1444
- /**
1445
- * Get payouts for a creator.
1446
- */
1447
- getCreatorPayouts(creatorId: string, period?: RevenuePeriod): PayoutRecord[];
1448
- /**
1449
- * Get all payouts.
1450
- */
1451
- getAllPayouts(): PayoutRecord[];
1452
- /**
1453
- * Get all tracked creator IDs.
1454
- */
1455
- getCreatorIds(): string[];
1456
- /**
1457
- * Get platform fee rate.
1458
- */
1459
- getPlatformFeeRate(): number;
1460
- /**
1461
- * Set platform fee rate.
1462
- */
1463
- setPlatformFeeRate(rate: number): void;
1464
- private getPeriodBounds;
1465
- private emitTelemetry;
1466
- }
1467
-
1468
- /**
1469
- * PaymentWebhookService — Webhook processing for payment confirmations
1470
- *
1471
- * Receives payment provider webhooks, verifies HMAC-SHA256 signatures,
1472
- * updates LedgerEntry settlement status, and emits telemetry events.
1473
- *
1474
- * Part of HoloScript v5.8 "Live Economy".
1475
- *
1476
- * @version 1.0.0
1477
- */
1478
-
1479
- /**
1480
- * Supported webhook providers.
1481
- */
1482
- type WebhookProvider = 'x402' | 'stripe' | 'coinbase' | 'custom';
1483
- /**
1484
- * Webhook event types.
1485
- */
1486
- type WebhookEventType = 'payment.confirmed' | 'payment.failed' | 'payment.refunded' | 'settlement.completed' | 'settlement.failed' | 'subscription.renewed' | 'subscription.cancelled';
1487
- /**
1488
- * Incoming webhook payload.
1489
- */
1490
- interface WebhookPayload {
1491
- /** Provider-specific event ID */
1492
- eventId: string;
1493
- /** Event type */
1494
- type: WebhookEventType;
1495
- /** Provider name */
1496
- provider: WebhookProvider;
1497
- /** Timestamp of the event (ISO 8601) */
1498
- timestamp: string;
1499
- /** Provider-specific data */
1500
- data: Record<string, unknown>;
1501
- /** Ledger entry ID (if applicable) */
1502
- ledgerEntryId?: string;
1503
- /** Transaction hash (if on-chain) */
1504
- transactionHash?: string;
1505
- /** Amount in USDC base units */
1506
- amount?: number;
1507
- /** Payer identifier */
1508
- payer?: string;
1509
- /** Recipient identifier */
1510
- recipient?: string;
1511
- }
1512
- /**
1513
- * Webhook verification result.
1514
- */
1515
- interface WebhookVerificationResult {
1516
- /** Whether the webhook signature is valid */
1517
- verified: boolean;
1518
- /** Provider name */
1519
- provider: WebhookProvider;
1520
- /** Error message if verification failed */
1521
- error?: string;
1522
- /** Parsed payload (if verified) */
1523
- payload?: WebhookPayload;
1524
- }
1525
- /**
1526
- * Webhook processing result.
1527
- */
1528
- interface WebhookProcessingResult {
1529
- /** Whether processing succeeded */
1530
- success: boolean;
1531
- /** Event ID that was processed */
1532
- eventId: string;
1533
- /** Event type */
1534
- type: WebhookEventType;
1535
- /** Updated ledger entry (if applicable) */
1536
- updatedEntry?: LedgerEntry;
1537
- /** Error message if processing failed */
1538
- error?: string;
1539
- }
1540
- /**
1541
- * Webhook handler function type.
1542
- */
1543
- type WebhookHandler = (payload: WebhookPayload) => Promise<WebhookProcessingResult> | WebhookProcessingResult;
1544
- /**
1545
- * Configuration for the webhook service.
1546
- */
1547
- interface WebhookServiceConfig {
1548
- /** HMAC secrets per provider */
1549
- secrets: Partial<Record<WebhookProvider, string>>;
1550
- /** Maximum age for webhook events (ms, default: 5 minutes) */
1551
- maxAgeMs?: number;
1552
- /** Maximum retry attempts for failed deliveries */
1553
- maxRetries?: number;
1554
- /** Retry backoff base (ms) */
1555
- retryBackoffMs?: number;
1556
- /** Telemetry collector */
1557
- telemetry?: TelemetryCollector;
1558
- }
1559
- declare class PaymentWebhookService {
1560
- private config;
1561
- private handlers;
1562
- private processedEvents;
1563
- private retryQueue;
1564
- private ledgerUpdateCallback?;
1565
- private stats;
1566
- constructor(config: WebhookServiceConfig);
1567
- /**
1568
- * Verify a webhook's HMAC-SHA256 signature.
1569
- */
1570
- verifySignature(rawBody: string, signature: string, provider: WebhookProvider): WebhookVerificationResult;
1571
- /**
1572
- * Process a verified webhook payload.
1573
- */
1574
- processWebhook(payload: WebhookPayload): Promise<WebhookProcessingResult>;
1575
- /**
1576
- * Register a handler for a specific webhook event type.
1577
- */
1578
- on(eventType: WebhookEventType, handler: WebhookHandler): void;
1579
- /**
1580
- * Remove a handler for a specific webhook event type.
1581
- */
1582
- off(eventType: WebhookEventType, handler: WebhookHandler): void;
1583
- /**
1584
- * Set callback for ledger entry updates.
1585
- */
1586
- onLedgerUpdate(callback: (entryId: string, updates: Partial<LedgerEntry>) => void): void;
1587
- /**
1588
- * Add a failed webhook to the retry queue.
1589
- */
1590
- private addToRetryQueue;
1591
- /**
1592
- * Process retry queue entries that are ready.
1593
- */
1594
- processRetryQueue(): Promise<number>;
1595
- /**
1596
- * Get retry queue length.
1597
- */
1598
- getRetryQueueLength(): number;
1599
- /**
1600
- * Check if an event has been processed.
1601
- */
1602
- isProcessed(eventId: string): boolean;
1603
- /**
1604
- * Get comprehensive stats.
1605
- */
1606
- getStats(): typeof this.stats & {
1607
- retryQueueLength: number;
1608
- };
1609
- /**
1610
- * Create a webhook signature for testing purposes.
1611
- */
1612
- createSignature(rawBody: string, provider: WebhookProvider): string;
1613
- private emitTelemetry;
1614
- }
1615
-
1616
- /**
1617
- * RevenueSplitter — Deterministic revenue splitting using bigint arithmetic.
1618
- *
1619
- * Splits revenue among multiple recipients with exact-sum invariant:
1620
- * sum(shares) === total (no rounding leakage).
1621
- *
1622
- * Moved from core into framework as part of FW-0.6.
1623
- *
1624
- * @module economy/RevenueSplitter
1625
- */
1626
- interface SplitRecipient {
1627
- /** Unique recipient ID (agent, creator, platform) */
1628
- id: string;
1629
- /** Basis points (1/10000) — e.g., 5000 = 50% */
1630
- basisPoints: number;
1631
- }
1632
- interface SplitResult {
1633
- /** Individual shares keyed by recipient ID */
1634
- shares: Map<string, bigint>;
1635
- /** Total input amount */
1636
- total: bigint;
1637
- /** Any dust (remainder) allocated to the first recipient */
1638
- dust: bigint;
1639
- /** Human-readable breakdown */
1640
- breakdown: SplitBreakdownEntry[];
1641
- }
1642
- interface SplitBreakdownEntry {
1643
- recipientId: string;
1644
- basisPoints: number;
1645
- amount: bigint;
1646
- percentage: string;
1647
- }
1648
- declare class RevenueSplitter {
1649
- private recipients;
1650
- /**
1651
- * Create a revenue splitter.
1652
- *
1653
- * @param recipients — Array of recipients with basis points.
1654
- * Basis points must sum to exactly 10000 (100%).
1655
- * @throws Error if basis points don't sum to 10000 or any are negative.
1656
- */
1657
- constructor(recipients: SplitRecipient[]);
1658
- /**
1659
- * Split an amount among recipients.
1660
- *
1661
- * Uses bigint arithmetic for exact splitting.
1662
- * Dust (remainder from integer division) goes to the first recipient.
1663
- *
1664
- * @param totalAmount — Total amount to split (in base units, e.g., USDC 6 decimals)
1665
- * @returns SplitResult with exact shares summing to totalAmount
1666
- */
1667
- split(totalAmount: bigint): SplitResult;
1668
- /**
1669
- * Split a numeric amount (convenience wrapper).
1670
- * Converts to bigint internally.
1671
- */
1672
- splitNumeric(totalAmount: number): SplitResult;
1673
- /**
1674
- * Get the configured recipients.
1675
- */
1676
- getRecipients(): readonly SplitRecipient[];
1677
- /**
1678
- * Validate that a split result sums correctly.
1679
- */
1680
- static validate(result: SplitResult): boolean;
1681
- }
1682
-
1683
- /**
1684
- * InvisibleWallet — Framework stub for zero-friction wallet abstraction.
1685
- *
1686
- * The canonical implementation lives in @holoscript/marketplace-api.
1687
- * This stub provides the type-compatible interface for framework consumers
1688
- * who don't need the full viem/blockchain dependency.
1689
- *
1690
- * For full blockchain operations, use:
1691
- * import { InvisibleWallet } from '@holoscript/marketplace-api';
1692
- *
1693
- * FW-0.6 — Moved wallet interface into framework.
1694
- *
1695
- * @module economy/InvisibleWallet
1696
- */
1697
- type HexAddress = `0x${string}`;
1698
- interface InvisibleWalletConfig {
1699
- /** Use testnet instead of mainnet */
1700
- testnet?: boolean;
1701
- /** Custom RPC URL */
1702
- rpcUrl?: string;
1703
- }
1704
- interface WalletInfo {
1705
- address: HexAddress;
1706
- chainId: number;
1707
- isTestnet: boolean;
1708
- }
1709
- /**
1710
- * Lightweight InvisibleWallet for framework consumers.
1711
- *
1712
- * Provides address management and config without blockchain dependencies.
1713
- * For signing transactions, use the full implementation from marketplace-api.
1714
- */
1715
- declare class InvisibleWalletStub {
1716
- private address;
1717
- private chainId;
1718
- private isTestnet;
1719
- constructor(address: HexAddress, config?: InvisibleWalletConfig);
1720
- /**
1721
- * Create from an address string (no private key needed for read-only).
1722
- */
1723
- static fromAddress(address: string, config?: InvisibleWalletConfig): InvisibleWalletStub;
1724
- /** Get the wallet address */
1725
- getAddress(): HexAddress;
1726
- /** Get chain ID */
1727
- getChainId(): number;
1728
- /** Get wallet info */
1729
- getInfo(): WalletInfo;
1730
- }
1731
-
1732
- export { type WebhookProcessingResult as $, type RevenueEvent as A, type Bounty as B, CHAIN_IDS as C, type RevenuePeriod as D, RevenueSplitter as E, type SettlementEvent as F, type SettlementEventListener as G, type SettlementEventType as H, InvisibleWalletStub as I, type SettlementMode as J, type KnowledgeListing as K, type LedgerEntry as L, MICRO_PAYMENT_THRESHOLD as M, type SplitBreakdownEntry as N, type SplitRecipient as O, PaymentGateway as P, type SplitResult as Q, type ResourceCategory as R, type SettlementChain as S, type TelemetryCollector as T, USDC_CONTRACTS as U, type InvisibleWalletConfig as V, type HexAddress as W, type WalletInfo as X, type WebhookEventType as Y, type WebhookHandler as Z, type WebhookPayload as _, type ResourceUsageNode as a, computeExcitability as a$, type WebhookProvider as a0, type WebhookServiceConfig as a1, type WebhookVerificationResult as a2, X402Facilitator as a3, type X402FacilitatorConfig as a4, type X402PaymentOption as a5, type X402PaymentPayload as a6, type X402PaymentRequired as a7, type X402SettlementResult as a8, type X402VerificationResult as a9, type DomainConsolidationConfig as aA, type KnowledgeInsight as aB, type ProtocolAgentConfig as aC, type ProtocolAgentHandle as aD, type AgentCycleResult as aE, type AgentPresenceStatus as aF, type AgentRole as aG, type AgentStatus as aH, type ClaimFilter as aI, type ConsensusMode as aJ, DOMAIN_CONSOLIDATION as aK, DOMAIN_HALF_LIVES as aL, type EmbedResult as aM, KNOWLEDGE_DOMAINS as aN, type KnowledgeConfig as aO, type LLMProvider as aP, type PhaseHook as aQ, type PresenceConfig as aR, type ProtocolStyle as aS, RECONSOLIDATION_WINDOW_MS as aT, type ReputationTier as aU, type SemanticSearchOptions as aV, type SlotInfo as aW, type SlotRole as aX, type Suggestion as aY, type SuggestionVoteEntry as aZ, applyHalfLifeDecay as a_, X402_VERSION as aa, creditTraitHandler as ab, type StoredEntry as ac, type ModelConfig as ad, KnowledgeStore as ae, type AgentConfig as af, type TeamConfig as ag, type TaskDef as ah, type CycleResult as ai, type ProposalResult as aj, type AgentRuntime as ak, type SuggestionCreateResult as al, type SuggestionVoteResult as am, type SuggestionStatus as an, type SuggestionListResult as ao, type TeamMode as ap, type SetModeResult as aq, type DeriveResult as ar, type AgentPresence as as, type PresenceResult as at, type HeartbeatResult as au, type ExcitabilityMetadata as av, type KnowledgeDomain as aw, type HotBufferEntry as ax, type ConsolidationResult as ay, type ReconsolidationEvent as az, type BountyCurrency as b, triggerReconsolidation as b0, BountyManager as c, type BountyManagerConfig as d, type BountyReward as e, type BountyStatus as f, CHAIN_ID_TO_NETWORK as g, type ClaimResult as h, type CompletionProof as i, type CreatorEarnings as j, CreatorRevenueAggregator as k, type CreditTraitConfig as l, KnowledgeMarketplace as m, type ListingResult as n, type ListingStatus as o, MicroPaymentLedger as p, type PaymentScheme as q, PaymentWebhookService as r, type PayoutRecord as s, type PayoutResult as t, type PluginRevenue as u, type PricingFactors as v, type PurchaseResult as w, type RefundRequest as x, type RefundResult as y, type RevenueAggregatorConfig as z };