@valiron/sdk 1.3.0 → 1.3.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/dist/clients.js CHANGED
@@ -311,27 +311,29 @@ class ValironClient {
311
311
  const controller = new AbortController();
312
312
  const timeoutMs = this.getTimeoutForPath(path);
313
313
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
314
- const start = Date.now();
314
+ const start = performance.now();
315
+ let responseStatus;
315
316
  try {
316
317
  const response = await fetch(url.toString(), {
317
318
  method: "GET",
318
319
  headers: this.buildHeaders(),
319
320
  signal: controller.signal,
320
321
  });
321
- clearTimeout(timeoutId);
322
- const durationMs = Date.now() - start;
322
+ responseStatus = response.status;
323
323
  const methodName = this.extractMethodName(path);
324
324
  if (!response.ok) {
325
325
  const body = await response
326
326
  .json()
327
327
  .catch(() => ({ message: response.statusText }));
328
+ clearTimeout(timeoutId);
329
+ const durationMs = Math.round(performance.now() - start);
328
330
  this.telemetry.emit("sdk_call", {
329
331
  method: methodName,
330
332
  chain: chain || "server_default",
331
333
  duration_ms: durationMs,
332
334
  success: false,
333
335
  http_status: response.status,
334
- error_code: "API_ERROR",
336
+ error_code: typeof body.code === "string" ? body.code : "API_ERROR",
335
337
  retries: 0,
336
338
  timeout_count: 0,
337
339
  abort_count: 0,
@@ -340,6 +342,8 @@ class ValironClient {
340
342
  throw this.createApiError(response, body, path, "GET");
341
343
  }
342
344
  const data = await response.json();
345
+ clearTimeout(timeoutId);
346
+ const durationMs = Math.round(performance.now() - start);
343
347
  this.telemetry.emit("sdk_call", {
344
348
  method: methodName,
345
349
  chain: chain || "server_default",
@@ -357,7 +361,7 @@ class ValironClient {
357
361
  }
358
362
  catch (error) {
359
363
  clearTimeout(timeoutId);
360
- const durationMs = Date.now() - start;
364
+ const durationMs = Math.round(performance.now() - start);
361
365
  const methodName = this.extractMethodName(path);
362
366
  if (error.name === "AbortError") {
363
367
  this.telemetry.emit("sdk_call", {
@@ -376,18 +380,22 @@ class ValironClient {
376
380
  }
377
381
  if (error instanceof types_1.ValironError)
378
382
  throw error;
383
+ const errorCode = responseStatus === undefined ? "NETWORK_ERROR" : "RESPONSE_ERROR";
379
384
  this.telemetry.emit("sdk_call", {
380
385
  method: methodName,
381
386
  chain: chain || "server_default",
382
387
  duration_ms: durationMs,
383
388
  success: false,
384
- error_code: "NETWORK_ERROR",
389
+ http_status: responseStatus,
390
+ error_code: errorCode,
385
391
  retries: 0,
386
392
  timeout_count: 0,
387
393
  abort_count: 0,
388
394
  });
389
395
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
390
- 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." });
396
+ throw new types_1.ValironError(responseStatus === undefined
397
+ ? `Could not reach Valiron: ${error.message || "network error"}`
398
+ : `Could not read Valiron's response: ${error.message || "response error"}`, errorCode, responseStatus, { method: "GET", path, action: "Check your endpoint URL, network egress, and DNS configuration before retrying." });
391
399
  }
392
400
  }
393
401
  async post(path, body, chain) {
@@ -400,7 +408,8 @@ class ValironClient {
400
408
  const controller = new AbortController();
401
409
  const timeoutMs = this.getTimeoutForPath(path);
402
410
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
403
- const start = Date.now();
411
+ const start = performance.now();
412
+ let responseStatus;
404
413
  try {
405
414
  const headers = this.buildHeaders();
406
415
  const hasBody = body !== undefined && body !== null;
@@ -412,20 +421,21 @@ class ValironClient {
412
421
  body: hasBody ? JSON.stringify(body) : undefined,
413
422
  signal: controller.signal,
414
423
  });
415
- clearTimeout(timeoutId);
416
- const durationMs = Date.now() - start;
424
+ responseStatus = response.status;
417
425
  const methodName = this.extractMethodName(path);
418
426
  if (!response.ok) {
419
427
  const respBody = await response
420
428
  .json()
421
429
  .catch(() => ({ message: response.statusText }));
430
+ clearTimeout(timeoutId);
431
+ const durationMs = Math.round(performance.now() - start);
422
432
  this.telemetry.emit("sdk_call", {
423
433
  method: methodName,
424
434
  chain: chain || "server_default",
425
435
  duration_ms: durationMs,
426
436
  success: false,
427
437
  http_status: response.status,
428
- error_code: "API_ERROR",
438
+ error_code: typeof respBody.code === "string" ? respBody.code : "API_ERROR",
429
439
  retries: 0,
430
440
  timeout_count: 0,
431
441
  abort_count: 0,
@@ -434,6 +444,8 @@ class ValironClient {
434
444
  throw this.createApiError(response, respBody, path, "POST");
435
445
  }
436
446
  const data = await response.json();
447
+ clearTimeout(timeoutId);
448
+ const durationMs = Math.round(performance.now() - start);
437
449
  this.telemetry.emit("sdk_call", {
438
450
  method: methodName,
439
451
  chain: chain || "server_default",
@@ -451,7 +463,7 @@ class ValironClient {
451
463
  }
452
464
  catch (error) {
453
465
  clearTimeout(timeoutId);
454
- const durationMs = Date.now() - start;
466
+ const durationMs = Math.round(performance.now() - start);
455
467
  const methodName = this.extractMethodName(path);
456
468
  if (error.name === "AbortError") {
457
469
  this.telemetry.emit("sdk_call", {
@@ -470,23 +482,31 @@ class ValironClient {
470
482
  }
471
483
  if (error instanceof types_1.ValironError)
472
484
  throw error;
485
+ const errorCode = responseStatus === undefined ? "NETWORK_ERROR" : "RESPONSE_ERROR";
473
486
  this.telemetry.emit("sdk_call", {
474
487
  method: methodName,
475
488
  chain: chain || "server_default",
476
489
  duration_ms: durationMs,
477
490
  success: false,
478
- error_code: "NETWORK_ERROR",
491
+ http_status: responseStatus,
492
+ error_code: errorCode,
479
493
  retries: 0,
480
494
  timeout_count: 0,
481
495
  abort_count: 0,
482
496
  });
483
497
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
484
- 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." });
498
+ throw new types_1.ValironError(responseStatus === undefined
499
+ ? `Could not reach Valiron: ${error.message || "network error"}`
500
+ : `Could not read Valiron's response: ${error.message || "response error"}`, errorCode, responseStatus, { method: "POST", path, action: "Check your endpoint URL, network egress, and DNS configuration before retrying." });
485
501
  }
486
502
  }
487
503
  extractMethodName(path) {
504
+ if (/^\/operator\/agent\/[^/]+\/snapshot(?:\?|$)/.test(path))
505
+ return "getAgentSnapshot";
488
506
  if (path.startsWith("/operator/agent/"))
489
507
  return "getAgentProfile";
508
+ if (path === "/operator/identity/verify")
509
+ return "verifyAgentIdentity";
490
510
  if (path.startsWith("/operator/resolve-wallet/"))
491
511
  return "resolveWallet";
492
512
  if (path.startsWith("/operator/wallet-risk/"))
package/dist/telemetry.js CHANGED
@@ -1,7 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TelemetryClient = void 0;
4
- const SDK_VERSION = "1.1.1";
4
+ // Read the shipped package version so releases cannot drift from telemetry.
5
+ const SDK_VERSION = require("../package.json").version;
6
+ function detectEnvironment() {
7
+ const nodeEnv = globalThis.process?.env?.NODE_ENV;
8
+ if (nodeEnv === "production")
9
+ return "prod";
10
+ if (nodeEnv === "development")
11
+ return "dev";
12
+ if (nodeEnv === "test")
13
+ return "test";
14
+ return "unknown";
15
+ }
5
16
  function detectRuntime() {
6
17
  return typeof globalThis.window === "undefined" ? "node" : "browser";
7
18
  }
@@ -26,7 +37,7 @@ class TelemetryClient {
26
37
  this.endpoint = config?.endpoint || `${apiEndpoint.replace(/\/$/, "")}/telemetry/sdk`;
27
38
  this.appId = config?.appId;
28
39
  this.workspaceId = config?.workspaceId;
29
- this.env = config?.env || "prod";
40
+ this.env = config?.env ?? detectEnvironment();
30
41
  this.runtime = detectRuntime();
31
42
  this.sampleRate = Math.max(0, Math.min(1, config?.sampleRate ?? 1));
32
43
  this.batchSize = Math.max(1, config?.batchSize ?? 25);
@@ -62,9 +73,10 @@ class TelemetryClient {
62
73
  emit(event, payload) {
63
74
  if (!this.enabled)
64
75
  return;
65
- if (Math.random() > this.sampleRate)
76
+ if (this.sampleRate <= 0 || Math.random() >= this.sampleRate)
66
77
  return;
67
78
  const enriched = {
79
+ ...payload,
68
80
  event,
69
81
  ts: new Date().toISOString(),
70
82
  sdk_version: SDK_VERSION,
@@ -72,9 +84,13 @@ class TelemetryClient {
72
84
  env: this.env,
73
85
  app_id: this.appId,
74
86
  workspace_id: this.workspaceId,
75
- ...payload,
87
+ sample_rate: this.sampleRate,
76
88
  };
77
- this.onEvent?.(enriched);
89
+ // A telemetry callback must never change the outcome of the observed API call.
90
+ try {
91
+ this.onEvent?.({ ...enriched });
92
+ }
93
+ catch { /* Best-effort telemetry. */ }
78
94
  this.queue.push(enriched);
79
95
  if (this.queue.length >= this.batchSize) {
80
96
  void this.flush();
@@ -100,11 +116,15 @@ class TelemetryClient {
100
116
  return;
101
117
  const batch = this.queue.splice(0, this.queue.length);
102
118
  try {
103
- await fetch(this.endpoint, {
104
- method: "POST",
105
- headers: { "Content-Type": "application/json" },
106
- body: JSON.stringify({ events: batch }),
107
- });
119
+ // Keep every request within the ingestion limit, including final disposal
120
+ // and custom batch sizes.
121
+ for (let offset = 0; offset < batch.length; offset += 100) {
122
+ await fetch(this.endpoint, {
123
+ method: "POST",
124
+ headers: { "Content-Type": "application/json" },
125
+ body: JSON.stringify({ events: batch.slice(offset, offset + 100) }),
126
+ });
127
+ }
108
128
  }
109
129
  catch {
110
130
  // Best-effort telemetry: drop on failures to avoid impacting SDK consumers.
package/dist/types.d.ts CHANGED
@@ -551,7 +551,7 @@ export interface CallOptions {
551
551
  /** Customer-selected scoring signals for profile/routing calls. */
552
552
  trustSignals?: TrustSignal[];
553
553
  }
554
- export type TelemetryEnvironment = "prod" | "staging" | "dev";
554
+ export type TelemetryEnvironment = "prod" | "staging" | "dev" | "test" | "unknown";
555
555
  export interface TelemetryEventBase {
556
556
  event: string;
557
557
  ts: string;
@@ -567,6 +567,7 @@ export interface TelemetryConfig {
567
567
  endpoint?: string;
568
568
  appId?: string;
569
569
  workspaceId?: string;
570
+ /** Defaults to NODE_ENV when recognized, otherwise unknown. */
570
571
  env?: TelemetryEnvironment;
571
572
  sampleRate?: number;
572
573
  flushIntervalMs?: number;
@@ -969,6 +969,7 @@ Get the current operator's profile. Requires JWT.
969
969
  "role": "operator",
970
970
  "plan": "standard",
971
971
  "fee_rate": "0.03",
972
+ "onboarding_completed_at": "2026-01-01T00:05:00.000Z",
972
973
  "created_at": "2026-01-01T00:00:00.000Z",
973
974
  "updated_at": "2026-01-01T00:00:00.000Z"
974
975
  }
@@ -991,6 +992,30 @@ Update operator name. Requires JWT.
991
992
 
992
993
  ---
993
994
 
995
+ ### POST /operator/onboarding/complete
996
+
997
+ Mark the guided account setup as completed or dismissed. Requires JWT. This
998
+ endpoint is idempotent, so clients can safely retry it.
999
+
1000
+ New accounts have a null `onboarding_completed_at` value until this endpoint is
1001
+ called. Valiron uses that value to resume unfinished setup after email, Google,
1002
+ or GitHub authentication.
1003
+
1004
+ #### Response — 200 OK
1005
+
1006
+ ```json
1007
+ {
1008
+ "ok": true,
1009
+ "operator": {
1010
+ "id": "uuid",
1011
+ "email": "you@example.com",
1012
+ "onboarding_completed_at": "2026-01-01T00:05:00.000Z"
1013
+ }
1014
+ }
1015
+ ```
1016
+
1017
+ ---
1018
+
994
1019
  ### GET /operator/keys
995
1020
 
996
1021
  List all API keys for the current operator. Requires JWT.
package/docs/DASHBOARD.md CHANGED
@@ -11,10 +11,21 @@
11
11
  To create an account:
12
12
 
13
13
  1. Go to [valiron.co/dashboard](https://www.valiron.co/dashboard) and click **Create account**
14
- 2. Enter your name, email, and password
14
+ 2. Enter your name, email, and password, or continue with Google or GitHub
15
15
  3. On success, you'll see a **one-time API key** — copy it immediately (it won't be shown again)
16
+ 4. Complete the same guided setup for every sign-up method: Account, Signals, Policy, Endpoint, Install, Deploy, and Finish
16
17
 
17
- After registration, sign in with your email and password. Your session is stored as a JWT in the browser.
18
+ Onboarding completion is stored on the operator account, so an unfinished setup
19
+ resumes after email, Google, or GitHub login and on another browser. If the
20
+ original one-time key is no longer available, the wizard can generate a
21
+ dedicated setup key. Existing operators are not forced back through onboarding.
22
+
23
+ The Signals step supports registered ERC-8004/Solana agents, persistent
24
+ key-based agents, and ANS or other provider-backed identities. ANS is an agent
25
+ identity option; it is not required to create a Valiron operator account.
26
+
27
+ After registration, sign in with your email and password, Google, or GitHub.
28
+ Your session is stored as a JWT in the browser.
18
29
 
19
30
  ---
20
31
 
@@ -4,9 +4,10 @@
4
4
 
5
5
  ## Prerequisites
6
6
 
7
- 1. **Create an account** on the [Operator Dashboard](./DASHBOARD.md) at [valiron.co/dashboard](https://www.valiron.co/dashboard)
8
- 2. **Copy your API key** from the Keys page
9
- 3. Add the SDK middleware below to the backend routes agents call.
7
+ 1. **Create an account** with email/password, Google, or GitHub on the [Operator Dashboard](./DASHBOARD.md) at [valiron.co/dashboard](https://www.valiron.co/dashboard)
8
+ 2. **Complete the guided setup** — every sign-up method enters the same resumable onboarding flow
9
+ 3. **Copy your API key** when it is shown; returning incomplete accounts can generate a dedicated setup key
10
+ 4. Add the SDK middleware below to the backend routes agents call. Choose registered, key-based, or ANS/provider-backed identity in the wizard.
10
11
 
11
12
  > **Tip:** Before writing any code, try the [API Playground](./DASHBOARD.md#api-playground) to see how Valiron evaluates agents at different trust levels against your endpoints.
12
13
 
@@ -654,13 +654,16 @@ Trusted-payload ingestion for local/internal tests only. Production integrations
654
654
 
655
655
  The SDK collects opt-out usage telemetry to improve reliability. Events include SDK version, runtime, environment, method names, chain labels, latency, HTTP status/error buckets, route decisions, and coarse score/reputation buckets. Raw agent IDs, wallet addresses, API keys, and exact scores are not sent in SDK telemetry. Operator paywall usage logs are separate customer analytics and are authenticated with the operator API key.
656
656
 
657
+ SDK reports are anonymous client reports and may be sampled. Signal counts describe reported selections, not successful verifications. Version comes from the shipped package metadata. Environment defaults to recognized `NODE_ENV` values (`production` → `prod`, `development` → `dev`, `test` → `test`), otherwise `unknown`; set it explicitly for browser applications. Telemetry observer failures do not affect API calls. Server statistics identify persisted counters versus counters limited to one process, and latency percentiles cover the latest 1,000 reported calls per method, chain, and version.
658
+
657
659
  ### TelemetryConfig
658
660
 
659
661
  | Field | Type | Default | Description |
660
662
  |-------|------|---------|-------------|
661
663
  | `enabled` | boolean | `true` | Enable/disable telemetry |
662
664
  | `sampleRate` | number | `1.0` | Fraction of events to sample (0–1) |
663
- | `onEvent` | function | — | Custom event handler |
665
+ | `env` | prod / staging / dev / test / unknown | NODE_ENV or unknown | Environment label |
666
+ | `onEvent` | function | — | Custom event handler; failures are isolated from API calls |
664
667
 
665
668
  **Example**:
666
669
  ```typescript
package/docs/llms.txt CHANGED
@@ -241,7 +241,7 @@ New key agents are automatically sandbox-evaluated on first gated request. Middl
241
241
 
242
242
  ## Telemetry
243
243
 
244
- Opt-in anonymous usage metrics. Disable with `telemetry: { enabled: false }`. Supports custom sampleRate (0–1) and custom handler function.
244
+ Opt-out anonymous client usage reports. Disable with `telemetry: { enabled: false }`. Supports custom sampleRate (0–1) and custom handler function. Environment defaults to recognized NODE_ENV values, otherwise unknown. Signal selections do not measure successful verifications.
245
245
 
246
246
  ## Middleware Error Responses
247
247
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valiron/sdk",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Official TypeScript SDK for Valiron — Trust & Reputation Middleware for API Protection",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,7 +20,7 @@
20
20
  "clean": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true});\"",
21
21
  "build": "pnpm clean && tsc",
22
22
  "dev": "tsc --watch",
23
- "test": "node test/validate.mjs && node test/validate-examples.mjs && node test/validate-middleware.mjs && node test/validate-provider-identity.mjs && tsx test/test-identity.ts",
23
+ "test": "node test/validate-telemetry.mjs && node test/validate.mjs && node test/validate-examples.mjs && node test/validate-middleware.mjs && node test/validate-provider-identity.mjs && node --import tsx test/test-identity.ts",
24
24
  "prepublishOnly": "pnpm build"
25
25
  },
26
26
  "keywords": [