@sardis/ai-sdk 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.
@@ -0,0 +1,216 @@
1
+ import { createSardisTools, createReadOnlySardisTools, createMinimalSardisTools } from './chunk-BVUWWUQU.js';
2
+
3
+ // src/provider.ts
4
+ var SardisProvider = class {
5
+ config;
6
+ _tools;
7
+ constructor(config) {
8
+ this.config = config;
9
+ switch (config.toolSet) {
10
+ case "minimal":
11
+ this._tools = createMinimalSardisTools(config);
12
+ break;
13
+ case "readonly":
14
+ this._tools = createReadOnlySardisTools(config);
15
+ break;
16
+ default:
17
+ this._tools = createSardisTools(config);
18
+ }
19
+ if (config.enableLogging || config.onTransaction) {
20
+ this._tools = this.wrapToolsWithLogging(this._tools);
21
+ }
22
+ }
23
+ /**
24
+ * Get the tools for Vercel AI SDK.
25
+ */
26
+ get tools() {
27
+ return this._tools;
28
+ }
29
+ /**
30
+ * Get the recommended system prompt for payment agents.
31
+ */
32
+ get systemPrompt() {
33
+ const basePrompt = `You are an AI assistant with access to a Sardis payment wallet.
34
+
35
+ ## Payment Guidelines
36
+
37
+ 1. **Always check policy before large payments** (>$50)
38
+ - Use sardis_check_policy to verify the payment would be allowed
39
+ - Report any policy violations to the user
40
+
41
+ 2. **Use holds for uncertain amounts**
42
+ - Create a hold when the final amount isn't known
43
+ - Capture the hold once the final amount is confirmed
44
+ - Void holds that are no longer needed
45
+
46
+ 3. **Provide transaction details**
47
+ - Always include the transaction ID and status in your response
48
+ - If a payment fails, explain why and suggest alternatives
49
+
50
+ 4. **Respect spending limits**
51
+ - Check remaining limits with sardis_get_spending
52
+ - Don't attempt payments that would exceed limits
53
+
54
+ 5. **Security practices**
55
+ - Never expose wallet IDs or API keys
56
+ - Verify merchant names before large payments
57
+ - Double-check amounts with the user for payments >$100
58
+
59
+ ## Available Actions
60
+
61
+ - **sardis_pay**: Execute a payment
62
+ - **sardis_create_hold**: Reserve funds for later
63
+ - **sardis_capture_hold**: Complete a held payment
64
+ - **sardis_void_hold**: Cancel a hold
65
+ - **sardis_check_policy**: Check if payment is allowed
66
+ - **sardis_get_balance**: Check wallet balance
67
+ - **sardis_get_spending**: View spending summary`;
68
+ if (this.config.customInstructions) {
69
+ return `${basePrompt}
70
+
71
+ ## Additional Instructions
72
+
73
+ ${this.config.customInstructions}`;
74
+ }
75
+ return basePrompt;
76
+ }
77
+ /**
78
+ * Execute a payment directly (without AI).
79
+ */
80
+ async pay(params) {
81
+ const tool = this._tools.sardis_pay;
82
+ if (!tool || typeof tool.execute !== "function") {
83
+ throw new Error("Payment tool not available");
84
+ }
85
+ return tool.execute(params, { toolCallId: "direct", messages: [] });
86
+ }
87
+ /**
88
+ * Create a hold directly (without AI).
89
+ */
90
+ async createHold(params) {
91
+ const tool = this._tools.sardis_create_hold;
92
+ if (!tool || typeof tool.execute !== "function") {
93
+ throw new Error("Hold tool not available");
94
+ }
95
+ return tool.execute(params, { toolCallId: "direct", messages: [] });
96
+ }
97
+ /**
98
+ * Capture a hold directly (without AI).
99
+ */
100
+ async captureHold(holdId, amount) {
101
+ const tool = this._tools.sardis_capture_hold;
102
+ if (!tool || typeof tool.execute !== "function") {
103
+ throw new Error("Capture tool not available");
104
+ }
105
+ return tool.execute({ holdId, amount }, { toolCallId: "direct", messages: [] });
106
+ }
107
+ /**
108
+ * Void a hold directly (without AI).
109
+ */
110
+ async voidHold(holdId) {
111
+ const tool = this._tools.sardis_void_hold;
112
+ if (!tool || typeof tool.execute !== "function") {
113
+ throw new Error("Void tool not available");
114
+ }
115
+ return tool.execute({ holdId }, { toolCallId: "direct", messages: [] });
116
+ }
117
+ /**
118
+ * Check policy directly (without AI).
119
+ */
120
+ async checkPolicy(params) {
121
+ const tool = this._tools.sardis_check_policy;
122
+ if (!tool || typeof tool.execute !== "function") {
123
+ throw new Error("Policy check tool not available");
124
+ }
125
+ return tool.execute(params, { toolCallId: "direct", messages: [] });
126
+ }
127
+ /**
128
+ * Get balance directly (without AI).
129
+ */
130
+ async getBalance(token, chain) {
131
+ const tool = this._tools.sardis_get_balance;
132
+ if (!tool || typeof tool.execute !== "function") {
133
+ throw new Error("Balance tool not available");
134
+ }
135
+ return tool.execute({ token, chain }, { toolCallId: "direct", messages: [] });
136
+ }
137
+ /**
138
+ * Wrap tools with logging functionality.
139
+ */
140
+ wrapToolsWithLogging(tools) {
141
+ const wrapped = {};
142
+ for (const [name, tool] of Object.entries(tools)) {
143
+ if (tool && typeof tool.execute === "function") {
144
+ const originalExecute = tool.execute.bind(tool);
145
+ wrapped[name] = {
146
+ ...tool,
147
+ execute: async (params, options) => {
148
+ const startTime = Date.now();
149
+ let result;
150
+ let success = true;
151
+ let error;
152
+ try {
153
+ result = await originalExecute(params, options);
154
+ if (result && typeof result === "object" && "success" in result) {
155
+ success = result.success;
156
+ if (!success && "error" in result) {
157
+ error = result.error;
158
+ }
159
+ }
160
+ } catch (e) {
161
+ success = false;
162
+ error = e instanceof Error ? e.message : "Unknown error";
163
+ throw e;
164
+ } finally {
165
+ const event = {
166
+ type: this.getEventType(name),
167
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
168
+ params,
169
+ result,
170
+ success,
171
+ error
172
+ };
173
+ if (this.config.enableLogging) {
174
+ const duration = Date.now() - startTime;
175
+ console.log(`[Sardis] ${name} ${success ? "\u2713" : "\u2717"} (${duration}ms)`, event);
176
+ }
177
+ if (this.config.onTransaction) {
178
+ try {
179
+ await this.config.onTransaction(event);
180
+ } catch (callbackError) {
181
+ console.error("[Sardis] Transaction callback error:", callbackError);
182
+ }
183
+ }
184
+ }
185
+ return result;
186
+ }
187
+ };
188
+ } else {
189
+ wrapped[name] = tool;
190
+ }
191
+ }
192
+ return wrapped;
193
+ }
194
+ /**
195
+ * Map tool name to event type.
196
+ */
197
+ getEventType(toolName) {
198
+ const mapping = {
199
+ sardis_pay: "payment",
200
+ sardis_create_hold: "hold_create",
201
+ sardis_capture_hold: "hold_capture",
202
+ sardis_void_hold: "hold_void",
203
+ sardis_check_policy: "policy_check",
204
+ sardis_get_balance: "balance_check",
205
+ sardis_get_spending: "balance_check"
206
+ };
207
+ return mapping[toolName] || "payment";
208
+ }
209
+ };
210
+ function createSardisProvider(config) {
211
+ return new SardisProvider(config);
212
+ }
213
+
214
+ export { SardisProvider, createSardisProvider };
215
+ //# sourceMappingURL=chunk-LMCXCW32.js.map
216
+ //# sourceMappingURL=chunk-LMCXCW32.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provider.ts"],"names":[],"mappings":";;;AAwEO,IAAM,iBAAN,MAAqB;AAAA,EAClB,MAAA;AAAA,EACA,MAAA;AAAA,EAER,YAAY,MAAA,EAA8B;AACxC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAGd,IAAA,QAAQ,OAAO,OAAA;AAAS,MACtB,KAAK,SAAA;AACH,QAAA,IAAA,CAAK,MAAA,GAAS,yBAAyB,MAAM,CAAA;AAC7C,QAAA;AAAA,MACF,KAAK,UAAA;AACH,QAAA,IAAA,CAAK,MAAA,GAAS,0BAA0B,MAAM,CAAA;AAC9C,QAAA;AAAA,MACF;AACE,QAAA,IAAA,CAAK,MAAA,GAAS,kBAAkB,MAAM,CAAA;AAAA;AAI1C,IAAA,IAAI,MAAA,CAAO,aAAA,IAAiB,MAAA,CAAO,aAAA,EAAe;AAChD,MAAA,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,oBAAA,CAAqB,IAAA,CAAK,MAAM,CAAA;AAAA,IACrD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,KAAA,GAA8B;AAChC,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,YAAA,GAAuB;AACzB,IAAA,MAAM,UAAA,GAAa,CAAA;;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;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qB;AAAA,KACvB;AACA,IAAA,OAAO,OAAA,CAAQ,QAAQ,CAAA,IAAK,SAAA;AAAA,EAC9B;AACF;AAOO,SAAS,qBAAqB,MAAA,EAA8C;AACjF,EAAA,OAAO,IAAI,eAAe,MAAM,CAAA;AAClC","file":"chunk-LMCXCW32.js","sourcesContent":["/**\n * Sardis Provider for Vercel AI SDK.\n *\n * Provides a higher-level abstraction for integrating Sardis payments\n * with AI agents, including automatic policy enforcement and transaction logging.\n *\n * @example\n * ```typescript\n * import { SardisProvider } from '@sardis/ai-sdk/provider'\n *\n * const sardis = new SardisProvider({\n * apiKey: process.env.SARDIS_API_KEY!,\n * walletId: 'wallet_abc123',\n * agentId: 'agent_xyz789',\n * })\n *\n * // Use with Vercel AI SDK\n * const { text } = await generateText({\n * model: openai('gpt-4o'),\n * tools: sardis.tools,\n * system: sardis.systemPrompt,\n * prompt: 'Purchase $50 worth of API credits',\n * })\n *\n * // Or execute directly\n * const result = await sardis.pay({\n * to: 'merchant_openai',\n * amount: 50,\n * memo: 'API credits',\n * })\n * ```\n */\n\nimport { createSardisTools, createMinimalSardisTools, createReadOnlySardisTools } from './tools'\nimport type { SardisToolsConfig, PaymentResult, HoldResult, PolicyCheckResult, BalanceResult } from './types'\nimport type { Tool, ToolExecutionOptions } from 'ai'\n\n/**\n * Extended configuration for SardisProvider.\n */\nexport interface SardisProviderConfig extends SardisToolsConfig {\n /** Log all transactions to console */\n enableLogging?: boolean\n /** Callback for transaction events */\n onTransaction?: (event: TransactionEvent) => void | Promise<void>\n /** Custom system prompt additions */\n customInstructions?: string\n /** Tool set to use: 'full', 'minimal', 'readonly' */\n toolSet?: 'full' | 'minimal' | 'readonly'\n}\n\n/**\n * Transaction event for logging/callbacks.\n */\nexport interface TransactionEvent {\n type: 'payment' | 'hold_create' | 'hold_capture' | 'hold_void' | 'policy_check' | 'balance_check'\n timestamp: string\n params: Record<string, unknown>\n result: PaymentResult | HoldResult | PolicyCheckResult | BalanceResult\n success: boolean\n error?: string\n}\n\n/**\n * Sardis Provider for streamlined AI agent integration.\n *\n * Provides:\n * - Pre-configured tools for Vercel AI SDK\n * - System prompt with payment guidelines\n * - Direct payment methods for programmatic access\n * - Transaction logging and callbacks\n */\nexport class SardisProvider {\n private config: SardisProviderConfig\n private _tools: Record<string, Tool>\n\n constructor(config: SardisProviderConfig) {\n this.config = config\n\n // Create appropriate tool set\n switch (config.toolSet) {\n case 'minimal':\n this._tools = createMinimalSardisTools(config)\n break\n case 'readonly':\n this._tools = createReadOnlySardisTools(config)\n break\n default:\n this._tools = createSardisTools(config)\n }\n\n // Wrap tools with logging if enabled\n if (config.enableLogging || config.onTransaction) {\n this._tools = this.wrapToolsWithLogging(this._tools)\n }\n }\n\n /**\n * Get the tools for Vercel AI SDK.\n */\n get tools(): Record<string, Tool> {\n return this._tools\n }\n\n /**\n * Get the recommended system prompt for payment agents.\n */\n get systemPrompt(): string {\n const basePrompt = `You are an AI assistant with access to a Sardis payment wallet.\n\n## Payment Guidelines\n\n1. **Always check policy before large payments** (>$50)\n - Use sardis_check_policy to verify the payment would be allowed\n - Report any policy violations to the user\n\n2. **Use holds for uncertain amounts**\n - Create a hold when the final amount isn't known\n - Capture the hold once the final amount is confirmed\n - Void holds that are no longer needed\n\n3. **Provide transaction details**\n - Always include the transaction ID and status in your response\n - If a payment fails, explain why and suggest alternatives\n\n4. **Respect spending limits**\n - Check remaining limits with sardis_get_spending\n - Don't attempt payments that would exceed limits\n\n5. **Security practices**\n - Never expose wallet IDs or API keys\n - Verify merchant names before large payments\n - Double-check amounts with the user for payments >$100\n\n## Available Actions\n\n- **sardis_pay**: Execute a payment\n- **sardis_create_hold**: Reserve funds for later\n- **sardis_capture_hold**: Complete a held payment\n- **sardis_void_hold**: Cancel a hold\n- **sardis_check_policy**: Check if payment is allowed\n- **sardis_get_balance**: Check wallet balance\n- **sardis_get_spending**: View spending summary`\n\n if (this.config.customInstructions) {\n return `${basePrompt}\\n\\n## Additional Instructions\\n\\n${this.config.customInstructions}`\n }\n\n return basePrompt\n }\n\n /**\n * Execute a payment directly (without AI).\n */\n async pay(params: {\n to: string\n amount: number\n token?: string\n chain?: 'base' | 'polygon' | 'ethereum' | 'arbitrum' | 'optimism'\n memo?: string\n merchant?: string\n category?: string\n }): Promise<PaymentResult> {\n const tool = this._tools.sardis_pay\n if (!tool || typeof tool.execute !== 'function') {\n throw new Error('Payment tool not available')\n }\n return tool.execute(params, { toolCallId: 'direct', messages: [] }) as Promise<PaymentResult>\n }\n\n /**\n * Create a hold directly (without AI).\n */\n async createHold(params: {\n amount: number\n merchant: string\n expiresInHours?: number\n description?: string\n }): Promise<HoldResult> {\n const tool = this._tools.sardis_create_hold\n if (!tool || typeof tool.execute !== 'function') {\n throw new Error('Hold tool not available')\n }\n return tool.execute(params, { toolCallId: 'direct', messages: [] }) as Promise<HoldResult>\n }\n\n /**\n * Capture a hold directly (without AI).\n */\n async captureHold(holdId: string, amount?: number): Promise<HoldResult> {\n const tool = this._tools.sardis_capture_hold\n if (!tool || typeof tool.execute !== 'function') {\n throw new Error('Capture tool not available')\n }\n return tool.execute({ holdId, amount }, { toolCallId: 'direct', messages: [] }) as Promise<HoldResult>\n }\n\n /**\n * Void a hold directly (without AI).\n */\n async voidHold(holdId: string): Promise<HoldResult> {\n const tool = this._tools.sardis_void_hold\n if (!tool || typeof tool.execute !== 'function') {\n throw new Error('Void tool not available')\n }\n return tool.execute({ holdId }, { toolCallId: 'direct', messages: [] }) as Promise<HoldResult>\n }\n\n /**\n * Check policy directly (without AI).\n */\n async checkPolicy(params: {\n amount: number\n merchant?: string\n category?: string\n }): Promise<PolicyCheckResult> {\n const tool = this._tools.sardis_check_policy\n if (!tool || typeof tool.execute !== 'function') {\n throw new Error('Policy check tool not available')\n }\n return tool.execute(params, { toolCallId: 'direct', messages: [] }) as Promise<PolicyCheckResult>\n }\n\n /**\n * Get balance directly (without AI).\n */\n async getBalance(token?: string, chain?: string): Promise<BalanceResult> {\n const tool = this._tools.sardis_get_balance\n if (!tool || typeof tool.execute !== 'function') {\n throw new Error('Balance tool not available')\n }\n return tool.execute({ token, chain }, { toolCallId: 'direct', messages: [] }) as Promise<BalanceResult>\n }\n\n /**\n * Wrap tools with logging functionality.\n */\n private wrapToolsWithLogging(tools: Record<string, Tool>): Record<string, Tool> {\n const wrapped: Record<string, Tool> = {}\n\n for (const [name, tool] of Object.entries(tools)) {\n if (tool && typeof tool.execute === 'function') {\n const originalExecute = tool.execute.bind(tool)\n\n wrapped[name] = {\n ...tool,\n execute: async (params: unknown, options: ToolExecutionOptions) => {\n const startTime = Date.now()\n let result: unknown\n let success = true\n let error: string | undefined\n\n try {\n result = await originalExecute(params, options)\n\n // Check if result indicates failure\n if (result && typeof result === 'object' && 'success' in result) {\n success = (result as { success: boolean }).success\n if (!success && 'error' in result) {\n error = (result as { error?: string }).error\n }\n }\n } catch (e) {\n success = false\n error = e instanceof Error ? e.message : 'Unknown error'\n throw e\n } finally {\n const event: TransactionEvent = {\n type: this.getEventType(name),\n timestamp: new Date().toISOString(),\n params: params as Record<string, unknown>,\n result: result as TransactionEvent['result'],\n success,\n error,\n }\n\n // Log to console if enabled\n if (this.config.enableLogging) {\n const duration = Date.now() - startTime\n console.log(`[Sardis] ${name} ${success ? '✓' : '✗'} (${duration}ms)`, event)\n }\n\n // Call transaction callback if provided\n if (this.config.onTransaction) {\n try {\n await this.config.onTransaction(event)\n } catch (callbackError) {\n console.error('[Sardis] Transaction callback error:', callbackError)\n }\n }\n }\n\n return result\n },\n } as Tool\n } else {\n wrapped[name] = tool\n }\n }\n\n return wrapped\n }\n\n /**\n * Map tool name to event type.\n */\n private getEventType(toolName: string): TransactionEvent['type'] {\n const mapping: Record<string, TransactionEvent['type']> = {\n sardis_pay: 'payment',\n sardis_create_hold: 'hold_create',\n sardis_capture_hold: 'hold_capture',\n sardis_void_hold: 'hold_void',\n sardis_check_policy: 'policy_check',\n sardis_get_balance: 'balance_check',\n sardis_get_spending: 'balance_check',\n }\n return mapping[toolName] || 'payment'\n }\n}\n\n/**\n * Create a SardisProvider instance.\n *\n * Convenience function for creating a provider.\n */\nexport function createSardisProvider(config: SardisProviderConfig): SardisProvider {\n return new SardisProvider(config)\n}\n"]}
@@ -0,0 +1,5 @@
1
+ export { createMinimalSardisTools, createReadOnlySardisTools, createSardisTools } from './tools.js';
2
+ export { SardisProvider, SardisProviderConfig, TransactionEvent, createSardisProvider } from './provider.js';
3
+ export { B as BalanceParams, a as BalanceParamsSchema, b as BalanceResult, C as CaptureParams, c as CaptureParamsSchema, H as HoldParams, d as HoldParamsSchema, e as HoldResult, P as PaymentParams, f as PaymentParamsSchema, g as PaymentResult, h as PolicyCheckParams, i as PolicyCheckParamsSchema, j as PolicyCheckResult, S as SardisToolsConfig } from './types-Cdb1Gu2W.js';
4
+ import 'ai';
5
+ import 'zod';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { SardisProvider, createSardisProvider } from './chunk-LMCXCW32.js';
2
+ export { BalanceParamsSchema, CaptureParamsSchema, HoldParamsSchema, PaymentParamsSchema, PolicyCheckParamsSchema, createMinimalSardisTools, createReadOnlySardisTools, createSardisTools } from './chunk-BVUWWUQU.js';
3
+ //# sourceMappingURL=index.js.map
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,140 @@
1
+ import { S as SardisToolsConfig, g as PaymentResult, e as HoldResult, j as PolicyCheckResult, b as BalanceResult } from './types-Cdb1Gu2W.js';
2
+ import { Tool } from 'ai';
3
+ import 'zod';
4
+
5
+ /**
6
+ * Sardis Provider for Vercel AI SDK.
7
+ *
8
+ * Provides a higher-level abstraction for integrating Sardis payments
9
+ * with AI agents, including automatic policy enforcement and transaction logging.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { SardisProvider } from '@sardis/ai-sdk/provider'
14
+ *
15
+ * const sardis = new SardisProvider({
16
+ * apiKey: process.env.SARDIS_API_KEY!,
17
+ * walletId: 'wallet_abc123',
18
+ * agentId: 'agent_xyz789',
19
+ * })
20
+ *
21
+ * // Use with Vercel AI SDK
22
+ * const { text } = await generateText({
23
+ * model: openai('gpt-4o'),
24
+ * tools: sardis.tools,
25
+ * system: sardis.systemPrompt,
26
+ * prompt: 'Purchase $50 worth of API credits',
27
+ * })
28
+ *
29
+ * // Or execute directly
30
+ * const result = await sardis.pay({
31
+ * to: 'merchant_openai',
32
+ * amount: 50,
33
+ * memo: 'API credits',
34
+ * })
35
+ * ```
36
+ */
37
+
38
+ /**
39
+ * Extended configuration for SardisProvider.
40
+ */
41
+ interface SardisProviderConfig extends SardisToolsConfig {
42
+ /** Log all transactions to console */
43
+ enableLogging?: boolean;
44
+ /** Callback for transaction events */
45
+ onTransaction?: (event: TransactionEvent) => void | Promise<void>;
46
+ /** Custom system prompt additions */
47
+ customInstructions?: string;
48
+ /** Tool set to use: 'full', 'minimal', 'readonly' */
49
+ toolSet?: 'full' | 'minimal' | 'readonly';
50
+ }
51
+ /**
52
+ * Transaction event for logging/callbacks.
53
+ */
54
+ interface TransactionEvent {
55
+ type: 'payment' | 'hold_create' | 'hold_capture' | 'hold_void' | 'policy_check' | 'balance_check';
56
+ timestamp: string;
57
+ params: Record<string, unknown>;
58
+ result: PaymentResult | HoldResult | PolicyCheckResult | BalanceResult;
59
+ success: boolean;
60
+ error?: string;
61
+ }
62
+ /**
63
+ * Sardis Provider for streamlined AI agent integration.
64
+ *
65
+ * Provides:
66
+ * - Pre-configured tools for Vercel AI SDK
67
+ * - System prompt with payment guidelines
68
+ * - Direct payment methods for programmatic access
69
+ * - Transaction logging and callbacks
70
+ */
71
+ declare class SardisProvider {
72
+ private config;
73
+ private _tools;
74
+ constructor(config: SardisProviderConfig);
75
+ /**
76
+ * Get the tools for Vercel AI SDK.
77
+ */
78
+ get tools(): Record<string, Tool>;
79
+ /**
80
+ * Get the recommended system prompt for payment agents.
81
+ */
82
+ get systemPrompt(): string;
83
+ /**
84
+ * Execute a payment directly (without AI).
85
+ */
86
+ pay(params: {
87
+ to: string;
88
+ amount: number;
89
+ token?: string;
90
+ chain?: 'base' | 'polygon' | 'ethereum' | 'arbitrum' | 'optimism';
91
+ memo?: string;
92
+ merchant?: string;
93
+ category?: string;
94
+ }): Promise<PaymentResult>;
95
+ /**
96
+ * Create a hold directly (without AI).
97
+ */
98
+ createHold(params: {
99
+ amount: number;
100
+ merchant: string;
101
+ expiresInHours?: number;
102
+ description?: string;
103
+ }): Promise<HoldResult>;
104
+ /**
105
+ * Capture a hold directly (without AI).
106
+ */
107
+ captureHold(holdId: string, amount?: number): Promise<HoldResult>;
108
+ /**
109
+ * Void a hold directly (without AI).
110
+ */
111
+ voidHold(holdId: string): Promise<HoldResult>;
112
+ /**
113
+ * Check policy directly (without AI).
114
+ */
115
+ checkPolicy(params: {
116
+ amount: number;
117
+ merchant?: string;
118
+ category?: string;
119
+ }): Promise<PolicyCheckResult>;
120
+ /**
121
+ * Get balance directly (without AI).
122
+ */
123
+ getBalance(token?: string, chain?: string): Promise<BalanceResult>;
124
+ /**
125
+ * Wrap tools with logging functionality.
126
+ */
127
+ private wrapToolsWithLogging;
128
+ /**
129
+ * Map tool name to event type.
130
+ */
131
+ private getEventType;
132
+ }
133
+ /**
134
+ * Create a SardisProvider instance.
135
+ *
136
+ * Convenience function for creating a provider.
137
+ */
138
+ declare function createSardisProvider(config: SardisProviderConfig): SardisProvider;
139
+
140
+ export { SardisProvider, type SardisProviderConfig, type TransactionEvent, createSardisProvider };
@@ -0,0 +1,4 @@
1
+ export { SardisProvider, createSardisProvider } from './chunk-LMCXCW32.js';
2
+ import './chunk-BVUWWUQU.js';
3
+ //# sourceMappingURL=provider.js.map
4
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"provider.js"}
@@ -0,0 +1,64 @@
1
+ import { Tool } from 'ai';
2
+ import { S as SardisToolsConfig } from './types-Cdb1Gu2W.js';
3
+ import 'zod';
4
+
5
+ /**
6
+ * Sardis payment tools for Vercel AI SDK.
7
+ *
8
+ * These tools enable AI agents to make payments with policy guardrails.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { generateText } from 'ai'
13
+ * import { openai } from '@ai-sdk/openai'
14
+ * import { createSardisTools } from '@sardis/ai-sdk'
15
+ *
16
+ * const sardisTools = createSardisTools({
17
+ * apiKey: process.env.SARDIS_API_KEY!,
18
+ * walletId: 'wallet_abc123',
19
+ * })
20
+ *
21
+ * const result = await generateText({
22
+ * model: openai('gpt-4o'),
23
+ * tools: sardisTools,
24
+ * prompt: 'Pay $50 to merchant_xyz for API credits',
25
+ * })
26
+ * ```
27
+ */
28
+
29
+ /**
30
+ * Create Sardis payment tools for Vercel AI SDK.
31
+ *
32
+ * Returns a set of tools that can be passed to `generateText` or `streamText`.
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const tools = createSardisTools({
37
+ * apiKey: process.env.SARDIS_API_KEY!,
38
+ * walletId: 'wallet_abc123',
39
+ * maxPaymentAmount: 100, // Optional: limit single payments
40
+ * blockedCategories: ['gambling', 'adult'], // Optional: block categories
41
+ * })
42
+ *
43
+ * const { text, toolResults } = await generateText({
44
+ * model: openai('gpt-4o'),
45
+ * tools,
46
+ * prompt: 'Check my balance and pay $25 to OpenAI for API credits',
47
+ * })
48
+ * ```
49
+ */
50
+ declare function createSardisTools(config: SardisToolsConfig): Record<string, Tool>;
51
+ /**
52
+ * Create a minimal set of Sardis tools (pay + balance only).
53
+ *
54
+ * Use this for simpler use cases that don't need holds or detailed policy checks.
55
+ */
56
+ declare function createMinimalSardisTools(config: SardisToolsConfig): Record<string, Tool>;
57
+ /**
58
+ * Create Sardis tools with only read operations (no payments).
59
+ *
60
+ * Use this for analytics, reporting, or view-only access.
61
+ */
62
+ declare function createReadOnlySardisTools(config: SardisToolsConfig): Record<string, Tool>;
63
+
64
+ export { createMinimalSardisTools, createReadOnlySardisTools, createSardisTools };
package/dist/tools.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createMinimalSardisTools, createReadOnlySardisTools, createSardisTools } from './chunk-BVUWWUQU.js';
2
+ //# sourceMappingURL=tools.js.map
3
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"tools.js"}
@@ -0,0 +1,192 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Type definitions for Sardis AI SDK integration.
5
+ */
6
+
7
+ /**
8
+ * Configuration for Sardis AI SDK tools.
9
+ */
10
+ interface SardisToolsConfig {
11
+ /** Sardis API key */
12
+ apiKey: string;
13
+ /** Default wallet ID for payments */
14
+ walletId: string;
15
+ /** Default agent ID */
16
+ agentId?: string;
17
+ /** Base URL for Sardis API (default: https://api.sardis.network) */
18
+ baseUrl?: string;
19
+ /** Enable simulation mode (no real transactions) */
20
+ simulationMode?: boolean;
21
+ /** Maximum single payment amount (policy limit) */
22
+ maxPaymentAmount?: number;
23
+ /** Blocked merchant categories */
24
+ blockedCategories?: string[];
25
+ /** Allowed merchants only (whitelist mode) */
26
+ allowedMerchants?: string[];
27
+ }
28
+ /**
29
+ * Payment execution parameters.
30
+ */
31
+ declare const PaymentParamsSchema: z.ZodObject<{
32
+ /** Recipient address or merchant identifier */
33
+ to: z.ZodString;
34
+ /** Amount in USD */
35
+ amount: z.ZodNumber;
36
+ /** Token to use (default: USDC) */
37
+ token: z.ZodDefault<z.ZodOptional<z.ZodString>>;
38
+ /** Chain to execute on */
39
+ chain: z.ZodDefault<z.ZodOptional<z.ZodEnum<["base", "polygon", "ethereum", "arbitrum", "optimism"]>>>;
40
+ /** Payment description/memo */
41
+ memo: z.ZodOptional<z.ZodString>;
42
+ /** Merchant name for policy checks */
43
+ merchant: z.ZodOptional<z.ZodString>;
44
+ /** Merchant category code */
45
+ category: z.ZodOptional<z.ZodString>;
46
+ /** Idempotency key to prevent duplicates */
47
+ idempotencyKey: z.ZodOptional<z.ZodString>;
48
+ }, "strip", z.ZodTypeAny, {
49
+ to: string;
50
+ amount: number;
51
+ token: string;
52
+ chain: "base" | "polygon" | "ethereum" | "arbitrum" | "optimism";
53
+ memo?: string | undefined;
54
+ merchant?: string | undefined;
55
+ category?: string | undefined;
56
+ idempotencyKey?: string | undefined;
57
+ }, {
58
+ to: string;
59
+ amount: number;
60
+ token?: string | undefined;
61
+ chain?: "base" | "polygon" | "ethereum" | "arbitrum" | "optimism" | undefined;
62
+ memo?: string | undefined;
63
+ merchant?: string | undefined;
64
+ category?: string | undefined;
65
+ idempotencyKey?: string | undefined;
66
+ }>;
67
+ type PaymentParams = z.infer<typeof PaymentParamsSchema>;
68
+ /**
69
+ * Hold creation parameters.
70
+ */
71
+ declare const HoldParamsSchema: z.ZodObject<{
72
+ /** Amount to hold in USD */
73
+ amount: z.ZodNumber;
74
+ /** Merchant name */
75
+ merchant: z.ZodString;
76
+ /** Hold expiration in hours (default: 24) */
77
+ expiresInHours: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
78
+ /** Description of the hold purpose */
79
+ description: z.ZodOptional<z.ZodString>;
80
+ }, "strip", z.ZodTypeAny, {
81
+ amount: number;
82
+ merchant: string;
83
+ expiresInHours: number;
84
+ description?: string | undefined;
85
+ }, {
86
+ amount: number;
87
+ merchant: string;
88
+ expiresInHours?: number | undefined;
89
+ description?: string | undefined;
90
+ }>;
91
+ type HoldParams = z.infer<typeof HoldParamsSchema>;
92
+ /**
93
+ * Hold capture parameters.
94
+ */
95
+ declare const CaptureParamsSchema: z.ZodObject<{
96
+ /** Hold ID to capture */
97
+ holdId: z.ZodString;
98
+ /** Amount to capture (defaults to full hold amount) */
99
+ amount: z.ZodOptional<z.ZodNumber>;
100
+ }, "strip", z.ZodTypeAny, {
101
+ holdId: string;
102
+ amount?: number | undefined;
103
+ }, {
104
+ holdId: string;
105
+ amount?: number | undefined;
106
+ }>;
107
+ type CaptureParams = z.infer<typeof CaptureParamsSchema>;
108
+ /**
109
+ * Policy check parameters.
110
+ */
111
+ declare const PolicyCheckParamsSchema: z.ZodObject<{
112
+ /** Amount to check */
113
+ amount: z.ZodNumber;
114
+ /** Merchant name */
115
+ merchant: z.ZodOptional<z.ZodString>;
116
+ /** Merchant category */
117
+ category: z.ZodOptional<z.ZodString>;
118
+ }, "strip", z.ZodTypeAny, {
119
+ amount: number;
120
+ merchant?: string | undefined;
121
+ category?: string | undefined;
122
+ }, {
123
+ amount: number;
124
+ merchant?: string | undefined;
125
+ category?: string | undefined;
126
+ }>;
127
+ type PolicyCheckParams = z.infer<typeof PolicyCheckParamsSchema>;
128
+ /**
129
+ * Balance check parameters.
130
+ */
131
+ declare const BalanceParamsSchema: z.ZodObject<{
132
+ /** Token to check (default: USDC) */
133
+ token: z.ZodDefault<z.ZodOptional<z.ZodString>>;
134
+ /** Chain to check */
135
+ chain: z.ZodOptional<z.ZodString>;
136
+ }, "strip", z.ZodTypeAny, {
137
+ token: string;
138
+ chain?: string | undefined;
139
+ }, {
140
+ token?: string | undefined;
141
+ chain?: string | undefined;
142
+ }>;
143
+ type BalanceParams = z.infer<typeof BalanceParamsSchema>;
144
+ /**
145
+ * Payment result.
146
+ */
147
+ interface PaymentResult {
148
+ success: boolean;
149
+ transactionId?: string;
150
+ txHash?: string;
151
+ amount: number;
152
+ token: string;
153
+ chain: string;
154
+ status: 'completed' | 'pending' | 'failed';
155
+ error?: string;
156
+ blockNumber?: number;
157
+ timestamp: string;
158
+ }
159
+ /**
160
+ * Hold result.
161
+ */
162
+ interface HoldResult {
163
+ success: boolean;
164
+ holdId?: string;
165
+ amount: number;
166
+ merchant: string;
167
+ expiresAt?: string;
168
+ status: 'active' | 'captured' | 'voided' | 'expired' | 'failed';
169
+ error?: string;
170
+ }
171
+ /**
172
+ * Policy check result.
173
+ */
174
+ interface PolicyCheckResult {
175
+ allowed: boolean;
176
+ reason?: string;
177
+ remainingDailyLimit?: number;
178
+ remainingMonthlyLimit?: number;
179
+ requiresApproval?: boolean;
180
+ }
181
+ /**
182
+ * Balance result.
183
+ */
184
+ interface BalanceResult {
185
+ available: number;
186
+ pending: number;
187
+ held: number;
188
+ token: string;
189
+ chain: string;
190
+ }
191
+
192
+ export { type BalanceParams as B, type CaptureParams as C, type HoldParams as H, type PaymentParams as P, type SardisToolsConfig as S, BalanceParamsSchema as a, type BalanceResult as b, CaptureParamsSchema as c, HoldParamsSchema as d, type HoldResult as e, PaymentParamsSchema as f, type PaymentResult as g, type PolicyCheckParams as h, PolicyCheckParamsSchema as i, type PolicyCheckResult as j };