@valiron/sdk 1.0.1 → 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 +6 -0
- package/dist/clients.d.ts +4 -0
- package/dist/clients.js +33 -6
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -0
- package/dist/middleware.d.ts +9 -1
- package/dist/middleware.js +227 -9
- package/dist/operatorSdk.d.ts +11 -1
- package/dist/operatorSdk.js +151 -3
- package/dist/telemetry.js +1 -1
- package/dist/types.d.ts +9 -2
- package/docs/API-REFERENCE.md +5 -1
- package/docs/ERRORS.md +1 -1
- package/docs/QUICKSTART.md +13 -1
- package/docs/SDK-REFERENCE.md +6 -4
- package/docs/TRUST-MODEL.md +36 -4
- package/package.json +1 -1
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
|
```
|
package/dist/clients.d.ts
CHANGED
|
@@ -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);
|
|
@@ -151,8 +152,11 @@ export declare class ValironClient {
|
|
|
151
152
|
getWorldIdProfile(agentId: string, options?: CallOptions): Promise<WorldIdAgentProfile>;
|
|
152
153
|
/** Flush any pending telemetry events and clean up resources. */
|
|
153
154
|
dispose(): Promise<void>;
|
|
155
|
+
/** Emit an SDK telemetry event from higher-level helpers. */
|
|
156
|
+
emitTelemetry(event: string, payload: Record<string, unknown>): void;
|
|
154
157
|
private buildHeaders;
|
|
155
158
|
private get;
|
|
156
159
|
private post;
|
|
157
160
|
private extractMethodName;
|
|
161
|
+
private getTimeoutForPath;
|
|
158
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.
|
|
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
|
|
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
|
}
|
|
@@ -215,6 +223,10 @@ class ValironClient {
|
|
|
215
223
|
async dispose() {
|
|
216
224
|
await this.telemetry.dispose();
|
|
217
225
|
}
|
|
226
|
+
/** Emit an SDK telemetry event from higher-level helpers. */
|
|
227
|
+
emitTelemetry(event, payload) {
|
|
228
|
+
this.telemetry.emit(event, payload);
|
|
229
|
+
}
|
|
218
230
|
// ─── HTTP helpers ───────────────────────────────────────────────────────
|
|
219
231
|
buildHeaders() {
|
|
220
232
|
const headers = {
|
|
@@ -233,7 +245,8 @@ class ValironClient {
|
|
|
233
245
|
console.log(`[Valiron SDK] GET ${url.toString()}`);
|
|
234
246
|
}
|
|
235
247
|
const controller = new AbortController();
|
|
236
|
-
const
|
|
248
|
+
const timeoutMs = this.getTimeoutForPath(path);
|
|
249
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
237
250
|
const start = Date.now();
|
|
238
251
|
try {
|
|
239
252
|
const response = await fetch(url.toString(), {
|
|
@@ -292,9 +305,10 @@ class ValironClient {
|
|
|
292
305
|
retries: 0,
|
|
293
306
|
timeout_count: 1,
|
|
294
307
|
abort_count: 1,
|
|
308
|
+
timeout_ms: timeoutMs,
|
|
295
309
|
});
|
|
296
310
|
this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
|
|
297
|
-
throw new types_1.ValironError(`Request timeout after ${
|
|
311
|
+
throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
|
|
298
312
|
}
|
|
299
313
|
if (error instanceof types_1.ValironError)
|
|
300
314
|
throw error;
|
|
@@ -320,7 +334,8 @@ class ValironClient {
|
|
|
320
334
|
console.log(`[Valiron SDK] POST ${url.toString()}`, body);
|
|
321
335
|
}
|
|
322
336
|
const controller = new AbortController();
|
|
323
|
-
const
|
|
337
|
+
const timeoutMs = this.getTimeoutForPath(path);
|
|
338
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
324
339
|
const start = Date.now();
|
|
325
340
|
try {
|
|
326
341
|
const headers = this.buildHeaders();
|
|
@@ -384,9 +399,10 @@ class ValironClient {
|
|
|
384
399
|
retries: 0,
|
|
385
400
|
timeout_count: 1,
|
|
386
401
|
abort_count: 1,
|
|
402
|
+
timeout_ms: timeoutMs,
|
|
387
403
|
});
|
|
388
404
|
this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
|
|
389
|
-
throw new types_1.ValironError(`Request timeout after ${
|
|
405
|
+
throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
|
|
390
406
|
}
|
|
391
407
|
if (error instanceof types_1.ValironError)
|
|
392
408
|
throw error;
|
|
@@ -425,5 +441,16 @@ class ValironClient {
|
|
|
425
441
|
return "keyAgent";
|
|
426
442
|
return "unknown";
|
|
427
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
|
+
}
|
|
428
455
|
}
|
|
429
456
|
exports.ValironClient = ValironClient;
|
package/dist/index.d.ts
CHANGED
|
@@ -375,6 +375,8 @@ export declare class ValironSDK {
|
|
|
375
375
|
* ```
|
|
376
376
|
*/
|
|
377
377
|
dispose(): Promise<void>;
|
|
378
|
+
/** @internal Emit Valiron SDK telemetry from helper modules. */
|
|
379
|
+
emitTelemetry(event: string, payload: Record<string, unknown>): void;
|
|
378
380
|
}
|
|
379
381
|
export * from "./types";
|
|
380
382
|
export { ValironClient } from "./clients";
|
package/dist/index.js
CHANGED
|
@@ -411,6 +411,10 @@ class ValironSDK {
|
|
|
411
411
|
dispose() {
|
|
412
412
|
return this.client.dispose();
|
|
413
413
|
}
|
|
414
|
+
/** @internal Emit Valiron SDK telemetry from helper modules. */
|
|
415
|
+
emitTelemetry(event, payload) {
|
|
416
|
+
this.client.emitTelemetry(event, payload);
|
|
417
|
+
}
|
|
414
418
|
}
|
|
415
419
|
exports.ValironSDK = ValironSDK;
|
|
416
420
|
// Re-export everything
|
package/dist/middleware.d.ts
CHANGED
|
@@ -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,6 +23,8 @@ export interface ValironGateConfig {
|
|
|
23
23
|
extractAgentAddress?: (req: any) => string | null;
|
|
24
24
|
/** Minimum Valiron score to allow (default: 65). */
|
|
25
25
|
minScore?: number;
|
|
26
|
+
/** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
|
|
27
|
+
trustSignals?: TrustSignal[];
|
|
26
28
|
/**
|
|
27
29
|
* Client-side profile cache TTL in ms.
|
|
28
30
|
*
|
|
@@ -89,6 +91,8 @@ export interface ValironFastifyConfig {
|
|
|
89
91
|
extractAgentAddress?: (req: any) => string | null;
|
|
90
92
|
/** Minimum Valiron score to allow (default: 65). */
|
|
91
93
|
minScore?: number;
|
|
94
|
+
/** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
|
|
95
|
+
trustSignals?: TrustSignal[];
|
|
92
96
|
/**
|
|
93
97
|
* Client-side profile cache TTL in ms (default: 30000).
|
|
94
98
|
* Set to `0` to disable.
|
|
@@ -150,6 +154,8 @@ export interface ValironNextConfig {
|
|
|
150
154
|
extractAgentAddress?: (req: Request) => string | null;
|
|
151
155
|
/** Minimum Valiron score to allow (default: 65). */
|
|
152
156
|
minScore?: number;
|
|
157
|
+
/** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
|
|
158
|
+
trustSignals?: TrustSignal[];
|
|
153
159
|
/**
|
|
154
160
|
* Client-side profile cache TTL in ms (default: 30000).
|
|
155
161
|
* Set to `0` to disable.
|
|
@@ -264,6 +270,8 @@ export declare function valironGateCheck(sdk: ValironSDK, opts: {
|
|
|
264
270
|
/** Key-based agent hash (web2). Checked if agentId is not provided. */
|
|
265
271
|
agentAddress?: string | null;
|
|
266
272
|
minScore?: number;
|
|
273
|
+
/** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
|
|
274
|
+
trustSignals?: TrustSignal[];
|
|
267
275
|
/**
|
|
268
276
|
* Client-side profile cache TTL in ms (default: 30000).
|
|
269
277
|
* Set to `0` to disable.
|
package/dist/middleware.js
CHANGED
|
@@ -138,6 +138,48 @@ function getGateCheckCache(sdk) {
|
|
|
138
138
|
}
|
|
139
139
|
return cache;
|
|
140
140
|
}
|
|
141
|
+
function normalizeTrustSignals(trustSignals) {
|
|
142
|
+
return trustSignals?.length ? [...trustSignals].sort() : undefined;
|
|
143
|
+
}
|
|
144
|
+
function cacheKeyFor(agentId, trustSignals) {
|
|
145
|
+
const normalized = normalizeTrustSignals(trustSignals);
|
|
146
|
+
return normalized ? `${agentId}:${normalized.join(",")}` : agentId;
|
|
147
|
+
}
|
|
148
|
+
function bucketScore(score) {
|
|
149
|
+
if (score === undefined || !Number.isFinite(score))
|
|
150
|
+
return "unknown";
|
|
151
|
+
if (score <= 40)
|
|
152
|
+
return "0-40";
|
|
153
|
+
if (score <= 70)
|
|
154
|
+
return "41-70";
|
|
155
|
+
if (score <= 90)
|
|
156
|
+
return "71-90";
|
|
157
|
+
return "91+";
|
|
158
|
+
}
|
|
159
|
+
function emitGateTelemetry(sdk, payload) {
|
|
160
|
+
if (typeof sdk.emitTelemetry !== "function")
|
|
161
|
+
return;
|
|
162
|
+
const signals = normalizeTrustSignals(payload.trustSignals);
|
|
163
|
+
sdk.emitTelemetry("gate_decision", {
|
|
164
|
+
framework: payload.framework,
|
|
165
|
+
agent_type: payload.agentType,
|
|
166
|
+
chain: payload.chain || "unknown",
|
|
167
|
+
allow: payload.allow,
|
|
168
|
+
route: payload.route,
|
|
169
|
+
tier: payload.tier,
|
|
170
|
+
risk_level: payload.riskLevel,
|
|
171
|
+
score_bucket: bucketScore(payload.score),
|
|
172
|
+
min_score_bucket: bucketScore(payload.minScore),
|
|
173
|
+
cached: payload.cached,
|
|
174
|
+
pending_evaluation: payload.pendingEvaluation || false,
|
|
175
|
+
trust_signals: signals?.join(","),
|
|
176
|
+
trust_signal_count: signals?.length,
|
|
177
|
+
world_included: signals?.includes("world"),
|
|
178
|
+
icebreaker_included: signals?.includes("icebreaker"),
|
|
179
|
+
status: payload.status || "ok",
|
|
180
|
+
latency_ms: payload.latencyMs,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
141
183
|
async function runGateCheck(config, req, cache) {
|
|
142
184
|
const minScore = config.minScore ?? 65;
|
|
143
185
|
const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
@@ -145,9 +187,10 @@ async function runGateCheck(config, req, cache) {
|
|
|
145
187
|
const extractAgentId = config.extractAgentId || defaultExtractAgentId;
|
|
146
188
|
const agentId = extractAgentId(req);
|
|
147
189
|
if (agentId) {
|
|
190
|
+
const agentCacheKey = cacheKeyFor(agentId, config.trustSignals);
|
|
148
191
|
// Check client-side cache first
|
|
149
192
|
if (cacheTtl > 0) {
|
|
150
|
-
const cached = cache.getCached(
|
|
193
|
+
const cached = cache.getCached(agentCacheKey, cacheTtl);
|
|
151
194
|
if (cached)
|
|
152
195
|
return { agentId, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
|
|
153
196
|
}
|
|
@@ -155,7 +198,9 @@ async function runGateCheck(config, req, cache) {
|
|
|
155
198
|
// Use getAgentProfile() which hits the PUBLIC /operator/agent/ endpoint.
|
|
156
199
|
// The old gate() call used POST /operator/gate/ which is protected by
|
|
157
200
|
// agent challenge-response auth and fails from server contexts.
|
|
158
|
-
const profile = await config.sdk.getAgentProfile(agentId
|
|
201
|
+
const profile = await config.sdk.getAgentProfile(agentId, {
|
|
202
|
+
trustSignals: normalizeTrustSignals(config.trustSignals),
|
|
203
|
+
});
|
|
159
204
|
const result = profileToGateResult(profile, minScore);
|
|
160
205
|
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
161
206
|
// Trigger a sandbox evaluation so the agent can build a score.
|
|
@@ -167,7 +212,7 @@ async function runGateCheck(config, req, cache) {
|
|
|
167
212
|
config.sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
168
213
|
}
|
|
169
214
|
if (cacheTtl > 0)
|
|
170
|
-
cache.setCache(
|
|
215
|
+
cache.setCache(agentCacheKey, result, isNewAgent || undefined);
|
|
171
216
|
return { agentId, result, pendingEvaluation: isNewAgent || undefined };
|
|
172
217
|
}
|
|
173
218
|
catch (error) {
|
|
@@ -178,9 +223,10 @@ async function runGateCheck(config, req, cache) {
|
|
|
178
223
|
const extractAddress = config.extractAgentAddress || defaultExtractAgentAddress;
|
|
179
224
|
const agentAddr = extractAddress(req);
|
|
180
225
|
if (agentAddr) {
|
|
226
|
+
const agentCacheKey = cacheKeyFor(agentAddr, config.trustSignals);
|
|
181
227
|
// Check client-side cache first
|
|
182
228
|
if (cacheTtl > 0) {
|
|
183
|
-
const cached = cache.getCached(
|
|
229
|
+
const cached = cache.getCached(agentCacheKey, cacheTtl);
|
|
184
230
|
if (cached)
|
|
185
231
|
return { agentId: agentAddr, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
|
|
186
232
|
}
|
|
@@ -194,7 +240,7 @@ async function runGateCheck(config, req, cache) {
|
|
|
194
240
|
config.sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
|
|
195
241
|
}
|
|
196
242
|
if (cacheTtl > 0)
|
|
197
|
-
cache.setCache(
|
|
243
|
+
cache.setCache(agentCacheKey, result, isNewKeyAgent || undefined);
|
|
198
244
|
return { agentId: agentAddr, result, pendingEvaluation: isNewKeyAgent || undefined };
|
|
199
245
|
}
|
|
200
246
|
catch (error) {
|
|
@@ -244,8 +290,22 @@ function createValironGate(config) {
|
|
|
244
290
|
const frozen = { ...config };
|
|
245
291
|
const cache = createProfileCache();
|
|
246
292
|
async function valironGateHandler(req, res, next) {
|
|
293
|
+
const startedAt = Date.now();
|
|
247
294
|
const { agentId, result, error, pendingEvaluation } = await runGateCheck(frozen, req, cache);
|
|
295
|
+
const latencyMs = Date.now() - startedAt;
|
|
296
|
+
const minScore = frozen.minScore ?? 65;
|
|
297
|
+
const agentType = agentId
|
|
298
|
+
? (defaultExtractAgentAddress(req) === agentId ? "key" : "onchain")
|
|
299
|
+
: "missing";
|
|
248
300
|
if (!agentId) {
|
|
301
|
+
emitGateTelemetry(frozen.sdk, {
|
|
302
|
+
framework: "express",
|
|
303
|
+
agentType: "missing",
|
|
304
|
+
minScore,
|
|
305
|
+
trustSignals: frozen.trustSignals,
|
|
306
|
+
status: "missing_identity",
|
|
307
|
+
latencyMs,
|
|
308
|
+
});
|
|
249
309
|
return res.status(401).json({
|
|
250
310
|
error: "Missing agent identity",
|
|
251
311
|
message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
|
|
@@ -253,10 +313,33 @@ function createValironGate(config) {
|
|
|
253
313
|
});
|
|
254
314
|
}
|
|
255
315
|
if (error) {
|
|
316
|
+
emitGateTelemetry(frozen.sdk, {
|
|
317
|
+
framework: "express",
|
|
318
|
+
agentType,
|
|
319
|
+
minScore,
|
|
320
|
+
trustSignals: frozen.trustSignals,
|
|
321
|
+
status: "error",
|
|
322
|
+
latencyMs,
|
|
323
|
+
});
|
|
256
324
|
return res.status(503).json({
|
|
257
325
|
error: "Trust gate unavailable \u2014 request denied (fail-closed)",
|
|
258
326
|
});
|
|
259
327
|
}
|
|
328
|
+
emitGateTelemetry(frozen.sdk, {
|
|
329
|
+
framework: "express",
|
|
330
|
+
agentType,
|
|
331
|
+
chain: result.chain?.network,
|
|
332
|
+
allow: result.allow,
|
|
333
|
+
route: result.route,
|
|
334
|
+
tier: result.tier,
|
|
335
|
+
riskLevel: result.riskLevel,
|
|
336
|
+
score: result.score,
|
|
337
|
+
minScore,
|
|
338
|
+
cached: result.cached,
|
|
339
|
+
pendingEvaluation,
|
|
340
|
+
trustSignals: frozen.trustSignals,
|
|
341
|
+
latencyMs,
|
|
342
|
+
});
|
|
260
343
|
if (result.allow) {
|
|
261
344
|
req.valiron = result;
|
|
262
345
|
if (config.onAllow)
|
|
@@ -341,8 +424,22 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
341
424
|
if (pathname !== prefix && !pathname.startsWith(prefix + "/"))
|
|
342
425
|
return;
|
|
343
426
|
}
|
|
427
|
+
const startedAt = Date.now();
|
|
344
428
|
const { agentId, result, error, pendingEvaluation } = await runGateCheck(gateConfig, request, cache);
|
|
429
|
+
const latencyMs = Date.now() - startedAt;
|
|
430
|
+
const minScore = opts.minScore ?? 65;
|
|
431
|
+
const agentType = agentId
|
|
432
|
+
? (defaultExtractAgentAddress(request) === agentId ? "key" : "onchain")
|
|
433
|
+
: "missing";
|
|
345
434
|
if (!agentId) {
|
|
435
|
+
emitGateTelemetry(opts.sdk, {
|
|
436
|
+
framework: "fastify",
|
|
437
|
+
agentType: "missing",
|
|
438
|
+
minScore,
|
|
439
|
+
trustSignals: opts.trustSignals,
|
|
440
|
+
status: "missing_identity",
|
|
441
|
+
latencyMs,
|
|
442
|
+
});
|
|
346
443
|
return reply.status(401).send({
|
|
347
444
|
error: "Missing agent identity",
|
|
348
445
|
message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
|
|
@@ -350,10 +447,33 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
350
447
|
});
|
|
351
448
|
}
|
|
352
449
|
if (error) {
|
|
450
|
+
emitGateTelemetry(opts.sdk, {
|
|
451
|
+
framework: "fastify",
|
|
452
|
+
agentType,
|
|
453
|
+
minScore,
|
|
454
|
+
trustSignals: opts.trustSignals,
|
|
455
|
+
status: "error",
|
|
456
|
+
latencyMs,
|
|
457
|
+
});
|
|
353
458
|
return reply.status(503).send({
|
|
354
459
|
error: "Trust gate unavailable \u2014 request denied (fail-closed)",
|
|
355
460
|
});
|
|
356
461
|
}
|
|
462
|
+
emitGateTelemetry(opts.sdk, {
|
|
463
|
+
framework: "fastify",
|
|
464
|
+
agentType,
|
|
465
|
+
chain: result.chain?.network,
|
|
466
|
+
allow: result.allow,
|
|
467
|
+
route: result.route,
|
|
468
|
+
tier: result.tier,
|
|
469
|
+
riskLevel: result.riskLevel,
|
|
470
|
+
score: result.score,
|
|
471
|
+
minScore,
|
|
472
|
+
cached: result.cached,
|
|
473
|
+
pendingEvaluation,
|
|
474
|
+
trustSignals: opts.trustSignals,
|
|
475
|
+
latencyMs,
|
|
476
|
+
});
|
|
357
477
|
if (result.allow) {
|
|
358
478
|
request.valiron = result;
|
|
359
479
|
if (opts.onAllow)
|
|
@@ -406,13 +526,14 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
406
526
|
* ```
|
|
407
527
|
*/
|
|
408
528
|
function createValironNextMiddleware(config) {
|
|
409
|
-
const { sdk, minScore, paths } = config;
|
|
529
|
+
const { sdk, minScore, paths, trustSignals } = config;
|
|
410
530
|
const cache = createProfileCache();
|
|
411
531
|
const extractAgentId = config.extractAgentId ||
|
|
412
532
|
((req) => req.headers.get("x-agent-id"));
|
|
413
533
|
const extractAddress = config.extractAgentAddress ||
|
|
414
534
|
((req) => req.headers.get("x-agent-address") || req.headers.get("x-agent-key-hash"));
|
|
415
535
|
return async function valironNextGate(request) {
|
|
536
|
+
const startedAt = Date.now();
|
|
416
537
|
// Skip paths not in scope
|
|
417
538
|
if (paths && paths.length > 0) {
|
|
418
539
|
const url = new URL(request.url);
|
|
@@ -424,6 +545,14 @@ function createValironNextMiddleware(config) {
|
|
|
424
545
|
const agentId = extractAgentId(request);
|
|
425
546
|
const agentAddr = agentId ? null : extractAddress(request);
|
|
426
547
|
if (!agentId && !agentAddr) {
|
|
548
|
+
emitGateTelemetry(sdk, {
|
|
549
|
+
framework: "next",
|
|
550
|
+
agentType: "missing",
|
|
551
|
+
minScore: minScore ?? 65,
|
|
552
|
+
trustSignals,
|
|
553
|
+
status: "missing_identity",
|
|
554
|
+
latencyMs: Date.now() - startedAt,
|
|
555
|
+
});
|
|
427
556
|
return Response.json({
|
|
428
557
|
error: "Missing agent identity",
|
|
429
558
|
message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
|
|
@@ -440,13 +569,30 @@ function createValironNextMiddleware(config) {
|
|
|
440
569
|
if (cacheTtl > 0) {
|
|
441
570
|
const cached = cache.getCached(identifier, cacheTtl);
|
|
442
571
|
if (cached) {
|
|
572
|
+
emitGateTelemetry(sdk, {
|
|
573
|
+
framework: "next",
|
|
574
|
+
agentType: agentId ? "onchain" : "key",
|
|
575
|
+
chain: cached.result.chain?.network,
|
|
576
|
+
allow: cached.result.allow,
|
|
577
|
+
route: cached.result.route,
|
|
578
|
+
tier: cached.result.tier,
|
|
579
|
+
riskLevel: cached.result.riskLevel,
|
|
580
|
+
score: cached.result.score,
|
|
581
|
+
minScore: effectiveMinScore,
|
|
582
|
+
cached: true,
|
|
583
|
+
pendingEvaluation: cached.pendingEvaluation,
|
|
584
|
+
trustSignals,
|
|
585
|
+
latencyMs: Date.now() - startedAt,
|
|
586
|
+
});
|
|
443
587
|
if (cached.result.allow)
|
|
444
588
|
return undefined;
|
|
445
589
|
return Response.json({ error: "Agent blocked by Valiron trust gate", ...cached.result }, { status: 403 });
|
|
446
590
|
}
|
|
447
591
|
}
|
|
448
592
|
if (agentId) {
|
|
449
|
-
const profile = await sdk.getAgentProfile(agentId
|
|
593
|
+
const profile = await sdk.getAgentProfile(agentId, {
|
|
594
|
+
trustSignals: normalizeTrustSignals(trustSignals),
|
|
595
|
+
});
|
|
450
596
|
result = profileToGateResult(profile, effectiveMinScore);
|
|
451
597
|
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
452
598
|
if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
|
|
@@ -467,6 +613,21 @@ function createValironNextMiddleware(config) {
|
|
|
467
613
|
}
|
|
468
614
|
if (cacheTtl > 0)
|
|
469
615
|
cache.setCache(identifier, result, pendingEvaluation || undefined);
|
|
616
|
+
emitGateTelemetry(sdk, {
|
|
617
|
+
framework: "next",
|
|
618
|
+
agentType: agentId ? "onchain" : "key",
|
|
619
|
+
chain: result.chain?.network,
|
|
620
|
+
allow: result.allow,
|
|
621
|
+
route: result.route,
|
|
622
|
+
tier: result.tier,
|
|
623
|
+
riskLevel: result.riskLevel,
|
|
624
|
+
score: result.score,
|
|
625
|
+
minScore: effectiveMinScore,
|
|
626
|
+
cached: result.cached,
|
|
627
|
+
pendingEvaluation,
|
|
628
|
+
trustSignals,
|
|
629
|
+
latencyMs: Date.now() - startedAt,
|
|
630
|
+
});
|
|
470
631
|
if (result.allow) {
|
|
471
632
|
return undefined; // continue to route handler
|
|
472
633
|
}
|
|
@@ -481,6 +642,14 @@ function createValironNextMiddleware(config) {
|
|
|
481
642
|
return Response.json({ error: "Agent blocked by Valiron trust gate", ...result }, { status: 403 });
|
|
482
643
|
}
|
|
483
644
|
catch {
|
|
645
|
+
emitGateTelemetry(sdk, {
|
|
646
|
+
framework: "next",
|
|
647
|
+
agentType: agentId ? "onchain" : "key",
|
|
648
|
+
minScore: effectiveMinScore,
|
|
649
|
+
trustSignals,
|
|
650
|
+
status: "error",
|
|
651
|
+
latencyMs: Date.now() - startedAt,
|
|
652
|
+
});
|
|
484
653
|
return Response.json({ error: "Trust gate unavailable \u2014 request denied (fail-closed)" }, { status: 503 });
|
|
485
654
|
}
|
|
486
655
|
};
|
|
@@ -528,9 +697,18 @@ function createValironNextMiddleware(config) {
|
|
|
528
697
|
* ```
|
|
529
698
|
*/
|
|
530
699
|
async function valironGateCheck(sdk, opts) {
|
|
531
|
-
const { agentId, agentAddress, minScore } = opts;
|
|
700
|
+
const { agentId, agentAddress, minScore, trustSignals } = opts;
|
|
701
|
+
const startedAt = Date.now();
|
|
532
702
|
const identifier = agentId || agentAddress || null;
|
|
533
703
|
if (!identifier) {
|
|
704
|
+
emitGateTelemetry(sdk, {
|
|
705
|
+
framework: "generic",
|
|
706
|
+
agentType: "missing",
|
|
707
|
+
minScore: minScore ?? 65,
|
|
708
|
+
trustSignals,
|
|
709
|
+
status: "missing_identity",
|
|
710
|
+
latencyMs: Date.now() - startedAt,
|
|
711
|
+
});
|
|
534
712
|
return {
|
|
535
713
|
hasAgent: false,
|
|
536
714
|
agentId: null,
|
|
@@ -551,6 +729,21 @@ async function valironGateCheck(sdk, opts) {
|
|
|
551
729
|
if (cacheTtl > 0) {
|
|
552
730
|
const cached = cache.getCached(identifier, cacheTtl);
|
|
553
731
|
if (cached) {
|
|
732
|
+
emitGateTelemetry(sdk, {
|
|
733
|
+
framework: "generic",
|
|
734
|
+
agentType: agentId ? "onchain" : "key",
|
|
735
|
+
chain: cached.result.chain?.network,
|
|
736
|
+
allow: cached.result.allow,
|
|
737
|
+
route: cached.result.route,
|
|
738
|
+
tier: cached.result.tier,
|
|
739
|
+
riskLevel: cached.result.riskLevel,
|
|
740
|
+
score: cached.result.score,
|
|
741
|
+
minScore: effectiveMinScore,
|
|
742
|
+
cached: true,
|
|
743
|
+
pendingEvaluation: cached.pendingEvaluation,
|
|
744
|
+
trustSignals,
|
|
745
|
+
latencyMs: Date.now() - startedAt,
|
|
746
|
+
});
|
|
554
747
|
if (cached.result.allow) {
|
|
555
748
|
return { hasAgent: true, agentId: identifier, ok: true, allow: true, result: cached.result, status: 200 };
|
|
556
749
|
}
|
|
@@ -570,7 +763,9 @@ async function valironGateCheck(sdk, opts) {
|
|
|
570
763
|
let result;
|
|
571
764
|
let pendingEvaluation = false;
|
|
572
765
|
if (agentId) {
|
|
573
|
-
const profile = await sdk.getAgentProfile(agentId
|
|
766
|
+
const profile = await sdk.getAgentProfile(agentId, {
|
|
767
|
+
trustSignals: normalizeTrustSignals(trustSignals),
|
|
768
|
+
});
|
|
574
769
|
result = profileToGateResult(profile, effectiveMinScore);
|
|
575
770
|
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
576
771
|
if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
|
|
@@ -591,6 +786,21 @@ async function valironGateCheck(sdk, opts) {
|
|
|
591
786
|
}
|
|
592
787
|
if (cacheTtl > 0)
|
|
593
788
|
cache.setCache(identifier, result, pendingEvaluation || undefined);
|
|
789
|
+
emitGateTelemetry(sdk, {
|
|
790
|
+
framework: "generic",
|
|
791
|
+
agentType: agentId ? "onchain" : "key",
|
|
792
|
+
chain: result.chain?.network,
|
|
793
|
+
allow: result.allow,
|
|
794
|
+
route: result.route,
|
|
795
|
+
tier: result.tier,
|
|
796
|
+
riskLevel: result.riskLevel,
|
|
797
|
+
score: result.score,
|
|
798
|
+
minScore: effectiveMinScore,
|
|
799
|
+
cached: result.cached,
|
|
800
|
+
pendingEvaluation,
|
|
801
|
+
trustSignals,
|
|
802
|
+
latencyMs: Date.now() - startedAt,
|
|
803
|
+
});
|
|
594
804
|
if (result.allow) {
|
|
595
805
|
return { hasAgent: true, agentId: identifier, ok: true, allow: true, result, status: 200 };
|
|
596
806
|
}
|
|
@@ -622,6 +832,14 @@ async function valironGateCheck(sdk, opts) {
|
|
|
622
832
|
};
|
|
623
833
|
}
|
|
624
834
|
catch {
|
|
835
|
+
emitGateTelemetry(sdk, {
|
|
836
|
+
framework: "generic",
|
|
837
|
+
agentType: agentId ? "onchain" : "key",
|
|
838
|
+
minScore: effectiveMinScore,
|
|
839
|
+
trustSignals,
|
|
840
|
+
status: "error",
|
|
841
|
+
latencyMs: Date.now() - startedAt,
|
|
842
|
+
});
|
|
625
843
|
return {
|
|
626
844
|
hasAgent: true,
|
|
627
845
|
agentId: identifier,
|
package/dist/operatorSdk.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ValironSDK } from "./index.js";
|
|
2
|
-
import type { SupportedChain } from "./types.js";
|
|
2
|
+
import type { SupportedChain, TrustSignal } from "./types.js";
|
|
3
3
|
/**
|
|
4
4
|
* Configuration for the Valiron Operator SDK.
|
|
5
5
|
*/
|
|
@@ -23,6 +23,8 @@ export interface PaywallConfig {
|
|
|
23
23
|
pricePerCall: number;
|
|
24
24
|
/** Minimum trust score to allow (default: 45). */
|
|
25
25
|
minTrustScore?: number;
|
|
26
|
+
/** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
|
|
27
|
+
trustSignals?: TrustSignal[];
|
|
26
28
|
/**
|
|
27
29
|
* Server-side gate result TTL in ms (default: 86400000 = 24h).
|
|
28
30
|
* @deprecated Use `cacheTtlMs` for client-side cache control.
|
|
@@ -66,7 +68,15 @@ export declare class ValironOperator {
|
|
|
66
68
|
private sdk;
|
|
67
69
|
private apiKey;
|
|
68
70
|
private debug;
|
|
71
|
+
private endpoint;
|
|
69
72
|
constructor(config: ValironOperatorConfig);
|
|
73
|
+
private buildAnalyticsUrl;
|
|
74
|
+
private recordUsage;
|
|
75
|
+
private extractHeader;
|
|
76
|
+
private expressPath;
|
|
77
|
+
private expressIp;
|
|
78
|
+
private fastifyPath;
|
|
79
|
+
private normalizeTrustSignals;
|
|
70
80
|
/**
|
|
71
81
|
* Create Express/Connect middleware that gates access + tracks usage.
|
|
72
82
|
*
|
package/dist/operatorSdk.js
CHANGED
|
@@ -31,6 +31,7 @@ class ValironOperator {
|
|
|
31
31
|
}
|
|
32
32
|
this.apiKey = config.apiKey;
|
|
33
33
|
this.debug = config.debug || false;
|
|
34
|
+
this.endpoint = config.endpoint || "https://valiron-edge-proxy.onrender.com";
|
|
34
35
|
this.sdk = new index_js_1.ValironSDK({
|
|
35
36
|
apiKey: config.apiKey,
|
|
36
37
|
chain: config.chain,
|
|
@@ -39,6 +40,65 @@ class ValironOperator {
|
|
|
39
40
|
debug: config.debug,
|
|
40
41
|
});
|
|
41
42
|
}
|
|
43
|
+
buildAnalyticsUrl() {
|
|
44
|
+
return new URL("/operator/analytics/ingest", this.endpoint).toString();
|
|
45
|
+
}
|
|
46
|
+
recordUsage(entry) {
|
|
47
|
+
const trustSignals = this.normalizeTrustSignals(entry.trustSignals);
|
|
48
|
+
const body = {
|
|
49
|
+
agent_id: entry.agentId || undefined,
|
|
50
|
+
agent_label: entry.agentLabel || undefined,
|
|
51
|
+
session_id: entry.sessionId || undefined,
|
|
52
|
+
chain: entry.chain || undefined,
|
|
53
|
+
path: entry.path,
|
|
54
|
+
method: entry.method,
|
|
55
|
+
status_code: entry.statusCode,
|
|
56
|
+
price_charged: entry.priceCharged,
|
|
57
|
+
response_ms: entry.responseMs,
|
|
58
|
+
user_agent: entry.userAgent || undefined,
|
|
59
|
+
ip_address: entry.ipAddress || undefined,
|
|
60
|
+
error_message: entry.errorMessage || undefined,
|
|
61
|
+
trust_signals: trustSignals,
|
|
62
|
+
trust_signal_count: trustSignals.length,
|
|
63
|
+
scoring_mode: trustSignals.length ? trustSignals.join("+") : undefined,
|
|
64
|
+
erc8004_included: trustSignals.includes("8004"),
|
|
65
|
+
sandbox_included: trustSignals.includes("sandbox"),
|
|
66
|
+
world_included: trustSignals.includes("world"),
|
|
67
|
+
icebreaker_included: trustSignals.includes("icebreaker"),
|
|
68
|
+
};
|
|
69
|
+
void fetch(this.buildAnalyticsUrl(), {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: {
|
|
72
|
+
"Content-Type": "application/json",
|
|
73
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
74
|
+
},
|
|
75
|
+
body: JSON.stringify(body),
|
|
76
|
+
})
|
|
77
|
+
.then((response) => response.arrayBuffer().catch(() => response.body?.cancel()))
|
|
78
|
+
.catch(() => {
|
|
79
|
+
// Best-effort usage analytics: never affect seller request handling.
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
extractHeader(source, name) {
|
|
83
|
+
const headers = source?.headers ?? {};
|
|
84
|
+
if (typeof headers.get === "function")
|
|
85
|
+
return headers.get(name);
|
|
86
|
+
const direct = headers[name] ?? headers[name.toLowerCase()];
|
|
87
|
+
return Array.isArray(direct) ? direct[0] : direct ?? null;
|
|
88
|
+
}
|
|
89
|
+
expressPath(req) {
|
|
90
|
+
return req.originalUrl || req.url || req.path || "/";
|
|
91
|
+
}
|
|
92
|
+
expressIp(req) {
|
|
93
|
+
const forwarded = this.extractHeader(req, "x-forwarded-for")?.split(",")[0]?.trim();
|
|
94
|
+
return forwarded || this.extractHeader(req, "x-real-ip") || req.ip || req.socket?.remoteAddress || null;
|
|
95
|
+
}
|
|
96
|
+
fastifyPath(req) {
|
|
97
|
+
return req.url || req.routerPath || "/";
|
|
98
|
+
}
|
|
99
|
+
normalizeTrustSignals(signals) {
|
|
100
|
+
return signals?.length ? [...signals].sort() : [];
|
|
101
|
+
}
|
|
42
102
|
/**
|
|
43
103
|
* Create Express/Connect middleware that gates access + tracks usage.
|
|
44
104
|
*
|
|
@@ -63,6 +123,7 @@ class ValironOperator {
|
|
|
63
123
|
const gateConfig = {
|
|
64
124
|
sdk: this.sdk,
|
|
65
125
|
minScore: config.minTrustScore ?? 45,
|
|
126
|
+
trustSignals: config.trustSignals,
|
|
66
127
|
cacheTtlMs: config.cacheTtlMs ?? config.ttlMs,
|
|
67
128
|
onDeny: config.onDeny,
|
|
68
129
|
onAllow: (req, result) => {
|
|
@@ -74,13 +135,55 @@ class ValironOperator {
|
|
|
74
135
|
},
|
|
75
136
|
};
|
|
76
137
|
const middleware = (0, middleware_js_1.createValironGate)(gateConfig);
|
|
138
|
+
const withUsageLogging = (req, res, next) => {
|
|
139
|
+
const startedAt = Date.now();
|
|
140
|
+
let logged = false;
|
|
141
|
+
const logOnce = () => {
|
|
142
|
+
if (logged)
|
|
143
|
+
return;
|
|
144
|
+
logged = true;
|
|
145
|
+
const gate = req.valiron;
|
|
146
|
+
const statusCode = res.statusCode;
|
|
147
|
+
const allowed = Boolean(gate?.allow);
|
|
148
|
+
const chargeable = allowed && statusCode >= 200 && statusCode < 400;
|
|
149
|
+
const errorMessage = !allowed
|
|
150
|
+
? "gate_denied"
|
|
151
|
+
: statusCode >= 400
|
|
152
|
+
? `downstream_${statusCode}`
|
|
153
|
+
: undefined;
|
|
154
|
+
const agentId = gate?.agentId ||
|
|
155
|
+
this.extractHeader(req, "x-agent-id") ||
|
|
156
|
+
this.extractHeader(req, "x-agent-address") ||
|
|
157
|
+
this.extractHeader(req, "x-agent-key-hash");
|
|
158
|
+
this.recordUsage({
|
|
159
|
+
agentId,
|
|
160
|
+
agentLabel: gate?.tier ? `${gate.tier}:${gate.route}` : undefined,
|
|
161
|
+
sessionId: this.extractHeader(req, "x-valiron-session-id") || this.extractHeader(req, "x-request-id"),
|
|
162
|
+
chain: gate?.chain?.network || this.extractHeader(req, "x-chain"),
|
|
163
|
+
path: this.expressPath(req).split("?")[0] || "/",
|
|
164
|
+
method: req.method || "GET",
|
|
165
|
+
statusCode,
|
|
166
|
+
priceCharged: chargeable ? config.pricePerCall : 0,
|
|
167
|
+
responseMs: Date.now() - startedAt,
|
|
168
|
+
userAgent: this.extractHeader(req, "user-agent"),
|
|
169
|
+
ipAddress: this.expressIp(req),
|
|
170
|
+
errorMessage,
|
|
171
|
+
trustSignals: config.trustSignals,
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
if (typeof res.once === "function") {
|
|
175
|
+
res.once("finish", logOnce);
|
|
176
|
+
res.once("close", logOnce);
|
|
177
|
+
}
|
|
178
|
+
return middleware(req, res, next);
|
|
179
|
+
};
|
|
77
180
|
if (this.debug) {
|
|
78
181
|
return async (req, res, next) => {
|
|
79
182
|
console.log(`[ValironOperator] Gate check for ${req.headers?.["x-agent-id"] || "unknown"} @ $${config.pricePerCall}/call`);
|
|
80
|
-
return
|
|
183
|
+
return withUsageLogging(req, res, next);
|
|
81
184
|
};
|
|
82
185
|
}
|
|
83
|
-
return
|
|
186
|
+
return withUsageLogging;
|
|
84
187
|
}
|
|
85
188
|
/**
|
|
86
189
|
* Create a Fastify plugin that gates access + tracks usage.
|
|
@@ -98,6 +201,7 @@ class ValironOperator {
|
|
|
98
201
|
const pluginConfig = {
|
|
99
202
|
sdk: this.sdk,
|
|
100
203
|
minScore: config.minTrustScore ?? 45,
|
|
204
|
+
trustSignals: config.trustSignals,
|
|
101
205
|
cacheTtlMs: config.cacheTtlMs ?? config.ttlMs,
|
|
102
206
|
prefix: config.prefix,
|
|
103
207
|
onDeny: config.onDeny,
|
|
@@ -109,7 +213,51 @@ class ValironOperator {
|
|
|
109
213
|
},
|
|
110
214
|
};
|
|
111
215
|
return (fastify, opts, done) => {
|
|
112
|
-
|
|
216
|
+
fastify.addHook?.("onRequest", async (request) => {
|
|
217
|
+
request.valironUsageStartedAt = Date.now();
|
|
218
|
+
});
|
|
219
|
+
(0, middleware_js_1.valironFastifyPlugin)(fastify, { ...pluginConfig, ...opts }).then(() => {
|
|
220
|
+
fastify.addHook?.("onResponse", async (request, reply) => {
|
|
221
|
+
const rawUrl = request.url || "";
|
|
222
|
+
if (config.prefix) {
|
|
223
|
+
const pathname = rawUrl.split("?")[0];
|
|
224
|
+
const prefix = config.prefix.endsWith("/") && config.prefix !== "/"
|
|
225
|
+
? config.prefix.slice(0, -1)
|
|
226
|
+
: config.prefix;
|
|
227
|
+
if (pathname !== prefix && !pathname.startsWith(prefix + "/"))
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const gate = request.valiron;
|
|
231
|
+
const statusCode = reply.statusCode;
|
|
232
|
+
const allowed = Boolean(gate?.allow);
|
|
233
|
+
const chargeable = allowed && statusCode >= 200 && statusCode < 400;
|
|
234
|
+
const errorMessage = !allowed
|
|
235
|
+
? "gate_denied"
|
|
236
|
+
: statusCode >= 400
|
|
237
|
+
? `downstream_${statusCode}`
|
|
238
|
+
: undefined;
|
|
239
|
+
const agentId = gate?.agentId ||
|
|
240
|
+
this.extractHeader(request, "x-agent-id") ||
|
|
241
|
+
this.extractHeader(request, "x-agent-address") ||
|
|
242
|
+
this.extractHeader(request, "x-agent-key-hash");
|
|
243
|
+
this.recordUsage({
|
|
244
|
+
agentId,
|
|
245
|
+
agentLabel: gate?.tier ? `${gate.tier}:${gate.route}` : undefined,
|
|
246
|
+
sessionId: this.extractHeader(request, "x-valiron-session-id") || this.extractHeader(request, "x-request-id"),
|
|
247
|
+
chain: gate?.chain?.network || this.extractHeader(request, "x-chain"),
|
|
248
|
+
path: this.fastifyPath(request).split("?")[0] || "/",
|
|
249
|
+
method: request.method || "GET",
|
|
250
|
+
statusCode,
|
|
251
|
+
priceCharged: chargeable ? config.pricePerCall : 0,
|
|
252
|
+
responseMs: Date.now() - (request.valironUsageStartedAt || Date.now()),
|
|
253
|
+
userAgent: this.extractHeader(request, "user-agent"),
|
|
254
|
+
ipAddress: request.ip || this.extractHeader(request, "x-forwarded-for")?.split(",")[0]?.trim() || null,
|
|
255
|
+
errorMessage,
|
|
256
|
+
trustSignals: config.trustSignals,
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
done();
|
|
260
|
+
}).catch(done);
|
|
113
261
|
};
|
|
114
262
|
}
|
|
115
263
|
/**
|
package/dist/telemetry.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.TelemetryClient = void 0;
|
|
4
|
-
const SDK_VERSION = "0.
|
|
4
|
+
const SDK_VERSION = "1.0.2";
|
|
5
5
|
function detectRuntime() {
|
|
6
6
|
return typeof globalThis.window === "undefined" ? "node" : "browser";
|
|
7
7
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export type SupportedChain = "ethereum" | "monad" | "arbitrum" | "base" | "avala
|
|
|
9
9
|
export type RouteDecision = "prod" | "prod_throttled" | "sandbox" | "sandbox_only";
|
|
10
10
|
export type RiskLevel = "GREEN" | "YELLOW" | "RED";
|
|
11
11
|
export type MoodysRating = "AAA" | "AA" | "A" | "BAA" | "BA" | "B" | "CAA" | "CA" | "C";
|
|
12
|
+
export type TrustSignal = "8004" | "sandbox" | "world" | "icebreaker";
|
|
12
13
|
export interface AgentIdentity {
|
|
13
14
|
agentId: string;
|
|
14
15
|
wallet: string;
|
|
@@ -192,6 +193,8 @@ export interface GateOptions {
|
|
|
192
193
|
minScore?: number;
|
|
193
194
|
/** TTL in ms for cached sandbox results. Stale results trigger re-testing (default: 86400000 = 24 h). */
|
|
194
195
|
ttlMs?: number;
|
|
196
|
+
/** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+icebreaker. */
|
|
197
|
+
trustSignals?: TrustSignal[];
|
|
195
198
|
/** Override the blockchain network for this call. */
|
|
196
199
|
chain?: SupportedChain;
|
|
197
200
|
}
|
|
@@ -354,7 +357,7 @@ export interface KeyAgentProfile {
|
|
|
354
357
|
agentAddress: string;
|
|
355
358
|
/** Whether identity has been verified via challenge-response */
|
|
356
359
|
verified: boolean;
|
|
357
|
-
/** Behavioral score (0-
|
|
360
|
+
/** Behavioral score (0-100) — same scoring as ERC-8004 agents */
|
|
358
361
|
score: number | null;
|
|
359
362
|
/** Moody's-style tier (AAA → C) */
|
|
360
363
|
tier: MoodysRating | null;
|
|
@@ -376,6 +379,8 @@ export interface CallOptions {
|
|
|
376
379
|
* Takes precedence over the default chain set in the constructor.
|
|
377
380
|
*/
|
|
378
381
|
chain?: SupportedChain;
|
|
382
|
+
/** Customer-selected scoring signals for profile/routing calls. */
|
|
383
|
+
trustSignals?: TrustSignal[];
|
|
379
384
|
}
|
|
380
385
|
export type TelemetryEnvironment = "prod" | "staging" | "dev";
|
|
381
386
|
export interface TelemetryEventBase {
|
|
@@ -418,7 +423,9 @@ export interface ValironConfig {
|
|
|
418
423
|
*/
|
|
419
424
|
chain?: SupportedChain;
|
|
420
425
|
/**
|
|
421
|
-
* Request timeout in milliseconds
|
|
426
|
+
* Request timeout in milliseconds. When omitted, the SDK uses method-aware
|
|
427
|
+
* defaults: 10s generally, 15s for gate/proxy calls, and 30s for sandbox
|
|
428
|
+
* triggers. When set, this value overrides all method-aware defaults.
|
|
422
429
|
*/
|
|
423
430
|
timeout?: number;
|
|
424
431
|
/**
|
package/docs/API-REFERENCE.md
CHANGED
|
@@ -146,7 +146,7 @@ Execute real-time sandbox tests against an agent and compute a trust evaluation.
|
|
|
146
146
|
|
|
147
147
|
## POST /operator/gate/:agentId
|
|
148
148
|
|
|
149
|
-
Trust gate —
|
|
149
|
+
Trust gate — selected trust signals scored on a normalized `0-100` scale. Returns an allow/deny decision. Designed for protecting payment endpoints (x402, etc.).
|
|
150
150
|
|
|
151
151
|
### Parameters
|
|
152
152
|
|
|
@@ -158,12 +158,16 @@ Trust gate — combined on-chain reputation + sandbox check. Returns an allow/de
|
|
|
158
158
|
|
|
159
159
|
```json
|
|
160
160
|
{
|
|
161
|
+
"minScore": 65,
|
|
162
|
+
"trustSignals": ["8004", "sandbox"],
|
|
161
163
|
"ttlMs": 86400000
|
|
162
164
|
}
|
|
163
165
|
```
|
|
164
166
|
|
|
165
167
|
| Field | Type | Default | Description |
|
|
166
168
|
|-------|------|---------|-------------|
|
|
169
|
+
| `minScore` | number | 65 | Minimum normalized trust score required to allow. Must be between 0 and 100. |
|
|
170
|
+
| `trustSignals` | string[] | auto | Optional selected signals: `8004`, `sandbox`, `world`, `icebreaker`. Free plans support `8004` + `sandbox`; Pro adds `world` + `icebreaker`. |
|
|
167
171
|
| `ttlMs` | number | 86400000 | Cache TTL in milliseconds (default 24 hours) |
|
|
168
172
|
|
|
169
173
|
### Response — 200 OK
|
package/docs/ERRORS.md
CHANGED
|
@@ -94,7 +94,7 @@ First-time agents that haven't been sandbox-tested yet receive provisional score
|
|
|
94
94
|
|
|
95
95
|
### Timeout errors
|
|
96
96
|
|
|
97
|
-
The default
|
|
97
|
+
The SDK uses method-aware default timeouts: 10 seconds generally, 15 seconds for `gate()`/`proxy()`, and 30 seconds for sandbox triggers. To force a single timeout for all calls, configure it explicitly:
|
|
98
98
|
|
|
99
99
|
```typescript
|
|
100
100
|
const valiron = new ValironSDK({ timeout: 30000 }); // 30 seconds
|
package/docs/QUICKSTART.md
CHANGED
|
@@ -26,7 +26,7 @@ import { ValironSDK } from "@valiron/sdk";
|
|
|
26
26
|
const valiron = new ValironSDK({
|
|
27
27
|
endpoint: "https://valiron-edge-proxy.onrender.com",
|
|
28
28
|
chain: "ethereum", // or: monad, arbitrum, base, polygon, solana, etc.
|
|
29
|
-
timeout:
|
|
29
|
+
// timeout: 30000, // optional override for all calls
|
|
30
30
|
});
|
|
31
31
|
```
|
|
32
32
|
|
|
@@ -68,6 +68,18 @@ app.use("/api/paid", createValironGate({ sdk: valiron }));
|
|
|
68
68
|
|
|
69
69
|
This reads `x-agent-id` from the request header, checks trust via the public agent profile endpoint, and returns 403 for untrusted agents. It's safe with Express 4 (async errors are handled) and includes a 30-second client-side cache for x402 compatibility.
|
|
70
70
|
|
|
71
|
+
You can also choose which trust signals an endpoint uses:
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
app.use("/api/paid", createValironGate({
|
|
75
|
+
sdk: valiron,
|
|
76
|
+
trustSignals: ["8004", "sandbox"], // Free
|
|
77
|
+
minScore: 70,
|
|
78
|
+
}));
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Free plans support `8004` and `sandbox`. Pro plans can also include `world` and `icebreaker`.
|
|
82
|
+
|
|
71
83
|
Or use `getAgentProfile()` directly for custom logic:
|
|
72
84
|
|
|
73
85
|
```typescript
|
package/docs/SDK-REFERENCE.md
CHANGED
|
@@ -25,7 +25,7 @@ const valiron = new ValironSDK(config?: ValironConfig);
|
|
|
25
25
|
| `apiKey` | string | — | API key (optional for read operations) |
|
|
26
26
|
| `endpoint` | string | `https://valiron-edge-proxy.onrender.com` | API base URL |
|
|
27
27
|
| `chain` | SupportedChain | `"ethereum"` | Default blockchain network |
|
|
28
|
-
| `timeout` | number |
|
|
28
|
+
| `timeout` | number | method-aware | Request timeout in milliseconds. Defaults are 10s generally, 15s for `gate()`/`proxy()`, and 30s for sandbox triggers. If set, this value overrides all method-aware defaults. |
|
|
29
29
|
| `debug` | boolean | `false` | Enable debug logging |
|
|
30
30
|
| `telemetry` | TelemetryConfig | — | Optional telemetry configuration |
|
|
31
31
|
|
|
@@ -360,6 +360,7 @@ import { ValironSDK, createValironGate } from "@valiron/sdk";
|
|
|
360
360
|
const gate = createValironGate(config: {
|
|
361
361
|
sdk: ValironSDK;
|
|
362
362
|
minScore?: number; // default: 65
|
|
363
|
+
trustSignals?: Array<"8004" | "sandbox" | "world" | "icebreaker">;
|
|
363
364
|
cacheTtlMs?: number; // default: 30000 (30s client-side cache)
|
|
364
365
|
extractAgentId?: (req: Request) => string | null;
|
|
365
366
|
extractAgentAddress?: (req: Request) => string | null;
|
|
@@ -386,6 +387,7 @@ app.use("/api/paid", createValironGate({ sdk: valiron }));
|
|
|
386
387
|
app.use("/api/premium", createValironGate({
|
|
387
388
|
sdk: valiron,
|
|
388
389
|
minScore: 85,
|
|
390
|
+
trustSignals: ["8004", "sandbox"],
|
|
389
391
|
cacheTtlMs: 60_000, // 60s
|
|
390
392
|
}));
|
|
391
393
|
|
|
@@ -555,7 +557,7 @@ const profile = await valiron.getWorldIdProfile(agentId: string, options?: {
|
|
|
555
557
|
|
|
556
558
|
## Telemetry
|
|
557
559
|
|
|
558
|
-
The SDK
|
|
560
|
+
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.
|
|
559
561
|
|
|
560
562
|
### TelemetryConfig
|
|
561
563
|
|
|
@@ -563,7 +565,7 @@ The SDK optionally collects anonymous usage metrics (gate calls, latency, error
|
|
|
563
565
|
|-------|------|---------|-------------|
|
|
564
566
|
| `enabled` | boolean | `true` | Enable/disable telemetry |
|
|
565
567
|
| `sampleRate` | number | `1.0` | Fraction of events to sample (0–1) |
|
|
566
|
-
| `
|
|
568
|
+
| `onEvent` | function | — | Custom event handler |
|
|
567
569
|
|
|
568
570
|
**Example**:
|
|
569
571
|
```typescript
|
|
@@ -577,7 +579,7 @@ const valiron = new ValironSDK({
|
|
|
577
579
|
const valiron = new ValironSDK({
|
|
578
580
|
telemetry: {
|
|
579
581
|
sampleRate: 0.1, // Sample 10% of events
|
|
580
|
-
|
|
582
|
+
onEvent: (event) => { // Custom handler
|
|
581
583
|
myAnalytics.track(event);
|
|
582
584
|
},
|
|
583
585
|
},
|
package/docs/TRUST-MODEL.md
CHANGED
|
@@ -4,7 +4,7 @@ Valiron uses a hybrid trust model to evaluate AI agents hitting your API. This d
|
|
|
4
4
|
|
|
5
5
|
## Trust Tiers
|
|
6
6
|
|
|
7
|
-
Valiron assigns a Moody's-style credit tier
|
|
7
|
+
Valiron assigns a Moody's-style credit tier from a normalized `0-100` trust score:
|
|
8
8
|
|
|
9
9
|
| Tier | Meaning | Route Decision |
|
|
10
10
|
|------|---------|----------------|
|
|
@@ -18,11 +18,33 @@ Valiron assigns a Moody's-style credit tier based on an agent's behavioral evalu
|
|
|
18
18
|
| CA | Extremely speculative | `sandbox_only` |
|
|
19
19
|
| C | Default risk | `sandbox_only` |
|
|
20
20
|
|
|
21
|
-
##
|
|
21
|
+
## Selectable Trust Signals
|
|
22
|
+
|
|
23
|
+
API sellers can use Valiron plug-and-play, or choose the trust signals used for a specific endpoint.
|
|
24
|
+
|
|
25
|
+
Supported signals:
|
|
26
|
+
|
|
27
|
+
| Signal | Description | Plan |
|
|
28
|
+
|--------|-------------|------|
|
|
29
|
+
| `8004` | ERC-8004 / Solana on-chain reputation | Free |
|
|
30
|
+
| `sandbox` | Valiron behavioral sandbox score | Free |
|
|
31
|
+
| `world` | World ID human-agent link | Pro |
|
|
32
|
+
| `icebreaker` | Icebreaker human/background attestation | Pro |
|
|
33
|
+
|
|
34
|
+
When multiple signals are selected, Valiron computes each signal on a `0-100` scale and normalizes the configured weights across only those selected signals. The default weights are:
|
|
35
|
+
|
|
36
|
+
| Signal | Default Weight |
|
|
37
|
+
|--------|----------------|
|
|
38
|
+
| `sandbox` | 55 |
|
|
39
|
+
| `8004` | 25 |
|
|
40
|
+
| `world` | 15 |
|
|
41
|
+
| `icebreaker` | 5 |
|
|
22
42
|
|
|
23
|
-
|
|
43
|
+
If no signals are specified, Valiron uses the plug-and-play default: sandbox plus any other available trust signals.
|
|
24
44
|
|
|
25
|
-
|
|
45
|
+
## Behavioral Factors
|
|
46
|
+
|
|
47
|
+
Valiron evaluates agents across multiple behavioral dimensions. The behavioral evaluation is holistic — no single sandbox behavior determines the outcome. The specific factors evaluated and their weights are proprietary and not disclosed.
|
|
26
48
|
|
|
27
49
|
## What Makes an Agent Trustworthy
|
|
28
50
|
|
|
@@ -47,6 +69,16 @@ Or via HTTP:
|
|
|
47
69
|
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox/AGENT_ID
|
|
48
70
|
```
|
|
49
71
|
|
|
72
|
+
Use selected signals in middleware:
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
app.use("/api/paid", createValironGate({
|
|
76
|
+
sdk: valiron,
|
|
77
|
+
trustSignals: ["8004", "sandbox"],
|
|
78
|
+
minScore: 70,
|
|
79
|
+
}));
|
|
80
|
+
```
|
|
81
|
+
|
|
50
82
|
---
|
|
51
83
|
|
|
52
84
|
## Solana Trust Evaluation
|