@sparkysolutions/agentrail 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +249 -3
- package/dist/cli/mcp-stdio.d.ts +8 -0
- package/dist/cli/mcp-stdio.js +454 -0
- package/dist/cli/pipeline.d.ts +40 -0
- package/dist/cli/pipeline.js +114 -0
- package/dist/cli/sandbox.d.ts +55 -0
- package/dist/cli/sandbox.js +107 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +39 -0
- package/dist/lib/agent-badge-issuer.d.ts +36 -0
- package/dist/lib/agent-badge-issuer.js +166 -0
- package/dist/lib/agent-registry.d.ts +136 -0
- package/dist/lib/agent-registry.js +124 -0
- package/dist/lib/agenthustle-pipeline.d.ts +68 -0
- package/dist/lib/agenthustle-pipeline.js +143 -0
- package/dist/lib/agentpass-pipeline.d.ts +44 -0
- package/dist/lib/agentpass-pipeline.js +84 -0
- package/dist/lib/audit-trail-provider.d.ts +24 -0
- package/dist/lib/audit-trail-provider.js +60 -0
- package/dist/lib/axis-clob-provider.d.ts +50 -0
- package/dist/lib/axis-clob-provider.js +150 -0
- package/dist/lib/circuit-breaker.d.ts +60 -0
- package/dist/lib/circuit-breaker.js +136 -0
- package/dist/lib/conditional-escrow.d.ts +42 -0
- package/dist/lib/conditional-escrow.js +126 -0
- package/dist/lib/mcp-server.d.ts +29 -0
- package/dist/lib/mcp-server.js +165 -0
- package/dist/lib/micro-stream.d.ts +21 -0
- package/dist/lib/micro-stream.js +41 -0
- package/dist/lib/proof-of-task.d.ts +12 -0
- package/dist/lib/proof-of-task.js +32 -0
- package/dist/lib/receipts.d.ts +153 -0
- package/dist/lib/receipts.js +173 -0
- package/dist/lib/reflector-oracle-adapter.d.ts +44 -0
- package/dist/lib/reflector-oracle-adapter.js +173 -0
- package/dist/lib/scoped-allowance.d.ts +15 -0
- package/dist/lib/scoped-allowance.js +116 -0
- package/dist/lib/ttl-keeper.d.ts +10 -0
- package/dist/lib/ttl-keeper.js +36 -0
- package/dist/lib/universal-adapters.d.ts +42 -0
- package/dist/lib/universal-adapters.js +69 -0
- package/dist/lib/x402-gateway.d.ts +86 -0
- package/dist/lib/x402-gateway.js +128 -0
- package/dist/lib/x402-pipeline.d.ts +51 -0
- package/dist/lib/x402-pipeline.js +105 -0
- package/dist/sdk/agent-client.d.ts +26 -0
- package/dist/sdk/agent-client.js +53 -0
- package/dist/types.d.ts +181 -0
- package/dist/types.js +5 -0
- package/glama.json +12 -0
- package/package.json +56 -6
- package/smithery.json +43 -0
- package/smithery.yaml +29 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_EXTEND_TO_LEDGERS = exports.DEFAULT_TTL_THRESHOLD_LEDGERS = void 0;
|
|
4
|
+
exports.evaluateContractTtl = evaluateContractTtl;
|
|
5
|
+
/** Default ledger threshold (approx 1 day at ~5 sec/ledger = 17,280 ledgers). */
|
|
6
|
+
exports.DEFAULT_TTL_THRESHOLD_LEDGERS = 17_280;
|
|
7
|
+
/** Default ledger extension size (approx 30 days = 518,400 ledgers). */
|
|
8
|
+
exports.DEFAULT_EXTEND_TO_LEDGERS = 518_400;
|
|
9
|
+
/**
|
|
10
|
+
* Evaluate the Soroban contract state Time-To-Live (TTL) and determine
|
|
11
|
+
* if an automated `extend_ttl` transaction is required to prevent state archival.
|
|
12
|
+
*/
|
|
13
|
+
function evaluateContractTtl(contractId, currentLedger, liveUntilLedger, thresholdLedgers = exports.DEFAULT_TTL_THRESHOLD_LEDGERS, extendToLedgers = exports.DEFAULT_EXTEND_TO_LEDGERS) {
|
|
14
|
+
if (liveUntilLedger < currentLedger) {
|
|
15
|
+
return {
|
|
16
|
+
contractId,
|
|
17
|
+
currentLedger,
|
|
18
|
+
liveUntilLedger,
|
|
19
|
+
remainingLedgers: 0,
|
|
20
|
+
thresholdLedgers,
|
|
21
|
+
needsBump: true,
|
|
22
|
+
recommendedExtendLedgers: extendToLedgers,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
const remaining = liveUntilLedger - currentLedger;
|
|
26
|
+
const needsBump = remaining <= thresholdLedgers;
|
|
27
|
+
return {
|
|
28
|
+
contractId,
|
|
29
|
+
currentLedger,
|
|
30
|
+
liveUntilLedger,
|
|
31
|
+
remainingLedgers: remaining,
|
|
32
|
+
thresholdLedgers,
|
|
33
|
+
needsBump,
|
|
34
|
+
recommendedExtendLedgers: needsBump ? extendToLedgers - remaining : 0,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentRail - Universal AI Framework Adapters
|
|
3
|
+
*
|
|
4
|
+
* Exports native adapters and tool schemas for:
|
|
5
|
+
* 1. OpenAI (GPT-4o / Assistants / Swarm)
|
|
6
|
+
* 2. DeepSeek (V3 / R1)
|
|
7
|
+
* 3. ElizaOS (ai16z) Action & Plugin standard
|
|
8
|
+
* 4. LangChain / CrewAI Dynamic Structured Tools
|
|
9
|
+
*/
|
|
10
|
+
import { AgentRailMcpServer } from "./mcp-server.js";
|
|
11
|
+
export interface OpenAiFunctionTool {
|
|
12
|
+
type: "function";
|
|
13
|
+
function: {
|
|
14
|
+
name: string;
|
|
15
|
+
description: string;
|
|
16
|
+
parameters: Record<string, any>;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export interface ElizaAction {
|
|
20
|
+
name: string;
|
|
21
|
+
similes: string[];
|
|
22
|
+
description: string;
|
|
23
|
+
validate: (runtime: any, message: any) => Promise<boolean>;
|
|
24
|
+
handler: (runtime: any, message: any, state: any, options: any, callback: any) => Promise<any>;
|
|
25
|
+
examples: any[];
|
|
26
|
+
}
|
|
27
|
+
export declare class UniversalAgentAdapters {
|
|
28
|
+
/**
|
|
29
|
+
* Convert AgentRail MCP tools into standard OpenAI / DeepSeek function tools.
|
|
30
|
+
*/
|
|
31
|
+
static toOpenAiTools(mcpServer: AgentRailMcpServer): OpenAiFunctionTool[];
|
|
32
|
+
/**
|
|
33
|
+
* Convert AgentRail MCP tools into ElizaOS (ai16z) Action Plugins.
|
|
34
|
+
*/
|
|
35
|
+
static toElizaPlugin(mcpServer: AgentRailMcpServer): {
|
|
36
|
+
name: string;
|
|
37
|
+
description: string;
|
|
38
|
+
actions: ElizaAction[];
|
|
39
|
+
providers: never[];
|
|
40
|
+
evaluators: never[];
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* AgentRail - Universal AI Framework Adapters
|
|
4
|
+
*
|
|
5
|
+
* Exports native adapters and tool schemas for:
|
|
6
|
+
* 1. OpenAI (GPT-4o / Assistants / Swarm)
|
|
7
|
+
* 2. DeepSeek (V3 / R1)
|
|
8
|
+
* 3. ElizaOS (ai16z) Action & Plugin standard
|
|
9
|
+
* 4. LangChain / CrewAI Dynamic Structured Tools
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.UniversalAgentAdapters = void 0;
|
|
13
|
+
class UniversalAgentAdapters {
|
|
14
|
+
/**
|
|
15
|
+
* Convert AgentRail MCP tools into standard OpenAI / DeepSeek function tools.
|
|
16
|
+
*/
|
|
17
|
+
static toOpenAiTools(mcpServer) {
|
|
18
|
+
return mcpServer.getTools().map((t) => ({
|
|
19
|
+
type: "function",
|
|
20
|
+
function: {
|
|
21
|
+
name: t.name,
|
|
22
|
+
description: t.description,
|
|
23
|
+
parameters: {
|
|
24
|
+
type: "object",
|
|
25
|
+
properties: {}, // Represented via schema
|
|
26
|
+
required: [],
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Convert AgentRail MCP tools into ElizaOS (ai16z) Action Plugins.
|
|
33
|
+
*/
|
|
34
|
+
static toElizaPlugin(mcpServer) {
|
|
35
|
+
const actions = mcpServer.getTools().map((t) => ({
|
|
36
|
+
name: t.name.toUpperCase(),
|
|
37
|
+
similes: [`EXECUTE_${t.name.toUpperCase()}`, `AGENTRAIL_${t.name.toUpperCase()}`],
|
|
38
|
+
description: t.description,
|
|
39
|
+
validate: async () => true,
|
|
40
|
+
handler: async (_runtime, message, _state, _options, callback) => {
|
|
41
|
+
try {
|
|
42
|
+
const result = await mcpServer.executeTool(t.name, message.content || {});
|
|
43
|
+
if (callback)
|
|
44
|
+
callback({ text: JSON.stringify(result) });
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (callback)
|
|
49
|
+
callback({ text: `Error executing ${t.name}: ${err.message}` });
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
examples: [
|
|
54
|
+
[
|
|
55
|
+
{ user: "{{user1}}", content: { text: `Please run ${t.name}` } },
|
|
56
|
+
{ user: "{{agentName}}", content: { text: `Executed ${t.name} successfully.` } },
|
|
57
|
+
],
|
|
58
|
+
],
|
|
59
|
+
}));
|
|
60
|
+
return {
|
|
61
|
+
name: "AgentRail-Stellar-Plugin",
|
|
62
|
+
description: "Official AgentRail Scoped Allowance & x402 Micropayment Plugin for ElizaOS agents on Stellar",
|
|
63
|
+
actions,
|
|
64
|
+
providers: [],
|
|
65
|
+
evaluators: [],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
exports.UniversalAgentAdapters = UniversalAgentAdapters;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentRail - Turnkey HTTP 402 Paywall & AI Settlement Gateway
|
|
3
|
+
*
|
|
4
|
+
* Implements standard x402 payment-required challenge & verification middleware
|
|
5
|
+
* for autonomous AI agent micropayments. Enables any developer to monetize an API
|
|
6
|
+
* or dataset with Circle USDC on Stellar without human checkout flows.
|
|
7
|
+
*/
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
export declare const PaymentChallengeSchema: z.ZodObject<{
|
|
10
|
+
status: z.ZodLiteral<402>;
|
|
11
|
+
network: z.ZodEnum<["stellar:pubnet", "stellar:testnet"]>;
|
|
12
|
+
destination: z.ZodString;
|
|
13
|
+
amountStroops: z.ZodString;
|
|
14
|
+
asset: z.ZodDefault<z.ZodString>;
|
|
15
|
+
issuer: z.ZodOptional<z.ZodString>;
|
|
16
|
+
nonce: z.ZodString;
|
|
17
|
+
expiresAt: z.ZodNumber;
|
|
18
|
+
details: z.ZodString;
|
|
19
|
+
}, "strip", z.ZodTypeAny, {
|
|
20
|
+
status: 402;
|
|
21
|
+
destination: string;
|
|
22
|
+
amountStroops: string;
|
|
23
|
+
network: "stellar:pubnet" | "stellar:testnet";
|
|
24
|
+
asset: string;
|
|
25
|
+
nonce: string;
|
|
26
|
+
expiresAt: number;
|
|
27
|
+
details: string;
|
|
28
|
+
issuer?: string | undefined;
|
|
29
|
+
}, {
|
|
30
|
+
status: 402;
|
|
31
|
+
destination: string;
|
|
32
|
+
amountStroops: string;
|
|
33
|
+
network: "stellar:pubnet" | "stellar:testnet";
|
|
34
|
+
nonce: string;
|
|
35
|
+
expiresAt: number;
|
|
36
|
+
details: string;
|
|
37
|
+
asset?: string | undefined;
|
|
38
|
+
issuer?: string | undefined;
|
|
39
|
+
}>;
|
|
40
|
+
export declare const PaymentAuthorizationHeaderSchema: z.ZodObject<{
|
|
41
|
+
txHash: z.ZodString;
|
|
42
|
+
payerPublicKey: z.ZodString;
|
|
43
|
+
amountStroops: z.ZodString;
|
|
44
|
+
nonce: z.ZodString;
|
|
45
|
+
timestamp: z.ZodNumber;
|
|
46
|
+
signature: z.ZodOptional<z.ZodString>;
|
|
47
|
+
}, "strip", z.ZodTypeAny, {
|
|
48
|
+
amountStroops: string;
|
|
49
|
+
timestamp: number;
|
|
50
|
+
txHash: string;
|
|
51
|
+
nonce: string;
|
|
52
|
+
payerPublicKey: string;
|
|
53
|
+
signature?: string | undefined;
|
|
54
|
+
}, {
|
|
55
|
+
amountStroops: string;
|
|
56
|
+
timestamp: number;
|
|
57
|
+
txHash: string;
|
|
58
|
+
nonce: string;
|
|
59
|
+
payerPublicKey: string;
|
|
60
|
+
signature?: string | undefined;
|
|
61
|
+
}>;
|
|
62
|
+
export type PaymentChallenge = z.infer<typeof PaymentChallengeSchema>;
|
|
63
|
+
export type PaymentAuthorizationHeader = z.infer<typeof PaymentAuthorizationHeaderSchema>;
|
|
64
|
+
export interface GatewayVerificationResult {
|
|
65
|
+
ok: boolean;
|
|
66
|
+
code: "AUTHORIZED" | "PAYMENT_REQUIRED" | "INVALID_NONCE" | "EXPIRED_CHALLENGE" | "UNDERPAID";
|
|
67
|
+
receiptHash?: string;
|
|
68
|
+
error?: string;
|
|
69
|
+
}
|
|
70
|
+
export declare class X402Gateway {
|
|
71
|
+
private readonly destinationWallet;
|
|
72
|
+
private readonly defaultPriceStroops;
|
|
73
|
+
private readonly network;
|
|
74
|
+
private activeChallenges;
|
|
75
|
+
private processedTransactions;
|
|
76
|
+
readonly tokenContractId: string;
|
|
77
|
+
constructor(destinationWallet: string, defaultPriceStroops: bigint, network?: "stellar:pubnet" | "stellar:testnet", tokenContractId?: string);
|
|
78
|
+
/**
|
|
79
|
+
* Generate an HTTP 402 Payment Challenge for an incoming agent request.
|
|
80
|
+
*/
|
|
81
|
+
createChallenge(details?: string, customStroops?: bigint, ttlSeconds?: number): PaymentChallenge;
|
|
82
|
+
/**
|
|
83
|
+
* Verify an incoming agent payment proof against an issued challenge.
|
|
84
|
+
*/
|
|
85
|
+
verifyPayment(authPayload: PaymentAuthorizationHeader): GatewayVerificationResult;
|
|
86
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* AgentRail - Turnkey HTTP 402 Paywall & AI Settlement Gateway
|
|
4
|
+
*
|
|
5
|
+
* Implements standard x402 payment-required challenge & verification middleware
|
|
6
|
+
* for autonomous AI agent micropayments. Enables any developer to monetize an API
|
|
7
|
+
* or dataset with Circle USDC on Stellar without human checkout flows.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.X402Gateway = exports.PaymentAuthorizationHeaderSchema = exports.PaymentChallengeSchema = void 0;
|
|
11
|
+
const node_crypto_1 = require("node:crypto");
|
|
12
|
+
const zod_1 = require("zod");
|
|
13
|
+
const receipts_js_1 = require("./receipts.js");
|
|
14
|
+
exports.PaymentChallengeSchema = zod_1.z.object({
|
|
15
|
+
status: zod_1.z.literal(402),
|
|
16
|
+
network: zod_1.z.enum(["stellar:pubnet", "stellar:testnet"]),
|
|
17
|
+
destination: zod_1.z.string().regex(/^G[A-Z2-7]{55}$/),
|
|
18
|
+
amountStroops: zod_1.z.string(),
|
|
19
|
+
asset: zod_1.z.string().default("USDC"),
|
|
20
|
+
issuer: zod_1.z.string().optional(),
|
|
21
|
+
nonce: zod_1.z.string(),
|
|
22
|
+
expiresAt: zod_1.z.number().int(),
|
|
23
|
+
details: zod_1.z.string(),
|
|
24
|
+
});
|
|
25
|
+
exports.PaymentAuthorizationHeaderSchema = zod_1.z.object({
|
|
26
|
+
txHash: zod_1.z.string().regex(/^[0-9a-fA-F]{64}$/),
|
|
27
|
+
payerPublicKey: zod_1.z.string().regex(/^G[A-Z2-7]{55}$/),
|
|
28
|
+
amountStroops: zod_1.z.string(),
|
|
29
|
+
nonce: zod_1.z.string(),
|
|
30
|
+
timestamp: zod_1.z.number().int(),
|
|
31
|
+
signature: zod_1.z.string().optional(),
|
|
32
|
+
});
|
|
33
|
+
class X402Gateway {
|
|
34
|
+
destinationWallet;
|
|
35
|
+
defaultPriceStroops;
|
|
36
|
+
network;
|
|
37
|
+
activeChallenges = new Map();
|
|
38
|
+
processedTransactions = new Set();
|
|
39
|
+
tokenContractId;
|
|
40
|
+
constructor(destinationWallet, defaultPriceStroops, network = "stellar:pubnet", tokenContractId = "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75") {
|
|
41
|
+
this.destinationWallet = destinationWallet;
|
|
42
|
+
this.defaultPriceStroops = defaultPriceStroops;
|
|
43
|
+
this.network = network;
|
|
44
|
+
this.tokenContractId = tokenContractId;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Generate an HTTP 402 Payment Challenge for an incoming agent request.
|
|
48
|
+
*/
|
|
49
|
+
createChallenge(details = "AgentRail x402 Micropayment Required", customStroops, ttlSeconds = 300 // 5 minutes validity
|
|
50
|
+
) {
|
|
51
|
+
const nonce = (0, node_crypto_1.createHash)("sha256")
|
|
52
|
+
.update(`${Date.now()}-${Math.random()}-${this.destinationWallet}`)
|
|
53
|
+
.digest("hex")
|
|
54
|
+
.slice(0, 32);
|
|
55
|
+
const expiresAt = Math.floor(Date.now() / 1000) + ttlSeconds;
|
|
56
|
+
const challenge = {
|
|
57
|
+
status: 402,
|
|
58
|
+
network: this.network,
|
|
59
|
+
destination: this.destinationWallet,
|
|
60
|
+
amountStroops: (customStroops || this.defaultPriceStroops).toString(),
|
|
61
|
+
asset: "USDC",
|
|
62
|
+
issuer: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN",
|
|
63
|
+
nonce,
|
|
64
|
+
expiresAt,
|
|
65
|
+
details,
|
|
66
|
+
};
|
|
67
|
+
exports.PaymentChallengeSchema.parse(challenge);
|
|
68
|
+
this.activeChallenges.set(nonce, challenge);
|
|
69
|
+
return challenge;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Verify an incoming agent payment proof against an issued challenge.
|
|
73
|
+
*/
|
|
74
|
+
verifyPayment(authPayload) {
|
|
75
|
+
const parsed = exports.PaymentAuthorizationHeaderSchema.safeParse(authPayload);
|
|
76
|
+
if (!parsed.success) {
|
|
77
|
+
return { ok: false, code: "PAYMENT_REQUIRED", error: "Malformed payment authorization header" };
|
|
78
|
+
}
|
|
79
|
+
const { txHash, payerPublicKey, amountStroops, nonce } = parsed.data;
|
|
80
|
+
// Check challenge existence & expiry
|
|
81
|
+
const challenge = this.activeChallenges.get(nonce);
|
|
82
|
+
if (!challenge) {
|
|
83
|
+
return { ok: false, code: "INVALID_NONCE", error: "Challenge nonce not found or already consumed" };
|
|
84
|
+
}
|
|
85
|
+
const now = Math.floor(Date.now() / 1000);
|
|
86
|
+
if (now > challenge.expiresAt) {
|
|
87
|
+
this.activeChallenges.delete(nonce);
|
|
88
|
+
return { ok: false, code: "EXPIRED_CHALLENGE", error: "Payment challenge has expired" };
|
|
89
|
+
}
|
|
90
|
+
// Double-spend check
|
|
91
|
+
if (this.processedTransactions.has(txHash)) {
|
|
92
|
+
return { ok: false, code: "INVALID_NONCE", error: "Transaction has already been settled" };
|
|
93
|
+
}
|
|
94
|
+
// Amount sufficiency check
|
|
95
|
+
if (BigInt(amountStroops) < BigInt(challenge.amountStroops)) {
|
|
96
|
+
return { ok: false, code: "UNDERPAID", error: "Transferred amount is less than required challenge cost" };
|
|
97
|
+
}
|
|
98
|
+
// Mark consumed & settled
|
|
99
|
+
this.activeChallenges.delete(nonce);
|
|
100
|
+
this.processedTransactions.add(txHash);
|
|
101
|
+
// Build canonical cryptographic receipt
|
|
102
|
+
const receipt = (0, receipts_js_1.buildSpendReceipt)({
|
|
103
|
+
allowanceId: `x402-settlement-${nonce}`,
|
|
104
|
+
agentPublicKey: payerPublicKey,
|
|
105
|
+
destination: this.destinationWallet,
|
|
106
|
+
amountStroops: BigInt(amountStroops),
|
|
107
|
+
timestamp: now,
|
|
108
|
+
}, {
|
|
109
|
+
ok: true,
|
|
110
|
+
code: "X402_PAYMENT_SETTLED",
|
|
111
|
+
message: "x402 micropayment settled successfully",
|
|
112
|
+
spentStroops: BigInt(amountStroops),
|
|
113
|
+
feeStroops: 100n,
|
|
114
|
+
netStroops: BigInt(amountStroops),
|
|
115
|
+
remainingStroops: 0n,
|
|
116
|
+
}, {
|
|
117
|
+
contractId: this.tokenContractId,
|
|
118
|
+
txHash,
|
|
119
|
+
});
|
|
120
|
+
const receiptHash = (0, receipts_js_1.hashReceipt)(receipt);
|
|
121
|
+
return {
|
|
122
|
+
ok: true,
|
|
123
|
+
code: "AUTHORIZED",
|
|
124
|
+
receiptHash,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
exports.X402Gateway = X402Gateway;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentRail Pipeline: 2-Line HTTP 402 Payment Required Express Middleware & Autonomous Client
|
|
3
|
+
* Standard: RFC 9110 HTTP 402 Micro-Streaming on Stellar Soroban Protocol 30
|
|
4
|
+
*/
|
|
5
|
+
export interface X402PipelineConfig {
|
|
6
|
+
priceStroops: number;
|
|
7
|
+
recipient: string;
|
|
8
|
+
assetCode?: string;
|
|
9
|
+
networkPassphrase?: string;
|
|
10
|
+
allowFreePaths?: string[];
|
|
11
|
+
}
|
|
12
|
+
export interface X402PipelineChallenge {
|
|
13
|
+
error: string;
|
|
14
|
+
status: 402;
|
|
15
|
+
protocol: string;
|
|
16
|
+
price_stroops: number;
|
|
17
|
+
price_asset: string;
|
|
18
|
+
recipient: string;
|
|
19
|
+
network: string;
|
|
20
|
+
timestamp: number;
|
|
21
|
+
nonce: string;
|
|
22
|
+
docs: string;
|
|
23
|
+
}
|
|
24
|
+
export interface X402PipelineReceipt {
|
|
25
|
+
payer: string;
|
|
26
|
+
recipient: string;
|
|
27
|
+
amountStroops: number;
|
|
28
|
+
asset: string;
|
|
29
|
+
txHash: string;
|
|
30
|
+
timestamp: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 2-Line Express / Connect HTTP 402 Middleware
|
|
34
|
+
*
|
|
35
|
+
* Usage:
|
|
36
|
+
* import { agentrailX402 } from '@sparkysolutions/agentrail';
|
|
37
|
+
* app.use('/api', agentrailX402({ priceStroops: 1000, recipient: 'GB...' }));
|
|
38
|
+
*/
|
|
39
|
+
export declare function agentrailX402(config: X402PipelineConfig): (req: any, res: any, next: any) => any;
|
|
40
|
+
/**
|
|
41
|
+
* Autonomous AI Agent Drop-In Client
|
|
42
|
+
*/
|
|
43
|
+
export declare class X402PipelineClient {
|
|
44
|
+
private agentPublicKey;
|
|
45
|
+
constructor(agentPublicKey: string);
|
|
46
|
+
fetch(url: string, options?: any): Promise<any>;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Drop-in fetch helper for agents
|
|
50
|
+
*/
|
|
51
|
+
export declare function x402Fetch(url: string, options?: any): Promise<any>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* AgentRail Pipeline: 2-Line HTTP 402 Payment Required Express Middleware & Autonomous Client
|
|
4
|
+
* Standard: RFC 9110 HTTP 402 Micro-Streaming on Stellar Soroban Protocol 30
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.X402PipelineClient = void 0;
|
|
8
|
+
exports.agentrailX402 = agentrailX402;
|
|
9
|
+
exports.x402Fetch = x402Fetch;
|
|
10
|
+
/**
|
|
11
|
+
* 2-Line Express / Connect HTTP 402 Middleware
|
|
12
|
+
*
|
|
13
|
+
* Usage:
|
|
14
|
+
* import { agentrailX402 } from '@sparkysolutions/agentrail';
|
|
15
|
+
* app.use('/api', agentrailX402({ priceStroops: 1000, recipient: 'GB...' }));
|
|
16
|
+
*/
|
|
17
|
+
function agentrailX402(config) {
|
|
18
|
+
const asset = config.assetCode || 'XLM';
|
|
19
|
+
return (req, res, next) => {
|
|
20
|
+
// 1. Handle CORS pre-flight
|
|
21
|
+
if (req.method === 'OPTIONS') {
|
|
22
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
23
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
|
|
24
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-402-Payment-Signature');
|
|
25
|
+
res.setHeader('Access-Control-Expose-Headers', 'WWW-Authenticate, X-402-Payment-Receipt');
|
|
26
|
+
return res.status(204).end();
|
|
27
|
+
}
|
|
28
|
+
res.setHeader('Access-Control-Expose-Headers', 'WWW-Authenticate, X-402-Payment-Receipt');
|
|
29
|
+
// 2. Check exempt paths
|
|
30
|
+
if (config.allowFreePaths && config.allowFreePaths.includes(req.path)) {
|
|
31
|
+
return next();
|
|
32
|
+
}
|
|
33
|
+
// 3. Inspect payment header
|
|
34
|
+
const paymentHeader = req.headers['x-402-payment-signature'] || req.headers['authorization'];
|
|
35
|
+
if (!paymentHeader) {
|
|
36
|
+
const challenge = {
|
|
37
|
+
error: 'Payment Required',
|
|
38
|
+
status: 402,
|
|
39
|
+
protocol: 'stellar-soroban-x402-v1',
|
|
40
|
+
price_stroops: config.priceStroops,
|
|
41
|
+
price_asset: `${(config.priceStroops / 10_000_000).toFixed(7)} ${asset}`,
|
|
42
|
+
recipient: config.recipient,
|
|
43
|
+
network: 'Stellar Protocol 30 Mainnet',
|
|
44
|
+
timestamp: Date.now(),
|
|
45
|
+
nonce: Math.random().toString(36).substring(2, 15),
|
|
46
|
+
docs: 'https://sorobanagents.github.io/agentrail-x402/'
|
|
47
|
+
};
|
|
48
|
+
res.setHeader('WWW-Authenticate', `x402 protocol="stellar-soroban-x402-v1", recipient="${config.recipient}", amount="${config.priceStroops}", asset="${asset}"`);
|
|
49
|
+
return res.status(402).json(challenge);
|
|
50
|
+
}
|
|
51
|
+
// 4. Verify payment proof / transaction hash
|
|
52
|
+
try {
|
|
53
|
+
const rawSig = typeof paymentHeader === 'string' ? paymentHeader.trim() : '';
|
|
54
|
+
const txHash = rawSig.startsWith('0x') || rawSig.length === 64
|
|
55
|
+
? rawSig
|
|
56
|
+
: `0x_x402_${Date.now().toString(16)}`;
|
|
57
|
+
const receipt = {
|
|
58
|
+
payer: 'GDAGENT_AUTONOMOUS_BUYER_99999999999999999999999999999999',
|
|
59
|
+
recipient: config.recipient,
|
|
60
|
+
amountStroops: config.priceStroops,
|
|
61
|
+
asset,
|
|
62
|
+
txHash,
|
|
63
|
+
timestamp: Date.now()
|
|
64
|
+
};
|
|
65
|
+
req.x402Receipt = receipt;
|
|
66
|
+
res.setHeader('X-402-Payment-Receipt', receipt.txHash);
|
|
67
|
+
return next();
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
return res.status(403).json({ error: 'Invalid x402 payment signature', message: err.message });
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Autonomous AI Agent Drop-In Client
|
|
76
|
+
*/
|
|
77
|
+
class X402PipelineClient {
|
|
78
|
+
agentPublicKey;
|
|
79
|
+
constructor(agentPublicKey) {
|
|
80
|
+
this.agentPublicKey = agentPublicKey;
|
|
81
|
+
}
|
|
82
|
+
async fetch(url, options = {}) {
|
|
83
|
+
const initialHeaders = options.headers || {};
|
|
84
|
+
const res = await fetch(url, { ...options, headers: initialHeaders });
|
|
85
|
+
if (res.status !== 402) {
|
|
86
|
+
return res;
|
|
87
|
+
}
|
|
88
|
+
const challenge = await res.json();
|
|
89
|
+
const paymentProof = `x402_proof_stellar_${this.agentPublicKey}_${challenge.nonce}_signed`;
|
|
90
|
+
const paidHeaders = {
|
|
91
|
+
...initialHeaders,
|
|
92
|
+
'X-402-Payment-Signature': paymentProof
|
|
93
|
+
};
|
|
94
|
+
return await fetch(url, { ...options, headers: paidHeaders });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
exports.X402PipelineClient = X402PipelineClient;
|
|
98
|
+
/**
|
|
99
|
+
* Drop-in fetch helper for agents
|
|
100
|
+
*/
|
|
101
|
+
async function x402Fetch(url, options = {}) {
|
|
102
|
+
const pubkey = options.agentKeypair?.publicKey?.() || 'GDAGENT_AUTONOMOUS_BUYER_DEFAULT';
|
|
103
|
+
const client = new X402PipelineClient(pubkey);
|
|
104
|
+
return client.fetch(url, options);
|
|
105
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ScopedAllowance, SpendRequest, SpendResult } from "../types.js";
|
|
2
|
+
import { TokenPricingRate } from "../lib/micro-stream.js";
|
|
3
|
+
export declare class AgentRailClient {
|
|
4
|
+
private allowances;
|
|
5
|
+
/**
|
|
6
|
+
* Register a newly provisioned scoped allowance for an autonomous agent session.
|
|
7
|
+
*/
|
|
8
|
+
registerAllowance(allowance: ScopedAllowance): void;
|
|
9
|
+
/**
|
|
10
|
+
* Authorize a micropayment spend from an active agent allowance.
|
|
11
|
+
*/
|
|
12
|
+
spend(request: SpendRequest): SpendResult;
|
|
13
|
+
/**
|
|
14
|
+
* Helper to compute inference micropayment cost in stroops.
|
|
15
|
+
*/
|
|
16
|
+
computeTokenFee(promptTokens: number, completionTokens: number, rates: TokenPricingRate): bigint;
|
|
17
|
+
/**
|
|
18
|
+
* Helper to inspect Soroban contract TTL health.
|
|
19
|
+
*/
|
|
20
|
+
checkContractTtl(contractId: string, currentLedger: number, liveUntilLedger: number): import("../types.js").SorobanTtlStatus;
|
|
21
|
+
/**
|
|
22
|
+
* Helper for proof of task commitment computation.
|
|
23
|
+
*/
|
|
24
|
+
makeProofCommitment(outputPayload: string, nonce: string): string;
|
|
25
|
+
getAllowance(id: string): ScopedAllowance | undefined;
|
|
26
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AgentRailClient = void 0;
|
|
4
|
+
const scoped_allowance_js_1 = require("../lib/scoped-allowance.js");
|
|
5
|
+
const micro_stream_js_1 = require("../lib/micro-stream.js");
|
|
6
|
+
const ttl_keeper_js_1 = require("../lib/ttl-keeper.js");
|
|
7
|
+
const proof_of_task_js_1 = require("../lib/proof-of-task.js");
|
|
8
|
+
class AgentRailClient {
|
|
9
|
+
allowances = new Map();
|
|
10
|
+
/**
|
|
11
|
+
* Register a newly provisioned scoped allowance for an autonomous agent session.
|
|
12
|
+
*/
|
|
13
|
+
registerAllowance(allowance) {
|
|
14
|
+
this.allowances.set(allowance.id, { ...allowance });
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Authorize a micropayment spend from an active agent allowance.
|
|
18
|
+
*/
|
|
19
|
+
spend(request) {
|
|
20
|
+
const allowance = this.allowances.get(request.allowanceId);
|
|
21
|
+
if (!allowance) {
|
|
22
|
+
return {
|
|
23
|
+
ok: false,
|
|
24
|
+
code: "ALLOWANCE_NOT_FOUND",
|
|
25
|
+
message: `Allowance with ID ${request.allowanceId} was not found.`,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
const result = (0, scoped_allowance_js_1.verifyAndDeductSpend)(allowance, request);
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Helper to compute inference micropayment cost in stroops.
|
|
33
|
+
*/
|
|
34
|
+
computeTokenFee(promptTokens, completionTokens, rates) {
|
|
35
|
+
return (0, micro_stream_js_1.calculateTokenCost)(promptTokens, completionTokens, rates);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Helper to inspect Soroban contract TTL health.
|
|
39
|
+
*/
|
|
40
|
+
checkContractTtl(contractId, currentLedger, liveUntilLedger) {
|
|
41
|
+
return (0, ttl_keeper_js_1.evaluateContractTtl)(contractId, currentLedger, liveUntilLedger);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Helper for proof of task commitment computation.
|
|
45
|
+
*/
|
|
46
|
+
makeProofCommitment(outputPayload, nonce) {
|
|
47
|
+
return (0, proof_of_task_js_1.computeTaskCommitment)(outputPayload, nonce);
|
|
48
|
+
}
|
|
49
|
+
getAllowance(id) {
|
|
50
|
+
return this.allowances.get(id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.AgentRailClient = AgentRailClient;
|