@circuitorg/agent-sdk 1.1.8 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +360 -667
  2. package/index.d.ts +1100 -516
  3. package/index.js +1 -1
  4. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -29,23 +29,33 @@ type SignAndSendRequest = {
29
29
  hexTransaction: string;
30
30
  };
31
31
  });
32
+ /**
33
+ * Success data from signAndSend operations
34
+ */
35
+ type SignAndSendData = {
36
+ /** Internal transaction ID for tracking */
37
+ internalTransactionId: number;
38
+ /** Transaction hash once broadcast */
39
+ txHash: string;
40
+ /** Optional transaction URL (explorer link) */
41
+ transactionUrl?: string;
42
+ };
32
43
  /**
33
44
  * Standard response from signAndSend operations
34
45
  */
35
46
  type SignAndSendResponse = {
36
47
  /** Whether the operation was successful */
37
48
  success: boolean;
38
- /** Internal transaction ID for tracking (only present on success) */
39
- internalTransactionId?: number;
40
- /** Transaction hash once broadcast (only present on success) */
41
- txHash?: string;
42
- /** Optional transaction URL (explorer link) (only present on success) */
43
- transactionUrl?: string;
44
- /** Error message (only present on failure) */
49
+ /** Transaction data (only present on success) */
50
+ data?: SignAndSendData;
51
+ /** Error category from API (only present on failure) */
45
52
  error?: string;
53
+ /** Detailed error message from API (only present on failure) */
54
+ errorMessage?: string;
46
55
  /** Detailed error information (only present on failure) */
47
56
  errorDetails?: {
48
- message: string;
57
+ message?: string;
58
+ error?: string;
49
59
  status?: number;
50
60
  statusText?: string;
51
61
  };
@@ -95,9 +105,9 @@ type SignMessageRequest = {
95
105
  };
96
106
  });
97
107
  /**
98
- * Standard response from signMessage operations
108
+ * Success data from signMessage operations
99
109
  */
100
- type SignMessageResponse = {
110
+ type SignMessageData = {
101
111
  /** Signature component v */
102
112
  v: number;
103
113
  /** Signature component r */
@@ -109,6 +119,26 @@ type SignMessageResponse = {
109
119
  /** Signature type */
110
120
  type: "evm";
111
121
  };
122
+ /**
123
+ * Standard response from signMessage operations
124
+ */
125
+ type SignMessageResponse = {
126
+ /** Whether the operation was successful */
127
+ success: boolean;
128
+ /** Signature data (only present on success) */
129
+ data?: SignMessageData;
130
+ /** Error category from API (only present on failure) */
131
+ error?: string;
132
+ /** Detailed error message from API (only present on failure) */
133
+ errorMessage?: string;
134
+ /** Detailed error information (only present on failure) */
135
+ errorDetails?: {
136
+ message?: string;
137
+ error?: string;
138
+ status?: number;
139
+ statusText?: string;
140
+ };
141
+ };
112
142
 
113
143
  /**
114
144
  * Agent log type definitions for agent communication
@@ -128,6 +158,18 @@ declare const AgentLogSchema: z.ZodObject<{
128
158
  shortMessage: z.ZodString;
129
159
  }, z.core.$strip>;
130
160
  type AgentLog = z.infer<typeof AgentLogSchema>;
161
+ /**
162
+ * Response from agent.log() method
163
+ *
164
+ * The log method accepts strings, objects, or arrays and pretty-prints them to console.
165
+ * Objects and arrays are serialized to JSON for backend (truncated to 250 chars).
166
+ */
167
+ interface LogResponse {
168
+ success: boolean;
169
+ error?: string;
170
+ errorMessage?: string;
171
+ errorDetails?: object;
172
+ }
131
173
 
132
174
  /**
133
175
  * Configuration type definitions for the Agent SDK
@@ -138,11 +180,7 @@ type AgentLog = z.infer<typeof AgentLogSchema>;
138
180
  interface SDKConfig {
139
181
  /** Session ID for the current agent instance */
140
182
  sessionId: number;
141
- /** Enable verbose logging for debugging */
142
- verbose?: boolean;
143
- /** Enable testing mode to return mock responses */
144
- testing?: boolean;
145
- /** Optional base URL for local development (auto-detected if omitted) */
183
+ /** Optional base URL (auto-detected if omitted - internal use only) */
146
184
  baseUrl?: string;
147
185
  }
148
186
 
@@ -176,10 +214,79 @@ declare const SwidgeQuoteRequestSchema: z.ZodObject<{
176
214
  fromToken: z.ZodOptional<z.ZodString>;
177
215
  toToken: z.ZodOptional<z.ZodString>;
178
216
  amount: z.ZodString;
179
- priceImpact: z.ZodOptional<z.ZodString>;
180
217
  slippage: z.ZodOptional<z.ZodString>;
181
218
  }, z.core.$strip>;
182
219
  type SwidgeQuoteRequest = z.infer<typeof SwidgeQuoteRequestSchema>;
220
+ declare const SwidgeQuoteDataSchema: z.ZodObject<{
221
+ engine: z.ZodLiteral<"relay">;
222
+ assetSend: z.ZodObject<{
223
+ network: z.ZodUnion<readonly [z.ZodLiteral<"solana">, z.ZodTemplateLiteral<`ethereum:${number}`>]>;
224
+ address: z.ZodString;
225
+ token: z.ZodNullable<z.ZodString>;
226
+ name: z.ZodOptional<z.ZodString>;
227
+ symbol: z.ZodOptional<z.ZodString>;
228
+ decimals: z.ZodOptional<z.ZodNumber>;
229
+ amount: z.ZodOptional<z.ZodString>;
230
+ minimumAmount: z.ZodOptional<z.ZodString>;
231
+ amountFormatted: z.ZodOptional<z.ZodString>;
232
+ amountUsd: z.ZodOptional<z.ZodString>;
233
+ }, z.core.$strip>;
234
+ assetReceive: z.ZodObject<{
235
+ network: z.ZodUnion<readonly [z.ZodLiteral<"solana">, z.ZodTemplateLiteral<`ethereum:${number}`>]>;
236
+ address: z.ZodString;
237
+ token: z.ZodNullable<z.ZodString>;
238
+ name: z.ZodOptional<z.ZodString>;
239
+ symbol: z.ZodOptional<z.ZodString>;
240
+ decimals: z.ZodOptional<z.ZodNumber>;
241
+ amount: z.ZodOptional<z.ZodString>;
242
+ minimumAmount: z.ZodOptional<z.ZodString>;
243
+ amountFormatted: z.ZodOptional<z.ZodString>;
244
+ amountUsd: z.ZodOptional<z.ZodString>;
245
+ }, z.core.$strip>;
246
+ priceImpact: z.ZodObject<{
247
+ usd: z.ZodOptional<z.ZodString>;
248
+ percentage: z.ZodOptional<z.ZodString>;
249
+ }, z.core.$strip>;
250
+ fees: z.ZodArray<z.ZodObject<{
251
+ name: z.ZodString;
252
+ amount: z.ZodOptional<z.ZodString>;
253
+ amountFormatted: z.ZodOptional<z.ZodString>;
254
+ amountUsd: z.ZodOptional<z.ZodString>;
255
+ }, z.core.$strip>>;
256
+ steps: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
257
+ type: z.ZodLiteral<"transaction">;
258
+ description: z.ZodString;
259
+ transactionDetails: z.ZodUnion<readonly [z.ZodObject<{
260
+ type: z.ZodLiteral<"evm">;
261
+ from: z.ZodString;
262
+ to: z.ZodString;
263
+ chainId: z.ZodNumber;
264
+ value: z.ZodNumber;
265
+ data: z.ZodString;
266
+ gas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
267
+ maxFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
268
+ maxPriorityFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
269
+ }, z.core.$strip>, z.ZodObject<{
270
+ type: z.ZodLiteral<"solana">;
271
+ instructions: z.ZodArray<z.ZodObject<{
272
+ programId: z.ZodString;
273
+ keys: z.ZodArray<z.ZodObject<{
274
+ pubkey: z.ZodString;
275
+ isSigner: z.ZodBoolean;
276
+ isWritable: z.ZodBoolean;
277
+ }, z.core.$strip>>;
278
+ data: z.ZodUnion<readonly [z.ZodString, z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>]>;
279
+ }, z.core.$strip>>;
280
+ addressLookupTableAddresses: z.ZodArray<z.ZodString>;
281
+ }, z.core.$strip>]>;
282
+ metadata: z.ZodRecord<z.ZodString, z.ZodString>;
283
+ }, z.core.$strip>, z.ZodObject<{
284
+ type: z.ZodLiteral<"signature">;
285
+ description: z.ZodString;
286
+ signatureData: z.ZodString;
287
+ metadata: z.ZodRecord<z.ZodString, z.ZodString>;
288
+ }, z.core.$strip>], "type">>;
289
+ }, z.core.$strip>;
183
290
  /**
184
291
  * Execute request schema - takes the complete quote response from quote() method
185
292
  */
@@ -229,9 +336,9 @@ declare const SwidgeExecuteRequestSchema: z.ZodObject<{
229
336
  chainId: z.ZodNumber;
230
337
  value: z.ZodNumber;
231
338
  data: z.ZodString;
232
- gas: z.ZodOptional<z.ZodNumber>;
233
- maxFeePerGas: z.ZodOptional<z.ZodNumber>;
234
- maxPriorityFeePerGas: z.ZodOptional<z.ZodNumber>;
339
+ gas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
340
+ maxFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
341
+ maxPriorityFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
235
342
  }, z.core.$strip>, z.ZodObject<{
236
343
  type: z.ZodLiteral<"solana">;
237
344
  instructions: z.ZodArray<z.ZodObject<{
@@ -321,9 +428,9 @@ declare const SwidgeQuoteResponseWrapperSchema: z.ZodObject<{
321
428
  chainId: z.ZodNumber;
322
429
  value: z.ZodNumber;
323
430
  data: z.ZodString;
324
- gas: z.ZodOptional<z.ZodNumber>;
325
- maxFeePerGas: z.ZodOptional<z.ZodNumber>;
326
- maxPriorityFeePerGas: z.ZodOptional<z.ZodNumber>;
431
+ gas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
432
+ maxFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
433
+ maxPriorityFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
327
434
  }, z.core.$strip>, z.ZodObject<{
328
435
  type: z.ZodLiteral<"solana">;
329
436
  instructions: z.ZodArray<z.ZodObject<{
@@ -346,8 +453,10 @@ declare const SwidgeQuoteResponseWrapperSchema: z.ZodObject<{
346
453
  }, z.core.$strip>], "type">>;
347
454
  }, z.core.$strip>>;
348
455
  error: z.ZodOptional<z.ZodString>;
456
+ errorMessage: z.ZodOptional<z.ZodString>;
349
457
  errorDetails: z.ZodOptional<z.ZodObject<{
350
- message: z.ZodString;
458
+ message: z.ZodOptional<z.ZodString>;
459
+ error: z.ZodOptional<z.ZodString>;
351
460
  status: z.ZodOptional<z.ZodNumber>;
352
461
  statusText: z.ZodOptional<z.ZodString>;
353
462
  }, z.core.$strip>>;
@@ -370,38 +479,19 @@ declare const SwidgeExecuteResponseWrapperSchema: z.ZodObject<{
370
479
  lastUpdated: z.ZodNumber;
371
480
  }, z.core.$strip>>;
372
481
  error: z.ZodOptional<z.ZodString>;
482
+ errorMessage: z.ZodOptional<z.ZodString>;
373
483
  errorDetails: z.ZodOptional<z.ZodObject<{
374
- message: z.ZodString;
484
+ message: z.ZodOptional<z.ZodString>;
485
+ error: z.ZodOptional<z.ZodString>;
375
486
  status: z.ZodOptional<z.ZodNumber>;
376
487
  statusText: z.ZodOptional<z.ZodString>;
377
488
  }, z.core.$strip>>;
378
489
  }, z.core.$strip>;
490
+ type SwidgeQuoteData = z.infer<typeof SwidgeQuoteDataSchema>;
379
491
  type SwidgeQuoteResponse = z.infer<typeof SwidgeQuoteResponseWrapperSchema>;
380
492
  type SwidgeExecuteRequest = z.infer<typeof SwidgeExecuteRequestSchema>;
381
493
  type SwidgeExecuteResponse = z.infer<typeof SwidgeExecuteResponseWrapperSchema>;
382
494
 
383
- declare const PolymarketPositionSchema: z.ZodObject<{
384
- contractAddress: z.ZodString;
385
- tokenId: z.ZodNullable<z.ZodString>;
386
- decimals: z.ZodNumber;
387
- conditionId: z.ZodString;
388
- formattedShares: z.ZodString;
389
- shares: z.ZodString;
390
- valueUsd: z.ZodString;
391
- question: z.ZodString;
392
- outcome: z.ZodString;
393
- priceUsd: z.ZodString;
394
- averagePriceUsd: z.ZodString;
395
- isRedeemable: z.ZodBoolean;
396
- isNegativeRisk: z.ZodBoolean;
397
- imageUrl: z.ZodString;
398
- initialValue: z.ZodString;
399
- pnlUsd: z.ZodString;
400
- pnlPercent: z.ZodString;
401
- pnlRealizedUsd: z.ZodString;
402
- pnlRealizedPercent: z.ZodString;
403
- endDate: z.ZodString;
404
- }, z.core.$strip>;
405
495
  declare const PolymarketMarketOrderRequestSchema: z.ZodObject<{
406
496
  tokenId: z.ZodString;
407
497
  size: z.ZodNumber;
@@ -413,40 +503,6 @@ declare const PolymarketMarketOrderRequestSchema: z.ZodObject<{
413
503
  declare const PolymarketRedeemPositionsRequestSchema: z.ZodObject<{
414
504
  tokenIds: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString>>>;
415
505
  }, z.core.$strip>;
416
- declare const PolymarketPositionsResponseSchema: z.ZodObject<{
417
- success: z.ZodBoolean;
418
- data: z.ZodOptional<z.ZodObject<{
419
- totalValue: z.ZodNumber;
420
- positions: z.ZodArray<z.ZodObject<{
421
- contractAddress: z.ZodString;
422
- tokenId: z.ZodNullable<z.ZodString>;
423
- decimals: z.ZodNumber;
424
- conditionId: z.ZodString;
425
- formattedShares: z.ZodString;
426
- shares: z.ZodString;
427
- valueUsd: z.ZodString;
428
- question: z.ZodString;
429
- outcome: z.ZodString;
430
- priceUsd: z.ZodString;
431
- averagePriceUsd: z.ZodString;
432
- isRedeemable: z.ZodBoolean;
433
- isNegativeRisk: z.ZodBoolean;
434
- imageUrl: z.ZodString;
435
- initialValue: z.ZodString;
436
- pnlUsd: z.ZodString;
437
- pnlPercent: z.ZodString;
438
- pnlRealizedUsd: z.ZodString;
439
- pnlRealizedPercent: z.ZodString;
440
- endDate: z.ZodString;
441
- }, z.core.$strip>>;
442
- }, z.core.$strip>>;
443
- error: z.ZodOptional<z.ZodString>;
444
- errorDetails: z.ZodOptional<z.ZodObject<{
445
- message: z.ZodString;
446
- status: z.ZodOptional<z.ZodNumber>;
447
- statusText: z.ZodOptional<z.ZodString>;
448
- }, z.core.$strip>>;
449
- }, z.core.$strip>;
450
506
  declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
451
507
  success: z.ZodBoolean;
452
508
  data: z.ZodOptional<z.ZodObject<{
@@ -461,8 +517,10 @@ declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
461
517
  }, z.core.$strip>;
462
518
  }, z.core.$strip>>;
463
519
  error: z.ZodOptional<z.ZodString>;
520
+ errorMessage: z.ZodOptional<z.ZodString>;
464
521
  errorDetails: z.ZodOptional<z.ZodObject<{
465
- message: z.ZodString;
522
+ message: z.ZodOptional<z.ZodString>;
523
+ error: z.ZodOptional<z.ZodString>;
466
524
  status: z.ZodOptional<z.ZodNumber>;
467
525
  statusText: z.ZodOptional<z.ZodString>;
468
526
  }, z.core.$strip>>;
@@ -496,16 +554,16 @@ declare const PolymarketRedeemPositionsResponseSchema: z.ZodObject<{
496
554
  transactionHash: z.ZodNullable<z.ZodString>;
497
555
  }, z.core.$strip>>>;
498
556
  error: z.ZodOptional<z.ZodString>;
557
+ errorMessage: z.ZodOptional<z.ZodString>;
499
558
  errorDetails: z.ZodOptional<z.ZodObject<{
500
- message: z.ZodString;
559
+ message: z.ZodOptional<z.ZodString>;
560
+ error: z.ZodOptional<z.ZodString>;
501
561
  status: z.ZodOptional<z.ZodNumber>;
502
562
  statusText: z.ZodOptional<z.ZodString>;
503
563
  }, z.core.$strip>>;
504
564
  }, z.core.$strip>;
505
- type PolymarketPosition = z.infer<typeof PolymarketPositionSchema>;
506
565
  type PolymarketMarketOrderRequest = z.infer<typeof PolymarketMarketOrderRequestSchema>;
507
566
  type PolymarketRedeemPositionsRequest = z.infer<typeof PolymarketRedeemPositionsRequestSchema>;
508
- type PolymarketPositionsResponse = z.infer<typeof PolymarketPositionsResponseSchema>;
509
567
  type PolymarketMarketOrderResponse = z.infer<typeof PolymarketMarketOrderResponseSchema>;
510
568
  type PolymarketRedeemPositionsResponse = z.infer<typeof PolymarketRedeemPositionsResponseSchema>;
511
569
 
@@ -516,29 +574,6 @@ type PolymarketRedeemPositionsResponse = z.infer<typeof PolymarketRedeemPosition
516
574
  * All keys are automatically namespaced by agentId and sessionId.
517
575
  */
518
576
 
519
- /**
520
- * Request to set a key-value pair in memory
521
- */
522
- declare const MemorySetRequestSchema: z.ZodObject<{
523
- key: z.ZodString;
524
- value: z.ZodString;
525
- }, z.core.$strip>;
526
- /**
527
- * Request to get a value by key from memory
528
- */
529
- declare const MemoryGetRequestSchema: z.ZodObject<{
530
- key: z.ZodString;
531
- }, z.core.$strip>;
532
- /**
533
- * Request to delete a key from memory
534
- */
535
- declare const MemoryDeleteRequestSchema: z.ZodObject<{
536
- key: z.ZodString;
537
- }, z.core.$strip>;
538
- /**
539
- * Request to list all keys in memory (no parameters needed)
540
- */
541
- declare const MemoryListRequestSchema: z.ZodObject<{}, z.core.$strip>;
542
577
  /**
543
578
  * Memory set response wrapper
544
579
  */
@@ -548,8 +583,10 @@ declare const MemorySetResponseSchema: z.ZodObject<{
548
583
  key: z.ZodString;
549
584
  }, z.core.$strip>>;
550
585
  error: z.ZodOptional<z.ZodString>;
586
+ errorMessage: z.ZodOptional<z.ZodString>;
551
587
  errorDetails: z.ZodOptional<z.ZodObject<{
552
- message: z.ZodString;
588
+ message: z.ZodOptional<z.ZodString>;
589
+ error: z.ZodOptional<z.ZodString>;
553
590
  status: z.ZodOptional<z.ZodNumber>;
554
591
  statusText: z.ZodOptional<z.ZodString>;
555
592
  }, z.core.$strip>>;
@@ -564,8 +601,10 @@ declare const MemoryGetResponseSchema: z.ZodObject<{
564
601
  value: z.ZodString;
565
602
  }, z.core.$strip>>;
566
603
  error: z.ZodOptional<z.ZodString>;
604
+ errorMessage: z.ZodOptional<z.ZodString>;
567
605
  errorDetails: z.ZodOptional<z.ZodObject<{
568
- message: z.ZodString;
606
+ message: z.ZodOptional<z.ZodString>;
607
+ error: z.ZodOptional<z.ZodString>;
569
608
  status: z.ZodOptional<z.ZodNumber>;
570
609
  statusText: z.ZodOptional<z.ZodString>;
571
610
  }, z.core.$strip>>;
@@ -579,8 +618,10 @@ declare const MemoryDeleteResponseSchema: z.ZodObject<{
579
618
  key: z.ZodString;
580
619
  }, z.core.$strip>>;
581
620
  error: z.ZodOptional<z.ZodString>;
621
+ errorMessage: z.ZodOptional<z.ZodString>;
582
622
  errorDetails: z.ZodOptional<z.ZodObject<{
583
- message: z.ZodString;
623
+ message: z.ZodOptional<z.ZodString>;
624
+ error: z.ZodOptional<z.ZodString>;
584
625
  status: z.ZodOptional<z.ZodNumber>;
585
626
  statusText: z.ZodOptional<z.ZodString>;
586
627
  }, z.core.$strip>>;
@@ -595,16 +636,14 @@ declare const MemoryListResponseSchema: z.ZodObject<{
595
636
  count: z.ZodNumber;
596
637
  }, z.core.$strip>>;
597
638
  error: z.ZodOptional<z.ZodString>;
639
+ errorMessage: z.ZodOptional<z.ZodString>;
598
640
  errorDetails: z.ZodOptional<z.ZodObject<{
599
- message: z.ZodString;
641
+ message: z.ZodOptional<z.ZodString>;
642
+ error: z.ZodOptional<z.ZodString>;
600
643
  status: z.ZodOptional<z.ZodNumber>;
601
644
  statusText: z.ZodOptional<z.ZodString>;
602
645
  }, z.core.$strip>>;
603
646
  }, z.core.$strip>;
604
- type MemorySetRequest = z.infer<typeof MemorySetRequestSchema>;
605
- type MemoryGetRequest = z.infer<typeof MemoryGetRequestSchema>;
606
- type MemoryDeleteRequest = z.infer<typeof MemoryDeleteRequestSchema>;
607
- type MemoryListRequest = z.infer<typeof MemoryListRequestSchema>;
608
647
  type MemorySetResponse = z.infer<typeof MemorySetResponseSchema>;
609
648
  type MemoryGetResponse = z.infer<typeof MemoryGetResponseSchema>;
610
649
  type MemoryDeleteResponse = z.infer<typeof MemoryDeleteResponseSchema>;
@@ -651,32 +690,18 @@ declare class AgentSdk {
651
690
  *
652
691
  * @param config - SDK configuration
653
692
  * @param config.sessionId - Numeric session identifier that scopes auth and actions
654
- * @param config.verbose - When true, prints detailed request/response logs
655
- * @param config.testing - When true, short-circuits network calls with mock values
656
- * @param config.baseUrl - Override API base URL (detected automatically otherwise)
657
693
  * @example
658
694
  * ```ts
659
- * const sdk = new AgentSdk({ sessionId: 42, verbose: true });
695
+ * const sdk = new AgentSdk({ sessionId: 42 });
660
696
  * ```
661
697
  */
662
698
  constructor(config: SDKConfig);
663
- private logging;
664
699
  /**
665
- * Add a log to the agent timeline.
666
- *
667
- * Messages show up in session traces and UIs and are useful for observability,
668
- * human-in-the-loop reviews, and debugging.
669
- *
670
- * @param log - Timeline message
671
- * @param log.type - One of: `"observe" | "validate" | "reflect" | "error" | "warning"`
672
- * @param log.shortMessage - Short, human-readable message (<= 250 chars)
673
- * @returns Resolves when the log is accepted by the backend
674
- * @example
675
- * ```ts
676
- * await sdk.sendLog({ type: "observe", shortMessage: "Starting swap" });
677
- * ```
700
+ * Internal method to send logs to the backend.
701
+ * Used by AgentContext.log() method.
702
+ * @internal
678
703
  */
679
- sendLog(log: AgentLog): Promise<void>;
704
+ _sendLog(logs: AgentLog[]): Promise<void>;
680
705
  /**
681
706
  * Sign and broadcast a transaction on the specified network.
682
707
  *
@@ -684,30 +709,42 @@ declare class AgentSdk {
684
709
  * the minimal request shape for the selected network.
685
710
  *
686
711
  * @param request - Network-specific transaction input
687
- * @param request.network - `"solana"` or `"ethereum:${number}"`
688
- * @param request.message - Optional human-readable context message (short), stored with the transaction
712
+ * @param request.network - `"solana"` or `"ethereum:${number}"` (e.g., "ethereum:1", "ethereum:42161")
713
+ * @param request.message - Optional context message for observability (max 250 chars)
689
714
  * @param request.request - Transaction payload
690
- * - For Ethereum: `{ toAddress, data, value }`
691
- * - `toAddress`: recipient contract or EOA as `0x${string}`
692
- * - `data`: calldata as `0x${string}` (use `"0x"` for simple transfers)
693
- * - `value`: stringified wei amount
715
+ * - For Ethereum: `{ toAddress, data, value, gas?, maxFeePerGas?, maxPriorityFeePerGas?, nonce?, enforceTransactionSuccess? }`
716
+ * - `toAddress`: Recipient address as hex string (`0x${string}`)
717
+ * - `data`: Calldata as hex string (`0x${string}`, use `"0x"` for simple transfers)
718
+ * - `value`: Wei amount as string
719
+ * - `gas`: Gas limit (optional)
720
+ * - `maxFeePerGas`: Max fee per gas in wei as string (optional)
721
+ * - `maxPriorityFeePerGas`: Max priority fee per gas in wei as string (optional)
722
+ * - `nonce`: Transaction nonce (optional)
723
+ * - `enforceTransactionSuccess`: Enforce transaction success (optional)
694
724
  * - For Solana: `{ hexTransaction }`
695
- * - `hexTransaction`: serialized `VersionedTransaction` as hex string
696
- * @returns Promise resolving to `{ internalTransactionId, txHash, transactionUrl? }`
697
- * @throws Error if the network is unsupported or the backend rejects the request
725
+ * - `hexTransaction`: Serialized `VersionedTransaction` as hex string
726
+ * @returns Promise resolving to SignAndSendResponse with success status and transaction hash or error details
698
727
  * @example
699
728
  * ```ts
700
729
  * // Ethereum (Arbitrum) native transfer
701
- * await sdk.signAndSend({
730
+ * const result = await sdk.signAndSend({
702
731
  * network: "ethereum:42161",
703
732
  * request: {
704
733
  * toAddress: "0xabc..." as `0x${string}`,
705
734
  * data: "0x" as `0x${string}`,
706
- * value: "1000000000000000" // 0.001 ETH
735
+ * value: "1000000000000000", // 0.001 ETH
736
+ * gas: 21000,
737
+ * maxFeePerGas: "20000000000"
707
738
  * },
708
- * message: "Self-transfer demo"
739
+ * message: "Transfer"
709
740
  * });
710
741
  *
742
+ * if (result.success) {
743
+ * console.log(`Transaction sent: ${result.txHash}`);
744
+ * } else {
745
+ * console.error(`Error: ${result.error}`);
746
+ * }
747
+ *
711
748
  * // Solana
712
749
  * await sdk.signAndSend({
713
750
  * network: "solana",
@@ -718,17 +755,24 @@ declare class AgentSdk {
718
755
  */
719
756
  signAndSend(request: SignAndSendRequest): Promise<SignAndSendResponse>;
720
757
  /**
721
- * Sign a message using the agent's key.
758
+ * Sign a message on an EVM network.
722
759
  *
723
- * This is useful for signing arbitrary messages, such as EIP-712 typed data.
760
+ * Supports both EIP-712 (typed structured data) and EIP-191 (simple message) signing.
724
761
  *
725
- * @param request - Message signing request with network-specific parameters
762
+ * @param request - EVM message signing input
726
763
  * @param request.network - `"ethereum:${number}"` for EVM networks
727
764
  * @param request.request - Message signing parameters
728
- * - For EIP-712: `{ messageType: "eip712", data: { domain, types, primaryType, message }, chainId }`
729
- * - For EIP-191: `{ messageType: "eip191", data: { message }, chainId }`
730
- * @returns Promise resolving to signature components `{ v, r, s, formattedSignature, type }`
731
- * @throws Error if the network is unsupported or the backend rejects the request
765
+ * - `messageType`: "eip712" or "eip191"
766
+ * - `chainId`: Ethereum chain ID
767
+ * - `data`: Message data structure
768
+ * - For EIP-712: `{ domain, types, primaryType, message }` with full typed data structure
769
+ * - For EIP-191: `{ message }` with the plain text message to sign
770
+ * @returns Promise resolving to SignMessageResponse with signature components
771
+ * - `v`: Signature v component
772
+ * - `r`: Signature r component (hex string)
773
+ * - `s`: Signature s component (hex string)
774
+ * - `formattedSignature`: Complete signature string (hex)
775
+ * - `type`: Always "evm"
732
776
  * @example
733
777
  * ```ts
734
778
  * // EIP-191 simple message signing
@@ -740,14 +784,33 @@ declare class AgentSdk {
740
784
  * chainId: 1
741
785
  * }
742
786
  * });
787
+ * console.log(`Signature: ${signature.formattedSignature}`);
743
788
  *
744
- * // EIP-712 typed data signing
745
- * const signature = await sdk.signMessage({
746
- * network: "ethereum:1",
789
+ * // EIP-712 typed data signing (for Polymarket orders, etc.)
790
+ * const typedSignature = await sdk.signMessage({
791
+ * network: "ethereum:137",
747
792
  * request: {
748
793
  * messageType: "eip712",
749
- * data: { domain: {...}, types: {...}, primaryType: "Message", message: {...} },
750
- * chainId: 1
794
+ * chainId: 137,
795
+ * data: {
796
+ * domain: {
797
+ * name: "MyApp",
798
+ * version: "1",
799
+ * chainId: 137,
800
+ * verifyingContract: "0x..."
801
+ * },
802
+ * types: {
803
+ * Order: [
804
+ * { name: "maker", type: "address" },
805
+ * { name: "amount", type: "uint256" }
806
+ * ]
807
+ * },
808
+ * primaryType: "Order",
809
+ * message: {
810
+ * maker: "0x...",
811
+ * amount: "1000000"
812
+ * }
813
+ * }
751
814
  * }
752
815
  * });
753
816
  * ```
@@ -774,15 +837,24 @@ declare class AgentSdk {
774
837
  * - **Different networks = bridge**: Same network = swap
775
838
  * - **Native tokens**: Omit `fromToken`/`toToken` for ETH, SOL, etc.
776
839
  *
777
- * @param request Quote parameters
778
- * @param request.from Source wallet `{ network, address }`
779
- * @param request.to Destination wallet `{ network, address }`
780
- * @param request.amount Amount in token's smallest unit (wei for ETH, lamports for SOL)
840
+ * @param request Quote parameters with wallet info, amount, and optional tokens/slippage
841
+ * @param request.from Source wallet `{ network: "ethereum:1" | "ethereum:42161" | etc., address: "0x..." }`
842
+ * @param request.to Destination wallet `{ network: "ethereum:42161" | "solana" | etc., address: "0x..." | "base58" }`
843
+ * @param request.amount Amount in smallest unit (e.g., "1000000000000000000" for 1 ETH, wei for EVM, lamports for Solana)
781
844
  * @param request.fromToken Source token contract address (optional, omit for native tokens like ETH/SOL)
782
845
  * @param request.toToken Destination token contract address (optional, omit for native tokens like ETH/SOL)
783
- * @param request.slippage Slippage tolerance % as string (e.g., "2.0" = 2%, default: "0.5")
784
- * @param request.priceImpact Max price impact % as string (e.g., "1.0" = 1%, default: "0.5")
785
- * @returns Quote with fees, price impact, and transaction steps
846
+ * @param request.slippage Slippage tolerance % as string (default: "0.5", e.g., "2.0" = 2% slippage)
847
+ * @param request.priceImpact Max price impact % as string (default: "0.5", e.g., "1.0" = 1% price impact)
848
+ * @returns SwidgeQuoteResponse with pricing, fees, and transaction steps
849
+ * - `success` (boolean): Whether the quote was retrieved successfully
850
+ * - `data` (SwidgeQuoteData | undefined): Quote data containing:
851
+ * - `assetSend`: Source asset details with amount and decimals
852
+ * - `assetReceive`: Destination asset details with expected amount
853
+ * - `fees`: Array of fee breakdown (network fees, bridge fees, etc.)
854
+ * - `steps`: Transaction steps required to complete the swap
855
+ * - `priceImpact`: Calculated price impact percentage
856
+ * - `error` (string | undefined): Error message if quote failed
857
+ * - `errorDetails` (object | undefined): Detailed error information
786
858
  *
787
859
  * @example
788
860
  * ```ts
@@ -807,18 +879,12 @@ declare class AgentSdk {
807
879
  * // slippage defaults to "0.5", priceImpact defaults to "0.5"
808
880
  * });
809
881
  *
810
- * if (quote.success) {
882
+ * if (quote.success && quote.data) {
811
883
  * console.log(`💰 You'll receive: ${quote.data.assetReceive.amountFormatted}`);
812
884
  * console.log(`💸 Total fees: ${quote.data.fees.map(f => f.name).join(", ")}`);
885
+ * console.log(`📊 Price impact: ${quote.data.priceImpact}%`);
813
886
  * } else if (quote.error) {
814
- * // Check for specific error types
815
- * if (quote.error === QUOTE_RESULT.WALLET_NOT_FOUND) {
816
- * console.log("👛 Wallet not found");
817
- * } else if (quote.error === QUOTE_RESULT.WALLET_MISMATCH) {
818
- * console.log("🔐 Wallet address doesn't match session");
819
- * } else {
820
- * console.log("❓ Quote not available for this swap");
821
- * }
887
+ * console.error(`❌ Quote failed: ${quote.error}`);
822
888
  * }
823
889
  * ```
824
890
  */
@@ -838,8 +904,16 @@ declare class AgentSdk {
838
904
  *
839
905
  * 💡 **Pro tip**: The backend handles all the complexity - you just pass the quote!
840
906
  *
841
- * @param quote Complete quote object from `sdk.swidge.quote()`
842
- * @returns Execution result with status and transaction details
907
+ * @param quote Complete quote object from `sdk.swidge.quote()` (the entire `data` field from the quote response)
908
+ * @returns SwidgeExecuteResponse with transaction status and details
909
+ * - `success` (boolean): Whether the execution was successful
910
+ * - `data` (SwidgeExecuteData | undefined): Execution result containing:
911
+ * - `status`: "success" | "failure" | "refund" | "delayed" - Final transaction status
912
+ * - `in`: Source transaction details with txs array (transaction hashes)
913
+ * - `out`: Destination transaction details with txs array (transaction hashes)
914
+ * - Additional metadata about the swap/bridge operation
915
+ * - `error` (string | undefined): Error message if execution failed
916
+ * - `errorDetails` (object | undefined): Detailed error information
843
917
  *
844
918
  * @example
845
919
  * ```ts
@@ -1010,213 +1084,210 @@ declare class AgentSdk {
1010
1084
  list: () => Promise<MemoryListResponse>;
1011
1085
  };
1012
1086
  /**
1013
- * 📈 Polymarket: Trade prediction markets seamlessly
1087
+ * 🔌 Platform Integrations
1014
1088
  *
1015
- * Access Polymarket positions, execute market orders, and redeem positions using your
1016
- * session wallet. All operations are policy-checked and signed automatically.
1089
+ * Access external platform integrations like Polymarket through the Circuit Agent SDK.
1017
1090
  */
1018
- readonly polymarket: {
1091
+ readonly platforms: {
1019
1092
  /**
1020
- * Get current positions on Polymarket
1093
+ * 📈 Polymarket: Trade prediction markets seamlessly
1021
1094
  *
1022
- * Fetches all open positions for the session wallet, including value, PNL, and market details.
1095
+ * Execute market orders and redeem positions using your session wallet.
1096
+ * All operations are policy-checked and signed automatically.
1023
1097
  *
1024
- * @returns Wrapped response with positions array and total value
1025
- * @example
1026
- * // Usage
1027
- * const result = await sdk.polymarket.positions();
1028
- *
1029
- * if (result.success && result.data) {
1030
- * console.log(`Total portfolio value: $${result.data.totalValue}`);
1031
- * result.data.positions.forEach(pos => {
1032
- * console.log(`${pos.question} - ${pos.outcome}: $${pos.valueUsd} (PNL: ${pos.pnlUsd})`);
1033
- * });
1034
- * } else {
1035
- * console.log(`Error: ${result.error}`);
1036
- * }
1037
- *
1038
- * // Input: None (GET request)
1039
- *
1040
- * // Output showcase (success case):
1041
- * {
1042
- * success: true,
1043
- * data: {
1044
- * totalValue: 150.75,
1045
- * positions: [
1046
- * {
1047
- * contractAddress: "0x...",
1048
- * tokenId: "123456",
1049
- * decimals: 6,
1050
- * conditionId: "0x...",
1051
- * formattedShares: "10.0",
1052
- * shares: "10000000",
1053
- * valueUsd: "10.5",
1054
- * question: "Will event X happen?",
1055
- * outcome: "Yes",
1056
- * priceUsd: "1.05",
1057
- * averagePriceUsd: "0.95",
1058
- * isRedeemable: false,
1059
- * imageUrl: "https://...",
1060
- * initialValue: "9.5",
1061
- * pnlUsd: "1.0",
1062
- * pnlPercent: "10.53",
1063
- * pnlRealizedUsd: "0",
1064
- * pnlRealizedPercent: "0",
1065
- * endDate: "2024-12-31"
1066
- * },
1067
- * // ... more positions
1068
- * ]
1069
- * }
1070
- * }
1071
- *
1072
- * // Error case:
1073
- * {
1074
- * success: false,
1075
- * error: "Could not get positions",
1076
- * errorDetails: { message: "Wallet not found", status: 400 }
1077
- * }
1078
- */
1079
- positions: () => Promise<PolymarketPositionsResponse>;
1080
- /**
1081
- * Execute a market order on Polymarket
1082
- *
1083
- * Places a buy or sell market order for the specified token and size. Handles approvals,
1084
- * signing, and submission automatically.
1085
- *
1086
- * ⚠️ **Important**: The `size` parameter meaning differs by order side:
1087
- * - **BUY**: `size` is the USD amount to spend (e.g., 10 = $10 worth of shares)
1088
- * - **SELL**: `size` is the number of shares/tokens to sell (e.g., 10 = 10 shares)
1089
- *
1090
- * @param request Order parameters
1091
- * @param request.tokenId Market token ID for the position
1092
- * @param request.size For BUY: USD amount to spend. For SELL: Number of shares to sell
1093
- * @param request.side "BUY" or "SELL"
1094
- * @returns Wrapped response with order details and submission result
1095
- * @example
1096
- * // BUY order - size is USD amount
1097
- * const buyResult = await sdk.polymarket.marketOrder({
1098
- * tokenId: "123456",
1099
- * size: 10, // Spend $10 to buy shares
1100
- * side: "BUY"
1101
- * });
1102
- *
1103
- * // SELL order - size is number of shares
1104
- * const sellResult = await sdk.polymarket.marketOrder({
1105
- * tokenId: "123456",
1106
- * size: 5, // Sell 5 shares
1107
- * side: "SELL"
1108
- * });
1109
- *
1110
- * if (buyResult.success && buyResult.data) {
1111
- * console.log(`Order ID: ${buyResult.data.submitOrder.orderId}`);
1112
- * console.log(`Success: ${buyResult.data.submitOrder.success}`);
1113
- * } else {
1114
- * console.log(`Error: ${buyResult.error}`);
1115
- * }
1116
- *
1117
- * // Input showcase:
1118
- * {
1119
- * tokenId: "123456", // Market token ID
1120
- * size: 10, // BUY: USD amount ($10) | SELL: Number of shares (10 shares)
1121
- * side: "BUY" // or "SELL"
1122
- * }
1123
- *
1124
- * // Output showcase (success case):
1125
- * {
1126
- * success: true,
1127
- * data: {
1128
- * order: {
1129
- * eip712Message: {
1130
- * // Typed data for signing (domain, types, message)
1131
- * },
1132
- * order: {
1133
- * salt: "123456789",
1134
- * maker: "0x...",
1135
- * signer: "0x...",
1136
- * taker: "0x...",
1137
- * tokenId: "123456",
1138
- * makerAmount: "105000000", // USD amount in USDC decimals
1139
- * takerAmount: "10000000", // Shares in decimals
1140
- * expiration: "0",
1141
- * nonce: "0",
1142
- * feeRateBps: "0",
1143
- * side: 0, // 0 = BUY, 1 = SELL
1144
- * signatureType: 0 // 0 = EIP712
1145
- * }
1146
- * },
1147
- * submitOrder: {
1148
- * orderId: "abc123",
1149
- * success: true,
1150
- * errorMessage: ""
1151
- * }
1152
- * }
1153
- * }
1154
- *
1155
- * // Error case:
1156
- * {
1157
- * success: false,
1158
- * error: "Could not get order",
1159
- * errorDetails: { message: "Invalid request", status: 400 }
1160
- * }
1161
- */
1162
- marketOrder: (request: PolymarketMarketOrderRequest) => Promise<PolymarketMarketOrderResponse>;
1163
- /**
1164
- * Redeem settled positions on Polymarket
1165
- *
1166
- * Redeems one or all redeemable positions, claiming winnings. Handles multiple transactions if needed.
1167
- *
1168
- * @param request Redemption parameters (omit to redeem all, or pass tokenIds for specific positions)
1169
- * @returns Wrapped response with per-position redemption results
1170
- * @example
1171
- * // Redeem all positions (no arguments - default behavior)
1172
- * const allResult = await sdk.polymarket.redeemPositions();
1173
- *
1174
- * // Redeem specific positions
1175
- * const specificResult = await sdk.polymarket.redeemPositions({ tokenIds: ["123456", "789012"] });
1176
- *
1177
- * if (result.success && result.data) {
1178
- * result.data.forEach(tx => {
1179
- * if (tx.success && tx.position) {
1180
- * console.log(`Redeemed ${tx.position.question}: Tx ${tx.transactionHash}`);
1181
- * } else if (tx.success) {
1182
- * console.log(`Unwrapped collateral: Tx ${tx.transactionHash}`);
1183
- * }
1184
- * });
1185
- * }
1186
- *
1187
- * // Input showcase:
1188
- * // No arguments - redeem all positions (default)
1189
- * // or
1190
- * { tokenIds: ["123456", "789012"] } // Redeem specific positions
1191
- *
1192
- * // Output showcase (success case):
1193
- * {
1194
- * success: true,
1195
- * data: [
1196
- * {
1197
- * success: true,
1198
- * position: {
1199
- * // Full position details as in positions response
1200
- * },
1201
- * transactionHash: "0xabc123..."
1202
- * },
1203
- * {
1204
- * success: true,
1205
- * position: null, // null for unwrap collateral transactions
1206
- * transactionHash: "0xdef456..."
1207
- * },
1208
- * // ... more redemptions
1209
- * ]
1210
- * }
1211
- *
1212
- * // Error case:
1213
- * {
1214
- * success: false,
1215
- * error: "Could not get positions",
1216
- * errorDetails: { message: "No redeemable positions", status: 404 }
1217
- * }
1098
+ * Note: Position data is available via agent.currentPositions in the request.
1218
1099
  */
1219
- redeemPositions: (request?: PolymarketRedeemPositionsRequest) => Promise<PolymarketRedeemPositionsResponse>;
1100
+ polymarket: {
1101
+ /**
1102
+ * Execute a market order on Polymarket
1103
+ *
1104
+ * Places a buy or sell market order for the specified token and size. Handles approvals,
1105
+ * signing, and submission automatically.
1106
+ *
1107
+ * ⚠️ **Important**: The `size` parameter meaning differs by order side:
1108
+ * - **BUY**: `size` is the USD amount to spend (e.g., 10 = $10 worth of shares)
1109
+ * - **SELL**: `size` is the number of shares/tokens to sell (e.g., 10 = 10 shares)
1110
+ *
1111
+ * **Input**: `PolymarketMarketOrderRequest`
1112
+ * - `tokenId` (string): Market token ID for the position
1113
+ * - `size` (number): For BUY: USD amount to spend. For SELL: Number of shares to sell
1114
+ * - `side` ("BUY" | "SELL"): Order side
1115
+ *
1116
+ * **Output**: `PolymarketMarketOrderResponse`
1117
+ * - `success` (boolean): Whether the operation was successful
1118
+ * - `data` (PolymarketMarketOrderData | undefined): Market order data (only present on success)
1119
+ * - `success` (boolean): Whether the order was successfully submitted
1120
+ * - `orderInfo` (PolymarketOrderInfo): Order information with transaction details
1121
+ * - `orderId` (string): Unique order identifier
1122
+ * - `side` (string): Order side ("BUY" or "SELL")
1123
+ * - `size` (string): Order size
1124
+ * - `priceUsd` (string): Price per share in USD
1125
+ * - `totalPriceUsd` (string): Total order value in USD
1126
+ * - `txHashes` (string[]): List of transaction hashes
1127
+ * - `error` (string | undefined): Error message (only present on failure)
1128
+ * - `errorDetails` (object | undefined): Detailed error info
1129
+ *
1130
+ * **Key Functionality**:
1131
+ * - Automatic approval handling for token spending
1132
+ * - EIP-712 signature generation for order placement
1133
+ * - Real-time order submission and confirmation
1134
+ * - Support for both buy and sell orders
1135
+ *
1136
+ * @param request Order parameters (tokenId, size, side)
1137
+ * @returns Promise resolving to PolymarketMarketOrderResponse with order details and submission result
1138
+ * @example
1139
+ * ```ts
1140
+ * // BUY order - size is USD amount
1141
+ * const buyResult = await sdk.polymarket.marketOrder({
1142
+ * tokenId: "123456",
1143
+ * size: 10, // Spend $10 to buy shares
1144
+ * side: "BUY"
1145
+ * });
1146
+ *
1147
+ * // SELL order - size is number of shares
1148
+ * const sellResult = await sdk.polymarket.marketOrder({
1149
+ * tokenId: "123456",
1150
+ * size: 5, // Sell 5 shares
1151
+ * side: "SELL"
1152
+ * });
1153
+ *
1154
+ * if (buyResult.success && buyResult.data) {
1155
+ * console.log(`Order Success: ${buyResult.data.success}`);
1156
+ * console.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
1157
+ * console.log(`Total Price: $${buyResult.data.orderInfo.totalPriceUsd}`);
1158
+ * } else {
1159
+ * console.error(`Error: ${buyResult.error}`);
1160
+ * }
1161
+ * ```
1162
+ *
1163
+ * **Success Case**:
1164
+ * ```json
1165
+ * {
1166
+ * "success": true,
1167
+ * "data": {
1168
+ * "success": true,
1169
+ * "orderInfo": {
1170
+ * "orderId": "abc123",
1171
+ * "side": "BUY",
1172
+ * "size": "10.0",
1173
+ * "priceUsd": "0.52",
1174
+ * "totalPriceUsd": "5.20",
1175
+ * "txHashes": ["0xabc..."]
1176
+ * }
1177
+ * },
1178
+ * "error": undefined
1179
+ * }
1180
+ * ```
1181
+ *
1182
+ * **Error Case**:
1183
+ * ```json
1184
+ * {
1185
+ * "success": false,
1186
+ * "data": undefined,
1187
+ * "error": "Could not get order",
1188
+ * "errorDetails": { "message": "Invalid request", "status": 400 }
1189
+ * }
1190
+ * ```
1191
+ */
1192
+ marketOrder: (request: PolymarketMarketOrderRequest) => Promise<PolymarketMarketOrderResponse>;
1193
+ /**
1194
+ * Redeem settled positions on Polymarket
1195
+ *
1196
+ * Redeems one or all redeemable positions, claiming winnings. Handles multiple transactions if needed.
1197
+ *
1198
+ * **Input**: `PolymarketRedeemPositionsRequest` (optional, defaults to redeem all)
1199
+ * - `tokenIds` (string[], optional): List of token IDs to redeem specific positions. Empty or omitted redeems all redeemable positions.
1200
+ *
1201
+ * **Output**: `PolymarketRedeemPositionsResponse`
1202
+ * - `success` (boolean): Whether the operation was successful
1203
+ * - `data` (PolymarketRedeemPositionResult[] | undefined): Redeem positions data (only present on success)
1204
+ * - Each result contains:
1205
+ * - `success` (boolean): Whether redemption was successful
1206
+ * - `position` (PolymarketPosition | null): Position that was redeemed (full position details, null for unwrap collateral)
1207
+ * - `transactionHash` (string | null): Transaction hash (null if redemption failed)
1208
+ * - `error` (string | undefined): Error message (only present on failure)
1209
+ * - `errorDetails` (object | undefined): Detailed error info
1210
+ *
1211
+ * **Key Functionality**:
1212
+ * - Automatic detection of redeemable positions
1213
+ * - Batch redemption support for multiple positions
1214
+ * - Single position redemption by token ID
1215
+ * - Transaction tracking for each redemption
1216
+ *
1217
+ * @param request Redemption parameters (tokenIds list for specific positions, empty for all)
1218
+ * @returns Promise resolving to PolymarketRedeemPositionsResponse with per-position redemption results
1219
+ * @example
1220
+ * ```ts
1221
+ * // Redeem all positions (no arguments - default behavior)
1222
+ * const allResult = await sdk.polymarket.redeemPositions();
1223
+ *
1224
+ * // Redeem specific positions
1225
+ * const specificResult = await sdk.polymarket.redeemPositions({
1226
+ * tokenIds: ["123456", "789012"]
1227
+ * });
1228
+ *
1229
+ * if (allResult.success && allResult.data) {
1230
+ * for (const tx of allResult.data) {
1231
+ * if (tx.success && tx.position) {
1232
+ * console.log(`Redeemed ${tx.position.question}: Tx ${tx.transactionHash}`);
1233
+ * } else if (tx.success) {
1234
+ * console.log(`Unwrapped collateral: Tx ${tx.transactionHash}`);
1235
+ * } else if (tx.position) {
1236
+ * console.log(`Failed to redeem ${tx.position.question}`);
1237
+ * }
1238
+ * }
1239
+ * } else {
1240
+ * console.error(`Error: ${allResult.error}`);
1241
+ * }
1242
+ * ```
1243
+ *
1244
+ * **Success Case (Multiple Redemptions)**:
1245
+ * ```json
1246
+ * {
1247
+ * "success": true,
1248
+ * "data": [
1249
+ * {
1250
+ * "success": true,
1251
+ * "position": {
1252
+ * "contractAddress": "0x...",
1253
+ * "tokenId": "123456",
1254
+ * "question": "Will event X happen?",
1255
+ * "outcome": "Yes"
1256
+ * },
1257
+ * "transactionHash": "0xabc123..."
1258
+ * },
1259
+ * {
1260
+ * "success": true,
1261
+ * "position": {
1262
+ * "contractAddress": "0x...",
1263
+ * "tokenId": "789012",
1264
+ * "question": "Will event Y happen?",
1265
+ * "outcome": "No"
1266
+ * },
1267
+ * "transactionHash": "0xdef456..."
1268
+ * },
1269
+ * {
1270
+ * "success": true,
1271
+ * "position": null,
1272
+ * "transactionHash": "0xghi789..."
1273
+ * }
1274
+ * ],
1275
+ * "error": undefined
1276
+ * }
1277
+ * ```
1278
+ *
1279
+ * **Error Case**:
1280
+ * ```json
1281
+ * {
1282
+ * "success": false,
1283
+ * "data": undefined,
1284
+ * "error": "Could not get positions",
1285
+ * "errorDetails": { "message": "No redeemable positions", "status": 404 }
1286
+ * }
1287
+ * ```
1288
+ */
1289
+ redeemPositions: (request?: PolymarketRedeemPositionsRequest) => Promise<PolymarketRedeemPositionsResponse>;
1290
+ };
1220
1291
  };
1221
1292
  /**
1222
1293
  * Handle EVM transaction signing and broadcasting
@@ -1230,15 +1301,12 @@ declare class AgentSdk {
1230
1301
  * Handle EVM message signing
1231
1302
  */
1232
1303
  private handleEvmSignMessage;
1233
- /**
1234
- * Send logs to the agent timeline (migrated from AgentToolset)
1235
- */
1236
- private _sendLog;
1237
1304
  /**
1238
1305
  * Internal method to update job status. Used by the Agent wrapper for automatic tracking.
1239
1306
  *
1240
1307
  * This method is not intended for direct use by agent developers - job status tracking
1241
1308
  * is handled automatically by the Agent wrapper.
1309
+ * @internal
1242
1310
  */
1243
1311
  _updateJobStatus(request: UpdateJobStatusRequest): Promise<UpdateJobStatusResponse>;
1244
1312
  /**
@@ -1249,7 +1317,6 @@ declare class AgentSdk {
1249
1317
  * Handle swidge execute requests
1250
1318
  */
1251
1319
  private handleSwidgeExecute;
1252
- private handlePolymarketPositions;
1253
1320
  private handlePolymarketMarketOrder;
1254
1321
  private handlePolymarketRedeemPositions;
1255
1322
  /**
@@ -1291,18 +1358,11 @@ declare class APIClient {
1291
1358
  * Create an API client.
1292
1359
  * @param config - SDK configuration
1293
1360
  * @param config.sessionId - Numeric session identifier propagated as header
1294
- * @param config.baseUrl - Override base URL for local development (auto-detected if omitted)
1295
- * @param config.verbose - Enable detailed logs for debugging
1296
1361
  */
1297
1362
  constructor(config: SDKConfig);
1298
1363
  private getAgentSlug;
1299
1364
  private getAuthHeaders;
1300
1365
  private loadAuthConfig;
1301
- private logging;
1302
- /**
1303
- * Mask sensitive headers and filter out noise headers for logging
1304
- */
1305
- private sanitizeHeaders;
1306
1366
  /**
1307
1367
  * Perform a JSON HTTP request.
1308
1368
  *
@@ -1334,161 +1394,670 @@ declare class APIClient {
1334
1394
  }
1335
1395
 
1336
1396
  /**
1337
- * Request object for agent functions containing session and wallet information.
1338
- * Provided to your `execution`, `chat`, and `stop` handlers.
1339
- */
1340
- declare const AgentRequestSchema: z.ZodObject<{
1341
- sessionId: z.ZodNumber;
1342
- sessionWalletAddress: z.ZodString;
1343
- jobId: z.ZodOptional<z.ZodString>;
1344
- currentPositions: z.ZodOptional<z.ZodArray<z.ZodObject<{
1345
- network: z.ZodString;
1346
- assetAddress: z.ZodString;
1347
- tokenId: z.ZodNullable<z.ZodString>;
1348
- avgUnitCost: z.ZodString;
1349
- currentQty: z.ZodString;
1350
- }, z.core.$strip>>>;
1351
- otherParameters: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
1352
- }, z.core.$strip>;
1353
- /**
1354
- * Standard response format for agent functions (execute and stop commands).
1397
+ * Unified agent interface combining request data and SDK methods.
1398
+ *
1399
+ * This module provides the AgentContext class that serves as the single interface
1400
+ * agent developers interact with. It combines request metadata with all SDK functionality
1401
+ * into one clean object.
1355
1402
  */
1356
- declare const AgentResponseSchema: z.ZodObject<{
1357
- success: z.ZodBoolean;
1358
- error: z.ZodOptional<z.ZodString>;
1359
- message: z.ZodOptional<z.ZodString>;
1360
- }, z.core.$strip>;
1403
+
1361
1404
  /**
1362
- * Health check response format.
1405
+ * Current positions allocated to the agent for this session
1363
1406
  */
1364
- declare const HealthResponseSchema: z.ZodObject<{
1365
- status: z.ZodString;
1366
- }, z.core.$strip>;
1367
- type AgentRequest = z.infer<typeof AgentRequestSchema>;
1368
- type AgentResponse = z.infer<typeof AgentResponseSchema>;
1369
- type HealthResponse = z.infer<typeof HealthResponseSchema>;
1407
+ interface CurrentPosition {
1408
+ network: string;
1409
+ assetAddress: string;
1410
+ tokenId: string | null;
1411
+ avgUnitCost: string;
1412
+ currentQty: string;
1413
+ }
1370
1414
  /**
1371
- * Contract for agent execution functions. Called to perform the agent's main task.
1372
- * @param request - Contains session info and wallet address to operate with
1373
- * @returns Promise resolving to a success/error response
1415
+ * Unified interface for agent developers combining request data and SDK methods.
1416
+ *
1417
+ * This class provides everything an agent needs in a single object:
1418
+ * - **Request metadata**: `sessionId`, `sessionWalletAddress`, `currentPositions`
1419
+ * - **Core methods**: `log()`, `signAndSend()`, `signMessage()`
1420
+ * - **Memory operations**: `memory.set()`, `memory.get()`, `memory.delete()`, `memory.list()`
1421
+ * - **Platform integrations**: `platforms.polymarket.*` for prediction market trading
1422
+ * - **Cross-chain swaps**: `swidge.quote()`, `swidge.execute()`
1423
+ *
1424
+ * The agent developer's execution and stop functions receive this object:
1425
+ *
1374
1426
  * @example
1375
1427
  * ```typescript
1376
- * // Execution function implementation
1377
- * const executionFunction: ExecutionFunctionContract = async (request) => {
1378
- * const agentToolset = new AgentToolset({ sessionId: request.sessionId });
1428
+ * async function execution_function(agent: AgentContext): Promise<void> {
1429
+ * // Logging
1430
+ * await agent.log(`Starting execution for session ${agent.sessionId}`);
1379
1431
  *
1380
- * try {
1381
- * // Send status message
1382
- * await agentToolset.sendLog([{
1383
- * type: "observe",
1384
- * shortMessage: "Starting agent execution..."
1385
- * }]);
1432
+ * // Memory operations
1433
+ * await agent.memory.set("last_run", Date.now().toString());
1434
+ * const saved = await agent.memory.get("last_run");
1386
1435
  *
1387
- * // Example: Send a transaction
1388
- * const { txResult, broadcastResult } = await agentToolset.transactionSignAndBroadcast({
1389
- * chainId: 1,
1390
- * toAddress: request.sessionWalletAddress,
1391
- * data: "0x",
1392
- * valueWei: "1000000000000000000" // 1 ETH
1393
- * });
1436
+ * // Polymarket trading
1437
+ * const order = await agent.platforms.polymarket.marketOrder({
1438
+ * tokenId: "123456",
1439
+ * size: 10,
1440
+ * side: "BUY"
1441
+ * });
1442
+ *
1443
+ * // Cross-chain swaps
1444
+ * const quote = await agent.swidge.quote({
1445
+ * from: { network: "ethereum:1", address: agent.sessionWalletAddress },
1446
+ * to: { network: "ethereum:42161", address: agent.sessionWalletAddress },
1447
+ * amount: "1000000000000000000"
1448
+ * });
1394
1449
  *
1395
- * if (broadcastResult.status === "broadcasted") {
1396
- * return {
1397
- * success: true,
1398
- * message: "Transaction executed successfully"
1399
- * };
1450
+ * // Sign and send transactions
1451
+ * const tx = await agent.signAndSend({
1452
+ * network: "ethereum:1",
1453
+ * request: {
1454
+ * toAddress: "0x...",
1455
+ * data: "0x",
1456
+ * value: "1000000000000000000"
1400
1457
  * }
1458
+ * });
1401
1459
  *
1402
- * return {
1403
- * success: false,
1404
- * error: "Transaction failed to broadcast",
1405
- * message: "Execution failed"
1406
- * };
1407
- * } catch (error) {
1408
- * return {
1409
- * success: false,
1410
- * error: error instanceof Error ? error.message : "Unknown error",
1411
- * message: "Execution failed"
1412
- * };
1413
- * }
1414
- * };
1460
+ * // Sign messages (EIP-712 / EIP-191)
1461
+ * const signature = await agent.signMessage({
1462
+ * network: "ethereum:1",
1463
+ * request: {
1464
+ * messageType: "eip191",
1465
+ * data: { message: "Hello!" },
1466
+ * chainId: 1
1467
+ * }
1468
+ * });
1469
+ * }
1415
1470
  * ```
1471
+ *
1472
+ * @property sessionId - Unique session identifier
1473
+ * @property sessionWalletAddress - Wallet address for this session
1474
+ * @property currentPositions - Current positions allocated to this agent
1475
+ *
1476
+ * @property log - Unified logging method that sends messages to console and Circuit UI
1477
+ * @property signAndSend - Sign and broadcast a transaction on Ethereum or Solana
1478
+ * @property signMessage - Sign a message using EIP-712 or EIP-191 on EVM networks
1479
+ *
1480
+ * @property memory - Session-scoped key-value storage
1481
+ * @property memory.set - Store a key-value pair in session memory
1482
+ * @property memory.get - Retrieve a value by key from session memory
1483
+ * @property memory.delete - Delete a key from session memory
1484
+ * @property memory.list - List all keys in session memory
1485
+ *
1486
+ * @property platforms - Platform integrations (Polymarket, etc.)
1487
+ * @property platforms.polymarket - Prediction market trading operations
1488
+ * @property platforms.polymarket.marketOrder - Execute a buy or sell market order on Polymarket
1489
+ * @property platforms.polymarket.redeemPositions - Redeem settled positions and claim winnings
1490
+ *
1491
+ * @property swidge - Cross-chain swap and bridge operations
1492
+ * @property swidge.quote - Get a quote for swapping tokens between networks
1493
+ * @property swidge.execute - Execute a swap using a quote
1416
1494
  */
1417
- type ExecutionFunctionContract = (request: AgentRequest) => Promise<AgentResponse>;
1495
+ declare class AgentContext {
1496
+ /** Unique session identifier */
1497
+ readonly sessionId: number;
1498
+ /** Wallet address for this session */
1499
+ readonly sessionWalletAddress: string;
1500
+ /** Current positions allocated to this agent (required) */
1501
+ readonly currentPositions: CurrentPosition[];
1502
+ /** Internal SDK instance */
1503
+ private _sdk;
1504
+ /**
1505
+ * Create a new AgentContext instance.
1506
+ *
1507
+ * This is typically created automatically by the Agent wrapper, but can be
1508
+ * instantiated manually for testing in Jupyter notebooks or scripts.
1509
+ *
1510
+ * @param config - Agent context configuration
1511
+ * @param config.sessionId - Unique session identifier
1512
+ * @param config.sessionWalletAddress - Wallet address for this session
1513
+ * @param config.currentPositions - Current positions allocated to this agent
1514
+ * @param config.baseUrl - Override API base URL (detected automatically otherwise)
1515
+ *
1516
+ * @example
1517
+ * ```typescript
1518
+ * // Manual instantiation for testing
1519
+ * const agent = new AgentContext({
1520
+ * sessionId: 123,
1521
+ * sessionWalletAddress: "0x742d35cc6634C0532925a3b8D65e95f32B6b5582",
1522
+ * currentPositions: []
1523
+ * });
1524
+ * await agent.log("Testing agent functionality");
1525
+ * ```
1526
+ */
1527
+ constructor(config: {
1528
+ sessionId: number;
1529
+ sessionWalletAddress: string;
1530
+ currentPositions: CurrentPosition[];
1531
+ baseUrl?: string;
1532
+ });
1533
+ /**
1534
+ * Unified logging method that handles console output and backend messaging.
1535
+ *
1536
+ * This method always logs to the console, and conditionally sends logs to the
1537
+ * backend based on the flags provided. Accepts strings, objects, or arrays -
1538
+ * structured data is automatically pretty-printed to console and serialized for backend.
1539
+ *
1540
+ * **Handles non-serializable data gracefully:**
1541
+ * - BigInt → converted to string
1542
+ * - Functions → shown as `[Function: name]`
1543
+ * - Custom objects → uses toString() if available
1544
+ *
1545
+ * **Behavior:**
1546
+ * - `agent.log("message")` → console.info() + backend POST with type="observe"
1547
+ * - `agent.log("message", { error: true })` → console.error() + backend POST with type="error"
1548
+ * - `agent.log("message", { debug: true })` → console.info() + NO backend call
1549
+ * - `agent.log({ key: "value" })` → Pretty-printed to console + serialized to backend (truncated to 250 chars)
1550
+ * - `agent.log([1, 2, 3])` → Pretty-printed to console + serialized to backend (truncated to 250 chars)
1551
+ *
1552
+ * **What happens:**
1553
+ * - Default (no flags): Shows in your terminal AND in the Circuit UI for your user
1554
+ * - error: true: Shows as error in terminal AND Circuit UI
1555
+ * - debug: true: Shows ONLY in your terminal (users don't see it)
1556
+ *
1557
+ * @param message - The message to log (string, object, or array) - backend receives max 250 chars
1558
+ * @param options - Logging options
1559
+ * @param options.error - If true, log as error and send to backend as error type (default: false)
1560
+ * @param options.debug - If true, only log to console, skip backend call (default: false)
1561
+ * @returns Promise resolving to LogResponse with success status
1562
+ *
1563
+ * @example
1564
+ * ```typescript
1565
+ * // User sees this in Circuit UI
1566
+ * await agent.log("Opening position on Polymarket");
1567
+ *
1568
+ * // Log an object (pretty-printed)
1569
+ * const response = await agent.memory.get("key");
1570
+ * await agent.log(response); // Pretty JSON in console, truncated for backend
1571
+ *
1572
+ * // Log a dict/object (pretty-printed)
1573
+ * await agent.log({ wallet: agent.sessionWalletAddress, status: "active" });
1574
+ *
1575
+ * // Log an array (pretty-printed)
1576
+ * await agent.log([{ position: 1 }, { position: 2 }]);
1577
+ *
1578
+ * // Log complex objects with BigInt, functions, etc. - handled automatically
1579
+ * await agent.log({
1580
+ * amount: 1000000000000000000n, // BigInt
1581
+ * callback: () => {}, // Function
1582
+ * positions: agent.currentPositions
1583
+ * });
1584
+ *
1585
+ * // User sees error in Circuit UI
1586
+ * const result = await agent.memory.get("key");
1587
+ * if (!result.success) {
1588
+ * await agent.log("Failed to load saved settings", { error: true });
1589
+ * }
1590
+ *
1591
+ * // Only you see this in your terminal
1592
+ * await agent.log("Internal debug info", { debug: true });
1593
+ * ```
1594
+ */
1595
+ log(message: string | object | any[], options?: {
1596
+ error?: boolean;
1597
+ debug?: boolean;
1598
+ }): Promise<LogResponse>;
1599
+ /**
1600
+ * Sign and broadcast a transaction on the specified network.
1601
+ *
1602
+ * Delegates to the underlying SDK's signAndSend method.
1603
+ *
1604
+ * **Input**: `SignAndSendRequest`
1605
+ * - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
1606
+ * - `message` (string | undefined): Optional context message (max 250 chars)
1607
+ * - `request` (object): Transaction payload
1608
+ * - For Ethereum:
1609
+ * - `toAddress` (string): Recipient address as hex string
1610
+ * - `data` (string): Calldata as hex string (use "0x" for transfers)
1611
+ * - `value` (string): Wei amount as string
1612
+ * - `gas` (number, optional): Gas limit
1613
+ * - `maxFeePerGas` (string, optional): Max fee per gas in wei
1614
+ * - `maxPriorityFeePerGas` (string, optional): Max priority fee per gas in wei
1615
+ * - `nonce` (number, optional): Transaction nonce
1616
+ * - `enforceTransactionSuccess` (boolean, optional): Enforce transaction success
1617
+ * - For Solana:
1618
+ * - `hexTransaction` (string): Serialized VersionedTransaction as hex string
1619
+ *
1620
+ * **Output**: `SignAndSendResponse`
1621
+ * - `success` (boolean): Whether the operation succeeded
1622
+ * - `txHash` (string | undefined): Transaction hash on success
1623
+ * - `transactionUrl` (string | undefined): Explorer link on success
1624
+ * - `internalTransactionId` (number | undefined): Internal tracking ID
1625
+ * - `error` (string | undefined): Error message on failure
1626
+ * - `errorDetails` (object | undefined): Detailed error info
1627
+ *
1628
+ * @param request - Transaction request with network and transaction details
1629
+ * @returns Promise resolving to SignAndSendResponse with transaction hash or error details
1630
+ *
1631
+ * @example
1632
+ * ```typescript
1633
+ * const response = await agent.signAndSend({
1634
+ * network: "ethereum:42161",
1635
+ * request: {
1636
+ * toAddress: "0x742d35cc6634C0532925a3b8D65e95f32B6b5582",
1637
+ * data: "0x",
1638
+ * value: "1000000000000000000", // 1 ETH
1639
+ * gas: 21000,
1640
+ * maxFeePerGas: "20000000000"
1641
+ * },
1642
+ * message: "Sending 1 ETH"
1643
+ * });
1644
+ *
1645
+ * if (response.success) {
1646
+ * await agent.log(`Transaction sent: ${response.txHash}`);
1647
+ * } else {
1648
+ * await agent.log(response.error || 'Transaction failed', { error: true });
1649
+ * }
1650
+ * ```
1651
+ */
1652
+ signAndSend(request: SignAndSendRequest): Promise<SignAndSendResponse>;
1653
+ /**
1654
+ * Sign a message on an EVM network.
1655
+ *
1656
+ * Delegates to the underlying SDK's signMessage method.
1657
+ * Supports both EIP-712 (typed structured data) and EIP-191 (simple message) signing.
1658
+ *
1659
+ * **Input**: `SignMessageRequest`
1660
+ * - `network` (string): "ethereum:chainId" for EVM networks
1661
+ * - `request` (object): Message signing parameters
1662
+ * - `messageType` (string): "eip712" or "eip191"
1663
+ * - `chainId` (number): Ethereum chain ID
1664
+ * - `data` (object): Message data structure
1665
+ * - For EIP-712: `{ domain, types, primaryType, message }` with full typed data
1666
+ * - For EIP-191: `{ message }` with plain text to sign
1667
+ *
1668
+ * **Output**: `SignMessageResponse`
1669
+ * - `v` (number): Signature v component
1670
+ * - `r` (string): Signature r component (hex string)
1671
+ * - `s` (string): Signature s component (hex string)
1672
+ * - `formattedSignature` (string): Complete signature string (hex)
1673
+ * - `type` (string): Always "evm"
1674
+ *
1675
+ * @param request - Message signing request with type and data
1676
+ * @returns Promise resolving to SignMessageResponse with signature components
1677
+ *
1678
+ * @example
1679
+ * ```typescript
1680
+ * // EIP-191 simple message signing
1681
+ * const signature = await agent.signMessage({
1682
+ * network: "ethereum:1",
1683
+ * request: {
1684
+ * messageType: "eip191",
1685
+ * data: { message: "Hello, world!" },
1686
+ * chainId: 1
1687
+ * }
1688
+ * });
1689
+ * console.log(`Signature: ${signature.formattedSignature}`);
1690
+ *
1691
+ * // EIP-712 typed data signing (for Polymarket orders, etc.)
1692
+ * const typedSignature = await agent.signMessage({
1693
+ * network: "ethereum:137",
1694
+ * request: {
1695
+ * messageType: "eip712",
1696
+ * chainId: 137,
1697
+ * data: {
1698
+ * domain: { name: "MyApp", version: "1", chainId: 137 },
1699
+ * types: { Order: [{ name: "maker", type: "address" }] },
1700
+ * primaryType: "Order",
1701
+ * message: { maker: "0x..." }
1702
+ * }
1703
+ * }
1704
+ * });
1705
+ * ```
1706
+ */
1707
+ signMessage(request: SignMessageRequest): Promise<SignMessageResponse>;
1708
+ /**
1709
+ * Access session-scoped key-value storage.
1710
+ *
1711
+ * Memory operations provide persistent storage for your agent session.
1712
+ * All keys are automatically namespaced by agentId and sessionId.
1713
+ */
1714
+ readonly memory: {
1715
+ /**
1716
+ * Set a key-value pair in session memory.
1717
+ *
1718
+ * Store a string value with a unique key. The key is automatically scoped to your
1719
+ * agent and session, so you don't need to worry about collisions.
1720
+ *
1721
+ * **Input**: `key: string, value: string`
1722
+ * - `key` (string): Unique identifier for the value (1-255 characters)
1723
+ * - `value` (string): String value to store
1724
+ *
1725
+ * **Output**: `MemorySetResponse`
1726
+ * - `success` (boolean): Whether the operation succeeded
1727
+ * - `data`: Present on success with the key that was set
1728
+ * - `error`: Error message on failure
1729
+ *
1730
+ * @param key - Unique identifier for the value (1-255 characters)
1731
+ * @param value - String value to store
1732
+ * @returns Promise resolving to MemorySetResponse with success status
1733
+ *
1734
+ * @example
1735
+ * ```typescript
1736
+ * const result = await agent.memory.set("lastSwapNetwork", "ethereum:42161");
1737
+ * if (result.success && result.data) {
1738
+ * await agent.log(`Stored key: ${result.data.key}`);
1739
+ * } else {
1740
+ * await agent.log(result.error || 'Failed to set memory', { error: true });
1741
+ * }
1742
+ * ```
1743
+ */
1744
+ set: (key: string, value: string) => Promise<MemorySetResponse>;
1745
+ /**
1746
+ * Get a value by key from session memory.
1747
+ *
1748
+ * Retrieve a previously stored value. Returns an error if the key doesn't exist.
1749
+ *
1750
+ * **Input**: `key: string`
1751
+ * - `key` (string): The key to retrieve
1752
+ *
1753
+ * **Output**: `MemoryGetResponse`
1754
+ * - `success` (boolean): Whether the operation succeeded
1755
+ * - `data`: Present on success with key and value
1756
+ * - `error`: Error message (e.g., "Key not found")
1757
+ *
1758
+ * @param key - The key to retrieve
1759
+ * @returns Promise resolving to MemoryGetResponse with key and value or error
1760
+ *
1761
+ * @example
1762
+ * ```typescript
1763
+ * const result = await agent.memory.get("lastSwapNetwork");
1764
+ * if (result.success && result.data) {
1765
+ * await agent.log(`Network: ${result.data.value}`);
1766
+ * } else {
1767
+ * await agent.log(`Key not found: ${result.error}`, { error: true });
1768
+ * }
1769
+ * ```
1770
+ */
1771
+ get: (key: string) => Promise<MemoryGetResponse>;
1772
+ /**
1773
+ * Delete a key from session memory.
1774
+ *
1775
+ * Remove a key-value pair. Succeeds even if the key doesn't exist.
1776
+ *
1777
+ * **Input**: `key: string`
1778
+ * - `key` (string): The key to delete
1779
+ *
1780
+ * **Output**: `MemoryDeleteResponse`
1781
+ * - `success` (boolean): Whether the operation succeeded
1782
+ * - `data`: Present on success with the deleted key
1783
+ * - `error`: Error message on failure
1784
+ *
1785
+ * @param key - The key to delete
1786
+ * @returns Promise resolving to MemoryDeleteResponse with success status
1787
+ *
1788
+ * @example
1789
+ * ```typescript
1790
+ * const result = await agent.memory.delete("tempSwapQuote");
1791
+ * if (result.success && result.data) {
1792
+ * await agent.log(`Deleted key: ${result.data.key}`);
1793
+ * }
1794
+ * ```
1795
+ */
1796
+ delete: (key: string) => Promise<MemoryDeleteResponse>;
1797
+ /**
1798
+ * List all keys in session memory.
1799
+ *
1800
+ * Get an array of all keys stored for this agent session. Useful for debugging
1801
+ * or iterating through stored data.
1802
+ *
1803
+ * **Input**: None
1804
+ *
1805
+ * **Output**: `MemoryListResponse`
1806
+ * - `success` (boolean): Whether the operation succeeded
1807
+ * - `data`: Present on success with keys array and count
1808
+ * - `error`: Error message on failure
1809
+ *
1810
+ * @returns Promise resolving to MemoryListResponse with array of keys
1811
+ *
1812
+ * @example
1813
+ * ```typescript
1814
+ * const result = await agent.memory.list();
1815
+ * if (result.success && result.data) {
1816
+ * await agent.log(`Found ${result.data.count} keys:`);
1817
+ * for (const key of result.data.keys) {
1818
+ * await agent.log(` - ${key}`);
1819
+ * }
1820
+ * }
1821
+ * ```
1822
+ */
1823
+ list: () => Promise<MemoryListResponse>;
1824
+ };
1825
+ /**
1826
+ * Access platform integrations for trading and DeFi operations.
1827
+ *
1828
+ * Platform integrations provide seamless access to external services like
1829
+ * prediction markets, lending protocols, and more.
1830
+ */
1831
+ readonly platforms: {
1832
+ /**
1833
+ * Access Polymarket prediction market trading operations.
1834
+ *
1835
+ * Note: Position data is available via agent.currentPositions in the request.
1836
+ */
1837
+ polymarket: {
1838
+ /**
1839
+ * Execute a market order on Polymarket.
1840
+ *
1841
+ * Places a buy or sell market order for the specified token and size. Handles approvals,
1842
+ * signing, and submission automatically.
1843
+ *
1844
+ * ⚠️ **Important**: The `size` parameter meaning differs by order side:
1845
+ * - **BUY**: `size` is the USD amount to spend (e.g., 10 = $10 worth of shares)
1846
+ * - **SELL**: `size` is the number of shares/tokens to sell (e.g., 10 = 10 shares)
1847
+ *
1848
+ * **Input**: `PolymarketMarketOrderRequest`
1849
+ * - `tokenId` (string): Market token ID for the position
1850
+ * - `size` (number): For BUY: USD amount to spend. For SELL: Number of shares to sell
1851
+ * - `side` ("BUY" | "SELL"): Order side
1852
+ *
1853
+ * **Output**: `PolymarketMarketOrderResponse`
1854
+ * - `success` (boolean): Whether the operation was successful
1855
+ * - `data`: Market order data with orderInfo (orderId, side, priceUsd, txHashes)
1856
+ * - `error`: Error message on failure
1857
+ *
1858
+ * @param request - Order parameters (tokenId, size, side)
1859
+ * @returns Promise resolving to PolymarketMarketOrderResponse with order details
1860
+ *
1861
+ * @example
1862
+ * ```typescript
1863
+ * // BUY order - size is USD amount
1864
+ * const buyResult = await agent.platforms.polymarket.marketOrder({
1865
+ * tokenId: "123456",
1866
+ * size: 10, // Spend $10 to buy shares
1867
+ * side: "BUY"
1868
+ * });
1869
+ *
1870
+ * if (buyResult.success && buyResult.data) {
1871
+ * await agent.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
1872
+ * await agent.log(`Total: $${buyResult.data.orderInfo.totalPriceUsd}`);
1873
+ * }
1874
+ *
1875
+ * // SELL order - size is number of shares
1876
+ * const sellResult = await agent.platforms.polymarket.marketOrder({
1877
+ * tokenId: "123456",
1878
+ * size: 5, // Sell 5 shares
1879
+ * side: "SELL"
1880
+ * });
1881
+ * ```
1882
+ */
1883
+ marketOrder: (request: PolymarketMarketOrderRequest) => Promise<PolymarketMarketOrderResponse>;
1884
+ /**
1885
+ * Redeem settled positions on Polymarket.
1886
+ *
1887
+ * Redeems one or all redeemable positions, claiming winnings. Handles multiple transactions if needed.
1888
+ *
1889
+ * **Input**: `PolymarketRedeemPositionsRequest` (optional)
1890
+ * - `tokenIds` (string[], optional): List of token IDs to redeem. Empty or omitted redeems all.
1891
+ *
1892
+ * **Output**: `PolymarketRedeemPositionsResponse`
1893
+ * - `success` (boolean): Whether the operation was successful
1894
+ * - `data`: Array of redemption results with position details and transaction hashes
1895
+ * - `error`: Error message on failure
1896
+ *
1897
+ * @param request - Redemption parameters (tokenIds list for specific positions, empty for all)
1898
+ * @returns Promise resolving to PolymarketRedeemPositionsResponse with redemption results
1899
+ *
1900
+ * @example
1901
+ * ```typescript
1902
+ * // Redeem all positions
1903
+ * const allResult = await agent.platforms.polymarket.redeemPositions();
1904
+ *
1905
+ * if (allResult.success && allResult.data) {
1906
+ * for (const tx of allResult.data) {
1907
+ * if (tx.success && tx.position) {
1908
+ * await agent.log(`Redeemed: ${tx.position.question}`);
1909
+ * }
1910
+ * }
1911
+ * }
1912
+ *
1913
+ * // Redeem specific positions
1914
+ * const specificResult = await agent.platforms.polymarket.redeemPositions({
1915
+ * tokenIds: ["123456", "789012"]
1916
+ * });
1917
+ * ```
1918
+ */
1919
+ redeemPositions: (request?: PolymarketRedeemPositionsRequest) => Promise<PolymarketRedeemPositionsResponse>;
1920
+ };
1921
+ };
1922
+ /**
1923
+ * Access cross-chain swap and bridge operations.
1924
+ *
1925
+ * Workflow: quote() -> execute(quote.data) -> check result.data.status
1926
+ */
1927
+ readonly swidge: {
1928
+ /**
1929
+ * Get a cross-chain swap or bridge quote.
1930
+ *
1931
+ * Get pricing and routing info for swapping tokens between networks or within the same network.
1932
+ *
1933
+ * **Input**: `SwidgeQuoteRequest`
1934
+ * - `from`: Source wallet `{ network, address }`
1935
+ * - `to`: Destination wallet `{ network, address }`
1936
+ * - `amount`: Amount in smallest unit (wei, lamports, etc.)
1937
+ * - `fromToken` (optional): Source token address (omit for native tokens)
1938
+ * - `toToken` (optional): Destination token address (omit for native tokens)
1939
+ * - `slippage` (optional): Slippage tolerance % as string (default: "0.5")
1940
+ * - `priceImpact` (optional): Max price impact % as string (default: "0.5")
1941
+ *
1942
+ * **Output**: `SwidgeQuoteResponse`
1943
+ * - `success`: Whether the quote was retrieved successfully
1944
+ * - `data`: Quote data with asset details, fees, and steps
1945
+ * - `error`: Error message if quote failed
1946
+ *
1947
+ * @param request - Quote parameters with wallet info, amount, and optional tokens/slippage
1948
+ * @returns Promise resolving to SwidgeQuoteResponse with pricing and transaction steps
1949
+ *
1950
+ * @example
1951
+ * ```typescript
1952
+ * const quote = await agent.swidge.quote({
1953
+ * from: { network: "ethereum:1", address: agent.sessionWalletAddress },
1954
+ * to: { network: "ethereum:42161", address: agent.sessionWalletAddress },
1955
+ * amount: "1000000000000000000", // 1 ETH
1956
+ * toToken: "0x2f2a2543B76A4166549F7aaB2e75BEF0aefC5b0f" // WBTC
1957
+ * });
1958
+ *
1959
+ * if (quote.success && quote.data) {
1960
+ * await agent.log(`You'll receive: ${quote.data.assetReceive.amountFormatted}`);
1961
+ * }
1962
+ * ```
1963
+ */
1964
+ quote: (request: SwidgeQuoteRequest) => Promise<SwidgeQuoteResponse>;
1965
+ /**
1966
+ * Execute a cross-chain swap or bridge using a quote.
1967
+ *
1968
+ * Takes your quote and signs/broadcasts transactions automatically.
1969
+ *
1970
+ * **Input**: `SwidgeQuoteData` - Complete quote object from agent.swidge.quote()
1971
+ *
1972
+ * **Output**: `SwidgeExecuteResponse`
1973
+ * - `success`: Whether the execution was successful
1974
+ * - `data`: Execution result with status ("success", "failure", "refund", "delayed") and transaction hashes
1975
+ * - `error`: Error message if execution failed
1976
+ *
1977
+ * @param quoteData - Complete quote object from agent.swidge.quote()
1978
+ * @returns Promise resolving to SwidgeExecuteResponse with transaction status
1979
+ *
1980
+ * @example
1981
+ * ```typescript
1982
+ * const quote = await agent.swidge.quote({...});
1983
+ * if (quote.success && quote.data) {
1984
+ * const result = await agent.swidge.execute(quote.data);
1985
+ * if (result.success && result.data) {
1986
+ * await agent.log(`Swap status: ${result.data.status}`);
1987
+ * if (result.data.status === "success") {
1988
+ * await agent.log(`Tx hash: ${result.data.out.txs[0]}`);
1989
+ * }
1990
+ * }
1991
+ * }
1992
+ * ```
1993
+ */
1994
+ execute: (quoteData: SwidgeQuoteData) => Promise<SwidgeExecuteResponse>;
1995
+ };
1996
+ }
1997
+
1418
1998
  /**
1419
- * Contract for agent stop/winddown function. Called to gracefully shut down and
1420
- * run cleanup logic (e.g. withdrawing positions, updating schedules).
1421
- * @param request - Contains session information and wallet address to operate with
1422
- * @returns Promise resolving to a success/error response
1999
+ * Contract for agent execution functions. Called to perform the agent's main task.
2000
+ *
2001
+ * Your execution function receives an AgentContext with all request data and SDK methods.
2002
+ * Simply perform your agent logic and return nothing - errors are caught automatically.
2003
+ *
2004
+ * @param agent - AgentContext with session data and SDK methods
2005
+ * @returns Promise that resolves when execution is complete (returns void)
2006
+ *
1423
2007
  * @example
1424
2008
  * ```typescript
1425
- * // Winddown function implementation
1426
- * const stopFunction: StopFunctionContract = async (request) => {
1427
- * const agentToolset = new AgentToolset({ sessionId: request.sessionId });
1428
- *
1429
- * try {
1430
- * // Notify about shutdown
1431
- * await agentToolset.sendLog([{
1432
- * type: "observe",
1433
- * shortMessage: "Agent shutting down...",
1434
- * }]);
2009
+ * async function execution_function(agent: AgentContext): Promise<void> {
2010
+ * await agent.log(`Starting execution for session ${agent.sessionId}`);
1435
2011
  *
1436
- * // Example: Update sleep interval before shutdown
1437
- * await agentToolset.sessionUpdateSleepInterval({
1438
- * sleepMinutes: 60 // Set longer interval during inactive period
1439
- * });
2012
+ * // Use SDK methods directly
2013
+ * await agent.memory.set("last_run", Date.now().toString());
1440
2014
  *
1441
- * // Example: Final status message
1442
- * await agentToolset.sendLog([{
1443
- * type: "observe",
1444
- * shortMessage: "Shutdown complete",
1445
- * }]);
2015
+ * // Check positions from request
2016
+ * await agent.log(`Managing ${agent.currentPositions.length} positions`);
1446
2017
  *
1447
- * return {
1448
- * success: true,
1449
- * message: "Agent stopped successfully"
1450
- * };
1451
- * } catch (error) {
1452
- * return {
1453
- * success: false,
1454
- * error: error instanceof Error ? error.message : "Failed to clean up",
1455
- * message: "Stop operation failed"
1456
- * };
2018
+ * // Error handling pattern
2019
+ * const result = await agent.memory.get("settings");
2020
+ * if (!result.success) {
2021
+ * await agent.log(result.error || 'Failed to get settings', { error: true });
2022
+ * return;
1457
2023
  * }
1458
- * };
2024
+ *
2025
+ * // Errors thrown here are caught automatically
2026
+ * }
1459
2027
  * ```
1460
2028
  */
1461
- type StopFunctionContract = (request: AgentRequest) => Promise<AgentResponse>;
2029
+ type runFunctionContract = (agent: AgentContext) => Promise<void>;
1462
2030
  /**
1463
- * Contract for agent health check functions. Handle health status requests.
1464
- * @returns Promise resolving to an object with a status field
2031
+ * Contract for agent stop/winddown function. Called to gracefully shut down and
2032
+ * run cleanup logic (e.g. redeeming positions, final logging).
2033
+ *
2034
+ * @param agent - AgentContext with session data and SDK methods
2035
+ * @returns Promise that resolves when stop is complete (returns void)
2036
+ *
1465
2037
  * @example
1466
2038
  * ```typescript
1467
- * // Health check function implementation
1468
- * const healthCheckFunction: HealthCheckFunctionContract = async () => {
1469
- * // Check database connection, external services, etc.
1470
- * const isHealthy = await checkSystemHealth();
2039
+ * async function stop_function(agent: AgentContext): Promise<void> {
2040
+ * await agent.log("Cleaning up...");
1471
2041
  *
1472
- * return {
1473
- * status: isHealthy ? "healthy" : "unhealthy",
1474
- * // Optional additional fields
1475
- * uptime: process.uptime(),
1476
- * timestamp: new Date().toISOString()
1477
- * };
1478
- * };
2042
+ * // Redeem positions from request
2043
+ * if (agent.currentPositions.length > 0) {
2044
+ * const redemption = await agent.platforms.polymarket.redeemPositions();
2045
+ * if (!redemption.success) {
2046
+ * await agent.log(redemption.error || 'Redemption failed', { error: true });
2047
+ * }
2048
+ * }
2049
+ * }
1479
2050
  * ```
1480
2051
  */
1481
- type HealthCheckFunctionContract = () => Promise<HealthResponse>;
2052
+ type StopFunctionContract = (agent: AgentContext) => Promise<void>;
1482
2053
  /**
1483
2054
  * Configuration object for creating a new agent
1484
2055
  */
1485
2056
  interface AgentConfig {
1486
2057
  /** Main execution function that implements the agent's core logic */
1487
- executionFunction: ExecutionFunctionContract;
2058
+ runFunction: runFunctionContract;
1488
2059
  /** Optional winddown function for cleanup operations, this is called when the agent is stopped */
1489
2060
  stopFunction?: StopFunctionContract;
1490
- /** Optional health check function for monitoring agent health status */
1491
- healthCheckFunction?: HealthCheckFunctionContract;
1492
2061
  }
1493
2062
  /**
1494
2063
  * HTTP server wrapper for agent functions.
@@ -1496,16 +2065,16 @@ interface AgentConfig {
1496
2065
  * Exposes the following endpoints:
1497
2066
  * - `POST /execute` — required, calls your execution function
1498
2067
  * - `POST /stop` — always available, uses provided or default stop function
1499
- * - `GET /health` — always available, uses provided or default health check
2068
+ * - `GET /health` — always available, uses default health check
1500
2069
  */
1501
2070
  declare class Agent {
1502
2071
  private app;
1503
- private executionFunction;
2072
+ private runFunction;
1504
2073
  private stopFunction?;
1505
- private healthCheckFunction?;
2074
+ private readonly healthCheckFunction;
1506
2075
  /**
1507
2076
  * Create a new `Agent` with the provided handlers.
1508
- * @param config - Execution function is required; chat/stop/health are optional.
2077
+ * @param config - Execution function is required; stop function is optional.
1509
2078
  */
1510
2079
  constructor(config: AgentConfig);
1511
2080
  /**
@@ -1514,10 +2083,25 @@ declare class Agent {
1514
2083
  private defaultStopFunction;
1515
2084
  /**
1516
2085
  * Execute a function with automatic job status tracking.
2086
+ *
2087
+ * Creates AgentContext from request, executes the function, and handles errors automatically.
2088
+ * Uses finally block to guarantee status update even if errors occur.
1517
2089
  */
1518
2090
  private executeWithJobTracking;
1519
2091
  /**
1520
- * Update job status using the AgentSdk.
2092
+ * Safely extract error message from exception with guaranteed fallback.
2093
+ * This method NEVER throws - always returns a valid string.
2094
+ */
2095
+ private getErrorMessage;
2096
+ /**
2097
+ * Update job status with retries and fallback. NEVER throws exceptions.
2098
+ *
2099
+ * Strategy:
2100
+ * 1. Try to send status with error message (3 retries with exponential backoff)
2101
+ * 2. If that fails, try to send status WITHOUT error message (final fallback)
2102
+ *
2103
+ * This ensures the job status is ALWAYS updated, even if the error message
2104
+ * causes issues or the API is temporarily unavailable.
1521
2105
  */
1522
2106
  private updateJobStatus;
1523
2107
  private setupRoutes;
@@ -1526,7 +2110,7 @@ declare class Agent {
1526
2110
  fetch: (request: Request, env: any, ctx: any) => Promise<Response>;
1527
2111
  } | undefined;
1528
2112
  /** Get the worker export for Cloudflare Workers environments. */
1529
- getWorkerExport(): {
2113
+ getExport(): {
1530
2114
  fetch: (request: Request, env: any, ctx: any) => Promise<Response>;
1531
2115
  };
1532
2116
  }
@@ -1554,4 +2138,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
1554
2138
  */
1555
2139
  declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
1556
2140
 
1557
- export { APIClient, Agent, AgentSdk, type ExecutionFunctionContract, type MemoryDeleteRequest, type MemoryDeleteResponse, type MemoryGetRequest, type MemoryGetResponse, type MemoryListRequest, type MemoryListResponse, type MemorySetRequest, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketPosition, type PolymarketPositionsResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type StopFunctionContract, type SwidgeExecuteResponse, type SwidgeQuoteRequest, type SwidgeQuoteResponse, type SwidgeQuoteResult, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork };
2141
+ export { APIClient, Agent, AgentContext, AgentSdk, type CurrentPosition, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type StopFunctionContract, type SwidgeExecuteResponse, type SwidgeQuoteRequest, type SwidgeQuoteResponse, type SwidgeQuoteResult, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };