python-codex 0.6.0__py3-none-any.whl → 0.6.2__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 +4 -4
- pycodex/agent.py +28 -9
- pycodex/bootstrap.py +10 -12
- pycodex/cli.py +0 -14
- pycodex/context.py +43 -32
- pycodex/events.py +20 -11
- pycodex/model.py +16 -7
- pycodex/prompts/models.json +14 -0
- pycodex/protocol.py +18 -0
- pycodex/runtime.py +49 -54
- pycodex/tools/__init__.py +9 -10
- pycodex/tools/clock_tool.py +57 -7
- pycodex/tools/exec_runtime.py +29 -78
- pycodex/tools/exec_tool.py +2 -6
- pycodex/utils/compat.py +41 -0
- pycodex/utils/dotenv.py +0 -7
- pycodex/utils/event_helpers.py +5 -9
- pycodex/utils/history.py +79 -20
- pycodex/utils/session_persist.py +133 -36
- pycodex/utils/skill_catalog.py +18 -0
- python_codex-0.6.2.dist-info/METADATA +216 -0
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/RECORD +33 -32
- responses_server/app.py +3 -1
- responses_server/config.py +6 -1
- responses_server/gemini_api.py +336 -0
- responses_server/messages_api.py +9 -1
- responses_server/request_translation.py +6 -0
- responses_server/stream_router.py +15 -0
- responses_server/tools/web_search.py +3 -0
- responses_server/transport.py +75 -19
- pycodex/tools/request_user_input_tool.py +0 -82
- python_codex-0.6.0.dist-info/METADATA +0 -352
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/WHEEL +0 -0
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.0.dist-info → python_codex-0.6.2.dist-info}/licenses/LICENSE +0 -0
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
|
|
@@ -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/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]" = {}
|
pycodex/utils/event_helpers.py
CHANGED
|
@@ -56,10 +56,13 @@ def format_command_result(result: "typing.Dict[str, object]") -> "str":
|
|
|
56
56
|
if kind in {"history", "resumed"}:
|
|
57
57
|
state = result["state"]
|
|
58
58
|
lines = ["Resumed session: " + state["title"]] if kind == "resumed" else []
|
|
59
|
-
|
|
59
|
+
turns = [turn for turn in state["history"] if turn["kind"] == "assistant"]
|
|
60
|
+
if not turns:
|
|
60
61
|
return "\n".join(lines + ["No history yet."])
|
|
61
62
|
lines.append("Session: " + (state["title"] or "untitled"))
|
|
62
|
-
for index,
|
|
63
|
+
for index, turn in enumerate(turns, 1):
|
|
64
|
+
prompt = "\n".join(message.text for message in turn["messages"])
|
|
65
|
+
response = turn["response"]
|
|
63
66
|
if prompt:
|
|
64
67
|
lines.append("[{0}]U> {1}".format(index, prompt))
|
|
65
68
|
if response:
|
|
@@ -98,13 +101,6 @@ def percent_of_context_window_remaining(total_tokens, context_window_tokens):
|
|
|
98
101
|
return int(round(max(0.0, min(100.0, (remaining / effective_window) * 100.0))))
|
|
99
102
|
|
|
100
103
|
|
|
101
|
-
def completed_history(state):
|
|
102
|
-
active = state["active_turn"]
|
|
103
|
-
if active is not None:
|
|
104
|
-
return active["completed_history"]
|
|
105
|
-
return state["history"]
|
|
106
|
-
|
|
107
|
-
|
|
108
104
|
def colorize_cli_message(text: "str", kind: "str", enabled: "bool") -> "str":
|
|
109
105
|
if not enabled:
|
|
110
106
|
return text
|
pycodex/utils/history.py
CHANGED
|
@@ -1,33 +1,92 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Message storage metadata and pure display conversion."""
|
|
2
2
|
|
|
3
|
-
import
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import replace
|
|
5
|
+
from hashlib import sha256
|
|
4
6
|
|
|
5
|
-
from ..protocol import AgentMessage, AssistantMessage,
|
|
7
|
+
from ..protocol import AgentMessage, AssistantMessage, UserMessage
|
|
6
8
|
|
|
7
9
|
|
|
8
|
-
def serialize_history_item(item
|
|
9
|
-
"""Include local message metadata without changing model serialization."""
|
|
10
|
+
def serialize_history_item(item):
|
|
10
11
|
payload = item.serialize()
|
|
11
12
|
if isinstance(item, UserMessage):
|
|
12
13
|
payload["name"] = item.name
|
|
14
|
+
if isinstance(item, (UserMessage, AgentMessage, AssistantMessage)):
|
|
15
|
+
payload.update(message_id=item.message_id, created_at=item.created_at,
|
|
16
|
+
turn_id=item.turn_id, visible=item.visible)
|
|
13
17
|
return payload
|
|
14
18
|
|
|
15
19
|
|
|
16
|
-
def
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
def restore_message_metadata(item, payload, record_id, timestamp=None):
|
|
21
|
+
visible = payload.get("visible", item.visible)
|
|
22
|
+
if not isinstance(visible, bool):
|
|
23
|
+
raise ValueError("history item visible must be a boolean")
|
|
24
|
+
legacy_id = sha256(json.dumps(
|
|
25
|
+
[record_id, timestamp, payload], ensure_ascii=False, sort_keys=True,
|
|
26
|
+
).encode("utf-8")).hexdigest()[:32]
|
|
27
|
+
return replace(
|
|
28
|
+
item, visible=visible, message_id=payload.get("message_id", "legacy-" + legacy_id),
|
|
29
|
+
created_at=payload.get("created_at", timestamp), turn_id=payload.get("turn_id"),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def conversation_history_to_turns(history, previous=()):
|
|
34
|
+
"""Convert a transcript or append committed items to existing display values.
|
|
35
|
+
|
|
36
|
+
The caller owns the result; neither the previous values nor messages change.
|
|
37
|
+
Explicit turn IDs group new messages. Old records retain phase boundaries.
|
|
38
|
+
"""
|
|
39
|
+
turns = [
|
|
40
|
+
{key: turn[key] for key in (
|
|
41
|
+
"turn_id", "messages", "response", "response_id", "response_at",
|
|
42
|
+
"response_phase", "kind",
|
|
43
|
+
)}
|
|
44
|
+
for turn in previous
|
|
45
|
+
]
|
|
46
|
+
by_id = {turn["turn_id"]: turn for turn in turns}
|
|
47
|
+
current = turns[-1] if turns else None
|
|
48
|
+
if current is not None and (
|
|
49
|
+
current["kind"] == "compaction" or current["response_phase"] == "final"
|
|
50
|
+
):
|
|
51
|
+
current = None
|
|
22
52
|
for item in history:
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
53
|
+
is_compaction = item is None or (
|
|
54
|
+
isinstance(item, dict) and item.get("type") == "compacted"
|
|
55
|
+
)
|
|
56
|
+
if is_compaction:
|
|
57
|
+
turn_id = item["id"] if item is not None else "compaction-{0}".format(len(turns))
|
|
58
|
+
current = None
|
|
59
|
+
elif isinstance(item, (UserMessage, AgentMessage, AssistantMessage)):
|
|
60
|
+
is_input = isinstance(item, (UserMessage, AgentMessage))
|
|
61
|
+
if item.turn_id is None and is_input and (
|
|
62
|
+
item.visible or (current is not None and current["response"]
|
|
63
|
+
and current["response_phase"] != "commentary")
|
|
64
|
+
):
|
|
65
|
+
current = None
|
|
66
|
+
if not item.visible:
|
|
67
|
+
continue
|
|
68
|
+
turn_id = item.turn_id or (current["turn_id"] if current is not None else item.message_id)
|
|
69
|
+
else:
|
|
70
|
+
continue
|
|
71
|
+
turn = by_id.get(turn_id)
|
|
72
|
+
if turn is None:
|
|
73
|
+
turn = {
|
|
74
|
+
"turn_id": turn_id, "messages": (), "response": "",
|
|
75
|
+
"response_id": None, "response_at": None, "response_phase": None,
|
|
76
|
+
"kind": "compaction" if is_compaction else "assistant",
|
|
77
|
+
}
|
|
78
|
+
turns.append(turn)
|
|
79
|
+
by_id[turn_id] = turn
|
|
80
|
+
if is_compaction:
|
|
28
81
|
continue
|
|
29
|
-
if
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
82
|
+
if is_input:
|
|
83
|
+
messages = list(turn["messages"])
|
|
84
|
+
position = next((index for index, message in enumerate(messages)
|
|
85
|
+
if message.message_id == item.message_id), len(messages))
|
|
86
|
+
messages[position:position + 1] = [item]
|
|
87
|
+
turn["messages"] = tuple(messages)
|
|
88
|
+
else:
|
|
89
|
+
turn.update(response=item.text, response_id=item.message_id,
|
|
90
|
+
response_at=item.created_at, response_phase=item.phase)
|
|
91
|
+
current = None if turn["response_phase"] == "final" else turn
|
|
33
92
|
return tuple(turns)
|
pycodex/utils/session_persist.py
CHANGED
|
@@ -23,7 +23,9 @@ from ..protocol import (
|
|
|
23
23
|
)
|
|
24
24
|
from .compactor import SUMMARY_PREFIX
|
|
25
25
|
from .event_helpers import shorten_title
|
|
26
|
-
from .history import
|
|
26
|
+
from .history import (
|
|
27
|
+
conversation_history_to_turns, restore_message_metadata, serialize_history_item,
|
|
28
|
+
)
|
|
27
29
|
from .get_env import get_package_version
|
|
28
30
|
|
|
29
31
|
SESSION_INDEX_FILENAME = "session_index.jsonl"
|
|
@@ -159,6 +161,10 @@ class SessionRolloutRecorder:
|
|
|
159
161
|
"type": "user_message",
|
|
160
162
|
"message": item.text,
|
|
161
163
|
"name": item.name,
|
|
164
|
+
"visible": item.visible,
|
|
165
|
+
"message_id": item.message_id,
|
|
166
|
+
"created_at": item.created_at,
|
|
167
|
+
"turn_id": item.turn_id,
|
|
162
168
|
"images": [],
|
|
163
169
|
"local_images": [],
|
|
164
170
|
"text_elements": [],
|
|
@@ -306,7 +312,7 @@ def load_resumed_session_path(
|
|
|
306
312
|
replacement_history = payload.get("replacement_history")
|
|
307
313
|
if isinstance(replacement_history, list):
|
|
308
314
|
history = _deserialize_compacted_history(
|
|
309
|
-
replacement_history, payload.get("message")
|
|
315
|
+
replacement_history, payload.get("message"), entry["_record_offset"],
|
|
310
316
|
)
|
|
311
317
|
saw_input = any(
|
|
312
318
|
isinstance(item, (UserMessage, AgentMessage, ContextMessage))
|
|
@@ -321,9 +327,7 @@ def load_resumed_session_path(
|
|
|
321
327
|
|
|
322
328
|
if item_type == "event_msg" and isinstance(payload, dict):
|
|
323
329
|
if payload.get("type") == "user_message":
|
|
324
|
-
history.append(
|
|
325
|
-
text=str(payload.get("message", "")), name=payload.get("name", "user")
|
|
326
|
-
))
|
|
330
|
+
history.append(_user_message_from_event(payload, entry))
|
|
327
331
|
saw_input = True
|
|
328
332
|
continue
|
|
329
333
|
|
|
@@ -339,6 +343,7 @@ def load_resumed_session_path(
|
|
|
339
343
|
payload,
|
|
340
344
|
tool_names_by_call_id,
|
|
341
345
|
include_user_messages=False,
|
|
346
|
+
record_id=entry["_record_offset"], timestamp=entry.get("timestamp"),
|
|
342
347
|
)
|
|
343
348
|
|
|
344
349
|
if not history:
|
|
@@ -349,7 +354,8 @@ def load_resumed_session_path(
|
|
|
349
354
|
raise ValueError(f"No resumable history found in {rollout_path}")
|
|
350
355
|
|
|
351
356
|
turns = conversation_history_to_turns(history)
|
|
352
|
-
first_prompt = next((
|
|
357
|
+
first_prompt = next(("\n".join(message.text for message in turn["messages"])
|
|
358
|
+
for turn in turns if turn["messages"]), "")
|
|
353
359
|
title = thread_name or shorten_title(first_prompt) or thread_id
|
|
354
360
|
return {
|
|
355
361
|
"session_id": session_id,
|
|
@@ -396,31 +402,75 @@ def read_rollout_history_page(rollout_path, before=None, limit=100):
|
|
|
396
402
|
|
|
397
403
|
def load_display_history(
|
|
398
404
|
rollout_path: "typing.Union[str, Path]",
|
|
399
|
-
limit: "int" = 80,
|
|
400
|
-
) -> "
|
|
401
|
-
"""Read
|
|
405
|
+
limit: "typing.Union[int, None]" = 80,
|
|
406
|
+
) -> "tuple":
|
|
407
|
+
"""Read recent complete display rows from the end of the rollout."""
|
|
408
|
+
if limit is None:
|
|
409
|
+
return conversation_history_to_turns(_iter_display_items(rollout_path))
|
|
410
|
+
if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
|
|
411
|
+
raise ValueError("limit must be a non-negative integer or None")
|
|
412
|
+
if limit == 0:
|
|
413
|
+
return ()
|
|
414
|
+
|
|
415
|
+
items = []
|
|
416
|
+
oldest_turn_id = None
|
|
417
|
+
remaining = limit + 1
|
|
418
|
+
with closing(_iter_display_items(rollout_path, reverse=True)) as history:
|
|
419
|
+
for item in history:
|
|
420
|
+
items.append(item)
|
|
421
|
+
if isinstance(item, dict):
|
|
422
|
+
remaining -= 1
|
|
423
|
+
if oldest_turn_id is not None:
|
|
424
|
+
continue
|
|
425
|
+
elif not item.visible:
|
|
426
|
+
continue
|
|
427
|
+
else:
|
|
428
|
+
if item.turn_id != oldest_turn_id or item.turn_id is None:
|
|
429
|
+
remaining -= 1
|
|
430
|
+
oldest_turn_id = item.turn_id
|
|
431
|
+
if remaining <= 0:
|
|
432
|
+
turns = conversation_history_to_turns(reversed(items))
|
|
433
|
+
if len(turns) > limit:
|
|
434
|
+
return turns[-limit:]
|
|
435
|
+
remaining = limit - len(turns) + 1
|
|
436
|
+
return conversation_history_to_turns(reversed(items))[-limit:]
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _user_message_from_event(payload, entry):
|
|
440
|
+
return restore_message_metadata(UserMessage(
|
|
441
|
+
text=str(payload.get("message", "")), name=payload.get("name", "user"),
|
|
442
|
+
), payload, entry["_record_offset"], entry.get("timestamp"))
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _iter_display_items(rollout_path, reverse=False):
|
|
402
446
|
path = Path(rollout_path).expanduser().resolve()
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
447
|
+
reader = _iter_rollout_entries_reverse if reverse else _iter_rollout_entries
|
|
448
|
+
with closing(reader(path)) as entries:
|
|
449
|
+
for entry in entries:
|
|
450
|
+
item_type = entry.get("type")
|
|
451
|
+
payload = entry.get("payload")
|
|
452
|
+
if not isinstance(payload, dict):
|
|
453
|
+
continue
|
|
454
|
+
timestamp = entry.get("timestamp")
|
|
455
|
+
if not isinstance(timestamp, str):
|
|
456
|
+
timestamp = None
|
|
457
|
+
if item_type == "compacted":
|
|
458
|
+
yield {"type": "compacted", "id": "compaction-{0}".format(entry["_record_offset"])}
|
|
459
|
+
elif item_type == "event_msg" and payload.get("type") == "user_message":
|
|
460
|
+
yield _user_message_from_event(payload, entry)
|
|
461
|
+
elif (
|
|
462
|
+
item_type == "response_item"
|
|
463
|
+
and (
|
|
464
|
+
payload.get("type") == "agent_message"
|
|
465
|
+
or (payload.get("type") == "message" and payload.get("role") == "assistant")
|
|
466
|
+
)
|
|
467
|
+
):
|
|
468
|
+
items = []
|
|
469
|
+
_append_deserialized_response_item(
|
|
470
|
+
items, payload, {}, False, entry["_record_offset"], timestamp,
|
|
471
|
+
)
|
|
472
|
+
for item in items:
|
|
473
|
+
yield item
|
|
424
474
|
|
|
425
475
|
|
|
426
476
|
def _drop_unmatched_tool_calls(
|
|
@@ -524,6 +574,7 @@ def _iter_rollout_entries(
|
|
|
524
574
|
) -> "typing.Iterable[typing.Dict[str, object]]":
|
|
525
575
|
decoder = json.JSONDecoder()
|
|
526
576
|
buffer = ""
|
|
577
|
+
byte_offset = start_offset
|
|
527
578
|
start = 0
|
|
528
579
|
parsed_entries = 0
|
|
529
580
|
|
|
@@ -537,14 +588,16 @@ def _iter_rollout_entries(
|
|
|
537
588
|
buffer += chunk
|
|
538
589
|
|
|
539
590
|
while True:
|
|
591
|
+
whitespace_start = start
|
|
540
592
|
while start < len(buffer) and buffer[start].isspace():
|
|
541
593
|
start += 1
|
|
594
|
+
byte_offset += len(buffer[whitespace_start:start].encode("utf-8"))
|
|
542
595
|
if start >= len(buffer):
|
|
543
596
|
buffer = ""
|
|
544
597
|
start = 0
|
|
545
598
|
break
|
|
546
599
|
try:
|
|
547
|
-
entry,
|
|
600
|
+
entry, end = decoder.raw_decode(buffer, start)
|
|
548
601
|
except json.JSONDecodeError as exc:
|
|
549
602
|
if eof:
|
|
550
603
|
if parsed_entries > 0:
|
|
@@ -556,8 +609,12 @@ def _iter_rollout_entries(
|
|
|
556
609
|
buffer = buffer[start:]
|
|
557
610
|
start = 0
|
|
558
611
|
break
|
|
612
|
+
record_offset = byte_offset
|
|
613
|
+
byte_offset += len(buffer[start:end].encode("utf-8"))
|
|
614
|
+
start = end
|
|
559
615
|
if isinstance(entry, dict):
|
|
560
616
|
parsed_entries += 1
|
|
617
|
+
entry["_record_offset"] = record_offset
|
|
561
618
|
yield entry
|
|
562
619
|
if start > ROLLOUT_READ_CHUNK_SIZE:
|
|
563
620
|
buffer = buffer[start:]
|
|
@@ -570,6 +627,38 @@ def _iter_rollout_entries(
|
|
|
570
627
|
raise ValueError(f"no rollout entries found in {rollout_path}")
|
|
571
628
|
|
|
572
629
|
|
|
630
|
+
def _iter_rollout_entries_reverse(rollout_path):
|
|
631
|
+
"""Walk JSONL records backwards, including pretty-printed legacy records."""
|
|
632
|
+
parsed_entries = 0
|
|
633
|
+
with rollout_path.open("rb") as handle:
|
|
634
|
+
if not rollout_path.stat().st_size:
|
|
635
|
+
raise ValueError("no rollout entries found in {0}".format(rollout_path))
|
|
636
|
+
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
|
|
637
|
+
end = len(mapped)
|
|
638
|
+
at_tail = True
|
|
639
|
+
while end:
|
|
640
|
+
start = mapped.rfind(b"\n{", 0, end)
|
|
641
|
+
start = start + 1 if start >= 0 else 0
|
|
642
|
+
text = mapped[start:end].decode("utf-8", errors="replace")
|
|
643
|
+
try:
|
|
644
|
+
entry = json.loads(text)
|
|
645
|
+
except json.JSONDecodeError as exc:
|
|
646
|
+
if not at_tail:
|
|
647
|
+
raise ValueError(
|
|
648
|
+
"failed to parse rollout file {0}: {1}".format(rollout_path, exc)
|
|
649
|
+
) from exc
|
|
650
|
+
else:
|
|
651
|
+
if isinstance(entry, dict):
|
|
652
|
+
leading = text[:len(text) - len(text.lstrip())]
|
|
653
|
+
entry["_record_offset"] = start + len(leading.encode("utf-8"))
|
|
654
|
+
parsed_entries += 1
|
|
655
|
+
yield entry
|
|
656
|
+
end = start
|
|
657
|
+
at_tail = False
|
|
658
|
+
if not parsed_entries:
|
|
659
|
+
raise ValueError("no rollout entries found in {0}".format(rollout_path))
|
|
660
|
+
|
|
661
|
+
|
|
573
662
|
def _extract_response_message_text(payload: "typing.Dict[str, object]") -> "str":
|
|
574
663
|
text_parts: "typing.List[str]" = []
|
|
575
664
|
for item in payload.get("content") or []:
|
|
@@ -594,10 +683,11 @@ def _compacted_payload(
|
|
|
594
683
|
def _deserialize_compacted_history(
|
|
595
684
|
replacement_history: "typing.Iterable[object]",
|
|
596
685
|
summary_message: "typing.Union[str, None]" = None,
|
|
686
|
+
record_id: "object" = "checkpoint",
|
|
597
687
|
) -> "typing.List[ConversationItem]":
|
|
598
688
|
history: "typing.List[ConversationItem]" = []
|
|
599
689
|
tool_names_by_call_id: "typing.Dict[str, str]" = {}
|
|
600
|
-
for payload in replacement_history:
|
|
690
|
+
for index, payload in enumerate(replacement_history):
|
|
601
691
|
if not isinstance(payload, dict):
|
|
602
692
|
continue
|
|
603
693
|
_append_deserialized_response_item(
|
|
@@ -605,6 +695,7 @@ def _deserialize_compacted_history(
|
|
|
605
695
|
payload,
|
|
606
696
|
tool_names_by_call_id,
|
|
607
697
|
include_user_messages=True,
|
|
698
|
+
record_id="{0}:{1}".format(record_id, index),
|
|
608
699
|
)
|
|
609
700
|
for index in range(len(history) - 1, -1, -1):
|
|
610
701
|
item = history[index]
|
|
@@ -622,22 +713,28 @@ def _append_deserialized_response_item(
|
|
|
622
713
|
payload: "typing.Dict[str, object]",
|
|
623
714
|
tool_names_by_call_id: "typing.Dict[str, str]",
|
|
624
715
|
include_user_messages: "bool",
|
|
716
|
+
record_id: "object" = "",
|
|
717
|
+
timestamp: "typing.Union[str, None]" = None,
|
|
625
718
|
) -> "None":
|
|
626
719
|
response_item_type = str(payload.get("type", "")).strip()
|
|
627
720
|
if response_item_type == "agent_message":
|
|
628
|
-
history.append(
|
|
721
|
+
history.append(restore_message_metadata(
|
|
722
|
+
AgentMessage.from_response_item(payload), payload, record_id, timestamp,
|
|
723
|
+
))
|
|
629
724
|
return
|
|
630
725
|
if response_item_type == "message":
|
|
631
726
|
role = str(payload.get("role", "")).strip()
|
|
632
727
|
if role == "assistant":
|
|
633
|
-
history.append(
|
|
728
|
+
history.append(restore_message_metadata(
|
|
729
|
+
AssistantMessage.from_response_item(payload), payload, record_id, timestamp,
|
|
730
|
+
))
|
|
634
731
|
return
|
|
635
732
|
if include_user_messages and role == "user":
|
|
636
733
|
history.append(
|
|
637
|
-
UserMessage(
|
|
734
|
+
restore_message_metadata(UserMessage(
|
|
638
735
|
text=_extract_response_message_text(payload), id=payload.get("id"),
|
|
639
736
|
name=payload.get("name", "user"),
|
|
640
|
-
)
|
|
737
|
+
), payload, record_id, timestamp)
|
|
641
738
|
)
|
|
642
739
|
return
|
|
643
740
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Skill catalog for workspace input suggestions."""
|
|
2
|
+
|
|
3
|
+
from ..context import discover_skills
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def list_skills(codex_home):
|
|
7
|
+
"""Return unique, deterministic names without exposing local filesystem paths."""
|
|
8
|
+
result = []
|
|
9
|
+
seen = set()
|
|
10
|
+
for skill in sorted(
|
|
11
|
+
discover_skills(codex_home),
|
|
12
|
+
key=lambda item: (item.scope_rank, item.name, str(item.path_to_skill_md)),
|
|
13
|
+
):
|
|
14
|
+
if skill.name in seen:
|
|
15
|
+
continue
|
|
16
|
+
seen.add(skill.name)
|
|
17
|
+
result.append({"name": skill.name, "description": skill.description})
|
|
18
|
+
return sorted(result, key=lambda item: item["name"].lower())
|