@rubric-protocol/sdk 1.0.1 → 1.0.3

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.js CHANGED
@@ -1,117 +1,28 @@
1
1
  "use strict";
2
- /**
3
- * RUBRIC PROTOCOL SDK
4
- * AI Attestation Infrastructure — EU AI Act Article 12 Compliance
5
- * Rubric Protocol
6
- */
7
2
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.RubricClient = void 0;
9
- class RubricClient {
10
- constructor(config) {
11
- this.baseUrl = config.baseUrl.replace(/\/$/, '');
12
- this.apiKey = config.apiKey;
13
- }
14
- async request(method, path, body) {
15
- const headers = { 'Content-Type': 'application/json' };
16
- if (this.apiKey)
17
- headers['x-api-key'] = this.apiKey;
18
- const opts = { method, headers };
19
- if (body)
20
- opts.body = JSON.stringify(body);
21
- const res = await fetch(`${this.baseUrl}${path}`, opts);
22
- if (!res.ok) {
23
- const err = await res.json().catch(() => ({ error: res.statusText }));
24
- throw new Error(err.error || `HTTP ${res.status}`);
25
- }
26
- return res.json();
27
- }
28
- // ── Health ──
29
- async health() { return this.request('GET', '/'); }
30
- async stats() { return this.request('GET', '/v1/stats'); }
31
- // ── Agents ──
32
- async registerAgent(name, capabilities, endpoint) {
33
- return this.request('POST', '/v1/agents', { name, capabilities, endpoint });
34
- }
35
- async listAgents(capability) {
36
- const q = capability ? `?capability=${capability}` : '';
37
- return this.request('GET', `/v1/agents${q}`);
38
- }
39
- async getAgent(agentId) {
40
- return this.request('GET', `/v1/agents/${agentId}`);
41
- }
42
- async deregisterAgent(agentId) {
43
- return this.request('DELETE', `/v1/agents/${agentId}`);
44
- }
45
- async getReputation(agentId) {
46
- return this.request('GET', `/v1/agents/${agentId}/reputation`);
47
- }
48
- async leaderboard() {
49
- return this.request('GET', '/v1/leaderboard');
50
- }
51
- // ── Tasks ──
52
- async submitTask(type, description, input) {
53
- return this.request('POST', '/v1/tasks', { type, description, input });
54
- }
55
- async listTasks() {
56
- return this.request('GET', '/v1/tasks');
57
- }
58
- async getTask(taskId) {
59
- return this.request('GET', `/v1/tasks/${taskId}`);
60
- }
61
- async placeBid(taskId, agentId, cost, estimatedTime, confidence) {
62
- return this.request('POST', `/v1/tasks/${taskId}/bid`, { agentId, cost, estimatedTime, confidence });
63
- }
64
- async assignTask(taskId) {
65
- return this.request('POST', `/v1/tasks/${taskId}/assign`, {});
66
- }
67
- async submitResult(taskId, agentId, output, executionTime) {
68
- return this.request('POST', `/v1/tasks/${taskId}/result`, { agentId, output, executionTime });
69
- }
70
- // ── Pipelines ──
71
- async createPipeline(name, steps) {
72
- return this.request('POST', '/v1/pipelines', { name, steps });
73
- }
74
- async listPipelines() {
75
- return this.request('GET', '/v1/pipelines');
76
- }
77
- async getPipeline(pipelineId) {
78
- return this.request('GET', `/v1/pipelines/${pipelineId}`);
79
- }
80
- async startPipeline(pipelineId, input) {
81
- return this.request('POST', `/v1/pipelines/${pipelineId}/start`, { input });
82
- }
83
- async completeStep(pipelineId, agentId, output, executionTime) {
84
- return this.request('POST', `/v1/pipelines/${pipelineId}/step-result`, { agentId, output, executionTime });
85
- }
86
- // ── Proof ──
87
- async verify(sequenceNumber) {
88
- return this.request('GET', `/v1/proof/${sequenceNumber}`);
89
- }
90
- // ── Events ──
91
- async events(limit = 50, type) {
92
- const params = [`limit=${limit}`];
93
- if (type)
94
- params.push(`type=${type}`);
95
- return this.request('GET', `/v1/events?${params.join('&')}`);
96
- }
97
- // ── Convenience: Run full task lifecycle ──
98
- async runTask(agentId, type, description, output, executionTime = 2000) {
99
- const task = await this.submitTask(type, description);
100
- await this.placeBid(task.taskId, agentId, 500, 3000, 0.95);
101
- await this.assignTask(task.taskId);
102
- return this.submitResult(task.taskId, agentId, output, executionTime);
103
- }
104
- // ── Convenience: Run full pipeline ──
105
- async runPipeline(name, steps, input) {
106
- const pipeline = await this.createPipeline(name, steps.map(s => ({ type: s.type, capability: s.capability, description: s.description })));
107
- await this.startPipeline(pipeline.pipelineId, input);
108
- let result;
109
- for (const step of steps) {
110
- result = await this.completeStep(pipeline.pipelineId, 'sdk-auto', step.output, 2000);
111
- }
112
- return { pipeline: await this.getPipeline(pipeline.pipelineId), attestations: result.attestations || [] };
113
- }
114
- }
115
- exports.RubricClient = RubricClient;
116
- // Default export
117
- exports.default = RubricClient;
3
+ exports.RubricOpenAIClient = exports.withRubric = exports.RubricLangChainHandler = exports.BackgroundQueue = exports.loadKeyPair = exports.saveKeyPair = exports.loadOrCreateKeyPair = exports.verifySignedPayload = exports.signPayload = exports.generateKeyPair = exports.resetUpgradeManager = exports.getUpgradeManager = exports.ProofUpgradeManager = exports.STAGE_METADATA = exports.LiveProof = exports.createRubricClient = exports.RubricClient = void 0;
4
+ var rubric_client_1 = require("./rubric-client");
5
+ Object.defineProperty(exports, "RubricClient", { enumerable: true, get: function () { return rubric_client_1.RubricClient; } });
6
+ Object.defineProperty(exports, "createRubricClient", { enumerable: true, get: function () { return rubric_client_1.createRubricClient; } });
7
+ var proof_types_1 = require("./proof-types");
8
+ Object.defineProperty(exports, "LiveProof", { enumerable: true, get: function () { return proof_types_1.LiveProof; } });
9
+ Object.defineProperty(exports, "STAGE_METADATA", { enumerable: true, get: function () { return proof_types_1.STAGE_METADATA; } });
10
+ var proof_upgrade_manager_1 = require("./proof-upgrade-manager");
11
+ Object.defineProperty(exports, "ProofUpgradeManager", { enumerable: true, get: function () { return proof_upgrade_manager_1.ProofUpgradeManager; } });
12
+ Object.defineProperty(exports, "getUpgradeManager", { enumerable: true, get: function () { return proof_upgrade_manager_1.getUpgradeManager; } });
13
+ Object.defineProperty(exports, "resetUpgradeManager", { enumerable: true, get: function () { return proof_upgrade_manager_1.resetUpgradeManager; } });
14
+ var ml_dsa_local_1 = require("./ml-dsa-local");
15
+ Object.defineProperty(exports, "generateKeyPair", { enumerable: true, get: function () { return ml_dsa_local_1.generateKeyPair; } });
16
+ Object.defineProperty(exports, "signPayload", { enumerable: true, get: function () { return ml_dsa_local_1.signPayload; } });
17
+ Object.defineProperty(exports, "verifySignedPayload", { enumerable: true, get: function () { return ml_dsa_local_1.verifySignedPayload; } });
18
+ Object.defineProperty(exports, "loadOrCreateKeyPair", { enumerable: true, get: function () { return ml_dsa_local_1.loadOrCreateKeyPair; } });
19
+ Object.defineProperty(exports, "saveKeyPair", { enumerable: true, get: function () { return ml_dsa_local_1.saveKeyPair; } });
20
+ Object.defineProperty(exports, "loadKeyPair", { enumerable: true, get: function () { return ml_dsa_local_1.loadKeyPair; } });
21
+ var background_queue_1 = require("./background-queue");
22
+ Object.defineProperty(exports, "BackgroundQueue", { enumerable: true, get: function () { return background_queue_1.BackgroundQueue; } });
23
+ var langchain_1 = require("./plugins/langchain");
24
+ Object.defineProperty(exports, "RubricLangChainHandler", { enumerable: true, get: function () { return langchain_1.RubricLangChainHandler; } });
25
+ var openai_plugin_1 = require("./plugins/openai-plugin");
26
+ Object.defineProperty(exports, "withRubric", { enumerable: true, get: function () { return openai_plugin_1.withRubric; } });
27
+ Object.defineProperty(exports, "RubricOpenAIClient", { enumerable: true, get: function () { return openai_plugin_1.RubricOpenAIClient; } });
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;AAAA,iDAAmE;AAA1D,6GAAA,YAAY,OAAA;AAAE,mHAAA,kBAAkB,OAAA;AAEzC,6CAA0D;AAAjD,wGAAA,SAAS,OAAA;AAAE,6GAAA,cAAc,OAAA;AAElC,iEAAsG;AAA7F,4HAAA,mBAAmB,OAAA;AAAE,0HAAA,iBAAiB,OAAA;AAAE,4HAAA,mBAAmB,OAAA;AAEpE,+CAAkI;AAAzH,+GAAA,eAAe,OAAA;AAAE,2GAAA,WAAW,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAAE,2GAAA,WAAW,OAAA;AAAE,2GAAA,WAAW,OAAA;AAEzG,uDAAqD;AAA5C,mHAAA,eAAe,OAAA;AAExB,iDAA6D;AAApD,mHAAA,sBAAsB,OAAA;AAE/B,yDAAyE;AAAhE,2GAAA,UAAU,OAAA;AAAE,mHAAA,kBAAkB,OAAA"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Rubric Protocol — Local ML-DSA-65 Signing
3
+ * Uses @noble/post-quantum (NIST FIPS 204)
4
+ * Handles key generation, signing, verification, and filesystem persistence.
5
+ */
6
+ export interface LocalKeyPair {
7
+ publicKey: Uint8Array;
8
+ secretKey: Uint8Array;
9
+ publicKeyHex: string;
10
+ created: string;
11
+ }
12
+ export interface SignedPayload {
13
+ payload: Record<string, unknown>;
14
+ signature: string;
15
+ publicKey: string;
16
+ signedAt: string;
17
+ algorithm: 'ML-DSA-65';
18
+ }
19
+ /**
20
+ * Generate a fresh ML-DRA-65 keypair from a 32-byte random seed.
21
+ */
22
+ export declare function generateKeyPair(): LocalKeyPair;
23
+ /**
24
+ * Sign an arbitrary payload object with a local secret key.
25
+ * Canonical JSON serialization ensures deterministic signing.
26
+ */
27
+ export declare function signPayload(payload: Record<string, unknown>, secretKey: Uint8Array, publicKey: Uint8Array): SignedPayload;
28
+ /**
29
+ * Verify a signed payload locally (for testing / offline verification).
30
+ */
31
+ export declare function verifySignedPayload(signed: SignedPayload): boolean;
32
+ export declare function saveKeyPair(kp: LocalKeyPair, filePath: string, passphrase?: string): void;
33
+ export declare function loadKeyPair(filePath: string, passphrase?: string): LocalKeyPair;
34
+ export declare function loadOrCreateKeyPair(filePath: string, passphrase?: string): LocalKeyPair;
35
+ //# sourceMappingURL=ml-dsa-local.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ml-dsa-local.d.ts","sourceRoot":"","sources":["../ml-dsa-local.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AASH,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,UAAU,CAAC;IACtB,SAAS,EAAE,UAAU,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,WAAW,CAAC;CACxB;AAID;;GAEG;AACH,wBAAgB,eAAe,IAAI,YAAY,CAS9C;AAID;;;GAGG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,UAAU,EACrB,SAAS,EAAE,UAAU,GACpB,aAAa,CAYf;AAID;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAUlE;AAcD,wBAAgB,WAAW,CACzB,EAAE,EAAE,YAAY,EAChB,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM,GAClB,IAAI,CAgBN;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,YAAY,CAc/E;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,YAAY,CAKvF"}
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * Rubric Protocol — Local ML-DSA-65 Signing
4
+ * Uses @noble/post-quantum (NIST FIPS 204)
5
+ * Handles key generation, signing, verification, and filesystem persistence.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.generateKeyPair = generateKeyPair;
42
+ exports.signPayload = signPayload;
43
+ exports.verifySignedPayload = verifySignedPayload;
44
+ exports.saveKeyPair = saveKeyPair;
45
+ exports.loadKeyPair = loadKeyPair;
46
+ exports.loadOrCreateKeyPair = loadOrCreateKeyPair;
47
+ const ml_dsa_js_1 = require("@noble/post-quantum/ml-dsa.js");
48
+ const fs = __importStar(require("fs"));
49
+ const path = __importStar(require("path"));
50
+ const crypto = __importStar(require("crypto"));
51
+ // ─── Key Generation ──────────────────────────────────────────────────────────
52
+ /**
53
+ * Generate a fresh ML-DRA-65 keypair from a 32-byte random seed.
54
+ */
55
+ function generateKeyPair() {
56
+ const seed = crypto.randomBytes(32);
57
+ const kp = ml_dsa_js_1.ml_dsa65.keygen(seed);
58
+ return {
59
+ publicKey: kp.publicKey,
60
+ secretKey: kp.secretKey,
61
+ publicKeyHex: Buffer.from(kp.publicKey).toString('hex'),
62
+ created: new Date().toISOString(),
63
+ };
64
+ }
65
+ // ─── Sign ─────────────────────────────────────────────────────────────────────
66
+ /**
67
+ * Sign an arbitrary payload object with a local secret key.
68
+ * Canonical JSON serialization ensures deterministic signing.
69
+ */
70
+ function signPayload(payload, secretKey, publicKey) {
71
+ const canonical = canonicalJson(payload);
72
+ const msgBytes = new TextEncoder().encode(canonical);
73
+ const sig = ml_dsa_js_1.ml_dsa65.sign(msgBytes, secretKey);
74
+ return {
75
+ payload,
76
+ signature: Buffer.from(sig).toString('hex'),
77
+ publicKey: Buffer.from(publicKey).toString('hex'),
78
+ signedAt: new Date().toISOString(),
79
+ algorithm: 'ML-DSA-65',
80
+ };
81
+ }
82
+ // ─── Verify ───────────────────────────────────────────────────────────────────
83
+ /**
84
+ * Verify a signed payload locally (for testing / offline verification).
85
+ */
86
+ function verifySignedPayload(signed) {
87
+ try {
88
+ const canonical = canonicalJson(signed.payload);
89
+ const msgBytes = new TextEncoder().encode(canonical);
90
+ const sigBytes = Uint8Array.from(Buffer.from(signed.signature, 'hex'));
91
+ const pubKeyBytes = Uint8Array.from(Buffer.from(signed.publicKey, 'hex'));
92
+ return ml_dsa_js_1.ml_dsa65.verify(sigBytes, msgBytes, pubKeyBytes);
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ }
98
+ function saveKeyPair(kp, filePath, passphrase) {
99
+ let store;
100
+ if (passphrase) {
101
+ const key = crypto.scryptSync(passphrase, 'rubric-sdk-salt', 32);
102
+ const iv = crypto.randomBytes(12);
103
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
104
+ const skHex = Buffer.from(kp.secretKey).toString('hex');
105
+ const encrypted = Buffer.concat([cipher.update(skHex, 'utf8'), cipher.final()]);
106
+ const authTag = cipher.getAuthTag();
107
+ store = { version: 1, algorithm: 'ML-DSA-65', publicKeyHex: kp.publicKeyHex, secretKeyHex: encrypted.toString('hex'), iv: iv.toString('hex'), authTag: authTag.toString('hex'), created: kp.created };
108
+ }
109
+ else {
110
+ store = { version: 1, algorithm: 'ML-DSA-65', publicKeyHex: kp.publicKeyHex, secretKeyHex: Buffer.from(kp.secretKey).toString('hex'), created: kp.created };
111
+ }
112
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
113
+ fs.writeFileSync(filePath, JSON.stringify(store, null, 2), { mode: 0o600 });
114
+ }
115
+ function loadKeyPair(filePath, passphrase) {
116
+ const raw = fs.readFileSync(filePath, 'utf8');
117
+ const store = JSON.parse(raw);
118
+ if (store.version !== 1 || store.algorithm !== 'ML-DSA-65')
119
+ throw new Error('Incompatible keystore format');
120
+ let skHex;
121
+ if (store.iv && store.authTag) {
122
+ if (!passphrase)
123
+ throw new Error('Keystore is encrypted passphrase required');
124
+ const key = crypto.scryptSync(passphrase, 'rubric-sdk-salt', 32);
125
+ const iv = Buffer.from(store.iv, 'hex');
126
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
127
+ decipher.setAuthTag(Buffer.from(store.authTag, 'hex'));
128
+ skHex = decipher.update(store.secretKeyHex, 'hex', 'utf8') + decipher.final('utf8');
129
+ }
130
+ else {
131
+ skHex = store.secretKeyHex;
132
+ }
133
+ return { publicKey: Uint8Array.from(Buffer.from(store.publicKeyHex, 'hex')), secretKey: Uint8Array.from(Buffer.from(skHex, 'hex')), publicKeyHex: store.publicKeyHex, created: store.created };
134
+ }
135
+ function loadOrCreateKeyPair(filePath, passphrase) {
136
+ if (fs.existsSync(filePath))
137
+ return loadKeyPair(filePath, passphrase);
138
+ const kp = generateKeyPair();
139
+ saveKeyPair(kp, filePath, passphrase);
140
+ return kp;
141
+ }
142
+ function canonicalJson(obj) {
143
+ if (obj === null || typeof obj !== 'object')
144
+ return JSON.stringify(obj);
145
+ if (Array.isArray(obj))
146
+ return '[' + obj.map(canonicalJson).join(',') + ']';
147
+ const keys = Object.keys(obj).sort();
148
+ const pairs = keys.map(k => JSON.stringify(k) + ':' + canonicalJson(obj[k]));
149
+ return '{' + pairs.join(',') + '}';
150
+ }
151
+ //# sourceMappingURL=ml-dsa-local.js.map
@@ -0,0 +1 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CAAC,QAAgB,EAAE,UAAmB;IACvE,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;QAAE,OAAO,WAAW,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IACtE,MAAM,EAAE,GAAG,eAAe,EAAE,CAAC;IAC7B,WAAW,CAAC,EAAE,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;IACtC,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,SAAS,aAAa,CAAC,GAAY;IACjC,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IACxE,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;IAC5E,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAA8B,CAAC,CAAC,IAAI,EAAE,CAAC;IAChE,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,aAAa,CAAE,GAA+B,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1G,OAAO,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACrC,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { RubricClientConfig } from '../rubric-client';
2
+ declare let BaseCallbackHandler: any;
3
+ type LLMResult = any;
4
+ type AgentAction = any;
5
+ type AgentFinish = any;
6
+ type ChainValues = any;
7
+ export interface RubricLangChainConfig extends RubricClientConfig {
8
+ events?: Array<'llm' | 'chain' | 'agent' | 'tool'>;
9
+ pipelineId?: string | ((runId: string) => string);
10
+ }
11
+ export declare class RubricLangChainHandler extends BaseCallbackHandler {
12
+ name: string;
13
+ private readonly client;
14
+ private readonly events;
15
+ private readonly pipelineId?;
16
+ constructor(config: RubricLangChainConfig);
17
+ handleLLMEnd(output: LLMResult, runId: string): Promise<void>;
18
+ handleLLMError(error: Error, runId: string): Promise<void>;
19
+ handleChainEnd(outputs: ChainValues, runId: string, parentRunId?: string): Promise<void>;
20
+ handleChainError(error: Error, runId: string): Promise<void>;
21
+ handleAgentAction(action: AgentAction, runId: string): Promise<void>;
22
+ handleAgentEnd(action: AgentFinish, runId: string): Promise<void>;
23
+ handleToolEnd(output: string, runId: string): Promise<void>;
24
+ handleToolError(error: Error, runId: string): Promise<void>;
25
+ private _attest;
26
+ private _pipeline;
27
+ shutdown(): Promise<void>;
28
+ }
29
+ export {};
30
+ //# sourceMappingURL=langchain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"langchain.d.ts","sourceRoot":"","sources":["../../plugins/langchain.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAGpE,QAAA,IAAI,mBAAmB,EAAE,GAAG,CAAC;AAU7B,KAAK,SAAS,GAAG,GAAG,CAAC;AACrB,KAAK,WAAW,GAAG,GAAG,CAAC;AACvB,KAAK,WAAW,GAAG,GAAG,CAAC;AACvB,KAAK,WAAW,GAAG,GAAG,CAAC;AAEvB,MAAM,WAAW,qBAAsB,SAAQ,kBAAkB;IAC/D,MAAM,CAAC,EAAE,KAAK,CAAC,KAAK,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC,CAAC;IACnD,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC;CACnD;AAED,qBAAa,sBAAuB,SAAQ,mBAAmB;IAC7D,IAAI,SAA4B;IAChC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAuC;gBAEvD,MAAM,EAAE,qBAAqB;IAOnC,YAAY,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ7D,cAAc,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK1D,cAAc,CAAC,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMxF,gBAAgB,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK5D,iBAAiB,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKpE,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKjE,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK3D,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YAKnD,OAAO;IAKrB,OAAO,CAAC,SAAS;IAKX,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAChC"}
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RubricLangChainHandler = void 0;
4
+ const rubric_client_1 = require("../rubric-client");
5
+ // Lazy-load LangChain types — optional peer dependency
6
+ let BaseCallbackHandler;
7
+ try {
8
+ BaseCallbackHandler = require('@langchain/core/callbacks/base').BaseCallbackHandler;
9
+ }
10
+ catch {
11
+ BaseCallbackHandler = class {
12
+ constructor() {
13
+ throw new Error('[RubricSDK] LangChain integration requires @langchain/core. Install with: npm install @langchain/core');
14
+ }
15
+ };
16
+ }
17
+ class RubricLangChainHandler extends BaseCallbackHandler {
18
+ constructor(config) {
19
+ super();
20
+ this.name = 'RubricLangChainHandler';
21
+ this.client = new rubric_client_1.RubricClient({ backgroundQueue: true, ...config });
22
+ this.events = new Set(config.events ?? ['llm', 'chain', 'agent', 'tool']);
23
+ this.pipelineId = config.pipelineId;
24
+ }
25
+ async handleLLMEnd(output, runId) {
26
+ if (!this.events.has('llm'))
27
+ return;
28
+ const gen = output.generations?.[0]?.[0];
29
+ const text = typeof gen?.text === 'string' ? gen.text : JSON.stringify(gen);
30
+ const tokenUsage = output.llmOutput?.tokenUsage;
31
+ await this._attest({ agentId: `langchain-llm:${runId.slice(0, 8)}`, output: text.slice(0, 2000), leafType: 'AGENT_OUTPUT', metadata: { runId, event: 'llm_end', promptTokens: tokenUsage?.promptTokens ?? 0, completionTokens: tokenUsage?.completionTokens ?? 0 }, pipelineId: this._pipeline(runId) });
32
+ }
33
+ async handleLLMError(error, runId) {
34
+ if (!this.events.has('llm'))
35
+ return;
36
+ await this._attest({ agentId: `langchain-llm:${runId.slice(0, 8)}`, output: `LLM_ERROR: ${error.message}`, leafType: 'AGENT_OUTPUT', metadata: { runId, event: 'llm_error', error: error.message } });
37
+ }
38
+ async handleChainEnd(outputs, runId, parentRunId) {
39
+ if (!this.events.has('chain'))
40
+ return;
41
+ const output = typeof outputs === 'string' ? outputs : JSON.stringify(outputs).slice(0, 2000);
42
+ await this._attest({ agentId: `langchain-chain:${runId.slice(0, 8)}`, output, leafType: 'AGENT_OUTPUT', metadata: { runId, parentRunId: parentRunId ?? '', event: 'chain_end' }, pipelineId: this._pipeline(parentRunId ?? runId) });
43
+ }
44
+ async handleChainError(error, runId) {
45
+ if (!this.events.has('chain'))
46
+ return;
47
+ await this._attest({ agentId: `langchain-chain:${runId.slice(0, 8)}`, output: `CHAIN_ERROR: ${error.message}`, leafType: 'AGENT_OUTPUT', metadata: { runId, event: 'chain_error', error: error.message } });
48
+ }
49
+ async handleAgentAction(action, runId) {
50
+ if (!this.events.has('agent'))
51
+ return;
52
+ await this._attest({ agentId: `langchain-agent:${runId.slice(0, 8)}`, output: `ACTION:${action.tool} LOG:${action.log?.slice(0, 500) ?? ''}`, leafType: 'RULE_APPLIED', metadata: { runId, event: 'agent_action', tool: action.tool, toolInput: JSON.stringify(action.toolInput).slice(0, 500) }, pipelineId: this._pipeline(runId) });
53
+ }
54
+ async handleAgentEnd(action, runId) {
55
+ if (!this.events.has('agent'))
56
+ return;
57
+ await this._attest({ agentId: `langchain-agent:${runId.slice(0, 8)}`, output: JSON.stringify(action.returnValues).slice(0, 2000), leafType: 'AGENT_OUTPUT', metadata: { runId, event: 'agent_finish' }, pipelineId: this._pipeline(runId) });
58
+ }
59
+ async handleToolEnd(output, runId) {
60
+ if (!this.events.has('tool'))
61
+ return;
62
+ await this._attest({ agentId: `langchain-tool:${runId.slice(0, 8)}`, output: output.slice(0, 2000), leafType: 'EXTERNAL_ORACLE', metadata: { runId, event: 'tool_end' } });
63
+ }
64
+ async handleToolError(error, runId) {
65
+ if (!this.events.has('tool'))
66
+ return;
67
+ await this._attest({ agentId: `langchain-tool:${runId.slice(0, 8)}`, output: `TOOL_ERROR: ${error.message}`, leafType: 'EXTERNAL_ORACLE', metadata: { runId, event: 'tool_error', error: error.message } });
68
+ }
69
+ async _attest(req) {
70
+ try {
71
+ await this.client.attest(req);
72
+ }
73
+ catch (err) {
74
+ console.warn('[RubricLangChain] Attestation error (non-fatal):', err);
75
+ }
76
+ }
77
+ _pipeline(runId) {
78
+ if (!this.pipelineId)
79
+ return undefined;
80
+ return typeof this.pipelineId === 'function' ? this.pipelineId(runId) : this.pipelineId;
81
+ }
82
+ async shutdown() { await this.client.shutdown(); }
83
+ }
84
+ exports.RubricLangChainHandler = RubricLangChainHandler;
85
+ //# sourceMappingURL=langchain.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"langchain.js","sourceRoot":"","sources":["../../plugins/langchain.ts"],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M,CAAC;YAAE,OAAO;QACrC,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,kBAAkB,KAAK,CAAC,KAAK,CAAC,CAAC,EAAC,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,eAAe,KAAK,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IAC7M,CAAC;IAEO,KAAK,CAAC,OAAO,CAAC,GAAQ;QAC5B,IAAI,CAAC;YAAC,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAAC,CAAC;QACtC,OAAO,GAAG,EAAE,CAAC;YAAC,OAAO,CAAC,IAAI,CAAC,kDAAkD,EAAE,GAAG,CAAC,CAAC;QAAC,CAAC;IACxF,CAAC;IAEO,SAAS,CAAC,KAAa;QAC7B,IAAI,CAAC,IAAI,CAAC,UAAU;YAAE,OAAO,SAAS,CAAC;QACvC,OAAO,OAAO,IAAI,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC;IAC1F,CAAC;IAED,KAAK,CAAC,QAAQ,KAAoB,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;CAClE;AApED,wDAoEC"}
@@ -0,0 +1,23 @@
1
+ import type OpenAI from 'openai';
2
+ import type { ChatCompletion, ChatCompletionCreateParamsNonStreaming } from 'openai/resources/chat/completions';
3
+ import { RubricClientConfig } from '../rubric-client';
4
+ export interface RubricOpenAIConfig extends RubricClientConfig {
5
+ agentId?: string;
6
+ attestStreaming?: boolean;
7
+ maxOutputLength?: number;
8
+ }
9
+ export declare function withRubric<T extends OpenAI>(openaiClient: T, config: RubricOpenAIConfig): T;
10
+ export declare class RubricOpenAIClient {
11
+ private readonly rubric;
12
+ private readonly openai;
13
+ private readonly agentId;
14
+ private readonly maxLen;
15
+ constructor(openaiClient: OpenAI, config: RubricOpenAIConfig);
16
+ readonly chat: {
17
+ completions: {
18
+ create: (params: ChatCompletionCreateParamsNonStreaming, options?: any) => Promise<ChatCompletion>;
19
+ };
20
+ };
21
+ shutdown(): Promise<void>;
22
+ }
23
+ //# sourceMappingURL=openai-plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-plugin.d.ts","sourceRoot":"","sources":["../../plugins/openai-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,KAAK,EAAE,cAAc,EAAuB,sCAAsC,EAAuC,MAAM,mCAAmC,CAAC;AAE1K,OAAO,EAAgB,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,WAAW,kBAAmB,SAAQ,kBAAkB;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,wBAAgB,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,MAAM,EAAE,kBAAkB,GAAG,CAAC,CA0B3F;AAED,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB;IAO5D,QAAQ,CAAC,IAAI;;6BAC2B,sCAAsC,YAAY,GAAG,KAAG,OAAO,CAAC,cAAc,CAAC;;MAOrH;IAEI,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAChC"}
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RubricOpenAIClient = void 0;
4
+ exports.withRubric = withRubric;
5
+ const rubric_client_1 = require("../rubric-client");
6
+ function withRubric(openaiClient, config) {
7
+ const rubric = new rubric_client_1.RubricClient({ backgroundQueue: true, ...config });
8
+ const agentId = config.agentId ?? 'openai-agent';
9
+ const maxLen = config.maxOutputLength ?? 3000;
10
+ const attestStreaming = config.attestStreaming ?? true;
11
+ const originalCreate = openaiClient.chat.completions.create.bind(openaiClient.chat.completions);
12
+ openaiClient.chat.completions.create = async function (params, options) {
13
+ const startedAt = Date.now();
14
+ if (params.stream) {
15
+ const stream = await originalCreate(params, options);
16
+ if (!attestStreaming)
17
+ return stream;
18
+ const collected = [];
19
+ const gen = async function* () {
20
+ for await (const chunk of stream) {
21
+ collected.push(chunk);
22
+ yield chunk;
23
+ }
24
+ const text = collected.flatMap(c => c.choices).map(c => c.delta?.content ?? '').join('');
25
+ safeAttest(rubric, { agentId, output: text.slice(0, maxLen), leafType: 'AGENT_OUTPUT', metadata: { model: params.model, streaming: true, durationMs: Date.now() - startedAt, promptMessages: params.messages?.length ?? 0 } }).catch(() => { });
26
+ };
27
+ return gen();
28
+ }
29
+ const completion = await originalCreate(params, options);
30
+ const text = completion.choices?.[0]?.message?.content ?? '';
31
+ await safeAttest(rubric, { agentId, output: text.slice(0, maxLen), leafType: 'AGENT_OUTPUT', metadata: { model: completion.model, streaming: false, durationMs: Date.now() - startedAt, promptTokens: completion.usage?.prompt_tokens ?? 0, completionTokens: completion.usage?.completion_tokens ?? 0, finishReason: completion.choices?.[0]?.finish_reason ?? '' }, confidence: finishToConf(completion.choices?.[0]?.finish_reason) });
32
+ return completion;
33
+ };
34
+ return openaiClient;
35
+ }
36
+ class RubricOpenAIClient {
37
+ constructor(openaiClient, config) {
38
+ this.chat = {
39
+ completions: { create: async (params, options) => {
40
+ const startedAt = Date.now();
41
+ const completion = await this.openai.chat.completions.create(params, options);
42
+ const text = completion.choices?.[0]?.message?.content ?? '';
43
+ await safeAttest(this.rubric, { agentId: this.agentId, output: text.slice(0, this.maxLen), leafType: 'AGENT_OUTPUT', metadata: { model: completion.model, durationMs: Date.now() - startedAt, promptTokens: completion.usage?.prompt_tokens ?? 0, completionTokens: completion.usage?.completion_tokens ?? 0 }, confidence: finishToConf(completion.choices?.[0]?.finish_reason) });
44
+ return completion;
45
+ } },
46
+ };
47
+ this.openai = openaiClient;
48
+ this.agentId = config.agentId ?? 'openai-agent';
49
+ this.maxLen = config.maxOutputLength ?? 3000;
50
+ this.rubric = new rubric_client_1.RubricClient({ backgroundQueue: true, ...config });
51
+ }
52
+ async shutdown() { await this.rubric.shutdown(); }
53
+ }
54
+ exports.RubricOpenAIClient = RubricOpenAIClient;
55
+ async function safeAttest(client, req) {
56
+ try {
57
+ await client.attest(req);
58
+ }
59
+ catch (err) {
60
+ console.warn('[RubricOpenAI] Attestation error (non-fatal):', err);
61
+ }
62
+ }
63
+ function finishToConf(reason) {
64
+ if (reason === 'stop')
65
+ return 0.95;
66
+ if (reason === 'length')
67
+ return 0.70;
68
+ if (reason === 'content_filter')
69
+ return 0.30;
70
+ return undefined;
71
+ }
72
+ //# sourceMappingURL=openai-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-plugin.js","sourceRoot":"","sources":["../../plugins/openai-plugin.ts"],"names":[],"mappings":";;;AAWA,gCA0BC;AAlCD,oDAAoE;AAQpE,SAAgB,UAAU,CAAmB,YAAe,EAAE,MAA0B;IACtF,MAAM,MAAM,GAAG,IAAI,4BAAY,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACtE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,cAAc,CAAC;IACjD,MAAM,MAAM,GAAG,MAAM,CAAC,eAAe,IAAI,IAAI,CAAC;IAC9C,MAAM,eAAe,GAAG,MAAM,CAAC,eAAe,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