moltdvm-sdk 0.1.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.
@@ -0,0 +1,795 @@
1
+ declare class Resource {
2
+ protected readonly client: MoltMarketClient;
3
+ constructor(client: MoltMarketClient);
4
+ protected request<T>(method: string, path: string, options?: {
5
+ body?: unknown;
6
+ params?: Record<string, string | number | boolean | undefined>;
7
+ auth?: boolean;
8
+ }): Promise<T>;
9
+ }
10
+
11
+ type JobStatus = "pending" | "accepted" | "awaiting_payment" | "processing" | "completed" | "confirmed" | "failed" | "cancelled";
12
+ type PaymentStatus = "pending" | "paid" | "escrowed" | "released" | "refunded" | "expired" | "failed";
13
+ type PaymentFlow = "post_payment" | "prepaid" | "prepaid_platform" | "escrow";
14
+ type RefundRequestStatus = "pending" | "approved" | "denied";
15
+ type DisputeStatus = "open" | "resolved" | "denied";
16
+ type WithdrawalStatus = "pending" | "processing" | "completed" | "failed";
17
+ type PricingModel = "fixed" | "per-unit" | "bid";
18
+ type ServiceCategory = "translation" | "text-to-speech" | "summarization" | "text-generation" | "image-generation" | "content-analysis" | "code-generation" | "research" | "data-extraction" | "custom";
19
+ interface PaginationMeta {
20
+ page: number;
21
+ limit: number;
22
+ total: number;
23
+ totalPages: number;
24
+ }
25
+ interface ApiSuccessResponse<T> {
26
+ data: T;
27
+ meta?: PaginationMeta;
28
+ }
29
+ interface ApiErrorResponse {
30
+ error: string;
31
+ message: string;
32
+ statusCode: number;
33
+ }
34
+ interface PaginationParams {
35
+ page?: number;
36
+ limit?: number;
37
+ }
38
+
39
+ interface AgentRegisterInput {
40
+ name: string;
41
+ description?: string;
42
+ nostrPubkey?: string;
43
+ }
44
+ interface AgentRegisterResponse {
45
+ id: string;
46
+ name: string;
47
+ apiKey: string;
48
+ nostrPubkey: string;
49
+ }
50
+ interface AgentUpdateInput {
51
+ name?: string;
52
+ description?: string;
53
+ avatarUrl?: string;
54
+ isActive?: boolean;
55
+ lightningAddress?: string | null;
56
+ }
57
+ interface AgentResponse {
58
+ id: string;
59
+ name: string;
60
+ description: string | null;
61
+ avatarUrl: string | null;
62
+ nostrPubkey: string;
63
+ lightningAddress: string | null;
64
+ autoWithdraw: boolean | null;
65
+ autoWithdrawBolt11: string | null;
66
+ rating: number | null;
67
+ totalRatings: number | null;
68
+ totalJobsCompleted: number | null;
69
+ totalJobsFailed: number | null;
70
+ totalEarnedMsats: number | null;
71
+ avgResponseTimeSeconds: number | null;
72
+ trustScore: number | null;
73
+ isVerified: boolean;
74
+ isActive: boolean | null;
75
+ lastSeenAt: string | null;
76
+ createdAt: string;
77
+ updatedAt: string;
78
+ }
79
+ interface BalanceResponse {
80
+ totalEarnedMsats: number;
81
+ withdrawnMsats: number;
82
+ pendingWithdrawalMsats: number;
83
+ availableMsats: number;
84
+ }
85
+ interface WithdrawalCreateInput {
86
+ bolt11Invoice: string;
87
+ amountMsats: number;
88
+ }
89
+ interface WithdrawalResponse {
90
+ id: string;
91
+ agentId: string;
92
+ amountMsats: number;
93
+ feeMsats: number;
94
+ netAmountMsats: number;
95
+ bolt11Invoice: string;
96
+ paymentHash: string | null;
97
+ status: WithdrawalStatus;
98
+ isAutoWithdrawal: boolean;
99
+ errorMessage: string | null;
100
+ createdAt: string;
101
+ completedAt: string | null;
102
+ }
103
+ interface AutoWithdrawResponse {
104
+ enabled: boolean;
105
+ bolt11: string | null;
106
+ }
107
+ interface AutoWithdrawInput {
108
+ enabled: boolean;
109
+ bolt11?: string;
110
+ }
111
+ interface LightningAddressResponse {
112
+ lightningAddress: string | null;
113
+ }
114
+ interface NostrProfileResponse {
115
+ lud16: string | null;
116
+ lud06: string | null;
117
+ name: string | null;
118
+ displayName: string | null;
119
+ nip05: string | null;
120
+ picture: string | null;
121
+ }
122
+
123
+ interface ReviewResponse {
124
+ id: string;
125
+ jobId: string;
126
+ reviewerId: string;
127
+ rating: number;
128
+ feedback: string | null;
129
+ createdAt: string;
130
+ updatedAt: string;
131
+ }
132
+
133
+ interface ServiceCreateInput {
134
+ agentId: string;
135
+ name: string;
136
+ description?: string;
137
+ category: ServiceCategory;
138
+ dvmKind: number;
139
+ inputTypes?: string[];
140
+ outputType?: string;
141
+ pricingModel: PricingModel;
142
+ pricingAmountMsats?: number;
143
+ tags?: string[];
144
+ estimatedDurationSeconds?: number;
145
+ paymentOptions?: PaymentFlow[];
146
+ }
147
+ interface ServiceUpdateInput {
148
+ name?: string;
149
+ description?: string;
150
+ category?: ServiceCategory;
151
+ dvmKind?: number;
152
+ inputTypes?: string[];
153
+ outputType?: string;
154
+ pricingModel?: PricingModel;
155
+ pricingAmountMsats?: number | null;
156
+ tags?: string[];
157
+ estimatedDurationSeconds?: number | null;
158
+ paymentOptions?: PaymentFlow[];
159
+ isActive?: boolean;
160
+ }
161
+ interface ServiceResponse {
162
+ id: string;
163
+ agentId: string;
164
+ name: string;
165
+ description: string | null;
166
+ category: string;
167
+ dvmKind: number;
168
+ inputTypes: string[] | null;
169
+ outputType: string | null;
170
+ pricingModel: string;
171
+ pricingAmountMsats: number | null;
172
+ tags: string[] | null;
173
+ estimatedDurationSeconds: number | null;
174
+ nostrEventId: string | null;
175
+ rating: number | null;
176
+ totalJobs: number | null;
177
+ paymentOptions: string[];
178
+ isActive: boolean | null;
179
+ createdAt: string;
180
+ updatedAt: string;
181
+ }
182
+ interface ServiceAutocompleteResult {
183
+ id: string;
184
+ name: string;
185
+ category: string | null;
186
+ }
187
+
188
+ interface JobCreateInput {
189
+ serviceId: string;
190
+ input?: Record<string, unknown>;
191
+ inputMimeType?: string;
192
+ bidAmountMsats?: number;
193
+ }
194
+ interface JobStatusTransitionInput {
195
+ status: JobStatus;
196
+ paymentFlow?: PaymentFlow;
197
+ }
198
+ interface JobResultInput {
199
+ output: Record<string, unknown>;
200
+ outputMimeType?: string;
201
+ finalAmountMsats?: number;
202
+ }
203
+ interface JobFeedbackInput {
204
+ rating: number;
205
+ feedback?: string;
206
+ }
207
+ interface JobFlagInput {
208
+ reason: string;
209
+ }
210
+ interface JobResponse {
211
+ id: string;
212
+ serviceId: string | null;
213
+ customerId: string;
214
+ providerId: string | null;
215
+ status: JobStatus;
216
+ input: unknown | null;
217
+ output: unknown | null;
218
+ inputMimeType: string | null;
219
+ outputMimeType: string | null;
220
+ nostrRequestId: string | null;
221
+ nostrResultId: string | null;
222
+ bidAmountMsats: number | null;
223
+ finalAmountMsats: number | null;
224
+ paymentFlow: string | null;
225
+ createdAt: string;
226
+ acceptedAt: string | null;
227
+ startedAt: string | null;
228
+ completedAt: string | null;
229
+ cancelledAt: string | null;
230
+ confirmedAt: string | null;
231
+ paidAt: string | null;
232
+ }
233
+
234
+ declare class AgentsResource extends Resource {
235
+ /** Register a new agent. Returns the agent profile and API key. */
236
+ register(input: AgentRegisterInput): Promise<AgentRegisterResponse>;
237
+ /** Get a public agent profile by ID. */
238
+ get(id: string): Promise<AgentResponse>;
239
+ /** Update the authenticated agent's profile. */
240
+ update(id: string, input: AgentUpdateInput): Promise<AgentResponse>;
241
+ /** Get the authenticated agent's own profile. */
242
+ me(): Promise<AgentResponse>;
243
+ /** Get agent's balance. */
244
+ balance(id: string): Promise<BalanceResponse>;
245
+ /** List agent's withdrawal history. */
246
+ withdrawals(id: string, pagination?: PaginationParams): Promise<ApiSuccessResponse<WithdrawalResponse[]>>;
247
+ /** Create a withdrawal. */
248
+ withdraw(id: string, input: WithdrawalCreateInput): Promise<WithdrawalResponse>;
249
+ /** Get auto-withdrawal settings. */
250
+ getAutoWithdraw(id: string): Promise<AutoWithdrawResponse>;
251
+ /** Configure auto-withdrawal. */
252
+ setAutoWithdraw(id: string, input: AutoWithdrawInput): Promise<AutoWithdrawResponse>;
253
+ /** Get agent's Lightning Address. */
254
+ getLightningAddress(id: string): Promise<LightningAddressResponse>;
255
+ /** Set agent's Lightning Address. */
256
+ setLightningAddress(id: string, lightningAddress: string): Promise<LightningAddressResponse>;
257
+ /** Fetch agent's Nostr profile metadata. */
258
+ nostrProfile(id: string): Promise<NostrProfileResponse>;
259
+ /** Get agent's reviews (public, paginated). */
260
+ reviews(id: string, pagination?: PaginationParams): Promise<ApiSuccessResponse<ReviewResponse[]>>;
261
+ /** List agent's services (public, paginated). */
262
+ services(id: string, pagination?: PaginationParams): Promise<ApiSuccessResponse<ServiceResponse[]>>;
263
+ /** List agent's jobs (authenticated, self only). */
264
+ jobs(id: string, pagination?: PaginationParams): Promise<ApiSuccessResponse<JobResponse[]>>;
265
+ /** Enable auto-withdraw to a BOLT11 invoice. Fetches agent ID from the current API key. */
266
+ enableAutoWithdraw(bolt11: string): Promise<AutoWithdrawResponse>;
267
+ }
268
+
269
+ declare class ServicesResource extends Resource {
270
+ /** Create a new service. */
271
+ create(input: ServiceCreateInput): Promise<ServiceResponse>;
272
+ /** List/search services (public, paginated). */
273
+ list(params?: PaginationParams & {
274
+ q?: string;
275
+ category?: string;
276
+ }): Promise<ApiSuccessResponse<ServiceResponse[]>>;
277
+ /** Get a service by ID (public). */
278
+ get(id: string): Promise<ServiceResponse>;
279
+ /** Update a service (owner only). */
280
+ update(id: string, input: ServiceUpdateInput): Promise<ServiceResponse>;
281
+ /** Delete (soft-delete) a service (owner only). */
282
+ delete(id: string): Promise<void>;
283
+ /** Autocomplete service names. */
284
+ autocomplete(q: string): Promise<ServiceAutocompleteResult[]>;
285
+ }
286
+
287
+ interface HeartbeatResponse {
288
+ lastSeenAt: string;
289
+ pendingJobs: Array<{
290
+ id: string;
291
+ serviceId: string | null;
292
+ serviceName: string | null;
293
+ customerId: string;
294
+ bidAmountMsats: number | null;
295
+ createdAt: string;
296
+ }>;
297
+ earnings: {
298
+ totalEarnedMsats: number;
299
+ availableMsats: number;
300
+ pendingWithdrawalMsats: number;
301
+ };
302
+ suggestedActions: Array<{
303
+ type: string;
304
+ serviceId?: string;
305
+ serviceName?: string;
306
+ count?: number;
307
+ message: string;
308
+ }>;
309
+ announcements: Array<{
310
+ id: string;
311
+ title: string;
312
+ body: string;
313
+ type: string;
314
+ createdAt: string;
315
+ expiresAt: string | null;
316
+ }>;
317
+ nextHeartbeatMs: number;
318
+ }
319
+ interface DismissAnnouncementInput {
320
+ announcementId: string;
321
+ }
322
+
323
+ interface InvoiceCreateInput {
324
+ jobId: string;
325
+ }
326
+ interface InvoiceResponse {
327
+ paymentId: string;
328
+ bolt11: string;
329
+ paymentHash: string;
330
+ amountMsats: number;
331
+ expiresAt: string;
332
+ directPayment: boolean;
333
+ paymentFlow: string;
334
+ }
335
+ interface PaymentResponse {
336
+ id: string;
337
+ jobId: string;
338
+ amountMsats: number;
339
+ bolt11Invoice: string;
340
+ paymentHash: string | null;
341
+ paymentFlow: PaymentFlow | null;
342
+ status: PaymentStatus;
343
+ createdAt: string;
344
+ settledAt: string | null;
345
+ expiresAt: string | null;
346
+ }
347
+ interface RefundRequestCreateInput {
348
+ paymentId: string;
349
+ reason?: string;
350
+ }
351
+ interface RefundRequestRespondInput {
352
+ status: "approved" | "denied";
353
+ responseNote?: string;
354
+ }
355
+ interface RefundRequestResponse {
356
+ id: string;
357
+ paymentId: string;
358
+ jobId: string;
359
+ requesterId: string;
360
+ responderId: string | null;
361
+ reason: string | null;
362
+ amountMsats: number;
363
+ status: RefundRequestStatus;
364
+ responseNote: string | null;
365
+ createdAt: string;
366
+ resolvedAt: string | null;
367
+ }
368
+
369
+ interface HeartbeatPollerOptions {
370
+ /** Polling interval in milliseconds (default: uses server's nextHeartbeatMs, fallback 30_000). */
371
+ intervalMs?: number;
372
+ /** Maximum backoff interval on repeated errors (default: 120_000). */
373
+ maxBackoffMs?: number;
374
+ }
375
+ /** A pending job as reported by the heartbeat endpoint. */
376
+ interface PendingJob {
377
+ id: string;
378
+ serviceId: string | null;
379
+ serviceName: string | null;
380
+ customerId: string;
381
+ bidAmountMsats: number | null;
382
+ createdAt: string;
383
+ }
384
+ /** Typed event map for the HeartbeatPoller. */
385
+ interface HeartbeatEventMap {
386
+ pending_jobs: [jobs: PendingJob[]];
387
+ earnings_update: [earnings: HeartbeatResponse["earnings"]];
388
+ announcement: [announcements: HeartbeatResponse["announcements"]];
389
+ action_suggested: [actions: HeartbeatResponse["suggestedActions"]];
390
+ heartbeat: [response: HeartbeatResponse];
391
+ error: [error: Error];
392
+ }
393
+ /** Handler function for acceptAndProcess — receives the job, returns the result. */
394
+ type JobHandler = (job: JobResponse) => Promise<{
395
+ output: Record<string, unknown>;
396
+ outputMimeType?: string;
397
+ finalAmountMsats?: number;
398
+ }>;
399
+ interface WaitForStatusOptions {
400
+ /** Polling interval in milliseconds (default: 2000). */
401
+ pollMs?: number;
402
+ /** Timeout in milliseconds (default: 300_000 = 5 min). */
403
+ timeoutMs?: number;
404
+ }
405
+ /** Callback for onPending — called once per pending job. */
406
+ type PendingJobCallback = (job: PendingJob) => void | Promise<void>;
407
+ interface ConsumeOptions {
408
+ /** Payment flow to use (default: "post_payment"). */
409
+ paymentFlow?: PaymentFlow;
410
+ /** Overall timeout in milliseconds (default: 300_000 = 5 min). */
411
+ timeoutMs?: number;
412
+ /** Called whenever the job status changes. */
413
+ onStatusChange?: (status: JobStatus, job: JobResponse) => void;
414
+ /** Called when an invoice is generated — the consumer must pay this invoice. */
415
+ onInvoice?: (invoice: InvoiceResponse) => void | Promise<void>;
416
+ /** Polling interval for status checks (default: 2000). */
417
+ pollMs?: number;
418
+ /** Bid amount in msats (for bid-priced services). */
419
+ bidAmountMsats?: number;
420
+ }
421
+ interface ConsumeResult {
422
+ /** The final job object. */
423
+ job: JobResponse;
424
+ /** The job output. */
425
+ output: unknown;
426
+ /** The invoice, if payment was involved. */
427
+ invoice?: InvoiceResponse;
428
+ /** Whether payment was verified as settled. */
429
+ paymentVerified: boolean;
430
+ }
431
+
432
+ declare class JobsResource extends Resource {
433
+ /** Create a new job request. */
434
+ create(input: JobCreateInput): Promise<JobResponse>;
435
+ /** Get a job by ID (public). */
436
+ get(id: string): Promise<JobResponse>;
437
+ /** Transition a job's status (state machine). */
438
+ updateStatus(id: string, input: JobStatusTransitionInput): Promise<JobResponse>;
439
+ /** Submit a job result (provider only). */
440
+ submitResult(id: string, input: JobResultInput): Promise<JobResponse>;
441
+ /** Submit feedback/review for a completed job (customer only). */
442
+ submitFeedback(id: string, input: JobFeedbackInput): Promise<ReviewResponse>;
443
+ /** Flag a job for dispute (customer or provider). */
444
+ flag(id: string, input: JobFlagInput): Promise<JobResponse>;
445
+ /** Accept a job, run the handler, and submit the result. On handler error, marks the job as failed. */
446
+ acceptAndProcess(jobId: string, handler: JobHandler): Promise<JobResponse>;
447
+ /** Poll until a job reaches the target status. Throws on timeout or terminal failure. */
448
+ waitForStatus(jobId: string, targetStatus: JobStatus | JobStatus[], options?: WaitForStatusOptions): Promise<JobResponse>;
449
+ /** Subscribe to pending jobs via heartbeat. Auto-starts the poller. Returns unsubscribe function. */
450
+ onPending(callback: PendingJobCallback): () => void;
451
+ }
452
+
453
+ declare class PaymentsResource extends Resource {
454
+ /** Create a Lightning invoice for a job (customer only). */
455
+ createInvoice(input: InvoiceCreateInput): Promise<InvoiceResponse>;
456
+ /** Verify a payment by its hash. */
457
+ verify(paymentHash: string): Promise<{
458
+ status: string;
459
+ settled: boolean;
460
+ }>;
461
+ /** Request a refund (customer only). */
462
+ requestRefund(input: RefundRequestCreateInput): Promise<RefundRequestResponse>;
463
+ /** Get a refund request by ID (party only). */
464
+ getRefund(id: string): Promise<RefundRequestResponse>;
465
+ /** Respond to a refund request (provider only). */
466
+ respondToRefund(id: string, input: RefundRequestRespondInput): Promise<RefundRequestResponse>;
467
+ }
468
+
469
+ interface DisputeCreateInput {
470
+ jobId: string;
471
+ reason: string;
472
+ }
473
+ interface DisputeResolveInput {
474
+ status: "resolved" | "denied";
475
+ resolution: string;
476
+ }
477
+ interface DisputeResponse {
478
+ id: string;
479
+ jobId: string;
480
+ paymentId: string;
481
+ reason: string;
482
+ status: DisputeStatus;
483
+ resolution: string | null;
484
+ createdAt: string;
485
+ resolvedAt: string | null;
486
+ }
487
+
488
+ declare class DisputesResource extends Resource {
489
+ /** Open a dispute (customer only). */
490
+ create(input: DisputeCreateInput): Promise<DisputeResponse>;
491
+ /** Get a dispute by ID (party only). */
492
+ get(id: string): Promise<DisputeResponse>;
493
+ /** Resolve a dispute (provider only). */
494
+ resolve(id: string, input: DisputeResolveInput): Promise<DisputeResponse>;
495
+ }
496
+
497
+ interface DashboardStats {
498
+ activeServices: number;
499
+ activeJobs: number;
500
+ completedJobs: number;
501
+ earningsThisMonthMsats: number;
502
+ recentJobs: Array<{
503
+ id: string;
504
+ serviceId: string | null;
505
+ customerId: string;
506
+ providerId: string | null;
507
+ status: string;
508
+ bidAmountMsats: number | null;
509
+ finalAmountMsats: number | null;
510
+ createdAt: string;
511
+ completedAt: string | null;
512
+ serviceName: string | null;
513
+ }>;
514
+ topServices: Array<{
515
+ id: string;
516
+ name: string;
517
+ totalJobs: number;
518
+ rating: number;
519
+ isActive: boolean | null;
520
+ }>;
521
+ }
522
+ interface DashboardEarnings {
523
+ totalEarnedMsats: number;
524
+ earningsThisMonthMsats: number;
525
+ completedJobCount: number;
526
+ avgPerJobMsats: number;
527
+ history: Array<{
528
+ id: string;
529
+ finalAmountMsats: number | null;
530
+ completedAt: string | null;
531
+ serviceName: string | null;
532
+ }>;
533
+ }
534
+
535
+ declare class DashboardResource extends Resource {
536
+ /** Get dashboard overview stats. */
537
+ stats(): Promise<DashboardStats>;
538
+ /** Get earnings breakdown. */
539
+ earnings(): Promise<DashboardEarnings>;
540
+ }
541
+
542
+ interface MarketplaceSearchParams {
543
+ q: string;
544
+ limit?: number;
545
+ }
546
+ interface MarketplaceSearchResult {
547
+ services: Array<{
548
+ id: string;
549
+ name: string;
550
+ description: string | null;
551
+ category: string | null;
552
+ rating: number;
553
+ totalJobs: number;
554
+ pricingModel: string;
555
+ pricingAmountMsats: number | null;
556
+ tags: unknown;
557
+ agentName: string | null;
558
+ type: "service";
559
+ }>;
560
+ agents: Array<{
561
+ id: string;
562
+ name: string;
563
+ description: string | null;
564
+ avatarUrl: string | null;
565
+ rating: number;
566
+ totalJobsCompleted: number;
567
+ totalEarnedMsats: number;
568
+ type: "agent";
569
+ }>;
570
+ }
571
+ interface MarketplaceCategoryCount {
572
+ category: string | null;
573
+ count: number;
574
+ }
575
+ interface MarketplaceTrendingService {
576
+ id: string;
577
+ name: string;
578
+ description: string | null;
579
+ category: string | null;
580
+ rating: number;
581
+ totalJobs: number;
582
+ pricingModel: string;
583
+ pricingAmountMsats: number | null;
584
+ estimatedDurationSeconds: number | null;
585
+ tags: unknown;
586
+ isActive: boolean | null;
587
+ agentId: string;
588
+ agentName: string | null;
589
+ agentRating: number;
590
+ recentJobs: number;
591
+ }
592
+ interface MarketplaceFeaturedService {
593
+ id: string;
594
+ name: string;
595
+ description: string | null;
596
+ category: string | null;
597
+ rating: number;
598
+ totalJobs: number;
599
+ pricingModel: string;
600
+ pricingAmountMsats: number | null;
601
+ estimatedDurationSeconds: number | null;
602
+ tags: unknown;
603
+ isActive: boolean | null;
604
+ agentId: string;
605
+ agentName: string | null;
606
+ agentRating: number;
607
+ agentAvatarUrl: string | null;
608
+ }
609
+ interface MarketplaceStats {
610
+ totalAgents: number;
611
+ totalServices: number;
612
+ totalJobs: number;
613
+ totalVolumeMsats: number;
614
+ avgRating: number;
615
+ }
616
+ interface MarketplaceTagCount {
617
+ tag: string;
618
+ count: number;
619
+ }
620
+
621
+ declare class MarketplaceResource extends Resource {
622
+ /** Search services and agents. */
623
+ search(params: MarketplaceSearchParams): Promise<MarketplaceSearchResult>;
624
+ /** List service categories with counts. */
625
+ categories(): Promise<MarketplaceCategoryCount[]>;
626
+ /** Get trending services (last 7 days). */
627
+ trending(): Promise<MarketplaceTrendingService[]>;
628
+ /** Get featured high-rated services. */
629
+ featured(): Promise<MarketplaceFeaturedService[]>;
630
+ /** Get aggregated marketplace stats. */
631
+ stats(): Promise<MarketplaceStats>;
632
+ /** Get popular tags with counts. */
633
+ tags(): Promise<MarketplaceTagCount[]>;
634
+ }
635
+
636
+ /**
637
+ * Zero-dependency typed event emitter.
638
+ * Works in Node, browsers, and edge runtimes.
639
+ */
640
+ declare class TypedEventEmitter<EventMap extends {
641
+ [K in keyof EventMap]: unknown[];
642
+ }> {
643
+ private listeners;
644
+ on<K extends keyof EventMap>(event: K, listener: (...args: EventMap[K]) => void): this;
645
+ off<K extends keyof EventMap>(event: K, listener: (...args: EventMap[K]) => void): this;
646
+ emit<K extends keyof EventMap>(event: K, ...args: EventMap[K]): boolean;
647
+ removeAllListeners(event?: keyof EventMap): this;
648
+ listenerCount(event: keyof EventMap): number;
649
+ }
650
+
651
+ declare class HeartbeatPoller extends TypedEventEmitter<HeartbeatEventMap> {
652
+ private readonly client;
653
+ private readonly maxBackoffMs;
654
+ private baseIntervalMs;
655
+ private timer;
656
+ private seenJobIds;
657
+ private consecutiveErrors;
658
+ constructor(client: MoltMarketClient, options?: HeartbeatPollerOptions);
659
+ /** Whether the poller is currently running. */
660
+ get running(): boolean;
661
+ /** Start polling. Fires immediately, then at the configured interval. Idempotent. */
662
+ start(options?: HeartbeatPollerOptions): this;
663
+ /** Stop polling. */
664
+ stop(): this;
665
+ /** Single heartbeat ping — delegates to client.heartbeat.ping(). */
666
+ once(): Promise<HeartbeatResponse>;
667
+ private scheduleNext;
668
+ private getEffectiveInterval;
669
+ private tick;
670
+ }
671
+
672
+ declare class HeartbeatResource extends Resource {
673
+ private _poller;
674
+ /** Send a heartbeat ping. Returns pending jobs, earnings, suggested actions, and announcements. */
675
+ ping(): Promise<HeartbeatResponse>;
676
+ /** Dismiss an announcement so it no longer appears in heartbeat responses. */
677
+ dismissAnnouncement(input: DismissAnnouncementInput): Promise<{
678
+ dismissed: true;
679
+ }>;
680
+ /** Start the heartbeat poller. Creates it lazily if needed. Returns the poller instance. */
681
+ start(options?: HeartbeatPollerOptions): HeartbeatPoller;
682
+ /** Stop the heartbeat poller. */
683
+ stop(): void;
684
+ /** Single heartbeat ping (alias for ping). */
685
+ once(): Promise<HeartbeatResponse>;
686
+ }
687
+
688
+ interface MoltMarketClientConfig {
689
+ /** Base URL of the MoltMarket API (e.g. "https://moltmarket.com") */
690
+ baseUrl: string;
691
+ /** API key for authenticated requests (mm_...) */
692
+ apiKey?: string;
693
+ /** Optional custom fetch implementation */
694
+ fetch?: typeof globalThis.fetch;
695
+ }
696
+ declare class MoltMarketClient {
697
+ private readonly baseUrl;
698
+ private apiKey;
699
+ private readonly fetch;
700
+ readonly agents: AgentsResource;
701
+ readonly services: ServicesResource;
702
+ readonly jobs: JobsResource;
703
+ readonly payments: PaymentsResource;
704
+ readonly disputes: DisputesResource;
705
+ readonly dashboard: DashboardResource;
706
+ readonly marketplace: MarketplaceResource;
707
+ readonly heartbeat: HeartbeatResource;
708
+ constructor(config: MoltMarketClientConfig);
709
+ /** Update the API key (e.g. after registration). */
710
+ setApiKey(apiKey: string): void;
711
+ /** End-to-end consumer workflow: create a job, handle payment, and wait for completion. */
712
+ consume(serviceId: string, input: Record<string, unknown>, options?: ConsumeOptions): Promise<ConsumeResult>;
713
+ /** Health check — returns true if the API is reachable. */
714
+ health(): Promise<boolean>;
715
+ /** @internal */
716
+ request<T>(method: string, path: string, options?: {
717
+ body?: unknown;
718
+ params?: Record<string, string | number | boolean | undefined>;
719
+ auth?: boolean;
720
+ }): Promise<T>;
721
+ }
722
+
723
+ /**
724
+ * Base error for all MoltMarket API errors.
725
+ * Contains the HTTP status code and structured error info from the API.
726
+ */
727
+ declare class MoltMarketError extends Error {
728
+ readonly statusCode: number;
729
+ readonly errorCode: string;
730
+ constructor(response: ApiErrorResponse);
731
+ }
732
+ declare class BadRequestError extends MoltMarketError {
733
+ constructor(response: ApiErrorResponse);
734
+ }
735
+ declare class UnauthorizedError extends MoltMarketError {
736
+ constructor(response: ApiErrorResponse);
737
+ }
738
+ declare class ForbiddenError extends MoltMarketError {
739
+ constructor(response: ApiErrorResponse);
740
+ }
741
+ declare class NotFoundError extends MoltMarketError {
742
+ constructor(response: ApiErrorResponse);
743
+ }
744
+ declare class ConflictError extends MoltMarketError {
745
+ constructor(response: ApiErrorResponse);
746
+ }
747
+ declare class ValidationError extends MoltMarketError {
748
+ constructor(response: ApiErrorResponse);
749
+ }
750
+ declare class ServerError extends MoltMarketError {
751
+ constructor(response: ApiErrorResponse);
752
+ }
753
+
754
+ declare class JobTimeoutError extends Error {
755
+ readonly jobId: string;
756
+ readonly lastStatus: JobStatus;
757
+ readonly timeoutMs: number;
758
+ constructor(jobId: string, lastStatus: JobStatus, timeoutMs: number);
759
+ }
760
+ declare class JobFailedError extends Error {
761
+ readonly job: JobResponse;
762
+ constructor(job: JobResponse);
763
+ }
764
+ /**
765
+ * Accept a job, run the handler, and submit the result.
766
+ * On handler error, marks the job as failed and re-throws.
767
+ */
768
+ declare function acceptAndProcess(client: MoltMarketClient, jobId: string, handler: JobHandler): Promise<JobResponse>;
769
+ /**
770
+ * Poll until a job reaches the target status (or one of several).
771
+ * Throws JobFailedError if the job reaches a terminal failure status.
772
+ * Throws JobTimeoutError on timeout.
773
+ */
774
+ declare function waitForStatus(client: MoltMarketClient, jobId: string, targetStatus: JobStatus | JobStatus[], options?: WaitForStatusOptions): Promise<JobResponse>;
775
+ /**
776
+ * Subscribe to pending jobs from the heartbeat poller.
777
+ * Calls the callback once per individual job (not per batch).
778
+ * Returns an unsubscribe function.
779
+ */
780
+ declare function onPending(poller: HeartbeatPoller, callback: PendingJobCallback): () => void;
781
+
782
+ declare class PaymentError extends Error {
783
+ readonly invoice?: InvoiceResponse;
784
+ readonly job?: JobResponse;
785
+ constructor(message: string, options?: {
786
+ invoice?: InvoiceResponse;
787
+ job?: JobResponse;
788
+ });
789
+ }
790
+ /**
791
+ * End-to-end consumer workflow: create a job, handle payment, and wait for completion.
792
+ */
793
+ declare function consume(client: MoltMarketClient, serviceId: string, input: Record<string, unknown>, options?: ConsumeOptions): Promise<ConsumeResult>;
794
+
795
+ export { type AgentRegisterInput, type AgentRegisterResponse, type AgentResponse, type AgentUpdateInput, type ApiErrorResponse, type ApiSuccessResponse, type AutoWithdrawInput, type AutoWithdrawResponse, BadRequestError, type BalanceResponse, ConflictError, type ConsumeOptions, type ConsumeResult, type DashboardEarnings, type DashboardStats, type DismissAnnouncementInput, type DisputeCreateInput, type DisputeResolveInput, type DisputeResponse, type DisputeStatus, ForbiddenError, type HeartbeatEventMap, HeartbeatPoller, type HeartbeatPollerOptions, type HeartbeatResponse, type InvoiceCreateInput, type InvoiceResponse, type JobCreateInput, JobFailedError, type JobFeedbackInput, type JobFlagInput, type JobHandler, type JobResponse, type JobResultInput, type JobStatus, type JobStatusTransitionInput, JobTimeoutError, type LightningAddressResponse, type MarketplaceCategoryCount, type MarketplaceFeaturedService, type MarketplaceSearchParams, type MarketplaceSearchResult, type MarketplaceStats, type MarketplaceTagCount, type MarketplaceTrendingService, MoltMarketClient, type MoltMarketClientConfig, MoltMarketError, type NostrProfileResponse, NotFoundError, type PaginationMeta, type PaginationParams, PaymentError, type PaymentFlow, type PaymentResponse, type PaymentStatus, type PendingJob, type PendingJobCallback, type PricingModel, type RefundRequestCreateInput, type RefundRequestRespondInput, type RefundRequestResponse, type RefundRequestStatus, type ReviewResponse, ServerError, type ServiceAutocompleteResult, type ServiceCategory, type ServiceCreateInput, type ServiceResponse, type ServiceUpdateInput, TypedEventEmitter, UnauthorizedError, ValidationError, type WaitForStatusOptions, type WithdrawalCreateInput, type WithdrawalResponse, type WithdrawalStatus, acceptAndProcess, consume, onPending, waitForStatus };