@vorionsys/cognigate 1.0.0

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/index.cjs ADDED
@@ -0,0 +1,515 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AgentSchema: () => AgentSchema,
24
+ Cognigate: () => Cognigate,
25
+ CognigateError: () => CognigateError,
26
+ GovernanceResultSchema: () => GovernanceResultSchema,
27
+ ProofRecordSchema: () => ProofRecordSchema,
28
+ TIER_THRESHOLDS: () => TIER_THRESHOLDS,
29
+ TrustStatusSchema: () => TrustStatusSchema,
30
+ TrustTier: () => TrustTier,
31
+ WebhookRouter: () => WebhookRouter,
32
+ parseWebhookPayload: () => parseWebhookPayload,
33
+ verifyWebhookSignature: () => verifyWebhookSignature,
34
+ z: () => import_zod2.z
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/types.ts
39
+ var import_zod = require("zod");
40
+ var TrustTier = /* @__PURE__ */ ((TrustTier2) => {
41
+ TrustTier2[TrustTier2["T0_SANDBOX"] = 0] = "T0_SANDBOX";
42
+ TrustTier2[TrustTier2["T1_OBSERVED"] = 1] = "T1_OBSERVED";
43
+ TrustTier2[TrustTier2["T2_PROVISIONAL"] = 2] = "T2_PROVISIONAL";
44
+ TrustTier2[TrustTier2["T3_VERIFIED"] = 3] = "T3_VERIFIED";
45
+ TrustTier2[TrustTier2["T4_OPERATIONAL"] = 4] = "T4_OPERATIONAL";
46
+ TrustTier2[TrustTier2["T5_TRUSTED"] = 5] = "T5_TRUSTED";
47
+ TrustTier2[TrustTier2["T6_CERTIFIED"] = 6] = "T6_CERTIFIED";
48
+ TrustTier2[TrustTier2["T7_AUTONOMOUS"] = 7] = "T7_AUTONOMOUS";
49
+ return TrustTier2;
50
+ })(TrustTier || {});
51
+ var TIER_THRESHOLDS = {
52
+ [0 /* T0_SANDBOX */]: { min: 0, max: 199, name: "Sandbox" },
53
+ [1 /* T1_OBSERVED */]: { min: 200, max: 349, name: "Observed" },
54
+ [2 /* T2_PROVISIONAL */]: { min: 350, max: 499, name: "Provisional" },
55
+ [3 /* T3_VERIFIED */]: { min: 500, max: 649, name: "Verified" },
56
+ [4 /* T4_OPERATIONAL */]: { min: 650, max: 799, name: "Operational" },
57
+ [5 /* T5_TRUSTED */]: { min: 800, max: 875, name: "Trusted" },
58
+ [6 /* T6_CERTIFIED */]: { min: 876, max: 949, name: "Certified" },
59
+ [7 /* T7_AUTONOMOUS */]: { min: 950, max: 1e3, name: "Autonomous" }
60
+ };
61
+ var TrustStatusSchema = import_zod.z.object({
62
+ entityId: import_zod.z.string(),
63
+ trustScore: import_zod.z.number().min(0).max(1e3),
64
+ trustTier: import_zod.z.nativeEnum(TrustTier),
65
+ tierName: import_zod.z.string(),
66
+ capabilities: import_zod.z.array(import_zod.z.string()),
67
+ factorScores: import_zod.z.record(import_zod.z.string(), import_zod.z.number()),
68
+ lastEvaluated: import_zod.z.coerce.date(),
69
+ compliant: import_zod.z.boolean(),
70
+ warnings: import_zod.z.array(import_zod.z.string())
71
+ });
72
+ var GovernanceResultSchema = import_zod.z.object({
73
+ decision: import_zod.z.enum(["ALLOW", "DENY", "ESCALATE", "DEGRADE"]),
74
+ trustScore: import_zod.z.number(),
75
+ trustTier: import_zod.z.nativeEnum(TrustTier),
76
+ grantedCapabilities: import_zod.z.array(import_zod.z.string()),
77
+ deniedCapabilities: import_zod.z.array(import_zod.z.string()),
78
+ reasoning: import_zod.z.string(),
79
+ constraints: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
80
+ proofId: import_zod.z.string().optional(),
81
+ timestamp: import_zod.z.coerce.date()
82
+ });
83
+ var ProofRecordSchema = import_zod.z.object({
84
+ id: import_zod.z.string(),
85
+ entityId: import_zod.z.string(),
86
+ intentId: import_zod.z.string(),
87
+ decision: import_zod.z.enum(["ALLOW", "DENY", "ESCALATE", "DEGRADE"]),
88
+ action: import_zod.z.string(),
89
+ outcome: import_zod.z.enum(["SUCCESS", "FAILURE", "PARTIAL", "PENDING"]),
90
+ trustScoreBefore: import_zod.z.number(),
91
+ trustScoreAfter: import_zod.z.number(),
92
+ timestamp: import_zod.z.coerce.date(),
93
+ hash: import_zod.z.string(),
94
+ previousHash: import_zod.z.string(),
95
+ metadata: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
96
+ });
97
+ var AgentSchema = import_zod.z.object({
98
+ id: import_zod.z.string(),
99
+ name: import_zod.z.string(),
100
+ description: import_zod.z.string(),
101
+ ownerId: import_zod.z.string(),
102
+ trustScore: import_zod.z.number(),
103
+ trustTier: import_zod.z.nativeEnum(TrustTier),
104
+ status: import_zod.z.enum(["ACTIVE", "PAUSED", "SUSPENDED", "TERMINATED"]),
105
+ capabilities: import_zod.z.array(import_zod.z.string()),
106
+ executions: import_zod.z.number(),
107
+ successRate: import_zod.z.number(),
108
+ createdAt: import_zod.z.coerce.date(),
109
+ updatedAt: import_zod.z.coerce.date(),
110
+ metadata: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
111
+ });
112
+
113
+ // src/client.ts
114
+ var DEFAULT_BASE_URL = "https://cognigate.dev/v1";
115
+ var DEFAULT_TIMEOUT = 3e4;
116
+ var DEFAULT_RETRIES = 3;
117
+ var CognigateError = class extends Error {
118
+ constructor(message, code, status, details) {
119
+ super(message);
120
+ this.code = code;
121
+ this.status = status;
122
+ this.details = details;
123
+ this.name = "CognigateError";
124
+ }
125
+ };
126
+ var Cognigate = class {
127
+ config;
128
+ agents;
129
+ trust;
130
+ governance;
131
+ proofs;
132
+ constructor(config) {
133
+ if (!config.apiKey) {
134
+ throw new CognigateError("API key is required", "MISSING_API_KEY");
135
+ }
136
+ this.config = {
137
+ apiKey: config.apiKey,
138
+ baseUrl: config.baseUrl || DEFAULT_BASE_URL,
139
+ timeout: config.timeout || DEFAULT_TIMEOUT,
140
+ retries: config.retries || DEFAULT_RETRIES,
141
+ debug: config.debug || false,
142
+ webhookSecret: config.webhookSecret
143
+ };
144
+ this.agents = new AgentsClient(this);
145
+ this.trust = new TrustClient(this);
146
+ this.governance = new GovernanceClient(this);
147
+ this.proofs = new ProofsClient(this);
148
+ }
149
+ /**
150
+ * Make an authenticated request to the Cognigate API
151
+ */
152
+ async request(method, path, body) {
153
+ const url = `${this.config.baseUrl}${path}`;
154
+ const headers = {
155
+ "Authorization": `Bearer ${this.config.apiKey}`,
156
+ "Content-Type": "application/json",
157
+ "X-SDK-Version": "1.0.0",
158
+ "X-SDK-Language": "typescript"
159
+ };
160
+ let lastError = null;
161
+ for (let attempt = 0; attempt < this.config.retries; attempt++) {
162
+ try {
163
+ const controller = new AbortController();
164
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
165
+ const response = await fetch(url, {
166
+ method,
167
+ headers,
168
+ body: body ? JSON.stringify(body) : void 0,
169
+ signal: controller.signal
170
+ });
171
+ clearTimeout(timeoutId);
172
+ if (this.config.debug) {
173
+ console.log(`[Cognigate] ${method} ${path} -> ${response.status}`);
174
+ }
175
+ if (!response.ok) {
176
+ const errorData = await response.json().catch(() => ({}));
177
+ throw new CognigateError(
178
+ errorData.message || `Request failed with status ${response.status}`,
179
+ errorData.code || "REQUEST_FAILED",
180
+ response.status,
181
+ errorData.details
182
+ );
183
+ }
184
+ const data = await response.json();
185
+ return data;
186
+ } catch (error) {
187
+ lastError = error;
188
+ if (error instanceof CognigateError && error.status && error.status < 500) {
189
+ throw error;
190
+ }
191
+ if (attempt < this.config.retries - 1) {
192
+ const delay = Math.pow(2, attempt) * 1e3;
193
+ await new Promise((resolve) => setTimeout(resolve, delay));
194
+ }
195
+ }
196
+ }
197
+ throw lastError || new CognigateError("Request failed", "UNKNOWN_ERROR");
198
+ }
199
+ /**
200
+ * Check API health
201
+ */
202
+ async health() {
203
+ return this.request("GET", "/health");
204
+ }
205
+ /**
206
+ * Get tier from trust score
207
+ */
208
+ static getTierFromScore(score) {
209
+ if (score >= 950) return 7 /* T7_AUTONOMOUS */;
210
+ if (score >= 876) return 6 /* T6_CERTIFIED */;
211
+ if (score >= 800) return 5 /* T5_TRUSTED */;
212
+ if (score >= 650) return 4 /* T4_OPERATIONAL */;
213
+ if (score >= 500) return 3 /* T3_VERIFIED */;
214
+ if (score >= 350) return 2 /* T2_PROVISIONAL */;
215
+ if (score >= 200) return 1 /* T1_OBSERVED */;
216
+ return 0 /* T0_SANDBOX */;
217
+ }
218
+ /**
219
+ * Get tier name
220
+ */
221
+ static getTierName(tier) {
222
+ return TIER_THRESHOLDS[tier].name;
223
+ }
224
+ /**
225
+ * Get tier thresholds
226
+ */
227
+ static getTierThresholds(tier) {
228
+ return TIER_THRESHOLDS[tier];
229
+ }
230
+ };
231
+ var AgentsClient = class {
232
+ constructor(client) {
233
+ this.client = client;
234
+ }
235
+ /**
236
+ * List all agents
237
+ */
238
+ async list(params) {
239
+ const query = new URLSearchParams();
240
+ if (params?.page) query.set("page", params.page.toString());
241
+ if (params?.pageSize) query.set("pageSize", params.pageSize.toString());
242
+ if (params?.status) query.set("status", params.status);
243
+ const queryString = query.toString();
244
+ const path = `/agents${queryString ? `?${queryString}` : ""}`;
245
+ return this.client.request("GET", path);
246
+ }
247
+ /**
248
+ * Get a specific agent
249
+ */
250
+ async get(agentId) {
251
+ const response = await this.client.request("GET", `/agents/${agentId}`);
252
+ return AgentSchema.parse(response);
253
+ }
254
+ /**
255
+ * Create a new agent
256
+ */
257
+ async create(data) {
258
+ const response = await this.client.request("POST", "/agents", data);
259
+ return AgentSchema.parse(response);
260
+ }
261
+ /**
262
+ * Update an agent
263
+ */
264
+ async update(agentId, data) {
265
+ const response = await this.client.request("PATCH", `/agents/${agentId}`, data);
266
+ return AgentSchema.parse(response);
267
+ }
268
+ /**
269
+ * Delete an agent
270
+ */
271
+ async delete(agentId) {
272
+ await this.client.request("DELETE", `/agents/${agentId}`);
273
+ }
274
+ /**
275
+ * Pause an agent
276
+ */
277
+ async pause(agentId) {
278
+ return this.update(agentId, { status: "PAUSED" });
279
+ }
280
+ /**
281
+ * Resume an agent
282
+ */
283
+ async resume(agentId) {
284
+ return this.update(agentId, { status: "ACTIVE" });
285
+ }
286
+ };
287
+ var TrustClient = class {
288
+ constructor(client) {
289
+ this.client = client;
290
+ }
291
+ /**
292
+ * Get trust status for an entity
293
+ */
294
+ async getStatus(entityId) {
295
+ const response = await this.client.request("GET", `/trust/${entityId}`);
296
+ return TrustStatusSchema.parse(response);
297
+ }
298
+ /**
299
+ * Get trust history
300
+ */
301
+ async getHistory(entityId, params) {
302
+ const query = new URLSearchParams();
303
+ if (params?.from) query.set("from", params.from.toISOString());
304
+ if (params?.to) query.set("to", params.to.toISOString());
305
+ if (params?.limit) query.set("limit", params.limit.toString());
306
+ const queryString = query.toString();
307
+ const path = `/trust/${entityId}/history${queryString ? `?${queryString}` : ""}`;
308
+ return this.client.request("GET", path);
309
+ }
310
+ /**
311
+ * Submit an outcome to update trust score
312
+ */
313
+ async submitOutcome(entityId, proofId, outcome) {
314
+ const response = await this.client.request(
315
+ "POST",
316
+ `/trust/${entityId}/outcome`,
317
+ { proofId, ...outcome }
318
+ );
319
+ return TrustStatusSchema.parse(response);
320
+ }
321
+ };
322
+ var GovernanceClient = class {
323
+ constructor(client) {
324
+ this.client = client;
325
+ }
326
+ /**
327
+ * Parse user intent into structured format
328
+ */
329
+ async parseIntent(entityId, rawInput) {
330
+ return this.client.request("POST", "/governance/parse", {
331
+ entityId,
332
+ rawInput
333
+ });
334
+ }
335
+ /**
336
+ * Enforce governance rules on an intent
337
+ */
338
+ async enforce(intent) {
339
+ const response = await this.client.request(
340
+ "POST",
341
+ "/governance/enforce",
342
+ intent
343
+ );
344
+ return GovernanceResultSchema.parse(response);
345
+ }
346
+ /**
347
+ * Convenience method: parse and enforce in one call
348
+ */
349
+ async evaluate(entityId, rawInput) {
350
+ const parseResult = await this.parseIntent(entityId, rawInput);
351
+ const result = await this.enforce(parseResult.intent);
352
+ return {
353
+ intent: parseResult.intent,
354
+ result
355
+ };
356
+ }
357
+ /**
358
+ * Check if an action is allowed without creating a proof record
359
+ */
360
+ async canPerform(entityId, action, capabilities) {
361
+ return this.client.request("POST", "/governance/check", {
362
+ entityId,
363
+ action,
364
+ capabilities
365
+ });
366
+ }
367
+ };
368
+ var ProofsClient = class {
369
+ constructor(client) {
370
+ this.client = client;
371
+ }
372
+ /**
373
+ * Get a specific proof record
374
+ */
375
+ async get(proofId) {
376
+ const response = await this.client.request("GET", `/proofs/${proofId}`);
377
+ return ProofRecordSchema.parse(response);
378
+ }
379
+ /**
380
+ * List proof records for an entity
381
+ */
382
+ async list(entityId, params) {
383
+ const query = new URLSearchParams();
384
+ query.set("entityId", entityId);
385
+ if (params?.page) query.set("page", params.page.toString());
386
+ if (params?.pageSize) query.set("pageSize", params.pageSize.toString());
387
+ if (params?.from) query.set("from", params.from.toISOString());
388
+ if (params?.to) query.set("to", params.to.toISOString());
389
+ if (params?.outcome) query.set("outcome", params.outcome);
390
+ return this.client.request("GET", `/proofs?${query.toString()}`);
391
+ }
392
+ /**
393
+ * Get proof chain statistics
394
+ */
395
+ async getStats(entityId) {
396
+ return this.client.request("GET", `/proofs/stats/${entityId}`);
397
+ }
398
+ /**
399
+ * Verify proof chain integrity
400
+ */
401
+ async verify(entityId) {
402
+ return this.client.request("POST", `/proofs/verify/${entityId}`);
403
+ }
404
+ };
405
+
406
+ // src/webhooks.ts
407
+ async function verifyWebhookSignature(payload, signature, secret) {
408
+ const encoder = new TextEncoder();
409
+ const data = encoder.encode(payload);
410
+ const key = await crypto.subtle.importKey(
411
+ "raw",
412
+ encoder.encode(secret),
413
+ { name: "HMAC", hash: "SHA-256" },
414
+ false,
415
+ ["sign"]
416
+ );
417
+ const signatureBuffer = await crypto.subtle.sign("HMAC", key, data);
418
+ const expectedSignature = bufferToHex(signatureBuffer);
419
+ return timingSafeEqual(signature, expectedSignature);
420
+ }
421
+ function parseWebhookPayload(body, signature, secret) {
422
+ return new Promise(async (resolve, reject) => {
423
+ const isValid = await verifyWebhookSignature(body, signature, secret);
424
+ if (!isValid) {
425
+ reject(new Error("Invalid webhook signature"));
426
+ return;
427
+ }
428
+ try {
429
+ const event = JSON.parse(body);
430
+ event.timestamp = new Date(event.timestamp);
431
+ resolve(event);
432
+ } catch (error) {
433
+ reject(new Error("Invalid webhook payload"));
434
+ }
435
+ });
436
+ }
437
+ var WebhookRouter = class {
438
+ handlers = /* @__PURE__ */ new Map();
439
+ /**
440
+ * Register a handler for a specific event type
441
+ */
442
+ on(type, handler) {
443
+ const existing = this.handlers.get(type) || [];
444
+ existing.push(handler);
445
+ this.handlers.set(type, existing);
446
+ return this;
447
+ }
448
+ /**
449
+ * Register a handler for all events
450
+ */
451
+ onAll(handler) {
452
+ const existing = this.handlers.get("*") || [];
453
+ existing.push(handler);
454
+ this.handlers.set("*", existing);
455
+ return this;
456
+ }
457
+ /**
458
+ * Handle a webhook event
459
+ */
460
+ async handle(event) {
461
+ const typeHandlers = this.handlers.get(event.type) || [];
462
+ const allHandlers = this.handlers.get("*") || [];
463
+ const handlers = [...typeHandlers, ...allHandlers];
464
+ for (const handler of handlers) {
465
+ await handler(event);
466
+ }
467
+ }
468
+ /**
469
+ * Create an Express/Connect compatible middleware
470
+ */
471
+ middleware(secret) {
472
+ return async (req, res, _next) => {
473
+ try {
474
+ const signature = req.headers["x-cognigate-signature"];
475
+ const body = typeof req.body === "string" ? req.body : JSON.stringify(req.body);
476
+ const event = await parseWebhookPayload(body, signature, secret);
477
+ await this.handle(event);
478
+ res.status(200).json({ received: true });
479
+ } catch (error) {
480
+ res.status(400).json({ error: error.message });
481
+ }
482
+ };
483
+ }
484
+ };
485
+ function bufferToHex(buffer) {
486
+ return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
487
+ }
488
+ function timingSafeEqual(a, b) {
489
+ if (a.length !== b.length) {
490
+ return false;
491
+ }
492
+ let result = 0;
493
+ for (let i = 0; i < a.length; i++) {
494
+ result |= a.charCodeAt(i) ^ b.charCodeAt(i);
495
+ }
496
+ return result === 0;
497
+ }
498
+
499
+ // src/index.ts
500
+ var import_zod2 = require("zod");
501
+ // Annotate the CommonJS export names for ESM import in node:
502
+ 0 && (module.exports = {
503
+ AgentSchema,
504
+ Cognigate,
505
+ CognigateError,
506
+ GovernanceResultSchema,
507
+ ProofRecordSchema,
508
+ TIER_THRESHOLDS,
509
+ TrustStatusSchema,
510
+ TrustTier,
511
+ WebhookRouter,
512
+ parseWebhookPayload,
513
+ verifyWebhookSignature,
514
+ z
515
+ });