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
pycodex/bootstrap.py CHANGED
@@ -1,29 +1,31 @@
1
- import atexit
2
1
  import os
3
2
  import sys
4
3
  import typing
5
- from dataclasses import replace
6
- from pathlib import Path
4
+ from dataclasses import dataclass, replace
7
5
 
8
- from .agent import Agent
9
- from .context import ContextConfig
10
6
  from .model import (
11
- DEFAULT_CODEX_CONFIG_PATH,
12
7
  ResponsesModelClient,
13
8
  ResponsesProviderConfig,
14
9
  )
15
- from .runtime import AgentRuntime
16
- from .tools.runtime_services import (
17
- AgentRuntimeEnvironment,
18
- create_agent_runtime_environment,
19
- )
20
- from .utils import get_debug_dir, load_codex_dotenv, uuid7_string
21
- from .utils.session_persist import rollout_path_for_session
10
+ from .utils import get_debug_dir
11
+
12
+ if typing.TYPE_CHECKING:
13
+ from responses_server import ManagedResponseServer
22
14
 
23
15
  LOCAL_RESPONSES_SERVER_API_KEY_ENV = "PYCODEX_LOCAL_RESPONSES_SERVER_KEY"
24
16
  CLI_ORIGINATOR = "codex-tui"
25
17
 
26
18
 
19
+ @dataclass(frozen=True)
20
+ class ModelBootstrapResult:
21
+ client: "ResponsesModelClient"
22
+ owned_server: "typing.Union[ManagedResponseServer, None]" = None
23
+
24
+ def close(self) -> "None":
25
+ if self.owned_server is not None:
26
+ self.owned_server.stop()
27
+
28
+
27
29
  def launch_chat_completion_compat_server(*args, **kwargs):
28
30
  from responses_server import (
29
31
  launch_chat_completion_compat_server as launch_compat_server,
@@ -83,228 +85,14 @@ def configure_loguru() -> "None":
83
85
  logger.add(sys.stderr, level="DEBUG")
84
86
 
85
87
 
86
- def get_tools(
87
- runtime_environment: "typing.Union[AgentRuntimeEnvironment, None]" = None,
88
- exec_mode: "bool" = False,
89
- toolset: "typing.Union[typing.Iterable[str], None]" = None,
90
- ):
91
- from .tools import (
92
- ApplyPatchTool,
93
- ClockManager,
94
- ClockTool,
95
- CloseAgentTool,
96
- CodeModeManager,
97
- ExecCommandTool,
98
- ExecTool,
99
- GrepFilesTool,
100
- ListDirTool,
101
- ReadFileTool,
102
- Registry,
103
- RequestPermissionsTool,
104
- RequestUserInputTool,
105
- ResumeAgentTool,
106
- SendInputTool,
107
- ShellCommandTool,
108
- ShellTool,
109
- SpawnAgentTool,
110
- UnifiedExecManager,
111
- UpdatePlanTool,
112
- ViewImageTool,
113
- WaitAgentTool,
114
- WaitTool,
115
- WebSearchTool,
116
- WriteStdinTool,
117
- )
118
-
119
- runtime_environment = runtime_environment or create_agent_runtime_environment()
120
- registry = Registry(runtime_environment)
121
- code_mode_manager = CodeModeManager(registry)
122
- unified_exec_manager = UnifiedExecManager()
123
- clock_manager = ClockManager()
124
- exec_tool = ExecTool(code_mode_manager)
125
- wait_tool = WaitTool(code_mode_manager)
126
- web_search_tool = WebSearchTool()
127
- update_plan_tool = UpdatePlanTool(runtime_environment.plan_store)
128
- request_user_input_tool = RequestUserInputTool()
129
- request_permissions_tool = RequestPermissionsTool(
130
- runtime_environment.request_permissions_manager
131
- )
132
- spawn_agent_tool = SpawnAgentTool(runtime_environment.subagent_manager)
133
- send_input_tool = SendInputTool(runtime_environment.subagent_manager)
134
- resume_agent_tool = ResumeAgentTool(runtime_environment.subagent_manager)
135
- wait_agent_tool = WaitAgentTool(runtime_environment.subagent_manager)
136
- close_agent_tool = CloseAgentTool(runtime_environment.subagent_manager)
137
- apply_patch_tool = ApplyPatchTool()
138
- shell_tool = ShellTool()
139
- shell_command_tool = ShellCommandTool()
140
- exec_command_tool = ExecCommandTool(unified_exec_manager)
141
- write_stdin_tool = WriteStdinTool(unified_exec_manager)
142
- clock_tool = ClockTool(clock_manager)
143
- grep_files_tool = GrepFilesTool()
144
- read_file_tool = ReadFileTool()
145
- list_dir_tool = ListDirTool()
146
- view_image_tool = ViewImageTool()
147
- tools = (
148
- shell_tool,
149
- shell_command_tool,
150
- exec_command_tool,
151
- write_stdin_tool,
152
- clock_tool,
153
- exec_tool,
154
- wait_tool,
155
- web_search_tool,
156
- update_plan_tool,
157
- request_user_input_tool,
158
- request_permissions_tool,
159
- spawn_agent_tool,
160
- send_input_tool,
161
- resume_agent_tool,
162
- wait_agent_tool,
163
- close_agent_tool,
164
- apply_patch_tool,
165
- grep_files_tool,
166
- read_file_tool,
167
- list_dir_tool,
168
- view_image_tool,
169
- )
170
- if toolset is not None:
171
- available_tools = {tool.name: tool for tool in tools}
172
- toolset = tuple(toolset)
173
- unknown_tools = set(toolset) - set(available_tools)
174
- if unknown_tools:
175
- raise ValueError(
176
- "unknown toolset entries: {0}".format(", ".join(sorted(unknown_tools)))
177
- )
178
- tools = tuple(available_tools[name] for name in toolset)
179
- elif exec_mode:
180
- tools = (
181
- exec_command_tool,
182
- write_stdin_tool,
183
- clock_tool,
184
- update_plan_tool,
185
- request_user_input_tool,
186
- apply_patch_tool,
187
- web_search_tool,
188
- view_image_tool,
189
- spawn_agent_tool,
190
- send_input_tool,
191
- resume_agent_tool,
192
- wait_agent_tool,
193
- close_agent_tool,
194
- )
195
- for tool in tools:
196
- registry.register(tool)
197
- return registry
198
-
199
-
200
- def get_subagent_tools(
201
- runtime_environment: "typing.Union[AgentRuntimeEnvironment, None]" = None,
202
- ):
203
- from .tools import (
204
- ApplyPatchTool,
205
- ExecCommandTool,
206
- Registry,
207
- UnifiedExecManager,
208
- UpdatePlanTool,
209
- ViewImageTool,
210
- WebSearchTool,
211
- WriteStdinTool,
212
- )
213
-
214
- runtime_environment = runtime_environment or create_agent_runtime_environment()
215
- registry = Registry(runtime_environment)
216
- unified_exec_manager = UnifiedExecManager()
217
- registry.register(ExecCommandTool(unified_exec_manager))
218
- registry.register(WriteStdinTool(unified_exec_manager))
219
- registry.register(UpdatePlanTool(runtime_environment.plan_store))
220
- registry.register(ApplyPatchTool())
221
- registry.register(WebSearchTool())
222
- registry.register(ViewImageTool())
223
- return registry
224
-
225
-
226
- def build_agent(
227
- client,
228
- config_path: "typing.Union[str, Path]" = DEFAULT_CODEX_CONFIG_PATH,
229
- profile: "typing.Union[str, None]" = None,
230
- system_prompt: "typing.Union[str, None]" = None,
231
- extra_contextual_user_messages: "typing.Iterable[str]" = (),
232
- cwd: "typing.Union[str, Path, None]" = None,
233
- toolset: "typing.Union[typing.Iterable[str], None]" = None,
234
- ) -> "Agent":
235
- config_path = str(config_path)
236
- resolved_cwd = Path(cwd or Path.cwd()).resolve()
237
- context_config = replace(
238
- ContextConfig.from_codex_config(config_path, profile),
239
- base_instructions_override=system_prompt,
240
- extra_contextual_user_messages=tuple(extra_contextual_user_messages),
241
- cwd=resolved_cwd,
242
- )
243
- runtime_environment = create_agent_runtime_environment()
244
-
245
- def make_subagent_runtime_builder(parent_agent):
246
- def build_subagent_runtime(
247
- model_override: "typing.Union[str, None]",
248
- reasoning_effort_override: "typing.Union[str, None]",
249
- initial_history=(),
250
- session_id: "typing.Union[str, None]" = None,
251
- ) -> "AgentRuntime":
252
- nested_client = parent_agent.model_client.with_overrides(
253
- model_override,
254
- reasoning_effort_override,
255
- session_id=session_id,
256
- openai_subagent="collab_spawn",
257
- )
258
- subagent_agent_runtime_environment = create_agent_runtime_environment()
259
- inherited_cwd = parent_agent.context_manager.cwd
260
- sub_agent = Agent(
261
- nested_client,
262
- get_subagent_tools(subagent_agent_runtime_environment),
263
- replace(context_config, cwd=inherited_cwd),
264
- initial_history=tuple(initial_history),
265
- session_id=session_id,
266
- )
267
- subagent_agent_runtime_environment.subagent_manager.set_runtime_builder(
268
- make_subagent_runtime_builder(sub_agent)
269
- )
270
- return AgentRuntime(sub_agent)
271
-
272
- return build_subagent_runtime
273
-
274
- session_id = uuid7_string()
275
- agent = Agent(
276
- client,
277
- get_tools(
278
- runtime_environment,
279
- exec_mode=True,
280
- toolset=toolset,
281
- ),
282
- context_config,
283
- session_file_path=rollout_path_for_session(
284
- context_config.codex_home, session_id
285
- ),
286
- session_id=session_id,
287
- )
288
- runtime_environment.subagent_manager.set_runtime_builder(
289
- make_subagent_runtime_builder(agent)
290
- )
291
- return agent
292
-
293
-
294
88
  def build_model(
295
- config_path: "typing.Union[str, Path]" = DEFAULT_CODEX_CONFIG_PATH,
296
- profile: "typing.Union[str, None]" = None,
89
+ provider_config: "ResponsesProviderConfig",
297
90
  timeout_seconds: "float" = 120.0,
298
91
  managed_responses_base_url: "typing.Union[str, None]" = None,
299
92
  vllm_endpoint: "typing.Union[str, None]" = None,
300
93
  use_chat_completion: "typing.Union[bool, None]" = None,
301
94
  use_messages: "bool" = False,
302
- ):
303
- load_codex_dotenv(config_path)
304
- provider_config = ResponsesProviderConfig.from_codex_config(
305
- config_path,
306
- profile,
307
- )
95
+ ) -> "ModelBootstrapResult":
308
96
  if use_chat_completion is None:
309
97
  use_chat_completion = bool(provider_config.use_chat_completion)
310
98
  if use_chat_completion and use_messages:
@@ -326,6 +114,7 @@ def build_model(
326
114
  timeout_seconds,
327
115
  ),
328
116
  )
117
+ managed_server = None
329
118
  url, key_env = provider_config.base_url, provider_config.api_key_env
330
119
  if managed_responses_base_url is not None:
331
120
  url, key_env = (
@@ -346,7 +135,6 @@ def build_model(
346
135
  model_provider=provider_config.provider_name,
347
136
  outcomming_api=("messages" if use_messages else "chat_completions"),
348
137
  )
349
- atexit.register(managed_server.stop)
350
138
  url, key_env = (
351
139
  managed_server.base_url,
352
140
  LOCAL_RESPONSES_SERVER_API_KEY_ENV,
@@ -363,12 +151,12 @@ def build_model(
363
151
  else provider_config.responses_lite_override
364
152
  ),
365
153
  )
366
- return ResponsesModelClient(
367
- provider_config,
368
- timeout_seconds,
369
- originator=CLI_ORIGINATOR,
370
- )
371
-
372
-
373
- def build_runtime(agent: "Agent") -> "AgentRuntime":
374
- return AgentRuntime(agent)
154
+ try:
155
+ client = ResponsesModelClient(
156
+ provider_config, timeout_seconds, originator=CLI_ORIGINATOR,
157
+ )
158
+ except BaseException:
159
+ if managed_server is not None:
160
+ managed_server.stop()
161
+ raise
162
+ return ModelBootstrapResult(client, managed_server)
pycodex/cli.py CHANGED
@@ -1,4 +1,5 @@
1
1
  import argparse
2
+ import atexit
2
3
  import asyncio
3
4
  import inspect
4
5
  import os
@@ -10,6 +11,7 @@ import threading
10
11
  import traceback
11
12
  import typing
12
13
  from contextlib import contextmanager
14
+ from dataclasses import replace
13
15
 
14
16
  from prompt_toolkit import PromptSession
15
17
  from prompt_toolkit.enums import DEFAULT_BUFFER
@@ -17,9 +19,11 @@ from prompt_toolkit.filters import has_focus
17
19
  from prompt_toolkit.key_binding import KeyBindings
18
20
  from prompt_toolkit.patch_stdout import patch_stdout
19
21
 
20
- from .bootstrap import build_agent, build_model, build_runtime, configure_loguru
22
+ from .bootstrap import build_model, configure_loguru
23
+ from .config import CodexConfig, DEFAULT_CODEX_CONFIG_PATH
21
24
  from .events import DEFAULT_MAIN_PROMPT, EventDisplay
22
- from .model import DEFAULT_CODEX_CONFIG_PATH, ModelControl
25
+ from .model import ModelControl
26
+ from .multi_agents import AgentsManager
23
27
  from .portable import bootstrap_called_home, upload_codex_home
24
28
  from .utils import get_debug_dir
25
29
  from .utils.event_helpers import format_error, render_result
@@ -50,7 +54,8 @@ def build_parser():
50
54
  help="Path to Codex config.toml.",
51
55
  )
52
56
  parser.add_argument(
53
- "--profile", default=None, help="Optional profile name from config.toml."
57
+ "--profile", default=None,
58
+ help="Select <name>.config.toml or [profiles.<name>], overriding the config default.",
54
59
  )
55
60
  parser.add_argument(
56
61
  "--vllm-endpoint",
@@ -140,24 +145,24 @@ async def run_cli(args):
140
145
  phase("bootstrap_called_home:done")
141
146
  os.environ["CODEX_HOME"] = str(config_path.parent)
142
147
  phase("build_model:start")
143
- model = build_model(
144
- config_path=str(config_path),
145
- profile=args.profile,
148
+ config = CodexConfig.from_env(config_path, args.profile)
149
+ bootstrap = build_model(
150
+ config.provider,
146
151
  timeout_seconds=args.timeout_seconds,
147
152
  vllm_endpoint=args.vllm_endpoint,
148
153
  use_chat_completion=args.use_chat_completion or None,
149
154
  use_messages=args.use_messages,
150
155
  )
156
+ if bootstrap.owned_server is not None:
157
+ atexit.register(bootstrap.owned_server.stop)
151
158
  phase("build_model:done")
152
- phase("build_agent:start")
153
- agent = build_agent(
154
- model,
155
- config_path=str(config_path),
156
- profile=args.profile,
157
- system_prompt=args.system_prompt,
159
+ phase("create_root_runtime:start")
160
+ context_config = replace(
161
+ config.context,
162
+ base_instructions_override=args.system_prompt,
158
163
  )
159
- phase("build_agent:done")
160
- runtime = build_runtime(agent)
164
+ runtime = AgentsManager(bootstrap.client, context_config).create_root_runtime()
165
+ phase("create_root_runtime:done")
161
166
  if should_run_interactive(args.prompt, sys.stdin.isatty()):
162
167
  return await run_interactive_session(runtime, args.json, str(config_path))
163
168
  prompt_text = resolve_prompt_text(args.prompt)
pycodex/config.py ADDED
@@ -0,0 +1,36 @@
1
+ """Load startup configuration once, then pass each component its own config."""
2
+
3
+ import typing
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ from .context import ContextConfig
8
+ from .model import ResponsesProviderConfig
9
+ from .utils.codex_config import DEFAULT_CODEX_CONFIG_PATH, read_codex_config
10
+ from .utils.dotenv import load_codex_dotenv
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class CodexConfig:
15
+ path: "Path"
16
+ profile: "typing.Union[str, None]"
17
+ provider: "ResponsesProviderConfig"
18
+ context: "ContextConfig"
19
+
20
+ @classmethod
21
+ def from_env(
22
+ cls,
23
+ config_path: "typing.Union[str, Path]" = DEFAULT_CODEX_CONFIG_PATH,
24
+ profile: "typing.Union[str, None]" = None,
25
+ use_default_profile: "bool" = True,
26
+ ) -> "CodexConfig":
27
+ """Load the selected TOML and adjacent dotenv; retain dynamic key lookup."""
28
+ path = Path(config_path)
29
+ load_codex_dotenv(path)
30
+ selected = read_codex_config(path, profile, use_default_profile)
31
+ return cls(
32
+ path=path,
33
+ profile=selected["profile"],
34
+ provider=ResponsesProviderConfig.from_mapping(selected),
35
+ context=ContextConfig.from_mapping(selected, path),
36
+ )