@valiron/sdk 1.0.0 → 1.0.2

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 CHANGED
@@ -28,6 +28,12 @@ if (gate.allow) { /* serve the request */ }
28
28
  // One-line Express middleware — blocks untrusted agents automatically
29
29
  app.use("/api/paid", createValironGate({ sdk: valiron }));
30
30
 
31
+ // Optional: choose endpoint-specific trust signals
32
+ app.use("/api/paid", createValironGate({
33
+ sdk: valiron,
34
+ trustSignals: ["8004", "sandbox"], // Pro can add "world" and "icebreaker"
35
+ }));
36
+
31
37
  // Fastify, Next.js, and generic middleware also available
32
38
  // See SDK Reference for valironFastifyPlugin, createValironNextMiddleware, valironGateCheck
33
39
  ```
@@ -36,8 +42,9 @@ No API key required for read operations.
36
42
 
37
43
  ### Additional Features
38
44
 
45
+ - **Auto-Sandbox** — Middleware automatically evaluates new agents (on-chain and key-based) on their first gated request
39
46
  - **Proxy Gateway** (Pro) — Forward requests through Valiron's edge proxy with SSRF protection
40
- - **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected)
47
+ - **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected, auto-sandboxed)
41
48
  - **World ID** — Verify agent-human linkage via Worldcoin proof-of-personhood
42
49
  - **Telemetry** — Optional anonymous usage metrics (disable with `telemetry: { enabled: false }`)
43
50
 
package/dist/clients.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
1
+ import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
2
2
  /**
3
3
  * HTTP client for the Valiron Operator API.
4
4
  *
@@ -10,6 +10,7 @@ export declare class ValironClient {
10
10
  private apiKey?;
11
11
  private defaultChain?;
12
12
  private timeout;
13
+ private timeoutConfigured;
13
14
  private debug;
14
15
  private telemetry;
15
16
  constructor(config?: ValironConfig);
@@ -63,6 +64,17 @@ export declare class ValironClient {
63
64
  * `POST /operator/trigger-sandbox/:agentId`
64
65
  */
65
66
  triggerSandboxTest(agentId: string, options?: CallOptions): Promise<SandboxResult>;
67
+ /**
68
+ * Trigger sandbox testing for a key-based (web2) agent.
69
+ *
70
+ * Key agents have no on-chain endpoints, so this uses sandbox_relay mode:
71
+ * the agent interacts with the sandbox-api mock server, and its behavior
72
+ * is observed and scored. The result is written to Redis so subsequent
73
+ * `getKeyAgentProfile()` calls return a real score.
74
+ *
75
+ * `POST /operator/trigger-sandbox-key/:agentAddress`
76
+ */
77
+ triggerKeyAgentSandbox(agentAddress: string): Promise<KeyAgentSandboxResult>;
66
78
  /**
67
79
  * Trust gate — single call combining on-chain reputation + sandbox tests.
68
80
  *
@@ -140,8 +152,11 @@ export declare class ValironClient {
140
152
  getWorldIdProfile(agentId: string, options?: CallOptions): Promise<WorldIdAgentProfile>;
141
153
  /** Flush any pending telemetry events and clean up resources. */
142
154
  dispose(): Promise<void>;
155
+ /** Emit an SDK telemetry event from higher-level helpers. */
156
+ emitTelemetry(event: string, payload: Record<string, unknown>): void;
143
157
  private buildHeaders;
144
158
  private get;
145
159
  private post;
146
160
  private extractMethodName;
161
+ private getTimeoutForPath;
147
162
  }
package/dist/clients.js CHANGED
@@ -15,7 +15,8 @@ class ValironClient {
15
15
  config.endpoint || "https://valiron-edge-proxy.onrender.com";
16
16
  this.apiKey = config.apiKey;
17
17
  this.defaultChain = config.chain;
18
- this.timeout = config.timeout || 5000;
18
+ this.timeoutConfigured = config.timeout !== undefined;
19
+ this.timeout = config.timeout ?? 10000;
19
20
  this.debug = config.debug || false;
20
21
  this.telemetry = new telemetry_1.TelemetryClient(config.telemetry, this.endpoint);
21
22
  }
@@ -34,7 +35,10 @@ class ValironClient {
34
35
  */
35
36
  async getAgentProfile(agentId, options) {
36
37
  const chain = this.resolveChain(options);
37
- const profile = await this.get(`/operator/agent/${agentId}`, chain);
38
+ const query = options?.trustSignals?.length
39
+ ? `?trustSignals=${encodeURIComponent([...options.trustSignals].sort().join(","))}`
40
+ : "";
41
+ const profile = await this.get(`/operator/agent/${agentId}${query}`, chain);
38
42
  // Strip internal fields that the API returns but SDK consumers should not see
39
43
  if (profile?.localReputation) {
40
44
  delete profile.localReputation.metrics;
@@ -51,6 +55,10 @@ class ValironClient {
51
55
  has_onchain_feedback: totalFeedback > 0,
52
56
  feedback_count_bucket: feedbackBucket,
53
57
  avg_score_bucket: avgScoreBucket,
58
+ trust_signals: options?.trustSignals ? [...options.trustSignals].sort().join(",") : undefined,
59
+ trust_signal_count: options?.trustSignals?.length,
60
+ world_included: options?.trustSignals?.includes("world"),
61
+ icebreaker_included: options?.trustSignals?.includes("icebreaker"),
54
62
  });
55
63
  return profile;
56
64
  }
@@ -112,6 +120,24 @@ class ValironClient {
112
120
  delete result.mode;
113
121
  return result;
114
122
  }
123
+ /**
124
+ * Trigger sandbox testing for a key-based (web2) agent.
125
+ *
126
+ * Key agents have no on-chain endpoints, so this uses sandbox_relay mode:
127
+ * the agent interacts with the sandbox-api mock server, and its behavior
128
+ * is observed and scored. The result is written to Redis so subsequent
129
+ * `getKeyAgentProfile()` calls return a real score.
130
+ *
131
+ * `POST /operator/trigger-sandbox-key/:agentAddress`
132
+ */
133
+ async triggerKeyAgentSandbox(agentAddress) {
134
+ const result = await this.post(`/operator/trigger-sandbox-key/${agentAddress}`);
135
+ // Strip internal behavioral metrics and execution details
136
+ delete result.metrics;
137
+ delete result.testSummary;
138
+ delete result.mode;
139
+ return result;
140
+ }
115
141
  /**
116
142
  * Trust gate — single call combining on-chain reputation + sandbox tests.
117
143
  *
@@ -197,6 +223,10 @@ class ValironClient {
197
223
  async dispose() {
198
224
  await this.telemetry.dispose();
199
225
  }
226
+ /** Emit an SDK telemetry event from higher-level helpers. */
227
+ emitTelemetry(event, payload) {
228
+ this.telemetry.emit(event, payload);
229
+ }
200
230
  // ─── HTTP helpers ───────────────────────────────────────────────────────
201
231
  buildHeaders() {
202
232
  const headers = {
@@ -215,7 +245,8 @@ class ValironClient {
215
245
  console.log(`[Valiron SDK] GET ${url.toString()}`);
216
246
  }
217
247
  const controller = new AbortController();
218
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
248
+ const timeoutMs = this.getTimeoutForPath(path);
249
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
219
250
  const start = Date.now();
220
251
  try {
221
252
  const response = await fetch(url.toString(), {
@@ -274,9 +305,10 @@ class ValironClient {
274
305
  retries: 0,
275
306
  timeout_count: 1,
276
307
  abort_count: 1,
308
+ timeout_ms: timeoutMs,
277
309
  });
278
310
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
279
- throw new types_1.ValironError(`Request timeout after ${this.timeout}ms`, "TIMEOUT_ERROR");
311
+ throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
280
312
  }
281
313
  if (error instanceof types_1.ValironError)
282
314
  throw error;
@@ -302,7 +334,8 @@ class ValironClient {
302
334
  console.log(`[Valiron SDK] POST ${url.toString()}`, body);
303
335
  }
304
336
  const controller = new AbortController();
305
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
337
+ const timeoutMs = this.getTimeoutForPath(path);
338
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
306
339
  const start = Date.now();
307
340
  try {
308
341
  const headers = this.buildHeaders();
@@ -366,9 +399,10 @@ class ValironClient {
366
399
  retries: 0,
367
400
  timeout_count: 1,
368
401
  abort_count: 1,
402
+ timeout_ms: timeoutMs,
369
403
  });
370
404
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
371
- throw new types_1.ValironError(`Request timeout after ${this.timeout}ms`, "TIMEOUT_ERROR");
405
+ throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
372
406
  }
373
407
  if (error instanceof types_1.ValironError)
374
408
  throw error;
@@ -407,5 +441,16 @@ class ValironClient {
407
441
  return "keyAgent";
408
442
  return "unknown";
409
443
  }
444
+ getTimeoutForPath(path) {
445
+ if (this.timeoutConfigured)
446
+ return this.timeout;
447
+ if (path.startsWith("/operator/trigger-sandbox/"))
448
+ return 30000;
449
+ if (path.startsWith("/operator/gate/"))
450
+ return 15000;
451
+ if (path.startsWith("/proxy/"))
452
+ return 15000;
453
+ return this.timeout;
454
+ }
410
455
  }
411
456
  exports.ValironClient = ValironClient;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, GateResult, GateOptions, RouteDecision, KeyAgentProfile, KeyAgentChallenge, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
1
+ import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, RouteDecision, KeyAgentProfile, KeyAgentChallenge, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
2
2
  /**
3
3
  * Valiron SDK – Official TypeScript SDK for the Trust Layer for Agentic Economy
4
4
  *
@@ -166,6 +166,24 @@ export declare class ValironSDK {
166
166
  * ```
167
167
  */
168
168
  triggerSandboxTest(agentId: string, options?: CallOptions): Promise<SandboxResult>;
169
+ /**
170
+ * Trigger sandbox testing for a key-based (web2) agent.
171
+ *
172
+ * Key agents have no on-chain endpoints, so this uses sandbox_relay mode.
173
+ * The result is written to Redis so subsequent `getKeyAgentProfile()` calls
174
+ * return a real score.
175
+ *
176
+ * @param agentAddress - The key agent's Ethereum address
177
+ * @returns Sandbox test results including score and tier
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * const result = await valiron.triggerKeyAgentSandbox('0xabc...');
182
+ * console.log(result.valironScore); // 82
183
+ * console.log(result.tier); // 'A'
184
+ * ```
185
+ */
186
+ triggerKeyAgentSandbox(agentAddress: string): Promise<KeyAgentSandboxResult>;
169
187
  /**
170
188
  * Trust gate — checks an agent by combining on-chain reputation with
171
189
  * sandbox behavioral tests and returns a single allow/deny decision.
@@ -357,6 +375,8 @@ export declare class ValironSDK {
357
375
  * ```
358
376
  */
359
377
  dispose(): Promise<void>;
378
+ /** @internal Emit Valiron SDK telemetry from helper modules. */
379
+ emitTelemetry(event: string, payload: Record<string, unknown>): void;
360
380
  }
361
381
  export * from "./types";
362
382
  export { ValironClient } from "./clients";
package/dist/index.js CHANGED
@@ -197,6 +197,26 @@ class ValironSDK {
197
197
  async triggerSandboxTest(agentId, options) {
198
198
  return this.client.triggerSandboxTest(agentId, options);
199
199
  }
200
+ /**
201
+ * Trigger sandbox testing for a key-based (web2) agent.
202
+ *
203
+ * Key agents have no on-chain endpoints, so this uses sandbox_relay mode.
204
+ * The result is written to Redis so subsequent `getKeyAgentProfile()` calls
205
+ * return a real score.
206
+ *
207
+ * @param agentAddress - The key agent's Ethereum address
208
+ * @returns Sandbox test results including score and tier
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * const result = await valiron.triggerKeyAgentSandbox('0xabc...');
213
+ * console.log(result.valironScore); // 82
214
+ * console.log(result.tier); // 'A'
215
+ * ```
216
+ */
217
+ async triggerKeyAgentSandbox(agentAddress) {
218
+ return this.client.triggerKeyAgentSandbox(agentAddress);
219
+ }
200
220
  /**
201
221
  * Trust gate — checks an agent by combining on-chain reputation with
202
222
  * sandbox behavioral tests and returns a single allow/deny decision.
@@ -391,6 +411,10 @@ class ValironSDK {
391
411
  dispose() {
392
412
  return this.client.dispose();
393
413
  }
414
+ /** @internal Emit Valiron SDK telemetry from helper modules. */
415
+ emitTelemetry(event, payload) {
416
+ this.client.emitTelemetry(event, payload);
417
+ }
394
418
  }
395
419
  exports.ValironSDK = ValironSDK;
396
420
  // Re-export everything
@@ -1,5 +1,5 @@
1
1
  import type { ValironSDK } from "./index";
2
- import type { GateResult } from "./types";
2
+ import type { GateResult, TrustSignal } from "./types";
3
3
  /**
4
4
  * Configuration for the Valiron trust gate middleware.
5
5
  *
@@ -23,8 +23,19 @@ export interface ValironGateConfig {
23
23
  extractAgentAddress?: (req: any) => string | null;
24
24
  /** Minimum Valiron score to allow (default: 65). */
25
25
  minScore?: number;
26
- /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
27
- ttlMs?: number;
26
+ /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
27
+ trustSignals?: TrustSignal[];
28
+ /**
29
+ * Client-side profile cache TTL in ms.
30
+ *
31
+ * When set, caches `getAgentProfile()` results in memory for this duration.
32
+ * This is important for protocols like x402 that make multiple requests
33
+ * per payment (discover → retry with payment) — without caching, the
34
+ * second request can fail due to cold-start latency on the edge proxy.
35
+ *
36
+ * Set to `0` to disable. Default: `30_000` (30 seconds).
37
+ */
38
+ cacheTtlMs?: number;
28
39
  /** Custom handler when an agent is denied. If provided, must send a response. */
29
40
  onDeny?: (req: any, res: any, result: GateResult) => void;
30
41
  /** Hook called after an agent is allowed — runs before next(). */
@@ -38,6 +49,11 @@ export interface ValironGateConfig {
38
49
  * On deny: returns 403 with the gate result (or delegates to `onDeny`).
39
50
  * On error: returns 503 (fail-closed).
40
51
  *
52
+ * **Express 4 compatibility**: The returned middleware wraps the async
53
+ * gate check with `Promise.resolve().catch(next)` so that unhandled
54
+ * rejections are forwarded to Express's error handler instead of causing
55
+ * silent failures. Express 4 does not natively `await` async middleware.
56
+ *
41
57
  * @example
42
58
  * ```typescript
43
59
  * import { ValironSDK, createValironGate } from '@valiron/sdk';
@@ -45,18 +61,18 @@ export interface ValironGateConfig {
45
61
  * const valiron = new ValironSDK({ chain: 'monad' });
46
62
  *
47
63
  * // Apply before your x402 / payment handler
48
- * Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
64
+ * // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
49
65
  * app.use('/api/paid', createValironGate({ sdk: valiron }));
50
66
  *
51
- * // Custom threshold
67
+ * // Custom threshold + cache TTL
52
68
  * app.use('/api/premium', createValironGate({
53
69
  * sdk: valiron,
54
70
  * minScore: 85,
55
- * ttlMs: 3600_000, // re-test every hour
71
+ * cacheTtlMs: 60_000, // 60s client-side cache
56
72
  * }));
57
73
  * ```
58
74
  */
59
- export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) => Promise<any>;
75
+ export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) => void;
60
76
  /**
61
77
  * Configuration for the Fastify Valiron trust gate plugin.
62
78
  */
@@ -75,8 +91,13 @@ export interface ValironFastifyConfig {
75
91
  extractAgentAddress?: (req: any) => string | null;
76
92
  /** Minimum Valiron score to allow (default: 65). */
77
93
  minScore?: number;
78
- /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
79
- ttlMs?: number;
94
+ /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
95
+ trustSignals?: TrustSignal[];
96
+ /**
97
+ * Client-side profile cache TTL in ms (default: 30000).
98
+ * Set to `0` to disable.
99
+ */
100
+ cacheTtlMs?: number;
80
101
  /** Custom handler when an agent is denied. If provided, must send a response. */
81
102
  onDeny?: (req: any, reply: any, result: GateResult) => void;
82
103
  /** Hook called after an agent is allowed. */
@@ -133,8 +154,13 @@ export interface ValironNextConfig {
133
154
  extractAgentAddress?: (req: Request) => string | null;
134
155
  /** Minimum Valiron score to allow (default: 65). */
135
156
  minScore?: number;
136
- /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
137
- ttlMs?: number;
157
+ /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
158
+ trustSignals?: TrustSignal[];
159
+ /**
160
+ * Client-side profile cache TTL in ms (default: 30000).
161
+ * Set to `0` to disable.
162
+ */
163
+ cacheTtlMs?: number;
138
164
  /**
139
165
  * URL path patterns to gate. Uses `startsWith` matching.
140
166
  * If omitted, gates all routes.
@@ -189,6 +215,12 @@ export interface ValironGateCheckResult {
189
215
  status: number;
190
216
  /** Suggested JSON body if the request should be blocked. Undefined if allowed. */
191
217
  body?: Record<string, unknown>;
218
+ /**
219
+ * True when the agent is brand-new (on-chain identity, zero reputation).
220
+ * A sandbox evaluation has been triggered in the background.
221
+ * The caller should tell the agent to retry after `retryAfterMs`.
222
+ */
223
+ pendingEvaluation?: boolean;
192
224
  }
193
225
  /**
194
226
  * Framework-agnostic gate check. Returns a structured result that you
@@ -238,5 +270,11 @@ export declare function valironGateCheck(sdk: ValironSDK, opts: {
238
270
  /** Key-based agent hash (web2). Checked if agentId is not provided. */
239
271
  agentAddress?: string | null;
240
272
  minScore?: number;
241
- ttlMs?: number;
273
+ /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
274
+ trustSignals?: TrustSignal[];
275
+ /**
276
+ * Client-side profile cache TTL in ms (default: 30000).
277
+ * Set to `0` to disable.
278
+ */
279
+ cacheTtlMs?: number;
242
280
  }): Promise<ValironGateCheckResult>;