bma-executor-sdk 1.0.5__tar.gz → 1.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.
Files changed (39) hide show
  1. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/PKG-INFO +3 -3
  2. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/README.md +2 -2
  3. bma_executor_sdk-1.2.0/examples/session_context.py +180 -0
  4. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/pyproject.toml +3 -3
  5. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/__init__.py +20 -1
  6. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/_rpc.py +64 -0
  7. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/client.py +47 -5
  8. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/generated.py +53 -5
  9. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/methods.py +8 -0
  10. bma_executor_sdk-1.2.0/src/bma_executor_sdk/session_context.py +111 -0
  11. bma_executor_sdk-1.2.0/tests/test_base_url.py +60 -0
  12. bma_executor_sdk-1.2.0/tests/test_example_session_context.py +50 -0
  13. bma_executor_sdk-1.2.0/tests/test_session_context.py +134 -0
  14. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/typecheck/typed_tools.py +2 -2
  15. bma_executor_sdk-1.0.5/tests/test_base_url.py +0 -36
  16. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/.gitignore +0 -0
  17. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/examples/agent_minimal.py +0 -0
  18. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/examples/executor_minimal.py +0 -0
  19. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/examples/harness_loopback.py +0 -0
  20. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/_methods.py +0 -0
  21. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/_npipe.py +0 -0
  22. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/agent.py +0 -0
  23. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/harness.py +0 -0
  24. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/py.typed +0 -0
  25. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/tools.py +0 -0
  26. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/src/bma_executor_sdk/transport.py +0 -0
  27. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/executor_helpers.py +0 -0
  28. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_close_codes.py +0 -0
  29. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_executor_conformance.py +0 -0
  30. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_executor_contract.py +0 -0
  31. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_executor_interop.py +0 -0
  32. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_executor_runtime.py +0 -0
  33. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_executor_token_refresh.py +0 -0
  34. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_npipe.py +0 -0
  35. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_reconnect.py +0 -0
  36. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_registration_refused.py +0 -0
  37. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_review.py +0 -0
  38. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_rpc_unretrieved_future.py +0 -0
  39. {bma_executor_sdk-1.0.5 → bma_executor_sdk-1.2.0}/tests/test_typed_tools.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bma-executor-sdk
3
- Version: 1.0.5
3
+ Version: 1.2.0
4
4
  Summary: BMA executor protocol (bma.executor.v1.1): executor, harness and agent ends on asyncio with WebSocket, Unix socket and in-process transports.
5
5
  Project-URL: Repository, https://github.com/beeos-ai/bma-executor-sdk
6
6
  License-Expression: Apache-2.0
@@ -58,7 +58,7 @@ async def main() -> None:
58
58
  asyncio.run(main())
59
59
  ```
60
60
 
61
- Set `base_url` to your BMA deployment: the hosted service is in early access and the default `DEFAULT_BASE_URL` (`https://api.bma.beeos.ai`) does not resolve yet. It is the deployment origin, the same value as `BMA_BASE_URL` in bma-sdk (for example `https://api.staging.bma.beeos.ai`); the client posts the environment key to `{base_url}/v1/executors/token` and drops a trailing `/api/v1`. The SDK does not read `BMA_BASE_URL` itself. A `token_source` carries its own channel URL.
61
+ Set `base_url` to your BMA deployment: the hosted service is in early access and the default `DEFAULT_BASE_URL` (`https://api.bma.beeos.ai`) does not resolve yet. It is the deployment origin, the same value as `BMA_BASE_URL` in bma-sdk (for example `https://api.staging.bma.beeos.ai`); the client posts the environment key to `{base_url}/v1/environments/{environment_id}/token` (a machine daemon token to `{base_url}/v1/machines/{machine_id}/token`) and drops a trailing `/api/v1`. `machine_id` and `environment_id` are alternatives; an empty `machine_id` reads `BMA_MACHINE_ID` (`MACHINE_ID_ENV`), and without any id the legacy `/api/v1/executors/token` alias is used. The SDK does not read `BMA_BASE_URL` itself. A `token_source` carries its own channel URL.
62
62
 
63
63
  ### A machine-scoped executor must declare `process` or `agent`
64
64
 
@@ -87,7 +87,7 @@ Behavior matches the Go SDK:
87
87
  - `tool.cancel` cancels the handler's task and reports `outcome: "canceled"`; duplicate `tool.call` ids run once.
88
88
  - `tool.result` retries `-32009` / `-32004` / `retryable` errors and hands a lost result to `on_tool_result_lost`.
89
89
  - Reconnect resumes with `resume.executor_id` / `active_sessions`, until `stop()` by default (backoff 1 s doubling to 60 s, jitter); only close codes 4003 and 4004 stop the client, and so does `RegistrationRefusedError` (3 refused registrations in a row). A positive `max_reconnect_attempts` bounds the attempts. `await client.wait_closed()` returns after `stop()` / `executor.close` and raises `ChannelClosed` (4003/4004), `RegistrationRefusedError`, `CredentialRejectedError` (the token endpoint answered 401/403 on reconnect: revoked or invalid credential, not retried) or `ReconnectExhaustedError`; let it end the process so a supervisor can restart it.
90
- - Call `session_ready` after setup and `session_ended` after cleanup. `client.on_request(methods.PROCESS_START, handler)` serves `process.*`, `terminal.*`, `skill.install` or `workspace.backup` yourself with the contract's TypedDicts; `await client.call(methods.SESSION_EVENT, params)` / `await client.notify(methods.TOOL_PROGRESS, params)` send typed methods (`bma_executor_sdk.methods`). There is no execution `Core` in Python.
90
+ - Call `session_ready` after setup and `session_ended` after cleanup. `client.on_request(methods.PROCESS_START, handler)` serves `process.*`, `terminal.*`, `skill.install` or `workspace.backup` yourself with the contract's TypedDicts; `await client.call(methods.SESSION_EVENT, params)` / `await client.notify(methods.TOOL_PROGRESS, params)` send typed methods (`bma_executor_sdk.methods`). There is no execution `Core` in Python. In a `process.start` handler, `await client.session_context(params["process_id"])` reads the session's metadata and `RPCError.with_reason(code, ErrorReason.X, msg)` refuses with a `data.reason` ([session context](../docs/executor/session-context.md)).
91
91
  - Input missing a required member fails the call before the handler runs; a `tool.call` for a tool without a handler is refused with `-32012` before the ack; `shell` / `files` are enabled while a handler of the group is registered unless set `enabled: False`, and a handler registered after `start()` sends `executor.capabilities.update`. `BashResult` beyond `INLINE_RESULT_BYTES` (or `truncated=True`) is cut to Go Core's preview. The `computer_*` tools get slots once the contract defines their input.
92
92
 
93
93
  ## Harness quick start
@@ -47,7 +47,7 @@ async def main() -> None:
47
47
  asyncio.run(main())
48
48
  ```
49
49
 
50
- Set `base_url` to your BMA deployment: the hosted service is in early access and the default `DEFAULT_BASE_URL` (`https://api.bma.beeos.ai`) does not resolve yet. It is the deployment origin, the same value as `BMA_BASE_URL` in bma-sdk (for example `https://api.staging.bma.beeos.ai`); the client posts the environment key to `{base_url}/v1/executors/token` and drops a trailing `/api/v1`. The SDK does not read `BMA_BASE_URL` itself. A `token_source` carries its own channel URL.
50
+ Set `base_url` to your BMA deployment: the hosted service is in early access and the default `DEFAULT_BASE_URL` (`https://api.bma.beeos.ai`) does not resolve yet. It is the deployment origin, the same value as `BMA_BASE_URL` in bma-sdk (for example `https://api.staging.bma.beeos.ai`); the client posts the environment key to `{base_url}/v1/environments/{environment_id}/token` (a machine daemon token to `{base_url}/v1/machines/{machine_id}/token`) and drops a trailing `/api/v1`. `machine_id` and `environment_id` are alternatives; an empty `machine_id` reads `BMA_MACHINE_ID` (`MACHINE_ID_ENV`), and without any id the legacy `/api/v1/executors/token` alias is used. The SDK does not read `BMA_BASE_URL` itself. A `token_source` carries its own channel URL.
51
51
 
52
52
  ### A machine-scoped executor must declare `process` or `agent`
53
53
 
@@ -76,7 +76,7 @@ Behavior matches the Go SDK:
76
76
  - `tool.cancel` cancels the handler's task and reports `outcome: "canceled"`; duplicate `tool.call` ids run once.
77
77
  - `tool.result` retries `-32009` / `-32004` / `retryable` errors and hands a lost result to `on_tool_result_lost`.
78
78
  - Reconnect resumes with `resume.executor_id` / `active_sessions`, until `stop()` by default (backoff 1 s doubling to 60 s, jitter); only close codes 4003 and 4004 stop the client, and so does `RegistrationRefusedError` (3 refused registrations in a row). A positive `max_reconnect_attempts` bounds the attempts. `await client.wait_closed()` returns after `stop()` / `executor.close` and raises `ChannelClosed` (4003/4004), `RegistrationRefusedError`, `CredentialRejectedError` (the token endpoint answered 401/403 on reconnect: revoked or invalid credential, not retried) or `ReconnectExhaustedError`; let it end the process so a supervisor can restart it.
79
- - Call `session_ready` after setup and `session_ended` after cleanup. `client.on_request(methods.PROCESS_START, handler)` serves `process.*`, `terminal.*`, `skill.install` or `workspace.backup` yourself with the contract's TypedDicts; `await client.call(methods.SESSION_EVENT, params)` / `await client.notify(methods.TOOL_PROGRESS, params)` send typed methods (`bma_executor_sdk.methods`). There is no execution `Core` in Python.
79
+ - Call `session_ready` after setup and `session_ended` after cleanup. `client.on_request(methods.PROCESS_START, handler)` serves `process.*`, `terminal.*`, `skill.install` or `workspace.backup` yourself with the contract's TypedDicts; `await client.call(methods.SESSION_EVENT, params)` / `await client.notify(methods.TOOL_PROGRESS, params)` send typed methods (`bma_executor_sdk.methods`). There is no execution `Core` in Python. In a `process.start` handler, `await client.session_context(params["process_id"])` reads the session's metadata and `RPCError.with_reason(code, ErrorReason.X, msg)` refuses with a `data.reason` ([session context](../docs/executor/session-context.md)).
80
80
  - Input missing a required member fails the call before the handler runs; a `tool.call` for a tool without a handler is refused with `-32012` before the ack; `shell` / `files` are enabled while a handler of the group is registered unless set `enabled: False`, and a handler registered after `start()` sends `executor.capabilities.update`. `BashResult` beyond `INLINE_RESULT_BYTES` (or `truncated=True`) is cut to Go Core's preview. The `computer_*` tools get slots once the contract defines their input.
81
81
 
82
82
  ## Harness quick start
@@ -0,0 +1,180 @@
1
+ """A machine-scoped executor whose processes run in a local folder chosen per session.
2
+
3
+ The caller puts opaque references in the session metadata, for example
4
+ {"workspace_ref": "ws_7", "owner": "u_42"}; before spawning, the process.start
5
+ handler reads the session context, refuses another owner's session
6
+ (session_rejected) or an unknown reference (workspace_unavailable), and runs the
7
+ command in this machine's folder for the reference. BMA never stores the path.
8
+
9
+ A process.start without metadata.agent_session_id has no session to check against:
10
+ it is refused with session_rejected, never run in a default folder (the harness
11
+ does not send one; a person's console terminal is terminal.attach, not
12
+ process.start). The exception is a process the platform starts on its own
13
+ (metadata initiator "platform", for example the machine desktop agent): with
14
+ EXAMPLE_PLATFORM_DIR set it runs in that directory by this machine's policy,
15
+ never in a session folder; without it, it is refused too. A package install runs
16
+ a package manager that writes outside the folder: this example has no local
17
+ confirmation, so it refuses with local_confirmation_denied.
18
+
19
+ Python has no built-in process runtime (Go's ProcessOptions.Launch): the executor
20
+ serves process.* itself. This example keeps output in memory and serves
21
+ process.start, process.read and process.list only.
22
+
23
+ BMA_BASE_URL=https://api.<env>.bma.beeos.ai BMA_MACHINE_TOKEN=... \\
24
+ EXAMPLE_OWNER=u_42 EXAMPLE_FOLDERS='{"ws_7": "/Users/me/projects/site"}' \\
25
+ EXAMPLE_PLATFORM_DIR=/Users/me/bma-platform \\
26
+ python session_context.py
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import base64
33
+ import json
34
+ import os
35
+ import platform
36
+ from pathlib import Path
37
+ from typing import Any
38
+
39
+ from bma_executor_sdk import ErrorReason, ExecutorClient, RPCError, methods
40
+ from bma_executor_sdk.generated import JsonRpcErrorCode
41
+
42
+ OWNER = os.environ.get("EXAMPLE_OWNER")
43
+ FOLDERS: dict[str, str] = json.loads(os.environ.get("EXAMPLE_FOLDERS", "{}"))
44
+ # Where platform-initiated processes run; empty means this machine hosts none.
45
+ PLATFORM_DIR = os.environ.get("EXAMPLE_PLATFORM_DIR", "")
46
+ PROCESSES: dict[str, dict[str, Any]] = {}
47
+
48
+
49
+ def refuse(reason: str, message: str) -> RPCError:
50
+ return RPCError.with_reason(JsonRpcErrorCode.Forbidden, reason, message)
51
+
52
+
53
+ def admit(params: dict[str, Any]) -> bool:
54
+ """Refuse what no session or local policy can allow, before reading the session context.
55
+
56
+ Returns True for a process the platform started on its own (no session,
57
+ handled by platform_cwd), False for a process of an agent session.
58
+ """
59
+ metadata = params.get("metadata") or {}
60
+ platform = False
61
+ if not metadata.get("agent_session_id"):
62
+ if not PLATFORM_DIR or metadata.get("initiator") != "platform":
63
+ raise refuse(ErrorReason.SessionRejected, "the process names no agent session")
64
+ platform = True
65
+ if params.get("package_install") is not None:
66
+ raise refuse(ErrorReason.LocalConfirmationDenied, "package installs need a local confirmation this executor does not offer")
67
+ return platform
68
+
69
+
70
+ def confine(folder: str, cwd: str | None) -> Path:
71
+ """Resolve cwd (relative to folder) and refuse one outside it."""
72
+ root = Path(folder).resolve()
73
+ resolved = (root / (cwd or ".")).resolve()
74
+ if not resolved.is_relative_to(root):
75
+ raise refuse(ErrorReason.WorkspaceBoundary, "cwd is outside the allowed folder")
76
+ return resolved
77
+
78
+
79
+ def platform_cwd(params: dict[str, Any]) -> Path:
80
+ return confine(PLATFORM_DIR, params.get("cwd"))
81
+
82
+
83
+ def state(proc: dict[str, Any]) -> dict[str, Any]:
84
+ return {
85
+ "accepted": True, "process_id": proc["id"], "state": proc["state"],
86
+ "cursors": {"stdout": len(proc["stdout"]), "stderr": len(proc["stderr"])},
87
+ "exit_code": proc["exit_code"], "exit_signal": None, **({"stderr": "merge"} if proc["merge"] else {}),
88
+ }
89
+
90
+
91
+ async def pump(stream: asyncio.StreamReader | None, sink: bytearray) -> None:
92
+ while stream and (chunk := await stream.read(65536)):
93
+ sink.extend(chunk)
94
+
95
+
96
+ async def run(proc: dict[str, Any], child: asyncio.subprocess.Process) -> None:
97
+ await asyncio.gather(pump(child.stdout, proc["stdout"]), pump(child.stderr, proc["stderr"]))
98
+ proc["exit_code"], proc["state"] = await child.wait(), "exited"
99
+
100
+
101
+ def make_client() -> ExecutorClient:
102
+ client = ExecutorClient(
103
+ # A machine daemon token and no environment id: a machine-scoped executor.
104
+ environment_id="",
105
+ environment_key=os.environ["BMA_MACHINE_TOKEN"],
106
+ base_url=os.environ.get("BMA_BASE_URL", "https://api.bma.beeos.ai"),
107
+ executor={"name": "session-context-example", "os": platform.system().lower(), "arch": platform.machine(), "version": "0.1.0"},
108
+ capabilities={"process": {"enabled": True, "max_processes": 8, "buffer_bytes": 1 << 20}},
109
+ )
110
+
111
+ async def process_start(params: Any) -> Any:
112
+ if existing := PROCESSES.get(params["process_id"]):
113
+ return state(existing) # a replayed start
114
+ if admit(params):
115
+ cwd = platform_cwd(params) # not a session: its own directory, never a session folder
116
+ else:
117
+ session = await client.session_context(params["process_id"])
118
+ if session["metadata"].get("owner") != OWNER:
119
+ raise refuse(ErrorReason.SessionRejected, "this machine does not serve the session owner")
120
+ folder = FOLDERS.get(session["metadata"].get("workspace_ref", ""))
121
+ if not folder:
122
+ raise refuse(ErrorReason.WorkspaceUnavailable, "unknown workspace on this machine")
123
+ cwd = confine(folder, params.get("cwd"))
124
+ merge = params.get("stderr") == "merge"
125
+ child = await asyncio.create_subprocess_exec(
126
+ *params["argv"], cwd=cwd, env={**os.environ, **(params.get("env") or {})},
127
+ # stderr "merge" (the harness asks for it): one stream, one cursor, reported in the state.
128
+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT if merge else asyncio.subprocess.PIPE,
129
+ stdin=asyncio.subprocess.DEVNULL,
130
+ )
131
+ proc: dict[str, Any] = {"id": params["process_id"], "stdout": bytearray(), "stderr": bytearray(), "exit_code": None, "state": "running", "merge": merge}
132
+ PROCESSES[params["process_id"]] = proc
133
+ asyncio.create_task(run(proc, child))
134
+ return state(proc)
135
+
136
+ async def process_read(params: Any) -> Any:
137
+ proc = PROCESSES.get(params["process_id"])
138
+ if proc is None:
139
+ raise RPCError(JsonRpcErrorCode.NotFound, "process not found")
140
+ data = bytes(proc[params["stream"]])[params["cursor"]:]
141
+ return {
142
+ "process_id": params["process_id"], "stream": params["stream"], "data": base64.b64encode(data).decode(),
143
+ "from_cursor": params["cursor"], "next_cursor": params["cursor"] + len(data), "earliest_cursor": 0,
144
+ "gap": False, "truncated": False, "eof": proc["state"] != "running", "state": proc["state"],
145
+ "exit_code": proc["exit_code"], "exit_signal": None,
146
+ }
147
+
148
+ async def session_assign(params: Any) -> Any:
149
+ # Python has no execution Core: accept the session and report it ready
150
+ # (nothing to prepare here), or the platform never uses this machine.
151
+ asyncio.get_running_loop().call_soon(lambda: asyncio.ensure_future(client.session_ready(
152
+ {"session_id": params["session_id"], "work_id": params["work_id"], "lease_token": params["lease"]["token"]})))
153
+ return {"accepted": True, "session_id": params["session_id"]}
154
+
155
+ client.on_session_assign(session_assign)
156
+ client.on_request(methods.PROCESS_START, process_start)
157
+ async def process_list(_params: Any) -> Any:
158
+ # The platform lists processes when it reconciles a session; a machine-scoped
159
+ # executor that declares process must answer it.
160
+ return {"processes": [state(proc) for proc in PROCESSES.values()]}
161
+
162
+ client.on_request(methods.PROCESS_LIST, process_list)
163
+ client.on_request(methods.PROCESS_READ, process_read)
164
+ return client
165
+
166
+
167
+ async def main() -> None:
168
+ if PLATFORM_DIR:
169
+ Path(PLATFORM_DIR).mkdir(parents=True, exist_ok=True)
170
+ client = make_client()
171
+ registered = await client.start()
172
+ print("registered as", registered["executor_id"])
173
+ try:
174
+ await client.wait_closed()
175
+ finally:
176
+ await client.stop("shutdown")
177
+
178
+
179
+ if __name__ == "__main__":
180
+ asyncio.run(main())
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "bma-executor-sdk"
3
- version = "1.0.5"
3
+ version = "1.2.0"
4
4
  description = "BMA executor protocol (bma.executor.v1.1): executor, harness and agent ends on asyncio with WebSocket, Unix socket and in-process transports."
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -11,7 +11,7 @@ dependencies = ["httpx>=0.27,<1", "websockets>=14,<17"]
11
11
  Repository = "https://github.com/beeos-ai/bma-executor-sdk"
12
12
 
13
13
  [dependency-groups]
14
- dev = ["pytest>=8", "pytest-asyncio>=0.24", "pyright==1.1.407"]
14
+ dev = ["pytest>=9", "pytest-asyncio>=1.4", "pyright==1.1.414"]
15
15
 
16
16
  [build-system]
17
17
  requires = ["hatchling>=1.26"]
@@ -26,7 +26,7 @@ asyncio_mode = "auto"
26
26
  asyncio_default_fixture_loop_scope = "function"
27
27
 
28
28
  [tool.pyright]
29
- include = ["tests/typecheck", "examples/executor_minimal.py"]
29
+ include = ["tests/typecheck", "examples/executor_minimal.py", "examples/session_context.py"]
30
30
  pythonVersion = "3.10"
31
31
  strict = ["tests/typecheck"]
32
32
  reportUnnecessaryTypeIgnoreComment = "error"
@@ -6,10 +6,22 @@ Protocol types are generated from the BMA contract into
6
6
  """
7
7
 
8
8
  from . import generated
9
- from ._rpc import ClientStoppedError, ExecutorError, NotConnectedError, RPCError
9
+ from ._rpc import (
10
+ METADATA_AGENT_SESSION_ID,
11
+ ClientStoppedError,
12
+ DaemonHTTPError,
13
+ ErrorReason,
14
+ ExecutorError,
15
+ MachineTokenRequiredError,
16
+ NotConnectedError,
17
+ RPCError,
18
+ SessionContextNotFoundError,
19
+ )
20
+ from .session_context import SessionContext
10
21
  from .agent import AgentEventRecord, AgentHandler, AgentPlatform, AgentSessionClosedError, AgentTurn
11
22
  from .client import (
12
23
  DEFAULT_BASE_URL,
24
+ MACHINE_ID_ENV,
13
25
  PROTOCOL_V1,
14
26
  PROTOCOL_V11,
15
27
  CredentialRejectedError,
@@ -60,11 +72,18 @@ from .transport import (
60
72
 
61
73
  __all__ = [
62
74
  "INLINE_RESULT_BYTES",
75
+ "METADATA_AGENT_SESSION_ID",
76
+ "DaemonHTTPError",
77
+ "ErrorReason",
78
+ "MachineTokenRequiredError",
79
+ "SessionContext",
80
+ "SessionContextNotFoundError",
63
81
  "Call",
64
82
  "Notification",
65
83
  "Request",
66
84
  "methods",
67
85
  "DEFAULT_BASE_URL",
86
+ "MACHINE_ID_ENV",
68
87
  "PROTOCOL_V1",
69
88
  "PROTOCOL_V11",
70
89
  "TERMINAL_CLOSE_CODES",
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import json
7
7
  from collections.abc import Awaitable, Callable
8
+ from enum import Enum
8
9
  from typing import Any
9
10
 
10
11
  from .generated import JsonRpcErrorCode
@@ -38,6 +39,14 @@ class RPCError(ExecutorError):
38
39
  self.message = message
39
40
  self.data = data
40
41
 
42
+ @classmethod
43
+ def with_reason(cls, code: int, reason: str, message: str) -> RPCError:
44
+ """An error refusing a request with a machine-readable ``data.reason``
45
+ (for example ``ErrorReason.SessionRejected``), which BMA passes to the
46
+ tool result's error_code and session.error.code unchanged. Go:
47
+ ``NewReasonError``."""
48
+ return cls(code, message, {"reason": reason.value if isinstance(reason, Enum) else reason})
49
+
41
50
  @property
42
51
  def retryable(self) -> bool | None:
43
52
  return None if self.data is None else self.data.get("retryable")
@@ -49,6 +58,61 @@ class RPCError(ExecutorError):
49
58
  return error
50
59
 
51
60
 
61
+ class ErrorReason(str, Enum):
62
+ """Recommended ``error.data.reason`` values (open set: any other value is
63
+ passed through as well). Go ``Reason*`` constants and TypeScript
64
+ ``ErrorReason`` carry the same names and values."""
65
+
66
+ WorkspaceUnavailable = "workspace_unavailable"
67
+ """The referenced workspace is gone or its directory does not exist."""
68
+ WorkspaceBoundary = "workspace_boundary"
69
+ """The request leaves what the executor's local policy allows."""
70
+ WorkspaceReadOnly = "workspace_read_only"
71
+ """The request writes where the local policy only allows reads."""
72
+ SessionRejected = "session_rejected"
73
+ """The session is not one this machine serves (an owner check failed)."""
74
+ LocalConfirmationDenied = "local_confirmation_denied"
75
+ """The local user denied the access."""
76
+ LocalConfirmationExpired = "local_confirmation_expired"
77
+ """Nobody answered the local confirmation in time."""
78
+ SpawnFailed = "spawn_failed"
79
+ """The process could not be started."""
80
+ ProcessIdSpecMismatch = "process_id_spec_mismatch"
81
+ """A process.start replay changed the spec of an existing process id."""
82
+
83
+
84
+ METADATA_AGENT_SESSION_ID = "agent_session_id"
85
+ """process.start metadata key naming the agent session a process runs for."""
86
+
87
+
88
+ class MachineTokenRequiredError(ExecutorError):
89
+ """session_context on a client that is not a machine-scoped executor:
90
+ environment_key must hold the machine daemon token and environment_id
91
+ must be empty."""
92
+
93
+ def __init__(self) -> None:
94
+ super().__init__("a machine-scoped executor (machine daemon token in environment_key, empty environment_id) is required")
95
+
96
+
97
+ class SessionContextNotFoundError(ExecutorError):
98
+ """The process is not on this machine (or ended over 15 minutes ago), or
99
+ the session is not bound to it."""
100
+
101
+ def __init__(self) -> None:
102
+ super().__init__("session context not found")
103
+
104
+
105
+ class DaemonHTTPError(ExecutorError):
106
+ """A non-2xx answer of a BMA daemon route; ``code`` and ``message`` are
107
+ BMA's error body when it sent one."""
108
+
109
+ def __init__(self, status: int, message: str, code: str = "") -> None:
110
+ super().__init__(f"daemon API returned {status}" + (f": {message}" if message else ""))
111
+ self.status = status
112
+ self.message = message
113
+ self.code = code
114
+
115
+
52
116
  def rpc_error(code: JsonRpcErrorCode, message: str, retryable: bool) -> RPCError:
53
117
  return RPCError(code, message, {"retryable": retryable})
54
118
 
@@ -8,15 +8,18 @@ lifecycle, tool cancellation, retried tool results, and the MCP channel.
8
8
  from __future__ import annotations
9
9
 
10
10
  import asyncio
11
+ import os
11
12
  import random as _random
12
13
  from collections.abc import Awaitable, Callable, Sequence
13
14
  from dataclasses import dataclass
14
15
  from typing import TYPE_CHECKING, Any, TypeVar
16
+ from urllib.parse import quote
15
17
 
16
18
  import httpx
17
19
 
18
20
  from ._methods import Call, Notification, Request
19
21
  from ._rpc import ClientStoppedError, ExecutorError, NotConnectedError, Peer, RPCError
22
+ from .session_context import SessionContext, SessionContexts
20
23
  from .generated import (
21
24
  METHOD_EXECUTOR_CAPABILITIES_UPDATE,
22
25
  METHOD_EXECUTOR_CLOSE,
@@ -63,6 +66,9 @@ if TYPE_CHECKING:
63
66
  from .generated import AgentCapability
64
67
 
65
68
  DEFAULT_BASE_URL = "https://api.bma.beeos.ai"
69
+ # The environment variable that carries the machine id of a machine-scoped executor
70
+ # (injected by the machine pool template).
71
+ MACHINE_ID_ENV = "BMA_MACHINE_ID"
66
72
  DEFAULT_REQUEST_TIMEOUT = 30.0
67
73
  # 0 reconnects until stop(), as gRPC connection backoff and long-running
68
74
  # agents (GitHub Actions runner, Buildkite agent) do.
@@ -126,6 +132,7 @@ class ExecutorClient:
126
132
  environment_id: str,
127
133
  executor: ExecutorInfo,
128
134
  capabilities: Capabilities | None = None,
135
+ machine_id: str = "",
129
136
  environment_key: str = "",
130
137
  base_url: str = DEFAULT_BASE_URL,
131
138
  ws_url: str = "",
@@ -145,17 +152,25 @@ class ExecutorClient:
145
152
  on_log: Callable[[LogEvent], None] | None = None,
146
153
  ) -> None:
147
154
  # environment_id may be empty: a machine-scoped executor registers
148
- # without one (executor.register in the v1.1 contract).
155
+ # without one (executor.register in the v1.1 contract). environment_id
156
+ # and machine_id are alternatives; machine_id defaults to BMA_MACHINE_ID
157
+ # when environment_id is empty. With neither, the legacy alias
158
+ # POST /api/v1/executors/token serves a machine daemon token.
159
+ if environment_id and machine_id:
160
+ raise ValueError("bma_executor_sdk: environment_id and machine_id are alternatives; set one")
161
+ if not environment_id and not machine_id:
162
+ machine_id = os.environ.get(MACHINE_ID_ENV, "").strip()
149
163
  if token_source is None and not environment_key.strip():
150
164
  raise ValueError("bma_executor_sdk: environment_key is required without token_source")
151
165
  if not executor.get("name"):
152
166
  raise ValueError("bma_executor_sdk: executor['name'] is required")
153
167
  self._environment_id = environment_id
168
+ self._machine_id = machine_id
154
169
  self._executor = executor
155
170
  self._capabilities: Capabilities = capabilities or {}
156
171
  self._environment_key = environment_key
157
172
  # The deployment origin (as BMA_BASE_URL in bma-sdk); a trailing
158
- # /api/v1 is dropped so the /v1/executors paths are not nested.
173
+ # /api/v1 is dropped so the /v1 paths are not nested.
159
174
  self._base_url = base_url.rstrip("/").removesuffix("/api/v1")
160
175
  self._ws_url = ws_url
161
176
  self._token_source = token_source
@@ -204,6 +219,10 @@ class ExecutorClient:
204
219
  # outboxes resend after a reconnect.
205
220
  self._registered = asyncio.Event()
206
221
  self._agent: _AgentRuntime | None = None
222
+ self._session_contexts = SessionContexts(
223
+ base_url=self._base_url, environment_id=environment_id, environment_key=environment_key,
224
+ http_client=http_client, timeout=request_timeout,
225
+ )
207
226
 
208
227
  # --- lifecycle ---
209
228
 
@@ -324,6 +343,22 @@ class ExecutorClient:
324
343
  def on_drain(self, handler: DrainHandler) -> None:
325
344
  self._drain_handler = handler
326
345
 
346
+ async def session_context(self, process_id: str) -> SessionContext:
347
+ """The context of the agent session ``process_id`` runs for
348
+ (process.start metadata agent_session_id): its environment and the
349
+ metadata its creator set. Read it in a process.start handler to
350
+ resolve a metadata reference or check an owner before spawning, and
351
+ refuse with ``RPCError.with_reason(...)``. Needs a machine-scoped
352
+ executor (``MachineTokenRequiredError``); cached per session, failures
353
+ are not. Raises ``SessionContextNotFoundError`` for a process not on
354
+ this machine."""
355
+ return await self._session_contexts.by_process(process_id)
356
+
357
+ async def session_context_by_id(self, session_id: str) -> SessionContext:
358
+ """The context of an agent session bound to this machine (for an agent
359
+ capability without a process); cached like ``session_context``."""
360
+ return await self._session_contexts.by_id(session_id)
361
+
327
362
  def on_request(self, method: Request[P, R], handler: Callable[[P], Awaitable[R]]) -> None:
328
363
  """Serve a harness-to-executor request (process.*, terminal.*,
329
364
  skill.install, workspace.backup) with the contract's params and result
@@ -450,6 +485,14 @@ class ExecutorClient:
450
485
  if self._on_log is not None:
451
486
  self._on_log(LogEvent(level, message, error))
452
487
 
488
+ def _token_path(self) -> str:
489
+ """The token exchange of the executor's own resource (ADR-0023 1.3)."""
490
+ if self._environment_id:
491
+ return f"/v1/environments/{quote(self._environment_id, safe='')}/token"
492
+ if self._machine_id:
493
+ return f"/v1/machines/{quote(self._machine_id, safe='')}/token"
494
+ return "/api/v1/executors/token"
495
+
453
496
  async def _fetch_token(self) -> ExecutorTokenResponse:
454
497
  if self._token_source is not None:
455
498
  token = await self._token_source()
@@ -459,9 +502,7 @@ class ExecutorClient:
459
502
  client = self._http_client or httpx.AsyncClient()
460
503
  try:
461
504
  response = await client.post(
462
- # A machine daemon token (no environment id) is exchanged by
463
- # bma-api, an environment key by managed-agents.
464
- f"{self._base_url}{'/v1' if self._environment_id else '/api/v1'}/executors/token",
505
+ f"{self._base_url}{self._token_path()}",
465
506
  json={"environment_id": self._environment_id, "executor": self._executor},
466
507
  headers={"Authorization": f"Bearer {self._environment_key}"},
467
508
  timeout=self._request_timeout,
@@ -915,6 +956,7 @@ def _canceled_tool_result(params: ToolCallParams, reason: str) -> ToolResultPara
915
956
 
916
957
  __all__ = [
917
958
  "DEFAULT_BASE_URL",
959
+ "MACHINE_ID_ENV",
918
960
  "PROTOCOL_V1",
919
961
  "PROTOCOL_V11",
920
962
  "ExecutorClient",
@@ -1,4 +1,4 @@
1
- # Code generated by tools/contract/gen-python.mjs from contracts/bma (executor protocol 1.1.0). DO NOT EDIT.
1
+ # Code generated by tools/contract/gen-python.mjs from contracts/bma (executor protocol 1.2.0). DO NOT EDIT.
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -24,6 +24,7 @@ class AgentCapability(TypedDict):
24
24
  file_inputs: NotRequired[bool]
25
25
  max_sessions: NotRequired[int]
26
26
  turn_resume: NotRequired[bool]
27
+ platform_credentials: NotRequired[list[Literal["brain_tools", "harness_model"]]]
27
28
  harness: NotRequired[AgentHarnessCapability]
28
29
 
29
30
  class AgentErrorInfo(TypedDict):
@@ -127,12 +128,12 @@ class AgentTurnConfig(TypedDict):
127
128
  system: NotRequired[str]
128
129
 
129
130
  class ArtifactCapability(TypedDict):
130
- """v1.1 artifact upload (POST /v1/executors/artifacts). Environment-scoped executors only."""
131
+ """v1.1 artifact upload (POST /v1/environments/{environment_id}/artifacts; legacy alias POST /v1/executors/artifacts). Environment-scoped executors only."""
131
132
  upload: bool
132
133
  max_bytes: NotRequired[int]
133
134
 
134
135
  class ArtifactRef(TypedDict):
135
- """Artifact reference returned by POST /v1/executors/artifacts and listed in tool.result artifacts (v1.1 §6.5)."""
136
+ """Artifact reference returned by POST /v1/environments/{environment_id}/artifacts (legacy alias POST /v1/executors/artifacts) and listed in tool.result artifacts (v1.1 §6.5)."""
136
137
  artifact_id: str
137
138
  name: NotRequired[str]
138
139
  mime_type: str
@@ -161,6 +162,8 @@ class Capabilities(TypedDict):
161
162
  skills: NotRequired[SkillsCapability]
162
163
  workspace: NotRequired[WorkspaceCapability]
163
164
  agent: NotRequired[AgentCapability]
165
+ session_files: NotRequired[SessionFilesCapability]
166
+ fs: NotRequired[FsCapability]
164
167
 
165
168
  class ChannelScope(str, Enum):
166
169
  """Channels a short-lived executor JWT may open."""
@@ -281,12 +284,12 @@ class ExecutorTokenRefreshResult(TypedDict):
281
284
  expires_at: str
282
285
 
283
286
  class ExecutorTokenRequest(TypedDict):
284
- """POST /v1/executors/token body. The bearer is an environment key, or a machine daemon token. An empty environment_id with a machine token requests a machine-scoped executor: its executor_id is exec_<machine_id>, stable across refreshes, and the JWT carries machine_id and daemon_token_id."""
287
+ """Token request body for POST /v1/machines/{machine_id}/token (bearer: machine daemon token) and POST /v1/environments/{environment_id}/token (bearer: environment key); the legacy alias POST /v1/executors/token takes either bearer. The id in the path must equal the credential's machine or environment, otherwise 404; on the new paths environment_id may be empty or absent for a machine and, when sent for an environment, must equal the path id. An empty environment_id with a machine token requests a machine-scoped executor: its executor_id is exec_<machine_id>, stable across refreshes, and the JWT carries machine_id and daemon_token_id."""
285
288
  environment_id: str
286
289
  executor: ExecutorInfo
287
290
 
288
291
  class ExecutorTokenResponse(TypedDict):
289
- """POST /v1/executors/token response."""
292
+ """Token response of POST /v1/machines/{machine_id}/token, POST /v1/environments/{environment_id}/token and the legacy alias POST /v1/executors/token."""
290
293
  executor_id: str
291
294
  token: str
292
295
  expires_in: int
@@ -316,6 +319,32 @@ class FilesCapability(TypedDict):
316
319
  read_roots: NotRequired[list[str]]
317
320
  write_roots: NotRequired[list[str]]
318
321
 
322
+ class FsCapability(TypedDict):
323
+ """Session file views mounted by the executor as FUSE file systems backed by bma-file (docs/adr/0021). Declared only after the executor probed that it can mount. Absent or fuse=false: the session files stay on the copy-and-scan protocol (session_files). views lists the views the executor can mount; the harness only mounts those. Machine-scoped executors only."""
324
+ fuse: bool
325
+ views: NotRequired[list[str]]
326
+
327
+ class FsMount(TypedDict):
328
+ """One view to mount. path is the absolute mount point on the executor host (derived from session_files by the harness). readonly is also fixed inside token; the executor mounts read-only when it is true. token is a capability token for this session and machine: keep it in memory only, never write it to disk, argv, environment or logs."""
329
+ view: str
330
+ path: str
331
+ readonly: bool
332
+ token: str
333
+ options: NotRequired[dict[str, str]]
334
+
335
+ class FsMountResult(TypedDict):
336
+ """fs.mount result. state is "mounted" once every listed view is mounted and serving, or "failed" with error_code and error (nothing stays half-mounted)."""
337
+ state: Literal["mounted", "failed"]
338
+ error_code: NotRequired[str]
339
+ error: NotRequired[str]
340
+
341
+ class FsUnmountResult(TypedDict):
342
+ """fs.unmount result. pending_bytes is data not yet committed to bma-file when flush was requested (always 0 for read-only views)."""
343
+ state: Literal["unmounted", "failed"]
344
+ pending_bytes: int
345
+ error_code: NotRequired[str]
346
+ error: NotRequired[str]
347
+
319
348
  class GlobInput(TypedDict):
320
349
  """glob input: list paths matching pattern."""
321
350
  pattern: str
@@ -703,6 +732,10 @@ class SessionEventType(str, Enum):
703
732
  SessionStatusIdle = "session.status_idle"
704
733
  SessionError = "session.error"
705
734
 
735
+ class SessionFilesCapability(TypedDict):
736
+ """Executor-owned per-session file layout. The harness derives <root>/<agent_session_id>/uploads (read-only session inputs) and <root>/<agent_session_id>/outputs (deliverables) from it, with agent_session_id as sent in process.start metadata, and uses these real paths in prompts, tool descriptions, write rules and the session files manifest. Absent: the harness keeps /mnt/session/uploads and /mnt/session/outputs. Fixed at executor.register: executor.capabilities.update does not change it. Machine-scoped executors only."""
737
+ root: str
738
+
706
739
  class SessionMemoryResource(TypedDict):
707
740
  """A memory store mounted into the session workspace."""
708
741
  type: Literal["memory_store"]
@@ -1087,6 +1120,17 @@ class WorkspaceBackupParams(TypedDict):
1087
1120
  exclude: NotRequired[list[str]]
1088
1121
  skip_if_fingerprint: NotRequired[str]
1089
1122
 
1123
+ class FsMountParams(TypedDict):
1124
+ "Params object of fs.mount."
1125
+ session_id: str
1126
+ service_url: str
1127
+ mounts: list[FsMount]
1128
+
1129
+ class FsUnmountParams(TypedDict):
1130
+ "Params object of fs.unmount."
1131
+ session_id: str
1132
+ flush: NotRequired[bool]
1133
+
1090
1134
  class TurnStartParams(TypedDict):
1091
1135
  "Params object of turn.start."
1092
1136
  session_id: str
@@ -1197,6 +1241,8 @@ METHOD_TERMINAL_ATTACH = "terminal.attach"
1197
1241
  METHOD_TERMINAL_CLOSE = "terminal.close"
1198
1242
  METHOD_SKILL_INSTALL = "skill.install"
1199
1243
  METHOD_WORKSPACE_BACKUP = "workspace.backup"
1244
+ METHOD_FS_MOUNT = "fs.mount"
1245
+ METHOD_FS_UNMOUNT = "fs.unmount"
1200
1246
  METHOD_TURN_START = "turn.start"
1201
1247
  METHOD_TURN_INPUT = "turn.input"
1202
1248
  METHOD_TURN_CANCEL = "turn.cancel"
@@ -1235,6 +1281,8 @@ METHODS: dict[str, MethodSpec] = {
1235
1281
  "terminal.close": MethodSpec(name="terminal.close", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="TerminalCloseParams", result_type="TerminalCloseResult", capability="terminal.enabled", idempotent_by="terminal_id"),
1236
1282
  "skill.install": MethodSpec(name="skill.install", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="SkillInstallParams", result_type="SkillInstallResult", capability="skills.install", idempotent_by="skill_id+revision_id+digest"),
1237
1283
  "workspace.backup": MethodSpec(name="workspace.backup", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="WorkspaceBackupParams", result_type="WorkspaceBackupResult", capability="workspace.backup", idempotent_by="backup_id"),
1284
+ "fs.mount": MethodSpec(name="fs.mount", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="FsMountParams", result_type="FsMountResult", capability="fs.fuse", idempotent_by="session_id+view"),
1285
+ "fs.unmount": MethodSpec(name="fs.unmount", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="FsUnmountParams", result_type="FsUnmountResult", capability="fs.fuse", idempotent_by="session_id"),
1238
1286
  "turn.start": MethodSpec(name="turn.start", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="TurnStartParams", result_type="TurnStartResult", capability="agent", idempotent_by="turn_id"),
1239
1287
  "turn.input": MethodSpec(name="turn.input", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="TurnInputParams", result_type="Ack", capability="agent", idempotent_by="input_id"),
1240
1288
  "turn.cancel": MethodSpec(name="turn.cancel", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="TurnCancelParams", result_type="TurnCancelResult", capability="agent", idempotent_by=None),
@@ -8,6 +8,10 @@ from ._methods import Call, Notification, Request
8
8
  from .generated import (
9
9
  Ack,
10
10
  ExecutorCapabilitiesUpdateParams,
11
+ FsMountParams,
12
+ FsMountResult,
13
+ FsUnmountParams,
14
+ FsUnmountResult,
11
15
  InteractionCancelParams,
12
16
  InteractionRequestParams,
13
17
  InteractionRequestResult,
@@ -53,6 +57,8 @@ __all__ = [
53
57
  "TERMINAL_CLOSE",
54
58
  "SKILL_INSTALL",
55
59
  "WORKSPACE_BACKUP",
60
+ "FS_MOUNT",
61
+ "FS_UNMOUNT",
56
62
  "SESSION_READY",
57
63
  "SESSION_EVENT",
58
64
  "SESSION_ENDED",
@@ -78,6 +84,8 @@ TERMINAL_ATTACH: Request[TerminalAttachParams, TerminalAttachResult] = Request("
78
84
  TERMINAL_CLOSE: Request[TerminalCloseParams, TerminalCloseResult] = Request("terminal.close")
79
85
  SKILL_INSTALL: Request[SkillInstallParams, SkillInstallResult] = Request("skill.install")
80
86
  WORKSPACE_BACKUP: Request[WorkspaceBackupParams, WorkspaceBackupResult] = Request("workspace.backup")
87
+ FS_MOUNT: Request[FsMountParams, FsMountResult] = Request("fs.mount")
88
+ FS_UNMOUNT: Request[FsUnmountParams, FsUnmountResult] = Request("fs.unmount")
81
89
 
82
90
  # Executor-to-harness requests a client sends with call.
83
91
  SESSION_READY: Call[SessionReadyParams, Ack] = Call("session.ready")
@@ -0,0 +1,111 @@
1
+ """Session context reads over the machine token (Go: ``Client.SessionContext``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import OrderedDict
7
+ from typing import Any, TypedDict
8
+ from urllib.parse import quote
9
+
10
+ import httpx
11
+
12
+ from ._rpc import DaemonHTTPError, MachineTokenRequiredError, SessionContextNotFoundError
13
+
14
+
15
+ class SessionContext(TypedDict):
16
+ """What BMA tells this machine about an agent session it serves
17
+ (GET /api/v1/daemon/processes/{process_id}/session and
18
+ GET /api/v1/daemon/sessions/{session_id}): the session's environment and
19
+ the metadata its creator set, never agent configuration or credentials."""
20
+
21
+ id: str
22
+ environment_id: str
23
+ metadata: dict[str, str]
24
+ created_at: str
25
+ """RFC 3339 date-time."""
26
+
27
+
28
+ _MAX_CACHED = 1024
29
+ _UNSAFE = re.compile(r"[/\\\x00]")
30
+
31
+
32
+ def _segment(kind: str, value: str) -> str:
33
+ if not value or len(value) > 256 or value in (".", "..") or _UNSAFE.search(value):
34
+ raise ValueError(f"bma_executor_sdk: invalid {kind} {value!r}")
35
+ return quote(value, safe="")
36
+
37
+
38
+ def _clone(context: SessionContext) -> SessionContext:
39
+ return {**context, "metadata": dict(context.get("metadata") or {})}
40
+
41
+
42
+ class SessionContexts:
43
+ """Cached per session (metadata is read once); failures are not cached."""
44
+
45
+ def __init__(self, *, base_url: str, environment_id: str, environment_key: str,
46
+ http_client: httpx.AsyncClient | None, timeout: float) -> None:
47
+ self._base_url = base_url
48
+ self._environment_id = environment_id
49
+ self._environment_key = environment_key
50
+ self._http_client = http_client
51
+ self._timeout = timeout
52
+ self._sessions: OrderedDict[str, SessionContext] = OrderedDict()
53
+ self._processes: OrderedDict[str, str] = OrderedDict()
54
+
55
+ async def by_process(self, process_id: str) -> SessionContext:
56
+ known = self._processes.get(process_id)
57
+ if known is not None:
58
+ return await self.by_id(known)
59
+ context = await self._fetch(f"/processes/{_segment('process id', process_id)}/session")
60
+ _put(self._processes, process_id, context["id"])
61
+ return self._remember(context)
62
+
63
+ async def by_id(self, session_id: str) -> SessionContext:
64
+ cached = self._sessions.get(session_id)
65
+ if cached is not None:
66
+ return _clone(cached)
67
+ return self._remember(await self._fetch(f"/sessions/{_segment('session id', session_id)}"))
68
+
69
+ def _remember(self, context: SessionContext) -> SessionContext:
70
+ cached = self._sessions.get(context["id"])
71
+ if cached is not None:
72
+ return _clone(cached)
73
+ _put(self._sessions, context["id"], context)
74
+ return _clone(context)
75
+
76
+ async def _fetch(self, path: str) -> SessionContext:
77
+ if self._environment_id or not self._environment_key.strip():
78
+ raise MachineTokenRequiredError()
79
+ client = self._http_client or httpx.AsyncClient()
80
+ try:
81
+ # follow_redirects stays off: a redirect would forward the machine token.
82
+ response = await client.get(
83
+ f"{self._base_url}/api/v1/daemon{path}",
84
+ headers={"Authorization": f"Bearer {self._environment_key}", "Accept": "application/json"},
85
+ timeout=self._timeout, follow_redirects=False,
86
+ )
87
+ finally:
88
+ if self._http_client is None:
89
+ await client.aclose()
90
+ if response.status_code == 404:
91
+ raise SessionContextNotFoundError()
92
+ if not 200 <= response.status_code < 300:
93
+ raw = response.text[: 64 * 1024]
94
+ try:
95
+ body = response.json()
96
+ except ValueError:
97
+ body = None
98
+ if isinstance(body, dict) and body.get("message"):
99
+ raise DaemonHTTPError(response.status_code, str(body["message"]), str(body.get("code") or ""))
100
+ raise DaemonHTTPError(response.status_code, raw.strip())
101
+ context = response.json()
102
+ if not isinstance(context, dict) or not context.get("id"):
103
+ raise ValueError("bma_executor_sdk: session context response has no id")
104
+ context.setdefault("metadata", {})
105
+ return context # type: ignore[return-value]
106
+
107
+
108
+ def _put(cache: OrderedDict[str, Any], key: str, value: Any) -> None:
109
+ if key not in cache and len(cache) >= _MAX_CACHED:
110
+ cache.popitem(last=False)
111
+ cache[key] = value
@@ -0,0 +1,60 @@
1
+ """base_url is the deployment origin: a trailing /api/v1 is dropped."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ import bma_executor_sdk as bx
8
+
9
+
10
+ @pytest.mark.parametrize("base_url", ["https://bma.test", "https://bma.test/", "https://bma.test/api/v1", "https://bma.test/api/v1/"])
11
+ def test_base_url_is_the_origin(base_url: str) -> None:
12
+ assert bx.DEFAULT_BASE_URL == "https://api.bma.beeos.ai"
13
+ client = bx.ExecutorClient(
14
+ environment_id="env", environment_key="k", base_url=base_url,
15
+ executor={"name": "t", "os": "linux", "arch": "arm64", "version": "0"},
16
+ )
17
+ assert client._base_url == "https://bma.test" # pyright: ignore[reportPrivateUsage]
18
+
19
+
20
+ _EXECUTOR = {"name": "t", "os": "linux", "arch": "arm64", "version": "0"}
21
+
22
+
23
+ async def _token_path(monkeypatch: pytest.MonkeyPatch, *, environment_id: str, machine_id: str = "", env: str = "") -> str:
24
+ import httpx
25
+
26
+ monkeypatch.setenv(bx.MACHINE_ID_ENV, env)
27
+ seen: list[str] = []
28
+
29
+ def handler(request: httpx.Request) -> httpx.Response:
30
+ seen.append(request.url.raw_path.decode().split("?")[0])
31
+ return httpx.Response(200, json={"executor_id": "exec_t", "token": "jwt", "expires_in": 300, "ws_url": "ws://x"})
32
+
33
+ client = bx.ExecutorClient(
34
+ environment_id=environment_id, machine_id=machine_id, environment_key="k", base_url="https://bma.test",
35
+ executor=_EXECUTOR, # type: ignore[arg-type]
36
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
37
+ )
38
+ await client._fetch_token() # pyright: ignore[reportPrivateUsage]
39
+ assert len(seen) == 1
40
+ return seen[0]
41
+
42
+
43
+ async def test_token_exchange_path_follows_the_resource(monkeypatch: pytest.MonkeyPatch) -> None:
44
+ assert await _token_path(monkeypatch, environment_id="env") == "/v1/environments/env/token"
45
+ assert await _token_path(monkeypatch, environment_id="", machine_id="mach_1") == "/v1/machines/mach_1/token"
46
+ assert await _token_path(monkeypatch, environment_id="", machine_id="a/b") == "/v1/machines/a%2Fb/token"
47
+ # No id: the legacy alias keeps serving a machine daemon token.
48
+ assert await _token_path(monkeypatch, environment_id="") == "/api/v1/executors/token"
49
+
50
+
51
+ async def test_machine_id_comes_from_bma_machine_id(monkeypatch: pytest.MonkeyPatch) -> None:
52
+ assert bx.MACHINE_ID_ENV == "BMA_MACHINE_ID"
53
+ assert await _token_path(monkeypatch, environment_id="", env="mach_env") == "/v1/machines/mach_env/token"
54
+ # An explicit environment_id wins over the ambient variable.
55
+ assert await _token_path(monkeypatch, environment_id="env", env="mach_env") == "/v1/environments/env/token"
56
+
57
+
58
+ def test_environment_id_and_machine_id_are_alternatives() -> None:
59
+ with pytest.raises(ValueError, match="environment_id and machine_id"):
60
+ bx.ExecutorClient(environment_id="env", machine_id="mach_1", environment_key="k", executor=_EXECUTOR) # type: ignore[arg-type]
@@ -0,0 +1,50 @@
1
+ """examples/session_context.py admit(): which process.start reaches the session
2
+ path. Mirrors examples/sandboxed-folder (Go) TestAdmit*."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import importlib.util
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import pytest
11
+
12
+ from bma_executor_sdk import ErrorReason, RPCError
13
+
14
+ _PATH = Path(__file__).resolve().parent.parent / "examples" / "session_context.py"
15
+ _SPEC = importlib.util.spec_from_file_location("session_context_example", _PATH)
16
+ assert _SPEC and _SPEC.loader
17
+ example = importlib.util.module_from_spec(_SPEC)
18
+ _SPEC.loader.exec_module(example)
19
+
20
+
21
+ def reason(error: pytest.ExceptionInfo[RPCError]) -> str | None:
22
+ return (error.value.data or {}).get("reason")
23
+
24
+
25
+ def test_a_process_without_a_session_is_refused() -> None:
26
+ for params in ({}, {"metadata": {}}, {"metadata": {"initiator": "other"}}, {"metadata": {"initiator": "platform"}}):
27
+ with pytest.raises(RPCError) as raised:
28
+ example.admit(params)
29
+ assert reason(raised) == ErrorReason.SessionRejected
30
+ assert example.admit({"metadata": {"agent_session_id": "sesn_1"}}) is False
31
+
32
+
33
+ def test_platform_processes_are_hosted_only_with_a_platform_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
34
+ monkeypatch.setattr(example, "PLATFORM_DIR", str(tmp_path))
35
+ params: dict[str, Any] = {"metadata": {"initiator": "platform"}}
36
+ assert example.admit(params) is True
37
+ assert example.platform_cwd({"cwd": None}) == tmp_path.resolve()
38
+ for cwd in ("..", "/etc"):
39
+ with pytest.raises(RPCError) as raised:
40
+ example.platform_cwd({"cwd": cwd})
41
+ assert reason(raised) == ErrorReason.WorkspaceBoundary
42
+ with pytest.raises(RPCError) as raised:
43
+ example.admit({**params, "package_install": {"manager": "apt", "packages": ["jq"]}})
44
+ assert reason(raised) == ErrorReason.LocalConfirmationDenied
45
+
46
+
47
+ def test_package_installs_are_refused() -> None:
48
+ with pytest.raises(RPCError) as raised:
49
+ example.admit({"metadata": {"agent_session_id": "sesn_1"}, "package_install": {"manager": "apt", "packages": ["jq"]}})
50
+ assert reason(raised) == ErrorReason.LocalConfirmationDenied
@@ -0,0 +1,134 @@
1
+ """Session context over the machine token (GET /api/v1/daemon/processes/{id}/session
2
+ and /api/v1/daemon/sessions/{id}), cached per session; RPCError.with_reason and
3
+ ErrorReason match Go; mirrors typescript/test/session-context.test.ts."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from typing import Any
9
+ from urllib.parse import unquote
10
+
11
+ import httpx
12
+ import pytest
13
+
14
+ import bma_executor_sdk as bx
15
+ from bma_executor_sdk import methods
16
+ from bma_executor_sdk.generated import JsonRpcErrorCode, ProcessStartParams, ProcessState
17
+
18
+ EXECUTOR = {"name": "py-ctx", "os": "linux", "arch": "arm64", "version": "0.1.0"}
19
+ SESSION_A = {"id": "sesn_a", "environment_id": "mch_1", "metadata": {"owner": "u_1", "app_ref": "ws_7"},
20
+ "created_at": "2026-11-07T00:00:00Z"}
21
+
22
+
23
+ class FakeDaemon:
24
+ def __init__(self, processes: dict[str, str], sessions: dict[str, Any]) -> None:
25
+ self.processes, self.sessions, self.calls = processes, sessions, []
26
+
27
+ def handler(self, request: httpx.Request) -> httpx.Response:
28
+ self.calls.append(request.url.path)
29
+ if request.headers.get("authorization") != "Bearer mtok":
30
+ return httpx.Response(401)
31
+ session_id = None
32
+ if m := re.fullmatch(r"/api/v1/daemon/processes/([^/]+)/session", request.url.path):
33
+ session_id = self.processes.get(unquote(m.group(1)))
34
+ elif m := re.fullmatch(r"/api/v1/daemon/sessions/([^/]+)", request.url.path):
35
+ session_id = unquote(m.group(1))
36
+ session = self.sessions.get(session_id or "")
37
+ if session is None:
38
+ return httpx.Response(404, json={"code": "not_found", "message": "session not bound to this machine"})
39
+ return httpx.Response(200, json=session)
40
+
41
+
42
+ def client(daemon: FakeDaemon | None = None, handler: Any = None, **overrides: Any) -> bx.ExecutorClient:
43
+ transport = httpx.MockTransport(handler or daemon.handler) # type: ignore[union-attr]
44
+ options: dict[str, Any] = {"environment_id": "", "environment_key": "mtok", "base_url": "https://bma.test/api/v1",
45
+ "executor": EXECUTOR, "http_client": httpx.AsyncClient(transport=transport)}
46
+ options.update(overrides)
47
+ return bx.ExecutorClient(**options)
48
+
49
+
50
+ async def test_by_process_and_by_id_are_cached_per_session() -> None:
51
+ daemon = FakeDaemon({"proc_1": "sesn_a", "proc_2": "sesn_a"}, {"sesn_a": SESSION_A})
52
+ executor = client(daemon)
53
+ got = await executor.session_context("proc_1")
54
+ assert got == SESSION_A
55
+ await executor.session_context("proc_1")
56
+ await executor.session_context_by_id("sesn_a")
57
+ assert daemon.calls == ["/api/v1/daemon/processes/proc_1/session"]
58
+ await executor.session_context("proc_2")
59
+ assert len(daemon.calls) == 2
60
+ got["metadata"]["owner"] = "u_2"
61
+ assert (await executor.session_context_by_id("sesn_a"))["metadata"]["owner"] == "u_1"
62
+
63
+
64
+ async def test_not_found_is_not_cached() -> None:
65
+ daemon = FakeDaemon({}, {})
66
+ executor = client(daemon)
67
+ with pytest.raises(bx.SessionContextNotFoundError):
68
+ await executor.session_context("proc_other")
69
+ with pytest.raises(bx.SessionContextNotFoundError):
70
+ await executor.session_context_by_id("sesn_b")
71
+ daemon.sessions["sesn_b"] = {**SESSION_A, "id": "sesn_b"}
72
+ assert (await executor.session_context_by_id("sesn_b"))["id"] == "sesn_b"
73
+
74
+
75
+ async def test_needs_a_machine_token_and_reports_server_errors() -> None:
76
+ daemon = FakeDaemon({}, {})
77
+ with pytest.raises(bx.MachineTokenRequiredError):
78
+ await client(daemon, environment_id="env_1").session_context_by_id("sesn_a")
79
+ failing = client(handler=lambda _r: httpx.Response(502, text="upstream down"))
80
+ with pytest.raises(bx.DaemonHTTPError) as raised:
81
+ await failing.session_context_by_id("sesn_a")
82
+ assert raised.value.status == 502
83
+ with pytest.raises(ValueError, match="invalid session id"):
84
+ await client(daemon).session_context_by_id("../processes/x")
85
+ assert daemon.calls == []
86
+
87
+
88
+ def test_error_reason_and_with_reason_match_go() -> None:
89
+ assert {r.name: r.value for r in bx.ErrorReason} == {
90
+ "WorkspaceUnavailable": "workspace_unavailable",
91
+ "WorkspaceBoundary": "workspace_boundary",
92
+ "WorkspaceReadOnly": "workspace_read_only",
93
+ "SessionRejected": "session_rejected",
94
+ "LocalConfirmationDenied": "local_confirmation_denied",
95
+ "LocalConfirmationExpired": "local_confirmation_expired",
96
+ "SpawnFailed": "spawn_failed",
97
+ "ProcessIdSpecMismatch": "process_id_spec_mismatch",
98
+ }
99
+ error = bx.RPCError.with_reason(JsonRpcErrorCode.Forbidden, bx.ErrorReason.SessionRejected, "not this machine")
100
+ assert error.to_wire() == {"code": -32001, "message": "not this machine", "data": {"reason": "session_rejected"}}
101
+ assert type(error.to_wire()["data"]["reason"]) is str
102
+
103
+
104
+ async def test_process_start_handler_reads_context_and_refuses_with_reason() -> None:
105
+ daemon = FakeDaemon({"proc_mine": "sesn_a", "proc_theirs": "sesn_b"},
106
+ {"sesn_a": SESSION_A, "sesn_b": {**SESSION_A, "id": "sesn_b", "metadata": {"owner": "u_9"}}})
107
+ harness = bx.Harness(request_timeout=2.0)
108
+ root = "/Users/me/Library/Application Support/example/sessions"
109
+ executor = client(daemon, token_source=bx.static_token("inprocess://harness"), dialer=harness.inprocess_dialer(),
110
+ capabilities={"session_files": {"root": root}})
111
+
112
+ async def start(params: ProcessStartParams) -> ProcessState:
113
+ context = await executor.session_context(params["process_id"])
114
+ if context["metadata"].get("owner") != "u_1":
115
+ raise bx.RPCError.with_reason(JsonRpcErrorCode.Forbidden, bx.ErrorReason.SessionRejected, "not this machine")
116
+ assert params.get("metadata", {}).get(bx.METADATA_AGENT_SESSION_ID) == context["id"]
117
+ return {"accepted": True, "process_id": params["process_id"], "state": "running", # type: ignore[typeddict-item]
118
+ "cursors": {"stdout": 0, "stderr": 0}, "exit_code": None, "exit_signal": None}
119
+
120
+ executor.on_request(methods.PROCESS_START, start)
121
+ await executor.start()
122
+ try:
123
+ remote = await harness.wait_executor()
124
+ assert remote.capabilities["session_files"]["root"] == root
125
+ call = remote._call # pyright: ignore[reportPrivateUsage]
126
+ started = await call("process.start", {"session_id": "s1", "process_id": "proc_mine", "argv": ["true"],
127
+ "metadata": {"agent_session_id": "sesn_a"}})
128
+ assert started["process_id"] == "proc_mine"
129
+ with pytest.raises(bx.RPCError) as raised:
130
+ await call("process.start", {"session_id": "s1", "process_id": "proc_theirs", "argv": ["true"],
131
+ "metadata": {"agent_session_id": "sesn_b"}})
132
+ assert raised.value.code == JsonRpcErrorCode.Forbidden and (raised.value.data or {}).get("reason") == "session_rejected"
133
+ finally:
134
+ await executor.stop()
@@ -12,12 +12,12 @@ from bma_executor_sdk.generated import ToolResultParams
12
12
 
13
13
  def register(client: ExecutorClient) -> None:
14
14
  @client.tools.bash.handler
15
- async def bash(input: BashInput, ctx: ToolContext) -> BashResult: # pyright: ignore[reportUnusedFunction]
15
+ async def bash(input: BashInput, ctx: ToolContext) -> BashResult:
16
16
  assert_type(input["command"], str)
17
17
  return BashResult(stdout="", stderr="", exit_code=0)
18
18
 
19
19
  @client.tools.read.handler
20
- async def read(input: ReadInput, ctx: ToolContext) -> str: # pyright: ignore[reportUnusedFunction]
20
+ async def read(input: ReadInput, ctx: ToolContext) -> str:
21
21
  return input["path"]
22
22
 
23
23
  async def wrong(input: BashInput, ctx: ToolContext) -> str:
@@ -1,36 +0,0 @@
1
- """base_url is the deployment origin: a trailing /api/v1 is dropped."""
2
-
3
- from __future__ import annotations
4
-
5
- import pytest
6
-
7
- import bma_executor_sdk as bx
8
-
9
-
10
- @pytest.mark.parametrize("base_url", ["https://bma.test", "https://bma.test/", "https://bma.test/api/v1", "https://bma.test/api/v1/"])
11
- def test_base_url_is_the_origin(base_url: str) -> None:
12
- assert bx.DEFAULT_BASE_URL == "https://api.bma.beeos.ai"
13
- client = bx.ExecutorClient(
14
- environment_id="env", environment_key="k", base_url=base_url,
15
- executor={"name": "t", "os": "linux", "arch": "arm64", "version": "0"},
16
- )
17
- assert client._base_url == "https://bma.test" # pyright: ignore[reportPrivateUsage]
18
-
19
-
20
- @pytest.mark.parametrize(("environment_id", "path"), [("", "/api/v1/executors/token"), ("env", "/v1/executors/token")])
21
- async def test_token_exchange_path_follows_the_credential(environment_id: str, path: str) -> None:
22
- import httpx
23
-
24
- seen: list[str] = []
25
-
26
- def handler(request: httpx.Request) -> httpx.Response:
27
- seen.append(request.url.path)
28
- return httpx.Response(200, json={"executor_id": "exec_t", "token": "jwt", "expires_in": 300, "ws_url": "ws://x"})
29
-
30
- client = bx.ExecutorClient(
31
- environment_id=environment_id, environment_key="k", base_url="https://bma.test",
32
- executor={"name": "t", "os": "linux", "arch": "arm64", "version": "0"},
33
- http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
34
- )
35
- await client._fetch_token() # pyright: ignore[reportPrivateUsage]
36
- assert seen == [path]