b3-prosaic-runtime 0.8.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.
Files changed (46) hide show
  1. b3_prosaic_runtime-0.8.1.dist-info/METADATA +650 -0
  2. b3_prosaic_runtime-0.8.1.dist-info/RECORD +46 -0
  3. b3_prosaic_runtime-0.8.1.dist-info/WHEEL +5 -0
  4. b3_prosaic_runtime-0.8.1.dist-info/entry_points.txt +2 -0
  5. b3_prosaic_runtime-0.8.1.dist-info/licenses/LICENSE +202 -0
  6. b3_prosaic_runtime-0.8.1.dist-info/licenses/LICENSE-MIT +21 -0
  7. b3_prosaic_runtime-0.8.1.dist-info/licenses/NOTICE.md +16 -0
  8. b3_prosaic_runtime-0.8.1.dist-info/top_level.txt +1 -0
  9. prosaic_runtime/__init__.py +27 -0
  10. prosaic_runtime/accounting.py +256 -0
  11. prosaic_runtime/accounting_capture.py +275 -0
  12. prosaic_runtime/admission.py +57 -0
  13. prosaic_runtime/anthropic.py +205 -0
  14. prosaic_runtime/anthropic_stream.py +179 -0
  15. prosaic_runtime/anthropic_usage.py +96 -0
  16. prosaic_runtime/artifacts.py +56 -0
  17. prosaic_runtime/budgets.py +67 -0
  18. prosaic_runtime/cli.py +153 -0
  19. prosaic_runtime/cli_tools.py +313 -0
  20. prosaic_runtime/config.py +127 -0
  21. prosaic_runtime/conformance.py +314 -0
  22. prosaic_runtime/console.py +37 -0
  23. prosaic_runtime/diagnostics.py +132 -0
  24. prosaic_runtime/events.py +56 -0
  25. prosaic_runtime/execution.py +442 -0
  26. prosaic_runtime/http_bounds.py +66 -0
  27. prosaic_runtime/openai_compatible.py +2373 -0
  28. prosaic_runtime/openai_compatible_compaction.py +219 -0
  29. prosaic_runtime/openai_compatible_filters.py +147 -0
  30. prosaic_runtime/openai_compatible_progress.py +405 -0
  31. prosaic_runtime/openai_compatible_transcript.py +79 -0
  32. prosaic_runtime/operation_context.py +39 -0
  33. prosaic_runtime/policy.py +50 -0
  34. prosaic_runtime/provider_types.py +19 -0
  35. prosaic_runtime/runtime.py +562 -0
  36. prosaic_runtime/sandbox.py +179 -0
  37. prosaic_runtime/smoke_prose/pilot.md +7 -0
  38. prosaic_runtime/smoke_prose/subagents/native-summarizer.md +10 -0
  39. prosaic_runtime/smoke_prose/subagents/reviewer.md +22 -0
  40. prosaic_runtime/smoke_prose/subagents/summarizer.md +11 -0
  41. prosaic_runtime/structured_tools.py +193 -0
  42. prosaic_runtime/telemetry.py +128 -0
  43. prosaic_runtime/tool_effects.py +112 -0
  44. prosaic_runtime/tool_registry.py +36 -0
  45. prosaic_runtime/tools.py +261 -0
  46. prosaic_runtime/types.py +23 -0
@@ -0,0 +1,46 @@
1
+ b3_prosaic_runtime-0.8.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
2
+ b3_prosaic_runtime-0.8.1.dist-info/licenses/LICENSE-MIT,sha256=6-Ji6m-C8v-MFxn1ZLt6SIL3zMZAUBPIpmvvcxb2fBk,1068
3
+ b3_prosaic_runtime-0.8.1.dist-info/licenses/NOTICE.md,sha256=uWefZhATihgWJw60ZgXk3VCLRwgjKxBvdL5K7f_Q1VM,1313
4
+ prosaic_runtime/__init__.py,sha256=Z_EpHVuQa4UfaYh-mOHD58pThRAajFjw_cpxIMR2lSc,1432
5
+ prosaic_runtime/accounting.py,sha256=RSZUUSANc-8SbMoEofQ6J8teyv6l2QoG8dBvTdaw2wc,11407
6
+ prosaic_runtime/accounting_capture.py,sha256=io2XEFmmHzbgXcj5U1SGJjeQ7Dqxj-UR1ktym1a_-Sc,11121
7
+ prosaic_runtime/admission.py,sha256=E3XZE4R7U4TUNWBT1BOarXfx0Wz102qY3AsaamAl0mA,3291
8
+ prosaic_runtime/anthropic.py,sha256=00tbgn9FHs38yCH6Lh5GgY9XFiK18zhCf_2HIjyRiPs,10407
9
+ prosaic_runtime/anthropic_stream.py,sha256=lDoyQtczi_HgPd04pelJaBGDw4oVz1ePriPSFT9qegU,8347
10
+ prosaic_runtime/anthropic_usage.py,sha256=zg1_Nc3kpJfX74e2lCkMmBI_Nclp1w5JAHdbg2xb6NA,3677
11
+ prosaic_runtime/artifacts.py,sha256=jgkgqbGu9tCzr_RyBhERd1jFRZTBiyduxhkn8-7TRGc,2631
12
+ prosaic_runtime/budgets.py,sha256=gLgFmRXKsYdCBx_DuqipVoL-ayT5ShSra1qQrzin9sQ,2629
13
+ prosaic_runtime/cli.py,sha256=HQkK8mIe8rK4IXTWuNlEGRz6AgVY7VJR87MO30zeByY,9865
14
+ prosaic_runtime/cli_tools.py,sha256=Uc8n8Cy5LWvV2dRlJolw0joswEG7uGdZFundnD9w4Ws,14060
15
+ prosaic_runtime/config.py,sha256=ZW31fkx2E6TiGBDeu98-DWpivSQal3kNWA8MumwQrm8,6421
16
+ prosaic_runtime/conformance.py,sha256=diffCzUNVQvJlRfTYXmXW5gOdXgOdTi1v9XUIIqiXXE,16730
17
+ prosaic_runtime/console.py,sha256=ziNUwpuptMW1ZrYFZ_h-NU9RFhep6vz6P3Y1PsJVuX8,1258
18
+ prosaic_runtime/diagnostics.py,sha256=zVZsISm8jx4o6g9QHW53X3R6q2fdEzmXf96pedJ5g9o,7860
19
+ prosaic_runtime/events.py,sha256=T0EPiUV8on6OI1iTLyNq9JLKjOV_LHd1udbO2fMC7Ms,1496
20
+ prosaic_runtime/execution.py,sha256=02xjuvXO4K74S0aIOUQW6BR6LIeucnZijgB6bDMa8dk,20913
21
+ prosaic_runtime/http_bounds.py,sha256=Ch69areRXWNMCDhVFeaioQnv0CEdBBhnvaSPxEGDfuY,2570
22
+ prosaic_runtime/openai_compatible.py,sha256=L_iF2-nj2O4uQEIXwv2BPoVwvz0oTxJfHP6DX0C60HA,84990
23
+ prosaic_runtime/openai_compatible_compaction.py,sha256=HUC3KKVuokHKG70WmHZ151tn7sCw_nI10jURn_K2dGU,7483
24
+ prosaic_runtime/openai_compatible_filters.py,sha256=9S6bXYPOiv-7sXPayiY_S7phlKdz282Wk5O9WsJRakg,3873
25
+ prosaic_runtime/openai_compatible_progress.py,sha256=ZEl6n_kn1-7JNJr9WRJNgApOx4HQbl0r3AjxI3z-z2U,13364
26
+ prosaic_runtime/openai_compatible_transcript.py,sha256=6Mp6CaPPd1bufUjw75aknCHiIjZlzupU6EvB_LgU6aA,2514
27
+ prosaic_runtime/operation_context.py,sha256=jiYDEX0LLzCEYwL-_FVB0owa8PGuzTqzcw0_6ABUd40,1237
28
+ prosaic_runtime/policy.py,sha256=Wfr8cSaF91z4Q8mgCSSE-MeP-PQjkltQXXhvw6rRKZw,2272
29
+ prosaic_runtime/provider_types.py,sha256=U1vYGqn3GLDoi2OmLfVRDSWcmHR3Y0jCOviHrytRJFk,528
30
+ prosaic_runtime/runtime.py,sha256=ZOonSqnh9mjWJfapAGXiEvhYFDx8gQoXecSUCvPF2_M,33092
31
+ prosaic_runtime/sandbox.py,sha256=BNMrPzr1_u2cr7jeQTmlhpEtwJZnWaPKXD0U8b_eGcg,9506
32
+ prosaic_runtime/structured_tools.py,sha256=piu2yPfDMq00_gCifpo0Sdp4bTP6saVq-j97J20QyGY,9721
33
+ prosaic_runtime/telemetry.py,sha256=hshegy3FU24svar58r7LGBlcU2xi1rRsBNoUPPAMIN4,5948
34
+ prosaic_runtime/tool_effects.py,sha256=-G4WbzOXjAlPFAEUnUWB0i3s8t5SHzkSj7wh5E2vGn0,4548
35
+ prosaic_runtime/tool_registry.py,sha256=JR_5zbuzv2VfydcoZ2JJ4bfLVZgegBPjzTS3oCjqnZc,1799
36
+ prosaic_runtime/tools.py,sha256=Kozy5A6ZB7NrBqASMB0D19jMwH0-XG77gHQjMFaV_ag,11212
37
+ prosaic_runtime/types.py,sha256=PQPBU0S7w91VUzvp_1ik7vQoN0MgT8zAuv65ly8MUvk,565
38
+ prosaic_runtime/smoke_prose/pilot.md,sha256=2ZC_INCU9WTLTymDyajNbJsPGZb28XcxSZe1J2I9XZ8,350
39
+ prosaic_runtime/smoke_prose/subagents/native-summarizer.md,sha256=7bp2CHAInaW5e7XdlyReMSyGbqCpoV8CsoOJvfwqhnc,289
40
+ prosaic_runtime/smoke_prose/subagents/reviewer.md,sha256=64cjTuMjsdp8u5bdibH66OksDrO9tw_cGRCY1rumcEw,849
41
+ prosaic_runtime/smoke_prose/subagents/summarizer.md,sha256=Ts7qoM9A9ABhdPgKncvTo_C2oJ_Hff2v_qLhYsateSk,252
42
+ b3_prosaic_runtime-0.8.1.dist-info/METADATA,sha256=3Mt8aY3PLVMqlgmt8OFQq9crBz98h-bqZZZl9pIPqyY,33279
43
+ b3_prosaic_runtime-0.8.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
44
+ b3_prosaic_runtime-0.8.1.dist-info/entry_points.txt,sha256=NIMgATR8tbHr7xZ8jjNdMYh0nAZ7bP5QiO6ymNYVX_M,61
45
+ b3_prosaic_runtime-0.8.1.dist-info/top_level.txt,sha256=xF2IIYWVhCdpoklAHne9oRuqHjeMRH_RC1ksW90VbRQ,16
46
+ b3_prosaic_runtime-0.8.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prosaic-runtime = prosaic_runtime.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Testimonial
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ # Provenance
2
+
3
+ The OpenAI-compatible transport, agent loop, compaction, path filters, progress helpers and transcript writer were extracted from B3Cognition/echelon at commit `3c606aa1ef9e44cc587ba122648392e0250f3094`.
4
+
5
+ The initial repository history preserves commits touching the five extracted implementation files and LICENSE, with `src/harness/ai_cli_backends/` renamed to `src/prosaic_runtime/`. Original author metadata and commit messages are retained. Commit IDs change because the history is filtered. The source repository and full context are available at https://github.com/B3Cognition/echelon.
6
+
7
+ Transport conformance tests were adapted from Echelon's `tests/unit/test_ai_cli_backend.py` at the same commit. Echelon-specific tools and control protocols remain in Echelon.
8
+
9
+ Prosaic Runtime is distributed under the Apache License, Version 2.0; see LICENSE.
10
+ Runtime integration and API work is Copyright (c) 2026 B3 Cognition.
11
+
12
+ The extracted code was originally distributed under MIT. Its original notice,
13
+ `Copyright (c) 2026 Testimonial`, and permission text are retained in LICENSE-MIT.
14
+ This historical attribution does not replace the project's Apache-2.0 license.
15
+ Third-party components retain their own licenses. Previously published versions
16
+ and tags retain the license notices shipped with them.
@@ -0,0 +1 @@
1
+ prosaic_runtime
@@ -0,0 +1,27 @@
1
+ """Execute neutral Prosaic artifacts with explicitly granted authority."""
2
+ __version__ = '0.8.1'
3
+
4
+ from .artifacts import ProsaicArtifact
5
+ from .config import EndpointConfig, RuntimeConfig, RunLimits, CliSandboxConfig
6
+ from .policy import RunPolicy
7
+ from .runtime import ProsaicRuntime
8
+ from .types import Result
9
+ from .tools import CustomTool, validate_custom_tools, custom_descriptors
10
+ from .admission import validate_execution_artifact
11
+ from .operation_context import InvocationScope, ToolExecutionContext
12
+ from .tool_effects import ToolClaim, ToolJournal, tool_journal_descriptor
13
+ from .telemetry import ObserverEmitter
14
+ from .conformance import evaluate_conformance
15
+
16
+ __all__ = ["ProsaicArtifact", "EndpointConfig", "RuntimeConfig", "RunLimits", "CliSandboxConfig", "RunPolicy", "ProsaicRuntime", "Result", "CustomTool"]
17
+ __all__ += ["validate_execution_artifact", "validate_custom_tools", "custom_descriptors"]
18
+
19
+ from .structured_tools import Completion, StructuredToolError, StructuredToolLoop, ToolRequest
20
+
21
+ __all__ += ["Completion", "StructuredToolError", "StructuredToolLoop", "ToolRequest"]
22
+
23
+ from .accounting import AccountingError, ExecutionContext, ResolvedContext, RateCard
24
+ __all__ += ["AccountingError", "ExecutionContext", "ResolvedContext", "RateCard"]
25
+ __all__ += ["InvocationScope", "ObserverEmitter"]
26
+ __all__ += ["ToolExecutionContext", "ToolClaim", "ToolJournal", "tool_journal_descriptor"]
27
+ __all__ += ["evaluate_conformance"]
@@ -0,0 +1,256 @@
1
+ """Trusted attribution and exact accounting contracts; no database dependency."""
2
+ from dataclasses import dataclass, replace, fields
3
+ from datetime import datetime, timezone
4
+ from decimal import Decimal, localcontext, ROUND_HALF_EVEN, InvalidOperation
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import uuid
9
+
10
+
11
+ class AccountingError(RuntimeError):
12
+ """Accounting failed; never retry a provider call because of this error."""
13
+
14
+
15
+ def identifier(value):
16
+ if type(value) is not str or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}', value):
17
+ raise ValueError('IDs must be bounded ASCII identifiers')
18
+ return value
19
+
20
+
21
+ def canonical(value):
22
+ return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False)
23
+
24
+
25
+ def fingerprint(value):
26
+ return hashlib.sha256(canonical(value).encode()).hexdigest()
27
+
28
+
29
+ def utc_now():
30
+ return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
31
+
32
+
33
+ ATTRIBUTION = ('application_id', 'tenant_id', 'billing_account_id')
34
+ OPTIONAL = ('actor_id', 'project_id', 'run_id', 'invocation_id', 'parent_invocation_id', 'step_id')
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ExecutionContext:
39
+ application_id: str | None = None
40
+ tenant_id: str | None = None
41
+ billing_account_id: str | None = None
42
+ actor_id: str | None = None
43
+ project_id: str | None = None
44
+ request_id: str | None = None
45
+ run_id: str | None = None
46
+ invocation_id: str | None = None
47
+ parent_invocation_id: str | None = None
48
+ step_id: str | None = None
49
+
50
+ def __post_init__(self):
51
+ for f in fields(self):
52
+ value = getattr(self, f.name)
53
+ if value is not None:
54
+ identifier(value)
55
+
56
+ def resolve(self, defaults=None):
57
+ defaults = defaults or ExecutionContext()
58
+ if type(defaults) is not ExecutionContext:
59
+ raise TypeError('defaults must be ExecutionContext')
60
+ values, sources = {}, []
61
+ for name in ATTRIBUTION:
62
+ provided, configured = getattr(self, name), getattr(defaults, name)
63
+ if name != 'application_id' and self.application_id is not None and self.application_id != defaults.application_id:
64
+ configured = None
65
+ # An explicit tenant must not inherit a deployment-wide payer.
66
+ if name == 'billing_account_id' and self.tenant_id is not None and self.tenant_id != defaults.tenant_id:
67
+ configured = None
68
+ values[name] = provided or configured or 'default'
69
+ sources.append('provided' if provided else 'configured' if configured else 'default')
70
+ values.update({name: getattr(self, name) for name in OPTIONAL})
71
+ values['request_id'] = self.request_id or uuid.uuid4().hex
72
+ values['invocation_id'] = self.invocation_id or uuid.uuid4().hex
73
+ return ResolvedContext(**values, sources=tuple(sources))
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class ResolvedContext:
78
+ application_id: str
79
+ tenant_id: str
80
+ billing_account_id: str
81
+ request_id: str
82
+ invocation_id: str
83
+ actor_id: str | None = None
84
+ project_id: str | None = None
85
+ run_id: str | None = None
86
+ parent_invocation_id: str | None = None
87
+ step_id: str | None = None
88
+ sources: tuple[str, ...] = ('provided', 'provided', 'provided')
89
+
90
+ def __post_init__(self):
91
+ for name in (*ATTRIBUTION, 'request_id', 'invocation_id'):
92
+ identifier(getattr(self, name))
93
+ for f in fields(self):
94
+ if f.name != 'sources' and getattr(self, f.name) is not None:
95
+ identifier(getattr(self, f.name))
96
+ if type(self.sources) is not tuple or len(self.sources) != 3 or any(s not in {'provided', 'configured', 'default'} for s in self.sources):
97
+ raise ValueError('invalid attribution provenance')
98
+
99
+ def to_dict(self):
100
+ result = {f.name: getattr(self, f.name) for f in fields(self) if f.name != 'sources'}
101
+ result['attribution_source'] = dict(zip(ATTRIBUTION, self.sources))
102
+ return result
103
+
104
+ @classmethod
105
+ def from_dict(cls, value):
106
+ if type(value) is not dict or set(value) != {f.name for f in fields(cls)} - {'sources'} | {'attribution_source'}:
107
+ raise ValueError('invalid execution context schema')
108
+ source = value['attribution_source']
109
+ if type(source) is not dict or set(source) != set(ATTRIBUTION):
110
+ raise ValueError('invalid attribution provenance')
111
+ return cls(**{k: v for k, v in value.items() if k != 'attribution_source'}, sources=tuple(source[n] for n in ATTRIBUTION))
112
+
113
+ def child(self, *, invocation_id, run_id=None, step_id=None):
114
+ return replace(self, invocation_id=invocation_id, parent_invocation_id=self.invocation_id,
115
+ run_id=run_id or self.run_id, step_id=step_id)
116
+
117
+
118
+ def resolve_context(context=None, defaults=None):
119
+ if type(context) is ResolvedContext:
120
+ return context
121
+ if context is None:
122
+ context = ExecutionContext()
123
+ if type(context) is not ExecutionContext:
124
+ raise TypeError('context must be ExecutionContext or ResolvedContext')
125
+ return context.resolve(defaults)
126
+
127
+
128
+ def _quantity(value):
129
+ return type(value) is int and 0 <= value <= 2**63 - 1
130
+
131
+
132
+ def normalize_usage(raw):
133
+ """OpenAI text snapshot semantics; detail availability is never guessed."""
134
+ names = ('input_tokens', 'output_tokens', 'total_tokens', 'cached_input_tokens', 'reasoning_output_tokens')
135
+ result = dict.fromkeys(names)
136
+ result['status'] = 'unknown'
137
+ if raw is None:
138
+ return result
139
+ if type(raw) is not dict:
140
+ result['status'] = 'untrusted'
141
+ return result
142
+ for src, dst in (('prompt_tokens', 'input_tokens'), ('completion_tokens', 'output_tokens'), ('total_tokens', 'total_tokens')):
143
+ if src in raw:
144
+ if not _quantity(raw[src]):
145
+ result['status'] = 'untrusted'
146
+ return result
147
+ result[dst] = raw[src]
148
+ for src, key, dst in (('prompt_tokens_details', 'cached_tokens', 'cached_input_tokens'),
149
+ ('completion_tokens_details', 'reasoning_tokens', 'reasoning_output_tokens')):
150
+ if src in raw:
151
+ if type(raw[src]) is not dict or (key in raw[src] and not _quantity(raw[src][key])):
152
+ result['status'] = 'untrusted'
153
+ return result
154
+ result[dst] = raw[src].get(key)
155
+ zero_only = {'audio_tokens'} if src == 'prompt_tokens_details' else {'audio_tokens', 'accepted_prediction_tokens', 'rejected_prediction_tokens'}
156
+ extras = set(raw[src]) - {key}
157
+ if extras - zero_only or any(type(raw[src][extra]) is not int or raw[src][extra] != 0 for extra in extras):
158
+ result['status'] = 'unsupported'
159
+ inp, out, total = (result[n] for n in names[:3])
160
+ if inp is not None and out is not None:
161
+ if inp + out > 2**63 - 1 or (total is not None and total != inp + out):
162
+ result['status'] = 'untrusted'
163
+ return result
164
+ result['total_tokens'] = inp + out
165
+ for detail, parent in (('cached_input_tokens', 'input_tokens'), ('reasoning_output_tokens', 'output_tokens')):
166
+ if result[detail] is not None and result[parent] is not None and result[detail] > result[parent]:
167
+ result['status'] = 'untrusted'
168
+ return result
169
+ known = {'prompt_tokens', 'completion_tokens', 'total_tokens', 'prompt_tokens_details', 'completion_tokens_details'}
170
+ if set(raw) - known or result['status'] == 'unsupported':
171
+ result['status'] = 'unsupported'
172
+ elif result['total_tokens'] is not None:
173
+ result['status'] = 'reported'
174
+ return result
175
+
176
+
177
+ def money(value):
178
+ if type(value) is not str or len(value) > 80:
179
+ raise ValueError('money must be a bounded decimal string')
180
+ try:
181
+ amount = Decimal(value)
182
+ except InvalidOperation as exc:
183
+ raise ValueError('invalid money') from exc
184
+ if not amount.is_finite() or amount < 0 or amount >= Decimal('1e20') or amount.as_tuple().exponent < -18:
185
+ raise ValueError('money outside NUMERIC(38,18)')
186
+ return amount
187
+
188
+
189
+ @dataclass(frozen=True)
190
+ class RateCard:
191
+ revision: str
192
+ model: str
193
+ input_per_million: str
194
+ output_per_million: str
195
+ cached_input_per_million: str | None = None
196
+ currency: str = 'USD'
197
+
198
+ def __post_init__(self):
199
+ identifier(self.revision)
200
+ if type(self.model) is not str or not self.model or len(self.model) > 256 or any(ord(c) < 32 for c in self.model):
201
+ raise ValueError('model must be a bounded printable identifier')
202
+ if not re.fullmatch('[A-Z]{3}', self.currency):
203
+ raise ValueError('currency must be a three-letter code')
204
+ money(self.input_per_million)
205
+ money(self.output_per_million)
206
+ if self.cached_input_per_million is not None:
207
+ money(self.cached_input_per_million)
208
+
209
+ def to_dict(self):
210
+ return {f.name: getattr(self, f.name) for f in fields(self)}
211
+
212
+ def assess(self, observation):
213
+ usage = observation['usage']
214
+ unavailable = {'status': 'unavailable', 'amount': None, 'currency': self.currency, 'rate_revision': self.revision}
215
+ model = observation.get('response_model')
216
+ if model != self.model or usage['status'] != 'reported' or observation.get('service_tier') not in (None, 'default'):
217
+ return unavailable
218
+ inp, out, cached = (usage[n] for n in ('input_tokens', 'output_tokens', 'cached_input_tokens'))
219
+ if inp is None or out is None:
220
+ return unavailable
221
+ if self.cached_input_per_million is not None and cached is None:
222
+ return unavailable
223
+ cached = cached or 0
224
+ cached_rate = self.cached_input_per_million or self.input_per_million
225
+ with localcontext() as ctx:
226
+ ctx.prec = 50
227
+ amount = ((Decimal(inp - cached) * money(self.input_per_million) + Decimal(cached) * money(cached_rate)
228
+ + Decimal(out) * money(self.output_per_million)) / Decimal(1_000_000)).quantize(Decimal('1e-18'), rounding=ROUND_HALF_EVEN)
229
+ money(str(amount))
230
+ return {'status': 'estimated', 'amount': str(amount), 'currency': self.currency, 'rate_revision': self.revision}
231
+
232
+
233
+ class MemoryRecorder:
234
+ """Non-durable testing recorder. Never use for financial production records."""
235
+ durable = False
236
+
237
+ def __init__(self, *, namespace='test', environment='test', defaults=None, rate_card=None,
238
+ provider_id='openai-compatible', credential_account='platform'):
239
+ self.namespace, self.environment = identifier(namespace), identifier(environment)
240
+ self.defaults = defaults
241
+ self.rate_card = rate_card
242
+ self.provider_id, self.credential_account = identifier(provider_id), identifier(credential_account)
243
+ self.intents, self.observations = {}, {}
244
+
245
+ def prepare(self, intent):
246
+ key = intent['provider_call_id']
247
+ if key in self.intents and self.intents[key] != intent:
248
+ raise AccountingError('conflicting intent')
249
+ self.intents[key] = json.loads(canonical(intent))
250
+
251
+ def observe(self, call_id, observation):
252
+ if call_id not in self.intents:
253
+ raise AccountingError('missing intent')
254
+ if call_id in self.observations and self.observations[call_id] != observation:
255
+ raise AccountingError('conflicting observation')
256
+ self.observations[call_id] = json.loads(canonical(observation))