python-codex 0.5.2__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 (71) 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 +13 -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 +370 -226
  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 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +2 -181
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  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 +122 -450
  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 +26 -35
  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 +78 -36
  52. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/METADATA +117 -27
  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.2.dist-info/RECORD +0 -90
  69. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
  70. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
  71. {python_codex-0.5.2.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,53 +1,44 @@
1
- """Shared runtime for Codex `exec` / `wait` tools.
2
-
3
- Original Codex mapping:
4
- - Corresponds to the code-mode runtime behind Codex `exec` and `wait`.
5
-
6
- Expected behavior:
7
- - Run raw JavaScript source in a background cell.
8
- - Let JavaScript call nested local tools through a `tools` object.
9
- - Support yielding/running cells and later polling or terminating them via
10
- `wait`.
11
- """
1
+ """Host for Python exec cells and their nested tool calls."""
12
2
 
13
3
  import asyncio
14
4
  import json
15
5
  import math
16
- import threading
6
+ import traceback
17
7
  import typing
18
8
  import uuid
19
- from dataclasses import dataclass, field
20
- from pathlib import Path
9
+ from dataclasses import dataclass, field, replace
21
10
 
22
11
  from loguru import logger
23
12
 
24
- from ..utils.compat import is_ascii, stream_writer_is_closing
25
- from ..protocol import JSONDict, JSONValue, ToolCall
13
+ from ..protocol import JSONDict, JSONValue, ToolCall, ToolResult
26
14
  from ..utils.truncation import DEFAULT_MAX_OUTPUT_TOKENS
27
15
  from .base_tool import StructuredToolOutput, ToolContext, ToolRegistry
16
+ from .exec_runtime import ExecRuntime
17
+ from .python_tool_schema import python_tool_declaration
28
18
 
19
+ DEFAULT_EXEC_YIELD_TIME_MS = 30_000
29
20
  DEFAULT_WAIT_YIELD_TIME_MS = 10_000
30
21
  CHARS_PER_TOKEN = 4
31
- EXEC_PRAGMA_PREFIX = "// @exec:"
22
+ EXEC_PRAGMA_PREFIX = "# @exec:"
32
23
  WAIT_COMPLETION_GRACE_SECONDS = 0.02
33
24
 
34
25
 
35
26
  @dataclass
36
27
  class ExecCell:
37
28
  cell_id: "str"
38
- process: "asyncio.subprocess.Process"
39
29
  started_at: "float"
30
+ call_id: "typing.Union[str, None]"
31
+ cwd: "str"
32
+ generation: "int"
33
+ runtime: "typing.Union[ExecRuntime, None]" = None
34
+ task: "typing.Union[asyncio.Task, None]" = None
40
35
  output_items: "typing.List[JSONDict]" = field(default_factory=list)
41
36
  delivered_count: "int" = 0
42
- reader_task: "typing.Union[asyncio.Task, None]" = None
43
- stderr_task: "typing.Union[asyncio.Task, None]" = None
44
37
  yield_event: "asyncio.Event" = field(default_factory=asyncio.Event)
45
38
  output_event: "asyncio.Event" = field(default_factory=asyncio.Event)
46
39
  done_event: "asyncio.Event" = field(default_factory=asyncio.Event)
47
- completed: "bool" = False
48
40
  terminated: "bool" = False
49
41
  error_text: "typing.Union[str, None]" = None
50
- stderr_chunks: "typing.List[str]" = field(default_factory=list)
51
42
 
52
43
 
53
44
  @dataclass(
@@ -55,21 +46,85 @@ class ExecCell:
55
46
  )
56
47
  class ParsedExecSource:
57
48
  code: "str"
58
- yield_time_ms: "typing.Union[int, None]"
49
+ yield_time_ms: "int"
59
50
  max_output_tokens: "typing.Union[int, None]"
60
51
 
61
52
 
62
53
  class CodeModeManager:
63
54
  def __init__(self, registry: "ToolRegistry") -> "None":
64
55
  self._registry = registry
65
- self._runtime_script = Path(__file__).with_name("exec_runtime.js")
66
56
  self._stored_values: "typing.Dict[str, JSONValue]" = {}
67
57
  self._cells: "typing.Dict[str, ExecCell]" = {}
68
- self._lock = threading.Lock()
58
+ self._retired_cells: "typing.List[ExecCell]" = []
59
+ self._generation = 0
60
+ self._output_handler = None
61
+ self._state_listener = None
62
+ self._closed = False
63
+
64
+ def bind(self, invoke, output, state_changed):
65
+ self._output_handler = output
66
+ self._state_listener = state_changed
67
+
68
+ def restart(self):
69
+ self._generation += 1
70
+ for cell in self._cells.values():
71
+ self._stop_cell(cell)
72
+ self._retired_cells.append(cell)
73
+ self._cells.clear()
74
+ self._stored_values = {}
75
+ self._closed = False
76
+
77
+ def set_state_listener(self, listener):
78
+ self._state_listener = listener
79
+
80
+ def _state_changed(self):
81
+ if self._state_listener is not None:
82
+ self._state_listener()
83
+
84
+ def background_work_snapshot(self):
85
+ return [
86
+ {
87
+ "cell_id": cell.cell_id,
88
+ "cwd": cell.cwd,
89
+ "running": not cell.done_event.is_set(),
90
+ }
91
+ for cell in self._cells.values()
92
+ ]
93
+
94
+ def shutdown(self):
95
+ self._closed = True
96
+ self._output_handler = None
97
+ self._state_listener = None
98
+ for cell in tuple(self._cells.values()) + tuple(self._retired_cells):
99
+ self._stop_cell(cell)
100
+
101
+ async def close(self):
102
+ self._closed = True
103
+ cells = tuple(self._cells.values()) + tuple(self._retired_cells)
104
+ if cells:
105
+ await asyncio.gather(*(self._terminate_cell(cell) for cell in cells))
106
+ self._cells.clear()
107
+ self._retired_cells.clear()
108
+ self._stored_values.clear()
109
+ self._state_changed()
110
+
111
+ def _stop_cell(self, cell):
112
+ if not cell.done_event.is_set():
113
+ cell.terminated = True
114
+ cell.runtime.request_stop()
115
+
116
+ async def _terminate_cell(self, cell):
117
+ self._stop_cell(cell)
118
+ await asyncio.shield(cell.task)
119
+
120
+ def background_work_count(self, after_reply) -> "int":
121
+ return sum(not cell.done_event.is_set() for cell in self._cells.values())
69
122
 
70
123
  async def exec(
71
124
  self, source: "str", context: "ToolContext"
72
125
  ) -> "typing.Union[StructuredToolOutput, str]":
126
+ if self._closed:
127
+ raise RuntimeError("exec runtime is closed")
73
128
  try:
74
129
  parsed = self._parse_exec_source(source)
75
130
  except ValueError as exc:
@@ -90,234 +145,109 @@ class CodeModeManager:
90
145
  if cell is None:
91
146
  return f"Error: unknown exec cell `{cell_id}`."
92
147
 
93
- if terminate and cell.process.returncode is None:
94
- cell.terminated = True
95
- cell.process.terminate()
96
- try:
97
- await asyncio.wait_for(cell.process.wait(), timeout=1.0)
98
- except asyncio.TimeoutError:
99
- cell.process.kill()
100
- await cell.process.wait()
148
+ if terminate:
149
+ await self._terminate_cell(cell)
101
150
 
102
151
  await self._wait_for_wait(cell, yield_time_ms)
103
152
  return await self._snapshot_cell(cell, max_tokens)
104
153
 
105
- def enabled_tools(self) -> "typing.List[typing.Dict[str, str]]":
106
- enabled: "typing.List[typing.Dict[str, str]]" = []
107
- for tool in self._registry.tools():
108
- if tool.name in {"exec", "wait"}:
109
- continue
110
- if tool.tool_type not in {"function", "custom"}:
111
- continue
112
- enabled.append(
113
- {
114
- "tool_name": tool.name,
115
- "js_name": self._normalize_identifier(tool.name),
116
- "description": tool.description,
117
- "tool_type": tool.tool_type,
118
- }
154
+ def describe_tools(self):
155
+ sections = []
156
+ for tool in self._registry.exec_tools():
157
+ sections.append(
158
+ "\n\n### `" + tool["namespace"] + "." + tool["name"] + "`\n"
159
+ + tool["description"]
160
+ + "\n\nexec tool declaration:\n```python\n"
161
+ + python_tool_declaration(tool) + "\n```"
119
162
  )
120
- enabled.sort(key=lambda item: item["tool_name"])
121
- return enabled
163
+ return "".join(sections)
122
164
 
123
165
  async def _start_cell(self, code: "str", context: "ToolContext") -> "ExecCell":
166
+ tools = self._registry.exec_tools()
124
167
  cell_id = uuid.uuid4().hex[:10]
125
- process = await asyncio.create_subprocess_exec(
126
- "node",
127
- str(self._runtime_script),
128
- cwd=str(context.cwd),
129
- stdin=asyncio.subprocess.PIPE,
130
- stdout=asyncio.subprocess.PIPE,
131
- stderr=asyncio.subprocess.PIPE,
132
- )
133
168
  cell = ExecCell(
134
169
  cell_id=cell_id,
135
- process=process,
136
170
  started_at=asyncio.get_running_loop().time(),
171
+ call_id=context.call_id,
172
+ cwd=str(context.cwd),
173
+ generation=self._generation,
137
174
  )
138
- self._cells[cell_id] = cell
139
- cell.reader_task = asyncio.create_task(self._read_stdout(cell, context))
140
- cell.stderr_task = asyncio.create_task(self._read_stderr(cell))
141
- await self._send_message(
142
- cell,
143
- {
144
- "type": "init",
145
- "cell_id": cell_id,
146
- "source": code,
147
- "stored_values": self._stored_values,
148
- "tools": self.enabled_tools(),
149
- },
175
+ cell.runtime = ExecRuntime(
176
+ code, tools, self._stored_values, context.cwd,
177
+ lambda message: self._receive(cell, message),
178
+ lambda spec, request_id, args: self._invoke_tool(
179
+ cell, context, spec, request_id, args,
180
+ ),
150
181
  )
182
+ self._cells[cell_id] = cell
183
+ cell.task = asyncio.create_task(self._run_cell(cell))
184
+ self._state_changed()
151
185
  logger.debug("exec start cell_id={} cwd={}", cell_id, context.cwd)
152
186
  return cell
153
187
 
154
- async def _read_stdout(self, cell: "ExecCell", context: "ToolContext") -> "None":
155
- stream = cell.process.stdout
156
- if stream is None:
157
- cell.error_text = "missing stdout pipe"
158
- cell.done_event.set()
159
- return
160
-
161
- while True:
162
- line = await stream.readline()
163
- if not line:
164
- break
165
- try:
166
- message = json.loads(line.decode("utf-8", errors="replace"))
167
- except json.JSONDecodeError:
168
- cell.output_items.append(
169
- {
170
- "type": "input_text",
171
- "text": line.decode("utf-8", errors="replace").rstrip("\n"),
172
- }
173
- )
174
- cell.output_event.set()
175
- continue
176
-
177
- msg_type = message.get("type")
178
- if msg_type == "output_text":
179
- cell.output_items.append(
180
- {
181
- "type": "input_text",
182
- "text": str(message.get("text", "")),
183
- }
184
- )
185
- cell.output_event.set()
186
- continue
187
- if msg_type == "output_image":
188
- image_item: "JSONDict" = {
189
- "type": "input_image",
190
- "image_url": str(message.get("image_url", "")),
191
- }
192
- detail = message.get("detail")
193
- if detail is not None:
194
- image_item["detail"] = detail
195
- cell.output_items.append(image_item)
196
- cell.output_event.set()
197
- continue
198
- if msg_type == "yield":
199
- cell.yield_event.set()
200
- continue
201
- if msg_type == "tool_call":
202
- await self._handle_nested_tool_call(cell, context, message)
203
- continue
204
- if msg_type == "result":
205
- cell.completed = True
206
- cell.error_text = self._coerce_optional_text(message.get("error_text"))
207
- stored_values = message.get("stored_values")
208
- if isinstance(stored_values, dict):
209
- with self._lock:
210
- self._stored_values = stored_values
211
- cell.done_event.set()
212
- cell.output_event.set()
213
- continue
214
-
215
- await cell.process.wait()
216
- if cell.stderr_task is not None:
217
- await cell.stderr_task
218
- if not cell.done_event.is_set():
219
- stderr_text = "".join(cell.stderr_chunks).strip()
220
- if stderr_text:
221
- cell.error_text = stderr_text
222
- elif cell.process.returncode not in (0, None):
223
- cell.error_text = f"process exited with code {cell.process.returncode}"
188
+ async def _run_cell(self, cell):
189
+ try:
190
+ cell.error_text = await cell.runtime.run()
191
+ except Exception:
192
+ cell.error_text = traceback.format_exc()
193
+ finally:
224
194
  cell.done_event.set()
225
195
  cell.output_event.set()
196
+ self._state_changed()
226
197
 
227
- async def _read_stderr(self, cell: "ExecCell") -> "None":
228
- stream = cell.process.stderr
229
- if stream is None:
230
- return
231
- while True:
232
- chunk = await stream.read(4096)
233
- if not chunk:
234
- break
235
- cell.stderr_chunks.append(chunk.decode("utf-8", errors="replace"))
236
-
237
- async def _handle_nested_tool_call(
238
- self,
239
- cell: "ExecCell",
240
- context: "ToolContext",
241
- message: "JSONDict",
242
- ) -> "None":
243
- tool_name = str(message.get("tool_name", ""))
244
- request_id = str(message.get("id", ""))
245
- tool = self._registry.get_tool(tool_name)
246
- if tool is None:
247
- await self._send_message(
248
- cell,
249
- {
250
- "type": "tool_result",
251
- "id": request_id,
252
- "ok": False,
253
- "error": f"unknown tool: {tool_name}",
254
- },
255
- )
256
- return
257
- if tool.tool_type not in {"function", "custom"}:
258
- await self._send_message(
259
- cell,
260
- {
261
- "type": "tool_result",
262
- "id": request_id,
263
- "ok": False,
264
- "error": f"tool `{tool_name}` is not available inside exec",
265
- },
266
- )
198
+ def _receive(self, cell, message):
199
+ if cell.generation != self._generation:
267
200
  return
201
+ msg_type = message["type"]
202
+ if msg_type == "content":
203
+ cell.output_items.append(message["item"])
204
+ cell.output_event.set()
205
+ elif msg_type == "yield":
206
+ cell.yield_event.set()
207
+ elif msg_type == "notify":
208
+ if self._output_handler is None or cell.call_id is None:
209
+ raise RuntimeError("notify requires an attached Runtime")
210
+ self._output_handler(ToolResult(
211
+ call_id=cell.call_id, name="exec",
212
+ output=message["text"], tool_type="custom",
213
+ ))
214
+ cell.yield_event.set()
215
+ else:
216
+ raise ValueError("unknown exec cell message: " + msg_type)
268
217
 
218
+ async def _invoke_tool(self, cell, context, spec, request_id, arguments):
269
219
  result = await self._registry.execute(
270
220
  ToolCall(
271
221
  call_id=f"{cell.cell_id}_{request_id}",
272
- name=tool_name,
273
- arguments=message.get("arguments"),
274
- tool_type=tool.tool_type,
222
+ name=spec["tool_name"],
223
+ arguments=arguments,
224
+ tool_type=spec["tool_type"],
225
+ namespace=self._registry.get_tool(spec["tool_name"]).namespace,
275
226
  ),
276
- context,
227
+ replace(context, encrypted_messages=False),
277
228
  )
278
229
  if result.is_error:
279
- payload = {
280
- "type": "tool_result",
281
- "id": request_id,
282
- "ok": False,
283
- "error": result.output_text(),
284
- }
285
- else:
286
- payload = {
287
- "type": "tool_result",
288
- "id": request_id,
289
- "ok": True,
290
- "result": result.output,
291
- }
292
- await self._send_message(cell, payload)
293
-
294
- async def _send_message(self, cell: "ExecCell", payload: "JSONDict") -> "None":
295
- stdin = cell.process.stdin
296
- if stdin is None or stream_writer_is_closing(stdin):
297
- return
298
- stdin.write((json.dumps(payload, ensure_ascii=False) + "\n").encode("utf-8"))
299
- await stdin.drain()
230
+ raise RuntimeError(result.output_text())
231
+ return result.output
300
232
 
301
233
  async def _wait_for_exec(
302
- self, cell: "ExecCell", yield_time_ms: "typing.Union[int, None]"
234
+ self, cell: "ExecCell", yield_time_ms: "int"
303
235
  ) -> "None":
304
236
  done_task = asyncio.create_task(cell.done_event.wait())
305
237
  yield_task = asyncio.create_task(cell.yield_event.wait())
306
238
  tasks = {done_task, yield_task}
307
239
  try:
308
- if yield_time_ms is None:
309
- await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
310
- else:
311
- await asyncio.wait_for(
312
- asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED),
313
- timeout=max(yield_time_ms, 1) / 1000.0,
314
- )
240
+ await asyncio.wait_for(
241
+ asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED),
242
+ timeout=max(yield_time_ms, 1) / 1000.0,
243
+ )
315
244
  except asyncio.TimeoutError:
316
245
  return
317
246
  finally:
318
247
  for task in tasks:
319
248
  if not task.done():
320
249
  task.cancel()
250
+ await asyncio.gather(*tasks, return_exceptions=True)
321
251
  cell.yield_event.clear()
322
252
 
323
253
  async def _wait_for_wait(self, cell: "ExecCell", yield_time_ms: "int") -> "None":
@@ -357,6 +287,7 @@ class CodeModeManager:
357
287
  for task in tasks:
358
288
  if not task.done():
359
289
  task.cancel()
290
+ await asyncio.gather(*tasks, return_exceptions=True)
360
291
 
361
292
  cell.output_event.clear()
362
293
  cell.yield_event.clear()
@@ -381,14 +312,15 @@ class CodeModeManager:
381
312
  for task in tasks:
382
313
  if not task.done():
383
314
  task.cancel()
315
+ await asyncio.gather(*tasks, return_exceptions=True)
384
316
 
385
317
  async def _snapshot_cell(
386
318
  self,
387
319
  cell: "ExecCell",
388
320
  max_tokens: "typing.Union[int, None]",
389
321
  ) -> "StructuredToolOutput":
390
- if cell.process.returncode is not None and cell.reader_task is not None:
391
- await cell.reader_task
322
+ if cell.done_event.is_set():
323
+ await cell.task
392
324
 
393
325
  wall_time = asyncio.get_running_loop().time() - cell.started_at
394
326
  new_items = list(cell.output_items[cell.delivered_count :])
@@ -422,9 +354,11 @@ class CodeModeManager:
422
354
 
423
355
  if cell.done_event.is_set():
424
356
  self._cells.pop(cell.cell_id, None)
357
+ self._state_changed()
425
358
 
426
359
  return StructuredToolOutput(
427
- output=output_text, content_items=tuple(content_items)
360
+ output=output_text, content_items=tuple(content_items),
361
+ success=not bool(cell.error_text),
428
362
  )
429
363
 
430
364
  def _truncate_content_items(
@@ -443,7 +377,7 @@ class CodeModeManager:
443
377
  text = str(item.get("text", ""))
444
378
  remaining = max_chars - total_chars
445
379
  if remaining <= 0:
446
- break
380
+ continue
447
381
  if len(text) > remaining:
448
382
  truncated.append(
449
383
  {
@@ -452,32 +386,32 @@ class CodeModeManager:
452
386
  }
453
387
  )
454
388
  total_chars = max_chars
455
- break
389
+ continue
456
390
  truncated.append(item)
457
391
  total_chars += len(text)
458
392
  return truncated
459
393
 
460
394
  def _status_text(self, cell: "ExecCell") -> "str":
461
- if cell.terminated:
462
- return "Script terminated"
463
395
  if not cell.done_event.is_set():
464
396
  return f"Script running with cell ID {cell.cell_id}"
397
+ if cell.terminated:
398
+ return "Script terminated"
465
399
  if cell.error_text:
466
400
  return "Script failed"
467
401
  return "Script completed"
468
402
 
469
403
  def _parse_exec_source(self, input_text: "str") -> "ParsedExecSource":
470
404
  if not input_text.strip():
471
- raise ValueError("exec expects raw JavaScript source text (non-empty).")
405
+ raise ValueError("exec expects non-empty Python source text")
472
406
  code = input_text
473
- yield_time_ms = None
407
+ yield_time_ms = DEFAULT_EXEC_YIELD_TIME_MS
474
408
  max_output_tokens = None
475
409
  lines = input_text.split("\n", 1)
476
410
  first_line = lines[0].lstrip()
477
411
  if first_line.startswith(EXEC_PRAGMA_PREFIX):
478
412
  if len(lines) == 1 or not lines[1].strip():
479
413
  raise ValueError(
480
- "exec pragma must be followed by JavaScript source on subsequent lines"
414
+ "exec pragma must be followed by Python source on subsequent lines"
481
415
  )
482
416
  pragma_text = first_line[len(EXEC_PRAGMA_PREFIX) :].strip()
483
417
  try:
@@ -494,9 +428,15 @@ class CodeModeManager:
494
428
  for key in value:
495
429
  if key not in {"yield_time_ms", "max_output_tokens"}:
496
430
  raise ValueError(f"unsupported exec pragma field `{key}`")
497
- if value.get("yield_time_ms") is not None:
431
+ for key, number in value.items():
432
+ if (
433
+ isinstance(number, bool) or not isinstance(number, (int, float))
434
+ or not math.isfinite(number) or int(number) != number or number < 0
435
+ ):
436
+ raise ValueError("exec pragma field " + key + " must be a non-negative integer")
437
+ if "yield_time_ms" in value:
498
438
  yield_time_ms = int(value["yield_time_ms"])
499
- if value.get("max_output_tokens") is not None:
439
+ if "max_output_tokens" in value:
500
440
  max_output_tokens = int(value["max_output_tokens"])
501
441
  code = lines[1]
502
442
  return ParsedExecSource(
@@ -504,24 +444,3 @@ class CodeModeManager:
504
444
  yield_time_ms=yield_time_ms,
505
445
  max_output_tokens=max_output_tokens,
506
446
  )
507
-
508
- def _normalize_identifier(self, tool_name: "str") -> "str":
509
- identifier = []
510
- for index, char in enumerate(tool_name):
511
- is_valid = (
512
- char == "_"
513
- or char == "$"
514
- or (
515
- is_ascii(char) and char.isalnum() and (index != 0 or char.isalpha())
516
- )
517
- )
518
- if is_valid:
519
- identifier.append(char)
520
- else:
521
- identifier.append("_")
522
- return "".join(identifier) or "_"
523
-
524
- def _coerce_optional_text(self, value: "JSONValue") -> "typing.Union[str, None]":
525
- if value in (None, ""):
526
- return None
527
- return str(value)
@@ -22,9 +22,6 @@ from .unified_exec_manager import (
22
22
  UnifiedExecManager,
23
23
  )
24
24
 
25
- if typing.TYPE_CHECKING:
26
- from ..agent import Agent
27
-
28
25
  MIN_EXEC_YIELD_TIME_MS = 250
29
26
  MAX_EXEC_YIELD_TIME_MS = 30_000
30
27
 
@@ -77,21 +74,6 @@ class ExecCommandTool(BaseTool):
77
74
  def __init__(self, manager: "UnifiedExecManager") -> "None":
78
75
  self._manager = manager
79
76
 
80
- def bind_agent(self, agent: "Agent") -> "None":
81
- self._manager.set_notify_hook(agent.maybe_invoke)
82
-
83
- def shutdown(self) -> "None":
84
- self._manager.set_notify_hook(None)
85
-
86
- def background_work_count(self, after_reply: "bool") -> "int":
87
- return self._manager.running_session_count()
88
-
89
- def background_work_snapshot(self):
90
- return self._manager.snapshot()
91
-
92
- def set_state_listener(self, listener):
93
- self._manager.set_state_listener(listener)
94
-
95
77
  async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
96
78
  cmd = str(args.get("cmd", "")).strip()
97
79
  if not cmd: