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
@@ -74,6 +74,7 @@ async def compact_history(
74
74
  prune_tool_results_on_context_error: "bool" = False,
75
75
  session_file: "typing.Union[str, None]" = None,
76
76
  turn_id: "typing.Union[str, None]" = None,
77
+ session_id: "typing.Union[str, None]" = None,
77
78
  ) -> "typing.Union[CompactResult, None]":
78
79
  from ..model import ContextLengthExceeded, ResponsesIncompleteError
79
80
 
@@ -91,6 +92,9 @@ async def compact_history(
91
92
  [],
92
93
  False,
93
94
  turn_id=turn_id,
95
+ reasoning_effort=model_client.reasoning_effort,
96
+ capture_context=False,
97
+ session_id=session_id,
94
98
  )
95
99
  try:
96
100
  response = await model_client.complete(
pycodex/utils/compat.py CHANGED
@@ -1,8 +1,11 @@
1
1
  """Compatibility helpers for supported Python versions."""
2
2
 
3
+ import ast
3
4
  import asyncio
4
5
  import functools
6
+ import io
5
7
  import shlex
8
+ import tokenize
6
9
 
7
10
  try:
8
11
  from http.server import ThreadingHTTPServer
@@ -20,9 +23,9 @@ except ImportError: # pragma: no cover - Python 3.6 path
20
23
  import importlib_metadata # type: ignore
21
24
 
22
25
  try:
23
- from typing import Literal, Protocol, TypeAlias
26
+ from typing import Literal, Protocol, TypeAlias, TypedDict
24
27
  except ImportError: # pragma: no cover - Python 3.6 path
25
- from typing_extensions import Literal, Protocol # type: ignore
28
+ from typing_extensions import Literal, Protocol, TypedDict # type: ignore
26
29
 
27
30
  try:
28
31
  from typing_extensions import TypeAlias # type: ignore
@@ -117,3 +120,41 @@ def is_ascii(text):
117
120
  except UnicodeEncodeError:
118
121
  return False
119
122
  return True
123
+
124
+
125
+ def compile_async_cell(source, filename="<exec>"):
126
+ if hasattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT"):
127
+ tree = ast.parse(source, filename=filename)
128
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
129
+ expr = tree.body[-1]
130
+ target = ast.Name(id="__exec_result__", ctx=ast.Store())
131
+ tree.body[-1] = ast.copy_location(
132
+ ast.Assign(targets=[target], value=expr.value), expr,
133
+ )
134
+ ast.fix_missing_locations(tree.body[-1])
135
+ return compile(tree, filename, "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
136
+ return compile_async_cell_compat(source, filename)
137
+
138
+
139
+ def compile_async_cell_compat(source, filename="<exec>"): # pragma: no cover - Python 3.6/3.7 path
140
+ source = source.replace("\r\n", "\n").replace("\r", "\n")
141
+ string_lines = set()
142
+ for token in tokenize.generate_tokens(io.StringIO(source).readline):
143
+ if tokenize.tok_name[token.type] in ("STRING", "FSTRING_MIDDLE", "TSTRING_MIDDLE"):
144
+ string_lines.update(range(token.start[0], token.end[0]))
145
+ source = (
146
+ "async def __exec_cell__():\n"
147
+ + "\n".join(
148
+ line if index in string_lines else " " + line
149
+ for index, line in enumerate(source.split("\n"))
150
+ )
151
+ + "\n pass\n"
152
+ )
153
+ tree = ast.parse(source, filename=filename)
154
+ body = tree.body[0].body
155
+ if len(body) > 1 and isinstance(body[-2], ast.Expr):
156
+ expression = body[-2]
157
+ body[-2] = ast.copy_location(ast.Return(value=expression.value), expression)
158
+ for statement in body:
159
+ ast.increment_lineno(statement, -1)
160
+ return compile(tree, filename, "exec")
pycodex/utils/doctor.py CHANGED
@@ -12,6 +12,7 @@ import requests
12
12
 
13
13
  from ..model import ResponsesModelClient, ResponsesProviderConfig
14
14
  from ..protocol import AssistantMessage, Prompt, UserMessage
15
+ from .codex_config import read_codex_config
15
16
  from .dotenv import DOTENV_FILENAME, load_codex_dotenv
16
17
 
17
18
 
@@ -56,7 +57,7 @@ def build_doctor_parser():
56
57
  parser.add_argument(
57
58
  "--profile",
58
59
  default=None,
59
- help="Optional profile name from config.toml.",
60
+ help="Select <name>.config.toml or [profiles.<name>], overriding the config default.",
60
61
  )
61
62
  parser.add_argument(
62
63
  "--timeout-seconds",
@@ -117,9 +118,9 @@ async def collect_doctor_report(
117
118
  load_codex_dotenv(config_file)
118
119
 
119
120
  try:
120
- provider_config = ResponsesProviderConfig.from_codex_config(
121
- config_file, profile
122
- )
121
+ selected = read_codex_config(config_file, profile)
122
+ report.profile = selected["profile"]
123
+ provider_config = ResponsesProviderConfig.from_mapping(selected)
123
124
  except Exception as exc:
124
125
  checks.append(
125
126
  DoctorCheck("config_parse", False, f"{type(exc).__name__}: {exc}")
pycodex/utils/dotenv.py CHANGED
@@ -4,17 +4,12 @@ from pathlib import Path
4
4
 
5
5
  ILLEGAL_ENV_VAR_PREFIX = "CODEX_"
6
6
  DOTENV_FILENAME = ".env"
7
- _LOADED_CODEX_DOTENV_HOMES: "typing.Set[str]" = set()
8
7
 
9
8
 
10
9
  def load_codex_dotenv(config_path: "typing.Union[str, Path]") -> "None":
11
10
  codex_home = str(Path(config_path).resolve().parent)
12
- if codex_home in _LOADED_CODEX_DOTENV_HOMES:
13
- return
14
-
15
11
  dotenv_path = Path(codex_home) / DOTENV_FILENAME
16
12
  if not dotenv_path.is_file():
17
- _LOADED_CODEX_DOTENV_HOMES.add(codex_home)
18
13
  return
19
14
 
20
15
  for key, value in parse_dotenv(
@@ -24,8 +19,6 @@ def load_codex_dotenv(config_path: "typing.Union[str, Path]") -> "None":
24
19
  continue
25
20
  os.environ[key] = value
26
21
 
27
- _LOADED_CODEX_DOTENV_HOMES.add(codex_home)
28
-
29
22
 
30
23
  def parse_dotenv(text: "str") -> "typing.Dict[str, str]":
31
24
  values: "typing.Dict[str, str]" = {}
@@ -1,6 +1,8 @@
1
1
  """Stateless presentation helpers; no event or frontend dependencies."""
2
2
 
3
3
  import json
4
+ import re
5
+ import shlex
4
6
  import typing
5
7
  from dataclasses import asdict
6
8
 
@@ -71,8 +73,6 @@ def format_command_result(result: "typing.Dict[str, object]") -> "str":
71
73
  result["retained_item_count"],
72
74
  result["pruned_tool_results"],
73
75
  )
74
- if kind == "forked":
75
- return "Forked session: " + result["session_id"]
76
76
  return "\n".join(result["lines"])
77
77
 
78
78
 
@@ -132,7 +132,7 @@ def colorize_tool_message(
132
132
  color = "\x1b[36m"
133
133
  elif tool_name == "exec_command" and "session_id=" in message:
134
134
  color = "\x1b[2m"
135
- elif tool_name == "exec_command" and not message.startswith("["):
135
+ elif tool_name in {"exec_command", "exec"} and not message.startswith("["):
136
136
  color = ""
137
137
  elif tool_name in {"exec_command", "shell", "shell_command", "exec"}:
138
138
  color = "\x1b[33m"
@@ -140,10 +140,11 @@ def colorize_tool_message(
140
140
  color = "\x1b[35m"
141
141
  elif tool_name in {
142
142
  "spawn_agent",
143
- "send_input",
144
143
  "wait_agent",
145
- "resume_agent",
146
- "close_agent",
144
+ "send_message",
145
+ "followup_task",
146
+ "interrupt_agent",
147
+ "list_agents",
147
148
  }:
148
149
  color = "\x1b[34m"
149
150
  else:
@@ -180,15 +181,144 @@ def agent_status_summary(status: "object") -> "str":
180
181
  return truncate_text(json.dumps(status, ensure_ascii=False, separators=(",", ":")))
181
182
 
182
183
 
183
- def short_id(value: "str", limit: "int" = 8) -> "str":
184
- compact = value.strip()
185
- if len(compact) <= limit + 4:
186
- return compact
187
- return f"{compact[:limit]}...{compact[-4:]}"
188
-
189
-
190
184
  def truncate_text(text: "str", limit: "int" = 96) -> "str":
191
185
  compact = " ".join(text.split())
192
186
  if len(compact) <= limit:
193
187
  return compact
194
188
  return compact[: limit - 3].rstrip() + "..."
189
+
190
+
191
+ def summarize_tool_result(call, result) -> "str":
192
+ """Format call/result data without changing it or interpreting process state text."""
193
+ name = call.name
194
+ arguments = call.arguments if isinstance(call.arguments, dict) else {}
195
+ output = result.output
196
+ call_summary = ""
197
+ result_summary = None
198
+ if name == "exec" and isinstance(call.arguments, str):
199
+ call_summary = call.arguments
200
+ elif name == "exec_command":
201
+ command = arguments.get("cmd")
202
+ if command not in (None, ""):
203
+ command = str(command)
204
+ call_summary = truncate_text(command, 200)
205
+ lines = command.splitlines()
206
+ match = re.search(
207
+ r"\bpython(?:\d+(?:\.\d+)?)?\s+-\s+<<[-]?\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1",
208
+ lines[0] if lines else "",
209
+ )
210
+ if match is not None:
211
+ for index, line in enumerate(lines[1:], 1):
212
+ if line.strip() == match.group(2):
213
+ call_summary = "\n".join(lines[: index + 1])
214
+ break
215
+ elif name == "shell_command":
216
+ command = arguments.get("command")
217
+ if command not in (None, ""):
218
+ call_summary = truncate_text(str(command), 200)
219
+ elif name == "shell":
220
+ command = arguments.get("command")
221
+ if isinstance(command, list) and command:
222
+ call_summary = truncate_text(
223
+ " ".join(shlex.quote(str(part)) for part in command), 200
224
+ )
225
+ elif name == "write_stdin":
226
+ session_id = arguments.get("session_id")
227
+ if session_id not in (None, ""):
228
+ session_id = str(session_id)
229
+ chars = arguments.get("chars") or ""
230
+ call_summary = (
231
+ f"session {session_id} <- {truncate_text(str(chars), 32)}"
232
+ if chars
233
+ else f"poll session {session_id}"
234
+ )
235
+ elif name in {"read_file", "list_dir", "view_image"}:
236
+ key = (
237
+ "file_path"
238
+ if name == "read_file"
239
+ else ("dir_path" if name == "list_dir" else "path")
240
+ )
241
+ path = arguments.get(key)
242
+ if path not in (None, ""):
243
+ call_summary = truncate_text(str(path), 200)
244
+ if name == "view_image" and isinstance(output, list):
245
+ result_summary = f"{len(output)} image item(s)"
246
+ elif name == "grep_files":
247
+ pattern, path = arguments.get("pattern"), arguments.get("path")
248
+ if pattern not in (None, ""):
249
+ call_summary = truncate_text(
250
+ f"{pattern} @ {path}" if path not in (None, "") else str(pattern),
251
+ 200,
252
+ )
253
+ elif name == "update_plan":
254
+ plan = arguments.get("plan")
255
+ if isinstance(plan, list):
256
+ total = len(plan)
257
+ completed = 0
258
+ in_progress = 0
259
+ for item in plan:
260
+ if isinstance(item, dict):
261
+ status = str(item.get("status", "")).strip()
262
+ completed += status == "completed"
263
+ in_progress += status == "in_progress"
264
+ if not total:
265
+ return "0 steps"
266
+ if completed >= total:
267
+ return f"Done {completed}/{total}"
268
+ if in_progress:
269
+ return f"Working on {completed + in_progress}/{total}"
270
+ return f"Planned {completed}/{total}"
271
+ if isinstance(output, dict) and isinstance(output.get("plan"), list):
272
+ return f"{len(output['plan'])} steps"
273
+ elif name == "spawn_agent":
274
+ if isinstance(output, dict):
275
+ if output.get("task_name"):
276
+ return str(output["task_name"])
277
+ elif name in {"send_message", "followup_task"}:
278
+ target = arguments.get("target", "")
279
+ message = arguments.get("message", "")
280
+ if target or message:
281
+ call_summary = "{0} <- {1}".format(target, truncate_text(str(message), 40))
282
+ elif name == "wait_agent":
283
+ if isinstance(output, dict):
284
+ if output.get("timed_out") is True:
285
+ return "timed out"
286
+ if output.get("message"):
287
+ return str(output["message"])
288
+ elif name == "list_agents":
289
+ if isinstance(output, dict) and isinstance(output.get("agents"), list):
290
+ return "{0} agents".format(len(output["agents"]))
291
+ elif name == "interrupt_agent":
292
+ call_summary = str(arguments.get("target", ""))
293
+ if isinstance(output, dict):
294
+ result_summary = agent_status_summary(output.get("previous_status"))
295
+ if result_summary is None:
296
+ if isinstance(output, (dict, list)):
297
+ result_summary = truncate_text(
298
+ json.dumps(output, ensure_ascii=False, separators=(",", ":"))
299
+ )
300
+ else:
301
+ lines = [
302
+ line.strip() for line in result.output_text().splitlines()
303
+ ]
304
+ if "Output:" in lines:
305
+ result_summary = next(
306
+ (line for line in lines[lines.index("Output:") + 1 :] if line),
307
+ None,
308
+ )
309
+ if result_summary is None:
310
+ result_summary = next(
311
+ (
312
+ line
313
+ for line in lines
314
+ if line
315
+ and not line.startswith(
316
+ ("Exit code:", "Wall time:", "Command:")
317
+ )
318
+ ),
319
+ "",
320
+ )
321
+ result_summary = truncate_text(result_summary)
322
+ if call_summary and result_summary:
323
+ return f"{call_summary} -> {result_summary}"
324
+ return call_summary or result_summary
@@ -0,0 +1,59 @@
1
+ """Pure conversation-history projections, independent of rollout storage."""
2
+
3
+ import typing
4
+ from dataclasses import replace
5
+
6
+ from ..protocol import AgentMessage, AssistantMessage, ConversationItem, UserMessage
7
+
8
+
9
+ def serialize_history_item(item: "ConversationItem") -> "typing.Dict[str, object]":
10
+ """Include local message metadata without changing model serialization."""
11
+ payload = item.serialize()
12
+ if isinstance(item, UserMessage):
13
+ payload["name"] = item.name
14
+ if isinstance(item, (UserMessage, AgentMessage, AssistantMessage)):
15
+ payload["visible"] = item.visible
16
+ return payload
17
+
18
+
19
+ def restore_visibility(item, payload):
20
+ """Older rollouts use the message type's visibility default."""
21
+ visible = payload.get("visible", item.visible)
22
+ if not isinstance(visible, bool):
23
+ raise ValueError("history item visible must be a boolean")
24
+ return replace(item, visible=visible)
25
+
26
+
27
+ def iter_display_turns(history):
28
+ """Project message visibility and grouping; None marks a compaction."""
29
+ prompt = None
30
+ response = ""
31
+ phase = None
32
+ for item in history:
33
+ if item is None:
34
+ if prompt is not None or response:
35
+ yield (prompt or "", response)
36
+ yield None
37
+ prompt, response, phase = None, "", None
38
+ elif isinstance(item, (UserMessage, AgentMessage)):
39
+ # Hidden mail must not split commentary from its final answer.
40
+ # Keep an existing unphased reply when the next input arrives.
41
+ if item.visible or (response and phase != "commentary"):
42
+ if prompt is not None or response:
43
+ yield (prompt or "", response)
44
+ prompt, response, phase = None, "", None
45
+ if item.visible:
46
+ prompt = item.text
47
+ elif isinstance(item, AssistantMessage) and item.visible:
48
+ response, phase = item.text, item.phase
49
+ if phase == "final":
50
+ yield (prompt or "", response)
51
+ prompt, response, phase = None, "", None
52
+ if prompt is not None or response:
53
+ yield (prompt or "", response)
54
+
55
+
56
+ def conversation_history_to_turns(
57
+ history: "typing.Iterable[ConversationItem]",
58
+ ) -> "typing.Tuple[typing.Tuple[str, str], ...]":
59
+ return tuple(entry for entry in iter_display_turns(history) if entry is not None)