python-codex 0.5.1__py3-none-any.whl → 0.6.0__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 (72) hide show
  1. pycodex/__init__.py +18 -8
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +27 -239
  4. pycodex/cli.py +19 -14
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +369 -51
  7. pycodex/events.py +28 -186
  8. pycodex/model.py +181 -88
  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 +1069 -140
  18. pycodex/protocol.py +78 -15
  19. pycodex/runtime.py +461 -203
  20. pycodex/tools/__init__.py +100 -7
  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 -29
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +2 -139
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -12
  28. pycodex/tools/exec_runtime.py +381 -0
  29. pycodex/tools/exec_tool.py +78 -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/request_user_input_tool.py +3 -23
  38. pycodex/tools/runtime_services.py +124 -408
  39. pycodex/tools/send_message_tool.py +42 -0
  40. pycodex/tools/spawn_agent_tool.py +55 -94
  41. pycodex/tools/unified_exec_manager.py +52 -34
  42. pycodex/tools/wait_agent_tool.py +46 -66
  43. pycodex/tools/wait_tool.py +24 -13
  44. pycodex/tools/web_search_tool.py +1 -0
  45. pycodex/utils/codex_config.py +105 -0
  46. pycodex/utils/compactor.py +4 -0
  47. pycodex/utils/compat.py +2 -2
  48. pycodex/utils/doctor.py +5 -4
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +33 -0
  51. pycodex/utils/session_persist.py +106 -33
  52. python_codex-0.6.0.dist-info/METADATA +352 -0
  53. python_codex-0.6.0.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +7 -6
  56. responses_server/config.py +0 -11
  57. responses_server/payload_processors.py +4 -4
  58. responses_server/request_translation.py +480 -0
  59. responses_server/server.py +31 -24
  60. responses_server/stream_events.py +124 -0
  61. responses_server/stream_router.py +33 -830
  62. responses_server/tools/custom_adapter.py +29 -29
  63. responses_server/transport.py +332 -0
  64. pycodex/tools/close_agent_tool.py +0 -60
  65. pycodex/tools/exec_runtime.js +0 -161
  66. pycodex/tools/resume_agent_tool.py +0 -54
  67. pycodex/tools/send_input_tool.py +0 -110
  68. python_codex-0.5.1.dist-info/METADATA +0 -235
  69. python_codex-0.5.1.dist-info/RECORD +0 -90
  70. {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
  71. {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
  72. {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,83 +1,47 @@
1
- """`spawn_agent` tool for the Python Codex prototype.
1
+ """Create a named task using the MultiAgentV2 contract."""
2
2
 
3
- Original Codex mapping:
4
- - Corresponds to the original Codex `spawn_agent` collaboration tool.
5
-
6
- Expected behavior:
7
- - Spawn a sibling agent runtime that can work in parallel with the caller.
8
- - Optionally seed the spawned agent with the current thread history.
9
- - Return the new agent identifier plus any user-facing nickname.
10
- """
11
-
12
- import typing
13
-
14
- from ..protocol import JSONDict, JSONValue
15
- from .agent_tool_schemas import COLLAB_INPUT_ITEMS_SCHEMA
16
- from .base_tool import BaseTool, ToolContext
17
- from .runtime_services import SubAgentManager
18
-
19
- SPAWN_AGENT_OUTPUT_SCHEMA = {
20
- "type": "object",
21
- "properties": {
22
- "agent_id": {
23
- "type": "string",
24
- "description": "Thread identifier for the spawned agent.",
25
- },
26
- "nickname": {
27
- "type": ["string", "null"],
28
- "description": "User-facing nickname for the spawned agent when available.",
29
- },
30
- },
31
- "required": ["agent_id", "nickname"],
32
- "additionalProperties": False,
33
- }
3
+ from .base_tool import BaseTool
34
4
 
35
5
 
36
6
  class SpawnAgentTool(BaseTool):
37
7
  name = "spawn_agent"
38
- description = """
39
- Spawn a sub-agent for a well-scoped task. Returns the spawned agent id plus the user-facing nickname when available. Spawned agents inherit your current model by default. Omit `model` to use that preferred default; set `model` only when an explicit override is needed.
40
- This spawn_agent tool provides you access to sub-agents that inherit your current model by default. Do not set the `model` field unless the user explicitly asks for a different model or there is a clear task-specific reason. You should follow the rules and guidelines below to use this tool.
41
-
42
- Do not spawn sub-agents unless the user explicitly asks for sub-agents, delegation, or parallel agent work.
43
-
44
- ### Designing delegated subtasks
45
- - Subtasks must be concrete, well-defined, and self-contained.
46
- - Delegated subtasks must materially advance the main task.
47
- - Do not duplicate work between the main rollout and delegated subtasks.
48
- - Avoid issuing multiple delegate calls on the same unresolved thread unless the new delegated task is genuinely different and necessary.
49
- - Narrow the delegated ask to the concrete output you need next.
50
- - For coding tasks, prefer delegating concrete code-change worker subtasks over read-only explorer analysis when the subagent can make a bounded patch in a clear write scope.
51
- - When delegating coding work, instruct the submodel to edit files directly in its forked workspace and list the file paths it changed in the final answer.
52
- - For code-edit subtasks, decompose work so each delegated task has a disjoint write set.
53
-
54
- ### After you delegate
55
- - Call wait_agent very sparingly. Only call wait_agent when you need the result immediately for the next critical-path step and you are blocked until it returns.
56
- - Do not redo delegated subagent tasks yourself; focus on integrating results or tackling non-overlapping work.
57
- - While the subagent is running in the background, do meaningful non-overlapping work immediately.
58
- - Do not repeatedly wait by reflex.
59
- - When a delegated coding task returns, quickly review the uploaded changes, then integrate or refine them.
60
-
61
- ### Parallel delegation patterns
62
- - Run multiple independent information-seeking subtasks in parallel when you have distinct questions that can be answered independently.
63
- - Split implementation into disjoint codebase slices and spawn multiple agents in parallel when the write scopes do not overlap.
64
- - Delegate verification only when it can run in parallel with ongoing implementation and is likely to catch a concrete risk before final integration.
65
- - The key is to find opportunities to spawn multiple independent subtasks in parallel within the same round, while ensuring each subtask is well-defined, self-contained, and materially advances the main task."""
8
+ namespace = "collaboration"
9
+ namespace_description = "Tools for spawning and managing sub-agents."
10
+ exec_only = False
11
+ description = (
12
+ 'Spawns an agent to work on the specified task. If your current task is '
13
+ '`/root/task1` and you spawn_agent with task_name "task_3" the agent will '
14
+ 'have canonical task name `/root/task1/task_3`.\n'
15
+ 'You are then able to refer to this agent as `task_3` or '
16
+ '`/root/task1/task_3` interchangeably. However an agent `/root/task2/task_3` '
17
+ 'would only be able to communicate with this agent via its canonical '
18
+ 'name `/root/task1/task_3`.\n'
19
+ 'The spawned agent will have the same tools as you and the ability to '
20
+ 'spawn its own subagents.\n\n'
21
+ 'It will be able to send you and other running agents messages, and its '
22
+ 'final answer will be provided to you when it finishes.\n'
23
+ 'The new agent\'s canonical task name will be provided to it along with '
24
+ 'the message.\n\n'
25
+ 'Note that passing `fork_turns="none"` will not pass any surrounding '
26
+ 'context to the spawned subagent, which may cause the agent to lack the '
27
+ 'context it needs to complete its task, whereas `fork_turns="all"` will '
28
+ 'provide the subagent with all surrounding context.'
29
+ )
66
30
  input_schema = {
67
31
  "type": "object",
68
32
  "properties": {
69
- "message": {
33
+ "task_name": {
70
34
  "type": "string",
71
- "description": "Initial plain-text task for the new agent. Use either message or items.",
35
+ "description": "Task name for the new agent. Use lowercase letters, digits, and underscores.",
72
36
  },
73
- "items": COLLAB_INPUT_ITEMS_SCHEMA,
74
- "agent_type": {
37
+ "message": {
75
38
  "type": "string",
76
- "description": "Optional type name for the new agent.",
39
+ "encrypted": True,
40
+ "description": "Initial plain-text task for the new agent.",
77
41
  },
78
- "fork_context": {
79
- "type": "boolean",
80
- "description": "True forks the current thread history into the new agent; false or omitted starts with only the initial prompt.",
42
+ "fork_turns": {
43
+ "type": "string",
44
+ "description": "Parent history to inherit. Defaults to `all`; use `none` to start without parent history. Only `all` and `none` are supported.",
81
45
  },
82
46
  "model": {
83
47
  "type": "string",
@@ -88,35 +52,32 @@ Do not spawn sub-agents unless the user explicitly asks for sub-agents, delegati
88
52
  "description": "Reasoning effort override for the new agent. Omit to inherit the parent effort.",
89
53
  },
90
54
  },
55
+ "required": ["task_name", "message"],
56
+ "additionalProperties": False,
57
+ }
58
+ output_schema = {
59
+ "type": "object",
60
+ "properties": {
61
+ "task_name": {
62
+ "type": "string",
63
+ "description": "Canonical task name for the spawned agent.",
64
+ },
65
+ },
66
+ "required": ["task_name"],
91
67
  "additionalProperties": False,
92
68
  }
93
- output_schema = SPAWN_AGENT_OUTPUT_SCHEMA
94
69
  supports_parallel = False
95
70
 
96
- def __init__(self, subagent_manager: "SubAgentManager") -> "None":
97
- self._subagent_manager = subagent_manager
71
+ def __init__(self, agents_manager):
72
+ self._agents_manager = agents_manager
98
73
 
99
- async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
100
- message = self._optional_string(args, "message")
101
- items = args.get("items")
102
- if items is not None and not isinstance(items, list):
103
- return "Error: `items` must be a list when provided."
104
- if message is None and not items:
105
- return "Provide one of: message or items"
106
- return await self._subagent_manager.spawn_agent(
107
- message=message,
108
- items=items,
109
- agent_type=self._optional_string(args, "agent_type"),
110
- fork_context=bool(args.get("fork_context", False)),
111
- model=self._optional_string(args, "model"),
112
- reasoning_effort=self._optional_string(args, "reasoning_effort"),
113
- history=context.history,
74
+ async def run(self, context, args):
75
+ if set(args) - set(self.input_schema["properties"]):
76
+ raise ValueError("unexpected spawn_agent argument")
77
+ agent_path = await self._agents_manager.spawn_agent(
78
+ context.agent_id, args["task_name"], args["message"],
79
+ args.get("fork_turns", "all"),
80
+ args.get("model"), args.get("reasoning_effort"), context.history,
81
+ encrypted=context.encrypted_messages,
114
82
  )
115
-
116
- def _optional_string(
117
- self, args: "JSONDict", key: "str"
118
- ) -> "typing.Union[str, None]":
119
- value = args.get(key)
120
- if value in (None, ""):
121
- return None
122
- return str(value)
83
+ return {"task_name": agent_path}
@@ -8,7 +8,7 @@ Expected behavior:
8
8
  - Start a long-lived command session for `exec_command`.
9
9
  - Preserve unread output between calls.
10
10
  - Accept follow-up stdin writes and polling through `write_stdin`.
11
- - Return summaries in the same textual shape Codex tools expect.
11
+ - Return structured results for nested exec tool calls.
12
12
  """
13
13
 
14
14
  import asyncio
@@ -22,6 +22,7 @@ from pathlib import Path
22
22
 
23
23
  from loguru import logger
24
24
 
25
+ from ..protocol import JSONValue
25
26
  from ..utils.compat import shlex_join, stream_writer_is_closing
26
27
  from ..utils.truncation import (
27
28
  DEFAULT_MAX_OUTPUT_TOKENS,
@@ -125,21 +126,46 @@ class UnifiedExecManager:
125
126
  self._next_session_id = DEFAULT_SESSION_ID_START
126
127
  self._sessions: "typing.Dict[int, UnifiedExecSession]" = {}
127
128
  self._lock = threading.Lock()
129
+ self._state_listener = None
128
130
  self._notify_hook: "typing.Union[typing.Callable[[typing.Dict[str, object]], typing.Awaitable[typing.Any]], None]" = (None)
129
131
 
130
- def set_notify_hook(
131
- self,
132
- callback: "typing.Union[typing.Callable[[typing.Dict[str, object]], typing.Awaitable[typing.Any]], None]",
133
- ) -> "None":
134
- self._notify_hook = callback
132
+ def bind(self, invoke, output, state_changed):
133
+ self._notify_hook = invoke
134
+ self._state_listener = state_changed
135
135
 
136
- def running_session_count(self) -> "int":
136
+ def shutdown(self):
137
+ self._notify_hook = None
138
+
139
+ def background_work_count(self, after_reply) -> "int":
137
140
  return sum(
138
141
  1
139
142
  for session in self._sessions.values()
140
143
  if session.process.returncode is None
141
144
  )
142
145
 
146
+ def set_state_listener(self, listener):
147
+ self._state_listener = listener
148
+
149
+ def _state_changed(self):
150
+ if self._state_listener is not None:
151
+ self._state_listener()
152
+
153
+ def background_work_snapshot(self):
154
+ with self._lock:
155
+ return [
156
+ {
157
+ "kind": "exec",
158
+ "session_id": session.session_id,
159
+ "pid": session.process.pid,
160
+ "tty": session.tty,
161
+ "status": (
162
+ "running" if session.process.returncode is None else "exited"
163
+ ),
164
+ "exit_code": session.process.returncode,
165
+ }
166
+ for session in self._sessions.values()
167
+ ]
168
+
143
169
  async def exec_command(
144
170
  self,
145
171
  cmd: "str",
@@ -149,7 +175,7 @@ class UnifiedExecManager:
149
175
  tty: "bool" = DEFAULT_TTY,
150
176
  yield_time_ms: "int" = DEFAULT_EXEC_YIELD_TIME_MS,
151
177
  max_output_tokens: "typing.Union[int, None]" = None,
152
- ) -> "str":
178
+ ) -> "JSONValue":
153
179
  session_id = await self._allocate_session_id()
154
180
  command = self._build_shell_command(cmd, shell, login)
155
181
  logger.debug(
@@ -180,6 +206,7 @@ class UnifiedExecManager:
180
206
 
181
207
  with self._lock:
182
208
  self._sessions[session_id] = session
209
+ self._state_changed()
183
210
 
184
211
  output = await self._wait_and_snapshot(
185
212
  session_id,
@@ -197,14 +224,12 @@ class UnifiedExecManager:
197
224
  chars: "str" = "",
198
225
  yield_time_ms: "int" = DEFAULT_WRITE_STDIN_YIELD_TIME_MS,
199
226
  max_output_tokens: "typing.Union[int, None]" = None,
200
- ) -> "str":
227
+ ) -> "JSONValue":
201
228
  session = await self._get_session(session_id)
202
229
  if session is None:
203
230
  return f"Error: session_id {session_id} is not running."
204
231
 
205
232
  if chars:
206
- if session.process.stdin is None:
207
- return f"Error: session_id {session_id} does not accept stdin."
208
233
  logger.debug(
209
234
  "write_stdin session_id={} chars_len={}", session_id, len(chars)
210
235
  )
@@ -236,7 +261,7 @@ class UnifiedExecManager:
236
261
  session_id: "int",
237
262
  yield_time_ms: "int",
238
263
  max_output_tokens: "typing.Union[int, None]",
239
- ) -> "str":
264
+ ) -> "JSONValue":
240
265
  session = await self._get_session(session_id)
241
266
  if session is None:
242
267
  return f"Error: session_id {session_id} is not running."
@@ -273,35 +298,32 @@ class UnifiedExecManager:
273
298
  wall_time = asyncio.get_running_loop().time() - start_wait
274
299
  output_bytes = session.unread_output.drain_bytes()
275
300
  output_text = output_bytes.decode("utf-8", errors="replace")
276
- original_token_count = self._estimate_token_count(output_text)
301
+ original_token_count = approx_token_count(output_text)
277
302
  output_text = self._truncate_output(output_text, max_output_tokens)
278
303
 
279
- lines = [
280
- f"Chunk ID: {uuid.uuid4().hex[:6]}",
281
- f"Wall time: {wall_time:.4f} seconds",
282
- ]
304
+ result = {
305
+ "chunk_id": uuid.uuid4().hex[:6],
306
+ "wall_time_seconds": wall_time,
307
+ "output": output_text,
308
+ }
283
309
  if session.process.returncode is None:
284
- lines.append(f"Process running with session ID {session_id}")
310
+ result["session_id"] = session_id
285
311
  else:
286
- lines.append(f"Process exited with code {session.process.returncode}")
287
- if original_token_count is not None:
288
- lines.append(f"Original token count: {original_token_count}")
289
- lines.append("Output:")
290
- lines.append(output_text)
312
+ result["exit_code"] = session.process.returncode
313
+ result["original_token_count"] = original_token_count
291
314
 
292
315
  if session.process.returncode is not None:
293
316
  await self._close_session(session_id)
294
317
 
295
- return "\n".join(lines)
318
+ return result
296
319
 
297
320
  async def _close_session(self, session_id: "int") -> "None":
298
321
  with self._lock:
299
322
  session = self._sessions.pop(session_id, None)
300
323
  if session is None:
301
324
  return
302
- if session.process.stdin is not None and not stream_writer_is_closing(
303
- session.process.stdin
304
- ):
325
+ self._state_changed()
326
+ if not stream_writer_is_closing(session.process.stdin):
305
327
  session.process.stdin.close()
306
328
 
307
329
  async def _drain_reader_after_exit(
@@ -330,8 +352,6 @@ class UnifiedExecManager:
330
352
 
331
353
  async def _pump_output(self, session: "UnifiedExecSession") -> "None":
332
354
  stream = session.process.stdout
333
- if stream is None:
334
- return
335
355
  while True:
336
356
  chunk = await stream.read(4096)
337
357
  if not chunk:
@@ -341,7 +361,7 @@ class UnifiedExecManager:
341
361
  session.output_event.set()
342
362
 
343
363
  async def _notify_when_session_completes(self, session_id: "int") -> "None":
344
- from ..agent import TurnInterrupted
364
+ from ..runtime import SubmissionInterrupted
345
365
 
346
366
  if self._notify_hook is None:
347
367
  return
@@ -349,6 +369,7 @@ class UnifiedExecManager:
349
369
  if session is None:
350
370
  return
351
371
  await session.process.wait()
372
+ self._state_changed()
352
373
  with self._lock:
353
374
  if self._sessions.get(session_id) is not session:
354
375
  return
@@ -364,7 +385,7 @@ class UnifiedExecManager:
364
385
  "command": session.command_display,
365
386
  }
366
387
  )
367
- except TurnInterrupted:
388
+ except SubmissionInterrupted:
368
389
  # A steer ended the notification turn at a safe boundary.
369
390
  return
370
391
  except asyncio.CancelledError:
@@ -391,9 +412,6 @@ class UnifiedExecManager:
391
412
  return [shell_path, "-NoProfile", "-Command", cmd]
392
413
  return [shell_path, "-lc" if login else "-c", cmd]
393
414
 
394
- def _estimate_token_count(self, output: "str") -> "typing.Union[int, None]":
395
- return approx_token_count(output)
396
-
397
415
  def _truncate_output(
398
416
  self, output: "str", max_output_tokens: "typing.Union[int, None]"
399
417
  ) -> "str":
@@ -1,85 +1,65 @@
1
- """`wait_agent` tool for the Python Codex prototype.
1
+ """Wait for MultiAgentV2 mailbox activity without consuming messages."""
2
2
 
3
- Original Codex mapping:
4
- - Corresponds to the original Codex `wait_agent` collaboration tool.
5
-
6
- Expected behavior:
7
- - Wait for one or more spawned agents to reach a final state.
8
- - Return the current status map for requested agents, or an empty map when the
9
- wait times out.
10
- """
11
-
12
- from ..protocol import JSONDict, JSONValue
13
- from .agent_tool_schemas import AGENT_STATUS_SCHEMA
14
- from .base_tool import BaseTool, ToolContext
15
- from .runtime_services import SubAgentManager
16
-
17
- DEFAULT_WAIT_AGENT_TIMEOUT_MS = 30_000
18
- MIN_WAIT_AGENT_TIMEOUT_MS = 10_000
19
- MAX_WAIT_AGENT_TIMEOUT_MS = 3_600_000
20
-
21
- WAIT_AGENT_OUTPUT_SCHEMA = {
22
- "type": "object",
23
- "properties": {
24
- "status": {
25
- "type": "object",
26
- "description": "Final statuses keyed by agent id.",
27
- "additionalProperties": AGENT_STATUS_SCHEMA,
28
- },
29
- "timed_out": {
30
- "type": "boolean",
31
- "description": "Whether the wait call returned due to timeout before any agent reached a final status.",
32
- },
33
- },
34
- "required": ["status", "timed_out"],
35
- "additionalProperties": False,
36
- }
3
+ from .base_tool import BaseTool
37
4
 
38
5
 
39
6
  class WaitAgentTool(BaseTool):
40
7
  name = "wait_agent"
8
+ namespace = "collaboration"
9
+ namespace_description = "Tools for spawning and managing sub-agents."
10
+ exec_only = False
41
11
  description = (
42
- "Wait for agents to reach a final status. Completed statuses may "
43
- "include the agent's final message. Returns empty status when timed "
44
- "out. Once the agent reaches a final status, a notification message "
45
- "will be received containing the same completed status."
12
+ "Wait for a mailbox update from any live agent, including queued messages "
13
+ "and final-status notifications. The wait also ends early when new user "
14
+ "input is steered into the active turn. Does not return the content; "
15
+ "returns either a summary of which agents have updates (if any), an "
16
+ "interruption summary for steered input, or a timeout summary if no "
17
+ "activity arrives before the deadline."
46
18
  )
47
19
  input_schema = {
48
20
  "type": "object",
49
21
  "properties": {
50
- "ids": {
51
- "type": "array",
52
- "items": {"type": "string"},
53
- "description": "Agent ids to wait on. Pass multiple ids to wait for whichever finishes first.",
54
- },
55
22
  "timeout_ms": {
56
- "type": "integer",
57
- "description": "Timeout in milliseconds. Defaults to 30000, min 10000, max 3600000. Prefer longer waits (minutes) to avoid busy polling.",
23
+ "type": "number",
24
+ "description": "Timeout in milliseconds. Defaults to 30000, min 10000, max 3600000.",
58
25
  },
59
26
  },
60
- "required": ["ids"],
61
27
  "additionalProperties": False,
62
28
  }
63
- output_schema = WAIT_AGENT_OUTPUT_SCHEMA
29
+ output_schema = {
30
+ "type": "object",
31
+ "properties": {
32
+ "message": {
33
+ "type": "string",
34
+ "description": "Brief wait summary without the agent's final content, including any timeout adjustment.",
35
+ },
36
+ "timed_out": {
37
+ "type": "boolean",
38
+ "description": "Whether the wait call returned because no mailbox update arrived before the timeout.",
39
+ },
40
+ },
41
+ "required": ["message", "timed_out"],
42
+ "additionalProperties": False,
43
+ }
64
44
  supports_parallel = False
65
45
 
66
- def __init__(self, subagent_manager: "SubAgentManager") -> "None":
67
- self._subagent_manager = subagent_manager
68
-
69
- async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
70
- del context
71
- ids = args.get("ids")
72
- if not isinstance(ids, list) or not ids:
73
- return "Error: `ids` must be a non-empty list."
74
- agent_ids = [str(item).strip() for item in ids if str(item).strip()]
75
- if not agent_ids:
76
- return "Error: `ids` must include at least one non-empty id."
77
- timeout_ms = self._timeout_ms(args)
78
- return await self._subagent_manager.wait_agents(agent_ids, timeout_ms)
46
+ def __init__(self, agents_manager):
47
+ self._agents_manager = agents_manager
79
48
 
80
- def _timeout_ms(self, args: "JSONDict") -> "int":
81
- value = int(args.get("timeout_ms", DEFAULT_WAIT_AGENT_TIMEOUT_MS))
82
- return min(
83
- max(value, MIN_WAIT_AGENT_TIMEOUT_MS),
84
- MAX_WAIT_AGENT_TIMEOUT_MS,
49
+ async def run(self, context, args):
50
+ if set(args) - {"timeout_ms"}:
51
+ raise ValueError("unexpected wait_agent argument")
52
+ requested = args.get("timeout_ms", 30000)
53
+ if type(requested) is not int:
54
+ raise ValueError("timeout_ms must be an integer")
55
+ if requested > 3600000:
56
+ raise ValueError("timeout_ms must be at most 3600000")
57
+ timeout = max(requested, 10000)
58
+ result = await self._agents_manager.wait_for_activity(
59
+ context.agent_id, timeout,
85
60
  )
61
+ if requested < timeout:
62
+ result["message"] += (
63
+ "\n\nRequested timeout of {0}ms was clamped to the minimum of {1}ms."
64
+ ).format(requested, timeout)
65
+ return result
@@ -9,7 +9,7 @@ Expected behavior:
9
9
  - Return only the new output since the previous `exec` / `wait` snapshot.
10
10
  """
11
11
 
12
- import typing
12
+ import math
13
13
 
14
14
  from ..protocol import JSONDict, JSONValue
15
15
  from .base_tool import BaseTool, ToolContext
@@ -18,6 +18,7 @@ from .code_mode_manager import DEFAULT_WAIT_YIELD_TIME_MS, CodeModeManager
18
18
 
19
19
  class WaitTool(BaseTool):
20
20
  name = "wait"
21
+ exec_only = False
21
22
  description = (
22
23
  "Waits on a yielded `exec` cell and returns new output or completion.\n"
23
24
  "- Use `wait` only after `exec` returns `Script running with cell ID ...`.\n"
@@ -43,11 +44,11 @@ class WaitTool(BaseTool):
43
44
  "description": "Identifier of the running exec cell.",
44
45
  },
45
46
  "yield_time_ms": {
46
- "type": "integer",
47
+ "type": "number",
47
48
  "description": "Wait before yielding more output. Defaults to 10000 ms.",
48
49
  },
49
50
  "max_tokens": {
50
- "type": "integer",
51
+ "type": "number",
51
52
  "description": "Output token budget for this wait call. Defaults to 10000 tokens.",
52
53
  },
53
54
  "terminate": {
@@ -65,18 +66,28 @@ class WaitTool(BaseTool):
65
66
 
66
67
  async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
67
68
  del context
68
- cell_id = str(args.get("cell_id", "")).strip()
69
- if not cell_id:
70
- return "Error: `cell_id` is required."
69
+ cell_id = args["cell_id"]
70
+ if not isinstance(cell_id, str) or not cell_id:
71
+ raise ValueError("cell_id must be a non-empty string")
72
+ terminate = args.get("terminate", False)
73
+ if not isinstance(terminate, bool):
74
+ raise ValueError("terminate must be a boolean")
71
75
  return await self._manager.wait(
72
76
  cell_id=cell_id,
73
- yield_time_ms=int(args.get("yield_time_ms", DEFAULT_WAIT_YIELD_TIME_MS)),
74
- max_tokens=self._optional_int(args, "max_tokens"),
75
- terminate=bool(args.get("terminate", False)),
77
+ yield_time_ms=self._integer(
78
+ args.get("yield_time_ms", DEFAULT_WAIT_YIELD_TIME_MS), "yield_time_ms",
79
+ ),
80
+ max_tokens=(
81
+ self._integer(args["max_tokens"], "max_tokens")
82
+ if "max_tokens" in args else None
83
+ ),
84
+ terminate=terminate,
76
85
  )
77
86
 
78
- def _optional_int(self, args: "JSONDict", key: "str") -> "typing.Union[int, None]":
79
- value = args.get(key)
80
- if value in (None, ""):
81
- return None
87
+ def _integer(self, value, name):
88
+ if (
89
+ isinstance(value, bool) or not isinstance(value, (int, float))
90
+ or not math.isfinite(value) or int(value) != value or value < 0
91
+ ):
92
+ raise ValueError(name + " must be a non-negative integer")
82
93
  return int(value)
@@ -16,6 +16,7 @@ from .base_tool import BaseTool, ToolContext
16
16
 
17
17
  class WebSearchTool(BaseTool):
18
18
  name = "web_search"
19
+ exec_only = False
19
20
  description = ""
20
21
  tool_type = "web_search"
21
22
  options = {