@circuitorg/agent-sdk 1.0.4 → 1.0.7
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/index.d.ts +2 -3
- package/index.js +1 -1
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import * as hono from 'hono';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
|
|
4
3
|
/**
|
|
@@ -464,11 +463,11 @@ declare class Agent {
|
|
|
464
463
|
private setupRoutes;
|
|
465
464
|
private getPortFromPackageJson;
|
|
466
465
|
run(port?: number): {
|
|
467
|
-
fetch: (request: Request,
|
|
466
|
+
fetch: (request: Request, env: any, ctx: any) => Promise<Response>;
|
|
468
467
|
} | undefined;
|
|
469
468
|
/** Get the worker export for Cloudflare Workers environments. */
|
|
470
469
|
getWorkerExport(): {
|
|
471
|
-
fetch: (request: Request,
|
|
470
|
+
fetch: (request: Request, env: any, ctx: any) => Promise<Response>;
|
|
472
471
|
};
|
|
473
472
|
}
|
|
474
473
|
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __getOwnPropNames=Object.getOwnPropertyNames,__require=(t=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(t,{get:(t,e)=>("undefined"!=typeof require?require:t)[e]}):t)(function(t){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),__commonJS=(t,e)=>function(){return e||(0,t[__getOwnPropNames(t)[0]])((e={exports:{}}).exports,e),e.exports},require_auth_loader=__commonJS({"src/utils/auth-loader.cjs"(exports,module){function loadAuthFromFileSystem(){try{if("undefined"==typeof process||!process.env?.HOME)return;const fs=eval("require")("fs"),path=eval("require")("path"),authPath=path.join(process.env.HOME,".config","circuit","auth.json");if(!fs.existsSync(authPath))return;const authContent=fs.readFileSync(authPath,"utf-8");return JSON.parse(authContent)}catch(t){return}}module.exports={loadAuthFromFileSystem:loadAuthFromFileSystem}}});import{z}from"zod";var API_BASE_URL_LOCAL="https://agents.circuit.org",MessageTypeSchema=z.enum(["observe","validate","reflect","error","warning"]),MessageSchema=z.object({type:MessageTypeSchema,shortMessage:z.string().max(250)}),MessagesRequestSchema=z.array(MessageSchema),MessagesResponseSchema=z.object({status:z.number(),message:z.string()}),TransactionSendRequestSchema=z.object({chainId:z.number(),toAddress:z.string(),data:z.string(),valueWei:z.string(),message:z.string().max(250).optional(),gas:z.number().optional(),maxFeePerGas:z.string().optional(),maxPriorityFeePerGas:z.string().optional()}),SolanaTransactionRequestSchema=z.object({hexTransaction:z.string(),message:z.string().max(250).optional()}),APIClient=class{config;baseUrl;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){
|
|
1
|
+
var __getOwnPropNames=Object.getOwnPropertyNames,__require=(t=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(t,{get:(t,e)=>("undefined"!=typeof require?require:t)[e]}):t)(function(t){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),__commonJS=(t,e)=>function(){return e||(0,t[__getOwnPropNames(t)[0]])((e={exports:{}}).exports,e),e.exports},require_auth_loader=__commonJS({"src/utils/auth-loader.cjs"(exports,module){function loadAuthFromFileSystem(){try{if("undefined"==typeof process||!process.env?.HOME)return;const fs=eval("require")("fs"),path=eval("require")("path"),authPath=path.join(process.env.HOME,".config","circuit","auth.json");if(!fs.existsSync(authPath))return;const authContent=fs.readFileSync(authPath,"utf-8");return JSON.parse(authContent)}catch(t){return}}module.exports={loadAuthFromFileSystem:loadAuthFromFileSystem}}});import{z}from"zod";var API_BASE_URL_LOCAL="https://agents.circuit.org",MessageTypeSchema=z.enum(["observe","validate","reflect","error","warning"]),MessageSchema=z.object({type:MessageTypeSchema,shortMessage:z.string().max(250)}),MessagesRequestSchema=z.array(MessageSchema),MessagesResponseSchema=z.object({status:z.number(),message:z.string()}),TransactionSendRequestSchema=z.object({chainId:z.number(),toAddress:z.string(),data:z.string(),valueWei:z.string(),message:z.string().max(250).optional(),gas:z.number().optional(),maxFeePerGas:z.string().optional(),maxPriorityFeePerGas:z.string().optional()}),SolanaTransactionRequestSchema=z.object({hexTransaction:z.string(),message:z.string().max(250).optional()}),APIClient=class{config;baseUrl;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){let t=!1;return this.isCloudflareWorker()&&(void 0!==globalThis.AGENTS_TO_API_PROXY||void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)&&(t=!0),this.config.verbose,t}constructor(t){this.config=t,this.baseUrl=t.baseUrl||API_BASE_URL_LOCAL}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 t={};t["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(t["X-Agent-Slug"]=e),!this.hasServiceBinding())try{const e=this.loadAuthConfig();e?.sessionToken&&(t.Authorization=`Bearer ${e.sessionToken}`)}catch(t){}return t}loadAuthConfig(){try{const{loadAuthFromFileSystem:t}=require_auth_loader();return t()}catch(t){this.config.verbose}}log(t,e){this.config.verbose}async makeRequest(t,e={}){const s={...{"Content-Type":"application/json",...this.getAuthHeaders()},...e.headers};let r;if(this.log("=== REQUEST DETAILS ==="),this.log("Endpoint:",t),this.log("Method:",e.method||"GET"),this.log("Headers:",s),this.log("Body:",e.body),this.log("Session ID:",this.config.sessionId),this.log("Agent Slug:",this.getAgentSlug()||"not set"),this.log("Using Service Binding:",this.hasServiceBinding()),this.log("====================="),this.hasServiceBinding()){let n;if(void 0!==globalThis.AGENTS_TO_API_PROXY)n=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");n=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}this.log("Using service binding AGENTS_TO_API_PROXY"),this.log("Service binding type:",typeof n);const o={...e,headers:s};r=await n.fetch(t,o)}else{this.log("Using HTTP fallback to:",this.baseUrl);const n=`${this.baseUrl}${t}`,o={...e,headers:s};r=await fetch(n,o)}if(this.log("=== RESPONSE DETAILS ==="),this.log("Status:",r.status),this.log("Status Text:",r.statusText),this.log("Response Headers:",Object.fromEntries(r.headers.entries())),this.log("======================"),!r.ok){const t=await r.json().catch(()=>({}));throw this.log("=== ERROR RESPONSE ==="),this.log("Error Data:",t),this.log("===================="),new Error(t.message||`HTTP ${r.status}: ${r.statusText}`)}const n=await r.json();return this.log("=== SUCCESS RESPONSE ==="),this.log("Response Data:",n),this.log("======================"),n}async get(t){return this.makeRequest(t,{method:"GET"})}async post(t,e){return this.makeRequest(t,{method:"POST",body:e?JSON.stringify(e):void 0})}};function isEthereumNetwork(t){return t.startsWith("ethereum:")}function isSolanaNetwork(t){return"solana"===t}function getChainIdFromNetwork(t){return Number(t.split(":")[1])}var AgentSdk=class{client;config;constructor(t){this.config=t,this.client=new APIClient(t)}log(t,e){this.config.verbose}async addMessage(t){this.log("=== ADD MESSAGE ==="),this.log("Message:",t),this.log("===================");const e=[{type:t.type,shortMessage:t.shortMessage}];await this.messageSend(e)}async signAndSend(t){if(this.log("=== SIGN AND SEND ==="),this.log("Request:",t),this.log("Testing mode:",this.config.testing),this.log("===================="),this.config.testing)return{internalTransactionId:123,txHash:isEthereumNetwork(t.network)?"0xTEST":"TEST_SOL_TX",transactionUrl:void 0};if(isEthereumNetwork(t.network)){const e=getChainIdFromNetwork(t.network);if("toAddress"in t.request)return this.handleEvmTransaction({chainId:e,toAddress:t.request.toAddress,data:t.request.data,valueWei:t.request.value,message:t.message})}if(isSolanaNetwork(t.network)&&"hexTransaction"in t.request)return this.handleSolanaTransaction({hexTransaction:t.request.hexTransaction,message:t.message});throw new Error(`Unsupported network: ${t.network}`)}async handleEvmTransaction(t){const e=await this.client.post("/v1/transactions/evm",t),s=await this.client.post(`/v1/transactions/evm/${e.internalTransactionId}/broadcast`);return{internalTransactionId:e.internalTransactionId,txHash:s.txHash,transactionUrl:s.transactionUrl}}async handleSolanaTransaction(t){const e=await this.client.post("/v1/transactions/solana",t),s=await this.client.post(`/v1/transactions/solana/${e.internalTransactionId}/broadcast`);return{internalTransactionId:e.internalTransactionId,txHash:s.txHash,transactionUrl:s.transactionUrl}}async messageSend(t){return this.config.testing?{status:200,message:"Messages added successfully (TESTING)"}:this.client.post("/v1/messages",t)}};import{zValidator}from"@hono/zod-validator";import{Hono}from"hono";import{cors}from"hono/cors";import{z as z2}from"zod";var AgentRequestSchema=z2.object({sessionId:z2.number(),sessionWalletAddress:z2.string(),otherParameters:z2.object().optional()}),AgentResponseSchema=z2.object({success:z2.boolean(),error:z2.string().optional(),message:z2.string().optional()}),HealthResponseSchema=z2.object({status:z2.string()}),Agent=class{app;executionFunction;chatFunction;stopFunction;healthCheckFunction;constructor(t){this.app=new Hono,this.executionFunction=t.executionFunction,this.chatFunction=t.chatFunction,this.stopFunction=t.stopFunction,this.healthCheckFunction=t.healthCheckFunction||(async()=>({status:"healthy"})),this.app.use("*",cors()),this.setupRoutes()}setupRoutes(){this.app.post("/execute",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=await this.executionFunction(e);return t.json(s)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Execution failed"},500)}}),this.chatFunction&&this.app.post("/chat",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=await(this.chatFunction?.(e));return t.json(s)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Chat failed"},500)}}),this.stopFunction&&(this.app.post("/stop",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=await(this.stopFunction?.(e));return t.json(s)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Stop operation failed"},500)}}),this.app.delete("/",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=await(this.stopFunction?.(e));return t.json(s)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Stop operation failed"},500)}})),this.app.get("/health",async t=>{try{const e=await(this.healthCheckFunction?.());return t.json(e)}catch(e){return t.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const t=__require("fs"),e=__require("path").join(process.cwd(),"package.json");if(t.existsSync(e)){const s=JSON.parse(t.readFileSync(e,"utf-8"));if(s.circuit?.port)return Number.parseInt(s.circuit.port,10)}}catch(t){}return null}run(port){const isCloudflareWorker="undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare;if(isCloudflareWorker)return this.getWorkerExport();const bunEnv=globalThis.Bun?.env,envPort=process.env.AGENT_PORT||bunEnv?.AGENT_PORT,packageJsonPort=this.getPortFromPackageJson();let finalPort=port;!finalPort&&envPort&&(finalPort=Number.parseInt(envPort,10)),!finalPort&&packageJsonPort&&(finalPort=packageJsonPort),finalPort||(finalPort=3e3);try{const req=eval("require"),{serve:serve}=req("@hono/node-server");serve({fetch:this.app.fetch,port:finalPort})}catch(t){process.exit(1)}}getWorkerExport(){return{fetch:async(t,e,s)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(t,e,s))}}};function createAgentHandler(t,e,s,r){return new Agent({executionFunction:t,chatFunction:e,stopFunction:s,healthCheckFunction:r})}export{APIClient,Agent,AgentSdk,getChainIdFromNetwork,isEthereumNetwork,isSolanaNetwork};
|