@framers/agentos-ext-content-policy-rewriter 0.1.0 → 0.1.1

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,98 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License.
30
+
31
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License.
34
+
35
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
36
+
37
+ 4. Redistribution.
38
+
39
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Submission of Contributions.
52
+
53
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
54
+
55
+ 6. Trademarks.
56
+
57
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
58
+
59
+ 7. Disclaimer of Warranty.
60
+
61
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
62
+
63
+ 8. Limitation of Liability.
64
+
65
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
66
+
67
+ 9. Accepting Warranty or Additional Liability.
68
+
69
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
70
+
71
+ END OF TERMS AND CONDITIONS
72
+
73
+ APPENDIX: How to apply the Apache License to your work.
74
+
75
+ To apply the Apache License to your work, attach the following
76
+ boilerplate notice, with the fields enclosed by brackets "[]"
77
+ replaced with your own identifying information. (Don't include
78
+ the brackets!) The text should be enclosed in the appropriate
79
+ comment syntax for the file format. We also recommend that a
80
+ file or class name and description of purpose be included on the
81
+ same "printed page" as the copyright notice for easier
82
+ identification within third-party archives.
83
+
84
+ Copyright (c) 2025 Framers
85
+
86
+ Licensed under the Apache License, Version 2.0 (the "License");
87
+ you may not use this file except in compliance with the License.
88
+ You may obtain a copy of the License at
89
+
90
+ http://www.apache.org/licenses/LICENSE-2.0
91
+
92
+ Unless required by applicable law or agreed to in writing, software
93
+ distributed under the License is distributed on an "AS IS" BASIS,
94
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
95
+ See the License for the specific language governing permissions and
96
+ limitations under the License.
97
+
98
+
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Main guardrail orchestrator for content policy rewriting.
3
4
  *
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Layer 1: Zero-cost keyword/regex pre-filter for streaming chunks.
3
4
  * Scans text against per-category keyword lists. No LLM calls.
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Layer 2a: LLM-based policy violation classifier.
3
4
  * Sends the full response text to an LLM with a structured classification prompt.
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Layer 2b: LLM-based content rewriter.
3
4
  * Takes text with identified violations and rewrites it to remove them.
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Built-in keyword lists per policy category.
3
4
  * @module content-policy-rewriter/categories
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Content Policy Rewriter — extension pack factory.
3
4
  *
package/dist/presets.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Preset configurations for common content policy scenarios.
3
4
  * @module content-policy-rewriter/presets
package/dist/types.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-nocheck
1
2
  /**
2
3
  * @fileoverview Types for the content policy rewriter guardrail.
3
4
  * @module content-policy-rewriter/types
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@framers/agentos-ext-content-policy-rewriter",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Opt-in content policy guardrail for AgentOS — detects violations and rewrites or blocks output via LLM judge",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -11,19 +11,32 @@
11
11
  "types": "./dist/index.d.ts"
12
12
  }
13
13
  },
14
- "scripts": {
15
- "build": "tsc",
16
- "clean": "rm -rf dist",
17
- "typecheck": "tsc --noEmit",
18
- "test": "vitest run"
19
- },
20
14
  "peerDependencies": {
21
- "@framers/agentos": ">=0.1.0"
15
+ "@framers/agentos": ">=0.10.40"
22
16
  },
23
17
  "devDependencies": {
24
- "@framers/agentos": "workspace:*",
18
+ "@framers/agentos": "^0.10.40",
25
19
  "typescript": "^5.7.0",
26
- "vitest": "^3.0.0"
20
+ "vitest": "^3.2.7"
21
+ },
22
+ "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/framerslab/agentos-extensions.git",
26
+ "directory": "registry/curated/safety/content-policy-rewriter"
27
27
  },
28
- "license": "MIT"
29
- }
28
+ "homepage": "https://github.com/framerslab/agentos-extensions/tree/master/registry/curated/safety/content-policy-rewriter#readme",
29
+ "bugs": {
30
+ "url": "https://github.com/framerslab/agentos-extensions/issues"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md"
35
+ ],
36
+ "scripts": {
37
+ "build": "tsc",
38
+ "clean": "rm -rf dist",
39
+ "typecheck": "tsc --noEmit",
40
+ "test": "vitest run --passWithNoTests"
41
+ }
42
+ }
@@ -1,126 +0,0 @@
1
- /**
2
- * @fileoverview Main guardrail orchestrator for content policy rewriting.
3
- *
4
- * Implements IGuardrailService with a two-layer hybrid pipeline:
5
- * - Layer 1: KeywordPreFilter on streaming TEXT_DELTA chunks (zero-cost)
6
- * - Layer 2: LLM Policy Judge + LLM Rewriter on FINAL_RESPONSE
7
- *
8
- * Phase 1 sanitizer — sequential execution, can return SANITIZE with modifiedText.
9
- *
10
- * @module content-policy-rewriter/ContentPolicyRewriterGuardrail
11
- */
12
-
13
- import type { ContentPolicyRewriterConfig, PolicyCategory, CategoryConfig, LlmInvoker } from './types.js';
14
- import { resolveCategoryConfig } from './categories.js';
15
- import { ALL_POLICY_CATEGORIES } from './types.js';
16
- import { KeywordPreFilter } from './KeywordPreFilter.js';
17
- import { LlmPolicyJudge } from './LlmPolicyJudge.js';
18
- import { LlmRewriter } from './LlmRewriter.js';
19
-
20
- /** GuardrailAction values (avoid import issues by inlining). */
21
- const BLOCK = 'block';
22
- const SANITIZE = 'sanitize';
23
-
24
- export interface ContentPolicyRewriterOptions extends ContentPolicyRewriterConfig {
25
- llmInvoker: LlmInvoker;
26
- }
27
-
28
- export class ContentPolicyRewriterGuardrail {
29
- readonly config = {
30
- canSanitize: true,
31
- evaluateStreamingChunks: true,
32
- streamingMode: 'per-chunk' as const,
33
- };
34
-
35
- private enabledCategories: Partial<Record<PolicyCategory, CategoryConfig>>;
36
- private keywordFilter: KeywordPreFilter;
37
- private judge: LlmPolicyJudge;
38
- private rewriter: LlmRewriter;
39
- private customRules?: string;
40
-
41
- constructor(options: ContentPolicyRewriterOptions) {
42
- this.customRules = options.customRules;
43
-
44
- // Resolve enabled categories
45
- this.enabledCategories = {};
46
- for (const cat of ALL_POLICY_CATEGORIES) {
47
- const resolved = resolveCategoryConfig(cat, options.categories);
48
- if (resolved.enabled) {
49
- this.enabledCategories[cat] = { enabled: true, action: resolved.action };
50
- }
51
- }
52
-
53
- this.keywordFilter = new KeywordPreFilter(options.keywordLists);
54
- this.judge = new LlmPolicyJudge(options.llmInvoker);
55
- this.rewriter = new LlmRewriter(options.llmInvoker);
56
-
57
- if (options.streamingPreFilter === false) {
58
- this.config.evaluateStreamingChunks = false;
59
- }
60
- }
61
-
62
- async evaluateInput(_payload: any): Promise<any> {
63
- return null; // Content policy rewriter only evaluates output
64
- }
65
-
66
- async evaluateOutput(payload: any): Promise<any> {
67
- const chunk = payload?.chunk;
68
- if (!chunk) return null;
69
-
70
- const hasEnabledCategories = Object.keys(this.enabledCategories).length > 0;
71
- if (!hasEnabledCategories) return null;
72
-
73
- // Layer 1: Keyword pre-filter on streaming chunks
74
- if (chunk.type === 'TEXT_DELTA' && chunk.text) {
75
- const match = this.keywordFilter.scan(chunk.text, this.enabledCategories);
76
- if (match) {
77
- const action = this.enabledCategories[match.category]?.action ?? BLOCK;
78
- return {
79
- action,
80
- reasonCode: `KEYWORD_${match.category.toUpperCase()}`,
81
- ...(action === SANITIZE ? { modifiedText: '[Content removed by policy]' } : {}),
82
- };
83
- }
84
- return null;
85
- }
86
-
87
- // Layer 2: LLM judge + rewriter on final response
88
- if (chunk.type === 'FINAL_RESPONSE' && chunk.finalResponseText) {
89
- const text = chunk.finalResponseText;
90
-
91
- // Quick keyword check — BLOCK immediately if keyword match + action=block
92
- const kwMatch = this.keywordFilter.scan(text, this.enabledCategories);
93
- if (kwMatch && this.enabledCategories[kwMatch.category]?.action === BLOCK) {
94
- return {
95
- action: BLOCK,
96
- reasonCode: `KEYWORD_${kwMatch.category.toUpperCase()}`,
97
- };
98
- }
99
-
100
- // LLM classification
101
- const judgeResult = await this.judge.classify(text, this.enabledCategories, this.customRules);
102
- if (judgeResult.violations.length === 0) return null;
103
-
104
- // Check if all violations map to BLOCK
105
- const allBlock = judgeResult.violations.every(
106
- v => this.enabledCategories[v.category]?.action === BLOCK,
107
- );
108
- if (allBlock) {
109
- return {
110
- action: BLOCK,
111
- reasonCode: judgeResult.violations.map(v => v.category).join(','),
112
- };
113
- }
114
-
115
- // At least one SANITIZE — rewrite
116
- const rewritten = await this.rewriter.rewrite(text, judgeResult.violations, this.customRules);
117
- return {
118
- action: SANITIZE,
119
- modifiedText: rewritten,
120
- reasonCode: judgeResult.violations.map(v => v.category).join(','),
121
- };
122
- }
123
-
124
- return null;
125
- }
126
- }
@@ -1,49 +0,0 @@
1
- /**
2
- * @fileoverview Layer 1: Zero-cost keyword/regex pre-filter for streaming chunks.
3
- * Scans text against per-category keyword lists. No LLM calls.
4
- * @module content-policy-rewriter/KeywordPreFilter
5
- */
6
-
7
- import type { PolicyCategory, CategoryConfig } from './types.js';
8
- import { DEFAULT_KEYWORD_LISTS } from './categories.js';
9
-
10
- export interface KeywordMatch {
11
- category: PolicyCategory;
12
- keyword: string;
13
- }
14
-
15
- export class KeywordPreFilter {
16
- private patterns: Map<PolicyCategory, RegExp[]>;
17
-
18
- constructor(customLists?: Partial<Record<PolicyCategory, string[]>>) {
19
- this.patterns = new Map();
20
- const merged = { ...DEFAULT_KEYWORD_LISTS, ...customLists };
21
- for (const [cat, keywords] of Object.entries(merged)) {
22
- if (keywords?.length) {
23
- this.patterns.set(
24
- cat as PolicyCategory,
25
- keywords.map(kw => new RegExp(`\\b${kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i')),
26
- );
27
- }
28
- }
29
- }
30
-
31
- /**
32
- * Scan text against enabled category keyword lists.
33
- * @returns First match found, or null if clean.
34
- */
35
- scan(
36
- text: string,
37
- enabledCategories: Partial<Record<PolicyCategory, CategoryConfig>>,
38
- ): KeywordMatch | null {
39
- for (const [cat, patterns] of this.patterns) {
40
- const cfg = enabledCategories[cat];
41
- if (!cfg?.enabled) continue;
42
- for (const re of patterns) {
43
- const match = text.match(re);
44
- if (match) return { category: cat, keyword: match[0] };
45
- }
46
- }
47
- return null;
48
- }
49
- }
@@ -1,41 +0,0 @@
1
- /**
2
- * @fileoverview Layer 2a: LLM-based policy violation classifier.
3
- * Sends the full response text to an LLM with a structured classification prompt.
4
- * @module content-policy-rewriter/LlmPolicyJudge
5
- */
6
-
7
- import type { LlmInvoker, PolicyCategory, CategoryConfig, JudgeResult } from './types.js';
8
- import { CATEGORY_DESCRIPTIONS } from './categories.js';
9
-
10
- const SYSTEM_PROMPT = `You are a content policy classifier. Analyze the provided text and identify any violations of the enabled policy categories. Respond with JSON only. If no violations, respond: { "violations": [] }`;
11
-
12
- export class LlmPolicyJudge {
13
- constructor(private llmInvoker: LlmInvoker) {}
14
-
15
- async classify(
16
- text: string,
17
- enabledCategories: Partial<Record<PolicyCategory, CategoryConfig>>,
18
- customRules?: string,
19
- ): Promise<JudgeResult> {
20
- const categoryList = Object.entries(enabledCategories)
21
- .filter(([, cfg]) => cfg?.enabled)
22
- .map(([cat]) => `- ${cat}: ${CATEGORY_DESCRIPTIONS[cat as PolicyCategory]}`)
23
- .join('\n');
24
-
25
- if (!categoryList) return { violations: [] };
26
-
27
- let userPrompt = `Enabled categories:\n${categoryList}\n`;
28
- if (customRules) userPrompt += `\nCustom rules: ${customRules}\n`;
29
- userPrompt += `\nText to analyze:\n"""\n${text}\n"""\n\nRespond with JSON: { "violations": [{ "category": "...", "severity": "low|medium|high", "spans": ["offending phrase"] }] }`;
30
-
31
- try {
32
- const raw = await this.llmInvoker(SYSTEM_PROMPT, userPrompt);
33
- const cleaned = raw.replace(/```json\n?|```\n?/g, '').trim();
34
- const parsed = JSON.parse(cleaned) as JudgeResult;
35
- if (!Array.isArray(parsed.violations)) return { violations: [] };
36
- return parsed;
37
- } catch {
38
- return { violations: [] };
39
- }
40
- }
41
- }
@@ -1,32 +0,0 @@
1
- /**
2
- * @fileoverview Layer 2b: LLM-based content rewriter.
3
- * Takes text with identified violations and rewrites it to remove them.
4
- * @module content-policy-rewriter/LlmRewriter
5
- */
6
-
7
- import type { LlmInvoker, PolicyViolation } from './types.js';
8
-
9
- const SYSTEM_PROMPT = `Rewrite the following text to remove policy violations while preserving the original meaning, tone, and information content. Do not add disclaimers or commentary — just output the clean version.`;
10
-
11
- export class LlmRewriter {
12
- constructor(private llmInvoker: LlmInvoker) {}
13
-
14
- async rewrite(text: string, violations: PolicyViolation[], customRules?: string): Promise<string> {
15
- if (violations.length === 0) return text;
16
-
17
- const violationList = violations
18
- .map(v => `- ${v.category}: ${v.spans.map(s => `"${s}"`).join(', ')}`)
19
- .join('\n');
20
-
21
- let userPrompt = `Violations to remove:\n${violationList}\n`;
22
- if (customRules) userPrompt += `\nAdditional rules: ${customRules}\n`;
23
- userPrompt += `\nOriginal text:\n"""\n${text}\n"""\n\nRewritten text:`;
24
-
25
- try {
26
- const raw = await this.llmInvoker(SYSTEM_PROMPT, userPrompt);
27
- return raw.replace(/^```\w*\s*\n?/gm, '').replace(/\n?```\s*$/gm, '').trim() || text;
28
- } catch {
29
- return text;
30
- }
31
- }
32
- }
package/src/categories.ts DELETED
@@ -1,77 +0,0 @@
1
- /**
2
- * @fileoverview Built-in keyword lists per policy category.
3
- * @module content-policy-rewriter/categories
4
- */
5
-
6
- import type { PolicyCategory, CategoryConfig } from './types.js';
7
-
8
- /** Default category descriptions used in LLM judge prompts. */
9
- export const CATEGORY_DESCRIPTIONS: Record<PolicyCategory, string> = {
10
- illegal_harmful: 'Child sexual abuse material (CSAM), sexual assault, bestiality, non-consensual acts, exploitation of minors, graphic torture',
11
- adult: 'Consensual sexually explicit content, pornographic descriptions',
12
- profanity: 'Slurs, vulgar language, obscenity, crude insults',
13
- violence: 'Graphic violence, gore, detailed injury descriptions',
14
- self_harm: 'Self-harm instructions, suicide methods, pro-anorexia content',
15
- hate_speech: 'Discriminatory language, bigotry, slurs targeting protected groups',
16
- illegal_activity: 'Drug synthesis instructions, weapons manufacturing, hacking tutorials',
17
- custom: 'User-defined policy rules',
18
- };
19
-
20
- /** Default actions per category. */
21
- export const DEFAULT_CATEGORY_ACTIONS: Record<PolicyCategory, 'block' | 'sanitize'> = {
22
- illegal_harmful: 'block',
23
- adult: 'sanitize',
24
- profanity: 'sanitize',
25
- violence: 'sanitize',
26
- self_harm: 'block',
27
- hate_speech: 'sanitize',
28
- illegal_activity: 'block',
29
- custom: 'sanitize',
30
- };
31
-
32
- /** Default enabled state — only illegal_harmful is on by default. */
33
- export const DEFAULT_CATEGORY_ENABLED: Record<PolicyCategory, boolean> = {
34
- illegal_harmful: true,
35
- adult: false,
36
- profanity: false,
37
- violence: false,
38
- self_harm: false,
39
- hate_speech: false,
40
- illegal_activity: false,
41
- custom: false,
42
- };
43
-
44
- /**
45
- * Built-in keyword lists for the streaming pre-filter.
46
- * Intentionally broad — false positives acceptable because the LLM judge
47
- * runs on the final response for accuracy.
48
- */
49
- export const DEFAULT_KEYWORD_LISTS: Partial<Record<PolicyCategory, string[]>> = {
50
- profanity: [
51
- 'fuck', 'shit', 'bitch', 'asshole', 'cunt', 'dick', 'bastard',
52
- 'damn', 'nigger', 'faggot', 'retard', 'slut', 'whore',
53
- ],
54
- illegal_harmful: [
55
- 'child porn', 'cp links', 'lolicon', 'underage sex', 'rape fantasy',
56
- 'snuff film', 'crush video',
57
- ],
58
- self_harm: [
59
- 'how to kill yourself', 'suicide method', 'cut yourself', 'end it all',
60
- ],
61
- hate_speech: [
62
- 'kill all', 'gas the', 'ethnic cleansing', 'race war', 'white power',
63
- 'heil hitler', 'death to',
64
- ],
65
- };
66
-
67
- /** Resolve effective config for a category. */
68
- export function resolveCategoryConfig(
69
- category: PolicyCategory,
70
- userConfig?: Partial<Record<PolicyCategory, CategoryConfig>>,
71
- ): { enabled: boolean; action: 'block' | 'sanitize' } {
72
- const cfg = userConfig?.[category];
73
- return {
74
- enabled: cfg?.enabled ?? DEFAULT_CATEGORY_ENABLED[category],
75
- action: cfg?.action ?? DEFAULT_CATEGORY_ACTIONS[category],
76
- };
77
- }
package/src/index.ts DELETED
@@ -1,92 +0,0 @@
1
- /**
2
- * @fileoverview Content Policy Rewriter — extension pack factory.
3
- *
4
- * Opt-in guardrail that detects content policy violations in agent output
5
- * and either blocks or rewrites them via LLM. Agents are uncensored by
6
- * default — this extension only activates when explicitly configured.
7
- *
8
- * @module content-policy-rewriter
9
- */
10
-
11
- import type { ContentPolicyRewriterConfig, LlmInvoker } from './types.js';
12
- import { ContentPolicyRewriterGuardrail } from './ContentPolicyRewriterGuardrail.js';
13
- import { resolvePreset } from './presets.js';
14
-
15
- export * from './types.js';
16
- export { ContentPolicyRewriterGuardrail } from './ContentPolicyRewriterGuardrail.js';
17
- export { KeywordPreFilter } from './KeywordPreFilter.js';
18
- export { LlmPolicyJudge } from './LlmPolicyJudge.js';
19
- export { LlmRewriter } from './LlmRewriter.js';
20
- export { resolvePreset } from './presets.js';
21
-
22
- /**
23
- * Create the content policy rewriter extension pack.
24
- *
25
- * @param config - Policy configuration or preset name.
26
- * @param llmInvoker - Callback to invoke an LLM for classification and rewriting.
27
- * @returns A configured ExtensionPack.
28
- */
29
- export function createContentPolicyRewriter(
30
- config: ContentPolicyRewriterConfig | string = {},
31
- llmInvoker?: LlmInvoker,
32
- ) {
33
- const resolved = typeof config === 'string' ? resolvePreset(config as any) : config;
34
-
35
- const invoker: LlmInvoker = llmInvoker ?? resolved.llmInvoker ?? createDefaultInvoker(resolved);
36
- const guardrail = new ContentPolicyRewriterGuardrail({ ...resolved, llmInvoker: invoker });
37
-
38
- return {
39
- name: 'content-policy-rewriter',
40
- version: '0.1.0',
41
- descriptors: [
42
- {
43
- id: 'content-policy-rewriter-guardrail',
44
- kind: 'guardrail' as const,
45
- priority: 3,
46
- payload: guardrail,
47
- },
48
- ],
49
- };
50
- }
51
-
52
- /** Manifest factory bridge for extension loader. */
53
- export function createExtensionPack(context: any) {
54
- return createContentPolicyRewriter(
55
- context.options as ContentPolicyRewriterConfig,
56
- context.llmInvoker,
57
- );
58
- }
59
-
60
- /** Default LLM invoker using fetch to OpenAI-compatible API. */
61
- function createDefaultInvoker(config: ContentPolicyRewriterConfig): LlmInvoker {
62
- return async (systemPrompt: string, userPrompt: string): Promise<string> => {
63
- const apiKey = process.env.OPENAI_API_KEY || process.env.OPENROUTER_API_KEY;
64
- if (!apiKey) throw new Error('No LLM API key for content policy judge');
65
-
66
- const isOpenRouter = !process.env.OPENAI_API_KEY && !!process.env.OPENROUTER_API_KEY;
67
- const baseUrl = isOpenRouter ? 'https://openrouter.ai/api/v1' : 'https://api.openai.com/v1';
68
- const model = config.llm?.model ?? (isOpenRouter ? 'anthropic/claude-haiku-4-5-20251001' : 'gpt-4o-mini');
69
-
70
- const res = await fetch(`${baseUrl}/chat/completions`, {
71
- method: 'POST',
72
- headers: {
73
- 'Content-Type': 'application/json',
74
- Authorization: `Bearer ${apiKey}`,
75
- ...(isOpenRouter && { 'HTTP-Referer': 'https://agentos.sh' }),
76
- },
77
- body: JSON.stringify({
78
- model,
79
- messages: [
80
- { role: 'system', content: systemPrompt },
81
- { role: 'user', content: userPrompt },
82
- ],
83
- max_tokens: 2048,
84
- temperature: 0.1,
85
- }),
86
- });
87
-
88
- if (!res.ok) throw new Error(`LLM API returned ${res.status}`);
89
- const data = (await res.json()) as any;
90
- return data.choices?.[0]?.message?.content ?? '';
91
- };
92
- }
package/src/presets.ts DELETED
@@ -1,53 +0,0 @@
1
- /**
2
- * @fileoverview Preset configurations for common content policy scenarios.
3
- * @module content-policy-rewriter/presets
4
- */
5
-
6
- import type { ContentPolicyRewriterConfig, ContentPolicyPreset, PolicyCategory, CategoryConfig } from './types.js';
7
-
8
- const ALL_ENABLED_SANITIZE: Partial<Record<PolicyCategory, CategoryConfig>> = {
9
- illegal_harmful: { enabled: true, action: 'block' },
10
- adult: { enabled: true, action: 'sanitize' },
11
- profanity: { enabled: true, action: 'sanitize' },
12
- violence: { enabled: true, action: 'sanitize' },
13
- self_harm: { enabled: true, action: 'block' },
14
- hate_speech: { enabled: true, action: 'sanitize' },
15
- illegal_activity: { enabled: true, action: 'block' },
16
- };
17
-
18
- const PRESET_CONFIGS: Record<ContentPolicyPreset, Partial<ContentPolicyRewriterConfig>> = {
19
- uncensored: {
20
- categories: {
21
- illegal_harmful: { enabled: false },
22
- adult: { enabled: false },
23
- profanity: { enabled: false },
24
- violence: { enabled: false },
25
- self_harm: { enabled: false },
26
- hate_speech: { enabled: false },
27
- illegal_activity: { enabled: false },
28
- },
29
- },
30
- 'uncensored-safe': {
31
- categories: {
32
- illegal_harmful: { enabled: true, action: 'block' },
33
- },
34
- },
35
- 'family-friendly': {
36
- categories: ALL_ENABLED_SANITIZE,
37
- },
38
- enterprise: {
39
- categories: ALL_ENABLED_SANITIZE,
40
- },
41
- };
42
-
43
- /** Resolve a preset string or config object into a full config. */
44
- export function resolvePreset(
45
- input: ContentPolicyPreset | ContentPolicyRewriterConfig,
46
- ): ContentPolicyRewriterConfig {
47
- if (typeof input === 'string') {
48
- const preset = PRESET_CONFIGS[input];
49
- if (!preset) return {};
50
- return { ...preset };
51
- }
52
- return input;
53
- }
package/src/types.ts DELETED
@@ -1,60 +0,0 @@
1
- /**
2
- * @fileoverview Types for the content policy rewriter guardrail.
3
- * @module content-policy-rewriter/types
4
- */
5
-
6
- /** Policy categories that can be individually enabled/disabled. */
7
- export type PolicyCategory =
8
- | 'illegal_harmful'
9
- | 'adult'
10
- | 'profanity'
11
- | 'violence'
12
- | 'self_harm'
13
- | 'hate_speech'
14
- | 'illegal_activity'
15
- | 'custom';
16
-
17
- export const ALL_POLICY_CATEGORIES: PolicyCategory[] = [
18
- 'illegal_harmful', 'adult', 'profanity', 'violence',
19
- 'self_harm', 'hate_speech', 'illegal_activity', 'custom',
20
- ];
21
-
22
- /** Per-category configuration. */
23
- export interface CategoryConfig {
24
- enabled?: boolean;
25
- action?: 'block' | 'sanitize';
26
- }
27
-
28
- /** A detected policy violation. */
29
- export interface PolicyViolation {
30
- category: PolicyCategory;
31
- severity: 'low' | 'medium' | 'high';
32
- spans: string[];
33
- }
34
-
35
- /** Result from the LLM policy judge. */
36
- export interface JudgeResult {
37
- violations: PolicyViolation[];
38
- }
39
-
40
- /** LLM invoker callback — matches the pattern used by ml-classifiers. */
41
- export type LlmInvoker = (systemPrompt: string, userPrompt: string) => Promise<string>;
42
-
43
- /** Full configuration for the content policy rewriter. */
44
- export interface ContentPolicyRewriterConfig {
45
- categories?: Partial<Record<PolicyCategory, CategoryConfig>>;
46
- customRules?: string;
47
- llm?: {
48
- provider?: string;
49
- model?: string;
50
- };
51
- /** Override built-in keyword lists per category. */
52
- keywordLists?: Partial<Record<PolicyCategory, string[]>>;
53
- /** Enable keyword pre-filter on streaming chunks. Default: true. */
54
- streamingPreFilter?: boolean;
55
- /** LLM invoker callback. If not provided, uses a default fetch-based invoker. */
56
- llmInvoker?: LlmInvoker;
57
- }
58
-
59
- /** Preset names for shorthand configuration. */
60
- export type ContentPolicyPreset = 'uncensored' | 'uncensored-safe' | 'family-friendly' | 'enterprise';
@@ -1,79 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import { ContentPolicyRewriterGuardrail } from '../src/ContentPolicyRewriterGuardrail.js';
3
-
4
- describe('ContentPolicyRewriterGuardrail', () => {
5
- it('has correct guardrail config', () => {
6
- const g = new ContentPolicyRewriterGuardrail({
7
- llmInvoker: vi.fn(),
8
- categories: { profanity: { enabled: true } },
9
- });
10
- expect(g.config.canSanitize).toBe(true);
11
- expect(g.config.evaluateStreamingChunks).toBe(true);
12
- });
13
-
14
- it('allows clean streaming chunk', async () => {
15
- const g = new ContentPolicyRewriterGuardrail({
16
- llmInvoker: vi.fn(),
17
- categories: { profanity: { enabled: true } },
18
- });
19
- const result = await g.evaluateOutput({
20
- chunk: { type: 'TEXT_DELTA', text: 'Hello world' },
21
- });
22
- expect(result).toBeNull();
23
- });
24
-
25
- it('blocks streaming chunk with keyword match', async () => {
26
- const g = new ContentPolicyRewriterGuardrail({
27
- llmInvoker: vi.fn(),
28
- categories: { profanity: { enabled: true, action: 'block' } },
29
- });
30
- const result = await g.evaluateOutput({
31
- chunk: { type: 'TEXT_DELTA', text: 'What the fuck' },
32
- });
33
- expect(result).not.toBeNull();
34
- expect(result!.action).toBe('block');
35
- });
36
-
37
- it('sanitizes final response via LLM', async () => {
38
- const mockLlm = vi.fn();
39
- mockLlm.mockResolvedValueOnce('{ "violations": [{ "category": "profanity", "severity": "medium", "spans": ["damn"] }] }');
40
- mockLlm.mockResolvedValueOnce('The person was very upset.');
41
-
42
- const g = new ContentPolicyRewriterGuardrail({
43
- llmInvoker: mockLlm,
44
- categories: { profanity: { enabled: true, action: 'sanitize' } },
45
- });
46
- const result = await g.evaluateOutput({
47
- chunk: { type: 'FINAL_RESPONSE', finalResponseText: 'The person was damn upset.' },
48
- });
49
- expect(result).not.toBeNull();
50
- expect(result!.action).toBe('sanitize');
51
- expect(result!.modifiedText).toBe('The person was very upset.');
52
- });
53
-
54
- it('allows clean final response (no LLM rewrite call)', async () => {
55
- const mockLlm = vi.fn();
56
- mockLlm.mockResolvedValueOnce('{ "violations": [] }');
57
-
58
- const g = new ContentPolicyRewriterGuardrail({
59
- llmInvoker: mockLlm,
60
- categories: { profanity: { enabled: true } },
61
- });
62
- const result = await g.evaluateOutput({
63
- chunk: { type: 'FINAL_RESPONSE', finalResponseText: 'Everything is fine.' },
64
- });
65
- expect(result).toBeNull();
66
- expect(mockLlm).toHaveBeenCalledTimes(1);
67
- });
68
-
69
- it('returns null when no categories enabled', async () => {
70
- const g = new ContentPolicyRewriterGuardrail({
71
- llmInvoker: vi.fn(),
72
- categories: {},
73
- });
74
- const result = await g.evaluateOutput({
75
- chunk: { type: 'FINAL_RESPONSE', finalResponseText: 'Anything goes.' },
76
- });
77
- expect(result).toBeNull();
78
- });
79
- });
@@ -1,46 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { KeywordPreFilter } from '../src/KeywordPreFilter.js';
3
-
4
- describe('KeywordPreFilter', () => {
5
- const filter = new KeywordPreFilter();
6
-
7
- it('returns null for clean text', () => {
8
- const result = filter.scan('Hello, how are you?', {
9
- profanity: { enabled: true, action: 'sanitize' },
10
- });
11
- expect(result).toBeNull();
12
- });
13
-
14
- it('detects profanity keyword', () => {
15
- const result = filter.scan('What the fuck is this?', {
16
- profanity: { enabled: true, action: 'block' },
17
- });
18
- expect(result).not.toBeNull();
19
- expect(result!.category).toBe('profanity');
20
- });
21
-
22
- it('skips disabled categories', () => {
23
- const result = filter.scan('What the fuck is this?', {
24
- profanity: { enabled: false, action: 'block' },
25
- });
26
- expect(result).toBeNull();
27
- });
28
-
29
- it('uses custom keyword list when provided', () => {
30
- const customFilter = new KeywordPreFilter({
31
- profanity: ['dingus', 'bozo'],
32
- });
33
- const result = customFilter.scan('You absolute bozo', {
34
- profanity: { enabled: true, action: 'sanitize' },
35
- });
36
- expect(result).not.toBeNull();
37
- expect(result!.category).toBe('profanity');
38
- });
39
-
40
- it('is case-insensitive', () => {
41
- const result = filter.scan('What the FUCK', {
42
- profanity: { enabled: true, action: 'block' },
43
- });
44
- expect(result).not.toBeNull();
45
- });
46
- });
@@ -1,51 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { LlmPolicyJudge } from '../src/LlmPolicyJudge.js';
3
- import type { LlmInvoker } from '../src/types.js';
4
-
5
- describe('LlmPolicyJudge', () => {
6
- let mockLlm: LlmInvoker;
7
-
8
- beforeEach(() => {
9
- mockLlm = vi.fn();
10
- });
11
-
12
- it('returns empty violations for clean content', async () => {
13
- (mockLlm as any).mockResolvedValueOnce('{ "violations": [] }');
14
- const judge = new LlmPolicyJudge(mockLlm);
15
- const result = await judge.classify('Hello world', {
16
- profanity: { enabled: true, action: 'sanitize' },
17
- });
18
- expect(result.violations).toEqual([]);
19
- });
20
-
21
- it('parses violation response correctly', async () => {
22
- (mockLlm as any).mockResolvedValueOnce(JSON.stringify({
23
- violations: [{ category: 'profanity', severity: 'medium', spans: ['bad word'] }],
24
- }));
25
- const judge = new LlmPolicyJudge(mockLlm);
26
- const result = await judge.classify('text with bad word', {
27
- profanity: { enabled: true, action: 'sanitize' },
28
- });
29
- expect(result.violations).toHaveLength(1);
30
- expect(result.violations[0].category).toBe('profanity');
31
- });
32
-
33
- it('handles malformed LLM response gracefully', async () => {
34
- (mockLlm as any).mockResolvedValueOnce('not json at all');
35
- const judge = new LlmPolicyJudge(mockLlm);
36
- const result = await judge.classify('some text', {
37
- profanity: { enabled: true, action: 'sanitize' },
38
- });
39
- expect(result.violations).toEqual([]);
40
- });
41
-
42
- it('includes custom rules in prompt', async () => {
43
- (mockLlm as any).mockResolvedValueOnce('{ "violations": [] }');
44
- const judge = new LlmPolicyJudge(mockLlm);
45
- await judge.classify('text', {
46
- custom: { enabled: true, action: 'sanitize' },
47
- }, 'Never mention competitor X');
48
- const call = (mockLlm as any).mock.calls[0];
49
- expect(call[1]).toContain('Never mention competitor X');
50
- });
51
- });
@@ -1,34 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import { LlmRewriter } from '../src/LlmRewriter.js';
3
- import type { LlmInvoker, PolicyViolation } from '../src/types.js';
4
-
5
- describe('LlmRewriter', () => {
6
- const mockLlm: LlmInvoker = vi.fn();
7
-
8
- it('returns rewritten text from LLM', async () => {
9
- (mockLlm as any).mockResolvedValueOnce('The person expressed frustration.');
10
- const rewriter = new LlmRewriter(mockLlm);
11
- const violations: PolicyViolation[] = [
12
- { category: 'profanity', severity: 'medium', spans: ['bad word'] },
13
- ];
14
- const result = await rewriter.rewrite('The person said bad word in anger.', violations);
15
- expect(result).toBe('The person expressed frustration.');
16
- });
17
-
18
- it('returns original text on LLM failure', async () => {
19
- (mockLlm as any).mockRejectedValueOnce(new Error('LLM unavailable'));
20
- const rewriter = new LlmRewriter(mockLlm);
21
- const violations = [{ category: 'profanity' as const, severity: 'low' as const, spans: ['x'] }];
22
- const result = await rewriter.rewrite('original text', violations);
23
- expect(result).toBe('original text');
24
- });
25
-
26
- it('strips markdown fences from LLM response', async () => {
27
- (mockLlm as any).mockResolvedValueOnce('```\nClean version of the text.\n```');
28
- const rewriter = new LlmRewriter(mockLlm);
29
- const result = await rewriter.rewrite('dirty text', [
30
- { category: 'profanity', severity: 'low', spans: ['dirty'] },
31
- ]);
32
- expect(result).toBe('Clean version of the text.');
33
- });
34
- });
@@ -1,30 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { resolvePreset } from '../src/presets.js';
3
-
4
- describe('presets', () => {
5
- it('uncensored disables all categories', () => {
6
- const cfg = resolvePreset('uncensored');
7
- for (const cat of Object.values(cfg.categories ?? {})) {
8
- expect(cat?.enabled).toBe(false);
9
- }
10
- });
11
-
12
- it('uncensored-safe enables only illegal_harmful', () => {
13
- const cfg = resolvePreset('uncensored-safe');
14
- expect(cfg.categories?.illegal_harmful?.enabled).toBe(true);
15
- expect(cfg.categories?.adult?.enabled).toBeUndefined();
16
- });
17
-
18
- it('family-friendly enables all categories', () => {
19
- const cfg = resolvePreset('family-friendly');
20
- expect(cfg.categories?.adult?.enabled).toBe(true);
21
- expect(cfg.categories?.profanity?.enabled).toBe(true);
22
- expect(cfg.categories?.violence?.enabled).toBe(true);
23
- });
24
-
25
- it('passes through config objects unchanged', () => {
26
- const input = { categories: { adult: { enabled: true } } };
27
- const cfg = resolvePreset(input);
28
- expect(cfg).toEqual(input);
29
- });
30
- });
package/tsconfig.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "ESNext",
5
- "moduleResolution": "bundler",
6
- "declaration": true,
7
- "outDir": "dist",
8
- "rootDir": "src",
9
- "strict": true,
10
- "esModuleInterop": true,
11
- "skipLibCheck": true
12
- },
13
- "include": ["src"]
14
- }
package/vitest.config.ts DELETED
@@ -1,8 +0,0 @@
1
- import { defineConfig } from 'vitest/config';
2
-
3
- export default defineConfig({
4
- test: {
5
- include: ['test/**/*.spec.ts'],
6
- testTimeout: 30_000,
7
- },
8
- });