@valiron/sdk 0.12.0 → 1.0.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.
@@ -6,7 +6,7 @@ import type { GateResult } from "./types";
6
6
  * Supports both on-chain (ERC-8004/Solana) and key-based (web2) agents.
7
7
  * Auto-detects agent type from request headers:
8
8
  * - `x-agent-id` → on-chain gate
9
- * - `x-agent-key-hash` → key-based profile lookup
9
+ * - `x-agent-address` (or legacy `x-agent-key-hash`) → key-based profile lookup
10
10
  */
11
11
  export interface ValironGateConfig {
12
12
  /** Configured ValironSDK instance. */
@@ -17,14 +17,23 @@ export interface ValironGateConfig {
17
17
  */
18
18
  extractAgentId?: (req: any) => string | null;
19
19
  /**
20
- * Extract the key-based agent hash from an incoming request.
21
- * Defaults to reading `x-agent-key-hash` header.
20
+ * Extract the key-based agent address from an incoming request.
21
+ * Defaults to reading `x-agent-address` header (falls back to `x-agent-key-hash`).
22
22
  */
23
- extractAgentKeyHash?: (req: any) => string | null;
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
+ /**
27
+ * Client-side profile cache TTL in ms.
28
+ *
29
+ * When set, caches `getAgentProfile()` results in memory for this duration.
30
+ * This is important for protocols like x402 that make multiple requests
31
+ * per payment (discover → retry with payment) — without caching, the
32
+ * second request can fail due to cold-start latency on the edge proxy.
33
+ *
34
+ * Set to `0` to disable. Default: `30_000` (30 seconds).
35
+ */
36
+ cacheTtlMs?: number;
28
37
  /** Custom handler when an agent is denied. If provided, must send a response. */
29
38
  onDeny?: (req: any, res: any, result: GateResult) => void;
30
39
  /** Hook called after an agent is allowed — runs before next(). */
@@ -38,6 +47,11 @@ export interface ValironGateConfig {
38
47
  * On deny: returns 403 with the gate result (or delegates to `onDeny`).
39
48
  * On error: returns 503 (fail-closed).
40
49
  *
50
+ * **Express 4 compatibility**: The returned middleware wraps the async
51
+ * gate check with `Promise.resolve().catch(next)` so that unhandled
52
+ * rejections are forwarded to Express's error handler instead of causing
53
+ * silent failures. Express 4 does not natively `await` async middleware.
54
+ *
41
55
  * @example
42
56
  * ```typescript
43
57
  * import { ValironSDK, createValironGate } from '@valiron/sdk';
@@ -45,18 +59,18 @@ export interface ValironGateConfig {
45
59
  * const valiron = new ValironSDK({ chain: 'monad' });
46
60
  *
47
61
  * // Apply before your x402 / payment handler
48
- * // Works with both on-chain (x-agent-id) and key-based (x-agent-key-hash) agents
62
+ * // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
49
63
  * app.use('/api/paid', createValironGate({ sdk: valiron }));
50
64
  *
51
- * // Custom threshold
65
+ * // Custom threshold + cache TTL
52
66
  * app.use('/api/premium', createValironGate({
53
67
  * sdk: valiron,
54
68
  * minScore: 85,
55
- * ttlMs: 3600_000, // re-test every hour
69
+ * cacheTtlMs: 60_000, // 60s client-side cache
56
70
  * }));
57
71
  * ```
58
72
  */
59
- export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) => Promise<any>;
73
+ export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) => void;
60
74
  /**
61
75
  * Configuration for the Fastify Valiron trust gate plugin.
62
76
  */
@@ -69,14 +83,17 @@ export interface ValironFastifyConfig {
69
83
  */
70
84
  extractAgentId?: (req: any) => string | null;
71
85
  /**
72
- * Extract the key-based agent hash from a Fastify request.
73
- * Defaults to reading `x-agent-key-hash` header.
86
+ * Extract the key-based agent address from a Fastify request.
87
+ * Defaults to reading `x-agent-address` header (falls back to `x-agent-key-hash`).
74
88
  */
75
- extractAgentKeyHash?: (req: any) => string | null;
89
+ extractAgentAddress?: (req: any) => string | null;
76
90
  /** Minimum Valiron score to allow (default: 65). */
77
91
  minScore?: number;
78
- /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
79
- ttlMs?: number;
92
+ /**
93
+ * Client-side profile cache TTL in ms (default: 30000).
94
+ * Set to `0` to disable.
95
+ */
96
+ cacheTtlMs?: number;
80
97
  /** Custom handler when an agent is denied. If provided, must send a response. */
81
98
  onDeny?: (req: any, reply: any, result: GateResult) => void;
82
99
  /** Hook called after an agent is allowed. */
@@ -127,14 +144,17 @@ export interface ValironNextConfig {
127
144
  */
128
145
  extractAgentId?: (req: Request) => string | null;
129
146
  /**
130
- * Extract the key-based agent hash from a Next.js request.
131
- * Defaults to reading `x-agent-key-hash` header.
147
+ * Extract the key-based agent address from a Next.js request.
148
+ * Defaults to reading `x-agent-address` header (falls back to `x-agent-key-hash`).
132
149
  */
133
- extractAgentKeyHash?: (req: Request) => string | null;
150
+ extractAgentAddress?: (req: Request) => string | null;
134
151
  /** Minimum Valiron score to allow (default: 65). */
135
152
  minScore?: number;
136
- /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
137
- ttlMs?: number;
153
+ /**
154
+ * Client-side profile cache TTL in ms (default: 30000).
155
+ * Set to `0` to disable.
156
+ */
157
+ cacheTtlMs?: number;
138
158
  /**
139
159
  * URL path patterns to gate. Uses `startsWith` matching.
140
160
  * If omitted, gates all routes.
@@ -189,6 +209,12 @@ export interface ValironGateCheckResult {
189
209
  status: number;
190
210
  /** Suggested JSON body if the request should be blocked. Undefined if allowed. */
191
211
  body?: Record<string, unknown>;
212
+ /**
213
+ * True when the agent is brand-new (on-chain identity, zero reputation).
214
+ * A sandbox evaluation has been triggered in the background.
215
+ * The caller should tell the agent to retry after `retryAfterMs`.
216
+ */
217
+ pendingEvaluation?: boolean;
192
218
  }
193
219
  /**
194
220
  * Framework-agnostic gate check. Returns a structured result that you
@@ -206,7 +232,7 @@ export interface ValironGateCheckResult {
206
232
  * app.use('/api/*', async (c, next) => {
207
233
  * const gate = await valironGateCheck(valiron, {
208
234
  * agentId: c.req.header('x-agent-id') ?? null,
209
- * agentKeyHash: c.req.header('x-agent-key-hash') ?? null,
235
+ * agentAddress: c.req.header('x-agent-address') ?? null,
210
236
  * });
211
237
  * if (!gate.allow) return c.json(gate.body, gate.status);
212
238
  * c.set('valiron', gate.result);
@@ -220,7 +246,7 @@ export interface ValironGateCheckResult {
220
246
  * app.use(async (ctx, next) => {
221
247
  * const gate = await valironGateCheck(valiron, {
222
248
  * agentId: ctx.get('x-agent-id') || null,
223
- * agentKeyHash: ctx.get('x-agent-key-hash') || null,
249
+ * agentAddress: ctx.get('x-agent-address') || null,
224
250
  * });
225
251
  * if (!gate.allow) {
226
252
  * ctx.status = gate.status;
@@ -236,7 +262,11 @@ export declare function valironGateCheck(sdk: ValironSDK, opts: {
236
262
  /** On-chain agent ID (ERC-8004 / Solana). */
237
263
  agentId?: string | null;
238
264
  /** Key-based agent hash (web2). Checked if agentId is not provided. */
239
- agentKeyHash?: string | null;
265
+ agentAddress?: string | null;
240
266
  minScore?: number;
241
- ttlMs?: number;
267
+ /**
268
+ * Client-side profile cache TTL in ms (default: 30000).
269
+ * Set to `0` to disable.
270
+ */
271
+ cacheTtlMs?: number;
242
272
  }): Promise<ValironGateCheckResult>;
@@ -20,8 +20,47 @@ function extractHeader(req, name) {
20
20
  function defaultExtractAgentId(req) {
21
21
  return extractHeader(req, "x-agent-id");
22
22
  }
23
- function defaultExtractAgentKeyHash(req) {
24
- return extractHeader(req, "x-agent-key-hash");
23
+ function defaultExtractAgentAddress(req) {
24
+ return extractHeader(req, "x-agent-address") || extractHeader(req, "x-agent-key-hash");
25
+ }
26
+ /**
27
+ * Convert an AgentProfile (from the public `/operator/agent/` endpoint)
28
+ * into a GateResult, computing the allow/deny decision client-side.
29
+ *
30
+ * **Allow logic**: The primary signal is `routing.finalRoute` — if the
31
+ * operator API routes the agent to `prod` or `prod_throttled`, the agent
32
+ * is allowed. The `minScore` acts as an *additional* override: even if
33
+ * the route is production-eligible, an operator can block agents below
34
+ * their score threshold. This prevents incorrectly denying agents that
35
+ * the API has already routed to production via World ID, behavioral
36
+ * reputation upgrades, or other trust signals beyond raw on-chain score.
37
+ *
38
+ * The `score` field uses `localReputation.score` when available (the
39
+ * combined trust score factoring in sandbox, World ID, Icebreaker),
40
+ * falling back to `onchainReputation.averageScore` for backward compat.
41
+ */
42
+ function profileToGateResult(profile, minScore) {
43
+ // Prefer the combined trust score (localReputation.score) over raw on-chain avg
44
+ const score = profile.localReputation?.score ??
45
+ profile.onchainReputation?.averageScore ??
46
+ 0;
47
+ const route = profile.routing?.finalRoute ?? "sandbox_only";
48
+ const tier = (profile.localReputation?.tier ?? "C");
49
+ const riskLevel = (profile.localReputation?.riskLevel ?? "RED");
50
+ const isProductionRoute = route === "prod" || route === "prod_throttled";
51
+ const allow = isProductionRoute && score >= minScore;
52
+ return {
53
+ allow,
54
+ score,
55
+ tier,
56
+ riskLevel,
57
+ route,
58
+ agentId: profile.agentId,
59
+ wallet: profile.identity?.wallet ?? "",
60
+ chain: profile.chain,
61
+ sandboxRan: false,
62
+ cached: false,
63
+ };
25
64
  }
26
65
  /**
27
66
  * Normalize a KeyAgentProfile into a GateResult so all middleware
@@ -39,7 +78,7 @@ function keyProfileToGateResult(profile, minScore) {
39
78
  tier,
40
79
  riskLevel,
41
80
  route,
42
- agentId: profile.agentKeyHash,
81
+ agentId: profile.agentAddress,
43
82
  wallet: "",
44
83
  chain: {
45
84
  network: "web2",
@@ -51,33 +90,115 @@ function keyProfileToGateResult(profile, minScore) {
51
90
  cached: true,
52
91
  };
53
92
  }
54
- async function runGateCheck(config, req) {
93
+ const DEFAULT_CACHE_TTL_MS = 30000;
94
+ const MAX_CACHE_SIZE = 1000;
95
+ /**
96
+ * Per-instance profile cache. Each `createValironGate()` /
97
+ * `createValironNextMiddleware()` call gets its own Map so that
98
+ * different SDK instances (potentially on different chains) don't
99
+ * share cached results.
100
+ */
101
+ function createProfileCache() {
102
+ const cache = new Map();
103
+ function getCached(agentId, ttl) {
104
+ const entry = cache.get(agentId);
105
+ if (!entry)
106
+ return null;
107
+ if (Date.now() - entry.ts > ttl) {
108
+ cache.delete(agentId);
109
+ return null;
110
+ }
111
+ return { result: { ...entry.result, cached: true }, pendingEvaluation: entry.pendingEvaluation };
112
+ }
113
+ function setCache(agentId, result, pendingEvaluation) {
114
+ // Don't cache pending evaluation results — the next request should
115
+ // re-fetch the profile to see if evaluation has completed.
116
+ if (pendingEvaluation)
117
+ return;
118
+ // Evict oldest entries when cache exceeds max size
119
+ if (cache.size >= MAX_CACHE_SIZE) {
120
+ const firstKey = cache.keys().next().value;
121
+ if (firstKey !== undefined)
122
+ cache.delete(firstKey);
123
+ }
124
+ cache.set(agentId, { result, ts: Date.now() });
125
+ }
126
+ return { getCached, setCache };
127
+ }
128
+ /**
129
+ * Per-SDK cache for `valironGateCheck()`. Uses a WeakMap so caches
130
+ * are garbage-collected when the SDK instance is no longer referenced.
131
+ */
132
+ const gateCheckCaches = new WeakMap();
133
+ function getGateCheckCache(sdk) {
134
+ let cache = gateCheckCaches.get(sdk);
135
+ if (!cache) {
136
+ cache = createProfileCache();
137
+ gateCheckCaches.set(sdk, cache);
138
+ }
139
+ return cache;
140
+ }
141
+ async function runGateCheck(config, req, cache) {
142
+ const minScore = config.minScore ?? 65;
143
+ const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
55
144
  // 1. Try on-chain agent ID (ERC-8004 / Solana)
56
145
  const extractAgentId = config.extractAgentId || defaultExtractAgentId;
57
146
  const agentId = extractAgentId(req);
58
147
  if (agentId) {
148
+ // Check client-side cache first
149
+ if (cacheTtl > 0) {
150
+ const cached = cache.getCached(agentId, cacheTtl);
151
+ if (cached)
152
+ return { agentId, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
153
+ }
59
154
  try {
60
- const result = await config.sdk.gate(agentId, {
61
- minScore: config.minScore,
62
- ttlMs: config.ttlMs,
63
- });
64
- return { agentId, result };
155
+ // Use getAgentProfile() which hits the PUBLIC /operator/agent/ endpoint.
156
+ // The old gate() call used POST /operator/gate/ which is protected by
157
+ // agent challenge-response auth and fails from server contexts.
158
+ const profile = await config.sdk.getAgentProfile(agentId);
159
+ const result = profileToGateResult(profile, minScore);
160
+ // Detect brand-new agent: on-chain identity exists but zero reputation.
161
+ // Trigger a sandbox evaluation so the agent can build a score.
162
+ // The result is cached normally — when the cache expires the next
163
+ // request will re-fetch the profile, which should now have a score.
164
+ const isNewAgent = !result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0;
165
+ if (isNewAgent) {
166
+ // Fire-and-forget — don't block the response on sandbox completion
167
+ config.sdk.triggerSandboxTest(agentId).catch(() => { });
168
+ }
169
+ if (cacheTtl > 0)
170
+ cache.setCache(agentId, result, isNewAgent || undefined);
171
+ return { agentId, result, pendingEvaluation: isNewAgent || undefined };
65
172
  }
66
173
  catch (error) {
67
174
  return { agentId, error };
68
175
  }
69
176
  }
70
177
  // 2. Fall back to key-based agent (web2)
71
- const extractKeyHash = config.extractAgentKeyHash || defaultExtractAgentKeyHash;
72
- const keyHash = extractKeyHash(req);
73
- if (keyHash) {
178
+ const extractAddress = config.extractAgentAddress || defaultExtractAgentAddress;
179
+ const agentAddr = extractAddress(req);
180
+ if (agentAddr) {
181
+ // Check client-side cache first
182
+ if (cacheTtl > 0) {
183
+ const cached = cache.getCached(agentAddr, cacheTtl);
184
+ if (cached)
185
+ return { agentId: agentAddr, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
186
+ }
74
187
  try {
75
- const profile = await config.sdk.getKeyAgentProfile(keyHash);
76
- const result = keyProfileToGateResult(profile, config.minScore ?? 65);
77
- return { agentId: keyHash, result };
188
+ const profile = await config.sdk.getKeyAgentProfile(agentAddr);
189
+ const result = keyProfileToGateResult(profile, minScore);
190
+ // Detect brand-new key agent: verified but never scored.
191
+ // Trigger a sandbox evaluation so the agent can build a score.
192
+ const isNewKeyAgent = !result.allow && profile.verified && profile.score == null;
193
+ if (isNewKeyAgent && typeof config.sdk.triggerKeyAgentSandbox === "function") {
194
+ config.sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
195
+ }
196
+ if (cacheTtl > 0)
197
+ cache.setCache(agentAddr, result, isNewKeyAgent || undefined);
198
+ return { agentId: agentAddr, result, pendingEvaluation: isNewKeyAgent || undefined };
78
199
  }
79
200
  catch (error) {
80
- return { agentId: keyHash, error };
201
+ return { agentId: agentAddr, error };
81
202
  }
82
203
  }
83
204
  // 3. No agent identity found
@@ -94,6 +215,11 @@ async function runGateCheck(config, req) {
94
215
  * On deny: returns 403 with the gate result (or delegates to `onDeny`).
95
216
  * On error: returns 503 (fail-closed).
96
217
  *
218
+ * **Express 4 compatibility**: The returned middleware wraps the async
219
+ * gate check with `Promise.resolve().catch(next)` so that unhandled
220
+ * rejections are forwarded to Express's error handler instead of causing
221
+ * silent failures. Express 4 does not natively `await` async middleware.
222
+ *
97
223
  * @example
98
224
  * ```typescript
99
225
  * import { ValironSDK, createValironGate } from '@valiron/sdk';
@@ -101,14 +227,14 @@ async function runGateCheck(config, req) {
101
227
  * const valiron = new ValironSDK({ chain: 'monad' });
102
228
  *
103
229
  * // Apply before your x402 / payment handler
104
- * // Works with both on-chain (x-agent-id) and key-based (x-agent-key-hash) agents
230
+ * // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
105
231
  * app.use('/api/paid', createValironGate({ sdk: valiron }));
106
232
  *
107
- * // Custom threshold
233
+ * // Custom threshold + cache TTL
108
234
  * app.use('/api/premium', createValironGate({
109
235
  * sdk: valiron,
110
236
  * minScore: 85,
111
- * ttlMs: 3600_000, // re-test every hour
237
+ * cacheTtlMs: 60_000, // 60s client-side cache
112
238
  * }));
113
239
  * ```
114
240
  */
@@ -116,10 +242,15 @@ function createValironGate(config) {
116
242
  // Snapshot config at creation time so mutations after middleware
117
243
  // creation don't affect behavior.
118
244
  const frozen = { ...config };
119
- return async function valironGate(req, res, next) {
120
- const { agentId, result, error } = await runGateCheck(frozen, req);
245
+ const cache = createProfileCache();
246
+ async function valironGateHandler(req, res, next) {
247
+ const { agentId, result, error, pendingEvaluation } = await runGateCheck(frozen, req, cache);
121
248
  if (!agentId) {
122
- return res.status(401).json({ error: "Missing agent identity (provide x-agent-id or x-agent-key-hash header)" });
249
+ return res.status(401).json({
250
+ error: "Missing agent identity",
251
+ message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
252
+ identitySkill: "https://valiron.co/auth.md",
253
+ });
123
254
  }
124
255
  if (error) {
125
256
  return res.status(503).json({
@@ -132,6 +263,15 @@ function createValironGate(config) {
132
263
  config.onAllow(req, result);
133
264
  return next();
134
265
  }
266
+ // New agent with no reputation — sandbox test triggered in background
267
+ if (pendingEvaluation) {
268
+ return res.status(403).json({
269
+ error: "Agent pending evaluation",
270
+ message: "This agent was recently registered and is being evaluated. Retry shortly.",
271
+ retryAfterMs: 30000,
272
+ ...result,
273
+ });
274
+ }
135
275
  if (config.onDeny) {
136
276
  return config.onDeny(req, res, result);
137
277
  }
@@ -139,6 +279,14 @@ function createValironGate(config) {
139
279
  error: "Agent blocked by Valiron trust gate",
140
280
  ...result,
141
281
  });
282
+ }
283
+ // Wrap with Promise.catch(next) for Express 4 async safety.
284
+ // Express 4 does NOT await async middleware, so without this wrapper
285
+ // an unhandled rejection would silently hang the request. This also
286
+ // prevents race conditions when chained with other async middleware
287
+ // (e.g. x402's paymentMiddleware running before the gate resolves).
288
+ return function valironGate(req, res, next) {
289
+ Promise.resolve(valironGateHandler(req, res, next)).catch(next);
142
290
  };
143
291
  }
144
292
  /**
@@ -172,11 +320,12 @@ async function valironFastifyPlugin(fastify, opts) {
172
320
  const gateConfig = {
173
321
  sdk: opts.sdk,
174
322
  extractAgentId: opts.extractAgentId,
175
- extractAgentKeyHash: opts.extractAgentKeyHash,
323
+ extractAgentAddress: opts.extractAgentAddress,
176
324
  minScore: opts.minScore,
177
- ttlMs: opts.ttlMs,
325
+ cacheTtlMs: opts.cacheTtlMs,
178
326
  onAllow: opts.onAllow,
179
327
  };
328
+ const cache = createProfileCache();
180
329
  // Decorate request with valiron property
181
330
  if (!fastify.hasRequestDecorator?.("valiron")) {
182
331
  fastify.decorateRequest("valiron", null);
@@ -192,9 +341,13 @@ async function valironFastifyPlugin(fastify, opts) {
192
341
  if (pathname !== prefix && !pathname.startsWith(prefix + "/"))
193
342
  return;
194
343
  }
195
- const { agentId, result, error } = await runGateCheck(gateConfig, request);
344
+ const { agentId, result, error, pendingEvaluation } = await runGateCheck(gateConfig, request, cache);
196
345
  if (!agentId) {
197
- return reply.status(401).send({ error: "Missing agent identity (provide x-agent-id or x-agent-key-hash header)" });
346
+ return reply.status(401).send({
347
+ error: "Missing agent identity",
348
+ message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
349
+ identitySkill: "https://valiron.co/auth.md",
350
+ });
198
351
  }
199
352
  if (error) {
200
353
  return reply.status(503).send({
@@ -207,6 +360,15 @@ async function valironFastifyPlugin(fastify, opts) {
207
360
  opts.onAllow(request, result);
208
361
  return; // continue to handler
209
362
  }
363
+ // New agent with no reputation — sandbox test triggered in background
364
+ if (pendingEvaluation) {
365
+ return reply.status(403).send({
366
+ error: "Agent pending evaluation",
367
+ message: "This agent was recently registered and is being evaluated. Retry shortly.",
368
+ retryAfterMs: 30000,
369
+ ...result,
370
+ });
371
+ }
210
372
  if (opts.onDeny) {
211
373
  return opts.onDeny(request, reply, result);
212
374
  }
@@ -244,11 +406,12 @@ async function valironFastifyPlugin(fastify, opts) {
244
406
  * ```
245
407
  */
246
408
  function createValironNextMiddleware(config) {
247
- const { sdk, minScore, ttlMs, paths } = config;
409
+ const { sdk, minScore, paths } = config;
410
+ const cache = createProfileCache();
248
411
  const extractAgentId = config.extractAgentId ||
249
412
  ((req) => req.headers.get("x-agent-id"));
250
- const extractKeyHash = config.extractAgentKeyHash ||
251
- ((req) => req.headers.get("x-agent-key-hash"));
413
+ const extractAddress = config.extractAgentAddress ||
414
+ ((req) => req.headers.get("x-agent-address") || req.headers.get("x-agent-key-hash"));
252
415
  return async function valironNextGate(request) {
253
416
  // Skip paths not in scope
254
417
  if (paths && paths.length > 0) {
@@ -257,24 +420,64 @@ function createValironNextMiddleware(config) {
257
420
  return undefined; // pass through
258
421
  }
259
422
  }
260
- // Try on-chain agent ID first, then key-based hash
423
+ // Try on-chain agent ID first, then key-based address
261
424
  const agentId = extractAgentId(request);
262
- const keyHash = agentId ? null : extractKeyHash(request);
263
- if (!agentId && !keyHash) {
264
- return Response.json({ error: "Missing agent identity (provide x-agent-id or x-agent-key-hash header)" }, { status: 401 });
425
+ const agentAddr = agentId ? null : extractAddress(request);
426
+ if (!agentId && !agentAddr) {
427
+ return Response.json({
428
+ error: "Missing agent identity",
429
+ message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
430
+ identitySkill: "https://valiron.co/auth.md",
431
+ }, { status: 401 });
265
432
  }
433
+ const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
434
+ const effectiveMinScore = minScore ?? 65;
266
435
  try {
267
436
  let result;
437
+ let pendingEvaluation = false;
438
+ const identifier = agentId || agentAddr;
439
+ // Check client-side cache first
440
+ if (cacheTtl > 0) {
441
+ const cached = cache.getCached(identifier, cacheTtl);
442
+ if (cached) {
443
+ if (cached.result.allow)
444
+ return undefined;
445
+ return Response.json({ error: "Agent blocked by Valiron trust gate", ...cached.result }, { status: 403 });
446
+ }
447
+ }
268
448
  if (agentId) {
269
- result = await sdk.gate(agentId, { minScore, ttlMs });
449
+ const profile = await sdk.getAgentProfile(agentId);
450
+ result = profileToGateResult(profile, effectiveMinScore);
451
+ // Detect brand-new agent: on-chain identity exists but zero reputation.
452
+ if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
453
+ sdk.triggerSandboxTest(agentId).catch(() => { });
454
+ pendingEvaluation = true;
455
+ }
270
456
  }
271
457
  else {
272
- const profile = await sdk.getKeyAgentProfile(keyHash);
273
- result = keyProfileToGateResult(profile, minScore ?? 65);
458
+ const profile = await sdk.getKeyAgentProfile(agentAddr);
459
+ result = keyProfileToGateResult(profile, effectiveMinScore);
460
+ // Detect brand-new key agent: verified but never scored.
461
+ if (!result.allow && profile.verified && profile.score == null) {
462
+ if (typeof sdk.triggerKeyAgentSandbox === "function") {
463
+ sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
464
+ }
465
+ pendingEvaluation = true;
466
+ }
274
467
  }
468
+ if (cacheTtl > 0)
469
+ cache.setCache(identifier, result, pendingEvaluation || undefined);
275
470
  if (result.allow) {
276
471
  return undefined; // continue to route handler
277
472
  }
473
+ if (pendingEvaluation) {
474
+ return Response.json({
475
+ error: "Agent pending evaluation",
476
+ message: "This agent was recently registered and is being evaluated. Retry shortly.",
477
+ retryAfterMs: 30000,
478
+ ...result,
479
+ }, { status: 403 });
480
+ }
278
481
  return Response.json({ error: "Agent blocked by Valiron trust gate", ...result }, { status: 403 });
279
482
  }
280
483
  catch {
@@ -298,7 +501,7 @@ function createValironNextMiddleware(config) {
298
501
  * app.use('/api/*', async (c, next) => {
299
502
  * const gate = await valironGateCheck(valiron, {
300
503
  * agentId: c.req.header('x-agent-id') ?? null,
301
- * agentKeyHash: c.req.header('x-agent-key-hash') ?? null,
504
+ * agentAddress: c.req.header('x-agent-address') ?? null,
302
505
  * });
303
506
  * if (!gate.allow) return c.json(gate.body, gate.status);
304
507
  * c.set('valiron', gate.result);
@@ -312,7 +515,7 @@ function createValironNextMiddleware(config) {
312
515
  * app.use(async (ctx, next) => {
313
516
  * const gate = await valironGateCheck(valiron, {
314
517
  * agentId: ctx.get('x-agent-id') || null,
315
- * agentKeyHash: ctx.get('x-agent-key-hash') || null,
518
+ * agentAddress: ctx.get('x-agent-address') || null,
316
519
  * });
317
520
  * if (!gate.allow) {
318
521
  * ctx.status = gate.status;
@@ -325,29 +528,89 @@ function createValironNextMiddleware(config) {
325
528
  * ```
326
529
  */
327
530
  async function valironGateCheck(sdk, opts) {
328
- const { agentId, agentKeyHash, minScore, ttlMs } = opts;
329
- const identifier = agentId || agentKeyHash || null;
531
+ const { agentId, agentAddress, minScore } = opts;
532
+ const identifier = agentId || agentAddress || null;
330
533
  if (!identifier) {
331
534
  return {
332
535
  hasAgent: false,
333
536
  agentId: null,
334
537
  ok: false,
335
538
  status: 401,
336
- body: { error: "Missing agent identity" },
539
+ body: {
540
+ error: "Missing agent identity",
541
+ message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
542
+ identitySkill: "https://valiron.co/auth.md",
543
+ },
337
544
  };
338
545
  }
546
+ const effectiveMinScore = minScore ?? 65;
547
+ const cacheTtl = opts.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
548
+ // Get or create a per-SDK cache instance
549
+ const cache = getGateCheckCache(sdk);
550
+ // Check client-side cache first
551
+ if (cacheTtl > 0) {
552
+ const cached = cache.getCached(identifier, cacheTtl);
553
+ if (cached) {
554
+ if (cached.result.allow) {
555
+ return { hasAgent: true, agentId: identifier, ok: true, allow: true, result: cached.result, status: 200 };
556
+ }
557
+ return {
558
+ hasAgent: true,
559
+ agentId: identifier,
560
+ ok: true,
561
+ allow: false,
562
+ result: cached.result,
563
+ status: 403,
564
+ body: { error: "Agent blocked by Valiron trust gate", ...cached.result,
565
+ ...(cached.pendingEvaluation ? { pendingEvaluation: true, retryAfterMs: 30000 } : {}) },
566
+ };
567
+ }
568
+ }
339
569
  try {
340
570
  let result;
571
+ let pendingEvaluation = false;
341
572
  if (agentId) {
342
- result = await sdk.gate(agentId, { minScore, ttlMs });
573
+ const profile = await sdk.getAgentProfile(agentId);
574
+ result = profileToGateResult(profile, effectiveMinScore);
575
+ // Detect brand-new agent: on-chain identity exists but zero reputation.
576
+ if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
577
+ sdk.triggerSandboxTest(agentId).catch(() => { });
578
+ pendingEvaluation = true;
579
+ }
343
580
  }
344
581
  else {
345
- const profile = await sdk.getKeyAgentProfile(agentKeyHash);
346
- result = keyProfileToGateResult(profile, minScore ?? 65);
582
+ const profile = await sdk.getKeyAgentProfile(agentAddress);
583
+ result = keyProfileToGateResult(profile, effectiveMinScore);
584
+ // Detect brand-new key agent: verified but never scored.
585
+ if (!result.allow && profile.verified && profile.score == null) {
586
+ if (typeof sdk.triggerKeyAgentSandbox === "function") {
587
+ sdk.triggerKeyAgentSandbox(agentAddress).catch(() => { });
588
+ }
589
+ pendingEvaluation = true;
590
+ }
347
591
  }
592
+ if (cacheTtl > 0)
593
+ cache.setCache(identifier, result, pendingEvaluation || undefined);
348
594
  if (result.allow) {
349
595
  return { hasAgent: true, agentId: identifier, ok: true, allow: true, result, status: 200 };
350
596
  }
597
+ if (pendingEvaluation) {
598
+ return {
599
+ hasAgent: true,
600
+ agentId: identifier,
601
+ ok: true,
602
+ allow: false,
603
+ result,
604
+ status: 403,
605
+ pendingEvaluation: true,
606
+ body: {
607
+ error: "Agent pending evaluation",
608
+ message: "This agent was recently registered and is being evaluated. Retry shortly.",
609
+ retryAfterMs: 30000,
610
+ ...result,
611
+ },
612
+ };
613
+ }
351
614
  return {
352
615
  hasAgent: true,
353
616
  agentId: identifier,