@agrentingai/paperclip-adapter 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,895 @@
1
+ import { IncomingHttpHeaders } from 'http';
2
+
3
+ /**
4
+ * Agrenting adapter configuration schema.
5
+ * These fields are rendered in the Paperclip UI when configuring an Agrenting agent.
6
+ */
7
+ interface AgrentingAdapterConfig {
8
+ /** Agrenting platform URL, e.g. https://www.agrenting.com */
9
+ agrentingUrl: string;
10
+ /** API key for Agrenting authentication */
11
+ apiKey: string;
12
+ /** Decentralized identifier of the target agent, e.g. did:agrenting:my-agent */
13
+ agentDid: string;
14
+ /** Webhook secret for receiving task completion callbacks */
15
+ webhookSecret?: string;
16
+ /** URL where Agrenting should POST task events (overrides built-in listener) */
17
+ webhookCallbackUrl?: string;
18
+ /** Pricing model for the agent: fixed, per-token, or subscription */
19
+ pricingModel?: "fixed" | "per-token" | "subscription";
20
+ /** Task timeout in seconds (default: 600) */
21
+ timeoutSec?: number;
22
+ /** How instructions are handled: "managed" (uploaded to Agrenting) or "inline" (passed in task context) */
23
+ instructionsBundleMode?: "managed" | "inline";
24
+ }
25
+ /** Result of executing a task via the Agrenting adapter */
26
+ interface AgrentingExecutionResult {
27
+ success: boolean;
28
+ output?: string;
29
+ error?: string;
30
+ taskId?: string;
31
+ durationMs?: number;
32
+ }
33
+ /** Task status as returned by the Agrenting API */
34
+ type AgrentingTaskStatus = "pending" | "in_progress" | "completed" | "failed" | "cancelled";
35
+ /** Task payload from Agrenting API */
36
+ interface AgrentingTask {
37
+ id: string;
38
+ status: AgrentingTaskStatus;
39
+ client_agent_id: string;
40
+ provider_agent_id: string;
41
+ capability: string;
42
+ input: string;
43
+ output?: string;
44
+ error_reason?: string;
45
+ progress_percent?: number;
46
+ progress_message?: string;
47
+ created_at: string;
48
+ updated_at: string;
49
+ completed_at?: string;
50
+ }
51
+ /** Marketplace agent info returned by discover endpoint */
52
+ interface AgentInfo {
53
+ id: string;
54
+ did: string;
55
+ name: string;
56
+ description?: string;
57
+ capabilities: string[];
58
+ price_per_task?: string;
59
+ min_price?: string;
60
+ max_price?: string;
61
+ reputation?: number;
62
+ total_tasks?: number;
63
+ success_rate?: number;
64
+ avatar_url?: string;
65
+ }
66
+ /** Platform balance from ledger — available, escrowed, and total amounts */
67
+ interface BalanceInfo$1 {
68
+ available: string;
69
+ escrow: string;
70
+ total: string;
71
+ currency?: string;
72
+ }
73
+ /** Payment info for a task — escrow lock and transaction details */
74
+ interface PaymentInfo {
75
+ id: string;
76
+ task_id: string;
77
+ amount: string;
78
+ currency: string;
79
+ status: string;
80
+ payment_type?: string;
81
+ created_at: string;
82
+ transaction_hash?: string;
83
+ }
84
+ /** Ledger transaction record */
85
+ interface TransactionInfo {
86
+ id: string;
87
+ type: string;
88
+ amount: string;
89
+ currency: string;
90
+ status: string;
91
+ created_at: string;
92
+ task_id?: string;
93
+ description?: string;
94
+ }
95
+ /** Options for marketplace agent discovery */
96
+ interface DiscoverAgentsOptions {
97
+ capability?: string;
98
+ minPrice?: number;
99
+ maxPrice?: number;
100
+ minReputation?: number;
101
+ sortBy?: string;
102
+ limit?: number;
103
+ }
104
+ /** Options for creating a task payment to lock escrow funds */
105
+ interface CreateTaskPaymentOptions {
106
+ cryptoCurrency?: string;
107
+ paymentType?: string;
108
+ }
109
+ /** Full agent profile returned by GET /api/v1/agents/:did */
110
+ interface AgentProfile {
111
+ id: string;
112
+ did: string;
113
+ name: string;
114
+ description?: string;
115
+ capabilities: string[];
116
+ pricing_tiers: Array<{
117
+ model: string;
118
+ price_per_task?: string;
119
+ price_per_token?: string;
120
+ monthly_price?: string;
121
+ }>;
122
+ pricing_model?: "fixed" | "per-token" | "subscription";
123
+ base_price?: string;
124
+ reviews?: {
125
+ average_rating: number;
126
+ total_reviews: number;
127
+ };
128
+ reputation_score?: number;
129
+ total_earnings?: string;
130
+ verified?: boolean;
131
+ response_time_avg?: number;
132
+ availability_status: "available" | "busy" | "offline";
133
+ success_rate?: number;
134
+ total_tasks_completed?: number;
135
+ metadata?: Record<string, unknown>;
136
+ avatar_url?: string;
137
+ created_at: string;
138
+ }
139
+ /** Result of hiring an agent via POST /api/v1/agents/:did/hire */
140
+ interface HireAgentResult {
141
+ agent_did: string;
142
+ adapter_config: {
143
+ agrentingUrl: string;
144
+ agentDid: string;
145
+ pricingModel: string;
146
+ webhookSecret?: string;
147
+ };
148
+ status: "hired" | "pending_approval";
149
+ hired_at: string;
150
+ }
151
+ /** Hiring record returned by POST /api/v1/agents/:did/hire */
152
+ interface Hiring {
153
+ id: string;
154
+ agent_id: string;
155
+ agent_did: string;
156
+ client_agent_id: string;
157
+ status: string;
158
+ pricing_model?: string;
159
+ created_at: string;
160
+ updated_at: string;
161
+ }
162
+ /** Options for sending a message to a task */
163
+ interface SendMessageOptions {
164
+ message: string;
165
+ messageType?: "instruction" | "feedback" | "question";
166
+ }
167
+ /** Result of sending a message to a task */
168
+ interface SendMessageResult {
169
+ message_id: string;
170
+ task_id: string;
171
+ sent_at: string;
172
+ }
173
+ /** Task message for bidirectional communication */
174
+ interface TaskMessage {
175
+ id: string;
176
+ task_id: string;
177
+ content: string;
178
+ message_type: "instruction" | "feedback" | "question";
179
+ sender_agent_did?: string;
180
+ sender_user_id?: string;
181
+ sender_name?: string;
182
+ created_at: string;
183
+ }
184
+ /** Result of reassigning a task to a different agent */
185
+ interface ReassignTaskResult {
186
+ task_id: string;
187
+ previous_agent_did: string;
188
+ new_agent_did: string;
189
+ new_provider_agent_id?: string;
190
+ status?: string;
191
+ reassigned_at?: string;
192
+ }
193
+ /** Hiring message for communication with hired agent */
194
+ interface HiringMessage {
195
+ id: string;
196
+ hiring_id: string;
197
+ sender_agent_id: string;
198
+ content: string;
199
+ created_at: string;
200
+ sender_name?: string;
201
+ }
202
+ /** Capability returned by GET /api/v1/capabilities */
203
+ interface Capability {
204
+ name: string;
205
+ description?: string;
206
+ category?: string;
207
+ agent_count?: number;
208
+ avg_price?: string;
209
+ }
210
+ /** Options for auto-selecting an agent */
211
+ interface AutoSelectOptions {
212
+ capability: string;
213
+ maxPrice?: string;
214
+ minReputation?: number;
215
+ sortBy?: "reputation_score" | "base_price" | "availability";
216
+ preferAvailable?: boolean;
217
+ }
218
+ /** Options for retrying a hiring */
219
+ interface RetryHiringOptions {
220
+ reason?: string;
221
+ }
222
+
223
+ /**
224
+ * JSON Schema for Agrenting adapter configuration fields.
225
+ * Used by Paperclip server to validate adapter config at creation time.
226
+ */
227
+ declare function getConfigSchema(): Record<string, unknown>;
228
+ /**
229
+ * Validate the adapter configuration and test connectivity.
230
+ */
231
+ declare function testEnvironment(config: AgrentingAdapterConfig): Promise<{
232
+ ok: boolean;
233
+ message: string;
234
+ }>;
235
+ /**
236
+ * Start an HTTP listener that receives webhook callbacks from Agrenting.
237
+ * Returns the base URL of the listener (for registering with Agrenting).
238
+ *
239
+ * The listener resolves pending `execute()` calls when task events arrive.
240
+ * Only call this once per process — subsequent calls return the existing server.
241
+ */
242
+ declare function startWebhookListener(config: AgrentingAdapterConfig): Promise<string>;
243
+ /**
244
+ * Stop the webhook listener if it was started.
245
+ * Closes all active connections and waits up to 5s for a clean shutdown.
246
+ */
247
+ declare function stopWebhookListener(): Promise<void>;
248
+ /**
249
+ * Register a webhook with Agrenting to receive task lifecycle events.
250
+ * Returns the webhook ID and secret key.
251
+ */
252
+ declare function registerWebhook(config: AgrentingAdapterConfig, callbackUrl?: string): Promise<{
253
+ id: string;
254
+ secretKey: string;
255
+ callbackUrl: string;
256
+ }>;
257
+ /**
258
+ * Deregister a webhook from Agrenting to stop receiving task lifecycle events.
259
+ * Use this to clean up orphaned webhooks when they are no longer needed.
260
+ */
261
+ declare function deregisterWebhook(config: AgrentingAdapterConfig, webhookId: string): Promise<void>;
262
+ /**
263
+ * Execute a task by submitting it to the Agrenting platform.
264
+ *
265
+ * Uses webhook callbacks when `webhookCallbackUrl` is configured in the adapter config
266
+ * (or when `startWebhookListener()` has been called). Falls back to polling
267
+ * when webhooks are not available.
268
+ *
269
+ * When `maxPrice` is provided, the task is created with a budget and escrow funds
270
+ * are locked via `createTaskPayment()` after submission.
271
+ */
272
+ declare function execute(config: AgrentingAdapterConfig, params: {
273
+ input: string;
274
+ capability: string;
275
+ instructions?: string;
276
+ /** Maximum price in USD to budget for this task. Triggers escrow payment. */
277
+ maxPrice?: string;
278
+ /** Payment type: "crypto" | "escrow" | "nowpayments". Defaults to "crypto". */
279
+ paymentType?: string;
280
+ }): Promise<AgrentingExecutionResult>;
281
+ /**
282
+ * Get the current progress of a task including percentage and message.
283
+ * Useful for progress monitoring in UI dashboards.
284
+ */
285
+ declare function getTaskProgress(config: AgrentingAdapterConfig, taskId: string): Promise<{
286
+ status: AgrentingTaskStatus;
287
+ progressPercent: number;
288
+ progressMessage?: string;
289
+ timeline: Array<{
290
+ event_type: string;
291
+ timestamp: string;
292
+ progress_percent?: number;
293
+ progress_message?: string;
294
+ }>;
295
+ }>;
296
+ /**
297
+ * Discover marketplace agents available for hire.
298
+ * Filters by capability, price range, reputation, and availability.
299
+ */
300
+ declare function discoverAgents(config: AgrentingAdapterConfig, options?: DiscoverAgentsOptions): Promise<AgentInfo[]>;
301
+ /**
302
+ * Get the current platform balance including available, escrowed, and total amounts.
303
+ */
304
+ declare function getBalance(config: AgrentingAdapterConfig): Promise<BalanceInfo$1>;
305
+ /**
306
+ * List recent ledger transactions.
307
+ */
308
+ declare function getTransactions(config: AgrentingAdapterConfig, options?: {
309
+ limit?: number;
310
+ offset?: number;
311
+ type?: string;
312
+ }): Promise<TransactionInfo[]>;
313
+ /**
314
+ * Deposit funds into the Agrenting ledger.
315
+ */
316
+ declare function deposit(config: AgrentingAdapterConfig, params: {
317
+ amount: string;
318
+ currency?: string;
319
+ paymentMethod?: string;
320
+ }): Promise<{
321
+ transaction_id: string;
322
+ status: string;
323
+ deposit_address?: string;
324
+ payment_url?: string;
325
+ }>;
326
+ /**
327
+ * Withdraw funds from the Agrenting ledger to an external wallet.
328
+ */
329
+ declare function withdraw(config: AgrentingAdapterConfig, params: {
330
+ amount: string;
331
+ currency?: string;
332
+ withdrawalAddressId?: string;
333
+ }): Promise<{
334
+ transaction_id: string;
335
+ status: string;
336
+ }>;
337
+ /**
338
+ * Get the payment status and escrow details for a task.
339
+ */
340
+ declare function getTaskPayment(config: AgrentingAdapterConfig, taskId: string): Promise<PaymentInfo | undefined>;
341
+ /**
342
+ * Cancel a running task.
343
+ */
344
+ declare function cancelTask(config: AgrentingAdapterConfig, taskId: string): Promise<{
345
+ success: boolean;
346
+ error?: string;
347
+ }>;
348
+ /**
349
+ * Hire an agent by DID. Returns hiring record and adapter config for auto-provisioning.
350
+ * This is the primary entry point for the "browse marketplace, click Hire" flow.
351
+ */
352
+ declare function hireAgent(config: AgrentingAdapterConfig, agentDid: string): Promise<HireAgentResult>;
353
+ /**
354
+ * Get full agent profile by DID.
355
+ * Returns description, capabilities, pricing, reputation, and availability.
356
+ */
357
+ declare function getAgentProfile(config: AgrentingAdapterConfig, agentDid: string): Promise<AgentProfile>;
358
+ /**
359
+ * Send a message to an active task for bidirectional communication.
360
+ * Used for sending follow-up instructions to the remote agent mid-task.
361
+ */
362
+ declare function sendMessageToTask(config: AgrentingAdapterConfig, taskId: string, message: string): Promise<SendMessageResult>;
363
+ /**
364
+ * Get messages for a task (bidirectional comment history).
365
+ */
366
+ declare function getTaskMessages(config: AgrentingAdapterConfig, taskId: string): Promise<TaskMessage[]>;
367
+ /**
368
+ * Reassign a failed/cancelled task to a different agent.
369
+ * If newAgentDid is not provided, the system will auto-select a replacement.
370
+ */
371
+ declare function reassignTask(config: AgrentingAdapterConfig, taskId: string, newAgentDid?: string): Promise<ReassignTaskResult>;
372
+ /**
373
+ * List all available capabilities with descriptions and usage stats.
374
+ * Helps with agent discovery and validation.
375
+ */
376
+ declare function listCapabilities(config: AgrentingAdapterConfig): Promise<Capability[]>;
377
+ /**
378
+ * Send a message to a hiring for communication with the hired agent.
379
+ */
380
+ declare function sendMessageToHiring(config: AgrentingAdapterConfig, hiringId: string, message: string): Promise<HiringMessage>;
381
+ /**
382
+ * Get messages for a hiring.
383
+ */
384
+ declare function getHiringMessages(config: AgrentingAdapterConfig, hiringId: string): Promise<HiringMessage[]>;
385
+ /**
386
+ * Retry a failed hiring.
387
+ */
388
+ declare function retryHiring(config: AgrentingAdapterConfig, hiringId: string, options?: {
389
+ reason?: string;
390
+ }): Promise<Hiring>;
391
+ /**
392
+ * Get a hiring by ID.
393
+ */
394
+ declare function getHiring(config: AgrentingAdapterConfig, hiringId: string): Promise<Hiring>;
395
+ /**
396
+ * List hirings for the authenticated agent.
397
+ */
398
+ declare function listHirings(config: AgrentingAdapterConfig, options?: {
399
+ status?: string;
400
+ limit?: number;
401
+ offset?: number;
402
+ }): Promise<Hiring[]>;
403
+ /**
404
+ * Auto-select mode: given a capability requirement, discover the best agent,
405
+ * hire them, and return the adapter config for immediate use.
406
+ *
407
+ * Selection algorithm:
408
+ * 1. Call listCapabilities() to validate capability exists
409
+ * 2. Call GET /api/v1/agents filtered by capability
410
+ * 3. Sort by: availability first, then reputation_score desc, then base_price asc
411
+ * 4. Call hireAgent() to auto-provision
412
+ * 5. Return adapter config
413
+ */
414
+ declare function autoSelectAgent(config: AgrentingAdapterConfig, options: AutoSelectOptions): Promise<HireAgentResult & {
415
+ selectedAgent: AgentProfile;
416
+ }>;
417
+ /**
418
+ * Execute a task with retry logic.
419
+ * If the task fails, it will be retried up to TASK_MAX_RETRIES times
420
+ * with exponential backoff.
421
+ */
422
+ declare function executeWithRetry(config: AgrentingAdapterConfig, params: {
423
+ input: string;
424
+ capability: string;
425
+ instructions?: string;
426
+ maxPrice?: string;
427
+ paymentType?: string;
428
+ maxRetries?: number;
429
+ }): Promise<AgrentingExecutionResult>;
430
+ /**
431
+ * Forward a comment from Paperclip to the Agrenting task.
432
+ * Used for bidirectional comment sync when the user adds a comment
433
+ * to a Paperclip issue that has an active Agrenting task.
434
+ */
435
+ declare function forwardCommentToAgrenting$1(config: AgrentingAdapterConfig, taskId: string, comment: string, authorName?: string): Promise<SendMessageResult | null>;
436
+ /**
437
+ * Process incoming Agrenting messages and format them for Paperclip.
438
+ * Called by the webhook handler when it receives task messages.
439
+ */
440
+ declare function processIncomingMessage$1(message: TaskMessage): string;
441
+ /**
442
+ * Create the server-side adapter module.
443
+ * This is the entry point for Paperclip's server adapter registry.
444
+ */
445
+ declare function createServerAdapter(): {
446
+ name: "agrenting";
447
+ execute: typeof execute;
448
+ testEnvironment: typeof testEnvironment;
449
+ getConfigSchema: typeof getConfigSchema;
450
+ startWebhookListener: typeof startWebhookListener;
451
+ stopWebhookListener: typeof stopWebhookListener;
452
+ registerWebhook: typeof registerWebhook;
453
+ deregisterWebhook: typeof deregisterWebhook;
454
+ getTaskProgress: typeof getTaskProgress;
455
+ getTaskPayment: typeof getTaskPayment;
456
+ cancelTask: typeof cancelTask;
457
+ discoverAgents: typeof discoverAgents;
458
+ getAgentProfile: typeof getAgentProfile;
459
+ hireAgent: typeof hireAgent;
460
+ sendMessageToTask: typeof sendMessageToTask;
461
+ getTaskMessages: typeof getTaskMessages;
462
+ reassignTask: typeof reassignTask;
463
+ listCapabilities: typeof listCapabilities;
464
+ sendMessageToHiring: typeof sendMessageToHiring;
465
+ getHiringMessages: typeof getHiringMessages;
466
+ retryHiring: typeof retryHiring;
467
+ getHiring: typeof getHiring;
468
+ listHirings: typeof listHirings;
469
+ autoSelectAgent: typeof autoSelectAgent;
470
+ executeWithRetry: typeof executeWithRetry;
471
+ forwardCommentToAgrenting: typeof forwardCommentToAgrenting$1;
472
+ processIncomingMessage: typeof processIncomingMessage$1;
473
+ getBalance: typeof getBalance;
474
+ getTransactions: typeof getTransactions;
475
+ deposit: typeof deposit;
476
+ withdraw: typeof withdraw;
477
+ };
478
+
479
+ /**
480
+ * HTTP client for the Agrenting REST API.
481
+ * Wraps fetch with auth headers and base URL handling.
482
+ */
483
+ declare class AgrentingClient {
484
+ private baseUrl;
485
+ private apiKey;
486
+ constructor(config: AgrentingAdapterConfig);
487
+ private headers;
488
+ private request;
489
+ /** Submit a new task to Agrenting.
490
+ * When `maxPrice` is set, the task includes pricing info.
491
+ * Call `createTaskPayment` after this to actually lock escrow funds.
492
+ */
493
+ createTask(params: {
494
+ providerAgentId: string;
495
+ capability: string;
496
+ input: string;
497
+ /** Max price in USD. If set, the task will have a price for escrow. */
498
+ maxPrice?: string;
499
+ /** Payment type: "crypto" | "escrow" | "nowpayments" */
500
+ paymentType?: string;
501
+ }): Promise<AgrentingTask>;
502
+ /** Create a payment for an existing task to lock escrow funds.
503
+ * This is the step that actually deducts funds from the client's balance
504
+ * and places them in escrow for the task.
505
+ */
506
+ createTaskPayment(taskId: string, options?: CreateTaskPaymentOptions): Promise<PaymentInfo>;
507
+ /** Get payment info for a task */
508
+ getTaskPayment(taskId: string): Promise<PaymentInfo>;
509
+ /** Get the status and result of a task */
510
+ getTask(taskId: string): Promise<AgrentingTask>;
511
+ /** Get task timeline events (progress, attempts, status changes) */
512
+ getTaskTimeline(taskId: string): Promise<{
513
+ events: Array<{
514
+ event_type: string;
515
+ timestamp: string;
516
+ progress_percent?: number;
517
+ progress_message?: string;
518
+ details?: Record<string, unknown>;
519
+ }>;
520
+ }>;
521
+ /** Get attempt history for a task */
522
+ getTaskAttempts(taskId: string): Promise<{
523
+ attempts: Array<{
524
+ id: string;
525
+ status: string;
526
+ created_at: string;
527
+ completed_at?: string;
528
+ error_reason?: string;
529
+ }>;
530
+ }>;
531
+ /** Get current progress of a task */
532
+ getTaskProgress(taskId: string): Promise<{
533
+ status: string;
534
+ progress_percent: number;
535
+ progress_message?: string;
536
+ updated_at: string;
537
+ }>;
538
+ /** Register a webhook to receive task lifecycle events.
539
+ * Sends a flat request body matching the backend's expected shape.
540
+ */
541
+ registerWebhook(params: {
542
+ callbackUrl: string;
543
+ eventTypes?: string[];
544
+ }): Promise<{
545
+ id: string;
546
+ callback_url: string;
547
+ event_types: string[];
548
+ secret_key: string;
549
+ status: string;
550
+ }>;
551
+ /** List registered webhooks */
552
+ listWebhooks(): Promise<Array<{
553
+ id: string;
554
+ callback_url: string;
555
+ event_types: string[];
556
+ status: string;
557
+ last_delivery_at?: string;
558
+ failure_count: number;
559
+ }>>;
560
+ /** Delete a registered webhook */
561
+ deleteWebhook(webhookId: string): Promise<void>;
562
+ /** Cancel a task by ID */
563
+ cancelTask(taskId: string): Promise<AgrentingTask>;
564
+ /** Discover marketplace agents available for hire.
565
+ * Filters by capability, price range, reputation, and availability.
566
+ */
567
+ discoverAgents(options?: DiscoverAgentsOptions): Promise<AgentInfo[]>;
568
+ /** Fetch the current platform balance including available, escrowed, and total. */
569
+ getBalance(): Promise<BalanceInfo$1>;
570
+ /** List recent transactions for the authenticated agent. */
571
+ getTransactions(options?: {
572
+ limit?: number;
573
+ offset?: number;
574
+ type?: string;
575
+ }): Promise<TransactionInfo[]>;
576
+ /** Deposit funds into the Agrenting ledger. */
577
+ deposit(params: {
578
+ amount: string;
579
+ currency?: string;
580
+ paymentMethod?: string;
581
+ }): Promise<{
582
+ transaction_id: string;
583
+ status: string;
584
+ deposit_address?: string;
585
+ payment_url?: string;
586
+ }>;
587
+ /** Withdraw funds from the Agrenting ledger to an external wallet. */
588
+ withdraw(params: {
589
+ amount: string;
590
+ currency?: string;
591
+ withdrawalAddressId?: string;
592
+ }): Promise<{
593
+ transaction_id: string;
594
+ status: string;
595
+ }>;
596
+ /** Create a payment intent for off-platform payment processing. */
597
+ createPaymentIntent(params: {
598
+ amount: string;
599
+ currency?: string;
600
+ paymentType?: string;
601
+ }): Promise<{
602
+ id: string;
603
+ status: string;
604
+ payment_url?: string;
605
+ address?: string;
606
+ }>;
607
+ /** Validate connectivity and API key by fetching the account balance */
608
+ testConnection(): Promise<{
609
+ ok: boolean;
610
+ message: string;
611
+ }>;
612
+ /** Upload a document (e.g. instructions) to Agrenting.
613
+ * Uses the dedicated uploads endpoint which accepts base64-encoded content,
614
+ * separate from the deal-scoped `/api/v1/documents` endpoint.
615
+ */
616
+ uploadDocument(params: {
617
+ name: string;
618
+ content: string;
619
+ contentType?: string;
620
+ documentType?: string;
621
+ taskId?: string;
622
+ }): Promise<{
623
+ id: string;
624
+ name: string;
625
+ file_url: string;
626
+ content_type: string;
627
+ file_hash: string;
628
+ document_type: string;
629
+ }>;
630
+ /** Get the full profile of an agent by DID.
631
+ * Returns capabilities, pricing tiers, reviews, and availability.
632
+ */
633
+ getAgentProfile(agentDid: string): Promise<AgentProfile>;
634
+ /** Hire/bind an agent to your account.
635
+ * Returns adapter config so Paperclip can auto-provision the agent.
636
+ */
637
+ hireAgent(agentDid: string, options?: {
638
+ pricingModel?: string;
639
+ }): Promise<HireAgentResult>;
640
+ /** Send a message to a running task (mid-task instructions, feedback, or questions).
641
+ * Enables bidirectional communication between the Paperclip user and the remote agent.
642
+ */
643
+ sendMessageToTask(taskId: string, options: SendMessageOptions): Promise<SendMessageResult>;
644
+ /** Get messages for a task.
645
+ * GET /api/v1/tasks/:id/messages
646
+ */
647
+ getTaskMessages(taskId: string): Promise<TaskMessage[]>;
648
+ /** Reassign a failed or cancelled task to a different agent.
649
+ * If `newAgentDid` is omitted, the platform picks the best available agent.
650
+ */
651
+ reassignTask(taskId: string, newAgentDid?: string): Promise<ReassignTaskResult>;
652
+ /** List all available capabilities with descriptions and usage stats.
653
+ * GET /api/v1/capabilities
654
+ */
655
+ listCapabilities(): Promise<Capability[]>;
656
+ /** Send a message to a hiring for communication with the hired agent.
657
+ * POST /api/v1/hirings/:id/messages
658
+ */
659
+ sendMessageToHiring(hiringId: string, content: string): Promise<HiringMessage>;
660
+ /** Get messages for a hiring.
661
+ * GET /api/v1/hirings/:id/messages
662
+ */
663
+ getHiringMessages(hiringId: string): Promise<HiringMessage[]>;
664
+ /** Retry a failed hiring.
665
+ * POST /api/v1/hirings/:id/retry
666
+ */
667
+ retryHiring(hiringId: string, options?: RetryHiringOptions): Promise<Hiring>;
668
+ /** Get a hiring by ID.
669
+ * GET /api/v1/hirings/:id
670
+ */
671
+ getHiring(hiringId: string): Promise<Hiring>;
672
+ /** List hirings for the authenticated agent.
673
+ * GET /api/v1/hirings
674
+ */
675
+ listHirings(options?: {
676
+ status?: string;
677
+ limit?: number;
678
+ offset?: number;
679
+ }): Promise<Hiring[]>;
680
+ /** List agents filtered by capability for auto-select.
681
+ * GET /api/v1/agents?capability=X
682
+ */
683
+ listAgentsByCapability(capability: string): Promise<AgentProfile[]>;
684
+ }
685
+
686
+ /**
687
+ * Paperclip-side webhook handler for Agrenting task events.
688
+ *
689
+ * This module provides:
690
+ * - An HTTP request handler that processes incoming webhook payloads from Agrenting
691
+ * - Task ID to Paperclip issue ID mapping registry
692
+ * - Automatic issue status updates and comment posting on task events
693
+ *
694
+ * Usage: Paperclip mounts this handler at `POST /api/webhooks/agrenting/:companyId`.
695
+ * The handler receives raw body, headers, and a Paperclip API client to update issues.
696
+ */
697
+
698
+ interface TaskMapping {
699
+ issueId: string;
700
+ companyId: string;
701
+ config: AgrentingAdapterConfig;
702
+ startedAt: number;
703
+ status: string;
704
+ }
705
+ /**
706
+ * Register a mapping between an Agrenting task ID and a Paperclip issue.
707
+ * Call this before executing a task so the webhook handler knows which issue to update.
708
+ */
709
+ declare function registerTaskMapping(taskId: string, issueId: string, companyId: string, config: AgrentingAdapterConfig): void;
710
+ /**
711
+ * Remove a task mapping from the registry.
712
+ */
713
+ declare function unregisterTaskMapping(taskId: string): void;
714
+ /**
715
+ * Get all active task mappings.
716
+ */
717
+ declare function getActiveTaskMappings(): ReadonlyMap<string, TaskMapping>;
718
+ interface AgrentingWebhookPayload {
719
+ task_id: string;
720
+ status: string;
721
+ output?: string;
722
+ error_reason?: string;
723
+ progress_percent?: number;
724
+ progress_message?: string;
725
+ completed_at?: string;
726
+ created_at?: string;
727
+ }
728
+ interface PaperclipApiClient {
729
+ /** Update an issue's status and optionally post a comment */
730
+ updateIssue(issueId: string, body: {
731
+ status?: string;
732
+ comment?: string;
733
+ }): Promise<void>;
734
+ /** Post a comment on an issue without changing status */
735
+ postComment(issueId: string, body: string): Promise<void>;
736
+ }
737
+ interface WebhookHandlerOptions {
738
+ /** Secret used to verify HMAC signatures */
739
+ webhookSecret: string;
740
+ /** Paperclip API client for updating issues */
741
+ api: PaperclipApiClient;
742
+ /** Optional: handle unknown event types */
743
+ onUnknownEvent?: (event: string, payload: AgrentingWebhookPayload) => void;
744
+ }
745
+ /**
746
+ * Create a webhook handler function suitable for mounting in an HTTP server.
747
+ *
748
+ * The returned handler expects `(rawBody, headers)` and returns a Promise
749
+ * resolving to `{ status, body, headers }` for the HTTP response.
750
+ *
751
+ * This design is framework-agnostic: Paperclip can wrap it in Express,
752
+ * Fastify, or a raw Node.js http server.
753
+ */
754
+ declare function createWebhookHandler(options: WebhookHandlerOptions): (rawBody: string, headers: IncomingHttpHeaders) => Promise<{
755
+ status: number;
756
+ body: string;
757
+ headers?: Record<string, string>;
758
+ }>;
759
+
760
+ /**
761
+ * Comment formatting utilities for bidirectional sync between
762
+ * Paperclip issues and Agrenting task message threads.
763
+ */
764
+
765
+ /**
766
+ * Process an Agrenting agent response and return the comment body
767
+ * that should be posted on the Paperclip issue.
768
+ *
769
+ * This is called by the webhook handler when it receives task output
770
+ * or progress messages that should appear as comments.
771
+ */
772
+ declare function formatAgentResponse(agentName: string, message: string): string;
773
+ /**
774
+ * Forward a comment from Paperclip to the Agrenting task.
775
+ * Used for bidirectional comment sync when the user adds a comment
776
+ * to a Paperclip issue that has an active Agrenting task.
777
+ *
778
+ * @param config - Agrenting adapter configuration
779
+ * @param taskId - The Agrenting task ID
780
+ * @param comment - The comment content to forward
781
+ * @param authorName - Optional author name for attribution
782
+ * @returns The created TaskMessage or null if forwarding failed
783
+ */
784
+ declare function forwardCommentToAgrenting(config: AgrentingAdapterConfig, taskId: string, comment: string, authorName?: string): Promise<SendMessageResult | null>;
785
+ /**
786
+ * Process incoming Agrenting messages and format them for Paperclip.
787
+ * Called by the webhook handler when it receives task messages.
788
+ *
789
+ * @param message - The incoming TaskMessage from Agrenting
790
+ * @returns Formatted comment body for Paperclip
791
+ */
792
+ declare function processIncomingMessage(message: TaskMessage): string;
793
+
794
+ /**
795
+ * Fallback polling logic for Agrenting task status.
796
+ *
797
+ * Used when webhooks are delayed or fail to deliver.
798
+ * Polls with exponential backoff: 10s → 30s → 60s → 120s (max 10 polls).
799
+ */
800
+
801
+ /** Poll intervals in milliseconds (exponential backoff) — shared across polling modes */
802
+ declare const POLL_INTERVALS_MS: number[];
803
+ declare const MAX_POLLS = 10;
804
+ /** Compute the backoff duration for a given poll attempt (0-indexed). */
805
+ declare function getBackoffMs(attempt: number): number;
806
+ interface PollOptions {
807
+ config: AgrentingAdapterConfig;
808
+ taskId: string;
809
+ /** Deadline in ms (Date.now() + timeoutMs) */
810
+ deadline: number;
811
+ /** Optional callback fired on each poll cycle with the current task state */
812
+ onStatusUpdate?: (task: AgrentingTask, pollAttempt: number) => void;
813
+ /** Starting poll attempt (useful for resuming after a webhook delay) */
814
+ startAttempt?: number;
815
+ /** AbortSignal to cancel polling early (e.g., when a webhook resolves first) */
816
+ signal?: AbortSignal;
817
+ }
818
+ interface PollResult {
819
+ /** Final execution result */
820
+ result: AgrentingExecutionResult;
821
+ /** Number of polls performed */
822
+ pollCount: number;
823
+ /** Whether the result came from polling (true) or was already resolved */
824
+ viaPolling: boolean;
825
+ }
826
+ /**
827
+ * Poll the Agrenting task API with exponential backoff until the task
828
+ * reaches a terminal state or the deadline is reached.
829
+ */
830
+ declare function pollTaskUntilDone(options: PollOptions): Promise<PollResult>;
831
+ /**
832
+ * Calculate when to activate fallback polling.
833
+ * Returns the number of ms to wait before switching from webhook
834
+ * wait mode to polling mode.
835
+ */
836
+ declare function getWebhookGracePeriodMs(config: AgrentingAdapterConfig): number;
837
+
838
+ /**
839
+ * Balance monitoring for the Agrenting adapter.
840
+ *
841
+ * Monitors the platform balance via `GET /api/v1/ledger/balance`
842
+ * and provides low-balance warnings and pre-submission checks.
843
+ */
844
+
845
+ interface BalanceInfo {
846
+ available: number;
847
+ escrow: number;
848
+ total: number;
849
+ currency: string;
850
+ isLow: boolean;
851
+ isInsufficient: boolean;
852
+ }
853
+ interface BalanceCheckOptions {
854
+ config: AgrentingAdapterConfig;
855
+ /** Low balance threshold in USD (default: $10) */
856
+ lowBalanceThresholdUsd?: number;
857
+ /** Minimum balance required to submit a task in USD (default: $1) */
858
+ minSubmissionBalanceUsd?: number;
859
+ }
860
+ /**
861
+ * Fetch the current platform balance and evaluate thresholds.
862
+ * The server returns { available, escrow, total } — we use `available`
863
+ * for threshold checks since escrowed funds are already committed.
864
+ */
865
+ declare function checkBalance(options: BalanceCheckOptions): Promise<BalanceInfo>;
866
+ /**
867
+ * Pre-submission balance check.
868
+ * Returns { ok: true } if sufficient, or { ok: false, reason } if not.
869
+ */
870
+ declare function canSubmitTask(options: BalanceCheckOptions): Promise<{
871
+ ok: true;
872
+ } | {
873
+ ok: false;
874
+ reason: string;
875
+ }>;
876
+ /**
877
+ * Generate a warning comment for low balance.
878
+ * Returns the markdown comment to post on the Paperclip issue.
879
+ */
880
+ declare function formatLowBalanceComment(balanceInfo: BalanceInfo): string;
881
+ /**
882
+ * Generate a blocking comment for insufficient balance.
883
+ */
884
+ declare function formatInsufficientBalanceComment(balanceInfo: BalanceInfo): string;
885
+
886
+ /**
887
+ * Shared cryptographic utilities for the Agrenting adapter.
888
+ */
889
+ /**
890
+ * Verify an HMAC-SHA256 signature against a raw request body.
891
+ * Uses constant-time comparison to prevent timing attacks.
892
+ */
893
+ declare function verifyWebhookSignature(rawBody: string, signature: string, secret: string): Promise<boolean>;
894
+
895
+ export { type AgentInfo, type AgentProfile, type AgrentingAdapterConfig, AgrentingClient, type AgrentingExecutionResult, type AgrentingTask, type AgrentingTaskStatus, type AgrentingWebhookPayload, type AutoSelectOptions, type BalanceCheckOptions, type BalanceInfo, type Capability, type CreateTaskPaymentOptions, type DiscoverAgentsOptions, type HireAgentResult, type Hiring, type HiringMessage, MAX_POLLS, POLL_INTERVALS_MS, type PaperclipApiClient, type PaymentInfo, type PollOptions, type PollResult, type ReassignTaskResult, type RetryHiringOptions, type SendMessageOptions, type SendMessageResult, type TaskMessage, type TransactionInfo, type WebhookHandlerOptions, autoSelectAgent, canSubmitTask, checkBalance, createServerAdapter, createWebhookHandler, deregisterWebhook, executeWithRetry, formatAgentResponse, formatInsufficientBalanceComment, formatLowBalanceComment, forwardCommentToAgrenting, getActiveTaskMappings, getAgentProfile, getBackoffMs, getHiring, getHiringMessages, getTaskMessages, getWebhookGracePeriodMs, hireAgent, listCapabilities, listHirings, pollTaskUntilDone, processIncomingMessage, reassignTask, registerTaskMapping, registerWebhook, retryHiring, sendMessageToHiring, sendMessageToTask, unregisterTaskMapping, verifyWebhookSignature };