macore-client-dev 0.1.150__tar.gz → 0.1.151__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: macore-client-dev
3
- Version: 0.1.150
3
+ Version: 0.1.151
4
4
  Summary: Client for the Model Access Core (MAC) server
5
5
  Requires-Python: >=3.11
6
6
  Requires-Dist: mcp-proxy-adapter<9,>=8.14.5
@@ -1,3 +1,3 @@
1
1
  """The single release version shared by the client and server packages."""
2
2
 
3
- __version__ = "0.1.150"
3
+ __version__ = "0.1.151"
@@ -0,0 +1,18 @@
1
+ # client/macore_client/__init__.py
2
+ # Author: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
3
+ # Project: model_access_core (71b1e006-b777-4edb-854e-f0a47120f793)
4
+ """Client package for the Model Access Core (MAC) server."""
5
+
6
+ from macore_client.client import MacClient, json_object_format, json_schema_format
7
+ from macore_client.content import image_block, image_block_from_bytes
8
+ from macore_client.__about__ import __version__
9
+ from macore_client.decision import DecisionResult, DecisionAuditReceipt, ThresholdResult, NoulAnswer, ChoiceAnswer, ScoreAnswer
10
+ from macore_client.stream import (
11
+ MacChatStream, MacStreamCancelled, MacStreamError, MacStreamGap, StreamAdapterFrame, StreamCancelled, StreamEnd, StreamError, StreamKeepalive,
12
+ StreamStart, StreamUsage, StreamWarning, TextDelta, ThinkingDelta, ThinkingSignature, ToolCallDelta, ToolCallEnd, ToolCallStart,
13
+ )
14
+
15
+ __all__ = ["MacClient", "json_object_format", "json_schema_format", "image_block", "image_block_from_bytes", "__version__", "DecisionResult", "DecisionAuditReceipt", "ThresholdResult", "NoulAnswer", "ChoiceAnswer", "ScoreAnswer",
16
+ "MacChatStream", "MacStreamCancelled", "MacStreamError", "MacStreamGap", "StreamAdapterFrame", "StreamCancelled", "StreamEnd", "StreamError",
17
+ "StreamKeepalive", "StreamStart", "StreamUsage", "StreamWarning", "TextDelta", "ThinkingDelta", "ThinkingSignature", "ToolCallDelta", "ToolCallEnd",
18
+ "ToolCallStart"]
@@ -23,6 +23,14 @@ from macore_client.decision import (
23
23
  selected_probability, validate_decision_request, DecisionRemoteError, _answer_from_dict,
24
24
  )
25
25
  from macore_client.trace import RequestTracePage
26
+ from macore_client.stream import MacChatStream
27
+ from macore_client.stream_defaults import (
28
+ DEFAULT_STREAM_HEARTBEAT_SECONDS,
29
+ DEFAULT_STREAM_MAX_MSG_SIZE_BYTES,
30
+ DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS,
31
+ DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS,
32
+ STREAM_COMMAND,
33
+ )
26
34
 
27
35
  if TYPE_CHECKING:
28
36
  from model_access_core.schemas.chat import ToolPolicySchema
@@ -158,6 +166,37 @@ class MacClient:
158
166
  )
159
167
  return _unwrap(raw)
160
168
 
169
+ def model_chat_stream(
170
+ self, *, open_timeout: float = DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS, receive_timeout: float = DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS,
171
+ heartbeat: float = DEFAULT_STREAM_HEARTBEAT_SECONDS, max_msg_size: int = DEFAULT_STREAM_MAX_MSG_SIZE_BYTES, include_keepalive: bool = False,
172
+ include_adapter_frames: bool = False, **params: Any,
173
+ ) -> MacChatStream:
174
+ """Stream one chat (owner_approval S2-REFRESH-2 section 11): the keyword arguments of ``model_chat`` without ``stream``; returns ``MacChatStream``
175
+ (``async with client.model_chat_stream(...) as stream: async for event in stream: ...``; ``await stream.response()`` is the ChatResponse)."""
176
+ if "stream" in params:
177
+ raise TypeError("model_chat_stream takes the model_chat keywords without 'stream'")
178
+ payload = {key: value for key, value in params.items() if value is not None}
179
+ return MacChatStream(self, payload, open_timeout=open_timeout, receive_timeout=receive_timeout, heartbeat=heartbeat, max_msg_size=max_msg_size,
180
+ include_keepalive=include_keepalive, include_adapter_frames=include_adapter_frames)
181
+
182
+ async def model_chat_stream_raw(
183
+ self, params: dict[str, Any], *, open_timeout: float = DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS, receive_timeout: float = DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS,
184
+ heartbeat: float = DEFAULT_STREAM_HEARTBEAT_SECONDS, max_msg_size: int = DEFAULT_STREAM_MAX_MSG_SIZE_BYTES,
185
+ ) -> Any:
186
+ """Bounded raw-parameter invocation of ``model_chat_stream`` for NEGATIVE cases (the pipeline only): the accepted adapter ``CommandSession``, or the
187
+ adapter error as data (``{"error": {code, message, data}}``) when the parameters are refused before a job exists."""
188
+ from mcp_proxy_adapter.client.jsonrpc_client import ClientRemoteResponseError, open_command_session
189
+
190
+ try:
191
+ return await open_command_session(self.transport, STREAM_COMMAND, dict(params), timeout=open_timeout, receive_timeout=receive_timeout,
192
+ heartbeat=heartbeat, max_msg_size=max_msg_size)
193
+ except ClientRemoteResponseError as exc:
194
+ details = getattr(exc, "details", None)
195
+ details = details if isinstance(details, dict) else {}
196
+ error = details.get("error") if isinstance(details.get("error"), dict) else details
197
+ return {"error": {"code": error.get("code", getattr(exc, "code", None)), "message": error.get("message", str(exc)),
198
+ "data": error.get("data", details.get("data", {}))}}
199
+
161
200
  async def close(self) -> None:
162
201
  """Close the underlying transport."""
163
202
  close = getattr(self.transport, "close", None)
@@ -0,0 +1,40 @@
1
+ # client/macore_client/content.py
2
+ # Author: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
3
+ # Project: model_access_core (71b1e006-b777-4edb-854e-f0a47120f793)
4
+ """Content-block helpers of the MAC client (NEW-CAPS-20261129-I, I-AMEND-2 C11).
5
+
6
+ ``image_block`` and ``image_block_from_bytes`` build the ``{type: image, ...}`` block of a user message for ``model_chat``, ``model_count_tokens`` and
7
+ ``model_estimate_request_capacity``. They can never produce a block the server refuses as REL-IMG-2 / REL-IMG-3: exactly one of ``url`` and ``data`` is required, and ``data`` needs
8
+ ``media_type``. The helpers add no data-URI prefix (the server builds it) and neither fetch nor decode anything.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ from typing import Any
15
+
16
+
17
+ def image_block(*, url: str | None = None, data: str | None = None, media_type: str | None = None, detail: str | None = None) -> dict[str, Any]:
18
+ """``{type: image, image_url | image_data, media_type, detail}``; a cell that is ``None`` is omitted.
19
+
20
+ ``url`` is an https URL, ``data`` is base64 WITHOUT a data-URI prefix. ``ValueError`` for neither or both of ``url`` / ``data`` and for ``data`` without ``media_type``.
21
+ """
22
+ if (url is None) == (data is None):
23
+ raise ValueError("image_block requires exactly one of url and data")
24
+ if data is not None and media_type is None:
25
+ raise ValueError("image_block requires media_type with data")
26
+ block: dict[str, Any] = {"type": "image"}
27
+ if url is not None:
28
+ block["image_url"] = url
29
+ if data is not None:
30
+ block["image_data"] = data
31
+ if media_type is not None:
32
+ block["media_type"] = media_type
33
+ if detail is not None:
34
+ block["detail"] = detail
35
+ return block
36
+
37
+
38
+ def image_block_from_bytes(raw: bytes, media_type: str, *, detail: str | None = None) -> dict[str, Any]:
39
+ """An image block of raw image bytes: ``image_data`` is their standard base64 (no data-URI prefix), ``media_type`` is required."""
40
+ return image_block(data=base64.b64encode(raw).decode("ascii"), media_type=media_type, detail=detail)
@@ -0,0 +1,477 @@
1
+ # client/macore_client/stream.py
2
+ # Author: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
3
+ # Project: model_access_core (71b1e006-b777-4edb-854e-f0a47120f793)
4
+ """Typed streaming client of ``model_chat_stream`` (owner_approval S2-REFRESH-2 section 11, A3.5, B3.3).
5
+
6
+ ``MacChatStream`` is an async context manager AND an async iterator over one adapter command session (``open_command_session``, one WebSocket per stream,
7
+ ``max_msg_size`` passed explicitly). ``__aenter__`` waits for the first of {``stream_start``, a terminal frame}: a terminal frame first is a pre-admission
8
+ refusal and raises ``MacStreamError`` with the ErrorResult's ``code`` / ``hal_code`` / ``hal_details``; an adapter -32602 raises it with the violation. Iteration
9
+ yields the typed events in ``n`` order (a gap raises ``MacStreamGap``) and ends after exactly one terminal event (``StreamEnd``, ``StreamError`` or
10
+ ``StreamCancelled``). ``response_part`` events are consumed internally; ``response()`` returns the ChatResponse from ``StreamEnd.response``, else from the joined
11
+ parts (sha256 and length verified), else from the command result. Only exports of ``mcp_proxy_adapter.client.jsonrpc_client`` are used.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import dataclasses
17
+ import hashlib
18
+ import json
19
+ from dataclasses import dataclass, field
20
+ from typing import Any
21
+
22
+ from macore_client.stream_defaults import (
23
+ DEFAULT_STREAM_HEARTBEAT_SECONDS,
24
+ DEFAULT_STREAM_MAX_MSG_SIZE_BYTES,
25
+ DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS,
26
+ DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS,
27
+ STREAM_COMMAND,
28
+ )
29
+
30
+ _ADAPTER_TERMINAL = ("command_completed", "command_failed", "command_cancelled", "command_error")
31
+ CAUSE_CONNECTION_LOST = "connection_lost"
32
+ CAUSE_FRAME_TOO_LARGE = "client_frame_too_large"
33
+ CAUSE_STREAM_ERROR = "stream_error"
34
+ CAUSE_REFUSED = "refused"
35
+ CAUSE_INVALID_PARAMS = "invalid_params"
36
+
37
+
38
+ # --------------------------------------------------------------------------------------------------------------------- typed events (6.2)
39
+
40
+
41
+ @dataclass
42
+ class StreamStart:
43
+ n: int
44
+ request_id: str | None = None
45
+ lifecycle_request_id: str | None = None
46
+ provider_id: str | None = None
47
+ model_id: str | None = None
48
+ served_model_id: str | None = None
49
+ state: str | None = None
50
+ resolved_model_id: str | None = None
51
+
52
+
53
+ @dataclass
54
+ class TextDelta:
55
+ n: int
56
+ block_index: int = 0
57
+ text: str = ""
58
+
59
+
60
+ @dataclass
61
+ class ThinkingDelta:
62
+ n: int
63
+ block_index: int = 0
64
+ text: str = ""
65
+
66
+
67
+ @dataclass
68
+ class ThinkingSignature:
69
+ n: int
70
+ block_index: int = 0
71
+ signature: str | None = None
72
+ encrypted_content: str | None = None
73
+
74
+
75
+ @dataclass
76
+ class ToolCallStart:
77
+ n: int
78
+ tool_call_id: str = ""
79
+ name: str = ""
80
+ block_index: int = 0
81
+
82
+
83
+ @dataclass
84
+ class ToolCallDelta:
85
+ n: int
86
+ tool_call_id: str = ""
87
+ arguments_delta: str = ""
88
+
89
+
90
+ @dataclass
91
+ class ToolCallEnd:
92
+ n: int
93
+ tool_call_id: str = ""
94
+ arguments: dict[str, Any] = field(default_factory=dict)
95
+ arguments_parse_status: str = "parsed"
96
+
97
+
98
+ @dataclass
99
+ class StreamWarning:
100
+ n: int
101
+ code: str = ""
102
+ message: str | None = None
103
+
104
+
105
+ @dataclass
106
+ class StreamUsage:
107
+ n: int
108
+ usage: dict[str, Any] = field(default_factory=dict)
109
+
110
+
111
+ @dataclass
112
+ class StreamEnd:
113
+ n: int
114
+ finish_reason: str | None = None
115
+ response: dict[str, Any] | None = None
116
+ response_omitted: dict[str, Any] | None = None
117
+
118
+
119
+ @dataclass
120
+ class StreamError:
121
+ n: int
122
+ error: dict[str, Any] = field(default_factory=dict)
123
+ partial: bool = False
124
+ usage: dict[str, Any] | None = None
125
+
126
+
127
+ @dataclass
128
+ class StreamCancelled:
129
+ """Synthesized from the adapter terminal frame ``command_cancelled`` (C8): ``reason`` caller (``cancel()`` was called) or connection_lost."""
130
+
131
+ reason: str = "caller"
132
+
133
+
134
+ @dataclass
135
+ class StreamKeepalive:
136
+ n: int
137
+ elapsed_ms: int = 0
138
+
139
+
140
+ @dataclass
141
+ class StreamAdapterFrame:
142
+ """An adapter frame (``command_progress`` or an unknown frame); yielded only with ``include_adapter_frames``."""
143
+
144
+ frame: dict[str, Any] = field(default_factory=dict)
145
+
146
+
147
+ _EVENT_TYPES: dict[str, type] = {
148
+ "stream_start": StreamStart, "text_delta": TextDelta, "thinking_delta": ThinkingDelta, "thinking_signature": ThinkingSignature,
149
+ "tool_call_start": ToolCallStart, "tool_call_delta": ToolCallDelta, "tool_call_end": ToolCallEnd, "warning": StreamWarning, "usage": StreamUsage,
150
+ "stream_end": StreamEnd, "stream_error": StreamError, "keepalive": StreamKeepalive,
151
+ }
152
+ _TERMINAL_TYPES = ("stream_end", "stream_error")
153
+
154
+
155
+ def _typed(event_type: str, data: dict[str, Any]) -> Any:
156
+ cls = _EVENT_TYPES[event_type]
157
+ names = {f.name for f in dataclasses.fields(cls)}
158
+ return cls(**{k: v for k, v in data.items() if k in names})
159
+
160
+
161
+ # --------------------------------------------------------------------------------------------------------------------- exceptions (11.4)
162
+
163
+
164
+ class MacStreamError(Exception):
165
+ """A pre-admission refusal or a stream-level failure; carries the error ``code``, ``hal_code``, ``hal_details`` and the ``cause``."""
166
+
167
+ def __init__(self, message: str, *, code: Any = None, hal_code: Any = None, hal_details: Any = None, cause: str | None = None, error: Any = None) -> None:
168
+ super().__init__(message)
169
+ self.code = code
170
+ self.hal_code = hal_code
171
+ self.hal_details = hal_details if hal_details is not None else {}
172
+ self.cause = cause
173
+ self.error = error
174
+
175
+
176
+ class MacStreamGap(MacStreamError):
177
+ """A gap in the macsc ``n`` counter (or an adapter ``stream_gap`` frame); ``response()`` falls back to the command result."""
178
+
179
+
180
+ class MacStreamCancelled(Exception):
181
+ """The stream was cancelled (``cancel()`` or a lost connection); ``reason`` caller | connection_lost."""
182
+
183
+ def __init__(self, reason: str) -> None:
184
+ super().__init__(f"the stream was cancelled ({reason})")
185
+ self.reason = reason
186
+
187
+
188
+ def _error_from_envelope(error: Any, *, cause: str) -> MacStreamError:
189
+ """MacStreamError of a JSON-RPC style error object ``{code, message, data {hal_code, hal_details, ...}}``."""
190
+ error = error if isinstance(error, dict) else {}
191
+ data = error.get("data") if isinstance(error.get("data"), dict) else {}
192
+ return MacStreamError(str(error.get("message") or "model_chat_stream failed"), code=error.get("code"), hal_code=data.get("hal_code"),
193
+ hal_details=data.get("hal_details") if isinstance(data.get("hal_details"), dict) else data, cause=cause, error=error)
194
+
195
+
196
+ def _find_outcome(value: Any, depth: int = 0) -> tuple[str, Any] | None:
197
+ """("error", error object) or ("data", success data) of a command result in whatever nesting the job status returns it."""
198
+ if depth > 6 or not isinstance(value, dict):
199
+ return None
200
+ if isinstance(value.get("error"), dict) and ("code" in value["error"] or "message" in value["error"]):
201
+ return "error", value["error"]
202
+ if value.get("success") is True and isinstance(value.get("data"), dict):
203
+ inner = _find_outcome(value["data"], depth + 1)
204
+ return inner if inner is not None and inner[0] == "error" else ("data", value["data"])
205
+ for key in ("result", "data"):
206
+ inner = _find_outcome(value.get(key), depth + 1)
207
+ if inner is not None:
208
+ return inner
209
+ if "finish_reason" in value and "message" in value:
210
+ return "data", value
211
+ return None
212
+
213
+
214
+ def _frame_too_large(exc: BaseException) -> bool:
215
+ text = f"{type(exc).__name__} {exc}".lower()
216
+ return "too big" in text or "too large" in text or "1009" in text or "max_msg_size" in text or "message size" in text
217
+
218
+
219
+ # --------------------------------------------------------------------------------------------------------------------- the stream
220
+
221
+
222
+ class MacChatStream:
223
+ """One ``model_chat_stream`` over its own WebSocket command session."""
224
+
225
+ def __init__(self, client: Any, params: dict[str, Any], *, open_timeout: float = DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS,
226
+ receive_timeout: float = DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS, heartbeat: float = DEFAULT_STREAM_HEARTBEAT_SECONDS,
227
+ max_msg_size: int = DEFAULT_STREAM_MAX_MSG_SIZE_BYTES, include_keepalive: bool = False, include_adapter_frames: bool = False) -> None:
228
+ self._client = client
229
+ self._params = params
230
+ self._open_timeout = open_timeout
231
+ self._receive_timeout = receive_timeout
232
+ self._heartbeat = heartbeat
233
+ self._max_msg_size = max_msg_size
234
+ self.include_keepalive = include_keepalive
235
+ self.include_adapter_frames = include_adapter_frames
236
+ self._session: Any = None
237
+ self._frames: Any = None
238
+ self._pending: list[Any] = []
239
+ self._last_n = 0
240
+ self._terminal: Any = None
241
+ self._adapter_terminal: dict[str, Any] | None = None
242
+ self._parts: dict[int, str] = {}
243
+ self._parts_count: int | None = None
244
+ self._gap = False
245
+ self._cancel_called = False
246
+ self._cancelled: StreamCancelled | None = None
247
+ self._finished = False
248
+ self.job_id: str | None = None
249
+ self.request_id: str | None = None
250
+
251
+ @property
252
+ def last_adapter_seq(self) -> int | None:
253
+ return getattr(self._session, "last_seq", None) if self._session is not None else None
254
+
255
+ # -- open ----------------------------------------------------------------------------------------------------------
256
+ async def __aenter__(self) -> "MacChatStream":
257
+ from mcp_proxy_adapter.client.jsonrpc_client import (
258
+ ClientRemoteResponseError,
259
+ CommandSessionFailedError,
260
+ open_command_session,
261
+ )
262
+
263
+ try:
264
+ self._session = await open_command_session(
265
+ self._client.transport, STREAM_COMMAND, self._params, timeout=self._open_timeout, receive_timeout=self._receive_timeout,
266
+ heartbeat=self._heartbeat, max_msg_size=self._max_msg_size,
267
+ )
268
+ except ClientRemoteResponseError as exc:
269
+ raise self._adapter_refusal(exc) from None
270
+ except CommandSessionFailedError as exc:
271
+ details = getattr(exc, "details", None) or {}
272
+ raise _error_from_envelope(details.get("error", details) if isinstance(details, dict) else {}, cause=CAUSE_REFUSED) from None
273
+ self.job_id = getattr(self._session, "job_id", None)
274
+ self.request_id = getattr(self._session, "request_id", None)
275
+ self._frames = self._session.events()
276
+ try:
277
+ first = await self._next_typed(opening=True)
278
+ except BaseException:
279
+ await self._close()
280
+ raise
281
+ if first is not None:
282
+ self._pending.append(first)
283
+ return self
284
+
285
+ def _adapter_refusal(self, exc: Any) -> MacStreamError:
286
+ details = getattr(exc, "details", None)
287
+ details = details if isinstance(details, dict) else {}
288
+ error = details.get("error") if isinstance(details.get("error"), dict) else details
289
+ data = error.get("data") if isinstance(error.get("data"), dict) else details.get("data") if isinstance(details.get("data"), dict) else {}
290
+ code = error.get("code", details.get("code", getattr(exc, "code", None)))
291
+ return MacStreamError(str(exc), code=code, hal_code=data.get("hal_code"), hal_details=data.get("hal_details") if isinstance(data.get("hal_details"), dict) else data,
292
+ cause=CAUSE_INVALID_PARAMS, error=error)
293
+
294
+ async def __aexit__(self, *exc: Any) -> None:
295
+ await self._close()
296
+
297
+ async def _close(self) -> None:
298
+ if self._session is not None:
299
+ try:
300
+ await self._session.close()
301
+ except Exception: # noqa: BLE001 - closing a dead socket is not an error of the stream
302
+ pass
303
+
304
+ # -- iteration -----------------------------------------------------------------------------------------------------
305
+ def __aiter__(self) -> "MacChatStream":
306
+ return self
307
+
308
+ async def __anext__(self) -> Any:
309
+ if self._pending:
310
+ return self._pending.pop(0)
311
+ if self._finished:
312
+ raise StopAsyncIteration
313
+ event = await self._next_typed()
314
+ if event is None:
315
+ raise StopAsyncIteration
316
+ return event
317
+
318
+ async def _frame(self) -> dict[str, Any] | None:
319
+ from mcp_proxy_adapter.client.jsonrpc_client import ClientError
320
+
321
+ try:
322
+ return await self._frames.__anext__()
323
+ except StopAsyncIteration:
324
+ return None
325
+ except ClientError as exc:
326
+ self._finished = True
327
+ raise MacStreamError(str(exc), cause=CAUSE_FRAME_TOO_LARGE if _frame_too_large(exc) else CAUSE_CONNECTION_LOST) from None
328
+
329
+ async def _next_typed(self, opening: bool = False) -> Any:
330
+ """The next event to yield; ``None`` when the iteration ends. Opening: stop at stream_start or turn a first terminal frame into the refusal."""
331
+ while True:
332
+ frame = await self._frame()
333
+ if frame is None:
334
+ self._finished = True
335
+ if self._terminal is None and self._cancelled is None:
336
+ raise MacStreamError("the stream ended without a terminal event", cause=CAUSE_CONNECTION_LOST)
337
+ return None
338
+ kind = frame.get("event")
339
+ if kind == "command_data":
340
+ event_type, data = frame.get("event_type"), frame.get("data") if isinstance(frame.get("data"), dict) else {}
341
+ n = data.get("n")
342
+ if isinstance(n, int) and n != self._last_n + 1:
343
+ self._gap = True
344
+ previous, self._last_n = self._last_n, n
345
+ raise MacStreamGap(f"macsc event n {n} follows {previous}: an event was lost", cause="gap")
346
+ if isinstance(n, int):
347
+ self._last_n = n
348
+ if event_type == "response_part":
349
+ if isinstance(data.get("index"), int) and isinstance(data.get("text"), str):
350
+ self._parts[data["index"]] = data["text"]
351
+ self._parts_count = data.get("count") if isinstance(data.get("count"), int) else self._parts_count
352
+ continue
353
+ if event_type == "keepalive" and not self.include_keepalive:
354
+ continue
355
+ if event_type not in _EVENT_TYPES:
356
+ if self.include_adapter_frames:
357
+ return StreamAdapterFrame(frame=frame)
358
+ continue
359
+ event = _typed(event_type, data)
360
+ if event_type in _TERMINAL_TYPES:
361
+ self._terminal = event
362
+ self._finished = True
363
+ return event
364
+ if kind == "stream_gap":
365
+ self._gap = True
366
+ raise MacStreamGap("the adapter reported a stream gap", cause="gap")
367
+ if kind in _ADAPTER_TERMINAL:
368
+ self._adapter_terminal = frame
369
+ self._finished = True
370
+ if kind == "command_cancelled":
371
+ self._cancelled = StreamCancelled(reason="caller" if self._cancel_called else CAUSE_CONNECTION_LOST)
372
+ return self._cancelled
373
+ if opening or self._last_n == 0:
374
+ raise await self._refusal()
375
+ if self._terminal is None:
376
+ raise MacStreamError("the command ended without a terminal stream event", cause=CAUSE_CONNECTION_LOST)
377
+ return None
378
+ if self.include_adapter_frames and kind != "command_accepted":
379
+ return StreamAdapterFrame(frame=frame)
380
+
381
+ async def _refusal(self) -> MacStreamError:
382
+ """A terminal frame before stream_start: the ErrorResult of the command result (a frame-less pre-admission refusal)."""
383
+ try:
384
+ result = await self._session.result()
385
+ except Exception as exc: # noqa: BLE001 - the result fetch itself reports the failure
386
+ details = getattr(exc, "details", None)
387
+ outcome = _find_outcome(details) if isinstance(details, dict) else None
388
+ if outcome is not None and outcome[0] == "error":
389
+ return _error_from_envelope(outcome[1], cause=CAUSE_REFUSED)
390
+ return MacStreamError(f"the refusal could not be read: {exc}", cause=CAUSE_REFUSED)
391
+ outcome = _find_outcome(result)
392
+ if outcome is not None and outcome[0] == "error":
393
+ return _error_from_envelope(outcome[1], cause=CAUSE_REFUSED)
394
+ return MacStreamError("the command ended before stream_start", cause=CAUSE_REFUSED, error=result)
395
+
396
+ # -- control -------------------------------------------------------------------------------------------------------
397
+ async def cancel(self) -> None:
398
+ """Cancel the stream (adapter ``cancel_command``); idempotent."""
399
+ if self._cancel_called or self._session is None:
400
+ return
401
+ self._cancel_called = True
402
+ if self._finished:
403
+ return
404
+ try:
405
+ await self._session.cancel(reason="cancelled")
406
+ except Exception: # noqa: BLE001 - a terminal or vanished job: cancelling is already done
407
+ pass
408
+
409
+ async def response(self) -> dict[str, Any]:
410
+ """The ChatResponse: StreamEnd.response, else the joined response parts (sha256 + length verified), else the command result."""
411
+ if self._cancelled is not None:
412
+ raise MacStreamCancelled(self._cancelled.reason)
413
+ if isinstance(self._terminal, StreamError):
414
+ raise _error_from_envelope(self._terminal.error, cause=CAUSE_STREAM_ERROR)
415
+ if isinstance(self._terminal, StreamEnd) and not self._gap:
416
+ if self._terminal.response is not None:
417
+ return self._terminal.response
418
+ joined = self._joined_parts(self._terminal.response_omitted)
419
+ if joined is not None:
420
+ return joined
421
+ if self._cancel_called and self._terminal is None:
422
+ raise MacStreamCancelled("caller")
423
+ await self._drain()
424
+ if self._cancelled is not None:
425
+ raise MacStreamCancelled(self._cancelled.reason)
426
+ if isinstance(self._terminal, StreamError):
427
+ raise _error_from_envelope(self._terminal.error, cause=CAUSE_STREAM_ERROR)
428
+ result = await self._session.result()
429
+ outcome = _find_outcome(result)
430
+ if outcome is None:
431
+ raise MacStreamError("the command result carries no ChatResponse", cause=CAUSE_CONNECTION_LOST, error=result)
432
+ if outcome[0] == "error":
433
+ raise _error_from_envelope(outcome[1], cause=CAUSE_STREAM_ERROR)
434
+ return outcome[1]
435
+
436
+ def _joined_parts(self, omitted: Any) -> dict[str, Any] | None:
437
+ if not isinstance(omitted, dict) or not isinstance(omitted.get("parts"), int):
438
+ return None
439
+ count = omitted["parts"]
440
+ if sorted(self._parts) != list(range(count)):
441
+ return None
442
+ payload = "".join(self._parts[i] for i in range(count)).encode("utf-8")
443
+ if len(payload) != omitted.get("response_bytes") or hashlib.sha256(payload).hexdigest() != omitted.get("sha256"):
444
+ return None
445
+ try:
446
+ value = json.loads(payload.decode("utf-8"))
447
+ except ValueError:
448
+ return None
449
+ return value if isinstance(value, dict) else None
450
+
451
+ async def _drain(self) -> None:
452
+ """Read the remaining frames up to the adapter terminal frame (the command result is final only then)."""
453
+ while self._adapter_terminal is None:
454
+ try:
455
+ frame = await self._frame()
456
+ except MacStreamError:
457
+ return
458
+ if frame is None:
459
+ return
460
+ kind = frame.get("event")
461
+ if kind == "command_data":
462
+ event_type, data = frame.get("event_type"), frame.get("data") if isinstance(frame.get("data"), dict) else {}
463
+ if event_type == "response_part" and isinstance(data.get("index"), int) and isinstance(data.get("text"), str):
464
+ self._parts[data["index"]] = data["text"]
465
+ elif event_type in _TERMINAL_TYPES and self._terminal is None:
466
+ self._terminal = _typed(event_type, data)
467
+ elif kind in _ADAPTER_TERMINAL:
468
+ self._adapter_terminal = frame
469
+ if kind == "command_cancelled":
470
+ self._cancelled = StreamCancelled(reason="caller" if self._cancel_called else CAUSE_CONNECTION_LOST)
471
+
472
+
473
+ __all__ = [
474
+ "MacChatStream", "MacStreamCancelled", "MacStreamError", "MacStreamGap", "StreamAdapterFrame", "StreamCancelled", "StreamEnd", "StreamError",
475
+ "StreamKeepalive", "StreamStart", "StreamUsage", "StreamWarning", "TextDelta", "ThinkingDelta", "ThinkingSignature", "ToolCallDelta", "ToolCallEnd",
476
+ "ToolCallStart",
477
+ ]
@@ -0,0 +1,15 @@
1
+ # client/macore_client/stream_defaults.py
2
+ # Author: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
3
+ # Project: model_access_core (71b1e006-b777-4edb-854e-f0a47120f793)
4
+ """Named client defaults of ``MacClient.model_chat_stream`` (owner_approval S2-REFRESH-2 9.3, 7.5); keyword arguments override them, never environment variables."""
5
+
6
+ DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS = 30.0
7
+ DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS = 60.0 # the adapter default, passed explicitly (> 2 x the largest server keepalive interval 30 s)
8
+ DEFAULT_STREAM_HEARTBEAT_SECONDS = 30.0
9
+ DEFAULT_STREAM_MAX_MSG_SIZE_BYTES = 4194304 # >= the largest frame: event limit + envelope (the macsc answer to adapter bug af58163e)
10
+ STREAM_COMMAND = "model_chat_stream"
11
+
12
+ __all__ = [
13
+ "DEFAULT_STREAM_HEARTBEAT_SECONDS", "DEFAULT_STREAM_MAX_MSG_SIZE_BYTES", "DEFAULT_STREAM_OPEN_TIMEOUT_SECONDS", "DEFAULT_STREAM_RECEIVE_TIMEOUT_SECONDS",
14
+ "STREAM_COMMAND",
15
+ ]
@@ -1,10 +0,0 @@
1
- # client/macore_client/__init__.py
2
- # Author: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
3
- # Project: model_access_core (71b1e006-b777-4edb-854e-f0a47120f793)
4
- """Client package for the Model Access Core (MAC) server."""
5
-
6
- from macore_client.client import MacClient, json_object_format, json_schema_format
7
- from macore_client.__about__ import __version__
8
- from macore_client.decision import DecisionResult, DecisionAuditReceipt, ThresholdResult, NoulAnswer, ChoiceAnswer, ScoreAnswer
9
-
10
- __all__ = ["MacClient", "json_object_format", "json_schema_format", "__version__", "DecisionResult", "DecisionAuditReceipt", "ThresholdResult", "NoulAnswer", "ChoiceAnswer", "ScoreAnswer"]