@kya-os/contracts 1.6.17 → 1.6.19

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.
@@ -0,0 +1,499 @@
1
+ "use strict";
2
+ /**
3
+ * Reputation Engine Schemas
4
+ *
5
+ * Zod schemas and TypeScript types for the Bayesian reputation scoring system.
6
+ * These schemas define the data structures for agent reputation calculation,
7
+ * including input data, score outputs, and configuration options.
8
+ *
9
+ * The reputation system uses a Bayesian approach:
10
+ * final_score = (1 - confidence) × prior_score + confidence × empirical_score
11
+ *
12
+ * Related Spec: MCP-I §5.1 (Reputation), CLAUDE-reputation-engine.md
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ScoreChangePredictionResponseSchema = exports.ScoreChangePredictionRequestSchema = exports.CalculatorConfigSchema = exports.CalculatorWeightsSchema = exports.CalculatorPresetSchema = exports.ReputationScoreSchema = exports.SimpleReputationLevelSchema = exports.ReputationLevelSchema = exports.ConfidenceLevelSchema = exports.ReputationFactorsSchema = exports.ScoreComponentsSchema = exports.PartialAgentDataSchema = exports.AgentDataSchema = exports.IssueMetricsSchema = exports.ReviewMetricsSchema = exports.InteractionMetricsSchema = exports.CredentialFlagsSchema = exports.MCPLevelSchema = void 0;
16
+ exports.toSimpleReputationLevel = toSimpleReputationLevel;
17
+ exports.getSimpleReputationLevel = getSimpleReputationLevel;
18
+ exports.validateAgentData = validateAgentData;
19
+ exports.validateReputationScore = validateReputationScore;
20
+ exports.validateCalculatorConfig = validateCalculatorConfig;
21
+ exports.getReputationLevel = getReputationLevel;
22
+ exports.getConfidenceLevel = getConfidenceLevel;
23
+ exports.calculateConfidence = calculateConfidence;
24
+ exports.isProvisionalScore = isProvisionalScore;
25
+ const zod_1 = require("zod");
26
+ // ============================================================================
27
+ // MCP LEVEL & CREDENTIALS
28
+ // ============================================================================
29
+ /**
30
+ * MCP Compliance Level
31
+ *
32
+ * Levels 0-3 representing increasing levels of MCP compliance:
33
+ * - 0: No MCP compliance
34
+ * - 1: Basic MCP compliance (+5 prior points)
35
+ * - 2: Standard MCP compliance (+10 prior points)
36
+ * - 3: Advanced MCP compliance (+15 prior points)
37
+ */
38
+ exports.MCPLevelSchema = zod_1.z.number().int().min(0).max(3);
39
+ /**
40
+ * Credential Flags Schema
41
+ *
42
+ * Boolean flags representing various verified credentials and certifications.
43
+ * Each flag contributes to the prior score calculation.
44
+ */
45
+ exports.CredentialFlagsSchema = zod_1.z.object({
46
+ /** Identity has been verified through a trusted provider */
47
+ identityVerified: zod_1.z.boolean().default(false),
48
+ /** Agent has passed a security audit */
49
+ securityAuditPassed: zod_1.z.boolean().default(false),
50
+ /** Agent source code is open source */
51
+ openSource: zod_1.z.boolean().default(false),
52
+ /** GitHub account is verified */
53
+ githubVerified: zod_1.z.boolean().default(false),
54
+ /** Company email has been verified */
55
+ companyEmailVerified: zod_1.z.boolean().default(false),
56
+ });
57
+ // ============================================================================
58
+ // INTERACTION METRICS
59
+ // ============================================================================
60
+ /**
61
+ * Interaction Metrics Schema
62
+ *
63
+ * Quantitative metrics about an agent's interactions with other agents/users.
64
+ * Used in calculating empirical score and confidence level.
65
+ */
66
+ exports.InteractionMetricsSchema = zod_1.z.object({
67
+ /** Total number of interactions */
68
+ totalInteractions: zod_1.z.number().int().nonnegative().default(0),
69
+ /** Number of successful interactions */
70
+ successfulInteractions: zod_1.z.number().int().nonnegative().default(0),
71
+ /** Number of failed interactions */
72
+ failedInteractions: zod_1.z.number().int().nonnegative().default(0),
73
+ /** Number of unique interaction partners */
74
+ uniquePartners: zod_1.z.number().int().nonnegative().default(0),
75
+ /** Total transaction/interaction volume (monetary or unit-based) */
76
+ totalVolume: zod_1.z.number().nonnegative().default(0),
77
+ });
78
+ // ============================================================================
79
+ // REVIEW METRICS
80
+ // ============================================================================
81
+ /**
82
+ * Review Metrics Schema
83
+ *
84
+ * Metrics derived from user/agent reviews.
85
+ * Primary source for empirical score calculation.
86
+ */
87
+ exports.ReviewMetricsSchema = zod_1.z.object({
88
+ /** Total number of reviews received */
89
+ totalReviews: zod_1.z.number().int().nonnegative().default(0),
90
+ /** Average rating (1.0 to 5.0 scale) */
91
+ averageRating: zod_1.z.number().min(1).max(5).optional(),
92
+ /** Number of positive reviews (4+ stars) */
93
+ positiveReviews: zod_1.z.number().int().nonnegative().default(0),
94
+ /** Number of negative reviews (2 or fewer stars) */
95
+ negativeReviews: zod_1.z.number().int().nonnegative().default(0),
96
+ });
97
+ // ============================================================================
98
+ // ISSUE METRICS
99
+ // ============================================================================
100
+ /**
101
+ * Issue Metrics Schema
102
+ *
103
+ * Metrics related to disputes, abuse reports, and other issues.
104
+ * Negatively impacts reputation score.
105
+ */
106
+ exports.IssueMetricsSchema = zod_1.z.object({
107
+ /** Number of disputes filed against this agent */
108
+ disputesFiled: zod_1.z.number().int().nonnegative().default(0),
109
+ /** Number of disputes lost (decided against this agent) */
110
+ disputesLost: zod_1.z.number().int().nonnegative().default(0),
111
+ /** Number of verified abuse reports */
112
+ abuseReportsVerified: zod_1.z.number().int().nonnegative().default(0),
113
+ });
114
+ // ============================================================================
115
+ // AGENT DATA (INPUT)
116
+ // ============================================================================
117
+ /**
118
+ * Agent Data Schema
119
+ *
120
+ * Complete input data structure for reputation calculation.
121
+ * Combines identity, credentials, interactions, reviews, and issues.
122
+ *
123
+ * This is the primary input to the reputation calculation engine.
124
+ */
125
+ exports.AgentDataSchema = zod_1.z.object({
126
+ // === Identity ===
127
+ /** Decentralized Identifier (DID) of the agent */
128
+ did: zod_1.z
129
+ .string()
130
+ .min(1)
131
+ .refine((val) => val.startsWith("did:"), {
132
+ message: 'DID must start with "did:"',
133
+ }),
134
+ /** Timestamp when the agent was registered (ISO 8601) */
135
+ createdAt: zod_1.z.string().datetime().optional(),
136
+ // === Credentials ===
137
+ /** MCP compliance level (0-3) */
138
+ mcpLevel: exports.MCPLevelSchema.default(0),
139
+ /** Credential flags */
140
+ credentials: exports.CredentialFlagsSchema.optional().default({}),
141
+ // === Metrics ===
142
+ /** Interaction metrics */
143
+ interactions: exports.InteractionMetricsSchema.optional().default({}),
144
+ /** Review metrics */
145
+ reviews: exports.ReviewMetricsSchema.optional().default({}),
146
+ /** Issue metrics */
147
+ issues: exports.IssueMetricsSchema.optional().default({}),
148
+ // === Extensibility ===
149
+ /** Optional metadata for custom extensions */
150
+ metadata: zod_1.z.record(zod_1.z.unknown()).optional(),
151
+ });
152
+ /**
153
+ * Partial Agent Data Schema
154
+ *
155
+ * For updates and partial data scenarios.
156
+ * All fields are optional except DID.
157
+ */
158
+ exports.PartialAgentDataSchema = exports.AgentDataSchema.partial().extend({
159
+ did: zod_1.z
160
+ .string()
161
+ .min(1)
162
+ .refine((val) => val.startsWith("did:"), {
163
+ message: 'DID must start with "did:"',
164
+ }),
165
+ });
166
+ // ============================================================================
167
+ // SCORE COMPONENTS (OUTPUT)
168
+ // ============================================================================
169
+ /**
170
+ * Score Components Schema (Bayesian Algorithm)
171
+ *
172
+ * Breakdown of how the final score was calculated using the Bayesian algorithm.
173
+ * Provides transparency into the scoring algorithm.
174
+ *
175
+ * Formula: final_score = (1 - confidence) × prior_score + confidence × empirical_score
176
+ */
177
+ exports.ScoreComponentsSchema = zod_1.z.object({
178
+ /** Prior score based on credentials (50-80 points) */
179
+ priorScore: zod_1.z.number().min(0).max(100),
180
+ /** Empirical score based on interactions and reviews (0-100 points) */
181
+ empiricalScore: zod_1.z.number().min(0).max(100),
182
+ /** Weight applied to confidence (derived from interactions) */
183
+ confidenceWeight: zod_1.z.number().min(0).max(1),
184
+ /** Weight applied to prior (1 - confidenceWeight) */
185
+ priorWeight: zod_1.z.number().min(0).max(1),
186
+ });
187
+ /**
188
+ * Reputation Factors Schema
189
+ *
190
+ * Detailed breakdown of factors contributing to the reputation score.
191
+ * This provides a human-readable explanation of why an agent has a particular score.
192
+ *
193
+ * Compatible with Know That AI API response format.
194
+ */
195
+ exports.ReputationFactorsSchema = zod_1.z.object({
196
+ /** Score based on successful vs failed interactions (0-100) */
197
+ interactionScore: zod_1.z.number().min(0).max(100),
198
+ /** Score based on consistency of behavior over time (0-100) */
199
+ consistencyScore: zod_1.z.number().min(0).max(100),
200
+ /** Score based on account age / longevity (0-100) */
201
+ longevityScore: zod_1.z.number().min(0).max(100),
202
+ /** Score based on diversity of interaction partners (0-100) */
203
+ partnerDiversityScore: zod_1.z.number().min(0).max(100),
204
+ /** Score based on positive feedback received (0-100) */
205
+ feedbackScore: zod_1.z.number().min(0).max(100),
206
+ });
207
+ /**
208
+ * Confidence Level Schema
209
+ *
210
+ * Human-readable confidence categories.
211
+ */
212
+ exports.ConfidenceLevelSchema = zod_1.z.enum([
213
+ "Low",
214
+ "Medium",
215
+ "High",
216
+ "VeryHigh",
217
+ ]);
218
+ /**
219
+ * Reputation Level Schema (Detailed)
220
+ *
221
+ * Human-readable reputation categories based on score ranges.
222
+ * Uses granular levels for detailed reputation assessment.
223
+ */
224
+ exports.ReputationLevelSchema = zod_1.z.enum([
225
+ "Unknown", // Score not calculable or insufficient data
226
+ "Poor", // 0-30
227
+ "BelowAverage", // 30-45
228
+ "Average", // 45-60
229
+ "Good", // 60-75
230
+ "Excellent", // 75-90
231
+ "Outstanding", // 90-100
232
+ ]);
233
+ /**
234
+ * Simple Reputation Level Schema
235
+ *
236
+ * Human-readable reputation categories matching Know That AI API.
237
+ * Uses 5-tier levels for simplified reputation display.
238
+ */
239
+ exports.SimpleReputationLevelSchema = zod_1.z.enum([
240
+ "Very Low", // 0-20
241
+ "Low", // 20-40
242
+ "Medium", // 40-60
243
+ "High", // 60-80
244
+ "Very High", // 80-100
245
+ ]);
246
+ /**
247
+ * Convert detailed ReputationLevel to SimpleReputationLevel
248
+ *
249
+ * Maps the 7-tier detailed levels to the 5-tier simple levels.
250
+ */
251
+ function toSimpleReputationLevel(level) {
252
+ switch (level) {
253
+ case "Unknown":
254
+ case "Poor":
255
+ return "Very Low";
256
+ case "BelowAverage":
257
+ return "Low";
258
+ case "Average":
259
+ return "Medium";
260
+ case "Good":
261
+ return "High";
262
+ case "Excellent":
263
+ case "Outstanding":
264
+ return "Very High";
265
+ }
266
+ }
267
+ /**
268
+ * Get simple reputation level from numeric score
269
+ *
270
+ * @param score - Numeric score (0-100)
271
+ * @returns Simple reputation level
272
+ */
273
+ function getSimpleReputationLevel(score) {
274
+ if (score < 0 || !Number.isFinite(score))
275
+ return "Very Low";
276
+ if (score < 20)
277
+ return "Very Low";
278
+ if (score < 40)
279
+ return "Low";
280
+ if (score < 60)
281
+ return "Medium";
282
+ if (score < 80)
283
+ return "High";
284
+ return "Very High";
285
+ }
286
+ // ============================================================================
287
+ // REPUTATION SCORE (OUTPUT)
288
+ // ============================================================================
289
+ /**
290
+ * Reputation Score Schema
291
+ *
292
+ * Complete output from the reputation calculation engine.
293
+ * Includes the final score, confidence metrics, and component breakdown.
294
+ */
295
+ exports.ReputationScoreSchema = zod_1.z.object({
296
+ /** Final reputation score (0-100) */
297
+ score: zod_1.z.number().min(0).max(100),
298
+ /** Confidence in the score (0-1) */
299
+ confidence: zod_1.z.number().min(0).max(1),
300
+ /** Human-readable confidence level */
301
+ confidenceLevel: exports.ConfidenceLevelSchema,
302
+ /** Human-readable reputation level */
303
+ level: exports.ReputationLevelSchema,
304
+ /** Detailed score component breakdown (Bayesian algorithm) */
305
+ components: exports.ScoreComponentsSchema,
306
+ /** Optional detailed factors breakdown (for Know That AI API compatibility) */
307
+ factors: exports.ReputationFactorsSchema.optional(),
308
+ /** Whether this score is provisional (limited data) */
309
+ isProvisional: zod_1.z.boolean(),
310
+ /** Timestamp when the score was calculated (ISO 8601) */
311
+ calculatedAt: zod_1.z.string().datetime(),
312
+ /** DID of the agent this score belongs to */
313
+ agentDid: zod_1.z.string().min(1),
314
+ });
315
+ // ============================================================================
316
+ // CALCULATOR CONFIGURATION
317
+ // ============================================================================
318
+ /**
319
+ * Calculator Preset Schema
320
+ *
321
+ * Pre-defined calculator configurations for different use cases.
322
+ */
323
+ exports.CalculatorPresetSchema = zod_1.z.enum([
324
+ "Testing", // k=5, fast confidence growth (for testing)
325
+ "Conservative", // k=20, slow confidence growth (production default)
326
+ "Aggressive", // k=10, moderate confidence growth
327
+ ]);
328
+ /**
329
+ * Calculator Weights Schema
330
+ *
331
+ * Weight distribution for scoring components.
332
+ * All weights should sum to 1.0.
333
+ */
334
+ exports.CalculatorWeightsSchema = zod_1.z
335
+ .object({
336
+ /** Weight for review-based scoring */
337
+ reviews: zod_1.z.number().min(0).max(1).default(0.4),
338
+ /** Weight for interaction-based scoring */
339
+ interactions: zod_1.z.number().min(0).max(1).default(0.3),
340
+ /** Weight for consistency metrics */
341
+ consistency: zod_1.z.number().min(0).max(1).default(0.3),
342
+ })
343
+ .refine((weights) => {
344
+ const sum = weights.reviews + weights.interactions + weights.consistency;
345
+ return Math.abs(sum - 1.0) < 0.001; // Allow small floating point variance
346
+ }, {
347
+ message: "Weights must sum to 1.0",
348
+ });
349
+ /**
350
+ * Calculator Config Schema
351
+ *
352
+ * Configuration options for the reputation calculator.
353
+ */
354
+ exports.CalculatorConfigSchema = zod_1.z.object({
355
+ /** K value for confidence calculation: confidence = n / (n + k) */
356
+ kValue: zod_1.z.number().positive().default(15),
357
+ /** Optional preset (overrides other settings) */
358
+ preset: exports.CalculatorPresetSchema.optional(),
359
+ /** Component weights */
360
+ weights: exports.CalculatorWeightsSchema.optional(),
361
+ /** Base prior score (default: 50) */
362
+ basePriorScore: zod_1.z.number().min(0).max(100).default(50),
363
+ /** Maximum prior score (default: 80) */
364
+ maxPriorScore: zod_1.z.number().min(0).max(100).default(80),
365
+ });
366
+ // ============================================================================
367
+ // SCORE PREDICTION
368
+ // ============================================================================
369
+ /**
370
+ * Score Change Prediction Schema
371
+ *
372
+ * Input for predicting how a score would change given hypothetical changes.
373
+ */
374
+ exports.ScoreChangePredictionRequestSchema = zod_1.z.object({
375
+ /** Current agent data */
376
+ current: exports.AgentDataSchema,
377
+ /** Hypothetical changes to apply */
378
+ changes: zod_1.z.object({
379
+ /** Additional reviews to add */
380
+ additionalReviews: zod_1.z.number().int().nonnegative().optional(),
381
+ /** New average rating after changes */
382
+ newAverageRating: zod_1.z.number().min(1).max(5).optional(),
383
+ /** Additional interactions */
384
+ additionalInteractions: zod_1.z.number().int().nonnegative().optional(),
385
+ /** Additional successful interactions */
386
+ additionalSuccessfulInteractions: zod_1.z.number().int().nonnegative().optional(),
387
+ }),
388
+ /** Optional calculator configuration */
389
+ config: exports.CalculatorConfigSchema.optional(),
390
+ });
391
+ /**
392
+ * Score Change Prediction Response Schema
393
+ */
394
+ exports.ScoreChangePredictionResponseSchema = zod_1.z.object({
395
+ /** Current score */
396
+ currentScore: exports.ReputationScoreSchema,
397
+ /** Predicted score after changes */
398
+ predictedScore: exports.ReputationScoreSchema,
399
+ /** Score difference */
400
+ scoreDelta: zod_1.z.number(),
401
+ /** Confidence difference */
402
+ confidenceDelta: zod_1.z.number(),
403
+ });
404
+ // ============================================================================
405
+ // VALIDATION HELPERS
406
+ // ============================================================================
407
+ /**
408
+ * Validate agent data
409
+ *
410
+ * @param data - The data to validate
411
+ * @returns Validation result
412
+ */
413
+ function validateAgentData(data) {
414
+ return exports.AgentDataSchema.safeParse(data);
415
+ }
416
+ /**
417
+ * Validate reputation score
418
+ *
419
+ * @param score - The score to validate
420
+ * @returns Validation result
421
+ */
422
+ function validateReputationScore(score) {
423
+ return exports.ReputationScoreSchema.safeParse(score);
424
+ }
425
+ /**
426
+ * Validate calculator config
427
+ *
428
+ * @param config - The config to validate
429
+ * @returns Validation result
430
+ */
431
+ function validateCalculatorConfig(config) {
432
+ return exports.CalculatorConfigSchema.safeParse(config);
433
+ }
434
+ // ============================================================================
435
+ // SCORE LEVEL HELPERS
436
+ // ============================================================================
437
+ /**
438
+ * Get reputation level from score
439
+ *
440
+ * @param score - Numeric score (0-100)
441
+ * @returns Reputation level
442
+ */
443
+ function getReputationLevel(score) {
444
+ if (score < 0 || !Number.isFinite(score))
445
+ return "Unknown";
446
+ if (score < 30)
447
+ return "Poor";
448
+ if (score < 45)
449
+ return "BelowAverage";
450
+ if (score < 60)
451
+ return "Average";
452
+ if (score < 75)
453
+ return "Good";
454
+ if (score < 90)
455
+ return "Excellent";
456
+ return "Outstanding";
457
+ }
458
+ /**
459
+ * Get confidence level from confidence value
460
+ *
461
+ * @param confidence - Numeric confidence (0-1)
462
+ * @returns Confidence level
463
+ */
464
+ function getConfidenceLevel(confidence) {
465
+ if (confidence < 0.25)
466
+ return "Low";
467
+ if (confidence < 0.5)
468
+ return "Medium";
469
+ if (confidence < 0.75)
470
+ return "High";
471
+ return "VeryHigh";
472
+ }
473
+ /**
474
+ * Calculate confidence from interaction count using the k formula
475
+ *
476
+ * confidence = n / (n + k)
477
+ *
478
+ * @param interactionCount - Number of interactions
479
+ * @param kValue - K value (default: 15)
480
+ * @returns Confidence value (0-1)
481
+ */
482
+ function calculateConfidence(interactionCount, kValue = 15) {
483
+ if (interactionCount < 0 || kValue <= 0)
484
+ return 0;
485
+ return interactionCount / (interactionCount + kValue);
486
+ }
487
+ /**
488
+ * Check if agent data indicates a provisional score
489
+ * (insufficient data for high confidence)
490
+ *
491
+ * @param data - Agent data
492
+ * @returns true if score should be marked provisional
493
+ */
494
+ function isProvisionalScore(data) {
495
+ const interactions = data.interactions?.totalInteractions ?? 0;
496
+ const reviews = data.reviews?.totalReviews ?? 0;
497
+ // Provisional if less than 5 interactions AND less than 3 reviews
498
+ return interactions < 5 && reviews < 3;
499
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/contracts",
3
- "version": "1.6.17",
3
+ "version": "1.6.19",
4
4
  "description": "Shared contracts, types, and schemas for MCP-I framework",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -72,6 +72,14 @@
72
72
  "./identity": {
73
73
  "types": "./dist/identity/index.d.ts",
74
74
  "default": "./dist/identity/index.js"
75
+ },
76
+ "./deploy": {
77
+ "types": "./dist/deploy/index.d.ts",
78
+ "default": "./dist/deploy/index.js"
79
+ },
80
+ "./reputation": {
81
+ "types": "./dist/reputation/index.d.ts",
82
+ "default": "./dist/reputation/index.js"
75
83
  }
76
84
  },
77
85
  "scripts": {