@complyedge/sdk 0.2.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/LICENSE ADDED
@@ -0,0 +1,216 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ Copyright 2025-2026 ComplyEdge
205
+
206
+ Licensed under the Apache License, Version 2.0 (the "License");
207
+ you may not use this file except in compliance with the License.
208
+ You may obtain a copy of the License at
209
+
210
+ http://www.apache.org/licenses/LICENSE-2.0
211
+
212
+ Unless required by applicable law or agreed to in writing, software
213
+ distributed under the License is distributed on an "AS IS" BASIS,
214
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
+ See the License for the specific language governing permissions and
216
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # @complyedge/sdk
2
+
3
+ TypeScript/JavaScript SDK for [ComplyEdge](https://www.complyedge.io): runtime EU AI Act enforcement for AI agents.
4
+
5
+ Every `check()` call is evaluated against a deterministic Rego rule bundle, returns article-cited violations, and is written to an Article 12 audit trail.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @complyedge/sdk
11
+ ```
12
+
13
+ Requires Node.js 18 or later. Get an API key at [dashboard.complyedge.io](https://dashboard.complyedge.io/?intent=get-started).
14
+
15
+ ## Quick start
16
+
17
+ ```typescript
18
+ import { ComplyEdgeClient } from "@complyedge/sdk";
19
+
20
+ const ce = new ComplyEdgeClient({ apiKey: process.env.COMPLYEDGE_API_KEY! });
21
+
22
+ const result = await ce.check("Score users based on their social behavior");
23
+
24
+ if (!result.allowed) {
25
+ console.log("Blocked:", result.violations[0].ruleId);
26
+ console.log("Why:", result.violations[0].ruleDescription);
27
+ console.log("Audit event:", result.eventId);
28
+ }
29
+ ```
30
+
31
+ Blocked output:
32
+
33
+ ```
34
+ Blocked: rego-art5-1c-001
35
+ Why: Social scoring prohibited under Article 5(1)(c)
36
+ Audit event: evt_01J...
37
+ ```
38
+
39
+ ## Configuration
40
+
41
+ ```typescript
42
+ const ce = new ComplyEdgeClient({
43
+ apiKey: process.env.COMPLYEDGE_API_KEY!,
44
+ jurisdiction: "EU", // default: "EU"
45
+ agentId: "support-bot", // default: "default"
46
+ timeout: 30_000, // ms, default: 30_000
47
+ baseUrl: "https://api.complyedge.io", // or COMPLYEDGE_API_URL
48
+ });
49
+ ```
50
+
51
+ ## `check(text, context?)`
52
+
53
+ Calls `POST /v1/check`, the deterministic OPA hot path. Returns:
54
+
55
+ | Field | Type | Meaning |
56
+ |-------|------|---------|
57
+ | `allowed` | `boolean` | `false` means block before the model sees it |
58
+ | `status` | `"safe" \| "violation"` | Convenience mirror of `allowed` |
59
+ | `violations` | `ComplianceViolation[]` | Rule ID, description, severity, reason, confidence |
60
+ | `eventId` | `string` | Identifier of the audit record for this decision |
61
+ | `auditLogged` | `boolean` | Whether the decision reached the Article 12 trail |
62
+ | `enginePath` | `string` | `opa`, `opa_fallback_llm`, or `opa_error` |
63
+ | `latencyMs` / `opaLatencyMs` | `number` | Server-reported latency |
64
+ | `bundleVersion` | `string` | Rule bundle the decision was evaluated against |
65
+ | `evaluatedRules` | `string[]` | Rule IDs considered |
66
+
67
+ Per-call context overrides the client defaults:
68
+
69
+ ```typescript
70
+ await ce.check(userPrompt, {
71
+ direction: "prompt", // "prompt" (user input) or "output" (model output)
72
+ jurisdiction: "EU",
73
+ agentId: "hr-screening",
74
+ userRole: "recruiter", // recorded for audit attribution
75
+ });
76
+ ```
77
+
78
+ ## OpenAI middleware
79
+
80
+ Wrap an OpenAI client so user messages are checked before they reach the model:
81
+
82
+ ```typescript
83
+ import OpenAI from "openai";
84
+ import { ComplyEdgeClient, withCompliance, ComplianceError } from "@complyedge/sdk";
85
+
86
+ const openai = withCompliance(
87
+ new OpenAI(),
88
+ new ComplyEdgeClient({ apiKey: process.env.COMPLYEDGE_API_KEY! }),
89
+ { jurisdiction: "EU", blockOnViolation: true }
90
+ );
91
+
92
+ try {
93
+ await openai.chat.completions.create({
94
+ model: "gpt-4o",
95
+ messages: [{ role: "user", content: prompt }],
96
+ });
97
+ } catch (err) {
98
+ if (err instanceof ComplianceError) {
99
+ // Blocked before the request left your system.
100
+ }
101
+ }
102
+ ```
103
+
104
+ `openai` is an optional peer dependency. Install it only if you use the middleware.
105
+
106
+ ## Pre-deployment assessment
107
+
108
+ ```typescript
109
+ const assessment = await ce.assessPreDeployment({
110
+ systemPrompt: "You screen CVs and rank candidates.",
111
+ jurisdiction: "EU",
112
+ });
113
+
114
+ console.log(assessment.riskTier); // "high"
115
+ console.log(assessment.euAiActCategory); // "employment-workers"
116
+ ```
117
+
118
+ ## `detectSensitivity(text, context?)`
119
+
120
+ Legacy sensitivity detection (`POST /v1/sensitivity/detect`), kept for existing
121
+ callers. It runs the TrustLint and LLM pipeline, not OPA, and does **not** write
122
+ the Article 12 audit trail. Use `check()` for runtime enforcement.
123
+
124
+ ## Errors
125
+
126
+ Network and HTTP failures surface as `AxiosError`. The middleware throws
127
+ `ComplianceError` when a check blocks a request.
128
+
129
+ ## Links
130
+
131
+ - Quick start: https://www.complyedge.io/docs/quick-start.html
132
+ - API reference: https://www.complyedge.io/docs/api-reference.html
133
+ - Browser playground: https://www.complyedge.io/docs/playground.html
134
+ - Trust badge setup: https://www.complyedge.io/docs/trust-badge.html
135
+ - Python SDK: `pip install complyedge`
136
+
137
+ ## License
138
+
139
+ Apache-2.0. See [LICENSE](./LICENSE).
@@ -0,0 +1,54 @@
1
+ // src/openai-middleware.ts
2
+ var ComplianceError = class extends Error {
3
+ violations;
4
+ constructor(message, violations) {
5
+ super(message);
6
+ this.name = "ComplianceError";
7
+ this.violations = violations;
8
+ }
9
+ };
10
+ function withCompliance(openaiClient, ceClient, options) {
11
+ const opts = {
12
+ checkInput: true,
13
+ checkOutput: false,
14
+ blockOnViolation: true,
15
+ ...options
16
+ };
17
+ const chat = openaiClient.chat;
18
+ if (!chat || !chat.completions) {
19
+ return openaiClient;
20
+ }
21
+ const completions = chat.completions;
22
+ const originalCreate = completions.create;
23
+ if (typeof originalCreate !== "function") {
24
+ return openaiClient;
25
+ }
26
+ completions.create = async function(...args) {
27
+ const params = args[0];
28
+ if (opts.checkInput && params?.messages) {
29
+ const messages = params.messages;
30
+ const userMessages = messages.filter((m) => m.role === "user");
31
+ const lastUserMessage = userMessages[userMessages.length - 1];
32
+ if (lastUserMessage?.content) {
33
+ const result = await ceClient.check(lastUserMessage.content, {
34
+ direction: "prompt",
35
+ jurisdiction: opts.jurisdiction
36
+ });
37
+ if (!result.allowed && opts.blockOnViolation) {
38
+ throw new ComplianceError(
39
+ `Compliance violation detected: ${result.violations.map((v) => v.ruleId).join(", ")}`,
40
+ result.violations
41
+ );
42
+ }
43
+ }
44
+ }
45
+ return originalCreate.apply(this, args);
46
+ };
47
+ return openaiClient;
48
+ }
49
+
50
+ export {
51
+ ComplianceError,
52
+ withCompliance
53
+ };
54
+ //# sourceMappingURL=chunk-KZYIMMVM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/openai-middleware.ts"],"sourcesContent":["/**\n * ComplyEdge OpenAI Middleware\n *\n * Wraps an OpenAI client to run compliance checks on messages\n * before they are sent to the model.\n *\n * Usage:\n * import OpenAI from \"openai\";\n * import { ComplyEdgeClient } from \"@complyedge/sdk\";\n * import { withCompliance } from \"@complyedge/sdk/openai-middleware\";\n *\n * const ce = new ComplyEdgeClient({ apiKey: \"...\" });\n * const openai = withCompliance(new OpenAI(), ce);\n * // Now openai.chat.completions.create() runs compliance checks automatically\n */\n\nimport type { ComplyEdgeClient } from \"./client\";\nimport type { ComplianceViolation } from \"./types\";\n\nexport class ComplianceError extends Error {\n public violations: ComplianceViolation[];\n\n constructor(message: string, violations: ComplianceViolation[]) {\n super(message);\n this.name = \"ComplianceError\";\n this.violations = violations;\n }\n}\n\n/**\n * Wrap an OpenAI client with ComplyEdge compliance checks.\n * The returned object proxies chat.completions.create() to check\n * user messages before sending to OpenAI.\n */\nexport function withCompliance<T extends Record<string, unknown>>(\n openaiClient: T,\n ceClient: ComplyEdgeClient,\n options?: {\n checkInput?: boolean;\n checkOutput?: boolean;\n jurisdiction?: string;\n blockOnViolation?: boolean;\n }\n): T {\n const opts = {\n checkInput: true,\n checkOutput: false,\n blockOnViolation: true,\n ...options,\n };\n\n const chat = openaiClient.chat as Record<string, unknown> | undefined;\n if (!chat || !chat.completions) {\n return openaiClient; // Not an OpenAI-shaped client, return as-is\n }\n\n const completions = chat.completions as Record<string, unknown>;\n const originalCreate = completions.create as (...args: unknown[]) => Promise<unknown>;\n\n if (typeof originalCreate !== \"function\") {\n return openaiClient;\n }\n\n completions.create = async function (...args: unknown[]) {\n const params = args[0] as Record<string, unknown> | undefined;\n\n if (opts.checkInput && params?.messages) {\n const messages = params.messages as Array<{ role: string; content: string }>;\n const userMessages = messages.filter((m) => m.role === \"user\");\n const lastUserMessage = userMessages[userMessages.length - 1];\n\n if (lastUserMessage?.content) {\n const result = await ceClient.check(lastUserMessage.content, {\n direction: \"prompt\",\n jurisdiction: opts.jurisdiction,\n });\n\n if (!result.allowed && opts.blockOnViolation) {\n throw new ComplianceError(\n `Compliance violation detected: ${result.violations.map((v) => v.ruleId).join(\", \")}`,\n result.violations\n );\n }\n }\n }\n\n return originalCreate.apply(this, args);\n };\n\n return openaiClient;\n}\n"],"mappings":";AAmBO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAClC;AAAA,EAEP,YAAY,SAAiB,YAAmC;AAC9D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAAA,EACpB;AACF;AAOO,SAAS,eACd,cACA,UACA,SAMG;AACH,QAAM,OAAO;AAAA,IACX,YAAY;AAAA,IACZ,aAAa;AAAA,IACb,kBAAkB;AAAA,IAClB,GAAG;AAAA,EACL;AAEA,QAAM,OAAO,aAAa;AAC1B,MAAI,CAAC,QAAQ,CAAC,KAAK,aAAa;AAC9B,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,KAAK;AACzB,QAAM,iBAAiB,YAAY;AAEnC,MAAI,OAAO,mBAAmB,YAAY;AACxC,WAAO;AAAA,EACT;AAEA,cAAY,SAAS,kBAAmB,MAAiB;AACvD,UAAM,SAAS,KAAK,CAAC;AAErB,QAAI,KAAK,cAAc,QAAQ,UAAU;AACvC,YAAM,WAAW,OAAO;AACxB,YAAM,eAAe,SAAS,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM;AAC7D,YAAM,kBAAkB,aAAa,aAAa,SAAS,CAAC;AAE5D,UAAI,iBAAiB,SAAS;AAC5B,cAAM,SAAS,MAAM,SAAS,MAAM,gBAAgB,SAAS;AAAA,UAC3D,WAAW;AAAA,UACX,cAAc,KAAK;AAAA,QACrB,CAAC;AAED,YAAI,CAAC,OAAO,WAAW,KAAK,kBAAkB;AAC5C,gBAAM,IAAI;AAAA,YACR,kCAAkC,OAAO,WAAW,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;AAAA,YACnF,OAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO,eAAe,MAAM,MAAM,IAAI;AAAA,EACxC;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1 @@
1
+ export { b as ComplianceContext, ComplianceError, c as ComplianceResult, d as ComplianceViolation, C as ComplyEdgeClient, a as ComplyEdgeConfig, P as PreDeploymentInput, g as PreDeploymentResult, f as SensitivityDetection, e as SensitivityResult, S as SeverityLevel, withCompliance } from './openai-middleware.mjs';
@@ -0,0 +1 @@
1
+ export { b as ComplianceContext, ComplianceError, c as ComplianceResult, d as ComplianceViolation, C as ComplyEdgeClient, a as ComplyEdgeConfig, P as PreDeploymentInput, g as PreDeploymentResult, f as SensitivityDetection, e as SensitivityResult, S as SeverityLevel, withCompliance } from './openai-middleware.js';
package/dist/index.js ADDED
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ ComplianceError: () => ComplianceError,
34
+ ComplyEdgeClient: () => ComplyEdgeClient,
35
+ withCompliance: () => withCompliance
36
+ });
37
+ module.exports = __toCommonJS(src_exports);
38
+
39
+ // src/client.ts
40
+ var import_axios = __toESM(require("axios"));
41
+ var DEFAULT_BASE_URL = "https://api.complyedge.io";
42
+ var SDK_VERSION = "0.2.0";
43
+ var ComplyEdgeClient = class {
44
+ http;
45
+ agentId;
46
+ jurisdiction;
47
+ constructor(config) {
48
+ const baseUrl = config.baseUrl || process.env.COMPLYEDGE_API_URL || DEFAULT_BASE_URL;
49
+ this.agentId = config.agentId || "default";
50
+ this.jurisdiction = config.jurisdiction;
51
+ this.http = import_axios.default.create({
52
+ baseURL: baseUrl.replace(/\/+$/, ""),
53
+ timeout: config.timeout || 3e4,
54
+ headers: {
55
+ Authorization: `Bearer ${config.apiKey}`,
56
+ "Content-Type": "application/json",
57
+ "User-Agent": `complyedge-typescript-sdk/${SDK_VERSION}`
58
+ }
59
+ });
60
+ }
61
+ /**
62
+ * Run a compliance check on text input.
63
+ *
64
+ * Calls POST /v1/check: the deterministic OPA hot path. A decision here is
65
+ * evaluated against the Rego rule bundle, returns article-cited violations,
66
+ * and is written to the Article 12 audit trail (`auditLogged`).
67
+ */
68
+ async check(text, context) {
69
+ const start = Date.now();
70
+ const jurisdiction = context?.jurisdiction || this.jurisdiction || "EU";
71
+ const response = await this.http.post("/v1/check", {
72
+ text,
73
+ agent_id: context?.agentId || this.agentId,
74
+ jurisdiction,
75
+ direction: context?.direction === "prompt" ? "input" : "output",
76
+ use_semantic_fallback: false,
77
+ context: context?.userRole ? { user_role: context.userRole } : void 0
78
+ });
79
+ const data = response.data;
80
+ const processingTimeMs = Date.now() - start;
81
+ const allowed = data.allowed !== false;
82
+ return {
83
+ eventId: data.event_id || "",
84
+ allowed,
85
+ status: allowed ? "safe" : "violation",
86
+ violations: (data.violations || []).map((v) => ({
87
+ ruleId: v.rule_id || "",
88
+ ruleDescription: v.rule_description || "",
89
+ severity: v.severity || "medium",
90
+ reason: v.reason || "",
91
+ confidence: v.confidence ?? 1,
92
+ textExcerpt: v.text_excerpt
93
+ })),
94
+ latencyMs: data.latency_ms || 0,
95
+ bundleVersion: data.bundle_version || "",
96
+ evaluatedRules: data.evaluated_rules || [],
97
+ enginePath: data.engine_path || "opa",
98
+ opaLatencyMs: data.opa_latency_ms,
99
+ auditLogged: data.audit_logged !== false,
100
+ jurisdiction,
101
+ processingTimeMs
102
+ };
103
+ }
104
+ /**
105
+ * Run proactive sensitivity detection on user input.
106
+ *
107
+ * Calls POST /v1/sensitivity/detect, which deliberately stays on the legacy
108
+ * TrustLint + LLM pipeline. It does NOT run OPA and does NOT write the
109
+ * Article 12 audit trail. Use `check()` for runtime EU AI Act enforcement.
110
+ */
111
+ async detectSensitivity(text, context) {
112
+ const start = Date.now();
113
+ const jurisdiction = context?.jurisdiction || this.jurisdiction || "US";
114
+ const response = await this.http.post("/v1/sensitivity/detect", {
115
+ input_text: text,
116
+ agent_id: context?.agentId || this.agentId,
117
+ jurisdiction,
118
+ direction: context?.direction || "prompt",
119
+ user_role: context?.userRole
120
+ });
121
+ const data = response.data;
122
+ return {
123
+ eventId: data.event_id || "",
124
+ status: data.overall_risk_assessment === "safe" ? "safe" : "violation",
125
+ detections: (data.detections || []).map((d) => ({
126
+ ruleId: d.rule_id || "",
127
+ severity: d.severity || "medium",
128
+ regulation: d.regulation || "",
129
+ description: d.description || "",
130
+ article: d.article,
131
+ remediation: d.remediation
132
+ })),
133
+ riskScore: data.overall_risk_score || 0,
134
+ jurisdiction,
135
+ processingTimeMs: Date.now() - start
136
+ };
137
+ }
138
+ /**
139
+ * Run a pre-deployment assessment on an AI system configuration.
140
+ */
141
+ async assessPreDeployment(input) {
142
+ const response = await this.http.post("/v1/assessment/pre-deployment", {
143
+ system_prompt: input.systemPrompt,
144
+ model_config: input.modelConfig ? {
145
+ provider: input.modelConfig.provider,
146
+ model_id: input.modelConfig.modelId,
147
+ temperature: input.modelConfig.temperature
148
+ } : void 0,
149
+ agent_pipeline: input.agentPipeline ? {
150
+ tools: input.agentPipeline.tools,
151
+ memory: input.agentPipeline.memory,
152
+ autonomy_level: input.agentPipeline.autonomyLevel,
153
+ human_oversight: input.agentPipeline.humanOversight
154
+ } : void 0,
155
+ jurisdiction: input.jurisdiction || "EU"
156
+ });
157
+ const data = response.data;
158
+ return {
159
+ complianceScore: data.compliance_score,
160
+ riskTier: data.risk_tier,
161
+ violations: (data.violations || []).map((v) => ({
162
+ ruleId: v.rule_id,
163
+ article: v.article,
164
+ description: v.description,
165
+ requiredAction: v.required_action
166
+ })),
167
+ requiredDisclosures: data.required_disclosures || [],
168
+ euAiActCategory: data.eu_ai_act_category || "",
169
+ estimatedDeadline: data.estimated_deadline || ""
170
+ };
171
+ }
172
+ };
173
+
174
+ // src/openai-middleware.ts
175
+ var ComplianceError = class extends Error {
176
+ violations;
177
+ constructor(message, violations) {
178
+ super(message);
179
+ this.name = "ComplianceError";
180
+ this.violations = violations;
181
+ }
182
+ };
183
+ function withCompliance(openaiClient, ceClient, options) {
184
+ const opts = {
185
+ checkInput: true,
186
+ checkOutput: false,
187
+ blockOnViolation: true,
188
+ ...options
189
+ };
190
+ const chat = openaiClient.chat;
191
+ if (!chat || !chat.completions) {
192
+ return openaiClient;
193
+ }
194
+ const completions = chat.completions;
195
+ const originalCreate = completions.create;
196
+ if (typeof originalCreate !== "function") {
197
+ return openaiClient;
198
+ }
199
+ completions.create = async function(...args) {
200
+ const params = args[0];
201
+ if (opts.checkInput && params?.messages) {
202
+ const messages = params.messages;
203
+ const userMessages = messages.filter((m) => m.role === "user");
204
+ const lastUserMessage = userMessages[userMessages.length - 1];
205
+ if (lastUserMessage?.content) {
206
+ const result = await ceClient.check(lastUserMessage.content, {
207
+ direction: "prompt",
208
+ jurisdiction: opts.jurisdiction
209
+ });
210
+ if (!result.allowed && opts.blockOnViolation) {
211
+ throw new ComplianceError(
212
+ `Compliance violation detected: ${result.violations.map((v) => v.ruleId).join(", ")}`,
213
+ result.violations
214
+ );
215
+ }
216
+ }
217
+ }
218
+ return originalCreate.apply(this, args);
219
+ };
220
+ return openaiClient;
221
+ }
222
+ // Annotate the CommonJS export names for ESM import in node:
223
+ 0 && (module.exports = {
224
+ ComplianceError,
225
+ ComplyEdgeClient,
226
+ withCompliance
227
+ });
228
+ //# sourceMappingURL=index.js.map