@valiron/sdk 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,6 +49,24 @@ No API key is required for basic read operations. Pro trust signals and `getWall
49
49
 
50
50
  Use `x-agent-id` for ERC-8004/Solana agents. Use `x-agent-address` plus Valiron challenge-response for local, Web2, or non-ERC-8004 agents. Agents can follow the hosted identity skill at https://www.valiron.co/auth.md.
51
51
 
52
+ ## Error diagnostics
53
+
54
+ SDK failures are `ValironError` instances. Handle the stable `code` programmatically and log `details.action`, `details.requestId`, `details.docsUrl`, and `details.retryAfterMs` to make recovery explicit.
55
+
56
+ ```typescript
57
+ import { ValironError } from "@valiron/sdk";
58
+
59
+ try {
60
+ await valiron.getAgentProfile("AGENT_ID");
61
+ } catch (error) {
62
+ if (error instanceof ValironError) {
63
+ console.error(error.code, error.message, error.details?.action);
64
+ }
65
+ }
66
+ ```
67
+
68
+ Trust middleware returns the same fields in JSON responses. Its primary codes are `MISSING_AGENT_IDENTITY`, `TRUST_GATE_DENIED`, `AGENT_EVALUATION_PENDING`, and `TRUST_GATE_UNAVAILABLE`. See the [error guide](https://valiron.co/docs#error-handling) for retry rules and hosted-wrapper diagnostics.
69
+
52
70
  ### Additional Features
53
71
 
54
72
  - **Auto-Sandbox** — Middleware automatically evaluates new agents (on-chain and key-based) on their first gated request
@@ -76,6 +94,8 @@ Full SDK reference, API docs, trust model, and integration guides:
76
94
  - **[SDK Reference](https://valiron.co/docs/agents/SDK-REFERENCE.md)** — all methods, options, and response types
77
95
  - **[API Reference](https://valiron.co/docs/agents/API-REFERENCE.md)** — HTTP endpoints
78
96
  - **[Quickstart](https://valiron.co/docs/agents/QUICKSTART.md)** — get started in 2 minutes
97
+ - **[End-to-End Middleware Integration](https://valiron.co/docs/agents/E2E-MIDDLEWARE-INTEGRATION.md)** — identity, trust signals, downstream policy, and testing
98
+ - **[Error Guide](https://valiron.co/docs#error-handling)** — codes, recovery actions, retries, and wrapper diagnostics
79
99
  - **[llms.txt](https://valiron.co/llms.txt)** — compact reference for LLM/agent integration
80
100
  - **Install agent skill**: `npx @valiron/skill`
81
101
 
package/dist/clients.d.ts CHANGED
@@ -192,6 +192,8 @@ export declare class ValironClient {
192
192
  /** Emit an SDK telemetry event from higher-level helpers. */
193
193
  emitTelemetry(event: string, payload: Record<string, unknown>): void;
194
194
  private buildHeaders;
195
+ /** Preserve safe server diagnostics instead of collapsing every non-2xx response into API_ERROR. */
196
+ private createApiError;
195
197
  private get;
196
198
  private post;
197
199
  private extractMethodName;
package/dist/clients.js CHANGED
@@ -278,6 +278,25 @@ class ValironClient {
278
278
  }
279
279
  return headers;
280
280
  }
281
+ /** Preserve safe server diagnostics instead of collapsing every non-2xx response into API_ERROR. */
282
+ createApiError(response, body, path, method) {
283
+ const message = (typeof body.message === "string" && body.message) ||
284
+ (typeof body.error === "string" && body.error) ||
285
+ `Request failed: ${response.statusText}`;
286
+ const requestId = response.headers.get("x-request-id") || response.headers.get("x-vercel-id") || undefined;
287
+ const retryAfterSeconds = Number(response.headers.get("retry-after"));
288
+ const bodyRetryAfterMs = typeof body.retryAfterMs === "number" ? body.retryAfterMs : undefined;
289
+ const details = {
290
+ method,
291
+ path,
292
+ requestId,
293
+ details: body.details,
294
+ action: typeof body.action === "string" ? body.action : typeof body.hint === "string" ? body.hint : undefined,
295
+ docsUrl: typeof body.docsUrl === "string" ? body.docsUrl : typeof body.identitySkill === "string" ? body.identitySkill : undefined,
296
+ retryAfterMs: bodyRetryAfterMs ?? (Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1000 : undefined),
297
+ };
298
+ return new types_1.ValironError(message, typeof body.code === "string" ? body.code : "API_ERROR", response.status, details);
299
+ }
281
300
  async get(path, chain) {
282
301
  const url = new URL(path, this.endpoint);
283
302
  if (chain)
@@ -314,7 +333,7 @@ class ValironClient {
314
333
  abort_count: 0,
315
334
  });
316
335
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
317
- throw new types_1.ValironError(body.error || body.message || `Request failed: ${response.statusText}`, "API_ERROR", response.status);
336
+ throw this.createApiError(response, body, path, "GET");
318
337
  }
319
338
  const data = await response.json();
320
339
  this.telemetry.emit("sdk_call", {
@@ -349,7 +368,7 @@ class ValironClient {
349
368
  timeout_ms: timeoutMs,
350
369
  });
351
370
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
352
- throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
371
+ throw new types_1.ValironError(`Valiron did not respond within ${timeoutMs}ms. Retry the request, increase timeout, or check the service status.`, "TIMEOUT_ERROR", undefined, { method: "GET", path, action: "Retry with a longer timeout or inspect the Valiron service status.", retryAfterMs: 1000 });
353
372
  }
354
373
  if (error instanceof types_1.ValironError)
355
374
  throw error;
@@ -364,7 +383,7 @@ class ValironClient {
364
383
  abort_count: 0,
365
384
  });
366
385
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
367
- throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
386
+ throw new types_1.ValironError(`Could not reach Valiron: ${error.message || "network error"}`, "NETWORK_ERROR", undefined, { method: "GET", path, action: "Check your endpoint URL, network egress, and DNS configuration before retrying." });
368
387
  }
369
388
  }
370
389
  async post(path, body, chain) {
@@ -408,7 +427,7 @@ class ValironClient {
408
427
  abort_count: 0,
409
428
  });
410
429
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
411
- throw new types_1.ValironError(respBody.error || respBody.message || `Request failed: ${response.statusText}`, "API_ERROR", response.status);
430
+ throw this.createApiError(response, respBody, path, "POST");
412
431
  }
413
432
  const data = await response.json();
414
433
  this.telemetry.emit("sdk_call", {
@@ -443,7 +462,7 @@ class ValironClient {
443
462
  timeout_ms: timeoutMs,
444
463
  });
445
464
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
446
- throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
465
+ throw new types_1.ValironError(`Valiron did not respond within ${timeoutMs}ms. Retry the request, increase timeout, or check the service status.`, "TIMEOUT_ERROR", undefined, { method: "POST", path, action: "Retry with a longer timeout or inspect the Valiron service status.", retryAfterMs: 1000 });
447
466
  }
448
467
  if (error instanceof types_1.ValironError)
449
468
  throw error;
@@ -458,7 +477,7 @@ class ValironClient {
458
477
  abort_count: 0,
459
478
  });
460
479
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
461
- throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
480
+ throw new types_1.ValironError(`Could not reach Valiron: ${error.message || "network error"}`, "NETWORK_ERROR", undefined, { method: "POST", path, action: "Check your endpoint URL, network egress, and DNS configuration before retrying." });
462
481
  }
463
482
  }
464
483
  extractMethodName(path) {
@@ -156,6 +156,57 @@ function bucketScore(score) {
156
156
  return "71-90";
157
157
  return "91+";
158
158
  }
159
+ const IDENTITY_SETUP_URL = "https://www.valiron.co/auth.md";
160
+ const ERROR_GUIDE_URL = "https://valiron.co/docs#error-handling";
161
+ function missingIdentityBody() {
162
+ return {
163
+ code: "MISSING_AGENT_IDENTITY",
164
+ error: "Missing agent identity",
165
+ message: "Provide x-agent-id for a registered agent or x-agent-address for a verified key-based agent.",
166
+ action: "Create or verify an agent identity, then retry this request with exactly one supported identity header.",
167
+ docsUrl: IDENTITY_SETUP_URL,
168
+ identitySkill: IDENTITY_SETUP_URL,
169
+ };
170
+ }
171
+ function unavailableGateBody(error) {
172
+ const cause = error instanceof Error ? error.message : undefined;
173
+ return {
174
+ code: "TRUST_GATE_UNAVAILABLE",
175
+ error: "Trust gate unavailable — request denied (fail-closed)",
176
+ message: "Valiron could not complete the trust evaluation, so this request was not allowed through.",
177
+ action: "Retry shortly. If it persists, verify your Valiron endpoint and include the request timestamp plus this cause in a support request.",
178
+ docsUrl: ERROR_GUIDE_URL,
179
+ ...(cause ? { cause } : {}),
180
+ };
181
+ }
182
+ function pendingEvaluationBody(result) {
183
+ return {
184
+ code: "AGENT_EVALUATION_PENDING",
185
+ error: "Agent pending evaluation",
186
+ message: "This newly identified agent is being sandbox-evaluated before it can access this endpoint.",
187
+ action: "Retry after the evaluation completes. Do not create a new identity; keep using the same agent identifier.",
188
+ docsUrl: ERROR_GUIDE_URL,
189
+ retryAfterMs: 30000,
190
+ pendingEvaluation: true,
191
+ ...result,
192
+ };
193
+ }
194
+ function deniedGateBody(result, minScore) {
195
+ return {
196
+ code: "TRUST_GATE_DENIED",
197
+ error: "Agent blocked by Valiron trust gate",
198
+ message: `The agent did not satisfy this endpoint's trust policy (minimum score: ${minScore}).`,
199
+ action: "Inspect route, tier, score, and reasons below. Use a sandbox route if offered, or improve the agent's trust signals before retrying.",
200
+ docsUrl: ERROR_GUIDE_URL,
201
+ ...result,
202
+ };
203
+ }
204
+ function logGateFailure(framework, agentId, error) {
205
+ console.error(`[Valiron middleware] ${framework} trust evaluation failed`, {
206
+ agentId: agentId || "missing",
207
+ error: error instanceof Error ? error.message : String(error),
208
+ });
209
+ }
159
210
  function emitGateTelemetry(sdk, payload) {
160
211
  if (typeof sdk.emitTelemetry !== "function")
161
212
  return;
@@ -308,11 +359,7 @@ function createValironGate(config) {
308
359
  status: "missing_identity",
309
360
  latencyMs,
310
361
  });
311
- return res.status(401).json({
312
- error: "Missing agent identity",
313
- message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
314
- identitySkill: "https://valiron.co/auth.md",
315
- });
362
+ return res.status(401).json(missingIdentityBody());
316
363
  }
317
364
  if (error) {
318
365
  emitGateTelemetry(frozen.sdk, {
@@ -323,9 +370,8 @@ function createValironGate(config) {
323
370
  status: "error",
324
371
  latencyMs,
325
372
  });
326
- return res.status(503).json({
327
- error: "Trust gate unavailable \u2014 request denied (fail-closed)",
328
- });
373
+ logGateFailure("express", agentId, error);
374
+ return res.status(503).json(unavailableGateBody(error));
329
375
  }
330
376
  emitGateTelemetry(frozen.sdk, {
331
377
  framework: "express",
@@ -350,20 +396,12 @@ function createValironGate(config) {
350
396
  }
351
397
  // New agent with no reputation — sandbox test triggered in background
352
398
  if (pendingEvaluation) {
353
- return res.status(403).json({
354
- error: "Agent pending evaluation",
355
- message: "This agent was recently registered and is being evaluated. Retry shortly.",
356
- retryAfterMs: 30000,
357
- ...result,
358
- });
399
+ return res.status(403).json(pendingEvaluationBody(result));
359
400
  }
360
401
  if (config.onDeny) {
361
402
  return config.onDeny(req, res, result);
362
403
  }
363
- return res.status(403).json({
364
- error: "Agent blocked by Valiron trust gate",
365
- ...result,
366
- });
404
+ return res.status(403).json(deniedGateBody(result, minScore));
367
405
  }
368
406
  // Wrap with Promise.catch(next) for Express 4 async safety.
369
407
  // Express 4 does NOT await async middleware, so without this wrapper
@@ -442,11 +480,7 @@ async function valironFastifyPlugin(fastify, opts) {
442
480
  status: "missing_identity",
443
481
  latencyMs,
444
482
  });
445
- return reply.status(401).send({
446
- error: "Missing agent identity",
447
- message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
448
- identitySkill: "https://valiron.co/auth.md",
449
- });
483
+ return reply.status(401).send(missingIdentityBody());
450
484
  }
451
485
  if (error) {
452
486
  emitGateTelemetry(opts.sdk, {
@@ -457,9 +491,8 @@ async function valironFastifyPlugin(fastify, opts) {
457
491
  status: "error",
458
492
  latencyMs,
459
493
  });
460
- return reply.status(503).send({
461
- error: "Trust gate unavailable \u2014 request denied (fail-closed)",
462
- });
494
+ logGateFailure("fastify", agentId, error);
495
+ return reply.status(503).send(unavailableGateBody(error));
463
496
  }
464
497
  emitGateTelemetry(opts.sdk, {
465
498
  framework: "fastify",
@@ -484,20 +517,12 @@ async function valironFastifyPlugin(fastify, opts) {
484
517
  }
485
518
  // New agent with no reputation — sandbox test triggered in background
486
519
  if (pendingEvaluation) {
487
- return reply.status(403).send({
488
- error: "Agent pending evaluation",
489
- message: "This agent was recently registered and is being evaluated. Retry shortly.",
490
- retryAfterMs: 30000,
491
- ...result,
492
- });
520
+ return reply.status(403).send(pendingEvaluationBody(result));
493
521
  }
494
522
  if (opts.onDeny) {
495
523
  return opts.onDeny(request, reply, result);
496
524
  }
497
- return reply.status(403).send({
498
- error: "Agent blocked by Valiron trust gate",
499
- ...result,
500
- });
525
+ return reply.status(403).send(deniedGateBody(result, minScore));
501
526
  });
502
527
  }
503
528
  /**
@@ -555,11 +580,7 @@ function createValironNextMiddleware(config) {
555
580
  status: "missing_identity",
556
581
  latencyMs: Date.now() - startedAt,
557
582
  });
558
- return Response.json({
559
- error: "Missing agent identity",
560
- message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
561
- identitySkill: "https://valiron.co/auth.md",
562
- }, { status: 401 });
583
+ return Response.json(missingIdentityBody(), { status: 401 });
563
584
  }
564
585
  const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
565
586
  const effectiveMinScore = minScore ?? 65;
@@ -588,7 +609,9 @@ function createValironNextMiddleware(config) {
588
609
  });
589
610
  if (cached.result.allow)
590
611
  return undefined;
591
- return Response.json({ error: "Agent blocked by Valiron trust gate", ...cached.result }, { status: 403 });
612
+ return Response.json(cached.pendingEvaluation
613
+ ? pendingEvaluationBody(cached.result)
614
+ : deniedGateBody(cached.result, effectiveMinScore), { status: 403 });
592
615
  }
593
616
  }
594
617
  if (agentId) {
@@ -634,16 +657,11 @@ function createValironNextMiddleware(config) {
634
657
  return undefined; // continue to route handler
635
658
  }
636
659
  if (pendingEvaluation) {
637
- return Response.json({
638
- error: "Agent pending evaluation",
639
- message: "This agent was recently registered and is being evaluated. Retry shortly.",
640
- retryAfterMs: 30000,
641
- ...result,
642
- }, { status: 403 });
660
+ return Response.json(pendingEvaluationBody(result), { status: 403 });
643
661
  }
644
- return Response.json({ error: "Agent blocked by Valiron trust gate", ...result }, { status: 403 });
662
+ return Response.json(deniedGateBody(result, effectiveMinScore), { status: 403 });
645
663
  }
646
- catch {
664
+ catch (error) {
647
665
  emitGateTelemetry(sdk, {
648
666
  framework: "next",
649
667
  agentType: agentId ? "onchain" : "key",
@@ -652,7 +670,8 @@ function createValironNextMiddleware(config) {
652
670
  status: "error",
653
671
  latencyMs: Date.now() - startedAt,
654
672
  });
655
- return Response.json({ error: "Trust gate unavailable \u2014 request denied (fail-closed)" }, { status: 503 });
673
+ logGateFailure("next", agentId || agentAddr, error);
674
+ return Response.json(unavailableGateBody(error), { status: 503 });
656
675
  }
657
676
  };
658
677
  }
@@ -716,11 +735,7 @@ async function valironGateCheck(sdk, opts) {
716
735
  agentId: null,
717
736
  ok: false,
718
737
  status: 401,
719
- body: {
720
- error: "Missing agent identity",
721
- message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
722
- identitySkill: "https://valiron.co/auth.md",
723
- },
738
+ body: missingIdentityBody(),
724
739
  };
725
740
  }
726
741
  const effectiveMinScore = minScore ?? 65;
@@ -756,8 +771,10 @@ async function valironGateCheck(sdk, opts) {
756
771
  allow: false,
757
772
  result: cached.result,
758
773
  status: 403,
759
- body: { error: "Agent blocked by Valiron trust gate", ...cached.result,
760
- ...(cached.pendingEvaluation ? { pendingEvaluation: true, retryAfterMs: 30000 } : {}) },
774
+ pendingEvaluation: cached.pendingEvaluation || undefined,
775
+ body: cached.pendingEvaluation
776
+ ? pendingEvaluationBody(cached.result)
777
+ : deniedGateBody(cached.result, effectiveMinScore),
761
778
  };
762
779
  }
763
780
  }
@@ -815,12 +832,7 @@ async function valironGateCheck(sdk, opts) {
815
832
  result,
816
833
  status: 403,
817
834
  pendingEvaluation: true,
818
- body: {
819
- error: "Agent pending evaluation",
820
- message: "This agent was recently registered and is being evaluated. Retry shortly.",
821
- retryAfterMs: 30000,
822
- ...result,
823
- },
835
+ body: pendingEvaluationBody(result),
824
836
  };
825
837
  }
826
838
  return {
@@ -830,10 +842,10 @@ async function valironGateCheck(sdk, opts) {
830
842
  allow: false,
831
843
  result,
832
844
  status: 403,
833
- body: { error: "Agent blocked by Valiron trust gate", ...result },
845
+ body: deniedGateBody(result, effectiveMinScore),
834
846
  };
835
847
  }
836
- catch {
848
+ catch (error) {
837
849
  emitGateTelemetry(sdk, {
838
850
  framework: "generic",
839
851
  agentType: agentId ? "onchain" : "key",
@@ -842,12 +854,13 @@ async function valironGateCheck(sdk, opts) {
842
854
  status: "error",
843
855
  latencyMs: Date.now() - startedAt,
844
856
  });
857
+ logGateFailure("generic", identifier, error);
845
858
  return {
846
859
  hasAgent: true,
847
860
  agentId: identifier,
848
861
  ok: false,
849
862
  status: 503,
850
- body: { error: "Trust gate unavailable \u2014 request denied (fail-closed)" },
863
+ body: unavailableGateBody(error),
851
864
  };
852
865
  }
853
866
  }
package/dist/types.d.ts CHANGED
@@ -562,8 +562,26 @@ export interface ValironConfig {
562
562
  */
563
563
  telemetry?: TelemetryConfig;
564
564
  }
565
+ /** Structured diagnostics attached to SDK failures for programmatic recovery. */
566
+ export interface ValironErrorDetails {
567
+ /** HTTP method used for the failed request, when applicable. */
568
+ method?: "GET" | "POST";
569
+ /** Valiron API path that failed. */
570
+ path?: string;
571
+ /** Server request ID, when the deployment supplies one. Include this in support requests. */
572
+ requestId?: string;
573
+ /** Safe server-provided explanation beyond the top-level message. */
574
+ details?: unknown;
575
+ /** Suggested next step supplied by Valiron. */
576
+ action?: string;
577
+ /** Documentation or setup URL relevant to the failure. */
578
+ docsUrl?: string;
579
+ /** Delay before retrying, when the operation is retryable. */
580
+ retryAfterMs?: number;
581
+ }
565
582
  export declare class ValironError extends Error {
566
583
  code: string;
567
584
  statusCode?: number | undefined;
568
- constructor(message: string, code: string, statusCode?: number | undefined);
585
+ details?: ValironErrorDetails | undefined;
586
+ constructor(message: string, code: string, statusCode?: number | undefined, details?: ValironErrorDetails | undefined);
569
587
  }
package/dist/types.js CHANGED
@@ -7,12 +7,12 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.ValironError = void 0;
10
- // ─── Errors ─────────────────────────────────────────────────────────────────
11
10
  class ValironError extends Error {
12
- constructor(message, code, statusCode) {
11
+ constructor(message, code, statusCode, details) {
13
12
  super(message);
14
13
  this.code = code;
15
14
  this.statusCode = statusCode;
15
+ this.details = details;
16
16
  this.name = "ValironError";
17
17
  }
18
18
  }
@@ -0,0 +1,213 @@
1
+ # End-to-End Valiron Middleware Integration
2
+
3
+ This guide helps API teams integrate Valiron middleware from the first incoming
4
+ agent request through the downstream action they want to take. Start with the
5
+ agent identity, choose the trust signals that match your policy, then use the
6
+ gate result to protect an endpoint, vary access, attach pricing context, or
7
+ record the decision.
8
+
9
+ ```text
10
+ Incoming request
11
+ -> identify the agent
12
+ -> evaluate selected trust signals
13
+ -> receive an allow/deny decision, score, tier, and route
14
+ -> apply your API policy
15
+ -> serve, limit, sandbox, price, or deny
16
+ ```
17
+
18
+ ## Before you start
19
+
20
+ 1. Create an operator account in the [Dashboard](./DASHBOARD.md).
21
+ 2. Copy an operator API key (`val_op_...`) if you will use Pro trust signals,
22
+ operator usage logging, or hosted products.
23
+ 3. Install the SDK:
24
+
25
+ ```bash
26
+ npm install @valiron/sdk
27
+ ```
28
+
29
+ 4. Choose the identity format your agent callers will send.
30
+
31
+ ## 1. Identify every agent
32
+
33
+ Valiron middleware supports both identity paths automatically. Send one of the
34
+ following headers on the request to your API:
35
+
36
+ | Agent type | Header | Value | Setup |
37
+ | --- | --- | --- | --- |
38
+ | ERC-8004 EVM agent | `x-agent-id` | ERC-8004 token ID | Agent is registered on-chain |
39
+ | Solana agent | `x-agent-id` | Metaplex Core asset pubkey or supported indexed ID | Use `chain: "solana"` |
40
+ | Local, Web2, or non-ERC-8004 agent | `x-agent-address` | Persistent Ethereum-style address | Complete [key-based challenge-response](https://www.valiron.co/auth.md) first |
41
+
42
+ Do not send a local agent name to `x-agent-id`. Key-based agents must prove
43
+ ownership of their persistent address before they can pass an identity-aware
44
+ policy.
45
+
46
+ > **Hosted wrapper note:** Valiron-hosted API Scaffolding currently requires
47
+ > `x-agent-id` when its trust check is enabled. Use the SDK middleware in your
48
+ > own backend for a policy that accepts either identity path.
49
+
50
+ ## 2. Choose trust signals
51
+
52
+ Pass `trustSignals` to the middleware configuration. Start with the default
53
+ baseline, then add signals only when they are meaningful for the action you are
54
+ protecting.
55
+
56
+ | Signal | What it contributes | Availability |
57
+ | --- | --- | --- |
58
+ | `8004` | Registry-backed on-chain identity and reputation | All plans |
59
+ | `sandbox` | Behavioral evaluation and route readiness | All plans |
60
+ | `world` | World ID proof-of-personhood linkage | Pro |
61
+ | `self` | Self eligible-human verification | Pro |
62
+ | `icebreaker` | Human-to-agent attestation | Pro |
63
+ | `wallet` | Explainable wallet-history risk, confidence, and hard flags | Pro |
64
+
65
+ For example, a high-value endpoint might require on-chain reputation,
66
+ behavioral evidence, and wallet intelligence:
67
+
68
+ ```typescript
69
+ import { ValironSDK, createValironGate } from "@valiron/sdk";
70
+
71
+ const valiron = new ValironSDK({
72
+ apiKey: process.env.VALIRON_API_KEY,
73
+ chain: "base",
74
+ });
75
+
76
+ const trustGate = createValironGate({
77
+ sdk: valiron,
78
+ trustSignals: ["8004", "sandbox", "wallet"],
79
+ minScore: 80,
80
+ });
81
+ ```
82
+
83
+ If a wallet-history provider is unavailable or a network is unsupported, its
84
+ result is neutral and excluded from the composite score rather than treated as
85
+ malicious. See [Trust Model](./TRUST-MODEL.md) for the complete signal model.
86
+
87
+ ## 3. Choose the downstream behavior
88
+
89
+ The middleware attaches a normalized result to the request after a successful
90
+ check. It includes `allow`, `score`, `tier`, `riskLevel`, `route`, and the
91
+ resolved `agentId`, regardless of which supported identity header the agent
92
+ used.
93
+
94
+ Choose the behavior that fits the endpoint:
95
+
96
+ | Goal | Use the decision for |
97
+ | --- | --- |
98
+ | Trust gate | Allow trusted agents and return a denial before your handler runs |
99
+ | Graduated access | Serve full access for `prod`, apply limits for `prod_throttled`, and use test data for sandbox routes |
100
+ | Trust-aware pricing | Read the result in your handler and apply your own price or entitlement policy |
101
+ | Monetized endpoint logging | Use `ValironOperator.paywall()` to gate access, attach a configured per-call price, and record usage |
102
+ | Agent profile lookup | Retrieve a profile when your product needs to display or review trust evidence |
103
+ | Predictive risk | Use dashboard/API forecasts as an additional operational signal; do not replace the runtime gate with a forecast |
104
+ | Audit and operations | Capture the result in your logs or use dashboard call logs and evaluation history |
105
+
106
+ Valiron does not itself settle a payment or choose a dynamic price table. It
107
+ provides the verified trust context that your payment and application policy
108
+ can use.
109
+
110
+ ## 4. Put the gate in front of your handler
111
+
112
+ Here is a complete Express example that supports both agent identity paths and
113
+ uses the route decision for graduated access:
114
+
115
+ ```typescript
116
+ import express from "express";
117
+ import { ValironSDK, createValironGate } from "@valiron/sdk";
118
+
119
+ const app = express();
120
+ const valiron = new ValironSDK({
121
+ apiKey: process.env.VALIRON_API_KEY,
122
+ chain: "base",
123
+ });
124
+
125
+ app.use("/api/research", createValironGate({
126
+ sdk: valiron,
127
+ trustSignals: ["8004", "sandbox", "wallet"],
128
+ minScore: 65,
129
+ }));
130
+
131
+ app.get("/api/research", (req, res) => {
132
+ const trust = (req as typeof req & { valiron: {
133
+ route: "prod" | "prod_throttled" | "sandbox" | "sandbox_only";
134
+ score: number;
135
+ tier: string;
136
+ } }).valiron;
137
+
138
+ if (trust.route === "prod_throttled") {
139
+ res.set("X-Rate-Limit-Policy", "reduced");
140
+ }
141
+
142
+ if (trust.route === "sandbox") {
143
+ return res.json({ mode: "sandbox", results: [] });
144
+ }
145
+
146
+ return res.json({
147
+ mode: "production",
148
+ trust: { score: trust.score, tier: trust.tier },
149
+ results: [/* your production response */],
150
+ });
151
+ });
152
+
153
+ app.listen(3000);
154
+ ```
155
+
156
+ The middleware checks `x-agent-id` first, then `x-agent-address`. If there is
157
+ no supported identity, the agent is denied. If an agent is pending its first
158
+ behavioral evaluation, it receives a retryable denial while sandbox evaluation
159
+ runs.
160
+
161
+ ## 5. Add a pricing or payment policy
162
+
163
+ For a server-side endpoint with a fixed price and usage logging, use the
164
+ operator SDK. It gates the route, makes the decision available as
165
+ `req.valiron`, and records the configured price only for successful allowed
166
+ calls.
167
+
168
+ ```typescript
169
+ import { ValironOperator } from "@valiron/sdk";
170
+
171
+ const operator = new ValironOperator({
172
+ apiKey: process.env.VALIRON_API_KEY!,
173
+ chain: "base",
174
+ });
175
+
176
+ app.use("/api/premium", operator.paywall({
177
+ pricePerCall: 0.05,
178
+ minTrustScore: 65,
179
+ trustSignals: ["8004", "sandbox", "wallet"],
180
+ }));
181
+ ```
182
+
183
+ If your payment provider supports multiple prices, select the price in your
184
+ handler from `req.valiron.tier`, `score`, or `route`. Keep payment settlement
185
+ in that provider; use Valiron first to decide whether the caller is eligible
186
+ to reach it.
187
+
188
+ ## 6. Test the complete request path
189
+
190
+ Test each case before production:
191
+
192
+ 1. A registered agent using `x-agent-id`.
193
+ 2. A verified key-based agent using `x-agent-address`.
194
+ 3. A request without either identity header.
195
+ 4. An agent below your `minScore`.
196
+ 5. A new agent pending sandbox evaluation.
197
+ 6. A production-eligible agent on every protected route.
198
+ 7. A paid or priced request, verifying that trust denial happens before your
199
+ payment or application handler.
200
+
201
+ Use the [Dashboard Playground](./DASHBOARD.md#api-playground) to inspect
202
+ decisions and the Dashboard's call logs to review outcome, latency, price, and
203
+ trust context after launch.
204
+
205
+ ## Next steps
206
+
207
+ - [Quickstart](./QUICKSTART.md) — protect a first endpoint quickly
208
+ - [SDK Reference](./SDK-REFERENCE.md#middleware) — Express, Fastify, Next.js,
209
+ and generic middleware APIs
210
+ - [Identity](./IDENTITY.md) — registry and key-based identity details
211
+ - [Trust Model](./TRUST-MODEL.md) — signals, tiers, and routes
212
+ - [API Scaffolding](./AGENT-READY-APIS.md) — hosted x402/MPP wrappers for an
213
+ existing API
package/docs/ERRORS.md CHANGED
@@ -2,6 +2,44 @@
2
2
 
3
3
  Common error scenarios, status codes, and guidance on how to handle them.
4
4
 
5
+ ## Read an error before retrying
6
+
7
+ Every SDK failure is a `ValironError`. Its stable `code` is for program logic; its `message` is safe to show in developer logs; and `details` provides the recovery information that was available from the API.
8
+
9
+ ```typescript
10
+ import { ValironError } from "@valiron/sdk";
11
+
12
+ try {
13
+ await valiron.getAgentProfile("99999");
14
+ } catch (error) {
15
+ if (error instanceof ValironError) {
16
+ console.error({
17
+ code: error.code,
18
+ status: error.statusCode,
19
+ message: error.message,
20
+ nextStep: error.details?.action,
21
+ requestId: error.details?.requestId,
22
+ docs: error.details?.docsUrl,
23
+ retryAfterMs: error.details?.retryAfterMs,
24
+ serverDetails: error.details?.details,
25
+ });
26
+ }
27
+ }
28
+ ```
29
+
30
+ HTTP errors from SDK calls and trust-gate responses use these fields where applicable:
31
+
32
+ | Field | Purpose |
33
+ |--------|---------|
34
+ | `code` | Stable, machine-readable category such as `MISSING_AGENT_IDENTITY` or `TRUST_GATE_DENIED` |
35
+ | `message` | Human-readable explanation of what happened |
36
+ | `action` / `details.action` | Concrete next debugging or recovery step |
37
+ | `docsUrl` / `details.docsUrl` | Relevant documentation section |
38
+ | `requestId` / `details.requestId` | Include with a timestamp in a support request |
39
+ | `retryAfterMs` | Minimum delay before retrying, when retrying is appropriate |
40
+
41
+ Treat `code` as the contract; wording may be refined over time.
42
+
5
43
  ## HTTP Status Codes
6
44
 
7
45
  | Status | Meaning | Action |
@@ -28,12 +66,11 @@ const valiron = new ValironSDK();
28
66
  try {
29
67
  const profile = await valiron.getAgentProfile("99999");
30
68
  } catch (error) {
31
- if (error.status === 404) {
69
+ if (error instanceof ValironError && error.statusCode === 404) {
32
70
  // Agent not registered — register via ERC-8004 first
33
- } else if (error.status === 429) {
71
+ } else if (error instanceof ValironError && error.statusCode === 429) {
34
72
  // Rate limited — wait and retry
35
- const retryAfter = error.headers?.["retry-after"];
36
- await sleep(parseInt(retryAfter || "5") * 1000);
73
+ await sleep(error.details?.retryAfterMs ?? 5_000);
37
74
  } else {
38
75
  // Unexpected error — log and retry with backoff
39
76
  console.error(error.message);
@@ -52,10 +89,11 @@ async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
52
89
  return await fn();
53
90
  } catch (error) {
54
91
  // Never retry auth errors
55
- if (error.status === 401 || error.status === 403) throw error;
92
+ const status = error instanceof ValironError ? error.statusCode : undefined;
93
+ if (status === 401 || status === 403) throw error;
56
94
 
57
95
  // Never retry client errors (except 429)
58
- if (error.status >= 400 && error.status < 500 && error.status !== 429) throw error;
96
+ if (status && status >= 400 && status < 500 && status !== 429) throw error;
59
97
 
60
98
  if (attempt === maxRetries) throw error;
61
99
 
@@ -177,11 +215,14 @@ SOLANA_RPC_URL=https://your-private-rpc.example.com
177
215
 
178
216
  All Valiron middleware (Express, Fastify, Next.js, generic) returns consistent error responses:
179
217
 
180
- | Status | When | Body |
218
+ | Status | Code | When | What to do |
181
219
  |--------|------|------|
182
- | 401 | No agent ID found in request | `{ error: "No agent identity provided" }` |
183
- | 403 | Agent denied by trust gate | `{ error: "Access denied", tier, riskLevel, route }` |
184
- | 503 | Valiron service unavailable | `{ error: "Trust evaluation unavailable" }` |
220
+ | 401 | `MISSING_AGENT_IDENTITY` | No identity header | Send one supported identity header: `x-agent-id` or `x-agent-address` |
221
+ | 403 | `TRUST_GATE_DENIED` | Agent did not meet the configured policy | Inspect `score`, `tier`, `route`, and `reasons`; do not blindly retry |
222
+ | 403 | `AGENT_EVALUATION_PENDING` | New identity is sandbox-evaluating | Keep the same identity and retry after `retryAfterMs` |
223
+ | 503 | `TRUST_GATE_UNAVAILABLE` | Trust evaluation could not complete | Fail closed; retry shortly and inspect the logged `cause` |
224
+
225
+ Each response includes `message`, `action`, and `docsUrl`; denials retain the trust result fields so an application can make a deliberate fallback decision.
185
226
 
186
227
  > **Fail-closed:** When the Valiron service is unreachable, middleware returns 503 — it never fails open and never allows unverified agents through.
187
228
 
@@ -194,6 +235,16 @@ All Valiron middleware (Express, Fastify, Next.js, generic) returns consistent e
194
235
  | 403 | SSRF blocked | The `targetUrl` resolves to a private IP, localhost, or metadata endpoint |
195
236
  | 503 | Origin server unreachable | Your upstream API base URL is down or timed out |
196
237
 
238
+ ## Hosted Wrapper Errors
239
+
240
+ | Status | Code | When | Action |
241
+ |--------|------|------|--------|
242
+ | 400 | `MISSING_AGENT_IDENTITY` | A trust-enabled hosted wrapper did not receive `x-agent-id` | Hosted wrappers currently require `x-agent-id`; use SDK middleware for key/address identity support |
243
+ | 404 | `WRAPPER_NOT_FOUND` | Operator ID, path, method, or endpoint activation does not match | Verify all four values in the dashboard |
244
+ | 413 | `WRAPPER_BODY_TOO_LARGE` | Body exceeds the wrapper limit | Send a smaller request or use an external input reference |
245
+ | 429 | `WRAPPER_RATE_LIMITED` | Endpoint rate limit reached | Honor `retryAfter` and use exponential backoff |
246
+ | 502 / 504 | `WRAPPER_UPSTREAM_REQUEST_FAILED` / `WRAPPER_UPSTREAM_TIMEOUT` | The target API failed or was too slow | Check upstream URL/auth; include `requestId` and timestamp when escalating |
247
+
197
248
  ## Key-Based Agent Errors
198
249
 
199
250
  | Status | When | Action |
@@ -244,6 +244,7 @@ process.on("SIGTERM", async () => {
244
244
 
245
245
  ## What's next?
246
246
 
247
+ - **[End-to-End Middleware Integration](./E2E-MIDDLEWARE-INTEGRATION.md)** — Choose identity, trust signals, and a downstream policy for a production integration
247
248
  - **[Proxy Gateway](./SDK-REFERENCE.md#proxy-gateway-pro)** — Forward requests through Valiron's edge proxy (Pro)
248
249
  - **[API Scaffolding](./AGENT-READY-APIS.md)** — Create hosted x402/MPP wrappers for existing APIs
249
250
  - **[Key-Based Agents](./SDK-REFERENCE.md#key-based-agents)** — Support Web2 agents without on-chain identity
package/docs/README.md CHANGED
@@ -15,6 +15,7 @@ Valiron also provides **API Scaffolding** as a separate product for organization
15
15
  | File | Purpose |
16
16
  |------|---------|
17
17
  | [QUICKSTART.md](./QUICKSTART.md) | Get started in under 2 minutes — install the SDK, gate your first endpoint |
18
+ | [E2E-MIDDLEWARE-INTEGRATION.md](./E2E-MIDDLEWARE-INTEGRATION.md) | End-to-end middleware integration — identity, trust signals, downstream policy, and testing |
18
19
  | [AGENT-READY-APIS.md](./AGENT-READY-APIS.md) | API Scaffolding — hosted x402/MPP wrappers for existing APIs |
19
20
  | [DASHBOARD.md](./DASHBOARD.md) | Operator Dashboard — manage endpoints, keys, analytics, and playground |
20
21
  | [API-REFERENCE.md](./API-REFERENCE.md) | Complete HTTP API reference with request/response schemas |
@@ -730,14 +730,14 @@ caching for that middleware instance. `createValironNextMiddleware` and
730
730
 
731
731
  ### Middleware Error Responses
732
732
 
733
- All middleware variants return consistent error responses:
733
+ All middleware variants return consistent error responses. Each body includes a stable `code`, a human-readable `message`, an `action`, and a `docsUrl` in addition to the trust result fields.
734
734
 
735
- | Status | When | Body |
735
+ | Status | Code | When |
736
736
  |--------|------|------|
737
- | 401 | No agent ID found in request | `{ error: "No agent identity provided" }` |
738
- | 403 | Agent denied by trust gate | `{ error: "Access denied", tier, riskLevel, route }` |
739
- | 403 | New agent pending evaluation | `{ error: "Agent pending evaluation", retryAfterMs: 30000 }` |
740
- | 503 | Valiron service unavailable | `{ error: "Trust evaluation unavailable" }` |
737
+ | 401 | `MISSING_AGENT_IDENTITY` | No agent identity found in request |
738
+ | 403 | `TRUST_GATE_DENIED` | Agent denied by trust gate; inspect `score`, `tier`, `route`, and `reasons` |
739
+ | 403 | `AGENT_EVALUATION_PENDING` | New agent pending evaluation; retry after `retryAfterMs` |
740
+ | 503 | `TRUST_GATE_UNAVAILABLE` | Valiron service unavailable; fail closed and retry shortly |
741
741
 
742
742
  > **Fail-closed:** When the Valiron service is unreachable, middleware returns 503 — it never fails open and never allows unverified agents through.
743
743
 
package/docs/llms.txt CHANGED
@@ -108,7 +108,7 @@ GET/POST/etc /wrap/{operatorId}/{path}
108
108
 
109
109
  Wrapper config fields: path, method, targetUrl (upstream API base URL), pricePerCall, paymentProtocol ("x402" or "mpp"), paymentNetwork ("eip155:8453", "eip155:84532", "tempo:4217", or "tempo:42431"), payoutAddress, trustEnabled, rateLimit, upstreamAuthType, upstreamAuthHeader, upstreamAuthSecret.
110
110
 
111
- Free wrappers (pricePerCall=0) forward directly to targetUrl. x402 paid wrappers return 402 with x402 payment challenge and require retry with X-PAYMENT. MPP paid wrappers return 402 with WWW-Authenticate: Payment and require retry with Authorization: Payment. Trust-enabled wrappers require x-agent-id or x-agent-address/session headers and deny untrusted agents before forwarding.
111
+ Free wrappers (pricePerCall=0) forward directly to targetUrl. x402 paid wrappers return 402 with x402 payment challenge and require retry with X-PAYMENT. MPP paid wrappers return 402 with WWW-Authenticate: Payment and require retry with Authorization: Payment. Trust-enabled wrappers require x-agent-id and deny untrusted agents before forwarding. Use SDK middleware in your own backend when you need to support x-agent-address.
112
112
 
113
113
  ## Operator SDK (ValironOperator)
114
114
 
@@ -232,7 +232,7 @@ Opt-in anonymous usage metrics. Disable with `telemetry: { enabled: false }`. Su
232
232
 
233
233
  ## Middleware Error Responses
234
234
 
235
- All middleware returns: 401 (no agent ID), 403 (denied by trust gate), 503 (service unavailable). Fail-closed: never allows unverified agents through.
235
+ All middleware returns actionable JSON. Use the stable `code` for program logic and read `message`, `action`, and `docsUrl` for recovery. Codes: `MISSING_AGENT_IDENTITY` (401), `TRUST_GATE_DENIED` (403), `AGENT_EVALUATION_PENDING` (403; honor `retryAfterMs`), and `TRUST_GATE_UNAVAILABLE` (503, fail-closed). SDK `ValironError` instances preserve the same server code plus `details.action`, `details.requestId`, `details.docsUrl`, and `details.retryAfterMs`.
236
236
 
237
237
  ## Solana Notes
238
238
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valiron/sdk",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Official TypeScript SDK for Valiron — Trust & Reputation Middleware for API Protection",
5
5
  "repository": {
6
6
  "type": "git",