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
@@ -0,0 +1,332 @@
1
+ """In-process Python cells with expression display and asyncio task ownership."""
2
+
3
+ import asyncio
4
+ import base64
5
+ import builtins
6
+ from copy import deepcopy
7
+ import inspect
8
+ import io
9
+ import json
10
+ import traceback
11
+ from types import SimpleNamespace
12
+ import wave
13
+
14
+ from ..utils.compat import compile_async_cell
15
+ from .python_tool_schema import python_tool_signature
16
+
17
+ _BLOCKED_MODULES = frozenset(("ctypes", "_ctypes", "cffi"))
18
+
19
+
20
+ def _guarded_import(name, globals=None, locals=None, fromlist=(), level=0):
21
+ if level == 0 and isinstance(name, str):
22
+ root = name.split(".", 1)[0]
23
+ if root in _BLOCKED_MODULES:
24
+ raise ImportError(
25
+ f"'{root}' is disabled in in-process exec cells; "
26
+ "use `await tools.exec_command(...)` to run native code in a subprocess."
27
+ )
28
+ return builtins.__import__(name, globals, locals, fromlist, level)
29
+
30
+
31
+ class CellTaskFactory:
32
+ """Track descendants of cell tasks without owning the host's tool tasks.
33
+
34
+ One factory serves the active cells on an event loop. The previous factory
35
+ is restored after the last cell has cleaned up; no process-global state or
36
+ changes to the asyncio module are needed.
37
+ """
38
+
39
+ def __init__(self, loop, previous):
40
+ self._loop = loop
41
+ self._previous = previous
42
+ self._owners = {}
43
+ self._users = 0
44
+
45
+ @classmethod
46
+ def acquire(cls, loop):
47
+ factory = loop.get_task_factory()
48
+ if not isinstance(factory, cls):
49
+ factory = cls(loop, factory)
50
+ loop.set_task_factory(factory)
51
+ factory._users += 1
52
+ return factory
53
+
54
+ def release(self):
55
+ self._users -= 1
56
+ if self._users == 0 and self._loop.get_task_factory() is self:
57
+ self._loop.set_task_factory(self._previous)
58
+
59
+ def __call__(self, loop, coroutine, **kwargs):
60
+ owner = self._owners.get(asyncio.current_task(loop=loop))
61
+ return self.create_task(coroutine, owner, **kwargs)
62
+
63
+ def create_task(self, coroutine, owner=None, **kwargs):
64
+ if self._previous is None:
65
+ task = asyncio.Task(coroutine, loop=self._loop, **kwargs)
66
+ else:
67
+ task = self._previous(self._loop, coroutine, **kwargs)
68
+ if owner is not None:
69
+ self._owners[task] = owner
70
+ owner._tasks.add(task)
71
+ task.add_done_callback(self._forget)
72
+ return task
73
+
74
+ def _forget(self, task):
75
+ self._owners.pop(task, None)
76
+
77
+
78
+ class ExecExit(BaseException):
79
+ pass
80
+
81
+
82
+ class TextWriter:
83
+ def __init__(self, emit):
84
+ self._emit = emit
85
+ self._buffer = ""
86
+
87
+ def write(self, value):
88
+ self._buffer += value
89
+ while "\n" in self._buffer:
90
+ line, self._buffer = self._buffer.split("\n", 1)
91
+ self._emit(line)
92
+ return len(value)
93
+
94
+ def flush(self):
95
+ if self._buffer:
96
+ self._emit(self._buffer)
97
+ self._buffer = ""
98
+
99
+
100
+ class ExecRuntime:
101
+ def __init__(self, source, tools, stored_values, cwd, emit, invoke_tool):
102
+ self._loop = asyncio.get_running_loop()
103
+ self._source = source
104
+ self._values = stored_values
105
+ self._tool_specs = tools
106
+ self._cwd = cwd
107
+ self._emit = emit
108
+ self._invoke_tool = invoke_tool
109
+ self._writer = TextWriter(self.text)
110
+ self._next_request_id = 0
111
+ self._tasks = set()
112
+ self._tool_tasks = []
113
+ self._factory = None
114
+ self._main_task = None
115
+ self._stop_requested = False
116
+ self._closing = False
117
+
118
+ def send(self, message):
119
+ self._emit(message)
120
+
121
+ def request_stop(self):
122
+ if not self._stop_requested:
123
+ self._stop_requested = True
124
+ if self._main_task is not None and not self._main_task.done():
125
+ self._main_task.cancel()
126
+
127
+ def print(self, *values, **kwargs):
128
+ if kwargs.get("file") is None:
129
+ kwargs["file"] = self._writer
130
+ builtins.print(*values, **kwargs)
131
+
132
+ def content(self, item):
133
+ self.send({"type": "content", "item": item})
134
+
135
+ def text(self, value):
136
+ text = value if isinstance(value, str) else json.dumps(
137
+ value, ensure_ascii=False, allow_nan=False,
138
+ )
139
+ self.content({"type": "input_text", "text": text})
140
+
141
+ def notify(self, value):
142
+ text = value if isinstance(value, str) else json.dumps(
143
+ value, ensure_ascii=False, allow_nan=False,
144
+ )
145
+ self.send({"type": "notify", "text": text})
146
+
147
+ def image(self, value, detail=...):
148
+ url, item = self._media_url(value, "image")
149
+ if detail is ...:
150
+ detail = item.get("detail", item.get("_meta", {}).get("codex/imageDetail"))
151
+ if detail not in (None, "auto", "low", "high", "original"):
152
+ raise ValueError("unsupported image detail")
153
+ output = {"type": "input_image", "image_url": url}
154
+ if detail is not None:
155
+ output["detail"] = detail
156
+ self.content(output)
157
+
158
+ def audio(self, value):
159
+ url, _item = self._media_url(value, "audio")
160
+ mime_type, encoded = url[5:].split(";base64,", 1)
161
+ if mime_type in ("audio/wav", "audio/x-wav"):
162
+ with wave.open(io.BytesIO(base64.b64decode(encoded)), "rb") as clip:
163
+ if clip.getnframes() / clip.getframerate() < 0.025:
164
+ self.text(
165
+ "Audio output omitted because the clip is shorter than "
166
+ "25 ms; use a longer clip."
167
+ )
168
+ return
169
+ self.content({"type": "input_audio", "audio_url": url})
170
+
171
+ def generated_image(self, result):
172
+ self.image(result["image_url"])
173
+ if "output_hint" in result:
174
+ if not isinstance(result["output_hint"], str):
175
+ raise TypeError("output_hint must be a string")
176
+ self.text(result["output_hint"])
177
+
178
+ def _media_url(self, value, kind):
179
+ item = {}
180
+ if isinstance(value, str):
181
+ url = value
182
+ elif isinstance(value, dict):
183
+ item = value
184
+ if value.get("type") == kind:
185
+ url = "data:{0};base64,{1}".format(value["mimeType"], value["data"])
186
+ else:
187
+ url = value[kind + "_url"]
188
+ else:
189
+ raise TypeError(kind + " expects a data URL or an individual media object")
190
+ if not isinstance(url, str) or not url.startswith("data:" + kind + "/"):
191
+ raise ValueError(kind + " expects a base64 data URL")
192
+ _header, encoded = url.split(";base64,", 1)
193
+ if not encoded:
194
+ raise ValueError(kind + " data must not be empty")
195
+ base64.b64decode(encoded, validate=True)
196
+ return url, item
197
+
198
+ def store(self, key, value):
199
+ if not isinstance(key, str):
200
+ raise TypeError("store key must be a string")
201
+ self._values[key] = json.loads(json.dumps(value, allow_nan=False))
202
+
203
+ def load(self, key):
204
+ if not isinstance(key, str):
205
+ raise TypeError("load key must be a string")
206
+ return deepcopy(self._values.get(key))
207
+
208
+ def exit(self):
209
+ raise ExecExit()
210
+
211
+ async def yield_control(self):
212
+ self.send({"type": "yield"})
213
+ await asyncio.sleep(0)
214
+
215
+ def _tool_caller(self, spec):
216
+ signature = python_tool_signature(spec)
217
+
218
+ def call(*args, **kwargs):
219
+ arguments = dict(signature.bind(*args, **kwargs).arguments)
220
+ if spec["tool_type"] == "custom":
221
+ arguments = arguments["input"]
222
+ if not isinstance(arguments, str):
223
+ raise TypeError(spec["name"] + " expects one source string")
224
+ return self._call_tool(spec, arguments)
225
+ call.__name__ = spec["name"]
226
+ call.__signature__ = signature
227
+ return call
228
+
229
+ async def _call_tool(self, spec, arguments):
230
+ if self._stop_requested or self._closing:
231
+ raise RuntimeError("exec cell is stopping")
232
+ self._next_request_id += 1
233
+ request_id = str(self._next_request_id)
234
+ task = self._factory.create_task(self._invoke_tool(
235
+ spec, request_id, deepcopy(arguments),
236
+ ))
237
+ self._tool_tasks.append(task)
238
+ # Once issued, host tool calls finish even if the cell is cancelled.
239
+ return deepcopy(await asyncio.shield(task))
240
+
241
+ async def run(self):
242
+ if self._stop_requested:
243
+ return None
244
+ tool_namespaces = {
245
+ "tools": SimpleNamespace(), "collaboration": SimpleNamespace(),
246
+ }
247
+ for spec in self._tool_specs:
248
+ setattr(
249
+ tool_namespaces[spec["namespace"]], spec["name"], self._tool_caller(spec),
250
+ )
251
+ namespace = {
252
+ "__name__": "__codex_exec__",
253
+ "__builtins__": dict(
254
+ vars(builtins), print=self.print, __import__=_guarded_import,
255
+ ),
256
+ "cwd": self._cwd,
257
+ "asyncio": asyncio,
258
+ "text": self.text, "image": self.image, "audio": self.audio,
259
+ "generated_image": self.generated_image,
260
+ "store": self.store, "load": self.load, "notify": self.notify,
261
+ "exit": self.exit, "yield_control": self.yield_control,
262
+ "ALL_TOOLS": tuple(
263
+ {
264
+ "name": spec["namespace"] + "." + spec["name"],
265
+ "description": spec["description"],
266
+ }
267
+ for spec in self._tool_specs
268
+ ),
269
+ }
270
+ namespace.update(tool_namespaces)
271
+ error_text = None
272
+ self._factory = CellTaskFactory.acquire(self._loop)
273
+ try:
274
+ self._main_task = self._factory.create_task(
275
+ self._execute(namespace), self,
276
+ )
277
+ try:
278
+ error_text = await self._main_task
279
+ except asyncio.CancelledError:
280
+ if not self._stop_requested:
281
+ error_text = "exec cell was cancelled"
282
+ finally:
283
+ self._closing = True
284
+ try:
285
+ # A cancelled task's finally block can create another task.
286
+ while True:
287
+ pending = [task for task in self._tasks if not task.done()]
288
+ if not pending:
289
+ break
290
+ for task in pending:
291
+ task.cancel()
292
+ outcomes = await asyncio.gather(*pending, return_exceptions=True)
293
+ for outcome in outcomes:
294
+ if (
295
+ isinstance(outcome, BaseException)
296
+ and not isinstance(outcome, (asyncio.CancelledError, ExecExit))
297
+ and error_text is None
298
+ ):
299
+ error_text = "".join(traceback.format_exception(
300
+ type(outcome), outcome, outcome.__traceback__,
301
+ ))
302
+ await asyncio.gather(*self._tool_tasks, return_exceptions=True)
303
+ self._writer.flush()
304
+ finally:
305
+ self._tasks.clear()
306
+ self._tool_tasks.clear()
307
+ self._factory.release()
308
+ return error_text
309
+
310
+ async def _execute(self, namespace):
311
+ try:
312
+ coro = eval(compile_async_cell(self._source), namespace)
313
+ if "__exec_cell__" in namespace:
314
+ coro = namespace.pop("__exec_cell__")()
315
+ if inspect.iscoroutine(coro):
316
+ result = await coro
317
+ else:
318
+ result = None
319
+ if result is None:
320
+ result = namespace.pop("__exec_result__", None)
321
+ if result is not None:
322
+ output = repr(result)
323
+ self._writer.flush()
324
+ self.text(output)
325
+ except ExecExit:
326
+ return None
327
+ except asyncio.CancelledError:
328
+ raise
329
+ except BaseException:
330
+ # User code (including sys.exit()) must report through its cell.
331
+ return traceback.format_exc()
332
+ return None
@@ -1,15 +1,6 @@
1
- """`exec` tool for the Python Codex prototype.
1
+ """Python implementation of the CodeModeOnly `exec` entrypoint."""
2
2
 
3
- Original Codex mapping:
4
- - Corresponds to the original Codex code-mode `exec` tool.
5
-
6
- Expected behavior:
7
- - Accept raw JavaScript source text as a freeform/custom tool payload.
8
- - Run the script inside a background exec cell with helper functions and nested
9
- tool access.
10
- - Return either a completed result or a running `cell_id` status that can be
11
- resumed via `wait`.
12
- """
3
+ from dataclasses import replace
13
4
 
14
5
  from ..protocol import JSONValue
15
6
  from .base_tool import BaseTool, ToolContext
@@ -19,7 +10,7 @@ EXEC_FREEFORM_GRAMMAR = r"""start: pragma_source | plain_source
19
10
  pragma_source: PRAGMA_LINE NEWLINE SOURCE
20
11
  plain_source: SOURCE
21
12
 
22
- PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/
13
+ PRAGMA_LINE: /[ \t]*# @exec:[^\r\n]*/
23
14
  NEWLINE: /\r?\n/
24
15
  SOURCE: /[\s\S]+/
25
16
  """
@@ -27,25 +18,69 @@ SOURCE: /[\s\S]+/
27
18
 
28
19
  class ExecTool(BaseTool):
29
20
  name = "exec"
21
+ exec_only = False
30
22
  description = (
31
- "Run JavaScript code to orchestrate/compose tool calls\n"
32
- "- Evaluates the provided JavaScript code in a fresh V8 isolate as an "
33
- "async module.\n"
34
- "- All nested tools are available on the global `tools` object, for "
35
- "example `await tools.exec_command(...)`.\n"
36
- "- Nested tool methods take either a string or an object as their input "
37
- "argument.\n"
38
- "- Runs raw JavaScript -- no Node, no file system, no network access, "
39
- "no console.\n"
40
- "- Accepts raw JavaScript source text, not JSON, quoted strings, or "
41
- "markdown code fences.\n"
42
- "- You may optionally start the tool input with a first-line pragma "
43
- 'like `// @exec: {"yield_time_ms": 10000, '
44
- '"max_output_tokens": 1000}`.\n'
45
- "- `yield_time_ms` asks `exec` to yield early if the script is still "
46
- "running. Defaults to 10000 ms.\n"
47
- "- `max_output_tokens` sets the token budget for direct `exec` results. "
48
- "Defaults to 10000 tokens."
23
+ "Run Python code to orchestrate and compose tool calls.\n"
24
+ "- Submit raw Python source with top-level `await`; the runner executes "
25
+ "it in the host process with a fresh namespace for each cell. "
26
+ "Imports and helper definitions are allowed. "
27
+ "Do not wrap the source in a main function, JSON, or Markdown.\n"
28
+ "- The final top-level expression is displayed with `repr()` unless its "
29
+ "value is None. Assignment-only cells do not display a value. "
30
+ "`print()` and `text()` remain available for explicit output.\n"
31
+ "- To run a shell command, submit Python such as "
32
+ '`await tools.exec_command(cmd="git status --short")`.\n'
33
+ "- Call ordinary nested tools through `tools.<name>(...)` and agent "
34
+ "tools through `collaboration.<name>(...)` inside this Python source. "
35
+ "Collaboration tools also remain available as direct tool calls. "
36
+ "Both namespaces are listed below. Follow the Python signatures: use "
37
+ "positional or keyword arguments, and `**arguments` to unpack a dict. "
38
+ "Freeform tools accept one string, either "
39
+ "positionally or with `input=...`.\n"
40
+ "- Tool calls are asynchronous: use `await tools.exec_command(cmd=\"pwd\")`. "
41
+ "Use `await asyncio.gather(...)` for independent calls, or "
42
+ "`await asyncio.gather(..., return_exceptions=True)` to inspect every "
43
+ "success and failure. Keep dependent operations sequential.\n"
44
+ "- `asyncio` and the Python standard library are available. Tasks created "
45
+ "through asyncio from cell tasks are cleaned up when the script finishes. "
46
+ "Already issued host tool calls finish before the cell is closed.\n"
47
+ "- Execution and stopping are cooperative. Use async operations and run "
48
+ "blocking work through tools.exec_command. Synchronous code blocks the host; "
49
+ "a non-yielding loop cannot be stopped independently. Imported modules and "
50
+ "process state are shared.\n"
51
+ "- `cwd` is the cell's workspace Path; use `cwd / \"file\"` for direct file "
52
+ "access. Nested tools use that workspace. The host's working directory "
53
+ "and sys.stdout are not changed. Plain `print()` writes to this cell; "
54
+ "output from imported modules is not captured.\n"
55
+ "- Optional first line: "
56
+ '`# @exec: {"yield_time_ms": 30000, "max_output_tokens": 1000}`. '
57
+ "The defaults are 30000 ms and 10000 tokens. A running script returns a "
58
+ "cell_id; use wait for subsequent output.\n"
59
+ "\n"
60
+ "Global helpers:\n"
61
+ "- `text(value)`: append text; non-string values use JSON encoding. "
62
+ "Use `text()` or `print()` for explicit output.\n"
63
+ "- `image(value, detail=...)`: append a base64 data-URL image, an object "
64
+ "with image_url/detail, or an individual MCP image block. An explicit "
65
+ "detail overrides the object's detail or codex/imageDetail metadata.\n"
66
+ "- `audio(value)`: append a base64 data-URL audio item, an object with "
67
+ "audio_url, or an individual MCP audio block.\n"
68
+ "- `generated_image(result)`: append the generated image_url and optional "
69
+ "output_hint. The URL must be a base64 data URL.\n"
70
+ "- `store(key, value)` / `load(key)`: save and retrieve JSON-serializable "
71
+ "values across exec cells in this session; a missing key returns None.\n"
72
+ "- `notify(value)`: immediately submit an additional output for this exec "
73
+ "call through the attached Runtime.\n"
74
+ "- `await yield_control()`: return accumulated output to the model while "
75
+ "the script continues running.\n"
76
+ "- `exit()`: finish the current script successfully.\n"
77
+ "- `ALL_TOOLS`: the available nested tools as qualified name/description records.\n"
78
+ "\n"
79
+ "Example:\n"
80
+ "```python\n"
81
+ "result = await tools.exec_command(cmd=\"pwd\")\n"
82
+ "result\n"
83
+ "```"
49
84
  )
50
85
  tool_type = "custom"
51
86
  format = {
@@ -58,5 +93,13 @@ class ExecTool(BaseTool):
58
93
  def __init__(self, manager: "CodeModeManager") -> "None":
59
94
  self._manager = manager
60
95
 
96
+ def spec(self):
97
+ return replace(
98
+ super().spec(),
99
+ description=self.description + self._manager.describe_tools(),
100
+ )
101
+
61
102
  async def run(self, context: "ToolContext", args: "JSONValue") -> "JSONValue":
62
- return await self._manager.exec(str(args), context)
103
+ if not isinstance(args, str):
104
+ raise ValueError("exec expects Python source text")
105
+ return await self._manager.exec(args, context)
@@ -0,0 +1,44 @@
1
+ """Deliver a MultiAgentV2 task, starting an idle recipient when necessary."""
2
+
3
+ from .base_tool import BaseTool
4
+
5
+
6
+ class FollowupTaskTool(BaseTool):
7
+ name = "followup_task"
8
+ namespace = "collaboration"
9
+ namespace_description = "Tools for spawning and managing sub-agents."
10
+ exec_only = False
11
+ description = (
12
+ "Send a follow-up task to an existing non-root target agent and trigger "
13
+ "a turn if it is idle. If the target is already running, deliver the task "
14
+ "promptly at message boundaries while sampling, or after the pending "
15
+ "tool call completes."
16
+ )
17
+ input_schema = {
18
+ "type": "object",
19
+ "properties": {
20
+ "target": {
21
+ "type": "string",
22
+ "description": "Agent id or canonical task name to send a follow-up task to (from spawn_agent).",
23
+ },
24
+ "message": {
25
+ "type": "string",
26
+ "encrypted": True,
27
+ "description": "Message text to send to the target agent.",
28
+ },
29
+ },
30
+ "required": ["target", "message"],
31
+ "additionalProperties": False,
32
+ }
33
+ supports_parallel = False
34
+
35
+ def __init__(self, agents_manager):
36
+ self._agents_manager = agents_manager
37
+
38
+ async def run(self, context, args):
39
+ if set(args) != {"target", "message"}:
40
+ raise ValueError("expected target and message")
41
+ return await self._agents_manager.send_message(
42
+ context.agent_id, args["target"], args["message"], trigger_turn=True,
43
+ encrypted=context.encrypted_messages,
44
+ )