python-codex 0.6.0__py3-none-any.whl → 0.6.2__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.
pycodex/runtime.py CHANGED
@@ -8,7 +8,6 @@ from time import monotonic
8
8
  from .agent import BASE_EVENT_HANDLER, Agent, TurnInterrupted
9
9
  from .events import (
10
10
  AssistantDeltaEvent,
11
- AutoCompactCompletedEvent,
12
11
  CommandCompletedEvent,
13
12
  CommandFailedEvent,
14
13
  CommandStartedEvent,
@@ -17,6 +16,7 @@ from .events import (
17
16
  InputQueuedEvent,
18
17
  InputRequestedEvent,
19
18
  InputResolvedEvent,
19
+ MessagesAddedEvent,
20
20
  RuntimeUpdatedEvent,
21
21
  SessionClosedEvent,
22
22
  SessionStateEvent,
@@ -30,7 +30,7 @@ from .events import (
30
30
  TurnStartedEvent,
31
31
  )
32
32
  from .model import ModelControl
33
- from .protocol import AgentMessage, ToolResult, TurnResult, UserMessage
33
+ from .protocol import AgentMessage, AssistantMessage, ToolResult, TurnResult, UserMessage
34
34
  from .tools.runtime_services import close_resources
35
35
  from .utils import uuid7_string
36
36
  from .utils.event_helpers import shorten_title
@@ -52,11 +52,10 @@ class SubmissionInterrupted(RuntimeError):
52
52
 
53
53
 
54
54
  class _QueuedSubmission:
55
- def __init__(self, texts: "typing.List[str]", name: "str" = "user") -> "None":
55
+ def __init__(self, messages) -> "None":
56
56
  self.submission_id = uuid7_string()
57
57
  self.turn_id = self.submission_id
58
- self.texts = texts
59
- self.name = name
58
+ self.messages = list(messages)
60
59
  self.futures: "typing.List[asyncio.Future[TurnResult]]" = []
61
60
 
62
61
 
@@ -228,12 +227,11 @@ class AgentRuntime:
228
227
  }
229
228
 
230
229
  def snapshot(self):
231
- execution = self.agent.execution_snapshot()
232
230
  rollout_path = self.agent.session_file_path
233
231
  recorded_path = self.agent.recorded_session_file_path
234
232
  return {
235
- **self._snapshot_fields(execution),
236
- "session_id": execution.session_id,
233
+ **self.state_snapshot(),
234
+ "session_id": self.agent.session_id,
237
235
  "rollout_path": str(rollout_path) if rollout_path is not None else None,
238
236
  "recorded_rollout_path": str(recorded_path) if recorded_path is not None else None,
239
237
  "model": "{0}:{1}".format(
@@ -241,9 +239,6 @@ class AgentRuntime:
241
239
  self.agent.model_client.reasoning_effort or "default",
242
240
  ),
243
241
  "history": conversation_history_to_turns(self.agent.history),
244
- "active_turn": (
245
- dict(self._active_turn) if self._active_turn is not None else None
246
- ),
247
242
  }
248
243
 
249
244
  def state_snapshot(self):
@@ -266,21 +261,14 @@ class AgentRuntime:
266
261
  "reasoning_effort": client.reasoning_effort,
267
262
  },
268
263
  "running": execution.running,
269
- "active_turn": (
270
- {
271
- key: active[key]
272
- for key in (
273
- "turn_id", "submission_id", "user_texts", "assistant_text",
274
- "model_errors",
275
- )
276
- } if active is not None else None
277
- ),
264
+ "active_turn": dict(active) if active is not None else None,
278
265
  "queued_inputs": [
279
266
  {
280
267
  "submission_id": item.submission_id,
281
268
  "turn_id": item.turn_id,
282
269
  "queue": name,
283
- "prompts": list(item.texts),
270
+ "messages": tuple(message for message in item.messages
271
+ if isinstance(message, (UserMessage, AgentMessage)) and message.visible),
284
272
  }
285
273
  for name, item in pending
286
274
  ],
@@ -515,18 +503,18 @@ class AgentRuntime:
515
503
 
516
504
  def _submit_turn(self, text, queue, sender, name):
517
505
  busy = self.is_busy
506
+ message = UserMessage(text, name=name)
518
507
  if queue == "enqueue":
519
- submission_id, future = self.enqueue(text, name=name)
508
+ submission_id, future = self.enqueue(message)
520
509
  else:
521
510
  current = self._current_submission if self.agent.is_running else None
522
511
  self.stop_asap()
523
- self.message(UserMessage(text, name=name))
512
+ self.message(message)
524
513
  submission_id, future = self.trigger()
525
- self._triggered_submission.texts.append(text)
526
514
  if current is not None:
527
515
  self._triggered_submission.turn_id = current.turn_id
528
516
  self._publish(
529
- InputQueuedEvent(submission_id, text, queue, sender, queue == "enqueue", busy)
517
+ InputQueuedEvent(submission_id, message, queue, sender, queue == "enqueue", busy)
530
518
  )
531
519
  return SubmittedInput(submission_id, "turn", future)
532
520
 
@@ -643,7 +631,7 @@ class AgentRuntime:
643
631
 
644
632
  async def submit_user_turn(self, text: "str") -> "TurnResult":
645
633
  """Enqueue one independent turn and wait for its receipt."""
646
- _submission_id, future = self.enqueue(text)
634
+ _submission_id, future = self.enqueue(UserMessage(text))
647
635
  return await future
648
636
 
649
637
  async def maybe_invoke(self, event: "typing.Dict[str, object]") -> "bool":
@@ -662,7 +650,6 @@ class AgentRuntime:
662
650
  await self.start()
663
651
  self.message(text)
664
652
  _submission_id, future = self.trigger()
665
- self._triggered_submission.texts.append(text)
666
653
  await future
667
654
  return True
668
655
 
@@ -682,11 +669,11 @@ class AgentRuntime:
682
669
  self._last_agent_status = "interrupted"
683
670
  self.publish_update("interrupt")
684
671
 
685
- def enqueue(self, text: "str", name: "str" = "user") -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
672
+ def enqueue(self, message: "UserMessage") -> "typing.Tuple[str, asyncio.Future[TurnResult]]":
686
673
  """Schedule an independent user turn without affecting active execution."""
687
674
  if not self.accepts_input:
688
675
  raise RuntimeError("agent is shutting down")
689
- queued = _QueuedSubmission([text], name=name)
676
+ queued = _QueuedSubmission([message])
690
677
  self._enqueue_queue.append(queued)
691
678
  return self._submission_receipt(queued)
692
679
 
@@ -697,7 +684,7 @@ class AgentRuntime:
697
684
  if self._active_turn is not None and not self.agent.execution_snapshot().stop_requested:
698
685
  return None
699
686
  if self._triggered_submission is None:
700
- self._triggered_submission = _QueuedSubmission([])
687
+ self._triggered_submission = _QueuedSubmission(self._take_messages())
701
688
  return self._submission_receipt(self._triggered_submission)
702
689
 
703
690
  def _submission_receipt(self, queued):
@@ -705,7 +692,7 @@ class AgentRuntime:
705
692
  future = loop.create_future()
706
693
  future.add_done_callback(self._observe_completion)
707
694
  queued.futures.append(future)
708
- # Publish after the input layer attaches display text and turn identity.
695
+ # Publish after the input layer attaches the execution identity.
709
696
  loop.call_soon(self._notify_queue_change)
710
697
  return queued.submission_id, future
711
698
 
@@ -716,22 +703,35 @@ class AgentRuntime:
716
703
  self.publish_update("queue")
717
704
  self._wake_worker()
718
705
 
719
- def message(self, text: "typing.Union[str, AgentMessage, ToolResult]") -> "None":
706
+ def message(self, text: "typing.Union[str, UserMessage, AgentMessage, ToolResult]") -> "None":
720
707
  """Deliver input to an open runtime's mailbox."""
721
708
  if not self.accepts_input:
722
709
  raise RuntimeError("agent is shutting down")
723
- self._steer_queue.append(UserMessage(text) if isinstance(text, str) else text)
710
+ item = UserMessage(text) if isinstance(text, str) else text
711
+ if self._triggered_submission is not None:
712
+ self._triggered_submission.messages.append(item)
713
+ else:
714
+ self._steer_queue.append(item)
724
715
  if self._active_turn is not None:
725
716
  self.agent.request_follow_up()
726
717
  if self._input_activity is not None:
727
718
  self._input_activity.set()
728
719
 
720
+ def _take_messages(self):
721
+ messages = tuple(self._steer_queue)
722
+ self._steer_queue.clear()
723
+ return messages
724
+
729
725
  def _deliver_messages(self):
730
726
  if not self._steer_queue or self.agent.execution_snapshot().stop_requested:
731
727
  return
732
- self.agent.receive_messages(tuple(self._steer_queue))
733
- self._steer_queue.clear()
734
- if self._input_activity is not None and not self._wait_interrupted:
728
+ messages = self._take_messages()
729
+ try:
730
+ self.agent.receive_messages(messages)
731
+ except BaseException:
732
+ self._steer_queue.extendleft(reversed(messages))
733
+ raise
734
+ if self._input_activity is not None and not self._steer_queue and not self._wait_interrupted:
735
735
  self._input_activity.clear()
736
736
 
737
737
  async def wait_for_activity(self, timeout_ms):
@@ -760,10 +760,10 @@ class AgentRuntime:
760
760
  pending = await self._next_submission()
761
761
  if pending is None:
762
762
  break
763
- queued, texts = pending
763
+ queued = pending
764
764
  self._current_submission = queued
765
765
  try:
766
- result = await self.agent.run_turn(texts, turn_id=queued.turn_id, name=queued.name)
766
+ result = await self.agent.run_turn(queued.messages, turn_id=queued.turn_id)
767
767
  except TurnInterrupted:
768
768
  self._finish_submission_exception(queued, SubmissionInterrupted())
769
769
  except Exception as exc:
@@ -788,17 +788,18 @@ class AgentRuntime:
788
788
  self._publish(SessionClosedEvent())
789
789
  self.agents_manager.unregister_runtime(self.agent.agent_id)
790
790
 
791
- async def _next_submission(self) -> "typing.Union[typing.Tuple[_QueuedSubmission, typing.List[str]], None]":
791
+ async def _next_submission(self) -> "typing.Union[_QueuedSubmission, None]":
792
792
  while True:
793
793
  await self.agent.wait_until_idle()
794
794
  if not self.accepts_input:
795
795
  return None
796
796
  if self._triggered_submission is not None:
797
797
  queued, self._triggered_submission = self._triggered_submission, None
798
- return queued, []
798
+ return queued
799
799
  if self._enqueue_queue:
800
800
  queued = self._enqueue_queue.popleft()
801
- return queued, list(queued.texts)
801
+ queued.messages[:0] = self._take_messages()
802
+ return queued
802
803
  if not self._steer_queue:
803
804
  continuation = self.agent.tool_registry.runtime_environment.take_continuation()
804
805
  if continuation is not None:
@@ -809,8 +810,7 @@ class AgentRuntime:
809
810
  or self._enqueue_queue or self._steer_queue
810
811
  ):
811
812
  continue
812
- self.message(continuation)
813
- return _QueuedSubmission([]), []
813
+ return _QueuedSubmission([continuation])
814
814
  self._queue_event.clear()
815
815
  await self._queue_event.wait()
816
816
 
@@ -843,9 +843,6 @@ class AgentRuntime:
843
843
  event = replace(
844
844
  event, submission_id=event.submission_id or queued.submission_id
845
845
  )
846
- if isinstance(event, TurnStartedEvent):
847
- # Triggered input is delivered through steer, not run_turn's texts.
848
- event = replace(event, user_texts=tuple(queued.texts))
849
846
  if isinstance(event, (TurnStartedEvent, CompactStartedEvent)):
850
847
  self._wait_interrupted = False
851
848
  if self._input_activity is not None and not self._steer_queue:
@@ -865,30 +862,28 @@ class AgentRuntime:
865
862
  self._active_turn = {
866
863
  "turn_id": event.turn_id,
867
864
  "submission_id": event.submission_id or event.turn_id,
868
- "user_text": "\n".join(event.user_texts),
869
- "user_texts": list(event.user_texts),
865
+ "messages": event.messages,
870
866
  "assistant_text": "",
871
- "completed_history": conversation_history_to_turns(self.agent.history),
872
867
  "model_errors": [],
873
868
  }
874
869
  elif self._active_turn is not None:
875
870
  if isinstance(event, AssistantDeltaEvent):
876
871
  self._active_turn["assistant_text"] += event.delta
872
+ elif isinstance(event, MessagesAddedEvent) and any(
873
+ isinstance(message, AssistantMessage) for message in event.messages
874
+ ):
875
+ self._active_turn["assistant_text"] = ""
877
876
  elif isinstance(event, StreamErrorEvent):
878
877
  self._active_turn["assistant_text"] = ""
879
878
  self._active_turn["model_errors"].append(event.detail())
880
879
  elif isinstance(event, ToolCompletedEvent):
881
880
  self._active_turn["assistant_text"] = ""
882
- elif isinstance(event, AutoCompactCompletedEvent):
883
- self._active_turn["completed_history"] = conversation_history_to_turns(
884
- self.agent.history
885
- )
886
881
  elif isinstance(
887
882
  event, (TurnCompletedEvent, TurnFailedEvent, TurnInterruptedEvent)
888
883
  ):
889
884
  self._active_turn = None
890
885
  if isinstance(event, TurnStartedEvent) and not self.title:
891
- prompt = "\n".join(event.user_texts)
886
+ prompt = event.visualize()
892
887
  if prompt:
893
888
  self.title = shorten_title(prompt)
894
889
  self.publish_state("auto_title")
pycodex/tools/__init__.py CHANGED
@@ -10,7 +10,7 @@ from ..protocol import qualified_tool_name
10
10
  from .apply_patch_tool import ApplyPatchTool
11
11
  from .base_tool import BaseTool, Registry, ToolContext, ToolRegistry
12
12
  from .clock_manager import ClockManager
13
- from .clock_tool import ClockTool
13
+ from .clock_tool import SetPeriodTool, SleepTool
14
14
  from .code_mode_manager import CodeModeManager
15
15
  from .exec_command_tool import ExecCommandTool
16
16
  from .exec_tool import ExecTool
@@ -22,7 +22,6 @@ from .list_agents_tool import ListAgentsTool
22
22
  from .list_dir_tool import ListDirTool
23
23
  from .read_file_tool import ReadFileTool
24
24
  from .request_permissions_tool import RequestPermissionsTool
25
- from .request_user_input_tool import RequestUserInputTool
26
25
  from .runtime_services import (
27
26
  AgentRuntimeEnvironment,
28
27
  create_agent_runtime_environment,
@@ -60,7 +59,6 @@ def get_tools(
60
59
  GetGoalTool(runtime_environment.goal_manager),
61
60
  UpdateGoalTool(runtime_environment.goal_manager),
62
61
  )
63
- request_user_input_tool = RequestUserInputTool()
64
62
  agent_tools = (
65
63
  SpawnAgentTool(agents_manager),
66
64
  SendMessageTool(agents_manager),
@@ -72,15 +70,16 @@ def get_tools(
72
70
  apply_patch_tool = ApplyPatchTool()
73
71
  exec_command_tool = ExecCommandTool(unified_exec_manager)
74
72
  write_stdin_tool = WriteStdinTool(unified_exec_manager)
75
- clock_tool = ClockTool(clock_manager)
73
+ set_period_tool = SetPeriodTool(clock_manager)
74
+ sleep_tool = SleepTool(agents_manager)
76
75
  view_image_tool = ViewImageTool()
77
76
  tools = (
78
77
  exec_tool,
79
78
  wait_tool,
80
79
  exec_command_tool,
81
80
  write_stdin_tool,
82
- clock_tool,
83
- request_user_input_tool,
81
+ set_period_tool,
82
+ sleep_tool,
84
83
  apply_patch_tool,
85
84
  view_image_tool,
86
85
  ) + goal_tools + agent_tools
@@ -110,9 +109,9 @@ def get_tools(
110
109
  )
111
110
  elif tool is exec_command_tool:
112
111
  runtime_environment.register_resource(tool.name, unified_exec_manager)
113
- elif tool is clock_tool:
112
+ elif tool is set_period_tool:
114
113
  runtime_environment.register_resource(
115
- tool.name, clock_manager, observer=clock_manager.handle_agent_event,
114
+ "clock", clock_manager, observer=clock_manager.handle_agent_event,
116
115
  )
117
116
  return registry
118
117
 
@@ -121,7 +120,6 @@ __all__ = [
121
120
  "ApplyPatchTool",
122
121
  "BaseTool",
123
122
  "ClockManager",
124
- "ClockTool",
125
123
  "CodeModeManager",
126
124
  "CreateGoalTool",
127
125
  "ExecTool",
@@ -136,10 +134,11 @@ __all__ = [
136
134
  "ReadFileTool",
137
135
  "Registry",
138
136
  "RequestPermissionsTool",
139
- "RequestUserInputTool",
140
137
  "SendMessageTool",
138
+ "SetPeriodTool",
141
139
  "ShellCommandTool",
142
140
  "ShellTool",
141
+ "SleepTool",
143
142
  "SpawnAgentTool",
144
143
  "ToolContext",
145
144
  "ToolRegistry",
@@ -1,10 +1,10 @@
1
- """Session-scoped periodic clock for waking an idle Agent.
1
+ """Periodic wake-ups and interruptible waits in the clock namespace.
2
2
 
3
- `clock` is a pycodex extension rather than an upstream Codex tool. A configured
4
- clock starts counting only after the Agent completes a reply. Every new turn
5
- cancels the pending countdown, and every successful reply starts a fresh one.
3
+ `set_period` is a local extension; `sleep` follows upstream's active-turn wait.
6
4
  """
7
5
 
6
+ from time import monotonic
7
+
8
8
  from ..protocol import JSONDict, JSONValue
9
9
  from .base_tool import BaseTool, ToolContext
10
10
  from .clock_manager import ClockManager
@@ -29,9 +29,11 @@ CLOCK_STATE_OUTPUT_SCHEMA = {
29
29
  }
30
30
 
31
31
 
32
- class ClockTool(BaseTool):
32
+ class SetPeriodTool(BaseTool):
33
33
  exec_only = False
34
- name = "clock"
34
+ name = "set_period"
35
+ namespace = "clock"
36
+ namespace_description = "Tools for waiting on time and scheduling periodic wake-ups."
35
37
  description = (
36
38
  "Set a periodic clock in minutes, or cancel it with null. After each "
37
39
  "Agent reply, the clock waits period_m minutes and then sends a "
@@ -60,5 +62,53 @@ class ClockTool(BaseTool):
60
62
  async def run(self, context: "ToolContext", args: "JSONDict") -> "JSONValue":
61
63
  del context
62
64
  if not isinstance(args, dict) or "period_m" not in args:
63
- raise ValueError("clock requires period_m")
65
+ raise ValueError("set_period requires period_m")
64
66
  return self._manager.set_period(args["period_m"])
67
+
68
+
69
+ class SleepTool(BaseTool):
70
+ name = "sleep"
71
+ namespace = "clock"
72
+ namespace_description = "Tools for waiting on time and scheduling periodic wake-ups."
73
+ exec_only = False
74
+ description = (
75
+ "Pause execution for a specified duration. The sleep ends early when new "
76
+ "input arrives for the active turn. Returns the elapsed wall-clock time."
77
+ )
78
+ input_schema = {
79
+ "type": "object",
80
+ "properties": {
81
+ "duration_ms": {
82
+ "type": "number",
83
+ "description": (
84
+ "How long to sleep in milliseconds. Must be between 1 and 43200000."
85
+ ),
86
+ },
87
+ },
88
+ "required": ["duration_ms"],
89
+ "additionalProperties": False,
90
+ }
91
+ supports_parallel = False
92
+
93
+ def __init__(self, agents_manager):
94
+ self._agents_manager = agents_manager
95
+
96
+ async def run(self, context, args):
97
+ if set(args) != {"duration_ms"}:
98
+ raise ValueError("sleep requires only duration_ms")
99
+ duration_ms = args["duration_ms"]
100
+ if type(duration_ms) is not int:
101
+ raise ValueError("duration_ms must be an integer")
102
+ if not 1 <= duration_ms <= 43200000:
103
+ raise ValueError("duration_ms must be between 1 and 43200000")
104
+ started = monotonic()
105
+ result = await self._agents_manager.wait_for_activity(
106
+ context.agent_id, duration_ms,
107
+ )
108
+ message = (
109
+ "Sleep completed." if result["timed_out"]
110
+ else "Sleep interrupted by new input."
111
+ )
112
+ return "Wall time: {0:.4f} seconds\n{1}".format(
113
+ monotonic() - started, message,
114
+ )
@@ -1,6 +1,5 @@
1
1
  """In-process Python cells with expression display and asyncio task ownership."""
2
2
 
3
- import ast
4
3
  import asyncio
5
4
  import base64
6
5
  import builtins
@@ -8,14 +7,26 @@ from copy import deepcopy
8
7
  import inspect
9
8
  import io
10
9
  import json
11
- import math
12
- import tokenize
13
10
  import traceback
14
11
  from types import SimpleNamespace
15
12
  import wave
16
13
 
14
+ from ..utils.compat import compile_async_cell
17
15
  from .python_tool_schema import python_tool_signature
18
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
+
19
30
 
20
31
  class CellTaskFactory:
21
32
  """Track descendants of cell tasks without owning the host's tool tasks.
@@ -99,11 +110,8 @@ class ExecRuntime:
99
110
  self._next_request_id = 0
100
111
  self._tasks = set()
101
112
  self._tool_tasks = []
102
- self._timers = set()
103
113
  self._factory = None
104
114
  self._main_task = None
105
- self._background_error = None
106
- self._exited = False
107
115
  self._stop_requested = False
108
116
  self._closing = False
109
117
 
@@ -204,47 +212,6 @@ class ExecRuntime:
204
212
  self.send({"type": "yield"})
205
213
  await asyncio.sleep(0)
206
214
 
207
- def set_timeout(self, callback, delay_ms=0):
208
- if self._stop_requested or self._closing:
209
- raise RuntimeError("exec cell is stopping")
210
- if not callable(callback):
211
- raise TypeError("set_timeout expects a callable")
212
- if (
213
- isinstance(delay_ms, bool) or not isinstance(delay_ms, (int, float))
214
- or not math.isfinite(delay_ms) or delay_ms < 0
215
- ):
216
- raise ValueError("delay_ms must be a finite non-negative number")
217
-
218
- async def invoke():
219
- try:
220
- result = callback()
221
- if inspect.isawaitable(result):
222
- await result
223
- except asyncio.CancelledError:
224
- raise
225
- except BaseException as error:
226
- # Catch control-flow exceptions before they reach asyncio.Task.
227
- if isinstance(error, ExecExit):
228
- self._exited = True
229
- else:
230
- self._background_error = "".join(traceback.format_exception(
231
- type(error), error, error.__traceback__,
232
- ))
233
- self._main_task.cancel()
234
-
235
- def fire():
236
- self._timers.discard(handle)
237
- self._factory.create_task(invoke(), self)
238
-
239
- handle = self._loop.call_later(delay_ms / 1000.0, fire)
240
- self._timers.add(handle)
241
- return handle
242
-
243
- def clear_timeout(self, handle=None):
244
- if handle is not None:
245
- handle.cancel()
246
- self._timers.discard(handle)
247
-
248
215
  def _tool_caller(self, spec):
249
216
  signature = python_tool_signature(spec)
250
217
 
@@ -271,27 +238,6 @@ class ExecRuntime:
271
238
  # Once issued, host tool calls finish even if the cell is cancelled.
272
239
  return deepcopy(await asyncio.shield(task))
273
240
 
274
- def _compile_source(self):
275
- source = self._source.replace("\r\n", "\n").replace("\r", "\n")
276
- string_lines = set()
277
- for token in tokenize.generate_tokens(io.StringIO(source).readline):
278
- if tokenize.tok_name[token.type] in ("STRING", "FSTRING_MIDDLE", "TSTRING_MIDDLE"):
279
- string_lines.update(range(token.start[0], token.end[0]))
280
- # Indent code into an async body without changing multiline string contents.
281
- source = "async def __exec_cell__():\n" + "\n".join(
282
- line if index in string_lines else " " + line
283
- for index, line in enumerate(source.split("\n"))
284
- ) + "\n pass\n"
285
- tree = ast.parse(source, filename="<exec>")
286
- body = tree.body[0].body
287
- # The trailing pass keeps comment-only cells valid.
288
- if len(body) > 1 and isinstance(body[-2], ast.Expr):
289
- expression = body[-2]
290
- body[-2] = ast.copy_location(ast.Return(value=expression.value), expression)
291
- for statement in body:
292
- ast.increment_lineno(statement, -1)
293
- return compile(tree, "<exec>", "exec")
294
-
295
241
  async def run(self):
296
242
  if self._stop_requested:
297
243
  return None
@@ -304,13 +250,14 @@ class ExecRuntime:
304
250
  )
305
251
  namespace = {
306
252
  "__name__": "__codex_exec__",
307
- "__builtins__": dict(vars(builtins), print=self.print),
253
+ "__builtins__": dict(
254
+ vars(builtins), print=self.print, __import__=_guarded_import,
255
+ ),
308
256
  "cwd": self._cwd,
309
257
  "asyncio": asyncio,
310
258
  "text": self.text, "image": self.image, "audio": self.audio,
311
259
  "generated_image": self.generated_image,
312
260
  "store": self.store, "load": self.load, "notify": self.notify,
313
- "set_timeout": self.set_timeout, "clear_timeout": self.clear_timeout,
314
261
  "exit": self.exit, "yield_control": self.yield_control,
315
262
  "ALL_TOOLS": tuple(
316
263
  {
@@ -330,14 +277,11 @@ class ExecRuntime:
330
277
  try:
331
278
  error_text = await self._main_task
332
279
  except asyncio.CancelledError:
333
- if not self._stop_requested and not self._exited:
334
- error_text = self._background_error or "exec cell was cancelled"
280
+ if not self._stop_requested:
281
+ error_text = "exec cell was cancelled"
335
282
  finally:
336
283
  self._closing = True
337
284
  try:
338
- for handle in self._timers:
339
- handle.cancel()
340
- self._timers.clear()
341
285
  # A cancelled task's finally block can create another task.
342
286
  while True:
343
287
  pending = [task for task in self._tasks if not task.done()]
@@ -361,12 +305,19 @@ class ExecRuntime:
361
305
  self._tasks.clear()
362
306
  self._tool_tasks.clear()
363
307
  self._factory.release()
364
- return error_text or self._background_error
308
+ return error_text
365
309
 
366
310
  async def _execute(self, namespace):
367
311
  try:
368
- exec(self._compile_source(), namespace)
369
- result = await namespace.pop("__exec_cell__")()
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)
370
321
  if result is not None:
371
322
  output = repr(result)
372
323
  self._writer.flush()
@@ -42,9 +42,8 @@ class ExecTool(BaseTool):
42
42
  "`await asyncio.gather(..., return_exceptions=True)` to inspect every "
43
43
  "success and failure. Keep dependent operations sequential.\n"
44
44
  "- `asyncio` and the Python standard library are available. Tasks created "
45
- "through asyncio from cell tasks, and timers created with `set_timeout`, "
46
- "are cleaned up when the script finishes. Already issued host tool calls "
47
- "finish before the cell is closed.\n"
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"
48
47
  "- Execution and stopping are cooperative. Use async operations and run "
49
48
  "blocking work through tools.exec_command. Synchronous code blocks the host; "
50
49
  "a non-yielding loop cannot be stopped independently. Imported modules and "
@@ -72,9 +71,6 @@ class ExecTool(BaseTool):
72
71
  "values across exec cells in this session; a missing key returns None.\n"
73
72
  "- `notify(value)`: immediately submit an additional output for this exec "
74
73
  "call through the attached Runtime.\n"
75
- "- `set_timeout(callback, delay_ms=0)` / `clear_timeout(handle)`: schedule "
76
- "or cancel a callback; timers alone do not keep the script alive. Use "
77
- "`await asyncio.sleep(seconds)` to wait.\n"
78
74
  "- `await yield_control()`: return accumulated output to the model while "
79
75
  "the script continues running.\n"
80
76
  "- `exit()`: finish the current script successfully.\n"