intentseal-core 0.1.0__tar.gz

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.
Files changed (46) hide show
  1. intentseal_core-0.1.0/LICENSE +202 -0
  2. intentseal_core-0.1.0/NOTICE +4 -0
  3. intentseal_core-0.1.0/PKG-INFO +73 -0
  4. intentseal_core-0.1.0/README.md +21 -0
  5. intentseal_core-0.1.0/intentseal_core/__init__.py +15 -0
  6. intentseal_core-0.1.0/intentseal_core/__main__.py +5 -0
  7. intentseal_core-0.1.0/intentseal_core/action_guard.py +174 -0
  8. intentseal_core-0.1.0/intentseal_core/classifier.py +127 -0
  9. intentseal_core-0.1.0/intentseal_core/cli.py +163 -0
  10. intentseal_core-0.1.0/intentseal_core/config.py +185 -0
  11. intentseal_core-0.1.0/intentseal_core/costs.py +35 -0
  12. intentseal_core-0.1.0/intentseal_core/decision_model.py +144 -0
  13. intentseal_core-0.1.0/intentseal_core/decode.py +92 -0
  14. intentseal_core-0.1.0/intentseal_core/defaults/models.yaml +88 -0
  15. intentseal_core-0.1.0/intentseal_core/defaults/policy-templates/blank.yaml +8 -0
  16. intentseal_core-0.1.0/intentseal_core/defaults/policy-templates/coding-agent.yaml +14 -0
  17. intentseal_core-0.1.0/intentseal_core/defaults/policy-templates/customer-support.yaml +16 -0
  18. intentseal_core-0.1.0/intentseal_core/defaults/policy-templates/rag-assistant.yaml +27 -0
  19. intentseal_core-0.1.0/intentseal_core/defaults/policy-templates/research-assistant.yaml +18 -0
  20. intentseal_core-0.1.0/intentseal_core/defaults/providers.yaml +144 -0
  21. intentseal_core-0.1.0/intentseal_core/engine.py +749 -0
  22. intentseal_core-0.1.0/intentseal_core/extract.py +402 -0
  23. intentseal_core-0.1.0/intentseal_core/llm/__init__.py +4 -0
  24. intentseal_core-0.1.0/intentseal_core/llm/adapters.py +278 -0
  25. intentseal_core-0.1.0/intentseal_core/llm/anthropic_adapter.py +294 -0
  26. intentseal_core-0.1.0/intentseal_core/llm/router.py +449 -0
  27. intentseal_core-0.1.0/intentseal_core/logger.py +245 -0
  28. intentseal_core-0.1.0/intentseal_core/markers.py +29 -0
  29. intentseal_core-0.1.0/intentseal_core/memory.py +157 -0
  30. intentseal_core-0.1.0/intentseal_core/normalise.py +88 -0
  31. intentseal_core-0.1.0/intentseal_core/outbound.py +76 -0
  32. intentseal_core-0.1.0/intentseal_core/policy.py +156 -0
  33. intentseal_core-0.1.0/intentseal_core/secrets.py +101 -0
  34. intentseal_core-0.1.0/intentseal_core/session.py +151 -0
  35. intentseal_core-0.1.0/intentseal_core/siem.py +252 -0
  36. intentseal_core-0.1.0/intentseal_core/store.py +194 -0
  37. intentseal_core-0.1.0/intentseal_core/taint.py +87 -0
  38. intentseal_core-0.1.0/intentseal_core/types.py +64 -0
  39. intentseal_core-0.1.0/intentseal_core.egg-info/PKG-INFO +73 -0
  40. intentseal_core-0.1.0/intentseal_core.egg-info/SOURCES.txt +44 -0
  41. intentseal_core-0.1.0/intentseal_core.egg-info/dependency_links.txt +1 -0
  42. intentseal_core-0.1.0/intentseal_core.egg-info/entry_points.txt +2 -0
  43. intentseal_core-0.1.0/intentseal_core.egg-info/requires.txt +33 -0
  44. intentseal_core-0.1.0/intentseal_core.egg-info/top_level.txt +1 -0
  45. intentseal_core-0.1.0/pyproject.toml +65 -0
  46. intentseal_core-0.1.0/setup.cfg +4 -0
@@ -0,0 +1,202 @@
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 [yyyy] [name of copyright owner]
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.
202
+
@@ -0,0 +1,4 @@
1
+ IntentSeal
2
+ Copyright 2026 Sankalp Wanjari
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: intentseal-core
3
+ Version: 0.1.0
4
+ Summary: IntentSeal Core Engine: prompt-injection firewall and action guard for LLM agents
5
+ Author-email: Sankalp Wanjari <sankalpwanjari85@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/sankalp2515/intentseal
8
+ Project-URL: Source, https://github.com/sankalp2515/intentseal
9
+ Project-URL: Documentation, https://github.com/sankalp2515/intentseal/blob/main/docs/INTEGRATION.md
10
+ Project-URL: Issues, https://github.com/sankalp2515/intentseal/issues
11
+ Keywords: prompt injection,llm security,ai agents,guardrails,firewall,rag
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ License-File: NOTICE
24
+ Requires-Dist: httpx>=0.27
25
+ Requires-Dist: pydantic>=2.6
26
+ Requires-Dist: pyyaml>=6.0
27
+ Requires-Dist: python-dotenv>=1.0
28
+ Requires-Dist: anyascii>=0.3
29
+ Provides-Extra: engine
30
+ Requires-Dist: beautifulsoup4>=4.12; extra == "engine"
31
+ Requires-Dist: pypdf>=4; extra == "engine"
32
+ Requires-Dist: pdfplumber>=0.11; extra == "engine"
33
+ Requires-Dist: python-docx>=1.1; extra == "engine"
34
+ Requires-Dist: ftfy>=6.1; extra == "engine"
35
+ Requires-Dist: confusable-homoglyphs>=3.2; extra == "engine"
36
+ Requires-Dist: detect-secrets>=1.4; extra == "engine"
37
+ Provides-Extra: classifiers
38
+ Requires-Dist: onnxruntime>=1.17; extra == "classifiers"
39
+ Requires-Dist: tokenizers>=0.15; extra == "classifiers"
40
+ Requires-Dist: huggingface_hub>=0.23; extra == "classifiers"
41
+ Requires-Dist: numpy>=1.26; extra == "classifiers"
42
+ Provides-Extra: ocr
43
+ Requires-Dist: rapidocr-onnxruntime>=1.3; extra == "ocr"
44
+ Requires-Dist: pillow>=10; extra == "ocr"
45
+ Provides-Extra: postgres
46
+ Requires-Dist: psycopg[binary]>=3.2; extra == "postgres"
47
+ Provides-Extra: anthropic
48
+ Requires-Dist: anthropic>=1.12; extra == "anthropic"
49
+ Provides-Extra: all
50
+ Requires-Dist: intentseal-core[classifiers,engine,ocr]; extra == "all"
51
+ Dynamic: license-file
52
+
53
+ # intentseal-core
54
+
55
+ The engine behind [IntentSeal](https://pypi.org/project/intentseal/), a prompt-injection firewall for AI agents:
56
+ content extraction for every format (PDF, Word, HTML, email, Markdown, JSON, code, images via OCR), normalisation and
57
+ decoding, a three-tier detector (structural rules, a local classifier, an AI judge), session risk and data-flow
58
+ tracking, the action guard and the decision log.
59
+
60
+ Most users install the SDK instead:
61
+
62
+ ```bash
63
+ pip install intentseal # SDK, remote mode
64
+ pip install "intentseal[embedded]" # SDK with this engine in-process
65
+ ```
66
+
67
+ Extras of this package: `engine` (extraction, normalisation, secret scan), `classifiers` (local ONNX classifier),
68
+ `ocr`, `postgres`, `anthropic`, `all`.
69
+
70
+ It also installs the `intentseal` command: `intentseal init` writes a starter policy; `intentseal providers check`
71
+ lists the configured model providers and tests each key (key values are never printed).
72
+
73
+ Source and documentation: https://github.com/sankalp2515/intentseal · Licensed under the Apache License 2.0.
@@ -0,0 +1,21 @@
1
+ # intentseal-core
2
+
3
+ The engine behind [IntentSeal](https://pypi.org/project/intentseal/), a prompt-injection firewall for AI agents:
4
+ content extraction for every format (PDF, Word, HTML, email, Markdown, JSON, code, images via OCR), normalisation and
5
+ decoding, a three-tier detector (structural rules, a local classifier, an AI judge), session risk and data-flow
6
+ tracking, the action guard and the decision log.
7
+
8
+ Most users install the SDK instead:
9
+
10
+ ```bash
11
+ pip install intentseal # SDK, remote mode
12
+ pip install "intentseal[embedded]" # SDK with this engine in-process
13
+ ```
14
+
15
+ Extras of this package: `engine` (extraction, normalisation, secret scan), `classifiers` (local ONNX classifier),
16
+ `ocr`, `postgres`, `anthropic`, `all`.
17
+
18
+ It also installs the `intentseal` command: `intentseal init` writes a starter policy; `intentseal providers check`
19
+ lists the configured model providers and tests each key (key values are never printed).
20
+
21
+ Source and documentation: https://github.com/sankalp2515/intentseal · Licensed under the Apache License 2.0.
@@ -0,0 +1,15 @@
1
+ """IntentSeal Core Engine."""
2
+
3
+ import os
4
+
5
+ __version__ = "0.1.0"
6
+
7
+
8
+ def adopt_legacy_env() -> None:
9
+ """Settings were named ASG_* before 8 Oct 2026 (D-038). An old name still works when the new one is unset."""
10
+ for name, value in list(os.environ.items()):
11
+ if name.startswith("ASG_"):
12
+ os.environ.setdefault("INTENTSEAL_" + name[4:], value)
13
+
14
+
15
+ adopt_legacy_env()
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,174 @@
1
+ """CORE-9 Action guard: deterministic checks on every tool call before it runs.
2
+
3
+ Checks, in order (first hard violation wins; all observations are recorded):
4
+ 1. tool allowed for this agent
5
+ 2. pinned fields: values come from trusted session context, never from the model
6
+ 3. outbound scan: canaries / secrets / registered values in any argument
7
+ 4. recipient allow-list (send-type tools)
8
+ 5. URL domain allow-list (fetch-type tools) - stops data leaving through a URL
9
+ 6. path stays inside the sandbox (file tools)
10
+ 7. provenance: high-risk target that appears only in untrusted content
11
+ 8. session risk: high-risk tool while the session carries risk from untrusted content
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import fnmatch
17
+ import time
18
+ from dataclasses import dataclass, field
19
+ from email.utils import getaddresses
20
+ from typing import Any
21
+
22
+ from .outbound import scan_args
23
+ from .policy import AgentPolicy, ToolPolicy
24
+ from .session import Session, domain_of
25
+ from .types import ActionResult, Decision
26
+
27
+
28
+ @dataclass
29
+ class ActionCheck:
30
+ rule: str
31
+ decision: Decision
32
+ reason: str
33
+ labels: list[str] = field(default_factory=list)
34
+
35
+
36
+ def _recipient_ok(addr: str, allowed: list[str]) -> bool:
37
+ a = addr.strip().lower()
38
+ if a.count("@") != 1 or not a.split("@")[0] or not a.split("@")[1]:
39
+ return False
40
+ for rule in allowed:
41
+ r = rule.lower()
42
+ if (r.startswith("@") and a.endswith(r)) or a == r:
43
+ return True
44
+ return False
45
+
46
+
47
+ def recipients(value: Any) -> list[str]:
48
+ """Addresses a mailer would deliver to, parsed the way mail libraries parse them (display names, angle
49
+ brackets, comma/semicolon lists). A piece that does not parse to an address is kept as is, so it fails."""
50
+ raw = ", ".join(map(str, value)) if isinstance(value, (list, tuple)) else str(value)
51
+ out: list[str] = []
52
+ for piece in raw.replace(";", ",").split(","):
53
+ if not piece.strip():
54
+ continue
55
+ parsed = [a for _, a in getaddresses([piece])]
56
+ out += parsed if parsed and all(parsed) else [piece]
57
+ # getaddresses splits "Name <x@a> @b" into two entries; any leftover fragment must also pass.
58
+ for _, a in getaddresses([raw.replace(";", ",")]):
59
+ if a and a not in out:
60
+ out.append(a)
61
+ return out
62
+
63
+
64
+ def _domain_ok(url: str, allowed: list[str]) -> bool:
65
+ d = domain_of(url)
66
+ if not d:
67
+ return False
68
+ return any(d == a.lower() or d.endswith("." + a.lower()) or fnmatch.fnmatch(d, a.lower()) for a in allowed)
69
+
70
+
71
+ def _path_ok(path: str) -> bool:
72
+ p = path.replace("\\", "/")
73
+ return not (p.startswith("/") or ".." in p.split("/") or (len(p) > 1 and p[1] == ":"))
74
+
75
+
76
+ def check_action(tool: str, args: dict[str, Any], policy: AgentPolicy, session: Session,
77
+ registered_secrets: list[str] | None = None) -> ActionResult:
78
+ t0 = time.perf_counter()
79
+ args = dict(args or {})
80
+ checks: list[ActionCheck] = []
81
+ tp: ToolPolicy | None = policy.tools.get(tool)
82
+
83
+ if tp is None:
84
+ if policy.unknown_tools == "block":
85
+ checks.append(ActionCheck("tool-not-allowed", Decision.BLOCK, f"'{tool}' is not an allowed tool for this agent",
86
+ ["Tool Abuse"]))
87
+ tp = ToolPolicy()
88
+
89
+ # 2. pinned fields (rewrite, never trust the model's value)
90
+ overrides: dict[str, Any] = {}
91
+ for f in tp.pinned:
92
+ if f in session.trusted:
93
+ if str(args.get(f, "")).strip() != str(session.trusted[f]).strip():
94
+ overrides[f] = {"requested": args.get(f), "pinned": session.trusted[f]}
95
+ args[f] = session.trusted[f]
96
+ if overrides:
97
+ checks.append(ActionCheck("pinned-field-override", Decision.ALLOW,
98
+ f"pinned field(s) {', '.join(overrides)} set from trusted context", ["Tool Abuse"]))
99
+
100
+ # 3. outbound secrets / canaries
101
+ hits = scan_args(args, policy.canary_values(), registered_secrets or [])
102
+ if hits:
103
+ kinds = sorted({h.kind for h in hits})
104
+ checks.append(ActionCheck("outbound-secret", Decision.BLOCK,
105
+ f"arguments contain protected data ({', '.join(kinds)}) in {', '.join(sorted({h.field for h in hits}))}",
106
+ ["Secret Extraction", "Credential Theft"]))
107
+
108
+ # 4. recipients
109
+ if tp.allowed_recipients and tp.recipient_arg in args:
110
+ parsed = recipients(args[tp.recipient_arg])
111
+ bad = [r for r in parsed if not _recipient_ok(r, tp.allowed_recipients)]
112
+ if bad or not parsed:
113
+ checks.append(ActionCheck("recipient-not-allowed", Decision.BLOCK,
114
+ f"recipient outside allowed list ({len(bad)} address(es))", ["Tool Abuse"]))
115
+
116
+ # 5. URL domains
117
+ if tp.allowed_domains and tp.url_arg in args:
118
+ if not _domain_ok(str(args[tp.url_arg]), tp.allowed_domains):
119
+ checks.append(ActionCheck("domain-not-allowed", Decision.BLOCK,
120
+ f"URL domain '{domain_of(str(args[tp.url_arg]))}' is not approved", ["Tool Abuse"]))
121
+
122
+ # 6. sandbox paths
123
+ if tp.path_arg and tp.path_arg in args and not _path_ok(str(args[tp.path_arg])):
124
+ checks.append(ActionCheck("path-outside-sandbox", Decision.BLOCK, "path leaves the workspace", ["Tool Abuse"]))
125
+
126
+ # 7. provenance of high-risk targets
127
+ if tp.risk == "high":
128
+ for key in (tp.recipient_arg, tp.url_arg):
129
+ if key in args and session.from_untrusted_only(str(args[key])):
130
+ checks.append(ActionCheck("target-from-untrusted-content",
131
+ Decision.ESCALATE if tp.escalate_if_uncertain else Decision.BLOCK,
132
+ f"'{key}' value appears only in untrusted content, not in the user's request",
133
+ ["Indirect Prompt Injection", "Tool Abuse"]))
134
+
135
+ # 8. session risk on high-risk tools
136
+ if tp.risk == "high" and session.risk >= policy.session.escalate_at:
137
+ hard = session.risk >= policy.session.block_at
138
+ checks.append(ActionCheck("high-risk-tool-in-risky-session", Decision.BLOCK if hard else Decision.ESCALATE,
139
+ f"session risk {session.risk:.2f} after untrusted content",
140
+ sorted(session.labels) or ["Multi-Step Jailbreaks"]))
141
+
142
+ # 8b. explicit intent (reported after the more specific rules above) (docs/13 L1): a share/destructive tool the user never asked for is held for approval
143
+ if tp.intent_terms and not session.user_asked_for(tp.intent_terms):
144
+ checks.append(ActionCheck("action-not-requested", Decision.ESCALATE,
145
+ f"the user's messages do not ask for this action ({', '.join(tp.intent_terms[:4])}…)",
146
+ ["Tool Abuse"]))
147
+
148
+ # 9. data flow (CORE-17): where each argument's text came from; flagged content into a high-risk tool
149
+ taint = session.taint.trace(args, policy.taint.min_coverage) if policy.taint.enabled else []
150
+ flagged = sorted({h.arg for h in taint if h.flagged})
151
+ if tp.risk == "high" and flagged and policy.taint.flagged_to_high_risk in ("escalate", "block"):
152
+ checks.append(ActionCheck("tainted-from-flagged-content",
153
+ Decision.BLOCK if policy.taint.flagged_to_high_risk == "block" else Decision.ESCALATE,
154
+ f"argument(s) {', '.join(flagged)} copy text from content the gateway flagged",
155
+ ["Indirect Prompt Injection", "Tool Abuse"]))
156
+
157
+ order = {Decision.BLOCK: 3, Decision.ESCALATE: 2, Decision.NEUTRALISE: 1, Decision.ALLOW: 0}
158
+ worst = max(checks, key=lambda c: order[c.decision], default=None)
159
+ decision = worst.decision if worst else Decision.ALLOW
160
+ enforced = decision if policy.mode == "enforce" else Decision.ALLOW
161
+ labels = sorted({l for c in checks for l in c.labels})
162
+ reason = "; ".join(c.reason for c in checks) or "within policy"
163
+ notice = None
164
+ if enforced == Decision.BLOCK:
165
+ notice = f"Action '{tool}' was blocked by the security policy: {worst.reason}. Continue the user's task without it."
166
+ elif enforced == Decision.ESCALATE:
167
+ notice = f"Action '{tool}' needs human approval ({worst.reason}). It was not performed; tell the user it is awaiting approval."
168
+ if decision != Decision.ALLOW:
169
+ session.add_risk(0.5 if decision == Decision.BLOCK else 0.3, labels)
170
+ return ActionResult(decision=decision, enforced=enforced,
171
+ final_args=args if enforced == Decision.ALLOW else None,
172
+ pinned_overrides=overrides, labels=labels, taint=[h.as_dict() for h in taint],
173
+ policy_rule=worst.rule if worst else "allow", reason=reason, notice=notice,
174
+ latency_ms=round((time.perf_counter() - t0) * 1000, 2))
@@ -0,0 +1,127 @@
1
+ """Tier 1 classifiers (CORE-4): cheap signals that decide what to escalate, never final decisions (D-011).
2
+
3
+ - LocalClassifier: protectai/deberta-v3-base-prompt-injection-v2 (Apache-2.0), ONNX on CPU, chunked.
4
+ - RemoteGuard: Llama Prompt Guard 2 via the router role `tier1_remote` (hosted, free tier).
5
+ Both cache by content hash (CC2).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import logging
13
+ import os
14
+ import threading
15
+ import time
16
+ from collections import OrderedDict
17
+ from pathlib import Path
18
+
19
+ from .config import repo_root
20
+
21
+ log = logging.getLogger("intentseal.tier1")
22
+ MODEL_REPO = os.environ.get("INTENTSEAL_TIER1_MODEL", "protectai/deberta-v3-base-prompt-injection-v2")
23
+
24
+
25
+ class LocalClassifier:
26
+ def __init__(self, repo: str = MODEL_REPO, threads: int | None = None) -> None:
27
+ import numpy as np # noqa: F401 (import check)
28
+ import onnxruntime as ort
29
+ from huggingface_hub import snapshot_download
30
+ from tokenizers import Tokenizer
31
+
32
+ os.environ.setdefault("HF_HOME", str(repo_root() / "data" / "hf_cache"))
33
+ path = Path(snapshot_download(repo, allow_patterns=["onnx/*", "*.json"]))
34
+ tok = path / "onnx" / "tokenizer.json"
35
+ self.tok = Tokenizer.from_file(str(tok if tok.exists() else path / "tokenizer.json"))
36
+ so = ort.SessionOptions()
37
+ so.intra_op_num_threads = threads or int(os.environ.get("INTENTSEAL_TIER1_THREADS") or "2")
38
+ self.sess = ort.InferenceSession(str(path / "onnx" / "model.onnx"), so, providers=["CPUExecutionProvider"])
39
+ self.inputs = {i.name for i in self.sess.get_inputs()}
40
+ cfg = json.loads((path / "config.json").read_text())
41
+ self.pos = next(int(k) for k, v in cfg["id2label"].items() if "INJ" in v.upper())
42
+ self.cls, self.sep = self.tok.token_to_id("[CLS]"), self.tok.token_to_id("[SEP]")
43
+ self._lock = threading.Lock()
44
+ self._cache: OrderedDict[str, float] = OrderedDict() # bounded: CACHE_MAX entries
45
+
46
+ def score(self, text: str) -> float:
47
+ """Max probability over windows of up to 256 tokens (shorter windows keep CPU latency low)."""
48
+ import numpy as np
49
+
50
+ key = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()
51
+ if key in self._cache:
52
+ return self._cache[key]
53
+ ids = self.tok.encode(text, add_special_tokens=False).ids
54
+ best, window, stride = 0.0, 254, 200
55
+ with self._lock:
56
+ for start in range(0, max(1, len(ids)), stride):
57
+ chunk = [self.cls] + ids[start:start + window] + [self.sep]
58
+ feed = {"input_ids": np.array([chunk], dtype=np.int64),
59
+ "attention_mask": np.ones((1, len(chunk)), dtype=np.int64)}
60
+ if "token_type_ids" in self.inputs:
61
+ feed["token_type_ids"] = np.zeros((1, len(chunk)), dtype=np.int64)
62
+ logits = self.sess.run(None, feed)[0][0]
63
+ p = np.exp(logits - logits.max())
64
+ best = max(best, float((p / p.sum())[self.pos]))
65
+ if start + window >= len(ids):
66
+ break
67
+ self._cache[key] = best
68
+ while len(self._cache) > CACHE_MAX:
69
+ self._cache.popitem(last=False)
70
+ return best
71
+
72
+
73
+ CACHE_MAX = 20000
74
+ RETRY_S = 60.0
75
+ _loaded: LocalClassifier | None = None
76
+ _failure: tuple[float, str] | None = None # (time, error type) of the last failed load
77
+ _load_lock = threading.Lock()
78
+
79
+
80
+ def local_classifier() -> LocalClassifier | None:
81
+ """The process-wide local classifier. A failed load is retried after RETRY_S (never cached for the life of the
82
+ process); while it is unavailable the engine sends content to the judge or holds it (fail closed)."""
83
+ global _loaded, _failure
84
+ if _loaded is not None:
85
+ return _loaded
86
+ with _load_lock:
87
+ if _loaded is None and (_failure is None or time.monotonic() - _failure[0] >= RETRY_S):
88
+ try:
89
+ _loaded, _failure = LocalClassifier(), None
90
+ except Exception as e: # missing model / runtime
91
+ _failure = (time.monotonic(), type(e).__name__)
92
+ log.warning("Tier 1 local classifier unavailable: %s", type(e).__name__)
93
+ return _loaded
94
+
95
+
96
+ def tier1_status() -> dict[str, str | bool]:
97
+ """For readiness checks: loaded, or the last load error."""
98
+ return {"loaded": _loaded is not None, "error": _failure[1] if _failure and _loaded is None else ""}
99
+
100
+
101
+ class RemoteGuard:
102
+ """Prompt Guard 2 via the router (role `tier1_remote`). Returns None when unavailable."""
103
+
104
+ def __init__(self, router, role: str = "tier1_remote") -> None:
105
+ self.router = router
106
+ self.role = role
107
+ self._cache: dict[str, float] = {}
108
+
109
+ async def score(self, text: str) -> float | None:
110
+ from .llm.adapters import ChatRequest
111
+ from .llm.router import AllProvidersFailed
112
+
113
+ if self.role not in self.router.settings.roles:
114
+ return None
115
+ key = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()
116
+ if key in self._cache:
117
+ return self._cache[key]
118
+ try:
119
+ r = await self.router.chat(self.role, ChatRequest(messages=[{"role": "user", "content": text[:2000]}],
120
+ max_tokens=8, temperature=None))
121
+ val = float((r.content or "").strip())
122
+ except (AllProvidersFailed, ValueError):
123
+ return None
124
+ self._cache[key] = val
125
+ if len(self._cache) > CACHE_MAX:
126
+ self._cache.pop(next(iter(self._cache)))
127
+ return val