abe-flow 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.
- abe_flow-0.1.0/LICENSE +201 -0
- abe_flow-0.1.0/NOTICE +19 -0
- abe_flow-0.1.0/PKG-INFO +62 -0
- abe_flow-0.1.0/README.md +45 -0
- abe_flow-0.1.0/abe_flow/__init__.py +221 -0
- abe_flow-0.1.0/abe_flow/py.typed +0 -0
- abe_flow-0.1.0/abe_flow.egg-info/PKG-INFO +62 -0
- abe_flow-0.1.0/abe_flow.egg-info/SOURCES.txt +12 -0
- abe_flow-0.1.0/abe_flow.egg-info/dependency_links.txt +1 -0
- abe_flow-0.1.0/abe_flow.egg-info/requires.txt +4 -0
- abe_flow-0.1.0/abe_flow.egg-info/top_level.txt +1 -0
- abe_flow-0.1.0/pyproject.toml +24 -0
- abe_flow-0.1.0/setup.cfg +4 -0
- abe_flow-0.1.0/tests/test_flow_resolver.py +133 -0
abe_flow-0.1.0/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 Flow Information Systems
|
|
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.
|
abe_flow-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Abe (FJP Gate reference implementation)
|
|
2
|
+
Copyright 2026 Flow Information Systems
|
|
3
|
+
|
|
4
|
+
This product was created and is maintained by Flow Information Systems
|
|
5
|
+
(https://flowinfo.co).
|
|
6
|
+
|
|
7
|
+
It includes the FJP-CONF v0.1 conformance checks from
|
|
8
|
+
https://github.com/flowinfosystems-index/fjp-conformance (Apache-2.0),
|
|
9
|
+
vendored in python/fjp/conformance/fjp_conf.py and typescript/src/fjpConf.ts.
|
|
10
|
+
|
|
11
|
+
Flow Judgment Protocol™, FJP™, FJP Gate™, Abe™, FJP-CONF™, FJP Compatible™,
|
|
12
|
+
Judgment-Grounded Agent™, Judgment-Grounded™, Flow™, and Flow Information
|
|
13
|
+
Systems™ are trademarks of Flow Information Systems. See TRADEMARKS.md.
|
|
14
|
+
|
|
15
|
+
The Apache License, Version 2.0 (LICENSE) governs use of the source code in this
|
|
16
|
+
repository. It does not grant any right to use the trademarks listed above.
|
|
17
|
+
|
|
18
|
+
This NOTICE file must be preserved in redistributions of this work, per Section 4
|
|
19
|
+
of the Apache License, Version 2.0.
|
abe_flow-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: abe-flow
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send Abe escalations to Flow's judgment service (resolve.flowinfo.co). Only ESCALATE results are sent.
|
|
5
|
+
Author-email: Flow Information Systems <flowinfosystems@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://fjp.flowinfo.co/abe
|
|
8
|
+
Project-URL: Source, https://github.com/flowinfosystems-index/abe
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: NOTICE
|
|
13
|
+
Requires-Dist: abe-ai<0.2,>=0.1.0
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# abe-flow
|
|
19
|
+
|
|
20
|
+
Send **only the actions Abe escalates** to Flow's judgment service, and get back a decision, a reason and a
|
|
21
|
+
falsifiable record.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install abe-ai abe-flow
|
|
25
|
+
export FLOW_API_KEY=fjp_live_... # https://fjp.flowinfo.co
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import os
|
|
30
|
+
from abe import Abe
|
|
31
|
+
from abe_flow import FlowResolver
|
|
32
|
+
|
|
33
|
+
abe = Abe("abe-policy.yaml", resolver=FlowResolver(api_key=os.environ["FLOW_API_KEY"]))
|
|
34
|
+
r = abe.check(action={"type": "purchase", "amount": 12500}, context={"agent_id": "procurement-agent"},
|
|
35
|
+
evidence={"vendor_approved": True})
|
|
36
|
+
|
|
37
|
+
r.gate_decision # "ESCALATE" (the Gate's own call, kept in records[0])
|
|
38
|
+
r.decision # "ACT" / "BLOCK" / "ESCALATE" after Flow
|
|
39
|
+
r.records # (gate record, linked Flow RESOLUTION record with Flow's own JGR inside)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
| Gate | Flow called? | Result |
|
|
43
|
+
|---|---|---|
|
|
44
|
+
| ACT | no | ACT |
|
|
45
|
+
| BLOCK | no (a resolver can never loosen a BLOCK) | BLOCK |
|
|
46
|
+
| ESCALATE (human approval / user confirmation / evaluation failure) | no | ESCALATE |
|
|
47
|
+
| ESCALATE (anything else) | yes | Flow `REACH` → ACT (high/medium confidence), `SKIP` → BLOCK, `WAIT` / `RESEARCH_FIRST` / `ESCALATE` → ESCALATE |
|
|
48
|
+
|
|
49
|
+
Flow unreachable, out of credits (402), rate-limited (429), slow (timeout, default 10 s), or degraded output → the
|
|
50
|
+
result stays **ESCALATE** and a linked RESOLUTION record says why. Card, account, routing, IBAN, SSN, password,
|
|
51
|
+
token and key fields are redacted before anything leaves your process (`redact_keys=` to extend).
|
|
52
|
+
|
|
53
|
+
Report how a Flow judgment turned out (free; improves Flow's calibration):
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
FlowResolver().report_outcome(r.resolution["resolver"]["reference"], "CORRECT") # or WRONG / PARTIAL
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Options: `base_url` (default `https://resolve.flowinfo.co`, env `FLOW_RESOLVER_URL`), `timeout`,
|
|
60
|
+
`accept_act_confidence` (default `("high", "medium")`), `redact_keys`, `include_context`, `include_evidence`.
|
|
61
|
+
|
|
62
|
+
Apache-2.0. The judgment itself runs on Flow's service; this package is only the client.
|
abe_flow-0.1.0/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# abe-flow
|
|
2
|
+
|
|
3
|
+
Send **only the actions Abe escalates** to Flow's judgment service, and get back a decision, a reason and a
|
|
4
|
+
falsifiable record.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install abe-ai abe-flow
|
|
8
|
+
export FLOW_API_KEY=fjp_live_... # https://fjp.flowinfo.co
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import os
|
|
13
|
+
from abe import Abe
|
|
14
|
+
from abe_flow import FlowResolver
|
|
15
|
+
|
|
16
|
+
abe = Abe("abe-policy.yaml", resolver=FlowResolver(api_key=os.environ["FLOW_API_KEY"]))
|
|
17
|
+
r = abe.check(action={"type": "purchase", "amount": 12500}, context={"agent_id": "procurement-agent"},
|
|
18
|
+
evidence={"vendor_approved": True})
|
|
19
|
+
|
|
20
|
+
r.gate_decision # "ESCALATE" (the Gate's own call, kept in records[0])
|
|
21
|
+
r.decision # "ACT" / "BLOCK" / "ESCALATE" after Flow
|
|
22
|
+
r.records # (gate record, linked Flow RESOLUTION record with Flow's own JGR inside)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
| Gate | Flow called? | Result |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| ACT | no | ACT |
|
|
28
|
+
| BLOCK | no (a resolver can never loosen a BLOCK) | BLOCK |
|
|
29
|
+
| ESCALATE (human approval / user confirmation / evaluation failure) | no | ESCALATE |
|
|
30
|
+
| ESCALATE (anything else) | yes | Flow `REACH` → ACT (high/medium confidence), `SKIP` → BLOCK, `WAIT` / `RESEARCH_FIRST` / `ESCALATE` → ESCALATE |
|
|
31
|
+
|
|
32
|
+
Flow unreachable, out of credits (402), rate-limited (429), slow (timeout, default 10 s), or degraded output → the
|
|
33
|
+
result stays **ESCALATE** and a linked RESOLUTION record says why. Card, account, routing, IBAN, SSN, password,
|
|
34
|
+
token and key fields are redacted before anything leaves your process (`redact_keys=` to extend).
|
|
35
|
+
|
|
36
|
+
Report how a Flow judgment turned out (free; improves Flow's calibration):
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
FlowResolver().report_outcome(r.resolution["resolver"]["reference"], "CORRECT") # or WRONG / PARTIAL
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Options: `base_url` (default `https://resolve.flowinfo.co`, env `FLOW_RESOLVER_URL`), `timeout`,
|
|
43
|
+
`accept_act_confidence` (default `("high", "medium")`), `redact_keys`, `include_context`, `include_evidence`.
|
|
44
|
+
|
|
45
|
+
Apache-2.0. The judgment itself runs on Flow's service; this package is only the client.
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""abe-flow — send FJP Gate escalations to Flow's judgment service.
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from abe import Gate
|
|
5
|
+
from abe_flow import FlowResolver
|
|
6
|
+
|
|
7
|
+
gate = Gate("abe-policy.yaml", resolver=FlowResolver(api_key=os.environ["FLOW_API_KEY"]))
|
|
8
|
+
|
|
9
|
+
Behavior:
|
|
10
|
+
Gate -> ACT return ACT (Flow is never called)
|
|
11
|
+
Gate -> BLOCK return BLOCK (Flow is never called; a resolver can never loosen a BLOCK)
|
|
12
|
+
Gate -> ESCALATE call Flow's judge, map its verb, append a linked RESOLUTION record
|
|
13
|
+
|
|
14
|
+
Only escalations create Flow cost. If Flow is unreachable, out of credits, rate-limited, slow, or returns degraded
|
|
15
|
+
output, the result simply stays ESCALATE. Escalations marked HUMAN_APPROVAL_REQUIRED, USER_CONFIRMATION_REQUIRED or
|
|
16
|
+
EVALUATION_FAILURE are never sent (policy: resolver.not_resolvable).
|
|
17
|
+
|
|
18
|
+
Flow verb -> Gate decision:
|
|
19
|
+
REACH -> ACT (only when Flow's confidence is in accept_act_confidence; default high, medium)
|
|
20
|
+
SKIP -> BLOCK
|
|
21
|
+
WAIT -> ESCALATE (not now; Flow's counter-signal says what would change it)
|
|
22
|
+
RESEARCH_FIRST -> ESCALATE (gather the evidence Flow names, then check again)
|
|
23
|
+
ESCALATE -> ESCALATE (a human should decide)
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import urllib.error
|
|
32
|
+
import urllib.request
|
|
33
|
+
from typing import Callable, Iterable
|
|
34
|
+
|
|
35
|
+
from abe import Resolution
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
38
|
+
|
|
39
|
+
DEFAULT_BASE_URL = "https://resolve.flowinfo.co"
|
|
40
|
+
VERB_TO_DECISION = {"REACH": "ACT", "SKIP": "BLOCK", "WAIT": "ESCALATE", "RESEARCH_FIRST": "ESCALATE",
|
|
41
|
+
"ESCALATE": "ESCALATE"}
|
|
42
|
+
CONFIDENCE_VALUE = {"high": 0.80, "medium": 0.55, "low": 0.30} # same constants as the Flow resolver's JGRs
|
|
43
|
+
DEFAULT_REDACT = ("card_number", "cvv", "cvc", "account_number", "routing_number", "iban", "ssn", "password",
|
|
44
|
+
"secret", "api_key", "token", "authorization", "private_key")
|
|
45
|
+
MAX_CONTEXT = 19_000
|
|
46
|
+
MAX_RESPONSE = 1_048_576
|
|
47
|
+
_ATTRIBUTION = re.compile(r"\s*(\(\s*per FJP[^)]*\)|—\s*Judged by FJP\.?)\s*$", re.IGNORECASE)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class FlowError(Exception):
|
|
51
|
+
"""Flow could not be reached or refused the call. The Gate turns this into ESCALATE (unavailable)."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, message: str, status: int | None = None):
|
|
54
|
+
super().__init__(message)
|
|
55
|
+
self.status = status
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _strip_attribution(text: str) -> str:
|
|
59
|
+
prev, text = None, (text or "").strip()
|
|
60
|
+
while prev != text:
|
|
61
|
+
prev, text = text, _ATTRIBUTION.sub("", text).strip()
|
|
62
|
+
return text
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def redact(value, keys: Iterable[str]):
|
|
66
|
+
"""Remove fields whose name contains any redaction key (case-insensitive), recursively."""
|
|
67
|
+
ks = tuple(k.lower() for k in keys)
|
|
68
|
+
if isinstance(value, dict):
|
|
69
|
+
return {k: ("[REDACTED]" if any(x in k.lower() for x in ks) else redact(v, ks)) for k, v in value.items()}
|
|
70
|
+
if isinstance(value, list):
|
|
71
|
+
return [redact(v, ks) for v in value]
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
Transport = Callable[[str, dict, bytes, float], tuple[int, bytes]]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _urllib_transport(url: str, headers: dict, body: bytes, timeout: float) -> tuple[int, bytes]:
|
|
79
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
80
|
+
try:
|
|
81
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - https base URL enforced
|
|
82
|
+
return resp.status, resp.read(MAX_RESPONSE + 1)
|
|
83
|
+
except urllib.error.HTTPError as e:
|
|
84
|
+
return e.code, e.read(MAX_RESPONSE + 1)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class FlowResolver:
|
|
88
|
+
"""Resolver that asks Flow's judgment service about actions the Gate escalated."""
|
|
89
|
+
|
|
90
|
+
implementation = "abe-flow"
|
|
91
|
+
|
|
92
|
+
def __init__(self, api_key: str | None = None, *, base_url: str | None = None, timeout: float = 10.0,
|
|
93
|
+
redact_keys: Iterable[str] = DEFAULT_REDACT, accept_act_confidence: Iterable[str] = ("high", "medium"),
|
|
94
|
+
transport: Transport | None = None, include_context: bool = True, include_evidence: bool = True):
|
|
95
|
+
self.api_key = api_key or os.environ.get("FLOW_API_KEY") or os.environ.get("FJP_API_KEY")
|
|
96
|
+
if not self.api_key:
|
|
97
|
+
raise ValueError("FlowResolver needs an API key (api_key=... or FLOW_API_KEY)")
|
|
98
|
+
self.base_url = (base_url or os.environ.get("FLOW_RESOLVER_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
99
|
+
if not (self.base_url.startswith("https://") or self.base_url.startswith("http://127.0.0.1")
|
|
100
|
+
or self.base_url.startswith("http://localhost")):
|
|
101
|
+
raise ValueError("base_url must be https:// (http only for localhost testing)")
|
|
102
|
+
self.timeout = timeout
|
|
103
|
+
self.redact_keys = tuple(redact_keys)
|
|
104
|
+
self.accept_act_confidence = set(accept_act_confidence)
|
|
105
|
+
self.transport = transport or _urllib_transport
|
|
106
|
+
self.include_context, self.include_evidence = include_context, include_evidence
|
|
107
|
+
|
|
108
|
+
# ------------------------------------------------------------ request building
|
|
109
|
+
|
|
110
|
+
def build_judge_request(self, request: dict, gate_result) -> dict:
|
|
111
|
+
rec = gate_result.record
|
|
112
|
+
safe = redact(request, self.redact_keys)
|
|
113
|
+
parts = [
|
|
114
|
+
"PRE-EXECUTION JUDGMENT (FJP Gate escalation).",
|
|
115
|
+
f"The agent's proposed action passed hard policy limits but the Gate escalated it: {rec.reason_code}"
|
|
116
|
+
f" (all reasons: {', '.join(rec.reason_codes)}). Matched: {', '.join(rec.matched_rules) or 'none'}.",
|
|
117
|
+
"Question: is this permitted action justified by the evidence, intent and context? "
|
|
118
|
+
"REACH = proceed, SKIP = do not proceed, WAIT = not now, RESEARCH_FIRST = establish more first, "
|
|
119
|
+
"ESCALATE = a human must decide.",
|
|
120
|
+
f"Actor: {json.dumps(safe.get('actor', {}), ensure_ascii=False)}",
|
|
121
|
+
f"Proposed action: {json.dumps({k: v for k, v in safe.get('action', {}).items()}, ensure_ascii=False)}",
|
|
122
|
+
f"Risk: {gate_result.risk_level}. Irreversibility: {gate_result.irreversibility_level}. "
|
|
123
|
+
f"Agent-supplied confidence (uncalibrated): {safe.get('confidence', 'not supplied')}.",
|
|
124
|
+
]
|
|
125
|
+
if gate_result.missing_evidence:
|
|
126
|
+
parts.append(f"Missing evidence: {', '.join(gate_result.missing_evidence)}.")
|
|
127
|
+
if self.include_evidence and safe.get("evidence"):
|
|
128
|
+
parts.append(f"Evidence: {json.dumps(safe['evidence'], ensure_ascii=False)}")
|
|
129
|
+
if self.include_context and safe.get("context"):
|
|
130
|
+
parts.append(f"Context: {json.dumps(safe['context'], ensure_ascii=False)}")
|
|
131
|
+
context = "\n".join(parts)
|
|
132
|
+
if len(context) > MAX_CONTEXT:
|
|
133
|
+
context = context[: MAX_CONTEXT - 1] + "…"
|
|
134
|
+
pol = rec.policy
|
|
135
|
+
return {
|
|
136
|
+
"context": context,
|
|
137
|
+
"background": f"Policy {pol.id or 'unnamed'} version {pol.version or 'unversioned'} ({pol.hash}).",
|
|
138
|
+
"sources": [f"fjp:gate-record:{rec.record_id}", f"fjp:policy:{pol.hash}", f"fjp:request:{rec.request_id}"],
|
|
139
|
+
"observed_at": rec.evaluation_time,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
def idempotency_key(self, gate_result) -> str:
|
|
143
|
+
rec = gate_result.record
|
|
144
|
+
return hashlib.sha256(f"{rec.request_id}|{rec.request_hash}|{rec.policy.hash}".encode()).hexdigest()
|
|
145
|
+
|
|
146
|
+
# ------------------------------------------------------------ Resolver interface
|
|
147
|
+
|
|
148
|
+
def resolve(self, request: dict, gate_result) -> Resolution:
|
|
149
|
+
body = json.dumps(self.build_judge_request(request, gate_result), ensure_ascii=False).encode("utf-8")
|
|
150
|
+
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json",
|
|
151
|
+
"Accept": "application/json", "X-Idempotency-Key": self.idempotency_key(gate_result),
|
|
152
|
+
"User-Agent": f"{self.implementation}/{__version__}"}
|
|
153
|
+
try:
|
|
154
|
+
status, raw = self.transport(f"{self.base_url}/api/v1/tools/judge", headers, body, self.timeout)
|
|
155
|
+
except Exception as e: # noqa: BLE001 - network failures, timeouts
|
|
156
|
+
raise FlowError(f"Flow unreachable: {type(e).__name__}: {e}") from e
|
|
157
|
+
if len(raw) > MAX_RESPONSE:
|
|
158
|
+
raise FlowError("Flow response too large")
|
|
159
|
+
if status == 401:
|
|
160
|
+
raise FlowError("Flow rejected the API key (401)", status)
|
|
161
|
+
if status == 402:
|
|
162
|
+
raise FlowError("Flow account is out of credits (402)", status)
|
|
163
|
+
if status == 429:
|
|
164
|
+
raise FlowError("Flow rate limit reached (429)", status)
|
|
165
|
+
if status != 200:
|
|
166
|
+
raise FlowError(f"Flow returned HTTP {status}", status)
|
|
167
|
+
try:
|
|
168
|
+
out = json.loads(raw)
|
|
169
|
+
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
|
170
|
+
raise FlowError("Flow returned invalid JSON") from e
|
|
171
|
+
return self.to_resolution(out)
|
|
172
|
+
|
|
173
|
+
def to_resolution(self, out: dict) -> Resolution:
|
|
174
|
+
verb = out.get("verb")
|
|
175
|
+
if verb not in VERB_TO_DECISION:
|
|
176
|
+
raise FlowError(f"Flow returned an unknown verb {verb!r}")
|
|
177
|
+
bucket = out.get("confidence") if out.get("confidence") in CONFIDENCE_VALUE else "low"
|
|
178
|
+
jgr = out.get("jgr") if isinstance(out.get("jgr"), dict) else None
|
|
179
|
+
framing = str(out.get("framing") or "").strip()
|
|
180
|
+
counter = _strip_attribution(str(out.get("counter_signal") or ""))
|
|
181
|
+
evidence = {"flow_verb": verb, "flow_timing": out.get("timing"), "flow_confidence": bucket,
|
|
182
|
+
"flow_request_id": out.get("request_id")}
|
|
183
|
+
ref = out.get("request_id")
|
|
184
|
+
|
|
185
|
+
if jgr is None:
|
|
186
|
+
# Degraded output: never act on it (fjp-resolve R3).
|
|
187
|
+
return Resolution(decision="ESCALATE", reason="Flow returned degraded output without a record; not acted on.",
|
|
188
|
+
reason_code="flow.degraded", confidence=None, resolver_type="FLOW",
|
|
189
|
+
implementation=self.implementation, implementation_version=__version__,
|
|
190
|
+
reference=ref, evidence=evidence)
|
|
191
|
+
|
|
192
|
+
decision = VERB_TO_DECISION[verb]
|
|
193
|
+
reason = framing or f"Flow verb {verb}."
|
|
194
|
+
if decision == "ACT" and bucket not in self.accept_act_confidence:
|
|
195
|
+
decision = "ESCALATE"
|
|
196
|
+
reason = f"Flow leaned REACH with {bucket} confidence, below this resolver's bar; escalating. " + reason
|
|
197
|
+
conf = jgr.get("judgment", {}).get("confidence")
|
|
198
|
+
if not isinstance(conf, (int, float)) or isinstance(conf, bool):
|
|
199
|
+
conf = CONFIDENCE_VALUE[bucket]
|
|
200
|
+
falsifier = (jgr.get("falsifier") or {}).get("condition") or counter
|
|
201
|
+
return Resolution(decision=decision, reason=reason, reason_code=f"flow.{verb.lower()}",
|
|
202
|
+
confidence=float(conf), falsifiers=tuple(x for x in (falsifier,) if x),
|
|
203
|
+
resolver_type="FLOW", implementation=self.implementation,
|
|
204
|
+
implementation_version=__version__, reference=ref, evidence=evidence, external_record=jgr)
|
|
205
|
+
|
|
206
|
+
# ------------------------------------------------------------ outcomes (free on Flow)
|
|
207
|
+
|
|
208
|
+
def report_outcome(self, flow_request_id: str, outcome: str, notes: str | None = None) -> dict:
|
|
209
|
+
"""Tell Flow how its judgment turned out: CORRECT | WRONG | PARTIAL. Free; feeds Flow's calibration."""
|
|
210
|
+
if outcome not in ("CORRECT", "WRONG", "PARTIAL"):
|
|
211
|
+
raise ValueError("outcome must be CORRECT, WRONG or PARTIAL")
|
|
212
|
+
body = json.dumps({"request_id": flow_request_id, "outcome": outcome, "notes": notes}).encode()
|
|
213
|
+
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json",
|
|
214
|
+
"X-Idempotency-Key": hashlib.sha256(f"{flow_request_id}|{outcome}".encode()).hexdigest()}
|
|
215
|
+
status, raw = self.transport(f"{self.base_url}/api/v1/outcome", headers, body, self.timeout)
|
|
216
|
+
if status != 200:
|
|
217
|
+
raise FlowError(f"Flow outcome report failed: HTTP {status}", status)
|
|
218
|
+
return json.loads(raw)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
__all__ = ["FlowResolver", "FlowError", "VERB_TO_DECISION", "redact", "__version__"]
|
|
File without changes
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: abe-flow
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send Abe escalations to Flow's judgment service (resolve.flowinfo.co). Only ESCALATE results are sent.
|
|
5
|
+
Author-email: Flow Information Systems <flowinfosystems@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://fjp.flowinfo.co/abe
|
|
8
|
+
Project-URL: Source, https://github.com/flowinfosystems-index/abe
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: NOTICE
|
|
13
|
+
Requires-Dist: abe-ai<0.2,>=0.1.0
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# abe-flow
|
|
19
|
+
|
|
20
|
+
Send **only the actions Abe escalates** to Flow's judgment service, and get back a decision, a reason and a
|
|
21
|
+
falsifiable record.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install abe-ai abe-flow
|
|
25
|
+
export FLOW_API_KEY=fjp_live_... # https://fjp.flowinfo.co
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import os
|
|
30
|
+
from abe import Abe
|
|
31
|
+
from abe_flow import FlowResolver
|
|
32
|
+
|
|
33
|
+
abe = Abe("abe-policy.yaml", resolver=FlowResolver(api_key=os.environ["FLOW_API_KEY"]))
|
|
34
|
+
r = abe.check(action={"type": "purchase", "amount": 12500}, context={"agent_id": "procurement-agent"},
|
|
35
|
+
evidence={"vendor_approved": True})
|
|
36
|
+
|
|
37
|
+
r.gate_decision # "ESCALATE" (the Gate's own call, kept in records[0])
|
|
38
|
+
r.decision # "ACT" / "BLOCK" / "ESCALATE" after Flow
|
|
39
|
+
r.records # (gate record, linked Flow RESOLUTION record with Flow's own JGR inside)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
| Gate | Flow called? | Result |
|
|
43
|
+
|---|---|---|
|
|
44
|
+
| ACT | no | ACT |
|
|
45
|
+
| BLOCK | no (a resolver can never loosen a BLOCK) | BLOCK |
|
|
46
|
+
| ESCALATE (human approval / user confirmation / evaluation failure) | no | ESCALATE |
|
|
47
|
+
| ESCALATE (anything else) | yes | Flow `REACH` → ACT (high/medium confidence), `SKIP` → BLOCK, `WAIT` / `RESEARCH_FIRST` / `ESCALATE` → ESCALATE |
|
|
48
|
+
|
|
49
|
+
Flow unreachable, out of credits (402), rate-limited (429), slow (timeout, default 10 s), or degraded output → the
|
|
50
|
+
result stays **ESCALATE** and a linked RESOLUTION record says why. Card, account, routing, IBAN, SSN, password,
|
|
51
|
+
token and key fields are redacted before anything leaves your process (`redact_keys=` to extend).
|
|
52
|
+
|
|
53
|
+
Report how a Flow judgment turned out (free; improves Flow's calibration):
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
FlowResolver().report_outcome(r.resolution["resolver"]["reference"], "CORRECT") # or WRONG / PARTIAL
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Options: `base_url` (default `https://resolve.flowinfo.co`, env `FLOW_RESOLVER_URL`), `timeout`,
|
|
60
|
+
`accept_act_confidence` (default `("high", "medium")`), `redact_keys`, `include_context`, `include_evidence`.
|
|
61
|
+
|
|
62
|
+
Apache-2.0. The judgment itself runs on Flow's service; this package is only the client.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
abe_flow/__init__.py
|
|
6
|
+
abe_flow/py.typed
|
|
7
|
+
abe_flow.egg-info/PKG-INFO
|
|
8
|
+
abe_flow.egg-info/SOURCES.txt
|
|
9
|
+
abe_flow.egg-info/dependency_links.txt
|
|
10
|
+
abe_flow.egg-info/requires.txt
|
|
11
|
+
abe_flow.egg-info/top_level.txt
|
|
12
|
+
tests/test_flow_resolver.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
abe_flow
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "abe-flow"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Send Abe escalations to Flow's judgment service (resolve.flowinfo.co). Only ESCALATE results are sent."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Flow Information Systems", email = "flowinfosystems@gmail.com" }]
|
|
13
|
+
dependencies = ["abe-ai>=0.1.0,<0.2"]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
dev = ["pytest>=8"]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://fjp.flowinfo.co/abe"
|
|
20
|
+
Source = "https://github.com/flowinfosystems-index/abe"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools]
|
|
23
|
+
packages = ["abe_flow"]
|
|
24
|
+
license-files = ["LICENSE", "NOTICE"]
|
abe_flow-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""FlowResolver against a fake transport that mimics resolve.flowinfo.co /api/v1/tools/judge."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from abe import Gate, verify_hash
|
|
8
|
+
from abe.conformance import fixtures_dir, fjp_conf, no_network
|
|
9
|
+
from abe.stores import MemoryStore
|
|
10
|
+
from abe_flow import FlowResolver, redact
|
|
11
|
+
|
|
12
|
+
STANDARD = os.path.join(fixtures_dir(), "policies", "standard.yaml")
|
|
13
|
+
ESC = {"actor": {"agent_id": "procurement-agent"}, "action": {"type": "purchase", "amount": 25000, "vendor": "Acme",
|
|
14
|
+
"card_number": "4111111111111111"},
|
|
15
|
+
"evidence": {"vendor_approved": True, "budget_remaining": 90000}, "confidence": 0.95}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def flow_reply(verb="REACH", confidence="high", jgr=True, request_id="call_123"):
|
|
19
|
+
out = {"verb": verb, "framing": "Budget headroom and vendor history support this. (per FJP judgment)",
|
|
20
|
+
"timing": "now", "confidence": confidence,
|
|
21
|
+
"counter_signal": "Vendor misses the Oct 15 delivery date — Judged by FJP.", "request_id": request_id}
|
|
22
|
+
if jgr:
|
|
23
|
+
out["jgr"] = {"record_id": request_id, "timestamp": "2026-09-29T16:00:00Z",
|
|
24
|
+
"signal": {"id": f"sig-{request_id}", "description": "x", "sources": ["fjp:gate-record:x"],
|
|
25
|
+
"observed_at": "2026-09-29T16:00:00Z"},
|
|
26
|
+
"judgment": {"id": f"jud-{request_id}", "assessment": "ok", "confidence": 0.8,
|
|
27
|
+
"signal_ref": f"sig-{request_id}"},
|
|
28
|
+
"action": {"directive": f"{verb} (timing: now)", "judgment_ref": f"jud-{request_id}"},
|
|
29
|
+
"falsifier": {"condition": "Vendor misses the Oct 15 delivery date.", "checkable": True,
|
|
30
|
+
"status": "open"}}
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FakeFlow:
|
|
35
|
+
def __init__(self, status=200, body=None, exc=None):
|
|
36
|
+
self.status, self.body, self.exc, self.calls = status, body if body is not None else flow_reply(), exc, []
|
|
37
|
+
|
|
38
|
+
def __call__(self, url, headers, body, timeout):
|
|
39
|
+
self.calls.append((url, headers, json.loads(body), timeout))
|
|
40
|
+
if self.exc:
|
|
41
|
+
raise self.exc
|
|
42
|
+
return self.status, json.dumps(self.body).encode()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def make(fake, **kw):
|
|
46
|
+
return Gate(STANDARD, resolver=FlowResolver(api_key="fjp_test_x", transport=fake, **kw), store=MemoryStore())
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_escalate_resolved_to_act_with_linked_records():
|
|
50
|
+
fake = FakeFlow()
|
|
51
|
+
r = make(fake).check(ESC)
|
|
52
|
+
assert r.gate_decision == "ESCALATE" and r.decision == "ACT"
|
|
53
|
+
url, headers, body, _ = fake.calls[0]
|
|
54
|
+
assert url == "https://resolve.flowinfo.co/api/v1/tools/judge"
|
|
55
|
+
assert headers["Authorization"] == "Bearer fjp_test_x" and len(headers["X-Idempotency-Key"]) == 64
|
|
56
|
+
assert "4111111111111111" not in body["context"] and "[REDACTED]" in body["context"]
|
|
57
|
+
assert body["sources"][0] == f"fjp:gate-record:{r.records[0].record_id}"
|
|
58
|
+
gate_rec, res = r.records
|
|
59
|
+
assert res.parent_record_id == gate_rec.record_id and res.resolver.type == "FLOW"
|
|
60
|
+
assert res.reason_code == "flow.reach" and res.external_record.record_id == "call_123"
|
|
61
|
+
assert res.judgment_detail.falsifiers[0] == "Vendor misses the Oct 15 delivery date."
|
|
62
|
+
assert verify_hash(res) and fjp_conf.conforms(fjp_conf.evaluate(res.to_dict(), 2))
|
|
63
|
+
assert gate_rec.decision == "ESCALATE" # the Gate record is never overwritten
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.mark.parametrize("verb,decision", [("SKIP", "BLOCK"), ("WAIT", "ESCALATE"), ("RESEARCH_FIRST", "ESCALATE"),
|
|
67
|
+
("ESCALATE", "ESCALATE")])
|
|
68
|
+
def test_verb_mapping(verb, decision):
|
|
69
|
+
assert make(FakeFlow(body=flow_reply(verb))).check(ESC).decision == decision
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_low_confidence_reach_stays_escalate():
|
|
73
|
+
r = make(FakeFlow(body=flow_reply("REACH", "low"))).check(ESC)
|
|
74
|
+
assert r.decision == "ESCALATE" and "below this resolver's bar" in r.resolution["reason"]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_degraded_output_never_acts():
|
|
78
|
+
r = make(FakeFlow(body=flow_reply("REACH", jgr=False))).check(ESC)
|
|
79
|
+
assert r.decision == "ESCALATE" and r.reason_code == "flow.degraded"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.mark.parametrize("status", [401, 402, 429, 500, 503])
|
|
83
|
+
def test_flow_errors_stay_escalate(status):
|
|
84
|
+
r = make(FakeFlow(status=status, body={"error": "x"})).check(ESC)
|
|
85
|
+
assert r.decision == "ESCALATE" and r.resolution["status"] == "unavailable"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_flow_unreachable_offline():
|
|
89
|
+
# Real urllib transport with the network blocked: the Gate must still answer.
|
|
90
|
+
with no_network():
|
|
91
|
+
g = Gate(STANDARD, resolver=FlowResolver(api_key="fjp_test_x", timeout=1))
|
|
92
|
+
r = g.check(ESC)
|
|
93
|
+
assert r.decision == "ESCALATE" and r.resolution["status"] == "unavailable"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_flow_never_called_for_act_or_block():
|
|
97
|
+
fake = FakeFlow()
|
|
98
|
+
g = make(fake)
|
|
99
|
+
g.check({"actor": {"agent_id": "procurement-agent"}, "action": {"type": "purchase", "amount": 100}, "confidence": 0.95})
|
|
100
|
+
g.check({"actor": {"agent_id": "procurement-agent"}, "action": {"type": "purchase", "amount": 500000}})
|
|
101
|
+
g.check({"actor": {"agent_id": "support-agent"}, "action": {"type": "refund", "amount": 5}}) # evidence missing -> sent
|
|
102
|
+
assert len(fake.calls) == 1
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_bad_verb_and_bad_json():
|
|
106
|
+
assert make(FakeFlow(body={"verb": "MAYBE"})).check(ESC).resolution["status"] == "unavailable"
|
|
107
|
+
|
|
108
|
+
def junk(url, headers, body, timeout):
|
|
109
|
+
return 200, b"<html>"
|
|
110
|
+
assert make(junk).check(ESC).resolution["status"] == "unavailable"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_redact_nested():
|
|
114
|
+
assert redact({"a": {"Card_Number": "1", "ok": [{"api_key": "k", "v": 1}]}}, ["card_number", "api_key"]) == \
|
|
115
|
+
{"a": {"Card_Number": "[REDACTED]", "ok": [{"api_key": "[REDACTED]", "v": 1}]}}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_requires_key_and_https(monkeypatch):
|
|
119
|
+
monkeypatch.delenv("FLOW_API_KEY", raising=False)
|
|
120
|
+
monkeypatch.delenv("FJP_API_KEY", raising=False)
|
|
121
|
+
with pytest.raises(ValueError):
|
|
122
|
+
FlowResolver()
|
|
123
|
+
with pytest.raises(ValueError):
|
|
124
|
+
FlowResolver(api_key="k", base_url="http://resolve.flowinfo.co")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_report_outcome():
|
|
128
|
+
fake = FakeFlow(body={"acknowledged": True, "feedback_id": "f1"})
|
|
129
|
+
res = FlowResolver(api_key="k", transport=fake)
|
|
130
|
+
assert res.report_outcome("call_123", "CORRECT")["acknowledged"] is True
|
|
131
|
+
assert fake.calls[0][0].endswith("/api/v1/outcome")
|
|
132
|
+
with pytest.raises(ValueError):
|
|
133
|
+
res.report_outcome("call_123", "GREAT")
|