Message bus API¶
The bus delivers parent-to-child steering messages for background delegations. See Steering and Message bus.
TaskManager owns the lifecycle of every background delegation: its
asyncio.Task, its TaskHandle, its cancellation event, and the future a blocked
ask_parent waits on.
TaskManager¶
subagents_pydantic_ai.TaskManager
dataclass
¶
Manages background tasks and their lifecycle.
Tracks running tasks, handles cancellation, and provides status querying capabilities.
Attributes:
| Name | Type | Description |
|---|---|---|
tasks |
dict[str, Task[None]]
|
Live |
handles |
dict[str, TaskHandle]
|
|
message_bus |
InMemoryMessageBus
|
Message bus used to deliver steering and cancel messages. |
cancel_grace_seconds |
float
|
How long |
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
create_task(task_id, coro, handle)
¶
Create and track a new background task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Unique identifier for the task. |
required |
coro
|
Coroutine[Any, Any, None]
|
The coroutine to run. |
required |
handle
|
TaskHandle
|
TaskHandle for status tracking. |
required |
Returns:
| Type | Description |
|---|---|
Task[None]
|
The created asyncio.Task. |
Source code in src/subagents_pydantic_ai/message_bus.py
get_handle(task_id)
¶
Get the handle for a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
Returns:
| Type | Description |
|---|---|
TaskHandle | None
|
The TaskHandle if found, None otherwise. |
Source code in src/subagents_pydantic_ai/message_bus.py
get_cancel_event(task_id)
¶
Get the cancellation event for a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
Returns:
| Type | Description |
|---|---|
Event | None
|
The cancellation event if found, None otherwise. |
Source code in src/subagents_pydantic_ai/message_bus.py
set_answer_future(task_id, future)
¶
Set an answer future for a task waiting for parent response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
future
|
Future[str]
|
The future to resolve when the answer arrives. |
required |
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
get_answer_future(task_id)
¶
Get the pending answer future for a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
Returns:
| Type | Description |
|---|---|
Future[str] | None
|
The answer future if set, None otherwise. |
Source code in src/subagents_pydantic_ai/message_bus.py
clear_answer_future(task_id)
¶
Remove the answer future for a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
resolve_answer(task_id, answer)
¶
Deliver an answer to a task blocked in ask_parent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
answer
|
str
|
The answer to deliver. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether a waiting |
Source code in src/subagents_pydantic_ai/message_bus.py
soft_cancel(task_id)
async
¶
Request cooperative cancellation of a task.
Sets a cancellation event that the run loop checks between graph nodes,
so the subagent stops at a clean boundary with its partial progress
intact. A task blocked in ask_parent sits inside a tool call rather
than at a node boundary, so its pending question is resolved too --
otherwise the cancel would only take effect after the ask timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task to cancel. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if cancellation was requested, False if task not found. |
Source code in src/subagents_pydantic_ai/message_bus.py
hard_cancel(task_id)
async
¶
Immediately cancel a task.
Calls cancel() on the asyncio.Task. The task's own
except asyncio.CancelledError branch records the terminal status; the
handle is only marked here for a bare task registered without that
wrapper. TaskHandle.finish makes the first terminal transition win, so
a cancel arriving while the task is already completing cannot overwrite
the real outcome.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task to cancel. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if task was cancelled, False if task not found. |
Source code in src/subagents_pydantic_ai/message_bus.py
cancel_all(parent_run_id=None)
async
¶
Cancel every live task and wait, up to the grace period, for it to unwind.
Called when a parent run ends. A background delegation that outlives its
parent keeps working against deps the application has already torn down,
and one blocked in ask_parent waits for an answer that can never come.
The wait is bounded because the caller is a finally block. A
CancelledError can be caught, and a subagent's toolset is arbitrary
consumer code -- an HTTP client with its own shield, a slow cleanup, a
contextlib.suppress a little too wide. An unbounded wait on one of
those never returns, so the parent run's teardown never returns either,
and the application hangs with nothing logged. A leaked task that is
reported is recoverable; a finally that never finishes is not.
The guarantee is therefore: every matching task is cancelled, and its
cleanup is awaited for at most cancel_grace_seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent_run_id
|
str | None
|
Only cancel tasks started by this parent run. |
None
|
Source code in src/subagents_pydantic_ai/message_bus.py
cleanup_task(task_id)
¶
Clean up resources for a completed task.
The handle is kept so status and telemetry stay queryable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task to clean up. |
required |
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
list_active_tasks()
¶
Get list of active (non-completed) task IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of task IDs for tasks that haven't completed. |
Source code in src/subagents_pydantic_ai/message_bus.py
list_handles()
¶
Get all task handles (completed and active).
Returns:
| Type | Description |
|---|---|
list[TaskHandle]
|
List of TaskHandle objects. |
InMemoryMessageBus¶
subagents_pydantic_ai.InMemoryMessageBus
dataclass
¶
In-memory message bus using asyncio queues.
This is the default message bus implementation, suitable for single-process applications. For distributed systems, consider implementing a Redis-based bus using the MessageBusProtocol.
Example
bus = InMemoryMessageBus()
# Register agents
parent_queue = bus.register_agent("parent")
worker_queue = bus.register_agent("worker-1")
# Send a message
await bus.send(AgentMessage(
type=MessageType.TASK_ASSIGNED,
sender="parent",
receiver="worker-1",
payload={"task": "analyze data"},
task_id="task-123",
))
# Worker receives message
msg = await worker_queue.get()
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
send(message)
async
¶
Send a message to a specific agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
AgentMessage
|
The message to send. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the receiver is not registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
ask(sender, receiver, question, task_id, timeout=30.0)
async
¶
Send a question and wait for a response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sender
|
str
|
ID of the asking agent. |
required |
receiver
|
str
|
ID of the agent to ask. |
required |
question
|
Any
|
The question payload. |
required |
task_id
|
str
|
Task ID for correlation. |
required |
timeout
|
float
|
Maximum time to wait in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
AgentMessage
|
The response message. |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If no response within timeout. |
KeyError
|
If the receiver is not registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
answer(original, answer)
async
¶
Answer a previously received question.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original
|
AgentMessage
|
The original question message. |
required |
answer
|
Any
|
The answer payload. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the original sender is not registered or if there's no pending question with the correlation_id. |
Source code in src/subagents_pydantic_ai/message_bus.py
register_agent(agent_id)
¶
Register an agent to receive messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
Unique identifier for the agent. |
required |
Returns:
| Type | Description |
|---|---|
Queue[AgentMessage]
|
A queue where messages for this agent will be delivered. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If agent_id is already registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
unregister_agent(agent_id)
¶
Unregister an agent from the message bus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent to unregister. |
required |
add_handler(handler)
¶
Add a message handler for debugging/logging.
Handlers are called for every message sent through the bus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Callable[[AgentMessage], Awaitable[None]]
|
Async function that receives messages. |
required |
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
remove_handler(handler)
¶
Remove a previously added handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Callable[[AgentMessage], Awaitable[None]]
|
The handler to remove. |
required |
Source code in src/subagents_pydantic_ai/message_bus.py
is_registered(agent_id)
¶
Check if an agent is registered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent ID to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the agent is registered, False otherwise. |
Source code in src/subagents_pydantic_ai/message_bus.py
registered_agents()
¶
Get list of registered agent IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of registered agent IDs. |
get_messages(agent_id, timeout=0.0)
async
¶
Get pending messages for an agent.
Non-blocking retrieval of all pending messages in the agent's queue.
Optionally waits up to timeout seconds for at least one message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent to get messages for. |
required |
timeout
|
float
|
Maximum time to wait for a message (0 = no wait). |
0.0
|
Returns:
| Type | Description |
|---|---|
list[AgentMessage]
|
List of pending messages (may be empty). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the agent is not registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
create_message_bus¶
subagents_pydantic_ai.create_message_bus(backend='memory', **kwargs)
¶
Create a message bus instance.
Factory function for creating message bus implementations. Currently only supports in-memory backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str
|
The backend type ("memory" is currently supported). |
'memory'
|
**kwargs
|
Any
|
Backend-specific configuration. |
{}
|
Returns:
| Type | Description |
|---|---|
InMemoryMessageBus
|
A message bus instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the backend is not supported. |