@withgateway/sdk 0.3.3 → 0.6.0

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 (158) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +3005 -1401
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +2996 -1392
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.js +128 -37
  7. package/dist/files/index.js.map +1 -1
  8. package/dist/files/index.mjs +126 -35
  9. package/dist/files/index.mjs.map +1 -1
  10. package/dist/hooks/index.d.mts +1 -1
  11. package/dist/hooks/index.d.ts +1 -1
  12. package/dist/hooks/index.js +124 -11
  13. package/dist/hooks/index.js.map +1 -1
  14. package/dist/hooks/index.mjs +124 -11
  15. package/dist/hooks/index.mjs.map +1 -1
  16. package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
  17. package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
  18. package/dist/{index-mJhG3vZU.d.mts → index-Di9nNqOY.d.mts} +26 -3
  19. package/dist/{index-DUHmS74p.d.ts → index-LA-PMRJT.d.ts} +26 -3
  20. package/dist/index.d.mts +4 -4
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +1078 -260
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +1040 -251
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/replay/index.d.mts +1 -1
  27. package/dist/replay/index.d.ts +1 -1
  28. package/dist/replay/index.js.map +1 -1
  29. package/dist/replay/index.mjs.map +1 -1
  30. package/dist/traces/index.js +125 -34
  31. package/dist/traces/index.js.map +1 -1
  32. package/dist/traces/index.mjs +123 -32
  33. package/dist/traces/index.mjs.map +1 -1
  34. package/dist/tracing/index.d.mts +1 -1
  35. package/dist/tracing/index.d.ts +1 -1
  36. package/dist/tracing/index.js +7 -1
  37. package/dist/tracing/index.js.map +1 -1
  38. package/dist/tracing/index.mjs +7 -1
  39. package/dist/tracing/index.mjs.map +1 -1
  40. package/dist/worlds/index.d.mts +819 -438
  41. package/dist/worlds/index.d.ts +819 -438
  42. package/dist/worlds/index.js +912 -236
  43. package/dist/worlds/index.js.map +1 -1
  44. package/dist/worlds/index.mjs +908 -232
  45. package/dist/worlds/index.mjs.map +1 -1
  46. package/package.json +1 -1
  47. package/runtime/gatewaysdk/environment/_bundle.py +4 -6
  48. package/runtime/gatewaysdk/environment/_materialize.py +5 -25
  49. package/runtime/gatewaysdk/environment/_world.py +82 -66
  50. package/runtime/gatewaysdk/environment/backing.py +20 -24
  51. package/runtime/gatewaysdk/environment/core.py +1 -16
  52. package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
  53. package/runtime/gatewaysdk/environment/runtime.py +45 -2
  54. package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
  55. package/runtime/gatewaysdk/environment/schema/api.py +198 -474
  56. package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
  57. package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
  58. package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
  59. package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
  60. package/runtime/gatewaysdk/environment/schema/call_capture.py +321 -0
  61. package/runtime/gatewaysdk/environment/schema/call_log.py +276 -18
  62. package/runtime/gatewaysdk/environment/schema/call_redaction.py +207 -19
  63. package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
  64. package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
  65. package/runtime/gatewaysdk/environment/schema/conform.py +38 -35
  66. package/runtime/gatewaysdk/environment/schema/connector.py +94 -152
  67. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
  68. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
  69. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
  70. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +10 -19
  71. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
  72. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
  75. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
  76. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
  77. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
  78. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
  79. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
  80. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
  81. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
  82. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
  83. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
  84. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
  85. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
  86. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
  87. package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
  88. package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
  89. package/runtime/gatewaysdk/environment/schema/data.py +14 -13
  90. package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
  91. package/runtime/gatewaysdk/environment/schema/database/guard.py +45 -37
  92. package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
  93. package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
  94. package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
  95. package/runtime/gatewaysdk/environment/schema/door.py +899 -0
  96. package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
  97. package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
  98. package/runtime/gatewaysdk/environment/schema/handler_errors.py +52 -5
  99. package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
  100. package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
  101. package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
  102. package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
  103. package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
  104. package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
  105. package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
  106. package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
  107. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
  108. package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
  109. package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
  110. package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
  111. package/runtime/gatewaysdk/environment/schema/journal.py +438 -0
  112. package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
  113. package/runtime/gatewaysdk/environment/schema/local.py +32 -116
  114. package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
  115. package/runtime/gatewaysdk/environment/schema/platform.py +29 -234
  116. package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
  117. package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
  118. package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
  119. package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
  120. package/runtime/gatewaysdk/environment/schema/runtime.py +136 -176
  121. package/runtime/gatewaysdk/environment/schema/scaffold.py +2 -1
  122. package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
  123. package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
  124. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
  125. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
  126. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  127. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +50 -28
  128. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
  129. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +20 -22
  130. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +25 -25
  131. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
  132. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +71 -7
  133. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
  134. package/runtime/gatewaysdk/environment/schema/snapshot.py +150 -30
  135. package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
  136. package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
  137. package/runtime/gatewaysdk/environment/schema/tools_world.py +103 -203
  138. package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
  139. package/runtime/gatewaysdk/environment/schema/verbs.py +38 -36
  140. package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
  141. package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
  142. package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
  143. package/runtime/gatewaysdk/environment/schema/world_host.py +970 -0
  144. package/runtime/gatewaysdk/environment/schema/world_tests.py +83 -11
  145. package/runtime/gatewaysdk/environment/world.py +1 -1
  146. package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
  147. package/skills/agents/connector-template-author.md +5 -1
  148. package/skills/benchmarks-getting-started/SKILL.md +8 -9
  149. package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
  150. package/skills/connector-schema-authoring/SKILL.md +50 -28
  151. package/skills/connector-schema-authoring/connector-worlds.md +282 -18
  152. package/skills/connector-schema-authoring/world-schema.md +7 -6
  153. package/skills/world-data-ingestion/ROWS.md +12 -8
  154. package/skills/world-data-ingestion/SKILL.md +20 -22
  155. package/skills/worlds-getting-started/SKILL.md +25 -25
  156. package/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
  157. package/skills/worlds-getting-started/references/gotchas.md +71 -7
  158. package/skills/worlds-getting-started/references/journal-checks.md +182 -0
@@ -0,0 +1,321 @@
1
+ """What the world request ledger keeps of one request a session's world answered: the
2
+ request's headers and each body's first :data:`CAPTURE_BYTES` as text, beside the
3
+ body's size as it went over the wire (``bodyBytes``) and whether the text was cut
4
+ (``truncated``).
5
+
6
+ A JSON body is kept as the call log keeps a request (:class:`CallRedaction`): a
7
+ credential by its name or its shape reads ``[redacted]``, and only the part of the
8
+ body the capture keeps is walked, so a large answer costs no more than its first
9
+ :data:`CAPTURE_BYTES`. A request's body is what the world read (a form's fields
10
+ included), redacted and written as JSON, so its text is not the wire's bytes; a
11
+ body the world did not read (a GET's) is not kept and reads ``truncated``. A body
12
+ answered as bytes is kept as its text when its first :data:`CAPTURE_BYTES` are UTF-8
13
+ and not at all when they are not (``body: null`` beside its size). Every body kept,
14
+ JSON or text, is scrubbed of the secrets it embeds before it is cut
15
+ (:meth:`CallRedaction.scrub`: the session's credential as sent and percent-encoded,
16
+ the value of a query parameter the world's ``[auth]`` carries a secret in, a JSON Web
17
+ Token), read :data:`~.call_redaction.SCRUB_MARGIN` past the cut so a secret across it
18
+ is seen whole; text the capture did not read to its end keeps nothing within that
19
+ margin of where it stopped. Header values are kept only under names that
20
+ say what they are (:meth:`CallRedaction.headers`), and each content type is its
21
+ first :data:`CONTENT_TYPE_CHARS` characters, the request's read from its kept
22
+ header.
23
+
24
+ A tool called by name is an exchange too: its arguments are the request's body and
25
+ its answer the response's, each as JSON. An exchange the request ledger's outbox sheds
26
+ (:class:`~.request_ledger.RequestOutbox`) keeps its sizes and status and gives up its
27
+ headers, text and content types, each body then ``truncated``.
28
+
29
+ The answer as the ledger keeps it is the answer as it goes on the wire
30
+ (:class:`ServedAnswer`), written by every world server (:class:`WorldRequestHandler`); a HEAD is
31
+ kept as the GET it mirrors, whose body the wire leaves off.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ from dataclasses import dataclass, replace
38
+ from http.server import BaseHTTPRequestHandler
39
+ from typing import TYPE_CHECKING, Any
40
+
41
+ from ..world_session_contract import REQUEST_BODY_CAPTURE_BYTES
42
+ from .call_redaction import SCRUB_MARGIN, CallRedaction
43
+
44
+ if TYPE_CHECKING:
45
+ from .webhooks import Delivery, WebhookAnswer
46
+
47
+ CAPTURE_BYTES = REQUEST_BODY_CAPTURE_BYTES
48
+ CONTENT_TYPE_CHARS = 256
49
+ JSON_TYPE = "application/json"
50
+ _MAX_CUT_CHARACTER = 3
51
+
52
+
53
+ def _utf8(head: bytes, cut: bool) -> str | None:
54
+ """``head`` as text, or None when it is not UTF-8. A head cut from a longer body
55
+ may end inside a character, whose bytes are let go; a whole body is text only
56
+ when every byte of it is."""
57
+ for trim in range(_MAX_CUT_CHARACTER + 1 if cut else 1):
58
+ try:
59
+ return head[: len(head) - trim].decode("utf-8")
60
+ except UnicodeDecodeError:
61
+ continue
62
+ return None
63
+
64
+
65
+ def _utf8_lead(head: bytes) -> int:
66
+ """How many leading bytes of ``head`` are UTF-8."""
67
+ try:
68
+ head.decode("utf-8")
69
+ except UnicodeDecodeError as error:
70
+ return error.start
71
+ return len(head)
72
+
73
+
74
+ def _typed(content_type: Any) -> str | None:
75
+ return None if content_type is None else str(content_type)[:CONTENT_TYPE_CHARS]
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class ServedAnswer:
80
+ """One ``WorldApp`` answer as it goes on the wire: nothing for a 204 or a
81
+ ``None``, bytes as they are, anything else as JSON labelled
82
+ ``application/json`` (an error ``error_content_type``) unless the answer named
83
+ its own type."""
84
+
85
+ headers: dict[str, str]
86
+ payload: bytes
87
+
88
+ @classmethod
89
+ def of(cls, status: int, body: Any, extra: dict[str, str] | None, error_content_type: str) -> ServedAnswer:
90
+ headers = dict(extra or {})
91
+ if status == 204 or body is None:
92
+ return cls(headers, b"")
93
+ if isinstance(body, bytes):
94
+ return cls(headers, body)
95
+ labelled = {"Content-Type": error_content_type if status >= 400 else "application/json", **headers}
96
+ return cls(labelled, json.dumps(body, ensure_ascii=False).encode("utf-8"))
97
+
98
+ @property
99
+ def content_type(self) -> str | None:
100
+ return next((value for name, value in self.headers.items() if name.lower() == "content-type"), None)
101
+
102
+
103
+ def send_response(
104
+ handler: BaseHTTPRequestHandler, status: int, body: Any, extra: dict[str, str] | None, error_content_type: str
105
+ ) -> None:
106
+ """Write one ``WorldApp`` answer to a request handler's socket."""
107
+ answer = ServedAnswer.of(status, body, extra, error_content_type)
108
+ handler.send_response(status)
109
+ for name, value in answer.headers.items():
110
+ handler.send_header(name, value)
111
+ handler.send_header("Content-Length", str(len(answer.payload)))
112
+ handler.end_headers()
113
+ write_body(handler, answer.payload)
114
+
115
+
116
+ def write_body(handler: BaseHTTPRequestHandler, payload: bytes) -> None:
117
+ """An answer's body, left off the wire for a HEAD, whose headers are the GET's."""
118
+ if handler.command != "HEAD":
119
+ handler.wfile.write(payload)
120
+
121
+
122
+ class WorldRequestHandler(BaseHTTPRequestHandler):
123
+ """The methods every world server answers, each through :meth:`_dispatch`: HEAD as the GET
124
+ it mirrors (:func:`write_body` leaves its body off), OPTIONS as the world answers it. A
125
+ request the standard library refuses before any of them (another method, a malformed
126
+ request line) is answered in JSON, never the library's HTML page. No request is
127
+ access-logged: a query-auth world's key rides the request line."""
128
+
129
+ def _dispatch(self, method: str) -> None:
130
+ raise NotImplementedError
131
+
132
+ def log_message(self, format: str, *args: object) -> None:
133
+ pass
134
+
135
+ def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None:
136
+ self.close_connection = True
137
+ reason = self.responses.get(code, ("error",))[0]
138
+ send_response(self, code, {"error": reason}, {"Connection": "close"}, JSON_TYPE)
139
+
140
+ def do_GET(self) -> None:
141
+ self._dispatch("GET")
142
+
143
+ def do_HEAD(self) -> None:
144
+ self._dispatch("GET")
145
+
146
+ def do_POST(self) -> None:
147
+ self._dispatch("POST")
148
+
149
+ def do_PUT(self) -> None:
150
+ self._dispatch("PUT")
151
+
152
+ def do_PATCH(self) -> None:
153
+ self._dispatch("PATCH")
154
+
155
+ def do_DELETE(self) -> None:
156
+ self._dispatch("DELETE")
157
+
158
+ def do_OPTIONS(self) -> None:
159
+ self._dispatch("OPTIONS")
160
+
161
+
162
+ @dataclass(frozen=True)
163
+ class Served:
164
+ """What the request ledger reads of one route request beyond what the call log
165
+ keeps: the headers the world read, the body's size as it arrived, the
166
+ answer's own headers, how the world labels an error, and the session's token,
167
+ which no kept header may carry."""
168
+
169
+ headers: dict[str, str]
170
+ body_bytes: int
171
+ extra: dict[str, str] | None
172
+ error_content_type: str
173
+ secret: str | None
174
+ read_body: bool = True
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class CapturedBody:
179
+ """One body as the request ledger keeps it (module docstring); ``size`` is None
180
+ for a value that could not be written as JSON."""
181
+
182
+ content_type: str | None
183
+ size: int | None
184
+ text: str | None = None
185
+ truncated: bool = False
186
+
187
+ @classmethod
188
+ def of_request(cls, body: Any, served: Served, content_type: Any, redaction: CallRedaction) -> CapturedBody:
189
+ typed, size = _typed(content_type), served.body_bytes
190
+ if size == 0:
191
+ return cls(typed, 0)
192
+ if not served.read_body:
193
+ return cls(typed, size, None, True)
194
+ return cls.of_value(body, size, typed, redaction)
195
+
196
+ @classmethod
197
+ def of_answer(cls, status: int, answer: Any, served: Served, redaction: CallRedaction) -> CapturedBody:
198
+ try:
199
+ wire = ServedAnswer.of(status, answer, served.extra, served.error_content_type)
200
+ except (RecursionError, TypeError, ValueError):
201
+ return cls(None, None, None, True)
202
+ size, content_type = len(wire.payload), _typed(wire.content_type)
203
+ if size == 0:
204
+ return cls(content_type, 0)
205
+ if isinstance(answer, bytes):
206
+ return cls.of_bytes(wire.payload, content_type, redaction)
207
+ return cls.of_value(answer, size, content_type, redaction)
208
+
209
+ @classmethod
210
+ def of_document(cls, value: Any, redaction: CallRedaction) -> CapturedBody:
211
+ """A tool's arguments or answer: the JSON it is, its size as JSON."""
212
+ if value is None:
213
+ return cls(None, 0)
214
+ try:
215
+ size = len(json.dumps(value, ensure_ascii=False).encode("utf-8", "replace"))
216
+ except (RecursionError, TypeError, ValueError):
217
+ return cls(JSON_TYPE, None, None, True)
218
+ return cls.of_value(value, size, JSON_TYPE, redaction)
219
+
220
+ @classmethod
221
+ def of_bytes(cls, payload: bytes, content_type: str | None, redaction: CallRedaction) -> CapturedBody:
222
+ """A body answered as bytes (module docstring): the UTF-8 text of its first
223
+ :data:`CAPTURE_BYTES` and :data:`SCRUB_MARGIN` more, scrubbed, then cut."""
224
+ head = payload[: CAPTURE_BYTES + SCRUB_MARGIN]
225
+ lead = _utf8_lead(head)
226
+ whole = lead == len(payload)
227
+ if lead < (len(payload) if len(payload) <= CAPTURE_BYTES else CAPTURE_BYTES - _MAX_CUT_CHARACTER):
228
+ return cls(_typed(content_type), len(payload))
229
+ scrubbed = redaction.scrub(head[:lead].decode("utf-8")).encode("utf-8")
230
+ limit = CAPTURE_BYTES if whole else max(0, min(CAPTURE_BYTES, len(scrubbed) - SCRUB_MARGIN))
231
+ cut = not whole or len(scrubbed) > CAPTURE_BYTES
232
+ return cls(_typed(content_type), len(payload), _utf8(scrubbed[:limit], cut), cut)
233
+
234
+ @classmethod
235
+ def of_value(cls, value: Any, size: int, content_type: str | None, redaction: CallRedaction) -> CapturedBody:
236
+ try:
237
+ kept, cut = redaction.prefix(value, CAPTURE_BYTES)
238
+ text = redaction.scrub(json.dumps(kept, ensure_ascii=False))
239
+ except (RecursionError, TypeError, ValueError):
240
+ return cls(content_type, size, None, True)
241
+ encoded = text.encode("utf-8", "replace")
242
+ longer = len(encoded) > CAPTURE_BYTES
243
+ return cls(content_type, size, _utf8(encoded[:CAPTURE_BYTES], longer), cut or longer)
244
+
245
+ @classmethod
246
+ def from_json(cls, data: dict) -> CapturedBody:
247
+ return cls(data.get("contentType"), data.get("bodyBytes"), data.get("body"), bool(data.get("truncated")))
248
+
249
+ def shed(self) -> CapturedBody:
250
+ return replace(self, text=None, content_type=None, truncated=self.truncated or self.text is not None)
251
+
252
+ @property
253
+ def charge(self) -> int:
254
+ return len(self.text or "") + len(self.content_type or "")
255
+
256
+ def as_json(self) -> dict:
257
+ return {
258
+ "body": self.text,
259
+ "bodyBytes": self.size,
260
+ "truncated": self.truncated,
261
+ "contentType": self.content_type,
262
+ }
263
+
264
+
265
+ @dataclass(frozen=True)
266
+ class Exchange:
267
+ """One HTTP request a session's world answered and the answer it gave, as
268
+ the request ledger keeps them."""
269
+
270
+ headers: dict[str, str]
271
+ request: CapturedBody
272
+ status: int
273
+ response: CapturedBody
274
+
275
+ @classmethod
276
+ def of(cls, served: Served, body: Any, status: int, answer: Any, redaction: CallRedaction) -> Exchange:
277
+ headers = redaction.headers(served.headers, served.secret, CAPTURE_BYTES)
278
+ return cls(
279
+ headers,
280
+ CapturedBody.of_request(body, served, headers.get("content-type"), redaction),
281
+ status,
282
+ CapturedBody.of_answer(status, answer, served, redaction),
283
+ )
284
+
285
+ @classmethod
286
+ def of_tool(cls, args: Any, status: int, answer: Any, redaction: CallRedaction) -> Exchange:
287
+ """A tool called by name: its arguments are what was asked, its answer what came back."""
288
+ return cls({}, CapturedBody.of_document(args, redaction), status, CapturedBody.of_document(answer, redaction))
289
+
290
+ @classmethod
291
+ def of_webhook(cls, delivery: Delivery, answer: WebhookAnswer, redaction: CallRedaction) -> Exchange:
292
+ """A delivery the world sent: its signed headers and body, and the receiver's answer
293
+ (status 0 and no body until one answered; an error it never answered with as the body)."""
294
+ headers = redaction.headers(delivery.headers, redaction.secret, CAPTURE_BYTES)
295
+ error = None if answer.error is None else {"error": answer.error}
296
+ sent = CapturedBody.of_document(delivery.event.body, redaction)
297
+ return cls(headers, sent, answer.status, CapturedBody.of_document(error, redaction))
298
+
299
+ @classmethod
300
+ def from_json(cls, data: dict) -> Exchange:
301
+ request, response = data.get("request") or {}, data.get("response") or {}
302
+ return cls(
303
+ dict(request.get("headers") or {}),
304
+ CapturedBody.from_json(request),
305
+ int(response.get("status") or 0),
306
+ CapturedBody.from_json(response),
307
+ )
308
+
309
+ def shed(self) -> Exchange:
310
+ return Exchange({}, self.request.shed(), self.status, self.response.shed())
311
+
312
+ @property
313
+ def charge(self) -> int:
314
+ held = sum(len(name) + len(str(value)) for name, value in self.headers.items())
315
+ return held + self.request.charge + self.response.charge
316
+
317
+ def as_json(self) -> dict:
318
+ return {
319
+ "request": {"headers": self.headers, **self.request.as_json()},
320
+ "response": {"status": self.status, **self.response.as_json()},
321
+ }