@gnldev/processors 0.1.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,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Karaca Yılmaz (https://gnl.dev)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # @gnldev/processors
2
+
3
+ **Input/output processors** for `@gnldev/durable` agents: PII masking, moderation, tool filtering, safety.
4
+ Built-ins inherit durability — input processors run before `persistInput` (masking is journaled → doesn't
5
+ run again on resume).
6
+
7
+ > Install: `pnpm add @gnldev/processors` — or use it from a [repo clone](https://github.com/Karaca7/gnldev): `pnpm install && pnpm -r build`.
8
+
9
+ ```bash
10
+ npm i @gnldev/processors # peer: @gnldev/durable
11
+ ```
12
+
13
+ ```ts
14
+ import { runDurable } from '@gnldev/durable';
15
+ import { piiRedactor, moderationProcessor, toolFilter } from '@gnldev/processors';
16
+
17
+ await runDurable({
18
+ runId: 'r1', journal, model, prompt: '...',
19
+ processors: [
20
+ piiRedactor(), // mask email/phone/card
21
+ moderationProcessor({ blocklist: ['...'] }), // tripwire on blocked content
22
+ toolFilter({ allow: ['searchPolicy', 'lookupOrder'] }), // restrict the tool set the model sees
23
+ ],
24
+ });
25
+ ```
26
+
27
+ ## API
28
+ - `piiRedactor(opts?)` · `moderationProcessor(opts?)` · `toolFilter(opts?)`
29
+ - `tokenLimit(...)` · `promptInjectionDetector(...)` · `outputLimit(...)`
30
+ - `piiTextRedactor(opts?) → (text: string) => string` — the same masking as `piiRedactor`, as a plain
31
+ string function, for text that never passes through a processor at all. A `Processor` only sees
32
+ `processInput`/`processOutput`/`processToolResult`; a run's failure message is written by
33
+ `recordRunOutcome` in `@gnldev/durable` and no processor is consulted about it, yet it can carry user
34
+ data (providers echo the offending input back when refusing). Wire it wherever that message is
35
+ shipped onward — `@gnldev/otel`'s `redact` option is the case it was added for. Takes `types`/`mask`
36
+ and shares `piiRedactor`'s defaults, on purpose: two copies of the defaults is how the redacted path
37
+ and the un-redacted one drift apart.
38
+ - Lower-level: `redactString`, `redactMessages`, `PII_PATTERNS`, `PII_VALIDATORS`, `PiiPattern`, `luhn`, `ibanMod97`
39
+
40
+ ### Checksums: why any sixteen digits is not a card
41
+
42
+ Some identifiers carry their own check digit, so whether a match is real is arithmetic rather than a
43
+ guess. `creditCard` is validated with Luhn and `iban` with mod-97, and a match that fails its own
44
+ check is left alone:
45
+
46
+ | Text | Masked |
47
+ |---|---|
48
+ | `kart 4111 1111 1111 1111` | yes — Luhn holds |
49
+ | `siparis 1234567812345678` | **no** — same shape, not a card |
50
+ | `TR330006100519786457841326` | yes — mod-97 holds |
51
+ | one digit changed | **no** |
52
+
53
+ The trade is real: a card typed with a wrong digit fails Luhn and is then not masked. Pass
54
+ `validate: false` to mask on shape alone — blunter, corrupts more text, but cannot be talked out of
55
+ masking anything.
56
+
57
+ `phone` has no checksum to appeal to, so it is bounded by shape instead: 7–15 digits, and short
58
+ groups once a number is split. That replaced a pattern which counted *characters*, and so masked
59
+ `2024-01-15 10` out of a timestamp, the whole of `1.2.3 - 4.5.6`, and a run id — text corruption in
60
+ exactly the payload it most often runs over. It is checked against 24 written forms across a dozen
61
+ countries, and against non-PII text that has to survive — both directions, because a first attempt
62
+ verified against a set chosen *after* the rule was written passed while `+49 30 12345678`,
63
+ `+90 5321112233` and `0212 5551234` were going through unmasked.
64
+
65
+ A match that fails its checksum is **skipped, not consumed**. That matters: with a plain
66
+ `String.replace`, a candidate spanning `1234567890 555-123-4567` failed the digit count and took the
67
+ real number out of reach of every later pattern — a leak caused by the validator meant to prevent one.
68
+
69
+ ### Masking an identifier the built-ins cannot name
70
+
71
+ National ids are a per-country long tail, so they are not shipped here — `extraPatterns` is how you
72
+ add your own, with the same checksum power the built-ins have:
73
+
74
+ ```ts
75
+ import { piiRedactor } from '@gnldev/processors';
76
+
77
+ piiRedactor({
78
+ extraPatterns: [
79
+ { name: 'mrn', pattern: /\bMRN-\d{6}\b/g },
80
+ // `test` is where the identifier's own checksum goes, so a custom pattern is as precise as a built-in.
81
+ { name: 'tckn', pattern: /\b\d{11}\b/g, mask: '[TCKN]', test: (v) => v[10] === String(
82
+ ([...v.slice(0, 10)].reduce((n, d) => n + Number(d), 0)) % 10) },
83
+ ],
84
+ });
85
+ ```
86
+
87
+ They run **before** the built-ins, and that ordering is load-bearing: `phone` would otherwise reach an
88
+ 11-digit national id first and mask it under the wrong name — which would also make the audit report
89
+ say the wrong type. Custom names appear in `recordProcessorReport` alongside the built-in ones, and
90
+ the counts come off the same call that performs the redaction, so the report cannot describe a masking
91
+ that did not run. A pattern without the `g` flag gets it added, rather than quietly masking only the
92
+ first occurrence.
93
+
94
+ A name in `types` with no pattern behind it is **refused at construction** instead of masking nothing
95
+ in silence; `piiTextRedactor` takes the same options.
96
+ - Re-exported: the `Processor` type + `ProcessorTripwire` (importable from a single package)
97
+
98
+ ## How it works
99
+ The processor pipeline is passed to `runDurable`/`createGnl` config. Pure transforms (masking) are
100
+ deterministic; non-deterministic ones are journaled via `ctx.step` → same result on replay. When a
101
+ tripwire fires, the run stops safely.
102
+
103
+ ## Limitations — an honest warning
104
+
105
+ `moderationProcessor`, `promptInjectionDetector`, `piiRedactor`, and `untrustedToolContent` use **naive
106
+ substring/regex matching**. This means they:
107
+
108
+ - **Are easily bypassed** — by adding whitespace/punctuation, typos, unicode homoglyphs, paraphrasing,
109
+ encoding (base64, etc.), or another language.
110
+ - **Are NOT a real security/compliance boundary** — prompt-injection defense is still an unsolved problem
111
+ in LLM safety; PII regexes don't guarantee GDPR/HIPAA/PCI-DSS-level detection.
112
+ - **Are designed as a first line of defense / noise-reduction layer.** For a critical flow (payment, data
113
+ deletion, external authorization), don't use these as the ONLY protection mechanism — combine them with
114
+ additional layers like a model-based judge, human approval, or least-privilege design.
115
+
116
+ For details, see the JSDoc on the relevant functions (`src/moderation.ts`, `src/safety.ts`, `src/pii.ts`,
117
+ `src/redact.ts`).
118
+
119
+ ## License
120
+
121
+ Apache-2.0 — see [LICENSE](./LICENSE).
@@ -0,0 +1,15 @@
1
+ export { piiRedactor, piiTextRedactor } from './pii.js';
2
+ export type { PiiRedactorOptions } from './pii.js';
3
+ export { moderationProcessor } from './moderation.js';
4
+ export type { ModerationOptions } from './moderation.js';
5
+ export { toolFilter } from './tool-filter.js';
6
+ export type { ToolFilterOptions } from './tool-filter.js';
7
+ export { tokenLimit, promptInjectionDetector, outputLimit, untrustedToolContent } from './safety.js';
8
+ export { tokenLimiter } from './token-limiter.js';
9
+ export type { TokenLimiterOptions } from './token-limiter.js';
10
+ export { PII_PATTERNS, PII_VALIDATORS, redactString, redactMessages, luhn, ibanMod97 } from './redact.js';
11
+ export type { PiiType, PiiPattern } from './redact.js';
12
+ export { ProcessorTripwire } from '@gnldev/durable';
13
+ export type { Processor, ProcessorToolResult } from '@gnldev/durable';
14
+ export { toolSearch } from './tool-search.js';
15
+ export type { ToolSearchOptions } from './tool-search.js';
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ // @gnldev/processors — input/output processors for @gnldev/durable agents.
2
+ // Built-ins inherit durability: input processors run before persistInput
3
+ // (masking is journaled), non-deterministic processors journal via ctx.step.
4
+ export { piiRedactor, piiTextRedactor } from './pii.js';
5
+ export { moderationProcessor } from './moderation.js';
6
+ export { toolFilter } from './tool-filter.js';
7
+ export { tokenLimit, promptInjectionDetector, outputLimit, untrustedToolContent } from './safety.js';
8
+ export { tokenLimiter } from './token-limiter.js';
9
+ export { PII_PATTERNS, PII_VALIDATORS, redactString, redactMessages, luhn, ibanMod97 } from './redact.js';
10
+ // Re-export: lets consumers get the Processor type/Tripwire from a single package.
11
+ export { ProcessorTripwire } from '@gnldev/durable';
12
+ export { toolSearch } from './tool-search.js';
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,yEAAyE;AACzE,6EAA6E;AAC7E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAExD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,UAAU,EAAE,uBAAuB,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACrG,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,cAAc,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE1G,mFAAmF;AACnF,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["// @gnldev/processors — input/output processors for @gnldev/durable agents.\n// Built-ins inherit durability: input processors run before persistInput\n// (masking is journaled), non-deterministic processors journal via ctx.step.\nexport { piiRedactor, piiTextRedactor } from './pii.js';\nexport type { PiiRedactorOptions } from './pii.js';\nexport { moderationProcessor } from './moderation.js';\nexport type { ModerationOptions } from './moderation.js';\nexport { toolFilter } from './tool-filter.js';\nexport type { ToolFilterOptions } from './tool-filter.js';\nexport { tokenLimit, promptInjectionDetector, outputLimit, untrustedToolContent } from './safety.js';\nexport { tokenLimiter } from './token-limiter.js';\nexport type { TokenLimiterOptions } from './token-limiter.js';\nexport { PII_PATTERNS, PII_VALIDATORS, redactString, redactMessages, luhn, ibanMod97 } from './redact.js';\nexport type { PiiType, PiiPattern } from './redact.js';\n// Re-export: lets consumers get the Processor type/Tripwire from a single package.\nexport { ProcessorTripwire } from '@gnldev/durable';\nexport type { Processor, ProcessorToolResult } from '@gnldev/durable';\nexport { toolSearch } from './tool-search.js';\nexport type { ToolSearchOptions } from './tool-search.js';\n"]}
@@ -0,0 +1,30 @@
1
+ import type { Processor } from '@gnldev/durable';
2
+ export interface ModerationOptions {
3
+ /**
4
+ * Blocked terms (normalized to lowercase before matching) — pure substring matching, bypassable
5
+ * (see `moderationProcessor` JSDoc). Not a real security boundary.
6
+ */
7
+ blocklist: string[];
8
+ /** input/output/both (default: 'both'). */
9
+ on?: 'input' | 'output' | 'both';
10
+ }
11
+ /**
12
+ * Rule-based moderation processor — throws `ProcessorTripwire` when a blocked term is found (run stops).
13
+ * Deterministic (blocklist is fixed) → no journaling needed.
14
+ *
15
+ * HONEST WARNING (naive matching): Matching is a plain, case-insensitive **substring** search
16
+ * (`String.includes`). This is NOT a real security/moderation boundary — it's easily bypassed:
17
+ * inserting spaces/punctuation ("s e c r e t"), unicode homoglyphs, typos, synonyms, another
18
+ * language, etc. — none of these are caught. Treat it as a first-line-of-defense / noise-reduction
19
+ * layer only — do not use it as the SOLE protection mechanism in a critical flow; for real
20
+ * moderation, layer in a model-based judge (see below) or a dedicated moderation service.
21
+ *
22
+ * For a model-based variant: inside `processInput`/`processOutput`, JOURNAL the LLM-judge call with
23
+ * `ctx.step('moderation', () => judge(...))` → same decision on resume, no duplicate judge call. Example:
24
+ * processOutput: async (out, ctx) => {
25
+ * const verdict = await ctx.step('moderation', () => callJudgeModel(out.text));
26
+ * if (verdict.blocked) throw new ProcessorTripwire('blocked', 'moderation', verdict);
27
+ * return out;
28
+ * }
29
+ */
30
+ export declare function moderationProcessor(opts: ModerationOptions): Processor;
@@ -0,0 +1,72 @@
1
+ import { ProcessorTripwire, recordProcessorReport } from '@gnldev/durable';
2
+ function collectText(input) {
3
+ const parts = [];
4
+ if (typeof input.system === 'string')
5
+ parts.push(input.system);
6
+ if (typeof input.prompt === 'string')
7
+ parts.push(input.prompt);
8
+ for (const m of input.messages ?? []) {
9
+ if (typeof m?.content === 'string')
10
+ parts.push(m.content);
11
+ else if (Array.isArray(m?.content)) {
12
+ for (const p of m.content)
13
+ if (typeof p?.text === 'string')
14
+ parts.push(p.text);
15
+ }
16
+ }
17
+ return parts.join('\n').toLowerCase();
18
+ }
19
+ function firstHit(text, blocklist) {
20
+ const lower = text.toLowerCase();
21
+ for (const term of blocklist)
22
+ if (lower.includes(term.toLowerCase()))
23
+ return term;
24
+ return null;
25
+ }
26
+ /**
27
+ * Rule-based moderation processor — throws `ProcessorTripwire` when a blocked term is found (run stops).
28
+ * Deterministic (blocklist is fixed) → no journaling needed.
29
+ *
30
+ * HONEST WARNING (naive matching): Matching is a plain, case-insensitive **substring** search
31
+ * (`String.includes`). This is NOT a real security/moderation boundary — it's easily bypassed:
32
+ * inserting spaces/punctuation ("s e c r e t"), unicode homoglyphs, typos, synonyms, another
33
+ * language, etc. — none of these are caught. Treat it as a first-line-of-defense / noise-reduction
34
+ * layer only — do not use it as the SOLE protection mechanism in a critical flow; for real
35
+ * moderation, layer in a model-based judge (see below) or a dedicated moderation service.
36
+ *
37
+ * For a model-based variant: inside `processInput`/`processOutput`, JOURNAL the LLM-judge call with
38
+ * `ctx.step('moderation', () => judge(...))` → same decision on resume, no duplicate judge call. Example:
39
+ * processOutput: async (out, ctx) => {
40
+ * const verdict = await ctx.step('moderation', () => callJudgeModel(out.text));
41
+ * if (verdict.blocked) throw new ProcessorTripwire('blocked', 'moderation', verdict);
42
+ * return out;
43
+ * }
44
+ */
45
+ export function moderationProcessor(opts) {
46
+ const on = opts.on ?? 'both';
47
+ const proc = { name: 'moderation' };
48
+ if (on === 'input' || on === 'both') {
49
+ // Synchronous throw is PRESERVED (see safety.ts promptInjectionDetector, same rationale) — recordProcessorReport
50
+ // is called fire-and-forget (best-effort, swallows errors), doesn't break the tripwire's synchronous behavior.
51
+ proc.processInput = (input, ctx) => {
52
+ const hit = firstHit(collectText(input), opts.blocklist);
53
+ if (hit) {
54
+ void recordProcessorReport(ctx, 'moderation', 'input', { hit });
55
+ throw new ProcessorTripwire(`Input blocked by moderation: "${hit}"`, 'moderation', { hit });
56
+ }
57
+ return input;
58
+ };
59
+ }
60
+ if (on === 'output' || on === 'both') {
61
+ proc.processOutput = (output, ctx) => {
62
+ const hit = firstHit(output.text ?? '', opts.blocklist);
63
+ if (hit) {
64
+ void recordProcessorReport(ctx, 'moderation', 'output', { hit });
65
+ throw new ProcessorTripwire(`Output blocked by moderation: "${hit}"`, 'moderation', { hit });
66
+ }
67
+ return output;
68
+ };
69
+ }
70
+ return proc;
71
+ }
72
+ //# sourceMappingURL=moderation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"moderation.js","sourceRoot":"","sources":["../src/moderation.ts"],"names":[],"mappings":"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","sourcesContent":["import { ProcessorTripwire, recordProcessorReport } from '@gnldev/durable';\nimport type { Processor, ProcessorInput, ProcessorOutput, ProcessorCtx } from '@gnldev/durable';\n\nexport interface ModerationOptions {\n /**\n * Blocked terms (normalized to lowercase before matching) — pure substring matching, bypassable\n * (see `moderationProcessor` JSDoc). Not a real security boundary.\n */\n blocklist: string[];\n /** input/output/both (default: 'both'). */\n on?: 'input' | 'output' | 'both';\n}\n\nfunction collectText(input: ProcessorInput): string {\n const parts: string[] = [];\n if (typeof input.system === 'string') parts.push(input.system);\n if (typeof input.prompt === 'string') parts.push(input.prompt);\n for (const m of input.messages ?? []) {\n if (typeof m?.content === 'string') parts.push(m.content);\n else if (Array.isArray(m?.content)) {\n for (const p of m.content) if (typeof p?.text === 'string') parts.push(p.text);\n }\n }\n return parts.join('\\n').toLowerCase();\n}\n\nfunction firstHit(text: string, blocklist: string[]): string | null {\n const lower = text.toLowerCase();\n for (const term of blocklist) if (lower.includes(term.toLowerCase())) return term;\n return null;\n}\n\n/**\n * Rule-based moderation processor — throws `ProcessorTripwire` when a blocked term is found (run stops).\n * Deterministic (blocklist is fixed) → no journaling needed.\n *\n * HONEST WARNING (naive matching): Matching is a plain, case-insensitive **substring** search\n * (`String.includes`). This is NOT a real security/moderation boundary — it's easily bypassed:\n * inserting spaces/punctuation (\"s e c r e t\"), unicode homoglyphs, typos, synonyms, another\n * language, etc. — none of these are caught. Treat it as a first-line-of-defense / noise-reduction\n * layer only — do not use it as the SOLE protection mechanism in a critical flow; for real\n * moderation, layer in a model-based judge (see below) or a dedicated moderation service.\n *\n * For a model-based variant: inside `processInput`/`processOutput`, JOURNAL the LLM-judge call with\n * `ctx.step('moderation', () => judge(...))` → same decision on resume, no duplicate judge call. Example:\n * processOutput: async (out, ctx) => {\n * const verdict = await ctx.step('moderation', () => callJudgeModel(out.text));\n * if (verdict.blocked) throw new ProcessorTripwire('blocked', 'moderation', verdict);\n * return out;\n * }\n */\nexport function moderationProcessor(opts: ModerationOptions): Processor {\n const on = opts.on ?? 'both';\n const proc: Processor = { name: 'moderation' };\n\n if (on === 'input' || on === 'both') {\n // Synchronous throw is PRESERVED (see safety.ts promptInjectionDetector, same rationale) — recordProcessorReport\n // is called fire-and-forget (best-effort, swallows errors), doesn't break the tripwire's synchronous behavior.\n proc.processInput = (input: ProcessorInput, ctx: ProcessorCtx) => {\n const hit = firstHit(collectText(input), opts.blocklist);\n if (hit) {\n void recordProcessorReport(ctx, 'moderation', 'input', { hit });\n throw new ProcessorTripwire(`Input blocked by moderation: \"${hit}\"`, 'moderation', { hit });\n }\n return input;\n };\n }\n\n if (on === 'output' || on === 'both') {\n proc.processOutput = (output: ProcessorOutput, ctx: ProcessorCtx) => {\n const hit = firstHit(output.text ?? '', opts.blocklist);\n if (hit) {\n void recordProcessorReport(ctx, 'moderation', 'output', { hit });\n throw new ProcessorTripwire(`Output blocked by moderation: \"${hit}\"`, 'moderation', { hit });\n }\n return output;\n };\n }\n\n return proc;\n}\n"]}
package/dist/pii.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ import type { Processor } from '@gnldev/durable';
2
+ import { type PiiType, type PiiPattern } from './redact.js';
3
+ export interface PiiRedactorOptions {
4
+ /** Which PII types to mask (default: all). */
5
+ types?: PiiType[];
6
+ /** Mask generator (default: `[REDACTED_<TYPE>]`). */
7
+ mask?: (type: PiiType) => string;
8
+ /** input/output/both (default: 'both'). */
9
+ on?: 'input' | 'output' | 'both';
10
+ /**
11
+ * Also redact the tool execute result (processToolResult hook) — default: false.
12
+ * known limitation: tool output (external API/DB/file result) was being written to the journal as
13
+ * PLAIN TEXT; it may contain PII. Left as opt-in so existing piiRedactor users' behavior does NOT
14
+ * CHANGE — this option only masks tool output when explicitly set to `true`.
15
+ */
16
+ redactToolResults?: boolean;
17
+ /**
18
+ * Extra patterns, for the identifiers the five built-in types cannot name.
19
+ *
20
+ * The built-in list is US-shaped (`ssn` exists nowhere else), so a national id, an IBAN, a patient
21
+ * record number or an internal customer id has no type that matches it. Dropping a built-in from
22
+ * `types` removes coverage rather than adding any, and mutating the exported `PII_PATTERNS` changes
23
+ * behavior for every redactor in the process — neither is a way to add your own.
24
+ *
25
+ * These run BEFORE the built-ins, deliberately: the built-in `phone` pattern is greedy enough to
26
+ * swallow a national id (measured — `12345678901` comes back `[REDACTED_PHONE]`), so a pattern that
27
+ * ran afterwards would find its text already masked under the wrong name.
28
+ *
29
+ * piiRedactor({ extraPatterns: [{ name: 'iban', pattern: /TR\d{24}/g }] })
30
+ */
31
+ extraPatterns?: PiiPattern[];
32
+ /**
33
+ * Run each identifier's own checksum before masking — Luhn for `creditCard`, mod-97 for `iban`,
34
+ * and any `test` on a custom pattern. Default: true.
35
+ *
36
+ * It is what separates a card number from any sixteen digits: measured, the pattern alone masked
37
+ * `order 1234567812345678` as a card, which loses the order number without protecting anything.
38
+ * The trade is real and worth stating — a card typed with a wrong digit fails Luhn and is then left
39
+ * alone. Set to `false` to mask on shape only, which is the older, blunter behavior: it corrupts
40
+ * more text but cannot be talked out of masking anything.
41
+ */
42
+ validate?: boolean;
43
+ }
44
+ /**
45
+ * The same masking as `piiRedactor`, as a plain string function, for the text that never passes
46
+ * through a processor at all.
47
+ *
48
+ * A `Processor` only sees `processInput`/`processOutput`/`processToolResult`. A run's failure
49
+ * message is written from `recordRunOutcome` in @gnldev/durable, which no processor is consulted
50
+ * about, and it is not always the host's own text: a provider that refuses a request commonly
51
+ * echoes the offending input back inside the message. Anything that ships that message onward —
52
+ * `@gnldev/otel`'s span attributes are the case this was added for — needs the same mask, and had
53
+ * no way to reuse it because `DEFAULT_TYPES` is private to this module.
54
+ *
55
+ * Shares that constant and the default mask with `piiRedactor` deliberately: two copies of the
56
+ * defaults is exactly how the redacted path and the un-redacted one drift apart.
57
+ *
58
+ * import { piiTextRedactor } from '@gnldev/processors';
59
+ * await exportRun(journal, runId, { endpoint, redact: piiTextRedactor() });
60
+ */
61
+ export declare function piiTextRedactor(opts?: Pick<PiiRedactorOptions, 'types' | 'mask' | 'extraPatterns' | 'validate'>): (text: string) => string;
62
+ /**
63
+ * PII redaction processor — pure regex (email/phone/credit-card/ssn/ip). Deterministic, so no
64
+ * journaling is needed: produces the same masking on resume. The input side runs BEFORE persistInput
65
+ * → masked content is written to the journal, the model NEVER sees raw PII.
66
+ *
67
+ * HONEST WARNING (naive regex matching): These regexes are best-effort, they do NOT provide an
68
+ * AUDIT/COMPLIANCE-grade (GDPR/HIPAA/PCI-DSS etc.) PII DETECTION GUARANTEE. Known limits: only
69
+ * matches specific formats (e.g. US/generic-format phone numbers, plain 16-digit card numbers) —
70
+ * international/local formats, unstructured PII like name/address, or unusual formatting (line
71
+ * breaks, different separators) can slip through; it can also produce false positives (e.g. a
72
+ * random 16-digit number). Use it as a noise-reduction / first-line-of-defense layer, not as a real
73
+ * compliance/security boundary.
74
+ *
75
+ * SCOPE, measured — WHAT THE OUTPUT SIDE DOES NOT COVER: `processOutput` transforms the
76
+ * `{text, messages}` view, so `result.text` and `result.response.messages` come back masked on both
77
+ * `runDurable` and `streamDurable`, and so does persisted thread memory. `result.steps` and
78
+ * `result.content` DO NOT — they still hold the model's raw output, and a caller reading either one
79
+ * sees unredacted PII. This is not fixable inside the hook: a processor's output arity is
80
+ * unconstrained (a summariser legally returns one message for a turn that produced three), so no
81
+ * mapping back onto per-step records exists, and `content` is a parts array rather than messages.
82
+ * Read `text`/`response.messages`; treat `steps`/`content` as raw. On the STREAM path the
83
+ * `textStream`/`fullStream` deltas are raw as well — they reach the client before the turn ends, so
84
+ * use `on: 'input'` (or `runDurable`) if the wire itself must never carry it.
85
+ */
86
+ export declare function piiRedactor(opts?: PiiRedactorOptions): Processor;