@circuitorg/agent-sdk 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,7 +24,7 @@ A simplified TypeScript SDK for building automated agents to deploy on Circuit.
24
24
  - [📈 Polymarket Prediction Markets](#-polymarket-prediction-markets)
25
25
  - [Place Market Orders](#place-market-orders)
26
26
  - [Redeem Positions](#redeem-positions)
27
- - [Hyperliquid Perpetuals Trading](#hyperliquid-perpetuals-trading)
27
+ - [Hyperliquid Trading](#hyperliquid-trading)
28
28
  - [Account Information](#account-information)
29
29
  - [Place Orders](#place-orders)
30
30
  - [Order Management](#order-management)
@@ -333,9 +333,17 @@ async function stop(agent: AgentContext): Promise<void> {
333
333
  }
334
334
  ```
335
335
 
336
- ## Hyperliquid Perpetuals Trading
336
+ ## Hyperliquid Trading
337
337
 
338
- Trade perpetual futures on Hyperliquid DEX with leverage.
338
+ Trade perpetual futures (with leverage) and spot markets on Hyperliquid DEX.
339
+
340
+ **Market Types:**
341
+ - **Perp**: Perpetual futures trading with leverage (use `market: "perp"` in order parameters)
342
+ - **Spot**: Spot trading (use `market: "spot"` in order parameters)
343
+
344
+ **Asset Naming for Spot:**
345
+ - Non-Hypercore-native assets use "Unit" prefix: `UBTC` (Unit BTC), `UETH` (Unit ETH)
346
+ - Example: To trade BTC spot, use symbol `UBTC-USDC`
339
347
 
340
348
  ### Account Information
341
349
 
@@ -363,8 +371,8 @@ async function run(agent: AgentContext): Promise<void> {
363
371
 
364
372
  ```typescript
365
373
  async function run(agent: AgentContext): Promise<void> {
366
- // Market order
367
- const order = await agent.platforms.hyperliquid.placeOrder({
374
+ // Perp market order
375
+ const perpOrder = await agent.platforms.hyperliquid.placeOrder({
368
376
  symbol: "BTC-USD",
369
377
  side: "buy",
370
378
  size: 0.0001,
@@ -373,10 +381,26 @@ async function run(agent: AgentContext): Promise<void> {
373
381
  type: "market"
374
382
  });
375
383
 
376
- if (order.success && order.data) {
377
- await agent.log(`Order ${order.data.orderId}: ${order.data.status}`);
384
+ if (perpOrder.success && perpOrder.data) {
385
+ await agent.log(`Perp Order ${perpOrder.data.orderId}: ${perpOrder.data.status}`);
386
+ } else {
387
+ await agent.log(perpOrder.error, { error: true });
388
+ }
389
+
390
+ // Spot market order (for non-Hypercore-native assets like BTC)
391
+ const spotOrder = await agent.platforms.hyperliquid.placeOrder({
392
+ symbol: "UBTC-USDC", // Unit BTC
393
+ side: "buy",
394
+ size: 0.0001,
395
+ price: 110000,
396
+ market: "spot", // Changed to spot
397
+ type: "market"
398
+ });
399
+
400
+ if (spotOrder.success && spotOrder.data) {
401
+ await agent.log(`Spot Order ${spotOrder.data.orderId}: ${spotOrder.data.status}`);
378
402
  } else {
379
- await agent.log(order.error, { error: true });
403
+ await agent.log(spotOrder.error, { error: true });
380
404
  }
381
405
  }
382
406
  ```
package/index.d.ts CHANGED
@@ -286,7 +286,7 @@ declare const AgentLogSchema: z.ZodObject<{
286
286
  reflect: "reflect";
287
287
  warning: "warning";
288
288
  }>;
289
- shortMessage: z.ZodString;
289
+ message: z.ZodString;
290
290
  }, z.core.$strip>;
291
291
  type AgentLog = z.infer<typeof AgentLogSchema>;
292
292
  /**
@@ -601,14 +601,14 @@ declare const SwidgeExecuteResponseWrapperSchema: z.ZodObject<{
601
601
  success: z.ZodBoolean;
602
602
  data: z.ZodOptional<z.ZodObject<{
603
603
  status: z.ZodUnion<readonly [z.ZodLiteral<"success">, z.ZodLiteral<"failure">, z.ZodLiteral<"refund">, z.ZodLiteral<"delayed">]>;
604
- in: z.ZodObject<{
604
+ in: z.ZodOptional<z.ZodObject<{
605
605
  network: z.ZodString;
606
606
  txs: z.ZodArray<z.ZodString>;
607
- }, z.core.$strip>;
608
- out: z.ZodObject<{
607
+ }, z.core.$strip>>;
608
+ out: z.ZodOptional<z.ZodObject<{
609
609
  network: z.ZodString;
610
610
  txs: z.ZodArray<z.ZodString>;
611
- }, z.core.$strip>;
611
+ }, z.core.$strip>>;
612
612
  lastUpdated: z.ZodNumber;
613
613
  error: z.ZodOptional<z.ZodString>;
614
614
  }, z.core.$strip>>;
@@ -640,15 +640,12 @@ declare const PolymarketRedeemPositionsRequestSchema: z.ZodObject<{
640
640
  declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
641
641
  success: z.ZodBoolean;
642
642
  data: z.ZodOptional<z.ZodObject<{
643
- success: z.ZodBoolean;
644
- orderInfo: z.ZodObject<{
645
- orderId: z.ZodString;
646
- side: z.ZodString;
647
- size: z.ZodString;
648
- priceUsd: z.ZodString;
649
- totalPriceUsd: z.ZodString;
650
- txHashes: z.ZodArray<z.ZodString>;
651
- }, z.core.$strip>;
643
+ orderId: z.ZodString;
644
+ side: z.ZodString;
645
+ size: z.ZodString;
646
+ priceUsd: z.ZodString;
647
+ totalPriceUsd: z.ZodString;
648
+ txHashes: z.ZodArray<z.ZodString>;
652
649
  }, z.core.$strip>>;
653
650
  error: z.ZodOptional<z.ZodString>;
654
651
  errorMessage: z.ZodOptional<z.ZodString>;
@@ -1034,7 +1031,7 @@ type MemoryListResponse = z.infer<typeof MemoryListResponseSchema>;
1034
1031
  * sessionId: 12345,
1035
1032
  * });
1036
1033
  *
1037
- * await sdk.sendLog({ type: "observe", shortMessage: "Starting" });
1034
+ * await sdk.sendLog({ type: "observe", message: "Starting" });
1038
1035
  * const tx = await sdk.signAndSend({
1039
1036
  * network: "ethereum:42161",
1040
1037
  * request: {
@@ -1060,6 +1057,17 @@ declare class AgentSdk {
1060
1057
  * ```
1061
1058
  */
1062
1059
  constructor(config: SDKConfig);
1060
+ /**
1061
+ * @internal
1062
+ *
1063
+ * **DO NOT USE - WILL BREAK YOUR AGENTS**
1064
+ *
1065
+ * ⚠️ **WARNING**: This method will cause issues and break your agents.
1066
+ * Do not use this method.
1067
+ *
1068
+ * @param baseUrl - New base URL to use for API requests
1069
+ */
1070
+ setBaseUrl(baseUrl: string): void;
1063
1071
  /**
1064
1072
  * Internal method to send logs to the backend.
1065
1073
  * Used by AgentContext.log() method.
@@ -1489,15 +1497,13 @@ declare class AgentSdk {
1489
1497
  *
1490
1498
  * **Output**: `PolymarketMarketOrderResponse`
1491
1499
  * - `success` (boolean): Whether the operation was successful
1492
- * - `data` (PolymarketMarketOrderData | undefined): Market order data (only present on success)
1493
- * - `success` (boolean): Whether the order was successfully submitted
1494
- * - `orderInfo` (PolymarketOrderInfo): Order information with transaction details
1495
- * - `orderId` (string): Unique order identifier
1496
- * - `side` (string): Order side ("BUY" or "SELL")
1497
- * - `size` (string): Order size
1498
- * - `priceUsd` (string): Price per share in USD
1499
- * - `totalPriceUsd` (string): Total order value in USD
1500
- * - `txHashes` (string[]): List of transaction hashes
1500
+ * - `data` (PolymarketOrderInfo | undefined): Order information (only present on success)
1501
+ * - `orderId` (string): Unique order identifier
1502
+ * - `side` (string): Order side ("BUY" or "SELL")
1503
+ * - `size` (string): Order size
1504
+ * - `priceUsd` (string): Price per share in USD
1505
+ * - `totalPriceUsd` (string): Total order value in USD
1506
+ * - `txHashes` (string[]): List of transaction hashes
1501
1507
  * - `error` (string | undefined): Error message (only present on failure)
1502
1508
  * - `errorDetails` (object | undefined): Detailed error info
1503
1509
  *
@@ -1526,9 +1532,8 @@ declare class AgentSdk {
1526
1532
  * });
1527
1533
  *
1528
1534
  * if (buyResult.success && buyResult.data) {
1529
- * console.log(`Order Success: ${buyResult.data.success}`);
1530
- * console.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
1531
- * console.log(`Total Price: $${buyResult.data.orderInfo.totalPriceUsd}`);
1535
+ * console.log(`Order ID: ${buyResult.data.orderId}`);
1536
+ * console.log(`Total Price: $${buyResult.data.totalPriceUsd}`);
1532
1537
  * } else {
1533
1538
  * console.error(`Error: ${buyResult.error}`);
1534
1539
  * }
@@ -1539,17 +1544,13 @@ declare class AgentSdk {
1539
1544
  * {
1540
1545
  * "success": true,
1541
1546
  * "data": {
1542
- * "success": true,
1543
- * "orderInfo": {
1544
- * "orderId": "abc123",
1545
- * "side": "BUY",
1546
- * "size": "10.0",
1547
- * "priceUsd": "0.52",
1548
- * "totalPriceUsd": "5.20",
1549
- * "txHashes": ["0xabc..."]
1550
- * }
1551
- * },
1552
- * "error": undefined
1547
+ * "orderId": "abc123",
1548
+ * "side": "BUY",
1549
+ * "size": "10.0",
1550
+ * "priceUsd": "0.52",
1551
+ * "totalPriceUsd": "5.20",
1552
+ * "txHashes": ["0xabc..."]
1553
+ * }
1553
1554
  * }
1554
1555
  * ```
1555
1556
  *
@@ -1557,7 +1558,6 @@ declare class AgentSdk {
1557
1558
  * ```json
1558
1559
  * {
1559
1560
  * "success": false,
1560
- * "data": undefined,
1561
1561
  * "error": "Could not get order",
1562
1562
  * "errorDetails": { "message": "Invalid request", "status": 400 }
1563
1563
  * }
@@ -2485,6 +2485,17 @@ declare class AgentContext {
2485
2485
  baseUrl?: string;
2486
2486
  authorizationHeader?: string;
2487
2487
  });
2488
+ /**
2489
+ * @internal
2490
+ *
2491
+ * **DO NOT USE - WILL BREAK YOUR AGENTS**
2492
+ *
2493
+ * ⚠️ **WARNING**: This method will cause issues and break your agents.
2494
+ * Do not use this method.
2495
+ *
2496
+ * @param baseUrl - New base URL to use for API requests
2497
+ */
2498
+ setBaseUrl(baseUrl: string): void;
2488
2499
  /**
2489
2500
  * Unified logging method that handles console output and backend messaging.
2490
2501
  *
package/index.js CHANGED
@@ -1 +1 @@
1
- import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){if(this.isCloudflareWorker()){if(void 0!==globalThis.AGENTS_TO_API_PROXY)return!0;if(void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)return!0}return!1}constructor(r){this.config=r,this.baseUrl=r.baseUrl||"https://agents.circuit.org",this.authorizationHeader=r.authorizationHeader}getAgentSlug(){return"undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG?process.env.CIRCUIT_AGENT_SLUG:void 0!==globalThis.CIRCUIT_AGENT_SLUG?globalThis.CIRCUIT_AGENT_SLUG:void 0}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCloudflareWorker())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json",...this.getAuthHeaders()},...e.headers};let s;if(this.hasServiceBinding()){let o;if(void 0!==globalThis.AGENTS_TO_API_PROXY)o=globalThis.AGENTS_TO_API_PROXY;else{if(void 0===globalThis.__AGENT_ENV__||!globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)throw new Error("Service binding detected but not accessible");o=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}const a={...e,headers:t},n=`https://agents-to-api-proxy.circuit-0bc.workers.dev${r}`;s=await o.fetch(n,a)}else{const o=`${this.baseUrl}${r}`,a={...e,headers:t};s=await fetch(o,a)}if(!s.ok){const r=await s.json().catch(()=>({})),e=r.message||r.error||`HTTP ${s.status}: ${s.statusText}`,t=new Error(e);throw t.error=r.error,t.errorMessage=r.message,t.errorDetails=r,t.statusCode=s.status,t}return await s.json()}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var a=class{client;config;constructor(r){this.config=r,this.client=new e(r)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=await this.client.post("/v1/transactions/evm",r),t=await this.client.post(`/v1/transactions/evm/${e.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:e.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=await this.client.post("/v1/transactions/solana",r),t=await this.client.post(`/v1/transactions/solana/${e.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:e.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return{success:!0,data:await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return{success:!0,data:await this.client.post("/v1/swidge/quote",r)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{const e=await this.client.post("/v1/swidge/execute",r);if(Array.isArray(e))return e.map(r=>{const e="success"===r.status;return{success:e,data:r,error:e?void 0:r.error}});const t="success"===e.status;return{success:t,data:e,error:t?void 0:e.error}}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},a=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{return{success:!0,data:await this.client.post("/v1/platforms/polymarket/market-order",r)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return{success:!0,data:await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{return await this.client.post("/v1/platforms/hyperliquid/order",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return{success:!0,data:await this.client.post(`/v1/memory/${r}`,{value:e})}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return{success:!0,data:await this.client.get(`/v1/memory/${r}`)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return{success:!0,data:await this.client.delete(`/v1/memory/${r}`)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return{success:!0,data:await this.client.get("/v1/memory/list")}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return{success:!0,data:await this.client.get("/v1/transactions/ledger")}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return{success:!0,data:await this.client.get("/v1/positions/current")}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}};import{existsSync as n,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.t=new a({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,a;const n=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,n,2),a=JSON.stringify(r,n)):(o=String(r),a=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{const r=a.length>250?a.slice(0,250):a;return await this.t._sendLog([{type:i,shortMessage:r}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),m=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p)}),g=(h.object({status:h.string()}),class{app;runFunction;stopFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.stopFunction=r.stopFunction,this.app.use("*",d()),this.setupRoutes()}defaultStopFunction=async r=>{await r.log(`Agent stopped for session ${r.sessionId}`)};async executeWithJobTracking(r,e,t){let s,o=!1;try{const s=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,authorizationHeader:t});await e(s),o=!0}catch(r){s=this.getErrorMessage(r),o=!1,console.error("Agent function error:",s)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,o?"success":"failed",s,t)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const n=new a({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await n._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await n._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/stop",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.stopFunction||this.defaultStopFunction;return await this.executeWithJobTracking(e,s,t),r.json({success:!0,message:"Stop completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(n(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){if("undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare)return this.getExport();const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /stop"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:async(r,e,t)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(r,e,t))}}});import{z as f}from"zod";var w=f.templateLiteral(["ethereum:",f.coerce.number().int().nonnegative()]),v=f.union([f.literal("solana"),w]),E=f.object({address:f.string(),network:v}),b=(f.object({from:E,to:E,fromToken:f.string().optional(),toToken:f.string().optional(),amount:f.string(),slippage:f.string().optional()}),f.object({network:v,address:f.string(),token:f.string().nullable(),name:f.string().optional(),symbol:f.string().optional(),decimals:f.number().optional(),amount:f.string().optional(),minimumAmount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()})),T=f.object({usd:f.string().optional(),percentage:f.string().optional()}),k=f.object({name:f.string(),amount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()}),D=f.object({programId:f.string(),keys:f.array(f.object({pubkey:f.string(),isSigner:f.boolean(),isWritable:f.boolean()})),data:f.union([f.string(),f.instanceof(Buffer)])}),F=f.object({type:f.literal("evm"),from:f.string().regex(/^0x[a-fA-F0-9]{40}$/),to:f.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:f.number(),value:f.number(),data:f.string().regex(/^0x[a-fA-F0-9]*$/),gas:f.number().nullish(),maxFeePerGas:f.number().nullish(),maxPriorityFeePerGas:f.number().nullish()}),S=f.object({type:f.literal("solana"),instructions:f.array(D),addressLookupTableAddresses:f.array(f.string())}),O=f.object({type:f.literal("transaction"),description:f.string(),transactionDetails:f.union([F,S]),metadata:f.record(f.string(),f.string())}),A=f.object({type:f.literal("signature"),description:f.string(),signatureData:f.string(),metadata:f.record(f.string(),f.string())}),M=f.discriminatedUnion("type",[O,A]),$=f.object({engine:f.literal("relay"),assetSend:b,assetReceive:b,priceImpact:T,fees:f.array(k),steps:f.array(M)}),q=f.object({network:f.string(),txs:f.array(f.string())}),P=f.object({status:f.union([f.literal("success"),f.literal("failure"),f.literal("refund"),f.literal("delayed")]),in:q,out:q,lastUpdated:f.number(),error:f.string().optional()}),U={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},x=r=>f.object({success:f.boolean(),data:r.optional(),error:f.string().optional(),errorMessage:f.string().optional(),errorDetails:f.object({message:f.string().optional(),error:f.string().optional(),status:f.number().optional(),statusText:f.string().optional()}).optional()});x($),x(P);export{e as APIClient,g as Agent,y as AgentContext,a as AgentSdk,U as QUOTE_RESULT,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
1
+ import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){if(this.isCloudflareWorker()){if(void 0!==globalThis.AGENTS_TO_API_PROXY)return!0;if(void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)return!0}return!1}constructor(r){this.config=r,this.baseUrl=r.baseUrl||"https://agents.circuit.org",this.authorizationHeader=r.authorizationHeader}getAgentSlug(){return"undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG?process.env.CIRCUIT_AGENT_SLUG:void 0!==globalThis.CIRCUIT_AGENT_SLUG?globalThis.CIRCUIT_AGENT_SLUG:void 0}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCloudflareWorker())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json",...this.getAuthHeaders()},...e.headers};let s;if(this.hasServiceBinding()){let o;if(void 0!==globalThis.AGENTS_TO_API_PROXY)o=globalThis.AGENTS_TO_API_PROXY;else{if(void 0===globalThis.__AGENT_ENV__||!globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)throw new Error("Service binding detected but not accessible");o=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}const a={...e,headers:t},n=`https://agents-to-api-proxy.circuit-0bc.workers.dev${r}`;s=await o.fetch(n,a)}else{const o=`${this.baseUrl}${r}`,a={...e,headers:t};s=await fetch(o,a)}if(!s.ok){const r=await s.json().catch(()=>({})),e=r.error||`HTTP ${s.status}: ${s.statusText}`,t=new Error(e);throw t.error=r.error,t.errorMessage=r.error,t.errorDetails=r,t.statusCode=s.status,t}return await s.json()}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var a=class{client;config;constructor(r){this.config=r,this.client=new e(r)}setBaseUrl(r){this.config.baseUrl=r,this.client=new e(this.config)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=(await this.client.post("/v1/transactions/evm",r)).data,t=(await this.client.post(`/v1/transactions/evm/${e.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:e.id,txHash:t.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=(await this.client.post("/v1/transactions/solana",r)).data,t=(await this.client.post(`/v1/transactions/solana/${e.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:e.id,txHash:t.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return await this.client.post("/v1/swap/quote",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{return await this.client.post("/v1/swap/execute",r)}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},a=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{return await this.client.post("/v1/platforms/polymarket/market-order",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{return await this.client.post("/v1/platforms/hyperliquid/order",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return await this.client.post(`/v1/memory/${r}`,{value:e})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return await this.client.get(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return await this.client.delete(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return await this.client.get("/v1/memory/list")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return await this.client.get("/v1/transactions/ledger")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return await this.client.get("/v1/positions/current")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}};import{existsSync as n,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.t=new a({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}setBaseUrl(r){this.t.setBaseUrl(r)}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,a;const n=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,n,2),a=JSON.stringify(r,n)):(o=String(r),a=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{const r=a.length>250?a.slice(0,250):a;return await this.t._sendLog([{type:i,message:r}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),m=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p)}),g=(h.object({status:h.string()}),class{app;runFunction;stopFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.stopFunction=r.stopFunction,this.app.use("*",d()),this.setupRoutes()}defaultStopFunction=async r=>{await r.log(`Agent stopped for session ${r.sessionId}`)};async executeWithJobTracking(r,e,t){let s,o=!1;try{const s=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,authorizationHeader:t});await e(s),o=!0}catch(r){s=this.getErrorMessage(r),o=!1,console.error("Agent function error:",s)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,o?"success":"failed",s,t)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const n=new a({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await n._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await n._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/stop",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.stopFunction||this.defaultStopFunction;return await this.executeWithJobTracking(e,s,t),r.json({success:!0,message:"Stop completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(n(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){if("undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare)return this.getExport();const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /stop"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:async(r,e,t)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(r,e,t))}}});import{z as f}from"zod";var w=f.templateLiteral(["ethereum:",f.coerce.number().int().nonnegative()]),v=f.union([f.literal("solana"),w]),E=f.object({address:f.string(),network:v}),b=(f.object({from:E,to:E,fromToken:f.string().optional(),toToken:f.string().optional(),amount:f.string(),slippage:f.string().optional()}),f.object({network:v,address:f.string(),token:f.string().nullable(),name:f.string().optional(),symbol:f.string().optional(),decimals:f.number().optional(),amount:f.string().optional(),minimumAmount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()})),T=f.object({usd:f.string().optional(),percentage:f.string().optional()}),k=f.object({name:f.string(),amount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()}),D=f.object({programId:f.string(),keys:f.array(f.object({pubkey:f.string(),isSigner:f.boolean(),isWritable:f.boolean()})),data:f.union([f.string(),f.instanceof(Buffer)])}),F=f.object({type:f.literal("evm"),from:f.string().regex(/^0x[a-fA-F0-9]{40}$/),to:f.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:f.number(),value:f.number(),data:f.string().regex(/^0x[a-fA-F0-9]*$/),gas:f.number().nullish(),maxFeePerGas:f.number().nullish(),maxPriorityFeePerGas:f.number().nullish()}),S=f.object({type:f.literal("solana"),instructions:f.array(D),addressLookupTableAddresses:f.array(f.string())}),O=f.object({type:f.literal("transaction"),description:f.string(),transactionDetails:f.union([F,S]),metadata:f.record(f.string(),f.string())}),A=f.object({type:f.literal("signature"),description:f.string(),signatureData:f.string(),metadata:f.record(f.string(),f.string())}),M=f.discriminatedUnion("type",[O,A]),$=f.object({engine:f.literal("relay"),assetSend:b,assetReceive:b,priceImpact:T,fees:f.array(k),steps:f.array(M)}),q=f.object({network:f.string(),txs:f.array(f.string())}),U=f.object({status:f.union([f.literal("success"),f.literal("failure"),f.literal("refund"),f.literal("delayed")]),in:q.optional(),out:q.optional(),lastUpdated:f.number(),error:f.string().optional()}),P={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},x=r=>f.object({success:f.boolean(),data:r.optional(),error:f.string().optional(),errorMessage:f.string().optional(),errorDetails:f.object({message:f.string().optional(),error:f.string().optional(),status:f.number().optional(),statusText:f.string().optional()}).optional()});x($),x(U);export{e as APIClient,g as Agent,y as AgentContext,a as AgentSdk,P as QUOTE_RESULT,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@circuitorg/agent-sdk",
3
- "version": "1.2.4",
3
+ "version": "1.3.0",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",