python-codex 0.6.0__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.
pycodex/__init__.py CHANGED
@@ -42,7 +42,6 @@ from .tools import (
42
42
  ApplyPatchTool,
43
43
  BaseTool,
44
44
  ClockManager,
45
- ClockTool,
46
45
  CodeModeManager,
47
46
  ExecCommandTool,
48
47
  ExecTool,
@@ -54,10 +53,11 @@ from .tools import (
54
53
  ReadFileTool,
55
54
  Registry,
56
55
  RequestPermissionsTool,
57
- RequestUserInputTool,
58
56
  SendMessageTool,
57
+ SetPeriodTool,
59
58
  ShellCommandTool,
60
59
  ShellTool,
60
+ SleepTool,
61
61
  SpawnAgentTool,
62
62
  ToolContext,
63
63
  ToolRegistry,
@@ -84,7 +84,6 @@ __all__ = [
84
84
  "AssistantMessage",
85
85
  "BaseTool",
86
86
  "ClockManager",
87
- "ClockTool",
88
87
  "create_agent_runtime_environment",
89
88
  "CodeModeManager",
90
89
  "CodexConfig",
@@ -105,7 +104,6 @@ __all__ = [
105
104
  "Registry",
106
105
  "ReadFileTool",
107
106
  "RequestPermissionsTool",
108
- "RequestUserInputTool",
109
107
  "ModelResponse",
110
108
  "ModelEvent",
111
109
  "PlanStore",
@@ -118,8 +116,10 @@ __all__ = [
118
116
  "ResponsesModelClient",
119
117
  "ResponsesProviderConfig",
120
118
  "SendMessageTool",
119
+ "SetPeriodTool",
121
120
  "ShellCommandTool",
122
121
  "ShellTool",
122
+ "SleepTool",
123
123
  "SpawnAgentTool",
124
124
  "ToolCall",
125
125
  "ToolContext",
pycodex/bootstrap.py CHANGED
@@ -90,20 +90,18 @@ def build_model(
90
90
  timeout_seconds: "float" = 120.0,
91
91
  managed_responses_base_url: "typing.Union[str, None]" = None,
92
92
  vllm_endpoint: "typing.Union[str, None]" = None,
93
- use_chat_completion: "typing.Union[bool, None]" = None,
94
- use_messages: "bool" = False,
95
93
  ) -> "ModelBootstrapResult":
96
- if use_chat_completion is None:
97
- use_chat_completion = bool(provider_config.use_chat_completion)
98
- if use_chat_completion and use_messages:
99
- raise ValueError("--use-chat-completion and --use-messages cannot be combined")
100
- if vllm_endpoint and use_messages:
101
- raise ValueError("--vllm-endpoint and --use-messages cannot be combined")
94
+ compat_api = provider_config.compat_api
95
+ if vllm_endpoint is not None and compat_api not in ("none", "chat_completions"):
96
+ raise ValueError("--vllm-endpoint cannot be combined with compat_api=" + compat_api)
97
+ if managed_responses_base_url is not None and (
98
+ vllm_endpoint is not None or compat_api != "none"
99
+ ):
100
+ raise ValueError("a managed Responses endpoint cannot be combined with compat_api or --vllm-endpoint")
102
101
  uses_local_responses_compat = (
103
102
  managed_responses_base_url is not None
104
103
  or vllm_endpoint is not None
105
- or bool(use_chat_completion)
106
- or use_messages
104
+ or compat_api != "none"
107
105
  )
108
106
  if vllm_endpoint is not None:
109
107
  provider_config = replace(
@@ -122,7 +120,7 @@ def build_model(
122
120
  LOCAL_RESPONSES_SERVER_API_KEY_ENV,
123
121
  )
124
122
  os.environ.setdefault(LOCAL_RESPONSES_SERVER_API_KEY_ENV, "dummy")
125
- elif vllm_endpoint or use_chat_completion or use_messages:
123
+ elif vllm_endpoint is not None or compat_api != "none":
126
124
  if vllm_endpoint:
127
125
  managed_server = launch_chat_completion_compat_server(
128
126
  vllm_endpoint,
@@ -133,7 +131,7 @@ def build_model(
133
131
  provider_config.base_url,
134
132
  provider_config.api_key_env,
135
133
  model_provider=provider_config.provider_name,
136
- outcomming_api=("messages" if use_messages else "chat_completions"),
134
+ outcomming_api=compat_api,
137
135
  )
138
136
  url, key_env = (
139
137
  managed_server.base_url,
pycodex/cli.py CHANGED
@@ -62,18 +62,6 @@ def build_parser():
62
62
  default=None,
63
63
  help="Start a local responses compat server for a chat-completions-backed vLLM endpoint.",
64
64
  )
65
- parser.add_argument(
66
- "--use-chat-completion",
67
- default=False,
68
- action="store_true",
69
- help="Start a local responses compat server for this session.",
70
- )
71
- parser.add_argument(
72
- "--use-messages",
73
- default=False,
74
- action="store_true",
75
- help="Route the local responses compat server to a downstream /v1/messages backend.",
76
- )
77
65
  parser.add_argument(
78
66
  "--system-prompt",
79
67
  default=None,
@@ -150,8 +138,6 @@ async def run_cli(args):
150
138
  config.provider,
151
139
  timeout_seconds=args.timeout_seconds,
152
140
  vllm_endpoint=args.vllm_endpoint,
153
- use_chat_completion=args.use_chat_completion or None,
154
- use_messages=args.use_messages,
155
141
  )
156
142
  if bootstrap.owned_server is not None:
157
143
  atexit.register(bootstrap.owned_server.stop)
pycodex/context.py CHANGED
@@ -281,8 +281,7 @@ class ContextManager:
281
281
  input_items.extend(block)
282
282
  position = offset
283
283
  input_items.extend(history[position:])
284
- if self._fork_context is not None:
285
- input_items = _normalize_fork_calls(input_items)
284
+ input_items = _normalize_tool_calls(input_items, self._fork_context is not None)
286
285
  base_instructions = self.resolve_base_instructions()
287
286
  if capture_context:
288
287
  self._last_context = ForkContext(
@@ -799,7 +798,7 @@ class ContextManager:
799
798
  return "\n".join(lines)
800
799
 
801
800
 
802
- def _normalize_fork_calls(items):
801
+ def _normalize_tool_calls(items, complete_calls):
803
802
  call_ids = {
804
803
  (item.tool_type, item.call_id)
805
804
  for item in items if isinstance(item, ToolCall)
@@ -817,7 +816,7 @@ def _normalize_fork_calls(items):
817
816
  continue
818
817
  normalized.append(item)
819
818
  if (
820
- isinstance(item, ToolCall)
819
+ complete_calls and isinstance(item, ToolCall)
821
820
  and (item.tool_type, item.call_id) not in result_ids
822
821
  ):
823
822
  prefix = "ctco" if item.tool_type == "custom" else "fco"
pycodex/events.py CHANGED
@@ -698,7 +698,7 @@ class InputRequestedEvent(Event):
698
698
  question = self.question
699
699
  return "\n".join(
700
700
  [
701
- "[request_user_input] waiting for user response",
701
+ "[input] waiting for user response",
702
702
  "[{0}] {1}".format(question["header"], question["question"]),
703
703
  ]
704
704
  + [
pycodex/model.py CHANGED
@@ -98,7 +98,6 @@ class ResponsesProviderConfig:
98
98
  provider_name: "str"
99
99
  base_url: "str"
100
100
  api_key_env: "typing.Union[str, None]"
101
- use_chat_completion: "bool" = False
102
101
  wire_api: "str" = "responses"
103
102
  query_params: "typing.Dict[str, str]" = field(default_factory=dict)
104
103
  reasoning_effort: "typing.Union[str, None]" = None
@@ -113,8 +112,11 @@ class ResponsesProviderConfig:
113
112
  fallback_models: "typing.Tuple[str, ...]" = ()
114
113
  fallback_cooldown_seconds: "int" = 900
115
114
  stream_first_data_timeout_ms: "typing.Union[int, None]" = None
115
+ compat_api: "str" = "none"
116
116
 
117
117
  def __post_init__(self):
118
+ if self.compat_api not in ("none", "chat_completions", "messages", "gemini"):
119
+ raise ValueError("compat_api must be none, chat_completions, messages or gemini")
118
120
  cooldown = self.fallback_cooldown_seconds
119
121
  if isinstance(cooldown, bool) or not isinstance(cooldown, int) or cooldown < 0:
120
122
  raise ValueError("fallback_cooldown_seconds must be a non-negative integer")
@@ -164,11 +166,18 @@ class ResponsesProviderConfig:
164
166
  beta_features: "typing.List[str]" = []
165
167
  if isinstance(features, dict) and features.get("guardian_approval") is True:
166
168
  beta_features.append("guardian_approval")
167
- use_chat_completion = _optional_bool(selected.get("use_chat_completion"))
168
- if use_chat_completion is None:
169
- use_chat_completion = _optional_bool(provider.get("use_chat_completion"))
170
- if use_chat_completion is None:
171
- use_chat_completion = False
169
+ for key in ("use_messages", "use_gemini"):
170
+ if key in selected or key in provider:
171
+ raise ValueError(f"{key} has been removed; use compat_api instead")
172
+ compat_api = "none"
173
+ for source in (selected, provider):
174
+ if "compat_api" in source:
175
+ compat_api = source["compat_api"]
176
+ break
177
+ use_chat_completion = _optional_bool(source.get("use_chat_completion"))
178
+ if use_chat_completion is not None:
179
+ compat_api = "chat_completions" if use_chat_completion else "none"
180
+ break
172
181
  fallback_models = provider.get("fallback_models", [])
173
182
  if not isinstance(fallback_models, list) or any(
174
183
  not isinstance(model, str) or not model or any(c.isspace() for c in model)
@@ -180,7 +189,7 @@ class ResponsesProviderConfig:
180
189
  provider_name=provider_name,
181
190
  base_url=provider["base_url"],
182
191
  api_key_env=api_key_env,
183
- use_chat_completion=use_chat_completion,
192
+ compat_api=compat_api,
184
193
  wire_api=wire_api,
185
194
  query_params=query_params,
186
195
  reasoning_effort=selected.get("model_reasoning_effort"),
@@ -1814,6 +1814,20 @@
1814
1814
  "personality_pragmatic": "# Personality\n\nYou are a deeply pragmatic, effective software engineer. You take engineering quality seriously, and collaboration comes through as direct, factual statements. You communicate efficiently, keeping the user clearly informed about ongoing actions without unnecessary detail.\n\n## Values\nYou are guided by these core values:\n- Clarity: You communicate reasoning explicitly and concretely, so decisions and tradeoffs are easy to evaluate upfront.\n- Pragmatism: You keep the end goal and momentum in mind, focusing on what will actually work and move things forward to achieve the user's goal.\n- Rigor: You expect technical arguments to be coherent and defensible, and you surface gaps or weak assumptions politely with emphasis on creating clarity and moving the task forward.\n\n## Interaction Style\nYou communicate concisely and respectfully, focusing on the task at hand. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\nYou avoid cheerleading, motivational language, or artificial reassurance, or any kind of fluff. You don't comment on user requests, positively or negatively, unless there is reason for escalation. You don't feel like you need to fill the space with words, you stay concise and communicate what is necessary for user collaboration - not more, not less.\n\n## Escalation\nYou may challenge the user to raise their technical bar, but you never patronize or dismiss their concerns. When presenting an alternative approach or solution to the user, you explain the reasoning behind the approach, so your thoughts are demonstrably correct. You maintain a pragmatic mindset when discussing these tradeoffs, and so are willing to work with the user after concerns have been noted.\n"
1815
1815
  }
1816
1816
  }
1817
+ },
1818
+ {
1819
+ "slug": "gemini-4-argon",
1820
+ "display_name": "Gemini 4 Argon",
1821
+ "description": "Local Gemini 4 Argon prompt adapted from Antigravity CLI 1.4.12.",
1822
+ "visibility": "hide",
1823
+ "model_messages": {
1824
+ "instructions_template": "You are Codex, a coding agent based on Gemini 4 Argon. You and the user share the same workspace and collaborate to achieve the user's goals.\n\n{{ personality }}\n\n# Role and workflow\n\nYou are pair programming with the user to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question. Prioritize addressing the user's request.\n\n- Read the relevant code and repository instructions before making changes. Build context from the actual workspace rather than assuming how the project works.\n- When the user asks you to implement or fix something, carry the work through implementation, appropriate verification, and a clear explanation of the result.\n- Follow the current run's autonomy, approval, and collaboration instructions. Work independently within the authorized scope; ask for clarification when missing information prevents progress.\n- Keep changes focused on the task and consistent with the project's existing conventions. Preserve unrelated user changes and existing comments unless the task requires changing them.\n- Run checks appropriate to the change. Report what was verified and any remaining limitations; do not claim success without evidence.\n\n# Tools\n\nUse only tools exposed in the current request, with the exact names and argument schemas in their definitions. Follow each tool's documented execution interface, including whether it is called directly or through exec.\n\nYou support batch function calling. When you need to execute multiple operations that are independent of each other, you SHOULD call multiple tools in parallel in a single turn. This is much more efficient than calling them sequentially.\n\nIndependent operations include:\n- Reading multiple files\n- Running multiple searches\n- Executing multiple independent commands\n- Checking status of multiple resources\n\nDo NOT batch operations if they depend on the output of a previous operation in the same batch.\n\n- Prefer `rg` or `rg --files` for text and file searches.\n- Use the available dedicated editing tool, such as `apply_patch`, for manual code edits.\n- Inspect the working tree before editing. Preserve changes you did not make, and avoid destructive Git commands unless explicitly authorized.\n- If an operation is blocked by sandbox restrictions, permissions, or a missing resource, do not try to work around the boundary by switching tools, paths, or services. Use an explicitly authorized alternative or explain what is needed to continue.\n- The runtime supplies available skills, workspace information, and tool guidance. Use those actual instructions and resources rather than assuming another harness's tools or directories exist.\n\n# Communication\n\n- Keep responses concise and use GitHub-flavored Markdown.\n- Give short progress updates in the commentary channel while working. State what you have learned and what you will do next.\n- Use the final channel to report the result, relevant verification, and any unresolved issue.\n- Use clickable Markdown links for file references, with absolute filesystem paths and an optional line number, such as [app.py](/workspace/app.py:42).\n- Match the amount of explanation to the task. Prefer short paragraphs for simple changes and lists when comparing or enumerating several items.\n",
1825
+ "instructions_variables": {
1826
+ "personality_default": "",
1827
+ "personality_friendly": "# Personality\n\nYou optimize for team morale and being a supportive teammate as much as code quality. You are consistent, reliable, and kind. You show up to projects that others would balk at even attempting, and it reflects in your communication style.\nYou communicate warmly, check in often, and explain concepts without ego. You excel at pairing, onboarding, and unblocking others. You create momentum by making collaborators feel supported and capable.\n\n## Values\nYou are guided by these core values:\n* Empathy: Interprets empathy as meeting people where they are - adjusting explanations, pacing, and tone to maximize understanding and confidence.\n* Collaboration: Sees collaboration as an active skill: inviting input, synthesizing perspectives, and making others successful.\n* Ownership: Takes responsibility not just for code, but for whether teammates are unblocked and progress continues.\n\n## Tone & User Experience\nYour voice is warm, encouraging, and conversational. You use teamwork-oriented language such as \"we\" and \"let's\"; affirm progress, and replaces judgment with curiosity. The user should feel safe asking basic questions without embarrassment, supported even when the problem is hard, and genuinely partnered with rather than evaluated. Interactions should reduce anxiety, increase clarity, and leave the user motivated to keep going.\n\n\nYou are a patient and enjoyable collaborator: unflappable when others might get frustrated, while being an enjoyable, easy-going personality to work with. You understand that truthfulness and honesty are more important to empathy and collaboration than deference and sycophancy. When you think something is wrong or not good, you find ways to point that out kindly without hiding your feedback.\n\nYou never make the user work for you. You can ask clarifying questions only when they are substantial. Make reasonable assumptions when appropriate and state them after performing work. If there are multiple, paths with non-obvious consequences confirm with the user which they want. Avoid open-ended questions, and prefer a list of options when possible.\n\n## Escalation\nYou escalate gently and deliberately when decisions have non-obvious consequences or hidden risk. Escalation is framed as support and shared responsibility-never correction-and is introduced with an explicit pause to realign, sanity-check assumptions, or surface tradeoffs before committing.\n",
1828
+ "personality_pragmatic": "# Personality\n\nYou are a deeply pragmatic, effective software engineer. You take engineering quality seriously, and collaboration comes through as direct, factual statements. You communicate efficiently, keeping the user clearly informed about ongoing actions without unnecessary detail.\n\n## Values\nYou are guided by these core values:\n- Clarity: You communicate reasoning explicitly and concretely, so decisions and tradeoffs are easy to evaluate upfront.\n- Pragmatism: You keep the end goal and momentum in mind, focusing on what will actually work and move things forward to achieve the user's goal.\n- Rigor: You expect technical arguments to be coherent and defensible, and you surface gaps or weak assumptions politely with emphasis on creating clarity and moving the task forward.\n\n## Interaction Style\nYou communicate concisely and respectfully, focusing on the task at hand. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\nYou avoid cheerleading, motivational language, or artificial reassurance, or any kind of fluff. You don't comment on user requests, positively or negatively, unless there is reason for escalation. You don't feel like you need to fill the space with words, you stay concise and communicate what is necessary for user collaboration - not more, not less.\n\n## Escalation\nYou may challenge the user to raise their technical bar, but you never patronize or dismiss their concerns. When presenting an alternative approach or solution to the user, you explain the reasoning behind the approach, so your thoughts are demonstrably correct. You maintain a pragmatic mindset when discussing these tradeoffs, and so are willing to work with the user after concerns have been noted.\n"
1829
+ }
1830
+ }
1817
1831
  }
1818
1832
  ]
1819
1833
  }
pycodex/protocol.py CHANGED
@@ -93,6 +93,7 @@ class UserMessage:
93
93
  id: "typing.Union[str, None]" = None
94
94
  # Local history metadata; serialize() is the model-facing representation.
95
95
  name: "str" = "user"
96
+ visible: "bool" = True
96
97
 
97
98
  def serialize(self) -> "JSONDict":
98
99
  payload = {
@@ -114,6 +115,7 @@ class AgentMessage:
114
115
  content_items: "typing.Tuple[JSONDict, ...]"
115
116
  id: "typing.Union[str, None]" = None
116
117
  internal_chat_message_metadata_passthrough: "typing.Union[JSONDict, None]" = None
118
+ visible: "bool" = False
117
119
 
118
120
  @property
119
121
  def text(self) -> "str":
@@ -164,6 +166,7 @@ class AssistantMessage:
164
166
  id: "typing.Union[str, None]" = None
165
167
  phase: "typing.Union[str, None]" = None
166
168
  content_items: "typing.Union[typing.Tuple[JSONDict, ...], None]" = None
169
+ visible: "bool" = True
167
170
 
168
171
  @classmethod
169
172
  def from_response_item(cls, payload: "JSONDict") -> "AssistantMessage":
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"