smoothie-framework 0.0.1rc1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. smoothie_framework-0.0.1rc1/LICENSE +184 -0
  2. smoothie_framework-0.0.1rc1/NOTICE +14 -0
  3. smoothie_framework-0.0.1rc1/PKG-INFO +61 -0
  4. smoothie_framework-0.0.1rc1/README.md +45 -0
  5. smoothie_framework-0.0.1rc1/pyproject.toml +25 -0
  6. smoothie_framework-0.0.1rc1/setup.cfg +4 -0
  7. smoothie_framework-0.0.1rc1/src/smoothie_framework/__init__.py +6 -0
  8. smoothie_framework-0.0.1rc1/src/smoothie_framework/agent/__init__.py +39 -0
  9. smoothie_framework-0.0.1rc1/src/smoothie_framework/agent/contract.py +265 -0
  10. smoothie_framework-0.0.1rc1/src/smoothie_framework/agent/runtime.py +194 -0
  11. smoothie_framework-0.0.1rc1/src/smoothie_framework/model/__init__.py +31 -0
  12. smoothie_framework-0.0.1rc1/src/smoothie_framework/model/contract.py +389 -0
  13. smoothie_framework-0.0.1rc1/src/smoothie_framework/model/providers/__init__.py +5 -0
  14. smoothie_framework-0.0.1rc1/src/smoothie_framework/model/providers/openai.py +195 -0
  15. smoothie_framework-0.0.1rc1/src/smoothie_framework/model/runtime.py +140 -0
  16. smoothie_framework-0.0.1rc1/src/smoothie_framework.egg-info/PKG-INFO +61 -0
  17. smoothie_framework-0.0.1rc1/src/smoothie_framework.egg-info/SOURCES.txt +23 -0
  18. smoothie_framework-0.0.1rc1/src/smoothie_framework.egg-info/dependency_links.txt +1 -0
  19. smoothie_framework-0.0.1rc1/src/smoothie_framework.egg-info/requires.txt +1 -0
  20. smoothie_framework-0.0.1rc1/src/smoothie_framework.egg-info/top_level.txt +1 -0
  21. smoothie_framework-0.0.1rc1/tests/test_agent_contract.py +70 -0
  22. smoothie_framework-0.0.1rc1/tests/test_agent_runtime.py +140 -0
  23. smoothie_framework-0.0.1rc1/tests/test_model_contract.py +110 -0
  24. smoothie_framework-0.0.1rc1/tests/test_model_runtime.py +64 -0
  25. smoothie_framework-0.0.1rc1/tests/test_openai_provider.py +93 -0
@@ -0,0 +1,184 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work (an example is provided in the Appendix
36
+ below).
37
+
38
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
39
+ is based on (or derived from) the Work and for which the editorial revisions,
40
+ annotations, elaborations, or other modifications represent, as a whole, an
41
+ original work of authorship. For the purposes of this License, Derivative Works
42
+ shall not include works that remain separable from, or merely link (or bind by
43
+ name) to the interfaces of, the Work and Derivative Works thereof.
44
+
45
+ "Contribution" shall mean any work of authorship, including the original version
46
+ of the Work and any modifications or additions to that Work or Derivative Works
47
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
48
+ by the copyright owner or by an individual or Legal Entity authorized to submit
49
+ on behalf of the copyright owner. For the purposes of this definition,
50
+ "submitted" means any form of electronic, verbal, or written communication sent
51
+ to the Licensor or its representatives, including but not limited to
52
+ communication on electronic mailing lists, source code control systems, and
53
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
54
+ the purpose of discussing and improving the Work, but excluding communication
55
+ that is conspicuously marked or otherwise designated in writing by the copyright
56
+ owner as "Not a Contribution."
57
+
58
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
59
+ of whom a Contribution has been received by Licensor and subsequently
60
+ incorporated within the Work.
61
+
62
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
63
+ License, each Contributor hereby grants to You a perpetual, worldwide,
64
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
65
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
66
+ sublicense, and distribute the Work and such Derivative Works in Source or
67
+ Object form.
68
+
69
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
70
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
71
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
72
+ license to make, have made, use, offer to sell, sell, import, and otherwise
73
+ transfer the Work, where such license applies only to those patent claims
74
+ licensable by such Contributor that are necessarily infringed by their
75
+ Contribution(s) alone or by combination of their Contribution(s) with the Work
76
+ to which such Contribution(s) was submitted. If You institute patent litigation
77
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
78
+ alleging that the Work or a Contribution incorporated within the Work
79
+ constitutes direct or contributory patent infringement, then any patent licenses
80
+ granted to You under this License for that Work shall terminate as of the date
81
+ such litigation is filed.
82
+
83
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
84
+ Derivative Works thereof in any medium, with or without modifications, and in
85
+ Source or Object form, provided that You meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
88
+ this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices stating that You
91
+ changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works that You
94
+ distribute, all copyright, patent, trademark, and attribution notices from the
95
+ Source form of the Work, excluding those notices that do not pertain to any part
96
+ of the Derivative Works; and
97
+
98
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
99
+ any Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+
112
+ You may add Your own copyright statement to Your modifications and may provide
113
+ additional or different license terms and conditions for use, reproduction, or
114
+ distribution of Your modifications, or for any such Derivative Works as a whole,
115
+ provided Your use, reproduction, and distribution of the Work otherwise complies
116
+ with the conditions stated in this License.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
119
+ Contribution intentionally submitted for inclusion in the Work by You to the
120
+ Licensor shall be under the terms and conditions of this License, without any
121
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
122
+ supersede or modify the terms of any separate license agreement you may have
123
+ executed with Licensor regarding such Contributions.
124
+
125
+ 6. Trademarks. This License does not grant permission to use the trade names,
126
+ trademarks, service marks, or product names of the Licensor, except as required
127
+ for reasonable and customary use in describing the origin of the Work and
128
+ reproducing the content of the NOTICE file.
129
+
130
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
131
+ writing, Licensor provides the Work (and each Contributor provides its
132
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
133
+ KIND, either express or implied, including, without limitation, any warranties
134
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
135
+ PARTICULAR PURPOSE. You are solely responsible for determining the
136
+ appropriateness of using or redistributing the Work and assume any risks
137
+ associated with Your exercise of permissions under this License.
138
+
139
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
140
+ tort (including negligence), contract, or otherwise, unless required by
141
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
142
+ writing, shall any Contributor be liable to You for damages, including any
143
+ direct, indirect, special, incidental, or consequential damages of any character
144
+ arising as a result of this License or out of the use or inability to use the
145
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
146
+ computer failure or malfunction, or any and all other commercial damages or
147
+ losses), even if such Contributor has been advised of the possibility of such
148
+ damages.
149
+
150
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
151
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
152
+ acceptance of support, warranty, indemnity, or other liability obligations
153
+ and/or rights consistent with this License. However, in accepting such
154
+ obligations, You may act only on Your own behalf and on Your sole
155
+ responsibility, not on behalf of any other Contributor, and only if You agree to
156
+ indemnify, defend, and hold each Contributor harmless for any liability incurred
157
+ by, or claims asserted against, such Contributor by reason of your accepting any
158
+ such warranty or additional liability.
159
+
160
+ END OF TERMS AND CONDITIONS
161
+
162
+ APPENDIX: How to apply the Apache License to your work.
163
+
164
+ To apply the Apache License to your work, attach the following boilerplate
165
+ notice, with the fields enclosed by brackets "[]" replaced with your own
166
+ identifying information. (Don't include the brackets!) The text should be
167
+ enclosed in the appropriate comment syntax for the file format. We also
168
+ recommend that a file or class name and description of purpose be included on
169
+ the same "printed page" as the copyright notice for easier identification within
170
+ third-party archives.
171
+
172
+ Copyright [yyyy] [name of copyright owner]
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.
@@ -0,0 +1,14 @@
1
+ Smoothie Framework
2
+ Copyright (c) 2026 Qwirklabs
3
+
4
+ This repository uses a mixed-license model.
5
+
6
+ - Default framework license: Apache-2.0 (`LICENSE`)
7
+ - Studio/product license: Proprietary (`LICENSE-PROPRIETARY-STUDIO`)
8
+
9
+ See `LICENSE_MAP.md` for component-level license mapping.
10
+
11
+ Trademarks:
12
+
13
+ - "Smoothie" and "Smoothie Studio" are trademarks of Qwirklabs.
14
+ - This notice does not grant rights to use Qwirklabs trademarks.
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: smoothie-framework
3
+ Version: 0.0.1rc1
4
+ Summary: Python capability projections for Smoothie Framework
5
+ Author: Smoothie Framework
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Documentation, https://docs.smoothie.dev/framework/0.1
8
+ Project-URL: Issues, https://github.com/Qwirklabs/smoothie/issues
9
+ Project-URL: Repository, https://github.com/Qwirklabs/smoothie
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Requires-Dist: jsonschema<5,>=4.23
15
+ Dynamic: license-file
16
+
17
+ # Smoothie Framework Python SDK
18
+
19
+ This experimental SDK independently implements the portable capability slices
20
+ selected for Framework 0.1. It does not mirror the TypeScript package tree or
21
+ claim capability parity.
22
+
23
+ The first 0.1 source slice is `smoothie_framework.model`: bounded Model invocation,
24
+ result, stream, usage, and safe-error values for `smoothie:model@1`.
25
+
26
+ ```python
27
+ from smoothie_framework.model import ModelInvocation, ModelRuntime
28
+
29
+ result = ModelRuntime(provider).generate(ModelInvocation(
30
+ model="openai/gpt-4.1-mini",
31
+ messages=({"role": "user", "content": "Summarize this ticket."},),
32
+ ))
33
+ ```
34
+
35
+ `ModelRuntime` validates provider output and stream ordering against the
36
+ portable contract. Provider configuration and credentials remain native Python
37
+ concerns. The initial `OpenAIResponsesProvider` uses the Python standard HTTP
38
+ stack, resolves its credential for each request, and caps JSON response bodies
39
+ at 16 MiB before parsing.
40
+
41
+ `smoothie_framework.agent` adds the bounded Framework 0.1 Agent slice:
42
+
43
+ ```python
44
+ from smoothie_framework.agent import AgentDefinition, AgentRuntime, AgentTool
45
+
46
+ agent = AgentRuntime(AgentDefinition(
47
+ name="ticket-agent",
48
+ instructions="Read the ticket before answering.",
49
+ model="openai/gpt-4.1-mini",
50
+ tools=(read_ticket,),
51
+ ), model_runtime)
52
+
53
+ result = agent.run("Read ticket T-1")
54
+ ```
55
+
56
+ Definitions are side-effect-free; `AgentRuntime` binds one definition to a
57
+ Model runtime. The initial synchronous loop is bounded to eight Model turns and
58
+ 32 Tool executions, validates Tool input before its binding, checks cooperative
59
+ cancellation at side-effect boundaries, and emits content-free lifecycle
60
+ evidence. It does not claim TypeScript Governance, Worker durability, approval,
61
+ steering, routing, or provider parity.
@@ -0,0 +1,45 @@
1
+ # Smoothie Framework Python SDK
2
+
3
+ This experimental SDK independently implements the portable capability slices
4
+ selected for Framework 0.1. It does not mirror the TypeScript package tree or
5
+ claim capability parity.
6
+
7
+ The first 0.1 source slice is `smoothie_framework.model`: bounded Model invocation,
8
+ result, stream, usage, and safe-error values for `smoothie:model@1`.
9
+
10
+ ```python
11
+ from smoothie_framework.model import ModelInvocation, ModelRuntime
12
+
13
+ result = ModelRuntime(provider).generate(ModelInvocation(
14
+ model="openai/gpt-4.1-mini",
15
+ messages=({"role": "user", "content": "Summarize this ticket."},),
16
+ ))
17
+ ```
18
+
19
+ `ModelRuntime` validates provider output and stream ordering against the
20
+ portable contract. Provider configuration and credentials remain native Python
21
+ concerns. The initial `OpenAIResponsesProvider` uses the Python standard HTTP
22
+ stack, resolves its credential for each request, and caps JSON response bodies
23
+ at 16 MiB before parsing.
24
+
25
+ `smoothie_framework.agent` adds the bounded Framework 0.1 Agent slice:
26
+
27
+ ```python
28
+ from smoothie_framework.agent import AgentDefinition, AgentRuntime, AgentTool
29
+
30
+ agent = AgentRuntime(AgentDefinition(
31
+ name="ticket-agent",
32
+ instructions="Read the ticket before answering.",
33
+ model="openai/gpt-4.1-mini",
34
+ tools=(read_ticket,),
35
+ ), model_runtime)
36
+
37
+ result = agent.run("Read ticket T-1")
38
+ ```
39
+
40
+ Definitions are side-effect-free; `AgentRuntime` binds one definition to a
41
+ Model runtime. The initial synchronous loop is bounded to eight Model turns and
42
+ 32 Tool executions, validates Tool input before its binding, checks cooperative
43
+ cancellation at side-effect boundaries, and emits content-free lifecycle
44
+ evidence. It does not claim TypeScript Governance, Worker durability, approval,
45
+ steering, routing, or provider parity.
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "smoothie-framework"
7
+ version = "0.0.1rc1"
8
+ description = "Python capability projections for Smoothie Framework"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{ name = "Smoothie Framework" }]
14
+ dependencies = ["jsonschema>=4.23,<5"]
15
+
16
+ [project.urls]
17
+ Documentation = "https://docs.smoothie.dev/framework/0.1"
18
+ Issues = "https://github.com/Qwirklabs/smoothie/issues"
19
+ Repository = "https://github.com/Qwirklabs/smoothie"
20
+
21
+ [tool.setuptools.packages.find]
22
+ where = ["src"]
23
+
24
+ [tool.pytest.ini_options]
25
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Smoothie Framework Python capability projections."""
2
+
3
+ from . import agent, model
4
+
5
+ __all__ = ["agent", "model"]
6
+ __version__ = "0.0.1rc1"
@@ -0,0 +1,39 @@
1
+ """Portable Agent authoring and execution."""
2
+
3
+ from .contract import (
4
+ AGENT_CONTRACT_VERSION,
5
+ AGENT_ERROR_CLASSIFICATIONS,
6
+ AGENT_EVENT_TYPES,
7
+ AGENT_PROTOCOL_VERSION,
8
+ AgentContractError,
9
+ validate_error,
10
+ validate_events,
11
+ validate_turn_request,
12
+ validate_turn_result,
13
+ )
14
+ from .runtime import (
15
+ AgentCancelled,
16
+ AgentDefinition,
17
+ AgentExecutionError,
18
+ AgentResult,
19
+ AgentRuntime,
20
+ AgentTool,
21
+ )
22
+
23
+ __all__ = [
24
+ "AGENT_CONTRACT_VERSION",
25
+ "AGENT_ERROR_CLASSIFICATIONS",
26
+ "AGENT_EVENT_TYPES",
27
+ "AGENT_PROTOCOL_VERSION",
28
+ "AgentCancelled",
29
+ "AgentContractError",
30
+ "AgentDefinition",
31
+ "AgentExecutionError",
32
+ "AgentResult",
33
+ "AgentRuntime",
34
+ "AgentTool",
35
+ "validate_error",
36
+ "validate_events",
37
+ "validate_turn_request",
38
+ "validate_turn_result",
39
+ ]
@@ -0,0 +1,265 @@
1
+ """Independent Python projection of ``smoothie:agent@1``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any
8
+
9
+ AGENT_CONTRACT_VERSION = "1.0.0"
10
+ AGENT_PROTOCOL_VERSION = "1.0"
11
+ AGENT_INPUT_CHARS_MAX = 1_048_576
12
+ AGENT_OUTPUT_CHARS_MAX = 1_048_576
13
+ AGENT_EVENTS_MAX = 10_000
14
+ AGENT_MODEL_TURNS_MAX = 8
15
+ AGENT_TOOLS_MAX = 32
16
+ MAX_SAFE_INTEGER = 9_007_199_254_740_991
17
+ AGENT_EVENT_TYPES = (
18
+ "run.accepted",
19
+ "run.started",
20
+ "model.completed",
21
+ "tool.started",
22
+ "tool.completed",
23
+ "tool.failed",
24
+ "cancel.requested",
25
+ "run.completed",
26
+ "run.failed",
27
+ "run.cancelled",
28
+ )
29
+ AGENT_ERROR_CLASSIFICATIONS = (
30
+ "invalid_request",
31
+ "denied",
32
+ "cancelled",
33
+ "timeout",
34
+ "model_failed",
35
+ "tool_failed",
36
+ "runtime_failed",
37
+ )
38
+
39
+ _AGENT = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{0,127}$")
40
+ _TOOL = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
41
+ _ERROR_CODE = re.compile(r"^[A-Z][A-Z0-9_]{0,127}$")
42
+ _USAGE_FIELDS = {
43
+ "inputTokens",
44
+ "outputTokens",
45
+ "totalTokens",
46
+ "cachedInputTokens",
47
+ "cacheWriteInputTokens",
48
+ "reasoningTokens",
49
+ "costUsdMicros",
50
+ }
51
+
52
+
53
+ class AgentContractError(ValueError):
54
+ """A portable Agent value violates the language-neutral contract."""
55
+
56
+
57
+ def _utf16_length(value: str) -> int:
58
+ return len(value.encode("utf-16-le")) // 2
59
+
60
+
61
+ def _record(value: Any, label: str) -> Mapping[str, Any]:
62
+ if not isinstance(value, Mapping) or any(not isinstance(key, str) for key in value):
63
+ raise AgentContractError(f"{label} must be an object")
64
+ return value
65
+
66
+
67
+ def _exact(value: Mapping[str, Any], required: set[str], optional: set[str], label: str) -> None:
68
+ missing = required - value.keys()
69
+ unknown = value.keys() - required - optional
70
+ if missing or unknown:
71
+ raise AgentContractError(f"{label} has missing or unknown fields")
72
+
73
+
74
+ def _text(value: Any, label: str, *, minimum: int = 0, maximum: int) -> str:
75
+ if not isinstance(value, str) or not minimum <= _utf16_length(value) <= maximum:
76
+ raise AgentContractError(f"{label} exceeds its bound")
77
+ return value
78
+
79
+
80
+ def _identifier(value: Any, label: str) -> str:
81
+ text = _text(value, label, minimum=1, maximum=256)
82
+ if text.strip() != text:
83
+ raise AgentContractError(f"{label} must be trimmed")
84
+ return text
85
+
86
+
87
+ def _identity(value: Mapping[str, Any], label: str) -> str:
88
+ if value.get("protocolVersion") != AGENT_PROTOCOL_VERSION:
89
+ raise AgentContractError(f"{label} protocolVersion must be {AGENT_PROTOCOL_VERSION}")
90
+ return _identifier(value.get("runId"), f"{label}.runId")
91
+
92
+
93
+ def _safe_integer(value: Any, label: str, *, maximum: int = MAX_SAFE_INTEGER) -> int:
94
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= maximum:
95
+ raise AgentContractError(f"{label} must be a non-negative interoperable integer")
96
+ return value
97
+
98
+
99
+ def _usage(value: Any, label: str) -> Mapping[str, int]:
100
+ usage = _record(value, label)
101
+ if not usage or usage.keys() - _USAGE_FIELDS:
102
+ raise AgentContractError(f"{label} must contain only normalized usage fields")
103
+ for field, count in usage.items():
104
+ _safe_integer(count, f"{label}.{field}")
105
+ return usage
106
+
107
+
108
+ def validate_turn_request(value: Any) -> Mapping[str, Any]:
109
+ request = _record(value, "request")
110
+ _exact(request, {"protocolVersion", "runId", "agent", "input"}, {"sessionId"}, "request")
111
+ _identity(request, "request")
112
+ agent = _text(request["agent"], "request.agent", minimum=1, maximum=128)
113
+ if not _AGENT.fullmatch(agent):
114
+ raise AgentContractError("request.agent is invalid")
115
+ _text(request["input"], "request.input", maximum=AGENT_INPUT_CHARS_MAX)
116
+ if "sessionId" in request:
117
+ _identifier(request["sessionId"], "request.sessionId")
118
+ return request
119
+
120
+
121
+ def validate_turn_result(value: Any) -> Mapping[str, Any]:
122
+ result = _record(value, "result")
123
+ _exact(
124
+ result,
125
+ {"protocolVersion", "runId", "agent", "status", "output"},
126
+ {"sessionId", "usage"},
127
+ "result",
128
+ )
129
+ _identity(result, "result")
130
+ agent = _text(result["agent"], "result.agent", minimum=1, maximum=128)
131
+ if not _AGENT.fullmatch(agent) or result["status"] != "completed":
132
+ raise AgentContractError("result agent or status is invalid")
133
+ _text(result["output"], "result.output", maximum=AGENT_OUTPUT_CHARS_MAX)
134
+ if "sessionId" in result:
135
+ _identifier(result["sessionId"], "result.sessionId")
136
+ if "usage" in result:
137
+ _usage(result["usage"], "result.usage")
138
+ return result
139
+
140
+
141
+ def validate_error(value: Any) -> Mapping[str, Any]:
142
+ error = _record(value, "error")
143
+ _exact(
144
+ error,
145
+ {"protocolVersion", "runId", "code", "classification", "message", "retryable"},
146
+ set(),
147
+ "error",
148
+ )
149
+ _identity(error, "error")
150
+ code = _text(error["code"], "error.code", minimum=1, maximum=128)
151
+ if not _ERROR_CODE.fullmatch(code) or error["classification"] not in AGENT_ERROR_CLASSIFICATIONS:
152
+ raise AgentContractError("error code or classification is invalid")
153
+ _text(error["message"], "error.message", minimum=1, maximum=1_024)
154
+ if not isinstance(error["retryable"], bool):
155
+ raise AgentContractError("error.retryable must be boolean")
156
+ return error
157
+
158
+
159
+ def validate_events(value: Any, expected: Mapping[str, Any] | None = None) -> Sequence[Mapping[str, Any]]:
160
+ if isinstance(value, (str, bytes)) or not isinstance(value, Sequence) or not 1 <= len(value) <= AGENT_EVENTS_MAX:
161
+ raise AgentContractError("events exceed the portable bound")
162
+ run_id: str | None = None
163
+ started = False
164
+ terminal = False
165
+ cancellation_requested = False
166
+ pending_tool: str | None = None
167
+ model_turns = 0
168
+ tool_calls = 0
169
+ aggregate_usage: dict[str, int] = {}
170
+ validated: list[Mapping[str, Any]] = []
171
+ for sequence, raw_event in enumerate(value):
172
+ event = _record(raw_event, f"events[{sequence}]")
173
+ event_type = _event_shape(event, sequence)
174
+ current_id = _identity(event, f"events[{sequence}]")
175
+ run_id = run_id or current_id
176
+ if current_id != run_id or _safe_integer(event["sequence"], "event.sequence", maximum=AGENT_EVENTS_MAX - 1) != sequence or terminal:
177
+ raise AgentContractError("event identity, ordering, or terminal state is invalid")
178
+ if sequence == 0 and event_type != "run.accepted":
179
+ raise AgentContractError("events must begin with run.accepted")
180
+ if event_type == "run.started":
181
+ if started or cancellation_requested:
182
+ raise AgentContractError("run.started is out of order")
183
+ started = True
184
+ elif event_type == "model.completed":
185
+ if not started or pending_tool is not None or model_turns >= AGENT_MODEL_TURNS_MAX:
186
+ raise AgentContractError("model event is out of order or exceeds its bound")
187
+ model_turns += 1
188
+ if "usage" in event:
189
+ _add_usage(aggregate_usage, event["usage"])
190
+ elif event_type == "tool.started":
191
+ tool_name = _tool_name(event["toolName"])
192
+ if not started or pending_tool is not None or model_turns < 1 or tool_calls >= AGENT_TOOLS_MAX:
193
+ raise AgentContractError("tool start is out of order or exceeds its bound")
194
+ pending_tool = tool_name
195
+ tool_calls += 1
196
+ elif event_type in ("tool.completed", "tool.failed"):
197
+ if _tool_name(event["toolName"]) != pending_tool:
198
+ raise AgentContractError("tool completion does not match its start")
199
+ pending_tool = None
200
+ elif event_type == "cancel.requested":
201
+ if cancellation_requested:
202
+ raise AgentContractError("cancellation was requested more than once")
203
+ cancellation_requested = True
204
+ elif event_type == "run.completed":
205
+ result = validate_turn_result(event["result"])
206
+ if not started or pending_tool is not None or result["runId"] != run_id or not _same_usage(result.get("usage"), aggregate_usage):
207
+ raise AgentContractError("completion does not match its run or usage")
208
+ terminal = True
209
+ elif event_type in ("run.failed", "run.cancelled"):
210
+ error = validate_error(event["error"])
211
+ if pending_tool is not None or error["runId"] != run_id or (event_type == "run.cancelled") != (error["classification"] == "cancelled"):
212
+ raise AgentContractError("terminal error does not match its run")
213
+ terminal = True
214
+ validated.append(event)
215
+ if not terminal:
216
+ raise AgentContractError("events are missing a terminal event")
217
+ if expected is not None:
218
+ terminal_event = validated[-1]
219
+ if terminal_event["runId"] != expected["runId"]:
220
+ raise AgentContractError("events do not match the turn request")
221
+ if terminal_event["type"] == "run.completed":
222
+ result = terminal_event["result"]
223
+ if result["agent"] != expected["agent"] or result.get("sessionId") != expected.get("sessionId"):
224
+ raise AgentContractError("events do not match the turn request")
225
+ return validated
226
+
227
+
228
+ def _event_shape(event: Mapping[str, Any], sequence: int) -> str:
229
+ event_type = event.get("type")
230
+ if event_type not in AGENT_EVENT_TYPES:
231
+ raise AgentContractError("event type is invalid")
232
+ payload = (
233
+ "toolName" if event_type in ("tool.started", "tool.completed", "tool.failed")
234
+ else "result" if event_type == "run.completed"
235
+ else "error" if event_type in ("run.failed", "run.cancelled")
236
+ else None
237
+ )
238
+ _exact(
239
+ event,
240
+ {"protocolVersion", "runId", "sequence", "type"} | ({payload} if payload else set()),
241
+ {"usage"} if event_type == "model.completed" else set(),
242
+ f"events[{sequence}]",
243
+ )
244
+ return event_type
245
+
246
+
247
+ def _tool_name(value: Any) -> str:
248
+ name = _text(value, "event.toolName", minimum=1, maximum=64)
249
+ if not _TOOL.fullmatch(name):
250
+ raise AgentContractError("event.toolName is invalid")
251
+ return name
252
+
253
+
254
+ def _add_usage(aggregate: dict[str, int], value: Any) -> None:
255
+ for field, count in _usage(value, "event.usage").items():
256
+ aggregate[field] = _safe_integer(aggregate.get(field, 0) + count, f"usage.{field}")
257
+
258
+
259
+ def _same_usage(value: Any, aggregate: Mapping[str, int]) -> bool:
260
+ if not aggregate:
261
+ return value is None
262
+ if value is None:
263
+ return False
264
+ usage = _usage(value, "result.usage")
265
+ return all(usage.get(field, 0) == aggregate.get(field, 0) for field in usage.keys() | aggregate.keys())