bma-executor-sdk 1.2.0__tar.gz → 1.4.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 (38) hide show
  1. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/PKG-INFO +1 -1
  2. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/pyproject.toml +1 -1
  3. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/agent.py +37 -0
  4. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/generated.py +83 -6
  5. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/harness.py +9 -0
  6. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/methods.py +12 -0
  7. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_executor_runtime.py +32 -0
  8. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/.gitignore +0 -0
  9. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/README.md +0 -0
  10. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/examples/agent_minimal.py +0 -0
  11. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/examples/executor_minimal.py +0 -0
  12. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/examples/harness_loopback.py +0 -0
  13. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/examples/session_context.py +0 -0
  14. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/__init__.py +0 -0
  15. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/_methods.py +0 -0
  16. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/_npipe.py +0 -0
  17. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/_rpc.py +0 -0
  18. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/client.py +0 -0
  19. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/py.typed +0 -0
  20. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/session_context.py +0 -0
  21. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/tools.py +0 -0
  22. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/src/bma_executor_sdk/transport.py +0 -0
  23. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/executor_helpers.py +0 -0
  24. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_base_url.py +0 -0
  25. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_close_codes.py +0 -0
  26. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_example_session_context.py +0 -0
  27. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_executor_conformance.py +0 -0
  28. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_executor_contract.py +0 -0
  29. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_executor_interop.py +0 -0
  30. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_executor_token_refresh.py +0 -0
  31. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_npipe.py +0 -0
  32. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_reconnect.py +0 -0
  33. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_registration_refused.py +0 -0
  34. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_review.py +0 -0
  35. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_rpc_unretrieved_future.py +0 -0
  36. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_session_context.py +0 -0
  37. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/test_typed_tools.py +0 -0
  38. {bma_executor_sdk-1.2.0 → bma_executor_sdk-1.4.0}/tests/typecheck/typed_tools.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bma-executor-sdk
3
- Version: 1.2.0
3
+ Version: 1.4.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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "bma-executor-sdk"
3
- version = "1.2.0"
3
+ version = "1.4.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"
@@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Any, Protocol
21
21
 
22
22
  from ._rpc import ClientStoppedError, ExecutorError, NotConnectedError, RPCError, rpc_error
23
23
  from .generated import (
24
+ METHOD_AGENT_CUSTOM_TOOL_RESULT,
24
25
  METHOD_INTERACTION_CANCEL,
25
26
  METHOD_INTERACTION_REQUEST,
26
27
  METHOD_INTERACTION_RESPONSE,
@@ -32,6 +33,7 @@ from .generated import (
32
33
  METHOD_TURN_INPUT,
33
34
  METHOD_TURN_START,
34
35
  AgentCapability,
36
+ AgentCustomToolResultParams,
35
37
  AgentEventType,
36
38
  ConnectionState,
37
39
  InteractionCancelParams,
@@ -171,6 +173,26 @@ class AgentTurn:
171
173
  finally:
172
174
  s.pending.pop(interaction_id, None)
173
175
 
176
+ async def request_custom_tool(self, name: str, tool_input: dict[str, Any]) -> tuple[str, AgentCustomToolResultParams]:
177
+ """Emit agent.custom_tool_use for a tool the user's application runs
178
+ (capability custom_tools) and wait for agent.custom_tool_result.
179
+ Returns the call's event id (the tool_use_id) and the result. The turn
180
+ stays open while it waits. When the task is canceled the wait raises
181
+ CancelledError and a later result answers accepted=false; to give up
182
+ on a call the agent emits a failed agent.tool_result naming the id
183
+ (wrap the call in asyncio.timeout for an executor-side limit)."""
184
+ s = self._session
185
+ tool_use_id = self.new_event_id()
186
+ answer: asyncio.Future[AgentCustomToolResultParams] = asyncio.get_running_loop().create_future()
187
+ # Register before emitting: the platform may answer as soon as the event is acknowledged.
188
+ s.custom_tools[tool_use_id] = answer
189
+ try:
190
+ self.emit_with_id(tool_use_id, {"type": "agent.custom_tool_use", "name": name, "input": tool_input})
191
+ return tool_use_id, await asyncio.shield(answer)
192
+ finally:
193
+ s.custom_tools.pop(tool_use_id, None)
194
+ s.custom_done.add(tool_use_id)
195
+
174
196
  async def cancel_interaction(self, interaction_id: str, reason: str) -> None:
175
197
  """Withdraw an open interaction, for example after the user answered it
176
198
  locally (reason resolved_locally)."""
@@ -189,6 +211,7 @@ class _AgentRuntime:
189
211
  METHOD_TURN_CANCEL: self.turn_cancel,
190
212
  METHOD_SESSION_CLOSE: self.session_close,
191
213
  METHOD_INTERACTION_RESPONSE: self.interaction_response,
214
+ METHOD_AGENT_CUSTOM_TOOL_RESULT: self.custom_tool_result,
192
215
  }
193
216
 
194
217
  def session(self, session_id: str, create: bool) -> _AgentSession | None:
@@ -325,6 +348,18 @@ class _AgentRuntime:
325
348
  waiter.set_result(params)
326
349
  return {"accepted": True}
327
350
 
351
+ async def custom_tool_result(self, params: AgentCustomToolResultParams) -> dict[str, bool]:
352
+ s = self.session(params.get("session_id", ""), False)
353
+ if s is None:
354
+ return {"accepted": False}
355
+ tool_use_id = params.get("tool_use_id", "")
356
+ waiter = s.custom_tools.get(tool_use_id)
357
+ if waiter is None or tool_use_id in s.custom_done or waiter.done():
358
+ return {"accepted": False}
359
+ s.custom_done.add(tool_use_id)
360
+ waiter.set_result(params)
361
+ return {"accepted": True}
362
+
328
363
 
329
364
  def _cancel_turn(turn: AgentTurn) -> None:
330
365
  turn._canceled = True # noqa: SLF001
@@ -353,6 +388,8 @@ class _AgentSession:
353
388
  self.turn: AgentTurn | None = None
354
389
  self.results: dict[str, TurnStartResult] = {}
355
390
  self.pending: dict[str, asyncio.Future[InteractionResponseParams]] = {}
391
+ self.custom_tools: dict[str, asyncio.Future[AgentCustomToolResultParams]] = {}
392
+ self.custom_done: set[str] = set()
356
393
  self.answered: set[str] = set()
357
394
  self.sender: asyncio.Task[Any] | None = None
358
395
 
@@ -1,4 +1,4 @@
1
- # Code generated by tools/contract/gen-python.mjs from contracts/bma (executor protocol 1.2.0). DO NOT EDIT.
1
+ # Code generated by tools/contract/gen-python.mjs from contracts/bma (executor protocol 1.4.0). DO NOT EDIT.
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -16,7 +16,7 @@ class Ack(TypedDict):
16
16
  accepted: bool
17
17
 
18
18
  class AgentCapability(TypedDict):
19
- """agent capability. Present with enabled=true when the executor runs a complete agent and accepts turn.start, turn.input, turn.cancel, session.close and interaction.response."""
19
+ """agent capability. Present with enabled=true when the executor runs a complete agent and accepts turn.start, turn.input, turn.cancel, session.close and interaction.response (and agent.custom_tool_result when custom_tools is true)."""
20
20
  enabled: bool
21
21
  models: NotRequired[list[AgentModel]]
22
22
  permission_modes: NotRequired[list[str]]
@@ -25,7 +25,25 @@ class AgentCapability(TypedDict):
25
25
  max_sessions: NotRequired[int]
26
26
  turn_resume: NotRequired[bool]
27
27
  platform_credentials: NotRequired[list[Literal["brain_tools", "harness_model"]]]
28
+ custom_tools: NotRequired[bool]
28
29
  harness: NotRequired[AgentHarnessCapability]
30
+ harnesses: NotRequired[list[AgentHarnessCapability]]
31
+
32
+ class AgentCustomToolUseEvent(TypedDict):
33
+ """A custom tool the local agent is calling: a tool the user's application runs and answers (capability agent.custom_tools). Its event_id is the tool_use_id. The platform shows the session as waiting (session.status_idle with stop_reason requires_action naming the event) and delivers the user's result with agent.custom_tool_result. The turn stays open while the executor waits: the executor does not send session.status_idle for it. If its own timeout passes first, the executor ends the call with a failed agent.tool_result naming this event."""
34
+ type: Literal["agent.custom_tool_use"]
35
+ name: str
36
+ input: dict[str, Any]
37
+
38
+ class AgentErrorCode(str, Enum):
39
+ """Stop code table: the error types an agent executor reports for a turn that ended failed, so every agent (Go ACP harness, brain hosts, local desktop agents) says the same thing for the same cause. output_limit_reached: the model reply was cut at its output-token limit (ACP stopReason max_tokens, DSH max-tokens, finish_reason length). context_too_large: the conversation does not fit the model context window even after compaction. model_stream_idle: the model stream sent no data for the idle limit (default 90 s). agent_error: any other failure of the agent. agent_unavailable: the agent process is gone or did not answer a cancel in time. agent_auth_required: the agent needs credentials it does not have. agent_protocol_error: the agent rejected the request as malformed or unsupported. A code is the type of session.error; an executor whose SDK cannot set the type yet (structured_errors false) puts it first in the message as '<code>: <detail>', and the platform reads both forms. The platform keeps the code in error.code and projects a type outside the official session.error union to unknown_error; a platform may map a code to an official type itself (context_too_large to compaction_limit_reached_error, ADR-0010). Executors report only these values; a new cause adds a value here first."""
40
+ OutputLimitReached = "output_limit_reached"
41
+ ContextTooLarge = "context_too_large"
42
+ ModelStreamIdle = "model_stream_idle"
43
+ AgentError = "agent_error"
44
+ AgentUnavailable = "agent_unavailable"
45
+ AgentAuthRequired = "agent_auth_required"
46
+ AgentProtocolError = "agent_protocol_error"
29
47
 
30
48
  class AgentErrorInfo(TypedDict):
31
49
  """Typed session error."""
@@ -38,6 +56,7 @@ class AgentEventType(str, Enum):
38
56
  AgentThinking = "agent.thinking"
39
57
  AgentToolUse = "agent.tool_use"
40
58
  AgentToolResult = "agent.tool_result"
59
+ AgentCustomToolUse = "agent.custom_tool_use"
41
60
  AgentMcpToolUse = "agent.mcp_tool_use"
42
61
  AgentMcpToolResult = "agent.mcp_tool_result"
43
62
  SessionStatusRunning = "session.status_running"
@@ -125,7 +144,9 @@ class AgentTurnConfig(TypedDict):
125
144
  thinking_level: NotRequired[str]
126
145
  permission_mode: NotRequired[str]
127
146
  cwd: NotRequired[str]
147
+ environment_info: NotRequired[EnvironmentInfo]
128
148
  system: NotRequired[str]
149
+ harness: NotRequired[str]
129
150
 
130
151
  class ArtifactCapability(TypedDict):
131
152
  """v1.1 artifact upload (POST /v1/environments/{environment_id}/artifacts; legacy alias POST /v1/executors/artifacts). Environment-scoped executors only."""
@@ -164,6 +185,7 @@ class Capabilities(TypedDict):
164
185
  agent: NotRequired[AgentCapability]
165
186
  session_files: NotRequired[SessionFilesCapability]
166
187
  fs: NotRequired[FsCapability]
188
+ remote_brain: NotRequired[RemoteBrainCapability]
167
189
 
168
190
  class ChannelScope(str, Enum):
169
191
  """Channels a short-lived executor JWT may open."""
@@ -217,6 +239,10 @@ class Cursors(TypedDict):
217
239
  stdout: int
218
240
  stderr: int
219
241
 
242
+ class CustomToolResultResult(TypedDict):
243
+ """agent.custom_tool_result result. accepted=true: the executor took the result for the call it was waiting on. accepted=false: it no longer waits (unknown tool_use_id, already answered, timed out, or canceled with its turn); the platform marks its copy stale and does not send it again."""
244
+ accepted: bool
245
+
220
246
  class DisplayCapability(TypedDict):
221
247
  """v1.1 display object. v1 sent a boolean; the server accepts both."""
222
248
  rfb: NotRequired[bool]
@@ -228,6 +254,14 @@ class EditInput(TypedDict):
228
254
  old_string: str
229
255
  new_string: str
230
256
 
257
+ class EnvironmentInfo(TypedDict):
258
+ """Contract 1.4.0. The hands machine as the platform knows it (AgentTurnConfig.environment_info), from the hands executor's registration and the session's file mounts. Every member is optional; an omitted member is unknown, not empty. Values describe the machine at the time of turn.start."""
259
+ os: NotRequired[str]
260
+ arch: NotRequired[str]
261
+ shell: NotRequired[str]
262
+ cwd: NotRequired[str]
263
+ session_files_root: NotRequired[str]
264
+
231
265
  class EvaluatedPermission(TypedDict):
232
266
  """Permission decision the executor applied to a tool use. ask means the executor opened an interaction.request for it."""
233
267
  type: Literal["allow", "ask", "deny"]
@@ -254,6 +288,7 @@ class ExecutorInfo(TypedDict):
254
288
  os: str
255
289
  arch: str
256
290
  version: str
291
+ labels: NotRequired[list[str]]
257
292
 
258
293
  class ExecutorLoad(TypedDict):
259
294
  """Advisory executor load reported with executor.heartbeat. The server does not act on it."""
@@ -323,9 +358,10 @@ class FsCapability(TypedDict):
323
358
  """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
359
  fuse: bool
325
360
  views: NotRequired[list[str]]
361
+ skills_per_session: NotRequired[bool]
326
362
 
327
363
  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."""
364
+ """One view to mount. path is the absolute mount point on the executor host (derived from session_files by the harness; the skills view is at <root>/<agent_session_id>/skills for an executor that declared fs.skills_per_session and a root, otherwise /mnt/skills). Mount points of different sessions never overlap, and the executor mounts exactly the path it is given. 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
365
  view: str
330
366
  path: str
331
367
  readonly: bool
@@ -393,7 +429,7 @@ class InteractionQuestionOption(TypedDict):
393
429
  label: str
394
430
 
395
431
  class InteractionRequestResult(TypedDict):
396
- """interaction.request result. Idempotent by interaction_id: a repeat returns the same platform interaction."""
432
+ """interaction.request result. Idempotent by interaction_id: a repeat returns the same platform interaction. platform_interaction_id equals interaction_id when that is an appr_ plus 24 lower-case hex id (adopted); otherwise it is the platform-assigned int_ id."""
397
433
  accepted: bool
398
434
  platform_interaction_id: str
399
435
 
@@ -598,6 +634,12 @@ class McpTransportType(str, Enum):
598
634
  Stdio = "stdio"
599
635
  Http = "http"
600
636
 
637
+ class ModelTokenRefreshResult(TypedDict):
638
+ """model_token.refresh result: the credential for the turn's next model calls, in the form of the turn.start metadata model_base_url and model_token."""
639
+ model_token: str
640
+ model_base_url: str
641
+ expires_at: str
642
+
601
643
  class PackageManager(str, Enum):
602
644
  """Package manager for process.start package_install."""
603
645
  Apt = "apt"
@@ -693,6 +735,10 @@ class ReadInput(TypedDict):
693
735
  offset: NotRequired[int]
694
736
  limit: NotRequired[int]
695
737
 
738
+ class RemoteBrainCapability(TypedDict):
739
+ """Contract 1.4.0. The machine's owner allows a brain that runs on another machine to use this machine as its hands (platform tools routed here for a session whose brain machine is a different one). Set only by the executor's local configuration (bmad configuration or SDK Options.RemoteBrain); the platform reads it back and cannot switch it on through any API. Absent or enabled=false: off, which is also what an executor that predates 1.4.0 means. It applies to a BYO (tenant-owned) machine; a platform pool machine does not need it. It does not restrict a platform-hosted brain driving this machine (project authorization is enough there), and a brain and hands on one machine never need it."""
740
+ enabled: bool
741
+
696
742
  class SessionAssignResult(TypedDict):
697
743
  """session.assign result."""
698
744
  accepted: bool
@@ -726,6 +772,7 @@ class SessionEventType(str, Enum):
726
772
  AgentMessage = "agent.message"
727
773
  AgentThinking = "agent.thinking"
728
774
  AgentToolUse = "agent.tool_use"
775
+ AgentCustomToolUse = "agent.custom_tool_use"
729
776
  AgentMcpToolUse = "agent.mcp_tool_use"
730
777
  AgentMcpToolResult = "agent.mcp_tool_result"
731
778
  SessionStatusRunning = "session.status_running"
@@ -733,7 +780,7 @@ class SessionEventType(str, Enum):
733
780
  SessionError = "session.error"
734
781
 
735
782
  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."""
783
+ """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. With the fs capability skills_per_session the same tree also holds <root>/<agent_session_id>/skills (the session's skills view, read-only). Fixed at executor.register: executor.capabilities.update does not change it. Machine-scoped executors only."""
737
784
  root: str
738
785
 
739
786
  class SessionMemoryResource(TypedDict):
@@ -876,6 +923,12 @@ class ToolPermission(TypedDict):
876
923
  """Tool permission resolved by the harness."""
877
924
  mode: PermissionMode
878
925
 
926
+ class ToolsTokenRefreshResult(TypedDict):
927
+ """Contract 1.4.0. tools_token.refresh result: the credential for the turn's next platform tool calls, in the form of the turn.start metadata tools_mcp_url, tools_mcp_token and tools_mcp_token_expires_at."""
928
+ tools_mcp_token: str
929
+ tools_mcp_url: str
930
+ expires_at: str
931
+
879
932
  class TurnCancelResult(TypedDict):
880
933
  """turn.cancel result. canceled=false when the turn is unknown or already ended; the turn still ends with its own session.status_idle event."""
881
934
  canceled: bool
@@ -913,7 +966,7 @@ class WriteInput(TypedDict):
913
966
  path: str
914
967
  content: str
915
968
 
916
- AgentEvent = AgentMessageEvent | AgentThinkingEvent | AgentToolUseEvent | AgentToolResultEvent | AgentMcpToolUseEvent | AgentMcpToolResultEvent | SessionStatusRunningEvent | SessionStatusIdleEvent | SessionErrorEvent
969
+ AgentEvent = AgentMessageEvent | AgentThinkingEvent | AgentToolUseEvent | AgentToolResultEvent | AgentCustomToolUseEvent | AgentMcpToolUseEvent | AgentMcpToolResultEvent | SessionStatusRunningEvent | SessionStatusIdleEvent | SessionErrorEvent
917
970
 
918
971
  JsonRpcId = str
919
972
 
@@ -974,6 +1027,7 @@ class SessionEventParams(TypedDict):
974
1027
  turn_id: NotRequired[str]
975
1028
  event_id: NotRequired[str]
976
1029
  sequence: NotRequired[int]
1030
+ idempotency_key: NotRequired[str]
977
1031
  event: SessionEvent
978
1032
 
979
1033
  class SessionStatusParams(TypedDict):
@@ -1192,12 +1246,29 @@ class InteractionResponseParams(TypedDict):
1192
1246
  answers: NotRequired[list[str]]
1193
1247
  responder: NotRequired[InteractionResponder]
1194
1248
 
1249
+ class AgentCustomToolResultParams(TypedDict):
1250
+ "Params object of agent.custom_tool_result."
1251
+ session_id: str
1252
+ tool_use_id: str
1253
+ content: list[ContentBlock]
1254
+ is_error: NotRequired[bool]
1255
+
1195
1256
  class InteractionCancelParams(TypedDict):
1196
1257
  "Params object of interaction.cancel."
1197
1258
  session_id: str
1198
1259
  interaction_id: str
1199
1260
  reason: InteractionCancelReason
1200
1261
 
1262
+ class ModelTokenRefreshParams(TypedDict):
1263
+ "Params object of model_token.refresh."
1264
+ session_id: str
1265
+ turn_id: str
1266
+
1267
+ class ToolsTokenRefreshParams(TypedDict):
1268
+ "Params object of tools_token.refresh."
1269
+ session_id: str
1270
+ turn_id: str
1271
+
1201
1272
 
1202
1273
  @dataclass(frozen=True, slots=True)
1203
1274
  class MethodSpec:
@@ -1250,7 +1321,10 @@ METHOD_SESSION_CLOSE = "session.close"
1250
1321
  METHOD_SESSION_EVENT_DELTA = "session.event_delta"
1251
1322
  METHOD_INTERACTION_REQUEST = "interaction.request"
1252
1323
  METHOD_INTERACTION_RESPONSE = "interaction.response"
1324
+ METHOD_AGENT_CUSTOM_TOOL_RESULT = "agent.custom_tool_result"
1253
1325
  METHOD_INTERACTION_CANCEL = "interaction.cancel"
1326
+ METHOD_MODEL_TOKEN_REFRESH = "model_token.refresh"
1327
+ METHOD_TOOLS_TOKEN_REFRESH = "tools_token.refresh"
1254
1328
 
1255
1329
  METHODS: dict[str, MethodSpec] = {
1256
1330
  "executor.register": MethodSpec(name="executor.register", direction="executor-to-harness", kind="request", since="bma.executor.v1", params_type="ExecutorRegisterParams", result_type="ExecutorRegisterResult", capability=None, idempotent_by=None),
@@ -1290,5 +1364,8 @@ METHODS: dict[str, MethodSpec] = {
1290
1364
  "session.event_delta": MethodSpec(name="session.event_delta", direction="executor-to-harness", kind="notification", since="bma.executor.v1.1", params_type="SessionEventDeltaParams", result_type=None, capability="agent", idempotent_by=None),
1291
1365
  "interaction.request": MethodSpec(name="interaction.request", direction="executor-to-harness", kind="request", since="bma.executor.v1.1", params_type="InteractionRequestParams", result_type="InteractionRequestResult", capability="agent", idempotent_by="interaction_id"),
1292
1366
  "interaction.response": MethodSpec(name="interaction.response", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="InteractionResponseParams", result_type="InteractionResponseResult", capability="agent", idempotent_by="interaction_id"),
1367
+ "agent.custom_tool_result": MethodSpec(name="agent.custom_tool_result", direction="harness-to-executor", kind="request", since="bma.executor.v1.1", params_type="AgentCustomToolResultParams", result_type="CustomToolResultResult", capability="agent", idempotent_by="tool_use_id"),
1293
1368
  "interaction.cancel": MethodSpec(name="interaction.cancel", direction="executor-to-harness", kind="request", since="bma.executor.v1.1", params_type="InteractionCancelParams", result_type="Ack", capability="agent", idempotent_by="interaction_id"),
1369
+ "model_token.refresh": MethodSpec(name="model_token.refresh", direction="executor-to-harness", kind="request", since="bma.executor.v1.1", params_type="ModelTokenRefreshParams", result_type="ModelTokenRefreshResult", capability="agent", idempotent_by=None),
1370
+ "tools_token.refresh": MethodSpec(name="tools_token.refresh", direction="executor-to-harness", kind="request", since="bma.executor.v1.1", params_type="ToolsTokenRefreshParams", result_type="ToolsTokenRefreshResult", capability="agent", idempotent_by=None),
1294
1371
  }
@@ -22,6 +22,7 @@ from urllib.parse import parse_qsl, urlsplit
22
22
  from ._rpc import ExecutorError, NotConnectedError, Peer, RPCError, rpc_error
23
23
  from .client import DEFAULT_REQUEST_TIMEOUT, PROTOCOL_V1, PROTOCOL_V11, LogEvent
24
24
  from .generated import (
25
+ METHOD_AGENT_CUSTOM_TOOL_RESULT,
25
26
  METHOD_EXECUTOR_CAPABILITIES_UPDATE,
26
27
  METHOD_EXECUTOR_CLOSE,
27
28
  METHOD_EXECUTOR_DRAIN,
@@ -44,7 +45,9 @@ from .generated import (
44
45
  METHOD_TURN_START,
45
46
  Ack,
46
47
  AgentCapability,
48
+ AgentCustomToolResultParams,
47
49
  BashInput,
50
+ CustomToolResultResult,
48
51
  EditInput,
49
52
  ExecutorDrainResult,
50
53
  ExecutorInfo,
@@ -463,6 +466,12 @@ class Executor:
463
466
  longer waits for it."""
464
467
  return await self._call(METHOD_INTERACTION_RESPONSE, params)
465
468
 
469
+ async def respond_custom_tool_result(self, params: AgentCustomToolResultParams) -> CustomToolResultResult:
470
+ """Deliver the user's result for an agent.custom_tool_use;
471
+ accepted=false means the executor no longer waits (mark the platform's
472
+ copy stale)."""
473
+ return await self._call(METHOD_AGENT_CUSTOM_TOOL_RESULT, params)
474
+
466
475
 
467
476
  class HarnessToolSlot(Generic[_I]):
468
477
  """``session.tools.<name>``: one built-in tool."""
@@ -7,6 +7,8 @@ from __future__ import annotations
7
7
  from ._methods import Call, Notification, Request
8
8
  from .generated import (
9
9
  Ack,
10
+ AgentCustomToolResultParams,
11
+ CustomToolResultResult,
10
12
  ExecutorCapabilitiesUpdateParams,
11
13
  FsMountParams,
12
14
  FsMountResult,
@@ -15,6 +17,8 @@ from .generated import (
15
17
  InteractionCancelParams,
16
18
  InteractionRequestParams,
17
19
  InteractionRequestResult,
20
+ ModelTokenRefreshParams,
21
+ ModelTokenRefreshResult,
18
22
  ProcessListParams,
19
23
  ProcessListResult,
20
24
  ProcessReadParams,
@@ -41,6 +45,8 @@ from .generated import (
41
45
  TerminalOpenResult,
42
46
  ToolProgressParams,
43
47
  ToolResultParams,
48
+ ToolsTokenRefreshParams,
49
+ ToolsTokenRefreshResult,
44
50
  WorkspaceBackupParams,
45
51
  WorkspaceBackupResult,
46
52
  )
@@ -59,12 +65,15 @@ __all__ = [
59
65
  "WORKSPACE_BACKUP",
60
66
  "FS_MOUNT",
61
67
  "FS_UNMOUNT",
68
+ "AGENT_CUSTOM_TOOL_RESULT",
62
69
  "SESSION_READY",
63
70
  "SESSION_EVENT",
64
71
  "SESSION_ENDED",
65
72
  "TOOL_RESULT",
66
73
  "INTERACTION_REQUEST",
67
74
  "INTERACTION_CANCEL",
75
+ "MODEL_TOKEN_REFRESH",
76
+ "TOOLS_TOKEN_REFRESH",
68
77
  "EXECUTOR_CAPABILITIES_UPDATE",
69
78
  "SESSION_STATUS",
70
79
  "TOOL_PROGRESS",
@@ -86,6 +95,7 @@ SKILL_INSTALL: Request[SkillInstallParams, SkillInstallResult] = Request("skill.
86
95
  WORKSPACE_BACKUP: Request[WorkspaceBackupParams, WorkspaceBackupResult] = Request("workspace.backup")
87
96
  FS_MOUNT: Request[FsMountParams, FsMountResult] = Request("fs.mount")
88
97
  FS_UNMOUNT: Request[FsUnmountParams, FsUnmountResult] = Request("fs.unmount")
98
+ AGENT_CUSTOM_TOOL_RESULT: Request[AgentCustomToolResultParams, CustomToolResultResult] = Request("agent.custom_tool_result")
89
99
 
90
100
  # Executor-to-harness requests a client sends with call.
91
101
  SESSION_READY: Call[SessionReadyParams, Ack] = Call("session.ready")
@@ -94,6 +104,8 @@ SESSION_ENDED: Call[SessionEndedParams, Ack] = Call("session.ended")
94
104
  TOOL_RESULT: Call[ToolResultParams, Ack] = Call("tool.result")
95
105
  INTERACTION_REQUEST: Call[InteractionRequestParams, InteractionRequestResult] = Call("interaction.request")
96
106
  INTERACTION_CANCEL: Call[InteractionCancelParams, Ack] = Call("interaction.cancel")
107
+ MODEL_TOKEN_REFRESH: Call[ModelTokenRefreshParams, ModelTokenRefreshResult] = Call("model_token.refresh")
108
+ TOOLS_TOKEN_REFRESH: Call[ToolsTokenRefreshParams, ToolsTokenRefreshResult] = Call("tools_token.refresh")
97
109
 
98
110
  # Executor-to-harness notifications a client sends with notify.
99
111
  EXECUTOR_CAPABILITIES_UPDATE: Notification[ExecutorCapabilitiesUpdateParams] = Notification("executor.capabilities.update")
@@ -284,6 +284,10 @@ class ScriptedAgent:
284
284
  await asyncio.sleep(60)
285
285
  if "fail" in text:
286
286
  raise RuntimeError("model unavailable")
287
+ if "custom" in text:
288
+ tool_use_id, result = await turn.request_custom_tool("lookup", {"q": "weather"})
289
+ turn.emit({"type": "agent.tool_result", "tool_use_id": tool_use_id, "content": result["content"], "is_error": result.get("is_error", False)})
290
+ return
287
291
  message_id = turn.new_event_id()
288
292
  await turn.delta(message_id, "agent.message", 0, "Working on: ")
289
293
  turn.emit_with_id(message_id, {"type": "agent.message", "content": [{"type": "text", "text": "Working on: " + text}]})
@@ -375,6 +379,34 @@ async def test_agent_turn_lifecycle(transport: str) -> None:
375
379
  assert (await executor.close_agent_session({"session_id": "ses_a"}))["closed"] is False # type: ignore[typeddict-item]
376
380
 
377
381
 
382
+ async def test_agent_custom_tool_result() -> None:
383
+ async with agent_pair() as (harness, executor, client, platform, agent):
384
+ unknown: dict[str, Any] = {"session_id": "ses_none", "tool_use_id": "evt_x", "content": [{"type": "text", "text": "x"}]}
385
+ assert (await executor.respond_custom_tool_result(unknown))["accepted"] is False # type: ignore[arg-type]
386
+
387
+ await executor.start_turn(turn_start("ses_t", "turn_t", "custom tool")) # type: ignore[arg-type]
388
+ await platform.wait_for(lambda: any(e.type == "agent.custom_tool_use" for e in platform.events))
389
+ await asyncio.sleep(0.05)
390
+ assert idle_of(platform, "turn_t") is None # the turn waits for the result
391
+ use = next(e for e in platform.events if e.type == "agent.custom_tool_use")
392
+ other = dict(unknown, session_id="ses_t", tool_use_id="evt_other")
393
+ assert (await executor.respond_custom_tool_result(other))["accepted"] is False # type: ignore[arg-type]
394
+ answer: dict[str, Any] = {"session_id": "ses_t", "tool_use_id": use.event_id, "content": [{"type": "text", "text": "sunny"}], "is_error": True}
395
+ assert (await executor.respond_custom_tool_result(answer))["accepted"] is True # type: ignore[arg-type]
396
+ assert (await executor.respond_custom_tool_result(answer))["accepted"] is False # type: ignore[arg-type]
397
+ await platform.wait_for(lambda: idle_of(platform, "turn_t"))
398
+ types = [e.type for e in platform.events if e.session_id == "ses_t"]
399
+ assert types == ["session.status_running", "agent.custom_tool_use", "agent.tool_result", "session.status_idle"]
400
+
401
+ # A result that arrives after the turn was canceled is stale.
402
+ await executor.start_turn(turn_start("ses_t", "turn_u", "custom tool")) # type: ignore[arg-type]
403
+ await platform.wait_for(lambda: sum(e.type == "agent.custom_tool_use" for e in platform.events) == 2)
404
+ second = [e for e in platform.events if e.type == "agent.custom_tool_use"][1]
405
+ assert (await executor.cancel_turn({"session_id": "ses_t", "turn_id": "turn_u"}))["canceled"] is True # type: ignore[typeddict-item]
406
+ await platform.wait_for(lambda: idle_of(platform, "turn_u"))
407
+ assert (await executor.respond_custom_tool_result(dict(answer, tool_use_id=second.event_id)))["accepted"] is False # type: ignore[arg-type]
408
+
409
+
378
410
  async def test_agent_events_resent_after_reconnect() -> None:
379
411
  async with agent_pair("ws") as (harness, executor, client, platform, agent):
380
412
  platform.fail_next_event = True # retryable internal error: the event stays queued