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/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,239 +85,23 @@ 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
- use_chat_completion: "typing.Union[bool, None]" = None,
301
- use_messages: "bool" = False,
302
- ):
303
- load_codex_dotenv(config_path)
304
- provider_config = ResponsesProviderConfig.from_codex_config(
305
- config_path,
306
- profile,
307
- )
308
- if use_chat_completion is None:
309
- use_chat_completion = bool(provider_config.use_chat_completion)
310
- if use_chat_completion and use_messages:
311
- raise ValueError("--use-chat-completion and --use-messages cannot be combined")
312
- if vllm_endpoint and use_messages:
313
- raise ValueError("--vllm-endpoint and --use-messages cannot be combined")
93
+ ) -> "ModelBootstrapResult":
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")
314
101
  uses_local_responses_compat = (
315
102
  managed_responses_base_url is not None
316
103
  or vllm_endpoint is not None
317
- or bool(use_chat_completion)
318
- or use_messages
104
+ or compat_api != "none"
319
105
  )
320
106
  if vllm_endpoint is not None:
321
107
  provider_config = replace(
@@ -326,6 +112,7 @@ def build_model(
326
112
  timeout_seconds,
327
113
  ),
328
114
  )
115
+ managed_server = None
329
116
  url, key_env = provider_config.base_url, provider_config.api_key_env
330
117
  if managed_responses_base_url is not None:
331
118
  url, key_env = (
@@ -333,7 +120,7 @@ def build_model(
333
120
  LOCAL_RESPONSES_SERVER_API_KEY_ENV,
334
121
  )
335
122
  os.environ.setdefault(LOCAL_RESPONSES_SERVER_API_KEY_ENV, "dummy")
336
- elif vllm_endpoint or use_chat_completion or use_messages:
123
+ elif vllm_endpoint is not None or compat_api != "none":
337
124
  if vllm_endpoint:
338
125
  managed_server = launch_chat_completion_compat_server(
339
126
  vllm_endpoint,
@@ -344,9 +131,8 @@ def build_model(
344
131
  provider_config.base_url,
345
132
  provider_config.api_key_env,
346
133
  model_provider=provider_config.provider_name,
347
- outcomming_api=("messages" if use_messages else "chat_completions"),
134
+ outcomming_api=compat_api,
348
135
  )
349
- atexit.register(managed_server.stop)
350
136
  url, key_env = (
351
137
  managed_server.base_url,
352
138
  LOCAL_RESPONSES_SERVER_API_KEY_ENV,
@@ -363,12 +149,12 @@ def build_model(
363
149
  else provider_config.responses_lite_override
364
150
  ),
365
151
  )
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)
152
+ try:
153
+ client = ResponsesModelClient(
154
+ provider_config, timeout_seconds, originator=CLI_ORIGINATOR,
155
+ )
156
+ except BaseException:
157
+ if managed_server is not None:
158
+ managed_server.stop()
159
+ raise
160
+ 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,25 +54,14 @@ 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",
57
62
  default=None,
58
63
  help="Start a local responses compat server for a chat-completions-backed vLLM endpoint.",
59
64
  )
60
- parser.add_argument(
61
- "--use-chat-completion",
62
- default=False,
63
- action="store_true",
64
- help="Start a local responses compat server for this session.",
65
- )
66
- parser.add_argument(
67
- "--use-messages",
68
- default=False,
69
- action="store_true",
70
- help="Route the local responses compat server to a downstream /v1/messages backend.",
71
- )
72
65
  parser.add_argument(
73
66
  "--system-prompt",
74
67
  default=None,
@@ -140,24 +133,22 @@ async def run_cli(args):
140
133
  phase("bootstrap_called_home:done")
141
134
  os.environ["CODEX_HOME"] = str(config_path.parent)
142
135
  phase("build_model:start")
143
- model = build_model(
144
- config_path=str(config_path),
145
- profile=args.profile,
136
+ config = CodexConfig.from_env(config_path, args.profile)
137
+ bootstrap = build_model(
138
+ config.provider,
146
139
  timeout_seconds=args.timeout_seconds,
147
140
  vllm_endpoint=args.vllm_endpoint,
148
- use_chat_completion=args.use_chat_completion or None,
149
- use_messages=args.use_messages,
150
141
  )
142
+ if bootstrap.owned_server is not None:
143
+ atexit.register(bootstrap.owned_server.stop)
151
144
  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,
145
+ phase("create_root_runtime:start")
146
+ context_config = replace(
147
+ config.context,
148
+ base_instructions_override=args.system_prompt,
158
149
  )
159
- phase("build_agent:done")
160
- runtime = build_runtime(agent)
150
+ runtime = AgentsManager(bootstrap.client, context_config).create_root_runtime()
151
+ phase("create_root_runtime:done")
161
152
  if should_run_interactive(args.prompt, sys.stdin.isatty()):
162
153
  return await run_interactive_session(runtime, args.json, str(config_path))
163
154
  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
+ )