python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl

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 (76) hide show
  1. pycodex/__init__.py +22 -12
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +37 -251
  4. pycodex/cli.py +19 -28
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +368 -51
  7. pycodex/events.py +14 -187
  8. pycodex/model.py +197 -95
  9. pycodex/multi_agents.py +401 -0
  10. pycodex/portable/__init__.py +8 -6
  11. pycodex/portable/client.py +24 -39
  12. pycodex/portable/protocol.py +28 -0
  13. pycodex/portable/server.py +3 -3
  14. pycodex/prompts/developer_messages.json +13 -0
  15. pycodex/prompts/goals/budget_limit.md +19 -0
  16. pycodex/prompts/goals/continuation.md +56 -0
  17. pycodex/prompts/models.json +1143 -200
  18. pycodex/protocol.py +81 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +102 -10
  21. pycodex/tools/agent_tool_schemas.py +0 -38
  22. pycodex/tools/apply_patch_tool.py +17 -34
  23. pycodex/tools/base_tool.py +63 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +58 -187
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +332 -0
  29. pycodex/tools/exec_tool.py +74 -31
  30. pycodex/tools/followup_task_tool.py +44 -0
  31. pycodex/tools/goal_manager.py +205 -0
  32. pycodex/tools/goal_tool.py +126 -0
  33. pycodex/tools/interrupt_agent_tool.py +48 -0
  34. pycodex/tools/list_agents_tool.py +66 -0
  35. pycodex/tools/python_tool_schema.py +141 -0
  36. pycodex/tools/request_permissions_tool.py +1 -0
  37. pycodex/tools/runtime_services.py +122 -450
  38. pycodex/tools/send_message_tool.py +42 -0
  39. pycodex/tools/spawn_agent_tool.py +55 -94
  40. pycodex/tools/unified_exec_manager.py +26 -35
  41. pycodex/tools/wait_agent_tool.py +46 -66
  42. pycodex/tools/wait_tool.py +24 -13
  43. pycodex/tools/web_search_tool.py +1 -0
  44. pycodex/utils/codex_config.py +105 -0
  45. pycodex/utils/compactor.py +4 -0
  46. pycodex/utils/compat.py +43 -2
  47. pycodex/utils/doctor.py +5 -4
  48. pycodex/utils/dotenv.py +0 -7
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +59 -0
  51. pycodex/utils/session_persist.py +104 -48
  52. python_codex-0.6.1.dist-info/METADATA +201 -0
  53. python_codex-0.6.1.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +10 -7
  56. responses_server/config.py +6 -12
  57. responses_server/gemini_api.py +333 -0
  58. responses_server/messages_api.py +9 -1
  59. responses_server/payload_processors.py +4 -4
  60. responses_server/request_translation.py +486 -0
  61. responses_server/server.py +31 -24
  62. responses_server/stream_events.py +124 -0
  63. responses_server/stream_router.py +48 -830
  64. responses_server/tools/custom_adapter.py +29 -29
  65. responses_server/tools/web_search.py +3 -0
  66. responses_server/transport.py +388 -0
  67. pycodex/tools/close_agent_tool.py +0 -60
  68. pycodex/tools/exec_runtime.js +0 -161
  69. pycodex/tools/request_user_input_tool.py +0 -102
  70. pycodex/tools/resume_agent_tool.py +0 -54
  71. pycodex/tools/send_input_tool.py +0 -110
  72. python_codex-0.5.2.dist-info/METADATA +0 -262
  73. python_codex-0.5.2.dist-info/RECORD +0 -90
  74. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
  75. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
  76. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
@@ -1,140 +1,19 @@
1
1
  import asyncio
2
- import json
3
- import random
4
2
  import typing
5
3
  from dataclasses import dataclass
6
- from typing import TYPE_CHECKING, Awaitable, Callable
7
-
8
- from ..events import (
9
- CompactCompletedEvent,
10
- CompactFailedEvent,
11
- CompactStartedEvent,
12
- Event,
13
- RuntimeUpdatedEvent,
14
- SessionClosedEvent,
15
- TurnCompletedEvent,
16
- TurnFailedEvent,
17
- TurnInterruptedEvent,
18
- TurnStartedEvent,
19
- )
20
- from ..protocol import ConversationItem, ToolCall, ToolResult, UserMessage
21
- from ..utils import uuid7_string
22
- from ..utils.compat import Literal
4
+ from typing import Awaitable, Callable
23
5
 
24
- if TYPE_CHECKING:
25
- from ..runtime import AgentRuntime
6
+ from ..events import CompactStartedEvent, TerminalEvent, TurnStartedEvent
7
+ from ..utils.compat import Literal
8
+ from .clock_manager import ClockManager
9
+ from .goal_manager import GoalManager
26
10
 
27
11
  PlanStatus = Literal["pending", "in_progress", "completed"]
28
- AgentStatus = typing.Union[
29
- Literal["pending_init", "running", "shutdown", "not_found"],
30
- typing.Dict[str, typing.Union[str, None]],
31
- ]
32
12
  PlanListener = Callable[[typing.Dict[str, object]], None]
33
- AgentRuntimeBuilder = Callable[
34
- [
35
- typing.Union[str, None],
36
- typing.Union[str, None],
37
- typing.Tuple[ConversationItem, ...],
38
- str,
39
- ],
40
- "AgentRuntime",
41
- ]
42
13
  AsyncJSONHandler = Callable[
43
14
  [typing.Dict[str, object]], Awaitable[typing.Union[typing.Dict[str, object], None]]
44
15
  ]
45
16
 
46
- DEFAULT_AGENT_NICKNAME_CANDIDATES = (
47
- "Bacon",
48
- "Descartes",
49
- "Pascal",
50
- "Fermat",
51
- "Huygens",
52
- "Leibniz",
53
- "Newton",
54
- "Halley",
55
- "Euler",
56
- "Lagrange",
57
- "Laplace",
58
- "Volta",
59
- "Gauss",
60
- "Ampere",
61
- "Faraday",
62
- "Darwin",
63
- "Lovelace",
64
- "Boole",
65
- "Pasteur",
66
- "Maxwell",
67
- "Mendel",
68
- "Curie",
69
- "Planck",
70
- "Tesla",
71
- "Poincare",
72
- "Noether",
73
- "Hilbert",
74
- "Einstein",
75
- "Raman",
76
- "Bohr",
77
- "Turing",
78
- "Hubble",
79
- "Feynman",
80
- "Franklin",
81
- "McClintock",
82
- "Meitner",
83
- "Herschel",
84
- "Linnaeus",
85
- "Wegener",
86
- "Chandrasekhar",
87
- "Sagan",
88
- "Goodall",
89
- "Carson",
90
- "Carver",
91
- "Socrates",
92
- "Plato",
93
- "Aristotle",
94
- "Epicurus",
95
- "Cicero",
96
- "Confucius",
97
- "Mencius",
98
- "Zeno",
99
- "Locke",
100
- "Hume",
101
- "Kant",
102
- "Hegel",
103
- "Kierkegaard",
104
- "Mill",
105
- "Nietzsche",
106
- "Peirce",
107
- "James",
108
- "Dewey",
109
- "Russell",
110
- "Popper",
111
- "Sartre",
112
- "Beauvoir",
113
- "Arendt",
114
- "Rawls",
115
- "Singer",
116
- "Anscombe",
117
- "Parfit",
118
- "Kuhn",
119
- "Boyle",
120
- "Hooke",
121
- "Harvey",
122
- "Dalton",
123
- "Helmholtz",
124
- "Gibbs",
125
- "Lorentz",
126
- "Schrodinger",
127
- "Heisenberg",
128
- "Pauli",
129
- "Dirac",
130
- "Bernoulli",
131
- "Godel",
132
- "Nash",
133
- "Banach",
134
- "Ramanujan",
135
- "Erdos",
136
- )
137
-
138
17
 
139
18
  @dataclass(
140
19
  frozen=True,
@@ -211,339 +90,132 @@ class RequestPermissionsManager:
211
90
  return await handler(payload)
212
91
 
213
92
 
214
- @dataclass
215
- class ManagedAgent:
216
- agent_id: "str"
217
- runtime: '"AgentRuntime"'
218
- nickname: "typing.Union[str, None]" = None
219
- last_status: "AgentStatus" = "pending_init"
220
-
221
-
222
- class SubAgentManager:
93
+ class AgentRuntimeEnvironment:
223
94
  def __init__(self) -> "None":
224
- self._runtime_builder: "typing.Union[AgentRuntimeBuilder, None]" = None
225
- self._agents: "typing.Dict[str, ManagedAgent]" = {}
226
- self._pending_notifications: "typing.List[UserMessage]" = []
227
- self._condition = None
228
- self._available_nicknames: "typing.List[str]" = []
229
- self._nickname_random = random.Random()
230
- self._state_listener = None
95
+ self.clock_manager = ClockManager()
96
+ self.goal_manager = GoalManager()
97
+ self.plan_store = PlanStore()
98
+ self.request_user_input_manager = RequestUserInputManager()
99
+ self.request_permissions_manager = RequestPermissionsManager()
100
+ self._resources = {}
101
+ self._restart_handlers = []
102
+ self._close_handlers = []
103
+ self._event_handlers = []
104
+ self._bindings = None
105
+
106
+ def register_resource(self, name, manager, restart=None, close=None, observer=None):
107
+ """Register one shared manager, independently of its callable tools."""
108
+ if name in self._resources or manager in self._resources.values():
109
+ raise ValueError("resource already registered: " + name)
110
+ self._resources[name] = manager
111
+ for handler, handlers in (
112
+ (restart, self._restart_handlers), (close, self._close_handlers),
113
+ (observer, self._event_handlers),
114
+ ):
115
+ if handler is not None:
116
+ handlers.append(handler)
117
+
118
+ def bind(self, invoke, output, changed, request_input, request_permissions):
119
+ self._bindings = (invoke, output, lambda: changed("background_work"))
120
+ self.request_user_input_manager.set_handler(request_input)
121
+ self.request_permissions_manager.set_handler(request_permissions)
122
+ self.plan_store.set_listener(lambda _plan: changed("plan"))
123
+ for manager in self._resources.values():
124
+ manager.bind(*self._bindings)
125
+
126
+ def restart(self):
127
+ for restart in self._restart_handlers:
128
+ restart()
129
+ if self._bindings is not None:
130
+ for manager in self._resources.values():
131
+ manager.bind(*self._bindings)
231
132
 
232
133
  def set_state_listener(self, listener):
233
- self._state_listener = listener
234
-
235
- def _state_changed(self):
236
- if self._state_listener is not None:
237
- self._state_listener()
238
-
239
- def list_agents(self, parent_agent_id):
240
- agents = []
241
- for managed in self._agents.values():
242
- agents.append({
243
- "agent_id": managed.agent_id,
244
- "parent_agent_id": parent_agent_id,
245
- "nickname": managed.nickname,
246
- "status": self._status_payload(managed),
247
- })
248
- agents.extend(
249
- managed.runtime.agent.tool_registry.runtime_environment
250
- .subagent_manager.list_agents(managed.agent_id)
251
- )
252
- return agents
253
-
254
- def get_runtime(self, agent_id):
255
- if agent_id in self._agents:
256
- return self._agents[agent_id].runtime
257
- for managed in self._agents.values():
258
- manager = managed.runtime.agent.tool_registry.runtime_environment.subagent_manager
259
- try:
260
- return manager.get_runtime(agent_id)
261
- except KeyError:
262
- continue
263
- raise KeyError(agent_id)
264
-
265
- def _get_condition(self):
266
- if self._condition is None:
267
- self._condition = asyncio.Condition()
268
- return self._condition
269
-
270
- def set_runtime_builder(
271
- self, builder: "typing.Union[AgentRuntimeBuilder, None]"
272
- ) -> "None":
273
- self._runtime_builder = builder
274
-
275
- def take_pending_notifications(self) -> "typing.Tuple[UserMessage, ...]":
276
- messages = tuple(self._pending_notifications)
277
- self._pending_notifications.clear()
278
- return messages
279
-
280
- async def spawn_agent(
281
- self,
282
- message: "typing.Union[str, None]",
283
- items: "typing.Union[typing.List[typing.Dict[str, object]], None]",
284
- agent_type: "typing.Union[str, None]",
285
- fork_context: "bool",
286
- model: "typing.Union[str, None]",
287
- reasoning_effort: "typing.Union[str, None]",
288
- history: "typing.Tuple[ConversationItem, ...]",
289
- ) -> "typing.Dict[str, object]":
290
- builder = self._runtime_builder
291
- if builder is None:
292
- raise RuntimeError(
293
- "spawn_agent is unavailable before runtime initialization"
294
- )
295
-
296
- initial_history = _fork_context_history(history) if fork_context else ()
297
- agent_id = uuid7_string()
298
- runtime = builder(model, reasoning_effort, initial_history, agent_id)
299
- await runtime.start()
300
- nickname = self._next_nickname()
301
- managed = ManagedAgent(
302
- agent_id=agent_id,
303
- runtime=runtime,
304
- nickname=nickname,
305
- )
306
- runtime.event_handler = lambda event: self._handle_agent_event(managed, event)
307
- async with self._get_condition():
308
- self._agents[agent_id] = managed
309
- self._condition.notify_all()
310
- self._state_changed()
311
-
312
- initial_prompt = self._compose_prompt(message, items)
313
- if initial_prompt:
314
- await self.send_input(agent_id, initial_prompt, interrupt=False)
315
-
134
+ for manager in self._resources.values():
135
+ manager.set_state_listener(listener)
136
+
137
+ def background_work_count(self, after_reply):
138
+ return sum(manager.background_work_count(after_reply) for manager in self._resources.values())
139
+
140
+ def background_work_snapshot(self):
141
+ return [
142
+ dict(item, tool=name)
143
+ for name, manager in self._resources.items()
144
+ for item in manager.background_work_snapshot()
145
+ ]
146
+
147
+ def event_observers(self, event):
148
+ return self._event_handlers if isinstance(
149
+ event, (TerminalEvent, TurnStartedEvent, CompactStartedEvent),
150
+ ) else []
151
+
152
+ def dump_state(self):
153
+ managers = {"clock": self.clock_manager.dump_state()}
154
+ goal = self.goal_manager.dump_state()
155
+ if goal is not None:
156
+ managers["goal"] = goal
316
157
  return {
317
- "agent_id": agent_id,
318
- "nickname": nickname,
158
+ "version": 1,
159
+ "managers": managers,
319
160
  }
320
161
 
321
- async def send_input(
322
- self,
323
- agent_id: "str",
324
- prompt_text: "str",
325
- interrupt: "bool",
326
- ) -> "typing.Dict[str, object]":
327
- managed = self._agents.get(agent_id)
328
- if managed is None:
329
- raise RuntimeError(f"unknown agent: {agent_id}")
330
- if managed.runtime.agent.is_shutdown:
331
- raise RuntimeError(f"agent is shutdown: {agent_id}")
332
-
333
- submission_id, future = await managed.runtime.enqueue_user_turn(
334
- prompt_text,
335
- queue="steer" if interrupt else "enqueue",
162
+ def validate_state(self, state):
163
+ if state is not None:
164
+ if state["version"] != 1:
165
+ raise ValueError("unsupported environment state version")
166
+ self.clock_manager.validate_state(state["managers"]["clock"])
167
+ self.goal_manager.validate_state(state["managers"].get("goal"))
168
+
169
+ def restore_state(self, state):
170
+ self.validate_state(state)
171
+ self.clock_manager.restore_state(
172
+ {"period_m": None} if state is None else state["managers"]["clock"]
336
173
  )
337
- future.add_done_callback(self._submission_finished)
338
- async with self._get_condition():
339
- self._condition.notify_all()
340
- self._state_changed()
341
- return {"submission_id": submission_id}
342
-
343
- async def resume_agent(self, agent_id: "str") -> "typing.Dict[str, object]":
344
- managed = self._agents.get(agent_id)
345
- if managed is None:
346
- return {"status": "not_found"}
347
- if managed.runtime.agent.is_shutdown:
348
- managed.runtime.resume()
349
- managed.last_status = "pending_init"
350
- await managed.runtime.start()
351
- async with self._get_condition():
352
- self._condition.notify_all()
353
- self._state_changed()
354
- return {"status": self._status_payload(managed)}
355
-
356
- async def close_agent(self, agent_id: "str") -> "typing.Dict[str, object]":
357
- managed = self._agents.get(agent_id)
358
- if managed is None:
359
- return {"previous_status": "not_found"}
360
- previous_status = self._status_payload(managed)
361
- await managed.runtime.close()
362
- async with self._get_condition():
363
- self._condition.notify_all()
364
- self._state_changed()
365
- return {"previous_status": previous_status}
366
-
367
- async def shutdown(self) -> "None":
368
- errors = []
369
- for agent_id in tuple(self._agents):
370
- try:
371
- await self.close_agent(agent_id)
372
- except Exception as exc:
373
- errors.append(exc)
374
- if errors:
375
- for error in errors[1:]:
376
- asyncio.get_running_loop().call_exception_handler(
377
- {
378
- "message": "Sub-agent close failed",
379
- "exception": error,
380
- }
381
- )
382
- raise errors[0]
383
-
384
- def _next_nickname(self) -> "str":
385
- if not self._available_nicknames:
386
- self._available_nicknames = list(DEFAULT_AGENT_NICKNAME_CANDIDATES)
387
- self._nickname_random.shuffle(self._available_nicknames)
388
- return self._available_nicknames.pop()
389
-
390
- async def wait_agents(
391
- self,
392
- agent_ids: "typing.List[str]",
393
- timeout_ms: "int" = 30_000,
394
- ) -> "typing.Dict[str, object]":
395
- timeout_seconds = max(timeout_ms, 1) / 1000.0
396
- loop = asyncio.get_running_loop()
397
- deadline = loop.time() + timeout_seconds
398
-
399
- async with self._get_condition():
400
- while True:
401
- snapshot = {
402
- agent_id: self._status_payload(self._agents.get(agent_id))
403
- for agent_id in agent_ids
404
- }
405
- if any(self._is_final_status(status) for status in snapshot.values()):
406
- return {"status": snapshot, "timed_out": False}
407
- remaining = deadline - loop.time()
408
- if remaining <= 0:
409
- return {"status": {}, "timed_out": True}
410
- waiter = asyncio.create_task(self._condition.wait())
411
- try:
412
- done, _pending = await asyncio.wait({waiter}, timeout=remaining)
413
- if not done:
414
- return {"status": {}, "timed_out": True}
415
- await waiter
416
- finally:
417
- if not waiter.done():
418
- waiter.cancel()
419
- # Condition.wait() must reacquire the lock before we leave
420
- # the context. Python 3.6 wait_for() does not await that.
421
- try:
422
- await waiter
423
- except asyncio.CancelledError:
424
- pass
425
-
426
- def _submission_finished(self, future: "asyncio.Future") -> "None":
427
- if not future.cancelled():
428
- future.exception()
429
- asyncio.create_task(self._notify_waiters())
430
-
431
- def _handle_agent_event(self, managed: "ManagedAgent", event: "Event") -> "None":
432
- if isinstance(event, (RuntimeUpdatedEvent, SessionClosedEvent)):
433
- self._state_changed()
434
- return
435
- if isinstance(event, TurnCompletedEvent):
436
- managed.last_status = {"completed": event.output_text}
437
- elif isinstance(event, CompactCompletedEvent):
438
- managed.last_status = {"completed": None}
439
- elif isinstance(event, (TurnFailedEvent, CompactFailedEvent)):
440
- managed.last_status = {
441
- "errored": "{0}: {1}".format(
442
- event.error_type,
443
- event.error,
444
- )
445
- }
446
- elif isinstance(event, TurnInterruptedEvent):
447
- managed.last_status = {"errored": "TurnInterrupted: turn interrupted"}
448
- elif isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
449
- asyncio.create_task(self._notify_waiters())
450
- return
451
- else:
452
- return
453
- self._pending_notifications.append(
454
- UserMessage(
455
- text=(
456
- "<subagent_notification>\n"
457
- + json.dumps(
458
- {
459
- "agent_id": managed.agent_id,
460
- "status": managed.last_status,
461
- },
462
- ensure_ascii=False,
463
- separators=(",", ":"),
464
- )
465
- + "\n</subagent_notification>"
466
- )
467
- )
174
+ self.goal_manager.restore_state(
175
+ None if state is None else state["managers"].get("goal")
468
176
  )
469
- asyncio.create_task(self._notify_waiters())
470
-
471
- async def _notify_waiters(self) -> "None":
472
- self._state_changed()
473
- async with self._get_condition():
474
- self._condition.notify_all()
475
177
 
476
- def _compose_prompt(
477
- self,
478
- message: "typing.Union[str, None]",
479
- items: "typing.Union[typing.List[typing.Dict[str, object]], None]",
480
- ) -> "str":
481
- parts: "typing.List[str]" = []
482
- if message:
483
- parts.append(message.strip())
484
- for item in items or []:
485
- item_type = str(item.get("type", ""))
486
- if item_type == "text":
487
- text = str(item.get("text", "")).strip()
488
- if text:
489
- parts.append(text)
490
- elif item_type == "image":
491
- image_url = str(item.get("image_url", "")).strip()
492
- if image_url:
493
- parts.append(f"[image] {image_url}")
494
- else:
495
- parts.append(json.dumps(item, ensure_ascii=False))
496
- return "\n\n".join(part for part in parts if part)
497
-
498
- def _status_payload(
499
- self, managed: "typing.Union[ManagedAgent, None]"
500
- ) -> "AgentStatus":
501
- if managed is None:
502
- return "not_found"
503
- agent = managed.runtime.agent
504
- if agent.is_shutdown:
505
- return "shutdown"
506
- if managed.runtime.is_busy:
507
- return "running"
508
- status = managed.last_status
509
- return dict(status) if isinstance(status, dict) else status
510
-
511
- def _is_final_status(self, status: "AgentStatus") -> "bool":
512
- if isinstance(status, str):
513
- return status in {"shutdown", "not_found"}
514
- if isinstance(status, dict):
515
- return "completed" in status or "errored" in status
516
- return False
517
-
518
-
519
- def _fork_context_history(
520
- history: "typing.Tuple[ConversationItem, ...]",
521
- ) -> "typing.Tuple[ConversationItem, ...]":
522
- call_ids = set()
523
- result_ids = set()
524
- for item in history:
525
- if isinstance(item, ToolCall):
526
- call_ids.add(item.call_id)
527
- elif isinstance(item, ToolResult):
528
- result_ids.add(item.call_id)
529
-
530
- paired_call_ids = call_ids & result_ids
531
- filtered = []
532
- for item in history:
533
- if isinstance(item, ToolCall) and item.call_id not in paired_call_ids:
534
- continue
535
- if isinstance(item, ToolResult) and item.call_id not in paired_call_ids:
536
- continue
537
- filtered.append(item)
538
- return tuple(filtered)
539
-
540
-
541
- class AgentRuntimeEnvironment:
542
- def __init__(self) -> "None":
543
- self.plan_store = PlanStore()
544
- self.subagent_manager = SubAgentManager()
545
- self.request_user_input_manager = RequestUserInputManager()
546
- self.request_permissions_manager = RequestPermissionsManager()
178
+ def start(self):
179
+ self.clock_manager.arm_after_reply()
180
+ self.goal_manager.start()
181
+
182
+ def handle_agent_event(self, event):
183
+ self.goal_manager.handle_agent_event(event)
184
+
185
+ def tool_completed(self):
186
+ self.goal_manager.account()
187
+
188
+ def follow_up_messages(self):
189
+ return self.goal_manager.follow_up_messages()
190
+
191
+ def take_continuation(self):
192
+ return self.goal_manager.take_continuation()
193
+
194
+ def shutdown(self, save_state):
195
+ try:
196
+ self.goal_manager.shutdown()
197
+ save_state()
198
+ finally:
199
+ for manager in self._resources.values():
200
+ manager.shutdown()
201
+
202
+ async def close(self):
203
+ await close_resources(self._close_handlers)
204
+
205
+
206
+ async def close_resources(handlers):
207
+ errors = []
208
+ for handler in handlers:
209
+ try:
210
+ await handler()
211
+ except Exception as exc:
212
+ errors.append(exc)
213
+ if errors:
214
+ for error in errors[1:]:
215
+ asyncio.get_running_loop().call_exception_handler(
216
+ {"message": "Session close handler failed", "exception": error}
217
+ )
218
+ raise errors[0]
547
219
 
548
220
 
549
221
  def create_agent_runtime_environment() -> "AgentRuntimeEnvironment":
@@ -0,0 +1,42 @@
1
+ """Deliver a MultiAgentV2 message without starting an idle agent."""
2
+
3
+ from .base_tool import BaseTool
4
+
5
+
6
+ class SendMessageTool(BaseTool):
7
+ name = "send_message"
8
+ namespace = "collaboration"
9
+ namespace_description = "Tools for spawning and managing sub-agents."
10
+ exec_only = False
11
+ description = (
12
+ "Send a message to an existing agent. The message will be delivered "
13
+ "promptly. Does not trigger a new turn."
14
+ )
15
+ input_schema = {
16
+ "type": "object",
17
+ "properties": {
18
+ "target": {
19
+ "type": "string",
20
+ "description": "Relative or canonical task name to message (from spawn_agent).",
21
+ },
22
+ "message": {
23
+ "type": "string",
24
+ "encrypted": True,
25
+ "description": "Message text to queue on the target agent.",
26
+ },
27
+ },
28
+ "required": ["target", "message"],
29
+ "additionalProperties": False,
30
+ }
31
+ supports_parallel = False
32
+
33
+ def __init__(self, agents_manager):
34
+ self._agents_manager = agents_manager
35
+
36
+ async def run(self, context, args):
37
+ if set(args) != {"target", "message"}:
38
+ raise ValueError("expected target and message")
39
+ return await self._agents_manager.send_message(
40
+ context.agent_id, args["target"], args["message"],
41
+ encrypted=context.encrypted_messages,
42
+ )