rag-security-protocol 0.1.1__py3-none-any.whl
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.
- rag_security_protocol-0.1.1.dist-info/METADATA +132 -0
- rag_security_protocol-0.1.1.dist-info/RECORD +16 -0
- rag_security_protocol-0.1.1.dist-info/WHEEL +4 -0
- rag_security_protocol-0.1.1.dist-info/entry_points.txt +2 -0
- rag_security_protocol-0.1.1.dist-info/licenses/LICENSE +201 -0
- rsp/__init__.py +0 -0
- rsp/cli.py +80 -0
- rsp/codec.py +167 -0
- rsp/config.py +146 -0
- rsp/guards.py +91 -0
- rsp/handshake.py +77 -0
- rsp/ingest.py +153 -0
- rsp/process.py +183 -0
- rsp/py.typed +0 -0
- rsp/runtime.py +273 -0
- rsp/spans.py +112 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rag-security-protocol
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: RAG Security Protocol — where security tools hook into a RAG pipeline, and what they return
|
|
5
|
+
Project-URL: Homepage, https://github.com/PCBZ/rsp
|
|
6
|
+
Project-URL: Specification, https://github.com/PCBZ/rsp/blob/main/SPEC.md
|
|
7
|
+
Project-URL: Issues, https://github.com/PCBZ/rsp/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/PCBZ/rsp/releases
|
|
9
|
+
Author: PCBZ
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: conformance,llm,protocol,rag,redaction,security
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Classifier: Topic :: Security
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Provides-Extra: llamaindex
|
|
24
|
+
Requires-Dist: llama-index-core<0.15,>=0.14; extra == 'llamaindex'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# RSP
|
|
28
|
+
|
|
29
|
+
A protocol for scanning content **before** it reaches a vector store.
|
|
30
|
+
|
|
31
|
+
Everything that ships today scans after storage, where an embedding already
|
|
32
|
+
exists and the text is recoverable from it. RSP puts the scanner at the
|
|
33
|
+
ingest hook instead, so that blocked means it was never there.
|
|
34
|
+
|
|
35
|
+
```console
|
|
36
|
+
$ rsp ingest demo/sample-docs --config demo/rsp.toml
|
|
37
|
+
scanned 11 chunks
|
|
38
|
+
REDACT aws-access-token demo/sample-docs/deploy-notes.md:1-14
|
|
39
|
+
REDACT private-key demo/sample-docs/runbook-backups.md:1-18
|
|
40
|
+
11 chunks indexed, 0 blocked, 2 redacted
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Nothing in that run is ours except the wiring: the detector is
|
|
44
|
+
[gitleaks](https://github.com/gitleaks/gitleaks), unmodified, and the pipeline
|
|
45
|
+
is LlamaIndex.
|
|
46
|
+
|
|
47
|
+
## What it is
|
|
48
|
+
|
|
49
|
+
`SPEC.md` is the deliverable — twenty-eight clauses, each with the reasoning
|
|
50
|
+
that produced it, twenty-three of them settled by a conformance case rather
|
|
51
|
+
than by assertion. The code in `rsp/` is one host implementation, and exists
|
|
52
|
+
to prove the clauses are implementable.
|
|
53
|
+
|
|
54
|
+
A plugin is a command. It reads one JSON object on stdin, writes one on
|
|
55
|
+
stdout, and exits:
|
|
56
|
+
|
|
57
|
+
```console
|
|
58
|
+
$ echo '{"rsp_version":"0.1","hook":"on_chunk","content":"key: AKIA47CQZHT2MVPF3JXB"}' | my-scanner
|
|
59
|
+
{"verdict":"REDACT","spans":[{"start":5,"end":25,"type":"aws"}],"replacement":"[REDACTED]"}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Offsets are bytes into UTF-8, half-open. The host applies them; a plugin never
|
|
63
|
+
sees the content again. [Writing a plugin](https://github.com/PCBZ/rsp/blob/main/WRITING-A-PLUGIN.md) is the page to
|
|
64
|
+
start from — the four messages, and the three things that bite.
|
|
65
|
+
|
|
66
|
+
## Try it
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
uv sync --extra llamaindex
|
|
70
|
+
uv run rsp ingest demo/sample-docs --config demo/rsp.toml # needs gitleaks and node
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Use it
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from rsp.config import load
|
|
77
|
+
from rsp.guards import RSPIngestGuard, RSPRetrieveGuard
|
|
78
|
+
from rsp.runtime import Runtime
|
|
79
|
+
|
|
80
|
+
runtime = Runtime(load("rsp.toml")) # every plugin handshakes here, or this raises
|
|
81
|
+
|
|
82
|
+
indexed = IngestionPipeline(
|
|
83
|
+
transformations=[SentenceSplitter(), RSPIngestGuard(runtime=runtime), embedding]
|
|
84
|
+
).run(documents=documents)
|
|
85
|
+
|
|
86
|
+
kept = RSPRetrieveGuard(runtime=runtime).postprocess_nodes(retrieved, query_str=query)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The ingest guard goes after the splitter and before the embedding, which is
|
|
90
|
+
the whole point: a blocked chunk is never embedded and never stored. The
|
|
91
|
+
retrieve guard catches what an index already held.
|
|
92
|
+
|
|
93
|
+
[`examples/host`](https://github.com/PCBZ/rsp/tree/main/examples/host) is that, whole and runnable: four documents
|
|
94
|
+
through one pipeline, judged by a Python plugin and a Go one at the same time.
|
|
95
|
+
The host code does not know which is which.
|
|
96
|
+
|
|
97
|
+
## Check your own plugin
|
|
98
|
+
|
|
99
|
+
```console
|
|
100
|
+
$ python conformance/run.py -- my-scanner
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Copy `conformance/` and `plugins/` next to your plugin — they are not in the
|
|
104
|
+
installed package, on purpose: you are checking against the protocol, not
|
|
105
|
+
against a version of it that shipped with a host. Standard library only, and
|
|
106
|
+
nothing in it imports this host. `conformance/README.md` explains roles
|
|
107
|
+
and the host cases.
|
|
108
|
+
|
|
109
|
+
## Where things are
|
|
110
|
+
|
|
111
|
+
| | |
|
|
112
|
+
|---|---|
|
|
113
|
+
| `SPEC.md` | the protocol |
|
|
114
|
+
| `WRITING-A-PLUGIN.md` | the on-ramp, quoting a plugin under test |
|
|
115
|
+
| `conformance/` | cases, a runner, and a plugin that misbehaves on request |
|
|
116
|
+
| `rsp/` | the reference host — five layers, one-way imports, zero dependencies |
|
|
117
|
+
| `plugins/rsp-echo` | the reference plugin, whose verdicts are chosen by markers |
|
|
118
|
+
| `examples/host` | a whole host in one file, judged by a Python plugin and a Go one |
|
|
119
|
+
| `examples/gitleaks-{ts,go,rs,py,c,java,swift}` | the same real scanner wrapped seven times, in seven languages |
|
|
120
|
+
| `demo/` | eight documents, two of them with fabricated credentials |
|
|
121
|
+
|
|
122
|
+
Decisions (D1–D9) and open questions live in the
|
|
123
|
+
[wiki](https://github.com/PCBZ/rsp/wiki). Clause IDs — `S1`, `E4` — resolve
|
|
124
|
+
inside a clone; issue numbers do not, so the spec never cites one.
|
|
125
|
+
|
|
126
|
+
## Status
|
|
127
|
+
|
|
128
|
+
v0.1 is the first freeze. Four clauses have no conformance case and
|
|
129
|
+
`SPEC.md` §10 says which and why. Two of them — blocked content never reaching
|
|
130
|
+
storage, and a dropped retrieval hit — are the ones a host case cannot observe
|
|
131
|
+
without the host offering somewhere to look, and they are the two the protocol
|
|
132
|
+
is most about. That is the honest state of it.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
rsp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
rsp/cli.py,sha256=GHv1oAEItdQUiHzPrvr02IN3lSMvcttjRdWmgd8h_R4,2683
|
|
3
|
+
rsp/codec.py,sha256=o-SGeLqUc5OOkc3Axr2t9f4BNWuDZ1B4g6Z2heJoD34,6256
|
|
4
|
+
rsp/config.py,sha256=qzs0W_40ooQH_mXrmVsiivSeymW10l5X10tLomrgJkg,5954
|
|
5
|
+
rsp/guards.py,sha256=33jdo6rzu4YawTeaFncaPQAnx7uA52Ayv4aMx3VMVZs,3304
|
|
6
|
+
rsp/handshake.py,sha256=2WJ-rvDA494ixmNOO2_yZQcfFsScLaWQutbImLS_NyU,2388
|
|
7
|
+
rsp/ingest.py,sha256=xddiatHxxnhzoouh_-N110nkPc-QimvD2yAoYMmmh5Q,5546
|
|
8
|
+
rsp/process.py,sha256=AChPxbTySX7nXqh8-UCg_klQyLNPFHER04d3_0caGBo,5488
|
|
9
|
+
rsp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
rsp/runtime.py,sha256=LXv_oVGGHpoIuTUajGSHX7_Qe-WoaS6Z2ZmExZNW3A0,9907
|
|
11
|
+
rsp/spans.py,sha256=mIw9TmYahPX3K91SsSlLITlQBHo8T4ep0HX2Bp5tjMw,3709
|
|
12
|
+
rag_security_protocol-0.1.1.dist-info/METADATA,sha256=qyAl--XPu-z2J5oKPFdDlfH-_hYmEhWbMeyrEC7pMHk,5338
|
|
13
|
+
rag_security_protocol-0.1.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
14
|
+
rag_security_protocol-0.1.1.dist-info/entry_points.txt,sha256=MpeFCB8yav-W9hF5Bd2yfQ-8G0_kfg9K9GPPgU5uY1w,37
|
|
15
|
+
rag_security_protocol-0.1.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
16
|
+
rag_security_protocol-0.1.1.dist-info/RECORD,,
|
|
@@ -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 [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.
|
rsp/__init__.py
ADDED
|
File without changes
|
rsp/cli.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""`rsp validate` checks a config; `rsp ingest` runs a directory through it.
|
|
2
|
+
|
|
3
|
+
`load` stops at the first problem, because a host with half its guards is worse
|
|
4
|
+
than one that does not start; `validate` turns that into a message and an exit
|
|
5
|
+
code for someone editing the file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import pathlib
|
|
12
|
+
import sys
|
|
13
|
+
from collections.abc import Sequence
|
|
14
|
+
|
|
15
|
+
from rsp.config import load
|
|
16
|
+
from rsp.runtime import ConfigError, Plugin
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _validate(plugins: list[Plugin]) -> int:
|
|
20
|
+
for plugin in plugins:
|
|
21
|
+
print(
|
|
22
|
+
f"{plugin.name}: {' '.join(plugin.command)} "
|
|
23
|
+
f"[on_error={plugin.on_error.value} timeout={plugin.timeout:g}s]"
|
|
24
|
+
)
|
|
25
|
+
# No handshake: a binary installed elsewhere does not make the config invalid.
|
|
26
|
+
print(f"{len(plugins)} plugin(s), not started", file=sys.stderr)
|
|
27
|
+
return 0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _ingest(directory: pathlib.Path, plugins: list[Plugin]) -> int:
|
|
31
|
+
try:
|
|
32
|
+
# rsp.ingest imports llama_index lazily, so a missing extra surfaces at the call.
|
|
33
|
+
from rsp.ingest import ingest
|
|
34
|
+
|
|
35
|
+
report = ingest(directory, plugins)
|
|
36
|
+
except ImportError:
|
|
37
|
+
print(
|
|
38
|
+
"rsp ingest needs the llamaindex extra: pip install 'rsp[llamaindex]'", file=sys.stderr
|
|
39
|
+
)
|
|
40
|
+
return 1
|
|
41
|
+
except (ConfigError, FileNotFoundError) as exc:
|
|
42
|
+
print(exc, file=sys.stderr)
|
|
43
|
+
return 1
|
|
44
|
+
|
|
45
|
+
print(f"scanned {report.scanned} chunks")
|
|
46
|
+
for item in report.findings:
|
|
47
|
+
# A chunk's lines, not a position: the host never sees a span (S4).
|
|
48
|
+
print(f" {item.verdict:7}{item.types:18} {item.source}:{item.lines}")
|
|
49
|
+
print(
|
|
50
|
+
f"{report.indexed} chunks indexed, "
|
|
51
|
+
f"{len(report.blocked)} blocked, {len(report.redacted)} redacted"
|
|
52
|
+
)
|
|
53
|
+
return 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
57
|
+
parser = argparse.ArgumentParser(prog="rsp")
|
|
58
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
59
|
+
|
|
60
|
+
check = commands.add_parser("validate", help="check a config file")
|
|
61
|
+
check.add_argument("config", help="path to a TOML config")
|
|
62
|
+
|
|
63
|
+
run = commands.add_parser("ingest", help="run a directory through the plugins")
|
|
64
|
+
run.add_argument("directory", help="directory of documents")
|
|
65
|
+
run.add_argument("--config", default="rsp.toml", help="path to a TOML config")
|
|
66
|
+
|
|
67
|
+
arguments = parser.parse_args(argv)
|
|
68
|
+
try:
|
|
69
|
+
plugins = load(arguments.config)
|
|
70
|
+
except ConfigError as exc:
|
|
71
|
+
print(exc, file=sys.stderr)
|
|
72
|
+
return 1
|
|
73
|
+
|
|
74
|
+
if arguments.command == "validate":
|
|
75
|
+
return _validate(plugins)
|
|
76
|
+
return _ingest(pathlib.Path(arguments.directory), plugins)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
raise SystemExit(main())
|
rsp/codec.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Wire codec: a request mapping in, a parsed response out, or why not.
|
|
2
|
+
|
|
3
|
+
Sits between rsp.process and plugin identity, so both directions can be tested on
|
|
4
|
+
raw bytes without spawning anything.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from rsp.process import DEFAULT_MAX_OUTPUT, DEFAULT_TIMEOUT, Invocation, Outcome, invoke
|
|
15
|
+
|
|
16
|
+
RSP_VERSION = "0.1"
|
|
17
|
+
# Past this, parsers lose precision and two hosts disagree about a span (RFC 8259 §6).
|
|
18
|
+
_SAFE_INTEGER = 2**53 - 1
|
|
19
|
+
# RFC 8259 §2 whitespace. str.strip() also removes characters a strict parser refuses.
|
|
20
|
+
_WHITESPACE = " \t\n\r"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _sendable(value: Any, seen: frozenset[int] = frozenset()) -> None:
|
|
24
|
+
"""Raise ValueError if any part of a request would break T4 on the wire.
|
|
25
|
+
|
|
26
|
+
`seen` holds the containers above this one, so a request nested inside
|
|
27
|
+
itself is named rather than reaching the stack limit. Depth that is merely
|
|
28
|
+
great still raises RecursionError, which `call` catches alongside the rest
|
|
29
|
+
(E2).
|
|
30
|
+
"""
|
|
31
|
+
if isinstance(value, (Mapping, list, tuple)):
|
|
32
|
+
if id(value) in seen:
|
|
33
|
+
raise ValueError("a request cannot contain itself")
|
|
34
|
+
seen = seen | {id(value)}
|
|
35
|
+
if isinstance(value, Mapping):
|
|
36
|
+
# json.dumps writes the key 1 as "1", so {1: "a", "1": "b"} repeats a key.
|
|
37
|
+
written = [str(key) if isinstance(key, (int, float, bool)) else key for key in value]
|
|
38
|
+
if len(set(written)) != len(written):
|
|
39
|
+
raise ValueError("a key would be repeated once written")
|
|
40
|
+
for nested in value.values():
|
|
41
|
+
_sendable(nested, seen)
|
|
42
|
+
elif isinstance(value, (list, tuple)):
|
|
43
|
+
for nested in value:
|
|
44
|
+
_sendable(nested, seen)
|
|
45
|
+
elif isinstance(value, int) and not isinstance(value, bool) and abs(value) > _SAFE_INTEGER:
|
|
46
|
+
raise ValueError(f"{value} is outside the interoperable range")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def encode(request: Mapping[str, Any]) -> bytes:
|
|
50
|
+
"""One request as compact UTF-8 JSON. Raises ValueError if it cannot be.
|
|
51
|
+
|
|
52
|
+
`ensure_ascii=False` keeps the bytes a plugin counts the bytes we sent (S1);
|
|
53
|
+
`allow_nan=False` stops Python writing NaN, which no other parser accepts.
|
|
54
|
+
"""
|
|
55
|
+
_sendable(request) # a host does not send what it would refuse (T4)
|
|
56
|
+
return json.dumps(request, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode(
|
|
57
|
+
"utf-8"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _reject_constant(token: str) -> Any:
|
|
62
|
+
"""NaN and Infinity are not JSON (RFC 8259); Python's parser takes them."""
|
|
63
|
+
raise ValueError(f"{token} is not JSON")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
67
|
+
"""Refuse a repeated key: parsers disagree about which one wins (RFC 8259 §4)."""
|
|
68
|
+
seen: set[str] = set()
|
|
69
|
+
for key, _ in pairs:
|
|
70
|
+
if key in seen:
|
|
71
|
+
raise ValueError(f"duplicate key {key!r}")
|
|
72
|
+
seen.add(key)
|
|
73
|
+
return dict(pairs)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _checked_number(token: str) -> int:
|
|
77
|
+
"""Integers a JavaScript host could not read back unchanged."""
|
|
78
|
+
value = int(token)
|
|
79
|
+
if abs(value) > _SAFE_INTEGER:
|
|
80
|
+
raise ValueError(f"{token} is outside the interoperable range")
|
|
81
|
+
return value
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
_DECODER = json.JSONDecoder(
|
|
85
|
+
parse_constant=_reject_constant,
|
|
86
|
+
object_pairs_hook=_reject_duplicate_keys,
|
|
87
|
+
parse_int=_checked_number,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def decode(raw: bytes) -> tuple[Outcome, dict[str, Any] | None]:
|
|
92
|
+
"""Exactly one JSON object and nothing else, or why not (T2).
|
|
93
|
+
|
|
94
|
+
Not the first object that parses: anything else on stdout makes the protocol
|
|
95
|
+
channel a log, where a stray line looks like a response.
|
|
96
|
+
"""
|
|
97
|
+
try:
|
|
98
|
+
text = raw.decode("utf-8")
|
|
99
|
+
except UnicodeDecodeError:
|
|
100
|
+
return Outcome.MALFORMED, None
|
|
101
|
+
|
|
102
|
+
# Stripped with JSON's four, not Python's: a plugin whose whole output is
|
|
103
|
+
# some other space character said something, and EMPTY means it did not.
|
|
104
|
+
body = text.lstrip(_WHITESPACE)
|
|
105
|
+
if not body:
|
|
106
|
+
return Outcome.EMPTY, None
|
|
107
|
+
|
|
108
|
+
try:
|
|
109
|
+
payload, end = _DECODER.raw_decode(body)
|
|
110
|
+
except (ValueError, RecursionError):
|
|
111
|
+
# ValueError: JSONDecodeError, or a value the hooks above refuse.
|
|
112
|
+
# RecursionError: nesting deep enough to exhaust the stack, which the
|
|
113
|
+
# output cap does not bound — 200KB of brackets is well under it. A
|
|
114
|
+
# plugin does not get to choose when the host falls over (D2).
|
|
115
|
+
return Outcome.MALFORMED, None
|
|
116
|
+
|
|
117
|
+
if body[end:].strip(_WHITESPACE):
|
|
118
|
+
return Outcome.MALFORMED, None # a second object, or trailing noise
|
|
119
|
+
if not isinstance(payload, dict):
|
|
120
|
+
return Outcome.MALFORMED, None # a list or a bare string is not a response
|
|
121
|
+
try:
|
|
122
|
+
# `\ud800` parses and cannot be written back as UTF-8 (M1). Through
|
|
123
|
+
# `encode`, whose walk also bounds the nesting: the C scanner reads two
|
|
124
|
+
# thousand brackets without complaint, and a plugin does not get to
|
|
125
|
+
# choose when the host falls over (D2).
|
|
126
|
+
encode(payload)
|
|
127
|
+
except (ValueError, RecursionError):
|
|
128
|
+
return Outcome.MALFORMED, None
|
|
129
|
+
|
|
130
|
+
return Outcome.OK, payload
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True)
|
|
134
|
+
class Reply:
|
|
135
|
+
outcome: Outcome
|
|
136
|
+
payload: dict[str, Any] | None
|
|
137
|
+
invocation: Invocation | None # None when no process was ever started
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def ok(self) -> bool:
|
|
141
|
+
return self.outcome is Outcome.OK
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def call(
|
|
145
|
+
command: Sequence[str],
|
|
146
|
+
request: Mapping[str, Any],
|
|
147
|
+
*,
|
|
148
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
149
|
+
max_output: int = DEFAULT_MAX_OUTPUT,
|
|
150
|
+
) -> Reply:
|
|
151
|
+
"""One plugin call, from a request mapping to a parsed response. Never raises (E2).
|
|
152
|
+
|
|
153
|
+
Only a clean exit has its output parsed: from a killed or truncated call it is
|
|
154
|
+
a fragment, whether or not it happens to parse.
|
|
155
|
+
"""
|
|
156
|
+
try:
|
|
157
|
+
payload_bytes = encode(request)
|
|
158
|
+
except (ValueError, TypeError, RecursionError):
|
|
159
|
+
# No plugin is at fault and none ran, but there is no verdict either (E3).
|
|
160
|
+
return Reply(Outcome.UNENCODABLE, None, None)
|
|
161
|
+
|
|
162
|
+
invocation = invoke(command, payload_bytes, timeout=timeout, max_output=max_output)
|
|
163
|
+
if not invocation.ok:
|
|
164
|
+
return Reply(invocation.outcome, None, invocation)
|
|
165
|
+
|
|
166
|
+
outcome, payload = decode(invocation.stdout)
|
|
167
|
+
return Reply(outcome, payload, invocation)
|