@fabric-platform/sdk 0.2.2

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.
@@ -0,0 +1,1884 @@
1
+ /**
2
+ * Auth strategy types and header resolution.
3
+ *
4
+ * The SDK is stateless — it does NOT manage auth state.
5
+ * Socialite (or any consumer) owns the session.
6
+ */
7
+ /** Static auth strategies. */
8
+ type AuthStrategy = {
9
+ type: "api-key";
10
+ key: string;
11
+ } | {
12
+ type: "bearer";
13
+ token: string;
14
+ } | {
15
+ type: "oauth";
16
+ clientId: string;
17
+ clientSecret: string;
18
+ };
19
+ /**
20
+ * Auth configuration for FabricClient.
21
+ *
22
+ * - Static `AuthStrategy` for fixed credentials
23
+ * - `() => Promise<string>` for dynamic per-request tokens (e.g., from Next.js cookies)
24
+ */
25
+ type AuthConfig = AuthStrategy | (() => Promise<string>);
26
+
27
+ /**
28
+ * Pagination types and async iterator helper.
29
+ */
30
+ /** Pagination metadata from Fabric API responses. */
31
+ interface Pagination {
32
+ count: number;
33
+ has_more: boolean;
34
+ next_cursor?: string;
35
+ }
36
+ /** A paginated list response. */
37
+ interface PaginatedResponse<T> {
38
+ items: T[];
39
+ pagination: Pagination;
40
+ }
41
+ /** Query parameters for paginated endpoints. */
42
+ interface PaginationParams {
43
+ limit?: number;
44
+ cursor?: string;
45
+ }
46
+ /**
47
+ * Async generator for auto-pagination.
48
+ *
49
+ * Yields pages of items until no more pages are available.
50
+ *
51
+ * ```typescript
52
+ * for await (const page of paginate((params) => fabric.organizations.list(params))) {
53
+ * for (const org of page) { ... }
54
+ * }
55
+ * ```
56
+ */
57
+ declare function paginate<T>(fetcher: (params: PaginationParams) => Promise<PaginatedResponse<T>>, options?: {
58
+ limit?: number;
59
+ }): AsyncGenerator<T[], void, unknown>;
60
+ /**
61
+ * Async generator for item-level iteration (single items, not pages).
62
+ *
63
+ * ```typescript
64
+ * for await (const org of paginateItems((params) => fabric.organizations.list(params))) {
65
+ * console.log(org.name);
66
+ * }
67
+ * ```
68
+ */
69
+ declare function paginateItems<T>(fetcher: (params: PaginationParams) => Promise<PaginatedResponse<T>>, options?: {
70
+ limit?: number;
71
+ }): AsyncGenerator<T, void, unknown>;
72
+ /**
73
+ * Collect all pages into a single array.
74
+ *
75
+ * ```typescript
76
+ * const allOrgs = await paginateAll((params) => fabric.organizations.list(params));
77
+ * ```
78
+ */
79
+ declare function paginateAll<T>(fetcher: (params: PaginationParams) => Promise<PaginatedResponse<T>>, options?: {
80
+ limit?: number;
81
+ }): Promise<T[]>;
82
+
83
+ /**
84
+ * Low-level HTTP transport for the Fabric API.
85
+ *
86
+ * Wraps `fetch` with:
87
+ * - Base URL prefixing
88
+ * - Auth header injection (resolved per-request)
89
+ * - Envelope unwrapping (`data` on success, throws on `error`)
90
+ * - Typed error mapping
91
+ * - Retry on 429 with Retry-After
92
+ * - Timeout via AbortSignal
93
+ * - Idempotency key support
94
+ */
95
+
96
+ /** Interceptor called before each request. Can modify headers or log. */
97
+ type RequestInterceptor = (method: string, url: string, headers: Record<string, string>) => void | Promise<void>;
98
+ /** Interceptor called after each response. Can log or inspect. */
99
+ type ResponseInterceptor = (method: string, url: string, status: number, durationMs: number) => void | Promise<void>;
100
+ interface HttpTransportConfig {
101
+ baseUrl: string;
102
+ auth?: AuthConfig;
103
+ organizationId?: string;
104
+ teamId?: string;
105
+ timeout?: number;
106
+ fetch?: typeof globalThis.fetch;
107
+ retry?: {
108
+ maxRetries: number;
109
+ baseDelayMs: number;
110
+ };
111
+ /** Log all requests and responses to console. */
112
+ debug?: boolean;
113
+ /** Called before each request. */
114
+ onRequest?: RequestInterceptor;
115
+ /** Called after each response. */
116
+ onResponse?: ResponseInterceptor;
117
+ }
118
+ interface RequestOptions {
119
+ body?: unknown;
120
+ query?: Record<string, string | number | boolean | undefined>;
121
+ headers?: Record<string, string>;
122
+ idempotencyKey?: string;
123
+ signal?: AbortSignal;
124
+ /** Pass-through for Next.js extended fetch options (e.g. `next: { revalidate }`) */
125
+ requestInit?: RequestInit;
126
+ }
127
+ declare class HttpTransport {
128
+ private readonly baseUrl;
129
+ private readonly auth?;
130
+ private readonly organizationId?;
131
+ private readonly teamId?;
132
+ private readonly timeoutMs;
133
+ private readonly fetchFn;
134
+ private readonly retryConfig;
135
+ private readonly debug;
136
+ private readonly onRequest?;
137
+ private readonly onResponse?;
138
+ private oauthManager?;
139
+ constructor(config: HttpTransportConfig);
140
+ /** Getters for context values (used by resources). */
141
+ getOrganizationId(): string | undefined;
142
+ getTeamId(): string | undefined;
143
+ getBaseUrl(): string;
144
+ /** Make a request and unwrap the envelope, returning `data`. */
145
+ request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;
146
+ /** Make a request and unwrap a paginated envelope. */
147
+ requestPaginated<T>(method: string, path: string, opts?: RequestOptions): Promise<PaginatedResponse<T>>;
148
+ /** Make a request and return the raw Response (for SSE, file uploads, etc). */
149
+ requestRaw(method: string, path: string, opts?: RequestOptions): Promise<Response>;
150
+ /** Build full headers for a request (used by streaming). */
151
+ buildHeaders(extra?: Record<string, string>): Promise<Record<string, string>>;
152
+ private doFetch;
153
+ private fetchWithRetry;
154
+ private resolveAuth;
155
+ private buildUrl;
156
+ private throwIfError;
157
+ }
158
+
159
+ /** RBAC role hierarchy. */
160
+ type Role = "owner" | "admin" | "member" | "viewer";
161
+
162
+ /** Response envelope metadata. */
163
+ interface Meta {
164
+ request_id: string;
165
+ trace_id?: string;
166
+ status: number;
167
+ api_version: string;
168
+ }
169
+ /** Request context attached to responses. */
170
+ interface RequestContext {
171
+ principal_id?: string;
172
+ organization_id?: string;
173
+ team_id?: string;
174
+ }
175
+ /** Structured error body. */
176
+ interface ErrorBody {
177
+ code: string;
178
+ message: string;
179
+ }
180
+ /** Standard Fabric API response envelope. */
181
+ interface Envelope<T = unknown> {
182
+ meta: Meta;
183
+ context?: RequestContext;
184
+ data?: T;
185
+ error?: ErrorBody;
186
+ }
187
+ /** Paginated data wrapper. */
188
+ interface PaginatedData<T> {
189
+ items: T[];
190
+ pagination: {
191
+ count: number;
192
+ has_more: boolean;
193
+ next_cursor?: string;
194
+ };
195
+ }
196
+
197
+ /** User info returned from auth endpoints. */
198
+ interface AuthUser {
199
+ id: string;
200
+ email?: string;
201
+ }
202
+ /** Response from signup, login, and refresh endpoints. */
203
+ interface AuthResponse {
204
+ access_token: string;
205
+ refresh_token: string;
206
+ expires_in: number;
207
+ token_type: string;
208
+ user: AuthUser;
209
+ }
210
+ /** MFA enrollment response. */
211
+ interface MfaEnrollResponse {
212
+ id: string;
213
+ type: string;
214
+ totp?: {
215
+ qr_code: string;
216
+ secret: string;
217
+ uri: string;
218
+ };
219
+ }
220
+ /** MFA challenge response. */
221
+ interface MfaChallengeResponse {
222
+ id: string;
223
+ expires_at: number;
224
+ }
225
+ /** MFA verify response. */
226
+ interface MfaVerifyResponse {
227
+ access_token: string;
228
+ refresh_token: string;
229
+ expires_in: number;
230
+ token_type: string;
231
+ user: AuthUser;
232
+ }
233
+
234
+ interface Organization {
235
+ id: string;
236
+ slug: string;
237
+ name: string;
238
+ archived: boolean;
239
+ created_at: string;
240
+ updated_at: string;
241
+ }
242
+ interface CreateOrganizationRequest {
243
+ slug?: string;
244
+ name: string;
245
+ }
246
+ interface UpdateOrganizationRequest {
247
+ name?: string;
248
+ }
249
+ interface Membership {
250
+ id: string;
251
+ principal_id: string;
252
+ organization_id: string;
253
+ team_id: string | null;
254
+ role: Role;
255
+ active: boolean;
256
+ created_at: string;
257
+ updated_at: string;
258
+ }
259
+ interface OrgUsageSummary {
260
+ organization_id: string;
261
+ total_runs: number;
262
+ total_cost_usd: number;
263
+ period_start: string;
264
+ period_end: string;
265
+ }
266
+ interface OrgBudget {
267
+ organization_id: string;
268
+ monthly_limit_usd: number | null;
269
+ current_spend_usd: number;
270
+ }
271
+ interface OrgSecret {
272
+ name: string;
273
+ created_at: string;
274
+ updated_at: string;
275
+ }
276
+ interface CreateSecretRequest {
277
+ name: string;
278
+ value: string;
279
+ }
280
+ /** Organization settings. */
281
+ interface OrgSettings {
282
+ id: string;
283
+ organization_id: string;
284
+ display_name: string | null;
285
+ logo_url: string | null;
286
+ email_from_name: string | null;
287
+ webhook_url: string | null;
288
+ webhook_events: string[] | null;
289
+ max_pending_invitations: number;
290
+ max_invitations_per_hour: number;
291
+ }
292
+ /** Request to update organization settings. */
293
+ interface UpdateOrgSettingsRequest {
294
+ display_name?: string | null;
295
+ logo_url?: string | null;
296
+ email_from_name?: string | null;
297
+ webhook_url?: string | null;
298
+ webhook_events?: string[] | null;
299
+ max_pending_invitations?: number;
300
+ max_invitations_per_hour?: number;
301
+ }
302
+ /** Rotated webhook secret (one-time reveal). */
303
+ interface RotateWebhookSecretResponse {
304
+ webhook_signing_secret: string;
305
+ }
306
+ /** A daily usage rollup entry. */
307
+ interface UsageDailyEntry {
308
+ date: string;
309
+ total_cost_usd: number;
310
+ total_input_tokens: number;
311
+ total_output_tokens: number;
312
+ total_runs: number;
313
+ group_key?: string;
314
+ }
315
+ /** A detailed usage record. */
316
+ interface UsageRecord {
317
+ id: string;
318
+ action: string;
319
+ provider: string | null;
320
+ model: string | null;
321
+ input_tokens: number;
322
+ output_tokens: number;
323
+ cost_usd: number;
324
+ created_at: string;
325
+ }
326
+ /** System info returned by admin endpoint. */
327
+ interface SystemInfo {
328
+ version: string;
329
+ features: string[];
330
+ uptime_seconds?: number;
331
+ }
332
+ /** System status returned by admin endpoint. */
333
+ interface SystemStatus {
334
+ status: string;
335
+ database: string;
336
+ event_bus: string;
337
+ }
338
+
339
+ interface Team {
340
+ id: string;
341
+ organization_id: string;
342
+ slug: string;
343
+ name: string;
344
+ archived: boolean;
345
+ created_at: string;
346
+ updated_at: string;
347
+ }
348
+ interface CreateTeamRequest {
349
+ organization_id: string;
350
+ slug?: string;
351
+ name: string;
352
+ }
353
+
354
+ /** All event kinds emitted by the Fabric event bus. */
355
+ type EventKind = "workflow.run.created" | "workflow.run.queued" | "workflow.run.promoted" | "workflow.run.started" | "workflow.run.completed" | "workflow.run.failed" | "workflow.run.cancelled" | "workflow.run.waiting" | "workflow.run.paused" | "workflow.node.ready" | "workflow.node.claimed" | "workflow.node.started" | "workflow.node.progress" | "workflow.node.completed" | "workflow.node.failed" | "workflow.node.retried" | "workflow.node.skipped" | "workflow.node.cancelled" | "workflow.node.waiting_for_event" | "workflow.node.resumed" | "job.created" | "job.started" | "job.completed" | "job.failed" | "workflow.schedule.triggered" | "workflow.schedule.skipped" | "workflow.schedule.failed" | "webhook.delivery.exhausted" | "organization.created" | "team.created" | "membership.created" | "invitation.created" | "invitation.accepted" | "invitation.revoked";
356
+ /** Terminal event kinds that signal a workflow run is done. */
357
+ declare const TERMINAL_RUN_EVENTS: EventKind[];
358
+ /** Node-level event kinds for filtering in watch/stream. */
359
+ declare const NODE_EVENT_KINDS: EventKind[];
360
+ /** A domain event from the Fabric event bus. */
361
+ interface DomainEvent {
362
+ id: string;
363
+ kind: EventKind;
364
+ organization_id?: string;
365
+ job_id?: string;
366
+ workflow_id?: string;
367
+ run_id?: string;
368
+ node_key?: string;
369
+ payload: Record<string, unknown>;
370
+ timestamp: string;
371
+ }
372
+ /** Event handler callback. */
373
+ type EventHandler = (event: DomainEvent) => void;
374
+ /** Client-side filter for SSE event streams. */
375
+ interface EventStreamFilter {
376
+ /** Only deliver events matching these kinds. */
377
+ kinds?: EventKind[];
378
+ /** Only deliver node events for these node keys. */
379
+ nodeKeys?: string[];
380
+ }
381
+ /** Commands the client can send over the WebSocket. */
382
+ type WebSocketCommand = {
383
+ subscribe_run: string;
384
+ } | {
385
+ unsubscribe: true;
386
+ };
387
+ /** Acknowledgements the server sends in response to commands. */
388
+ type WebSocketAck = {
389
+ subscribed_to_run: string;
390
+ } | {
391
+ unsubscribed: true;
392
+ };
393
+
394
+ /** Workflow language for registry entries. */
395
+ type WorkflowLanguage = "rust" | "python" | "typescript";
396
+ /** Workflow source type. */
397
+ type WorkflowSource = "builtin" | "composed" | "custom";
398
+ /** Workflow run status. */
399
+ type RunStatus = "pending" | "running" | "completed" | "failed" | "cancelled" | "paused" | "waiting";
400
+ /** A workflow definition in the hierarchical registry. */
401
+ interface RegistryEntry {
402
+ id: string;
403
+ organization_id: string | null;
404
+ team_id: string | null;
405
+ name: string;
406
+ language: WorkflowLanguage;
407
+ source: WorkflowSource;
408
+ entry_point: string | null;
409
+ compose_from: string[] | null;
410
+ config: Record<string, unknown> | null;
411
+ version: string;
412
+ worker_tags: string[];
413
+ input_schema: Record<string, unknown> | null;
414
+ output_schema: Record<string, unknown> | null;
415
+ description: string | null;
416
+ created_at: string;
417
+ updated_at: string;
418
+ }
419
+ /** Request to create a registry entry. */
420
+ interface CreateRegistryRequest {
421
+ name: string;
422
+ language: WorkflowLanguage;
423
+ source: WorkflowSource;
424
+ entry_point?: string;
425
+ compose_from?: string[];
426
+ config?: Record<string, unknown>;
427
+ version?: string;
428
+ worker_tags?: string[];
429
+ input_schema?: Record<string, unknown>;
430
+ output_schema?: Record<string, unknown>;
431
+ description?: string;
432
+ }
433
+ /** Request to compose multiple workflows. */
434
+ interface ComposeWorkflowRequest {
435
+ name: string;
436
+ steps: string[];
437
+ description?: string;
438
+ }
439
+ /** Progress tracking for a workflow run. */
440
+ interface RunProgress {
441
+ total_tasks: number;
442
+ completed_tasks: number;
443
+ current_task: string | null;
444
+ percentage: number;
445
+ }
446
+ /** A workflow run (execution instance). */
447
+ interface WorkflowRun {
448
+ id: string;
449
+ sayiir_instance_id: string;
450
+ organization_id: string;
451
+ team_id: string | null;
452
+ registry_entry_id: string | null;
453
+ workflow_name: string;
454
+ created_by: string | null;
455
+ metadata: Record<string, unknown> | null;
456
+ status: RunStatus;
457
+ progress: RunProgress | null;
458
+ output: unknown | null;
459
+ error: string | null;
460
+ created_at: string;
461
+ }
462
+ /** Request to submit a workflow run. */
463
+ interface SubmitRunRequest {
464
+ input: Record<string, unknown>;
465
+ metadata?: Record<string, unknown>;
466
+ priority?: number;
467
+ }
468
+ /** Cost hint for a single workflow node. */
469
+ interface NodeCostHint {
470
+ provider?: string;
471
+ model?: string;
472
+ modality?: string;
473
+ calls?: number;
474
+ calls_from_input?: string;
475
+ }
476
+ /** Historical cost summary from past completed runs. */
477
+ interface HistoricalCostSummary {
478
+ avg_cost_usd: number;
479
+ min_cost_usd: number;
480
+ max_cost_usd: number;
481
+ sample_count: number;
482
+ per_node_avg: Record<string, number>;
483
+ }
484
+ /** Pre-execution workflow cost estimate. */
485
+ interface WorkflowCostEstimate {
486
+ total_estimated_usd: number;
487
+ per_node: Record<string, number>;
488
+ best_case_usd: number;
489
+ worst_case_usd: number;
490
+ source: "config" | "historical" | "hybrid" | "none";
491
+ historical: HistoricalCostSummary | null;
492
+ }
493
+ /** Request to estimate workflow cost. */
494
+ interface EstimateWorkflowRequest {
495
+ input?: Record<string, unknown>;
496
+ cost_profile?: {
497
+ nodes: Record<string, NodeCostHint>;
498
+ };
499
+ }
500
+ /** Options for `runs.watch()` — high-level workflow run observation. */
501
+ interface WatchRunOptions {
502
+ /** Only deliver node events for these node keys (omit for all nodes). */
503
+ nodeKeys?: string[];
504
+ /** Called when a node reports progress. */
505
+ onNodeProgress?: (nodeKey: string, payload: Record<string, unknown>) => void;
506
+ /** Called when a node starts executing. */
507
+ onNodeStarted?: (nodeKey: string, payload: Record<string, unknown>) => void;
508
+ /** Called when a node completes successfully. */
509
+ onNodeCompleted?: (nodeKey: string, payload: Record<string, unknown>) => void;
510
+ /** Called when a node fails. */
511
+ onNodeFailed?: (nodeKey: string, payload: Record<string, unknown>) => void;
512
+ /** Called when the workflow run completes. */
513
+ onRunCompleted?: (payload: Record<string, unknown>) => void;
514
+ /** Called when the workflow run fails. */
515
+ onRunFailed?: (payload: Record<string, unknown>) => void;
516
+ /** Called when the workflow run is cancelled. */
517
+ onRunCancelled?: (payload: Record<string, unknown>) => void;
518
+ /** Called for every event (in addition to typed callbacks). */
519
+ onEvent?: (event: DomainEvent) => void;
520
+ /** Called on stream errors. */
521
+ onError?: (error: Error) => void;
522
+ /** AbortSignal for manual cancellation. */
523
+ signal?: AbortSignal;
524
+ /** Enable auto-reconnection (default: true). */
525
+ reconnect?: boolean;
526
+ /** Resume from a specific event ID. */
527
+ lastEventId?: string;
528
+ }
529
+ /** Handle returned by `runs.watch()`. */
530
+ interface RunWatcher {
531
+ /** Abort the watcher and disconnect. */
532
+ abort(): void;
533
+ /** Resolves when the watcher stops (terminal event, abort, or max reconnect failures). */
534
+ readonly done: Promise<void>;
535
+ }
536
+ /** An artifact produced by a workflow run. */
537
+ interface RunArtifact {
538
+ id: string;
539
+ run_id: string;
540
+ asset_id: string | null;
541
+ task_id: string;
542
+ filename: string;
543
+ content_type: string | null;
544
+ produced_by: string | null;
545
+ consumed_from: string[] | null;
546
+ metadata: Record<string, unknown> | null;
547
+ created_at: string;
548
+ /** Signed download URL (populated by `artifactsWithUrls()`). */
549
+ download_url?: string;
550
+ }
551
+ /** Request to record an artifact for a workflow run. */
552
+ interface RecordArtifactRequest {
553
+ asset_id?: string;
554
+ task_id: string;
555
+ filename: string;
556
+ content_type?: string;
557
+ produced_by?: string;
558
+ consumed_from?: string[];
559
+ metadata?: Record<string, unknown>;
560
+ }
561
+ /** Node execution attempt with log excerpts. */
562
+ interface NodeAttempt {
563
+ id: string;
564
+ workflow_run_node_id: string;
565
+ status: string;
566
+ stdout_excerpt: string | null;
567
+ stderr_excerpt: string | null;
568
+ error_message: string | null;
569
+ duration_ms: number | null;
570
+ output: unknown | null;
571
+ created_at: string;
572
+ }
573
+
574
+ /** Asset kind. */
575
+ type AssetKind = "upload" | "generated" | "derivation";
576
+ /** An uploaded or generated asset. */
577
+ interface Asset {
578
+ id: string;
579
+ organization_id: string;
580
+ created_by: string;
581
+ kind: AssetKind;
582
+ content_type: string;
583
+ filename: string | null;
584
+ size_bytes: number;
585
+ storage_path: string;
586
+ derived_from: string | null;
587
+ created_at: string;
588
+ }
589
+ /** Response from signed URL generation. */
590
+ interface SignedUrlResponse {
591
+ url: string;
592
+ }
593
+
594
+ interface Gallery {
595
+ id: string;
596
+ organization_id: string | null;
597
+ name: string;
598
+ description: string | null;
599
+ kind: string;
600
+ tags: string[];
601
+ created_at: string;
602
+ updated_at: string;
603
+ }
604
+ interface GalleryItem {
605
+ id: string;
606
+ gallery_id: string;
607
+ asset_id: string;
608
+ label: string | null;
609
+ tags: string[];
610
+ sort_order: number;
611
+ created_at: string;
612
+ }
613
+ interface CreateGalleryRequest {
614
+ name: string;
615
+ description?: string;
616
+ kind: string;
617
+ tags?: string[];
618
+ }
619
+ interface AddGalleryItemRequest {
620
+ asset_id: string;
621
+ label?: string;
622
+ tags?: string[];
623
+ sort_order?: number;
624
+ }
625
+
626
+ interface ApiKey {
627
+ id: string;
628
+ prefix: string;
629
+ owner_principal_id: string;
630
+ organization_id: string;
631
+ team_id: string | null;
632
+ description: string | null;
633
+ scopes: string[];
634
+ disabled: boolean;
635
+ expires_at: string | null;
636
+ last_used_at: string | null;
637
+ created_at: string;
638
+ updated_at: string;
639
+ }
640
+ /** Returned only at creation time — includes the raw secret. */
641
+ interface CreateApiKeyResponse {
642
+ id: string;
643
+ prefix: string;
644
+ secret: string;
645
+ scopes: string[];
646
+ created_at: string;
647
+ }
648
+ interface CreateApiKeyRequest {
649
+ description?: string;
650
+ scopes?: string[];
651
+ expires_in_days?: number;
652
+ }
653
+
654
+ interface ServiceAccount {
655
+ id: string;
656
+ organization_id: string;
657
+ team_id: string | null;
658
+ name: string;
659
+ disabled: boolean;
660
+ created_at: string;
661
+ updated_at: string;
662
+ }
663
+ interface CreateServiceAccountRequest {
664
+ name: string;
665
+ team_id?: string;
666
+ }
667
+
668
+ type PermissionEffect = "allow" | "deny";
669
+ interface Permission {
670
+ id: string;
671
+ principal_id: string;
672
+ resource_type: string;
673
+ resource_id: string;
674
+ action: string;
675
+ effect: PermissionEffect;
676
+ granted_by: string | null;
677
+ created_at: string;
678
+ expires_at: string | null;
679
+ }
680
+ interface GrantPermissionRequest {
681
+ principal_id: string;
682
+ resource_type: string;
683
+ resource_id: string;
684
+ action: string;
685
+ effect?: PermissionEffect;
686
+ expires_in_hours?: number;
687
+ }
688
+ interface AuthzCheckRequest {
689
+ resource: string;
690
+ action: string;
691
+ }
692
+ interface AuthzCheckResponse {
693
+ allowed: boolean;
694
+ reason?: string;
695
+ }
696
+
697
+ interface Webhook {
698
+ id: string;
699
+ organization_id: string;
700
+ url: string;
701
+ description: string | null;
702
+ event_filter: string[];
703
+ resource_filter: WebhookResourceFilter | null;
704
+ active: boolean;
705
+ max_retries: number;
706
+ created_by: string | null;
707
+ created_at: string;
708
+ updated_at: string;
709
+ }
710
+ interface WebhookResourceFilter {
711
+ workflow_definition_id?: string;
712
+ workflow_run_id?: string;
713
+ job_id?: string;
714
+ }
715
+ interface WebhookDelivery {
716
+ id: string;
717
+ webhook_id: string;
718
+ event_id: string;
719
+ event_kind: string;
720
+ status: string;
721
+ status_code: number | null;
722
+ error_message: string | null;
723
+ attempt: number;
724
+ next_retry_at: string | null;
725
+ created_at: string;
726
+ completed_at: string | null;
727
+ }
728
+ interface CreateWebhookRequest {
729
+ url: string;
730
+ event_filter?: string[];
731
+ resource_filter?: WebhookResourceFilter;
732
+ description?: string;
733
+ max_retries?: number;
734
+ }
735
+ interface UpdateWebhookRequest {
736
+ url?: string;
737
+ event_filter?: string[];
738
+ resource_filter?: WebhookResourceFilter | null;
739
+ description?: string;
740
+ active?: boolean;
741
+ max_retries?: number;
742
+ }
743
+
744
+ interface WorkflowSchedule {
745
+ id: string;
746
+ workflow_definition_id: string;
747
+ organization_id: string;
748
+ cron_expression: string;
749
+ timezone: string;
750
+ enabled: boolean;
751
+ input_context: Record<string, unknown>;
752
+ input_template: Record<string, unknown> | null;
753
+ on_failure: 'skip' | 'retry';
754
+ max_retries: number;
755
+ consecutive_failures: number;
756
+ concurrency_policy: 'allow' | 'skip' | 'queue';
757
+ active_run_id: string | null;
758
+ next_run_at: string | null;
759
+ last_run_id: string | null;
760
+ last_run_at: string | null;
761
+ created_at: string;
762
+ updated_at: string;
763
+ }
764
+ interface ScheduleRun {
765
+ id: string;
766
+ schedule_id: string;
767
+ workflow_run_id: string;
768
+ triggered_at: string;
769
+ trigger_type: 'cron' | 'manual';
770
+ status: 'submitted' | 'skipped_overlap' | 'failed_to_submit';
771
+ error_message: string | null;
772
+ resolved_input: Record<string, unknown> | null;
773
+ created_at: string;
774
+ }
775
+ interface CreateScheduleRequest {
776
+ cron_expression: string;
777
+ timezone?: string;
778
+ input_context?: Record<string, unknown>;
779
+ input_template?: Record<string, unknown>;
780
+ on_failure?: 'skip' | 'retry';
781
+ max_retries?: number;
782
+ concurrency_policy?: 'allow' | 'skip' | 'queue';
783
+ enabled?: boolean;
784
+ }
785
+ interface UpdateScheduleRequest {
786
+ cron_expression?: string;
787
+ timezone?: string;
788
+ input_context?: Record<string, unknown>;
789
+ input_template?: Record<string, unknown> | null;
790
+ on_failure?: 'skip' | 'retry';
791
+ max_retries?: number;
792
+ concurrency_policy?: 'allow' | 'skip' | 'queue';
793
+ enabled?: boolean;
794
+ }
795
+
796
+ interface MeResponse {
797
+ principal_id: string;
798
+ principal_type: "user" | "service_account";
799
+ email?: string;
800
+ display_name?: string;
801
+ }
802
+ interface MyOrgSummary {
803
+ id: string;
804
+ slug: string;
805
+ name: string;
806
+ role: Role;
807
+ }
808
+ interface MyTeamSummary {
809
+ id: string;
810
+ organization_id: string;
811
+ slug: string;
812
+ name: string;
813
+ role: Role;
814
+ }
815
+
816
+ type InvitationStatus = "pending" | "accepted" | "revoked" | "expired";
817
+ interface Invitation {
818
+ id: string;
819
+ organization_id: string;
820
+ team_id: string | null;
821
+ email: string;
822
+ role: Role;
823
+ status: InvitationStatus;
824
+ expires_at: string;
825
+ accepted_at: string | null;
826
+ revoked_at: string | null;
827
+ created_at: string;
828
+ updated_at: string;
829
+ }
830
+ interface CreateInvitationRequest {
831
+ organization_id: string;
832
+ email: string;
833
+ role: Role;
834
+ team_id?: string;
835
+ }
836
+
837
+ interface OAuthClient {
838
+ id: string;
839
+ organization_id: string;
840
+ client_name: string;
841
+ client_id: string;
842
+ redirect_uris: string[];
843
+ scopes: string[];
844
+ created_at: string;
845
+ updated_at: string;
846
+ }
847
+ interface CreateOAuthClientRequest {
848
+ client_name: string;
849
+ redirect_uris?: string[];
850
+ scopes?: string[];
851
+ }
852
+ interface OAuthTokenResponse {
853
+ access_token: string;
854
+ refresh_token: string;
855
+ expires_in: number;
856
+ token_type: string;
857
+ }
858
+
859
+ /** Platform identifier for source documents. */
860
+ type Platform = "reddit" | "twitter" | "youtube" | "hn" | (string & {});
861
+ /** Raw ingested content from a platform. */
862
+ interface SourceDocument {
863
+ id: string;
864
+ platform: Platform;
865
+ subreddit: string | null;
866
+ post_id: string;
867
+ parent_id: string | null;
868
+ author: string | null;
869
+ title: string | null;
870
+ body: string;
871
+ score: number;
872
+ num_comments: number;
873
+ created_at: string;
874
+ url: string;
875
+ embedding: number[] | null;
876
+ }
877
+ /** Atomic extracted problem signal from a source document. */
878
+ interface ProblemMention {
879
+ id: string;
880
+ source_document_id: string;
881
+ source_document_ids: string[];
882
+ problem_text: string;
883
+ normalized_problem: string;
884
+ persona: string | null;
885
+ context: string | null;
886
+ /** Range: -1 to 1 */
887
+ sentiment: number;
888
+ /** Range: 0 to 1 */
889
+ frustration: number;
890
+ /** Range: 0 to 1 */
891
+ urgency: number;
892
+ existing_solutions: string[];
893
+ /** Range: 0 to 1 */
894
+ dissatisfaction: number;
895
+ created_at: string;
896
+ }
897
+ /** Canonical grouping of related problem mentions. */
898
+ interface ProblemCluster {
899
+ id: string;
900
+ canonical_problem: string;
901
+ category: string;
902
+ persona: string;
903
+ mention_count: number;
904
+ unique_users: number;
905
+ avg_sentiment: number;
906
+ avg_frustration: number;
907
+ avg_urgency: number;
908
+ avg_dissatisfaction: number;
909
+ growth_velocity: number;
910
+ recency_score: number;
911
+ opportunity_score: number;
912
+ example_mentions: string[];
913
+ created_at: string;
914
+ updated_at: string;
915
+ }
916
+ /** Maps a problem mention to the cluster it belongs to. */
917
+ interface ProblemClusterMember {
918
+ problem_cluster_id: string;
919
+ problem_mention_id: string;
920
+ }
921
+ /** Ambiguous mention flagged for human review. */
922
+ interface ReviewItem {
923
+ problem_mention_id: string;
924
+ reason: string;
925
+ }
926
+ /** Detected solution/tool associated with a problem cluster. */
927
+ interface SolutionMention {
928
+ id: string;
929
+ problem_cluster_id: string;
930
+ name: string;
931
+ sentiment: number;
932
+ dissatisfaction: number;
933
+ frequency: number;
934
+ }
935
+ /** Scoring weights used for opportunity scoring. */
936
+ interface ScoringWeights {
937
+ pain: number;
938
+ demand: number;
939
+ growth: number;
940
+ solution_gap: number;
941
+ recency: number;
942
+ }
943
+ /** Complete problem intelligence pipeline output. */
944
+ interface ProblemIntelligenceOutput {
945
+ workflow: "research/problem-intelligence";
946
+ scope: "global" | "niche";
947
+ query: string;
948
+ platforms_queried: string[];
949
+ total_sources_collected: number;
950
+ platform_summary: Record<string, number>;
951
+ ranked_clusters: ProblemCluster[];
952
+ source_documents: SourceDocument[];
953
+ problem_mentions: ProblemMention[];
954
+ clusters: ProblemCluster[];
955
+ solution_mentions: SolutionMention[];
956
+ problem_cluster_members?: ProblemClusterMember[];
957
+ review_items?: ReviewItem[];
958
+ ideas: unknown[];
959
+ specs: unknown[];
960
+ scoring_weights: {
961
+ opportunity: ScoringWeights;
962
+ idea: Record<string, number>;
963
+ };
964
+ errors: Record<string, string>;
965
+ }
966
+
967
+ /** AI provider modality. */
968
+ type Modality = "text" | "image" | "audio" | "video" | "embedding" | "classification";
969
+ /** Quality tier for provider routing. */
970
+ type Tier = "basic" | "standard" | "premium";
971
+ /** Capability tag for filtering providers. */
972
+ type CapabilityTag = "reasoning" | "coding" | "creative" | "fast" | "multimodal" | "local" | "structured_output";
973
+ /** A provider capability summary from the registry. */
974
+ interface ProviderCapability {
975
+ provider_id: string;
976
+ modality: Modality;
977
+ model: string;
978
+ supports_streaming: boolean;
979
+ }
980
+ /** Per-request credentials (BYOK). */
981
+ interface ProviderCredentials {
982
+ [key: string]: string;
983
+ }
984
+ /** Request to execute a provider. */
985
+ interface ProviderExecuteRequest {
986
+ modality: Modality;
987
+ model?: string;
988
+ tier?: Tier;
989
+ input: unknown;
990
+ params?: Record<string, unknown>;
991
+ provider_id?: string;
992
+ credentials?: ProviderCredentials;
993
+ response_schema?: Record<string, unknown>;
994
+ required_tags?: CapabilityTag[];
995
+ preferred_tags?: CapabilityTag[];
996
+ }
997
+ /** Response from provider execution. */
998
+ interface ProviderExecuteResponse {
999
+ provider_id: string;
1000
+ model: string;
1001
+ modality: Modality;
1002
+ output: unknown;
1003
+ usage: {
1004
+ input_tokens: number;
1005
+ output_tokens: number;
1006
+ estimated_cost_usd: number;
1007
+ };
1008
+ }
1009
+
1010
+ /** An installed domain package. */
1011
+ interface Package {
1012
+ name: string;
1013
+ version: string;
1014
+ description: string;
1015
+ operation_prefixes: string[];
1016
+ node_count: number;
1017
+ }
1018
+
1019
+ /**
1020
+ * Auth resource — stateless.
1021
+ *
1022
+ * All methods RETURN tokens. They do NOT store them on the client.
1023
+ * Socialite is responsible for persisting tokens in cookies/session.
1024
+ */
1025
+
1026
+ declare class MfaResource {
1027
+ private readonly http;
1028
+ constructor(http: HttpTransport);
1029
+ /** Enroll a new MFA factor (e.g., "totp"). */
1030
+ enroll(factorType: string, friendlyName?: string): Promise<MfaEnrollResponse>;
1031
+ /** Request an MFA challenge for a factor. */
1032
+ challenge(factorId: string): Promise<MfaChallengeResponse>;
1033
+ /** Verify an MFA code. Returns new tokens on success. */
1034
+ verify(factorId: string, challengeId: string, code: string): Promise<MfaVerifyResponse>;
1035
+ /** Remove an MFA factor. */
1036
+ unenroll(factorId: string): Promise<void>;
1037
+ }
1038
+ declare class AuthResource {
1039
+ private readonly http;
1040
+ readonly mfa: MfaResource;
1041
+ constructor(http: HttpTransport);
1042
+ /** Sign up with email and password. Returns tokens + user. */
1043
+ signup(email: string, password: string): Promise<AuthResponse>;
1044
+ /** Log in with email and password. Returns tokens + user. */
1045
+ login(email: string, password: string): Promise<AuthResponse>;
1046
+ /** Log out (revoke tokens). */
1047
+ logout(): Promise<void>;
1048
+ /** Refresh an access token using a refresh token. */
1049
+ refresh(refreshToken: string): Promise<AuthResponse>;
1050
+ /** Request a magic link email. */
1051
+ magicLink(email: string): Promise<void>;
1052
+ /** Request a password reset email. */
1053
+ forgotPassword(email: string): Promise<void>;
1054
+ /** Reset password with a recovery token. */
1055
+ resetPassword(accessToken: string, newPassword: string): Promise<void>;
1056
+ /** Get the URL for social login redirect (e.g., "google", "github"). */
1057
+ socialLoginUrl(provider: string): string;
1058
+ /** Verify an email address using a verification token. */
1059
+ verify(token: string): Promise<void>;
1060
+ }
1061
+
1062
+ declare class MeResource {
1063
+ private readonly http;
1064
+ constructor(http: HttpTransport);
1065
+ /** Get current principal info. */
1066
+ get(): Promise<MeResponse>;
1067
+ /** List organizations the current user belongs to. */
1068
+ organizations(): Promise<MyOrgSummary[]>;
1069
+ /** List teams the current user belongs to. */
1070
+ teams(): Promise<MyTeamSummary[]>;
1071
+ /** List effective permissions for the current user. */
1072
+ permissions(): Promise<Permission[]>;
1073
+ }
1074
+
1075
+ declare class OrganizationsResource {
1076
+ private readonly http;
1077
+ constructor(http: HttpTransport);
1078
+ /** Create an organization. */
1079
+ create(opts: CreateOrganizationRequest): Promise<Organization>;
1080
+ /** List organizations (paginated). */
1081
+ list(params?: PaginationParams): Promise<PaginatedResponse<Organization>>;
1082
+ /** Get an organization by ID. */
1083
+ get(orgId: string): Promise<Organization>;
1084
+ /** Update an organization (e.g., rename). */
1085
+ update(orgId: string, opts: UpdateOrganizationRequest): Promise<Organization>;
1086
+ /** Archive an organization (soft-delete). */
1087
+ archive(orgId: string): Promise<Organization>;
1088
+ /** List teams in an organization. */
1089
+ teams(orgId: string, params?: PaginationParams): Promise<PaginatedResponse<Team>>;
1090
+ /** List members in an organization. */
1091
+ members(orgId: string, params?: PaginationParams): Promise<PaginatedResponse<Membership>>;
1092
+ /** List permissions for an organization. */
1093
+ permissions(orgId: string): Promise<Permission[]>;
1094
+ /** Get usage summary for an organization. */
1095
+ usage(orgId: string): Promise<OrgUsageSummary>;
1096
+ /** Get audit logs for an organization. */
1097
+ auditLogs(orgId: string, params?: PaginationParams): Promise<PaginatedResponse<Record<string, unknown>>>;
1098
+ /** Export organization data. */
1099
+ export(orgId: string): Promise<Record<string, unknown>>;
1100
+ /** Request organization deletion. */
1101
+ requestDeletion(orgId: string): Promise<void>;
1102
+ /** Get budget configuration. */
1103
+ getBudget(orgId: string): Promise<OrgBudget>;
1104
+ /** Set budget limit. */
1105
+ setBudget(orgId: string, monthlyLimitUsd: number): Promise<OrgBudget>;
1106
+ /** Get organization settings. */
1107
+ getSettings(orgId: string): Promise<OrgSettings>;
1108
+ /** Update organization settings. */
1109
+ updateSettings(orgId: string, settings: UpdateOrgSettingsRequest): Promise<OrgSettings>;
1110
+ /** Rotate the webhook signing secret (one-time reveal of new secret). */
1111
+ rotateWebhookSecret(orgId: string): Promise<RotateWebhookSecretResponse>;
1112
+ /** Get daily usage rollup with optional grouping (provider, model, workflow). */
1113
+ usageDaily(orgId: string, params?: {
1114
+ from?: string;
1115
+ to?: string;
1116
+ group_by?: string;
1117
+ limit?: number;
1118
+ cursor?: string;
1119
+ }): Promise<PaginatedResponse<UsageDailyEntry>>;
1120
+ /** Get detailed usage records (individual provider executions). */
1121
+ usageRecords(orgId: string): Promise<UsageRecord[]>;
1122
+ /** List secrets for an organization. */
1123
+ listSecrets(orgId: string): Promise<OrgSecret[]>;
1124
+ /** Create a secret. */
1125
+ createSecret(orgId: string, opts: CreateSecretRequest): Promise<OrgSecret>;
1126
+ /** Delete a secret. */
1127
+ deleteSecret(orgId: string, name: string): Promise<void>;
1128
+ }
1129
+
1130
+ declare class TeamsResource {
1131
+ private readonly http;
1132
+ constructor(http: HttpTransport);
1133
+ /** Create a team within an organization. */
1134
+ create(opts: CreateTeamRequest): Promise<Team>;
1135
+ /** Get a team by ID. */
1136
+ get(teamId: string): Promise<Team>;
1137
+ }
1138
+
1139
+ /**
1140
+ * SSE (Server-Sent Events) parser for real-time event streaming.
1141
+ *
1142
+ * Uses `fetch` + `ReadableStream` instead of `EventSource` to support
1143
+ * custom headers (auth) and work in both Node.js 18+ and browsers/Edge Runtime.
1144
+ */
1145
+
1146
+ interface SSEOptions {
1147
+ /** Full URL to the SSE endpoint. */
1148
+ url: string;
1149
+ /** Headers to send (including auth). */
1150
+ headers: Record<string, string>;
1151
+ /** Resume from a specific event ID (Last-Event-ID header). */
1152
+ lastEventId?: string;
1153
+ /** AbortSignal for cancellation. */
1154
+ signal?: AbortSignal;
1155
+ /** Custom fetch implementation. */
1156
+ fetch?: typeof globalThis.fetch;
1157
+ /** Retry delay in ms from the server's `retry:` directive. */
1158
+ onRetry?: (retryMs: number) => void;
1159
+ }
1160
+ interface ReconnectingSSEOptions extends SSEOptions {
1161
+ /** Enable auto-reconnection on connection drop (default: false). */
1162
+ reconnect?: boolean;
1163
+ /** Maximum reconnection attempts before giving up (default: 10). */
1164
+ maxReconnectAttempts?: number;
1165
+ /** Base delay in ms for exponential backoff (default: 1000). */
1166
+ reconnectBaseDelayMs?: number;
1167
+ /** Client-side event filter. */
1168
+ filter?: EventStreamFilter;
1169
+ }
1170
+ interface SSEEvent {
1171
+ /** Event type from the `event:` field. */
1172
+ event?: string;
1173
+ /** Parsed JSON data from the `data:` field. */
1174
+ data: unknown;
1175
+ /** Event ID from the `id:` field. */
1176
+ id?: string;
1177
+ }
1178
+ /** Handle for a running SSE stream. */
1179
+ interface EventStream {
1180
+ /** Abort the stream. */
1181
+ abort(): void;
1182
+ /** Resolves when the stream ends (terminal event, server close, or abort). */
1183
+ readonly done: Promise<void>;
1184
+ }
1185
+ /** Returns true if the event passes the filter (or if no filter is set). */
1186
+ declare function matchesFilter(event: DomainEvent, filter?: EventStreamFilter): boolean;
1187
+ /**
1188
+ * Connect to an SSE endpoint with automatic reconnection and client-side filtering.
1189
+ *
1190
+ * On connection drop, reconnects with exponential backoff using the last
1191
+ * received event ID (Last-Event-ID) so the server replays missed events.
1192
+ */
1193
+ declare function connectReconnectingSSE<T extends DomainEvent = DomainEvent>(options: ReconnectingSSEOptions, onEvent: (event: T, raw: SSEEvent) => void, onError?: (error: Error) => void): EventStream;
1194
+
1195
+ /**
1196
+ * Workflows resource — the core resource for Socialite.
1197
+ *
1198
+ * Nested sub-resources:
1199
+ * - `registry` — CRUD for workflow definitions
1200
+ * - `runs` — execution, streaming, cancellation
1201
+ * - `compose()` — chain multiple workflows
1202
+ */
1203
+
1204
+ declare class WorkflowRegistryResource {
1205
+ private readonly http;
1206
+ constructor(http: HttpTransport);
1207
+ /** Create a workflow definition in the registry. */
1208
+ create(opts: CreateRegistryRequest): Promise<RegistryEntry>;
1209
+ /** List workflows visible to the current org (global + org + team). */
1210
+ list(params?: PaginationParams & {
1211
+ organization_id?: string;
1212
+ team_id?: string;
1213
+ }): Promise<PaginatedResponse<RegistryEntry>>;
1214
+ /** Get a workflow by name (resolves hierarchically: team > org > global). */
1215
+ get(name: string, opts?: {
1216
+ organization_id?: string;
1217
+ }): Promise<RegistryEntry>;
1218
+ /** Delete an org/team-scoped workflow (not global). */
1219
+ delete(name: string, opts?: {
1220
+ organization_id?: string;
1221
+ }): Promise<void>;
1222
+ }
1223
+ interface StreamEventsOptions {
1224
+ onEvent: EventHandler;
1225
+ onError?: (error: Error) => void;
1226
+ signal?: AbortSignal;
1227
+ lastEventId?: string;
1228
+ /** Client-side event filter. */
1229
+ filter?: EventStreamFilter;
1230
+ /** Enable auto-reconnection on connection drop. */
1231
+ reconnect?: boolean;
1232
+ /** Maximum reconnection attempts (default: 10). */
1233
+ maxReconnectAttempts?: number;
1234
+ }
1235
+ interface SubmitAndWaitOptions extends SubmitRunRequest {
1236
+ onEvent?: EventHandler;
1237
+ timeoutMs?: number;
1238
+ organization_id?: string;
1239
+ team_id?: string;
1240
+ }
1241
+ declare class WorkflowRunsResource {
1242
+ private readonly http;
1243
+ constructor(http: HttpTransport);
1244
+ /** Submit a workflow run. Returns immediately with a run ID. */
1245
+ submit(workflowName: string, opts?: SubmitRunRequest & {
1246
+ organization_id?: string;
1247
+ team_id?: string;
1248
+ idempotencyKey?: string;
1249
+ }): Promise<WorkflowRun>;
1250
+ /** List workflow runs. */
1251
+ list(params?: PaginationParams & {
1252
+ organization_id?: string;
1253
+ team_id?: string;
1254
+ }): Promise<PaginatedResponse<WorkflowRun>>;
1255
+ /** Get a run's status and progress. */
1256
+ get(runId: string): Promise<WorkflowRun>;
1257
+ /** Cancel a running workflow. */
1258
+ cancel(runId: string, reason?: string): Promise<void>;
1259
+ /** Pause a running workflow. */
1260
+ pause(runId: string, reason?: string): Promise<void>;
1261
+ /** Resume a paused workflow. */
1262
+ resume(runId: string): Promise<void>;
1263
+ /** Recover a stalled workflow from its last Sayiir checkpoint. */
1264
+ recover(runId: string): Promise<void>;
1265
+ /** Send an external signal to a waiting workflow (e.g. HITL approval). */
1266
+ signal(runId: string, signalName: string, payload?: Record<string, unknown>): Promise<void>;
1267
+ /** Approve or reject a waiting workflow (convenience wrapper over signal). */
1268
+ approve(runId: string, opts: {
1269
+ approved: boolean;
1270
+ reason?: string;
1271
+ data?: Record<string, unknown>;
1272
+ }): Promise<void>;
1273
+ /** List workflow runs currently waiting for a signal (pending approvals). */
1274
+ listWaiting(params?: {
1275
+ organization_id?: string;
1276
+ team_id?: string;
1277
+ }): Promise<WorkflowRun[]>;
1278
+ /**
1279
+ * Stream SSE events for a workflow run.
1280
+ *
1281
+ * - Replays existing events, then streams live
1282
+ * - Auto-reconnects via Last-Event-ID (when `reconnect: true`)
1283
+ * - Client-side filtering by event kind and node key
1284
+ * - Auto-closes on terminal events (completed/failed/cancelled)
1285
+ *
1286
+ * Returns an EventStream handle for cancellation.
1287
+ */
1288
+ streamEvents(runId: string, opts: StreamEventsOptions): EventStream;
1289
+ /**
1290
+ * Submit a workflow and wait for it to complete.
1291
+ *
1292
+ * Streams events via SSE while waiting. Returns the final WorkflowRun
1293
+ * with status and output.
1294
+ */
1295
+ submitAndWait(workflowName: string, opts: SubmitAndWaitOptions): Promise<WorkflowRun>;
1296
+ /** Get node execution attempts (logs) for a specific node. */
1297
+ getNodeAttempts(runId: string, nodeKey: string): Promise<NodeAttempt[]>;
1298
+ /** List artifacts produced by a workflow run. */
1299
+ artifacts(runId: string): Promise<RunArtifact[]>;
1300
+ /**
1301
+ * List artifacts with signed download URLs for each asset.
1302
+ *
1303
+ * Fetches artifacts, then generates a signed URL for each one that has
1304
+ * an `asset_id`. This is the recommended way for consumers to access
1305
+ * output files (videos, images, audio, text) from completed workflows.
1306
+ *
1307
+ * @example
1308
+ * ```ts
1309
+ * const artifacts = await fabric.workflows.runs.artifactsWithUrls(runId);
1310
+ * for (const a of artifacts) {
1311
+ * console.log(a.filename, a.download_url); // signed URL ready for download
1312
+ * }
1313
+ * ```
1314
+ */
1315
+ artifactsWithUrls(runId: string, expirySeconds?: number): Promise<RunArtifact[]>;
1316
+ /** Record an artifact produced by a workflow run (called by workers). */
1317
+ recordArtifact(runId: string, artifact: RecordArtifactRequest): Promise<RunArtifact>;
1318
+ /**
1319
+ * Watch a workflow run step-by-step with typed callbacks.
1320
+ *
1321
+ * High-level convenience that composes SSE streaming, client-side
1322
+ * filtering, auto-reconnection, and typed event dispatch.
1323
+ *
1324
+ * @example
1325
+ * ```ts
1326
+ * const watcher = fabric.workflows.runs.watch(runId, {
1327
+ * nodeKeys: ["transcribe", "render"],
1328
+ * onNodeStarted: (key) => console.log(`${key} started`),
1329
+ * onNodeProgress: (key, p) => console.log(`${key}: ${p.percentage}%`),
1330
+ * onNodeCompleted: (key) => console.log(`${key} done`),
1331
+ * onNodeFailed: (key, p) => console.error(`${key} failed:`, p),
1332
+ * onRunCompleted: () => console.log("Workflow finished!"),
1333
+ * onRunFailed: (p) => console.error("Workflow failed:", p),
1334
+ * });
1335
+ *
1336
+ * // Stop watching early
1337
+ * watcher.abort();
1338
+ *
1339
+ * // Or wait until completion
1340
+ * await watcher.done;
1341
+ * ```
1342
+ */
1343
+ watch(runId: string, opts?: WatchRunOptions): RunWatcher;
1344
+ }
1345
+ declare class WorkflowsResource {
1346
+ private readonly http;
1347
+ readonly registry: WorkflowRegistryResource;
1348
+ readonly runs: WorkflowRunsResource;
1349
+ constructor(http: HttpTransport);
1350
+ /** Compose multiple workflows into a pipeline. */
1351
+ compose(opts: ComposeWorkflowRequest): Promise<RegistryEntry>;
1352
+ /** Estimate cost of a workflow before running it. */
1353
+ estimate(workflowName: string, opts?: EstimateWorkflowRequest & {
1354
+ organization_id?: string;
1355
+ team_id?: string;
1356
+ }): Promise<WorkflowCostEstimate>;
1357
+ }
1358
+
1359
+ /**
1360
+ * Events resource — real-time event streaming.
1361
+ */
1362
+
1363
+ interface WebSocketConnection {
1364
+ /** Subscribe to events for a specific run. */
1365
+ subscribeToRun(runId: string): void;
1366
+ /** Unsubscribe from run-specific filtering. */
1367
+ unsubscribe(): void;
1368
+ /** Close the WebSocket connection. */
1369
+ close(): void;
1370
+ }
1371
+ interface WebSocketOptions {
1372
+ onEvent: EventHandler;
1373
+ onError?: (error: Event) => void;
1374
+ onClose?: () => void;
1375
+ /** Client-side event filter. */
1376
+ filter?: EventStreamFilter;
1377
+ /** Callback for server acknowledgements. */
1378
+ onAck?: (ack: WebSocketAck) => void;
1379
+ }
1380
+ interface StreamOptions {
1381
+ onEvent: EventHandler;
1382
+ onError?: (error: Error) => void;
1383
+ signal?: AbortSignal;
1384
+ lastEventId?: string;
1385
+ /** Client-side event filter. */
1386
+ filter?: EventStreamFilter;
1387
+ /** Enable auto-reconnection on connection drop (default: false). */
1388
+ reconnect?: boolean;
1389
+ /** Maximum reconnection attempts (default: 10). */
1390
+ maxReconnectAttempts?: number;
1391
+ }
1392
+ declare class EventsResource {
1393
+ private readonly http;
1394
+ constructor(http: HttpTransport);
1395
+ /** Build fetch wrapper that injects auth headers. */
1396
+ private authFetch;
1397
+ /**
1398
+ * Stream all domain events via SSE.
1399
+ *
1400
+ * This is a long-lived connection — call `stream.abort()` to disconnect.
1401
+ */
1402
+ stream(opts: StreamOptions): EventStream;
1403
+ /**
1404
+ * Stream events for a specific workflow run via SSE.
1405
+ *
1406
+ * Supports client-side filtering by event kind and node key, plus
1407
+ * auto-reconnection with Last-Event-ID replay.
1408
+ */
1409
+ streamRun(runId: string, opts: StreamOptions): EventStream;
1410
+ /**
1411
+ * Stream events for a specific job via SSE.
1412
+ *
1413
+ * A job is a single-node execution. Use this to watch one node
1414
+ * without receiving events from the rest of the workflow.
1415
+ */
1416
+ streamJob(jobId: string, opts: StreamOptions): EventStream;
1417
+ /**
1418
+ * Connect via WebSocket for bidirectional event streaming.
1419
+ *
1420
+ * Supports dynamic run subscription via `subscribeToRun()` / `unsubscribe()`.
1421
+ * Server acknowledgements are typed and delivered via `onAck`.
1422
+ * Only available in environments with WebSocket support (browser, Node.js 21+).
1423
+ */
1424
+ connectWebSocket(opts: WebSocketOptions): WebSocketConnection;
1425
+ }
1426
+
1427
+ declare class AssetsResource {
1428
+ private readonly http;
1429
+ constructor(http: HttpTransport);
1430
+ /**
1431
+ * Upload an asset (max 100 MB).
1432
+ *
1433
+ * @param data - File data as Blob, ArrayBuffer, or ReadableStream
1434
+ * @param opts - Content type and optional filename
1435
+ */
1436
+ upload(data: Blob | ArrayBuffer | ReadableStream<Uint8Array>, opts?: {
1437
+ contentType?: string;
1438
+ filename?: string;
1439
+ organization_id?: string;
1440
+ }): Promise<Asset>;
1441
+ /** List assets for the current organization. */
1442
+ list(params?: PaginationParams & {
1443
+ organization_id?: string;
1444
+ }): Promise<PaginatedResponse<Asset>>;
1445
+ /** Generate a signed download URL for an asset. */
1446
+ signedUrl(assetId: string, expirySeconds?: number): Promise<SignedUrlResponse>;
1447
+ /** Download an asset by path. Returns the raw Response for streaming. */
1448
+ download(path: string): Promise<Response>;
1449
+ }
1450
+
1451
+ declare class GalleriesResource {
1452
+ private readonly http;
1453
+ constructor(http: HttpTransport);
1454
+ /** Create a gallery. */
1455
+ create(opts: CreateGalleryRequest): Promise<Gallery>;
1456
+ /** List galleries. */
1457
+ list(params?: PaginationParams): Promise<PaginatedResponse<Gallery>>;
1458
+ /** Get a gallery by ID. */
1459
+ get(galleryId: string): Promise<Gallery>;
1460
+ /** Delete a gallery. */
1461
+ delete(galleryId: string): Promise<void>;
1462
+ /** Add an item to a gallery. */
1463
+ addItem(galleryId: string, opts: AddGalleryItemRequest): Promise<GalleryItem>;
1464
+ /** List items in a gallery. */
1465
+ listItems(galleryId: string, params?: PaginationParams): Promise<PaginatedResponse<GalleryItem>>;
1466
+ /** Remove an item from a gallery. */
1467
+ removeItem(itemId: string): Promise<void>;
1468
+ }
1469
+
1470
+ declare class ApiKeysResource {
1471
+ private readonly http;
1472
+ constructor(http: HttpTransport);
1473
+ /** Create an API key. Returns the raw secret (only shown once). */
1474
+ create(opts: CreateApiKeyRequest): Promise<CreateApiKeyResponse>;
1475
+ /** List API keys. */
1476
+ list(params?: PaginationParams): Promise<PaginatedResponse<ApiKey>>;
1477
+ /** Get an API key by ID. */
1478
+ get(keyId: string): Promise<ApiKey>;
1479
+ /** Delete an API key. */
1480
+ delete(keyId: string): Promise<void>;
1481
+ /** Disable an API key. */
1482
+ disable(keyId: string): Promise<void>;
1483
+ /** Rotate an API key (new secret issued). */
1484
+ rotate(keyId: string): Promise<CreateApiKeyResponse>;
1485
+ }
1486
+
1487
+ declare class InvitationsResource {
1488
+ private readonly http;
1489
+ constructor(http: HttpTransport);
1490
+ /** Create an invitation. */
1491
+ create(opts: CreateInvitationRequest): Promise<Invitation>;
1492
+ /** Accept an invitation. */
1493
+ accept(invitationId: string): Promise<void>;
1494
+ /** Revoke/cancel an invitation. */
1495
+ revoke(invitationId: string): Promise<void>;
1496
+ }
1497
+
1498
+ declare class PermissionsResource {
1499
+ private readonly http;
1500
+ constructor(http: HttpTransport);
1501
+ /** Check a single permission. */
1502
+ check(opts: AuthzCheckRequest): Promise<AuthzCheckResponse>;
1503
+ /** Check multiple permissions in batch. */
1504
+ checkBatch(checks: AuthzCheckRequest[]): Promise<AuthzCheckResponse[]>;
1505
+ /** Grant a permission (ACL entry). */
1506
+ grant(opts: GrantPermissionRequest): Promise<Permission>;
1507
+ /** List permissions. */
1508
+ list(params?: PaginationParams & {
1509
+ resource_type?: string;
1510
+ resource_id?: string;
1511
+ }): Promise<PaginatedResponse<Permission>>;
1512
+ /** Revoke a permission. */
1513
+ revoke(permissionId: string): Promise<void>;
1514
+ }
1515
+
1516
+ declare class WebhooksResource {
1517
+ private readonly http;
1518
+ constructor(http: HttpTransport);
1519
+ /** Create a webhook for an organization. */
1520
+ create(orgId: string, opts: CreateWebhookRequest): Promise<Webhook>;
1521
+ /** List webhooks for an organization. */
1522
+ list(orgId: string, params?: PaginationParams): Promise<PaginatedResponse<Webhook>>;
1523
+ /** Get a webhook by ID. */
1524
+ get(webhookId: string): Promise<Webhook>;
1525
+ /** Update a webhook. */
1526
+ update(webhookId: string, opts: UpdateWebhookRequest): Promise<Webhook>;
1527
+ /** Delete a webhook. */
1528
+ delete(webhookId: string): Promise<void>;
1529
+ /** List delivery attempts for a webhook. */
1530
+ deliveries(webhookId: string, params?: PaginationParams): Promise<PaginatedResponse<WebhookDelivery>>;
1531
+ }
1532
+
1533
+ declare class ServiceAccountsResource {
1534
+ private readonly http;
1535
+ constructor(http: HttpTransport);
1536
+ /** Create a service account. */
1537
+ create(opts: CreateServiceAccountRequest): Promise<ServiceAccount>;
1538
+ /** List service accounts. */
1539
+ list(params?: PaginationParams): Promise<PaginatedResponse<ServiceAccount>>;
1540
+ /** Get a service account by ID. */
1541
+ get(id: string): Promise<ServiceAccount>;
1542
+ /** Disable a service account. */
1543
+ disable(id: string): Promise<void>;
1544
+ /** Enable a service account. */
1545
+ enable(id: string): Promise<void>;
1546
+ /** Create an API key for a service account. */
1547
+ createApiKey(id: string): Promise<CreateApiKeyResponse>;
1548
+ /** List API keys for a service account. */
1549
+ listApiKeys(id: string): Promise<ApiKey[]>;
1550
+ /** Revoke an API key for a service account. */
1551
+ revokeApiKey(id: string, keyId: string): Promise<void>;
1552
+ /** Rotate an API key for a service account. */
1553
+ rotateApiKey(id: string, keyId: string): Promise<CreateApiKeyResponse>;
1554
+ }
1555
+
1556
+ declare class OAuthResource {
1557
+ private readonly http;
1558
+ constructor(http: HttpTransport);
1559
+ /** Create an OAuth client for an organization. */
1560
+ createClient(opts: CreateOAuthClientRequest): Promise<OAuthClient>;
1561
+ /** List OAuth clients. */
1562
+ listClients(): Promise<OAuthClient[]>;
1563
+ /** Delete an OAuth client. */
1564
+ deleteClient(clientId: string): Promise<void>;
1565
+ /** Exchange client credentials for an access token. */
1566
+ token(clientId: string, clientSecret: string): Promise<OAuthTokenResponse>;
1567
+ /** Refresh an access token. */
1568
+ refresh(refreshToken: string): Promise<OAuthTokenResponse>;
1569
+ /** Revoke an OAuth token. */
1570
+ revoke(token: string): Promise<void>;
1571
+ }
1572
+
1573
+ interface ConcurrencyLimit {
1574
+ id: string;
1575
+ scope: string;
1576
+ max_concurrent_runs: number;
1577
+ created_at: string;
1578
+ updated_at: string;
1579
+ }
1580
+ declare class AdminResource {
1581
+ private readonly http;
1582
+ constructor(http: HttpTransport);
1583
+ /** Bootstrap the system (dev mode: creates org + admin). */
1584
+ bootstrap(): Promise<Record<string, unknown>>;
1585
+ /** List concurrency limits. */
1586
+ listConcurrencyLimits(): Promise<ConcurrencyLimit[]>;
1587
+ /** Set a concurrency limit for a scope (e.g., "org:<uuid>"). */
1588
+ setConcurrencyLimit(scope: string, maxConcurrentRuns: number): Promise<ConcurrencyLimit>;
1589
+ /** Get system information (version, features, uptime). */
1590
+ systemInfo(): Promise<SystemInfo>;
1591
+ /** Get detailed system status (database, event bus health). */
1592
+ systemStatus(): Promise<SystemStatus>;
1593
+ /** List audit logs (standalone, not org-scoped). */
1594
+ auditLogs(params?: PaginationParams): Promise<PaginatedResponse<Record<string, unknown>>>;
1595
+ }
1596
+
1597
+ declare class SchedulesResource {
1598
+ private readonly http;
1599
+ constructor(http: HttpTransport);
1600
+ /** Create a schedule for a workflow definition. */
1601
+ create(workflowDefId: string, opts: CreateScheduleRequest): Promise<WorkflowSchedule>;
1602
+ /** List schedules for a workflow definition. */
1603
+ list(workflowDefId: string): Promise<WorkflowSchedule[]>;
1604
+ /** Get a schedule by ID. */
1605
+ get(scheduleId: string): Promise<WorkflowSchedule>;
1606
+ /** Update a schedule. */
1607
+ update(scheduleId: string, opts: UpdateScheduleRequest): Promise<WorkflowSchedule>;
1608
+ /** Delete a schedule. */
1609
+ delete(scheduleId: string): Promise<void>;
1610
+ /** Manually trigger a scheduled workflow run. */
1611
+ trigger(scheduleId: string): Promise<{
1612
+ workflow_run_id: string;
1613
+ schedule_id: string;
1614
+ trigger_type: string;
1615
+ }>;
1616
+ /** List run history for a schedule. */
1617
+ history(scheduleId: string): Promise<ScheduleRun[]>;
1618
+ }
1619
+
1620
+ /**
1621
+ * Providers resource — AI provider execution (feature-gated).
1622
+ *
1623
+ * Exposes modality-based routing to AI providers (text, image, audio, video, etc.)
1624
+ * with BYOK support via per-request credentials.
1625
+ */
1626
+
1627
+ declare class ProvidersResource {
1628
+ private readonly http;
1629
+ constructor(http: HttpTransport);
1630
+ /** List all available provider capabilities. */
1631
+ list(): Promise<ProviderCapability[]>;
1632
+ /** Execute a provider (request/response). */
1633
+ execute(request: ProviderExecuteRequest): Promise<ProviderExecuteResponse>;
1634
+ /**
1635
+ * Execute a provider with streaming (SSE).
1636
+ *
1637
+ * Streams token-level chunks during LLM inference.
1638
+ * Events: `chunk` (delta), `complete` (final response + usage), `error`.
1639
+ */
1640
+ executeStream(request: ProviderExecuteRequest, opts: {
1641
+ onChunk: (data: Record<string, unknown>) => void;
1642
+ onComplete?: (data: ProviderExecuteResponse) => void;
1643
+ onError?: (error: Error) => void;
1644
+ signal?: AbortSignal;
1645
+ }): EventStream;
1646
+ /** Estimate the cost of a provider execution before running it. */
1647
+ estimate(request: ProviderExecuteRequest): Promise<number>;
1648
+ }
1649
+
1650
+ declare class PackagesResource {
1651
+ private readonly http;
1652
+ constructor(http: HttpTransport);
1653
+ /** List all installed domain packages. */
1654
+ list(): Promise<Package[]>;
1655
+ }
1656
+
1657
+ /**
1658
+ * FabricClient — the main entry point for the SDK.
1659
+ *
1660
+ * Instantiate with a config, then access resources via namespaced properties:
1661
+ *
1662
+ * ```typescript
1663
+ * const fabric = new FabricClient({
1664
+ * baseUrl: 'https://api.fabric.ai',
1665
+ * auth: { type: 'api-key', key: 'fab_...' },
1666
+ * organizationId: 'org-uuid',
1667
+ * });
1668
+ *
1669
+ * const run = await fabric.workflows.runs.submit('research/deep_research', {
1670
+ * input: { query: 'AI trends' },
1671
+ * });
1672
+ *
1673
+ * const stream = fabric.workflows.runs.streamEvents(run.id, {
1674
+ * onEvent(event) { console.log(event.kind, event.node_key); },
1675
+ * });
1676
+ * ```
1677
+ */
1678
+
1679
+ interface FabricConfig {
1680
+ /** Base URL of the Fabric API. Default: http://localhost:3001 */
1681
+ baseUrl?: string;
1682
+ /**
1683
+ * Authentication strategy.
1684
+ *
1685
+ * - `{ type: 'api-key', key: 'fab_...' }` — API key auth
1686
+ * - `{ type: 'bearer', token: '...' }` — JWT bearer token
1687
+ * - `{ type: 'oauth', clientId, clientSecret }` — OAuth client credentials
1688
+ * - `() => Promise<string>` — dynamic per-request token (e.g., from Next.js cookies)
1689
+ */
1690
+ auth?: AuthConfig;
1691
+ /** Default organization ID for scoped requests. */
1692
+ organizationId?: string;
1693
+ /** Default team ID for scoped requests. */
1694
+ teamId?: string;
1695
+ /** Request timeout in milliseconds. Default: 30000 */
1696
+ timeout?: number;
1697
+ /** Custom fetch implementation (e.g., Next.js enhanced fetch for caching). */
1698
+ fetch?: typeof globalThis.fetch;
1699
+ /** Log all requests and responses to console. */
1700
+ debug?: boolean;
1701
+ /** Called before each request. Use for logging, metrics, tracing. */
1702
+ onRequest?: RequestInterceptor;
1703
+ /** Called after each response. Use for logging, metrics, tracing. */
1704
+ onResponse?: ResponseInterceptor;
1705
+ }
1706
+ declare class FabricClient {
1707
+ readonly auth: AuthResource;
1708
+ readonly me: MeResource;
1709
+ readonly organizations: OrganizationsResource;
1710
+ readonly teams: TeamsResource;
1711
+ readonly workflows: WorkflowsResource;
1712
+ readonly events: EventsResource;
1713
+ readonly assets: AssetsResource;
1714
+ readonly galleries: GalleriesResource;
1715
+ readonly apiKeys: ApiKeysResource;
1716
+ readonly invitations: InvitationsResource;
1717
+ readonly permissions: PermissionsResource;
1718
+ readonly webhooks: WebhooksResource;
1719
+ readonly serviceAccounts: ServiceAccountsResource;
1720
+ readonly oauth: OAuthResource;
1721
+ readonly admin: AdminResource;
1722
+ readonly schedules: SchedulesResource;
1723
+ readonly providers: ProvidersResource;
1724
+ readonly packages: PackagesResource;
1725
+ constructor(config?: FabricConfig);
1726
+ }
1727
+
1728
+ /**
1729
+ * Typed error classes mapping to Fabric API error responses.
1730
+ *
1731
+ * The HTTP transport parses the envelope's `error.code` and `error.message`
1732
+ * and throws the appropriate subclass, allowing consumers to catch specific
1733
+ * error types:
1734
+ *
1735
+ * ```typescript
1736
+ * try {
1737
+ * await fabric.organizations.create({ name: 'Acme' });
1738
+ * } catch (e) {
1739
+ * if (e instanceof FabricConflictError) { // slug taken }
1740
+ * if (e instanceof FabricAuthError) { // re-authenticate }
1741
+ * }
1742
+ * ```
1743
+ */
1744
+ interface FabricErrorParams {
1745
+ code: string;
1746
+ status: number;
1747
+ message: string;
1748
+ requestId?: string;
1749
+ traceId?: string;
1750
+ }
1751
+ declare class FabricError extends Error {
1752
+ readonly code: string;
1753
+ readonly status: number;
1754
+ readonly requestId?: string;
1755
+ readonly traceId?: string;
1756
+ constructor(params: FabricErrorParams);
1757
+ }
1758
+ /** 400 Bad Request / 422 Unprocessable Entity */
1759
+ declare class FabricValidationError extends FabricError {
1760
+ constructor(params: FabricErrorParams);
1761
+ }
1762
+ /** 401 Unauthorized */
1763
+ declare class FabricAuthError extends FabricError {
1764
+ constructor(params: FabricErrorParams);
1765
+ }
1766
+ /** 403 Forbidden */
1767
+ declare class FabricForbiddenError extends FabricError {
1768
+ constructor(params: FabricErrorParams);
1769
+ }
1770
+ /** 404 Not Found */
1771
+ declare class FabricNotFoundError extends FabricError {
1772
+ constructor(params: FabricErrorParams);
1773
+ }
1774
+ /** 409 Conflict */
1775
+ declare class FabricConflictError extends FabricError {
1776
+ constructor(params: FabricErrorParams);
1777
+ }
1778
+ /** 429 Too Many Requests */
1779
+ declare class FabricRateLimitError extends FabricError {
1780
+ readonly retryAfterMs?: number;
1781
+ constructor(params: FabricErrorParams & {
1782
+ retryAfterMs?: number;
1783
+ });
1784
+ }
1785
+ /** 5xx Server Error */
1786
+ declare class FabricServerError extends FabricError {
1787
+ constructor(params: FabricErrorParams);
1788
+ }
1789
+
1790
+ /**
1791
+ * Webhook signature verification utility.
1792
+ *
1793
+ * The Fabric backend signs every webhook delivery with HMAC-SHA256.
1794
+ * Headers sent with each delivery:
1795
+ * - `X-Fabric-Signature`: `sha256=<hex>` — HMAC of the raw body
1796
+ * - `X-Fabric-Event`: event kind (e.g. `workflow.run.completed`)
1797
+ * - `X-Fabric-Delivery`: unique delivery/event ID
1798
+ *
1799
+ * Works in both Node.js 18+ and browsers via Web Crypto API.
1800
+ */
1801
+
1802
+ /** Headers sent with each webhook delivery. */
1803
+ interface WebhookHeaders {
1804
+ "x-fabric-signature": string;
1805
+ "x-fabric-event": string;
1806
+ "x-fabric-delivery": string;
1807
+ }
1808
+ /**
1809
+ * Verify a webhook signature.
1810
+ *
1811
+ * @param rawBody - The raw request body string (do NOT parse before verifying)
1812
+ * @param signature - The `X-Fabric-Signature` header value (format: `sha256=<hex>`)
1813
+ * @param secret - Your webhook signing secret
1814
+ * @returns `true` if the signature is valid
1815
+ *
1816
+ * @example
1817
+ * ```ts
1818
+ * import { verifyWebhookSignature } from "@fabric-platform/sdk";
1819
+ *
1820
+ * app.post("/webhook", async (req, res) => {
1821
+ * const rawBody = req.body; // must be the raw string
1822
+ * const sig = req.headers["x-fabric-signature"];
1823
+ * if (!await verifyWebhookSignature(rawBody, sig, process.env.WEBHOOK_SECRET!)) {
1824
+ * return res.status(401).send("Invalid signature");
1825
+ * }
1826
+ * // safe to process
1827
+ * });
1828
+ * ```
1829
+ */
1830
+ declare function verifyWebhookSignature(rawBody: string, signature: string, secret: string): Promise<boolean>;
1831
+ /**
1832
+ * Verify the signature and parse the webhook payload in one call (Stripe pattern).
1833
+ *
1834
+ * Throws if the signature is invalid.
1835
+ *
1836
+ * @param rawBody - The raw request body string
1837
+ * @param signature - The `X-Fabric-Signature` header value
1838
+ * @param secret - Your webhook signing secret
1839
+ * @returns The parsed and typed `DomainEvent`
1840
+ *
1841
+ * @example
1842
+ * ```ts
1843
+ * import { constructWebhookEvent } from "@fabric-platform/sdk";
1844
+ *
1845
+ * app.post("/webhook", async (req, res) => {
1846
+ * let event;
1847
+ * try {
1848
+ * event = await constructWebhookEvent(
1849
+ * req.body,
1850
+ * req.headers["x-fabric-signature"]!,
1851
+ * process.env.WEBHOOK_SECRET!,
1852
+ * );
1853
+ * } catch {
1854
+ * return res.status(401).send("Invalid signature");
1855
+ * }
1856
+ *
1857
+ * switch (event.kind) {
1858
+ * case "workflow.run.completed":
1859
+ * console.log("Run completed:", event.run_id);
1860
+ * break;
1861
+ * case "workflow.run.failed":
1862
+ * console.error("Run failed:", event.payload);
1863
+ * break;
1864
+ * }
1865
+ * res.sendStatus(200);
1866
+ * });
1867
+ * ```
1868
+ */
1869
+ declare function constructWebhookEvent(rawBody: string, signature: string, secret: string): Promise<DomainEvent>;
1870
+
1871
+ /**
1872
+ * Backwards-compatible event logger from the original SDK.
1873
+ *
1874
+ * Usage:
1875
+ * ```typescript
1876
+ * import { logEvents } from '@fabric-platform/sdk';
1877
+ * fabric.workflows.runs.streamEvents(runId, { onEvent: logEvents });
1878
+ * ```
1879
+ */
1880
+
1881
+ /** Built-in event logger — prints workflow progress to the console. */
1882
+ declare const logEvents: (event: DomainEvent) => void;
1883
+
1884
+ export { type AddGalleryItemRequest, AdminResource, type ApiKey, ApiKeysResource, type Asset, type AssetKind, AssetsResource, type AuthConfig, AuthResource, type AuthResponse, type AuthStrategy, type AuthUser, type AuthzCheckRequest, type AuthzCheckResponse, type CapabilityTag, type ComposeWorkflowRequest, type ConcurrencyLimit, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateGalleryRequest, type CreateInvitationRequest, type CreateOAuthClientRequest, type CreateOrganizationRequest, type CreateRegistryRequest, type CreateScheduleRequest, type CreateSecretRequest, type CreateServiceAccountRequest, type CreateTeamRequest, type CreateWebhookRequest, type DomainEvent, type Envelope, type ErrorBody, type EstimateWorkflowRequest, type EventHandler, type EventKind, type EventStream, type EventStreamFilter, EventsResource, FabricAuthError, FabricClient, type FabricConfig, FabricConflictError, FabricError, type FabricErrorParams, FabricForbiddenError, FabricNotFoundError, FabricRateLimitError, FabricServerError, FabricValidationError, GalleriesResource, type Gallery, type GalleryItem, type GrantPermissionRequest, type HistoricalCostSummary, type Invitation, type InvitationStatus, InvitationsResource, MeResource, type MeResponse, type Membership, type Meta, type MfaChallengeResponse, type MfaEnrollResponse, type MfaVerifyResponse, type Modality, type MyOrgSummary, type MyTeamSummary, NODE_EVENT_KINDS, type NodeAttempt, type NodeCostHint, type OAuthClient, OAuthResource, type OAuthTokenResponse, type OrgBudget, type OrgSecret, type OrgSettings, type OrgUsageSummary, type Organization, OrganizationsResource, type Package, PackagesResource, type PaginatedData, type PaginatedResponse, type Pagination, type PaginationParams, type Permission, type PermissionEffect, PermissionsResource, type Platform, type ProblemCluster, type ProblemClusterMember, type ProblemIntelligenceOutput, type ProblemMention, type ProviderCapability, type ProviderCredentials, type ProviderExecuteRequest, type ProviderExecuteResponse, ProvidersResource, type ReconnectingSSEOptions, type RecordArtifactRequest, type RegistryEntry, type RequestContext, type RequestInterceptor, type ResponseInterceptor, type ReviewItem, type Role, type RotateWebhookSecretResponse, type RunArtifact, type RunProgress, type RunStatus, type RunWatcher, type SSEEvent, type ScheduleRun, SchedulesResource, type ScoringWeights, type ServiceAccount, ServiceAccountsResource, type SignedUrlResponse, type SolutionMention, type SourceDocument, type StreamEventsOptions, type StreamOptions, type SubmitAndWaitOptions, type SubmitRunRequest, type SystemInfo, type SystemStatus, TERMINAL_RUN_EVENTS, type Team, TeamsResource, type Tier, type UpdateOrgSettingsRequest, type UpdateOrganizationRequest, type UpdateScheduleRequest, type UpdateWebhookRequest, type UsageDailyEntry, type UsageRecord, type WatchRunOptions, type WebSocketAck, type WebSocketCommand, type WebSocketConnection, type WebSocketOptions, type Webhook, type WebhookDelivery, type WebhookHeaders, type WebhookResourceFilter, WebhooksResource, type WorkflowCostEstimate, type WorkflowLanguage, WorkflowRegistryResource, type WorkflowRun, WorkflowRunsResource, type WorkflowSchedule, type WorkflowSource, WorkflowsResource, connectReconnectingSSE, constructWebhookEvent, logEvents, matchesFilter, paginate, paginateAll, paginateItems, verifyWebhookSignature };