runlayer-hooks-sdk 0.2.0__tar.gz → 0.2.2__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. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/.gitignore +16 -1
  2. runlayer_hooks_sdk-0.2.2/LICENSE +201 -0
  3. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/PKG-INFO +23 -1
  4. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/README.md +21 -0
  5. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/pyproject.toml +1 -1
  6. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/client.py +69 -16
  7. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/hook_transport.py +48 -11
  8. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/preflight.py +31 -3
  9. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/tool_enforcement.py +20 -2
  10. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/tests/test_client.py +166 -9
  11. runlayer_hooks_sdk-0.2.2/tests/test_hook_transport.py +121 -0
  12. runlayer_hooks_sdk-0.2.2/tests/test_license.py +11 -0
  13. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/tests/test_tool_enforcement.py +48 -0
  14. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/uv.lock +2 -2
  15. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/Makefile +0 -0
  16. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/__init__.py +0 -0
  17. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/claude_agent_sdk.py +0 -0
  18. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/google_adk.py +0 -0
  19. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/openai_agents_sdk.py +0 -0
  20. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/tool_adapter.py +0 -0
  21. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/types.py +0 -0
  22. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/runlayer_sdk/vercel_ai_sdk.py +0 -0
  23. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/tests/http_mock.py +0 -0
  24. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/tests/test_adapters.py +0 -0
  25. {runlayer_hooks_sdk-0.2.0 → runlayer_hooks_sdk-0.2.2}/tests/test_claude_agent_sdk.py +0 -0
@@ -4,6 +4,12 @@
4
4
  .worktrees
5
5
  node_modules/
6
6
  .pnpm-store
7
+
8
+ # Any stray `pnpm` invocation in a bun subproject writes these into the working
9
+ # tree. Ignore by default; re-allow the subprojects that are still on pnpm.
10
+ pnpm-lock.yaml
11
+ pnpm-workspace.yaml
12
+ !/llm-gateway/test/clients/pnpm-lock.yaml
7
13
  /test-results/
8
14
  /playwright-report/
9
15
  /blob-report/
@@ -30,7 +36,11 @@ terraform.tfstate.*
30
36
  .terraform.lock.hcl
31
37
  terraform.tfvars
32
38
  terraform.*.tfvars
33
- tfplan
39
+ # Prefix glob on purpose: plan/state artifacts get ad-hoc names (tfplan2,
40
+ # tfplan-restore, ...) and embed resolved secrets in plaintext — a bare
41
+ # `tfplan` rule let a 388KB plan+state zip reach a PR once.
42
+ tfplan*
43
+ *.tfplan
34
44
 
35
45
  # Python
36
46
  __pycache__/
@@ -105,3 +115,8 @@ docs/superpowers/
105
115
 
106
116
  # SDD (subagent-driven-development) task reports — internal artifacts
107
117
  sdd/
118
+ tmp/
119
+
120
+ # Extractor-emitted load models are artifacts; the committed fixture stays hand-built.
121
+ /load-testing/load-model.json
122
+ /load-testing/model/load-model.json
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: runlayer-hooks-sdk
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Runlayer Hooks SDK for Python agent runtimes
5
5
  Project-URL: Homepage, https://runlayer.com
6
6
  Project-URL: Documentation, https://docs.runlayer.com/
7
7
  Author-email: Runlayer <engineering@runlayer.com>
8
8
  License: Apache-2.0
9
+ License-File: LICENSE
9
10
  Keywords: agent,llm,mcp,runlayer,security
10
11
  Classifier: Intended Audience :: Developers
11
12
  Classifier: License :: OSI Approved :: Apache Software License
@@ -60,6 +61,11 @@ export RUNLAYER_AGENT_SUBJECT_TOKEN="user@example.com"
60
61
  export RUNLAYER_AGENT_SUBJECT_TOKEN_TYPE="urn:runlayer:token-type:user-email"
61
62
  ```
62
63
 
64
+ The SDK mints an agent token with `client_credentials` and, when an OBO subject
65
+ is configured, exchanges it via RFC 8693 token exchange
66
+ (`urn:ietf:params:oauth:grant-type:token-exchange`); both tokens are cached and
67
+ refreshed internally.
68
+
63
69
  Optional runtime controls:
64
70
 
65
71
  | Variable | Purpose |
@@ -122,6 +128,9 @@ for the actionable reasons so a misconfiguration is not silent:
122
128
  workspace. Enable the client (and any required SDK toggle) in Runlayer
123
129
  settings. This is a separate switch from tool enforcement, so both must be on
124
130
  to get full session + tool telemetry.
131
+ - `sessions_disabled` — the applicable MDM configuration disables session
132
+ reporting. Ask a Runlayer administrator to enable **Sessions** in that MDM
133
+ configuration.
125
134
  - `actor_unresolved` — the request authenticated but Runlayer could not map it
126
135
  to a user/agent. With an organization API key, set `RUNLAYER_USER_EMAIL` (or
127
136
  the `user_email` client option) to the Runlayer user the deployment runs as;
@@ -162,3 +171,16 @@ The adapter exports:
162
171
  - `tool_type_from_name`
163
172
 
164
173
  TypeScript-style camelCase aliases are also available for SDK parity.
174
+
175
+ Each `query()` call starts a new Claude Agent SDK session with a fresh
176
+ `session_id`, and Runlayer records each session id as a separate session. To
177
+ keep a multi-prompt conversation in a single Runlayer session, resume the
178
+ previous session on follow-up calls (leave `fork_session` unset so the session
179
+ id is preserved), then emit the transcript `Stop` per run as usual:
180
+
181
+ ```python
182
+ options = ClaudeAgentOptions(
183
+ hooks=create_claude_agent_sdk_hooks(runlayer, include_stop=False),
184
+ resume=session_id, # session_id captured from the previous run's init message
185
+ )
186
+ ```
@@ -39,6 +39,11 @@ export RUNLAYER_AGENT_SUBJECT_TOKEN="user@example.com"
39
39
  export RUNLAYER_AGENT_SUBJECT_TOKEN_TYPE="urn:runlayer:token-type:user-email"
40
40
  ```
41
41
 
42
+ The SDK mints an agent token with `client_credentials` and, when an OBO subject
43
+ is configured, exchanges it via RFC 8693 token exchange
44
+ (`urn:ietf:params:oauth:grant-type:token-exchange`); both tokens are cached and
45
+ refreshed internally.
46
+
42
47
  Optional runtime controls:
43
48
 
44
49
  | Variable | Purpose |
@@ -101,6 +106,9 @@ for the actionable reasons so a misconfiguration is not silent:
101
106
  workspace. Enable the client (and any required SDK toggle) in Runlayer
102
107
  settings. This is a separate switch from tool enforcement, so both must be on
103
108
  to get full session + tool telemetry.
109
+ - `sessions_disabled` — the applicable MDM configuration disables session
110
+ reporting. Ask a Runlayer administrator to enable **Sessions** in that MDM
111
+ configuration.
104
112
  - `actor_unresolved` — the request authenticated but Runlayer could not map it
105
113
  to a user/agent. With an organization API key, set `RUNLAYER_USER_EMAIL` (or
106
114
  the `user_email` client option) to the Runlayer user the deployment runs as;
@@ -141,3 +149,16 @@ The adapter exports:
141
149
  - `tool_type_from_name`
142
150
 
143
151
  TypeScript-style camelCase aliases are also available for SDK parity.
152
+
153
+ Each `query()` call starts a new Claude Agent SDK session with a fresh
154
+ `session_id`, and Runlayer records each session id as a separate session. To
155
+ keep a multi-prompt conversation in a single Runlayer session, resume the
156
+ previous session on follow-up calls (leave `fork_session` unset so the session
157
+ id is preserved), then emit the transcript `Stop` per run as usual:
158
+
159
+ ```python
160
+ options = ClaudeAgentOptions(
161
+ hooks=create_claude_agent_sdk_hooks(runlayer, include_stop=False),
162
+ resume=session_id, # session_id captured from the previous run's init message
163
+ )
164
+ ```
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "runlayer-hooks-sdk"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "Runlayer Hooks SDK for Python agent runtimes"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -43,6 +43,8 @@ from runlayer_sdk.types import (
43
43
  DEFAULT_TIMEOUT_MS = 10_000
44
44
  DEFAULT_MAX_TOOL_OUTPUT_BYTES = 64 * 1024
45
45
  DEFAULT_TOKEN_REFRESH_WINDOW_MS = 60_000
46
+ _TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange"
47
+ _ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
46
48
 
47
49
 
48
50
  @dataclass
@@ -52,6 +54,12 @@ class _CachedAgentToken:
52
54
  refresh_at_ms: int
53
55
 
54
56
 
57
+ @dataclass
58
+ class _CachedActorToken:
59
+ access_token: str
60
+ expires_at_ms: int
61
+
62
+
55
63
  class RunlayerClient:
56
64
  def __init__(
57
65
  self,
@@ -116,6 +124,7 @@ class RunlayerClient:
116
124
  )
117
125
  self._timeout_override_seconds = timeout_ms / 1000 if timeout_ms else None
118
126
  self._cached_agent_token: _CachedAgentToken | None = None
127
+ self._cached_actor_token: _CachedActorToken | None = None
119
128
  self._agent_token_lock = threading.Lock()
120
129
  self._warned_ignored_reasons: set[str] = set()
121
130
 
@@ -305,7 +314,7 @@ class RunlayerClient:
305
314
  transcript: str | None = None,
306
315
  *,
307
316
  strict: bool = False,
308
- ) -> None:
317
+ ) -> JsonObject | None:
309
318
  try:
310
319
  response = self._post(
311
320
  HOOK_RELAY_TARGETS["event"].endpoint,
@@ -318,10 +327,12 @@ class RunlayerClient:
318
327
  target="event",
319
328
  )
320
329
  self._warn_if_ignored(event_name, response)
330
+ return response
321
331
  except Exception as exc:
322
332
  if strict:
323
333
  raise
324
334
  _debug("Runlayer event hook failed", exc)
335
+ return None
325
336
 
326
337
  def _warn_if_ignored(self, event_name: str, response: JsonObject) -> None:
327
338
  # A 200 with status="ignored" means the event was accepted but dropped
@@ -333,7 +344,7 @@ class RunlayerClient:
333
344
  return
334
345
  reason = response.get("reason") or "unknown"
335
346
 
336
- if reason in ("client_not_enabled", "actor_unresolved"):
347
+ if reason in ("client_not_enabled", "actor_unresolved", "sessions_disabled"):
337
348
  if reason in self._warned_ignored_reasons:
338
349
  return
339
350
  self._warned_ignored_reasons.add(reason)
@@ -342,6 +353,12 @@ class RunlayerClient:
342
353
  f'Enable SDK session monitoring for client "{self.client}" '
343
354
  "in Runlayer settings."
344
355
  )
356
+ elif reason == "sessions_disabled":
357
+ remedy = (
358
+ "Your MDM configuration disables session reporting. Contact "
359
+ "your Runlayer administrator to enable Sessions in the "
360
+ "applicable MDM configuration."
361
+ )
345
362
  else:
346
363
  remedy = (
347
364
  "The acting identity could not be resolved. With an "
@@ -851,33 +868,69 @@ class RunlayerClient:
851
868
  return self._cached_agent_token.access_token
852
869
  raise
853
870
 
854
- def _fetch_agent_access_token(self, agent_account: AgentAccountOptions) -> str:
855
- form = _strip_empty(
856
- {
857
- "client_id": agent_account["client_id"],
858
- "client_secret": agent_account["client_secret"],
859
- "grant_type": "client_credentials",
860
- "subject_token": agent_account.get("subject_token"),
861
- "subject_token_type": agent_account.get("subject_token_type"),
862
- }
863
- )
864
- response = self._post_token_request(form)
871
+ def _request_token(self, form: dict[str, str | None]) -> dict[str, Any]:
872
+ response = self._post_token_request(_strip_empty(form))
865
873
  text = response.text
866
874
  if not response.is_success:
867
875
  raise RuntimeError(
868
876
  f"Runlayer token request failed ({response.status_code}): {text}"
869
877
  )
870
-
871
878
  token = response.json()
872
- access_token = token.get("access_token")
873
- if not access_token:
879
+ if not token.get("access_token"):
874
880
  raise RuntimeError("Runlayer token response did not include access_token")
875
881
  token_type = token.get("token_type")
876
882
  if token_type and token_type.lower() != "bearer":
877
883
  raise RuntimeError(
878
884
  f"Runlayer token response used unsupported token_type {token_type}"
879
885
  )
886
+ return token
887
+
888
+ def _actor_access_token(self, agent_account: AgentAccountOptions) -> str:
889
+ now = int(time.time() * 1000)
890
+ cached = self._cached_actor_token
891
+ # Fixed 60s skew (vs the configurable agent refresh window): the actor
892
+ # token is only used transiently to mint exchange tokens, so a simple
893
+ # skew is sufficient.
894
+ if cached and cached.expires_at_ms - 60_000 > now:
895
+ return cached.access_token
896
+ token = self._request_token(
897
+ {
898
+ "client_id": agent_account["client_id"],
899
+ "client_secret": agent_account["client_secret"],
900
+ "grant_type": "client_credentials",
901
+ }
902
+ )
903
+ access_token = token["access_token"]
904
+ expires_in_ms = _token_expires_in_ms(token.get("expires_in"))
905
+ self._cached_actor_token = _CachedActorToken(
906
+ access_token=access_token,
907
+ expires_at_ms=int(time.time() * 1000) + expires_in_ms,
908
+ )
909
+ return access_token
910
+
911
+ def _fetch_agent_access_token(self, agent_account: AgentAccountOptions) -> str:
912
+ subject_token = agent_account.get("subject_token")
913
+ if subject_token:
914
+ actor_token = self._actor_access_token(agent_account)
915
+ token = self._request_token(
916
+ {
917
+ "grant_type": _TOKEN_EXCHANGE_GRANT,
918
+ "actor_token": actor_token,
919
+ "actor_token_type": _ACCESS_TOKEN_TYPE,
920
+ "subject_token": subject_token,
921
+ "subject_token_type": agent_account.get("subject_token_type"),
922
+ }
923
+ )
924
+ else:
925
+ token = self._request_token(
926
+ {
927
+ "client_id": agent_account["client_id"],
928
+ "client_secret": agent_account["client_secret"],
929
+ "grant_type": "client_credentials",
930
+ }
931
+ )
880
932
 
933
+ access_token = token["access_token"]
881
934
  expires_in_ms = _token_expires_in_ms(token.get("expires_in"))
882
935
  issued_at_ms = int(time.time() * 1000)
883
936
  refresh_window_ms = max(
@@ -1,9 +1,10 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import gzip
3
4
  from collections.abc import Callable
4
5
  from contextlib import AbstractContextManager
5
6
  from dataclasses import dataclass
6
- from typing import Any, Protocol
7
+ from typing import Any, Protocol, TypedDict
7
8
 
8
9
  import httpx
9
10
  from runlayer_sdk.types import FetchLike, FetchResponse
@@ -12,6 +13,38 @@ API_KEY_HEADER_NAME = "x-runlayer-api-key"
12
13
  ENFORCEMENT_HOOK_TIMEOUT_SECONDS = 30
13
14
  EVENT_HOOK_TIMEOUT_SECONDS = 5
14
15
 
16
+ # Compress only bodies past this size: small hook bodies gain nothing from
17
+ # gzip, and the compress call would just add CPU to the latency-critical path.
18
+ GZIP_MIN_PAYLOAD_BYTES = 16 * 1024
19
+ # Speed over ratio: hook POSTs are latency-critical, and level 1 already
20
+ # collapses JSON transcript bodies dramatically.
21
+ GZIP_COMPRESS_LEVEL = 1
22
+
23
+
24
+ class WireBody(TypedDict):
25
+ """What actually goes on the wire: body + any transport headers it needs."""
26
+
27
+ content: str | bytes
28
+ headers: dict[str, str]
29
+
30
+
31
+ def encode_wire_body(payload: str | bytes, *, compress: bool = False) -> WireBody:
32
+ """Gzip the payload when opted in and larger than ``GZIP_MIN_PAYLOAD_BYTES``.
33
+
34
+ ``bytes`` input is treated as an already-encoded wire body and passed
35
+ through untouched, so a caller that pre-encoded (to measure the wire size)
36
+ can post the result without double-compressing.
37
+ """
38
+ if not compress or isinstance(payload, bytes):
39
+ return {"content": payload, "headers": {}}
40
+ raw = payload.encode("utf-8")
41
+ if len(raw) <= GZIP_MIN_PAYLOAD_BYTES:
42
+ return {"content": payload, "headers": {}}
43
+ return {
44
+ "content": gzip.compress(raw, compresslevel=GZIP_COMPRESS_LEVEL),
45
+ "headers": {"Content-Encoding": "gzip"},
46
+ }
47
+
15
48
 
16
49
  @dataclass(frozen=True)
17
50
  class HookTarget:
@@ -22,6 +55,7 @@ class HookTarget:
22
55
  HOOK_RELAY_TARGETS: dict[str, HookTarget] = {
23
56
  "enforce": HookTarget("/api/v1/hooks/cursor", ENFORCEMENT_HOOK_TIMEOUT_SECONDS),
24
57
  "event": HookTarget("/api/v1/hooks/events", EVENT_HOOK_TIMEOUT_SECONDS),
58
+ "mcp-usage": HookTarget("/api/v1/hooks/mcp-usage", EVENT_HOOK_TIMEOUT_SECONDS),
25
59
  # Tool lifecycle endpoints normalize into LocalToolPre/PostRequest for
26
60
  # scanning. Routing them to /events would silently downgrade enforcement.
27
61
  "tool-pre": HookTarget("/api/v1/hooks/tool/pre", ENFORCEMENT_HOOK_TIMEOUT_SECONDS),
@@ -44,9 +78,9 @@ class HookHTTPClient(Protocol):
44
78
  self,
45
79
  url: str,
46
80
  *,
47
- content: str,
81
+ content: str | bytes,
48
82
  headers: dict[str, str],
49
- timeout: int | float,
83
+ timeout: int | float | httpx.Timeout,
50
84
  ) -> HookHTTPResponse: ...
51
85
 
52
86
 
@@ -67,9 +101,9 @@ class FetchLikeHookHTTPClient:
67
101
  self,
68
102
  url: str,
69
103
  *,
70
- content: str,
104
+ content: str | bytes,
71
105
  headers: dict[str, str],
72
- timeout: int | float,
106
+ timeout: int | float | httpx.Timeout,
73
107
  ) -> FetchResponse:
74
108
  return self.fetch_impl(
75
109
  url,
@@ -86,11 +120,14 @@ def post_hook_endpoint(
86
120
  http_client: HookHTTPClient,
87
121
  base_url: str,
88
122
  endpoint: str,
89
- payload: str,
123
+ payload: str | bytes,
90
124
  *,
91
125
  headers: dict[str, str],
92
- timeout: int | float,
126
+ timeout: int | float | httpx.Timeout,
93
127
  ) -> HookHTTPResponse:
128
+ # Compression happens upstream via encode_wire_body: callers that opt in
129
+ # pre-encode the payload (and its Content-Encoding header) so they can
130
+ # also measure the wire size without re-compressing. bytes pass through.
94
131
  return http_client.post(
95
132
  f"{base_url.rstrip('/')}{endpoint}",
96
133
  content=payload,
@@ -117,9 +154,9 @@ class HookAPIClient:
117
154
  def post_target(
118
155
  self,
119
156
  target: str,
120
- payload: str,
157
+ payload: str | bytes,
121
158
  *,
122
- timeout: int | float | None = None,
159
+ timeout: int | float | httpx.Timeout | None = None,
123
160
  ) -> HookHTTPResponse:
124
161
  spec = HOOK_RELAY_TARGETS[target]
125
162
  effective_timeout = timeout if timeout is not None else spec.timeout
@@ -128,9 +165,9 @@ class HookAPIClient:
128
165
  def post_endpoint(
129
166
  self,
130
167
  endpoint: str,
131
- payload: str,
168
+ payload: str | bytes,
132
169
  *,
133
- timeout: int | float,
170
+ timeout: int | float | httpx.Timeout,
134
171
  ) -> HookHTTPResponse:
135
172
  with self.http_client_factory() as http_client:
136
173
  return post_hook_endpoint(
@@ -8,6 +8,7 @@ from uuid import uuid4
8
8
 
9
9
  if TYPE_CHECKING:
10
10
  from runlayer_sdk.client import RunlayerClient
11
+ from runlayer_sdk.types import JsonObject
11
12
 
12
13
 
13
14
  @dataclass(frozen=True)
@@ -24,6 +25,28 @@ class PreflightOptions(TypedDict, total=False):
24
25
  source: str
25
26
 
26
27
 
28
+ def _require_ingested(response: JsonObject | None) -> None:
29
+ if response is not None and response.get("status") == "ingested":
30
+ return
31
+
32
+ reason = response.get("reason") if response is not None else None
33
+ if reason == "sessions_disabled":
34
+ message = "The applicable MDM configuration disables Sessions."
35
+ elif reason == "client_not_enabled":
36
+ message = "SDK session monitoring is not enabled for this workspace."
37
+ else:
38
+ message = (
39
+ response.get("message")
40
+ if response is not None
41
+ else "Runlayer preflight event was not ingested."
42
+ )
43
+ message = (
44
+ message
45
+ or f"Runlayer preflight event was not ingested: {reason or 'unknown'}"
46
+ )
47
+ raise RuntimeError(message)
48
+
49
+
27
50
  def send_runlayer_preflight(
28
51
  runlayer: RunlayerClient,
29
52
  *,
@@ -35,7 +58,7 @@ def send_runlayer_preflight(
35
58
  session_id = f"python-sdk-preflight-{uuid4()}"
36
59
  timestamp = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
37
60
 
38
- runlayer.emit_event(
61
+ response = runlayer.emit_event(
39
62
  "SessionStart",
40
63
  {
41
64
  "cwd": cwd or os.getcwd(),
@@ -47,7 +70,9 @@ def send_runlayer_preflight(
47
70
  },
48
71
  strict=True,
49
72
  )
50
- runlayer.emit_event(
73
+ _require_ingested(response)
74
+
75
+ response = runlayer.emit_event(
51
76
  "UserPromptSubmit",
52
77
  {
53
78
  "model": model,
@@ -58,7 +83,9 @@ def send_runlayer_preflight(
58
83
  },
59
84
  strict=True,
60
85
  )
61
- runlayer.emit_event(
86
+ _require_ingested(response)
87
+
88
+ response = runlayer.emit_event(
62
89
  "Stop",
63
90
  {
64
91
  "model": model,
@@ -68,6 +95,7 @@ def send_runlayer_preflight(
68
95
  },
69
96
  strict=True,
70
97
  )
98
+ _require_ingested(response)
71
99
 
72
100
  return PreflightResult(
73
101
  client=runlayer.client_name,
@@ -1,6 +1,5 @@
1
1
  from __future__ import annotations
2
2
 
3
- import re
4
3
  from collections.abc import Sequence
5
4
  from typing import cast
6
5
  from urllib.parse import ParseResult, urljoin, urlparse
@@ -186,7 +185,26 @@ def _option_bool(
186
185
 
187
186
 
188
187
  def _has_explicit_origin_reference(value: str) -> bool:
189
- return bool(re.match(r"^[a-zA-Z][a-zA-Z\d+\-.]*:", value)) or value.startswith("//")
188
+ # Detects an RFC-3986 scheme prefix (``scheme:``) or a protocol-relative
189
+ # ``//`` origin. Pure string scan: a published SDK must not carry a
190
+ # regex-engine dependency for one prefix check. Semantics are exactly
191
+ # ``^[a-zA-Z][a-zA-Z\d+\-.]*:`` with Unicode-aware ``\d`` — first char an
192
+ # ASCII letter, then a run of scheme chars (ASCII letter, any Unicode
193
+ # decimal digit per ``str.isdecimal()`` == the ``Nd`` category, or one of
194
+ # ``+ - .``), then a colon.
195
+ if value.startswith("//"):
196
+ return True
197
+ if not value or not ("a" <= value[0] <= "z" or "A" <= value[0] <= "Z"):
198
+ return False
199
+ i = 1
200
+ while i < len(value) and (
201
+ "a" <= value[i] <= "z"
202
+ or "A" <= value[i] <= "Z"
203
+ or value[i] in "+-."
204
+ or value[i].isdecimal()
205
+ ):
206
+ i += 1
207
+ return i < len(value) and value[i] == ":"
190
208
 
191
209
 
192
210
  def _has_valid_explicit_host(value: str) -> bool:
@@ -199,10 +199,21 @@ def test_agent_account_auth_exchanges_and_reuses_bearer_token():
199
199
  def handler(request: httpx.Request) -> httpx.Response:
200
200
  requests.append(request)
201
201
  if request.url.path == "/api/v1/oauth/token":
202
+ form = parse_qs(request.content.decode())
203
+ grant_type = form.get("grant_type", [None])[0]
204
+ if grant_type == "client_credentials":
205
+ return httpx.Response(
206
+ 200,
207
+ json={
208
+ "access_token": "agent-actor-token",
209
+ "expires_in": 3600,
210
+ "token_type": "Bearer",
211
+ },
212
+ )
202
213
  return httpx.Response(
203
214
  200,
204
215
  json={
205
- "access_token": "agent-access-token",
216
+ "access_token": "obo-access-token",
206
217
  "expires_in": 3600,
207
218
  "token_type": "Bearer",
208
219
  },
@@ -224,19 +235,130 @@ def test_agent_account_auth_exchanges_and_reuses_bearer_token():
224
235
  client.emit_event("SessionStart", {"session_id": "sess-1"}, strict=True)
225
236
  client.emit_event("Stop", {"session_id": "sess-1"}, strict=True)
226
237
 
227
- form = parse_qs(requests[0].content.decode())
228
- assert requests[0].url.path == "/api/v1/oauth/token"
229
- assert requests[0].headers["Content-Type"] == "application/x-www-form-urlencoded"
230
- assert form == {
238
+ token_requests = [r for r in requests if r.url.path == "/api/v1/oauth/token"]
239
+ assert len(token_requests) == 2
240
+
241
+ actor_form = parse_qs(token_requests[0].content.decode())
242
+ assert (
243
+ token_requests[0].headers["Content-Type"] == "application/x-www-form-urlencoded"
244
+ )
245
+ assert actor_form == {
231
246
  "client_id": ["client_123"],
232
247
  "client_secret": ["secret_123"],
233
248
  "grant_type": ["client_credentials"],
249
+ }
250
+ assert "subject_token" not in actor_form
251
+ assert "actor_token" not in actor_form
252
+
253
+ exchange_form = parse_qs(token_requests[1].content.decode())
254
+ assert exchange_form == {
255
+ "grant_type": ["urn:ietf:params:oauth:grant-type:token-exchange"],
256
+ "actor_token": ["agent-actor-token"],
257
+ "actor_token_type": ["urn:ietf:params:oauth:token-type:access_token"],
234
258
  "subject_token": ["user@example.com"],
235
259
  "subject_token_type": ["urn:runlayer:token-type:user-email"],
236
260
  }
237
- assert requests[1].headers["Authorization"] == "Bearer agent-access-token"
238
- assert requests[2].headers["Authorization"] == "Bearer agent-access-token"
239
- assert [request.url.path for request in requests].count("/api/v1/oauth/token") == 1
261
+ assert "client_secret" not in exchange_form
262
+ assert "client_id" not in exchange_form
263
+
264
+ hook_requests = [r for r in requests if r.url.path != "/api/v1/oauth/token"]
265
+ assert hook_requests[0].headers["Authorization"] == "Bearer obo-access-token"
266
+ assert hook_requests[1].headers["Authorization"] == "Bearer obo-access-token"
267
+
268
+
269
+ def test_agent_account_m2m_uses_single_client_credentials_request():
270
+ requests = []
271
+
272
+ def handler(request: httpx.Request) -> httpx.Response:
273
+ requests.append(request)
274
+ if request.url.path == "/api/v1/oauth/token":
275
+ return httpx.Response(
276
+ 200,
277
+ json={
278
+ "access_token": "m2m-access-token",
279
+ "expires_in": 3600,
280
+ "token_type": "Bearer",
281
+ },
282
+ )
283
+ return httpx.Response(200, json={})
284
+
285
+ client = RunlayerClient(
286
+ agent_account={
287
+ "client_id": "client_123",
288
+ "client_secret": "secret_123",
289
+ },
290
+ allow_insecure_transport=True,
291
+ base_url="http://tenant.runlayer.test",
292
+ http_client=httpx.Client(transport=httpx.MockTransport(handler)),
293
+ )
294
+
295
+ client.emit_event("SessionStart", {"session_id": "sess-1"}, strict=True)
296
+ client.emit_event("Stop", {"session_id": "sess-1"}, strict=True)
297
+
298
+ token_requests = [r for r in requests if r.url.path == "/api/v1/oauth/token"]
299
+ assert len(token_requests) == 1
300
+ form = parse_qs(token_requests[0].content.decode())
301
+ assert form == {
302
+ "client_id": ["client_123"],
303
+ "client_secret": ["secret_123"],
304
+ "grant_type": ["client_credentials"],
305
+ }
306
+ assert "subject_token" not in form
307
+ assert "actor_token" not in form
308
+
309
+
310
+ def test_agent_account_reuses_cached_actor_token_across_exchange_refreshes(monkeypatch):
311
+ client_credentials_requests = 0
312
+ token_exchange_requests = 0
313
+
314
+ def handler(request: httpx.Request) -> httpx.Response:
315
+ nonlocal client_credentials_requests, token_exchange_requests
316
+ if request.url.path == "/api/v1/oauth/token":
317
+ form = parse_qs(request.content.decode())
318
+ grant_type = form.get("grant_type", [None])[0]
319
+ if grant_type == "client_credentials":
320
+ client_credentials_requests += 1
321
+ return httpx.Response(
322
+ 200,
323
+ json={
324
+ "access_token": "agent-actor-token",
325
+ "expires_in": 3600,
326
+ "token_type": "Bearer",
327
+ },
328
+ )
329
+ token_exchange_requests += 1
330
+ return httpx.Response(
331
+ 200,
332
+ json={
333
+ "access_token": f"obo-access-token-{token_exchange_requests}",
334
+ "expires_in": 30,
335
+ "token_type": "Bearer",
336
+ },
337
+ )
338
+ return httpx.Response(200, json={})
339
+
340
+ client = RunlayerClient(
341
+ agent_account={
342
+ "client_id": "client_123",
343
+ "client_secret": "secret_123",
344
+ "subject_token": "user@example.com",
345
+ "subject_token_type": "urn:runlayer:token-type:user-email",
346
+ "token_refresh_window_ms": 60_000,
347
+ },
348
+ allow_insecure_transport=True,
349
+ base_url="http://tenant.runlayer.test",
350
+ http_client=httpx.Client(transport=httpx.MockTransport(handler)),
351
+ )
352
+
353
+ now = 1_000.0
354
+ monkeypatch.setattr(client_module.time, "time", lambda: now)
355
+
356
+ client.emit_event("SessionStart", {"session_id": "sess-1"}, strict=True)
357
+ now += 25.0
358
+ client.emit_event("Stop", {"session_id": "sess-1"}, strict=True)
359
+
360
+ assert client_credentials_requests == 1
361
+ assert token_exchange_requests >= 2
240
362
 
241
363
 
242
364
  def test_agent_account_auth_coalesces_concurrent_token_refreshes():
@@ -580,6 +702,24 @@ def test_emit_event_warns_once_when_server_ignores_client_not_enabled(capsys):
580
702
  assert "send_runlayer_preflight" in err
581
703
 
582
704
 
705
+ def test_emit_event_warns_once_when_mdm_disables_session_reporting(capsys):
706
+ client, _requests = make_client(
707
+ [
708
+ {"status": "ignored", "reason": "sessions_disabled"},
709
+ {"status": "ignored", "reason": "sessions_disabled"},
710
+ ]
711
+ )
712
+
713
+ client.emit_event("SessionStart", {"session_id": "sess-1"})
714
+ client.emit_event("Stop", {"session_id": "sess-1"})
715
+
716
+ err = capsys.readouterr().err
717
+ assert err.count("status=ignored") == 1
718
+ assert "sessions_disabled" in err
719
+ assert "MDM configuration disables session reporting" in err
720
+ assert "contact your runlayer administrator" in err.lower()
721
+
722
+
583
723
  def test_emit_event_surfaces_org_key_guidance_on_actor_unresolved(capsys):
584
724
  client, _requests = make_client(
585
725
  [{"status": "ignored", "reason": "actor_unresolved"}]
@@ -610,7 +750,13 @@ def test_emit_event_stays_quiet_on_transient_ignored_without_debug(capsys, monke
610
750
 
611
751
 
612
752
  def test_send_runlayer_preflight_emits_strict_session_events():
613
- client, requests = make_client([{}, {}, {}])
753
+ client, requests = make_client(
754
+ [
755
+ {"status": "ingested"},
756
+ {"status": "ingested"},
757
+ {"status": "ingested"},
758
+ ]
759
+ )
614
760
 
615
761
  result = send_runlayer_preflight(client, cwd="/workspace", prompt="preflight")
616
762
 
@@ -626,3 +772,14 @@ def test_send_runlayer_preflight_emits_strict_session_events():
626
772
  assert payload["cwd"] == "/workspace"
627
773
  assert payload["prompt"] == "preflight"
628
774
  assert payload["session_id"] == result.session_id
775
+
776
+
777
+ def test_send_runlayer_preflight_fails_when_mdm_disables_sessions():
778
+ client, requests = make_client(
779
+ [{"status": "ignored", "reason": "sessions_disabled"}]
780
+ )
781
+
782
+ with pytest.raises(RuntimeError, match="MDM configuration disables Sessions"):
783
+ send_runlayer_preflight(client)
784
+
785
+ assert len(requests) == 1
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+
3
+ import gzip
4
+ import json
5
+
6
+ from runlayer_sdk.hook_transport import (
7
+ GZIP_MIN_PAYLOAD_BYTES,
8
+ HookAPIClient,
9
+ encode_wire_body,
10
+ post_hook_endpoint,
11
+ )
12
+
13
+ _LARGE_PAYLOAD = json.dumps({"transcript": "x" * (GZIP_MIN_PAYLOAD_BYTES + 1024)})
14
+ _SMALL_PAYLOAD = json.dumps({"k": "v"})
15
+
16
+
17
+ class _Response:
18
+ text = "{}"
19
+ status_code = 200
20
+ is_success = True
21
+
22
+ def json(self):
23
+ return {}
24
+
25
+
26
+ class _CapturingHTTPClient:
27
+ def __init__(self) -> None:
28
+ self.calls: list[dict] = []
29
+
30
+ def __enter__(self) -> _CapturingHTTPClient:
31
+ return self
32
+
33
+ def __exit__(self, *_args: object) -> None:
34
+ pass
35
+
36
+ def post(self, url, *, content, headers, timeout):
37
+ self.calls.append(
38
+ {"url": url, "content": content, "headers": headers, "timeout": timeout}
39
+ )
40
+ return _Response()
41
+
42
+
43
+ class TestEncodeWireBody:
44
+ def test_default_is_identity(self):
45
+ wire = encode_wire_body(_LARGE_PAYLOAD)
46
+ assert wire["content"] == _LARGE_PAYLOAD
47
+ assert wire["headers"] == {}
48
+
49
+ def test_small_payload_not_compressed_even_when_opted_in(self):
50
+ wire = encode_wire_body(_SMALL_PAYLOAD, compress=True)
51
+ assert wire["content"] == _SMALL_PAYLOAD
52
+ assert wire["headers"] == {}
53
+
54
+ def test_payload_at_threshold_not_compressed(self):
55
+ payload = "x" * GZIP_MIN_PAYLOAD_BYTES
56
+ wire = encode_wire_body(payload, compress=True)
57
+ assert wire["content"] == payload
58
+ assert wire["headers"] == {}
59
+
60
+ def test_large_payload_compressed_with_header_and_round_trips(self):
61
+ wire = encode_wire_body(_LARGE_PAYLOAD, compress=True)
62
+ content = wire["content"]
63
+ assert isinstance(content, bytes)
64
+ assert len(content) < len(_LARGE_PAYLOAD.encode("utf-8"))
65
+ assert wire["headers"] == {"Content-Encoding": "gzip"}
66
+ assert gzip.decompress(content).decode("utf-8") == _LARGE_PAYLOAD
67
+
68
+ def test_bytes_input_passes_through_without_double_compression(self):
69
+ pre_encoded = encode_wire_body(_LARGE_PAYLOAD, compress=True)["content"]
70
+ assert isinstance(pre_encoded, bytes)
71
+ wire = encode_wire_body(pre_encoded, compress=True)
72
+ assert wire["content"] is pre_encoded
73
+ assert wire["headers"] == {}
74
+
75
+
76
+ class TestPostHookEndpoint:
77
+ def test_str_payload_sent_identity(self):
78
+ http_client = _CapturingHTTPClient()
79
+ post_hook_endpoint(
80
+ http_client,
81
+ "https://api.example.test",
82
+ "/api/v1/hooks/events",
83
+ _LARGE_PAYLOAD,
84
+ headers={},
85
+ timeout=5,
86
+ )
87
+ (call,) = http_client.calls
88
+ assert call["content"] == _LARGE_PAYLOAD
89
+ assert "Content-Encoding" not in call["headers"]
90
+
91
+ def test_pre_encoded_bytes_and_headers_pass_through_untouched(self):
92
+ """Compression lives in encode_wire_body; the transport posts exactly
93
+ the bytes + headers the caller pre-encoded."""
94
+ wire = encode_wire_body(_LARGE_PAYLOAD, compress=True)
95
+ http_client = _CapturingHTTPClient()
96
+ post_hook_endpoint(
97
+ http_client,
98
+ "https://api.example.test",
99
+ "/api/v1/hooks/events",
100
+ wire["content"],
101
+ headers={"x-runlayer-api-key": "sk", **wire["headers"]},
102
+ timeout=5,
103
+ )
104
+ (call,) = http_client.calls
105
+ assert call["content"] is wire["content"]
106
+ assert call["headers"]["Content-Encoding"] == "gzip"
107
+ assert call["headers"]["x-runlayer-api-key"] == "sk"
108
+ assert gzip.decompress(call["content"]).decode("utf-8") == _LARGE_PAYLOAD
109
+
110
+ def test_post_target_sends_payload_as_given(self):
111
+ http_client = _CapturingHTTPClient()
112
+ client = HookAPIClient(
113
+ "https://api.example.test",
114
+ headers={},
115
+ http_client_factory=lambda: http_client,
116
+ )
117
+ client.post_target("event", _LARGE_PAYLOAD)
118
+ (call,) = http_client.calls
119
+ assert call["url"].endswith("/api/v1/hooks/events")
120
+ assert call["content"] == _LARGE_PAYLOAD
121
+ assert "Content-Encoding" not in call["headers"]
@@ -0,0 +1,11 @@
1
+ from pathlib import Path
2
+
3
+
4
+ PACKAGE_ROOT = Path(__file__).parents[1]
5
+
6
+
7
+ def test_package_ships_apache_2_license_text():
8
+ license_text = (PACKAGE_ROOT / "LICENSE").read_text()
9
+
10
+ assert "Apache License" in license_text
11
+ assert "Version 2.0, January 2004" in license_text
@@ -225,3 +225,51 @@ def test_client_sends_tool_url_to_enforcement_filter_only():
225
225
  "/api/v1/hooks/events",
226
226
  ]
227
227
  assert "tool_url" not in request_json(requests[1])
228
+
229
+
230
+ # regex-engine: stdlib-parity
231
+ def test_has_explicit_origin_reference_matches_old_regex():
232
+ """Pins the pure-string scheme detector to the pre-RE2 regex exactly,
233
+ including the Unicode-decimal-digit behavior of the old ``\\d`` (ENG-4056)."""
234
+ import random
235
+ import re as stdlib_re
236
+
237
+ from runlayer_sdk.tool_enforcement import _has_explicit_origin_reference
238
+
239
+ old = stdlib_re.compile(r"^[a-zA-Z][a-zA-Z\d+\-.]*:")
240
+
241
+ def old_impl(value: str) -> bool:
242
+ return bool(old.match(value)) or value.startswith("//")
243
+
244
+ corpus = [
245
+ "",
246
+ "http://x",
247
+ "https://x",
248
+ "mailto:a@b",
249
+ "a+b-c.d:rest",
250
+ "//protocol-relative",
251
+ "/single-slash",
252
+ "no-scheme-here",
253
+ "1http:", # leading digit -> not a scheme
254
+ "+bad:", # leading + -> not a scheme
255
+ ".bad:",
256
+ "a b:", # space breaks the run before the colon
257
+ "scheme", # no colon
258
+ "scheme:",
259
+ "x:",
260
+ "HTTP://X",
261
+ "a:",
262
+ "://",
263
+ "a²:", # superscript-2 (category No) — NOT \d, breaks the run
264
+ "a٠:", # Arabic-Indic digit (category Nd) — IS \d
265
+ "a\n:",
266
+ "urn:isbn:0451450523",
267
+ ]
268
+ for v in corpus:
269
+ assert _has_explicit_origin_reference(v) == old_impl(v), repr(v)
270
+
271
+ rng = random.Random(4056)
272
+ alphabet = "abAB01+-.: /²٠\t"
273
+ for _ in range(2000):
274
+ v = "".join(rng.choices(alphabet, k=rng.randint(0, 8)))
275
+ assert _has_explicit_origin_reference(v) == old_impl(v), repr(v)
@@ -3,7 +3,7 @@ revision = 3
3
3
  requires-python = ">=3.10"
4
4
 
5
5
  [options]
6
- exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
6
+ exclude-newer = "2026-08-04T20:02:56.085185Z"
7
7
  exclude-newer-span = "P7D"
8
8
 
9
9
  [[package]]
@@ -177,7 +177,7 @@ wheels = [
177
177
 
178
178
  [[package]]
179
179
  name = "runlayer-hooks-sdk"
180
- version = "0.2.0"
180
+ version = "0.2.2"
181
181
  source = { editable = "." }
182
182
  dependencies = [
183
183
  { name = "httpx" },