python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. pycodex/__init__.py +22 -12
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +37 -251
  4. pycodex/cli.py +19 -28
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +368 -51
  7. pycodex/events.py +14 -187
  8. pycodex/model.py +197 -95
  9. pycodex/multi_agents.py +401 -0
  10. pycodex/portable/__init__.py +8 -6
  11. pycodex/portable/client.py +24 -39
  12. pycodex/portable/protocol.py +28 -0
  13. pycodex/portable/server.py +3 -3
  14. pycodex/prompts/developer_messages.json +13 -0
  15. pycodex/prompts/goals/budget_limit.md +19 -0
  16. pycodex/prompts/goals/continuation.md +56 -0
  17. pycodex/prompts/models.json +1143 -200
  18. pycodex/protocol.py +81 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +102 -10
  21. pycodex/tools/agent_tool_schemas.py +0 -38
  22. pycodex/tools/apply_patch_tool.py +17 -34
  23. pycodex/tools/base_tool.py +63 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +58 -187
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +332 -0
  29. pycodex/tools/exec_tool.py +74 -31
  30. pycodex/tools/followup_task_tool.py +44 -0
  31. pycodex/tools/goal_manager.py +205 -0
  32. pycodex/tools/goal_tool.py +126 -0
  33. pycodex/tools/interrupt_agent_tool.py +48 -0
  34. pycodex/tools/list_agents_tool.py +66 -0
  35. pycodex/tools/python_tool_schema.py +141 -0
  36. pycodex/tools/request_permissions_tool.py +1 -0
  37. pycodex/tools/runtime_services.py +122 -450
  38. pycodex/tools/send_message_tool.py +42 -0
  39. pycodex/tools/spawn_agent_tool.py +55 -94
  40. pycodex/tools/unified_exec_manager.py +26 -35
  41. pycodex/tools/wait_agent_tool.py +46 -66
  42. pycodex/tools/wait_tool.py +24 -13
  43. pycodex/tools/web_search_tool.py +1 -0
  44. pycodex/utils/codex_config.py +105 -0
  45. pycodex/utils/compactor.py +4 -0
  46. pycodex/utils/compat.py +43 -2
  47. pycodex/utils/doctor.py +5 -4
  48. pycodex/utils/dotenv.py +0 -7
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +59 -0
  51. pycodex/utils/session_persist.py +104 -48
  52. python_codex-0.6.1.dist-info/METADATA +201 -0
  53. python_codex-0.6.1.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +10 -7
  56. responses_server/config.py +6 -12
  57. responses_server/gemini_api.py +333 -0
  58. responses_server/messages_api.py +9 -1
  59. responses_server/payload_processors.py +4 -4
  60. responses_server/request_translation.py +486 -0
  61. responses_server/server.py +31 -24
  62. responses_server/stream_events.py +124 -0
  63. responses_server/stream_router.py +48 -830
  64. responses_server/tools/custom_adapter.py +29 -29
  65. responses_server/tools/web_search.py +3 -0
  66. responses_server/transport.py +388 -0
  67. pycodex/tools/close_agent_tool.py +0 -60
  68. pycodex/tools/exec_runtime.js +0 -161
  69. pycodex/tools/request_user_input_tool.py +0 -102
  70. pycodex/tools/resume_agent_tool.py +0 -54
  71. pycodex/tools/send_input_tool.py +0 -110
  72. python_codex-0.5.2.dist-info/METADATA +0 -262
  73. python_codex-0.5.2.dist-info/RECORD +0 -90
  74. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
  75. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
  76. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
pycodex/__init__.py CHANGED
@@ -9,12 +9,17 @@ from .model import (
9
9
  NOOP_MODEL_STREAM_EVENT_HANDLER,
10
10
  ContextLengthExceeded,
11
11
  ModelClient,
12
+ ModelControl,
13
+ ModelRecordingMetadata,
12
14
  ResponsesApiError,
13
15
  ResponsesIncompleteError,
14
16
  ResponsesModelClient,
15
17
  ResponsesProviderConfig,
16
18
  )
19
+ from .config import CodexConfig
20
+ from .multi_agents import AgentsManager
17
21
  from .protocol import (
22
+ AgentMessage,
18
23
  AssistantMessage,
19
24
  ContextMessage,
20
25
  ModelResponse,
@@ -31,28 +36,28 @@ from .tools.runtime_services import (
31
36
  PlanStore,
32
37
  RequestPermissionsManager,
33
38
  RequestUserInputManager,
34
- SubAgentManager,
35
39
  create_agent_runtime_environment,
36
40
  )
37
41
  from .tools import (
38
42
  ApplyPatchTool,
39
43
  BaseTool,
40
44
  ClockManager,
41
- ClockTool,
42
- CloseAgentTool,
43
45
  CodeModeManager,
44
46
  ExecCommandTool,
45
47
  ExecTool,
48
+ FollowupTaskTool,
46
49
  GrepFilesTool,
50
+ InterruptAgentTool,
51
+ ListAgentsTool,
47
52
  ListDirTool,
48
53
  ReadFileTool,
49
54
  Registry,
50
55
  RequestPermissionsTool,
51
- RequestUserInputTool,
52
- ResumeAgentTool,
53
- SendInputTool,
56
+ SendMessageTool,
57
+ SetPeriodTool,
54
58
  ShellCommandTool,
55
59
  ShellTool,
60
+ SleepTool,
56
61
  SpawnAgentTool,
57
62
  ToolContext,
58
63
  ToolRegistry,
@@ -71,29 +76,34 @@ __all__ = [
71
76
  "ContextLengthExceeded",
72
77
  "Event",
73
78
  "Agent",
79
+ "AgentMessage",
74
80
  "AgentRuntime",
81
+ "AgentsManager",
75
82
  "TurnInterrupted",
76
83
  "ApplyPatchTool",
77
84
  "AssistantMessage",
78
85
  "BaseTool",
79
86
  "ClockManager",
80
- "ClockTool",
81
- "CloseAgentTool",
82
87
  "create_agent_runtime_environment",
83
88
  "CodeModeManager",
89
+ "CodexConfig",
84
90
  "ContextConfig",
85
91
  "ContextManager",
86
92
  "ContextMessage",
87
93
  "ExecTool",
88
94
  "ExecCommandTool",
95
+ "FollowupTaskTool",
89
96
  "GrepFilesTool",
97
+ "InterruptAgentTool",
98
+ "ListAgentsTool",
90
99
  "ListDirTool",
91
100
  "ModelClient",
101
+ "ModelControl",
102
+ "ModelRecordingMetadata",
92
103
  "NOOP_MODEL_STREAM_EVENT_HANDLER",
93
104
  "Registry",
94
105
  "ReadFileTool",
95
106
  "RequestPermissionsTool",
96
- "RequestUserInputTool",
97
107
  "ModelResponse",
98
108
  "ModelEvent",
99
109
  "PlanStore",
@@ -101,16 +111,16 @@ __all__ = [
101
111
  "ReasoningItem",
102
112
  "RequestPermissionsManager",
103
113
  "RequestUserInputManager",
104
- "ResumeAgentTool",
105
114
  "ResponsesApiError",
106
115
  "ResponsesIncompleteError",
107
116
  "ResponsesModelClient",
108
117
  "ResponsesProviderConfig",
109
- "SendInputTool",
118
+ "SendMessageTool",
119
+ "SetPeriodTool",
110
120
  "ShellCommandTool",
111
121
  "ShellTool",
122
+ "SleepTool",
112
123
  "SpawnAgentTool",
113
- "SubAgentManager",
114
124
  "ToolCall",
115
125
  "ToolContext",
116
126
  "ToolRegistry",
pycodex/agent.py CHANGED
@@ -1,5 +1,4 @@
1
1
  import asyncio
2
- import json
3
2
  import typing
4
3
  from dataclasses import dataclass, replace
5
4
  from pathlib import Path
@@ -26,17 +25,18 @@ from .events import (
26
25
  TurnCompletedEvent,
27
26
  TurnEvent,
28
27
  TurnFailedEvent,
28
+ TurnInputReadyEvent,
29
29
  TurnInterruptedEvent,
30
30
  TurnStartedEvent,
31
31
  )
32
32
  from .model import (
33
- DEFAULT_ORIGINATOR,
34
33
  ContextLengthExceeded,
35
34
  ModelClient,
36
35
  ModelControl,
37
36
  ResponsesIncompleteError,
38
37
  )
39
38
  from .protocol import (
39
+ AgentMessage,
40
40
  AssistantMessage,
41
41
  ConversationItem,
42
42
  ModelResponse,
@@ -52,7 +52,6 @@ from .utils.session_persist import (
52
52
  SessionRolloutRecorder,
53
53
  load_resumed_session_path,
54
54
  resolve_codex_home,
55
- rollout_path_for_session,
56
55
  )
57
56
  from .utils.truncation import truncate_tool_result_for_history
58
57
 
@@ -76,6 +75,14 @@ class _TurnState:
76
75
  output_text: "typing.Union[str, None]" = None
77
76
 
78
77
 
78
+ @dataclass(frozen=True)
79
+ class ExecutionSnapshot:
80
+ session_id: "str"
81
+ running: "bool"
82
+ stop_requested: "bool"
83
+ usage_tokens: "typing.Union[int, None]"
84
+
85
+
79
86
  class Agent:
80
87
  """Minimal Python port of Codex's turn loop.
81
88
 
@@ -90,11 +97,12 @@ class Agent:
90
97
  model_client: "ModelClient",
91
98
  tool_registry: "ToolRegistry",
92
99
  context_config: "ContextConfig",
100
+ session_id: "str",
93
101
  parallel_tool_calls: "bool" = True,
94
102
  event_handler: "EventHandler" = BASE_EVENT_HANDLER,
95
103
  initial_history: "typing.Tuple[ConversationItem, ...]" = (),
96
104
  session_file_path: "typing.Union[str, Path, None]" = None,
97
- session_id: "typing.Union[str, None]" = None,
105
+ agent_path: "str" = "/root",
98
106
  ) -> "None":
99
107
  self.model_client = model_client
100
108
  self.tool_registry = tool_registry
@@ -104,14 +112,16 @@ class Agent:
104
112
  self._parallel_tool_calls = parallel_tool_calls
105
113
  self.event_handler = event_handler
106
114
  self._history: "typing.List[ConversationItem]" = list(initial_history)
107
- self._configure_recording(session_id or uuid7_string(), session_file_path)
115
+ # Agent identity stays fixed when resume changes the rollout session.
116
+ self.agent_id = session_id
117
+ self.agent_path = agent_path
118
+ self._configure_recording(session_id, session_file_path)
108
119
  self._last_total_usage_tokens: "typing.Union[int, None]" = None
109
120
  self._idle: "typing.Union[asyncio.Event, None]" = None
110
121
  self.is_shutdown = False
111
122
  self.accepts_input = True
112
123
  self._stop_requested = False
113
- for tool in self.tool_registry.tools():
114
- tool.bind_agent(self)
124
+ self._follow_up_requested = False
115
125
 
116
126
  @property
117
127
  def history(self) -> "typing.Tuple[ConversationItem, ...]":
@@ -125,14 +135,19 @@ class Agent:
125
135
  @property
126
136
  def recorded_session_file_path(self) -> "typing.Union[Path, None]":
127
137
  recorder = self._rollout_recorder
128
- if recorder is None or recorder._session_meta is not None:
129
- return None
130
- return recorder.rollout_path
138
+ return recorder.recorded_path if recorder is not None else None
131
139
 
132
140
  @property
133
141
  def is_running(self) -> "bool":
134
142
  return self._idle is not None
135
143
 
144
+ def execution_snapshot(self) -> "ExecutionSnapshot":
145
+ """Read execution facts without retaining a second lifecycle state."""
146
+ return ExecutionSnapshot(
147
+ self.session_id, self.is_running,
148
+ self._stop_requested, self._last_total_usage_tokens,
149
+ )
150
+
136
151
  async def wait_until_idle(self) -> "None":
137
152
  while self.is_running:
138
153
  await self._idle.wait()
@@ -141,6 +156,17 @@ class Agent:
141
156
  if self.is_running:
142
157
  self._stop_requested = True
143
158
 
159
+ def request_follow_up(self) -> "None":
160
+ """Keep the active turn open for input at its next safe boundary."""
161
+ if self.is_running:
162
+ self._follow_up_requested = True
163
+
164
+ def receive_messages(
165
+ self, messages: "typing.Tuple[typing.Union[UserMessage, AgentMessage, ToolResult], ...]",
166
+ ) -> "None":
167
+ """Commit messages delivered at a sampling input boundary."""
168
+ self._append_history(messages)
169
+
144
170
  @property
145
171
  def model_name(self) -> "str":
146
172
  return self.model_client.model
@@ -174,11 +200,10 @@ class Agent:
174
200
  restored_history = list(resumed["history"])
175
201
  self._configure_recording(session_id, resumed["rollout_path"], resume=True)
176
202
  self._history = restored_history
203
+ self.context_manager.reset_history_context()
177
204
  self._last_total_usage_tokens = None
178
205
  self.is_shutdown = False
179
206
  self.accepts_input = True
180
- for tool in self.tool_registry.tools():
181
- tool.bind_agent(self)
182
207
  return resumed
183
208
 
184
209
  def ask(self, text: "str") -> "TurnResult":
@@ -186,18 +211,6 @@ class Agent:
186
211
 
187
212
  return run_async(self.run_turn([text]))
188
213
 
189
- def fork(self) -> "None":
190
- if self.is_running:
191
- raise RuntimeError("cannot fork session while agent is running")
192
- session_id = uuid7_string()
193
- path = None
194
- if self._rollout_recorder is not None:
195
- path = rollout_path_for_session(
196
- self.context_manager._config.codex_home or resolve_codex_home(),
197
- session_id,
198
- )
199
- self._configure_recording(session_id, path)
200
-
201
214
  def _configure_recording(
202
215
  self,
203
216
  session_id: "str",
@@ -208,22 +221,22 @@ class Agent:
208
221
  recorder = None
209
222
  elif resume:
210
223
  recorder = SessionRolloutRecorder.resume(session_file_path)
224
+ environment_state = recorder.read_environment_state()
225
+ self.tool_registry.runtime_environment.validate_state(environment_state)
211
226
  else:
212
227
  recorder = SessionRolloutRecorder.create(
213
- self.context_manager._config.codex_home or resolve_codex_home(),
228
+ self.context_manager.config.codex_home or resolve_codex_home(),
214
229
  session_id,
215
230
  self.context_manager.cwd,
216
- getattr(self.model_client, "_originator", DEFAULT_ORIGINATOR),
217
- getattr(
218
- getattr(self.model_client, "_config", None), "provider_name", None
219
- ),
231
+ self.model_client.recording_metadata.originator,
232
+ self.model_client.recording_metadata.provider_name,
220
233
  self.context_manager.resolve_base_instructions(),
221
234
  session_file_path,
222
235
  )
223
- if hasattr(self.model_client, "_session_id"):
224
- self.model_client._session_id = session_id
225
236
  self.session_id = session_id
226
237
  self._rollout_recorder = recorder
238
+ if resume:
239
+ self.tool_registry.runtime_environment.restore_state(environment_state)
227
240
 
228
241
  async def compact(
229
242
  self,
@@ -247,13 +260,15 @@ class Agent:
247
260
  self._idle = None
248
261
 
249
262
  async def run_turn(
250
- self, texts: "typing.List[str]", turn_id: "typing.Union[str, None]" = None
263
+ self, texts: "typing.List[str]", turn_id: "typing.Union[str, None]" = None,
264
+ name: "str" = "user",
251
265
  ) -> "TurnResult":
252
266
  if self.is_shutdown:
253
267
  raise RuntimeError("agent is shutdown")
254
268
  if self.is_running:
255
269
  raise RuntimeError("agent already has an active turn")
256
270
  self._stop_requested = False
271
+ self._follow_up_requested = False
257
272
  self._idle = asyncio.Event()
258
273
  turn = _TurnState(turn_id or uuid7_string())
259
274
  try:
@@ -261,12 +276,13 @@ class Agent:
261
276
  while True:
262
277
  phase = "pre_turn" if turn.iteration == 0 else "mid_turn"
263
278
  await self._maybe_auto_compact(turn.turn_id, phase)
264
- manager = self.tool_registry.runtime_environment.subagent_manager
265
- notifications = manager.take_pending_notifications()
266
- if notifications:
267
- self._append_history(notifications)
279
+ self._follow_up_requested = False
280
+ # Input delivery commits history; its failures must fail the turn.
281
+ self.event_handler(TurnInputReadyEvent(turn.turn_id))
268
282
  if turn.iteration == 0:
269
- self._append_history(UserMessage(text=text) for text in texts)
283
+ self.receive_messages(
284
+ tuple(UserMessage(text=text, name=name) for text in texts)
285
+ )
270
286
  response = await self._sample(turn)
271
287
  self._emit(
272
288
  ModelCompletedEvent(
@@ -285,7 +301,7 @@ class Agent:
285
301
  await self._execute_tool_batch(turn.turn_id, tool_calls)
286
302
  if self._stop_requested:
287
303
  raise TurnInterrupted()
288
- if not tool_calls:
304
+ if not tool_calls and not self._follow_up_requested:
289
305
  break
290
306
 
291
307
  self._emit(
@@ -330,6 +346,7 @@ class Agent:
330
346
  raise
331
347
  finally:
332
348
  self._stop_requested = False
349
+ self._follow_up_requested = False
333
350
  self._idle.set()
334
351
  self._idle = None
335
352
 
@@ -357,28 +374,12 @@ class Agent:
357
374
  prune_tool_results_on_context_error=True,
358
375
  )
359
376
 
360
- async def maybe_invoke(self, event: "typing.Dict[str, object]") -> "bool":
361
- if self.is_running or not self.accepts_input:
362
- return False
363
- tag = event["type"]
364
- if not isinstance(tag, str) or not tag.isidentifier():
365
- raise ValueError("invoke event type must be an identifier")
366
- payload = {key: value for key, value in event.items() if key != "type"}
367
- text = (
368
- f"<{tag}>\n"
369
- f"{json.dumps(payload, ensure_ascii=False, separators=(',', ':'))}\n"
370
- f"</{tag}>"
371
- )
372
- await self.run_turn([text])
373
- return True
374
-
375
377
  def shutdown(self) -> "None":
376
378
  if self.is_shutdown:
377
379
  return
378
380
  self.accepts_input = False
379
381
  self.is_shutdown = True
380
- for tool in self.tool_registry.tools():
381
- tool.shutdown()
382
+ self.tool_registry.runtime_environment.shutdown(self._save_environment_state)
382
383
 
383
384
  async def _execute_tool_batch(
384
385
  self,
@@ -405,16 +406,12 @@ class Agent:
405
406
 
406
407
  results: "typing.List[ToolResult]" = []
407
408
  for batch in batches:
408
- context = ToolContext(
409
- turn_id=turn_id,
410
- history=self.history,
411
- cwd=self.context_manager.cwd,
412
- )
409
+ history = self.history
413
410
  if len(batch) == 1:
414
- results.append(await self._run_single_tool(turn_id, batch[0], context))
411
+ results.append(await self._run_single_tool(turn_id, batch[0], history))
415
412
  continue
416
413
  outcomes = await asyncio.gather(
417
- *(self._run_single_tool(turn_id, call, context) for call in batch),
414
+ *(self._run_single_tool(turn_id, call, history) for call in batch),
418
415
  return_exceptions=True,
419
416
  )
420
417
  for outcome in outcomes:
@@ -422,25 +419,40 @@ class Agent:
422
419
  raise outcome
423
420
  results.append(outcome)
424
421
  self._append_history(self.tool_registry.follow_up_messages(results))
422
+ self._append_history(self.tool_registry.runtime_environment.follow_up_messages())
425
423
 
426
424
  async def _run_single_tool(
427
425
  self,
428
426
  turn_id: "str",
429
427
  call: "ToolCall",
430
- context: "ToolContext",
428
+ history: "typing.Tuple[ConversationItem, ...]",
431
429
  ) -> "ToolResult":
430
+ context = ToolContext(
431
+ turn_id=turn_id,
432
+ history=history,
433
+ cwd=self.context_manager.cwd,
434
+ agent_id=self.agent_id,
435
+ encrypted_messages=call.encrypted_function_args != [],
436
+ session_id=self.session_id,
437
+ )
432
438
  self._emit(ToolStartedEvent(turn_id, call))
433
439
  result = await self.tool_registry.execute(call, context)
434
440
  self._append_history([truncate_tool_result_for_history(result)])
435
441
  self._emit(ToolCompletedEvent(turn_id, call, result))
436
442
  return result
437
443
 
444
+ def _save_environment_state(self) -> "None":
445
+ if self.recorded_session_file_path is not None:
446
+ self._rollout_recorder.save_environment_state(
447
+ self.tool_registry.runtime_environment.dump_state()
448
+ )
449
+
438
450
  def _emit(self, event: "TurnEvent") -> "None":
439
- handlers = [self.event_handler]
440
- if isinstance(event, (TerminalEvent, TurnStartedEvent, CompactStartedEvent)):
441
- handlers = [
442
- tool.handle_agent_event for tool in self.tool_registry.tools()
443
- ] + handlers
451
+ environment = self.tool_registry.runtime_environment
452
+ environment.handle_agent_event(event)
453
+ if isinstance(event, (ToolCompletedEvent, TerminalEvent)):
454
+ self._save_environment_state()
455
+ handlers = environment.event_observers(event) + [self.event_handler]
444
456
  for handler in handlers:
445
457
  try:
446
458
  handler(event)
@@ -454,11 +466,8 @@ class Agent:
454
466
 
455
467
  def _background_work_count(self, event_type) -> "typing.Union[int, None]":
456
468
  try:
457
- return sum(
458
- tool.background_work_count(
459
- event_type in (TurnCompletedEvent, CompactCompletedEvent)
460
- )
461
- for tool in self.tool_registry.tools()
469
+ return self.tool_registry.runtime_environment.background_work_count(
470
+ event_type in (TurnCompletedEvent, CompactCompletedEvent)
462
471
  )
463
472
  except Exception as exc:
464
473
  asyncio.get_running_loop().call_exception_handler(
@@ -499,9 +508,13 @@ class Agent:
499
508
  ) -> "ModelResponse":
500
509
  prompt = self.context_manager.build_prompt(
501
510
  self._history,
502
- self.tool_registry.model_visible_specs(),
511
+ self.tool_registry.model_visible_specs(
512
+ self.context_manager.resolve_code_mode_only(),
513
+ ),
503
514
  self._parallel_tool_calls,
504
515
  turn_id=turn_id,
516
+ reasoning_effort=self.model_client.reasoning_effort,
517
+ session_id=self.session_id,
505
518
  )
506
519
  self._emit(
507
520
  ModelCalledEvent(turn_id, iteration, len(prompt.input), len(prompt.tools))
@@ -574,10 +587,12 @@ class Agent:
574
587
  prune_tool_results_on_context_error,
575
588
  str(recorder.rollout_path) if recorder is not None else None,
576
589
  turn_id,
590
+ self.session_id,
577
591
  )
578
592
  if recorder is not None:
579
593
  recorder.append_compacted_history(compact_result.history, self._history)
580
594
  self._history = list(compact_result.history)
595
+ self.context_manager.reset_history_context()
581
596
  self._last_total_usage_tokens = None
582
597
  except Exception as exc:
583
598
  if phase == "manual":