bma-sdk 2.0.0__tar.gz → 2.2.0__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: bma-sdk
3
- Version: 2.0.0
3
+ Version: 2.2.0
4
4
  Summary: Python client for BMA: the official Anthropic SDK with the BMA extensions (machines, machine pools, desktop and terminal sessions) under client.beta.
5
5
  Project-URL: Repository, https://github.com/beeos-ai/bma-sdk
6
6
  License-Expression: Apache-2.0
@@ -27,7 +27,7 @@ credential (hand end users a ticket, never the key).
27
27
 
28
28
  | | |
29
29
  | --- | --- |
30
- | Version | 2.0.0, see [CHANGELOG](../CHANGELOG.md); from 1.x: [MIGRATION](../MIGRATION.md#python-1x--20) |
30
+ | Version | 2.2.0, see [CHANGELOG](../CHANGELOG.md); from 1.x: [MIGRATION](../MIGRATION.md#python-1x--20) |
31
31
  | Official core | `anthropic` 2.6.0 (exact pin) |
32
32
  | Python | 3.10 or newer |
33
33
 
@@ -71,13 +71,29 @@ except bma_sdk.NotFoundError as err:
71
71
 
72
72
  `AsyncBma` is the same with `await` / `async for` (`await client.beta.sessions.events.stream(id)`).
73
73
 
74
+ To send first, use `send_and_stream`: it opens the stream at the cursor read
75
+ before the send (`bma_resume_cursor`), so frames an executor wrote before the
76
+ stream opened are not lost. `replayed` is true when the server gave no cursor
77
+ and the stream starts at `Last-Event-ID: 0` (pick your turn by `bma_input_id`).
78
+
79
+ ```python
80
+ result = client.beta.sessions.events.send_and_stream(session.id, events=[
81
+ {"type": "user.message", "content": [{"type": "text", "text": "Next step."}]},
82
+ ])
83
+ with result.stream as stream:
84
+ for event in stream:
85
+ if event.type == "session.status_idle":
86
+ break
87
+ ```
88
+ (`await client.beta.sessions.events.send_and_stream(...)` on `AsyncBma`.)
89
+
74
90
  - **Extension fields.** `session_extensions`, `agent_extensions`,
75
91
  `environment_extensions` and `event_extensions` read `bma_*` response fields
76
92
  as typed values. To write them on the official create / update, splat the
77
93
  typed `extra_body` of `session_options(model_override=…, harness=…)`,
78
94
  `agent_options(harness=…)` or `environment_options(desktop=…)`
79
95
  (`model_override=None` revokes).
80
- - **Project.** `Bma(project=…)` sets `x-bma-project-id`;
96
+ - **Project.** `Bma(project=…)` sets `bma-workspace-id`;
81
97
  `client.with_options(project=…)` copies the client into another project.
82
98
  - **Idempotency.** Extension creates send a random `Idempotency-Key` once per
83
99
  call, so automatic retries resend it; pass `idempotency_key=` to choose it.
@@ -17,7 +17,7 @@ credential (hand end users a ticket, never the key).
17
17
 
18
18
  | | |
19
19
  | --- | --- |
20
- | Version | 2.0.0, see [CHANGELOG](../CHANGELOG.md); from 1.x: [MIGRATION](../MIGRATION.md#python-1x--20) |
20
+ | Version | 2.2.0, see [CHANGELOG](../CHANGELOG.md); from 1.x: [MIGRATION](../MIGRATION.md#python-1x--20) |
21
21
  | Official core | `anthropic` 2.6.0 (exact pin) |
22
22
  | Python | 3.10 or newer |
23
23
 
@@ -61,13 +61,29 @@ except bma_sdk.NotFoundError as err:
61
61
 
62
62
  `AsyncBma` is the same with `await` / `async for` (`await client.beta.sessions.events.stream(id)`).
63
63
 
64
+ To send first, use `send_and_stream`: it opens the stream at the cursor read
65
+ before the send (`bma_resume_cursor`), so frames an executor wrote before the
66
+ stream opened are not lost. `replayed` is true when the server gave no cursor
67
+ and the stream starts at `Last-Event-ID: 0` (pick your turn by `bma_input_id`).
68
+
69
+ ```python
70
+ result = client.beta.sessions.events.send_and_stream(session.id, events=[
71
+ {"type": "user.message", "content": [{"type": "text", "text": "Next step."}]},
72
+ ])
73
+ with result.stream as stream:
74
+ for event in stream:
75
+ if event.type == "session.status_idle":
76
+ break
77
+ ```
78
+ (`await client.beta.sessions.events.send_and_stream(...)` on `AsyncBma`.)
79
+
64
80
  - **Extension fields.** `session_extensions`, `agent_extensions`,
65
81
  `environment_extensions` and `event_extensions` read `bma_*` response fields
66
82
  as typed values. To write them on the official create / update, splat the
67
83
  typed `extra_body` of `session_options(model_override=…, harness=…)`,
68
84
  `agent_options(harness=…)` or `environment_options(desktop=…)`
69
85
  (`model_override=None` revokes).
70
- - **Project.** `Bma(project=…)` sets `x-bma-project-id`;
86
+ - **Project.** `Bma(project=…)` sets `bma-workspace-id`;
71
87
  `client.with_options(project=…)` copies the client into another project.
72
88
  - **Idempotency.** Extension creates send a random `Idempotency-Key` once per
73
89
  call, so automatic retries resend it; pass `idempotency_key=` to choose it.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "bma-sdk"
3
- version = "2.0.0"
3
+ version = "2.2.0"
4
4
  description = "Python client for BMA: the official Anthropic SDK with the BMA extensions (machines, machine pools, desktop and terminal sessions) under client.beta."
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -18,7 +18,7 @@ from anthropic import (
18
18
  UnprocessableEntityError,
19
19
  )
20
20
 
21
- from ._beta import AsyncBmaBeta, BmaBeta
21
+ from ._beta import AsyncBmaBeta, BmaBeta, SentStream
22
22
  from ._client import DEFAULT_BASE_URL, AsyncBma, Bma
23
23
  from ._errors import error_code
24
24
  from ._extensions import (
@@ -43,7 +43,7 @@ from ._resume import StreamNotResumedError
43
43
  __all__ = [
44
44
  "APIConnectionError", "APIError", "APIStatusError", "APITimeoutError", "AnthropicError",
45
45
  "AsyncBma", "AsyncBmaBeta", "AgentExt", "AuthenticationError", "BadRequestError", "Bma", "BmaBeta",
46
- "ConflictError", "DEFAULT_BASE_URL", "EnvironmentDesktop", "EnvironmentExt", "EnvironmentMachine",
46
+ "ConflictError", "DEFAULT_BASE_URL", "SentStream", "EnvironmentDesktop", "EnvironmentExt", "EnvironmentMachine",
47
47
  "EventExt", "Harness", "InternalServerError", "NotFoundError", "PermissionDeniedError", "RateLimitError",
48
48
  "SessionExt", "StreamNotResumedError", "UnprocessableEntityError", "agent_extensions", "agent_options",
49
49
  "environment_extensions", "environment_options", "error_code", "event_extensions", "models", "params",
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import List, Optional, Union
3
+ from dataclasses import dataclass
4
+ from typing import Any, List, Optional, Union
4
5
 
5
6
  import httpx2
6
7
  from anthropic._compat import cached_property
@@ -20,7 +21,33 @@ from ._generated.resources import (
20
21
  ExtensionServices,
21
22
  OrganizationProjects,
22
23
  )
23
- from ._resume import AsyncResumingStream, ResumingStream
24
+ from ._resume import AsyncResumingStream, ResumingStream, resume_cursor
25
+
26
+
27
+ @dataclass
28
+ class SentStream:
29
+ """The result of `send_and_stream`."""
30
+
31
+ sent: Any
32
+ """The send response."""
33
+ stream: Any
34
+ """Starts at the cursor read before the send: its first frames are the sent
35
+ `user.message` and its turn."""
36
+ replayed: bool
37
+ """True when the server gave no `bma_resume_cursor` for a `user.message`: the
38
+ stream replays from `Last-Event-ID: 0`, so it can carry events that precede
39
+ the send; pick this one's turn by `bma_input_id`."""
40
+
41
+
42
+ _SEND_AND_STREAM_DOC = """Send events, then open the resuming stream at the cursor the send returned
43
+ (`bma_resume_cursor`: the session's last sequence before the send), so a
44
+ frame an executor wrote before the stream opened is not lost. The
45
+ official pattern, a stream opened before the send, needs no cursor; this
46
+ one is for a caller that sends first. Without a cursor for a
47
+ `user.message` the stream starts at `Last-Event-ID: 0` (`replayed`); a
48
+ send with no `user.message` streams from the server's default position
49
+ (new events only). A send error raises with no stream; an error opening
50
+ the stream raises too, after the message was accepted."""
24
51
 
25
52
 
26
53
  class BmaEvents(Events):
@@ -44,6 +71,12 @@ class BmaEvents(Events):
44
71
  frame and returns every event once. The official, non-resuming stream is
45
72
  `Events.stream(client.beta.sessions.events, ...)`."""
46
73
 
74
+ return self._open(session_id, None, event_deltas, betas, workspace_id, extra_headers, extra_query, extra_body, timeout)
75
+
76
+ def _open(
77
+ self, session_id: str, after: Optional[int], event_deltas: Any, betas: Any, workspace_id: Any,
78
+ extra_headers: Any, extra_query: Any, extra_body: Any, timeout: Any,
79
+ ) -> Stream[BetaManagedAgentsStreamSessionEvents]:
47
80
  def open_stream(last_event_id: Optional[str]) -> Stream[BetaManagedAgentsStreamSessionEvents]:
48
81
  headers = extra_headers if last_event_id is None else {**(extra_headers or {}), "Last-Event-ID": last_event_id}
49
82
  return Events.stream(
@@ -58,7 +91,30 @@ class BmaEvents(Events):
58
91
  timeout=timeout,
59
92
  )
60
93
 
61
- return ResumingStream(open_stream(None), open_stream)
94
+ return ResumingStream(open_stream(None if after is None else str(after)), open_stream, after)
95
+
96
+ def send_and_stream(
97
+ self,
98
+ session_id: str,
99
+ *,
100
+ events: Any,
101
+ event_deltas: List[BetaManagedAgentsDeltaType] | Omit = omit,
102
+ betas: List[AnthropicBetaParam] | Omit = omit,
103
+ workspace_id: str | Omit = omit,
104
+ extra_headers: Headers | None = None,
105
+ extra_query: Query | None = None,
106
+ extra_body: Body | None = None,
107
+ timeout: float | httpx2.Timeout | None | NotGiven = not_given,
108
+ ) -> SentStream:
109
+ sent = self.send(
110
+ session_id, events=events, betas=betas, workspace_id=workspace_id,
111
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout,
112
+ )
113
+ after, replayed = resume_cursor(sent)
114
+ stream = self._open(session_id, after, event_deltas, betas, workspace_id, extra_headers, extra_query, extra_body, timeout)
115
+ return SentStream(sent, stream, replayed)
116
+
117
+ send_and_stream.__doc__ = _SEND_AND_STREAM_DOC
62
118
 
63
119
 
64
120
  class AsyncBmaEvents(AsyncEvents):
@@ -79,6 +135,12 @@ class AsyncBmaEvents(AsyncEvents):
79
135
  """Stream Events. Same signature and frames as the official method, resuming
80
136
  a dropped connection with `Last-Event-ID` (see `BmaEvents.stream`)."""
81
137
 
138
+ return await self._open(session_id, None, event_deltas, betas, workspace_id, extra_headers, extra_query, extra_body, timeout)
139
+
140
+ async def _open(
141
+ self, session_id: str, after: Optional[int], event_deltas: Any, betas: Any, workspace_id: Any,
142
+ extra_headers: Any, extra_query: Any, extra_body: Any, timeout: Any,
143
+ ) -> AsyncStream[BetaManagedAgentsStreamSessionEvents]:
82
144
  async def open_stream(last_event_id: Optional[str]) -> AsyncStream[BetaManagedAgentsStreamSessionEvents]:
83
145
  headers = extra_headers if last_event_id is None else {**(extra_headers or {}), "Last-Event-ID": last_event_id}
84
146
  return await AsyncEvents.stream(
@@ -93,7 +155,30 @@ class AsyncBmaEvents(AsyncEvents):
93
155
  timeout=timeout,
94
156
  )
95
157
 
96
- return AsyncResumingStream(await open_stream(None), open_stream)
158
+ return AsyncResumingStream(await open_stream(None if after is None else str(after)), open_stream, after)
159
+
160
+ async def send_and_stream(
161
+ self,
162
+ session_id: str,
163
+ *,
164
+ events: Any,
165
+ event_deltas: List[BetaManagedAgentsDeltaType] | Omit = omit,
166
+ betas: List[AnthropicBetaParam] | Omit = omit,
167
+ workspace_id: str | Omit = omit,
168
+ extra_headers: Headers | None = None,
169
+ extra_query: Query | None = None,
170
+ extra_body: Body | None = None,
171
+ timeout: float | httpx2.Timeout | None | NotGiven = not_given,
172
+ ) -> SentStream:
173
+ sent = await self.send(
174
+ session_id, events=events, betas=betas, workspace_id=workspace_id,
175
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout,
176
+ )
177
+ after, replayed = resume_cursor(sent)
178
+ stream = await self._open(session_id, after, event_deltas, betas, workspace_id, extra_headers, extra_query, extra_body, timeout)
179
+ return SentStream(sent, stream, replayed)
180
+
181
+ send_and_stream.__doc__ = _SEND_AND_STREAM_DOC
97
182
 
98
183
 
99
184
  class BmaSessions(Sessions):
@@ -31,10 +31,10 @@ def _settings(
31
31
  env_project = os.environ.get("BMA_PROJECT_ID", "").strip()
32
32
  headers: dict[str, str] = {"X-BMA-SDK": f"bma-sdk-py/{_version()}"}
33
33
  if env_project:
34
- headers["x-bma-project-id"] = env_project
34
+ headers["bma-workspace-id"] = env_project
35
35
  headers.update(default_headers or {})
36
36
  if project:
37
- headers["x-bma-project-id"] = project
37
+ headers["bma-workspace-id"] = project
38
38
  return {
39
39
  **kwargs,
40
40
  "api_key": key,
@@ -48,7 +48,7 @@ class Bma(Anthropic):
48
48
  whose `beta` adds the BMA extensions. It never reads ANTHROPIC_API_KEY,
49
49
  ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL or the credential profiles of the
50
50
  official client: the key defaults to BMA_API_KEY, the origin to BMA_BASE_URL
51
- and the project (header x-bma-project-id) to BMA_PROJECT_ID.
51
+ and the project (header bma-workspace-id) to BMA_PROJECT_ID.
52
52
 
53
53
  Only use it on a server: the API key is a tenant credential. End-user
54
54
  clients get single-use tickets instead.
@@ -72,7 +72,7 @@ class Bma(Anthropic):
72
72
  def copy(self, *, project: Optional[str] = None, **kwargs: Any) -> Self:
73
73
  """A copy with other options; `project` replaces the project scope."""
74
74
  if project:
75
- kwargs["default_headers"] = {**(kwargs.get("default_headers") or {}), "x-bma-project-id": project}
75
+ kwargs["default_headers"] = {**(kwargs.get("default_headers") or {}), "bma-workspace-id": project}
76
76
  return super().copy(**kwargs)
77
77
 
78
78
  with_options = copy
@@ -99,7 +99,7 @@ class AsyncBma(AsyncAnthropic):
99
99
  def copy(self, *, project: Optional[str] = None, **kwargs: Any) -> Self:
100
100
  """A copy with other options; `project` replaces the project scope."""
101
101
  if project:
102
- kwargs["default_headers"] = {**(kwargs.get("default_headers") or {}), "x-bma-project-id": project}
102
+ kwargs["default_headers"] = {**(kwargs.get("default_headers") or {}), "bma-workspace-id": project}
103
103
  return super().copy(**kwargs)
104
104
 
105
105
  with_options = copy
@@ -50,8 +50,9 @@ def _position(event: Any) -> tuple[int, str]:
50
50
  class _Tracker:
51
51
  """Which frames were returned already (shared by the sync and async stream)."""
52
52
 
53
- def __init__(self) -> None:
53
+ def __init__(self, after: Optional[int] = None) -> None:
54
54
  self.sequence = 0
55
+ self.after = after # the Last-Event-ID the stream was opened with
55
56
  self.seen: set[str] = set()
56
57
 
57
58
  def fresh(self, event: Any) -> bool:
@@ -76,8 +77,11 @@ class _Tracker:
76
77
  return True
77
78
 
78
79
  def resume_id(self) -> Optional[str]:
79
- # None means the server's default position (new events only).
80
- return str(self.sequence - 1) if self.sequence >= 1 else None
80
+ # Before any durable frame: the anchor the stream was opened with; None
81
+ # means the server's default position (new events only).
82
+ if self.sequence >= 1:
83
+ return str(self.sequence - 1)
84
+ return None if self.after is None else str(self.after)
81
85
 
82
86
  def delay(self, failures: int) -> float:
83
87
  return min(CONFIG.backoff * 2**failures, CONFIG.max_backoff)
@@ -92,13 +96,14 @@ class _State(Generic[_T]):
92
96
  class ResumingStream(Stream[_T]):
93
97
  """The official `Stream` that reconnects with Last-Event-ID."""
94
98
 
95
- def __init__(self, first: Stream[_T], connect: Callable[[Optional[str]], Stream[_T]]) -> None:
99
+ def __init__(self, first: Stream[_T], connect: Callable[[Optional[str]], Stream[_T]], after: Optional[int] = None) -> None:
96
100
  super().__init__(cast_to=first._cast_to, response=first.response, client=first._client, options=first._options)
97
101
  self._state: _State[_T] = _State(first)
98
102
  self._connect = connect
103
+ self._after = after
99
104
 
100
105
  def __stream__(self) -> Iterator[_T]:
101
- state, track, failures = self._state, _Tracker(), 0
106
+ state, track, failures = self._state, _Tracker(self._after), 0
102
107
  try:
103
108
  while True:
104
109
  cause: BaseException = StreamNotResumedError("stream ended")
@@ -143,13 +148,16 @@ class ResumingStream(Stream[_T]):
143
148
  class AsyncResumingStream(AsyncStream[_T]):
144
149
  """The official `AsyncStream` that reconnects with Last-Event-ID."""
145
150
 
146
- def __init__(self, first: AsyncStream[_T], connect: Callable[[Optional[str]], Awaitable[AsyncStream[_T]]]) -> None:
151
+ def __init__(
152
+ self, first: AsyncStream[_T], connect: Callable[[Optional[str]], Awaitable[AsyncStream[_T]]], after: Optional[int] = None
153
+ ) -> None:
147
154
  super().__init__(cast_to=first._cast_to, response=first.response, client=first._client, options=first._options)
148
155
  self._state: _State[_T] = _State(first)
149
156
  self._connect = connect
157
+ self._after = after
150
158
 
151
159
  async def __stream__(self) -> AsyncIterator[_T]:
152
- state, track, failures = self._state, _Tracker(), 0
160
+ state, track, failures = self._state, _Tracker(self._after), 0
153
161
  try:
154
162
  while True:
155
163
  cause: BaseException = StreamNotResumedError("stream ended")
@@ -189,3 +197,18 @@ class AsyncResumingStream(AsyncStream[_T]):
189
197
  async def close(self) -> None:
190
198
  self._state.closed = True
191
199
  await self._state.current.close()
200
+
201
+
202
+ def resume_cursor(sent: Any) -> tuple[Optional[int], bool]:
203
+ """The Last-Event-ID for a stream opened after a send, and whether it is a
204
+ replay: the smallest `bma_resume_cursor` of the response's `user.message`
205
+ events; (0, True) when one has none; (None, False) without a `user.message`."""
206
+ after: Optional[int] = None
207
+ for event in getattr(sent, "data", None) or []:
208
+ if getattr(event, "type", None) != "user.message":
209
+ continue
210
+ cursor = (getattr(event, "model_extra", None) or {}).get("bma_resume_cursor")
211
+ if not isinstance(cursor, int) or isinstance(cursor, bool):
212
+ return 0, True
213
+ after = cursor if after is None else min(after, cursor)
214
+ return after, False
@@ -21,7 +21,7 @@ def test_reads_the_bma_environment_only(serve, monkeypatch):
21
21
  assert [r.path for r in s.seen] == ["/v1/machines", "/v1/agents"]
22
22
  for r in s.seen:
23
23
  assert r.headers["authorization"] == "Bearer bma-key"
24
- assert r.headers["x-bma-project-id"] == "proj_1"
24
+ assert r.headers["bma-workspace-id"] == "proj_1"
25
25
  assert r.headers["x-bma-sdk"].startswith("bma-sdk-py/")
26
26
 
27
27
 
@@ -37,7 +37,7 @@ def test_default_origin_requires_key_and_copy_keeps_settings(serve, monkeypatch)
37
37
  assert isinstance(clone, Bma)
38
38
  base.beta.machines.list()
39
39
  clone.beta.machines.list()
40
- assert [r.headers["x-bma-project-id"] for r in s.seen] == ["proj_a", "proj_b"]
40
+ assert [r.headers["bma-workspace-id"] for r in s.seen] == ["proj_a", "proj_b"]
41
41
  assert s.seen[1].headers["authorization"] == "Bearer bma-key"
42
42
 
43
43
 
@@ -66,6 +66,21 @@ class CuttingTransport(httpx2.HTTPTransport):
66
66
  return httpx2.Response(res.status_code, headers=res.headers, stream=CutStream(res.stream, self.cut_after), extensions=res.extensions)
67
67
 
68
68
 
69
+ class DelayedStreamTransport(httpx2.HTTPTransport):
70
+ """Holds the first event-stream request back and records its Last-Event-ID."""
71
+
72
+ def __init__(self, delay: float) -> None:
73
+ super().__init__()
74
+ self.delay, self.last_event_ids = delay, []
75
+
76
+ def handle_request(self, request: httpx2.Request) -> httpx2.Response:
77
+ if request.url.path.endswith("/events/stream"):
78
+ self.last_event_ids.append(request.headers.get("last-event-id", ""))
79
+ if len(self.last_event_ids) == 1:
80
+ time.sleep(self.delay)
81
+ return super().handle_request(request)
82
+
83
+
69
84
  def wait_for(events: Iterator[Any], type: str, timeout: float, seen: Optional[Any] = None) -> Any:
70
85
  deadline = time.time() + timeout
71
86
  for event in events:
@@ -186,6 +201,28 @@ def test_staging() -> None:
186
201
  idle = wait_for(events, "session.status_idle", 90)
187
202
  print(f"interrupted: session.status_idle after {int((time.time() - start) * 1000)}ms (stop_reason {idle.stop_reason.type})")
188
203
 
204
+ # send_and_stream subscribes from the cursor read before the send: the
205
+ # stream request is held back, so the executor writes the turn's first
206
+ # frames before the stream opens, and the stream must still start at
207
+ # this message's user.message.
208
+ held = DelayedStreamTransport(15)
209
+ delayed = Bma(http_client=httpx2.Client(transport=held, timeout=httpx2.Timeout(600)))
210
+ result = delayed.beta.sessions.events.send_and_stream(session.id, events=text("Reply with the single word OK."))
211
+ assert result.replayed is False, f"server gave no bma_resume_cursor: {result.sent.to_json()}"
212
+ sent_id = result.sent.data[0].id
213
+ order: list[str] = []
214
+ with result.stream as frames:
215
+ for ev in frames:
216
+ assert ev.type != "session.error", ev.to_json()
217
+ order.append(ev.type)
218
+ if ev.type == "user.message":
219
+ # The send response id is the input (ain_); the event carries it as bma_input_id.
220
+ assert bma_sdk.event_extensions(ev).input_id == sent_id, "the first user.message is not the sent one (stream started too early)"
221
+ if ev.type == "session.status_idle" and "agent.message" in order:
222
+ break
223
+ assert "user.message" in order and "agent.message" in order, order
224
+ print(f"sent {sent_id}, stream held 15s, Last-Event-ID {held.last_event_ids}; frames {order}")
225
+
189
226
  # files
190
227
  content = f"hello from bma-sdk py 2.0 {suffix}"
191
228
  meta = c.beta.files.upload(file=(f"{suffix}.txt", content.encode(), "text/plain"))
@@ -0,0 +1,201 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import pytest
6
+
7
+ from bma_sdk import AsyncBma, BadRequestError, Bma, NotFoundError, StreamNotResumedError, _resume
8
+ from conftest import frame
9
+
10
+
11
+ def handler_for(frames_by_connection):
12
+ def handler(r, req, n):
13
+ frames = frames_by_connection(n)
14
+ if frames is None:
15
+ r.json(404, {"type": "error", "error": {"type": "not_found_error", "message": "gone"}})
16
+ else:
17
+ r.sse(*frames)
18
+
19
+ return handler
20
+
21
+
22
+ def script(n):
23
+ if n == 1: # two events of sequence 1, an announcement, then the connection ends
24
+ return [frame("session.status_running", "sesst_1_run", 1), frame("user.message", "evt_1", 1), frame("session.status_idle", "sesst_x", 0)]
25
+ if n == 2: # the server resumes after sequence 0: replays sequence 1
26
+ return [frame("session.status_running", "sesst_1_run", 1), frame("user.message", "evt_1", 1), frame("session.status_idle", "sesst_x", 1), frame("agent.message", "evt_2", 2), "event: ping\ndata: {}\n\n"]
27
+ if n == 3:
28
+ return [frame("session.status_idle", "sesst_2_idle", 2)]
29
+ return None
30
+
31
+
32
+ EXPECTED = ["sesst_1_run", "evt_1", "sesst_x", "evt_2", "sesst_2_idle"]
33
+
34
+
35
+ def check_requests(s):
36
+ assert len(s.seen) == 4
37
+ assert [r.headers.get("last-event-id") for r in s.seen[:3]] == [None, "0", "1"]
38
+ assert s.seen[0].headers["anthropic-beta"] == "managed-agents-2026-04-01"
39
+ assert s.seen[0].path == "/v1/sessions/ses_1/events/stream"
40
+
41
+
42
+ def test_resumes_with_last_event_id_and_returns_every_event_once(serve):
43
+ s = serve(handler_for(script))
44
+ stream = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.stream("ses_1")
45
+ got: list[str] = []
46
+ with pytest.raises(NotFoundError):
47
+ for event in stream:
48
+ got.append(event.id) # type: ignore[union-attr]
49
+ assert got == EXPECTED
50
+ check_requests(s)
51
+
52
+
53
+ async def test_async_resumes_with_last_event_id(serve):
54
+ s = serve(handler_for(script))
55
+ client = AsyncBma(api_key="k", base_url=s.url, max_retries=0)
56
+ stream = await client.beta.sessions.events.stream("ses_1")
57
+ got: list[str] = []
58
+ with pytest.raises(NotFoundError):
59
+ async for event in stream:
60
+ got.append(event.id) # type: ignore[union-attr]
61
+ assert got == EXPECTED
62
+ check_requests(s)
63
+ await client.close()
64
+
65
+
66
+ def test_gives_up_after_max_reconnects(serve):
67
+ s = serve(lambda r, req, n: r.sse())
68
+ stream = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.stream("ses_1")
69
+ with pytest.raises(StreamNotResumedError, match="not resumed after 5 attempts"):
70
+ list(stream)
71
+ assert len(s.seen) == 1 + 5
72
+
73
+
74
+ async def test_async_gives_up_after_max_reconnects(serve):
75
+ s = serve(lambda r, req, n: r.sse())
76
+ client = AsyncBma(api_key="k", base_url=s.url, max_retries=0)
77
+ stream = await client.beta.sessions.events.stream("ses_1")
78
+ with pytest.raises(StreamNotResumedError):
79
+ async for _ in stream:
80
+ pass
81
+ assert len(s.seen) == 1 + 5
82
+ await client.close()
83
+
84
+
85
+ def test_close_stops_the_stream(serve, monkeypatch):
86
+ from bma_sdk import _resume
87
+
88
+ monkeypatch.setattr(_resume.CONFIG, "backoff", 60.0)
89
+ s = serve(lambda r, req, n: r.sse(frame("user.message", "evt_1", 1)))
90
+ stream = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.stream("ses_1")
91
+ got = []
92
+ for event in stream:
93
+ got.append(event.id) # type: ignore[union-attr]
94
+ stream.close()
95
+ assert got == ["evt_1"] and len(s.seen) == 1
96
+
97
+
98
+ # A queued input's executor frames are written before the caller subscribes:
99
+ # POST events appends them to a log and answers with the cursor (None: none);
100
+ # the stream replays the log after Last-Event-ID, and with no header it sends
101
+ # nothing (a live-only stream opened after the send sees no past frame).
102
+ def anchor_handler(cursor=None, drops=0, old=0, send_type="user.message"):
103
+ log = [frame("agent.message", f"old_{i + 1}", i + 1) for i in range(old)]
104
+ streams = [0]
105
+
106
+ def handler(r, req, n):
107
+ if req.method == "POST":
108
+ before = len(log)
109
+ log.extend([frame("user.message", "evt_in", before + 1), frame("agent.message", "evt_out", before + 2)])
110
+ event: dict[str, Any] = {"type": send_type, "id": "evt_in", "processed_at": "2026-11-08T00:00:00Z"}
111
+ if send_type == "user.message":
112
+ event["content"] = [{"type": "text", "text": "hi"}]
113
+ if cursor is not None:
114
+ event["bma_resume_cursor"] = cursor
115
+ return r.json(200, {"data": [event]})
116
+ streams[0] += 1
117
+ last = req.headers.get("last-event-id")
118
+ if streams[0] <= drops or last is None:
119
+ return r.sse() # a drop, or live only: the frames were written before
120
+ r.sse(*log[int(last):])
121
+
122
+ return handler
123
+
124
+
125
+ USER_MESSAGE: Any = [{"type": "user.message", "content": [{"type": "text", "text": "hi"}]}]
126
+
127
+
128
+ INTERRUPT: Any = [{"type": "user.interrupt"}]
129
+
130
+
131
+ def first_two(stream):
132
+ got = []
133
+ for event in stream:
134
+ got.append(event.id)
135
+ if len(got) == 2:
136
+ break
137
+ return got
138
+
139
+
140
+ def test_send_and_stream_keeps_frames_written_before_the_subscribe(serve, monkeypatch):
141
+ s = serve(anchor_handler(cursor=0))
142
+ client = Bma(api_key="k", base_url=s.url, max_retries=0)
143
+ client.beta.sessions.events.send("ses_1", events=USER_MESSAGE)
144
+ monkeypatch.setattr(_resume.CONFIG, "max_reconnects", 1)
145
+ with pytest.raises(StreamNotResumedError): # a live-only stream after the send gets nothing
146
+ first_two(client.beta.sessions.events.stream("ses_1"))
147
+ monkeypatch.setattr(_resume.CONFIG, "max_reconnects", 5)
148
+ s.seen.clear()
149
+
150
+ result = client.beta.sessions.events.send_and_stream("ses_1", events=USER_MESSAGE)
151
+ assert result.replayed is False
152
+ assert result.sent.data[0].id == "evt_in"
153
+ assert first_two(result.stream) == ["evt_in", "evt_out"]
154
+ assert [r.method for r in s.seen] == ["POST", "GET"]
155
+ assert s.seen[1].headers.get("last-event-id") == "0" # cursor 0 is still sent
156
+
157
+
158
+ def test_send_and_stream_reconnect_keeps_the_cursor(serve):
159
+ s = serve(anchor_handler(cursor=7, drops=2, old=7))
160
+ result = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.send_and_stream("ses_1", events=USER_MESSAGE)
161
+ assert first_two(result.stream) == ["evt_in", "evt_out"]
162
+ assert [r.headers.get("last-event-id") for r in s.seen[1:]] == ["7", "7", "7"]
163
+
164
+
165
+ def test_send_and_stream_without_cursor_replays_from_the_start(serve):
166
+ s = serve(anchor_handler())
167
+ result = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.send_and_stream("ses_1", events=USER_MESSAGE)
168
+ assert result.replayed is True
169
+ assert first_two(result.stream) == ["evt_in", "evt_out"]
170
+ assert s.seen[1].headers.get("last-event-id") == "0"
171
+
172
+
173
+ def test_send_and_stream_without_user_message_is_live_only(serve):
174
+ s = serve(anchor_handler(send_type="user.interrupt"))
175
+ result = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.send_and_stream(
176
+ "ses_1", events=INTERRUPT
177
+ )
178
+ assert result.replayed is False
179
+ assert s.seen[1].headers.get("last-event-id") is None
180
+ result.stream.close()
181
+
182
+
183
+ def test_send_and_stream_send_error_opens_no_stream(serve):
184
+ s = serve(lambda r, req, n: r.json(400, {"type": "error", "error": {"type": "invalid_request_error", "message": "bad"}}))
185
+ with pytest.raises(BadRequestError):
186
+ Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.send_and_stream("ses_1", events=USER_MESSAGE)
187
+ assert len(s.seen) == 1
188
+
189
+
190
+ async def test_async_send_and_stream_keeps_frames_written_before_the_subscribe(serve):
191
+ s = serve(anchor_handler(cursor=3, drops=1, old=3))
192
+ client = AsyncBma(api_key="k", base_url=s.url, max_retries=0)
193
+ result = await client.beta.sessions.events.send_and_stream("ses_1", events=USER_MESSAGE)
194
+ got = []
195
+ async for event in result.stream:
196
+ got.append(event.id)
197
+ if len(got) == 2:
198
+ break
199
+ assert got == ["evt_in", "evt_out"]
200
+ assert [r.headers.get("last-event-id") for r in s.seen[1:]] == ["3", "3"]
201
+ await client.close()
@@ -1,93 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import pytest
4
-
5
- from bma_sdk import AsyncBma, Bma, NotFoundError, StreamNotResumedError
6
- from conftest import frame
7
-
8
-
9
- def handler_for(frames_by_connection):
10
- def handler(r, req, n):
11
- frames = frames_by_connection(n)
12
- if frames is None:
13
- r.json(404, {"type": "error", "error": {"type": "not_found_error", "message": "gone"}})
14
- else:
15
- r.sse(*frames)
16
-
17
- return handler
18
-
19
-
20
- def script(n):
21
- if n == 1: # two events of sequence 1, an announcement, then the connection ends
22
- return [frame("session.status_running", "sesst_1_run", 1), frame("user.message", "evt_1", 1), frame("session.status_idle", "sesst_x", 0)]
23
- if n == 2: # the server resumes after sequence 0: replays sequence 1
24
- return [frame("session.status_running", "sesst_1_run", 1), frame("user.message", "evt_1", 1), frame("session.status_idle", "sesst_x", 1), frame("agent.message", "evt_2", 2), "event: ping\ndata: {}\n\n"]
25
- if n == 3:
26
- return [frame("session.status_idle", "sesst_2_idle", 2)]
27
- return None
28
-
29
-
30
- EXPECTED = ["sesst_1_run", "evt_1", "sesst_x", "evt_2", "sesst_2_idle"]
31
-
32
-
33
- def check_requests(s):
34
- assert len(s.seen) == 4
35
- assert [r.headers.get("last-event-id") for r in s.seen[:3]] == [None, "0", "1"]
36
- assert s.seen[0].headers["anthropic-beta"] == "managed-agents-2026-04-01"
37
- assert s.seen[0].path == "/v1/sessions/ses_1/events/stream"
38
-
39
-
40
- def test_resumes_with_last_event_id_and_returns_every_event_once(serve):
41
- s = serve(handler_for(script))
42
- stream = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.stream("ses_1")
43
- got: list[str] = []
44
- with pytest.raises(NotFoundError):
45
- for event in stream:
46
- got.append(event.id) # type: ignore[union-attr]
47
- assert got == EXPECTED
48
- check_requests(s)
49
-
50
-
51
- async def test_async_resumes_with_last_event_id(serve):
52
- s = serve(handler_for(script))
53
- client = AsyncBma(api_key="k", base_url=s.url, max_retries=0)
54
- stream = await client.beta.sessions.events.stream("ses_1")
55
- got: list[str] = []
56
- with pytest.raises(NotFoundError):
57
- async for event in stream:
58
- got.append(event.id) # type: ignore[union-attr]
59
- assert got == EXPECTED
60
- check_requests(s)
61
- await client.close()
62
-
63
-
64
- def test_gives_up_after_max_reconnects(serve):
65
- s = serve(lambda r, req, n: r.sse())
66
- stream = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.stream("ses_1")
67
- with pytest.raises(StreamNotResumedError, match="not resumed after 5 attempts"):
68
- list(stream)
69
- assert len(s.seen) == 1 + 5
70
-
71
-
72
- async def test_async_gives_up_after_max_reconnects(serve):
73
- s = serve(lambda r, req, n: r.sse())
74
- client = AsyncBma(api_key="k", base_url=s.url, max_retries=0)
75
- stream = await client.beta.sessions.events.stream("ses_1")
76
- with pytest.raises(StreamNotResumedError):
77
- async for _ in stream:
78
- pass
79
- assert len(s.seen) == 1 + 5
80
- await client.close()
81
-
82
-
83
- def test_close_stops_the_stream(serve, monkeypatch):
84
- from bma_sdk import _resume
85
-
86
- monkeypatch.setattr(_resume.CONFIG, "backoff", 60.0)
87
- s = serve(lambda r, req, n: r.sse(frame("user.message", "evt_1", 1)))
88
- stream = Bma(api_key="k", base_url=s.url, max_retries=0).beta.sessions.events.stream("ses_1")
89
- got = []
90
- for event in stream:
91
- got.append(event.id) # type: ignore[union-attr]
92
- stream.close()
93
- assert got == ["evt_1"] and len(s.seen) == 1
File without changes
File without changes
File without changes
File without changes