python-codex 0.5.1__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.
- pycodex/__init__.py +18 -8
- pycodex/agent.py +89 -74
- pycodex/bootstrap.py +27 -239
- pycodex/cli.py +19 -14
- pycodex/config.py +36 -0
- pycodex/context.py +369 -51
- pycodex/events.py +28 -186
- pycodex/model.py +181 -88
- pycodex/multi_agents.py +401 -0
- pycodex/portable/__init__.py +8 -6
- pycodex/portable/client.py +24 -39
- pycodex/portable/protocol.py +28 -0
- pycodex/portable/server.py +3 -3
- pycodex/prompts/developer_messages.json +13 -0
- pycodex/prompts/goals/budget_limit.md +19 -0
- pycodex/prompts/goals/continuation.md +56 -0
- pycodex/prompts/models.json +1069 -140
- pycodex/protocol.py +78 -15
- pycodex/runtime.py +461 -203
- pycodex/tools/__init__.py +100 -7
- pycodex/tools/agent_tool_schemas.py +0 -38
- pycodex/tools/apply_patch_tool.py +17 -34
- pycodex/tools/base_tool.py +63 -29
- pycodex/tools/clock_manager.py +182 -0
- pycodex/tools/clock_tool.py +2 -139
- pycodex/tools/code_mode_manager.py +165 -246
- pycodex/tools/exec_command_tool.py +0 -12
- pycodex/tools/exec_runtime.py +381 -0
- pycodex/tools/exec_tool.py +78 -31
- pycodex/tools/followup_task_tool.py +44 -0
- pycodex/tools/goal_manager.py +205 -0
- pycodex/tools/goal_tool.py +126 -0
- pycodex/tools/interrupt_agent_tool.py +48 -0
- pycodex/tools/list_agents_tool.py +66 -0
- pycodex/tools/python_tool_schema.py +141 -0
- pycodex/tools/request_permissions_tool.py +1 -0
- pycodex/tools/request_user_input_tool.py +3 -23
- pycodex/tools/runtime_services.py +124 -408
- pycodex/tools/send_message_tool.py +42 -0
- pycodex/tools/spawn_agent_tool.py +55 -94
- pycodex/tools/unified_exec_manager.py +52 -34
- pycodex/tools/wait_agent_tool.py +46 -66
- pycodex/tools/wait_tool.py +24 -13
- pycodex/tools/web_search_tool.py +1 -0
- pycodex/utils/codex_config.py +105 -0
- pycodex/utils/compactor.py +4 -0
- pycodex/utils/compat.py +2 -2
- pycodex/utils/doctor.py +5 -4
- pycodex/utils/event_helpers.py +143 -13
- pycodex/utils/history.py +33 -0
- pycodex/utils/session_persist.py +106 -33
- python_codex-0.6.0.dist-info/METADATA +352 -0
- python_codex-0.6.0.dist-info/RECORD +106 -0
- responses_server/__init__.py +2 -0
- responses_server/app.py +7 -6
- responses_server/config.py +0 -11
- responses_server/payload_processors.py +4 -4
- responses_server/request_translation.py +480 -0
- responses_server/server.py +31 -24
- responses_server/stream_events.py +124 -0
- responses_server/stream_router.py +33 -830
- responses_server/tools/custom_adapter.py +29 -29
- responses_server/transport.py +332 -0
- pycodex/tools/close_agent_tool.py +0 -60
- pycodex/tools/exec_runtime.js +0 -161
- pycodex/tools/resume_agent_tool.py +0 -54
- pycodex/tools/send_input_tool.py +0 -110
- python_codex-0.5.1.dist-info/METADATA +0 -235
- python_codex-0.5.1.dist-info/RECORD +0 -90
- {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/WHEEL +0 -0
- {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/entry_points.txt +0 -0
- {python_codex-0.5.1.dist-info → python_codex-0.6.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import typing
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import tomllib
|
|
7
|
+
except ModuleNotFoundError: # pragma: no cover - Python 3.10 and earlier
|
|
8
|
+
import tomli as tomllib
|
|
9
|
+
|
|
10
|
+
DEFAULT_CODEX_CONFIG_PATH = Path.home() / ".codex" / "config.toml"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def read_codex_config(
|
|
14
|
+
config_path: "typing.Union[str, Path]",
|
|
15
|
+
profile: "typing.Union[str, None]" = None,
|
|
16
|
+
use_default_profile: "bool" = True,
|
|
17
|
+
) -> "typing.Dict[str, typing.Any]":
|
|
18
|
+
"""Merge a file or embedded profile over the base config.
|
|
19
|
+
|
|
20
|
+
Disable default selection when restoring an explicitly saved base config.
|
|
21
|
+
The returned ``profile`` is the effective name, or None for the base config.
|
|
22
|
+
"""
|
|
23
|
+
path = Path(config_path)
|
|
24
|
+
selected = _read_config_file(path)
|
|
25
|
+
profiles = _embedded_profiles(selected, path)
|
|
26
|
+
if profile is None and use_default_profile:
|
|
27
|
+
profile = selected.get("profile")
|
|
28
|
+
if profile is not None:
|
|
29
|
+
_validate_profile_name(profile)
|
|
30
|
+
profile_path = path.parent / (profile + ".config.toml")
|
|
31
|
+
if profile in profiles:
|
|
32
|
+
if profile_path.exists():
|
|
33
|
+
_raise_profile_conflict(path, profile)
|
|
34
|
+
overrides = profiles[profile]
|
|
35
|
+
else:
|
|
36
|
+
overrides = _read_config_file(profile_path)
|
|
37
|
+
if "profile" in overrides:
|
|
38
|
+
raise ValueError(
|
|
39
|
+
"Codex profile {!r} cannot select another profile".format(profile)
|
|
40
|
+
)
|
|
41
|
+
selected = _merge_config(selected, overrides)
|
|
42
|
+
selected["profile"] = profile
|
|
43
|
+
return selected
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def list_codex_profiles(
|
|
47
|
+
config_path: "typing.Union[str, Path]",
|
|
48
|
+
) -> "typing.List[str]":
|
|
49
|
+
"""List file and embedded profiles, rejecting ambiguous names."""
|
|
50
|
+
config_path = Path(config_path)
|
|
51
|
+
profiles = _embedded_profiles(_read_config_file(config_path), config_path)
|
|
52
|
+
suffix = ".config.toml"
|
|
53
|
+
files = {
|
|
54
|
+
path.name[:-len(suffix)]
|
|
55
|
+
for path in config_path.parent.glob("*" + suffix)
|
|
56
|
+
if path.is_file()
|
|
57
|
+
and re.fullmatch(r"[A-Za-z0-9_-]+", path.name[:-len(suffix)])
|
|
58
|
+
}
|
|
59
|
+
for profile in sorted(files.intersection(profiles)):
|
|
60
|
+
_raise_profile_conflict(config_path, profile)
|
|
61
|
+
return sorted(files.union(profiles))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _validate_profile_name(profile: "str") -> "None":
|
|
65
|
+
if not isinstance(profile, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", profile):
|
|
66
|
+
raise ValueError("invalid Codex profile name: {!r}".format(profile))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _embedded_profiles(
|
|
70
|
+
data: "typing.Dict[str, typing.Any]", path: "Path",
|
|
71
|
+
) -> "typing.Dict[str, typing.Any]":
|
|
72
|
+
profiles = data.get("profiles", {})
|
|
73
|
+
if not isinstance(profiles, dict):
|
|
74
|
+
raise ValueError("profiles in {} must be a table".format(path))
|
|
75
|
+
for name, settings in profiles.items():
|
|
76
|
+
_validate_profile_name(name)
|
|
77
|
+
if not isinstance(settings, dict):
|
|
78
|
+
raise ValueError("[profiles.{}] in {} must be a table".format(name, path))
|
|
79
|
+
return profiles
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _raise_profile_conflict(path: "Path", profile: "str") -> "None":
|
|
83
|
+
raise ValueError(
|
|
84
|
+
"ambiguous Codex profile {0!r}: both [profiles.{0}] in {1} and {2} "
|
|
85
|
+
"exist; keep only one definition".format(
|
|
86
|
+
profile, path, path.parent / (profile + ".config.toml"),
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _merge_config(
|
|
92
|
+
base: "typing.Dict[str, typing.Any]",
|
|
93
|
+
overrides: "typing.Dict[str, typing.Any]",
|
|
94
|
+
) -> "typing.Dict[str, typing.Any]":
|
|
95
|
+
merged = dict(base)
|
|
96
|
+
for key, value in overrides.items():
|
|
97
|
+
if isinstance(merged.get(key), dict) and isinstance(value, dict):
|
|
98
|
+
merged[key] = _merge_config(merged[key], value)
|
|
99
|
+
else:
|
|
100
|
+
merged[key] = value
|
|
101
|
+
return merged
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _read_config_file(path: "Path") -> "typing.Dict[str, typing.Any]":
|
|
105
|
+
return tomllib.loads(path.read_text(encoding="utf-8"))
|
pycodex/utils/compactor.py
CHANGED
|
@@ -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
|
@@ -20,9 +20,9 @@ except ImportError: # pragma: no cover - Python 3.6 path
|
|
|
20
20
|
import importlib_metadata # type: ignore
|
|
21
21
|
|
|
22
22
|
try:
|
|
23
|
-
from typing import Literal, Protocol, TypeAlias
|
|
23
|
+
from typing import Literal, Protocol, TypeAlias, TypedDict
|
|
24
24
|
except ImportError: # pragma: no cover - Python 3.6 path
|
|
25
|
-
from typing_extensions import Literal, Protocol # type: ignore
|
|
25
|
+
from typing_extensions import Literal, Protocol, TypedDict # type: ignore
|
|
26
26
|
|
|
27
27
|
try:
|
|
28
28
|
from typing_extensions import TypeAlias # type: ignore
|
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="
|
|
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
|
-
|
|
121
|
-
|
|
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/event_helpers.py
CHANGED
|
@@ -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
|
|
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
|
-
"
|
|
146
|
-
"
|
|
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
|
pycodex/utils/history.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Pure conversation-history projections, independent of rollout storage."""
|
|
2
|
+
|
|
3
|
+
import typing
|
|
4
|
+
|
|
5
|
+
from ..protocol import AgentMessage, AssistantMessage, ConversationItem, UserMessage
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def serialize_history_item(item: "ConversationItem") -> "typing.Dict[str, object]":
|
|
9
|
+
"""Include local message metadata without changing model serialization."""
|
|
10
|
+
payload = item.serialize()
|
|
11
|
+
if isinstance(item, UserMessage):
|
|
12
|
+
payload["name"] = item.name
|
|
13
|
+
return payload
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def conversation_history_to_turns(
|
|
17
|
+
history: "typing.Iterable[ConversationItem]",
|
|
18
|
+
) -> "typing.Tuple[typing.Tuple[str, str], ...]":
|
|
19
|
+
turns: "typing.List[typing.Tuple[str, str]]" = []
|
|
20
|
+
current_user_text: "typing.Union[str, None]" = None
|
|
21
|
+
current_assistant_text = ""
|
|
22
|
+
for item in history:
|
|
23
|
+
if isinstance(item, (UserMessage, AgentMessage)):
|
|
24
|
+
if current_user_text is not None or current_assistant_text:
|
|
25
|
+
turns.append((current_user_text or "", current_assistant_text))
|
|
26
|
+
current_user_text = item.text
|
|
27
|
+
current_assistant_text = ""
|
|
28
|
+
continue
|
|
29
|
+
if isinstance(item, AssistantMessage):
|
|
30
|
+
current_assistant_text = item.text
|
|
31
|
+
if current_user_text is not None or current_assistant_text:
|
|
32
|
+
turns.append((current_user_text or "", current_assistant_text))
|
|
33
|
+
return tuple(turns)
|
pycodex/utils/session_persist.py
CHANGED
|
@@ -2,13 +2,16 @@ import json
|
|
|
2
2
|
import mmap
|
|
3
3
|
import os
|
|
4
4
|
import re
|
|
5
|
+
import tempfile
|
|
5
6
|
import typing
|
|
6
7
|
from collections import deque
|
|
7
8
|
from contextlib import closing
|
|
9
|
+
from copy import deepcopy
|
|
8
10
|
from datetime import datetime
|
|
9
11
|
from pathlib import Path
|
|
10
12
|
|
|
11
13
|
from ..protocol import (
|
|
14
|
+
AgentMessage,
|
|
12
15
|
AssistantMessage,
|
|
13
16
|
ContextMessage,
|
|
14
17
|
ConversationItem,
|
|
@@ -16,9 +19,11 @@ from ..protocol import (
|
|
|
16
19
|
ToolCall,
|
|
17
20
|
ToolResult,
|
|
18
21
|
UserMessage,
|
|
22
|
+
qualified_tool_name,
|
|
19
23
|
)
|
|
20
24
|
from .compactor import SUMMARY_PREFIX
|
|
21
25
|
from .event_helpers import shorten_title
|
|
26
|
+
from .history import conversation_history_to_turns, serialize_history_item
|
|
22
27
|
from .get_env import get_package_version
|
|
23
28
|
|
|
24
29
|
SESSION_INDEX_FILENAME = "session_index.jsonl"
|
|
@@ -44,9 +49,49 @@ def resolve_codex_home(
|
|
|
44
49
|
|
|
45
50
|
|
|
46
51
|
class SessionRolloutRecorder:
|
|
52
|
+
@property
|
|
53
|
+
def recorded_path(self):
|
|
54
|
+
return self.rollout_path if self._session_meta is None else None
|
|
55
|
+
|
|
47
56
|
def __init__(self, rollout_path: "Path") -> "None":
|
|
48
57
|
self.rollout_path = rollout_path
|
|
49
58
|
self._session_meta: "typing.Union[typing.Dict[str, object], None]" = None
|
|
59
|
+
self._environment_state_json = None
|
|
60
|
+
|
|
61
|
+
def read_environment_state(self):
|
|
62
|
+
path = Path(str(self.rollout_path) + ".state.json")
|
|
63
|
+
try:
|
|
64
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
65
|
+
state = json.load(handle)
|
|
66
|
+
except FileNotFoundError:
|
|
67
|
+
return None
|
|
68
|
+
self._environment_state_json = json.dumps(
|
|
69
|
+
state, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
|
70
|
+
)
|
|
71
|
+
return state
|
|
72
|
+
|
|
73
|
+
def save_environment_state(self, state):
|
|
74
|
+
serialized = json.dumps(
|
|
75
|
+
state, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
|
76
|
+
)
|
|
77
|
+
if serialized == self._environment_state_json:
|
|
78
|
+
return
|
|
79
|
+
path = Path(str(self.rollout_path) + ".state.json")
|
|
80
|
+
temporary = tempfile.NamedTemporaryFile(
|
|
81
|
+
mode="w", encoding="utf-8", dir=str(path.parent),
|
|
82
|
+
prefix=path.name + ".", delete=False,
|
|
83
|
+
)
|
|
84
|
+
temporary_path = Path(temporary.name)
|
|
85
|
+
try:
|
|
86
|
+
with temporary as handle:
|
|
87
|
+
handle.write(serialized + "\n")
|
|
88
|
+
handle.flush()
|
|
89
|
+
os.fsync(handle.fileno())
|
|
90
|
+
os.replace(str(temporary_path), str(path))
|
|
91
|
+
finally:
|
|
92
|
+
if temporary_path.exists():
|
|
93
|
+
temporary_path.unlink()
|
|
94
|
+
self._environment_state_json = serialized
|
|
50
95
|
|
|
51
96
|
@classmethod
|
|
52
97
|
def create(
|
|
@@ -103,16 +148,17 @@ class SessionRolloutRecorder:
|
|
|
103
148
|
for item in items:
|
|
104
149
|
history.append(item)
|
|
105
150
|
if isinstance(item, ContextMessage) and item.role == "user":
|
|
106
|
-
# Preserve
|
|
151
|
+
# Preserve compact summaries as context when replayed.
|
|
107
152
|
yield "compacted", _compacted_payload(history)
|
|
108
153
|
continue
|
|
109
|
-
serialized = item
|
|
154
|
+
serialized = serialize_history_item(item)
|
|
110
155
|
if isinstance(serialized, dict):
|
|
111
156
|
yield "response_item", serialized
|
|
112
157
|
if isinstance(item, UserMessage):
|
|
113
158
|
yield "event_msg", {
|
|
114
159
|
"type": "user_message",
|
|
115
160
|
"message": item.text,
|
|
161
|
+
"name": item.name,
|
|
116
162
|
"images": [],
|
|
117
163
|
"local_images": [],
|
|
118
164
|
"text_elements": [],
|
|
@@ -232,7 +278,7 @@ def load_resumed_session_path(
|
|
|
232
278
|
thread_id = _thread_id_from_rollout_path(rollout_path) or ""
|
|
233
279
|
session_id = thread_id
|
|
234
280
|
history: "typing.List[ConversationItem]" = []
|
|
235
|
-
|
|
281
|
+
saw_input = False
|
|
236
282
|
tool_names_by_call_id: "typing.Dict[str, str]" = {}
|
|
237
283
|
|
|
238
284
|
# A rollout is append-only, and a compacted entry replaces everything
|
|
@@ -262,8 +308,9 @@ def load_resumed_session_path(
|
|
|
262
308
|
history = _deserialize_compacted_history(
|
|
263
309
|
replacement_history, payload.get("message")
|
|
264
310
|
)
|
|
265
|
-
|
|
266
|
-
isinstance(item, (UserMessage, ContextMessage))
|
|
311
|
+
saw_input = any(
|
|
312
|
+
isinstance(item, (UserMessage, AgentMessage, ContextMessage))
|
|
313
|
+
for item in history
|
|
267
314
|
)
|
|
268
315
|
tool_names_by_call_id = {
|
|
269
316
|
item.call_id: item.name
|
|
@@ -274,15 +321,17 @@ def load_resumed_session_path(
|
|
|
274
321
|
|
|
275
322
|
if item_type == "event_msg" and isinstance(payload, dict):
|
|
276
323
|
if payload.get("type") == "user_message":
|
|
277
|
-
history.append(UserMessage(
|
|
278
|
-
|
|
324
|
+
history.append(UserMessage(
|
|
325
|
+
text=str(payload.get("message", "")), name=payload.get("name", "user")
|
|
326
|
+
))
|
|
327
|
+
saw_input = True
|
|
279
328
|
continue
|
|
280
329
|
|
|
281
|
-
if (
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
330
|
+
if item_type != "response_item" or not isinstance(payload, dict):
|
|
331
|
+
continue
|
|
332
|
+
if payload.get("type") == "agent_message":
|
|
333
|
+
saw_input = True
|
|
334
|
+
if not saw_input:
|
|
286
335
|
continue
|
|
287
336
|
|
|
288
337
|
_append_deserialized_response_item(
|
|
@@ -312,24 +361,37 @@ def load_resumed_session_path(
|
|
|
312
361
|
}
|
|
313
362
|
|
|
314
363
|
|
|
315
|
-
def
|
|
316
|
-
|
|
317
|
-
)
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
364
|
+
def read_rollout_history_page(rollout_path, before=None, limit=100):
|
|
365
|
+
"""Read a bounded page of conversation records in chronological order."""
|
|
366
|
+
if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 200:
|
|
367
|
+
raise ValueError("limit must be between 1 and 200")
|
|
368
|
+
if before is not None and (
|
|
369
|
+
isinstance(before, bool) or not isinstance(before, int) or before < 0
|
|
370
|
+
):
|
|
371
|
+
raise ValueError("before must be a non-negative record index")
|
|
372
|
+
entries = deque(maxlen=limit + 1)
|
|
373
|
+
index = 0
|
|
374
|
+
for entry in _iter_rollout_entries(Path(rollout_path)):
|
|
375
|
+
kind = entry.get("type")
|
|
376
|
+
if kind not in {"response_item", "compacted"}:
|
|
327
377
|
continue
|
|
328
|
-
if
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
378
|
+
if before is not None and index >= before:
|
|
379
|
+
break
|
|
380
|
+
payload = entry["payload"]
|
|
381
|
+
if kind == "compacted":
|
|
382
|
+
payload = {"message": payload.get("message", "")}
|
|
383
|
+
elif payload.get("type") == "message" and payload.get("role") == "user":
|
|
384
|
+
payload.setdefault("name", "user")
|
|
385
|
+
entries.append({"index": index, "type": kind, "payload": payload})
|
|
386
|
+
index += 1
|
|
387
|
+
if before is not None and before > index:
|
|
388
|
+
raise ValueError("history cursor is beyond the current history")
|
|
389
|
+
more = len(entries) > limit
|
|
390
|
+
items = list(entries)[-limit:]
|
|
391
|
+
return {
|
|
392
|
+
"items": items,
|
|
393
|
+
"next_before": items[0]["index"] if more else None,
|
|
394
|
+
}
|
|
333
395
|
|
|
334
396
|
|
|
335
397
|
def load_display_history(
|
|
@@ -348,6 +410,8 @@ def load_display_history(
|
|
|
348
410
|
turns.append(None)
|
|
349
411
|
elif item_type == "event_msg" and payload.get("type") == "user_message":
|
|
350
412
|
turns.append((str(payload.get("message", "")), ""))
|
|
413
|
+
elif item_type == "response_item" and payload.get("type") == "agent_message":
|
|
414
|
+
turns.append((AgentMessage.from_response_item(payload).text, ""))
|
|
351
415
|
elif (
|
|
352
416
|
item_type == "response_item"
|
|
353
417
|
and payload.get("type") == "message"
|
|
@@ -519,7 +583,7 @@ def _compacted_payload(
|
|
|
519
583
|
) -> "typing.Dict[str, object]":
|
|
520
584
|
payload: "typing.Dict[str, object]" = {"replacement_history": []}
|
|
521
585
|
for item in history:
|
|
522
|
-
serialized = item
|
|
586
|
+
serialized = serialize_history_item(item)
|
|
523
587
|
if isinstance(serialized, dict):
|
|
524
588
|
payload["replacement_history"].append(serialized)
|
|
525
589
|
if isinstance(item, ContextMessage) and item.role == "user":
|
|
@@ -560,6 +624,9 @@ def _append_deserialized_response_item(
|
|
|
560
624
|
include_user_messages: "bool",
|
|
561
625
|
) -> "None":
|
|
562
626
|
response_item_type = str(payload.get("type", "")).strip()
|
|
627
|
+
if response_item_type == "agent_message":
|
|
628
|
+
history.append(AgentMessage.from_response_item(payload))
|
|
629
|
+
return
|
|
563
630
|
if response_item_type == "message":
|
|
564
631
|
role = str(payload.get("role", "")).strip()
|
|
565
632
|
if role == "assistant":
|
|
@@ -568,7 +635,8 @@ def _append_deserialized_response_item(
|
|
|
568
635
|
if include_user_messages and role == "user":
|
|
569
636
|
history.append(
|
|
570
637
|
UserMessage(
|
|
571
|
-
text=_extract_response_message_text(payload), id=payload.get("id")
|
|
638
|
+
text=_extract_response_message_text(payload), id=payload.get("id"),
|
|
639
|
+
name=payload.get("name", "user"),
|
|
572
640
|
)
|
|
573
641
|
)
|
|
574
642
|
return
|
|
@@ -594,6 +662,8 @@ def _append_deserialized_response_item(
|
|
|
594
662
|
name = str(payload.get("name", "")).strip()
|
|
595
663
|
if not call_id or not name:
|
|
596
664
|
return
|
|
665
|
+
namespace = payload.get("namespace")
|
|
666
|
+
name = qualified_tool_name(name, namespace)
|
|
597
667
|
history.append(
|
|
598
668
|
ToolCall(
|
|
599
669
|
call_id=call_id,
|
|
@@ -601,7 +671,8 @@ def _append_deserialized_response_item(
|
|
|
601
671
|
arguments=arguments,
|
|
602
672
|
id=payload.get("id"),
|
|
603
673
|
raw_arguments=raw_arguments if isinstance(raw_arguments, str) else None,
|
|
604
|
-
namespace=
|
|
674
|
+
namespace=namespace,
|
|
675
|
+
encrypted_function_args=deepcopy(payload.get("encrypted_function_args")),
|
|
605
676
|
)
|
|
606
677
|
)
|
|
607
678
|
tool_names_by_call_id[call_id] = name
|
|
@@ -612,6 +683,8 @@ def _append_deserialized_response_item(
|
|
|
612
683
|
name = str(payload.get("name", "")).strip()
|
|
613
684
|
if not call_id or not name:
|
|
614
685
|
return
|
|
686
|
+
namespace = payload.get("namespace")
|
|
687
|
+
name = qualified_tool_name(name, namespace)
|
|
615
688
|
history.append(
|
|
616
689
|
ToolCall(
|
|
617
690
|
call_id=call_id,
|
|
@@ -619,7 +692,7 @@ def _append_deserialized_response_item(
|
|
|
619
692
|
arguments=str(payload.get("input", "")),
|
|
620
693
|
tool_type="custom",
|
|
621
694
|
id=payload.get("id"),
|
|
622
|
-
namespace=
|
|
695
|
+
namespace=namespace,
|
|
623
696
|
status=payload.get("status"),
|
|
624
697
|
)
|
|
625
698
|
)
|