@hivemind-os/collective-core 0.2.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.
Files changed (145) hide show
  1. package/.test-data/05a845c4-1682-41b9-97e5-65a5263156c0/spending.sqlite +0 -0
  2. package/.test-data/10e18ba5-98f0-42e0-8899-06a09459ae85/agents.sqlite +0 -0
  3. package/.test-data/20464456-23cb-4ff7-8df5-3c129fb95a90/agents.sqlite +0 -0
  4. package/.test-data/2e2ec66c-e8b4-43eb-945f-cca84ed0a0f6/agents.sqlite +0 -0
  5. package/.test-data/2f5ef9b7-01da-4ba0-a6fa-af8063a2567c/agents.sqlite +0 -0
  6. package/.test-data/3ac13cd5-84c9-4e71-8b89-6d3ef4dd819c/agents.sqlite +0 -0
  7. package/.test-data/40b7dd4a-fae0-4a5d-a6a0-64c9048af35e/agents.sqlite +0 -0
  8. package/.test-data/59511a04-42f8-4286-bb1e-733795e08749/agents.sqlite +0 -0
  9. package/.test-data/6778e8c5-6eb5-416d-8aca-9d559cdf83e4/agents.sqlite +0 -0
  10. package/.test-data/7648dc86-df90-4460-8f9c-55cdb481324b/agents.sqlite +0 -0
  11. package/.test-data/77162d98-6b22-41b1-a50f-536fab739f8a/agents.sqlite +0 -0
  12. package/.test-data/798dbdab-cbe7-4edd-8a5b-ae99c285fe17/agents.sqlite +0 -0
  13. package/.test-data/8033d6ac-8b85-454d-b708-00ac695b22f8/agents.sqlite +0 -0
  14. package/.test-data/9155a4f4-cda3-487c-9eed-921c82d7550f/agents.sqlite +0 -0
  15. package/.test-data/9bfeee53-c231-46c3-8c93-2180933f5d50/agents.sqlite +0 -0
  16. package/.test-data/a4c64287-79f6-46e9-847d-2803c63a74fd/agents.sqlite +0 -0
  17. package/.test-data/b8f58952-1ed8-46ff-abd7-21fb86e9457f/agents.sqlite +0 -0
  18. package/.test-data/c3060504-3187-41ed-8532-82332be48b0b/spending.sqlite +0 -0
  19. package/.test-data/cc471629-8006-4fc1-b8a1-399d2df2cc4e/agents.sqlite +0 -0
  20. package/.test-data/dbca3bef-397d-4bbc-bd4c-4f7b14103e04/spending.sqlite +0 -0
  21. package/.test-data/f1283dd1-6602-4de7-a050-16aac7abc288/agents.sqlite +0 -0
  22. package/.turbo/turbo-build.log +14 -0
  23. package/dist/index.d.ts +1675 -0
  24. package/dist/index.js +8006 -0
  25. package/dist/index.js.map +1 -0
  26. package/package.json +41 -0
  27. package/src/auth/device-flow.ts +108 -0
  28. package/src/auth/ed25519-provider.ts +43 -0
  29. package/src/auth/errors.ts +82 -0
  30. package/src/auth/evm-key.ts +55 -0
  31. package/src/auth/index.ts +8 -0
  32. package/src/auth/session-state.ts +25 -0
  33. package/src/auth/session-store.ts +510 -0
  34. package/src/auth/types.ts +81 -0
  35. package/src/auth/zklogin-provider.ts +902 -0
  36. package/src/blobstore/WALRUS_FINDINGS.md +284 -0
  37. package/src/blobstore/encrypted-store.ts +56 -0
  38. package/src/blobstore/fs-store.ts +91 -0
  39. package/src/blobstore/hybrid-store.ts +144 -0
  40. package/src/blobstore/index.ts +5 -0
  41. package/src/blobstore/interface.ts +33 -0
  42. package/src/blobstore/walrus-spike.ts +345 -0
  43. package/src/blobstore/walrus-store.ts +551 -0
  44. package/src/cache/agent-cache.ts +403 -0
  45. package/src/cache/index.ts +1 -0
  46. package/src/crypto/encryption.ts +152 -0
  47. package/src/crypto/index.ts +2 -0
  48. package/src/crypto/x25519.ts +41 -0
  49. package/src/dispute/client.ts +191 -0
  50. package/src/dispute/index.ts +1 -0
  51. package/src/events/index.ts +2 -0
  52. package/src/events/parser.ts +291 -0
  53. package/src/events/subscription.ts +131 -0
  54. package/src/evm/constants.ts +6 -0
  55. package/src/evm/index.ts +2 -0
  56. package/src/evm/wallet.ts +136 -0
  57. package/src/identity/did.ts +36 -0
  58. package/src/identity/index.ts +4 -0
  59. package/src/identity/keypair.ts +199 -0
  60. package/src/identity/signing.ts +28 -0
  61. package/src/index.ts +22 -0
  62. package/src/internal/parsing.ts +416 -0
  63. package/src/marketplace/client.ts +349 -0
  64. package/src/marketplace/index.ts +1 -0
  65. package/src/metering/hash-chain.ts +94 -0
  66. package/src/metering/index.ts +4 -0
  67. package/src/metering/meter.ts +80 -0
  68. package/src/metering/streaming.ts +196 -0
  69. package/src/metering/verification.ts +104 -0
  70. package/src/payment/index.ts +1 -0
  71. package/src/payment/rail-selector.ts +41 -0
  72. package/src/registry/client.ts +328 -0
  73. package/src/registry/index.ts +1 -0
  74. package/src/relay/consumer-client.ts +497 -0
  75. package/src/relay/index.ts +1 -0
  76. package/src/relay-registry/client.ts +295 -0
  77. package/src/relay-registry/discovery.ts +109 -0
  78. package/src/relay-registry/index.ts +2 -0
  79. package/src/reputation/anchor-client.ts +126 -0
  80. package/src/reputation/event-publisher.ts +67 -0
  81. package/src/reputation/index.ts +5 -0
  82. package/src/reputation/merkle.ts +79 -0
  83. package/src/reputation/score-calculator.ts +133 -0
  84. package/src/reputation/serialization.ts +37 -0
  85. package/src/reputation/store.ts +165 -0
  86. package/src/reputation/validation.ts +135 -0
  87. package/src/routing/circuit-breaker.ts +111 -0
  88. package/src/routing/fan-out.ts +266 -0
  89. package/src/routing/index.ts +4 -0
  90. package/src/routing/performance.ts +244 -0
  91. package/src/routing/selector.ts +225 -0
  92. package/src/spending/index.ts +1 -0
  93. package/src/spending/policy.ts +271 -0
  94. package/src/staking/client.ts +319 -0
  95. package/src/staking/index.ts +1 -0
  96. package/src/sui/client.ts +214 -0
  97. package/src/sui/index.ts +2 -0
  98. package/src/sui/tx-helpers.ts +1070 -0
  99. package/src/task/client.ts +215 -0
  100. package/src/task/index.ts +1 -0
  101. package/src/x402/client.ts +295 -0
  102. package/src/x402/index.ts +1 -0
  103. package/tests/auth/device-flow.test.ts +62 -0
  104. package/tests/auth/ed25519-provider.test.ts +24 -0
  105. package/tests/auth/evm-key.test.ts +31 -0
  106. package/tests/auth/session-store.test.ts +201 -0
  107. package/tests/auth/zklogin-provider.test.ts +366 -0
  108. package/tests/blobstore/encrypted-store.test.ts +78 -0
  109. package/tests/blobstore.test.ts +91 -0
  110. package/tests/cache.test.ts +124 -0
  111. package/tests/crypto/encryption.test.ts +70 -0
  112. package/tests/crypto/x25519.test.ts +47 -0
  113. package/tests/dispute/client.test.ts +238 -0
  114. package/tests/events.test.ts +202 -0
  115. package/tests/evm/wallet.test.ts +101 -0
  116. package/tests/hybrid-store.test.ts +121 -0
  117. package/tests/identity.test.ts +161 -0
  118. package/tests/marketplace.test.ts +308 -0
  119. package/tests/metering/hash-chain.test.ts +32 -0
  120. package/tests/metering/meter.test.ts +23 -0
  121. package/tests/metering/streaming.test.ts +52 -0
  122. package/tests/metering/verification.test.ts +27 -0
  123. package/tests/payment/rail-selector.test.ts +95 -0
  124. package/tests/registry.test.ts +183 -0
  125. package/tests/relay-consumer-client.test.ts +119 -0
  126. package/tests/relay-registry/client.test.ts +261 -0
  127. package/tests/reputation/event-publisher.test.ts +70 -0
  128. package/tests/reputation/merkle.test.ts +44 -0
  129. package/tests/reputation/score-calculator.test.ts +104 -0
  130. package/tests/reputation/store.test.ts +94 -0
  131. package/tests/routing/circuit-breaker.test.ts +45 -0
  132. package/tests/routing/fan-out.test.ts +123 -0
  133. package/tests/routing/performance.test.ts +49 -0
  134. package/tests/routing/selector.test.ts +114 -0
  135. package/tests/spending.test.ts +133 -0
  136. package/tests/staking/client.test.ts +286 -0
  137. package/tests/sui-client.test.ts +85 -0
  138. package/tests/task.test.ts +249 -0
  139. package/tests/tx-helpers.test.ts +70 -0
  140. package/tests/walrus-spike.test.ts +100 -0
  141. package/tests/walrus-store.test.ts +196 -0
  142. package/tests/x402/client.test.ts +116 -0
  143. package/tsconfig.json +9 -0
  144. package/tsup.config.ts +11 -0
  145. package/vitest.config.ts +8 -0
@@ -0,0 +1,1675 @@
1
+ import { DID, NetworkConfig, Capability, AgentCard, ReputationScore, Task, Bid, BidRecommendation, Dispute, MeshEvent, PaymentRail, RelayListFilters, RelayNode, SpendingPolicy, ReputationEvent, ReputationAnchor, ReputationEventType, StakePosition, HashChainProof, MeteringReport, StreamingPaymentState, ProviderScore, MultiProviderRequest, MultiProviderResult, ProviderSelectionStrategy } from '@hivemind-os/collective-types';
2
+ export * from '@hivemind-os/collective-types';
3
+ import { Signer } from '@mysten/sui/cryptography';
4
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
5
+ import { SuiClient, SuiTransactionBlockResponseOptions, SuiTransactionBlockResponse, EventId, SuiEvent } from '@mysten/sui/client';
6
+ import pino from 'pino';
7
+ import { Transaction } from '@mysten/sui/transactions';
8
+ import { Chain, WalletClient, PublicClient } from 'viem';
9
+
10
+ interface KeytarModule {
11
+ getPassword(service: string, account: string): Promise<string | null>;
12
+ setPassword(service: string, account: string, password: string): Promise<void>;
13
+ }
14
+ interface SimpleKeypair {
15
+ publicKey: Uint8Array;
16
+ secretKey: Uint8Array;
17
+ }
18
+ interface KeyStore {
19
+ load(): Promise<Uint8Array>;
20
+ save(secretKey: Uint8Array): Promise<void>;
21
+ exists(): Promise<boolean>;
22
+ }
23
+ declare class FileKeyStore implements KeyStore {
24
+ private readonly keyPath;
25
+ constructor(keyPath: string);
26
+ load(): Promise<Uint8Array>;
27
+ save(secretKey: Uint8Array): Promise<void>;
28
+ exists(): Promise<boolean>;
29
+ delete(): void;
30
+ }
31
+ declare class KeychainStore implements KeyStore {
32
+ private readonly keytar;
33
+ private readonly service;
34
+ private readonly account;
35
+ constructor(keytar: KeytarModule, service?: string, account?: string);
36
+ load(): Promise<Uint8Array>;
37
+ save(secretKey: Uint8Array): Promise<void>;
38
+ exists(): Promise<boolean>;
39
+ }
40
+ declare function generateKeypair(): SimpleKeypair;
41
+ declare function keypairFromSecretKey(secretKey: Uint8Array): SimpleKeypair;
42
+ declare function createKeyStore(dataDir: string): Promise<KeyStore>;
43
+ declare function identityKeyExists(dataDir: string): Promise<boolean>;
44
+ declare function loadOrCreateKeypair(dataDir: string): Promise<SimpleKeypair>;
45
+
46
+ declare function createDID(publicKey: Uint8Array): DID;
47
+ declare function parseDID(did: string): {
48
+ publicKey: Uint8Array;
49
+ };
50
+ declare function isValidDID(did: string): boolean;
51
+
52
+ declare function sign(message: Uint8Array, secretKey: Uint8Array): Uint8Array;
53
+ declare function verify(message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean;
54
+ declare function signString(message: string, secretKey: Uint8Array): string;
55
+
56
+ interface X25519KeyPair {
57
+ publicKey: Uint8Array;
58
+ privateKey: Uint8Array;
59
+ }
60
+ declare function generateX25519KeyPair(): X25519KeyPair;
61
+ declare function ed25519ToX25519(ed25519PrivateKey: Uint8Array): X25519KeyPair;
62
+ declare function computeSharedSecret(myPrivateKey: Uint8Array, theirPublicKey: Uint8Array): Uint8Array;
63
+
64
+ interface EncryptedPayload {
65
+ version: 1;
66
+ senderPublicKey: string;
67
+ nonce: string;
68
+ ciphertext: string;
69
+ tag: string;
70
+ }
71
+ declare function encryptForRecipient(plaintext: Uint8Array, senderPrivateKey: Uint8Array, recipientPublicKey: Uint8Array): Promise<EncryptedPayload>;
72
+ declare function decryptFromSender(payload: EncryptedPayload, recipientPrivateKey: Uint8Array): Promise<Uint8Array>;
73
+ declare function serializeEncryptedPayload(payload: EncryptedPayload): Uint8Array;
74
+ declare function parseEncryptedPayload(data: Uint8Array): EncryptedPayload | null;
75
+ declare function isEncryptedPayload(value: unknown): value is EncryptedPayload;
76
+
77
+ declare enum SessionState {
78
+ VALID = "valid",
79
+ REFRESHING = "refreshing",
80
+ NEEDS_REAUTH = "needs_reauth",
81
+ EXPIRED = "expired"
82
+ }
83
+ interface SessionRefreshPolicy {
84
+ maxAttempts?: number;
85
+ backoffMs?: readonly number[];
86
+ maxConsecutiveFailures?: number;
87
+ }
88
+ interface SessionStateChangeEvent {
89
+ previousState: SessionState;
90
+ currentState: SessionState;
91
+ session: StoredZkLoginSession | null;
92
+ reason?: string;
93
+ refreshFailureCount: number;
94
+ error?: unknown;
95
+ }
96
+ type SessionStateChangeCallback = (event: SessionStateChangeEvent) => void;
97
+
98
+ type AuthMode = 'ed25519' | 'zklogin';
99
+ type OAuthProvider = 'google' | 'apple';
100
+ interface AuthProvider {
101
+ mode: AuthMode;
102
+ getAddress(): Promise<string>;
103
+ getDID(): string;
104
+ signTransaction(tx: Uint8Array): Promise<Uint8Array>;
105
+ signPersonalMessage(message: Uint8Array): Promise<{
106
+ signature: Uint8Array;
107
+ }>;
108
+ isAuthenticated(): boolean;
109
+ getPublicKey(): Uint8Array;
110
+ toSuiSigner(): Signer;
111
+ getSessionState?(): SessionState;
112
+ isSessionValid?(): boolean | Promise<boolean>;
113
+ onSessionStateChange?(callback: SessionStateChangeCallback): () => void;
114
+ }
115
+ interface ZkLoginSession {
116
+ provider: OAuthProvider;
117
+ jwt: string;
118
+ salt: string;
119
+ epoch: number;
120
+ ephemeralKeypair: Ed25519Keypair;
121
+ proof: ZkLoginProof;
122
+ maxEpoch: number;
123
+ address: string;
124
+ sub: string;
125
+ iss: string;
126
+ aud: string;
127
+ }
128
+ interface StoredZkLoginSession extends ZkLoginSession {
129
+ randomness: string;
130
+ refreshToken?: string;
131
+ createdAt: number;
132
+ updatedAt: number;
133
+ sessionState?: SessionState;
134
+ refreshFailureCount?: number;
135
+ }
136
+ interface ZkLoginProof {
137
+ proofPoints: {
138
+ a: string[];
139
+ b: string[][];
140
+ c: string[];
141
+ };
142
+ issBase64Details: {
143
+ value: string;
144
+ indexMod4: number;
145
+ };
146
+ headerBase64: string;
147
+ addressSeed: string;
148
+ }
149
+ interface OAuthConfig {
150
+ provider: OAuthProvider;
151
+ clientId: string;
152
+ redirectUri: string;
153
+ authorizationEndpoint?: string;
154
+ tokenEndpoint?: string;
155
+ deviceCodeEndpoint?: string;
156
+ saltEndpoint?: string;
157
+ proverEndpoint?: string;
158
+ issuer?: string;
159
+ scopes?: string[];
160
+ }
161
+ interface OAuthTokenResponse {
162
+ jwt: string;
163
+ refreshToken?: string;
164
+ accessToken?: string;
165
+ expiresIn?: number;
166
+ tokenType?: string;
167
+ scope?: string;
168
+ }
169
+ interface DeviceFlowStatus {
170
+ userCode: string;
171
+ verificationUri: string;
172
+ deviceCode: string;
173
+ pollInterval: number;
174
+ expiresIn: number;
175
+ }
176
+
177
+ interface SessionContext {
178
+ address: string;
179
+ iss: string;
180
+ maxEpoch: number;
181
+ updatedAt: number;
182
+ }
183
+ interface SessionRefreshErrorOptions {
184
+ attempts: number;
185
+ maxAttempts: number;
186
+ retryDelaysMs: readonly number[];
187
+ consecutiveFailures: number;
188
+ sessionState: SessionState;
189
+ session?: StoredZkLoginSession | null;
190
+ cause?: unknown;
191
+ }
192
+ declare class SessionRefreshError extends Error {
193
+ readonly attempts: number;
194
+ readonly maxAttempts: number;
195
+ readonly retryDelaysMs: readonly number[];
196
+ readonly consecutiveFailures: number;
197
+ readonly sessionState: SessionState;
198
+ readonly session?: SessionContext;
199
+ constructor(message: string, options: SessionRefreshErrorOptions);
200
+ }
201
+ interface SessionExpiredErrorOptions {
202
+ attempts?: number;
203
+ maxAttempts?: number;
204
+ retryDelaysMs?: readonly number[];
205
+ consecutiveFailures?: number;
206
+ sessionState?: SessionState;
207
+ session?: StoredZkLoginSession | null;
208
+ cause?: unknown;
209
+ }
210
+ declare class SessionExpiredError extends Error {
211
+ readonly attempts?: number;
212
+ readonly maxAttempts?: number;
213
+ readonly retryDelaysMs?: readonly number[];
214
+ readonly consecutiveFailures?: number;
215
+ readonly sessionState: SessionState;
216
+ readonly session?: SessionContext;
217
+ constructor(message: string, options?: SessionExpiredErrorOptions);
218
+ }
219
+
220
+ declare class Ed25519AuthProvider implements AuthProvider {
221
+ private readonly keypair;
222
+ readonly mode: "ed25519";
223
+ constructor(keypair: Ed25519Keypair);
224
+ getAddress(): Promise<string>;
225
+ getDID(): string;
226
+ signTransaction(tx: Uint8Array): Promise<Uint8Array>;
227
+ signPersonalMessage(message: Uint8Array): Promise<{
228
+ signature: Uint8Array;
229
+ }>;
230
+ isAuthenticated(): boolean;
231
+ getPublicKey(): Uint8Array;
232
+ toSuiSigner(): Ed25519Keypair;
233
+ }
234
+
235
+ type SessionStoreLogger = Pick<ReturnType<typeof pino>, 'info' | 'warn' | 'error'>;
236
+ interface ZkLoginSessionStoreOptions {
237
+ refresh?: SessionRefreshPolicy;
238
+ logger?: SessionStoreLogger;
239
+ onSessionStateChange?: SessionStateChangeCallback;
240
+ sleep?: (ms: number) => Promise<void>;
241
+ }
242
+ declare class ZkLoginSessionStore {
243
+ private readonly baseDir;
244
+ private readonly encryptionKey;
245
+ private readonly legacyEncryptionKey;
246
+ private readonly refreshPolicy;
247
+ private readonly logger;
248
+ private readonly sleep;
249
+ private readonly stateChangeListeners;
250
+ private sessionState;
251
+ private refreshFailureCount;
252
+ constructor(baseDir: string, encryptionKey: Uint8Array, options?: ZkLoginSessionStoreOptions);
253
+ getSessionState(): SessionState;
254
+ getRefreshFailureCount(): number;
255
+ onSessionStateChange(callback: SessionStateChangeCallback): () => void;
256
+ save(session: StoredZkLoginSession): Promise<void>;
257
+ loadLatest(): Promise<StoredZkLoginSession | null>;
258
+ loadAll(): Promise<StoredZkLoginSession[]>;
259
+ loadLatestValid(currentEpoch: number): Promise<StoredZkLoginSession | null>;
260
+ hasValidSession(currentEpoch: number): Promise<boolean>;
261
+ isExpired(session: Pick<StoredZkLoginSession, 'maxEpoch'>, currentEpoch: number): boolean;
262
+ isNearExpiry(session: Pick<StoredZkLoginSession, 'maxEpoch'>, currentEpoch: number, remainingEpochs?: number): boolean;
263
+ refreshIfNeeded(currentEpoch: number, refresher: (session: StoredZkLoginSession) => Promise<StoredZkLoginSession | null>, options?: {
264
+ force?: boolean;
265
+ }): Promise<StoredZkLoginSession | null>;
266
+ delete(session: Pick<StoredZkLoginSession, 'iss' | 'sub'>): Promise<void>;
267
+ deleteExpired(currentEpoch: number): Promise<void>;
268
+ private serializeSession;
269
+ private deserializeSession;
270
+ private normalizeSession;
271
+ private resolveSessionState;
272
+ private updateSessionState;
273
+ private encrypt;
274
+ private decrypt;
275
+ private decryptEnvelope;
276
+ private ensureBaseDir;
277
+ }
278
+
279
+ interface ZkLoginPendingSession {
280
+ epoch: number;
281
+ maxEpoch: number;
282
+ randomness: string;
283
+ nonce: string;
284
+ ephemeralKeypair: Ed25519Keypair;
285
+ }
286
+ interface ZkLoginAuthorizationRequest {
287
+ authorizationUrl: string;
288
+ pendingSession: ZkLoginPendingSession;
289
+ }
290
+ interface ZkLoginProviderOptions {
291
+ client: Pick<SuiClient, 'getCurrentEpoch'>;
292
+ oauth: OAuthConfig;
293
+ sessionStore?: ZkLoginSessionStore;
294
+ fetchFn?: typeof fetch;
295
+ }
296
+ interface RefreshSessionOptions {
297
+ force?: boolean;
298
+ invalidateOnFailure?: boolean;
299
+ throwOnFailure?: boolean;
300
+ now?: number;
301
+ }
302
+ declare class ZkLoginProvider implements AuthProvider {
303
+ private readonly options;
304
+ readonly mode: "zklogin";
305
+ private session;
306
+ private sessionState;
307
+ private readonly signer;
308
+ private readonly fetchFn;
309
+ private readonly sessionStateListeners;
310
+ private oauth;
311
+ constructor(options: ZkLoginProviderOptions);
312
+ getOAuthConfig(): OAuthConfig;
313
+ setOAuthConfig(oauth: OAuthConfig): void;
314
+ restoreSession(): Promise<boolean>;
315
+ createAuthorizationRequest(params: {
316
+ redirectUri: string;
317
+ state: string;
318
+ codeChallenge: string;
319
+ scopes?: string[];
320
+ }): Promise<ZkLoginAuthorizationRequest>;
321
+ exchangeAuthorizationCode(code: string, codeVerifier: string, redirectUri: string): Promise<OAuthTokenResponse>;
322
+ refreshSessionIfNeeded(currentEpoch?: number, options?: RefreshSessionOptions): Promise<StoredZkLoginSession | null>;
323
+ authenticateWithJwt(jwt: string, params: {
324
+ pendingSession: ZkLoginPendingSession;
325
+ refreshToken?: string;
326
+ validateNonce?: boolean;
327
+ }): Promise<StoredZkLoginSession>;
328
+ getAddress(): Promise<string>;
329
+ getDID(): string;
330
+ signTransaction(tx: Uint8Array): Promise<Uint8Array>;
331
+ signPersonalMessage(message: Uint8Array): Promise<{
332
+ signature: Uint8Array;
333
+ }>;
334
+ isAuthenticated(): boolean;
335
+ getPublicKey(): Uint8Array;
336
+ toSuiSigner(): Signer;
337
+ getSession(): StoredZkLoginSession | null;
338
+ getSessionState(): SessionState;
339
+ onSessionStateChange(callback: SessionStateChangeCallback): () => void;
340
+ isSessionValid(currentEpoch?: number): Promise<boolean>;
341
+ getSessionExpiryMs(session?: StoredZkLoginSession | null): number | null;
342
+ clearSession(session?: StoredZkLoginSession | null): Promise<void>;
343
+ private refreshTokens;
344
+ private createPendingSession;
345
+ private buildAuthorizationUrl;
346
+ private fetchSalt;
347
+ private fetchProof;
348
+ private fetchJson;
349
+ private getPublicIdentifier;
350
+ private requireSession;
351
+ private loadCurrentSession;
352
+ private handleRefreshFailure;
353
+ private dropSession;
354
+ private updateSessionState;
355
+ private getCurrentEpoch;
356
+ private getAuthorizationEndpoint;
357
+ private getTokenEndpoint;
358
+ private getSaltEndpoint;
359
+ private getProverEndpoint;
360
+ private getIssuer;
361
+ }
362
+ declare function createPkcePair(): {
363
+ verifier: string;
364
+ challenge: string;
365
+ };
366
+
367
+ declare function startDeviceFlow(config: OAuthConfig): Promise<DeviceFlowStatus>;
368
+ declare function pollDeviceFlow(deviceCode: string, config: OAuthConfig): Promise<{
369
+ jwt: string;
370
+ refreshToken?: string;
371
+ } | null>;
372
+
373
+ declare function deriveEvmKey(identityPrivateKey: Uint8Array, userSalt: string, oauthSub: string): Uint8Array;
374
+
375
+ interface ExecuteTransactionOptions {
376
+ requestType?: 'WaitForEffectsCert' | 'WaitForLocalExecution';
377
+ responseOptions?: SuiTransactionBlockResponseOptions;
378
+ timeout?: number;
379
+ pollInterval?: number;
380
+ }
381
+ declare class SuiTransactionExecutionError extends Error {
382
+ readonly digest?: string;
383
+ readonly retryable: boolean;
384
+ constructor(message: string, options?: {
385
+ cause?: unknown;
386
+ digest?: string;
387
+ retryable?: boolean;
388
+ });
389
+ }
390
+ declare function createSuiClient(config: NetworkConfig): SuiClient;
391
+ declare class MeshSuiClient {
392
+ private readonly networkConfig;
393
+ private readonly suiClient;
394
+ constructor(networkConfig: NetworkConfig);
395
+ executeTransaction(tx: Transaction, keypair: Signer, options?: ExecuteTransactionOptions): Promise<SuiTransactionBlockResponse>;
396
+ getBalance(address: string): Promise<bigint>;
397
+ queryEvents(eventType: string, cursor?: EventId | null, limit?: number): Promise<{
398
+ events: SuiEvent[];
399
+ nextCursor: EventId | null;
400
+ hasMore: boolean;
401
+ }>;
402
+ getObject<T>(objectId: string): Promise<T>;
403
+ get client(): SuiClient;
404
+ get config(): NetworkConfig;
405
+ }
406
+
407
+ declare const CLOCK_OBJECT_ID = "0x6";
408
+ interface RegisterAgentParams {
409
+ packageId: string;
410
+ registryId: string;
411
+ name: string;
412
+ did: string;
413
+ description: string;
414
+ capabilities: Capability[];
415
+ endpoint: string;
416
+ }
417
+ interface UpdateAgentParams {
418
+ packageId: string;
419
+ registryId: string;
420
+ cardId: string;
421
+ name: string;
422
+ description: string;
423
+ endpoint: string;
424
+ }
425
+ interface SetEncryptionKeyParams {
426
+ packageId: string;
427
+ cardId: string;
428
+ encryptionPublicKey: Uint8Array;
429
+ }
430
+ interface UpdateCapabilitiesParams {
431
+ packageId: string;
432
+ registryId: string;
433
+ cardId: string;
434
+ capabilities: Capability[];
435
+ }
436
+ interface DeactivateAgentParams {
437
+ packageId: string;
438
+ registryId: string;
439
+ cardId: string;
440
+ }
441
+ interface ReactivateAgentParams {
442
+ packageId: string;
443
+ registryId: string;
444
+ cardId: string;
445
+ }
446
+ interface PostTaskParams {
447
+ packageId: string;
448
+ capability: string;
449
+ category: string;
450
+ inputBlobId: string;
451
+ agreementHash?: string;
452
+ priceMist: bigint;
453
+ disputeWindowMs: number;
454
+ expiryHours: number;
455
+ }
456
+ interface PostMeteredTaskParams {
457
+ packageId: string;
458
+ capability: string;
459
+ category: string;
460
+ inputBlobId: string;
461
+ agreementHash?: string;
462
+ maxPriceMist: bigint;
463
+ unitPriceMist: bigint;
464
+ disputeWindowMs: number;
465
+ expiryHours: number;
466
+ }
467
+ interface AcceptTaskParams {
468
+ packageId: string;
469
+ taskId: string;
470
+ }
471
+ interface CompleteTaskParams {
472
+ packageId: string;
473
+ taskId: string;
474
+ resultBlobId: string;
475
+ providerCardId?: string;
476
+ }
477
+ interface CompleteMeteredTaskParams {
478
+ packageId: string;
479
+ taskId: string;
480
+ resultBlobId: string;
481
+ meteredUnits: number;
482
+ verificationHash: string;
483
+ providerCardId?: string;
484
+ }
485
+ interface ReleasePaymentParams {
486
+ packageId: string;
487
+ taskId: string;
488
+ }
489
+ interface ReleaseMeteredPaymentParams {
490
+ packageId: string;
491
+ taskId: string;
492
+ }
493
+ interface ClaimPaymentParams {
494
+ packageId: string;
495
+ taskId: string;
496
+ providerCardId?: string;
497
+ }
498
+ interface CancelTaskParams {
499
+ packageId: string;
500
+ taskId: string;
501
+ }
502
+ interface RefundExpiredTaskParams {
503
+ packageId: string;
504
+ taskId: string;
505
+ }
506
+ interface PlaceBidParams {
507
+ packageId: string;
508
+ taskId: string;
509
+ bidPriceMist: bigint;
510
+ reputationScore: bigint;
511
+ evidenceBlob?: string;
512
+ }
513
+ interface AcceptBidParams {
514
+ packageId: string;
515
+ taskId: string;
516
+ bidId: string;
517
+ otherBidIds?: string[];
518
+ }
519
+ interface WithdrawBidParams {
520
+ packageId: string;
521
+ bidId: string;
522
+ }
523
+ interface RejectBidParams {
524
+ packageId: string;
525
+ taskId: string;
526
+ bidId: string;
527
+ }
528
+ interface OpenDisputeParams {
529
+ packageId: string;
530
+ taskId: string;
531
+ evidenceBlobId: string;
532
+ proposedSplitMist: bigint;
533
+ arbitratorAddress?: string;
534
+ }
535
+ interface RespondToDisputeParams {
536
+ packageId: string;
537
+ disputeId: string;
538
+ evidenceBlobId: string;
539
+ proposedSplitMist: bigint;
540
+ }
541
+ interface AcceptResolutionParams {
542
+ packageId: string;
543
+ disputeId: string;
544
+ taskId: string;
545
+ }
546
+ interface ArbitrateDisputeParams {
547
+ packageId: string;
548
+ disputeId: string;
549
+ taskId: string;
550
+ rulingSplitMist: bigint;
551
+ }
552
+ interface PublishReputationAnchorParams {
553
+ packageId: string;
554
+ merkleRoot: number[];
555
+ eventCount: number;
556
+ blobId: string;
557
+ fromTimestamp: number;
558
+ toTimestamp: number;
559
+ }
560
+ interface DepositStakeParams {
561
+ packageId: string;
562
+ amountMist: bigint;
563
+ stakeType: 'agent' | 'relay';
564
+ }
565
+ interface AddStakeParams {
566
+ packageId: string;
567
+ stakeId: string;
568
+ amountMist: bigint;
569
+ }
570
+ interface StartDeactivationParams {
571
+ packageId: string;
572
+ stakeId: string;
573
+ }
574
+ interface WithdrawStakeParams {
575
+ packageId: string;
576
+ stakeId: string;
577
+ }
578
+ interface SlashStakeParams {
579
+ packageId: string;
580
+ stakeId: string;
581
+ taskId: string;
582
+ }
583
+ interface RegisterRelayParams {
584
+ packageId: string;
585
+ endpoint: string;
586
+ stakeId: string;
587
+ capabilities: string[];
588
+ region: string;
589
+ routingFeeBps: number;
590
+ }
591
+ interface RelayMutationParams {
592
+ packageId: string;
593
+ relayId: string;
594
+ }
595
+ interface RecordRelayRoutingParams extends RelayMutationParams {
596
+ feeAmountMist: bigint;
597
+ }
598
+ declare function buildRegisterAgentTx(params: RegisterAgentParams): Transaction;
599
+ declare function buildUpdateAgentTx(params: UpdateAgentParams): Transaction;
600
+ declare function buildUpdateCapabilitiesTx(params: UpdateCapabilitiesParams): Transaction;
601
+ declare function buildSetEncryptionKeyTx(params: SetEncryptionKeyParams): Transaction;
602
+ declare function buildDeactivateAgentTx(params: DeactivateAgentParams): Transaction;
603
+ declare function buildReactivateAgentTx(params: ReactivateAgentParams): Transaction;
604
+ declare function buildPostTaskTx(params: PostTaskParams): Transaction;
605
+ declare function buildPostMeteredTaskTx(params: PostMeteredTaskParams): Transaction;
606
+ declare function buildAcceptTaskTx(params: AcceptTaskParams): Transaction;
607
+ declare function buildCompleteTaskTx(params: CompleteTaskParams): Transaction;
608
+ declare function buildCompleteMeteredTaskTx(params: CompleteMeteredTaskParams): Transaction;
609
+ declare function buildReleasePaymentTx(params: ReleasePaymentParams): Transaction;
610
+ declare function buildReleaseMeteredPaymentTx(params: ReleaseMeteredPaymentParams): Transaction;
611
+ declare function buildClaimPaymentTx(params: ClaimPaymentParams): Transaction;
612
+ declare function buildCancelTaskTx(params: CancelTaskParams): Transaction;
613
+ declare function buildRefundExpiredTaskTx(params: RefundExpiredTaskParams): Transaction;
614
+ declare function buildPlaceBidTx(params: PlaceBidParams): Transaction;
615
+ declare function buildAcceptBidTx(params: AcceptBidParams): Transaction;
616
+ declare function buildWithdrawBidTx(params: WithdrawBidParams): Transaction;
617
+ declare function buildRejectBidTx(params: RejectBidParams): Transaction;
618
+ declare function buildOpenDisputeTx(params: OpenDisputeParams): Transaction;
619
+ declare function buildRespondToDisputeTx(params: RespondToDisputeParams): Transaction;
620
+ declare function buildAcceptResolutionTx(params: AcceptResolutionParams): Transaction;
621
+ declare function buildArbitrateDisputeTx(params: ArbitrateDisputeParams): Transaction;
622
+ declare function buildPublishReputationAnchorTx(params: PublishReputationAnchorParams): Transaction;
623
+ declare function buildDepositStakeTx(params: DepositStakeParams): Transaction;
624
+ declare function buildAddStakeTx(params: AddStakeParams): Transaction;
625
+ declare function buildStartDeactivationTx(params: StartDeactivationParams): Transaction;
626
+ declare function buildWithdrawStakeTx(params: WithdrawStakeParams): Transaction;
627
+ declare function buildSlashExpiredEscrowTx(params: SlashStakeParams): Transaction;
628
+ declare function buildSlashNonDeliveryTx(params: SlashStakeParams): Transaction;
629
+ declare function buildRegisterRelayTx(params: RegisterRelayParams): Transaction;
630
+ declare function buildHeartbeatRelayTx(params: RelayMutationParams): Transaction;
631
+ declare function buildDeactivateRelayTx(params: RelayMutationParams): Transaction;
632
+ declare function buildRecordRelayRoutingTx(params: RecordRelayRoutingParams): Transaction;
633
+
634
+ declare class RegistryClient {
635
+ private readonly suiClient;
636
+ private readonly config;
637
+ private readonly scoreCalculator;
638
+ private readonly stakingClient;
639
+ constructor(suiClient: MeshSuiClient, config: NetworkConfig);
640
+ registerAgent(params: {
641
+ name: string;
642
+ did: string;
643
+ description: string;
644
+ capabilities: Capability[];
645
+ endpoint: string;
646
+ encryptionPublicKey?: Uint8Array;
647
+ keypair: Signer;
648
+ }): Promise<{
649
+ txDigest: string;
650
+ agentCardId: string;
651
+ }>;
652
+ updateAgent(params: {
653
+ cardId: string;
654
+ name: string;
655
+ description: string;
656
+ endpoint: string;
657
+ encryptionPublicKey?: Uint8Array;
658
+ keypair: Signer;
659
+ }): Promise<{
660
+ txDigest: string;
661
+ }>;
662
+ setEncryptionKey(params: {
663
+ cardId: string;
664
+ encryptionPublicKey: Uint8Array;
665
+ keypair: Signer;
666
+ }): Promise<{
667
+ txDigest: string;
668
+ }>;
669
+ updateCapabilities(params: {
670
+ cardId: string;
671
+ capabilities: Capability[];
672
+ keypair: Signer;
673
+ }): Promise<{
674
+ txDigest: string;
675
+ }>;
676
+ deactivateAgent(params: {
677
+ cardId: string;
678
+ keypair: Signer;
679
+ }): Promise<{
680
+ txDigest: string;
681
+ }>;
682
+ reactivateAgent(params: {
683
+ cardId: string;
684
+ keypair: Signer;
685
+ }): Promise<{
686
+ txDigest: string;
687
+ }>;
688
+ getAgentCard(cardId: string): Promise<AgentCard | null>;
689
+ getAgentCardByOwner(owner: string): Promise<AgentCard | null>;
690
+ findAgentByDid(did: string): Promise<AgentCard | null>;
691
+ discoverByCapability(capability: string, limit?: number, options?: {
692
+ sortByReputation?: boolean;
693
+ scores?: Map<string, ReputationScore>;
694
+ }): Promise<AgentCard[]>;
695
+ private enrichAgentStake;
696
+ }
697
+
698
+ declare class TaskClient {
699
+ private readonly suiClient;
700
+ private readonly config;
701
+ constructor(suiClient: MeshSuiClient, config: NetworkConfig);
702
+ postTask(params: {
703
+ capability: string;
704
+ category: string;
705
+ inputBlobId: string;
706
+ agreementHash?: string;
707
+ priceMist: bigint;
708
+ disputeWindowMs: number;
709
+ expiryHours: number;
710
+ keypair: Signer;
711
+ }): Promise<{
712
+ txDigest: string;
713
+ taskId: string;
714
+ }>;
715
+ postMeteredTask(params: {
716
+ capability: string;
717
+ category: string;
718
+ inputBlobId: string;
719
+ agreementHash?: string;
720
+ maxPriceMist: bigint;
721
+ unitPriceMist: bigint;
722
+ disputeWindowMs: number;
723
+ expiryHours: number;
724
+ keypair: Signer;
725
+ }): Promise<{
726
+ txDigest: string;
727
+ taskId: string;
728
+ }>;
729
+ acceptTask(params: {
730
+ taskId: string;
731
+ keypair: Signer;
732
+ }): Promise<{
733
+ txDigest: string;
734
+ }>;
735
+ completeTask(params: {
736
+ taskId: string;
737
+ resultBlobId: string;
738
+ keypair: Signer;
739
+ providerCardId?: string;
740
+ }): Promise<{
741
+ txDigest: string;
742
+ }>;
743
+ completeMeteredTask(params: {
744
+ taskId: string;
745
+ resultBlobId: string;
746
+ meteredUnits: number;
747
+ verificationHash: string;
748
+ keypair: Signer;
749
+ providerCardId?: string;
750
+ }): Promise<{
751
+ txDigest: string;
752
+ }>;
753
+ releasePayment(params: {
754
+ taskId: string;
755
+ keypair: Signer;
756
+ }): Promise<{
757
+ txDigest: string;
758
+ }>;
759
+ releaseMeteredPayment(params: {
760
+ taskId: string;
761
+ keypair: Signer;
762
+ }): Promise<{
763
+ txDigest: string;
764
+ }>;
765
+ claimPayment(params: {
766
+ taskId: string;
767
+ keypair: Signer;
768
+ providerCardId?: string;
769
+ }): Promise<{
770
+ txDigest: string;
771
+ }>;
772
+ cancelTask(params: {
773
+ taskId: string;
774
+ keypair: Signer;
775
+ }): Promise<{
776
+ txDigest: string;
777
+ }>;
778
+ refundExpiredTask(params: {
779
+ taskId: string;
780
+ keypair: Signer;
781
+ }): Promise<{
782
+ txDigest: string;
783
+ }>;
784
+ getTask(taskId: string): Promise<Task | null>;
785
+ private submitTaskCreation;
786
+ }
787
+
788
+ interface BrowseOpenTasksFilters {
789
+ category?: string;
790
+ minPriceMist?: bigint;
791
+ maxPriceMist?: bigint;
792
+ limit?: number;
793
+ }
794
+ declare class MarketplaceClient {
795
+ private readonly suiClient;
796
+ private readonly config;
797
+ private readonly taskClient;
798
+ private readonly registryClient;
799
+ private readonly scoreCalculator;
800
+ constructor(suiClient: MeshSuiClient, config: NetworkConfig);
801
+ postOpenTask(params: {
802
+ capability: string;
803
+ category: string;
804
+ inputBlobId: string;
805
+ agreementHash?: string;
806
+ priceMist: bigint;
807
+ disputeWindowMs: number;
808
+ expiryHours: number;
809
+ signer: Signer;
810
+ }): Promise<{
811
+ txDigest: string;
812
+ taskId: string;
813
+ }>;
814
+ placeBid(params: {
815
+ taskId: string;
816
+ bidPriceMist: bigint;
817
+ signer: Signer;
818
+ reputationScore?: bigint | number;
819
+ evidenceBlob?: string;
820
+ }): Promise<{
821
+ bidId: string;
822
+ txDigest: string;
823
+ reputationScore: bigint;
824
+ }>;
825
+ acceptBid(params: {
826
+ taskId: string;
827
+ bidId: string;
828
+ signer: Signer;
829
+ rejectCompeting?: boolean;
830
+ }): Promise<{
831
+ txDigest: string;
832
+ rejectedBidIds: string[];
833
+ }>;
834
+ withdrawBid(params: {
835
+ bidId: string;
836
+ signer: Signer;
837
+ }): Promise<{
838
+ txDigest: string;
839
+ }>;
840
+ rejectBid(params: {
841
+ taskId: string;
842
+ bidId: string;
843
+ signer: Signer;
844
+ }): Promise<{
845
+ txDigest: string;
846
+ }>;
847
+ getBid(bidId: string): Promise<Bid | null>;
848
+ getBidsForTask(taskId: string): Promise<Bid[]>;
849
+ browseOpenTasks(filters?: BrowseOpenTasksFilters): Promise<Task[]>;
850
+ getRecommendedBid(taskId: string, options?: {
851
+ reputationWeight?: bigint | number;
852
+ priceWeight?: bigint | number;
853
+ }): Promise<BidRecommendation | null>;
854
+ private deriveReputationScore;
855
+ }
856
+
857
+ declare class DisputeClient {
858
+ private readonly suiClient;
859
+ private readonly config;
860
+ constructor(suiClient: MeshSuiClient, config: Pick<NetworkConfig, 'packageId'>);
861
+ openDispute(params: {
862
+ taskId: string;
863
+ evidenceBlobId: string;
864
+ proposedSplitMist: bigint;
865
+ arbitratorAddress?: string;
866
+ signer: Ed25519Keypair;
867
+ }): Promise<{
868
+ disputeId: string;
869
+ txDigest: string;
870
+ }>;
871
+ respondToDispute(params: {
872
+ disputeId: string;
873
+ evidenceBlobId: string;
874
+ proposedSplitMist: bigint;
875
+ signer: Ed25519Keypair;
876
+ }): Promise<{
877
+ txDigest: string;
878
+ }>;
879
+ acceptResolution(params: {
880
+ disputeId: string;
881
+ taskId: string;
882
+ signer: Ed25519Keypair;
883
+ }): Promise<{
884
+ requesterAmount: bigint;
885
+ providerAmount: bigint;
886
+ txDigest: string;
887
+ }>;
888
+ arbitrate(params: {
889
+ disputeId: string;
890
+ taskId: string;
891
+ rulingSplitMist: bigint;
892
+ signer: Ed25519Keypair;
893
+ }): Promise<{
894
+ txDigest: string;
895
+ }>;
896
+ getDispute(disputeId: string): Promise<Dispute | null>;
897
+ getDisputeByTask(taskId: string): Promise<Dispute | null>;
898
+ }
899
+
900
+ interface CursorStore {
901
+ getCursor(eventType: string): Promise<EventId | null>;
902
+ setCursor(eventType: string, cursor: EventId): Promise<void>;
903
+ }
904
+ declare class EventSubscription {
905
+ private readonly params;
906
+ private running;
907
+ private timer?;
908
+ private cursor;
909
+ private polling;
910
+ constructor(params: {
911
+ suiClient: MeshSuiClient;
912
+ eventType: string;
913
+ pollIntervalMs?: number;
914
+ onEvent: (event: SuiEvent) => Promise<void>;
915
+ onError?: (error: unknown) => void;
916
+ cursorStore: CursorStore;
917
+ });
918
+ start(): void;
919
+ stop(): void;
920
+ isRunning(): boolean;
921
+ private poll;
922
+ }
923
+ declare class SqliteCursorStore implements CursorStore {
924
+ private readonly db;
925
+ constructor(dbPath: string);
926
+ getCursor(eventType: string): Promise<EventId | null>;
927
+ setCursor(eventType: string, cursor: EventId): Promise<void>;
928
+ close(): void;
929
+ }
930
+
931
+ declare function parseRawEvent(rawEvent: SuiEvent, packageId: string): MeshEvent | null;
932
+
933
+ interface AdvancedAgentQueryFilters {
934
+ capability?: string;
935
+ minReputation?: number;
936
+ category?: string;
937
+ search?: string;
938
+ limit?: number;
939
+ offset?: number;
940
+ sortBy?: 'stake' | 'reputation';
941
+ }
942
+ type AdvancedAgentQueryDelegate = (filters: AdvancedAgentQueryFilters) => Promise<AgentCard[]>;
943
+ declare class AgentCache {
944
+ private readonly db;
945
+ private readonly scoreCalculator;
946
+ private readonly queryDelegate?;
947
+ constructor(dbPath: string, options?: {
948
+ queryDelegate?: AdvancedAgentQueryDelegate;
949
+ });
950
+ upsertAgent(agent: AgentCard): void;
951
+ removeAgent(agentId: string): void;
952
+ getAgent(agentId: string): AgentCard | null;
953
+ getAgentByDID(did: string): AgentCard | null;
954
+ searchByCapability(query: string, limit?: number, options?: {
955
+ sortByReputation?: boolean;
956
+ scores?: Map<string, ReputationScore>;
957
+ }): AgentCard[];
958
+ getAllActive(limit?: number): AgentCard[];
959
+ queryAgentsAdvanced(filters?: AdvancedAgentQueryFilters): Promise<AgentCard[]>;
960
+ close(): void;
961
+ }
962
+
963
+ interface ContentAddressedBlob {
964
+ blobId: string;
965
+ contentHash: string;
966
+ size: number;
967
+ storedAt: number;
968
+ }
969
+ interface StoredBlob extends ContentAddressedBlob {
970
+ hash: string;
971
+ checksum: string;
972
+ }
973
+ type BlobMetadata = ContentAddressedBlob;
974
+ declare class BlobIntegrityError extends Error {
975
+ readonly blobId: string;
976
+ readonly expectedHash: string;
977
+ readonly actualHash: string;
978
+ constructor(message: string, blobId: string, expectedHash: string, actualHash: string);
979
+ }
980
+ interface BlobStore {
981
+ store(data: Uint8Array): Promise<StoredBlob>;
982
+ fetch(blobId: string): Promise<Uint8Array | null>;
983
+ exists(blobId: string): Promise<boolean>;
984
+ delete(blobId: string): Promise<void>;
985
+ getMetadata?(blobId: string): Promise<BlobMetadata | null>;
986
+ }
987
+
988
+ declare class FilesystemBlobStore implements BlobStore {
989
+ private readonly baseDir;
990
+ constructor(baseDir: string);
991
+ store(data: Uint8Array): Promise<StoredBlob>;
992
+ fetch(blobId: string): Promise<Uint8Array | null>;
993
+ exists(blobId: string): Promise<boolean>;
994
+ getMetadata(blobId: string): Promise<BlobMetadata | null>;
995
+ delete(blobId: string): Promise<void>;
996
+ }
997
+
998
+ declare const DEFAULT_WALRUS_PUBLISHER_URL = "https://publisher.walrus-testnet.walrus.space";
999
+ declare const DEFAULT_WALRUS_AGGREGATOR_URL = "https://aggregator.walrus-testnet.walrus.space";
1000
+ declare const DEFAULT_WALRUS_EPOCHS = 5;
1001
+ declare const DEFAULT_WALRUS_MAX_BLOB_SIZE: number;
1002
+ declare const DEFAULT_WALRUS_RETRY_ATTEMPTS = 3;
1003
+ declare const DEFAULT_WALRUS_RETRY_DELAY_MS = 1000;
1004
+ declare const DEFAULT_WALRUS_TIMEOUT_MS = 30000;
1005
+ interface WalrusLogger {
1006
+ debug(bindings: Record<string, unknown>, message?: string): void;
1007
+ info(bindings: Record<string, unknown>, message?: string): void;
1008
+ warn(bindings: Record<string, unknown>, message?: string): void;
1009
+ error(bindings: Record<string, unknown>, message?: string): void;
1010
+ }
1011
+ interface WalrusBlobStoreConfig {
1012
+ publisherUrl: string;
1013
+ aggregatorUrl: string;
1014
+ epochs?: number;
1015
+ maxBlobSize?: number;
1016
+ retryAttempts?: number;
1017
+ retryDelayMs?: number;
1018
+ timeoutMs?: number;
1019
+ fetchImpl?: typeof fetch;
1020
+ logger?: WalrusLogger;
1021
+ }
1022
+ interface WalrusBlobMetadata extends BlobMetadata {
1023
+ storageBlobId: string;
1024
+ objectId?: string;
1025
+ deletable?: boolean;
1026
+ endEpoch?: number;
1027
+ }
1028
+ interface WalrusBlobReference {
1029
+ blobId: string;
1030
+ storageBlobId: string;
1031
+ contentHash?: string;
1032
+ }
1033
+ declare class WalrusRequestError extends Error {
1034
+ readonly url: string;
1035
+ readonly transient: boolean;
1036
+ readonly status?: number | undefined;
1037
+ readonly body?: string | undefined;
1038
+ constructor(message: string, url: string, transient: boolean, status?: number | undefined, body?: string | undefined, options?: ErrorOptions);
1039
+ }
1040
+ declare class WalrusNetworkError extends WalrusRequestError {
1041
+ constructor(message: string, url: string, options?: ErrorOptions);
1042
+ }
1043
+ declare class WalrusTimeoutError extends WalrusRequestError {
1044
+ readonly timeoutMs: number;
1045
+ constructor(message: string, url: string, timeoutMs: number, options?: ErrorOptions);
1046
+ }
1047
+ declare class WalrusHttpError extends WalrusRequestError {
1048
+ constructor(message: string, url: string, status: number, body: string);
1049
+ }
1050
+ declare class WalrusResponseError extends WalrusRequestError {
1051
+ constructor(message: string, url: string, body: string, options?: ErrorOptions);
1052
+ }
1053
+ declare class WalrusBlobTooLargeError extends Error {
1054
+ readonly size: number;
1055
+ readonly maxBlobSize: number;
1056
+ constructor(size: number, maxBlobSize: number);
1057
+ }
1058
+ declare class WalrusBlobStore implements BlobStore {
1059
+ private readonly config;
1060
+ private readonly metadata;
1061
+ constructor(config: WalrusBlobStoreConfig);
1062
+ store(data: Uint8Array): Promise<StoredBlob>;
1063
+ fetch(blobId: string): Promise<Uint8Array | null>;
1064
+ exists(blobId: string): Promise<boolean>;
1065
+ getMetadata(blobId: string): Promise<BlobMetadata | null>;
1066
+ delete(blobId: string): Promise<void>;
1067
+ private executeWithRetry;
1068
+ private fetchWithTimeout;
1069
+ private rememberMetadata;
1070
+ private log;
1071
+ }
1072
+ declare function createWalrusBlobReference(storageBlobId: string, contentHash: string): string;
1073
+ declare function parseWalrusBlobReference(blobId: string): WalrusBlobReference;
1074
+
1075
+ interface HybridBlobStoreOptions {
1076
+ preferWalrus?: boolean;
1077
+ cacheLocally?: boolean;
1078
+ }
1079
+ declare class HybridBlobStore implements BlobStore {
1080
+ private readonly walrus;
1081
+ private readonly local;
1082
+ private readonly options;
1083
+ constructor(walrus: WalrusBlobStore, local: FilesystemBlobStore, options?: HybridBlobStoreOptions);
1084
+ store(data: Uint8Array): Promise<StoredBlob>;
1085
+ fetch(blobId: string): Promise<Uint8Array | null>;
1086
+ exists(blobId: string): Promise<boolean>;
1087
+ getMetadata(blobId: string): Promise<BlobMetadata | null>;
1088
+ delete(blobId: string): Promise<void>;
1089
+ private get preferWalrus();
1090
+ private get cacheLocally();
1091
+ }
1092
+
1093
+ declare class EncryptedBlobStore implements BlobStore {
1094
+ private readonly inner;
1095
+ private readonly myKeyPair;
1096
+ constructor(inner: BlobStore, myKeyPair: X25519KeyPair);
1097
+ storeEncrypted(data: Uint8Array, recipientPublicKey: Uint8Array): Promise<{
1098
+ blobId: string;
1099
+ hash: string;
1100
+ }>;
1101
+ fetchDecrypted(blobId: string): Promise<Uint8Array | null>;
1102
+ store(data: Uint8Array): Promise<StoredBlob>;
1103
+ fetch(blobId: string): Promise<Uint8Array | null>;
1104
+ exists(blobId: string): Promise<boolean>;
1105
+ delete(blobId: string): Promise<void>;
1106
+ getMetadata(blobId: string): Promise<BlobMetadata | null>;
1107
+ }
1108
+
1109
+ declare const USDC_ADDRESS: {
1110
+ readonly base: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
1111
+ readonly 'base-sepolia': "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
1112
+ };
1113
+ declare const PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
1114
+
1115
+ interface EvmWalletConfig {
1116
+ network: 'base' | 'base-sepolia' | 'localhost';
1117
+ rpcUrl?: string;
1118
+ }
1119
+ declare class EvmWallet {
1120
+ private readonly config;
1121
+ private readonly account;
1122
+ private readonly chainConfig;
1123
+ private readonly walletClient;
1124
+ private readonly publicClient;
1125
+ constructor(privateKey: Uint8Array, config: EvmWalletConfig);
1126
+ get address(): string;
1127
+ get chain(): Chain;
1128
+ getBalance(): Promise<bigint>;
1129
+ getTokenBalance(tokenAddress: string): Promise<bigint>;
1130
+ signMessage(message: string | Uint8Array): Promise<string>;
1131
+ signTypedData(typedData: Omit<Parameters<WalletClient['signTypedData']>[0], 'account'>): Promise<string>;
1132
+ sendTransaction(to: string, value: bigint): Promise<string>;
1133
+ getWalletClient(): WalletClient;
1134
+ getPublicClient(): PublicClient;
1135
+ }
1136
+
1137
+ type SelectedPaymentRail = 'sui-escrow' | 'sui-transfer' | 'x402-base';
1138
+ interface RailSelectionContext {
1139
+ executionMode: 'sync' | 'async';
1140
+ consumerHasSuiWallet: boolean;
1141
+ consumerHasEvmWallet: boolean;
1142
+ providerAcceptsSui: boolean;
1143
+ providerAcceptsX402: boolean;
1144
+ amount: bigint;
1145
+ currency: string;
1146
+ }
1147
+ declare class PaymentRailSelector {
1148
+ selectRail(context: RailSelectionContext): SelectedPaymentRail;
1149
+ getAvailableRails(context: RailSelectionContext): SelectedPaymentRail[];
1150
+ }
1151
+
1152
+ interface X402PaymentRequest {
1153
+ paymentAddress: string;
1154
+ amount: string;
1155
+ currency: string;
1156
+ network: string;
1157
+ nonce: string;
1158
+ expiresAt: number;
1159
+ }
1160
+ interface X402PaymentSignature {
1161
+ signature: string;
1162
+ payerAddress: string;
1163
+ network: string;
1164
+ nonce: string;
1165
+ }
1166
+ declare class X402Client {
1167
+ private readonly wallet;
1168
+ constructor(wallet: EvmWallet);
1169
+ parse402Response(headers: Record<string, string>, body?: unknown): X402PaymentRequest;
1170
+ signPayment(request: X402PaymentRequest): Promise<X402PaymentSignature>;
1171
+ createPaymentHeader(request: X402PaymentRequest): Promise<string>;
1172
+ verifyPayment(signature: X402PaymentSignature, request: X402PaymentRequest): Promise<boolean>;
1173
+ }
1174
+
1175
+ interface RelaySuiPaymentProof {
1176
+ rail: PaymentRail.SUI_TRANSFER;
1177
+ payerDid: DID;
1178
+ payerAddress: string;
1179
+ paymentAddress: string;
1180
+ amount: string;
1181
+ currency: string;
1182
+ network: string;
1183
+ nonce: string;
1184
+ expiresAt: number;
1185
+ signature: string;
1186
+ }
1187
+ declare class RelayConsumerClient {
1188
+ private readonly x402Client;
1189
+ private readonly identity;
1190
+ private readonly config;
1191
+ private readonly sessionId;
1192
+ private sequence;
1193
+ constructor(x402Client: X402Client | null, identity: AuthProvider, config: {
1194
+ relayUrl: string;
1195
+ });
1196
+ executeSync(request: {
1197
+ providerDid: string;
1198
+ capability: string;
1199
+ input: unknown;
1200
+ paymentRail: PaymentRail;
1201
+ timeoutMs?: number;
1202
+ }): Promise<{
1203
+ result: unknown;
1204
+ paymentReceipt?: string;
1205
+ latencyMs: number;
1206
+ taskId?: string;
1207
+ providerDid?: string;
1208
+ }>;
1209
+ executeSyncStreaming(request: {
1210
+ providerDid: string;
1211
+ capability: string;
1212
+ input: unknown;
1213
+ paymentRail: PaymentRail;
1214
+ onChunk: (chunk: string) => void;
1215
+ onProgress: (progress: number, message?: string) => void;
1216
+ timeoutMs?: number;
1217
+ }): Promise<{
1218
+ result: unknown;
1219
+ paymentReceipt?: string;
1220
+ }>;
1221
+ private executeWithPayment;
1222
+ private sendExecuteRequest;
1223
+ private requirePaymentChallenge;
1224
+ private createPaymentHeader;
1225
+ private nextSequence;
1226
+ }
1227
+ declare function createRelaySuiPaymentProof(identity: AuthProvider, request: {
1228
+ paymentAddress: string;
1229
+ amount: string;
1230
+ currency: string;
1231
+ network: string;
1232
+ nonce: string;
1233
+ expiresAt: number;
1234
+ }): Promise<RelaySuiPaymentProof>;
1235
+ declare function encodeRelaySuiPaymentProof(proof: RelaySuiPaymentProof): string;
1236
+ declare function decodeRelaySuiPaymentProof(header: string): RelaySuiPaymentProof;
1237
+ declare function verifyRelaySuiPaymentProof(proof: RelaySuiPaymentProof): boolean;
1238
+
1239
+ interface RelayRegistryContractConfig {
1240
+ packageId: string;
1241
+ heartbeatFreshnessMs?: number;
1242
+ }
1243
+ declare const DEFAULT_RELAY_HEARTBEAT_FRESHNESS_MS: number;
1244
+ declare class RelayRegistryClient {
1245
+ private readonly suiClient;
1246
+ private readonly config;
1247
+ private readonly stakingClient;
1248
+ private readonly heartbeatFreshnessMs;
1249
+ constructor(suiClient: MeshSuiClient, config: RelayRegistryContractConfig);
1250
+ registerRelay(params: {
1251
+ endpoint: string;
1252
+ stakeId: string;
1253
+ capabilities: string[];
1254
+ region: string;
1255
+ routingFeeBps: number;
1256
+ signer: Signer;
1257
+ }): Promise<{
1258
+ relayId: string;
1259
+ txDigest: string;
1260
+ }>;
1261
+ heartbeat(params: {
1262
+ relayId: string;
1263
+ signer: Signer;
1264
+ }): Promise<{
1265
+ lastHeartbeat: number;
1266
+ txDigest: string;
1267
+ }>;
1268
+ recordRouting(params: {
1269
+ relayId: string;
1270
+ feeAmountMist: bigint;
1271
+ signer: Signer;
1272
+ }): Promise<{
1273
+ txDigest: string;
1274
+ }>;
1275
+ deactivateRelay(params: {
1276
+ relayId: string;
1277
+ signer: Signer;
1278
+ }): Promise<{
1279
+ txDigest: string;
1280
+ }>;
1281
+ listRelays(filters?: RelayListFilters): Promise<RelayNode[]>;
1282
+ getRelay(relayId: string): Promise<RelayNode | null>;
1283
+ getRelaysByRegion(region: string): Promise<RelayNode[]>;
1284
+ private collectRelayIds;
1285
+ private enrichRelay;
1286
+ }
1287
+
1288
+ interface RelayDiscoveryOptions {
1289
+ cacheTtlMs?: number;
1290
+ heartbeatFreshnessMs?: number;
1291
+ now?: () => number;
1292
+ }
1293
+ declare class RelayDiscovery {
1294
+ private readonly registryClient;
1295
+ private readonly cacheTtlMs;
1296
+ private readonly heartbeatFreshnessMs;
1297
+ private readonly now;
1298
+ private cache?;
1299
+ constructor(registryClient: Pick<RelayRegistryClient, 'listRelays'>, options?: RelayDiscoveryOptions);
1300
+ findBestRelay(capability: string, region?: string): Promise<RelayNode | null>;
1301
+ invalidateCache(): void;
1302
+ private getRelayList;
1303
+ }
1304
+
1305
+ interface SpendingPolicyDecision {
1306
+ approved: boolean;
1307
+ reason?: string;
1308
+ }
1309
+ interface SpendingPolicyConfig extends SpendingPolicy {
1310
+ perApp?: Record<string, {
1311
+ limits: SpendingPolicy['limits'];
1312
+ }>;
1313
+ }
1314
+ interface SpendingAmount {
1315
+ amount?: bigint;
1316
+ amountMist?: bigint;
1317
+ currency?: string;
1318
+ }
1319
+ interface SpendingLogEntry {
1320
+ id: number;
1321
+ amountBaseUnits: bigint;
1322
+ rail: PaymentRail;
1323
+ currency?: string;
1324
+ taskId?: string;
1325
+ appId?: string;
1326
+ timestamp: number;
1327
+ }
1328
+ declare class SpendingPolicyEngine {
1329
+ private readonly db;
1330
+ private policy;
1331
+ constructor(params: {
1332
+ policy: SpendingPolicyConfig;
1333
+ dbPath: string;
1334
+ });
1335
+ evaluate(request: SpendingAmount & {
1336
+ rail: PaymentRail;
1337
+ appId?: string;
1338
+ originAppName?: string;
1339
+ }): SpendingPolicyDecision;
1340
+ record(entry: SpendingAmount & {
1341
+ rail: PaymentRail;
1342
+ taskId: string;
1343
+ appId?: string;
1344
+ originAppName?: string;
1345
+ }): void;
1346
+ getSpent(interval: 'hour' | 'day' | 'month', rail?: PaymentRail, appId?: string, currency?: string): bigint;
1347
+ /** Return the most recent spending log entries, newest first. */
1348
+ getRecentEntries(limit?: number): SpendingLogEntry[];
1349
+ updatePolicy(policy: SpendingPolicyConfig): void;
1350
+ close(): void;
1351
+ private evaluateLimits;
1352
+ private getSpentForLimit;
1353
+ private migrateSpendingLogSchema;
1354
+ }
1355
+
1356
+ interface ContractConfig {
1357
+ packageId: string;
1358
+ }
1359
+ declare class ReputationAnchorClient {
1360
+ private readonly suiClient;
1361
+ private readonly config;
1362
+ constructor(suiClient: MeshSuiClient, config: ContractConfig);
1363
+ publishAnchor(events: ReputationEvent[], blobStore: BlobStore, signer: Signer): Promise<{
1364
+ anchorId: string;
1365
+ merkleRoot: string;
1366
+ txDigest: string;
1367
+ }>;
1368
+ getAnchors(author?: string, limit?: number): Promise<ReputationAnchor[]>;
1369
+ private fetchAnchor;
1370
+ }
1371
+
1372
+ declare class ReputationEventPublisher {
1373
+ private readonly blobStore;
1374
+ private readonly identity;
1375
+ constructor(blobStore: BlobStore, identity: AuthProvider);
1376
+ createEvent(params: {
1377
+ type: ReputationEventType;
1378
+ subject: string;
1379
+ taskId: string;
1380
+ outcome: string;
1381
+ capability: string;
1382
+ rating?: number;
1383
+ latencyMs?: number;
1384
+ paymentAmount?: {
1385
+ amount: string;
1386
+ currency: string;
1387
+ };
1388
+ }): Promise<ReputationEvent>;
1389
+ publishEvent(event: ReputationEvent): Promise<void>;
1390
+ }
1391
+
1392
+ declare function buildMerkleTree(events: ReputationEvent[]): {
1393
+ root: Uint8Array;
1394
+ proof: (index: number) => Uint8Array[];
1395
+ };
1396
+ declare function verifyMerkleProof(event: ReputationEvent, proof: Uint8Array[], root: Uint8Array, index: number): boolean;
1397
+
1398
+ declare class ReputationScoreCalculator {
1399
+ computeScore(agentCard: AgentCard, events: ReputationEvent[]): ReputationScore;
1400
+ rankByReputation(agents: AgentCard[], scores: Map<string, ReputationScore>): AgentCard[];
1401
+ }
1402
+
1403
+ declare class ReputationStore {
1404
+ private readonly db;
1405
+ constructor(dbPath: string);
1406
+ addEvent(event: ReputationEvent): Promise<void>;
1407
+ getEvents(options: {
1408
+ subject?: string;
1409
+ author?: string;
1410
+ since?: number;
1411
+ limit?: number;
1412
+ }): Promise<ReputationEvent[]>;
1413
+ getUnanchoredEvents(limit?: number): Promise<ReputationEvent[]>;
1414
+ markAnchored(eventIds: string[], anchorId: string): Promise<void>;
1415
+ getStats(subject: string): Promise<{
1416
+ completed: number;
1417
+ failed: number;
1418
+ disputed: number;
1419
+ }>;
1420
+ close(): void;
1421
+ }
1422
+
1423
+ interface StakingContractConfig {
1424
+ packageId: string;
1425
+ }
1426
+ declare const STAKING_COOLDOWN_MS = 604800000;
1427
+ declare class StakingClient {
1428
+ private readonly suiClient;
1429
+ private readonly config;
1430
+ constructor(suiClient: MeshSuiClient, config: StakingContractConfig);
1431
+ depositStake(params: {
1432
+ amountMist: bigint;
1433
+ stakeType: 'agent' | 'relay';
1434
+ signer: Ed25519Keypair;
1435
+ }): Promise<{
1436
+ stakeId: string;
1437
+ txDigest: string;
1438
+ }>;
1439
+ addStake(params: {
1440
+ stakeId: string;
1441
+ amountMist: bigint;
1442
+ signer: Ed25519Keypair;
1443
+ }): Promise<{
1444
+ txDigest: string;
1445
+ }>;
1446
+ startDeactivation(params: {
1447
+ stakeId: string;
1448
+ signer: Ed25519Keypair;
1449
+ }): Promise<{
1450
+ cooldownEndsAt: number;
1451
+ txDigest: string;
1452
+ }>;
1453
+ withdrawStake(params: {
1454
+ stakeId: string;
1455
+ signer: Ed25519Keypair;
1456
+ }): Promise<{
1457
+ amountReturned: bigint;
1458
+ txDigest: string;
1459
+ }>;
1460
+ slashExpiredEscrow(params: {
1461
+ stakeId: string;
1462
+ taskId: string;
1463
+ signer: Ed25519Keypair;
1464
+ }): Promise<{
1465
+ slashedAmount: bigint;
1466
+ txDigest: string;
1467
+ }>;
1468
+ slashNonDelivery(params: {
1469
+ stakeId: string;
1470
+ taskId: string;
1471
+ signer: Ed25519Keypair;
1472
+ }): Promise<{
1473
+ slashedAmount: bigint;
1474
+ txDigest: string;
1475
+ }>;
1476
+ getStakePosition(stakeId: string): Promise<StakePosition | null>;
1477
+ getStakeByOwner(owner: string): Promise<StakePosition | null>;
1478
+ getStakeByOwners(owners: string[]): Promise<Map<string, StakePosition>>;
1479
+ }
1480
+
1481
+ declare const DEFAULT_METERING_CHUNK_SIZE = 1024;
1482
+ declare class HashChain {
1483
+ private readonly seed;
1484
+ private currentHash;
1485
+ private readonly intermediateHashes;
1486
+ constructor(seed?: Uint8Array);
1487
+ addUnit(data: Uint8Array): string;
1488
+ getRoot(): string;
1489
+ getProof(): HashChainProof;
1490
+ static verifyChain(proof: HashChainProof, unitData: Uint8Array[], seed?: Uint8Array): boolean;
1491
+ }
1492
+ declare function createMeteringSeed(taskId: string): Uint8Array;
1493
+ declare function splitIntoMeteringUnits(data: Uint8Array, chunkSize?: number): Uint8Array[];
1494
+
1495
+ interface UsageMeterOptions {
1496
+ taskId: string;
1497
+ maxPrice: bigint;
1498
+ unitPrice?: bigint;
1499
+ seed?: Uint8Array;
1500
+ }
1501
+ declare class UsageMeter {
1502
+ private readonly hashChain;
1503
+ private actualUnits;
1504
+ private readonly taskId;
1505
+ private readonly maxPrice;
1506
+ private readonly unitPrice;
1507
+ constructor(options: UsageMeterOptions);
1508
+ recordUnit(data: Uint8Array): number;
1509
+ getActualUnits(): number;
1510
+ getVerificationHash(): string;
1511
+ getProof(): HashChainProof;
1512
+ getCost(unitPrice?: bigint): bigint;
1513
+ getReport(): MeteringReport;
1514
+ }
1515
+
1516
+ interface StreamingPaymentManagerOptions {
1517
+ dbPath: string;
1518
+ now?: () => number;
1519
+ paymentProcessor?: (entry: {
1520
+ taskId: string;
1521
+ amount: bigint;
1522
+ unitIndex: number;
1523
+ totalPaid: bigint;
1524
+ timestamp: number;
1525
+ }) => Promise<void> | void;
1526
+ }
1527
+ declare class StreamingPaymentManager {
1528
+ private readonly options;
1529
+ private readonly db;
1530
+ private readonly now;
1531
+ constructor(options: StreamingPaymentManagerOptions);
1532
+ startStream(taskId: string, maxBudget: bigint, unitPrice: bigint): StreamingPaymentState;
1533
+ getState(taskId: string): StreamingPaymentState | null;
1534
+ payUnit(taskId: string): Promise<StreamingPaymentState>;
1535
+ finalizeStream(taskId: string): {
1536
+ state: StreamingPaymentState;
1537
+ refundAmount: bigint;
1538
+ };
1539
+ getAuditTrail(taskId: string): Array<{
1540
+ taskId: string;
1541
+ unitIndex: number;
1542
+ amount: bigint;
1543
+ timestamp: number;
1544
+ }>;
1545
+ close(): void;
1546
+ private requireStreamRow;
1547
+ }
1548
+
1549
+ declare const METERED_RESULT_SCHEMA = "agentic-mesh-metered-result/v1";
1550
+ interface MeteredResultEnvelope {
1551
+ schema: typeof METERED_RESULT_SCHEMA;
1552
+ resultEncoding: 'base64';
1553
+ result: string;
1554
+ proof: HashChainProof;
1555
+ unitChunkSize: number;
1556
+ }
1557
+ declare class ResultVerifier {
1558
+ verify(task: Pick<Task, 'id' | 'verificationHash'>, proof: HashChainProof, expectedData: Uint8Array[]): boolean;
1559
+ }
1560
+ declare function createMeteredResultEnvelope(resultData: Uint8Array, proof: HashChainProof, unitChunkSize?: number): MeteredResultEnvelope;
1561
+ declare function serializeMeteredResultEnvelope(envelope: MeteredResultEnvelope): Uint8Array;
1562
+ declare function parseMeteredResultEnvelope(data: Uint8Array): MeteredResultEnvelope | null;
1563
+ declare function decodeMeteredResult(envelope: MeteredResultEnvelope): Uint8Array;
1564
+ declare function getMeteredResultUnits(envelope: MeteredResultEnvelope): Uint8Array[];
1565
+
1566
+ declare enum CircuitBreakerState {
1567
+ CLOSED = "closed",
1568
+ OPEN = "open",
1569
+ HALF_OPEN = "half_open"
1570
+ }
1571
+ interface CircuitBreakerOptions {
1572
+ failureThreshold?: number;
1573
+ recoveryTimeoutMs?: number;
1574
+ now?: () => number;
1575
+ }
1576
+ declare class CircuitBreaker {
1577
+ private readonly failureThreshold;
1578
+ private readonly recoveryTimeoutMs;
1579
+ private readonly now;
1580
+ private readonly states;
1581
+ constructor(options?: CircuitBreakerOptions);
1582
+ recordSuccess(providerId: string): void;
1583
+ recordFailure(providerId: string): void;
1584
+ allowRequest(providerId: string): boolean;
1585
+ isOpen(providerId: string): boolean;
1586
+ getState(providerId: string): CircuitBreakerState;
1587
+ private getStateRecord;
1588
+ }
1589
+
1590
+ interface PerformanceTrackerOptions {
1591
+ dbPath?: string;
1592
+ now?: () => number;
1593
+ maxSamplesPerCapability?: number;
1594
+ }
1595
+ interface ProviderCapabilityPerformance {
1596
+ capability: string;
1597
+ avgDurationMs: number;
1598
+ p50: number;
1599
+ p95: number;
1600
+ successCount: number;
1601
+ failureCount: number;
1602
+ lastUpdated: number;
1603
+ }
1604
+ interface ProviderPerformanceStats {
1605
+ providerDid: string;
1606
+ avgDurationMs: number;
1607
+ p50: number;
1608
+ p95: number;
1609
+ successCount: number;
1610
+ failureCount: number;
1611
+ lastUpdated?: number;
1612
+ capabilities: ProviderCapabilityPerformance[];
1613
+ }
1614
+ declare class PerformanceTracker {
1615
+ private readonly db;
1616
+ private readonly now;
1617
+ private readonly maxSamplesPerCapability;
1618
+ constructor(options?: PerformanceTrackerOptions);
1619
+ recordCompletion(provider: string, capability: string, durationMs: number, success: boolean): void;
1620
+ getEstimatedLatency(provider: string, capability: string): number | undefined;
1621
+ getProviderStats(provider: string): ProviderPerformanceStats;
1622
+ close(): void;
1623
+ }
1624
+
1625
+ interface ProviderExecutionOutput {
1626
+ value: unknown;
1627
+ aggregateValue?: unknown;
1628
+ cost?: bigint;
1629
+ }
1630
+ interface FanOutExecutorOptions {
1631
+ executeProvider: (provider: ProviderScore, request: MultiProviderRequest, context: {
1632
+ signal: AbortSignal;
1633
+ }) => Promise<ProviderExecutionOutput>;
1634
+ circuitBreaker?: Pick<CircuitBreaker, 'allowRequest' | 'recordSuccess' | 'recordFailure'>;
1635
+ performanceTracker?: Pick<PerformanceTracker, 'recordCompletion'>;
1636
+ now?: () => number;
1637
+ }
1638
+ declare class FanOutExecutor {
1639
+ private readonly options;
1640
+ private readonly now;
1641
+ constructor(options: FanOutExecutorOptions);
1642
+ execute(request: MultiProviderRequest, providers: ProviderScore[]): Promise<MultiProviderResult>;
1643
+ private runProvider;
1644
+ private waitForFirstSuccess;
1645
+ private waitForMajority;
1646
+ }
1647
+
1648
+ interface ProviderSelectionWeights {
1649
+ reputation: number;
1650
+ price: number;
1651
+ speed: number;
1652
+ }
1653
+ interface ProviderSelectorOptions {
1654
+ circuitBreaker?: Pick<CircuitBreaker, 'isOpen'>;
1655
+ performanceTracker?: Pick<PerformanceTracker, 'getEstimatedLatency'>;
1656
+ reputationCalculator?: ReputationScoreCalculator;
1657
+ }
1658
+ declare class ProviderSelector {
1659
+ private readonly circuitBreaker?;
1660
+ private readonly performanceTracker?;
1661
+ private readonly reputationCalculator;
1662
+ private roundRobinOffset;
1663
+ constructor(options?: ProviderSelectorOptions);
1664
+ rankProviders(agents: AgentCard[], capability: string, weights?: Partial<ProviderSelectionWeights>): ProviderScore[];
1665
+ selectProviders(agents: AgentCard[], capability: string, strategy: ProviderSelectionStrategy, count: number, weights?: Partial<ProviderSelectionWeights>): ProviderScore[];
1666
+ selectCheapest(providers: ProviderScore[], count: number): ProviderScore[];
1667
+ selectFastest(providers: ProviderScore[], count: number): ProviderScore[];
1668
+ selectHighestReputation(providers: ProviderScore[], count: number): ProviderScore[];
1669
+ selectRoundRobin(providers: ProviderScore[], count: number): ProviderScore[];
1670
+ selectWeighted(providers: ProviderScore[], count: number, weights?: Partial<ProviderSelectionWeights>): ProviderScore[];
1671
+ private toProviderScore;
1672
+ private applyCompositeScores;
1673
+ }
1674
+
1675
+ export { type AcceptBidParams, type AcceptResolutionParams, type AcceptTaskParams, type AddStakeParams, type AdvancedAgentQueryDelegate, type AdvancedAgentQueryFilters, AgentCache, type ArbitrateDisputeParams, type AuthMode, type AuthProvider, BlobIntegrityError, type BlobMetadata, type BlobStore, type BrowseOpenTasksFilters, CLOCK_OBJECT_ID, type CancelTaskParams, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerState, type ClaimPaymentParams, type CompleteMeteredTaskParams, type CompleteTaskParams, type ContentAddressedBlob, type ContractConfig, type CursorStore, DEFAULT_METERING_CHUNK_SIZE, DEFAULT_RELAY_HEARTBEAT_FRESHNESS_MS, DEFAULT_WALRUS_AGGREGATOR_URL, DEFAULT_WALRUS_EPOCHS, DEFAULT_WALRUS_MAX_BLOB_SIZE, DEFAULT_WALRUS_PUBLISHER_URL, DEFAULT_WALRUS_RETRY_ATTEMPTS, DEFAULT_WALRUS_RETRY_DELAY_MS, DEFAULT_WALRUS_TIMEOUT_MS, type DeactivateAgentParams, type DepositStakeParams, type DeviceFlowStatus, DisputeClient, Ed25519AuthProvider, EncryptedBlobStore, type EncryptedPayload, EventSubscription, EvmWallet, type EvmWalletConfig, type ExecuteTransactionOptions, FanOutExecutor, type FanOutExecutorOptions, FileKeyStore, FilesystemBlobStore, HashChain, HybridBlobStore, type HybridBlobStoreOptions, type KeyStore, KeychainStore, MarketplaceClient, MeshSuiClient, type MeteredResultEnvelope, type OAuthConfig, type OAuthProvider, type OAuthTokenResponse, type OpenDisputeParams, PERMIT2_ADDRESS, PaymentRailSelector, PerformanceTracker, type PerformanceTrackerOptions, type PlaceBidParams, type PostMeteredTaskParams, type PostTaskParams, type ProviderCapabilityPerformance, type ProviderExecutionOutput, type ProviderPerformanceStats, type ProviderSelectionWeights, ProviderSelector, type ProviderSelectorOptions, type PublishReputationAnchorParams, type RailSelectionContext, type ReactivateAgentParams, type RecordRelayRoutingParams, type RefreshSessionOptions, type RefundExpiredTaskParams, type RegisterAgentParams, type RegisterRelayParams, RegistryClient, type RejectBidParams, RelayConsumerClient, RelayDiscovery, type RelayDiscoveryOptions, type RelayMutationParams, RelayRegistryClient, type RelayRegistryContractConfig, type ReleaseMeteredPaymentParams, type ReleasePaymentParams, ReputationAnchorClient, ReputationEventPublisher, ReputationScoreCalculator, ReputationStore, type RespondToDisputeParams, ResultVerifier, STAKING_COOLDOWN_MS, type SelectedPaymentRail, SessionExpiredError, type SessionExpiredErrorOptions, SessionRefreshError, type SessionRefreshErrorOptions, type SessionRefreshPolicy, SessionState, type SessionStateChangeCallback, type SessionStateChangeEvent, type SetEncryptionKeyParams, type SimpleKeypair, type SlashStakeParams, type SpendingLogEntry, type SpendingPolicyConfig, type SpendingPolicyDecision, SpendingPolicyEngine, SqliteCursorStore, StakingClient, type StakingContractConfig, type StartDeactivationParams, type StoredBlob, type StoredZkLoginSession, StreamingPaymentManager, type StreamingPaymentManagerOptions, SuiTransactionExecutionError, TaskClient, USDC_ADDRESS, type UpdateAgentParams, type UpdateCapabilitiesParams, UsageMeter, type UsageMeterOptions, type WalrusBlobMetadata, type WalrusBlobReference, WalrusBlobStore, type WalrusBlobStoreConfig, WalrusBlobTooLargeError, WalrusHttpError, type WalrusLogger, WalrusNetworkError, WalrusRequestError, WalrusResponseError, WalrusTimeoutError, type WithdrawBidParams, type WithdrawStakeParams, type X25519KeyPair, X402Client, type X402PaymentRequest, type X402PaymentSignature, type ZkLoginAuthorizationRequest, type ZkLoginPendingSession, type ZkLoginProof, ZkLoginProvider, type ZkLoginProviderOptions, type ZkLoginSession, ZkLoginSessionStore, type ZkLoginSessionStoreOptions, buildAcceptBidTx, buildAcceptResolutionTx, buildAcceptTaskTx, buildAddStakeTx, buildArbitrateDisputeTx, buildCancelTaskTx, buildClaimPaymentTx, buildCompleteMeteredTaskTx, buildCompleteTaskTx, buildDeactivateAgentTx, buildDeactivateRelayTx, buildDepositStakeTx, buildHeartbeatRelayTx, buildMerkleTree, buildOpenDisputeTx, buildPlaceBidTx, buildPostMeteredTaskTx, buildPostTaskTx, buildPublishReputationAnchorTx, buildReactivateAgentTx, buildRecordRelayRoutingTx, buildRefundExpiredTaskTx, buildRegisterAgentTx, buildRegisterRelayTx, buildRejectBidTx, buildReleaseMeteredPaymentTx, buildReleasePaymentTx, buildRespondToDisputeTx, buildSetEncryptionKeyTx, buildSlashExpiredEscrowTx, buildSlashNonDeliveryTx, buildStartDeactivationTx, buildUpdateAgentTx, buildUpdateCapabilitiesTx, buildWithdrawBidTx, buildWithdrawStakeTx, computeSharedSecret, createDID, createKeyStore, createMeteredResultEnvelope, createMeteringSeed, createPkcePair, createRelaySuiPaymentProof, createSuiClient, createWalrusBlobReference, decodeMeteredResult, decodeRelaySuiPaymentProof, decryptFromSender, deriveEvmKey, ed25519ToX25519, encodeRelaySuiPaymentProof, encryptForRecipient, generateKeypair, generateX25519KeyPair, getMeteredResultUnits, identityKeyExists, isEncryptedPayload, isValidDID, keypairFromSecretKey, loadOrCreateKeypair, parseDID, parseEncryptedPayload, parseMeteredResultEnvelope, parseRawEvent, parseWalrusBlobReference, pollDeviceFlow, serializeEncryptedPayload, serializeMeteredResultEnvelope, sign, signString, splitIntoMeteringUnits, startDeviceFlow, verify, verifyMerkleProof, verifyRelaySuiPaymentProof };