aliasgate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ """Anthropic Messages, `POST /v1/messages` and `POST /v1/messages/count_tokens` (architecture §6).
2
+
3
+ Request, response and streaming shapes checked on 2026-11-18 against the Messages API
4
+ reference, the streaming guide and the errors page on platform.claude.com.
5
+
6
+ Slot order, which placeholder numbering follows:
7
+
8
+ 1. `system`: the string, or each of its `text` blocks in order;
9
+ 2. each message in order (any role): `content` as a string, or its blocks in order, where a
10
+ `text` block is one slot, a `tool_use` block gives a slot per string value of its `input`,
11
+ and a `tool_result` block gives its `content` string, or its inner blocks by the same rules;
12
+ 3. if the policy says so, every `description` string inside `tools`.
13
+
14
+ `thinking` and `redacted_thinking` blocks carry a provider signature over their exact content
15
+ and are never slots, in either direction. Every other block type is uninspectable content.
16
+
17
+ Where the dialect expects a shape and finds another, it raises MalformedRequestError naming the
18
+ position (for example `messages[2].content[0].input`), never the content.
19
+ """
20
+
21
+ import json
22
+ from typing import Any, Final
23
+
24
+ from aliasgate.dialects.base import (
25
+ MalformedRequestError,
26
+ Policy,
27
+ PreparedRequest,
28
+ Slot,
29
+ StreamTransformer,
30
+ UnsupportedContentError,
31
+ key_slot,
32
+ restore_all_strings,
33
+ slots_for_json_strings,
34
+ slots_for_key_strings,
35
+ )
36
+ from aliasgate.dialects.sse import SSEEvent
37
+ from aliasgate.engine import count_unresolved, restore
38
+ from aliasgate.mapping import Mapping
39
+ from aliasgate.stream import StreamRestorer
40
+
41
+ _SIGNED_BLOCKS: Final = frozenset({"thinking", "redacted_thinking"})
42
+ _ERROR_TYPES: Final = {
43
+ 400: "invalid_request_error",
44
+ 422: "invalid_request_error",
45
+ 404: "not_found_error",
46
+ 413: "request_too_large",
47
+ }
48
+ _FALLBACK_ERROR_TYPE: Final = "api_error"
49
+
50
+
51
+ def _object(value: object, where: str) -> dict[str, Any]:
52
+ if not isinstance(value, dict):
53
+ raise MalformedRequestError(f"{where}: expected an object")
54
+ return value
55
+
56
+
57
+ def _kind(block: dict[str, Any], where: str) -> str:
58
+ kind = block.get("type")
59
+ if not isinstance(kind, str):
60
+ raise MalformedRequestError(f"{where}.type: expected a string")
61
+ return kind
62
+
63
+
64
+ class _Collector:
65
+ """Accumulates the slots of one request while walking it."""
66
+
67
+ __slots__ = ("policy", "slots")
68
+
69
+ def __init__(self, policy: Policy) -> None:
70
+ self.policy = policy
71
+ self.slots: list[Slot] = []
72
+
73
+ def system(self, body: dict[str, Any]) -> None:
74
+ value = body.get("system")
75
+ if value is None:
76
+ return
77
+ if isinstance(value, str):
78
+ self.slots.append(key_slot(body, "system"))
79
+ return
80
+ if not isinstance(value, list):
81
+ raise MalformedRequestError("system: expected a string, a list or null")
82
+ for index, item in enumerate(value):
83
+ where = f"system[{index}]"
84
+ block = _object(item, where)
85
+ kind = _kind(block, where)
86
+ if kind == "text":
87
+ self.required_string(block, "text", where)
88
+ else:
89
+ self.unsupported(kind)
90
+
91
+ def content(self, holder: dict[str, Any], where: str) -> None:
92
+ """The `content` of a message or a tool result: a string, a list of blocks or null."""
93
+ value = holder.get("content")
94
+ where = f"{where}.content"
95
+ if value is None:
96
+ return
97
+ if isinstance(value, str):
98
+ self.slots.append(key_slot(holder, "content"))
99
+ return
100
+ if not isinstance(value, list):
101
+ raise MalformedRequestError(f"{where}: expected a string, a list or null")
102
+ for index, item in enumerate(value):
103
+ self.block(item, f"{where}[{index}]")
104
+
105
+ def block(self, value: object, where: str) -> None:
106
+ block = _object(value, where)
107
+ kind = _kind(block, where)
108
+ if kind == "text":
109
+ self.required_string(block, "text", where)
110
+ elif kind == "tool_use":
111
+ tool_input = block.get("input")
112
+ if not isinstance(tool_input, dict):
113
+ raise MalformedRequestError(f"{where}.input: expected an object")
114
+ self.slots.extend(slots_for_json_strings(tool_input))
115
+ elif kind == "tool_result":
116
+ self.content(block, where)
117
+ elif kind not in _SIGNED_BLOCKS:
118
+ self.unsupported(kind)
119
+
120
+ def required_string(self, holder: dict[str, Any], key: str, where: str) -> None:
121
+ if not isinstance(holder.get(key), str):
122
+ raise MalformedRequestError(f"{where}.{key}: expected a string")
123
+ self.slots.append(key_slot(holder, key))
124
+
125
+ def unsupported(self, kind: str) -> None:
126
+ if self.policy.unsupported_content == "block":
127
+ raise UnsupportedContentError(kind)
128
+
129
+ def tool_definitions(self, body: dict[str, Any]) -> None:
130
+ definitions = body.get("tools")
131
+ if definitions is None:
132
+ return
133
+ if not isinstance(definitions, list):
134
+ raise MalformedRequestError("tools: expected a list")
135
+ self.slots.extend(slots_for_key_strings(definitions, "description"))
136
+
137
+
138
+ def _strip_user_id(body: dict[str, Any]) -> None:
139
+ metadata = body.get("metadata")
140
+ if isinstance(metadata, dict):
141
+ metadata.pop("user_id", None)
142
+ if not metadata:
143
+ del body["metadata"]
144
+
145
+
146
+ class AnthropicMessagesDialect:
147
+ """Anthropic Messages payloads: slots in a fixed order, restoration of responses."""
148
+
149
+ name = "anthropic_messages"
150
+
151
+ def prepare_request(self, body: dict[str, Any], policy: Policy) -> PreparedRequest:
152
+ """Collect the slots of `body` in the documented order and strip `metadata.user_id`.
153
+
154
+ Raises UnsupportedContentError for uninspectable content under policy `block`, and
155
+ MalformedRequestError when a walked field has the wrong shape. Changes `body` only
156
+ through the returned slots, and by removing the identifier. Thinking blocks are never
157
+ read or written.
158
+ """
159
+ if not isinstance(body, dict):
160
+ raise MalformedRequestError("body: expected an object")
161
+ messages = body.get("messages")
162
+ if not isinstance(messages, list):
163
+ raise MalformedRequestError("messages: expected a list")
164
+ collector = _Collector(policy)
165
+ collector.system(body)
166
+ for index, message in enumerate(messages):
167
+ where = f"messages[{index}]"
168
+ collector.content(_object(message, where), where)
169
+ if policy.tool_definitions:
170
+ collector.tool_definitions(body)
171
+ if policy.strip_user_identifiers:
172
+ _strip_user_id(body)
173
+ return PreparedRequest(collector.slots, [])
174
+
175
+ def restore_response(self, body: dict[str, Any], mapping: Mapping) -> None:
176
+ """Restore, in place, the `text` of text blocks and every string of `tool_use` inputs.
177
+
178
+ Everything else (thinking blocks, citations, server tool blocks, usage, ids) is left
179
+ untouched, and so is a body without `content`; use `restore_all_strings` for errors.
180
+ """
181
+ content = body.get("content")
182
+ if not isinstance(content, list):
183
+ return
184
+ for block in content:
185
+ if not isinstance(block, dict):
186
+ continue
187
+ kind = block.get("type")
188
+ if kind == "text" and isinstance(text := block.get("text"), str):
189
+ block["text"] = restore(text, mapping)
190
+ elif kind == "tool_use" and "input" in block:
191
+ block["input"] = restore_all_strings(block["input"], mapping)
192
+
193
+ def stream_transformer(self, mapping: Mapping) -> StreamTransformer:
194
+ """A transformer that restores one streamed message with `mapping`."""
195
+ return AnthropicStreamTransformer(mapping)
196
+
197
+ def error_body(self, status: int, code: str, message: str) -> dict[str, Any]:
198
+ """A gateway error in the Anthropic error shape, the gateway code in parentheses."""
199
+ family = _ERROR_TYPES.get(status, _FALLBACK_ERROR_TYPE)
200
+ return {"type": "error", "error": {"type": family, "message": f"{message} ({code})"}}
201
+
202
+
203
+ # The delta type each restorable block streams, and the delta field that carries its text.
204
+ _DELTA_FIELDS: Final = {"text_delta": "text", "input_json_delta": "partial_json"}
205
+
206
+
207
+ def _dumps(value: object) -> str:
208
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
209
+
210
+
211
+ def _index(data: dict[str, Any]) -> int | None:
212
+ index = data.get("index")
213
+ return index if isinstance(index, int) and not isinstance(index, bool) else None
214
+
215
+
216
+ class AnthropicStreamTransformer:
217
+ """Restores the placeholders of one streamed message, event by event.
218
+
219
+ Each `text` and `tool_use` content block has its own `StreamRestorer`, keyed by the block
220
+ `index`, so placeholders split across deltas are restored and blocks never mix. Text still
221
+ held when a block stops, at `message_stop` or at `end()` is sent in a synthetic
222
+ `content_block_delta` just before; nothing held is emitted any other way. Thinking deltas,
223
+ signatures, citations and every other event pass unchanged, as the original object.
224
+ """
225
+
226
+ def __init__(self, mapping: Mapping) -> None:
227
+ self._mapping = mapping
228
+ self._blocks: dict[int, tuple[str, StreamRestorer]] = {} # index → (delta type, restorer)
229
+ self._settled = 0 # unresolved placeholders of discarded restorers and block starts
230
+ self.unresolved = 0
231
+
232
+ def feed(self, event: SSEEvent) -> list[SSEEvent]:
233
+ """The events to send in place of `event`: synthetic flushes first, then the event."""
234
+ try:
235
+ data = json.loads(event.data)
236
+ except (ValueError, RecursionError):
237
+ return [event]
238
+ if not isinstance(data, dict):
239
+ return [event]
240
+ kind = data.get("type")
241
+ if kind == "message_stop":
242
+ return [*self._flush_all(), event]
243
+ index = _index(data)
244
+ if index is None:
245
+ return [event]
246
+ if kind == "content_block_start":
247
+ return self._start(event, data, index)
248
+ if kind == "content_block_delta":
249
+ return [self._delta(event, data, index)]
250
+ if kind == "content_block_stop":
251
+ return [*self._flush(index), event]
252
+ return [event]
253
+
254
+ def end(self) -> list[SSEEvent]:
255
+ """Synthetic deltas for any text still held; called when the upstream stream ends."""
256
+ return self._flush_all()
257
+
258
+ def _start(self, event: SSEEvent, data: dict[str, Any], index: int) -> list[SSEEvent]:
259
+ flushed = self._flush(index) # a repeated index: send what the earlier block held
260
+ block = data.get("content_block")
261
+ if not isinstance(block, dict):
262
+ return [*flushed, event]
263
+ changed = False
264
+ kind = block.get("type")
265
+ if kind == "text":
266
+ restorer = StreamRestorer(self._mapping)
267
+ self._blocks[index] = ("text_delta", restorer)
268
+ text = block.get("text")
269
+ if isinstance(text, str) and text:
270
+ block["text"] = restorer.feed(text)
271
+ changed = block["text"] != text
272
+ elif kind == "tool_use":
273
+ self._blocks[index] = (
274
+ "input_json_delta",
275
+ StreamRestorer(self._mapping, json_escape=True),
276
+ )
277
+ tool_input = block.get("input")
278
+ if isinstance(tool_input, dict) and tool_input:
279
+ self._settled += sum(
280
+ count_unresolved(slot.get(), self._mapping)
281
+ for slot in slots_for_json_strings(tool_input)
282
+ )
283
+ block["input"] = restore_all_strings(tool_input, self._mapping)
284
+ changed = block["input"] != tool_input
285
+ self._count()
286
+ if not changed:
287
+ return [*flushed, event]
288
+ return [*flushed, SSEEvent(event.event, _dumps(data), event.raw_fields)]
289
+
290
+ def _delta(self, event: SSEEvent, data: dict[str, Any], index: int) -> SSEEvent:
291
+ delta = data.get("delta")
292
+ block = self._blocks.get(index)
293
+ if not isinstance(delta, dict) or block is None:
294
+ return event
295
+ delta_type, restorer = block
296
+ if delta.get("type") != delta_type:
297
+ return event
298
+ key = _DELTA_FIELDS[delta_type]
299
+ value = delta.get(key)
300
+ if not isinstance(value, str):
301
+ return event
302
+ restored = restorer.feed(value)
303
+ self._count()
304
+ if restored == value:
305
+ return event
306
+ delta[key] = restored
307
+ return SSEEvent(event.event, _dumps(data), event.raw_fields)
308
+
309
+ def _flush(self, index: int) -> list[SSEEvent]:
310
+ """A synthetic delta with the held text of one block, which is then discarded."""
311
+ block = self._blocks.pop(index, None)
312
+ if block is None:
313
+ return []
314
+ delta_type, restorer = block
315
+ text = restorer.flush()
316
+ self._settled += restorer.unresolved
317
+ self._count()
318
+ if not text:
319
+ return []
320
+ delta = {"type": delta_type, _DELTA_FIELDS[delta_type]: text}
321
+ data = {"type": "content_block_delta", "index": index, "delta": delta}
322
+ return [SSEEvent("content_block_delta", _dumps(data))]
323
+
324
+ def _flush_all(self) -> list[SSEEvent]:
325
+ return [event for index in list(self._blocks) for event in self._flush(index)]
326
+
327
+ def _count(self) -> None:
328
+ active = sum(restorer.unresolved for _, restorer in self._blocks.values())
329
+ self.unresolved = self._settled + active
@@ -0,0 +1,193 @@
1
+ """Building blocks shared by dialects: slots, prepared requests, policy, errors (architecture §6).
2
+
3
+ Dialects translate one provider's JSON payloads into slots and back. They know nothing about
4
+ HTTP and perform no I/O.
5
+ """
6
+
7
+ import re
8
+ from collections.abc import Callable, Iterator, Sequence
9
+ from dataclasses import dataclass
10
+ from functools import partial
11
+ from typing import Any, Final, Literal, Protocol
12
+
13
+ from aliasgate.dialects.sse import SSEEvent
14
+ from aliasgate.engine import restore
15
+ from aliasgate.mapping import Mapping
16
+
17
+ # A content kind is echoed in error messages and may reach logs, so it must be a short
18
+ # label, never free text taken from the request.
19
+ _KIND: Final = re.compile(r"[a-z][a-z0-9_]{0,39}")
20
+ UNKNOWN_KIND: Final = "unknown"
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class Policy:
25
+ """How a dialect treats uninspectable content, end-user identifiers and tool definitions."""
26
+
27
+ unsupported_content: Literal["block", "pass"] = "block"
28
+ strip_user_identifiers: bool = True
29
+ tool_definitions: bool = True
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class Slot:
34
+ """One string inside a payload: `get` reads its current value, `set` replaces it."""
35
+
36
+ get: Callable[[], str]
37
+ set: Callable[[str], None]
38
+
39
+
40
+ class PreparedRequest:
41
+ """The ordered slots of one request body, and the finalizers that complete writing it."""
42
+
43
+ __slots__ = ("_finalizers", "_slots")
44
+
45
+ def __init__(self, slots: list[Slot], finalizers: list[Callable[[], None]]) -> None:
46
+ self._slots = list(slots)
47
+ self._finalizers = list(finalizers)
48
+
49
+ def texts(self) -> list[str]:
50
+ """The current value of every slot, in slot order."""
51
+ return [slot.get() for slot in self._slots]
52
+
53
+ def apply(self, new_texts: Sequence[str]) -> None:
54
+ """Set every slot in order, then run finalizers. Raise ValueError on length mismatch.
55
+
56
+ Nothing is written unless `new_texts` holds exactly one string per slot.
57
+ """
58
+ if isinstance(new_texts, str):
59
+ raise TypeError("new_texts must be a sequence of strings, not a single string")
60
+ if len(new_texts) != len(self._slots):
61
+ raise ValueError(f"expected {len(self._slots)} texts, got {len(new_texts)}")
62
+ if not all(isinstance(text, str) for text in new_texts):
63
+ raise TypeError("new_texts must contain only strings")
64
+ for slot, text in zip(self._slots, new_texts, strict=True):
65
+ slot.set(text)
66
+ for finalize in self._finalizers:
67
+ finalize()
68
+
69
+
70
+ class UnsupportedContentError(Exception):
71
+ """Content the gateway cannot inspect. `kind` is a short label such as "image_url".
72
+
73
+ A kind that does not look like a label (lower-case ASCII letters, digits and underscores,
74
+ at most 40 characters) is replaced by "unknown", so the error never carries request text.
75
+ """
76
+
77
+ def __init__(self, kind: str) -> None:
78
+ self.kind = kind if _KIND.fullmatch(kind) else UNKNOWN_KIND
79
+ super().__init__(f"unsupported content: {self.kind}")
80
+
81
+
82
+ class MalformedRequestError(Exception):
83
+ """The body does not have the shape this dialect requires. Message has no user text."""
84
+
85
+
86
+ class StreamTransformer(Protocol):
87
+ """Restores one streamed response, event by event, never emitting text it still holds.
88
+
89
+ `unresolved` is the running count of placeholders left unrestored in emitted text.
90
+ """
91
+
92
+ unresolved: int
93
+
94
+ def feed(self, event: SSEEvent) -> list[SSEEvent]:
95
+ """The events to send in place of `event`, in order."""
96
+ ...
97
+
98
+ def end(self) -> list[SSEEvent]:
99
+ """Events carrying any held text; called when the upstream closes without [DONE]."""
100
+ ...
101
+
102
+
103
+ class Dialect(Protocol):
104
+ """Translates one provider API into slots and back; contains no HTTP and does no I/O."""
105
+
106
+ name: str
107
+
108
+ def prepare_request(self, body: dict[str, Any], policy: Policy) -> PreparedRequest: ...
109
+
110
+ def restore_response(self, body: dict[str, Any], mapping: Mapping) -> None: ...
111
+
112
+ def stream_transformer(self, mapping: Mapping) -> StreamTransformer: ...
113
+
114
+ def error_body(self, status: int, code: str, message: str) -> dict[str, Any]: ...
115
+
116
+
117
+ def _string_value(value: object) -> str:
118
+ if not isinstance(value, str):
119
+ # The value is not echoed: it is request content.
120
+ raise TypeError(f"slot value is a {type(value).__name__}, not a string")
121
+ return value
122
+
123
+
124
+ def key_slot(obj: dict[str, Any], key: str) -> Slot:
125
+ """A slot on `obj[key]`; reading it raises TypeError if the value is not a string."""
126
+
127
+ def set_value(value: str) -> None:
128
+ obj[key] = value
129
+
130
+ return Slot(lambda: _string_value(obj[key]), set_value)
131
+
132
+
133
+ def index_slot(arr: list[Any], index: int) -> Slot:
134
+ """A slot on `arr[index]`; reading it raises TypeError if the item is not a string."""
135
+
136
+ def set_value(value: str) -> None:
137
+ arr[index] = value
138
+
139
+ return Slot(lambda: _string_value(arr[index]), set_value)
140
+
141
+
142
+ type _Child = tuple[Any, Callable[[], Slot], str | None]
143
+
144
+
145
+ def _children(container: dict[str, Any] | list[Any]) -> Iterator[_Child]:
146
+ if isinstance(container, dict):
147
+ for key in list(container):
148
+ yield container[key], partial(key_slot, container, key), key
149
+ else:
150
+ for index, item in enumerate(container):
151
+ yield item, partial(index_slot, container, index), None
152
+
153
+
154
+ def _string_slots(container: dict[str, Any] | list[Any]) -> Iterator[tuple[Slot, str | None]]:
155
+ """Every string value as a slot, with the dict key holding it (None for a list item).
156
+
157
+ Depth-first, dicts in insertion order, lists in index order. Iterative, so deeply nested
158
+ input cannot exhaust the interpreter stack.
159
+ """
160
+ stack = [_children(container)]
161
+ while stack:
162
+ child = next(stack[-1], None)
163
+ if child is None:
164
+ stack.pop()
165
+ continue
166
+ value, make_slot, key = child
167
+ if isinstance(value, str):
168
+ yield make_slot(), key
169
+ elif isinstance(value, dict | list):
170
+ stack.append(_children(value))
171
+
172
+
173
+ def slots_for_json_strings(container: dict[str, Any] | list[Any]) -> list[Slot]:
174
+ """A slot for every string VALUE reachable in the container, depth-first, dicts in insertion
175
+ order, lists in index order. Keys are never slots."""
176
+ return [slot for slot, _ in _string_slots(container)]
177
+
178
+
179
+ def slots_for_key_strings(container: dict[str, Any] | list[Any], key: str) -> list[Slot]:
180
+ """A slot for every string stored directly under `key` in any dict reachable from the
181
+ container, in the order of `slots_for_json_strings`. Other strings are never slots."""
182
+ return [slot for slot, holder in _string_slots(container) if holder == key]
183
+
184
+
185
+ def restore_all_strings(value: Any, mapping: Mapping) -> Any:
186
+ """Return a copy of a JSON value with `restore` applied to every string value."""
187
+ if isinstance(value, str):
188
+ return restore(value, mapping)
189
+ if isinstance(value, dict):
190
+ return {key: restore_all_strings(item, mapping) for key, item in value.items()}
191
+ if isinstance(value, list):
192
+ return [restore_all_strings(item, mapping) for item in value]
193
+ return value