@syfthub/sdk 0.1.0 → 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.
package/dist/index.d.ts CHANGED
@@ -21,8 +21,8 @@ interface AuthTokens {
21
21
  * Internal HTTP client for making API requests.
22
22
  *
23
23
  * Handles:
24
- * - Bearer token authentication
25
- * - Automatic token refresh on 401 responses
24
+ * - Bearer token authentication (JWT or API token)
25
+ * - Automatic token refresh on 401 responses (JWT only)
26
26
  * - JSON serialization/deserialization
27
27
  * - snake_case <-> camelCase conversion
28
28
  * - Error handling and exception mapping
@@ -32,6 +32,7 @@ declare class HTTPClient {
32
32
  private readonly timeout;
33
33
  private accessToken;
34
34
  private refreshToken;
35
+ private apiToken;
35
36
  private isRefreshing;
36
37
  private refreshPromise;
37
38
  /**
@@ -42,21 +43,38 @@ declare class HTTPClient {
42
43
  */
43
44
  constructor(baseUrl: string, timeout?: number);
44
45
  /**
45
- * Set authentication tokens.
46
+ * Set JWT authentication tokens.
47
+ * Clears any API token if set.
46
48
  */
47
49
  setTokens(access: string, refresh: string): void;
48
50
  /**
49
- * Get current authentication tokens.
51
+ * Set API token for authentication.
52
+ * Clears any JWT tokens if set.
53
+ *
54
+ * @param token - The API token (starts with "syft_")
55
+ */
56
+ setApiToken(token: string): void;
57
+ /**
58
+ * Get current JWT authentication tokens.
59
+ * Returns null if using API token authentication.
50
60
  */
51
61
  getTokens(): AuthTokens | null;
52
62
  /**
53
- * Clear authentication tokens.
63
+ * Check if using API token authentication.
64
+ */
65
+ isUsingApiToken(): boolean;
66
+ /**
67
+ * Clear all authentication (JWT and API tokens).
54
68
  */
55
69
  clearTokens(): void;
56
70
  /**
57
- * Check if the client has valid tokens.
71
+ * Check if the client has valid authentication (JWT or API token).
58
72
  */
59
73
  hasTokens(): boolean;
74
+ /**
75
+ * Get the current bearer token (API token or JWT access token).
76
+ */
77
+ private getBearerToken;
60
78
  /**
61
79
  * Make a GET request.
62
80
  */
@@ -108,6 +126,184 @@ declare class HTTPClient {
108
126
  private attemptTokenRefresh;
109
127
  }
110
128
 
129
+ /**
130
+ * API Token models for managing personal access tokens.
131
+ */
132
+ /**
133
+ * Permission scopes for API tokens.
134
+ */
135
+ type APITokenScope = 'read' | 'write' | 'full';
136
+ /**
137
+ * API token representation (without the actual token value).
138
+ */
139
+ interface APIToken {
140
+ /** Unique token identifier */
141
+ id: number;
142
+ /** User-friendly label for the token */
143
+ name: string;
144
+ /** First characters of the token for identification (e.g., 'syft_pat_aB3d') */
145
+ tokenPrefix: string;
146
+ /** Permission scopes */
147
+ scopes: readonly APITokenScope[];
148
+ /** Expiration timestamp, null if never expires */
149
+ expiresAt: Date | null;
150
+ /** Last time the token was used for authentication */
151
+ lastUsedAt: Date | null;
152
+ /** IP address from the last authentication */
153
+ lastUsedIp: string | null;
154
+ /** Whether the token is active (not revoked) */
155
+ isActive: boolean;
156
+ /** When the token was created */
157
+ createdAt: Date;
158
+ /** When the token was last updated */
159
+ updatedAt: Date | null;
160
+ }
161
+ /**
162
+ * Response when creating a new API token.
163
+ * IMPORTANT: The token is only shown ONCE in this response!
164
+ */
165
+ interface APITokenCreateResponse extends APIToken {
166
+ /** The full API token. SAVE THIS NOW - it will not be shown again! */
167
+ token: string;
168
+ }
169
+ /**
170
+ * Input for creating a new API token.
171
+ */
172
+ interface CreateAPITokenInput {
173
+ /** User-friendly label for the token (e.g., 'CI/CD Pipeline') */
174
+ name: string;
175
+ /** Permission scopes. Defaults to ['full'] if not specified. */
176
+ scopes?: APITokenScope[];
177
+ /** Optional expiration timestamp. Null means never expires. */
178
+ expiresAt?: Date | null;
179
+ }
180
+ /**
181
+ * Input for updating an API token.
182
+ */
183
+ interface UpdateAPITokenInput {
184
+ /** New name for the token */
185
+ name: string;
186
+ }
187
+ /**
188
+ * Response for listing API tokens.
189
+ */
190
+ interface APITokenListResponse {
191
+ /** List of API tokens */
192
+ tokens: APIToken[];
193
+ /** Total number of tokens */
194
+ total: number;
195
+ }
196
+
197
+ /**
198
+ * Resource for managing API tokens.
199
+ */
200
+
201
+ /**
202
+ * Resource for managing API tokens.
203
+ *
204
+ * API tokens provide an alternative to username/password authentication.
205
+ * They are ideal for CI/CD pipelines, scripts, and programmatic access.
206
+ *
207
+ * @example
208
+ * // Create a new token
209
+ * const result = await client.apiTokens.create({
210
+ * name: 'CI/CD Pipeline',
211
+ * scopes: ['write'],
212
+ * });
213
+ * console.log('Save this token:', result.token);
214
+ *
215
+ * // List all tokens
216
+ * const { tokens } = await client.apiTokens.list();
217
+ *
218
+ * // Revoke a token
219
+ * await client.apiTokens.revoke(tokenId);
220
+ */
221
+ declare class APITokensResource {
222
+ private readonly http;
223
+ constructor(http: HTTPClient);
224
+ /**
225
+ * Create a new API token.
226
+ *
227
+ * IMPORTANT: The returned token is only shown ONCE!
228
+ * Make sure to save it immediately - it cannot be retrieved later.
229
+ *
230
+ * @param input - Token creation options
231
+ * @returns The created token with the full token value
232
+ *
233
+ * @example
234
+ * const result = await client.apiTokens.create({
235
+ * name: 'CI/CD Pipeline',
236
+ * scopes: ['write'],
237
+ * expiresAt: new Date('2025-12-31'),
238
+ * });
239
+ *
240
+ * // SAVE THIS TOKEN - it will not be shown again!
241
+ * console.log(result.token);
242
+ */
243
+ create(input: CreateAPITokenInput): Promise<APITokenCreateResponse>;
244
+ /**
245
+ * List all API tokens for the current user.
246
+ *
247
+ * By default, only active tokens are returned.
248
+ * Note: The full token value is never returned - only the prefix.
249
+ *
250
+ * @param options - List options
251
+ * @returns List of tokens and total count
252
+ *
253
+ * @example
254
+ * // List active tokens
255
+ * const { tokens, total } = await client.apiTokens.list();
256
+ *
257
+ * // Include revoked tokens
258
+ * const all = await client.apiTokens.list({ includeInactive: true });
259
+ */
260
+ list(options?: {
261
+ includeInactive?: boolean;
262
+ skip?: number;
263
+ limit?: number;
264
+ }): Promise<APITokenListResponse>;
265
+ /**
266
+ * Get a single API token by ID.
267
+ *
268
+ * Note: The full token value is never returned - only the prefix.
269
+ *
270
+ * @param tokenId - The token ID
271
+ * @returns The token details
272
+ *
273
+ * @example
274
+ * const token = await client.apiTokens.get(123);
275
+ * console.log(token.name, token.lastUsedAt);
276
+ */
277
+ get(tokenId: number): Promise<APIToken>;
278
+ /**
279
+ * Update an API token's name.
280
+ *
281
+ * Only the name can be updated. Scopes and expiration cannot be
282
+ * changed after creation.
283
+ *
284
+ * @param tokenId - The token ID
285
+ * @param input - Update options
286
+ * @returns The updated token
287
+ *
288
+ * @example
289
+ * const updated = await client.apiTokens.update(123, {
290
+ * name: 'New Name',
291
+ * });
292
+ */
293
+ update(tokenId: number, input: UpdateAPITokenInput): Promise<APIToken>;
294
+ /**
295
+ * Revoke an API token.
296
+ *
297
+ * The token becomes immediately unusable. This action cannot be undone.
298
+ *
299
+ * @param tokenId - The token ID to revoke
300
+ *
301
+ * @example
302
+ * await client.apiTokens.revoke(123);
303
+ */
304
+ revoke(tokenId: number): Promise<void>;
305
+ }
306
+
111
307
  /**
112
308
  * Visibility levels for endpoints.
113
309
  */
@@ -116,7 +312,7 @@ declare const Visibility: {
116
312
  readonly PUBLIC: "public";
117
313
  /** Only visible to the owner and collaborators */
118
314
  readonly PRIVATE: "private";
119
- /** Visible to authenticated users within the organization */
315
+ /** Behaves like private only visible to the owner */
120
316
  readonly INTERNAL: "internal";
121
317
  };
122
318
  type Visibility = (typeof Visibility)[keyof typeof Visibility];
@@ -128,6 +324,10 @@ declare const EndpointType: {
128
324
  readonly MODEL: "model";
129
325
  /** Data source endpoint */
130
326
  readonly DATA_SOURCE: "data_source";
327
+ /** Both model and data source endpoint */
328
+ readonly MODEL_DATA_SOURCE: "model_data_source";
329
+ /** Agent endpoint with session-based interaction */
330
+ readonly AGENT: "agent";
131
331
  };
132
332
  type EndpointType = (typeof EndpointType)[keyof typeof EndpointType];
133
333
  /**
@@ -142,18 +342,6 @@ declare const UserRole: {
142
342
  readonly GUEST: "guest";
143
343
  };
144
344
  type UserRole = (typeof UserRole)[keyof typeof UserRole];
145
- /**
146
- * Organization member roles.
147
- */
148
- declare const OrganizationRole: {
149
- /** Organization owner with full control */
150
- readonly OWNER: "owner";
151
- /** Administrator with management privileges */
152
- readonly ADMIN: "admin";
153
- /** Regular member */
154
- readonly MEMBER: "member";
155
- };
156
- type OrganizationRole = (typeof OrganizationRole)[keyof typeof OrganizationRole];
157
345
 
158
346
  /**
159
347
  * User account information.
@@ -170,6 +358,12 @@ interface User {
170
358
  readonly updatedAt: Date | null;
171
359
  /** Domain for endpoint URL construction (e.g., "api.example.com" or "api.example.com:8080") */
172
360
  readonly domain: string | null;
361
+ /** Custom aggregator URL for RAG/chat workflows */
362
+ readonly aggregatorUrl: string | null;
363
+ /** Markdown bio shown on the user's public profile */
364
+ readonly bio?: string | null;
365
+ /** Whether the user's email is shown on their public profile */
366
+ readonly isEmailPublic?: boolean;
173
367
  }
174
368
  /**
175
369
  * Input for user registration.
@@ -204,6 +398,54 @@ interface UserUpdateInput {
204
398
  avatarUrl?: string;
205
399
  /** Domain for endpoint URL construction (no protocol, e.g., "api.example.com:8080") */
206
400
  domain?: string;
401
+ /** Custom aggregator URL for RAG/chat workflows */
402
+ aggregatorUrl?: string;
403
+ /** Markdown bio shown on the user's public profile */
404
+ bio?: string;
405
+ /** Whether the user's email is shown on their public profile */
406
+ isEmailPublic?: boolean;
407
+ }
408
+ /**
409
+ * Result of user registration.
410
+ *
411
+ * When `requiresEmailVerification` is true, tokens are null and the client
412
+ * must call `auth.verifyOtp()` before the user can log in.
413
+ */
414
+ interface RegisterResult {
415
+ readonly user: User;
416
+ /** Whether the user must verify their email via OTP before receiving tokens. */
417
+ readonly requiresEmailVerification: boolean;
418
+ }
419
+ /**
420
+ * Input for verifying a registration OTP.
421
+ */
422
+ interface VerifyOTPInput {
423
+ email: string;
424
+ /** 6-digit numeric code sent to the user's email */
425
+ code: string;
426
+ }
427
+ /**
428
+ * Input for requesting a password reset.
429
+ */
430
+ interface PasswordResetRequestInput {
431
+ email: string;
432
+ }
433
+ /**
434
+ * Input for confirming a password reset with OTP.
435
+ */
436
+ interface PasswordResetConfirmInput {
437
+ email: string;
438
+ /** 6-digit numeric OTP code */
439
+ code: string;
440
+ newPassword: string;
441
+ }
442
+ /**
443
+ * Platform authentication configuration (from GET /auth/config).
444
+ */
445
+ interface AuthConfig {
446
+ readonly requireEmailVerification: boolean;
447
+ readonly smtpConfigured: boolean;
448
+ readonly passwordResetEnabled: boolean;
207
449
  }
208
450
  /**
209
451
  * Input for changing password.
@@ -224,6 +466,75 @@ interface AccountingCredentials {
224
466
  /** Password for authenticating with the accounting service (null if not configured) */
225
467
  readonly password: string | null;
226
468
  }
469
+ /**
470
+ * Input for sending a heartbeat.
471
+ */
472
+ interface HeartbeatInput {
473
+ /** Full URL of this space (e.g., "https://myspace.example.com") */
474
+ url: string;
475
+ /** Time-to-live in seconds (1-3600, server caps at 600). Default is 300. */
476
+ ttlSeconds?: number;
477
+ }
478
+ /**
479
+ * Response from the heartbeat endpoint.
480
+ *
481
+ * The heartbeat mechanism allows SyftAI Spaces to signal their availability
482
+ * to SyftHub. The server returns the effective TTL (which may be capped)
483
+ * and the expiration time.
484
+ */
485
+ interface HeartbeatResponse {
486
+ /** Status of the heartbeat (typically 'ok') */
487
+ readonly status: string;
488
+ /** When the heartbeat was received (ISO 8601 string) */
489
+ readonly receivedAt: Date;
490
+ /** When the heartbeat will expire (ISO 8601 string) */
491
+ readonly expiresAt: Date;
492
+ /** Extracted domain from the URL */
493
+ readonly domain: string;
494
+ /** Effective TTL applied (may be capped by server) */
495
+ readonly ttlSeconds: number;
496
+ }
497
+ /**
498
+ * A user's aggregator configuration.
499
+ *
500
+ * Aggregators are custom RAG orchestration service endpoints that users can
501
+ * configure to use for chat operations. Each user can have multiple aggregator
502
+ * configurations, with one set as the default.
503
+ */
504
+ interface UserAggregator {
505
+ /** Unique aggregator configuration ID */
506
+ readonly id: number;
507
+ /** Owner user ID */
508
+ readonly userId: number;
509
+ /** Display name for the aggregator */
510
+ readonly name: string;
511
+ /** Aggregator service URL */
512
+ readonly url: string;
513
+ /** Whether this is the user's default aggregator */
514
+ readonly isDefault: boolean;
515
+ /** When the aggregator was created */
516
+ readonly createdAt: Date;
517
+ /** When the aggregator was last updated */
518
+ readonly updatedAt: Date;
519
+ }
520
+ /**
521
+ * Input for creating an aggregator configuration.
522
+ */
523
+ interface UserAggregatorCreateInput {
524
+ /** Display name for the aggregator */
525
+ name: string;
526
+ /** Aggregator service URL */
527
+ url: string;
528
+ }
529
+ /**
530
+ * Input for updating an aggregator configuration.
531
+ */
532
+ interface UserAggregatorUpdateInput {
533
+ /** New display name (optional) */
534
+ name?: string;
535
+ /** New aggregator URL (optional) */
536
+ url?: string;
537
+ }
227
538
 
228
539
  /**
229
540
  * Policy configuration for an endpoint.
@@ -249,8 +560,7 @@ interface Connection {
249
560
  */
250
561
  interface Endpoint {
251
562
  readonly id: number;
252
- readonly userId: number | null;
253
- readonly organizationId: number | null;
563
+ readonly userId: number;
254
564
  readonly name: string;
255
565
  readonly slug: string;
256
566
  readonly description: string;
@@ -287,6 +597,42 @@ interface EndpointPublic {
287
597
  readonly createdAt: Date;
288
598
  readonly updatedAt: Date;
289
599
  }
600
+ /**
601
+ * Search result with relevance score from semantic search.
602
+ *
603
+ * Extends the public endpoint fields with a relevance score indicating
604
+ * how well the endpoint matches the search query.
605
+ */
606
+ interface EndpointSearchResult {
607
+ readonly name: string;
608
+ readonly slug: string;
609
+ readonly description: string;
610
+ readonly type: EndpointType;
611
+ readonly ownerUsername: string;
612
+ /** Number of contributors (user IDs not exposed for privacy) */
613
+ readonly contributorsCount: number;
614
+ readonly version: string;
615
+ readonly readme: string;
616
+ readonly tags: readonly string[];
617
+ readonly starsCount: number;
618
+ readonly policies: readonly Policy[];
619
+ readonly connect: readonly Connection[];
620
+ readonly createdAt: Date;
621
+ readonly updatedAt: Date;
622
+ /** Relevance score from semantic search (0.0-1.0) */
623
+ readonly relevanceScore: number;
624
+ }
625
+ /**
626
+ * Options for semantic search.
627
+ */
628
+ interface SearchOptions {
629
+ /** Maximum number of results to return (default: 10) */
630
+ topK?: number;
631
+ /** Filter by endpoint type */
632
+ type?: EndpointType;
633
+ /** Minimum relevance score threshold (0.0-1.0, default: 0.0) */
634
+ minScore?: number;
635
+ }
290
636
  /**
291
637
  * Input for creating a new endpoint.
292
638
  */
@@ -317,13 +663,6 @@ interface EndpointUpdateInput {
317
663
  connect?: Connection[];
318
664
  contributors?: number[];
319
665
  }
320
- /**
321
- * Get the owner type for an endpoint.
322
- *
323
- * @param endpoint - The endpoint to check
324
- * @returns 'user' if user-owned, 'organization' if org-owned
325
- */
326
- declare function getEndpointOwnerType(endpoint: Endpoint): 'user' | 'organization';
327
666
  /**
328
667
  * Get the full path for a public endpoint (owner/slug format).
329
668
  *
@@ -331,148 +670,82 @@ declare function getEndpointOwnerType(endpoint: Endpoint): 'user' | 'organizatio
331
670
  * @returns The path in "owner/slug" format
332
671
  */
333
672
  declare function getEndpointPublicPath(endpoint: EndpointPublic): string;
334
-
335
673
  /**
336
- * Accounting Models
674
+ * Response from the sync endpoints operation.
337
675
  *
338
- * Models for the external accounting service. The accounting service manages
339
- * user balances and transactions, and uses its own authentication separate
340
- * from SyftHub.
341
- */
342
- /**
343
- * Transaction status in the accounting service.
676
+ * Contains details about the sync operation including how many endpoints
677
+ * were deleted, how many were created, and the full list of created endpoints.
344
678
  */
345
- declare const TransactionStatus: {
346
- /** Transaction created, awaiting confirmation */
347
- readonly PENDING: "pending";
348
- /** Transaction confirmed, funds transferred */
349
- readonly COMPLETED: "completed";
350
- /** Transaction cancelled, no funds transferred */
351
- readonly CANCELLED: "cancelled";
352
- };
353
- type TransactionStatus = (typeof TransactionStatus)[keyof typeof TransactionStatus];
354
- /**
355
- * Who created or resolved a transaction.
356
- */
357
- declare const CreatorType: {
358
- /** System-initiated transaction */
359
- readonly SYSTEM: "system";
360
- /** Sender-initiated transaction */
361
- readonly SENDER: "sender";
362
- /** Recipient-initiated transaction (delegated) */
363
- readonly RECIPIENT: "recipient";
364
- };
365
- type CreatorType = (typeof CreatorType)[keyof typeof CreatorType];
366
- /**
367
- * User from accounting service with balance.
368
- *
369
- * This represents the user's account in the external accounting service,
370
- * which is separate from the SyftHub user account.
371
- */
372
- interface AccountingUser {
373
- readonly id: string;
374
- readonly email: string;
375
- readonly balance: number;
376
- readonly organization: string | null;
679
+ interface SyncEndpointsResponse {
680
+ /** Number of endpoints created */
681
+ readonly synced: number;
682
+ /** Number of endpoints deleted */
683
+ readonly deleted: number;
684
+ /** List of created endpoints with full details */
685
+ readonly endpoints: readonly Endpoint[];
377
686
  }
687
+
378
688
  /**
379
- * Transaction record from accounting service.
380
- *
381
- * Transactions go through a lifecycle:
382
- * 1. Created (status=PENDING)
383
- * 2. Confirmed or Cancelled (status=COMPLETED or CANCELLED)
689
+ * Accounting Models (MPP Wallet)
384
690
  *
385
- * The createdBy field indicates who initiated the transaction:
386
- * - SENDER: Direct transaction by the payer
387
- * - RECIPIENT: Delegated transaction using a token
388
- * - SYSTEM: System-initiated transaction
389
- *
390
- * The resolvedBy field indicates who confirmed/cancelled.
391
- */
392
- interface Transaction {
393
- readonly id: string;
394
- readonly senderEmail: string;
395
- readonly recipientEmail: string;
396
- readonly amount: number;
397
- readonly status: TransactionStatus;
398
- readonly createdBy: CreatorType;
399
- readonly resolvedBy: CreatorType | null;
400
- readonly createdAt: Date;
401
- readonly resolvedAt: Date | null;
402
- readonly appName: string | null;
403
- readonly appEpPath: string | null;
404
- }
405
- /**
406
- * Input for creating a direct transaction.
691
+ * Models for the MPP wallet system. Replaces the previous external accounting
692
+ * service models with wallet-based types for the Micropayment Protocol.
407
693
  */
408
- interface CreateTransactionInput {
409
- /** Email of the recipient */
410
- recipientEmail: string;
411
- /** Amount to transfer (must be > 0) */
412
- amount: number;
413
- /** Optional app name for context (e.g., "syftai-space") */
414
- appName?: string;
415
- /** Optional endpoint path for context (e.g., "alice/model") */
416
- appEpPath?: string;
417
- }
418
694
  /**
419
- * Input for creating a delegated transaction.
695
+ * Wallet information for the current user.
420
696
  */
421
- interface CreateDelegatedTransactionInput {
422
- /** Email of the sender who created the token */
423
- senderEmail: string;
424
- /** Amount to transfer (must be > 0) */
425
- amount: number;
426
- /** JWT token from sender's createTransactionToken() */
427
- token: string;
697
+ interface WalletInfo {
698
+ /** Wallet address (null if no wallet configured) */
699
+ address: string | null;
700
+ /** Whether a wallet exists for this user */
701
+ exists: boolean;
428
702
  }
429
703
  /**
430
- * Input for updating password.
704
+ * Wallet balance and recent activity.
431
705
  */
432
- interface UpdatePasswordInput {
433
- /** Current password for verification */
434
- currentPassword: string;
435
- /** New password to set */
436
- newPassword: string;
706
+ interface WalletBalance {
707
+ /** Current balance amount */
708
+ balance: number;
709
+ /** Currency identifier */
710
+ currency: string;
711
+ /** Recent transactions for this wallet */
712
+ recent_transactions: WalletTransaction[];
713
+ /** Whether a wallet is configured */
714
+ wallet_configured: boolean;
437
715
  }
438
716
  /**
439
- * Raw transaction response from API (before date parsing).
717
+ * A wallet transaction record.
440
718
  */
441
- interface TransactionResponse {
719
+ interface WalletTransaction {
720
+ /** Unique transaction identifier */
442
721
  id: string;
443
- senderEmail: string;
444
- recipientEmail: string;
722
+ /** Email of the sender */
723
+ sender_email: string;
724
+ /** Email of the recipient */
725
+ recipient_email: string;
726
+ /** Transaction amount */
445
727
  amount: number;
446
- status: TransactionStatus;
447
- createdBy: CreatorType;
448
- resolvedBy: CreatorType | null;
449
- createdAt: string;
450
- resolvedAt: string | null;
451
- appName: string | null;
452
- appEpPath: string | null;
728
+ /** Transaction status (e.g., "completed", "pending") */
729
+ status: string;
730
+ /** When the transaction was created (ISO 8601) */
731
+ created_at: string;
732
+ /** App name associated with the transaction */
733
+ app_name?: string;
734
+ /** Endpoint path associated with the transaction */
735
+ app_ep_path?: string;
453
736
  }
454
737
  /**
455
- * Token response from createTransactionToken.
738
+ * Response from transaction tokens endpoint.
739
+ *
740
+ * @deprecated Transaction tokens are no longer used. Payments are handled
741
+ * via the MPP 402 flow. Kept for backward compatibility with getTransactionTokens().
456
742
  */
457
- interface TransactionTokenResponse {
458
- token: string;
743
+ interface TransactionTokensResponse {
744
+ /** Mapping of owner_username to transaction token */
745
+ tokens: Record<string, string>;
746
+ /** Mapping of owner_username to error message (for failed tokens) */
747
+ errors: Record<string, string>;
459
748
  }
460
- /**
461
- * Parse a transaction response into a Transaction object.
462
- */
463
- declare function parseTransaction(response: TransactionResponse): Transaction;
464
- /**
465
- * Check if a transaction is pending.
466
- */
467
- declare function isTransactionPending(tx: Transaction): boolean;
468
- /**
469
- * Check if a transaction is completed.
470
- */
471
- declare function isTransactionCompleted(tx: Transaction): boolean;
472
- /**
473
- * Check if a transaction is cancelled.
474
- */
475
- declare function isTransactionCancelled(tx: Transaction): boolean;
476
749
 
477
750
  /**
478
751
  * Chat-related types for the SyftHub SDK.
@@ -579,6 +852,8 @@ interface ChatResponse {
579
852
  metadata: ChatMetadata;
580
853
  /** Token usage if available */
581
854
  usage?: TokenUsage;
855
+ /** Normalized contribution scores per source (owner/slug to fraction 0-1) */
856
+ profitShare?: Record<string, number>;
582
857
  }
583
858
  /**
584
859
  * A chat message for model queries.
@@ -609,6 +884,16 @@ interface ChatOptions {
609
884
  similarityThreshold?: number;
610
885
  /** AbortSignal for request cancellation */
611
886
  signal?: AbortSignal;
887
+ /** Custom aggregator URL to use instead of the default */
888
+ aggregatorUrl?: string;
889
+ /** Peer token for NATS tunneling (auto-fetched if tunneling endpoints detected) */
890
+ peerToken?: string;
891
+ /** Peer channel for NATS replies (auto-fetched if tunneling endpoints detected) */
892
+ peerChannel?: string;
893
+ /** Use guest mode for unauthenticated access to policy-free endpoints */
894
+ guestMode?: boolean;
895
+ /** Conversation history (prior turns) for multi-turn context */
896
+ messages?: Message[];
612
897
  }
613
898
  /**
614
899
  * Options for querying a data source directly.
@@ -664,16 +949,43 @@ interface RetrievalCompleteEvent {
664
949
  totalDocuments: number;
665
950
  timeMs: number;
666
951
  }
952
+ /**
953
+ * Fired when document reranking begins (after all sources complete).
954
+ */
955
+ interface RerankingStartEvent {
956
+ type: 'reranking_start';
957
+ /** Number of documents being reranked */
958
+ documents: number;
959
+ }
960
+ /**
961
+ * Fired when document reranking completes.
962
+ */
963
+ interface RerankingCompleteEvent {
964
+ type: 'reranking_complete';
965
+ /** Number of documents after reranking */
966
+ documents: number;
967
+ /** Time taken for reranking in milliseconds */
968
+ timeMs: number;
969
+ }
667
970
  /**
668
971
  * Fired when model generation begins.
669
972
  */
670
973
  interface GenerationStartEvent {
671
974
  type: 'generation_start';
672
975
  }
976
+ /**
977
+ * Fired periodically during non-streaming model generation to indicate progress.
978
+ * Emitted every ~3 seconds while waiting for the model response.
979
+ */
980
+ interface GenerationHeartbeatEvent {
981
+ type: 'generation_heartbeat';
982
+ /** Milliseconds elapsed since generation_start */
983
+ elapsedMs: number;
984
+ }
673
985
  /**
674
986
  * Fired for each token from the model.
675
987
  */
676
- interface TokenEvent {
988
+ interface TokenEvent$1 {
677
989
  type: 'token';
678
990
  content: string;
679
991
  }
@@ -689,6 +1001,14 @@ interface DoneEvent {
689
1001
  metadata: ChatMetadata;
690
1002
  /** Token usage if available (only from non-streaming mode) */
691
1003
  usage?: TokenUsage;
1004
+ /** Normalized contribution scores per source (owner/slug to fraction 0-1) */
1005
+ profitShare?: Record<string, number>;
1006
+ /**
1007
+ * Clean response text with attribution markers stripped.
1008
+ * Present when attribution ran (data sources were used). Frontends should
1009
+ * replace the streamed content with this field to remove raw <cite:[N]> tags.
1010
+ */
1011
+ response?: string;
692
1012
  }
693
1013
  /**
694
1014
  * Fired on error.
@@ -717,7 +1037,7 @@ interface ErrorEvent {
717
1037
  * }
718
1038
  * }
719
1039
  */
720
- type ChatStreamEvent = RetrievalStartEvent | SourceCompleteEvent | RetrievalCompleteEvent | GenerationStartEvent | TokenEvent | DoneEvent | ErrorEvent;
1040
+ type ChatStreamEvent = RetrievalStartEvent | SourceCompleteEvent | RetrievalCompleteEvent | RerankingStartEvent | RerankingCompleteEvent | GenerationStartEvent | GenerationHeartbeatEvent | TokenEvent$1 | DoneEvent | ErrorEvent;
721
1041
 
722
1042
  /**
723
1043
  * Authentication resource for login, register, and session management.
@@ -803,7 +1123,7 @@ declare class AuthResource {
803
1123
  * }
804
1124
  * }
805
1125
  */
806
- register(input: UserRegisterInput): Promise<User>;
1126
+ register(input: UserRegisterInput): Promise<RegisterResult>;
807
1127
  /**
808
1128
  * Login with username/email and password.
809
1129
  *
@@ -845,6 +1165,81 @@ declare class AuthResource {
845
1165
  * @throws {ValidationError} If new password doesn't meet requirements
846
1166
  */
847
1167
  changePassword(currentPassword: string, newPassword: string): Promise<void>;
1168
+ /**
1169
+ * Get the platform's authentication configuration.
1170
+ *
1171
+ * No authentication required. Use this to determine whether email
1172
+ * verification or password reset is available.
1173
+ *
1174
+ * @returns AuthConfig with feature flags
1175
+ */
1176
+ getAuthConfig(): Promise<AuthConfig>;
1177
+ /**
1178
+ * Verify a registration OTP and receive auth tokens.
1179
+ *
1180
+ * After registering when email verification is required, call this with
1181
+ * the 6-digit code sent to the user's email.
1182
+ *
1183
+ * Idempotent: if the user is already verified, tokens are issued immediately.
1184
+ *
1185
+ * @param input - Email and 6-digit code
1186
+ * @returns The authenticated User
1187
+ * @throws {APIError} If the code is invalid or max attempts exceeded
1188
+ */
1189
+ verifyOtp(input: VerifyOTPInput): Promise<User>;
1190
+ /**
1191
+ * Resend the registration OTP code.
1192
+ *
1193
+ * Rate-limited. Always returns successfully to prevent email enumeration.
1194
+ *
1195
+ * @param email - Email address to resend the OTP to
1196
+ */
1197
+ resendOtp(email: string): Promise<void>;
1198
+ /**
1199
+ * Request a password reset OTP.
1200
+ *
1201
+ * Always returns successfully to prevent email enumeration.
1202
+ * If SMTP is not configured on the server, this is a no-op.
1203
+ *
1204
+ * @param input - Email address for password reset
1205
+ */
1206
+ requestPasswordReset(input: PasswordResetRequestInput): Promise<void>;
1207
+ /**
1208
+ * Confirm a password reset with OTP and set a new password.
1209
+ *
1210
+ * @param input - Email, 6-digit code, and new password
1211
+ * @throws {APIError} If the code is invalid or max attempts exceeded
1212
+ */
1213
+ confirmPasswordReset(input: PasswordResetConfirmInput): Promise<void>;
1214
+ /**
1215
+ * Get a peer token for NATS communication with tunneling spaces.
1216
+ *
1217
+ * Peer tokens are short-lived credentials that allow the aggregator to
1218
+ * communicate with tunneling SyftAI Spaces via NATS pub/sub.
1219
+ *
1220
+ * @param targetUsernames - Usernames of the tunneling spaces to communicate with
1221
+ * @returns PeerTokenResponse with token, channel, expiry, and NATS URL
1222
+ * @throws {AuthenticationError} If not authenticated
1223
+ *
1224
+ * @example
1225
+ * const peer = await client.auth.getPeerToken(['alice', 'bob']);
1226
+ * console.log(`Peer channel: ${peer.peerChannel}, expires in ${peer.expiresIn}s`);
1227
+ */
1228
+ getPeerToken(targetUsernames: string[]): Promise<PeerTokenResponse>;
1229
+ /**
1230
+ * Get a guest peer token for NATS communication without authentication.
1231
+ *
1232
+ * Guest peer tokens are rate-limited by IP address. They use the same
1233
+ * response format as authenticated peer tokens.
1234
+ *
1235
+ * @param targetUsernames - Usernames of the tunneling spaces to communicate with
1236
+ * @returns PeerTokenResponse with token, channel, expiry, and NATS URL
1237
+ *
1238
+ * @example
1239
+ * const peer = await client.auth.getGuestPeerToken(['alice']);
1240
+ * console.log(`Guest peer channel: ${peer.peerChannel}`);
1241
+ */
1242
+ getGuestPeerToken(targetUsernames: string[]): Promise<PeerTokenResponse>;
848
1243
  /**
849
1244
  * Get a satellite token for a specific audience (target service).
850
1245
  *
@@ -880,27 +1275,65 @@ declare class AuthResource {
880
1275
  */
881
1276
  getSatelliteTokens(audiences: string[]): Promise<Map<string, string>>;
882
1277
  /**
883
- * Get transaction tokens for multiple endpoint owners.
1278
+ * Get a guest satellite token for a specific audience (target service).
1279
+ *
1280
+ * Guest tokens allow unauthenticated users to access policy-free endpoints.
1281
+ * No authentication is required to call this method.
884
1282
  *
885
- * Transaction tokens are short-lived JWTs that pre-authorize the endpoint owner
886
- * (recipient) to charge the current user (sender) for usage. These tokens are
887
- * created via the accounting service and passed to the aggregator.
1283
+ * @param audience - Target service identifier (username of the service owner)
1284
+ * @returns Satellite token response with token and expiry
1285
+ * @throws {ValidationError} If audience is invalid or inactive
888
1286
  *
889
- * This is used by the chat flow to enable billing for endpoint usage.
1287
+ * @example
1288
+ * // Get a guest token for querying alice's policy-free endpoints
1289
+ * const tokenResponse = await client.auth.getGuestSatelliteToken('alice');
1290
+ */
1291
+ getGuestSatelliteToken(audience: string): Promise<SatelliteTokenResponse>;
1292
+ /**
1293
+ * Get guest satellite tokens for multiple audiences in parallel.
890
1294
  *
891
- * @param ownerUsernames - Array of endpoint owner usernames
892
- * @returns TransactionTokensResponse with tokens map and any errors
893
- * @throws {AuthenticationError} If not authenticated
1295
+ * No authentication is required to call this method.
1296
+ *
1297
+ * @param audiences - Array of unique audience identifiers (usernames)
1298
+ * @returns Map of audience to satellite token
894
1299
  *
895
1300
  * @example
896
- * // Get transaction tokens for endpoint owners
897
- * const response = await client.auth.getTransactionTokens(['alice', 'bob']);
898
- * console.log(`Got ${Object.keys(response.tokens).length} tokens`);
899
- * if (Object.keys(response.errors).length > 0) {
900
- * console.log('Some tokens failed:', response.errors);
901
- * }
1301
+ * const tokens = await client.auth.getGuestSatelliteTokens(['alice', 'bob']);
1302
+ */
1303
+ getGuestSatelliteTokens(audiences: string[]): Promise<Map<string, string>>;
1304
+ /**
1305
+ * Get transaction tokens for multiple endpoint owners.
1306
+ *
1307
+ * @deprecated Transaction tokens are no longer needed. Payments are handled
1308
+ * via the MPP 402 flow. This method is kept for backward compatibility and
1309
+ * always returns empty tokens/errors.
1310
+ *
1311
+ * @param ownerUsernames - Array of endpoint owner usernames (ignored)
1312
+ * @returns TransactionTokensResponse with empty tokens and errors
902
1313
  */
903
1314
  getTransactionTokens(ownerUsernames: string[]): Promise<TransactionTokensResponse>;
1315
+ /**
1316
+ * Get the current access token (JWT or API token).
1317
+ *
1318
+ * This is used by the chat flow to pass the user's Hub token to the
1319
+ * aggregator for the MPP payment callback.
1320
+ *
1321
+ * @returns The current access token, or null if not authenticated
1322
+ */
1323
+ getAccessToken(): string | null;
1324
+ }
1325
+ /**
1326
+ * Response from peer token endpoint.
1327
+ */
1328
+ interface PeerTokenResponse {
1329
+ /** Short-lived token for NATS authentication */
1330
+ peerToken: string;
1331
+ /** Unique reply channel for receiving responses */
1332
+ peerChannel: string;
1333
+ /** Seconds until the token expires */
1334
+ expiresIn: number;
1335
+ /** NATS server URL for WebSocket connections */
1336
+ natsUrl: string;
904
1337
  }
905
1338
  /**
906
1339
  * Response from satellite token endpoint.
@@ -911,14 +1344,130 @@ interface SatelliteTokenResponse {
911
1344
  /** Seconds until the token expires */
912
1345
  expiresIn: number;
913
1346
  }
1347
+
914
1348
  /**
915
- * Response from transaction tokens endpoint.
1349
+ * Resource for managing user's aggregator configurations.
1350
+ *
1351
+ * Aggregators are custom RAG orchestration service endpoints that users can
1352
+ * configure to use for chat operations. Each user can have multiple aggregator
1353
+ * configurations, with one set as the default.
1354
+ *
1355
+ * The first aggregator created is automatically set as the default. Only one
1356
+ * aggregator can be the default at a time; setting a new default automatically
1357
+ * unsets the previous one.
1358
+ *
1359
+ * @example
1360
+ * // List all aggregators
1361
+ * const aggregators = await client.users.aggregators.list();
1362
+ * for (const agg of aggregators) {
1363
+ * console.log(`${agg.name}: ${agg.url}`);
1364
+ * }
1365
+ *
1366
+ * @example
1367
+ * // Create a new aggregator
1368
+ * const agg = await client.users.aggregators.create({
1369
+ * name: 'My Custom Aggregator',
1370
+ * url: 'https://my-aggregator.example.com'
1371
+ * });
1372
+ *
1373
+ * @example
1374
+ * // Set as default
1375
+ * const defaultAgg = await client.users.aggregators.setDefault(agg.id);
916
1376
  */
917
- interface TransactionTokensResponse {
918
- /** Mapping of owner_username to transaction token */
919
- tokens: Record<string, string>;
920
- /** Mapping of owner_username to error message (for failed tokens) */
921
- errors: Record<string, string>;
1377
+ declare class AggregatorsResource {
1378
+ private readonly http;
1379
+ constructor(http: HTTPClient);
1380
+ /**
1381
+ * List all aggregator configurations for the current user.
1382
+ *
1383
+ * @returns Array of UserAggregator objects
1384
+ * @throws {AuthenticationError} If not authenticated
1385
+ *
1386
+ * @example
1387
+ * const aggregators = await client.users.aggregators.list();
1388
+ * for (const agg of aggregators) {
1389
+ * if (agg.isDefault) {
1390
+ * console.log(`Default: ${agg.name}`);
1391
+ * }
1392
+ * }
1393
+ */
1394
+ list(): Promise<UserAggregator[]>;
1395
+ /**
1396
+ * Get a specific aggregator configuration by ID.
1397
+ *
1398
+ * @param aggregatorId - The aggregator ID
1399
+ * @returns The UserAggregator object
1400
+ * @throws {AuthenticationError} If not authenticated
1401
+ * @throws {NotFoundError} If aggregator not found
1402
+ *
1403
+ * @example
1404
+ * const agg = await client.users.aggregators.get(1);
1405
+ * console.log(`${agg.name}: ${agg.url}`);
1406
+ */
1407
+ get(aggregatorId: number): Promise<UserAggregator>;
1408
+ /**
1409
+ * Create a new aggregator configuration.
1410
+ *
1411
+ * The first aggregator created is automatically set as the default.
1412
+ *
1413
+ * @param input - Aggregator creation input
1414
+ * @returns The created UserAggregator object
1415
+ * @throws {AuthenticationError} If not authenticated
1416
+ * @throws {ValidationError} If input is invalid
1417
+ *
1418
+ * @example
1419
+ * const agg = await client.users.aggregators.create({
1420
+ * name: 'My Custom Aggregator',
1421
+ * url: 'https://my-aggregator.example.com'
1422
+ * });
1423
+ * console.log(`Created: ${agg.id}`);
1424
+ */
1425
+ create(input: UserAggregatorCreateInput): Promise<UserAggregator>;
1426
+ /**
1427
+ * Update an aggregator configuration.
1428
+ *
1429
+ * Only provided fields will be updated.
1430
+ *
1431
+ * @param aggregatorId - The aggregator ID to update
1432
+ * @param input - Fields to update
1433
+ * @returns The updated UserAggregator object
1434
+ * @throws {AuthenticationError} If not authenticated
1435
+ * @throws {NotFoundError} If aggregator not found
1436
+ * @throws {ValidationError} If input is invalid
1437
+ *
1438
+ * @example
1439
+ * const agg = await client.users.aggregators.update(1, {
1440
+ * name: 'Updated Name'
1441
+ * });
1442
+ */
1443
+ update(aggregatorId: number, input: UserAggregatorUpdateInput): Promise<UserAggregator>;
1444
+ /**
1445
+ * Delete an aggregator configuration.
1446
+ *
1447
+ * @param aggregatorId - The aggregator ID to delete
1448
+ * @throws {AuthenticationError} If not authenticated
1449
+ * @throws {NotFoundError} If aggregator not found
1450
+ *
1451
+ * @example
1452
+ * await client.users.aggregators.delete(1);
1453
+ */
1454
+ delete(aggregatorId: number): Promise<void>;
1455
+ /**
1456
+ * Set an aggregator as the default.
1457
+ *
1458
+ * Only one aggregator can be the default at a time. Setting a new default
1459
+ * automatically unsets the previous one.
1460
+ *
1461
+ * @param aggregatorId - The aggregator ID to set as default
1462
+ * @returns The updated UserAggregator object with isDefault=true
1463
+ * @throws {AuthenticationError} If not authenticated
1464
+ * @throws {NotFoundError} If aggregator not found
1465
+ *
1466
+ * @example
1467
+ * const agg = await client.users.aggregators.setDefault(2);
1468
+ * console.log(`${agg.name} is now the default`);
1469
+ */
1470
+ setDefault(aggregatorId: number): Promise<UserAggregator>;
922
1471
  }
923
1472
 
924
1473
  /**
@@ -938,10 +1487,41 @@ interface TransactionTokensResponse {
938
1487
  * @example
939
1488
  * // Check if email is available
940
1489
  * const available = await client.users.checkEmail('new@example.com');
1490
+ *
1491
+ * @example
1492
+ * // Manage aggregators
1493
+ * const aggregators = await client.users.aggregators.list();
1494
+ * const newAgg = await client.users.aggregators.create({
1495
+ * name: 'My Aggregator',
1496
+ * url: 'https://my-aggregator.example.com'
1497
+ * });
941
1498
  */
942
1499
  declare class UsersResource {
943
1500
  private readonly http;
1501
+ private _aggregators?;
944
1502
  constructor(http: HTTPClient);
1503
+ /**
1504
+ * Access aggregator management operations.
1505
+ *
1506
+ * @returns AggregatorsResource for managing user's aggregator configurations
1507
+ *
1508
+ * @example
1509
+ * // List aggregators
1510
+ * const aggregators = await client.users.aggregators.list();
1511
+ * for (const agg of aggregators) {
1512
+ * console.log(`${agg.name}: ${agg.url}`);
1513
+ * }
1514
+ *
1515
+ * // Create aggregator
1516
+ * const agg = await client.users.aggregators.create({
1517
+ * name: 'My Aggregator',
1518
+ * url: 'https://my-aggregator.example.com'
1519
+ * });
1520
+ *
1521
+ * // Set as default
1522
+ * await client.users.aggregators.setDefault(agg.id);
1523
+ */
1524
+ get aggregators(): AggregatorsResource;
945
1525
  /**
946
1526
  * Update the current user's profile.
947
1527
  *
@@ -983,6 +1563,38 @@ declare class UsersResource {
983
1563
  * }
984
1564
  */
985
1565
  getAccountingCredentials(): Promise<AccountingCredentials>;
1566
+ /**
1567
+ * Send a heartbeat to indicate this SyftAI Space is alive.
1568
+ *
1569
+ * The heartbeat mechanism allows SyftAI Spaces to signal their availability
1570
+ * to SyftHub. This should be called periodically (before the TTL expires)
1571
+ * to maintain the "active" status.
1572
+ *
1573
+ * @param input - Heartbeat parameters
1574
+ * @param input.url - Full URL of this space (e.g., "https://myspace.example.com").
1575
+ * The server extracts the domain from this URL.
1576
+ * @param input.ttlSeconds - Time-to-live in seconds (1-3600). The server caps this
1577
+ * at a maximum of 600 seconds (10 minutes). Default is 300
1578
+ * seconds (5 minutes).
1579
+ * @returns HeartbeatResponse containing status, expiry time, domain, and effective TTL
1580
+ * @throws {AuthenticationError} If not authenticated
1581
+ * @throws {ValidationError} If URL or TTL is invalid
1582
+ *
1583
+ * @example
1584
+ * // Send heartbeat with default TTL (300 seconds)
1585
+ * const response = await client.users.sendHeartbeat({
1586
+ * url: 'https://myspace.example.com'
1587
+ * });
1588
+ * console.log(`Next heartbeat before: ${response.expiresAt}`);
1589
+ *
1590
+ * @example
1591
+ * // Send heartbeat with custom TTL
1592
+ * const response = await client.users.sendHeartbeat({
1593
+ * url: 'https://myspace.example.com',
1594
+ * ttlSeconds: 600 // Maximum allowed
1595
+ * });
1596
+ */
1597
+ sendHeartbeat(input: HeartbeatInput): Promise<HeartbeatResponse>;
986
1598
  }
987
1599
 
988
1600
  /**
@@ -1110,13 +1722,6 @@ declare class MyEndpointsResource {
1110
1722
  * @throws {Error} If path format is invalid
1111
1723
  */
1112
1724
  private parsePath;
1113
- /**
1114
- * Resolve an endpoint path to its ID.
1115
- *
1116
- * @param path - Endpoint path in "owner/slug" format
1117
- * @returns The endpoint ID
1118
- */
1119
- private resolveEndpointId;
1120
1725
  /**
1121
1726
  * List the current user's endpoints.
1122
1727
  *
@@ -1129,12 +1734,11 @@ declare class MyEndpointsResource {
1129
1734
  * Create a new endpoint.
1130
1735
  *
1131
1736
  * @param input - Endpoint creation details
1132
- * @param organizationId - Optional organization ID (for org-owned endpoints)
1133
1737
  * @returns The created Endpoint
1134
1738
  * @throws {AuthenticationError} If not authenticated
1135
1739
  * @throws {ValidationError} If input validation fails
1136
1740
  */
1137
- create(input: EndpointCreateInput, organizationId?: number): Promise<Endpoint>;
1741
+ create(input: EndpointCreateInput): Promise<Endpoint>;
1138
1742
  /**
1139
1743
  * Get a specific endpoint by path.
1140
1744
  *
@@ -1167,12 +1771,47 @@ declare class MyEndpointsResource {
1167
1771
  * @throws {AuthorizationError} If not owner/admin
1168
1772
  */
1169
1773
  delete(path: string): Promise<void>;
1774
+ /**
1775
+ * Synchronize user's endpoints with provided list.
1776
+ *
1777
+ * This is a DESTRUCTIVE operation that:
1778
+ * 1. Deletes ALL existing endpoints owned by the current user
1779
+ * 2. Creates ALL endpoints from the provided list
1780
+ * 3. Is ATOMIC: either all endpoints sync successfully, or none do
1781
+ *
1782
+ * Important Notes:
1783
+ * - Stars on existing endpoints will be lost (reset to 0)
1784
+ * - Endpoint IDs will change (new IDs assigned)
1785
+ * - Maximum 100 endpoints per sync request
1786
+ *
1787
+ * @param endpoints - List of endpoint specifications to sync.
1788
+ * Pass an empty array to delete ALL user endpoints.
1789
+ * @returns SyncEndpointsResponse with synced count, deleted count, and created endpoints
1790
+ * @throws {AuthenticationError} If not authenticated
1791
+ * @throws {ValidationError} If any endpoint fails validation (entire batch rejected)
1792
+ *
1793
+ * @example
1794
+ * // Sync with new endpoints
1795
+ * const result = await client.myEndpoints.sync([
1796
+ * { name: 'Model A', type: 'model', visibility: 'public' },
1797
+ * { name: 'Data Source B', type: 'data_source', visibility: 'private' },
1798
+ * ]);
1799
+ * console.log(`Deleted ${result.deleted}, created ${result.synced} endpoints`);
1800
+ *
1801
+ * @example
1802
+ * // Clear all endpoints
1803
+ * const result = await client.myEndpoints.sync([]);
1804
+ * console.log(`Deleted ${result.deleted} endpoints`);
1805
+ */
1806
+ sync(endpoints?: EndpointCreateInput[]): Promise<SyncEndpointsResponse>;
1170
1807
  }
1171
1808
 
1172
1809
  /**
1173
1810
  * Options for browsing endpoints.
1174
1811
  */
1175
1812
  interface BrowseOptions {
1813
+ /** Filter by endpoint type ('model' or 'data_source') */
1814
+ endpointType?: string;
1176
1815
  /** Number of items per page (default: 20) */
1177
1816
  pageSize?: number;
1178
1817
  }
@@ -1180,11 +1819,22 @@ interface BrowseOptions {
1180
1819
  * Options for trending endpoints.
1181
1820
  */
1182
1821
  interface TrendingOptions {
1822
+ /** Filter by endpoint type ('model' or 'data_source') */
1823
+ endpointType?: string;
1183
1824
  /** Minimum number of stars */
1184
1825
  minStars?: number;
1185
1826
  /** Number of items per page (default: 20) */
1186
1827
  pageSize?: number;
1187
1828
  }
1829
+ /**
1830
+ * Options for listing guest-accessible endpoints.
1831
+ */
1832
+ interface GuestAccessibleOptions {
1833
+ /** Filter by endpoint type ('model' or 'data_source') */
1834
+ endpointType?: string;
1835
+ /** Number of items per page (default: 20) */
1836
+ pageSize?: number;
1837
+ }
1188
1838
  /**
1189
1839
  * Hub resource for browsing and discovering public endpoints.
1190
1840
  *
@@ -1203,6 +1853,13 @@ interface TrendingOptions {
1203
1853
  * }
1204
1854
  *
1205
1855
  * @example
1856
+ * // Semantic search for endpoints
1857
+ * const results = await client.hub.search('machine learning for images');
1858
+ * for (const result of results) {
1859
+ * console.log(`${result.ownerUsername}/${result.slug}: ${result.relevanceScore.toFixed(2)}`);
1860
+ * }
1861
+ *
1862
+ * @example
1206
1863
  * // Get a specific endpoint
1207
1864
  * const endpoint = await client.hub.get('alice/cool-api');
1208
1865
  * console.log(endpoint.readme);
@@ -1237,8 +1894,12 @@ declare class HubResource {
1237
1894
  /**
1238
1895
  * Browse all public endpoints.
1239
1896
  *
1240
- * @param options - Pagination options
1897
+ * @param options - Filter and pagination options
1241
1898
  * @returns PageIterator that lazily fetches endpoints
1899
+ *
1900
+ * @example
1901
+ * // Browse only model endpoints
1902
+ * const models = await client.hub.browse({ endpointType: 'model' }).firstPage();
1242
1903
  */
1243
1904
  browse(options?: BrowseOptions): PageIterator<EndpointPublic>;
1244
1905
  /**
@@ -1246,8 +1907,61 @@ declare class HubResource {
1246
1907
  *
1247
1908
  * @param options - Filter and pagination options
1248
1909
  * @returns PageIterator that lazily fetches endpoints
1910
+ *
1911
+ * @example
1912
+ * // Get trending models only
1913
+ * const models = await client.hub.trending({ endpointType: 'model' }).firstPage();
1249
1914
  */
1250
1915
  trending(options?: TrendingOptions): PageIterator<EndpointPublic>;
1916
+ /**
1917
+ * List endpoints accessible to unauthenticated (guest) users.
1918
+ *
1919
+ * Guest-accessible endpoints are public, active, and have no policies attached.
1920
+ * No authentication is required to call this method.
1921
+ *
1922
+ * @param options - Filter and pagination options
1923
+ * @returns PageIterator that lazily fetches guest-accessible endpoints
1924
+ *
1925
+ * @example
1926
+ * // List all guest-accessible endpoints
1927
+ * for await (const endpoint of client.hub.guestAccessible()) {
1928
+ * console.log(`${endpoint.ownerUsername}/${endpoint.slug}: ${endpoint.name}`);
1929
+ * }
1930
+ *
1931
+ * @example
1932
+ * // List only guest-accessible models
1933
+ * const models = await client.hub.guestAccessible({ endpointType: 'model' }).firstPage();
1934
+ */
1935
+ guestAccessible(options?: GuestAccessibleOptions): PageIterator<EndpointPublic>;
1936
+ /**
1937
+ * Search for endpoints using semantic search.
1938
+ *
1939
+ * Uses RAG-powered semantic search to find endpoints that match the
1940
+ * natural language query. Returns results sorted by relevance score.
1941
+ *
1942
+ * Note: If RAG is not configured on the server (no OpenAI API key),
1943
+ * this method returns an empty array.
1944
+ *
1945
+ * @param query - Natural language search query (e.g., "machine learning models for image classification")
1946
+ * @param options - Search options (topK, type filter, minScore)
1947
+ * @returns Promise resolving to array of EndpointSearchResult with relevance scores.
1948
+ * Returns empty array if query is too short (<3 chars) or no matches found.
1949
+ *
1950
+ * @example
1951
+ * // Search for machine learning models
1952
+ * const results = await client.hub.search('image classification models');
1953
+ * for (const result of results) {
1954
+ * console.log(`${result.ownerUsername}/${result.slug}: ${result.relevanceScore.toFixed(2)}`);
1955
+ * }
1956
+ *
1957
+ * @example
1958
+ * // Filter by type and minimum score
1959
+ * const dataSources = await client.hub.search('customer data', {
1960
+ * type: EndpointType.DATA_SOURCE,
1961
+ * minScore: 0.5,
1962
+ * });
1963
+ */
1964
+ search(query: string, options?: SearchOptions): Promise<EndpointSearchResult[]>;
1251
1965
  /**
1252
1966
  * Get an endpoint by its path.
1253
1967
  *
@@ -1275,6 +1989,22 @@ declare class HubResource {
1275
1989
  * @throws {NotFoundError} If endpoint not found
1276
1990
  */
1277
1991
  unstar(path: string): Promise<void>;
1992
+ /**
1993
+ * Get the owner/slug paths of a collective's approved member endpoints,
1994
+ * optionally narrowed to a single shared-endpoint subset.
1995
+ *
1996
+ * Used by the chat resource to expand both `collective/<slug>` and
1997
+ * `collective/<slug>/<shared-slug>` data-source references into the
1998
+ * individual endpoint paths before building the aggregator request.
1999
+ *
2000
+ * @param slug - The collective slug (e.g. "genomics-research")
2001
+ * @param sharedSlug - Optional curated-subset slug. When provided, only the
2002
+ * intersection of the subset's configured endpoints with the collective's
2003
+ * currently approved members is returned. Omit for "all approved members".
2004
+ * @returns Array of "owner/slug" path strings
2005
+ * @throws {NotFoundError} If the collective (or shared endpoint) does not exist
2006
+ */
2007
+ getCollectiveEndpointPaths(slug: string, sharedSlug?: string): Promise<string[]>;
1278
2008
  /**
1279
2009
  * Check if you have starred an endpoint.
1280
2010
  *
@@ -1287,295 +2017,176 @@ declare class HubResource {
1287
2017
  }
1288
2018
 
1289
2019
  /**
1290
- * Accounting Resource for SyftHub SDK
2020
+ * Accounting Resource for SyftHub SDK (MPP Wallet)
1291
2021
  *
1292
- * This module connects to an external accounting/billing service for managing
1293
- * user balances and transactions. The accounting service is separate from SyftHub
1294
- * and uses its own authentication (Basic auth with email/password).
2022
+ * This module provides wallet management operations via the SyftHub API.
2023
+ * Payments are handled through the MPP (Micropayment Protocol) 402 flow,
2024
+ * replacing the previous external accounting service with direct wallet support.
1295
2025
  *
1296
2026
  * @example
1297
2027
  * ```typescript
1298
- * // Create accounting client
1299
- * const accounting = new AccountingResource({
1300
- * url: 'https://accounting.example.com',
1301
- * email: 'user@example.com',
1302
- * password: 'secret'
1303
- * });
1304
- *
1305
- * // Get user balance
1306
- * const user = await accounting.getUser();
1307
- * console.log(`Balance: ${user.balance}`);
1308
- *
1309
- * // Create a transaction
1310
- * const tx = await accounting.createTransaction({
1311
- * recipientEmail: 'recipient@example.com',
1312
- * amount: 10.0,
1313
- * appName: 'syftai-space',
1314
- * appEpPath: 'alice/my-model'
1315
- * });
1316
- *
1317
- * // Confirm the transaction
1318
- * await accounting.confirmTransaction(tx.id);
2028
+ * // Initialize via client (after login)
2029
+ * await client.auth.login('alice', 'password');
2030
+ * await client.initAccounting();
2031
+ *
2032
+ * // Get wallet info
2033
+ * const wallet = await client.accounting.getWallet();
2034
+ * console.log(`Wallet address: ${wallet.address}`);
2035
+ *
2036
+ * // Get balance
2037
+ * const balance = await client.accounting.getBalance();
2038
+ * console.log(`Balance: ${balance.balance} ${balance.currency}`);
2039
+ *
2040
+ * // Get transactions
2041
+ * const transactions = await client.accounting.getTransactions();
2042
+ * for (const tx of transactions) {
2043
+ * console.log(`${tx.created_at}: ${tx.amount} from ${tx.sender_email}`);
2044
+ * }
1319
2045
  * ```
1320
2046
  */
1321
2047
 
1322
2048
  /**
1323
2049
  * Options for creating an AccountingResource.
2050
+ *
2051
+ * @deprecated The old AccountingResourceOptions with external service credentials
2052
+ * are no longer needed. Use the HTTPClient-based constructor instead.
1324
2053
  */
1325
2054
  interface AccountingResourceOptions {
1326
- /** Accounting service URL */
2055
+ /** @deprecated No longer used - wallet API is accessed via SyftHub */
1327
2056
  url: string;
1328
- /** Email for Basic auth */
2057
+ /** @deprecated No longer used */
1329
2058
  email: string;
1330
- /** Password for Basic auth */
2059
+ /** @deprecated No longer used */
1331
2060
  password: string;
1332
- /** Request timeout in milliseconds (default: 30000) */
2061
+ /** @deprecated No longer used */
1333
2062
  timeout?: number;
1334
2063
  }
1335
2064
  /**
1336
2065
  * Options for listing transactions.
2066
+ *
2067
+ * @deprecated Use getTransactions() which returns all transactions directly.
1337
2068
  */
1338
2069
  interface TransactionsOptions {
1339
2070
  /** Number of items per page (default: 20) */
1340
2071
  pageSize?: number;
1341
2072
  }
1342
2073
  /**
1343
- * Handle accounting/billing operations with external service.
2074
+ * Wallet and payment operations via the SyftHub API.
1344
2075
  *
1345
- * The accounting service manages user balances and transactions. It uses
1346
- * Basic auth (email/password) for authentication, which is separate from
1347
- * SyftHub's JWT-based authentication.
2076
+ * Manages MPP (Micropayment Protocol) wallets for users. Payments for
2077
+ * endpoint usage are handled automatically via the 402 payment flow
2078
+ * between the aggregator and SyftAI-Space instances.
1348
2079
  *
1349
- * Transaction Workflow:
1350
- * 1. Sender creates transaction (status=PENDING)
1351
- * 2. Either party confirms (status=COMPLETED) or cancels (status=CANCELLED)
2080
+ * @example
2081
+ * ```typescript
2082
+ * // Get wallet info
2083
+ * const wallet = await client.accounting.getWallet();
2084
+ * if (!wallet.exists) {
2085
+ * // Create a new wallet
2086
+ * const result = await client.accounting.createWallet();
2087
+ * console.log(`Created wallet: ${result.address}`);
2088
+ * }
1352
2089
  *
1353
- * Delegated Transaction Workflow:
1354
- * 1. Sender creates a transaction token for recipient
1355
- * 2. Recipient uses token to create delegated transaction
1356
- * 3. Recipient confirms the transaction
2090
+ * // Check balance
2091
+ * const balance = await client.accounting.getBalance();
2092
+ * console.log(`Balance: ${balance.balance} ${balance.currency}`);
2093
+ * ```
1357
2094
  */
1358
2095
  declare class AccountingResource {
1359
- private readonly baseUrl;
1360
- private readonly email;
1361
- private readonly password;
1362
- private readonly timeout;
1363
- private readonly authHeader;
1364
- constructor(options: AccountingResourceOptions);
1365
- /**
1366
- * Make an authenticated request to the accounting service.
1367
- */
1368
- private request;
1369
- /**
1370
- * Make a request using Bearer token auth (for delegated transactions).
1371
- */
1372
- private requestWithToken;
1373
- /**
1374
- * Get the current user's account information including balance.
1375
- *
1376
- * @returns AccountingUser with id, email, balance, and organization
1377
- * @throws {AuthenticationError} If authentication fails
1378
- * @throws {APIError} On other errors
1379
- *
1380
- * @example
1381
- * ```typescript
1382
- * const user = await accounting.getUser();
1383
- * console.log(`Balance: ${user.balance}`);
1384
- * console.log(`Organization: ${user.organization}`);
1385
- * ```
1386
- */
1387
- getUser(): Promise<AccountingUser>;
1388
- /**
1389
- * Update the user's password.
1390
- *
1391
- * @param currentPassword - Current password for verification
1392
- * @param newPassword - New password to set
1393
- * @throws {AuthenticationError} If current password is wrong
1394
- * @throws {ValidationError} If new password doesn't meet requirements
1395
- *
1396
- * @example
1397
- * ```typescript
1398
- * await accounting.updatePassword('old_secret', 'new_secret');
1399
- * ```
1400
- */
1401
- updatePassword(currentPassword: string, newPassword: string): Promise<void>;
1402
- /**
1403
- * Update the user's organization.
1404
- *
1405
- * @param organization - New organization name
1406
- * @throws {AuthenticationError} If authentication fails
1407
- *
1408
- * @example
1409
- * ```typescript
1410
- * await accounting.updateOrganization('OpenMined');
1411
- * ```
1412
- */
1413
- updateOrganization(organization: string): Promise<void>;
2096
+ private readonly http;
2097
+ constructor(http: HTTPClient);
1414
2098
  /**
1415
- * List account transactions with pagination.
2099
+ * Get the current user's wallet information.
1416
2100
  *
1417
- * Returns a lazy iterator that fetches pages on demand.
1418
- *
1419
- * @param options - Pagination options
1420
- * @returns PageIterator that yields Transaction objects
2101
+ * @returns WalletInfo with address and existence status
2102
+ * @throws {AuthenticationError} If not authenticated
1421
2103
  *
1422
2104
  * @example
1423
2105
  * ```typescript
1424
- * // Iterate through all transactions
1425
- * for await (const tx of accounting.getTransactions()) {
1426
- * console.log(`${tx.createdAt}: ${tx.amount} from ${tx.senderEmail}`);
2106
+ * const wallet = await client.accounting.getWallet();
2107
+ * if (wallet.exists) {
2108
+ * console.log(`Wallet address: ${wallet.address}`);
2109
+ * } else {
2110
+ * console.log('No wallet configured');
1427
2111
  * }
1428
- *
1429
- * // Get first page only
1430
- * const firstPage = await accounting.getTransactions().firstPage();
1431
- *
1432
- * // Get all transactions
1433
- * const allTxs = await accounting.getTransactions().all();
1434
- * ```
1435
- */
1436
- getTransactions(options?: TransactionsOptions): PageIterator<Transaction>;
1437
- /**
1438
- * Get a specific transaction by ID.
1439
- *
1440
- * @param transactionId - The transaction ID
1441
- * @returns Transaction object
1442
- * @throws {NotFoundError} If transaction not found
1443
- *
1444
- * @example
1445
- * ```typescript
1446
- * const tx = await accounting.getTransaction('tx_123');
1447
- * console.log(`Status: ${tx.status}`);
1448
- * ```
1449
- */
1450
- getTransaction(transactionId: string): Promise<Transaction>;
1451
- /**
1452
- * Create a new transaction (direct transfer).
1453
- *
1454
- * Creates a PENDING transaction that must be confirmed or cancelled.
1455
- * The transaction is created by the sender (current user).
1456
- *
1457
- * @param input - Transaction details
1458
- * @returns Transaction in PENDING status
1459
- * @throws {ValidationError} If amount <= 0 or insufficient balance
1460
- *
1461
- * @example
1462
- * ```typescript
1463
- * const tx = await accounting.createTransaction({
1464
- * recipientEmail: 'bob@example.com',
1465
- * amount: 10.0,
1466
- * appName: 'syftai-space',
1467
- * appEpPath: 'alice/my-model'
1468
- * });
1469
- * console.log(`Created transaction ${tx.id}: ${tx.status}`);
1470
- *
1471
- * // Later, confirm or cancel
1472
- * await accounting.confirmTransaction(tx.id);
1473
2112
  * ```
1474
2113
  */
1475
- createTransaction(input: CreateTransactionInput): Promise<Transaction>;
2114
+ getWallet(): Promise<WalletInfo>;
1476
2115
  /**
1477
- * Confirm a pending transaction.
1478
- *
1479
- * Confirms the transaction, transferring funds from sender to recipient.
1480
- * Can be called by either the sender or recipient.
2116
+ * Get the current user's wallet balance and recent transactions.
1481
2117
  *
1482
- * @param transactionId - The transaction ID to confirm
1483
- * @returns Transaction in COMPLETED status
1484
- * @throws {NotFoundError} If transaction not found
1485
- * @throws {ValidationError} If transaction is not in PENDING status
2118
+ * @returns WalletBalance with balance, currency, and recent transactions
2119
+ * @throws {AuthenticationError} If not authenticated
1486
2120
  *
1487
2121
  * @example
1488
2122
  * ```typescript
1489
- * const tx = await accounting.confirmTransaction('tx_123');
1490
- * console.log(`Confirmed: ${tx.status}`); // "completed"
2123
+ * const balance = await client.accounting.getBalance();
2124
+ * console.log(`Balance: ${balance.balance} ${balance.currency}`);
2125
+ * console.log(`Wallet configured: ${balance.wallet_configured}`);
1491
2126
  * ```
1492
2127
  */
1493
- confirmTransaction(transactionId: string): Promise<Transaction>;
2128
+ getBalance(): Promise<WalletBalance>;
1494
2129
  /**
1495
- * Cancel a pending transaction.
1496
- *
1497
- * Cancels the transaction without transferring funds.
1498
- * Can be called by either the sender or recipient.
2130
+ * Get the current user's wallet transactions.
1499
2131
  *
1500
- * @param transactionId - The transaction ID to cancel
1501
- * @returns Transaction in CANCELLED status
1502
- * @throws {NotFoundError} If transaction not found
1503
- * @throws {ValidationError} If transaction is not in PENDING status
2132
+ * @returns Array of WalletTransaction objects
2133
+ * @throws {AuthenticationError} If not authenticated
1504
2134
  *
1505
2135
  * @example
1506
2136
  * ```typescript
1507
- * const tx = await accounting.cancelTransaction('tx_123');
1508
- * console.log(`Cancelled: ${tx.status}`); // "cancelled"
2137
+ * const transactions = await client.accounting.getTransactions();
2138
+ * for (const tx of transactions) {
2139
+ * console.log(`${tx.created_at}: ${tx.amount} ${tx.status}`);
2140
+ * }
1509
2141
  * ```
1510
2142
  */
1511
- cancelTransaction(transactionId: string): Promise<Transaction>;
2143
+ getTransactions(): Promise<WalletTransaction[]>;
1512
2144
  /**
1513
- * Create a transaction token for delegated transfers.
2145
+ * Create a new wallet for the current user.
1514
2146
  *
1515
- * Creates a JWT token that authorizes the recipient to create a
1516
- * transaction on behalf of the sender (current user). The token
1517
- * is short-lived (typically ~5 minutes).
2147
+ * Generates a new wallet with a fresh keypair. The wallet address
2148
+ * is returned and stored on the server.
1518
2149
  *
1519
- * Use this when you want to pre-authorize a payment that will be
1520
- * initiated by the recipient (e.g., a service charging for usage).
1521
- *
1522
- * @param recipientEmail - Email of the authorized recipient
1523
- * @returns JWT token string to share with recipient
2150
+ * @returns Object with the new wallet address
2151
+ * @throws {AuthenticationError} If not authenticated
2152
+ * @throws {ValidationError} If user already has a wallet
1524
2153
  *
1525
2154
  * @example
1526
2155
  * ```typescript
1527
- * // Sender creates token
1528
- * const token = await accounting.createTransactionToken('service@example.com');
1529
- *
1530
- * // Share token with recipient out-of-band
1531
- * // Recipient uses token to create delegated transaction
2156
+ * const result = await client.accounting.createWallet();
2157
+ * console.log(`New wallet address: ${result.address}`);
1532
2158
  * ```
1533
2159
  */
1534
- createTransactionToken(recipientEmail: string): Promise<string>;
2160
+ createWallet(): Promise<{
2161
+ address: string;
2162
+ }>;
1535
2163
  /**
1536
- * Create a delegated transaction using a pre-authorized token.
1537
- *
1538
- * Creates a transaction on behalf of the sender using their token.
1539
- * This is typically used by services to charge users for usage.
2164
+ * Import an existing wallet using a private key.
1540
2165
  *
1541
- * The token authenticates the request instead of Basic auth.
1542
- *
1543
- * @param senderEmail - Email of the sender who created the token
1544
- * @param amount - Amount to transfer (must be > 0)
1545
- * @param token - JWT token from sender's createTransactionToken()
1546
- * @returns Transaction in PENDING status (createdBy=RECIPIENT)
1547
- * @throws {AuthenticationError} If token is invalid or expired
1548
- * @throws {ValidationError} If amount <= 0
2166
+ * @param privateKey - The private key to import
2167
+ * @returns Object with the imported wallet address
2168
+ * @throws {AuthenticationError} If not authenticated
2169
+ * @throws {ValidationError} If the private key is invalid
1549
2170
  *
1550
2171
  * @example
1551
2172
  * ```typescript
1552
- * // Recipient creates transaction using sender's token
1553
- * const tx = await accounting.createDelegatedTransaction(
1554
- * 'alice@example.com',
1555
- * 5.0,
1556
- * aliceToken
1557
- * );
1558
- *
1559
- * // Recipient confirms the transaction
1560
- * await accounting.confirmTransaction(tx.id);
2173
+ * const result = await client.accounting.importWallet('0x...');
2174
+ * console.log(`Imported wallet address: ${result.address}`);
1561
2175
  * ```
1562
2176
  */
1563
- createDelegatedTransaction(senderEmail: string, amount: number, token: string): Promise<Transaction>;
2177
+ importWallet(privateKey: string): Promise<{
2178
+ address: string;
2179
+ }>;
1564
2180
  }
1565
2181
  /**
1566
2182
  * Create a new AccountingResource instance.
1567
2183
  *
1568
- * @param options - Configuration options
1569
- * @returns AccountingResource instance
2184
+ * @deprecated Use the SyftHubClient's built-in accounting resource instead.
2185
+ * The wallet API is now accessed through the SyftHub HTTP client, not
2186
+ * a separate external service.
1570
2187
  *
1571
- * @example
1572
- * ```typescript
1573
- * const accounting = createAccountingResource({
1574
- * url: process.env.ACCOUNTING_URL!,
1575
- * email: process.env.ACCOUNTING_EMAIL!,
1576
- * password: process.env.ACCOUNTING_PASSWORD!
1577
- * });
1578
- * ```
2188
+ * @param options - Configuration options (ignored, kept for backward compatibility)
2189
+ * @returns AccountingResource instance
1579
2190
  */
1580
2191
  declare function createAccountingResource(options: AccountingResourceOptions): AccountingResource;
1581
2192
 
@@ -1704,6 +2315,225 @@ declare class AccountingServiceUnavailableError extends SyftHubError {
1704
2315
  constructor(message?: string, detail?: unknown | undefined);
1705
2316
  }
1706
2317
 
2318
+ /**
2319
+ * TypeScript type definitions for agent events, session state, and message payloads.
2320
+ */
2321
+ /**
2322
+ * Agent session state machine states.
2323
+ */
2324
+ type AgentSessionState = 'idle' | 'connecting' | 'running' | 'awaiting_input' | 'completed' | 'failed' | 'cancelled' | 'error';
2325
+ interface ThinkingEvent {
2326
+ type: 'agent.thinking';
2327
+ payload: {
2328
+ content: string;
2329
+ is_streaming: boolean;
2330
+ };
2331
+ }
2332
+ interface ToolCallEvent {
2333
+ type: 'agent.tool_call';
2334
+ payload: {
2335
+ tool_call_id: string;
2336
+ tool_name: string;
2337
+ arguments: Record<string, unknown>;
2338
+ requires_confirmation: boolean;
2339
+ description?: string;
2340
+ };
2341
+ }
2342
+ interface ToolResultEvent {
2343
+ type: 'agent.tool_result';
2344
+ payload: {
2345
+ tool_call_id: string;
2346
+ status: 'success' | 'error';
2347
+ result?: unknown;
2348
+ error?: string;
2349
+ duration_ms?: number;
2350
+ };
2351
+ }
2352
+ interface AgentMessageEvent {
2353
+ type: 'agent.message';
2354
+ payload: {
2355
+ content: string;
2356
+ is_complete: boolean;
2357
+ };
2358
+ }
2359
+ interface TokenEvent {
2360
+ type: 'agent.token';
2361
+ payload: {
2362
+ token: string;
2363
+ };
2364
+ }
2365
+ interface StatusEvent {
2366
+ type: 'agent.status';
2367
+ payload: {
2368
+ status: string;
2369
+ detail: string;
2370
+ progress?: number;
2371
+ };
2372
+ }
2373
+ interface RequestInputEvent {
2374
+ type: 'agent.request_input';
2375
+ payload: {
2376
+ prompt: string;
2377
+ };
2378
+ }
2379
+ interface SessionCreatedEvent {
2380
+ type: 'session.created';
2381
+ payload: {
2382
+ session_id: string;
2383
+ };
2384
+ }
2385
+ interface SessionCompletedEvent {
2386
+ type: 'session.completed';
2387
+ payload: {
2388
+ session_id: string;
2389
+ };
2390
+ }
2391
+ interface SessionFailedEvent {
2392
+ type: 'session.failed';
2393
+ payload: {
2394
+ error: string;
2395
+ reason: string;
2396
+ };
2397
+ }
2398
+ interface AgentErrorEvent {
2399
+ type: 'agent.error';
2400
+ payload: {
2401
+ code: string;
2402
+ message: string;
2403
+ recoverable: boolean;
2404
+ };
2405
+ }
2406
+ /**
2407
+ * Union type of all possible agent events.
2408
+ */
2409
+ type AgentEvent = ThinkingEvent | ToolCallEvent | ToolResultEvent | AgentMessageEvent | TokenEvent | StatusEvent | RequestInputEvent | SessionCreatedEvent | SessionCompletedEvent | SessionFailedEvent | AgentErrorEvent;
2410
+ /**
2411
+ * Configuration for agent sessions.
2412
+ */
2413
+ interface AgentConfig {
2414
+ maxTokens?: number;
2415
+ temperature?: number;
2416
+ systemPrompt?: string;
2417
+ metadata?: Record<string, unknown>;
2418
+ }
2419
+ /**
2420
+ * Message in conversation history.
2421
+ */
2422
+ interface AgentHistoryMessage {
2423
+ role: string;
2424
+ content: string;
2425
+ }
2426
+ /**
2427
+ * Options for starting an agent session.
2428
+ */
2429
+ interface AgentSessionOptions {
2430
+ /** The initial prompt */
2431
+ prompt: string;
2432
+ /** Endpoint in "owner/slug" format or { owner, slug } object */
2433
+ endpoint: string | {
2434
+ owner: string;
2435
+ slug: string;
2436
+ };
2437
+ /** Optional agent configuration */
2438
+ config?: AgentConfig;
2439
+ /** Optional conversation history */
2440
+ messages?: AgentHistoryMessage[];
2441
+ /** Optional AbortSignal for cancellation */
2442
+ signal?: AbortSignal;
2443
+ }
2444
+
2445
+ /**
2446
+ * Agent resource for bidirectional agent sessions via WebSocket.
2447
+ *
2448
+ * @example
2449
+ * const session = await client.agent.startSession({
2450
+ * prompt: 'Help me refactor this code',
2451
+ * endpoint: 'alice/code-assistant',
2452
+ * });
2453
+ *
2454
+ * for await (const event of session.events()) {
2455
+ * switch (event.type) {
2456
+ * case 'agent.message':
2457
+ * console.log(event.payload.content);
2458
+ * break;
2459
+ * case 'agent.tool_call':
2460
+ * if (event.payload.requires_confirmation) {
2461
+ * await session.confirm(event.payload.tool_call_id);
2462
+ * }
2463
+ * break;
2464
+ * }
2465
+ * }
2466
+ */
2467
+
2468
+ /**
2469
+ * Error thrown during agent session operations.
2470
+ */
2471
+ declare class AgentSessionError extends SyftHubError {
2472
+ readonly code?: string | undefined;
2473
+ constructor(message: string, code?: string | undefined);
2474
+ }
2475
+ /**
2476
+ * AgentResource manages agent session lifecycle.
2477
+ */
2478
+ declare class AgentResource {
2479
+ private readonly auth;
2480
+ private readonly aggregatorUrl;
2481
+ constructor(auth: AuthResource, aggregatorUrl: string);
2482
+ /**
2483
+ * Start a new agent session.
2484
+ *
2485
+ * @param options - Session options including prompt, endpoint, and config
2486
+ * @returns An AgentSessionClient for interacting with the session
2487
+ */
2488
+ startSession(options: AgentSessionOptions): Promise<AgentSessionClient>;
2489
+ }
2490
+ /**
2491
+ * Client for an active agent session.
2492
+ * Provides both async iterable and callback-based APIs for receiving events.
2493
+ */
2494
+ declare class AgentSessionClient {
2495
+ private readonly ws;
2496
+ readonly sessionId: string;
2497
+ private _state;
2498
+ private _sequenceCounter;
2499
+ private _messageQueue;
2500
+ private _messageResolvers;
2501
+ private _closed;
2502
+ constructor(ws: WebSocket, sessionId: string);
2503
+ /** Current session state */
2504
+ get state(): AgentSessionState;
2505
+ /**
2506
+ * Async generator yielding agent events.
2507
+ *
2508
+ * @example
2509
+ * for await (const event of session.events()) {
2510
+ * console.log(event.type, event.payload);
2511
+ * }
2512
+ */
2513
+ events(): AsyncGenerator<AgentEvent>;
2514
+ /**
2515
+ * Register an event handler.
2516
+ *
2517
+ * @param eventType - The event type to listen for, or '*' for all events
2518
+ * @param handler - Callback function
2519
+ */
2520
+ on(eventType: string, handler: (event: AgentEvent) => void): void;
2521
+ /** Send a user message to the agent */
2522
+ sendMessage(content: string): void;
2523
+ /** Confirm a tool call */
2524
+ confirm(toolCallId: string): void;
2525
+ /** Deny a tool call */
2526
+ deny(toolCallId: string, reason?: string): void;
2527
+ /** Cancel the session */
2528
+ cancel(): void;
2529
+ /** Close the session and WebSocket */
2530
+ close(): void;
2531
+ private _send;
2532
+ private _handleMessage;
2533
+ private _handleClose;
2534
+ private _nextEvent;
2535
+ }
2536
+
1707
2537
  /**
1708
2538
  * Chat resource for RAG-augmented conversations via the Aggregator service.
1709
2539
  *
@@ -1757,6 +2587,11 @@ declare class ChatResource {
1757
2587
  private readonly auth;
1758
2588
  private readonly aggregatorUrl;
1759
2589
  constructor(hub: HubResource, auth: AuthResource, aggregatorUrl: string);
2590
+ /**
2591
+ * Check if an endpoint type matches the expected type.
2592
+ * A model_data_source endpoint matches both 'model' and 'data_source'.
2593
+ */
2594
+ private static typeMatches;
1760
2595
  /**
1761
2596
  * Convert any endpoint format to EndpointRef with URL and owner info.
1762
2597
  * The ownerUsername is critical for satellite token authentication.
@@ -1770,16 +2605,16 @@ declare class ChatResource {
1770
2605
  /**
1771
2606
  * Get satellite tokens for all unique endpoint owners.
1772
2607
  * Returns a map of owner username to satellite token.
2608
+ *
2609
+ * @param owners - Array of unique owner usernames
2610
+ * @param guestMode - If true, fetch guest tokens (no auth required)
1773
2611
  */
1774
2612
  private getSatelliteTokensForOwners;
1775
2613
  /**
1776
- * Get transaction tokens for all unique endpoint owners.
1777
- * Returns a map of owner username to transaction token.
1778
- *
1779
- * Transaction tokens are used for billing - they authorize the endpoint
1780
- * owner to charge the current user for usage.
2614
+ * Get the user's Hub access token for MPP payment flow.
2615
+ * Returns null if in guest mode or not authenticated.
1781
2616
  */
1782
- private getTransactionTokensForOwners;
2617
+ private getUserToken;
1783
2618
  /**
1784
2619
  * Type guard for EndpointRef.
1785
2620
  */
@@ -1788,10 +2623,42 @@ declare class ChatResource {
1788
2623
  * Type guard for EndpointPublic.
1789
2624
  */
1790
2625
  private isEndpointPublic;
2626
+ private static readonly COLLECTIVE_PREFIX;
2627
+ private static readonly TUNNELING_PREFIX;
2628
+ /**
2629
+ * Expand any `collective/<slug>` (or `collective/<slug>/<shared-slug>`)
2630
+ * entries in the data-sources list into the individual `owner/slug` paths
2631
+ * of the collective's approved members.
2632
+ *
2633
+ * Path forms recognised:
2634
+ * - `collective/<slug>` → every approved member (backward-compatible)
2635
+ * - `collective/<slug>/all` → equivalent alias of the above
2636
+ * - `collective/<slug>/<shared-slug>` → the named subset, intersected with
2637
+ * the collective's currently approved members
2638
+ *
2639
+ * Non-collective entries pass through unchanged. String paths are
2640
+ * deduplicated so a regular endpoint that also belongs to a selected
2641
+ * collective is not queried twice.
2642
+ */
2643
+ private expandCollectivePaths;
2644
+ /**
2645
+ * Check if any endpoints use tunneling URLs and extract target usernames.
2646
+ */
2647
+ private collectTunnelingUsernames;
2648
+ /**
2649
+ * Shared request preparation for complete() and stream().
2650
+ * Resolves endpoints, fetches tokens, and builds the aggregator request body.
2651
+ * Returns the request body and the resolved aggregator URL.
2652
+ */
2653
+ private prepareRequest;
2654
+ /**
2655
+ * Parse an error response from the aggregator into an AggregatorError.
2656
+ */
2657
+ private handleAggregatorErrorResponse;
1791
2658
  /**
1792
2659
  * Build the request body for the aggregator.
1793
2660
  * Includes endpoint_tokens mapping for satellite token authentication.
1794
- * Includes transaction_tokens mapping for billing authorization.
2661
+ * Includes user_token for MPP payment callback authorization.
1795
2662
  * User identity is derived from satellite tokens, not passed in request body.
1796
2663
  */
1797
2664
  private buildRequestBody;
@@ -1822,7 +2689,7 @@ declare class ChatResource {
1822
2689
  * This method automatically:
1823
2690
  * 1. Resolves endpoints and extracts owner information
1824
2691
  * 2. Exchanges Hub tokens for satellite tokens (one per unique owner)
1825
- * 3. Fetches transaction tokens for billing authorization
2692
+ * 3. Passes the user's Hub access token for MPP payment authorization
1826
2693
  * 4. Sends tokens to the aggregator for forwarding to SyftAI-Space
1827
2694
  *
1828
2695
  * @param options - Chat completion options
@@ -1837,7 +2704,7 @@ declare class ChatResource {
1837
2704
  * This method automatically:
1838
2705
  * 1. Resolves endpoints and extracts owner information
1839
2706
  * 2. Exchanges Hub tokens for satellite tokens (one per unique owner)
1840
- * 3. Fetches transaction tokens for billing authorization
2707
+ * 3. Passes the user's Hub access token for MPP payment authorization
1841
2708
  * 4. Sends tokens to the aggregator for forwarding to SyftAI-Space
1842
2709
  *
1843
2710
  * @param options - Chat completion options
@@ -1848,6 +2715,7 @@ declare class ChatResource {
1848
2715
  * Parse an SSE event into a typed event object.
1849
2716
  */
1850
2717
  private parseSSEEvent;
2718
+ private getAvailableEndpoints;
1851
2719
  /**
1852
2720
  * Get model endpoints that have connection URLs configured.
1853
2721
  *
@@ -1969,20 +2837,12 @@ interface SyftHubClientOptions {
1969
2837
  */
1970
2838
  aggregatorUrl?: string;
1971
2839
  /**
1972
- * Base URL for the accounting service (optional).
1973
- * Falls back to SYFTHUB_ACCOUNTING_URL environment variable.
2840
+ * API token for authentication (alternative to username/password login).
2841
+ * If provided, the client will be authenticated immediately without needing to call login().
2842
+ * Falls back to SYFTHUB_API_TOKEN environment variable.
2843
+ * @example 'syft_pat_xxxxx...'
1974
2844
  */
1975
- accountingUrl?: string;
1976
- /**
1977
- * Email for accounting service authentication (optional).
1978
- * Falls back to SYFTHUB_ACCOUNTING_EMAIL environment variable.
1979
- */
1980
- accountingEmail?: string;
1981
- /**
1982
- * Password for accounting service authentication (optional).
1983
- * Falls back to SYFTHUB_ACCOUNTING_PASSWORD environment variable.
1984
- */
1985
- accountingPassword?: string;
2845
+ apiToken?: string;
1986
2846
  }
1987
2847
  /**
1988
2848
  * SyftHub SDK client for interacting with the SyftHub API.
@@ -2029,15 +2889,16 @@ interface SyftHubClientOptions {
2029
2889
  */
2030
2890
  declare class SyftHubClient {
2031
2891
  private readonly http;
2032
- private readonly options;
2033
2892
  private readonly aggregatorUrl;
2034
2893
  private _auth?;
2035
2894
  private _users?;
2036
2895
  private _myEndpoints?;
2037
2896
  private _hub?;
2038
2897
  private _accounting?;
2898
+ private _agent?;
2039
2899
  private _chat?;
2040
2900
  private _syftai?;
2901
+ private _apiTokens?;
2041
2902
  /**
2042
2903
  * Create a new SyftHub client.
2043
2904
  *
@@ -2079,28 +2940,60 @@ declare class SyftHubClient {
2079
2940
  */
2080
2941
  get hub(): HubResource;
2081
2942
  /**
2082
- * Accounting resource for billing and transactions.
2943
+ * Agent resource for bidirectional agent sessions via WebSocket.
2944
+ *
2945
+ * @example
2946
+ * const session = await client.agent.startSession({
2947
+ * prompt: 'Help me refactor this code',
2948
+ * endpoint: 'alice/code-assistant',
2949
+ * });
2950
+ *
2951
+ * for await (const event of session.events()) {
2952
+ * console.log(event.type, event.payload);
2953
+ * }
2954
+ */
2955
+ get agent(): AgentResource;
2956
+ /**
2957
+ * Accounting resource for wallet and payment operations.
2083
2958
  *
2084
- * The accounting service is external and uses separate credentials
2085
- * (email/password Basic auth) from SyftHub's JWT authentication.
2959
+ * Provides access to MPP wallet management (balance, transactions,
2960
+ * wallet creation/import). Uses the same SyftHub JWT authentication
2961
+ * as other resources.
2086
2962
  *
2087
- * Credentials can be provided via:
2088
- * - Constructor options: accountingUrl, accountingEmail, accountingPassword
2089
- * - Environment variables: SYFTHUB_ACCOUNTING_URL, SYFTHUB_ACCOUNTING_EMAIL, SYFTHUB_ACCOUNTING_PASSWORD
2963
+ * You must call `initAccounting()` after login to initialize this resource,
2964
+ * or access it directly if already initialized.
2090
2965
  *
2091
- * @throws {SyftHubError} If accounting credentials are not configured
2966
+ * @throws {AuthenticationError} If not initialized
2092
2967
  *
2093
2968
  * @example
2094
- * const user = await client.accounting.getUser();
2095
- * console.log(`Balance: ${user.balance}`);
2969
+ * // Login first, then initialize accounting
2970
+ * await client.auth.login('alice', 'password');
2971
+ * await client.initAccounting();
2096
2972
  *
2097
- * // Create a transaction
2098
- * const tx = await client.accounting.createTransaction({
2099
- * recipientEmail: 'bob@example.com',
2100
- * amount: 10.0
2101
- * });
2973
+ * // Now accounting is available
2974
+ * const wallet = await client.accounting.getWallet();
2975
+ * const balance = await client.accounting.getBalance();
2102
2976
  */
2103
2977
  get accounting(): AccountingResource;
2978
+ /**
2979
+ * Initialize the accounting (wallet) resource.
2980
+ *
2981
+ * The wallet API uses the same SyftHub authentication as other resources.
2982
+ * This method simply verifies authentication and creates the resource.
2983
+ *
2984
+ * @returns The initialized AccountingResource
2985
+ * @throws {AuthenticationError} If not authenticated
2986
+ *
2987
+ * @example
2988
+ * // Login first, then initialize accounting
2989
+ * await client.auth.login('alice', 'password');
2990
+ * await client.initAccounting();
2991
+ *
2992
+ * // Now accounting is available
2993
+ * const wallet = await client.accounting.getWallet();
2994
+ * const balance = await client.accounting.getBalance();
2995
+ */
2996
+ initAccounting(): Promise<AccountingResource>;
2104
2997
  /**
2105
2998
  * Chat resource for RAG-augmented conversations via the Aggregator.
2106
2999
  *
@@ -2153,6 +3046,33 @@ declare class SyftHubClient {
2153
3046
  * });
2154
3047
  */
2155
3048
  get syftai(): SyftAIResource;
3049
+ /**
3050
+ * API Tokens resource for managing personal access tokens.
3051
+ *
3052
+ * API tokens provide an alternative to username/password authentication.
3053
+ * They are ideal for CI/CD pipelines, scripts, and programmatic access.
3054
+ *
3055
+ * @example
3056
+ * // Create a new token
3057
+ * const result = await client.apiTokens.create({
3058
+ * name: 'CI/CD Pipeline',
3059
+ * scopes: ['write'],
3060
+ * });
3061
+ * console.log('Save this token:', result.token);
3062
+ *
3063
+ * // List all tokens
3064
+ * const { tokens } = await client.apiTokens.list();
3065
+ *
3066
+ * // Revoke a token
3067
+ * await client.apiTokens.revoke(tokenId);
3068
+ */
3069
+ get apiTokens(): APITokensResource;
3070
+ /**
3071
+ * Check if the client is using API token authentication.
3072
+ *
3073
+ * @returns True if authenticated with an API token (vs JWT)
3074
+ */
3075
+ get isUsingApiToken(): boolean;
2156
3076
  /**
2157
3077
  * Get current authentication tokens.
2158
3078
  *
@@ -2188,19 +3108,19 @@ declare class SyftHubClient {
2188
3108
  */
2189
3109
  get isAuthenticated(): boolean;
2190
3110
  /**
2191
- * Check if accounting service is configured.
3111
+ * Check if the accounting (wallet) resource has been initialized.
2192
3112
  *
2193
- * Use this to check if accounting credentials are available before
2194
- * accessing the `accounting` property, which will throw if not configured.
3113
+ * Use this to check if accounting is available before accessing
3114
+ * the `accounting` property, which will throw if not initialized.
2195
3115
  *
2196
- * @returns True if accounting url, email, and password are all configured
3116
+ * @returns True if accounting has been initialized via `initAccounting()`
2197
3117
  *
2198
3118
  * @example
2199
- * if (client.isAccountingConfigured) {
2200
- * const user = await client.accounting.getUser();
3119
+ * if (client.isAccountingInitialized) {
3120
+ * const wallet = await client.accounting.getWallet();
2201
3121
  * }
2202
3122
  */
2203
- get isAccountingConfigured(): boolean;
3123
+ get isAccountingInitialized(): boolean;
2204
3124
  /**
2205
3125
  * Close the client and clean up resources.
2206
3126
  *
@@ -2209,4 +3129,4 @@ declare class SyftHubClient {
2209
3129
  close(): void;
2210
3130
  }
2211
3131
 
2212
- export { APIError, AccountingAccountExistsError, type AccountingCredentials, AccountingResource, type AccountingResourceOptions, AccountingServiceUnavailableError, type AccountingUser, AggregatorError, type AuthTokens, AuthenticationError, AuthorizationError, type BrowseOptions, type ChatMetadata, type ChatOptions, ChatResource, type ChatResponse, type ChatStreamEvent, ConfigurationError, type Connection, type CreateDelegatedTransactionInput, type CreateTransactionInput, CreatorType, type Document, type DoneEvent, type Endpoint, type EndpointCreateInput, type EndpointPublic, type EndpointRef, EndpointResolutionError, EndpointType, type EndpointUpdateInput, type ErrorEvent, GenerationError, type GenerationStartEvent, InvalidAccountingPasswordError, type ListEndpointsOptions, type Message, NetworkError, NotFoundError, OrganizationRole, type PageFetcher, PageIterator, type PasswordChangeInput, type Policy, type QueryDataSourceOptions, type QueryModelOptions, type RetrievalCompleteEvent, RetrievalError, type RetrievalStartEvent, type SourceCompleteEvent, type SourceInfo, type SourceStatus, SyftAIResource, SyftHubClient, type SyftHubClientOptions, SyftHubError, type TokenEvent, type Transaction, type TransactionResponse, TransactionStatus, type TransactionTokenResponse, type TransactionsOptions, type TrendingOptions, type UpdatePasswordInput, type User, UserAlreadyExistsError, type UserRegisterInput, UserRole, type UserUpdateInput, ValidationError, Visibility, createAccountingResource, getEndpointOwnerType, getEndpointPublicPath, isTransactionCancelled, isTransactionCompleted, isTransactionPending, parseTransaction };
3132
+ export { APIError, type APIToken, type APITokenCreateResponse, type APITokenListResponse, type APITokenScope, APITokensResource, AccountingAccountExistsError, type AccountingCredentials, AccountingResource, type AccountingResourceOptions, AccountingServiceUnavailableError, type AgentConfig, type AgentErrorEvent, type AgentEvent, type AgentHistoryMessage, type AgentMessageEvent, type RequestInputEvent as AgentRequestInputEvent, AgentResource, AgentSessionClient, type SessionCompletedEvent as AgentSessionCompletedEvent, type SessionCreatedEvent as AgentSessionCreatedEvent, AgentSessionError, type SessionFailedEvent as AgentSessionFailedEvent, type AgentSessionOptions, type AgentSessionState, type StatusEvent as AgentStatusEvent, type ThinkingEvent as AgentThinkingEvent, type TokenEvent as AgentTokenEvent, type ToolCallEvent as AgentToolCallEvent, type ToolResultEvent as AgentToolResultEvent, AggregatorError, AggregatorsResource, type AuthConfig, type AuthTokens, AuthenticationError, AuthorizationError, type BrowseOptions, type ChatMetadata, type ChatOptions, ChatResource, type ChatResponse, type ChatStreamEvent, ConfigurationError, type Connection, type CreateAPITokenInput, type Document, type DocumentSource, type DoneEvent, type Endpoint, type EndpointCreateInput, type EndpointPublic, type EndpointRef, EndpointResolutionError, EndpointType, type EndpointUpdateInput, type ErrorEvent, GenerationError, type GenerationStartEvent, type HeartbeatInput, type HeartbeatResponse, InvalidAccountingPasswordError, type ListEndpointsOptions, type Message, NetworkError, NotFoundError, type PageFetcher, PageIterator, type PasswordChangeInput, type PasswordResetConfirmInput, type PasswordResetRequestInput, type Policy, type QueryDataSourceOptions, type QueryModelOptions, type RegisterResult, type RetrievalCompleteEvent, RetrievalError, type RetrievalStartEvent, type SourceCompleteEvent, type SourceInfo, type SourceStatus, SyftAIResource, SyftHubClient, type SyftHubClientOptions, SyftHubError, type SyncEndpointsResponse, type TokenEvent$1 as TokenEvent, type TransactionTokensResponse, type TransactionsOptions, type TrendingOptions, type UpdateAPITokenInput, type User, type UserAggregator, type UserAggregatorCreateInput, type UserAggregatorUpdateInput, UserAlreadyExistsError, type UserRegisterInput, UserRole, type UserUpdateInput, ValidationError, type VerifyOTPInput, Visibility, type WalletBalance, type WalletInfo, type WalletTransaction, createAccountingResource, getEndpointPublicPath };