@obelyzk/sdk 1.4.0 → 1.5.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.
@@ -1,166 +1,272 @@
1
- import * as starknet from 'starknet';
1
+ import { T as TransactionFeatures, D as Decision, A as AgentFirewallSDK } from '../client-DFxKbDns.js';
2
+ export { a as AgentStatus, C as ClassifyResult, E as EvaluateActionResult, F as FirewallConfig, R as ResolveResult, S as SubmitActionResult } from '../client-DFxKbDns.js';
3
+ import 'starknet';
2
4
 
3
5
  /**
4
- * Types for the ZKML Agent Firewall SDK.
6
+ * ObelyZK Agent Middleware
5
7
  *
6
- * These types map 1:1 to the Rust classifier and Cairo AgentFirewallZK contract.
8
+ * Wraps agent tool execution with automatic ZKML classification.
9
+ * Designed for use with the Claude Agent SDK or any tool-calling agent framework.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { createPolicyEnforcer } from '@obelyzk/sdk/firewall';
14
+ *
15
+ * const enforcer = createPolicyEnforcer({
16
+ * proverUrl: 'http://localhost:8080',
17
+ * agentId: 'my-agent-001',
18
+ * });
19
+ *
20
+ * // Check before executing an on-chain action
21
+ * const decision = await enforcer.checkAction({
22
+ * target: '0x049d...',
23
+ * value: '1000000000',
24
+ * selector: '0xa9059cbb',
25
+ * });
26
+ *
27
+ * if (decision.allowed) {
28
+ * // safe to execute
29
+ * } else {
30
+ * console.log(decision.reason); // "Blocked: threat_score=85000"
31
+ * }
32
+ *
33
+ * // Get MCP server config for Claude Agent SDK
34
+ * const mcpConfig = enforcer.getMcpServerConfig();
35
+ * // Pass to agent's mcpServers option
36
+ *
37
+ * // Get allowed tools list
38
+ * const tools = enforcer.getAllowedTools();
39
+ * // Pass to agent's allowedTools option
40
+ * ```
7
41
  */
8
- /** Transaction features sent to the classifier. */
9
- interface TransactionFeatures {
10
- /** Target contract address (hex, 0x-prefixed). */
11
- target: string;
12
- /** Transaction value (decimal string, u256). */
13
- value?: string;
14
- /** Function selector (hex, 4 bytes, 0x-prefixed). */
15
- selector?: string;
16
- /** Calldata (hex, after selector, 0x-prefixed). */
17
- calldata?: string;
18
- /** Agent's current trust score (0-100000). */
19
- agentTrustScore?: number;
20
- /** Agent's current strike count. */
21
- agentStrikes?: number;
22
- /** Agent age in blocks since registration. */
23
- agentAgeBlocks?: number;
24
- /** Target contract metadata. */
25
- targetVerified?: boolean;
26
- targetIsProxy?: boolean;
27
- targetHasSource?: boolean;
28
- targetInteractionCount?: number;
29
- /** Behavioral features. */
30
- txFrequency?: number;
31
- uniqueTargets24h?: number;
32
- avgValue24h?: number;
33
- maxValue24h?: number;
42
+
43
+ /** Policy enforcer configuration. */
44
+ interface PolicyEnforcerConfig {
45
+ /** Prove-server base URL. */
46
+ proverUrl: string;
47
+ /** Agent ID for firewall registration. */
48
+ agentId?: string;
49
+ /** Starknet RPC URL (for on-chain queries). */
50
+ rpcUrl?: string;
51
+ /** Firewall contract address (for on-chain queries). */
52
+ firewallContract?: string;
53
+ /** Verifier contract address. */
54
+ verifierContract?: string;
55
+ /** API key for prove-server. */
56
+ apiKey?: string;
57
+ /** Threat score threshold for blocking (default: 70000). */
58
+ blockThreshold?: number;
59
+ /** Threat score threshold for escalation (default: 40000). */
60
+ escalateThreshold?: number;
61
+ /** Path to MCP server entry point (for getMcpServerConfig). */
62
+ mcpServerPath?: string;
34
63
  }
35
- /** Classifier decision. */
36
- type Decision = "approve" | "escalate" | "block";
37
- /** Result from evaluating a transaction through the ZKML classifier. */
38
- interface ClassifyResult {
39
- /** Unique request ID. */
40
- requestId: string;
64
+ /** Result from checking an action. */
65
+ interface ActionCheck {
66
+ /** Whether the action is allowed to proceed. */
67
+ allowed: boolean;
41
68
  /** Classifier decision. */
42
69
  decision: Decision;
43
70
  /** Threat score (0-100000). */
44
71
  threatScore: number;
45
- /** Raw output scores: [safe, suspicious, malicious]. */
46
- scores: [number, number, number];
47
- /** IO commitment (Poseidon hash of classifier input + output). */
72
+ /** Human-readable reason for the decision. */
73
+ reason: string;
74
+ /** IO commitment from the proof (for audit trail). */
48
75
  ioCommitment: string;
49
- /** Policy commitment (strict policy hash). */
76
+ /** Policy commitment hash. */
50
77
  policyCommitment: string;
51
78
  /** Proving time in milliseconds. */
52
79
  proveTimeMs: number;
53
80
  }
54
- /** Result from submitting an action to the firewall contract. */
55
- interface SubmitActionResult {
56
- /** Action ID assigned by the contract. */
57
- actionId: number;
58
- /** Transaction hash. */
59
- txHash: string;
60
- }
61
- /** Result from resolving an action with a verified proof. */
62
- interface ResolveResult {
63
- /** Final decision after proof verification. */
64
- decision: Decision;
65
- /** Threat score applied to the agent. */
66
- threatScore: number;
67
- /** Transaction hash. */
68
- txHash: string;
69
- }
70
- /** Agent trust status. */
71
- interface AgentStatus {
72
- /** Whether the agent is registered. */
73
- registered: boolean;
74
- /** Whether the agent is active (not frozen). */
75
- active: boolean;
76
- /** Current trust score (0-100000, EMA smoothed). */
77
- trustScore: number;
78
- /** Current strike count. */
79
- strikes: number;
80
- /** Whether the agent is trusted (active + score < threshold + strikes < max). */
81
- trusted: boolean;
82
- }
83
- /** Firewall SDK configuration. */
84
- interface FirewallConfig {
85
- /** Prover server URL (for /api/v1/classify). */
86
- proverUrl: string;
87
- /** AgentFirewallZK contract address on Starknet. */
88
- firewallContract: string;
89
- /** ObelyskVerifier contract address on Starknet. */
90
- verifierContract: string;
91
- /** Starknet RPC URL. */
92
- rpcUrl: string;
93
- /** Starknet account for signing transactions. */
94
- account?: starknet.Account;
95
- /** API key for the prover server (optional). */
96
- apiKey?: string;
81
+ /**
82
+ * Create a policy enforcer for programmatic agent use.
83
+ *
84
+ * The enforcer wraps the AgentFirewallSDK and provides a simplified API
85
+ * for checking actions, getting MCP server configs, and building
86
+ * allowedTools lists for the Claude Agent SDK.
87
+ */
88
+ declare function createPolicyEnforcer(config: PolicyEnforcerConfig): PolicyEnforcer;
89
+ declare class PolicyEnforcer {
90
+ private sdk;
91
+ private config;
92
+ private blockThreshold;
93
+ private escalateThreshold;
94
+ constructor(config: PolicyEnforcerConfig);
95
+ /**
96
+ * Check whether an action should be allowed.
97
+ * Calls the ZKML classifier and returns a structured decision.
98
+ */
99
+ checkAction(tx: TransactionFeatures): Promise<ActionCheck>;
100
+ /**
101
+ * Check if a Bash command contains an on-chain transaction pattern.
102
+ * Returns the target address if found, null otherwise.
103
+ */
104
+ extractTarget(command: string): string | null;
105
+ /**
106
+ * Build a canUseTool callback for the Claude Agent SDK.
107
+ *
108
+ * Returns an async function that:
109
+ * - Auto-allows ObelyZK policy tools
110
+ * - Auto-allows safe read-only tools (Read, Glob, Grep)
111
+ * - Classifies Bash commands containing on-chain transactions
112
+ * - Blocks everything else
113
+ */
114
+ buildCanUseTool(): (tool: string, input: Record<string, unknown>) => Promise<{
115
+ approved: boolean;
116
+ reason?: string;
117
+ }>;
118
+ /**
119
+ * Get the MCP server configuration for .claude/settings.json
120
+ * or Claude Agent SDK's mcpServers option.
121
+ */
122
+ getMcpServerConfig(): Record<string, unknown>;
123
+ /**
124
+ * Get the list of allowed tools for Claude Agent SDK.
125
+ * Includes safe read-only tools and all ObelyZK policy tools.
126
+ */
127
+ getAllowedTools(): string[];
128
+ /** Get the underlying AgentFirewallSDK for advanced use. */
129
+ getSDK(): AgentFirewallSDK;
97
130
  }
98
131
 
99
132
  /**
100
- * AgentFirewallSDK ZKML-powered transaction guardrails for AI agents.
133
+ * CIRO Intelligence Client Runtime Enrichment
101
134
  *
102
- * Wraps the full flow:
103
- * 1. Classify transaction via prove-server (/api/v1/classify)
104
- * 2. Submit action to AgentFirewallZK contract
105
- * 3. Submit ZKML proof to ObelyskVerifier (streaming or recursive)
106
- * 4. Resolve action with proven threat score
107
- * 5. Query approval status
135
+ * Fetches real-time address risk, transaction enrichment, and alerts
136
+ * from CIRO's blockchain data lake. Used by the classifier to augment
137
+ * the 48-feature input with on-chain intelligence before classification.
108
138
  *
109
139
  * @example
110
140
  * ```typescript
111
- * import { AgentFirewallSDK } from '@obelyzk/sdk/firewall';
141
+ * import { CiroClient } from '@obelyzk/sdk/firewall';
112
142
  *
113
- * const firewall = new AgentFirewallSDK({
114
- * proverUrl: 'https://prover.bitsage.network',
115
- * firewallContract: '0x...',
116
- * verifierContract: '0x...',
117
- * rpcUrl: process.env.STARKNET_RPC!,
118
- * account: myAccount,
143
+ * const ciro = new CiroClient({
144
+ * baseUrl: 'https://ciro.bitsage.network',
145
+ * apiKey: process.env.CIRO_API_KEY!,
119
146
  * });
120
147
  *
121
- * const result = await firewall.evaluateAction({
122
- * target: '0x1234...',
148
+ * // Enrich a transaction before classification
149
+ * const enrichment = await ciro.enrichTransaction({
150
+ * target: '0x049d...',
123
151
  * value: '1000000000',
124
152
  * selector: '0xa9059cbb',
125
153
  * });
126
154
  *
127
- * if (result.decision === 'approve') {
128
- * // safe to execute
129
- * }
155
+ * // Check address risk
156
+ * const risk = await ciro.getAddressRisk('0x049d...');
157
+ * console.log(risk.riskLevel, risk.riskScore); // "LOW", 12
158
+ *
159
+ * // Get recent alerts
160
+ * const alerts = await ciro.getRecentAlerts({ severity: 'CRITICAL' });
130
161
  * ```
131
162
  */
132
-
133
- declare class AgentFirewallSDK {
134
- private config;
135
- private provider;
136
- constructor(config: FirewallConfig);
163
+ /** CIRO client configuration. */
164
+ interface CiroConfig {
165
+ /** CIRO Intelligence API base URL. */
166
+ baseUrl: string;
167
+ /** API key for authentication. */
168
+ apiKey: string;
169
+ /** Organization slug (default: "obelyzk"). */
170
+ org?: string;
171
+ /** Request timeout in ms (default: 10000). */
172
+ timeout?: number;
173
+ }
174
+ /** Address risk level. */
175
+ type RiskLevel = "clean" | "low" | "medium" | "high" | "critical" | "unknown";
176
+ /** Enrichment response from CIRO. */
177
+ interface EnrichmentResult {
178
+ targetRisk: RiskLevel;
179
+ targetRiskScore: number;
180
+ targetVerified: boolean;
181
+ targetIsProxy: boolean;
182
+ targetHasSource: boolean;
183
+ targetInteractionCount: number;
184
+ targetUniqueCallers: number;
185
+ targetFirstSeenBlocksAgo: number;
186
+ isSanctioned: boolean;
187
+ sanctionLists: string[];
188
+ fortaAlerts24h: number;
189
+ fortaSeverityMax: string | null;
190
+ senderTxFrequency: number;
191
+ senderUniqueTargets24h: number;
192
+ senderAvgValue24h: number;
193
+ senderMaxValue24h: number;
194
+ senderAgeBlocks: number;
195
+ dataFreshnessS: number;
196
+ enrichmentTimeMs: number;
197
+ }
198
+ /** Address risk assessment. */
199
+ interface AddressRisk {
200
+ address: string;
201
+ chain: string;
202
+ riskLevel: RiskLevel;
203
+ riskScore: number;
204
+ isContract: boolean;
205
+ isVerified: boolean;
206
+ isProxy: boolean;
207
+ isSanctioned: boolean;
208
+ sanctionLists: string[];
209
+ fortaAlertsCount: number;
210
+ knownExploitInvolvement: boolean;
211
+ exploitNames: string[];
212
+ totalTxCount: number;
213
+ clusterSize: number;
214
+ }
215
+ /** Alert from CIRO's detection pipeline. */
216
+ interface CiroAlert {
217
+ alertId: string;
218
+ source: string;
219
+ severity: string;
220
+ chain: string;
221
+ timestamp: string;
222
+ addresses: string[];
223
+ txHash: string | null;
224
+ name: string;
225
+ description: string;
226
+ }
227
+ /** Data lake statistics. */
228
+ interface DataLakeStats {
229
+ totalTransactions: number;
230
+ labeledTransactions: number;
231
+ labelDistribution: Record<string, number>;
232
+ lastUpdated: string;
233
+ fortaBotsActive: number;
234
+ addressesIndexed: number;
235
+ sanctionedAddresses: number;
236
+ }
237
+ declare class CiroClient {
238
+ private baseUrl;
239
+ private apiKey;
240
+ private org;
241
+ private timeout;
242
+ constructor(config: CiroConfig);
243
+ private get apiBase();
244
+ private request;
137
245
  /**
138
- * Classify a transaction through the ZKML classifier.
139
- *
140
- * Sends the transaction features to the prove-server, which runs
141
- * the MLP classifier and generates a GKR+STARK proof. Returns the
142
- * proven threat score and decision.
143
- *
144
- * Does NOT submit anything on-chain — use `evaluateAction()` for
145
- * the full flow including on-chain submission.
246
+ * Enrich a transaction with CIRO intelligence.
247
+ * Returns target risk, sanctions status, Forta alerts, and behavioral context.
248
+ */
249
+ enrichTransaction(params: {
250
+ target: string;
251
+ sender?: string;
252
+ value?: string;
253
+ selector?: string;
254
+ }): Promise<EnrichmentResult>;
255
+ /**
256
+ * Get risk assessment for a specific address.
257
+ */
258
+ getAddressRisk(address: string): Promise<AddressRisk>;
259
+ /**
260
+ * Get recent alerts from CIRO's detection pipeline.
146
261
  */
147
- classify(tx: TransactionFeatures): Promise<ClassifyResult>;
262
+ getRecentAlerts(params?: {
263
+ severity?: string;
264
+ limit?: number;
265
+ }): Promise<CiroAlert[]>;
148
266
  /**
149
- * Register a new agent on the firewall contract.
150
- * The calling account becomes the agent owner.
267
+ * Get data lake statistics.
151
268
  */
152
- registerAgent(agentId: string): Promise<string>;
153
- /** Deactivate an agent (owner or contract admin). */
154
- deactivateAgent(agentId: string): Promise<string>;
155
- /** Reactivate an agent and reset strikes (agent owner only). */
156
- reactivateAgent(agentId: string): Promise<string>;
157
- /** Get the full status of an agent. */
158
- getAgentStatus(agentId: string): Promise<AgentStatus>;
159
- /** Check if a specific action has been approved. */
160
- isActionApproved(actionId: number): Promise<boolean>;
161
- /** Check if an agent is trusted. */
162
- isAgentTrusted(agentId: string): Promise<boolean>;
163
- private requireAccount;
269
+ getStats(): Promise<DataLakeStats>;
164
270
  }
165
271
 
166
- export { AgentFirewallSDK, type AgentStatus, type ClassifyResult, type Decision, type FirewallConfig, type ResolveResult, type SubmitActionResult, type TransactionFeatures };
272
+ export { type ActionCheck, type AddressRisk, AgentFirewallSDK, type CiroAlert, CiroClient, type CiroConfig, type DataLakeStats, Decision, type EnrichmentResult, PolicyEnforcer, type PolicyEnforcerConfig, type RiskLevel, TransactionFeatures, createPolicyEnforcer };