@0xgasless/agentos 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/dist/config/env.d.ts +12 -0
- package/dist/config/env.js +63 -0
- package/dist/core/AgentOSClient.d.ts +48 -0
- package/dist/core/AgentOSClient.js +115 -0
- package/dist/core/IntentBuilder.d.ts +76 -0
- package/dist/core/IntentBuilder.js +47 -0
- package/dist/cre/CREWorkflowClient.d.ts +22 -0
- package/dist/cre/CREWorkflowClient.js +148 -0
- package/dist/cre/creTypes.d.ts +58 -0
- package/dist/cre/creTypes.js +1 -0
- package/dist/http/fetchWithRetry.d.ts +12 -0
- package/dist/http/fetchWithRetry.js +49 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +16 -0
- package/dist/protocols/erc8004/IdentityManager.d.ts +52 -0
- package/dist/protocols/erc8004/IdentityManager.js +120 -0
- package/dist/protocols/erc8004/erc8004Types.d.ts +15 -0
- package/dist/protocols/erc8004/erc8004Types.js +1 -0
- package/dist/protocols/x402/FacilitatorClient.d.ts +9 -0
- package/dist/protocols/x402/FacilitatorClient.js +106 -0
- package/dist/protocols/x402/X402PaymentHandler.d.ts +25 -0
- package/dist/protocols/x402/X402PaymentHandler.js +139 -0
- package/dist/protocols/x402/x402Types.d.ts +52 -0
- package/dist/protocols/x402/x402Types.js +1 -0
- package/dist/security/ValidationGate.d.ts +12 -0
- package/dist/security/ValidationGate.js +14 -0
- package/dist/sxt/SXTQueryProvider.d.ts +30 -0
- package/dist/sxt/SXTQueryProvider.js +220 -0
- package/dist/sxt/sxtTypes.d.ts +48 -0
- package/dist/sxt/sxtTypes.js +1 -0
- package/dist/telemetry/DashboardLogger.d.ts +35 -0
- package/dist/telemetry/DashboardLogger.js +66 -0
- package/dist/wallet/GaslessWalletProvider.d.ts +55 -0
- package/dist/wallet/GaslessWalletProvider.js +99 -0
- package/package.json +47 -4
package/README.md
CHANGED
|
@@ -1,3 +1,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @0xgasless/agentos
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Client-side agent SDK for [0xGasless](https://0xgasless.com): gasless smart-account wallets, x402 payments and ERC-8004 agent identity.
|
|
4
|
+
|
|
5
|
+
> Early preview (0.x). APIs may change.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i @0xgasless/agentos
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
ESM package. Node 18.18 or newer.
|
|
14
|
+
|
|
15
|
+
## What's inside
|
|
16
|
+
|
|
17
|
+
| Export | What it does |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `GaslessWalletProvider` | Wraps a `@0xgasless/smart-account` account and the `@0xgasless/core` client. Sends sponsored transactions. |
|
|
20
|
+
| `X402PaymentHandler` | Pays an HTTP 402 endpoint through the 0xGasless facilitator (`https://x402.0xgasless.com`). Signs EIP-3009 `TransferWithAuthorization` under the token's own EIP-712 domain (USDC, XSGD on Avalanche and Fuji). |
|
|
21
|
+
| `FacilitatorClient` | `verify` / `settle` calls to an x402 facilitator. |
|
|
22
|
+
| `IdentityManager` | ERC-8004 register, lookup and feedback. |
|
|
23
|
+
| `AgentOSClient`, `IntentBuilder`, `ValidationGate` | Intent parsing and validation before execution. |
|
|
24
|
+
|
|
25
|
+
## x402 note
|
|
26
|
+
|
|
27
|
+
`X402PaymentHandler` settles the payment itself through the facilitator, then retries the request with the transaction hash in an `x402-payment` header. To pay a standard x402 v2 server (one that settles with an `X-PAYMENT` header), use the official [`@x402/fetch`](https://www.npmjs.com/package/@x402/fetch) client and point the server at `https://x402.0xgasless.com`.
|
|
28
|
+
|
|
29
|
+
The retired A402 relayer flow is no longer used. `relayerContract` in payment requirements is ignored.
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
|
|
33
|
+
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CREWorkflowConfig } from "../cre/creTypes.js";
|
|
2
|
+
import type { SXTQueryConfig } from "../sxt/sxtTypes.js";
|
|
3
|
+
import type { ERC8004RegistryConfig } from "../protocols/erc8004/erc8004Types.js";
|
|
4
|
+
type EnvMap = Record<string, string | undefined>;
|
|
5
|
+
/**
|
|
6
|
+
* Optional helpers to hydrate configs from environment variables (e.g. in Node workers).
|
|
7
|
+
* Set variables only in secure execution environments — never embed secrets in browser bundles.
|
|
8
|
+
*/
|
|
9
|
+
export declare function sxtConfigFromEnv(env?: EnvMap): SXTQueryConfig;
|
|
10
|
+
export declare function creConfigFromEnv(env?: EnvMap): CREWorkflowConfig;
|
|
11
|
+
export declare function erc8004ConfigFromEnv(env?: EnvMap): ERC8004RegistryConfig;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
function defaultEnv() {
|
|
2
|
+
const g = globalThis;
|
|
3
|
+
return g.process?.env ?? {};
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Optional helpers to hydrate configs from environment variables (e.g. in Node workers).
|
|
7
|
+
* Set variables only in secure execution environments — never embed secrets in browser bundles.
|
|
8
|
+
*/
|
|
9
|
+
export function sxtConfigFromEnv(env = defaultEnv()) {
|
|
10
|
+
const baseUrl = env.AGENTOS_SXT_BASE_URL ?? env.SXT_BASE_URL ?? "";
|
|
11
|
+
const accessToken = env.AGENTOS_SXT_ACCESS_TOKEN ?? env.SXT_ACCESS_TOKEN ?? "";
|
|
12
|
+
const erc20TransfersTableFqn = env.AGENTOS_SXT_ERC20_TABLE ?? env.SXT_ERC20_TRANSFERS_TABLE ?? "";
|
|
13
|
+
if (!baseUrl || !accessToken || !erc20TransfersTableFqn) {
|
|
14
|
+
throw new Error("sxtConfigFromEnv: set AGENTOS_SXT_BASE_URL, AGENTOS_SXT_ACCESS_TOKEN, and AGENTOS_SXT_ERC20_TABLE (or SXT_* aliases)");
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
baseUrl,
|
|
18
|
+
accessToken,
|
|
19
|
+
erc20TransfersTableFqn,
|
|
20
|
+
toAddressColumn: env.AGENTOS_SXT_TO_COLUMN,
|
|
21
|
+
valueColumn: env.AGENTOS_SXT_VALUE_COLUMN,
|
|
22
|
+
blockTimestampColumn: env.AGENTOS_SXT_TS_COLUMN,
|
|
23
|
+
requestTimeoutMs: env.AGENTOS_SXT_TIMEOUT_MS ? Number(env.AGENTOS_SXT_TIMEOUT_MS) : undefined,
|
|
24
|
+
maxRetries: env.AGENTOS_SXT_MAX_RETRIES ? Number(env.AGENTOS_SXT_MAX_RETRIES) : undefined,
|
|
25
|
+
mockMode: env.AGENTOS_SXT_MOCK === "1" || env.AGENTOS_SXT_MOCK === "true",
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function creConfigFromEnv(env = defaultEnv()) {
|
|
29
|
+
const endpointUrl = env.AGENTOS_CRE_ENDPOINT_URL ?? env.CRE_ENDPOINT_URL ?? "";
|
|
30
|
+
const workflowId = env.AGENTOS_CRE_WORKFLOW_ID ?? env.CRE_WORKFLOW_ID ?? "";
|
|
31
|
+
if (!endpointUrl || !workflowId) {
|
|
32
|
+
throw new Error("creConfigFromEnv: set AGENTOS_CRE_ENDPOINT_URL and AGENTOS_CRE_WORKFLOW_ID");
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
endpointUrl,
|
|
36
|
+
workflowId,
|
|
37
|
+
useWorkflowPath: env.AGENTOS_CRE_USE_WORKFLOW_PATH === "0" ? false : undefined,
|
|
38
|
+
headers: env.AGENTOS_CRE_API_KEY
|
|
39
|
+
? { "x-api-key": env.AGENTOS_CRE_API_KEY }
|
|
40
|
+
: env.AGENTOS_CRE_AUTH_HEADER && env.AGENTOS_CRE_AUTH_VALUE
|
|
41
|
+
? { [env.AGENTOS_CRE_AUTH_HEADER]: env.AGENTOS_CRE_AUTH_VALUE }
|
|
42
|
+
: undefined,
|
|
43
|
+
requestTimeoutMs: env.AGENTOS_CRE_TIMEOUT_MS ? Number(env.AGENTOS_CRE_TIMEOUT_MS) : undefined,
|
|
44
|
+
maxRetries: env.AGENTOS_CRE_MAX_RETRIES ? Number(env.AGENTOS_CRE_MAX_RETRIES) : undefined,
|
|
45
|
+
minConsensusSignatures: env.AGENTOS_CRE_MIN_SIGNATURES
|
|
46
|
+
? Number(env.AGENTOS_CRE_MIN_SIGNATURES)
|
|
47
|
+
: undefined,
|
|
48
|
+
mockMode: env.AGENTOS_CRE_MOCK === "1" || env.AGENTOS_CRE_MOCK === "true",
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export function erc8004ConfigFromEnv(env = defaultEnv()) {
|
|
52
|
+
const identityRegistry = env.AGENTOS_ERC8004_IDENTITY_REGISTRY ?? "";
|
|
53
|
+
const reputationRegistry = env.AGENTOS_ERC8004_REPUTATION_REGISTRY ?? "";
|
|
54
|
+
const validationRegistry = env.AGENTOS_ERC8004_VALIDATION_REGISTRY;
|
|
55
|
+
if (!identityRegistry || !reputationRegistry) {
|
|
56
|
+
throw new Error("erc8004ConfigFromEnv: set AGENTOS_ERC8004_IDENTITY_REGISTRY and AGENTOS_ERC8004_REPUTATION_REGISTRY (optional AGENTOS_ERC8004_VALIDATION_REGISTRY)");
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
identityRegistry: identityRegistry,
|
|
60
|
+
reputationRegistry: reputationRegistry,
|
|
61
|
+
validationRegistry: validationRegistry ? validationRegistry : undefined,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { GaslessWalletProvider } from "../wallet/GaslessWalletProvider.js";
|
|
2
|
+
import { CREWorkflowClient } from "../cre/CREWorkflowClient.js";
|
|
3
|
+
import { SXTQueryProvider } from "../sxt/SXTQueryProvider.js";
|
|
4
|
+
import { X402PaymentHandler } from "../protocols/x402/X402PaymentHandler.js";
|
|
5
|
+
import { IdentityManager } from "../protocols/erc8004/IdentityManager.js";
|
|
6
|
+
import type { ERC8004RegistryConfig } from "../protocols/erc8004/erc8004Types.js";
|
|
7
|
+
import { DashboardLogger } from "../telemetry/DashboardLogger.js";
|
|
8
|
+
export interface AgentOSConfig {
|
|
9
|
+
walletProvider: GaslessWalletProvider;
|
|
10
|
+
creClient: CREWorkflowClient;
|
|
11
|
+
sxtProvider: SXTQueryProvider;
|
|
12
|
+
logger?: DashboardLogger;
|
|
13
|
+
/** ERC-8004 registry addresses for the active chain. */
|
|
14
|
+
erc8004?: ERC8004RegistryConfig;
|
|
15
|
+
/**
|
|
16
|
+
* When set to `"production"`, hard-fails if any module is running in `mockMode`.
|
|
17
|
+
* This prevents accidentally shipping a build that bypasses the Decision Boundary.
|
|
18
|
+
*/
|
|
19
|
+
mode?: "development" | "production";
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Enterprise client-side agent orchestrator integrating 0xGasless infrastructure.
|
|
23
|
+
* This client manages the 7-step trustless flow:
|
|
24
|
+
* Intent Creation -> Data Verification (SXT) -> Policy Evaluation (CRE) -> Signing (CRE DON) -> Settlement (x402/ERC-4337).
|
|
25
|
+
*/
|
|
26
|
+
export declare class AgentOSClient {
|
|
27
|
+
private readonly erc8004Override?;
|
|
28
|
+
private erc8004Resolved;
|
|
29
|
+
readonly wallet: GaslessWalletProvider;
|
|
30
|
+
readonly cre: CREWorkflowClient;
|
|
31
|
+
readonly sxt: SXTQueryProvider;
|
|
32
|
+
readonly x402: X402PaymentHandler;
|
|
33
|
+
readonly identity: IdentityManager;
|
|
34
|
+
readonly logger: DashboardLogger;
|
|
35
|
+
constructor(config: AgentOSConfig);
|
|
36
|
+
/**
|
|
37
|
+
* Executes the 7-step Trustless Intent Flow.
|
|
38
|
+
* Eliminates single-server trust by enforcing BFT consensus and ZK proofs
|
|
39
|
+
* prior to ERC-4337 settlement. tightly bounds execution exclusively to 0xGasless.
|
|
40
|
+
* Emits precise telemetry states for dashboarding.
|
|
41
|
+
*/
|
|
42
|
+
executeIntent(rawInput: unknown): Promise<{
|
|
43
|
+
success: boolean;
|
|
44
|
+
txHash?: string;
|
|
45
|
+
error?: string;
|
|
46
|
+
}>;
|
|
47
|
+
private resolveErc8004DefaultsIfNeeded;
|
|
48
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { X402PaymentHandler } from "../protocols/x402/X402PaymentHandler.js";
|
|
2
|
+
import { IdentityManager } from "../protocols/erc8004/IdentityManager.js";
|
|
3
|
+
import { IntentBuilder } from "./IntentBuilder.js";
|
|
4
|
+
import { DashboardLogger } from "../telemetry/DashboardLogger.js";
|
|
5
|
+
const DEFAULT_ERC8004_REGISTRIES_FUJI = {
|
|
6
|
+
identityRegistry: "0xD610EB5f4dbBa10EB1bC95C9e84c025dCeac8291",
|
|
7
|
+
reputationRegistry: "0x8969005399f7440b2758950248dA385471fF4AF5",
|
|
8
|
+
validationRegistry: "0xE85759f7EB1D41d3AF295a16b1e2DB17270d4c81",
|
|
9
|
+
};
|
|
10
|
+
const DEFAULT_ERC8004_REGISTRIES_AVALANCHE_MAINNET = {
|
|
11
|
+
identityRegistry: "0x06d49e79da8a241dd2c412bf5d22e19c619a39d1",
|
|
12
|
+
reputationRegistry: "0x29A62d678dCc581414BB3A74dF27E99c17e60dD7",
|
|
13
|
+
validationRegistry: "0xa490b79113d8ef4e7c7912759a3fcaff8a58cd05",
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Enterprise client-side agent orchestrator integrating 0xGasless infrastructure.
|
|
17
|
+
* This client manages the 7-step trustless flow:
|
|
18
|
+
* Intent Creation -> Data Verification (SXT) -> Policy Evaluation (CRE) -> Signing (CRE DON) -> Settlement (x402/ERC-4337).
|
|
19
|
+
*/
|
|
20
|
+
export class AgentOSClient {
|
|
21
|
+
erc8004Override;
|
|
22
|
+
erc8004Resolved = false;
|
|
23
|
+
wallet;
|
|
24
|
+
cre;
|
|
25
|
+
sxt;
|
|
26
|
+
x402;
|
|
27
|
+
identity;
|
|
28
|
+
logger;
|
|
29
|
+
constructor(config) {
|
|
30
|
+
this.wallet = config.walletProvider;
|
|
31
|
+
this.cre = config.creClient;
|
|
32
|
+
this.sxt = config.sxtProvider;
|
|
33
|
+
this.logger = config.logger || new DashboardLogger();
|
|
34
|
+
this.x402 = new X402PaymentHandler(this.wallet);
|
|
35
|
+
this.erc8004Override = config.erc8004;
|
|
36
|
+
// Default: Avalanche Fuji; will auto-switch to Avalanche mainnet if chainId=43114 and no override is provided.
|
|
37
|
+
this.identity = new IdentityManager(this.wallet, this.sxt, this.erc8004Override ?? DEFAULT_ERC8004_REGISTRIES_FUJI);
|
|
38
|
+
if ((config.mode ?? "development") === "production") {
|
|
39
|
+
if (this.cre.config.mockMode) {
|
|
40
|
+
throw new Error("AgentOSClient: CREWorkflowClient is in mockMode (forbidden in production)");
|
|
41
|
+
}
|
|
42
|
+
if (this.sxt.config.mockMode) {
|
|
43
|
+
throw new Error("AgentOSClient: SXTQueryProvider is in mockMode (forbidden in production)");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Executes the 7-step Trustless Intent Flow.
|
|
49
|
+
* Eliminates single-server trust by enforcing BFT consensus and ZK proofs
|
|
50
|
+
* prior to ERC-4337 settlement. tightly bounds execution exclusively to 0xGasless.
|
|
51
|
+
* Emits precise telemetry states for dashboarding.
|
|
52
|
+
*/
|
|
53
|
+
async executeIntent(rawInput) {
|
|
54
|
+
try {
|
|
55
|
+
await this.resolveErc8004DefaultsIfNeeded();
|
|
56
|
+
this.logger.info("EXECUTION_START", "AI Agent initiated a new action request", { rawInput });
|
|
57
|
+
const intent = IntentBuilder.build(rawInput);
|
|
58
|
+
this.logger.debug("INTENT_FORMULATED", "Successfully parsed strict Zod Intent", { intent });
|
|
59
|
+
const agentAddress = await this.wallet.getAddress();
|
|
60
|
+
this.logger.info("SXT_QUERY_START", `Fetching ZK Proof of SXT spending history for ${agentAddress}`);
|
|
61
|
+
const spendingData = await this.sxt.getAgentSpendingHistory(agentAddress, 24);
|
|
62
|
+
this.logger.debug("SXT_QUERY_SUCCESS", "Retrieved historical bounds", { total: spendingData.total.toString(), proof: spendingData.proof.substring(0, 10) + "..." });
|
|
63
|
+
this.logger.info("CRE_CONSENSUS_START", "Submitting Intent to Chainlink DON for rule evaluation");
|
|
64
|
+
const evaluation = await this.cre.evaluateIntent(intent, spendingData);
|
|
65
|
+
if (!evaluation.approved || !evaluation.signature) {
|
|
66
|
+
this.logger.warn("CRE_CONSENSUS_REJECTED", "DON consensus blocked the execution due to policy bounds", { reason: evaluation.error });
|
|
67
|
+
throw new Error(`CRE Policy Rejection: ${evaluation.error || 'Consensus failed'}`);
|
|
68
|
+
}
|
|
69
|
+
this.logger.info("CRE_CONSENSUS_APPROVED", "DON consensus reached, BLS signature acquired", { signature: evaluation.signature.substring(0, 10) + "..." });
|
|
70
|
+
// Handle branching based on Intent Action Type
|
|
71
|
+
if (intent.actionType === "X402_PAYMENT") {
|
|
72
|
+
if (!intent.amount)
|
|
73
|
+
throw new Error("Amount is required for X402_PAYMENT");
|
|
74
|
+
this.logger.info("X402_EXECUTION_START", "Routing approved Intent to X402 Payment Handler");
|
|
75
|
+
const paymentResult = await this.x402.performPayment(intent.target, intent.amount);
|
|
76
|
+
if (paymentResult.success) {
|
|
77
|
+
this.logger.info("X402_EXECUTION_SUCCESS", "x402 HTTP Payment completed", { token: paymentResult.token });
|
|
78
|
+
return { success: true, txHash: paymentResult.token }; // Token acts as proof of settlement
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
this.logger.error("X402_EXECUTION_FAILED", "x402 Payment failed", { error: paymentResult.error });
|
|
82
|
+
return { success: false, error: paymentResult.error };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Default EVM Layer 2 Execution
|
|
86
|
+
this.logger.info("ERC4337_EXECUTION_START", "Routing approved Intent to 0xGasless Smart Account execution");
|
|
87
|
+
const txResult = await this.wallet.sendTransactionFromIntent(intent, evaluation.signature);
|
|
88
|
+
if (txResult.success) {
|
|
89
|
+
this.logger.info("ERC4337_EXECUTION_SUCCESS", "Gasless transaction settled via Paymaster", { txHash: txResult.txHash }, txResult.txHash);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
this.logger.error("ERC4337_EXECUTION_FAILED", "Smart account execution reverted", { error: txResult.error });
|
|
93
|
+
}
|
|
94
|
+
return txResult;
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
this.logger.error("EXECUTION_EXCEPTION", "Agent operation failed or was actively blocked", e);
|
|
98
|
+
return { success: false, error: e.message };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async resolveErc8004DefaultsIfNeeded() {
|
|
102
|
+
if (this.erc8004Resolved)
|
|
103
|
+
return;
|
|
104
|
+
this.erc8004Resolved = true;
|
|
105
|
+
if (this.erc8004Override)
|
|
106
|
+
return;
|
|
107
|
+
const chainId = await this.wallet.getChainId();
|
|
108
|
+
if (chainId === 43114) {
|
|
109
|
+
this.identity.setRegistries(DEFAULT_ERC8004_REGISTRIES_AVALANCHE_MAINNET);
|
|
110
|
+
}
|
|
111
|
+
else if (chainId === 43113) {
|
|
112
|
+
this.identity.setRegistries(DEFAULT_ERC8004_REGISTRIES_FUJI);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const IntentSchema: z.ZodDiscriminatedUnion<"actionType", [z.ZodObject<{
|
|
3
|
+
actionType: z.ZodLiteral<"TRANSFER">;
|
|
4
|
+
target: z.ZodString;
|
|
5
|
+
amount: z.ZodString;
|
|
6
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
7
|
+
}, "strict", z.ZodTypeAny, {
|
|
8
|
+
actionType: "TRANSFER";
|
|
9
|
+
target: string;
|
|
10
|
+
amount: string;
|
|
11
|
+
data?: Record<string, any> | undefined;
|
|
12
|
+
}, {
|
|
13
|
+
actionType: "TRANSFER";
|
|
14
|
+
target: string;
|
|
15
|
+
amount: string;
|
|
16
|
+
data?: Record<string, any> | undefined;
|
|
17
|
+
}>, z.ZodObject<{
|
|
18
|
+
actionType: z.ZodLiteral<"SWAP">;
|
|
19
|
+
target: z.ZodString;
|
|
20
|
+
amount: z.ZodString;
|
|
21
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
22
|
+
}, "strict", z.ZodTypeAny, {
|
|
23
|
+
actionType: "SWAP";
|
|
24
|
+
target: string;
|
|
25
|
+
amount: string;
|
|
26
|
+
data?: Record<string, any> | undefined;
|
|
27
|
+
}, {
|
|
28
|
+
actionType: "SWAP";
|
|
29
|
+
target: string;
|
|
30
|
+
amount: string;
|
|
31
|
+
data?: Record<string, any> | undefined;
|
|
32
|
+
}>, z.ZodObject<{
|
|
33
|
+
actionType: z.ZodLiteral<"API_CALL">;
|
|
34
|
+
target: z.ZodString;
|
|
35
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
36
|
+
}, "strict", z.ZodTypeAny, {
|
|
37
|
+
actionType: "API_CALL";
|
|
38
|
+
target: string;
|
|
39
|
+
data?: Record<string, any> | undefined;
|
|
40
|
+
}, {
|
|
41
|
+
actionType: "API_CALL";
|
|
42
|
+
target: string;
|
|
43
|
+
data?: Record<string, any> | undefined;
|
|
44
|
+
}>, z.ZodObject<{
|
|
45
|
+
actionType: z.ZodLiteral<"X402_PAYMENT">;
|
|
46
|
+
target: z.ZodString;
|
|
47
|
+
amount: z.ZodString;
|
|
48
|
+
}, "strict", z.ZodTypeAny, {
|
|
49
|
+
actionType: "X402_PAYMENT";
|
|
50
|
+
target: string;
|
|
51
|
+
amount: string;
|
|
52
|
+
}, {
|
|
53
|
+
actionType: "X402_PAYMENT";
|
|
54
|
+
target: string;
|
|
55
|
+
amount: string;
|
|
56
|
+
}>, z.ZodObject<{
|
|
57
|
+
actionType: z.ZodLiteral<"IDENTITY_REGISTER">;
|
|
58
|
+
target: z.ZodString;
|
|
59
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
60
|
+
}, "strict", z.ZodTypeAny, {
|
|
61
|
+
actionType: "IDENTITY_REGISTER";
|
|
62
|
+
target: string;
|
|
63
|
+
data?: Record<string, any> | undefined;
|
|
64
|
+
}, {
|
|
65
|
+
actionType: "IDENTITY_REGISTER";
|
|
66
|
+
target: string;
|
|
67
|
+
data?: Record<string, any> | undefined;
|
|
68
|
+
}>]>;
|
|
69
|
+
export type Intent = z.infer<typeof IntentSchema>;
|
|
70
|
+
/**
|
|
71
|
+
* Transforms raw LLM/Agent tool outputs into structured Intent objects.
|
|
72
|
+
* An Intent is *not* a transaction; it is a request for the CRE DON to evaluate.
|
|
73
|
+
*/
|
|
74
|
+
export declare class IntentBuilder {
|
|
75
|
+
static build(rawInput: unknown): Intent;
|
|
76
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ValidationGate } from "../security/ValidationGate.js";
|
|
3
|
+
/**
|
|
4
|
+
* Strict schema defining structured Intents.
|
|
5
|
+
* Uses a discriminated union to apply completely different validation per actionType.
|
|
6
|
+
* Prevents prompt injections (e.g., passing a URL to a TRANSFER target).
|
|
7
|
+
*/
|
|
8
|
+
const TransferIntent = z.object({
|
|
9
|
+
actionType: z.literal("TRANSFER"),
|
|
10
|
+
target: z.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid EVM address"),
|
|
11
|
+
amount: z.string().regex(/^\d+(\.\d+)?$/, "Amount must be a numeric string"),
|
|
12
|
+
data: z.record(z.string(), z.any()).optional()
|
|
13
|
+
}).strict();
|
|
14
|
+
const SwapIntent = z.object({
|
|
15
|
+
actionType: z.literal("SWAP"),
|
|
16
|
+
target: z.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid EVM address"),
|
|
17
|
+
amount: z.string().regex(/^\d+(\.\d+)?$/, "Amount must be a numeric string"),
|
|
18
|
+
data: z.record(z.string(), z.any()).optional()
|
|
19
|
+
}).strict();
|
|
20
|
+
const ApiCallIntent = z.object({
|
|
21
|
+
actionType: z.literal("API_CALL"),
|
|
22
|
+
target: z.string().url("Must be a valid URL"),
|
|
23
|
+
data: z.record(z.string(), z.any()).optional()
|
|
24
|
+
}).strict();
|
|
25
|
+
const X402PaymentIntent = z.object({
|
|
26
|
+
actionType: z.literal("X402_PAYMENT"),
|
|
27
|
+
target: z.string().url("Must be a valid URL"),
|
|
28
|
+
amount: z.string().regex(/^\d+(\.\d+)?$/, "Amount must be a numeric string"),
|
|
29
|
+
}).strict();
|
|
30
|
+
const IdentityRegisterIntent = z.object({
|
|
31
|
+
actionType: z.literal("IDENTITY_REGISTER"),
|
|
32
|
+
target: z.string(), // Extensible metadata payload location
|
|
33
|
+
data: z.record(z.string(), z.any()).optional()
|
|
34
|
+
}).strict();
|
|
35
|
+
export const IntentSchema = z.discriminatedUnion("actionType", [
|
|
36
|
+
TransferIntent, SwapIntent, ApiCallIntent, X402PaymentIntent, IdentityRegisterIntent
|
|
37
|
+
]);
|
|
38
|
+
/**
|
|
39
|
+
* Transforms raw LLM/Agent tool outputs into structured Intent objects.
|
|
40
|
+
* An Intent is *not* a transaction; it is a request for the CRE DON to evaluate.
|
|
41
|
+
*/
|
|
42
|
+
export class IntentBuilder {
|
|
43
|
+
static build(rawInput) {
|
|
44
|
+
// Uses the ValidationGate to ensure a hard failure on format mismatches
|
|
45
|
+
return ValidationGate.validate(IntentSchema, rawInput);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Intent } from "../core/IntentBuilder.js";
|
|
2
|
+
import type { CREWorkflowConfig, CREEvaluateResult, SxtDataPayload } from "./creTypes.js";
|
|
3
|
+
/**
|
|
4
|
+
* Production client for Chainlink CRE workflow HTTP triggers: posts intents + SXT bounds
|
|
5
|
+
* to your DON gateway with timeouts, retries, and optional BFT signature counting.
|
|
6
|
+
*
|
|
7
|
+
* Workflow code itself is authored with `@chainlink/cre-sdk` and deployed to CRE; this class
|
|
8
|
+
* is the **off-DON** caller that your AgentOS process uses at the decision boundary.
|
|
9
|
+
*
|
|
10
|
+
* @see https://docs.chain.link/cre
|
|
11
|
+
*/
|
|
12
|
+
export declare class CREWorkflowClient {
|
|
13
|
+
private readonly cfg;
|
|
14
|
+
constructor(config: CREWorkflowConfig);
|
|
15
|
+
/** Exposes effective config for enterprise guardrails. */
|
|
16
|
+
get config(): Readonly<CREWorkflowConfig>;
|
|
17
|
+
private resolveUrl;
|
|
18
|
+
/**
|
|
19
|
+
* Submits an Intent and SXT ZK-bounded aggregates to the workflow gateway for policy / consensus.
|
|
20
|
+
*/
|
|
21
|
+
evaluateIntent(intent: Intent, sxtData: SxtDataPayload): Promise<CREEvaluateResult>;
|
|
22
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { fetchWithRetry } from "../http/fetchWithRetry.js";
|
|
2
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
3
|
+
const DEFAULT_RETRIES = 3;
|
|
4
|
+
const DEFAULT_RETRY_DELAY_MS = 500;
|
|
5
|
+
function parseEvaluateJson(body) {
|
|
6
|
+
if (body === null || typeof body !== "object") {
|
|
7
|
+
return { approved: false, error: "CRE: empty or invalid JSON body" };
|
|
8
|
+
}
|
|
9
|
+
let o = body;
|
|
10
|
+
if (o.data && typeof o.data === "object")
|
|
11
|
+
o = o.data;
|
|
12
|
+
if (o.result && typeof o.result === "object")
|
|
13
|
+
o = o.result;
|
|
14
|
+
const approved = Boolean(o.approved ?? o.success);
|
|
15
|
+
const signature = (o.signature ?? o.authSignature ?? o.donSignature);
|
|
16
|
+
const error = (o.error ?? o.message ?? o.reason);
|
|
17
|
+
let consensus;
|
|
18
|
+
const c = o.consensus ?? o.report;
|
|
19
|
+
if (c && typeof c === "object") {
|
|
20
|
+
const cs = c;
|
|
21
|
+
const sigs = cs.signatures ?? cs.oracleSignatures;
|
|
22
|
+
if (Array.isArray(sigs) && sigs.every((x) => typeof x === "string")) {
|
|
23
|
+
consensus = { signatures: sigs, reports: cs.reports };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
approved,
|
|
28
|
+
signature: typeof signature === "string" ? signature : undefined,
|
|
29
|
+
error: typeof error === "string" ? error : undefined,
|
|
30
|
+
consensus,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function evaluateMockPolicy(intent, sxtData, threshold) {
|
|
34
|
+
try {
|
|
35
|
+
if (intent.actionType === "TRANSFER" && intent.amount) {
|
|
36
|
+
const requestedAmount = BigInt(String(intent.amount).split(".")[0] || "0");
|
|
37
|
+
const historicalSpending = sxtData.total;
|
|
38
|
+
if (historicalSpending + requestedAmount > threshold) {
|
|
39
|
+
return {
|
|
40
|
+
approved: false,
|
|
41
|
+
error: `SXT SpendingLimitViolation: requested plus historical (${historicalSpending}) exceeds mock threshold (${threshold}).`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const bftSignature = "0x" + Array.from({ length: 130 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
|
|
46
|
+
return { approved: true, signature: bftSignature };
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
50
|
+
return { approved: false, error: `Workflow Execution Error: ${msg}` };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Production client for Chainlink CRE workflow HTTP triggers: posts intents + SXT bounds
|
|
55
|
+
* to your DON gateway with timeouts, retries, and optional BFT signature counting.
|
|
56
|
+
*
|
|
57
|
+
* Workflow code itself is authored with `@chainlink/cre-sdk` and deployed to CRE; this class
|
|
58
|
+
* is the **off-DON** caller that your AgentOS process uses at the decision boundary.
|
|
59
|
+
*
|
|
60
|
+
* @see https://docs.chain.link/cre
|
|
61
|
+
*/
|
|
62
|
+
export class CREWorkflowClient {
|
|
63
|
+
cfg;
|
|
64
|
+
constructor(config) {
|
|
65
|
+
this.cfg = config;
|
|
66
|
+
}
|
|
67
|
+
/** Exposes effective config for enterprise guardrails. */
|
|
68
|
+
get config() {
|
|
69
|
+
return this.cfg;
|
|
70
|
+
}
|
|
71
|
+
resolveUrl() {
|
|
72
|
+
const base = this.cfg.endpointUrl.replace(/\/$/, "");
|
|
73
|
+
if (this.cfg.useWorkflowPath === false)
|
|
74
|
+
return base;
|
|
75
|
+
return `${base}/workflows/${encodeURIComponent(this.cfg.workflowId)}/evaluate`;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Submits an Intent and SXT ZK-bounded aggregates to the workflow gateway for policy / consensus.
|
|
79
|
+
*/
|
|
80
|
+
async evaluateIntent(intent, sxtData) {
|
|
81
|
+
if (this.cfg.mockMode) {
|
|
82
|
+
const threshold = this.cfg.mockHistoricalThreshold ?? 1000000n;
|
|
83
|
+
return evaluateMockPolicy(intent, sxtData, threshold);
|
|
84
|
+
}
|
|
85
|
+
const timeoutMs = this.cfg.requestTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
86
|
+
const maxRetries = this.cfg.maxRetries ?? DEFAULT_RETRIES;
|
|
87
|
+
const baseDelayMs = this.cfg.retryBaseDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
|
88
|
+
const minSigs = this.cfg.minConsensusSignatures ?? 1;
|
|
89
|
+
const payload = {
|
|
90
|
+
workflowId: this.cfg.workflowId,
|
|
91
|
+
intent,
|
|
92
|
+
sxtData: {
|
|
93
|
+
total: sxtData.total.toString(),
|
|
94
|
+
proof: sxtData.proof,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const t = setTimeout(() => controller.abort(), timeoutMs);
|
|
99
|
+
try {
|
|
100
|
+
const headers = {
|
|
101
|
+
accept: "application/json",
|
|
102
|
+
"content-type": "application/json",
|
|
103
|
+
...this.cfg.headers,
|
|
104
|
+
};
|
|
105
|
+
const res = await fetchWithRetry(this.resolveUrl(), {
|
|
106
|
+
method: "POST",
|
|
107
|
+
signal: controller.signal,
|
|
108
|
+
headers,
|
|
109
|
+
body: JSON.stringify(payload),
|
|
110
|
+
}, {
|
|
111
|
+
maxRetries,
|
|
112
|
+
baseDelayMs,
|
|
113
|
+
signal: controller.signal,
|
|
114
|
+
retryOnRateLimit: true,
|
|
115
|
+
});
|
|
116
|
+
const text = await res.text();
|
|
117
|
+
let json;
|
|
118
|
+
try {
|
|
119
|
+
json = text ? JSON.parse(text) : {};
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return {
|
|
123
|
+
approved: false,
|
|
124
|
+
error: `CRE: non-JSON response (${res.status}): ${text.slice(0, 240)}`,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
if (!res.ok) {
|
|
128
|
+
const parsed = parseEvaluateJson(json);
|
|
129
|
+
return {
|
|
130
|
+
approved: false,
|
|
131
|
+
error: parsed.error ?? `CRE HTTP ${res.status}`,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const out = parseEvaluateJson(json);
|
|
135
|
+
if (out.consensus?.signatures && out.consensus.signatures.length < minSigs) {
|
|
136
|
+
return {
|
|
137
|
+
approved: false,
|
|
138
|
+
error: `CRE BFT: insufficient oracle signatures (${out.consensus.signatures.length} < ${minSigs})`,
|
|
139
|
+
consensus: out.consensus,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
clearTimeout(t);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Intent } from "../core/IntentBuilder.js";
|
|
2
|
+
/**
|
|
3
|
+
* Client-side configuration for invoking a deployed Chainlink CRE workflow
|
|
4
|
+
* (typically via HTTP trigger). The response shape is defined by your workflow’s
|
|
5
|
+
* published contract with the DON; defaults below match a common JSON envelope.
|
|
6
|
+
*
|
|
7
|
+
* @see https://docs.chain.link/cre
|
|
8
|
+
*/
|
|
9
|
+
export interface CREWorkflowConfig {
|
|
10
|
+
/**
|
|
11
|
+
* Base URL for the workflow HTTP trigger (no trailing slash).
|
|
12
|
+
* Often provided by CRE CLI / dashboard after deployment.
|
|
13
|
+
*/
|
|
14
|
+
endpointUrl: string;
|
|
15
|
+
/** Workflow identifier (path segment or query, depending on gateway). */
|
|
16
|
+
workflowId: string;
|
|
17
|
+
/** If true, path is `${endpointUrl}/workflows/${workflowId}/evaluate` — set false to post only to `endpointUrl`. */
|
|
18
|
+
useWorkflowPath?: boolean;
|
|
19
|
+
/** Extra headers (e.g. `x-api-key`, `Authorization`). */
|
|
20
|
+
headers?: Record<string, string>;
|
|
21
|
+
requestTimeoutMs?: number;
|
|
22
|
+
maxRetries?: number;
|
|
23
|
+
retryBaseDelayMs?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Minimum number of distinct oracle signatures / reports required in the response
|
|
26
|
+
* for BFT-style acceptance. If the payload has no `consensus.signatures`, this check is skipped.
|
|
27
|
+
*/
|
|
28
|
+
minConsensusSignatures?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Local dev only: bypass HTTP and use in-process policy (never enable in production).
|
|
31
|
+
*/
|
|
32
|
+
mockMode?: boolean;
|
|
33
|
+
/** Mock policy threshold for TRANSFER amount + historical SXT total (wei-like units), mockMode only. */
|
|
34
|
+
mockHistoricalThreshold?: bigint;
|
|
35
|
+
}
|
|
36
|
+
export interface SxtDataPayload {
|
|
37
|
+
total: bigint;
|
|
38
|
+
proof: string;
|
|
39
|
+
}
|
|
40
|
+
export interface CREEvaluateResult {
|
|
41
|
+
approved: boolean;
|
|
42
|
+
signature?: string;
|
|
43
|
+
error?: string;
|
|
44
|
+
/** Raw consensus payload when the gateway returns structured oracle metadata. */
|
|
45
|
+
consensus?: {
|
|
46
|
+
signatures: string[];
|
|
47
|
+
reports?: unknown[];
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** JSON body sent to the CRE HTTP trigger (`total` as decimal string for interoperability). */
|
|
51
|
+
export type CREEvaluateRequestBody = {
|
|
52
|
+
workflowId: string;
|
|
53
|
+
intent: Intent;
|
|
54
|
+
sxtData: {
|
|
55
|
+
total: string;
|
|
56
|
+
proof: string;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface FetchWithRetryOptions {
|
|
2
|
+
readonly maxRetries: number;
|
|
3
|
+
readonly baseDelayMs: number;
|
|
4
|
+
readonly signal: AbortSignal;
|
|
5
|
+
/** Retry on 429 and 5xx (not on 4xx validation errors). */
|
|
6
|
+
readonly retryOnRateLimit: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Bounded retries with exponential backoff and jitter for oracle / indexer drift.
|
|
10
|
+
*/
|
|
11
|
+
export declare function fetchWithRetry(input: RequestInfo | URL, init: RequestInit, opts: FetchWithRetryOptions): Promise<Response>;
|
|
12
|
+
export declare function mergeSignals(a: AbortSignal, b: AbortSignal): AbortSignal;
|